pyast.py

clew/pyast.py

The Python tree-sitter dialect: call sites, spawn sites, and import bindings.

_call_scope

tuple[str, str] clew.pyast._call_scope(Any callee, str name, list[tuple[int, int, str]] ranges, int offset, bytes src_bytes)

What a Python call site says about the class it targets: a qualifier, or a receiver.

clew/pyast.py:954

Source · 45 lines
def _call_scope(
    callee: Any,
    name: str,
    ranges: list[tuple[int, int, str]],
    offset: int,
    src_bytes: bytes,
) -> tuple[str, str]:
    """TWO DIFFERENT STRENGTHS OF EVIDENCE, and conflating them would waste the stronger one.

    `self.foo()` names its class EXACTLY — it is the enclosing one — so it is emitted as a
    QUALIFIER. `_narrow_by_qualifier` then RESOLVES it, the same path a C++ `Ns::Class::method()`
    takes. Emitting `self` as a receiver instead would send it to `_narrow_by_receiver`, which
    would look `self` up in the member-variable type map, find nothing, and refuse — which is
    precisely what happened to every Python member call before this existed.

    `self.cache.clear()` is the receiver case: the target class is whatever `cache` was declared
    as, which the index may or may not hold. The TAIL is what carries a declared type, exactly as
    `_receiver_tail` records for `handle->engine->run_turn()` — taking the whole text or the root
    (`self`) resolves to the wrong thing in both languages.

    A bare `identifier` callee is a free function and gets neither: marking one would send it
    down the member path where a unique name is NOT evidence.

    @brief Classify a Python call site as class-qualified or receiver-borne.
    @return (qualifier, receiver).
    @version 2
    """
    if callee is None or callee.type != "attribute":
        return "", ""
    obj = callee.child_by_field_name("object")
    if obj is None:
        return "", ""
    if obj.type == "identifier" and is_receiver(obj, node_text(obj, src_bytes), src_bytes):
        owner = enclosing_class(ranges, offset)
        return (f"{owner}.{name}" if owner else ""), ""
    ## The tail of the receiver chain, matching the C rule one grammar over.
    inner = obj.child_by_field_name("attribute") if obj.type == "attribute" else obj
    if inner is None or inner.type != "identifier":
        return "", ""
    return "", node_text(inner, src_bytes)


# ── thread spawn sites ──────────────────────────────────────────────────────

Activity · 12 steps
lines 981–981◇ if callee is None or callee.type != "attribute"lines 982–982return "", ""lines 983–983obj = callee.child_by_field_name("object")lines 984–984◇ if obj is Nonelines 985–985return "", ""lines 986–986◇ if obj.type == "identifier" and is_receiver(obj, node_text(obj, src_bytes), src_bytes)lines 987–987owner = enclosing_class(ranges, offset)lines 988–988return (f"{owner}.{name}" if owner else ""), ""lines 990–990inner = obj.child_by_field_name("attribute") if obj.type == "attribute" else objlines 991–991◇ if inner is None or inner.type != "identifier"lines 992–992return "", ""lines 993–993return "", node_text(inner, src_bytes)

Requirements

REQ-DDB-PIPE-003

callee_tail

tuple[str, bool] | None clew.pyast.callee_tail(Any callee, bytes src_bytes)

The callee's bare tail name plus whether it was attribute-qualified.

clew/pyast.py:524

Source · 27 lines
def callee_tail(callee: Any, src_bytes: bytes) -> tuple[str, bool] | None:
    """Reads the tail out of the `attribute` field DIRECTLY rather than going
    through `dotted_name`, and that difference is the whole point.

    `dotted_name` refuses a chain whose receiver is not itself a static name —
    correct for pattern matching, where `threading.Thread` must be told apart
    from `.models.Thread`. For a CALL EDGE the receiver is irrelevant: only the
    tail is ever matched against `memberdef.name`. Routing call harvest through
    `dotted_name` therefore dropped every chained call outright — measured on the
    committed fixture, `threading.Thread(target=..., name=...).start()` produced
    NO `start` site at all, because its receiver is a `call`. The C path already
    unwraps `field_expression -> field` for exactly this shape
    (`make_obj()->run()`), so refusing it on Python was a dialect inconsistency,
    not a safety property.

    @brief Reduce a Python callee to its tail name and qualification flag.
    @return (tail, qualified) or None.
    @version 1
    """
    if callee is None:
        return None
    if callee.type == "identifier":
        return node_text(callee, src_bytes), False
    field = callee.child_by_field_name("attribute") if callee.type == "attribute" else None
    return (node_text(field, src_bytes), True) if field is not None else None

