kconfig_gates.py

clew/kconfig_gates.py

symbol → `file:line` — which source lines a `CONFIG_*` symbol gates.

ensure_kconfig_gates_table

None clew.kconfig_gates.ensure_kconfig_gates_table(sqlite3.Connection conn)

Idempotent creation of the kconfig_gates table.

clew/kconfig_gates.py:111

Source · 54 lines
def ensure_kconfig_gates_table(conn: sqlite3.Connection) -> None:
    """Created SEPARATELY from `kconfig_symbols`, next to the harvest that fills it,
    for the reason `ensure_kconfig_tables` records: the two layers fail
    independently — a repo can have a parseable Kconfig and no C sources, or gated C
    and an unparseable Kconfig — and a shared creator would make one layer's absence
    look like the other's.

    `symbol` stores the Kconfig symbol name WITHOUT the `CONFIG_` prefix, so it joins
    `kconfig_symbols.name` directly; `macro` keeps the token as the source wrote it,
    because that is what a reader greps for.

    No foreign key to `kconfig_symbols`: a gate on an undeclared symbol is a finding
    this layer exists to keep, and a REFERENCES would make storing it impossible.

    `origin` says how the symbol's NAME is accounted for — Kconfig's prefix, the target's
    own declared preprocessor configuration, or nothing this build could see. It is a label
    and never a filter: an undeclared gate is a finding about the target (a symbol nobody
    has declared, or dead code behind one nobody can set), and dropping those rows would
    delete the evidence — the same argument this module already makes for a gate on a
    symbol no Kconfig declares.

    `end_line` CLOSES THE RANGE, and the branch it closes is the one the row's own `form`
    describes — NOT the whole conditional. Measured with `.claude/tmp/gate_extent_probe.py`: a
    `preproc_ifdef` node spans lines 3-7 for `#ifdef FEATURE_A ... #else ... #endif`, so a range
    join over the node's own extent reports the code in the `#else` as gated ON `FEATURE_A` when
    it is present exactly when `FEATURE_A` is NOT set. A confidently inverted variant is worse
    than no answer, so the row stops at its alternative and the alternative gets its own row with
    the opposite polarity.

    DEFAULT 0 MEANS "EXTENT UNKNOWN", which is what an index built before this column knew. A
    consumer must not read 0 as "covers nothing" or as "covers everything" — `gates_covering`
    skips those rows and says so, rather than guessing a range for them.

    @brief Create the CONFIG-gating table.
    @version 3
    """
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS kconfig_gates (
            symbol    TEXT NOT NULL,
            macro     TEXT NOT NULL,
            form      TEXT NOT NULL {check("kconfig_gates", "form")},
            file_path TEXT NOT NULL,
            line      INTEGER NOT NULL,
            end_line  INTEGER NOT NULL DEFAULT 0,
            origin    TEXT NOT NULL {check("kconfig_gates", "origin")},
            UNIQUE(symbol, form, file_path, line)
        )
        """
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_kconfig_gates_symbol ON kconfig_gates(symbol)")
    conn.commit()

Activity · 3 steps
lines 147–160conn.execute( f""" CREATE TABLE IF NOT EXISTS kconfig_gates ( symbol TEXT NOT NULL, macro TEXT NOT NULL, form TEXT NOT NULL {check("kconfig_gates", "form")}, file_path TEXT NOT NULL, line INTEGER NOT NULL, end_line INTEGER NOT NULL DEFAULT 0, origin TEXT NOT NULL {check("kconfig_gates", "origin")}, UNIQUE(symbol, form, file_path, line) ) """ )lines 161–161conn.execute("CREATE INDEX IF NOT EXISTS idx_kconfig_gates_symbol ON kconfig_gates(symbol)")lines 162–162conn.commit()

Requirements

REQ-DDB-SCHEMA-013

gate_harvester

Harvester clew.kconfig_gates.gate_harvester()

The kconfig-gate stage's harvester.

clew/kconfig_gates.py:438

Source · 12 lines
def gate_harvester() -> Harvester:
    """Public factory so the gh#358 shared parse pass can warm this stage's cache
    rows without importing a private class — and so there is ONE construction
    site, which is what makes the pass's key and the stage's key equal by
    construction rather than by two matching edits.

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

Activity · 1 steps
lines 447–447return _GateHarvester()

Requirements

REQ-DDB-PIPE-007

harvest

Any clew.kconfig_gates._GateHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's CONFIG gating sites.

clew/kconfig_gates.py:414

Show on the map →

Called by none

Calls _gates_from_node, list

