harvest.py

clew/harvest.py

Per-file tree-sitter parse plumbing + the cached harvest driver.

_ast_parse_one_file

tuple[Any, bytes] | None clew.harvest._ast_parse_one_file(str rel_path, Path abs_path, dict parser_cache)

Parse one file with the appropriate tree-sitter grammar.

clew/harvest.py:359

Show on the map →

Called by _harvest_file, _parse, _parse, _parse, _parse, _parse, _parse_and_store, _real_function_name_at, _self_sites_for, _shared_parse_one_file, _sites, _worker_parse

2 morecensus_call_sites, scan_repo

Tested by

2 teststest_c_harvest_output_unchanged_on_the_c_fixture, test_the_harvest_reads_both_branches_of_a_conditional_define

Calls _cached_parser, _disambiguate_header, _parseable_file, _ts_language_for

Source · 30 lines
def _ast_parse_one_file(
    rel_path: str,
    abs_path: Path,
    parser_cache: dict,
) -> tuple[Any, bytes] | None:
    """Parse one file with the appropriate tree-sitter grammar.

    Returns (tree, src_bytes) on success or None when the file's extension
    isn't recognized, the file isn't a regular file, or the read failed.
    `parser_cache` is mutated in place to memoize per-language parsers.

    A `.h` that fails to parse as C is retried as C++ (see _AMBIGUOUS_EXTS).

    @brief Parse one source file into a tree-sitter tree.
    @version 5
    """
    lang_mod = _ts_language_for(rel_path)
    parser = _cached_parser(lang_mod.__name__, parser_cache) if lang_mod is not None else None
    if parser is None or not _parseable_file(abs_path):
        return None
    try:
        src_bytes = abs_path.read_bytes()
    except OSError:
        return None
    tree = parser.parse(src_bytes)
    if rel_path.lower().endswith(_AMBIGUOUS_EXTS) and tree.root_node.has_error:
        tree = _disambiguate_header(tree, src_bytes, parser_cache)
    return tree, src_bytes

Activity · 12 steps
lines 375–375lang_mod = _ts_language_for(rel_path)lines 376–376parser = _cached_parser(lang_mod.__name__, parser_cache) if lang_mod is not None else Nonelines 377–377◇ if parser is None or not _parseable_file(abs_path)lines 378–378return Nonelines 379–379trylines 380–380src_bytes = abs_path.read_bytes()lines 381–381except OSErrorlines 382–382return Nonelines 383–383tree = parser.parse(src_bytes)lines 384–384◇ if rel_path.lower().endswith(_AMBIGUOUS_EXTS) and tree.root_node.has_errorlines 385–385tree = _disambiguate_header(tree, src_bytes, parser_cache)lines 386–386return tree, src_bytes

Flows

_cached_parser

clew.harvest._cached_parser(str mod_name, dict parser_cache)

Memoized substrate parser for one grammar name.

clew/harvest.py:279

Source · 18 lines
def _cached_parser(mod_name: str, parser_cache: dict):
    """Every grammar is parsed by clew/tsnode.py's substrate parser.

    @brief Build (once) and return the parser for a grammar name.
    @return A parser, or None when the grammar is unknown.
    @version 4
    """
    parser = parser_cache.get(mod_name)
    if parser is None:
        mod = _try_import_ts_module(mod_name)
        if mod is not None:
            from .tsnode import Parser as SubstrateParser

            parser = SubstrateParser(mod.key)
        parser_cache[mod_name] = parser
    return parser

Activity · 8 steps
lines 286–286parser = parser_cache.get(mod_name)lines 287–287◇ if parser is Nonelines 288–288mod = _try_import_ts_module(mod_name)lines 289–289◇ if mod is not Nonelines 290–290from .tsnode import Parser as SubstrateParserlines 292–292parser = SubstrateParser(mod.key)lines 293–293parser_cache[mod_name] = parserlines 294–294return parser

Flows

_disambiguate_header

clew.harvest._disambiguate_header(c_tree, bytes src_bytes, dict parser_cache)

Re-parse an erroring ambiguous header as C++ and keep the cleaner tree.

clew/harvest.py:340

