kconfig.py

clew/query/kconfig.py

R2 access to the configuration space (gh#18): what variants this firmware has.

_defaults_for_macros

list[tuple] clew.query.kconfig._defaults_for_macros(sqlite3.Connection conn, list[str] macros)

Read config_defaults rows for a macro list, in bounded chunks.

clew/query/kconfig.py:593

Source · 20 lines
def _defaults_for_macros(conn: sqlite3.Connection, macros: list[str]) -> list[tuple]:
    """Split out of `_with_defaults` so the resolution RULE and the parameter bound are
    separately readable; the rule is what `test_shipped_config_tiebreak` pins and it should not
    have to be re-read to change a chunk size.

    @brief Chunked read of the shipped-defaults corpus.
    @return The rows.
    @version 1
    """
    rows: list[tuple] = []
    for start in range(0, len(macros), _MACRO_CHUNK):
        batch = macros[start : start + _MACRO_CHUNK]
        rows += conn.execute(
            f"SELECT macro, state, file_path, line, origin FROM config_defaults "  # noqa: S608
            f"WHERE macro IN ({','.join('?' * len(batch))})",
            batch,
        ).fetchall()
    return rows

Activity · 5 steps
lines 602–602rows: list[tuple] = []lines 603–603◇ for start in range(0, len(macros), _MACRO_CHUNK)lines 604–604batch = macros[start : start + _MACRO_CHUNK]lines 605–609rows += conn.execute( f"SELECT macro, state, file_path, line, origin FROM config_defaults " # noqa: S608 f"WHERE macro IN ({','.join('?' * len(batch))})", batch, ).fetchall()lines 610–610return rows

Flows

_gate_columns

str clew.query.kconfig._gate_columns(sqlite3.Connection conn)

The SELECT list that builds a KconfigGate positionally.

clew/query/kconfig.py:273

Source · 20 lines
def _gate_columns(conn: sqlite3.Connection) -> str:
    """EVERY OPTIONAL COLUMN IS SELECTED AS A LITERAL WHEN ABSENT rather than omitted, because
    `KconfigGate(*row)` is positional: omitting `origin` on an older index would shift `end_line`
    into its slot and report a line number as a provenance string. The literals equal the
    dataclass defaults, so a degraded database reads back as exactly what it knew.

    ONE CONSTRUCTION SITE for two readers. `gates_covering` needs the same list with a different
    WHERE clause, and two copies of a positional SELECT is how the shift above eventually happens
    for real.

    @brief Build the gate SELECT list for this index's actual columns.
    @return The column expressions.
    @version 1
    """
    selected = ["symbol", "macro", "form", "file_path", "line"]
    selected.append("origin" if has_columns(conn, "kconfig_gates", "origin") else "''")
    selected.append("end_line" if has_columns(conn, "kconfig_gates", "end_line") else "0")
    return ", ".join(selected)

Activity · 4 steps
lines 287–287selected = ["symbol", "macro", "form", "file_path", "line"]lines 288–288selected.append("origin" if has_columns(conn, "kconfig_gates", "origin") else "''")lines 289–289selected.append("end_line" if has_columns(conn, "kconfig_gates", "end_line") else "0")lines 290–290return ", ".join(selected)

Flows

_gate_layer_state

tuple[str, int] clew.query.kconfig._gate_layer_state(sqlite3.Connection conn)

What the GATE HARVEST measured, independently of whether a Kconfig exists.

clew/query/kconfig.py:428

Source · 24 lines
def _gate_layer_state(conn: sqlite3.Connection) -> tuple[str, int]:
    """gh#404 — BECAUSE `found` ANSWERS A DIFFERENT QUESTION THAN THE ONE CALLERS ASK. `found` is
    true when a Kconfig was discovered and parsed, and that is all it ever claimed. But a caller
    reads `found: false` as "this repository has no configuration space", and on mbedtls — where
    `found` is false, because mbedtls has no Kconfig — the index holds 12,096 gating sites over
    1,107 distinct symbols, harvested from `#if` directives. Kconfig is a Zephyr/Linux convention;
    a header of `#define`s is the dominant C one.

    THREE STATES IN `layer_state`'s EXISTING VOCABULARY, not a fourth spelling of the same idea:
    `absent` when the table was never built (the layer did not run), `empty` when it ran and found
    no gating site, `populated` otherwise. The distinction between the first two is the one this
    project keeps relearning — a table that exists and holds nothing is a MEASUREMENT, while an
    absent table is a detector that never looked, and only the first is evidence about the repo.

    @brief Report the gate layer's state and symbol count.
    @return (state, distinct symbol count).
    @version 1
    """
    if not table_exists(conn, "kconfig_gates"):
        return LAYER_STATE_ABSENT, 0
    count = int(conn.execute("SELECT COUNT(DISTINCT symbol) FROM kconfig_gates").fetchone()[0])
    return (LAYER_STATE_POPULATED if count else LAYER_STATE_EMPTY), count

Activity · 4 steps
lines 446–446◇ if not table_exists(conn, "kconfig_gates")lines 447–447return LAYER_STATE_ABSENT, 0lines 448–448count = int(conn.execute("SELECT COUNT(DISTINCT symbol) FROM kconfig_gates").fetchone()[0])lines 449–449return (LAYER_STATE_POPULATED if count else LAYER_STATE_EMPTY), count

Requirements

REQ-DDB-QUERY-006

Flows

_gate_symbol_names

tuple[tuple[str, ...], int] clew.query.kconfig._gate_symbol_names(sqlite3.Connection conn, str|None text)

The distinct symbols that gate code, optionally filtered by name.

clew/query/kconfig.py:348

Source · 33 lines
def _gate_symbol_names(conn: sqlite3.Connection, text: str | None) -> tuple[tuple[str, ...], int]:
    """WHICH SYMBOLS EXIST, which is the question this corpus says it answers and the one it was
    not answering. `_search_config` asked for the whole space with no symbol, so the reply carried
    every gate SITE: measured on mbedtls 2026-08-14, `search(corpus='config',
    text='MBEDTLS_THREADING_C')` returned 2,149,463 characters — all 12,096 rows, because
    inventory corpora ignore `text` by design — while reporting `found: false` for a symbol whose
    name sits in `configured_macros` in the same reply. In a graded cell that is either a
    budget-destroying reply or a bail-out, on the very axis under test.

    The sites are `dossier`'s job, and were already: `resolve_subject` classifies a gating macro
    as `kind='config'`, and `dossier('MBEDTLS_THREADING_C')` returns its 154 sites correctly
    filtered. So the fix is not a new capability, it is this corpus returning the inventory it
    claims to and routing to the other tool for the detail.

    `text` IS HONOURED HERE, unlike the other inventory corpora. Filtering an inventory by name is
    not ranking, costs one `LIKE`, and is what makes a 1,107-symbol space usable at all — an
    ignored argument that silently returns everything is the shape of the defect above.

    @brief List the distinct gating symbols, filtered and capped.
    @return (capped names, total matching).
    @version 1
    """
    if not table_exists(conn, "kconfig_gates"):
        return (), 0
    sql = "SELECT DISTINCT symbol FROM kconfig_gates"
    params: tuple[str, ...] = ()
    if text:
        sql += " WHERE symbol LIKE ?"
        params = (f"%{text.removeprefix('CONFIG_')}%",)
    rows = [r[0] for r in conn.execute(sql + " ORDER BY symbol", params).fetchall()]
    return tuple(rows[:_NAME_CAP]), len(rows)

Activity · 9 steps
lines 370–370◇ if not table_exists(conn, "kconfig_gates")lines 371–371return (), 0lines 372–372sql = "SELECT DISTINCT symbol FROM kconfig_gates"lines 373–373params: tuple[str, ...] = ()lines 374–374◇ if textlines 375–375sql += " WHERE symbol LIKE ?"lines 376–376params = (f"%{text.removeprefix('CONFIG_')}%",)lines 377–377rows = [r[0] for r in conn.execute(sql + " ORDER BY symbol", params).fetchall()]lines 378–378return tuple(rows[:_NAME_CAP]), len(rows)

Requirements

REQ-DDB-QUERY-006

Flows

_gates

tuple[KconfigGate, ...] clew.query.kconfig._gates(sqlite3.Connection conn, str|None symbol)

The gating sites recorded for the whole repo, or for one symbol.

clew/query/kconfig.py:300

Source · 33 lines
def _gates(conn: sqlite3.Connection, symbol: str | None) -> tuple[KconfigGate, ...]:
    """Accepts the symbol either bare or `CONFIG_`-prefixed, because a caller reading
    a gate out of source code has the prefixed form in front of them and requiring
    them to strip it is a papercut that produces a confident empty result — the
    failure mode gh#31 records for `search`.

    `origin` and `end_line` are selected only when the column is present. An index built before
    gh#390 has no `origin` and one built before the extent work has no `end_line`; `KconfigGate`
    defaults them to `undeclared` and `0`, which is precisely what those indexes knew — reading a
    degraded database thinly rather than failing is the query layer's standing rule.

    @brief Read kconfig_gates, optionally for one symbol.
    @return Gate rows.
    @version 4
    """
    if not table_exists(conn, "kconfig_gates"):
        return ()
    sql = f"SELECT {_gate_columns(conn)} FROM kconfig_gates"  # noqa: S608
    params: tuple[str, ...] = ()
    if symbol:
        sql += " WHERE symbol = ?"
        params = (symbol.removeprefix("CONFIG_"),)
    rows = conn.execute(sql + " ORDER BY file_path, line", params).fetchall()
    ## C3 of the 1.1.0 acceptance review: THE SAME JOIN THE FUNCTION ROUTE ALREADY USED.
    ## `_with_defaults` was wired into `gates_covering` only, so `dossier("mbedtls_calloc")`
    ## learned which preprocessor arm the default build takes and
    ## `dossier("MBEDTLS_PLATFORM_MEMORY")` — the more direct question, and where a
    ## `search(corpus="config")` row points — got sites with no way to tell. One join, two
    ## callers; a second implementation for the second caller is how two surfaces come to
    ## disagree about one macro.
    return _with_defaults(conn, tuple(KconfigGate(*row) for row in rows))

Activity · 9 steps
lines 315–315◇ if not table_exists(conn, "kconfig_gates")lines 316–316return ()lines 317–317sql = f"SELECT {_gate_columns(conn)} FROM kconfig_gates"lines 318–318params: tuple[str, ...] = ()lines 319–319◇ if symbollines 320–320sql += " WHERE symbol = ?"lines 321–321params = (symbol.removeprefix("CONFIG_"),)lines 322–322rows = conn.execute(sql + " ORDER BY file_path, line", params).fetchall()lines 330–330return _with_defaults(conn, tuple(KconfigGate(*row) for row in rows))

Flows

_in_default_build

bool | None clew.query.kconfig._in_default_build(str form, str state)

Whether a gate's guarded code is in the default build.

clew/query/kconfig.py:688

Source · 11 lines
def _in_default_build(form: str, state: str) -> bool | None:
    """T5 served (2.0.0). `ifdef` is in when the macro is on, `ifndef` when it is off. `if_expr`
    asserts dependence without a polarity, so it decides nothing.

    @brief Combine polarity and default.
    @return The answer, or None.
    """
    polarity = {KCONFIG_GATE_IFDEF: True, KCONFIG_GATE_IFNDEF: False}.get(form)
    if polarity is None or state not in (CONFIG_DEFAULT_ON, CONFIG_DEFAULT_OFF):
        return None
    return (state == CONFIG_DEFAULT_ON) == polarity

1 more lines, not shown

Activity · 4 steps
lines 695–695polarity = {KCONFIG_GATE_IFDEF: True, KCONFIG_GATE_IFNDEF: False}.get(form)lines 696–696◇ if polarity is None or state not in (CONFIG_DEFAULT_ON, CONFIG_DEFAULT_OFF)lines 697–697return Nonelines 698–698return (state == CONFIG_DEFAULT_ON) == polarity

Requirements

REQ-DDB-QUERY-004

Flows

_meta

dict[str, str] clew.query.kconfig._meta(sqlite3.Connection conn)

Every kconfig.

clew/query/kconfig.py:204

Source · 31 lines
def _meta(conn: sqlite3.Connection) -> dict[str, str]:
    """Degrades to {} when `build_meta` is absent, matching the query layer's standing
    contract: it returns empty results on a partial database rather than raising,
    because a stale index missing a later layer is a normal thing to query.

    @brief Read the kconfig and preprocessor build_meta rows.
    @return Key -> value, kconfig keys with the prefix stripped.
    @version 3
    """
    if not table_exists(conn, "build_meta"):
        return {}
    rows = conn.execute("SELECT key, value FROM build_meta").fetchall()
    meta = {k[len(_META_PREFIX) :]: v for k, v in rows if str(k).startswith(_META_PREFIX)}
    ## EVERY PREPROCESSOR KEY A CONSUMER READS, and `_PREPROCESSOR_STATED_ONLY` is here because it
    ## was NOT. It was defined, documented, and passed to `macros_meaning` at the call site — but
    ## never fetched, so it resolved to "" on every build and the answer branch that reads it was
    ## unreachable code. The reply fell through to "this build did not record which came from
    ## which" while the split was sitting in `build_meta`.
    ##
    ## The suite could not see it: the existing test calls `macros_meaning` DIRECTLY and never
    ## through `kconfig_space`, so it pinned the wording of a branch nothing could reach.
    for key in (
        _PREPROCESSOR_MACROS,
        _PREPROCESSOR_SOURCE,
        _PREPROCESSOR_HEADER,
        _PREPROCESSOR_STATED_ONLY,
    ):
        meta[key] = next((v for k, v in rows if k == key), "")
    return meta

Activity · 7 steps
lines 213–213◇ if not table_exists(conn, "build_meta")lines 214–214return {}lines 215–215rows = conn.execute("SELECT key, value FROM build_meta").fetchall()lines 216–216meta = {k[len(_META_PREFIX) :]: v for k, v in rows if str(k).startswith(_META_PREFIX)}lines 225–225◇ for key in (lines 231–231meta[key] = next((v for k, v in rows if k == key), "")lines 232–232return meta

Flows

_symbols

tuple[KconfigEntry, ...] clew.query.kconfig._symbols(sqlite3.Connection conn)

The symbol rows, each with the group it belongs to and its gate count.

clew/query/kconfig.py:240

Source · 28 lines
def _symbols(conn: sqlite3.Connection) -> tuple[KconfigEntry, ...]:
    """Joins the choice group in as its HUMAN identity — the prompt, falling back to
    the name — rather than exposing the synthetic `choice_key`. The key is a per-build
    ordinal with no meaning outside the row it joins, so surfacing it would publish an
    implementation detail a consumer could mistake for a stable id.

    `gate_count` is a correlated COUNT rather than a second query, so a symbol that
    gates nothing arrives as 0 rather than as an absence a caller has to interpret.
    Counted only when `kconfig_gates` EXISTS: the two layers fail independently, and
    reporting 0 for every symbol when the gate harvest never ran would be a
    measurement where there is none.

    @brief Read kconfig_symbols with group identity and gate counts.
    @return Symbol entries.
    @version 1
    """
    have_gates = table_exists(conn, "kconfig_gates")
    gates = "(SELECT COUNT(*) FROM kconfig_gates g WHERE g.symbol = s.name)" if have_gates else "0"
    rows = conn.execute(
        "SELECT s.name, s.type, s.prompt, s.help, s.default_expr, "
        "COALESCE(NULLIF(c.prompt, ''), NULLIF(c.name, '')), s.file_path, s.line, "
        f"{gates} FROM kconfig_symbols s "
        "LEFT JOIN kconfig_choices c ON c.key = s.choice_key "
        "ORDER BY s.file_path, s.line"
    ).fetchall()
    return tuple(KconfigEntry(*row) for row in rows)

Activity · 4 steps
lines 256–256have_gates = table_exists(conn, "kconfig_gates")lines 257–257gates = "(SELECT COUNT(*) FROM kconfig_gates g WHERE g.symbol = s.name)" if have_gates else "0"lines 258–264rows = conn.execute( "SELECT s.name, s.type, s.prompt, s.help, s.default_expr, " "COALESCE(NULLIF(c.prompt, ''), NULLIF(c.name, '')), s.file_path, s.line, " f"{gates} FROM kconfig_symbols s " "LEFT JOIN kconfig_choices c ON c.key = s.choice_key " "ORDER BY s.file_path, s.line" ).fetchall()lines 265–265return tuple(KconfigEntry(*row) for row in rows)

Flows

_with_defaults

tuple[KconfigGate, ...] clew.query.kconfig._with_defaults(sqlite3.Connection conn, tuple[KconfigGate,...] gates)

Attach each gating macro's shipped default to its gate.

clew/query/kconfig.py:638

Source · 43 lines
def _with_defaults(
    conn: sqlite3.Connection, gates: tuple[KconfigGate, ...]
) -> tuple[KconfigGate, ...]:
    """THE DECLARED HEADER WINS, AND DISAGREEMENT AMONG GUESSES DECIDES NOTHING.

    mbedtls is the motivating shape exactly: `MBEDTLS_PLATFORM_MEMORY` is commented out in the
    declared `mbedtls_config.h` and actively defined in two alternative profiles under
    `configs/`. The declared header is what a default build reads, so it answers; the profiles
    are other builds and must not outvote it.

    When no declared header mentions the macro and the heuristic ones DISAGREE, the field stays
    empty. Picking one of two profiles and calling it the default is the confident wrong answer
    this layer was built to remove, re-made one level up.

    @brief Join shipped defaults onto gates.
    @return Gates with defaults where they are unambiguous.
    @version 6
    """
    if not gates or not table_exists(conn, "config_defaults"):
        return gates
    macros = sorted({gate.macro for gate in gates})
    by_macro: dict[str, list[tuple[str, str, int, str]]] = {}
    for macro, state, path, line_no, origin in _defaults_for_macros(conn, macros):
        by_macro.setdefault(str(macro), []).append(
            (str(state), str(path), int(line_no), str(origin))
        )
    ## ONE RULE WITH THE BUILD (`_common.decided_default`): declared, then shipped, then all rows,
    ## the first non-empty tier deciding only when unanimous. The history this replaces is in the
    ## version notes above; `default_site` still names the file that was believed.
    decided = {m: d for m, rows in by_macro.items() if (d := decided_default(rows)) is not None}
    return tuple(
        replace(
            gate,
            default_state=decided[gate.macro][0],
            default_site=decided[gate.macro][1],
            in_default_build=_in_default_build(gate.form, decided[gate.macro][0]),
        )
        if gate.macro in decided
        else gate
        for gate in gates
    )

Activity · 8 steps
lines 656–656◇ if not gates or not table_exists(conn, "config_defaults")lines 657–657return gateslines 658–658macros = sorted({gate.macro for gate in gates})lines 659–659by_macro: dict[str, list[tuple[str, str, int, str]]] = {}lines 660–660◇ for macro, state, path, line_no, origin in _defaults_for_macros(conn, macros)lines 661–663by_macro.setdefault(str(macro), []).append( (str(state), str(path), int(line_no), str(origin)) )lines 667–667decided = {m: d for m, rows in by_macro.items() if (d := decided_default(rows)) is not None}lines 668–678return tuple( replace( gate, default_state=decided[gate.macro][0], default_site=decided[gate.macro][1], in_default_build=_in_default_build(gate.form, decided[gate.macro][0]), ) if gate.macro in decided else gate for gate in gates )

Flows

gates_covering

tuple[tuple[KconfigGate, ...], int] clew.query.kconfig.gates_covering(sqlite3.Connection conn, str file_path, int line)

The configuration gates whose branch covers one source line.

clew/query/kconfig.py:517

Source · 56 lines
def gates_covering(
    conn: sqlite3.Connection, file_path: str, line: int
) -> tuple[tuple[KconfigGate, ...], int]:
    """THE INVERSE DIRECTION, AND THE ONE A QUESTION ACTUALLY ASKS. `kconfig_space` answers
    "which lines does symbol X gate", which needs the symbol first. Both graded questions on
    this project's matrix ask the other way round: here is a function — is it compiled in, and
    under what flag. Answering that from the symbol direction means enumerating the whole
    configuration space and reading it, which is an inventory where an adjacency was wanted.

    A ROW WITH NO EXTENT IS SKIPPED AND COUNTED, never guessed at. An index built before the
    extent column stores `end_line = 0`, and both available guesses are wrong in a way that
    looks right: treating it as covering nothing silently reports an entirely gated file as
    ungated, and treating it as covering the rest of the file attributes ordinary code to the
    last conditional above it. So the count comes back with the answer and the caller says
    "this index cannot tell" rather than answering from a coin flip.

    NO POLARITY IS EVALUATED HERE. Each gate carries its own `form`, and the harvest already
    split an `#else` into its own row with the polarity inverted, so a covering set of
    `[ifdef MBEDTLS_THREADING_C]` and one of `[ifndef MBEDTLS_THREADING_C]` are different
    answers about the same symbol. Collapsing them to "gated by MBEDTLS_THREADING_C" would
    throw away exactly the half that says whether the code is there.

    @brief Which gates decide whether one line exists.
    @return The covering gates and the unknown-extent count.
    @version 1
    """
    if not table_exists(conn, "kconfig_gates"):
        return (), 0
    unknown = 0
    if has_columns(conn, "kconfig_gates", "end_line"):
        unknown = int(
            conn.execute(
                "SELECT COUNT(*) FROM kconfig_gates WHERE file_path = ? AND end_line = 0",
                (file_path,),
            ).fetchone()[0]
        )
    else:
        unknown = int(
            conn.execute(
                "SELECT COUNT(*) FROM kconfig_gates WHERE file_path = ?", (file_path,)
            ).fetchone()[0]
        )
        return (), unknown
    ## FILTERED IN SQL, not in Python over every gate in the repository. mbedtls harvests
    ## thousands of gating sites and this runs per dossier subject; reading them all to keep three
    ## would put the cost of the whole configuration space behind one function lookup.
    rows = conn.execute(
        f"SELECT {_gate_columns(conn)} FROM kconfig_gates "  # noqa: S608
        "WHERE file_path = ? AND end_line > 0 AND line <= ? AND end_line >= ? "
        "ORDER BY line",
        (file_path, line, line),
    ).fetchall()
    gates = tuple(KconfigGate(*row) for row in rows)
    return _with_defaults(conn, gates), unknown

Activity · 11 steps
lines 543–543◇ if not table_exists(conn, "kconfig_gates")lines 544–544return (), 0lines 545–545unknown = 0lines 546–546◇ if has_columns(conn, "kconfig_gates", "end_line")lines 547–552unknown = int( conn.execute( "SELECT COUNT(*) FROM kconfig_gates WHERE file_path = ? AND end_line = 0", (file_path,), ).fetchone()[0] )lines 553–553elselines 554–558unknown = int( conn.execute( "SELECT COUNT(*) FROM kconfig_gates WHERE file_path = ?", (file_path,) ).fetchone()[0] )lines 559–559return (), unknownlines 563–568rows = conn.execute( f"SELECT {_gate_columns(conn)} FROM kconfig_gates " # noqa: S608 "WHERE file_path = ? AND end_line > 0 AND line <= ? AND end_line >= ? " "ORDER BY line", (file_path, line, line), ).fetchall()lines 569–569gates = tuple(KconfigGate(*row) for row in rows)lines 570–570return _with_defaults(conn, gates), unknown

Requirements

REQ-DDB-QUERY-006

Flows

gates_meaning

str clew.query.kconfig.gates_meaning(int names, int total, bool filtered)

Say what the gate list holds and where the omitted detail is.

clew/query/kconfig.py:388

Source · 35 lines
def gates_meaning(names: int, total: int, filtered: bool) -> str:
    """AN EMPTY `gates` LIST MUST NOT READ AS "NOTHING GATES CODE HERE". This module exists
    because three different repositories yield zero symbols for three different reasons, and an
    inventory reply that omits the SITES deliberately would reintroduce exactly that ambiguity one
    field over.

    So it says the sites were omitted, why, and the one call that returns them.

    @brief Explain the inventory reply's gate list and route to the sites.
    @return The sentence, or "".
    @version 1
    """
    if not total:
        return ""
    parts = [
        f"{total} distinct symbol(s) gate code in this index"
        + (" matching your text" if filtered else "")
        + ". This corpus lists the symbols that EXIST; the per-site rows are omitted "
        "DELIBERATELY, not absent — mbedtls has 12,096 of them and returning the set costs "
        "over 2 MB."
    ]
    if names < total:
        ## NEVER a silent cap: a truncated inventory that does not say so reads as the whole space.
        parts.append(
            f"Only the first {names} names are listed — pass `text` to narrow, because the "
            f"remaining {total - names} are not shown."
        )
    parts.append(
        "For ONE symbol's gating sites, with their files, lines and branch form, call "
        "`dossier` on the symbol name: it resolves a gating macro as `kind='config'` and "
        "returns those rows filtered."
    )
    return " ".join(parts)

Activity · 7 steps
lines 400–400◇ if not totallines 401–401return ""lines 402–408parts = [ f"{total} distinct symbol(s) gate code in this index" + (" matching your text" if filtered else "") + ". This corpus lists the symbols that EXIST; the per-site rows are omitted " "DELIBERATELY, not absent — mbedtls has 12,096 of them and returning the set costs " "over 2 MB." ]lines 409–409◇ if names < totallines 411–414parts.append( f"Only the first {names} names are listed — pass `text` to narrow, because the " f"remaining {total - names} are not shown." )lines 415–419parts.append( "For ONE symbol's gating sites, with their files, lines and branch form, call " "`dossier` on the symbol name: it resolves a gating macro as `kind='config'` and " "returns those rows filtered." )lines 420–420return " ".join(parts)

Requirements

REQ-DDB-QUERY-006

Flows

kconfig_space

KconfigSpace clew.query.kconfig.kconfig_space(DbSource db, str|None symbol=None, bool include_gates=True)

A repo's configuration space: its symbols, their groups, and what they gate.

clew/query/kconfig.py:459

Source · 51 lines
def kconfig_space(
    db: DbSource, symbol: str | None = None, include_gates: bool = True
) -> KconfigSpace:
    """`found` comes from `build_meta`, NOT from the presence of the table, and the
    difference is the point. A build that found a Kconfig and failed to parse it
    creates the tables empty and stamps `kconfig.error`; a build on a repo with no
    Kconfig creates nothing and stamps nothing. Deciding `found` from the table would
    collapse those two into one answer, which is precisely the collapse this layer
    exists to prevent.

    The gate list is NOT filtered to declared symbols. A gate on a symbol no Kconfig
    declares is dead code behind a symbol nobody can set — a finding worth returning
    rather than tidying away.

    @brief Query the configuration space with the provenance of the answer.
    @return The space.
    @version 4
    """
    with connect(db) as conn:
        meta = _meta(conn)
        symbols = _symbols(conn) if table_exists(conn, "kconfig_symbols") else ()
        gate_state, gate_symbols = _gate_layer_state(conn)
        ## THE INVENTORY FORM omits the per-site rows and lists the symbol NAMES instead. When a
        ## caller names a symbol the sites ARE the answer, so `include_gates` stays True there;
        ## `_search_config` — which names none — is what was returning all 12,096.
        names, name_total = ((), 0) if include_gates else _gate_symbol_names(conn, symbol)
        return KconfigSpace(
            found=bool(meta.get("source")),
            source=meta.get("source", ""),
            root=meta.get("root", ""),
            symbols=symbols,
            gates=_gates(conn, symbol) if include_gates else (),
            error=meta.get("error", ""),
            configured_macros=meta.get(_PREPROCESSOR_MACROS, ""),
            configured_macros_source=meta.get(_PREPROCESSOR_SOURCE, ""),
            config_header=meta.get(_PREPROCESSOR_HEADER, ""),
            macros_meaning=macros_meaning(
                meta.get(_PREPROCESSOR_MACROS, ""),
                meta.get(_PREPROCESSOR_SOURCE, ""),
                meta.get(_PREPROCESSOR_HEADER, ""),
                meta.get(_PREPROCESSOR_STATED_ONLY, ""),
            ),
            gate_state=gate_state,
            gate_symbols=gate_symbols,
            gate_symbol_names=names,
            gates_meaning=gates_meaning(len(names), name_total, bool(symbol))
            if not include_gates
            else "",
        )

Activity · 6 steps
lines 477–477with connect(db) as connlines 478–478meta = _meta(conn)lines 479–479symbols = _symbols(conn) if table_exists(conn, "kconfig_symbols") else ()lines 480–480gate_state, gate_symbols = _gate_layer_state(conn)lines 484–484names, name_total = ((), 0) if include_gates else _gate_symbol_names(conn, symbol)lines 485–507return KconfigSpace( found=bool(meta.get("source")), source=meta.get("source", ""), root=meta.get("root", ""), symbols=symbols, gates=_gates(conn, symbol) if include_gates else (), error=meta.get("error", ""), configured_macros=meta.get(_PREPROCESSOR_MACROS, ""), configured_macros_source=meta.get(_PREPROCESSOR_SOURCE, ""), config_header=meta.get(_PREPROCESSOR_HEADER, ""), macros_meaning=macros_meaning( meta.get(_PREPROCESSOR_MACROS, ""), meta.get(_PREPROCESSOR_SOURCE, ""), meta.get(_PREPROCESSOR_HEADER, ""), meta.get(_PREPROCESSOR_STATED_ONLY, ""), ), gate_state=gate_state, gate_symbols=gate_symbols, gate_symbol_names=names, gates_meaning=gates_meaning(len(names), name_total, bool(symbol)) if not include_gates else "", )

Requirements

REQ-DDB-QUERY-006

Flows

macros_meaning

str clew.query.kconfig.macros_meaning(str macros, str source, str header, str stated_only="")

Say what configured_macros is evidence OF, and route to the repo's own default.

clew/query/kconfig.py:91

Source · 108 lines
def macros_meaning(macros: str, source: str, header: str, stated_only: str = "") -> str:
    """ROUTE, DO NOT DISCLAIM — this repo's standing pattern, and the reason it is needed here
    is that the previous reply argued for a FALSE answer rather than merely withholding a true
    one. `configured_macros` says which variant the INDEX was built in. A reader takes it for
    which variant the REPOSITORY ships, and on a target whose macros were stated by the operator
    those are opposites.

    Measured on mbedtls: the acceptance build predefines `MBEDTLS_THREADING_C` and
    `MBEDTLS_THREADING_PTHREAD`; the shipped `include/mbedtls/mbedtls_config.h` has both
    commented out. Two graded marks ask for the shipped state, and every reply pointed the other
    way — including all 154 gate rows, labelled `origin: "declared"`, where "declared" means
    "named in the list THIS BUILD was given" and reads as "the repository declares it".

    A DISCLAIMER WOULD NOT HAVE HELPED. "these macros may not reflect the default" leaves the
    agent to hunt or to quote the number anyway; naming the file collapses the follow-up to one
    grep. So when the header is known this says where to look, and when it is not, it says the
    default is not recorded rather than implying the stated list is one.

    @brief Explain what the configured macro list is and is not evidence of.
    @return The sentence, or "" when nothing was recorded.
    @version 3
    """
    if not macros and not source:
        return ""
    ## THE LEAD SENTENCE IS CONDITIONAL, because a blanket "never a statement about the
    ## repository's default" is FALSE in the one case where the list was read out of the
    ## repository's own header — and a note that contradicts its own next sentence teaches a
    ## reader to skip the whole thing.
    parts = [
        f"`configured_macros` is the variant THIS INDEX was built in (source: {source or 'unrecorded'})."
        if source == "config_header"
        else f"`configured_macros` is the variant THIS INDEX was built in "
        f"(source: {source or 'unrecorded'}), not a statement about what the repository "
        "enables by default."
    ]
    ## THREE SOURCES, THREE DIFFERENT SENTENCES, and the MIXED one is the trap. An earlier
    ## version said "these were STATED BY THE OPERATOR" whenever a statement was involved,
    ## which on mbedtls describes 2 macros out of 144 — the other 142 are read from the
    ## repository's own header. That inverts the disclosure in the opposite direction: it
    ## invites a reader to discount the whole list as an artifact of the build. A correction
    ## that is wrong the other way is not a correction.
    ## THE OVERRIDE CASE, AND IT IS THE ACCEPTANCE BUILD'S CASE. `source` is `flag` whenever a
    ## macro list was passed as an argument — which `clew/cli.py` does with a declared
    ## `predefined:` — so this is the branch mbedtls actually takes. When the declaration ALSO
    ## named a config header, the split is computable and this states the answer rather than
    ## warning that an answer exists. Before, this branch could only ever disclaim.
    if source in ("flag", "declared") and stated_only:
        listed = stated_only if isinstance(stated_only, str) else ", ".join(stated_only)
        parts.append(
            f"These macros were STATED FOR THIS BUILD, so they are evidence about the build and "
            f"not about the repository. AND THE REPOSITORY'S OWN HEADER DOES NOT DEFINE: {listed} "
            f"— those ship OFF and are ON here only because this build declared them. Every other "
            f"macro in the list was read from that header and IS on by default."
        )
    elif source in ("flag", "declared"):
        parts.append(
            "These macros were STATED BY THE OPERATOR for this build — typically so the "
            "preprocessor could reach code behind an `#if` — so they are evidence about the "
            "build and NOT about the repository. A macro listed here may well be OFF, or "
            "commented out, in the repository's own configuration."
        )
    elif source == "declared+config_header" and stated_only:
        ## THE SPLIT IS NOW RECORDED, so this states the answer instead of routing to a file read.
        ## `preprocessor.stated_only` holds exactly the names the operator supplied that the
        ## repository's own header does NOT define — which is to say, the ones that ship OFF. Every
        ## other macro in the list was READ OUT OF that header and therefore ships ON.
        ##
        ## This is the difference between a caveat and an answer. The previous wording said the
        ## field "does not say which came from which" and pointed at the config file; two graded
        ## marks asked which, and the agent went to the shell. Naming the set costs a clause.
        ## ALREADY JOINED, so do NOT join it again. `PreprocessorConfig.as_meta` writes this row as
        ## `", ".join(self.stated_only)` (clew/preprocessor.py:404), so what arrives is a string.
        ## `', '.join()` over a string iterates CHARACTERS, and the one sentence that answers the
        ## question rendered as "M, B, E, D, T, L, S, _, T, H, R, E, A, D, I, N, G, _, C, ,, …".
        ## Normalised rather than assumed: a caller holding the tuple form gets the same output
        ## instead of "('A', 'B')".
        listed = stated_only if isinstance(stated_only, str) else ", ".join(stated_only)
        parts.append(
            f"This list COMBINES the repository's own configuration header with macros stated for "
            f"this build. THE STATED ONES ARE: {listed} — these are OFF in the "
            f"repository's own configuration and are ON here only because this build declared "
            f"them. Every OTHER macro in the list was read from that header and IS on by default."
        )
    elif source == "declared+config_header":
        parts.append(
            "This list COMBINES the repository's own configuration header with macros stated "
            "for this build, and this build did not record which came from which. So a macro "
            "listed here is not evidence that the repository enables it."
        )
    elif source == "config_header":
        parts.append(
            "This configuration was read from the repository's own header, so it does describe "
            "what the repository builds by default."
        )
    if header:
        parts.append(
            f"The repository's own default is in `{header}`: a macro absent or commented out "
            "there is off by default. Read that file to settle what a DEFAULT build does."
        )
    else:
        parts.append(
            "No config header is recorded for this target, so the repository's own default is "
            "NOT in this index — declare `preprocessor.config_header` to make it answerable, "
            "and until then treat the default as unknown rather than as the list above."
        )
    return " ".join(parts)

Activity · 20 steps
lines 113–113◇ if not macros and not sourcelines 114–114return ""lines 119–125parts = [ f"`configured_macros` is the variant THIS INDEX was built in (source: {source or 'unrecorded'})." if source == "config_header" else f"`configured_macros` is the variant THIS INDEX was built in " f"(source: {source or 'unrecorded'}), not a statement about what the repository " "enables by default." ]lines 137–137◇ if source in ("flag", "declared") and stated_onlylines 138–138listed = stated_only if isinstance(stated_only, str) else ", ".join(stated_only)lines 139–144parts.append( f"These macros were STATED FOR THIS BUILD, so they are evidence about the build and " f"not about the repository. AND THE REPOSITORY'S OWN HEADER DOES NOT DEFINE: {listed} " f"— those ship OFF and are ON here only because this build declared them. Every other " f"macro in the list was read from that header and IS on by default." )lines 145–145◇ elif source in ("flag", "declared")lines 146–151parts.append( "These macros were STATED BY THE OPERATOR for this build — typically so the " "preprocessor could reach code behind an `#if` — so they are evidence about the " "build and NOT about the repository. A macro listed here may well be OFF, or " "commented out, in the repository's own configuration." )lines 152–152◇ elif source == "declared+config_header" and stated_onlylines 167–167listed = stated_only if isinstance(stated_only, str) else ", ".join(stated_only)lines 168–173parts.append( f"This list COMBINES the repository's own configuration header with macros stated for " f"this build. THE STATED ONES ARE: {listed} — these are OFF in the " f"repository's own configuration and are ON here only because this build declared " f"them. Every OTHER macro in the list was read from that header and IS on by default." )lines 174–174◇ elif source == "declared+config_header"lines 175–179parts.append( "This list COMBINES the repository's own configuration header with macros stated " "for this build, and this build did not record which came from which. So a macro " "listed here is not evidence that the repository enables it." )lines 180–180◇ elif source == "config_header"lines 181–184parts.append( "This configuration was read from the repository's own header, so it does describe " "what the repository builds by default." )lines 185–185◇ if headerlines 186–189parts.append( f"The repository's own default is in `{header}`: a macro absent or commented out " "there is off by default. Read that file to settle what a DEFAULT build does." )lines 190–190elselines 191–195parts.append( "No config header is recorded for this target, so the repository's own default is " "NOT in this index — declare `preprocessor.config_header` to make it answerable, " "and until then treat the default as unknown rather than as the list above." )lines 196–196return " ".join(parts)

Requirements

REQ-DDB-QUERY-006

Flows