Activity · 6 steps
lines 543–543◇ if callee is Nonelines 544–544return Nonelines 545–545◇ if callee.type == "identifier"lines 546–546return node_text(callee, src_bytes), Falselines 547–547field = callee.child_by_field_name("attribute") if callee.type == "attribute" else Nonelines 548–548return (node_text(field, src_bytes), True) if field is not None else None

Requirements

REQ-DDB-PIPE-003

class_ranges

list[tuple[int, int, str]] clew.pyast.class_ranges(Any tree, bytes src_bytes)

Byte ranges of every class body in a file, with the class name.

clew/pyast.py:477

Show on the map →

Called by _fixture_functions, _walk_py_spawn_sites, harvest_calls, harvest_python_definitions

Calls _collect_by_type

Source · 17 lines
def class_ranges(tree: Any, src_bytes: bytes) -> list[tuple[int, int, str]]:
    """Ranges rather than a walk-time scope stack: the harvesters here use flat
    iterative stacks (matching the C walkers), and a containing-range lookup
    keeps that shape while still answering "which class is this call inside?".

    @brief Collect class-body byte ranges and names.
    @return List of (start, end, name).
    @version 1
    """
    ranges: list[tuple[int, int, str]] = []
    for node in _collect_by_type(tree.root_node, ("class_definition",)):
        name_node = node.child_by_field_name("name")
        if name_node is not None:
            ranges.append((node.start_byte, node.end_byte, node_text(name_node, src_bytes)))
    return ranges

Activity · 6 steps
lines 486–486ranges: list[tuple[int, int, str]] = []lines 487–487◇ for node in _collect_by_type(tree.root_node, ("class_definition",))lines 488–488name_node = node.child_by_field_name("name")lines 489–489◇ if name_node is not Nonelines 490–490ranges.append((node.start_byte, node.end_byte, node_text(name_node, src_bytes)))lines 491–491return ranges

Requirements

REQ-DDB-PIPE-003

collect_bindings

PyBindings clew.pyast.collect_bindings(Any tree, bytes src_bytes)

Collect one file's import and receiver bindings.

clew/pyast.py:265

Source · 32 lines
def collect_bindings(tree: Any, src_bytes: bytes) -> PyBindings:
    """Two passes, because a receiver binding is resolved THROUGH the import
    bindings (`ex = ThreadPoolExecutor()` needs `ThreadPoolExecutor` to already
    mean `concurrent.futures.ThreadPoolExecutor`). Imports are collected first,
    then assignments and `with ... as` targets.

    DEFAULT_RECEIVER_PRODUCERS is read directly rather than taken as an override
    parameter (gh#317). The parameter existed from the start, was documented as the
    seam a `.clew.yaml` declaration would reach, and was never passed by
    anything — so it was not a seam, it was an untested branch that made the
    constant look configurable while the pipeline could only ever use the default.

    @brief Build a file's binding table from its imports and local constructions.
    @return Populated PyBindings.
    @version 2
    """
    bindings = PyBindings()
    nodes = _collect_by_type(
        tree.root_node,
        ("import_statement", "import_from_statement", "assignment", "as_pattern"),
    )
    for node in nodes:
        if node.type == "import_statement":
            _bind_import(node, src_bytes, bindings)
        elif node.type == "import_from_statement":
            _bind_import_from(node, src_bytes, bindings)
    for node in nodes:
        if node.type in ("assignment", "as_pattern"):
            _bind_receiver(node, src_bytes, bindings, DEFAULT_RECEIVER_PRODUCERS)
    return bindings

