macros.py

clew/query/macros.py

R2 accessor over the preprocessor-definition rows doxygen already writes.

_macro_def

MacroDef clew.query.macros._macro_def(sqlite3.Connection conn, tuple row)

Build one MacroDef from a selected row, adding its parameters and gates.

clew/query/macros.py:180

Source · 30 lines
def _macro_def(conn: sqlite3.Connection, row: tuple) -> MacroDef:
    """Split out of `macro_definitions_conn` so the per-site enrichment — parameters,
    cross-references, provenance and gates, four queries against three tables — is not a
    comprehension the reader has to unpick, and so the SELECT list stays adjacent to the
    positional indices it feeds.

    `gates_covering` is called with the site's OWN file and line. A macro whose `line` is
    NULL (an index that recorded no position) is passed 0, which no gate extent covers, so
    it comes back ungated rather than borrowing the first gate in the file.

    @brief Assemble one macro definition site.
    @return MacroDef.
    @version 1
    """
    gates, unplaceable = gates_covering(conn, row[2], int(row[3] or 0))
    return MacroDef(
        name=row[1],
        rowid=row[0],
        file=row[2],
        line=row[3],
        params=_macro_params(conn, row[0]),
        expansion=row[4],
        brief=strip_xml(row[5]),
        referenced_by=_referenced_by(conn, row[0]),
        provenance=symbol_provenance(conn, row[0]),
        gated_by=gates,
        gates_unplaceable=unplaceable,
    )

Activity · 2 steps
lines 194–194gates, unplaceable = gates_covering(conn, row[2], int(row[3] or 0))lines 195–207return MacroDef( name=row[1], rowid=row[0], file=row[2], line=row[3], params=_macro_params(conn, row[0]), expansion=row[4], brief=strip_xml(row[5]), referenced_by=_referenced_by(conn, row[0]), provenance=symbol_provenance(conn, row[0]), gated_by=gates, gates_unplaceable=unplaceable, )

Flows

_macro_params

str clew.query.macros._macro_params(sqlite3.Connection conn, int rowid)

The parameter list of one function-like macro, as it is written.

clew/query/macros.py:91

Source · 33 lines
def _macro_params(conn: sqlite3.Connection, rowid: int) -> str:
    """NOT `memberdef.argsstring`, which is NULL on every macro row — that column
    holds a FUNCTION's argument text and a `#define`'s parameters go to the `param`
    table instead. Reading `argsstring` is the obvious first guess and it silently
    returns nothing, which reports every function-like macro as object-like.

    READS `defname` AND NOTHING ELSE, deliberately. doxygen's sqlite3 generator
    de-duplicates `param` rows with a loose match that treats a NULL field as
    matching any value, so a macro's one-field parameter row can be UNIFIED with an
    unrelated function parameter that happens to share its `defname` — measured here:
    `MBEDTLS_PRIVATE`'s `member` came back carrying `type='unsigned char'`,
    `declname='mac'`, `array='[16]'` from some function's buffer argument. The
    `defname` is the macro's own and is correct; every other column on that row may
    belong to a different symbol. Rendering the type would print a fabricated
    signature with total confidence.

    @brief Read a macro's parameter names in declaration order.
    @return Parenthesised parameter list, or ''.
    @version 1
    """
    if not table_exists(conn, "memberdef_param") or not table_exists(conn, "param"):
        return ""
    names = [
        r[0]
        for r in conn.execute(
            "SELECT COALESCE(p.defname, p.declname, '') FROM memberdef_param mp "
            "JOIN param p ON p.rowid = mp.param_id WHERE mp.memberdef_id=? ORDER BY mp.rowid",
            (rowid,),
        )
    ]
    return f"({', '.join(names)})" if names else ""

Activity · 4 steps
lines 111–111◇ if not table_exists(conn, "memberdef_param") or not table_exists(conn, "param")lines 112–112return ""lines 113–120names = [ r[0] for r in conn.execute( "SELECT COALESCE(p.defname, p.declname, '') FROM memberdef_param mp " "JOIN param p ON p.rowid = mp.param_id WHERE mp.memberdef_id=? ORDER BY mp.rowid", (rowid,), ) ]lines 121–121return f"({', '.join(names)})" if names else ""

Flows

_referenced_by

tuple[str, ...] clew.query.macros._referenced_by(sqlite3.Connection conn, int rowid)