Source · 15 lines
def _disambiguate_header(c_tree, src_bytes: bytes, parser_cache: dict):
    """Only reached for a `.h` whose C parse ALREADY errored, so a genuine C
    header never pays for this. Comparing error counts (rather than demanding
    zero) keeps the right grammar for a C++ header that also trips on macros.
    Ties keep C, so nothing changes unless C++ is strictly better.
    """
    cpp = _cached_parser("substrate:cpp", parser_cache)
    if cpp is None:
        return c_tree
    cpp_tree = cpp.parse(src_bytes)
    if _parse_error_count(cpp_tree.root_node) < _parse_error_count(c_tree.root_node):
        return cpp_tree
    return c_tree

Activity · 7 steps
lines 346–346cpp = _cached_parser("substrate:cpp", parser_cache)lines 347–347◇ if cpp is Nonelines 348–348return c_treelines 349–349cpp_tree = cpp.parse(src_bytes)lines 350–350◇ if _parse_error_count(cpp_tree.root_node) < _parse_error_count(c_tree.root_node)lines 351–351return cpp_treelines 352–352return c_tree

Flows

_grammar_available

bool clew.harvest._grammar_available(str modname)

Whether a routed grammar is actually compiled into the installed substrate.

clew/harvest.py:240

Source · 21 lines
def _grammar_available(modname: str) -> bool:
    """Only the optional keys are measured, and only they can be missing — see
    `_OPTIONAL_KEYS`. `clew/substrate.py` caches the answer, so this costs one set lookup
    per file after the first.

    @brief Optional-grammar capability check.
    """
    key = modname[len(_SUBSTRATE_PREFIX) :]
    if key not in _OPTIONAL_KEYS:
        return True
    from . import substrate

    return substrate.has_language(key)


# `.h` says nothing about the language: C uses it, and so does every C++ project
# following the Google style guide. Routing it to C unconditionally does not
# merely fail on a C++ header — it FABRICATES structure. Measured on a header
# with a namespace + class + mutable std::mutex member + template function:
# the C grammar yields 7 ERROR/MISSING nodes and reports TWO function
# definitions where one exists; the C++ grammar yields 0 errors and one.
Activity · 5 steps
lines 247–247key = modname[len(_SUBSTRATE_PREFIX) :]lines 248–248◇ if key not in _OPTIONAL_KEYSlines 249–249return Truelines 250–250from . import substratelines 252–252return substrate.has_language(key)

Flows

_parse_error_count

int clew.harvest._parse_error_count(root)

Count ERROR/MISSING nodes in a parsed tree.

clew/harvest.py:321

Source · 12 lines
def _parse_error_count(root) -> int:
    """@brief Total ERROR/MISSING nodes, used to compare two candidate grammars."""
    errors = 0
    stack = [root]
    while stack:
        node = stack.pop()
        if node.type == "ERROR" or node.is_missing:
            errors += 1
        stack.extend(node.children)
    return errors

Activity · 8 steps
lines 323–323errors = 0lines 324–324stack = [root]lines 325–325◇ while stacklines 326–326node = stack.pop()lines 327–327◇ if node.type == "ERROR" or node.is_missinglines 328–328errors += 1lines 329–329stack.extend(node.children)lines 330–330return errors

Flows

_parseable_file

bool clew.harvest._parseable_file(Path abs_path)

Whether a file may be parsed: it exists and is not binary.

clew/harvest.py:302

Show on the map →

Called by _ast_parse_one_file, _harvest_one_file, _shareable_sha

Calls binary_file

Source · 14 lines
def _parseable_file(abs_path: Path) -> bool:
    """The doxygen stage already drops binaries from the scanned tree, but `path` rows
    also come from doxygen's followed includes and from rustdoc, outside that scan. This
    is the gate in front of every harvest read, and it sits before the content hash so a
    2 GB archive named `.c` is never read whole.

    @brief Existence plus binary check ahead of a parse.
    @return Whether to parse the file.
    """
    from .filetypes import binary_file

    return abs_path.is_file() and binary_file(abs_path) is None

Activity · 2 steps
lines 311–311from .filetypes import binary_filelines 313–313return abs_path.is_file() and binary_file(abs_path) is None

Requirements

REQ-DDB-PIPE-011

Flows

_try_import_ts_module

clew.harvest._try_import_ts_module(str modname)

The grammar handle for a substrate: name, or None for any other name.

clew/harvest.py:195

Source · 6 lines
def _try_import_ts_module(modname: str):
    if modname.startswith(_SUBSTRATE_PREFIX):
        return _SubstrateGrammar(modname)
    return None

