ast_symbols.py

clew/ast_symbols.py

gh#11 — recover the function definitions doxygen never emitted.

_recover_class_fields_into

int clew.ast_symbols._recover_class_fields_into(sqlite3.Connection conn, Any harvested)

Insert the Python class attributes doxygen dropped, linked to their compound.

clew/ast_symbols.py:2167

Source · 50 lines
def _recover_class_fields_into(conn: sqlite3.Connection, harvested: Any) -> int:
    """gh#17. doxygen's Python parser drops a class attribute written as a bare annotation
    with a simple-identifier type — `name: str` — while keeping `line: int | None` and
    `brief: str = ""`. Measured on this repository: 164 of 357 fields in
    `clew/query/models.py` reached the index, all 49 dataclasses were short, and
    `LockNestingPair` reported an EMPTY member list for a class declaring ten fields.

    WRITES THE `member` LINK TOO, which is what makes this different from every other
    recovery here. The existing kinds are file-scope, so a `memberdef` row is the whole
    answer; a class attribute is only reachable through `member(scope_rowid,
    memberdef_rowid)`, and a row without that link is present in the table and absent from
    every class view — the defect in a subtler form.

    THE COMPOUND IS MATCHED BY (file, name tail), not by name alone. doxygen names a Python
    class `module::ClassName`, and two modules may each declare a `Config`; the file the
    attribute was parsed from settles it, and a single file cannot declare one class name
    twice.

    DEDUPED AGAINST THE EXISTING LINKS, so the fields doxygen DID emit are left alone
    rather than duplicated under a second row. The harvest deliberately collects all of
    them — which are already present is a fact about the database, not about the source.

    @brief Insert recovered Python class attributes and link them to their class.
    @return Rows inserted.
    @version 1
    """
    if not all(_table_exists(conn, t) for t in ("compounddef", "member")):
        return 0
    compounds = _compounds_by_file_and_tail(conn)
    linked = {
        (int(scope), str(name))
        for scope, name in conn.execute(
            "SELECT mm.scope_rowid, m.name FROM member mm "
            "JOIN memberdef m ON m.rowid = mm.memberdef_rowid"
        )
    }
    inserted = 0
    for file_rowid, payload in harvested:
        for name, class_name, type_text, line in payload.get(_PAYLOAD_CLASS_FIELDS, []):
            scope_rowid = compounds.get((file_rowid, class_name))
            if scope_rowid is None or (scope_rowid, name) in linked:
                continue
            _insert_recovered_class_field(
                conn, file_rowid, scope_rowid, name, class_name, type_text, line
            )
            linked.add((scope_rowid, name))
            inserted += 1
    return inserted

Activity · 14 steps
lines 2193–2193◇ if not all(_table_exists(conn, t) for t in ("compounddef", "member"))lines 2194–2194return 0lines 2195–2195compounds = _compounds_by_file_and_tail(conn)lines 2196–2202linked = { (int(scope), str(name)) for scope, name in conn.execute( "SELECT mm.scope_rowid, m.name FROM member mm " "JOIN memberdef m ON m.rowid = mm.memberdef_rowid" ) }lines 2203–2203inserted = 0lines 2204–2204◇ for file_rowid, payload in harvestedlines 2205–2205◇ for name, class_name, type_text, line in payload.get(_PAYLOAD_CLASS_FIELDS, [])lines 2206–2206scope_rowid = compounds.get((file_rowid, class_name))lines 2207–2207◇ if scope_rowid is None or (scope_rowid, name) in linkedlines 2208–2208continuelines 2209–2211_insert_recovered_class_field( conn, file_rowid, scope_rowid, name, class_name, type_text, line )lines 2212–2212linked.add((scope_rowid, name))lines 2213–2213inserted += 1lines 2214–2214return inserted

Requirements

REQ-DDB-INDEX-004

_recover_enumerators_into

int clew.ast_symbols._recover_enumerators_into(sqlite3.Connection conn, Any harvested)

Insert the enum values doxygen emits no rows for.

clew/ast_symbols.py:2081

Show on the map →

Called by _recover_into

Calls _covered_names, _insert_recovered_enumerator