Names doxygen recorded as referencing one macro-definition row.

clew/query/macros.py:60

Source · 25 lines
def _referenced_by(conn: sqlite3.Connection, rowid: int) -> tuple[str, ...]:
    """EMPTY IS THE COMMON CASE AND IT IS NOT "UNUSED". doxygen writes an `xrefs`
    row when it sees a reference from inside a documented BODY, so a macro used in
    struct declarations, in `#if` conditions or in another macro's expansion has
    none. Measured on mbedtls: 871 of 2,504 macro rows have an inbound reference,
    and `MBEDTLS_PRIVATE` — used ~2,000 times, in declarations — has zero.

    The field is still worth carrying for the 871, and the docstring on `MacroDef`
    says plainly what an empty one means, so a consumer cannot read it as a measured
    negative. That disclosure is the whole reason this is not silently omitted.

    @brief List the symbols doxygen recorded referencing this macro.
    @return Referencing names, capped and alphabetical.
    @version 1
    """
    if not table_exists(conn, "xrefs"):
        return ()
    rows = conn.execute(
        "SELECT DISTINCT s.name FROM xrefs x JOIN memberdef s ON s.rowid = x.src_rowid "
        "WHERE x.dst_rowid=? ORDER BY s.name LIMIT ?",
        (rowid, MAX_MACRO_REFERENCES),
    ).fetchall()
    return tuple(r[0] for r in rows)

Activity · 4 steps
lines 75–75◇ if not table_exists(conn, "xrefs")lines 76–76return ()lines 77–81rows = conn.execute( "SELECT DISTINCT s.name FROM xrefs x JOIN memberdef s ON s.rowid = x.src_rowid " "WHERE x.dst_rowid=? ORDER BY s.name LIMIT ?", (rowid, MAX_MACRO_REFERENCES), ).fetchall()lines 82–82return tuple(r[0] for r in rows)

Flows

config_defaults_conn

list[ConfigDefault] clew.query.macros.config_defaults_conn(sqlite3.Connection conn, str name)

Every configured-default site for a macro name, shipped config first.

clew/query/macros.py:231

Source · 40 lines
def config_defaults_conn(conn: sqlite3.Connection, name: str) -> list[ConfigDefault]:
    """**THE LAYER EXISTED AND NO SUBJECT REPLY READ IT.** `config_defaults` records each config
    macro's state per header, including the commented-out lines that are a shipped default's
    whole point, and only `kconfig.py` ever queried it. A macro dossier therefore answered "where
    is this defined" with doxygen's active definitions and said nothing about whether the shipped
    build turns it on.

    SHIPPED FIRST, NOT MERELY INCLUDED. A site buried mid-list reads as one option among many;
    `MBEDTLS_ERROR_C` already had its shipped site listed third and stateless and its mark failed.
    The shipped header is the one under the repository's own include root rather than under a
    profile, example or test directory — the ordering is a heuristic over paths and says so by
    setting `shipped` rather than by silently sorting.

    A DECLARED ORIGIN OUTVOTES A GUESSED ONE within the same file, because an operator naming a
    config header is better evidence than a filename pattern matching one.

    @brief Configured-default sites for a macro.
    @return Rows, shipped first.
    @version 1
    """
    if not table_exists(conn, "config_defaults"):
        return []
    rows = conn.execute(
        "SELECT macro, state, file_path, line, origin FROM config_defaults WHERE macro=? "
        "ORDER BY file_path, line",
        (name,),
    ).fetchall()
    out = [
        ConfigDefault(
            macro=str(macro),
            state=str(state),
            file=str(path),
            line=line,
            origin=str(origin or ""),
            shipped=is_shipped_config(str(path)),
        )
        for macro, state, path, line, origin in rows
    ]
    ## Shipped first, then declared over heuristic, then by path for determinism.
    return sorted(out, key=lambda c: (not c.shipped, c.origin != "declared", c.file, c.line or 0))

1 more lines, not shown

Activity · 5 steps
lines 251–251◇ if not table_exists(conn, "config_defaults")lines 252–252return []lines 253–257rows = conn.execute( "SELECT macro, state, file_path, line, origin FROM config_defaults WHERE macro=? " "ORDER BY file_path, line", (name,), ).fetchall()lines 258–268out = [ ConfigDefault( macro=str(macro), state=str(state), file=str(path), line=line, origin=str(origin or ""), shipped=is_shipped_config(str(path)), ) for macro, state, path, line, origin in rows ]lines 270–270return sorted(out, key=lambda c: (not c.shipped, c.origin != "declared", c.file, c.line or 0))