Activity · 11 steps
lines 281–281bindings = PyBindings()lines 282–285nodes = _collect_by_type( tree.root_node, ("import_statement", "import_from_statement", "assignment", "as_pattern"), )lines 286–286◇ for node in nodeslines 287–287◇ if node.type == "import_statement"lines 288–288_bind_import(node, src_bytes, bindings)lines 289–289◇ elif node.type == "import_from_statement"lines 290–290_bind_import_from(node, src_bytes, bindings)lines 291–291◇ for node in nodeslines 292–292◇ if node.type in ("assignment", "as_pattern")lines 293–293_bind_receiver(node, src_bytes, bindings, DEFAULT_RECEIVER_PRODUCERS)lines 294–294return bindings

Requirements

REQ-DDB-PIPE-003

dotted_name

str | None clew.pyast.dotted_name(Any node, bytes src_bytes)

Flatten an identifier/attribute/dotted_name chain to dotted text.

clew/pyast.py:120

Show on the map →

Called by _bind_receiver, _called_names, _named_entry_names, _py_matched_patterns, _resolve_py_literal_key, _walk_py_shared_key_calls

Tested by

2 teststest_dotted_name_refuses_non_static_chain, test_positional_argument_skips_keyword_arguments

Calls _is_static_chain

Source · 16 lines
def dotted_name(node: Any, src_bytes: bytes) -> str | None:
    """`attribute` nests left-recursively (`a.b.c` is `attribute(attribute(a,b),c)`),
    so the whole span's text IS the dotted name — but only once we know every
    link is a plain name. A chain containing a call or subscript (`f().b`,
    `d["k"].b`) has no static name and is refused rather than having its text
    taken literally.

    @brief Flatten a static name chain to dotted text.
    @return Dotted name or None.
    @version 1
    """
    if node is None or node.type not in _PY_NAME_NODES:
        return None
    return node_text(node, src_bytes) if _is_static_chain(node) else None

Activity · 3 steps
lines 131–131◇ if node is None or node.type not in _PY_NAME_NODESlines 132–132return Nonelines 133–133return node_text(node, src_bytes) if _is_static_chain(node) else None

Requirements

REQ-DDB-PIPE-003

enclosing_class

str | None clew.pyast.enclosing_class(list[tuple[int, int, str]] ranges, int offset)

The innermost class whose body contains a byte offset.

clew/pyast.py:500

Show on the map →

Called by _call_scope, _fixture_functions, _parsed_python_function, _resolve_py_spawn_site

Calls none

Source · 18 lines
def enclosing_class(ranges: list[tuple[int, int, str]], offset: int) -> str | None:
    """Innermost wins (a nested class shadows its outer), chosen by narrowest
    containing span.

    @brief Find the innermost class containing an offset.
    @return Class name or None.
    @version 1
    """
    best: tuple[int, str] | None = None
    for start, end, name in ranges:
        if start <= offset < end and (best is None or (end - start) < best[0]):
            best = (end - start, name)
    return best[1] if best is not None else None


# ── Layer 3: call sites ─────────────────────────────────────────────────────

Activity · 5 steps
lines 508–508best: tuple[int, str] | None = Nonelines 509–509◇ for start, end, name in rangeslines 510–510◇ if start <= offset < end and (best is None or (end - start) < best[0])lines 511–511best = (end - start, name)lines 512–512return best[1] if best is not None else None

Requirements

REQ-DDB-PIPE-003

entry_names

tuple[str, str] | None clew.pyast.entry_names(Any arg, bytes src_bytes, str|None class_name)

Resolve a spawn call's entry argument to (qualified, tail) names.

clew/pyast.py:1060

Show on the map →

Called by _awaited_call_entry, _resolve_py_spawn_site

Calls none

