astdefs.py¶
clew/propose/astdefs.py
Definition / parameter / forwarding-call extraction from a parse tree.
_bare_identifier
str clew.propose.astdefs._bare_identifier(Any node, bytes src)
The bare identifier an argument names, unwrapping &/casts/parentheses.
Source · 11 lines
def _bare_identifier(node: Any, src: bytes) -> str:
"""@brief Reduce an argument expression to the plain name it passes."""
cur = node
while cur is not None and cur.type in _UNWRAP_TYPES:
inner = cur.child_by_field_name("value")
cur = inner if inner is not None else next(iter(cur.named_children), None)
if cur is None or cur.type != "identifier":
return ""
return text_of(cur, src)
Activity · 7 steps
Flows
_first_identifier
str | None clew.propose.astdefs._first_identifier(Any node, bytes src, tuple[str,...] kinds)
The first identifier of a subtree in document order.
Source · 21 lines
def _first_identifier(node: Any, src: bytes, kinds: tuple[str, ...]) -> str | None:
"""Document order matters: a function-pointer parameter nests its name
(`(*task_fn)`) BEFORE its own parameter list, so the first identifier is the
parameter's name and not something from its signature.
@brief Find a subtree's first identifier in document order.
@version 1
"""
found: str | None = None
stack = [node] if node is not None else []
while stack and found is None:
cur = stack.pop()
if cur.type in kinds:
found = text_of(cur, src)
else:
# Reversed so `pop()` yields the FIRST child — a plain stack walk
# would return the last identifier, not the first.
stack.extend(reversed(cur.children))
return found
Activity · 9 steps
Flows
_forward_call
ForwardCall | None clew.propose.astdefs._forward_call(Any node, bytes src, dict[str, int] positions, int line)
One call's parameter-forwarding map, or None when it forwards nothing.
Source · 18 lines
def _forward_call(
node: Any, src: bytes, positions: dict[str, int], line: int
) -> ForwardCall | None:
"""@brief Map a call's arguments onto the enclosing definition's parameters."""
name = callee_name(node, src)
args = node.child_by_field_name("arguments")
if not name or args is None:
return None
mapped = [
(index, positions[ident])
for index, arg in enumerate(args.named_children)
if (ident := _bare_identifier(arg, src)) in positions
]
if not mapped:
return None
return ForwardCall(name, line, tuple(mapped))
Activity · 8 steps
Flows
_forward_calls
tuple[ForwardCall, ...] clew.propose.astdefs._forward_calls(Any body, bytes src, tuple[str,...] params, int line)
Calls inside a body that pass one of the definition's parameters on.
Source · 17 lines
def _forward_calls(
body: Any, src: bytes, params: tuple[str, ...], line: int
) -> tuple[ForwardCall, ...]:
"""@brief Collect the parameter-forwarding calls inside one definition."""
positions = {name: idx for idx, name in enumerate(params) if name}
if not positions:
return ()
found: list[ForwardCall] = []
for node in walk(body):
if node.type != "call_expression":
continue
call = _forward_call(node, src, positions, line)
if call is not None:
found.append(call)
return tuple(found)
Activity · 11 steps
Flows
_function_declarator
Any clew.propose.astdefs._function_declarator(Any node)
Descend a declarator chain to its function_declarator .
Source · 17 lines
def _function_declarator(node: Any) -> Any:
"""`void *f(void)` and `int (*g(void))(void)` wrap the function declarator in
pointer/parenthesized declarators, so the chain has to be walked rather than
assumed one level deep.
@brief Locate the function_declarator of a definition.
@version 1
"""
cur = node
while cur is not None and cur.type != "function_declarator":
nxt = cur.child_by_field_name("declarator")
if nxt is None:
return None
cur = nxt
return cur
Activity · 7 steps
Flows
_function_signature
tuple[str, tuple[str, ...], Any, bytes] | None clew.propose.astdefs._function_signature(Any node, bytes src)
Name, parameters and body of a function_definition .
Called by _signature, enclosing_definition
Source · 13 lines
def _function_signature(node: Any, src: bytes) -> tuple[str, tuple[str, ...], Any, bytes] | None:
"""@brief Read a C/C++ function definition's name, parameters and body."""
declarator = _function_declarator(node.child_by_field_name("declarator"))
if declarator is None:
return None
name_node = declarator.child_by_field_name("declarator")
name = _tail_name(name_node, src) if name_node is not None else ""
if not name:
return None
params = _param_names(declarator.child_by_field_name("parameters"), src)
return name, params, node.child_by_field_name("body") or node, src
Activity · 9 steps
Flows
_macro_body
tuple[Any, bytes] clew.propose.astdefs._macro_body(Any node, bytes src)
Re-parse a macro's body so its calls become visible.
Source · 20 lines
def _macro_body(node: Any, src: bytes) -> tuple[Any, bytes]:
"""Wrap the body in a synthetic function so an expression-shaped body parses
as a statement. A body that still fails to parse yields ERROR nodes, and the
`call_expression` nodes inside it are usually recovered anyway — which is
strictly better than the alternative of not looking at all.
@brief Parse a function-like macro's replacement text.
@version 1
"""
arg = node.child_by_field_name("value")
body_text = text_of(arg, src).replace("\\\n", "\n").strip() if arg is not None else ""
if not body_text:
return None, b""
wrapped = b"void __docsdb_macro__(void){\n" + body_text.encode("utf-8") + b"\n;}\n"
parser = _macro_parser()
if parser is None:
return None, b""
return parser.parse(wrapped).root_node, wrapped
Activity · 9 steps
Flows
_macro_parser
Any clew.propose.astdefs._macro_parser()
Memoised C parser used for macro replacement text.
Source · 14 lines
def _macro_parser() -> Any:
"""Always the C grammar: a replacement list is preprocessor text, and the
C++ grammar buys nothing for the call shapes this module reads.
@brief Build (once) the parser for macro bodies.
@version 3
"""
if not _MACRO_PARSER:
from ..tsnode import Parser
_MACRO_PARSER.append(Parser("c"))
return _MACRO_PARSER[0]
Activity · 4 steps
Flows
_macro_signature
tuple[str, tuple[str, ...]] | None clew.propose.astdefs._macro_signature(Any node, bytes src)
Name and parameters of a preproc_function_def .
Source · 14 lines
def _macro_signature(node: Any, src: bytes) -> tuple[str, tuple[str, ...]] | None:
"""@brief Read a function-like macro's name and parameter identifiers."""
name_node = node.child_by_field_name("name")
if name_node is None:
return None
params_node = node.child_by_field_name("parameters")
params = (
tuple(text_of(c, src) for c in params_node.named_children if c.type == "identifier")
if params_node is not None
else ()
)
return text_of(name_node, src), params
Activity · 6 steps
Flows
_param_names
tuple[str, ...] clew.propose.astdefs._param_names(Any params_node, bytes src)
Parameter identifiers of a parameter list, in declaration order.
Source · 11 lines
def _param_names(params_node: Any, src: bytes) -> tuple[str, ...]:
"""@brief Read a parameter list's declared identifiers."""
if params_node is None:
return ()
return tuple(
_first_identifier(child, src, ("identifier",)) or ""
for child in params_node.named_children
if child.type in _PARAM_TYPES
)
Activity · 3 steps
Flows
_signature
tuple[str, tuple[str, ...], Any, bytes] | None clew.propose.astdefs._signature(Any node, bytes src)
Name, parameters and walkable body of one definition node.
Called by definition_record
Source · 16 lines
def _signature(node: Any, src: bytes) -> tuple[str, tuple[str, ...], Any, bytes] | None:
"""A macro's body lives in a different byte buffer than the file's, because
it had to be re-parsed — so the buffer travels with the body node rather
than being assumed to be `src`.
@brief Resolve one definition to (name, params, body, body bytes).
@version 1
"""
if node.type == "preproc_function_def":
named = _macro_signature(node, src)
body, body_src = _macro_body(node, src) if named else (None, b"")
return (*named, body, body_src) if named else None
signature = _function_signature(node, src)
return signature
Activity · 6 steps
Flows
_tail_name
str clew.propose.astdefs._tail_name(Any node, bytes src)
The trailing simple name of a declarator node.
Source · 11 lines
def _tail_name(node: Any, src: bytes) -> str:
"""C++ member definitions declare `Class::method`; the corpus keys on the
bare name because that is what a call site writes.
@brief Reduce a declarator to its bare trailing name.
@version 1
"""
found = _first_identifier(node, src, ("identifier", "field_identifier"))
return found or ""
Activity · 2 steps
Flows
callee_name
str clew.propose.astdefs.callee_name(Any node, bytes src)
The callee's text when it is an identifier / qualified identifier.
Source · 8 lines
def callee_name(node: Any, src: bytes) -> str:
"""@brief Decode a call's callee name, restricted to matchable shapes."""
callee = node.child_by_field_name("function")
if callee is None or callee.type not in CALLEE_TYPES:
return ""
return src[callee.start_byte : callee.end_byte].decode("utf-8", errors="replace")
Activity · 4 steps
Requirements
Flows
definition_record
FuncDef | None clew.propose.astdefs.definition_record(Any node, bytes src, str rel, bool scoped)
Build the FuncDef for one definition node, or None when unusable.
Source · 18 lines
def definition_record(node: Any, src: bytes, rel: str, scoped: bool) -> FuncDef | None:
"""@brief Extract one definition's name, parameters and forwarding calls."""
signature = _signature(node, src)
if signature is None:
return None
name, params, body, body_src = signature
line = node.start_point[0] + 1
return FuncDef(
name=name,
rel_path=rel,
line=line,
params=params,
is_macro=node.type == "preproc_function_def",
in_scope=scoped,
forwards=_forward_calls(body, body_src, params, line) if body is not None else (),
)
Activity · 6 steps
Requirements
Flows
enclosing_definition
tuple[str, tuple[str, ...]] clew.propose.astdefs.enclosing_definition(Any node, bytes src)
The definition enclosing a node, as (name, parameters).
Source · 9 lines
def enclosing_definition(node: Any, src: bytes) -> tuple[str, tuple[str, ...]]:
"""@brief Walk up to the enclosing function definition."""
cur = node.parent
while cur is not None:
if cur.type == "function_definition":
signature = _function_signature(cur, src)
return (signature[0], signature[1]) if signature is not None else ("", ())
cur = cur.parent
return "", ()1 more lines, not shown
Activity · 7 steps
Requirements
text_of
str clew.propose.astdefs.text_of(Any node, bytes src)
Text of a node.
Called by _bare_identifier, _first_identifier, _macro_body, _macro_signature
Calls none
Source · 5 lines
def text_of(node: Any, src: bytes) -> str:
"""@brief Decode one node's source text."""
return src[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
Activity · 1 steps
Requirements
Flows
walk
Any clew.propose.astdefs.walk(Any root)
Iterate every node of a tree-sitter subtree, depth first.
Source · 9 lines
def walk(root: Any) -> Any:
"""@brief Depth-first iteration over a parse subtree."""
stack = [root]
while stack:
node = stack.pop()
stack.extend(node.children)
yield node