callback_edges.py

clew/callback_edges.py

Layer 4: resolve callback-registration function-pointer calls into real `call_edges` rows.

_binding_branch

bool | None clew.callback_edges._binding_branch(tuple guards, PreprocessorConfig config)

Whether a binding's preprocessor branch is live under a configuration.

clew/callback_edges.py:1291

Show on the map →

Called by _branch_eliminated_bindings, _live_direct_bindings, _log_branch_verdicts

Calls _guard_holds

Source · 28 lines
def _binding_branch(guards: tuple, config: PreprocessorConfig) -> bool | None:
    """gh#35's three-way answer, and each value means something different downstream:
    True emits a 'resolved' edge, None emits a 'fuzzy' one, False emits NOTHING.

    AN UNDECLARED CONFIGURATION RETURNS None, NEVER False, and the `declared` check is
    what makes that so. `defined(X)` against an empty macro set evaluates to False
    perfectly correctly — that is what doxygen parses — but reading that as "the branch is
    dead" would DELETE every conditional binding on every target that declares no
    configuration, i.e. empty the layer for most repositories in exchange for fixing a
    double edge. The declaration is what turns a False into evidence.

    An EMPTY chain returns True unconditionally and before anything else is consulted, so
    a branch-free binding grades exactly as it did before gh#35 whatever the config says.

    @brief Decide a binding's branch under the declared configuration.
    @return True, False, or None.
    @version 1
    """
    if not guards:
        return True
    if not config.declared:
        return None
    verdicts = [_guard_holds(text, negated, config.defined_names) for text, negated in guards]
    dead = any(v is False for v in verdicts)
    unknown = any(v is None for v in verdicts)
    return False if dead else (None if unknown else True)

Activity · 8 steps
lines 1309–1309◇ if not guardslines 1310–1310return Truelines 1311–1311◇ if not config.declaredlines 1312–1312return Nonelines 1313–1313verdicts = [_guard_holds(text, negated, config.defined_names) for text, negated in guards]lines 1314–1314dead = any(v is False for v in verdicts)lines 1315–1315unknown = any(v is None for v in verdicts)lines 1316–1316return False if dead else (None if unknown else True)

Requirements

REQ-DDB-PIPE-003

_branch_eliminated_bindings

dict[str, bool] clew.callback_edges._branch_eliminated_bindings(str global_name, _CallbackCollector collector, PreprocessorConfig config)

The bindings of one global that branch selection eliminated entirely.

clew/callback_edges.py:1360

Show on the map →

Called by _emit_resolved_edges

Calls _binding_branch, _is_known_function

Source · 40 lines
def _branch_eliminated_bindings(
    global_name: str,
    collector: _CallbackCollector,
    config: PreprocessorConfig,
) -> dict[str, bool]:
    """BRANCH SELECTION IS A SELECTION AMONG ALTERNATIVES, NEVER AN ERASER, and this is
    the function that says so. It is consulted only when selection left a global with
    nothing at all — at which point the configuration did not tell us which
    implementation is live, it told us this variant binds none of them, while the index
    still carries every one of the bound functions because gh#11 recovered them from the
    source text precisely BECAUSE the preprocessor skipped them.

    Emitting nothing there is the fallback-to-False that `evaluate_condition` refuses one
    level down, arrived at by a different route: not "we could not read the guard" but
    "we read every guard and they were all dead". The honest statement is the same one,
    and 'fuzzy' is what it already means to every consumer — skipped by both
    `mark_reachability` and the thread BFS, so no traversal reads a branch this build
    cannot compile as fact.

    EVERY value is False, never `branch is None`. A restored binding is by construction
    one whose branch evaluated dead, so it is the weakest premise this layer emits; a
    True here would grade a definitively-dead branch above an undecidable one.

    Measured on Mbed-TLS v3.6.7 with the 142 macros harvested from its own
    `include/mbedtls/mbedtls_config.h`: that header ships `MBEDTLS_THREADING_C` commented
    out, so all 8 bindings of the four `mbedtls_mutex_*` pointers graded dead and this
    layer went from 157 rows to 0 — including the 38 callers of
    `threading_mutex_lock_pthread`, a function the same build indexes.

    @brief Restore the bindings a configuration eliminated, at the undecided grading.
    @return Bound name -> False, for every branch-eliminated binding.
    @version 1
    """
    return {
        name: False
        for name, guards in collector.direct_bindings.get(global_name, [])
        if _is_known_function(name, collector) and _binding_branch(guards, config) is False
    }

