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.
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
Tested by
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
Flows
_cached_parser
clew.harvest._cached_parser(str mod_name, dict parser_cache)
Memoized substrate parser for one grammar name.
Called by _ast_parse_one_file, _disambiguate_header, _parse, _parse_c
Calls _try_import_ts_module
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
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.
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
Flows
_grammar_available
bool clew.harvest._grammar_available(str modname)
Whether a routed grammar is actually compiled into the installed substrate.
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
Flows
_parse_error_count
int clew.harvest._parse_error_count(root)
Count ERROR/MISSING nodes in a parsed tree.
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
Flows
_parseable_file
bool clew.harvest._parseable_file(Path abs_path)
Whether a file may be parsed: it exists and is not binary.
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
Requirements
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.
Source · 6 lines
def _try_import_ts_module(modname: str):
if modname.startswith(_SUBSTRATE_PREFIX):
return _SubstrateGrammar(modname)
return None
Activity · 3 steps
Flows
_ts_language_for
clew.harvest._ts_language_for(str path)
Select the C, C++, Python or Rust tree-sitter language by extension.
Called by _ast_parse_one_file, _harvest_one_file, _shareable_sha, ast_readable_in_scope, external_callees, repo_source_files
Tested by 9 tests
test_a_doxygen_indexed_cpp_suffix_has_a_grammar, test_a_file_merely_ending_in_the_cmake_name_is_not_cmake, test_a_missing_grammar_routes_to_nothing_instead_of_raising, test_a_shell_script_routes_to_the_bash_grammar, test_an_upper_case_C_suffix_is_cpp, test_the_cmake_file_name_routes_even_though_its_extension_is_txt, test_ts_language_for_recognizes_extensions, test_ts_language_for_routes_python, test_ts_language_for_routes_rust
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
Flows
enclosing
Any clew.harvest.enclosing(Any node, tuple[str,...] types)
Nearest enclosing node of one of the given types.
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
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
Requirements
harvest
Any clew.harvest.Harvester.harvest(self, Any tree, bytes src_bytes)
Extract this stage's rowid-free facts from one parsed file.
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
Requirements
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.
Called by _harvest_all_spawn_sites, _harvest_sites, _harvest_subscribe_sites, _recover_into, _walk_all_files_for_shared_keys, emit_definitions, enrich_python_docstrings, extract_blocking_calls, extract_locks, import_ast_call_edges, import_ast_includes, import_ast_macro_refs
Tested by
Calls _harvest_one_file, make_progress
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