Activity · 3 steps
lines 196–196◇ if modname.startswith(_SUBSTRATE_PREFIX)lines 197–197return _SubstrateGrammar(modname)lines 198–198return None

Flows

_ts_language_for

clew.harvest._ts_language_for(str path)

Select the C, C++, Python or Rust tree-sitter language by extension.

clew/harvest.py:206

Source · 29 lines
def _ts_language_for(path: str):
    """Select the tree-sitter grammar for one path's extension.

    Python is routed here rather than at each stage so that EVERY cacheable AST
    stage sees `.py` files at once — the per-file harvest driver gates on this
    function twice (`_harvest_one_file`'s early-out and `_ast_parse_one_file`),
    so a stage cannot opt in on its own.

    Order matters and is carried by `_TS_GRAMMARS`: `.h` is checked after the C++
    list so an ambiguous header still lands on C first and is retried per
    `_AMBIGUOUS_EXTS`.

    `.C` AND `.H` ARE C++ (agent C's W9): the traditional Unix C++ suffixes, which GCC reads as
    C++; lowering the path first sent them to the C grammar. Checked case-sensitively, first.

    @brief Grammar module for one path.
    @version 4
    """
    if path.endswith((".C", ".H")):
        path = path[:-2] + ".hpp"
    lower = path.lower()
    modname = _NAME_GRAMMARS.get(PurePosixPath(lower).name)
    if modname is None:
        modname = next((m for exts, m in _TS_GRAMMARS if lower.endswith(exts)), None)
    if modname is None or not _grammar_available(modname):
        return None
    return _try_import_ts_module(modname)

Activity · 9 steps
lines 224–224◇ if path.endswith((".C", ".H"))lines 225–225path = path[:-2] + ".hpp"lines 226–226lower = path.lower()lines 227–227modname = _NAME_GRAMMARS.get(PurePosixPath(lower).name)lines 228–228◇ if modname is Nonelines 229–229modname = next((m for exts, m in _TS_GRAMMARS if lower.endswith(exts)), None)lines 230–230◇ if modname is None or not _grammar_available(modname)lines 231–231return Nonelines 232–232return _try_import_ts_module(modname)

Flows

enclosing

Any clew.harvest.enclosing(Any node, tuple[str,...] types)

Nearest enclosing node of one of the given types.

clew/harvest.py:395

Show on the map →

Called by _by_block, _class_scope, _closing_release, _enclosing_condition, _enclosing_function_name, _harvest_rust_struct_literal_field, _out_of_line_scope, _rust_enclosing_type, _sealed_in_branch, _shadowed, is_receiver, resolve_section

Tested by

1 teststest_enclosing_walks_parents_so_a_block_is_not_its_own_ancestor

Calls none

Source · 14 lines
def enclosing(node: Any, types: tuple[str, ...]) -> Any:
    """Walks the PARENT chain, so a node is never its own ancestor — the section
    walk relies on that to find the block a `compound_statement` release sits
    inside rather than the release's own body.

    @brief Walk up to the first ancestor of a wanted type.
    @version 1
    """
    current = node.parent
    while current is not None and current.type not in types:
        current = current.parent
    return current

Activity · 4 steps
lines 403–403current = node.parentlines 404–404◇ while current is not None and current.type not in typeslines 405–405current = current.parentlines 406–406return current

Requirements

REQ-DDB-PIPE-003

harvest

Any clew.harvest.Harvester.harvest(self, Any tree, bytes src_bytes)

Extract this stage's rowid-free facts from one parsed file.

clew/harvest.py:438

Show on the map →

Called by none

Calls none

Source · 9 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        """Subclass hook. MUST return JSON-serializable, rowid-free data.

        @brief Per-file extraction hook.
        @version 1
        """
        raise NotImplementedError

Activity · 1 steps
lines 444–444raise NotImplementedError

Requirements

REQ-DDB-PIPE-003

run_harvest

list[tuple[int, Any]] clew.harvest.run_harvest(sqlite3.Connection conn, Path repo_root, Harvester harvester, IndexCache|None cache=None)

Run one harvester over every indexed file, cache-first.

clew/harvest.py:583