Activity · 1 steps
lines 1393–1397return { name: False for name, guards in collector.direct_bindings.get(global_name, []) if _is_known_function(name, collector) and _binding_branch(guards, config) is False }

Requirements

REQ-DDB-PIPE-003

_ensure_external_boundaries_table

None clew.callback_edges._ensure_external_boundaries_table(sqlite3.Connection conn)

Create the external_boundaries table if it doesn't exist.

clew/callback_edges.py:1506

Source · 35 lines
def _ensure_external_boundaries_table(conn: sqlite3.Connection) -> None:
    """Always-create the terminus table (empty when nothing dead-ends), so
    R2/R4 never branch on its existence — the requirements.py precedent.

    `source` gained a CHECK here: it was `TEXT NOT NULL DEFAULT 'callback_edges'`
    with nothing constraining it, i.e. free text on a column a consumer reads as
    provenance. Only the default was ever written, so the constraint is a
    tightening no existing row can violate.

    @brief Idempotent external_boundaries table creation.
    @version 3
    """
    conn.execute(
        f"""
        CREATE TABLE IF NOT EXISTS external_boundaries (
            memberdef_rowid        INTEGER NOT NULL REFERENCES memberdef(rowid),
            global_name            TEXT NOT NULL,
            kind                   TEXT NOT NULL {check("external_boundaries", "kind")},
            registered_by_rowid    INTEGER REFERENCES memberdef(rowid),
            registered_param_index INTEGER,
            note                   TEXT,
            source                 TEXT NOT NULL DEFAULT 'callback_edges'
                                     {check("external_boundaries", "source")},
            confidence             TEXT NOT NULL {check("external_boundaries", "confidence")},
            UNIQUE(memberdef_rowid, global_name)
        )
        """,
    )
    conn.execute(
        "CREATE INDEX IF NOT EXISTS idx_external_boundaries_member "
        "ON external_boundaries(memberdef_rowid)",
    )
    conn.commit()

Activity · 3 steps
lines 1518–1533conn.execute( f""" CREATE TABLE IF NOT EXISTS external_boundaries ( memberdef_rowid INTEGER NOT NULL REFERENCES memberdef(rowid), global_name TEXT NOT NULL, kind TEXT NOT NULL {check("external_boundaries", "kind")}, registered_by_rowid INTEGER REFERENCES memberdef(rowid), registered_param_index INTEGER, note TEXT, source TEXT NOT NULL DEFAULT 'callback_edges' {check("external_boundaries", "source")}, confidence TEXT NOT NULL {check("external_boundaries", "confidence")}, UNIQUE(memberdef_rowid, global_name) ) """, )lines 1534–1537conn.execute( "CREATE INDEX IF NOT EXISTS idx_external_boundaries_member " "ON external_boundaries(memberdef_rowid)", )lines 1538–1538conn.commit()

Requirements

REQ-DDB-SCHEMA-003 REQ-DDB-SCHEMA-007

_insert_external_boundaries

int clew.callback_edges._insert_external_boundaries(sqlite3.Connection conn, list[_ExternalBoundary] boundaries)

Insert recorded external-boundary terminus rows.

clew/callback_edges.py:1544

