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.
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
Requirements
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.
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
Requirements
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.
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
Requirements
collect_bindings
PyBindings clew.pyast.collect_bindings(Any tree, bytes src_bytes)
Collect one file's import and receiver bindings.
Called by _walk_py_spawn_sites
Tested by
Calls _bind_import, _bind_import_from, _bind_receiver, _collect_by_type
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
Requirements
dotted_name
str | None clew.pyast.dotted_name(Any node, bytes src_bytes)
Flatten an identifier/attribute/dotted_name chain to dotted text.
Called by _bind_receiver, _called_names, _named_entry_names, _py_matched_patterns, _resolve_py_literal_key, _walk_py_shared_key_calls
Tested by
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
Requirements
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.
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
Requirements
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.
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
Requirements
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].
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
Requirements
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.
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
Requirements
is_python_tree
bool clew.pyast.is_python_tree(Any tree)
True when a parsed tree came from the Python grammar.
Called by _ast_harvest_calls, _walk_shared_key_calls, _walk_spawn_sites, harvest, harvest, harvest
Tested by
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
Requirements
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.
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
Requirements
keyword_argument
Any | None clew.pyast.keyword_argument(Any call_node, str keyword)
Read a call's keyword argument by name.
Called by _py_entry_argument, _py_thread_name
Tested by
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
Requirements
node_text
str clew.pyast.node_text(Any node, bytes src_bytes)
Decode one node's source text.
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
Requirements
positional_argument
Any | None clew.pyast.positional_argument(Any call_node, int index)
Read a call's Nth POSITIONAL argument, skipping keyword arguments.
Called by _py_entry_argument, _py_thread_name, _record_py_call_site
Tested by
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
Requirements
resolve
str | None clew.pyast.PyBindings.resolve(self, str dotted)
Resolve a dotted callee to its fully-qualified name.
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
Requirements
string_value
str | None clew.pyast.string_value(Any node, bytes src_bytes)
The text of a Python string literal, without its quotes.
Called by _py_thread_name, _resolve_py_literal_key
Tested by
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
Requirements
tail_name
str clew.pyast.tail_name(str dotted)
The trailing segment of a dotted name.
Source · 8 lines
def tail_name(dotted: str) -> str:
"""@brief Last segment of a dotted name.
@version 1
"""
return dotted.rsplit(".", 1)[-1]