Source · 26 lines
def entry_names(arg: Any, src_bytes: bytes, class_name: str | None) -> tuple[str, str] | None:
    """Four shapes resolve, and everything else fails closed:
      - `worker` → (`worker`, `worker`).
      - `self.method` with a known enclosing class → (`Class.method`, `method`).
        This is what separates five classes' `target=self._run`; without it they
        either all vanish or one borrows another's rowid.
      - a deeper chain (`self._server.serve_forever`, `params.get`) → the
        receiver's type is unknown, so only the TAIL is offered and rowid
        resolution succeeds solely when that name is unique in the index.
      - `lambda: self.loop()` / `create_task(coro())` → unwrapped to the single
        called function; a lambda with several calls is ambiguous and refused,
        exactly as the C++ layer refuses a multi-call lambda body.

    Dispatched through a table rather than an if-chain so the shapes stay one
    exit apiece (house limit: at most three returns per function).

    @brief Resolve a Python spawn entry argument to its names.
    @return (qualified, tail) or None.
    @version 2
    """
    if arg is None:
        return None
    handlers = {"lambda": _lambda_entry, "call": _awaited_call_entry}
    return handlers.get(arg.type, _named_entry_names)(arg, src_bytes, class_name)

Activity · 4 steps
lines 1080–1080◇ if arg is Nonelines 1081–1081return Nonelines 1082–1082handlers = {"lambda": _lambda_entry, "call": _awaited_call_entry}lines 1083–1083return handlers.get(arg.type, _named_entry_names)(arg, src_bytes, class_name)

Requirements

REQ-DDB-PIPE-003

harvest_calls

list[list[Any]] clew.pyast.harvest_calls(Any tree, bytes src_bytes, str source_plain, str source_member, str source_binding)

Harvest one Python file's call sites as [callee_name, line, source].

clew/pyast.py:608

Show on the map →

Called by none

Calls _call_scope, _enclosing_function, _keyword_bindings, _locals_of, _own_locals, _receiver_module, callee_tail, class_ranges, import_bindings

Source · 80 lines
def harvest_calls(
    tree: Any,
    src_bytes: bytes,
    source_plain: str,
    source_member: str,
    source_binding: str,
) -> list[list[Any]]:
    """Emits exactly the shape the C harvester does — `[name, line, source]`,
    rowid-free so it caches on the file's content sha — and reuses the SAME two
    provenance tags rather than inventing Python-specific ones.

    That reuse is a judgement, not a convenience: `ast_member` means "the callee
    was recovered by unwrapping a qualified form down to its unqualified tail,
    which may match several classes". `obj.method()` in Python is precisely that,
    and `memberdef.name` stores the tail for both languages, so the two are the
    same fact about the same kind of edge. A separate value would split one
    concept across two tokens and force every consumer to know both.

    Comprehension bodies, decorator calls (`@app.route(...)`) and calls inside
    lambdas need no special case: each is a `call` node and the flat walk reaches
    all of them.

    Keyword-argument BINDINGS (gh#1) are collected from the same `call` node and
    BEFORE the callee is resolved — a call whose own callee is unreadable can still
    carry a perfectly readable binding, and the original `continue` skipped both.

    gh#21 ADDED THE QUALIFIER AND RECEIVER, in the C path's element order so
    `_fold_call_payload` reads them by the same indices. Without them every Python member call
    reached the refusal path with nothing known about it — measured, 3,367 blind refusals on
    this repository's own index, 100% of them.

    NO ARITY, unlike the C path. `argc` exists to separate overloads and Python has none, so
    emitting it would cost a count per call site to break no tie.

    @brief Harvest Python call sites with call/member/binding provenance.
    @return List of [callee_name, line, source, qualifier, receiver(, -1, False, None, module)].
    @version 5
    """
    sites: list[list[Any]] = []
    ## Computed once per file rather than per call site: `enclosing_class` is a containing-span
    ## lookup, and rebuilding the range list inside the walk would make it quadratic on a module
    ## of many classes.
    ranges = class_ranges(tree, src_bytes)
    imports = import_bindings(tree, src_bytes)
    shadows: dict[int, frozenset[str]] = {}
    own: dict[int, frozenset[str]] = {}
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        stack.extend(node.children)
        if node.type != "call":
            continue
        local = _locals_of(_enclosing_function(node), src_bytes, shadows)
        sites.extend(_keyword_bindings(node, src_bytes, source_binding, local))
        callee = node.child_by_field_name("function")
        tail = callee_tail(callee, src_bytes)
        if tail is None:
            continue
        name, qualified = tail
        if not qualified and name in _own_locals(_enclosing_function(node), src_bytes, own):
            ## `def go(finish): finish()` calls what was passed in (agent C's W2): resolving
            ## it to a function named `finish` minted a resolved edge from a spelling.
            continue
        qualifier, receiver = _call_scope(callee, name, ranges, node.start_byte, src_bytes)
        site = [
            name,
            node.start_point[0] + 1,
            source_member if qualified else source_plain,
            qualifier,
            receiver,
        ]
        module = _receiver_module(callee, src_bytes, imports) if qualified else None
        if module:
            ## NINTH ELEMENT: the module the receiver is bound to by an IMPORT. Elements 6-8
            ## (argc, construction, via_import) are C / JS facts and stay at their neutral values.
            site += [-1, False, None, module]
        sites.append(site)
    return sites

