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.

clew/propose/astdefs.py:402

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
lines 404–404cur = nodelines 405–405◇ while cur is not None and cur.type in _UNWRAP_TYPESlines 406–406inner = cur.child_by_field_name("value")lines 407–407cur = inner if inner is not None else next(iter(cur.named_children), None)lines 408–408◇ if cur is None or cur.type != "identifier"lines 409–409return ""lines 410–410return text_of(cur, src)

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.

clew/propose/astdefs.py:307

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
lines 315–315found: str | None = Nonelines 316–316stack = [node] if node is not None else []lines 317–317◇ while stack and found is Nonelines 318–318cur = stack.pop()lines 319–319◇ if cur.type in kindslines 320–320found = text_of(cur, src)lines 321–321elselines 324–324stack.extend(reversed(cur.children))lines 325–325return found

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.

clew/propose/astdefs.py:378

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
lines 382–382name = callee_name(node, src)lines 383–383args = node.child_by_field_name("arguments")lines 384–384◇ if not name or args is Nonelines 385–385return Nonelines 386–390mapped = [ (index, positions[ident]) for index, arg in enumerate(args.named_children) if (ident := _bare_identifier(arg, src)) in positions ]lines 391–391◇ if not mappedlines 392–392return Nonelines 393–393return ForwardCall(name, line, tuple(mapped))

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.

clew/propose/astdefs.py:353

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
lines 357–357positions = {name: idx for idx, name in enumerate(params) if name}lines 358–358◇ if not positionslines 359–359return ()lines 360–360found: list[ForwardCall] = []lines 361–361◇ for node in walk(body)lines 362–362◇ if node.type != "call_expression"lines 363–363continuelines 364–364call = _forward_call(node, src, positions, line)lines 365–365◇ if call is not Nonelines 366–366found.append(call)lines 367–367return tuple(found)

Flows

_function_declarator

Any clew.propose.astdefs._function_declarator(Any node)

Descend a declarator chain to its function_declarator .

clew/propose/astdefs.py:266

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
lines 274–274cur = nodelines 275–275◇ while cur is not None and cur.type != "function_declarator"lines 276–276nxt = cur.child_by_field_name("declarator")lines 277–277◇ if nxt is Nonelines 278–278return Nonelines 279–279cur = nxtlines 280–280return cur

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 .

clew/propose/astdefs.py:181

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
lines 183–183declarator = _function_declarator(node.child_by_field_name("declarator"))lines 184–184◇ if declarator is Nonelines 185–185return Nonelines 186–186name_node = declarator.child_by_field_name("declarator")lines 187–187name = _tail_name(name_node, src) if name_node is not None else ""lines 188–188◇ if not namelines 189–189return Nonelines 190–190params = _param_names(declarator.child_by_field_name("parameters"), src)lines 191–191return name, params, node.child_by_field_name("body") or node, src

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.

clew/propose/astdefs.py:220

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
lines 229–229arg = node.child_by_field_name("value")lines 230–230body_text = text_of(arg, src).replace("\\\n", "\n").strip() if arg is not None else ""lines 231–231◇ if not body_textlines 232–232return None, b""lines 233–233wrapped = b"void __docsdb_macro__(void){\n" + body_text.encode("utf-8") + b"\n;}\n"lines 234–234parser = _macro_parser()lines 235–235◇ if parser is Nonelines 236–236return None, b""lines 237–237return parser.parse(wrapped).root_node, wrapped

Flows

_macro_parser

Any clew.propose.astdefs._macro_parser()

Memoised C parser used for macro replacement text.

clew/propose/astdefs.py:247

Show on the map →

Called by _macro_body

Calls none

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
lines 254–254◇ if not _MACRO_PARSERlines 255–255from ..tsnode import Parserlines 257–257_MACRO_PARSER.append(Parser("c"))lines 258–258return _MACRO_PARSER[0]

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 .

clew/propose/astdefs.py:200

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
lines 202–202name_node = node.child_by_field_name("name")lines 203–203◇ if name_node is Nonelines 204–204return Nonelines 205–205params_node = node.child_by_field_name("parameters")lines 206–210params = ( tuple(text_of(c, src) for c in params_node.named_children if c.type == "identifier") if params_node is not None else () )lines 211–211return text_of(name_node, src), params

Flows

_param_names

tuple[str, ...] clew.propose.astdefs._param_names(Any params_node, bytes src)

Parameter identifiers of a parameter list, in declaration order.

clew/propose/astdefs.py:334

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
lines 336–336◇ if params_node is Nonelines 337–337return ()lines 338–342return tuple( _first_identifier(child, src, ("identifier",)) or "" for child in params_node.named_children if child.type in _PARAM_TYPES )

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.

clew/propose/astdefs.py:159

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
lines 167–167◇ if node.type == "preproc_function_def"lines 168–168named = _macro_signature(node, src)lines 169–169body, body_src = _macro_body(node, src) if named else (None, b"")lines 170–170return (*named, body, body_src) if named else Nonelines 171–171signature = _function_signature(node, src)lines 172–172return signature

Flows

_tail_name

str clew.propose.astdefs._tail_name(Any node, bytes src)

The trailing simple name of a declarator node.

clew/propose/astdefs.py:289

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
lines 296–296found = _first_identifier(node, src, ("identifier", "field_identifier"))lines 297–297return found or ""

Flows

callee_name

str clew.propose.astdefs.callee_name(Any node, bytes src)

The callee's text when it is an identifier / qualified identifier.

clew/propose/astdefs.py:108

Show on the map →

Called by _accessor_site, _collect_watched, _forward_call

Calls none

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
lines 110–110callee = node.child_by_field_name("function")lines 111–111◇ if callee is None or callee.type not in CALLEE_TYPESlines 112–112return ""lines 113–113return src[callee.start_byte : callee.end_byte].decode("utf-8", errors="replace")

Requirements

REQ-DDB-CONFIG-001

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.

clew/propose/astdefs.py:135

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
lines 137–137signature = _signature(node, src)lines 138–138◇ if signature is Nonelines 139–139return Nonelines 140–140name, params, body, body_src = signaturelines 141–141line = node.start_point[0] + 1lines 142–150return 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 (), )

Requirements

REQ-DDB-CONFIG-001

Flows

enclosing_definition

tuple[str, tuple[str, ...]] clew.propose.astdefs.enclosing_definition(Any node, bytes src)

The definition enclosing a node, as (name, parameters).

clew/propose/astdefs.py:419

Show on the map →

Called by _call_site

Calls _function_signature

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
lines 421–421cur = node.parentlines 422–422◇ while cur is not Nonelines 423–423◇ if cur.type == "function_definition"lines 424–424signature = _function_signature(cur, src)lines 425–425return (signature[0], signature[1]) if signature is not None else ("", ())lines 426–426cur = cur.parentlines 427–427return "", ()

Requirements

REQ-DDB-CONFIG-001

text_of

str clew.propose.astdefs.text_of(Any node, bytes src)

Text of a node.

clew/propose/astdefs.py:122

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
lines 124–124return src[node.start_byte : node.end_byte].decode("utf-8", errors="replace")

Requirements

REQ-DDB-CONFIG-001

Flows

walk

Any clew.propose.astdefs.walk(Any root)

Iterate every node of a tree-sitter subtree, depth first.

clew/propose/astdefs.py:93

Show on the map →

Called by none

Calls none

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

Activity · 5 steps
lines 95–95stack = [root]lines 96–96◇ while stacklines 97–97node = stack.pop()lines 98–98stack.extend(node.children)lines 99–99yield node

Requirements

REQ-DDB-CONFIG-001