Source · 60 lines
def run_harvest(
    conn: sqlite3.Connection,
    repo_root: Path,
    harvester: Harvester,
    cache: IndexCache | None = None,
) -> list[tuple[int, Any]]:
    """Iterate the `path` table in rowid order (so edge insertion order — and
    therefore the INSERT OR IGNORE dedup outcome — is identical whether the
    payloads came from a fresh parse or the cache) and collect each file's
    harvest payload.

    Since gh#358 the payloads are normally already in the cache, put there by
    `run_shared_parse` off ONE parse of each file, so this walk is a sequence of
    sqlite reads. It still parses whatever it cannot find, which is what makes
    the shared pass an optimization rather than a dependency: a stage whose
    harvester the shared pass never saw (or a build with no cache at all) is
    slower and identical.

    The per-stage `cached`/`computed` split is LOGGED, because it is the only
    direct evidence that invalidating one stage recomputed one stage.

    Payloads this stage had to parse for itself are flushed before it returns, so an
    abort in a later stage does not discard them (#505).

    @brief Drive one cacheable per-file stage across the whole index.
    @version 3
    """
    parser_cache: dict = {}
    results: list[tuple[int, Any]] = []
    tally = HarvestTally()
    all_paths = conn.execute("SELECT rowid, name FROM path").fetchall()
    with make_progress(known_total=True) as progress:
        task = progress.add_task(harvester.label, total=len(all_paths))
        for path_rowid, rel_path in all_paths:
            progress.advance(task)
            payload = _harvest_one_file(
                rel_path,
                repo_root / rel_path,
                harvester,
                parser_cache,
                cache,
                tally,
            )
            if payload is not None:
                results.append((path_rowid, payload))
    ## Whatever THIS stage had to parse for itself is banked before the next one starts (#505).
    ## Normally near-free: since the shared pass most payloads are already cached and already
    ## flushed, so this commits nothing. It earns its place on the stages the shared pass does
    ## not cover, and on a build with no shared pass at all (`--no-index-cache` aside).
    if cache is not None:
        cache.flush()
    logger.info(
        "harvest %s: %d payload(s) from cache, %d parsed here",
        harvester.stage,
        tally.cached,
        tally.computed,
    )
    return results

Activity · 15 steps
lines 610–610parser_cache: dict = {}lines 611–611results: list[tuple[int, Any]] = []lines 612–612tally = HarvestTally()lines 613–613all_paths = conn.execute("SELECT rowid, name FROM path").fetchall()lines 614–614with make_progress(known_total=True) as progresslines 615–615task = progress.add_task(harvester.label, total=len(all_paths))lines 616–616◇ for path_rowid, rel_path in all_pathslines 617–617progress.advance(task)lines 618–625payload = _harvest_one_file( rel_path, repo_root / rel_path, harvester, parser_cache, cache, tally, )lines 626–626◇ if payload is not Nonelines 627–627results.append((path_rowid, payload))lines 632–632◇ if cache is not Nonelines 633–633cache.flush()lines 634–639logger.info( "harvest %s: %d payload(s) from cache, %d parsed here", harvester.stage, tally.cached, tally.computed, )lines 640–640return results

Requirements

REQ-DDB-PIPE-003

run_shared_parse

HarvestTally clew.harvest.run_shared_parse(sqlite3.Connection conn, Path repo_root, list[Harvester] harvesters, IndexCache|None cache=None, int jobs=1)

Parse every indexed file ONCE, warming all eleven stages' cache rows.

clew/harvest.py:872