Source · 28 lines
def _insert_external_boundaries(
    conn: sqlite3.Connection,
    boundaries: list[_ExternalBoundary],
) -> int:
    """Bulk-insert terminus rows (kind='unresolved_callback', 'high').

    @brief Insert external_boundaries rows, ignoring duplicates.
    @version 2
    """
    return conn.executemany(
        """
        INSERT OR IGNORE INTO external_boundaries
            (memberdef_rowid, global_name, kind, registered_by_rowid,
             registered_param_index, source, confidence)
        VALUES (?, ?, 'unresolved_callback', ?, ?, 'callback_edges', 'high')
        """,
        [
            (
                b.memberdef_rowid,
                b.global_name,
                b.registered_by_rowid,
                b.registered_param_index,
            )
            for b in boundaries
        ],
    ).rowcount

Activity · 1 steps
lines 1553–1569return conn.executemany( """ INSERT OR IGNORE INTO external_boundaries (memberdef_rowid, global_name, kind, registered_by_rowid, registered_param_index, source, confidence) VALUES (?, ?, 'unresolved_callback', ?, ?, 'callback_edges', 'high') """, [ ( b.memberdef_rowid, b.global_name, b.registered_by_rowid, b.registered_param_index, ) for b in boundaries ], ).rowcount

Requirements

REQ-DDB-SCHEMA-003

_record_external_boundary

None clew.callback_edges._record_external_boundary(str global_name, list[tuple[int, int]] registrations, _CallbackCollector collector, dict[int, str] rowid_to_name, list[_ExternalBoundary] boundaries)

Record an external-boundary row for a dead-ended registration.

clew/callback_edges.py:1224

Show on the map →

Called by _emit_resolved_edges

Calls _registration_forwards_externally

Source · 43 lines
def _record_external_boundary(
    global_name: str,
    registrations: list[tuple[int, int]],
    collector: _CallbackCollector,
    rowid_to_name: dict[int, str],
    boundaries: list[_ExternalBoundary],
) -> None:
    """Gate to the genuinely-external case (a forwarded-param dead-end, NOT
    a NULL-only registration) and, when it applies, record one terminus row
    per in-repo invoking function — capturing the registering function +
    param index (in-hand at this exact point) per the consumer-fit add.

    @brief Record terminus rows for a dead-ended callback registration.
    @version 2
    """
    call_sites = collector.call_sites.get(global_name, [])
    if not call_sites:
        return  # never invoked in-repo — nothing to terminate a chain at
    external = any(
        _registration_forwards_externally(
            collector.signatures[func_rowid].name,
            param_index,
            collector,
            rowid_to_name,
            set(),
        )
        for func_rowid, param_index in registrations
        if func_rowid in collector.signatures
    )
    if not external:
        return  # NULL-only / non-forwarding registration — not a terminus
    registered_by_rowid, registered_param_index = registrations[0]
    for caller_rowid, _args in call_sites:
        boundaries.append(
            _ExternalBoundary(
                memberdef_rowid=caller_rowid,
                global_name=global_name,
                registered_by_rowid=registered_by_rowid,
                registered_param_index=registered_param_index,
            ),
        )

Activity · 9 steps
lines 1239–1239call_sites = collector.call_sites.get(global_name, [])lines 1240–1240◇ if not call_siteslines 1241–1241returnlines 1242–1252external = any( _registration_forwards_externally( collector.signatures[func_rowid].name, param_index, collector, rowid_to_name, set(), ) for func_rowid, param_index in registrations if func_rowid in collector.signatures )lines 1253–1253◇ if not externallines 1254–1254returnlines 1255–1255registered_by_rowid, registered_param_index = registrations[0]lines 1256–1256◇ for caller_rowid, _args in call_siteslines 1257–1264boundaries.append( _ExternalBoundary( memberdef_rowid=caller_rowid, global_name=global_name, registered_by_rowid=registered_by_rowid, registered_param_index=registered_param_index, ), )

Requirements

REQ-DDB-SCHEMA-003

_registration_forwards_externally

bool clew.callback_edges._registration_forwards_externally(str func_name, int param_index, _CallbackCollector collector, dict[int, str] rowid_to_name, set[tuple[str, int]] visited)