Source · 34 lines
def _recover_enumerators_into(conn: sqlite3.Connection, harvested: Any) -> int:
    """gh#6. doxygen emits NO `enumvalue` rows — zero on entropic against 35 `enumeration`
    rows — so an enum value was addressable by nothing: `dossier` missed it and `search`
    could not find it, on a codebase whose authoritative definitions are C enums.

    `kind='enumvalue'` is doxygen's OWN vocabulary value for this, listed in its schema
    beside the kinds it does write, so this adds no column, no table and no CHECK value.
    The declaring enum goes in `scope` — the same column doxygen uses to say which class a
    member belongs to — and the initialiser, when one is written, in `initializer`.

    NO `member` LINK, unlike the class attributes beside it, and the difference is real
    rather than an omission: a C enum is a `memberdef` and not a `compounddef`, so there is
    no compound to link to. The relation is carried by `scope`, which is what the query
    layer reads back.

    Deduped by (file, name) through `_covered_names`, the same rule the variable recovery
    uses, so a value doxygen somehow did emit is left alone rather than doubled.

    @brief Insert recovered enum values, scoped to their enum.
    @return Rows inserted.
    @version 1
    """
    covered = _covered_names(conn)
    inserted = 0
    for file_rowid, payload in harvested:
        for name, enum_name, value, line in payload.get(_PAYLOAD_ENUMERATORS, []):
            if (file_rowid, name) in covered:
                continue
            _insert_recovered_enumerator(conn, file_rowid, name, enum_name, value, line)
            covered.add((file_rowid, name))
            inserted += 1
    return inserted

Activity · 10 steps
lines 2103–2103covered = _covered_names(conn)lines 2104–2104inserted = 0lines 2105–2105◇ for file_rowid, payload in harvestedlines 2106–2106◇ for name, enum_name, value, line in payload.get(_PAYLOAD_ENUMERATORS, [])lines 2107–2107◇ if (file_rowid, name) in coveredlines 2108–2108continuelines 2109–2109_insert_recovered_enumerator(conn, file_rowid, name, enum_name, value, line)lines 2110–2110covered.add((file_rowid, name))lines 2111–2111inserted += 1lines 2112–2112return inserted

Requirements

REQ-DDB-INDEX-004

definition

str clew.ast_symbols.ParsedVariable.definition(self)

doxygen's own definition spelling for this variable.

clew/ast_symbols.py:391

Show on the map →

Called by none

Calls none

Source · 24 lines
    def definition(self) -> str:
        """Matches the convention doxygen already uses for its own variable rows —
        one reads `size_t mbedtls_ecp_group::nbits` and another
        `FStar_UInt128_uint128(* FStar_UInt128_op_Plus_Hat) (...)` — so a consumer
        reading `definition` gets the same shape whichever provenance the row has.
        Read off a real index rather than invented, because a second spelling for one
        column is what makes a caller write two parsers.

        THE DECLARATOR, NOT THE BARE NAME, and this was a measured correction. A C
        `declaration`'s `type` field holds only the BASE type: for
        `int (*mbedtls_mutex_lock)(mbedtls_threading_mutex_t *)` it is just `int`, with
        the pointer-to-function part living in the declarator. Building the definition
        from the name alone therefore published mbedtls's lock PRIMITIVE as
        `int mbedtls_mutex_lock` — indistinguishable from an integer counter, on the
        one row whose whole value is telling a reader it is a function pointer rather
        than a mutex object. Confirmed on the built index before the fix.

        @brief Render the type-and-declarator definition string.
        @return The definition text.
        @version 2
        """
        return f"{self.type_text} {self.declarator_text or self.name}".strip()

Activity · 1 steps
lines 412–412return f"{self.type_text} {self.declarator_text or self.name}".strip()

Requirements

REQ-DDB-INDEX-004

ensure_symbol_provenance

bool clew.ast_symbols.ensure_symbol_provenance(sqlite3.Connection conn)

Add the provenance column to doxygen's memberdef table, idempotently.

clew/ast_symbols.py:1610

Source · 30 lines
def ensure_symbol_provenance(conn: sqlite3.Connection) -> bool:
    """HOW A COLUMN GETS ONTO A TABLE WE DO NOT CREATE. `memberdef` is created by
    doxygen's own sqlite3 backend; the pipeline copies that file to `clew.db` and
    augments the copy (`doxygen.copy_database`), and it already UPDATEs, DELETEs and
    re-NAMEs rows in it — `doxygen._repair_one_attribute_row` does all three. So the
    copy is ours to alter, and `ALTER TABLE ... ADD COLUMN` is the right instrument.

    The `NOT NULL DEFAULT 'doxygen'` is the load-bearing part. It labels every row
    doxygen already wrote, retroactively and correctly, with no UPDATE sweep and no
    window in which a row exists unlabelled — which also means an index built by an
    older clew is not wrong about provenance, merely silent about it. SQLite
    rewrites the stored CREATE TABLE text, so the generated CHECK is visible in
    `sqlite_master` and the schema-reconcile test accounts for it like any other.

    Idempotent, because the R4/viewer surfaces and the tests may open a database
    that has already been through a build.

    @brief Ensure `memberdef` carries its provenance column.
    @return True when the column was newly added.
    @version 3
    """
    if _has_column(conn, "memberdef", SYMBOL_SOURCE_COLUMN):
        return False
    conn.execute(
        f"ALTER TABLE memberdef ADD COLUMN {SYMBOL_SOURCE_COLUMN} TEXT NOT NULL "
        f"DEFAULT '{SYMBOL_SOURCE_DOXYGEN}' {check('memberdef', SYMBOL_SOURCE_COLUMN)}"
    )
    return True