Requirements

REQ-DDB-QUERY-013

macro_definitions

list[MacroDef] clew.query.macros.macro_definitions(DbSource db, str name)

Every #define of one name, opening the database itself.

clew/query/macros.py:216

Source · 9 lines
def macro_definitions(db: DbSource, name: str) -> list[MacroDef]:
    """@brief Look up a macro's definition sites from a database source.
    @return MacroDef rows, file/line ordered.
    @version 1
    """
    with connect(db) as conn:
        return macro_definitions_conn(conn, name)

Activity · 2 steps
lines 221–221with connect(db) as connlines 222–222return macro_definitions_conn(conn, name)

Requirements

REQ-DDB-QUERY-012

Flows

macro_definitions_conn

list[MacroDef] clew.query.macros.macro_definitions_conn(sqlite3.Connection conn, str name)

Every #define of one name, with expansion, parameters, location and gating branch.

clew/query/macros.py:130

Show on the map →

Called by _dossier_conn, _is_macro, _macro_subject, macro_definitions

Calls _macro_def, has_columns

Source · 44 lines
def macro_definitions_conn(conn: sqlite3.Connection, name: str) -> list[MacroDef]:
    """ONE ROW PER SITE. A conditionally redefined macro genuinely has several, and
    on the motivating case the several ARE the answer:
    `MBEDTLS_ALLOW_PRIVATE_ACCESS` is defined in `library/common.h` and in two
    `programs/ssl/` mains, which is precisely how the library sees the plain field
    names while an application sees the `private_`-prefixed ones. A collapse to one
    row would have deleted the only fact the question was asking for.

    EACH SITE CARRIES THE GATES COVERING ITS OWN LINE (gh#403), which is what turns two
    disagreeing expansions into an answer. `MBEDTLS_PRIVATE` has two sites eleven columns
    apart in one file: line 15 comes back under `[ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS]`
    and line 17 under `[ifdef …]`, so the payload states which translation unit gets which
    spelling instead of leaving a reader to infer it from two rows that contradict.

    Attached PER ROW rather than once for the name, because the sites are in different
    branches and often in different files — a single list could only describe one of them,
    and would describe the others wrongly with complete confidence.

    Takes an open connection so a caller already inside a `with connect(...)` block
    — `dossier` is the one that matters — does not open a second one per call.
    `macro_definitions` is the standalone wrapper.

    @brief List every definition site of a macro name, each with its gating branch.
    @return MacroDef rows, file/line ordered.
    @version 2
    """
    ## Column-level, not table-level. `initializer` and `line` are doxygen's own
    ## columns and a current build always has them, but a database this consumer was
    ## merely POINTED AT may not — and a query layer that raises a raw
    ## `OperationalError` on a partial schema is the failure `has_columns` exists to
    ## prevent. Both are required together: without `initializer` there is no
    ## expansion, which is the entire reason to ask.
    if not has_columns(conn, "memberdef", "kind", "line", "initializer", "briefdescription"):
        return []
    rows = conn.execute(
        "SELECT m.rowid, m.name, COALESCE(p.name,''), m.line, "
        "COALESCE(m.initializer,''), COALESCE(m.briefdescription,'') "
        "FROM memberdef m LEFT JOIN path p ON p.rowid = m.file_id "
        "WHERE m.name=? AND m.kind=? ORDER BY COALESCE(p.name,''), m.line",
        (name, MACRO_KIND),
    ).fetchall()
    return [_macro_def(conn, row) for row in rows]

Activity · 4 steps
lines 162–162◇ if not has_columns(conn, "memberdef", "kind", "line", "initializer", "briefdescription")lines 163–163return []lines 164–170rows = conn.execute( "SELECT m.rowid, m.name, COALESCE(p.name,''), m.line, " "COALESCE(m.initializer,''), COALESCE(m.briefdescription,'') " "FROM memberdef m LEFT JOIN path p ON p.rowid = m.file_id " "WHERE m.name=? AND m.kind=? ORDER BY COALESCE(p.name,''), m.line", (name, MACRO_KIND), ).fetchall()lines 171–171return [_macro_def(conn, row) for row in rows]

Requirements

REQ-DDB-QUERY-012

Flows