Activity · 27 steps
lines 646–646sites: list[list[Any]] = []lines 650–650ranges = class_ranges(tree, src_bytes)lines 651–651imports = import_bindings(tree, src_bytes)lines 652–652shadows: dict[int, frozenset[str]] = {}lines 653–653own: dict[int, frozenset[str]] = {}lines 654–654stack = [tree.root_node]lines 655–655◇ while stacklines 656–656node = stack.pop()lines 657–657stack.extend(node.children)lines 658–658◇ if node.type != "call"lines 659–659continuelines 660–660local = _locals_of(_enclosing_function(node), src_bytes, shadows)lines 661–661sites.extend(_keyword_bindings(node, src_bytes, source_binding, local))lines 662–662callee = node.child_by_field_name("function")lines 663–663tail = callee_tail(callee, src_bytes)lines 664–664◇ if tail is Nonelines 665–665continuelines 666–666name, qualified = taillines 667–667◇ if not qualified and name in _own_locals(_enclosing_function(node), src_bytes, own)lines 670–670continuelines 671–671qualifier, receiver = _call_scope(callee, name, ranges, node.start_byte, src_bytes)lines 672–678site = [ name, node.start_point[0] + 1, source_member if qualified else source_plain, qualifier, receiver, ]lines 679–679module = _receiver_module(callee, src_bytes, imports) if qualified else Nonelines 680–680◇ if modulelines 683–683site += [-1, False, None, module]lines 684–684sites.append(site)lines 685–685return sites

Requirements

REQ-DDB-PIPE-003

import_bindings

PyBindings clew.pyast.import_bindings(Any tree, bytes src_bytes)

A file's IMPORT bindings only: aliases that name modules or imported names.

clew/pyast.py:694

Show on the map →

Called by _py_import_modules, harvest_calls

Calls _bind_import, _bind_import_from, _collect_by_type

Source · 16 lines
def import_bindings(tree: Any, src_bytes: bytes) -> PyBindings:
    """A LOCAL CONSTRUCTION IS NOT A MODULE: `ex = Executor()` binds `ex` to a class, and a call
    `ex.submit()` must never be looked up as a module path, so only import statements count.

    @brief Import bindings.
    @return Table.
    """
    bindings = PyBindings()
    for node in _collect_by_type(tree.root_node, ("import_statement", "import_from_statement")):
        if node.type == "import_statement":
            _bind_import(node, src_bytes, bindings)
        else:
            _bind_import_from(node, src_bytes, bindings)
    return bindings

Activity · 7 steps
lines 701–701bindings = PyBindings()lines 702–702◇ for node in _collect_by_type(tree.root_node, ("import_statement", "import_from_statement"))lines 703–703◇ if node.type == "import_statement"lines 704–704_bind_import(node, src_bytes, bindings)lines 705–705elselines 706–706_bind_import_from(node, src_bytes, bindings)lines 707–707return bindings

Requirements

REQ-DDB-PIPE-003

is_python_tree

bool clew.pyast.is_python_tree(Any tree)

True when a parsed tree came from the Python grammar.

clew/pyast.py:89

Show on the map →

Called by _ast_harvest_calls, _walk_shared_key_calls, _walk_spawn_sites, harvest, harvest, harvest

Tested by

1 teststest_is_python_tree_discriminates_by_root_type

Calls none

Source · 11 lines
def is_python_tree(tree: Any) -> bool:
    """Discriminates on the grammar's own root node type, so a stage can pick a
    dialect without the language being threaded through `Harvester.harvest`.

    @brief Detect a Python parse tree.
    @return Whether the tree's root is Python's `module`.
    @version 1
    """
    return tree.root_node.type == PY_ROOT_TYPE