Activity · 4 steps
lines 1631–1631◇ if _has_column(conn, "memberdef", SYMBOL_SOURCE_COLUMN)lines 1632–1632return Falselines 1633–1636conn.execute( f"ALTER TABLE memberdef ADD COLUMN {SYMBOL_SOURCE_COLUMN} TEXT NOT NULL " f"DEFAULT '{SYMBOL_SOURCE_DOXYGEN}' {check('memberdef', SYMBOL_SOURCE_COLUMN)}" )lines 1637–1637return True

Requirements

REQ-DDB-INDEX-004

function_definition_harvester

Harvester clew.ast_symbols.function_definition_harvester()

The recovered-symbol stage's harvester.

clew/ast_symbols.py:1557

Source · 12 lines
def function_definition_harvester() -> Harvester:
    """Public factory so gh#358's shared parse pass can warm this stage's cache rows
    from the same construction site the stage itself uses. This stage still EMITS
    first — every later layer resolves endpoints to the memberdef rowids it writes —
    and sharing a parse does not share an emit.

    @brief Build this stage's harvester.
    @version 1
    """
    return _FunctionDefinitionHarvester()

Activity · 1 steps
lines 1566–1566return _FunctionDefinitionHarvester()

Requirements

REQ-DDB-PIPE-003

harvest

Any clew.ast_symbols._FunctionDefinitionHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's function definitions, file-scope variables, typedefs and macros.

clew/ast_symbols.py:1125

Source · 57 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        """Returns plain lists rather than dataclass instances because the payload is
        JSON round-tripped through the cache — a dataclass would come back as a list
        on a cache HIT and as a dataclass on a MISS, which is the kind of shape
        divergence that only shows up on the second build.

        PYTHON NOW RECOVERS FUNCTIONS TOO (gh#397), and only functions: there is no
        Python analogue of a file-scope C variable declaration worth recovering here —
        a module-level assignment is already indexed, and `harvest_variable_declarations`
        reads C declarator shapes that the Python grammar does not produce. Nor is there a
        Python analogue of a `#define`: tree-sitter-python emits no `preproc_*` node, so
        the Python branch omits the key and never runs the macro walk — which would have
        returned an empty list, but paying for a whole traversal to learn that on every
        Python file in every repository is a cost with no answer at the end of it.

        @brief Per-file definition, variable, typedef, macro, class-field and enumerator extraction.
        @version 6
        """
        if is_python_tree(tree):
            return {
                _PAYLOAD_FUNCTIONS: [
                    [f.name, f.qualified, f.args, int(f.static), f.start, f.end]
                    for f in harvest_python_definitions(tree, src_bytes)
                ],
                _PAYLOAD_VARIABLES: [],
                ## gh#17. Python ONLY: a C struct field is already emitted by doxygen, so
                ## this walk would cost a traversal per file to learn nothing.
                _PAYLOAD_CLASS_FIELDS: [
                    [f.name, f.class_name, f.type_text, f.line]
                    for f in harvest_python_class_fields(tree, src_bytes)
                ],
            }
        return {
            _PAYLOAD_FUNCTIONS: [
                [f.name, f.qualified, f.args, int(f.static), f.start, f.end]
                for f in harvest_function_definitions(tree, src_bytes)
            ],
            _PAYLOAD_VARIABLES: [
                [v.name, v.type_text, v.declarator_text, int(v.static), v.line]
                for v in harvest_variable_declarations(tree, src_bytes)
            ],
            _PAYLOAD_TYPEDEFS: [
                [t.name, t.type_text, t.declarator_text, int(t.static), t.line]
                for t in harvest_type_definitions(tree, src_bytes)
            ],
            _PAYLOAD_MACROS: [
                [m.name, list(m.params), m.expansion, m.line]
                for m in harvest_macro_definitions(tree, src_bytes)
            ],
            ## gh#6. C/C++ ONLY: a Python enum is a class whose members doxygen already
            ## emits, so the walk would cost a traversal per file to learn nothing.
            _PAYLOAD_ENUMERATORS: [
                [e.name, e.enum_name, e.value, e.line] for e in harvest_enumerators(tree, src_bytes)
            ],
        }