True if a registration's binding chain forwards a param out of repo.

clew/callback_edges.py:1188

Show on the map →

Called by _record_external_boundary

Calls _caller_signature, _is_known_function

Source · 33 lines
def _registration_forwards_externally(
    func_name: str,
    param_index: int,
    collector: _CallbackCollector,
    rowid_to_name: dict[int, str],
    visited: set[tuple[str, int]],
) -> bool:
    """Distinguish a genuinely-external terminus (a forwarded-parameter
    chain that dead-ends at an out-of-repo caller — the `svc_notify_cb` shape)
    from a NULL-only registration (`DataModel_Initialize(NULL)`), which must
    NOT be recorded. Returns True as soon as any call site forwards one of
    the caller's OWN parameters into `param_index`: since this is only ever
    called when the overall binding resolved to nothing, a forward hop means
    the callback is passed through but never bound in-repo.

    @brief Detect a forwarded-parameter (external) binding dead-end.
    @version 3
    """
    if (func_name, param_index) in visited:
        return False
    visited.add((func_name, param_index))
    for caller_rowid, args in collector.call_sites.get(func_name, []):
        if param_index >= len(args):
            continue
        arg = args[param_index]
        if arg is None or _is_known_function(arg, collector):
            continue
        caller_sig = _caller_signature(caller_rowid, rowid_to_name, collector)
        if caller_sig is not None and arg in caller_sig.param_names:
            return True
    return False

Activity · 13 steps
lines 1206–1206◇ if (func_name, param_index) in visitedlines 1207–1207return Falselines 1208–1208visited.add((func_name, param_index))lines 1209–1209◇ for caller_rowid, args in collector.call_sites.get(func_name, [])lines 1210–1210◇ if param_index >= len(args)lines 1211–1211continuelines 1212–1212arg = args[param_index]lines 1213–1213◇ if arg is None or _is_known_function(arg, collector)lines 1214–1214continuelines 1215–1215caller_sig = _caller_signature(caller_rowid, rowid_to_name, collector)lines 1216–1216◇ if caller_sig is not None and arg in caller_sig.param_nameslines 1217–1217return Truelines 1218–1218return False

Requirements

REQ-DDB-SCHEMA-003

callback_harvester

Harvester clew.callback_edges.callback_harvester()

Layer 4's per-file harvester.

clew/callback_edges.py:932

