macro_refs.py

clew/macro_refs.py

Recover macro references doxygen's xref pass does not record.

harvest

Any clew.macro_refs.MacroRefHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one parsed file.

clew/macro_refs.py:99

Show on the map →

Called by none

Calls _function_bodies, _identifiers_in

Source · 17 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        """@brief Collect identifier uses inside each function body.
        @return Rowid-free triples.
        @version 1
        """
        out: list[list[Any]] = []
        seen: set[tuple[str, str]] = set()
        for fn_node, fn_name in _function_bodies(tree.root_node, src_bytes):
            for name, line in _identifiers_in(fn_node, src_bytes):
                key = (fn_name, name)
                if key in seen:
                    continue
                seen.add(key)
                out.append([fn_name, name, line])
        return out

Activity · 10 steps
lines 104–104out: list[list[Any]] = []lines 105–105seen: set[tuple[str, str]] = set()lines 106–106◇ for fn_node, fn_name in _function_bodies(tree.root_node, src_bytes)lines 107–107◇ for name, line in _identifiers_in(fn_node, src_bytes)lines 108–108key = (fn_name, name)lines 109–109◇ if key in seenlines 110–110continuelines 111–111seen.add(key)lines 112–112out.append([fn_name, name, line])lines 113–113return out

Requirements

REQ-DDB-PIPE-003

import_ast_macro_refs

int clew.macro_refs.import_ast_macro_refs(Path db, Path repo_root, IndexCache|None cache=None, tuple[str,...]|list[str]|None test_patterns=None)

Insert the macro references doxygen's xref pass did not record.

clew/macro_refs.py:498

Source · 81 lines
def import_ast_macro_refs(
    db: Path,
    repo_root: Path,
    cache: IndexCache | None = None,
    test_patterns: tuple[str, ...] | list[str] | None = None,
) -> int:
    """FILTERED AGAINST REAL MACRO ROWS, so an identifier that merely shares a name with nothing
    contributes nothing: the join is the filter, and the layer's size is bounded by how many
    macros the index actually holds.

    `INSERT OR IGNORE` plus the table's own `UNIQUE(src_rowid, dst_rowid, context)` makes this
    idempotent, and the distinct `context` means a pair doxygen already recorded gains a second
    row rather than colliding — `_referenced_by` selects DISTINCT names, so a consumer sees one
    entry either way while the provenance stays readable.

    SELF-REFERENCE IS DROPPED. A macro whose expansion names another macro can produce a body
    identifier equal to the enclosing function; recording that would assert a function references
    itself.

    @brief Recover and insert AST-sourced macro references.
    THE CALLER IS RESOLVED IN ITS OWN FILE. The enclosing function is looked up by the
    file the body was harvested from and its name. Only when that file holds no row for it
    does a name resolve alone, and then only if no other function shares it.

    @return Rows inserted.
    @version 4
    """
    conn = sqlite3.connect(str(db))
    try:
        payloads = run_harvest(conn, repo_root, MacroRefHarvester(), cache)
        macros = macro_definitions(conn, test_patterns)
        if not macros:
            logger.info("macro_refs: index holds no macro definitions — nothing to recover")
            return 0
        ## Keyed by the defining file as well as the name: a bare name is shared across
        ## files (two vendored copies of one program, a C `help` and a shell `help`), and a
        ## name-only map credits every body to whichever row was read last.
        functions: dict[tuple[int, str], int] = {}
        by_name: dict[str, list[int]] = {}
        for rowid, name, file_id, bodyfile_id in conn.execute(
            "SELECT rowid, name, file_id, bodyfile_id FROM memberdef "
            "WHERE kind='function' ORDER BY rowid"
        ):
            functions[(file_id, name)] = rowid
            if bodyfile_id is not None:
                functions[(bodyfile_id, name)] = rowid
            by_name.setdefault(name, []).append(rowid)
        ## A body whose file holds no row for it (only a prototype elsewhere carries the
        ## name) still resolves when the name is unambiguous across the index.
        unique = {name: rowids[0] for name, rowids in by_name.items() if len(rowids) == 1}

        ## Read once (2.1, refresh cost), not per reference.
        sites = _macro_sites(conn)
        rows: list[tuple[int, int, str]] = []
        for path_rowid, payload in payloads:
            for fn_name, ident, _line in payload or ():
                src = functions.get((path_rowid, fn_name), unique.get(fn_name))
                if src is None:
                    continue
                rows += [
                    (src, dst, AST_REF_CONTEXT)
                    for dst in _same_file_first(macros.get(ident, ()), path_rowid, conn, sites)
                    if dst != src
                ]

        conn.executemany(
            "INSERT OR IGNORE INTO xrefs (src_rowid, dst_rowid, context) VALUES (?, ?, ?)",
            rows,
        )
        inserted = conn.total_changes
        conn.commit()
    finally:
        conn.close()

    logger.info(
        "macro_refs: recovered %d macro reference(s) doxygen did not record "
        "(context='%s'; doxygen's xref pass misses non-type template argument uses)",
        inserted,
        AST_REF_CONTEXT,
    )
    return inserted

1 more lines, not shown