Activity · 3 steps
lines 1143–1143◇ if is_python_tree(tree)lines 1144–1156return { _PAYLOAD_FUNCTIONS: [ [f.name, f.qualified, f.args, int(f.static), f.start, f.end] for f in harvest_python_definitions(tree, src_bytes) ], _PAYLOAD_VARIABLES: [], ## gh#17. Python ONLY: a C struct field is already emitted by doxygen, so ## this walk would cost a traversal per file to learn nothing. _PAYLOAD_CLASS_FIELDS: [ [f.name, f.class_name, f.type_text, f.line] for f in harvest_python_class_fields(tree, src_bytes) ], }lines 1157–1179return { _PAYLOAD_FUNCTIONS: [ [f.name, f.qualified, f.args, int(f.static), f.start, f.end] for f in harvest_function_definitions(tree, src_bytes) ], _PAYLOAD_VARIABLES: [ [v.name, v.type_text, v.declarator_text, int(v.static), v.line] for v in harvest_variable_declarations(tree, src_bytes) ], _PAYLOAD_TYPEDEFS: [ [t.name, t.type_text, t.declarator_text, int(t.static), t.line] for t in harvest_type_definitions(tree, src_bytes) ], _PAYLOAD_MACROS: [ [m.name, list(m.params), m.expansion, m.line] for m in harvest_macro_definitions(tree, src_bytes) ], ## gh#6. C/C++ ONLY: a Python enum is a class whose members doxygen already ## emits, so the walk would cost a traversal per file to learn nothing. _PAYLOAD_ENUMERATORS: [ [e.name, e.enum_name, e.value, e.line] for e in harvest_enumerators(tree, src_bytes) ], }

Requirements

REQ-DDB-INDEX-004

harvest_enumerators

list[ParsedEnumerator] clew.ast_symbols.harvest_enumerators(Any tree, bytes src_bytes)

Every enumerator declared in one parsed C/C++ tree.

clew/ast_symbols.py:1221

Show on the map →

Called by harvest

Tested by

1 teststest_an_enum_class_in_a_dot_h_still_yields_its_values

Calls _enum_name, _enumerators_of

Source · 35 lines
def harvest_enumerators(tree: Any, src_bytes: bytes) -> list[ParsedEnumerator]:
    """THE ANONYMOUS TYPEDEF IS THE COMMON CASE, NOT THE EDGE CASE. `typedef enum { ... }
    ent_decision_t;` gives an `enum_specifier` with NO name — the name is on the enclosing
    `type_definition` — and that is the shape entropic's own enums use. Reading only the
    specifier's `name` field would harvest the values of every C enum under an empty string
    and file them all together.

    An enum with neither a name nor a typedef is skipped rather than given a placeholder:
    its values are real, but nothing here can say what declares them, and an invented
    scope is worse than a missing row.

    FAILS CLOSED ON `enum class` UNDER THE C GRAMMAR, which parses it as an enum named
    `class` with no body — so the values are simply not found. A miss, not a fabrication;
    the C++ grammar reads it correctly, and `.h` reparsing (gh#50) is what routes a C++
    header to it.

    @brief Collect a file's enumerators with the enum that declares them.
    @return ParsedEnumerator records.
    @version 1
    """
    found: list[ParsedEnumerator] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        stack.extend(node.children)
        if node.type != _ENUM_SPECIFIER:
            continue
        enum_name = _enum_name(node, src_bytes)
        body = node.child_by_field_name("body")
        if not enum_name or body is None:
            continue
        found.extend(_enumerators_of(body, enum_name, src_bytes))
    return found

Activity · 13 steps
lines 1241–1241found: list[ParsedEnumerator] = []lines 1242–1242stack = [tree.root_node]lines 1243–1243◇ while stacklines 1244–1244node = stack.pop()lines 1245–1245stack.extend(node.children)lines 1246–1246◇ if node.type != _ENUM_SPECIFIERlines 1247–1247continuelines 1248–1248enum_name = _enum_name(node, src_bytes)lines 1249–1249body = node.child_by_field_name("body")lines 1250–1250◇ if not enum_name or body is Nonelines 1251–1251continuelines 1252–1252found.extend(_enumerators_of(body, enum_name, src_bytes))lines 1253–1253return found

Requirements

REQ-DDB-INDEX-004

harvest_function_definitions

list[ParsedFunction] clew.ast_symbols.harvest_function_definitions(Any tree, bytes src_bytes)

Version 2 (gh#62): an error-recovered definition ends where its body's braces close, a definition swallowed by one is found inside it, and a C keyword is never a function name.

clew/ast_symbols.py:566

Source · 32 lines
def harvest_function_definitions(tree: Any, src_bytes: bytes) -> list[ParsedFunction]:
    """Does NOT descend into a definition once one is found. A function nested
    inside another (a GNU nested function, or a lambda the grammar happened to
    shape as a definition) would otherwise be recorded as a second symbol whose
    span sits INSIDE its parent's — and the span-overlap dedup would then reject
    whichever of the two it saw second, making the outcome order-dependent.

    Class and namespace bodies ARE descended into, because a method defined
    in-class is a top-level symbol as far as this stage is concerned.

    @brief Collect a C/C++ file's function definitions.
    @return ParsedFunction records.
    @version 1
    """
    found: list[ParsedFunction] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        if node.type != _FUNCTION_DEFINITION:
            stack.extend(reversed(node.children))
            continue
        parsed = _parsed_function(node, src_bytes)
        if parsed is not None and node.has_error:
            parsed = _brace_extent(parsed, node, src_bytes)
            ## AN ERROR-RECOVERED NODE CAN HOLD WHOLE DEFINITIONS: mbedtls's overrunning
            ## `ssl_parse_server_key_exchange` contained the eight that follow it in the file.
            stack.extend(reversed(node.children))
        if parsed is not None:
            found.append(parsed)
    return _settled(found)

Activity · 14 steps
lines 580–580found: list[ParsedFunction] = []lines 581–581stack = [tree.root_node]lines 582–582◇ while stacklines 583–583node = stack.pop()lines 584–584◇ if node.type != _FUNCTION_DEFINITIONlines 585–585stack.extend(reversed(node.children))lines 586–586continuelines 587–587parsed = _parsed_function(node, src_bytes)lines 588–588◇ if parsed is not None and node.has_errorlines 589–589parsed = _brace_extent(parsed, node, src_bytes)lines 592–592stack.extend(reversed(node.children))lines 593–593◇ if parsed is not Nonelines 594–594found.append(parsed)lines 595–595return _settled(found)

Requirements

REQ-DDB-INDEX-004

harvest_macro_definitions

list[ParsedMacro] clew.ast_symbols.harvest_macro_definitions(Any tree, bytes src_bytes)

A C/C++ file's #define s, including ones in a branch the preprocessor drops.

clew/ast_symbols.py:985

Source · 29 lines
def harvest_macro_definitions(tree: Any, src_bytes: bytes) -> list[ParsedMacro]:
    """SKIPS NOTHING, unlike the variable and typedef walks, and that is deliberate
    rather than an oversight. A `#define` is translation-unit scoped WHEREVER it
    textually sits: one written inside a function body or between two class members is
    still a file-scope macro, so the `function_definition` /
    `field_declaration_list` skips those walks need in order to avoid recovering locals
    and members would here DISCARD real macros for no benefit.

    It does not descend into an accepted node either, for a reason the other walks do
    not have: a function-like macro's replacement text can itself contain `#`, and
    `preproc_arg` is a single opaque token, so there is nothing to find below.

    @brief Collect a C/C++ file's preprocessor definitions.
    @return ParsedMacro records.
    @version 1
    """
    found: list[ParsedMacro] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        if node.type not in _MACRO_DEF_NODES:
            stack.extend(reversed(node.children))
            continue
        parsed = _parsed_macro(node, src_bytes)
        if parsed is not None:
            found.append(parsed)
    return found

Activity · 11 steps
lines 1001–1001found: list[ParsedMacro] = []lines 1002–1002stack = [tree.root_node]lines 1003–1003◇ while stacklines 1004–1004node = stack.pop()lines 1005–1005◇ if node.type not in _MACRO_DEF_NODESlines 1006–1006stack.extend(reversed(node.children))lines 1007–1007continuelines 1008–1008parsed = _parsed_macro(node, src_bytes)lines 1009–1009◇ if parsed is not Nonelines 1010–1010found.append(parsed)lines 1011–1011return found

Requirements

REQ-DDB-PIPE-003

harvest_python_class_fields

list[ParsedClassField] clew.ast_symbols.harvest_python_class_fields(Any tree, bytes src_bytes)

Every annotated attribute declared directly in a Python class body.

clew/ast_symbols.py:1359

Source · 39 lines
def harvest_python_class_fields(tree: Any, src_bytes: bytes) -> list[ParsedClassField]:
    """DIRECT CHILDREN OF THE CLASS BODY ONLY, which is what keeps a method's locals out.
    An annotated local inside a method is indented under the class and looks identical to a
    field one level deeper; a recursive walk collects it and files it under the class as a
    member that does not exist. Reading only the body block's own statements makes that
    structural rather than a filter someone can forget.

    ANNOTATED ONLY. `CONST = 3` is a real class attribute and doxygen already emits it — a
    value assignment always saves a row — so recovering it would duplicate what the index
    holds. The `type` field is present exactly when an annotation was written, so it is both
    the thing that identifies a field and the thing that identifies doxygen's blind spot.

    Harvests ALL annotated fields, including the ones doxygen DID emit. Which rows are
    already present is a question about the database, and answering it here would put the
    dedup rule in the parser where it cannot see the index — the same split
    `harvest_variable_declarations` keeps from `_recoverable_variables`.

    @brief Collect a Python file's annotated class attributes.
    @return ParsedClassField records.
    @version 1
    """
    found: list[ParsedClassField] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        stack.extend(node.children)
        if node.type != _PY_CLASS_DEFINITION:
            continue
        name_node = node.child_by_field_name("name")
        body = node.child_by_field_name("body")
        if name_node is None or body is None:
            continue
        class_name = src_bytes[name_node.start_byte : name_node.end_byte].decode(
            "utf-8", errors="replace"
        )
        found.extend(_class_body_fields(body, class_name, src_bytes))
    return found

Activity · 14 steps
lines 1380–1380found: list[ParsedClassField] = []lines 1381–1381stack = [tree.root_node]lines 1382–1382◇ while stacklines 1383–1383node = stack.pop()lines 1384–1384stack.extend(node.children)lines 1385–1385◇ if node.type != _PY_CLASS_DEFINITIONlines 1386–1386continuelines 1387–1387name_node = node.child_by_field_name("name")lines 1388–1388body = node.child_by_field_name("body")lines 1389–1389◇ if name_node is None or body is Nonelines 1390–1390continuelines 1391–1393class_name = src_bytes[name_node.start_byte : name_node.end_byte].decode( "utf-8", errors="replace" )lines 1394–1394found.extend(_class_body_fields(body, class_name, src_bytes))lines 1395–1395return found

Requirements

REQ-DDB-INDEX-004

harvest_python_definitions

list[ParsedFunction] clew.ast_symbols.harvest_python_definitions(Any tree, bytes src_bytes)

A Python file's function and method definitions, qualified by enclosing class.

clew/ast_symbols.py:1468

Source · 44 lines
def harvest_python_definitions(tree: Any, src_bytes: bytes) -> list[ParsedFunction]:
    """WHY THIS EXISTS AT ALL, having been refused for the life of this module. The
    refusal's stated ground was "doxygen indexes Python fully — a Doxyfile-less Python
    codebase measured 4,739 functions — so there is nothing to recover there". That premise
    is FALSE, measured on this repository's own index at build 42:
    `tests/test_mcp_server.py` declares 93 top-level functions and doxygen emitted 41.
    Fifty-two are absent from every table, not misattributed and not truncated (rows reach
    the file's last line). So the backstop for doxygen's misses was switched off on the
    grounds that doxygen does not miss.

    The second stated ground — "a `function_definition` inside a Python `class` would need
    scope handling this stage does not do" — was true of THIS module and not of the package:
    `pyast.class_ranges`/`enclosing_class` already do exactly that, for the call-edge layer.
    Reused here rather than reimplemented, so one answer to "which class is this in" serves
    both.

    DOES NOT DESCEND INTO A DEFINITION, matching the C harvester and for the same reason: a
    closure or a nested helper would otherwise be recorded as a symbol whose span sits INSIDE
    its parent's, and the span-overlap dedup would then reject whichever it saw second,
    making the result order-dependent. Locals stay out; methods come in, qualified.

    @brief Collect a Python file's `def`s, including decorated ones and methods.
    @return ParsedFunction records.
    @version 1
    """
    ranges = class_ranges(tree, src_bytes)
    found: list[ParsedFunction] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        ## A decorated definition is a WRAPPER: descend into it so the `def` inside is seen,
        ## but never treat the wrapper itself as the symbol.
        if node.type not in (_PY_FUNCTION_DEFINITION, _PY_DECORATED):
            stack.extend(reversed(node.children))
            continue
        if node.type == _PY_DECORATED:
            stack.extend(reversed(node.children))
            continue
        parsed = _parsed_python_function(node, src_bytes, ranges)
        if parsed is not None:
            found.append(parsed)
    return found

Activity · 15 steps
lines 1493–1493ranges = class_ranges(tree, src_bytes)lines 1494–1494found: list[ParsedFunction] = []lines 1495–1495stack = [tree.root_node]lines 1496–1496◇ while stacklines 1497–1497node = stack.pop()lines 1500–1500◇ if node.type not in (_PY_FUNCTION_DEFINITION, _PY_DECORATED)lines 1501–1501stack.extend(reversed(node.children))lines 1502–1502continuelines 1503–1503◇ if node.type == _PY_DECORATEDlines 1504–1504stack.extend(reversed(node.children))lines 1505–1505continuelines 1506–1506parsed = _parsed_python_function(node, src_bytes, ranges)lines 1507–1507◇ if parsed is not Nonelines 1508–1508found.append(parsed)lines 1509–1509return found

Requirements

REQ-DDB-PIPE-003

harvest_type_definitions

list[ParsedVariable] clew.ast_symbols.harvest_type_definitions(Any tree, bytes src_bytes)

A C/C++ file's typedef names, including ones behind unsatisfied guards.

clew/ast_symbols.py:839

Source · 46 lines
def harvest_type_definitions(tree: Any, src_bytes: bytes) -> list[ParsedVariable]:
    """gh#395, and it is gh#11 one kind over. The MEASURED gap:
    `dossier("mbedtls_threading_mutex_t")` returns the alt-dummy at
    `tests/include/alt-dummy/threading_alt.h` — a `struct { int dummy; }` — while the real
    pthread-backed type at `include/mbedtls/threading.h:29` produces NO ROW IN ANY TABLE,
    because it sits behind `MBEDTLS_THREADING_PTHREAD`. Exactly one `compounddef` row exists
    for that name, so resolution picked the only row available and was right to.

    THAT IS WHY IT WAS NEARLY MISFILED AS A RANKING BUG. A test-path demotion tier would
    have produced a green test proving a demotion worked while the real type stayed
    invisible. "No rows" is a claim about the detector until you read the source.

    REUSES `ParsedVariable`, which is the honest shape: a typedef has a name, a declared
    text and a line, and NO BODY SPAN — the same three facts, and the same absence, that
    type already models for a variable. Recovered as `kind='typedef'`, which is doxygen's
    OWN vocabulary value and already in `SEARCHED_MEMBERDEF_KINDS`, so the recovered type
    becomes findable with no schema change and no new enum.

    MEMBERS ARE NOT RECOVERED HERE, deliberately and it is a real limitation. mbedtls
    declares them as `pthread_mutex_t MBEDTLS_PRIVATE(mutex)` — the member names are wrapped
    in a MACRO, which is the same blindness this project has recorded three times, and
    unwrapping it correctly is Q2's own subject rather than a detail of this walk. Members
    need `compounddef` + `member` writes; this gives existence, kind, file and line.

    Skips the same subtrees as the variable walk: a typedef inside a function body or a
    class member list is not a file-scope type.

    @brief Collect a C/C++ file's typedef definitions.
    @return ParsedVariable records.
    @version 1
    """
    found: list[ParsedVariable] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        if node.type in _VARIABLE_WALK_SKIPS:
            continue
        if node.type != _TYPE_DEFINITION:
            stack.extend(reversed(node.children))
            continue
        parsed = _parsed_typedef(node, src_bytes)
        if parsed is not None:
            found.append(parsed)
    return found

Activity · 13 steps
lines 870–870found: list[ParsedVariable] = []lines 871–871stack = [tree.root_node]lines 872–872◇ while stacklines 873–873node = stack.pop()lines 874–874◇ if node.type in _VARIABLE_WALK_SKIPSlines 875–875continuelines 876–876◇ if node.type != _TYPE_DEFINITIONlines 877–877stack.extend(reversed(node.children))lines 878–878continuelines 879–879parsed = _parsed_typedef(node, src_bytes)lines 880–880◇ if parsed is not Nonelines 881–881found.append(parsed)lines 882–882return found

Requirements

REQ-DDB-PIPE-003

harvest_variable_declarations

list[ParsedVariable] clew.ast_symbols.harvest_variable_declarations(Any tree, bytes src_bytes)

Every file-scope variable declaration in one parsed C/C++ tree.

clew/ast_symbols.py:793

Show on the map →

Called by harvest

Calls _parsed_variables

Source · 29 lines
def harvest_variable_declarations(tree: Any, src_bytes: bytes) -> list[ParsedVariable]:
    """Skips `function_definition` and `field_declaration_list` subtrees entirely, so
    a function's locals and a C++ class's members are never reached — the two ways a
    `declaration` node can be something other than a global. It also does not descend
    into a `declaration` it has already read, so a declaration nested inside another
    cannot produce a second record for the same name.

    A `declaration` inside a `preproc_if` IS reached, and that is the whole point:
    mbedtls's five global mutexes sit under `#if defined(MBEDTLS_FS_IO)` and friends,
    which is why doxygen never emitted them. Verified by probe — tree-sitter shapes
    them as `translation_unit → preproc_if → declaration`.

    @brief Collect a C/C++ file's file-scope variable declarations.
    @return ParsedVariable records.
    @version 1
    """
    found: list[ParsedVariable] = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        if node.type in _VARIABLE_WALK_SKIPS:
            continue
        if node.type != _DECLARATION:
            stack.extend(reversed(node.children))
            continue
        found.extend(_parsed_variables(node, src_bytes))
    return found

Activity · 11 steps
lines 809–809found: list[ParsedVariable] = []lines 810–810stack = [tree.root_node]lines 811–811◇ while stacklines 812–812node = stack.pop()lines 813–813◇ if node.type in _VARIABLE_WALK_SKIPSlines 814–814continuelines 815–815◇ if node.type != _DECLARATIONlines 816–816stack.extend(reversed(node.children))lines 817–817continuelines 818–818found.extend(_parsed_variables(node, src_bytes))lines 819–819return found

Requirements

REQ-DDB-INDEX-004

overlaps

bool clew.ast_symbols.ParsedFunction.overlaps(self, int other_start, int other_end)

True when this definition's body overlaps a given line span.

clew/ast_symbols.py:342

Show on the map →

Called by none

Calls start, start

Source · 20 lines
    def overlaps(self, other_start: int, other_end: int) -> bool:
        """Closed-interval overlap on both ends: doxygen's `bodystart` is the
        signature line and its `bodyend` the closing brace, and tree-sitter's
        `function_definition` span covers the same extent, so a genuine match
        overlaps heavily rather than merely touching. A single shared line is
        still treated as a match because the failure direction is deliberate —
        dropping a real symbol is a known limitation, duplicating one is not.

        An `other_end` below `other_start` (doxygen records `-1` for a body it
        never saw closed) collapses to the single line `other_start`, so a
        malformed span cannot match everything after it.

        @brief Do this definition's lines intersect the given span?
        @return True on any shared line.
        @version 1
        """
        end = max(other_end, other_start)
        return self.start <= end and other_start <= self.end

Activity · 2 steps
lines 358–358end = max(other_end, other_start)lines 359–359return self.start <= end and other_start <= self.end

Requirements

REQ-DDB-INDEX-004

recover_ast_symbols

int clew.ast_symbols.recover_ast_symbols(Path db_path, Path repo_root, IndexCache|None cache=None)

Recover the function definitions doxygen did not emit.

clew/ast_symbols.py:2044

Show on the map →

Called by _build_stages, run_real_stages

Tested by

25 teststest_a_bare_call_reaches_a_RECOVERED_definition, test_a_declaration_only_header_contributes_no_phantom_body, test_a_documented_declaration_keeps_its_brief_when_its_body_is_recovered, test_a_function_doxygen_already_emitted_is_never_duplicated, test_a_function_local_never_becomes_a_global, test_a_function_pointer_global_is_a_variable_and_a_prototype_is_not, test_a_guarded_global_is_recovered_with_its_declared_type, test_a_macro_only_dossier_carries_the_first_sites_gates, test_a_parsed_row_carries_no_brief_and_nothing_pretends_otherwise, test_a_parsed_row_is_distinguishable_from_a_doxygen_row_at_every_surface, test_a_recovered_global_is_findable_through_search_and_typed_as_a_variable, test_a_recovered_variable_carries_no_body_and_no_bodyfile
13 moretest_decl_def_duality_survives_and_the_two_rows_stay_one_function, test_each_definition_site_reports_its_own_gate_polarity, test_one_declaration_declaring_two_names_yields_two_rows, test_recovery_inserts_the_guarded_functions_and_marks_them_ast, test_recovery_is_idempotent_for_macros, test_recovery_lowers_the_barren_ratio_and_leaves_the_documented_gap_visible, test_running_recovery_twice_inserts_nothing_the_second_time, test_search_discloses_a_dropped_row_only_when_provenance_DIFFERS, test_search_still_prefers_a_function_when_a_name_scores_equally, test_the_coverage_meta_publishes_both_ratios, test_the_else_branch_is_recovered_and_doxygens_own_row_is_untouched, test_the_include_guard_is_not_reported_as_a_configuration_gate, test_the_recovered_body_is_readable_source_which_it_previously_was_not

Calls _recover_into

Source · 30 lines
def recover_ast_symbols(
    db_path: Path,
    repo_root: Path,
    cache: IndexCache | None = None,
) -> int:
    """MUST run before every call-edge layer and after `repair_attribute_named_functions`.

    Before the call layers, because those resolve their endpoints to memberdef
    rowids — recovering a symbol afterwards would give it a row and no edges, which
    is the defect in a subtler form. After the `__attribute__` repair, because that
    pass merges and renames doxygen's own rows, and the spans this stage compares
    against must be the repaired ones.

    Returns 0 without touching the database when tree-sitter is unavailable or
    `memberdef`/`refid` are absent, so a build with no grammars installed is
    unchanged rather than failed.

    @brief Insert ast-sourced memberdef rows for parser-visible definitions.
    @return Rows inserted.
    @version 2
    """
    conn = sqlite3.connect(str(db_path))
    try:
        inserted = _recover_into(conn, repo_root, cache)
        conn.commit()
    finally:
        conn.close()
    return inserted

Activity · 5 steps
lines 2065–2065conn = sqlite3.connect(str(db_path))lines 2066–2066trylines 2067–2067inserted = _recover_into(conn, repo_root, cache)lines 2068–2068conn.commit()lines 2071–2071return inserted

Requirements

REQ-DDB-INDEX-004