Activity · 1 steps
lines 97–97return tree.root_node.type == PY_ROOT_TYPE

Requirements

REQ-DDB-PIPE-003

is_receiver

bool clew.pyast.is_receiver(Any node, str name, bytes src_bytes)

Whether a name, at a node, is the enclosing method's receiver.

clew/pyast.py:894

Show on the map →

Called by _call_scope, _named_entry_names

Calls _first_parameter, enclosing

Source · 17 lines
def is_receiver(node: Any, name: str, src_bytes: bytes) -> bool:
    """R5-CORE D1 (2.0.0): `SELF_NAMES` is PEP 8 convention, not grammar — `def m(this)`, a
    metaclass's `mcs` and a `klass` receiver were missed. THE TREE STATES THE RECEIVER: the first
    parameter of the nearest enclosing function, when that function is defined directly in a class
    body and is not a `@staticmethod`. `self` / `cls` still count wherever they appear, as before.

    @brief Receiver test.
    @return Bool.
    """
    if name in SELF_NAMES:
        return True
    from .harvest import enclosing

    func = enclosing(node, ("function_definition",))
    return func is not None and _first_parameter(func, src_bytes) == name

Activity · 5 steps
lines 903–903◇ if name in SELF_NAMESlines 904–904return Truelines 905–905from .harvest import enclosinglines 907–907func = enclosing(node, ("function_definition",))lines 908–908return func is not None and _first_parameter(func, src_bytes) == name

Requirements

REQ-DDB-PIPE-003

keyword_argument

Any | None clew.pyast.keyword_argument(Any call_node, str keyword)

Read a call's keyword argument by name.

clew/pyast.py:1032

Show on the map →

Called by _py_entry_argument, _py_thread_name

Tested by

1 teststest_positional_argument_skips_keyword_arguments

Calls none

Source · 21 lines
def keyword_argument(call_node: Any, keyword: str) -> Any | None:
    """Real Python passes the thread entry by keyword essentially always — all 40
    `threading.Thread` sites measured across the two real codebases use
    `target=` — so this, not the positional index, is the common path.

    @brief Fetch a call's keyword-argument value.
    @return Value node or None.
    @version 2
    """
    args = call_node.child_by_field_name("arguments")
    if args is None:
        return None
    for child in args.named_children:
        if child.type != "keyword_argument":
            continue
        name = child.child_by_field_name("name")
        if name is not None and name.text == keyword.encode():
            return child.child_by_field_name("value")
    return None

Activity · 10 steps
lines 1041–1041args = call_node.child_by_field_name("arguments")lines 1042–1042◇ if args is Nonelines 1043–1043return Nonelines 1044–1044◇ for child in args.named_childrenlines 1045–1045◇ if child.type != "keyword_argument"lines 1046–1046continuelines 1047–1047name = child.child_by_field_name("name")lines 1048–1048◇ if name is not None and name.text == keyword.encode()lines 1049–1049return child.child_by_field_name("value")lines 1050–1050return None

Requirements

REQ-DDB-PIPE-003

node_text

str clew.pyast.node_text(Any node, bytes src_bytes)

Decode one node's source text.

clew/pyast.py:106

Show on the map →

Called by none

Calls none

Source · 8 lines
def node_text(node: Any, src_bytes: bytes) -> str:
    """@brief Decode a node's byte span to text.

    @version 1
    """
    return src_bytes[node.start_byte : node.end_byte].decode("utf-8", errors="replace")

Activity · 1 steps
lines 111–111return src_bytes[node.start_byte : node.end_byte].decode("utf-8", errors="replace")

Requirements

REQ-DDB-PIPE-003

positional_argument

Any | None clew.pyast.positional_argument(Any call_node, int index)

Read a call's Nth POSITIONAL argument, skipping keyword arguments.

clew/pyast.py:1005

Show on the map →

Called by _py_entry_argument, _py_thread_name, _record_py_call_site

Tested by

1 teststest_positional_argument_skips_keyword_arguments

Calls none