Activity · 28 steps
lines 525–525conn = sqlite3.connect(str(db))lines 526–526trylines 527–527payloads = run_harvest(conn, repo_root, MacroRefHarvester(), cache)lines 528–528macros = macro_definitions(conn, test_patterns)lines 529–529◇ if not macroslines 530–530logger.info("macro_refs: index holds no macro definitions — nothing to recover")lines 531–531return 0lines 535–535functions: dict[tuple[int, str], int] = {}lines 536–536by_name: dict[str, list[int]] = {}lines 537–537◇ for rowid, name, file_id, bodyfile_id in conn.execute(lines 541–541functions[(file_id, name)] = rowidlines 542–542◇ if bodyfile_id is not Nonelines 543–543functions[(bodyfile_id, name)] = rowidlines 544–544by_name.setdefault(name, []).append(rowid)lines 547–547unique = {name: rowids[0] for name, rowids in by_name.items() if len(rowids) == 1}lines 550–550sites = _macro_sites(conn)lines 551–551rows: list[tuple[int, int, str]] = []lines 552–552◇ for path_rowid, payload in payloadslines 553–553◇ for fn_name, ident, _line in payload or ()lines 554–554src = functions.get((path_rowid, fn_name), unique.get(fn_name))lines 555–555◇ if src is Nonelines 556–556continuelines 557–561rows += [ (src, dst, AST_REF_CONTEXT) for dst in _same_file_first(macros.get(ident, ()), path_rowid, conn, sites) if dst != src ]lines 563–566conn.executemany( "INSERT OR IGNORE INTO xrefs (src_rowid, dst_rowid, context) VALUES (?, ?, ?)", rows, )lines 567–567inserted = conn.total_changeslines 568–568conn.commit()lines 572–577logger.info( "macro_refs: recovered %d macro reference(s) doxygen did not record " "(context='%s'; doxygen's xref pass misses non-type template argument uses)", inserted, AST_REF_CONTEXT, )lines 578–578return inserted

Requirements

REQ-DDB-PIPE-003

macro_definitions

dict[str, list[int]] clew.macro_refs.macro_definitions(sqlite3.Connection conn, tuple[str,...]|list[str]|None test_patterns=None)

Every macro name's definitions, those the default build does not compile removed.

clew/macro_refs.py:228

Show on the map →

Called by none

Calls _compiled, _gates_by_file, _shipped_states

Source · 40 lines
def macro_definitions(
    conn: sqlite3.Connection, test_patterns: tuple[str, ...] | list[str] | None = None
) -> dict[str, list[int]]:
    """UPERF T5 (2.0.0, mbedtls F3): `{name: rowid}` kept whichever same-name definition was read
    LAST, so `mbedtls_calloc` — defined in three `#if` branches of platform.h — was credited to an
    arbitrary one. A definition inside a branch the DEFAULT BUILD does not compile is dropped: its
    covering gates of known polarity (`ifdef` / `ifndef`) are evaluated against the shipped
    configuration (`config_defaults`). A gate whose symbol the configuration does not decide, or
    whose polarity is unknown (`if_expr`), drops nothing — unknown is never read as off.

    @brief Every macro name's definitions, those the default build skips removed.
    @return {name: [rowids]}.
    @version 1
    """
    by_name: dict[str, list[tuple[int, str, int]]] = {}
    has_path = conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'path'").fetchone()
    query = (
        "SELECT m.rowid, m.name, p.name, m.line FROM memberdef m "
        "LEFT JOIN path p ON p.rowid = m.file_id WHERE m.kind = 'macro definition'"
        if has_path
        ## No file table: no gate can be located, so every definition is kept (never dropped).
        else "SELECT rowid, name, '', 0 FROM memberdef WHERE kind = 'macro definition'"
    )
    for rowid, name, file_path, line in conn.execute(query):
        by_name.setdefault(name, []).append((rowid, file_path or "", line or 0))
    states = _shipped_states(conn, test_patterns)
    ## 2.1 (refresh cost): the gates are read ONCE, not once per same-name definition — measured
    ## on mbedtls, 2,462 `_compiled` queries took 1.4 s of this stage's 2.1 s.
    gates = _gates_by_file(conn)
    out = {}
    for name, defs in by_name.items():
        kept = [
            d
            for d in defs
            if len(defs) == 1 or _compiled(conn, d[1], d[2], states, gates) is not False
        ]
        out[name] = [d[0] for d in (kept or defs)]
    return out

Activity · 12 steps
lines 242–242by_name: dict[str, list[tuple[int, str, int]]] = {}lines 243–243has_path = conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'path'").fetchone()lines 244–250query = ( "SELECT m.rowid, m.name, p.name, m.line FROM memberdef m " "LEFT JOIN path p ON p.rowid = m.file_id WHERE m.kind = 'macro definition'" if has_path ## No file table: no gate can be located, so every definition is kept (never dropped). else "SELECT rowid, name, '', 0 FROM memberdef WHERE kind = 'macro definition'" )lines 251–251◇ for rowid, name, file_path, line in conn.execute(query)lines 252–252by_name.setdefault(name, []).append((rowid, file_path or "", line or 0))lines 253–253states = _shipped_states(conn, test_patterns)lines 256–256gates = _gates_by_file(conn)lines 257–257out = {}lines 258–258◇ for name, defs in by_name.items()lines 259–263kept = [ d for d in defs if len(defs) == 1 or _compiled(conn, d[1], d[2], states, gates) is not False ]lines 264–264out[name] = [d[0] for d in (kept or defs)]lines 265–265return out

Requirements

REQ-DDB-PIPE-003