Source · 20 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        """Returns LISTS rather than tuples because the payload is JSON-serialised
        into the cache, where a tuple comes back as a list anyway — so producing
        lists here keeps a cache hit and a fresh parse structurally identical, which
        is the invariant `run_harvest`'s docstring depends on.

        @brief Walk one file's preprocessor conditionals.
        @return Gate entries for this file.
        @version 1
        """
        found: list[list[Any]] = []
        stack = [tree.root_node]
        while stack:
            node = stack.pop()
            if node.type == _IFDEF_NODE or node.type in _EXPR_NODES:
                found.extend(list(gate) for gate in _gates_from_node(node))
            stack.extend(node.children)
        return found

Activity · 8 steps
lines 424–424found: list[list[Any]] = []lines 425–425stack = [tree.root_node]lines 426–426◇ while stacklines 427–427node = stack.pop()lines 428–428◇ if node.type == _IFDEF_NODE or node.type in _EXPR_NODESlines 429–429found.extend(list(gate) for gate in _gates_from_node(node))lines 430–430stack.extend(node.children)lines 431–431return found

Requirements

REQ-DDB-PIPE-007

import_kconfig_gates

int clew.kconfig_gates.import_kconfig_gates(Path db_path, Path repo_root, IndexCache|None cache=None, Iterable[str] declared=())

Harvest and store every preprocessor gating site, labelled by its origin.

clew/kconfig_gates.py:515

Source · 50 lines
def import_kconfig_gates(
    db_path: Path,
    repo_root: Path,
    cache: IndexCache | None = None,
    declared: Iterable[str] = (),
) -> int:
    """CREATES THE TABLE UNCONDITIONALLY once tree-sitter is available, even at zero
    rows, and does NOT create it when tree-sitter is missing. That asymmetry is the
    point: an empty table means "we walked the tree and this repo gates nothing",
    an absent one means "this layer never ran", and a consumer distinguishing a
    correct negative from a detector failure needs both. Writing down the wrong one
    is the mistake this repo has made three times.

    Runs INDEPENDENTLY of whether a Kconfig was found — see the module docstring on
    why a gate is recorded for an undeclared symbol. `declared` only LABELS the rows, so
    a target that has declared nothing still gets a complete layer.

    @brief Fill kconfig_gates from the indexed source tree.
    @return Row count.
    @version 5
    """
    conn = sqlite3.connect(str(db_path))
    try:
        ensure_kconfig_gates_table(conn)
        harvested = run_harvest(conn, repo_root, gate_harvester(), cache)
        names = declared_macro_names(declared)
        rows = [
            (symbol, macro, form, path, line, end, _origin(symbol, macro, names))
            for symbol, macro, form, path, line, end in _rows_from_harvest(conn, harvested)
        ]
        conn.executemany(
            "INSERT OR IGNORE INTO kconfig_gates"
            "(symbol, macro, form, file_path, line, end_line, origin) VALUES(?,?,?,?,?,?,?)",
            rows,
        )
        conn.commit()
    finally:
        conn.close()
    logger.info(
        "kconfig gates: %d gating site(s) over %d distinct symbol(s) "
        "(%d kconfig, %d declared, %d undeclared)",
        len(rows),
        len({row[0] for row in rows}),
        sum(1 for row in rows if row[6] == GATE_ORIGIN_KCONFIG),
        sum(1 for row in rows if row[6] == GATE_ORIGIN_DECLARED),
        sum(1 for row in rows if row[6] == GATE_ORIGIN_UNDECLARED),
    )
    return len(rows)

Activity · 10 steps
lines 536–536conn = sqlite3.connect(str(db_path))lines 537–537trylines 538–538ensure_kconfig_gates_table(conn)lines 539–539harvested = run_harvest(conn, repo_root, gate_harvester(), cache)lines 540–540names = declared_macro_names(declared)lines 541–544rows = [ (symbol, macro, form, path, line, end, _origin(symbol, macro, names)) for symbol, macro, form, path, line, end in _rows_from_harvest(conn, harvested) ]lines 545–549conn.executemany( "INSERT OR IGNORE INTO kconfig_gates" "(symbol, macro, form, file_path, line, end_line, origin) VALUES(?,?,?,?,?,?,?)", rows, )lines 550–550conn.commit()lines 553–561logger.info( "kconfig gates: %d gating site(s) over %d distinct symbol(s) " "(%d kconfig, %d declared, %d undeclared)", len(rows), len({row[0] for row in rows}), sum(1 for row in rows if row[6] == GATE_ORIGIN_KCONFIG), sum(1 for row in rows if row[6] == GATE_ORIGIN_DECLARED), sum(1 for row in rows if row[6] == GATE_ORIGIN_UNDECLARED), )lines 562–562return len(rows)

Requirements

REQ-DDB-PIPE-007