Source · 21 lines
def positional_argument(call_node: Any, index: int) -> Any | None:
    """The C helper counts every named child, which in Python's `argument_list`
    includes `keyword_argument` nodes — so `Thread(target=f)` would report `f` at
    position 0 when `target` is really the second POSITIONAL parameter. Counting
    only positional nodes keeps an index meaning what the callee's signature says.

    @brief Fetch a call's Nth positional argument.
    @return Argument node or None.
    @version 1
    """
    args = call_node.child_by_field_name("arguments")
    if args is None:
        return None
    positional = [
        c
        for c in args.named_children
        if c.type not in ("keyword_argument", "dictionary_splat", "list_splat", "comment")
    ]
    return positional[index] if 0 <= index < len(positional) else None

Activity · 5 steps
lines 1015–1015args = call_node.child_by_field_name("arguments")lines 1016–1016◇ if args is Nonelines 1017–1017return Nonelines 1018–1022positional = [ c for c in args.named_children if c.type not in ("keyword_argument", "dictionary_splat", "list_splat", "comment") ]lines 1023–1023return positional[index] if 0 <= index < len(positional) else None

Requirements

REQ-DDB-PIPE-003

resolve

str | None clew.pyast.PyBindings.resolve(self, str dotted)

Resolve a dotted callee to its fully-qualified name.

clew/pyast.py:243

Show on the map →

Called by none

Calls none

Source · 16 lines
    def resolve(self, dotted: str) -> str | None:
        """Rewrites only the HEAD segment, since that is the only part an import
        or an assignment can bind; the remaining segments are attribute access on
        whatever the head denotes and pass through unchanged.

        @brief Resolve a dotted name through this file's bindings.
        @return Fully-qualified dotted name, or None.
        @version 1
        """
        head, _, rest = dotted.partition(".")
        base = self.names.get(head)
        if base is None:
            return None
        return f"{base}.{rest}" if rest else base

Activity · 5 steps
lines 252–252head, _, rest = dotted.partition(".")lines 253–253base = self.names.get(head)lines 254–254◇ if base is Nonelines 255–255return Nonelines 256–256return f"{base}.{rest}" if rest else base

Requirements

REQ-DDB-PIPE-003

string_value

str | None clew.pyast.string_value(Any node, bytes src_bytes)

The text of a Python string literal, without its quotes.

clew/pyast.py:175

Show on the map →

Called by _py_thread_name, _resolve_py_literal_key

Tested by

1 teststest_string_value_reads_content_not_quotes

Calls none

Source · 21 lines
def string_value(node: Any, src_bytes: bytes) -> str | None:
    """Python's grammar splits a string into `string_start` / `string_content` /
    `string_end`, so the C path's `text.strip('"')` would keep the quotes of a
    `'single'` or `f"..."` literal. Reading `string_content` also refuses an
    f-string with an interpolation (which has several content pieces) instead of
    recording a template as if it were a name.

    @brief Read a plain string literal's content.
    @return The content, or None.
    @version 1
    """
    if node is None or node.type != "string":
        return None
    parts = [c for c in node.children if c.type == "string_content"]
    if len(parts) != 1:
        return None
    return node_text(parts[0], src_bytes)


# ── per-file import / receiver bindings ─────────────────────────────────────
Activity · 6 steps
lines 186–186◇ if node is None or node.type != "string"lines 187–187return Nonelines 188–188parts = [c for c in node.children if c.type == "string_content"]lines 189–189◇ if len(parts) != 1lines 190–190return Nonelines 191–191return node_text(parts[0], src_bytes)

Requirements

REQ-DDB-PIPE-003

tail_name

str clew.pyast.tail_name(str dotted)

The trailing segment of a dotted name.

clew/pyast.py:161

Show on the map →

Called by _called_names, _named_entry_names, _walk_py_shared_key_calls

Calls none

Source · 8 lines
def tail_name(dotted: str) -> str:
    """@brief Last segment of a dotted name.

    @version 1
    """
    return dotted.rsplit(".", 1)[-1]

Activity · 1 steps
lines 166–166return dotted.rsplit(".", 1)[-1]

Requirements

REQ-DDB-PIPE-003