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.

clew/propose/scanning.py:259

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
lines 267–267tree, src = parsedlines 268–268◇ for node in walk(tree.root_node)lines 269–269◇ if node.type in DEF_TYPESlines 270–270fdef = definition_record(node, src, rel, scoped)lines 271–271◇ if fdef is not Nonelines 272–272corpus.defs.setdefault(fdef.name, []).append(fdef)lines 273–273◇ elif node.type == "call_expression"lines 274–274site = _accessor_site(node, src, rel, scoped, accessor_split)lines 275–275◇ if site is not Nonelines 276–276corpus.accessor_sites.append(site)

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.

clew/propose/scanning.py:288

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
lines 292–292name = callee_name(node, src)lines 293–293◇ if not name or accessor_split(name) is Nonelines 294–294return Nonelines 295–295args = node.child_by_field_name("arguments")lines 296–296argc = len(args.named_children) if args is not None else 0lines 297–297return AccessorSite(rel, node.start_point[0] + 1, name, argc, scoped)

Flows

_scandir

list[os.DirEntry] clew.propose.scanning._scandir(Path directory)

Directory entries, or an empty list when the directory is unreadable.

clew/propose/scanning.py:179

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
lines 181–181trylines 182–182return sorted(os.scandir(directory), key=lambda e: e.name)lines 183–183except OSErrorlines 184–184return []

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.

clew/propose/scanning.py:158

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
lines 166–171return sum( 1 for path in files if getattr(_ts_language_for(path.name), "__name__", "") in _AST_GRAMMARS and bool(in_scope(path)) )

Requirements

REQ-DDB-CONFIG-001

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.

clew/propose/scanning.py:308

Show on the map →

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
lines 322–322◇ if not watchlines 323–323return []lines 324–324needles = [name.encode("utf-8") for name in watch]lines 325–325parser_cache: dict = {}lines 326–326sites: list[CallSite] = []lines 327–327◇ for path in files[:MAX_CORPUS_FILES]lines 328–328raw = _read_bytes(path)lines 329–329◇ if raw is None or not any(needle in raw for needle in needles)lines 330–330continuelines 331–331rel = relative_to(path, repo_root)lines 332–332parsed = _ast_parse_one_file(rel, path, parser_cache)lines 333–333◇ if parsed is not Nonelines 334–334_collect_watched(sites, parsed, rel, bool(in_scope(path)), watch)lines 335–335return sites

Requirements

REQ-DDB-CONFIG-001

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.

clew/propose/scanning.py:399

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
lines 401–401trylines 402–402return path.relative_to(repo_root).as_posix()lines 403–403except ValueErrorlines 404–404return str(path)

Requirements

REQ-DDB-CONFIG-001

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.

clew/propose/scanning.py:123

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
lines 132–132found: list[Path] = []lines 133–133stack = [repo_root]lines 134–134◇ while stacklines 135–135◇ for entry in _scandir(stack.pop())lines 136–136◇ if entry.is_dir(follow_symlinks=False)lines 137–137◇ if not entry.name.startswith(".") and entry.name not in _PRUNE_DIRSlines 138–138stack.append(Path(entry.path))lines 139–139◇ elif _ts_language_for(entry.name) is not Nonelines 140–140found.append(Path(entry.path))lines 141–141return tuple(sorted(found))

Requirements

REQ-DDB-CONFIG-001

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.

clew/propose/scanning.py:223

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
lines 237–237corpus = Corpus(truncated=len(files) > MAX_CORPUS_FILES)lines 238–238parser_cache: dict = {}lines 239–239◇ for path in files[:MAX_CORPUS_FILES]lines 240–240rel = relative_to(path, repo_root)lines 241–241parsed = _ast_parse_one_file(rel, path, parser_cache)lines 242–242◇ if parsed is Nonelines 243–243continuelines 244–244corpus.files_parsed += 1lines 245–245scoped = bool(in_scope(path))lines 246–246corpus.files_in_scope += 1 if scoped else 0lines 247–247_absorb_file(corpus, parsed, rel, scoped, accessor_split)lines 248–248return corpus

Requirements

REQ-DDB-CONFIG-001

Flows

scope_membership

Any clew.propose.scanning.scope_membership(DerivedScope scope)

Build the "is this path inside the derived index scope?" predicate.

clew/propose/scanning.py:192

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

Activity · 4 steps
lines 199–199roots = [Path(r) for r in scope.roots]lines 200–200excludes = [Path(e) for e in scope.excludes]lines 206–210def 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)lines 212–212return inside

Requirements

REQ-DDB-CONFIG-001

Flows