scanning.py¶
clew/propose/scanning.py
The shared tree-sitter walk behind both detectors — corpus, no policy.
_absorb_file
None clew.propose.scanning._absorb_file(Corpus corpus, tuple[Any, bytes] parsed, str rel, bool scoped, Any accessor_split)
Fold one parsed file's definitions and accessor sites into the corpus.
Source · 20 lines
def _absorb_file(
corpus: Corpus,
parsed: tuple[Any, bytes],
rel: str,
scoped: bool,
accessor_split: Any,
) -> None:
"""@brief Record one file's definitions and accessor call sites."""
tree, src = parsed
for node in walk(tree.root_node):
if node.type in DEF_TYPES:
fdef = definition_record(node, src, rel, scoped)
if fdef is not None:
corpus.defs.setdefault(fdef.name, []).append(fdef)
elif node.type == "call_expression":
site = _accessor_site(node, src, rel, scoped, accessor_split)
if site is not None:
corpus.accessor_sites.append(site)
Activity · 10 steps
Flows
_accessor_site
AccessorSite | None clew.propose.scanning._accessor_site(Any node, bytes src, str rel, bool scoped, Any accessor_split)
One accessor-shaped call site, or None when the callee is not one.
Source · 12 lines
def _accessor_site(
node: Any, src: bytes, rel: str, scoped: bool, accessor_split: Any
) -> AccessorSite | None:
"""@brief Record a call site whose callee name is accessor-shaped."""
name = callee_name(node, src)
if not name or accessor_split(name) is None:
return None
args = node.child_by_field_name("arguments")
argc = len(args.named_children) if args is not None else 0
return AccessorSite(rel, node.start_point[0] + 1, name, argc, scoped)
Activity · 6 steps
Flows
_scandir
list[os.DirEntry] clew.propose.scanning._scandir(Path directory)
Directory entries, or an empty list when the directory is unreadable.
Source · 8 lines
def _scandir(directory: Path) -> list[os.DirEntry]:
"""@brief List one directory, tolerating permission errors."""
try:
return sorted(os.scandir(directory), key=lambda e: e.name)
except OSError:
return []
Activity · 4 steps
Flows
ast_readable_in_scope
int clew.propose.scanning.ast_readable_in_scope(tuple[Path,...] files, Any in_scope)
How many in-scope files a grammar the AST detectors understand handles.
Source · 16 lines
def ast_readable_in_scope(files: tuple[Path, ...], in_scope: Any) -> int:
"""Keyed on the grammar module `_ts_language_for` chooses, not on a duplicated
extension list, so widening that router (as the Python layer did) cannot
silently widen what these detectors claim to have measured.
@brief Count the in-scope files the C/C++ detectors can actually read.
@version 1
"""
return sum(
1
for path in files
if getattr(_ts_language_for(path.name), "__name__", "") in _AST_GRAMMARS
and bool(in_scope(path))
)
Activity · 1 steps
Requirements
Flows
census_call_sites
list[CallSite] clew.propose.scanning.census_call_sites(Path repo_root, tuple[Path,...] files, Any in_scope, frozenset[str] watch)
Second pass: every call site of a watched callee, repo-wide.
Called by propose_thread_patterns
Calls _ast_parse_one_file, _collect_watched, _read_bytes, relative_to
Source · 30 lines
def census_call_sites(
repo_root: Path,
files: tuple[Path, ...],
in_scope: Any,
watch: frozenset[str],
) -> list[CallSite]:
"""Byte-prefiltered: a file that does not literally contain a watched name
cannot hold a call to it, so it is never parsed. That turns the second pass
from "parse the tree again" into "parse the handful of files that mention
the candidates".
@brief Collect repo-wide call sites for a small set of callee names.
@version 1
"""
if not watch:
return []
needles = [name.encode("utf-8") for name in watch]
parser_cache: dict = {}
sites: list[CallSite] = []
for path in files[:MAX_CORPUS_FILES]:
raw = _read_bytes(path)
if raw is None or not any(needle in raw for needle in needles):
continue
rel = relative_to(path, repo_root)
parsed = _ast_parse_one_file(rel, path, parser_cache)
if parsed is not None:
_collect_watched(sites, parsed, rel, bool(in_scope(path)), watch)
return sites
Activity · 14 steps
Requirements
relative_to
str clew.propose.scanning.relative_to(Path path, Path repo_root)
Repo-root-relative POSIX path for an absolute path under the root.
Source · 8 lines
def relative_to(path: Path, repo_root: Path) -> str:
"""@brief Key a scanned path the way doxygen's `path` table does."""
try:
return path.relative_to(repo_root).as_posix()
except ValueError:
return str(path)
Activity · 4 steps
Requirements
Flows
repo_source_files
tuple[Path, ...] clew.propose.scanning.repo_source_files(Path repo_root)
Every C/C++ source file under a repo root, in sorted order.
Source · 21 lines
def repo_source_files(repo_root: Path) -> tuple[Path, ...]:
"""Walk the tree once, pruning dot-directories and cache/vendor directories,
and keep only paths `harvest._ts_language_for` recognises — the exact filter
the pipeline's own per-file stages use, so the corpus can never be wider
than what the pipeline could parse.
@brief Enumerate the repo's parseable source files.
@version 1
"""
found: list[Path] = []
stack = [repo_root]
while stack:
for entry in _scandir(stack.pop()):
if entry.is_dir(follow_symlinks=False):
if not entry.name.startswith(".") and entry.name not in _PRUNE_DIRS:
stack.append(Path(entry.path))
elif _ts_language_for(entry.name) is not None:
found.append(Path(entry.path))
return tuple(sorted(found))
Activity · 10 steps
Requirements
Flows
scan_repo
Corpus clew.propose.scanning.scan_repo(Path repo_root, tuple[Path,...] files, Any in_scope, Any accessor_split)
Scan the whole repo tree for definitions and accessor-shaped calls.
Source · 28 lines
def scan_repo(
repo_root: Path,
files: tuple[Path, ...],
in_scope: Any,
accessor_split: Any,
) -> Corpus:
"""One pass over every file collecting the two compact things the detectors
need: definitions with their parameter-forwarding calls, and accessor-shaped
call sites. Both are recorded repo-wide and tagged `in_scope`, per the
two-corpora rule in the module docstring.
@brief Build the repo-wide corpus in a single parse pass.
@version 1
"""
corpus = Corpus(truncated=len(files) > MAX_CORPUS_FILES)
parser_cache: dict = {}
for path in files[:MAX_CORPUS_FILES]:
rel = relative_to(path, repo_root)
parsed = _ast_parse_one_file(rel, path, parser_cache)
if parsed is None:
continue
corpus.files_parsed += 1
scoped = bool(in_scope(path))
corpus.files_in_scope += 1 if scoped else 0
_absorb_file(corpus, parsed, rel, scoped, accessor_split)
return corpus
Activity · 12 steps
Requirements
Flows
scope_membership
Any clew.propose.scanning.scope_membership(DerivedScope scope)
Build the "is this path inside the derived index scope?" predicate.
Source · 23 lines
def scope_membership(scope: DerivedScope) -> Any:
"""The scope's roots are absolute paths (a directory OR a single file — the
guard derivation emits both) and its excludes prune subtrees beneath them.
@brief Make a scope-membership predicate for absolute paths.
@version 1
"""
roots = [Path(r) for r in scope.roots]
excludes = [Path(e) for e in scope.excludes]
## @brief Whether one absolute path lies inside the derived scope.
## @param path Absolute path to test.
## @return True when the path is under a root and under no exclude.
## @version 1
def inside(path: Path) -> bool:
"""@brief Test one path against the derived roots and excludes."""
if any(path == ex or ex in path.parents for ex in excludes):
return False
return any(path == root or root in path.parents for root in roots)
return inside