Source · 13 lines
def callback_harvester() -> Harvester:
    """Public factory for gh#358's shared parse pass. This stage's `extra_key` is
    empty ONLY because the harvest stores the raw preprocessor guard chain and the
    `PreprocessorConfig` is applied after it; the shared pass changes nothing about
    that, and branch selection must stay out of `harvest` or the empty key becomes a
    lie.

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

Activity · 1 steps
lines 942–942return _CallbackHarvester()

Requirements

REQ-DDB-PIPE-003

harvest

Any clew.callback_edges._CallbackHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's callback-edge source material.

clew/callback_edges.py:924

Show on the map →

Called by none

Calls _harvest_callback_file

Source · 4 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        return _harvest_callback_file(tree, src_bytes)

Activity · 1 steps
lines 925–925return _harvest_callback_file(tree, src_bytes)

Requirements

REQ-DDB-PIPE-003

import_callback_registration_edges

None clew.callback_edges.import_callback_registration_edges(Path db_path, Path repo_root, IndexCache|None cache=None, PreprocessorConfig|None preprocessor=None)

Layer 4: resolve callback-registration calls into call_edges rows.

clew/callback_edges.py:1635

Source · 62 lines
def import_callback_registration_edges(
    db_path: Path,
    repo_root: Path,
    cache: IndexCache | None = None,
    preprocessor: PreprocessorConfig | None = None,
) -> None:
    """Walk every indexed C/C++ file, detect `GLOBAL = PARAM;` callback
    registrations, resolve each to its concrete function(s), and insert
    `call_edges` rows for every call site of the registered global.
    Runs unconditionally — no CLI flag, since the pattern is structural, not repo-specific.

    The per-file harvest is content-sha cached; the rowid resolution and the
    cross-file binding resolution always rerun.

    `preprocessor` selects which `#if` branch a conditional binding belongs to (gh#35).
    Defaulting it to None rather than requiring it keeps every existing caller working, and
    the default is the SAFE direction: an undeclared configuration grades conditional
    bindings DOWN to 'fuzzy', so a caller that forgets to pass one under-states an edge
    rather than asserting the wrong branch as fact.

    @brief Import callback-registration call edges (Layer 4).
    @version 6
    """
    conn = sqlite3.connect(str(db_path))
    _ensure_external_boundaries_table(conn)
    name_to_rowids, file_funcs = _build_function_indexes(conn)
    collector = _CallbackCollector()
    for path_rowid, payload in run_harvest(
        conn,
        repo_root,
        callback_harvester(),
        cache,
    ):
        _fold_callback_payload(payload, file_funcs.get(path_rowid, []), collector)

    edges_resolved, edges_fuzzy, boundaries = _emit_resolved_edges(
        collector, name_to_rowids, preprocessor
    )
    inserted_resolved = conn.executemany(
        "INSERT OR IGNORE INTO call_edges "
        "(caller_rowid, callee_rowid, source, confidence) "
        "VALUES (?, ?, ?, 'resolved')",
        edges_resolved,
    ).rowcount
    inserted_fuzzy = conn.executemany(
        "INSERT OR IGNORE INTO call_edges "
        "(caller_rowid, callee_rowid, source, confidence) "
        "VALUES (?, ?, ?, 'fuzzy')",
        edges_fuzzy,
    ).rowcount
    inserted_boundaries = _insert_external_boundaries(conn, boundaries)
    conn.commit()
    conn.close()
    logger.info(
        "callback_edges: resolved %d registrations, added %d resolved + "
        "%d fuzzy call_edges rows, %d external-boundary terminus rows",
        len(collector.registrations),
        inserted_resolved,
        inserted_fuzzy,
        inserted_boundaries,
    )
    _log_branch_verdicts(collector, preprocessor or PreprocessorConfig())

1 more lines, not shown

Activity · 14 steps
lines 1658–1658conn = sqlite3.connect(str(db_path))lines 1659–1659_ensure_external_boundaries_table(conn)lines 1660–1660name_to_rowids, file_funcs = _build_function_indexes(conn)lines 1661–1661collector = _CallbackCollector()lines 1662–1662◇ for path_rowid, payload in run_harvest(lines 1668–1668_fold_callback_payload(payload, file_funcs.get(path_rowid, []), collector)lines 1670–1672edges_resolved, edges_fuzzy, boundaries = _emit_resolved_edges( collector, name_to_rowids, preprocessor )lines 1673–1678inserted_resolved = conn.executemany( "INSERT OR IGNORE INTO call_edges " "(caller_rowid, callee_rowid, source, confidence) " "VALUES (?, ?, ?, 'resolved')", edges_resolved, ).rowcountlines 1679–1684inserted_fuzzy = conn.executemany( "INSERT OR IGNORE INTO call_edges " "(caller_rowid, callee_rowid, source, confidence) " "VALUES (?, ?, ?, 'fuzzy')", edges_fuzzy, ).rowcountlines 1685–1685inserted_boundaries = _insert_external_boundaries(conn, boundaries)lines 1686–1686conn.commit()lines 1687–1687conn.close()lines 1688–1695logger.info( "callback_edges: resolved %d registrations, added %d resolved + " "%d fuzzy call_edges rows, %d external-boundary terminus rows", len(collector.registrations), inserted_resolved, inserted_fuzzy, inserted_boundaries, )lines 1696–1696_log_branch_verdicts(collector, preprocessor or PreprocessorConfig())

Requirements

REQ-DDB-PIPE-003