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.
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
Requirements
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.
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 inserted1 more lines, not shown
Activity · 28 steps
Requirements
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.
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