Source · 89 lines
def run_shared_parse(
    conn: sqlite3.Connection,
    repo_root: Path,
    harvesters: list[Harvester],
    cache: IndexCache | None = None,
    jobs: int = 1,
) -> HarvestTally:
    """gh#358. Nothing here EMITS: it only fills the per-stage cache rows the
    stages are about to read, so stage ordering — `ast_symbols` before every
    endpoint-resolving layer, `prune_fabricated_self_edges` inside call_edges,
    callback_edges applying its `PreprocessorConfig` after its own harvest — is
    untouched and stays the stages' business. That is why one pass can serve all
    ten despite an ordering constraint that forbids merging their EMITS:
    `Harvester.harvest(tree, src_bytes)` reads only the file, and payloads are
    rowid-free by contract.

    With no cache (`--no-index-cache`) there is nowhere to put the payloads, so
    this no-ops and every stage parses for itself exactly as it did before —
    slower, identical output.

    Payload rows are flushed every `_FLUSH_EVERY` files and once more at the end, so a
    build killed part-way through keeps what it has already parsed (#505).

    `jobs > 1` RUNS THE PARSE ACROSS PROCESSES and takes a different code path, but the
    serial one is kept rather than reimplemented in terms of the pool: `jobs=1` must stay
    the exact code that has been shipping, so the parallel path can be switched off in one
    flag and the two compared as independent implementations of the same contract. The
    invariance test asserts they produce identical indexes.

    THE PARENT REMAINS THE ONLY CACHE WRITER either way. Workers receive files and return
    payloads; nothing in a worker touches the sidecar. That is what keeps the parallel path
    free of sqlite locking rather than merely careful about it.

    @brief One parse per file, feeding every stage's own cache row.
    @version 3
    """
    if cache is None or not harvesters:
        logger.info("shared ast parse: skipped (no index cache or no per-file stages)")
        return HarvestTally()
    if jobs > 1:
        tally = HarvestTally()
        work, shas = _plan_shared_jobs(conn, repo_root, harvesters, cache, tally)
        if work:
            _shared_parse_pooled(work, shas, harvesters, cache, tally, jobs)
        cache.flush()
        logger.info(
            "shared ast parse: %d file(s) parsed once across %d worker(s) for %d stage "
            "payload(s); %d payload(s) already cached across %d stage(s)",
            tally.parsed,
            jobs,
            tally.computed,
            tally.cached,
            len(harvesters),
        )
        return tally
    parser_cache: dict = {}
    tally = HarvestTally()
    all_paths = conn.execute("SELECT rowid, name FROM path").fetchall()
    with make_progress(known_total=True) as progress:
        task = progress.add_task("shared ast parse", total=len(all_paths))
        for done, (_path_rowid, rel_path) in enumerate(all_paths, start=1):
            progress.advance(task)
            _shared_parse_one_file(
                rel_path,
                repo_root / rel_path,
                harvesters,
                parser_cache,
                cache,
                tally,
            )
            ## FLUSHED PART-WAY THROUGH, not merely at the end, and on a large target that is
            ## the whole value. This pass is the single longest stage there — a kill fifteen
            ## minutes into a twenty-minute parse banked NOTHING when the only flush was after
            ## the loop, which is the shape that made a big corpus unbuildable no matter how
            ## many times it was retried.
            if done % _FLUSH_EVERY == 0 and cache is not None:
                cache.flush()
    ## The tail the periodic flush above did not reach. `flush` persists payload rows only; the
    ## "this tree was indexed" claim stays with `commit`, after the swap.
    cache.flush()
    logger.info(
        "shared ast parse: %d file(s) parsed once for %d stage payload(s); "
        "%d payload(s) already cached across %d stage(s)",
        tally.parsed,
        tally.computed,
        tally.cached,
        len(harvesters),
    )
    return tally

1 more lines, not shown

Activity · 24 steps
lines 908–908◇ if cache is None or not harvesterslines 909–909logger.info("shared ast parse: skipped (no index cache or no per-file stages)")lines 910–910return HarvestTally()lines 911–911◇ if jobs > 1lines 912–912tally = HarvestTally()lines 913–913work, shas = _plan_shared_jobs(conn, repo_root, harvesters, cache, tally)lines 914–914◇ if worklines 915–915_shared_parse_pooled(work, shas, harvesters, cache, tally, jobs)lines 916–916cache.flush()lines 917–925logger.info( "shared ast parse: %d file(s) parsed once across %d worker(s) for %d stage " "payload(s); %d payload(s) already cached across %d stage(s)", tally.parsed, jobs, tally.computed, tally.cached, len(harvesters), )lines 926–926return tallylines 927–927parser_cache: dict = {}lines 928–928tally = HarvestTally()lines 929–929all_paths = conn.execute("SELECT rowid, name FROM path").fetchall()lines 930–930with make_progress(known_total=True) as progresslines 931–931task = progress.add_task("shared ast parse", total=len(all_paths))lines 932–932◇ for done, (_path_rowid, rel_path) in enumerate(all_paths, start=1)lines 933–933progress.advance(task)lines 934–941_shared_parse_one_file( rel_path, repo_root / rel_path, harvesters, parser_cache, cache, tally, )lines 947–947◇ if done % _FLUSH_EVERY == 0 and cache is not Nonelines 948–948cache.flush()lines 951–951cache.flush()lines 952–959logger.info( "shared ast parse: %d file(s) parsed once for %d stage payload(s); " "%d payload(s) already cached across %d stage(s)", tally.parsed, tally.computed, tally.cached, len(harvesters), )lines 960–960return tally

Requirements

REQ-DDB-PIPE-003