"""dependency-diagram — renders a source tree's first-party import graph
and top-level symbols as a Mermaid class or block diagram, across every
language dependency-graph and repo-map support (the 139 repo-map
languages as of `L5-T01`'s Batch P parity pass — Odin excepted, its
own stated node gap, deliberately matching the engine's — get a node;
74 also get real, resolved import edges. The "60" this line used to
claim was stale against this skill's own README the whole time — see
those two
skills' own module docstrings for the exact list and per-language shape).
**This is a composition, not a 1:1 module port** (see README.md
"Provenance" for the full honesty note) — there is no single
`packages/engine/src/*` module this mirrors. It's built by directly
reusing the exact, already-verified algorithms behind two other skills in
this same bundle, copied in below rather than imported (each skill in
this bundle ships as an independent, self-contained download — see the
bundle's own README.md "Verification methodology"):
- the import graph is dependency-graph's own `build()`/`DependencyGraph`
(one real resolution family per language shape, `is_recognized_source_
extension`/`RECOGNIZED_EXTENSIONS` for node-vs-edge honesty).
- the top-level symbol extraction is repo-map's own `symbols_for_file`
dispatch (filename-based checks first for the extension-less kinds —
`Dockerfile`/`Makefile`/`BUILD`/`CMakeLists.txt`/`justfile` — then the
keyword-table/dedicated-extractor path for everything else).
**E31-T30, real multi-language port.** Before this batch this skill was
genuinely Rust-only — its own hand-written duplicate of just the Rust
`use`-resolution and `fn`/`struct`/`enum`/`trait` extraction, predating
both sibling skills' own multi-language growth (`E31-T13`..`E31-T29`).
That duplicate is gone; this file now carries the two sibling skills'
*current* engine bodies verbatim. **Correction (`E31-T38`):** the claim
that used to sit here — a `scripts/` generator keeping the vendored
sections in sync automatically — described a script that was never
actually written; no such generator exists anywhere in this repo. The
Batch K/L/M re-vendor was done by hand (and verified by this skill's own
tests plus a node-visibility test for the new languages), and until a
real generator ships, re-vendoring after any sibling change *is* a
manual step to remember — stating that honestly beats pointing at
tooling that doesn't exist, the exact stale-claim shape this same
batch's audit history keeps catching (`E31-T26`/`E31-T37`).
**Resolved (`E31-T41`):** the promised generator now exists for real —
`scripts/revendor.py` regenerates both vendored sections mechanically
from the current sibling bodies (the pragma convention applied by
machine, not by memory) and its `--check` mode fails CI on drift, so
the manual step this correction warned about is gone. The vendored
sections below are generator-written as of `E31-T42`'s Batch N parity
pass (117 → 123), and regenerated for `E31-T44`'s Batch O pass
(123 → 129) — the first re-vendor where "run the generator" was the
entire step, exactly what the resolution above promised. Regenerated
again for `L5-T01`'s Batch P pass (129 → 139), the L track's first
closed ticket.
**Rendering note: no more per-symbol "kind" tag.** The old Rust-only
version tagged each member `+name()` for a function or `+<<struct>> Name`
for a type, because its own duplicated extractor tracked a `kind` per
symbol. `repo_map.symbols_for_file` returns plain name strings across all
139 languages — there is no single "kind" concept that generalizes past
Rust (a Python `def`, a YAML top-level key, and a Markdown heading aren't
the same *shape* of thing) — so members now render as a flat `+name`,
identical to the real engine's own `dependency_diagram` module. This is a
real, deliberate behavior change from before E31-T30, not an oversight.
**Coverage note.** Every ported `def`/`class` below carries its own
`# pragma: no cover` -- not hiding untested code, declaring already-
verified code: the source skill's own test suite (200+ tests each)
exercises every branch of it under its own file identity, and coverage
tooling has no way to know that without being told explicitly. This
file's own test suite (`tests/test_dependency_diagram.py`) covers only
what's genuinely unique to this module -- the composition layer below --
and reports 100% of that.
**Honest scope**: inherits both source skills' own honest-scope notes in
full — see dependency-graph's for exactly which languages get resolved
edges vs. which are walked with none, and repo-map's for exactly which
languages get real symbol extraction vs. which are unrecognized and
skipped (never silently guessed at, always still shown as an unlabeled
node... no — an unrecognized extension is not a node at all here either,
same as both source skills). A Mermaid class diagram is used as a
readable, widely-rendered *notation*; it is not a claim that a given
codebase is object-oriented.
Pure stdlib, no network call.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from collections import deque
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable
SKIPPED_DIR_NAMES = {
".git", "node_modules", "target", "dist", "build", ".venv", "venv",
"__pycache__", ".next", ".cache",
}
RECOGNIZED_EXTENSIONS = frozenset({
"1", "1in", "2", "3", "3in", "4", "5", "6", "7", "7z", "8", "a", "aac", "abap", "adb",
"ado", "adoc", "ads", "agda", "ahk", "anim", "applescript", "arrow", "as", "asax", "asc",
"ascx", "ashx", "asm", "asmdef", "asmref", "aspx", "astro", "atom", "automount", "avdl",
"avi", "avif", "avsc", "awk", "axml", "bal", "bash", "bat", "bib", "bicep", "bin", "blend",
"bmp", "bz2", "bzl", "c", "cabal", "cairo", "capnp", "cbl", "cc", "cfg", "cfm", "cfml",
"cginc", "chpl", "cjs", "ckpt", "class", "clj", "cljc", "cljs", "cls", "cmake", "cmd",
"cob", "cobol", "coffee", "conf", "controller", "cpp", "cpy", "cr", "creole", "cs",
"cshtml", "csproj", "css", "csv", "cu", "cubemap", "cue", "cuh", "cwl", "cxx", "d", "dart",
"deb", "defconfig", "desktop", "dhall", "dll", "dmg", "do", "dox", "doxyfile", "dpr", "dtd",
"dts", "dtsi", "dylib", "ear", "edn", "eex", "ejs", "el", "elf", "elm", "entitlements",
"eot", "erb", "erl", "escn", "ex", "exe", "exr", "exs", "f", "f03", "f08", "f77", "f90",
"f95", "fbs", "fbx", "feather", "feature", "fish", "fits", "flac", "flare", "for", "fpp",
"frag", "fs", "fsproj", "fsx", "fx", "fxh", "gd", "gdshader", "gdshaderinc", "gemspec",
"geojson", "geom", "ggml", "gguf", "gif", "glb", "gleam", "glsl", "gltf", "go", "gpg",
"gql", "gradle", "graphql", "groovy", "guiskin", "gvy", "gz", "h", "h5", "hack",
"handlebars", "har", "hbs", "hcl", "hdf5", "hdr", "heex", "heic", "hh", "hhi", "hlean",
"hlsl", "hlsli", "hpp", "hrl", "hs", "htm", "html", "hx", "icns", "ico", "idr", "import",
"inc", "ini", "ino", "ipynb", "j2", "jar", "java", "jbuilder", "jinja", "jinja2", "jl",
"joblib", "jpeg", "jpg", "jq", "js", "json", "json5", "jsonc", "jsonnet", "jsp", "jspx",
"jsx", "kdl", "keras", "kt", "kts", "lean", "leex", "less", "lib", "libsonnet", "liquid",
"lisp", "lkml", "lockfile", "lsp", "lua", "m", "m4", "m4a", "man", "markdown", "marko",
"master", "mata", "mathematica", "matlab", "mc", "md", "mdown", "mdx", "mediawiki", "metal",
"mjs", "mk", "mkd", "mkdn", "mkv", "ml", "mli", "mm", "mojo", "mount", "mov", "move", "mp3",
"mp4", "msi", "mustache", "nasm", "nb", "nc", "nf", "nim", "nix", "npy", "npz", "nqp",
"nroff", "nsh", "nsi", "nu", "nuspec", "nut", "o", "odin", "ogg", "onnx", "opml", "opus",
"orc", "org", "otf", "overlay", "p6", "parquet", "pas", "path", "pb", "pbxproj", "pck",
"pde", "php", "phtml", "physicsmaterial", "pkl", "pl", "pl6", "plb", "plist", "pls", "pm",
"pm6", "png", "po", "pod", "podspec", "pot", "pp", "pprx", "prefab", "prefs", "prf", "pri",
"pro", "proj", "properties", "props", "proto", "ps1", "psd", "psm1", "pt", "pth", "pug",
"purs", "py", "pyc", "pyo", "qmd", "qml", "qs", "r", "rake", "raku", "rakumod", "rakutest",
"razor", "rb", "rbi", "rdoc", "re", "rei", "rendertexture", "res", "resi", "resx", "rex",
"rexx", "riot", "rkt", "rmd", "rng", "robot", "roff", "ron", "ronn", "rpm", "rs", "rss",
"rst", "ru", "safetensors", "sas", "sass", "sbt", "scad", "scala", "scm", "scope", "scss",
"service", "sh", "sig", "slice", "sln", "slnx", "sls", "smk", "sml", "snap", "so", "socket",
"sol", "spdx", "sql", "ss", "st", "storyboard", "strings", "stringsdict", "styl", "sv",
"svelte", "svg", "svh", "swift", "tag", "tar", "targets", "tcl", "tesc", "tese", "tex",
"texi", "texinfo", "text", "textile", "tf", "tflite", "tfvars", "tgz", "thor", "thrift",
"tif", "tiff", "timer", "tla", "tmac", "toml", "topojson", "tres", "trigger", "troff", "ts",
"tscn", "tsv", "tsx", "ttf", "twig", "txi", "txt", "typ", "uasset", "uid", "umap", "unity",
"unitypackage", "uplugin", "uproject", "v", "vala", "vb", "vbproj", "vbs", "vert", "vh",
"vhd", "vhdl", "vim", "vue", "vy", "vyi", "war", "wasm", "wast", "wat", "wav", "webm",
"webmanifest", "webp", "wgsl", "whl", "wiki", "wikitext", "wl", "wlt", "woff", "woff2",
"wren", "wsdl", "xaml", "xcconfig", "xcscheme", "xcworkspacedata", "xhtml", "xib", "xml",
"xq", "xql", "xqm", "xquery", "xqy", "xsd", "xsl", "xslt", "xul", "xz", "yaml", "yar",
"yara", "yml", "zarr", "zig", "zip", "zsh",
})
ASSET_EXTENSIONS = frozenset({
"7z", "a", "aac", "avi", "avif", "bin", "blend", "bmp", "bz2", "ckpt", "class", "deb",
"dll", "dmg", "dylib", "ear", "elf", "eot", "exe", "exr", "fbx", "flac", "ggml", "gguf",
"gif", "glb", "gz", "h5", "hdf5", "hdr", "heic", "icns", "ico", "jar", "joblib", "jpeg",
"jpg", "keras", "lib", "m4a", "mkv", "mov", "mp3", "mp4", "msi", "npy", "npz", "o", "ogg",
"onnx", "opus", "otf", "pb", "pck", "png", "psd", "pt", "pth", "pyc", "pyo", "rpm",
"safetensors", "so", "tar", "tflite", "tgz", "tif", "tiff", "ttf", "uasset", "umap",
"unitypackage", "war", "wasm", "wav", "webm", "webp", "whl", "woff", "woff2", "xz", "zip",
})
def is_recognized_source_extension(extension: str) -> bool:
"""The engine's `dependency_graph::is_recognized_source_extension`, one
for one (task L11-T04): in the registry, and not an asset.
Assets are registry entries so they can be *counted*, and never graph
nodes so they are never walked. The list and the predicate are separate
in the engine; they are separate here for the same reason.
"""
return extension in RECOGNIZED_EXTENSIONS and extension not in ASSET_EXTENSIONS
_USE_KEYWORD = re.compile(r"\buse\s+")
def _extract_use_bodies(source: str) -> list[str]:
"""Finds every `use <body>;` declaration's `<body>` text via a small
brace-depth scan (handles `use a::{b, c::{d, e}};` nesting) -- see the
module doc for why this isn't a real parser.
"""
bodies: list[str] = []
n = len(source)
for match in _USE_KEYWORD.finditer(source):
start = match.end()
depth = 0
j = start
while j < n:
ch = source[j]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
elif ch == ";" and depth == 0:
break
j += 1
if j < n:
bodies.append(source[start:j].strip())
return bodies
def split_top_level_commas(text: str) -> list[str]:
parts: list[str] = []
depth = 0
current: list[str] = []
for ch in text:
if ch == "{":
depth += 1
current.append(ch)
elif ch == "}":
depth -= 1
current.append(ch)
elif ch == "," and depth == 0:
parts.append("".join(current).strip())
current = []
else:
current.append(ch)
if "".join(current).strip():
parts.append("".join(current).strip())
return parts
def expand_use_tree(text: str) -> list[str]:
"""Recursively expands a `use`-tree body into its full dotted paths,
handling brace groups and stripping `as` aliases and glob imports.
"""
text = text.strip()
brace_start = text.find("::{")
if brace_start != -1:
prefix = text[:brace_start]
if not text.endswith("}"):
return []
inner = text[brace_start + 3 : -1]
out: list[str] = []
for part in split_top_level_commas(inner):
for suffix in expand_use_tree(part):
out.append(f"{prefix}::{suffix}")
return out
if text == "*" or text.endswith("::*"):
return []
without_alias = text.split(" as ")[0].strip()
return [without_alias] if without_alias else []
def use_paths(source: str) -> list[str]:
out: list[str] = []
for body in _extract_use_bodies(source):
out.extend(expand_use_tree(body))
return out
def parent_module(module: str) -> str:
if "::" not in module:
return ""
return module.rsplit("::", 1)[0]
def join(module: str, rest: str) -> str:
return rest if not module else f"{module}::{rest}"
def resolve(used_path: str, own_module: str) -> str | None:
"""Resolves a raw `use`-path segment (already brace-expanded) against
the importing file's own module path -- `crate::`-prefixed and bare
paths resolve from the crate root, `super::`/`self::` resolve
relative to `own_module`. Returns `None` for anything not first-party.
"""
if used_path.startswith("crate::"):
return used_path[len("crate::") :]
if used_path.startswith("self::"):
return join(own_module, used_path[len("self::") :])
if used_path.startswith("super::"):
rest = used_path[len("super::") :]
parent = parent_module(own_module)
while rest.startswith("super::"):
parent = parent_module(parent)
rest = rest[len("super::") :]
return join(parent, rest)
return None
def module_path_map(root: Path, files: list[Path]) -> dict[Path, str]:
"""Maps each `.rs` file to its crate-relative module path (`""` for
the crate root file itself), by directory position.
"""
mapping: dict[Path, str] = {}
for file in files:
try:
relative = file.relative_to(root)
except ValueError:
continue
segments = list(relative.parts)
if segments:
segments[-1] = segments[-1][:-3] if segments[-1].endswith(".rs") else segments[-1]
if segments and segments[-1] in ("mod", "lib"):
segments.pop()
mapping[file] = "::".join(segments)
return mapping
def longest_prefix_match(used_path: str, module_paths: dict[Path, str]) -> Path | None:
"""Finds the file whose module path is the longest prefix of
`used_path` (so `hooks::verbosity_guard::rewrite` matches the file at
module path `hooks::verbosity_guard`, not just an exact-length match).
"""
segments = used_path.split("::")
by_path = {path: file for file, path in module_paths.items()}
for take in range(len(segments), 0, -1):
candidate = "::".join(segments[:take])
if candidate in by_path:
return by_path[candidate]
return None
@dataclass(frozen=True)
class QuotedFamily:
keywords: tuple[str, ...]
filter: Callable[[str], bool]
allow_bareword: bool
resolve_extensions: tuple[str, ...]
def starts_with_dot(specifier: str) -> bool:
return specifier.startswith(".")
def has_no_uri_scheme(specifier: str) -> bool:
return ":" not in specifier
def always_resolvable(_specifier: str) -> bool:
return True
def ends_in_module_file(specifier: str) -> bool:
return specifier.startswith(".") or specifier.lower().endswith(".php")
def ends_in_perl_module(specifier: str) -> bool:
return specifier.startswith(".") or specifier.lower().endswith(".pm")
def looks_like_a_path(specifier: str) -> bool:
return specifier.startswith(".") or "/" in specifier or "\\" in specifier
def has_no_shell_variable_expansion(specifier: str) -> bool:
"""Shell's `source ./foo.sh`/`. foo.sh` almost always name a literal
sibling file, but just as commonly interpolate a shell variable
(`source "$HOME/.bashrc"`) -- unresolvable without running the
script, so filtered out, the same "don't guess" principle as
Python's dot-less absolute imports.
"""
return "$" not in specifier
def has_no_cmake_variable_expansion(specifier: str) -> bool:
"""CMake's own `${VAR}` variable-interpolation convention
(`include("${CMAKE_CURRENT_LIST_DIR}/cmake/Utils.cmake")`) is
unresolvable here for the identical reason a shell `$VAR` expansion is
-- same shape as `has_no_shell_variable_expansion`, kept as its own
function since a shell-named filter guarding a CMake arm would read
as shell-specific machinery it isn't (E31-T25).
"""
return "$" not in specifier
def is_makefile_include_sibling(specifier: str) -> bool:
"""GNU Make's `include`/`-include`/`sinclude` resolve a non-absolute
target against `make`'s own current working directory, *not* the
including Makefile's own directory the way CMake's `include()` does.
For a single-directory project the two coincide, but a target naming
a subdirectory (`include config/common.mk`) could genuinely resolve
differently depending on where `make` was actually invoked from --
something this static analysis has no way to know. Rather than
guess, this accepts only a bareword same-directory sibling: no `$`
(variable expansion, unresolvable), no `/`/`\\` (a subdirectory
reference, the ambiguous case above), and no `*`/`?` (GNU Make's own
wildcard-expansion syntax, which names a set of files, not one) --
the identical "partial over wrong" call already made for Prolog's
`.pro` extension choice (E31-T25).
"""
return not any(c in specifier for c in ("$", "/", "\\", "*", "?"))
def ends_in_zig_module(specifier: str) -> bool:
"""Zig's `@import(...)` names either a real sibling `.zig` file or one
of the compiler's own virtual modules (`"std"`, `"builtin"`, `"root"`,
a `build.zig`-declared package name) -- none of those are files this
tree can resolve, so the only real signal is whether the string
itself looks like a file: a leading `.`/`..` or a literal `.zig`
suffix, the same two shapes `ends_in_module_file`/`ends_in_perl_module`
already check for PHP/Perl.
"""
return specifier.startswith(".") or specifier.lower().endswith(".zig")
def ends_in_racket_module(specifier: str) -> bool:
"""Racket's `(require "...")` quoted-string form always names a real
file (the far more common unquoted form, `(require racket/base)`,
names a collection path instead and is filtered out for free by
`allow_bareword=False` -- it's never even extracted). Same shape as
`ends_in_zig_module`, just for `.rkt`.
"""
return specifier.startswith(".") or specifier.lower().endswith(".rkt")
def vue_script_blocks(source: str) -> str:
"""Extracts and concatenates every `<script ...>...</script>` block's
inner text from a Vue single-file component -- the only part of a
`.vue` file with real import statements (`<template>`/`<style>`
never do). Returns an empty string if no script block is present.
Reused as-is for Svelte (batch A, E31-T19): a `.svelte` component uses
the identical `<script>` HTML-tag convention Vue does, and this
extraction was never actually Vue-specific.
"""
out: list[str] = []
rest = source
while True:
open_start = rest.find("<script")
if open_start == -1:
break
after_open = rest[open_start:]
tag_end = after_open.find(">")
if tag_end == -1:
break
body_start = tag_end + 1
close_idx = after_open.find("</script>", body_start)
if close_idx == -1:
break
out.append(after_open[body_start:close_idx])
out.append("\n")
rest = after_open[close_idx + len("</script>") :]
return "".join(out)
def astro_frontmatter_block(source: str) -> str:
"""Extracts an Astro component's frontmatter block -- the real,
TypeScript-capable code between the file's opening `---` fence and
its closing `---` fence, each on its own line at column 0. Returns an
empty string if there's no frontmatter, or an opening fence with no
matching close.
"""
lines = source.splitlines(keepends=True)
if not lines or lines[0].rstrip("\r\n") != "---":
return ""
offset = len(lines[0])
body_start = offset
for line in lines[1:]:
if line.rstrip("\r\n") == "---":
return source[body_start:offset]
offset += len(line)
return ""
_JS_TS_EXTENSIONS = ("ts", "tsx", "js", "jsx", "mjs", "cjs")
QUOTED_FAMILIES: dict[str, QuotedFamily] = {
**{
ext: QuotedFamily(("from ", "import ", "require("), starts_with_dot, False, _JS_TS_EXTENSIONS)
for ext in ("js", "jsx", "mjs", "cjs", "ts", "tsx")
},
"vue": QuotedFamily(("from ", "import ", "require("), starts_with_dot, False, ("vue", "ts", "tsx", "js", "jsx")),
"astro": QuotedFamily(("from ", "import "), starts_with_dot, False, ("astro", "ts", "tsx", "js", "jsx")),
"dart": QuotedFamily(("import ",), has_no_uri_scheme, False, ("dart",)),
"rb": QuotedFamily(("require_relative ",), always_resolvable, False, ("rb",)),
"cr": QuotedFamily(("require ",), starts_with_dot, False, ("cr",)),
"php": QuotedFamily(
("require_once ", "require ", "include_once ", "include "), ends_in_module_file, False, ("php",)
),
**{
ext: QuotedFamily(
("#include ",), always_resolvable, False, ("h", "hpp", "hh", "c", "cpp", "cu", "cuh")
)
for ext in ("c", "h", "cpp", "cc", "cxx", "hpp", "hh", "cu", "cuh")
},
"m": QuotedFamily(("#import ", "#include "), always_resolvable, False, ("h",)),
"mm": QuotedFamily(("#import ", "#include "), always_resolvable, False, ("h",)),
"pl": QuotedFamily(("require ",), ends_in_perl_module, False, ("pm", "pl")),
"pm": QuotedFamily(("require ",), ends_in_perl_module, False, ("pm", "pl")),
"ps1": QuotedFamily((". ", "Import-Module "), looks_like_a_path, True, ("ps1", "psm1")),
"psm1": QuotedFamily((". ", "Import-Module "), looks_like_a_path, True, ("ps1", "psm1")),
"nim": QuotedFamily(("import ",), always_resolvable, True, ("nim",)),
"sh": QuotedFamily(("source ", ". "), has_no_shell_variable_expansion, True, ("sh", "bash", "zsh")),
"bash": QuotedFamily(("source ", ". "), has_no_shell_variable_expansion, True, ("sh", "bash", "zsh")),
"zsh": QuotedFamily(("source ", ". "), has_no_shell_variable_expansion, True, ("sh", "bash", "zsh")),
"fish": QuotedFamily(("source ",), has_no_shell_variable_expansion, True, ("fish",)),
"tcl": QuotedFamily(("source ",), has_no_shell_variable_expansion, True, ("tcl",)),
"svelte": QuotedFamily(
("from ", "import "), starts_with_dot, False, ("svelte", "ts", "tsx", "js", "jsx")
),
"r": QuotedFamily(("source(",), has_no_uri_scheme, False, ("R", "r")),
"jl": QuotedFamily(("include(",), always_resolvable, False, ("jl",)),
"zig": QuotedFamily(("@import(",), ends_in_zig_module, False, ("zig",)),
"sol": QuotedFamily(("from ", "import "), starts_with_dot, False, ("sol",)),
"erl": QuotedFamily(("-include(",), always_resolvable, False, ("hrl", "erl")),
"rkt": QuotedFamily(("require ",), ends_in_racket_module, False, ("rkt",)),
"awk": QuotedFamily(("@include ",), always_resolvable, False, ("awk",)),
"cmake": QuotedFamily(("include(",), has_no_cmake_variable_expansion, True, ("cmake",)),
"pro": QuotedFamily(
("use_module(", "consult(", "ensure_loaded("), always_resolvable, True, ("pro",)
),
"mk": QuotedFamily(("include ",), is_makefile_include_sibling, True, ()),
"tex": QuotedFamily(("\\input{", "\\include{"), always_resolvable, True, ("tex",)),
"lisp": QuotedFamily(("(load ",), always_resolvable, False, ("lisp", "lsp")),
"lsp": QuotedFamily(("(load ",), always_resolvable, False, ("lisp", "lsp")),
**{
ext: QuotedFamily(("`include ",), always_resolvable, False, ("vh", "v", "svh", "sv"))
for ext in ("v", "sv", "svh")
},
"jsonnet": QuotedFamily(("import ",), always_resolvable, False, ()),
"libsonnet": QuotedFamily(("import ",), always_resolvable, False, ()),
"coffee": QuotedFamily(("from ", "require "), starts_with_dot, False, ("coffee",)),
"less": QuotedFamily(("@import ",), always_resolvable, False, ("less",)),
"css": QuotedFamily(("@import ",), always_resolvable, False, ("css",)),
**{
ext: QuotedFamily(("extends ", "include "), always_resolvable, False, ("jinja", "jinja2", "j2"))
for ext in ("jinja", "jinja2", "j2")
},
"twig": QuotedFamily(("extends ", "include "), always_resolvable, False, ("twig",)),
"wren": QuotedFamily(("import ",), always_resolvable, False, ("wren",)),
"vim": QuotedFamily(("source ",), has_no_shell_variable_expansion, True, ("vim",)),
**{
ext: QuotedFamily(("%include ", ".include "), always_resolvable, False, ("inc", "asm", "nasm"))
for ext in ("asm", "nasm", "inc")
},
"pug": QuotedFamily(("include ",), always_resolvable, True, ("pug",)),
}
def extract_path_token(rest: str, allow_bareword: bool) -> str | None:
"""Extracts a quoted (single or double) string at the start of
`rest`. Falls back to a whitespace-delimited bareword token only when
`allow_bareword` is set. The bareword scan also stops at `}` (E31-T27,
added for LaTeX's `\\input{path}`/`\\include{path}` -- a curly-brace-
delimited argument, the same "real closing delimiter this family
hasn't needed yet" addition `)` already was for CMake/Prolog/
Makefile's parenthesized call syntax) -- safe for every existing
bareword-tolerant language too, since none of their own real path
specifiers ever legitimately contain a literal `}`.
"""
trimmed = rest.lstrip()
if trimmed.startswith('"'):
after = trimmed[1:]
end = after.find('"')
token = after if end == -1 else after[:end]
return token or None
if trimmed.startswith("'"):
after = trimmed[1:]
end = after.find("'")
token = after if end == -1 else after[:end]
return token or None
if not allow_bareword:
return None
token_chars: list[str] = []
for ch in trimmed:
if ch.isspace() or ch in ";)}":
break
token_chars.append(ch)
token = "".join(token_chars)
return token or None
def extract_quoted_imports(source: str, family: QuotedFamily) -> list[str]:
out: list[str] = []
for line in source.splitlines():
for keyword in family.keywords:
idx = line.find(keyword)
if idx == -1:
continue
rest = line[idx + len(keyword) :]
specifier = extract_path_token(rest, family.allow_bareword)
if specifier is not None and family.filter(specifier):
out.append(specifier)
break
return out
def _with_extension_appended(path: Path, ext: str) -> Path:
return Path(str(path) + "." + ext)
def resolve_relative_specifier(
base_dir: Path, specifier: str, resolve_extensions: tuple[str, ...], canonical_lookup: dict[Path, Path]
) -> Path | None:
normalized = specifier.replace("\\", "/")
joined = base_dir / normalized
candidates = [joined]
candidates.extend(_with_extension_appended(joined, ext) for ext in resolve_extensions)
candidates.extend(joined / f"index.{ext}" for ext in resolve_extensions)
return _lookup_candidates(candidates, canonical_lookup)
def _lookup_candidates(candidates: list[Path], canonical_lookup: dict[Path, Path]) -> Path | None:
for candidate in candidates:
try:
canon = candidate.resolve()
except OSError:
continue
original = canonical_lookup.get(canon)
if original is not None:
return original
return None
@dataclass
class PythonRelativeImport:
dots: int
module_path: str
def python_relative_imports(source: str) -> list[PythonRelativeImport]:
out: list[PythonRelativeImport] = []
for line in source.splitlines():
trimmed = line.lstrip()
if not trimmed.startswith("from "):
continue
after_from = trimmed[len("from ") :]
dots = len(after_from) - len(after_from.lstrip("."))
if dots == 0:
continue
after_dots = after_from[dots:]
module_chars: list[str] = []
for ch in after_dots:
if ch.isalnum() or ch in "_.":
module_chars.append(ch)
else:
break
module_path = "".join(module_chars)
rest = after_dots[len(module_path) :].lstrip()
if not rest.startswith("import "):
continue
out.append(PythonRelativeImport(dots=dots, module_path=module_path))
return out
def resolve_python_relative(
file: Path, imp: PythonRelativeImport, canonical_lookup: dict[Path, Path]
) -> list[Path]:
base = file.parent
for _ in range(imp.dots - 1):
base = base.parent
if imp.module_path:
target_stub = base.joinpath(*imp.module_path.split("."))
candidates = [_with_extension_appended(target_stub, "py"), target_stub / "__init__.py"]
else:
candidates = [base / "__init__.py"]
found = _lookup_candidates(candidates, canonical_lookup)
return [found] if found else []
def find_go_module_prefix(root: Path) -> str | None:
"""Searches `root` then its ancestors for a `go.mod`, returning its
`module` directive's value -- `None` if none is found anywhere.
"""
for directory in (root, *root.parents):
go_mod = directory / "go.mod"
if go_mod.is_file():
try:
text = go_mod.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return None
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("module "):
return stripped[len("module ") :].strip()
return None
return None
def go_import_paths(source: str) -> list[str]:
out: list[str] = []
lines = source.splitlines()
i = 0
while i < len(lines):
stripped = lines[i].strip()
if stripped.startswith("import ("):
i += 1
while i < len(lines) and lines[i].strip() != ")":
token = extract_path_token(lines[i].strip(), False)
if token is not None:
out.append(token)
i += 1
elif stripped.startswith("import "):
token = extract_path_token(stripped[len("import ") :], False)
if token is not None:
out.append(token)
i += 1
return out
def resolve_go_import(import_path: str, go_prefix: str | None, root: Path, files: list[Path]) -> list[Path]:
if go_prefix is None or not import_path.startswith(go_prefix):
return []
remainder = import_path[len(go_prefix) :].lstrip("/")
target_dir = root / remainder if remainder else root
return [f for f in files if f.suffix == ".go" and f.parent == target_dir]
def jvm_package_of(source: str) -> str | None:
for line in source.splitlines():
stripped = line.strip()
if stripped.startswith("package "):
return stripped[len("package ") :].rstrip(";").strip()
return None
def jvm_import_targets(source: str) -> list[str]:
out: list[str] = []
for line in source.splitlines():
stripped = line.strip()
if stripped.startswith("import static "):
continue
if stripped.startswith("import "):
dotted = stripped[len("import ") :].rstrip(";").strip()
if not dotted.endswith(".*"):
out.append(dotted)
return out
def resolve_jvm_import(dotted: str, package_of: dict[Path, str]) -> list[Path]:
if "." not in dotted:
return []
package, _, stem = dotted.rpartition(".")
return [f for f, pkg in package_of.items() if pkg == package and f.stem == stem]
def declared_name_of(source: str, extension: str) -> str | None:
if extension == "cs":
keywords = ("namespace ",)
elif extension == "vb":
keywords = ("Namespace ",)
elif extension in ("f90", "f95", "f03", "f08"):
keywords = ("module ", "MODULE ")
elif extension in ("pas", "pp", "dpr"):
keywords = ("unit ",)
else:
keywords = ("module ",)
for line in source.splitlines():
stripped = line.strip()
for keyword in keywords:
if not stripped.startswith(keyword):
continue
rest = stripped[len(keyword) :]
name_chars: list[str] = []
for ch in rest:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
name = "".join(name_chars)
if name:
return name
return None
def declared_import_names(source: str, extension: str) -> list[str]:
out: list[str] = []
for line in source.splitlines():
stripped = line.strip()
if extension == "cs":
if stripped.startswith("using static ") or not stripped.startswith("using "):
continue
name = stripped[len("using ") :].rstrip(";").strip()
if "=" in name:
continue
out.append(name)
elif extension in ("hs", "purs", "idr", "elm"):
if not stripped.startswith("import "):
continue
rest = stripped[len("import ") :]
rest = rest[len("qualified ") :] if rest.startswith("qualified ") else rest
name_chars: list[str] = []
for ch in rest:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
elif extension == "agda":
rest = stripped[len("open ") :] if stripped.startswith("open ") else stripped
if not rest.startswith("import "):
continue
rest = rest[len("import ") :]
name_chars = []
for ch in rest:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
elif extension == "fs" or extension == "fsx":
if not stripped.startswith("open "):
continue
rest = stripped[len("open ") :]
name_chars = []
for ch in rest:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
elif extension == "vb":
if not stripped.startswith("Imports "):
continue
rest = stripped[len("Imports ") :].rstrip(";").strip()
name_source = rest.split("=", 1)[1].strip() if "=" in rest else rest
name_chars = []
for ch in name_source:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
elif extension in ("f90", "f95", "f03", "f08"):
if stripped.startswith("use "):
rest = stripped[len("use ") :]
elif stripped.startswith("USE "):
rest = stripped[len("USE ") :]
else:
continue
name_chars = []
for ch in rest:
if ch.isalnum() or ch == "_":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
if extension in ("pas", "pp", "dpr"):
out.extend(pascal_uses_targets(source))
return out
def pascal_uses_targets(source: str) -> list[str]:
"""A Pascal/Delphi `uses UnitA, UnitB in 'UnitB.pas', UnitC;` clause --
real, idiomatic Pascal also commonly wraps this across several lines
with no `uses` keyword repeated on the continuation lines, unlike
every other language in this family, so this tracks an `in_uses` flag
across lines rather than assuming one line holds the whole clause. A
real `in '<path>'` clause naming the unit's own file explicitly is
stripped before the name scan -- only the unit name itself is a
declared-qualified-name this family can resolve.
"""
out: list[str] = []
in_uses = False
for line in source.splitlines():
stripped = line.strip()
if in_uses:
rest = stripped
elif stripped.startswith("uses "):
rest = stripped[len("uses ") :]
in_uses = True
elif stripped.startswith("Uses "):
rest = stripped[len("Uses ") :]
in_uses = True
elif stripped in ("uses", "Uses"):
in_uses = True
continue
else:
continue
ends_clause = ";" in rest
clause = rest.split(";", 1)[0]
for segment in clause.split(","):
unit = segment.split(" in ", 1)[0].strip()
name_chars: list[str] = []
for ch in unit:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
if ends_clause:
in_uses = False
return out
def resolve_declared_name(name: str, declared_names_of: dict[Path, str]) -> list[Path]:
return [f for f, declared in declared_names_of.items() if declared == name]
def camel_to_snake(segment: str) -> str:
out: list[str] = []
for i, ch in enumerate(segment):
if ch.isupper() and i > 0:
out.append("_")
out.append(ch.lower())
return "".join(out)
def lua_require_paths(source: str) -> list[str]:
out: list[str] = []
for line in source.splitlines():
idx = line.find("require(")
if idx == -1:
continue
token = extract_path_token(line[idx + len("require(") :], False)
if token is not None:
out.append(token)
return out
def elixir_module_refs(source: str) -> list[str]:
out: list[str] = []
for line in source.splitlines():
stripped = line.strip()
for keyword in ("alias ", "import ", "require "):
if stripped.startswith(keyword):
rest = stripped[len(keyword) :]
name_chars: list[str] = []
for ch in rest:
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars and name_chars[0].isupper():
out.append("".join(name_chars))
break
return out
def d_import_targets(source: str) -> list[str]:
"""D's `import pack.module;` (and its comma-separated multi-import
form, `import pack.a, pack.b;`, and selective form, `import
pack.module : Symbol;`). D has exactly one import keyword, unlike
Elixir's `alias/import/require`, so this only needs to find it and
split on commas -- the selective-import colon and anything after it
are stripped first, since it qualifies the whole statement's last
module, not a separate module of its own.
"""
out: list[str] = []
for line in source.splitlines():
stripped = line.strip()
if not stripped.startswith("import "):
continue
rest = stripped[len("import ") :]
rest = rest.split(":", 1)[0]
rest = rest.rstrip(";").rstrip()
for module in rest.split(","):
name_chars: list[str] = []
for ch in module.strip():
if ch.isalnum() or ch in "_.":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
return out
def dotted_to_relative_path(dotted: str, snake_case_segments: bool) -> str:
segments = dotted.split(".")
if snake_case_segments:
segments = [camel_to_snake(s) for s in segments]
return "/".join(segments)
def resolve_dotted_best_effort(
relative: str, root: Path, extensions: tuple[str, ...], canonical_lookup: dict[Path, Path]
) -> Path | None:
direct_candidates = [_with_extension_appended(root / relative, ext) for ext in extensions]
found = _lookup_candidates(direct_candidates, canonical_lookup)
if found is not None:
return found
suffixes = tuple(f"{relative}.{ext}" for ext in extensions)
matches = [f for f in canonical_lookup.values() if str(f).replace("\\", "/").endswith(suffixes)]
unique = list(dict.fromkeys(matches))
return unique[0] if len(unique) == 1 else None
def clojure_ns_requires(source: str) -> list[str]:
"""Every namespace named by a `:require` clause in `source` -- a bare
symbol (`my.app.bare`) or the far more common `[namespace ...]` vector
form, whose own first token is the namespace (the `:as`/`:refer`
clause after it, and any nested `:refer [...]` symbol list, are never
captured).
"""
start = source.find(":require")
if start == -1:
return []
rest = source[start + len(":require") :]
out: list[str] = []
depth = 1
ready = True
i = 0
while i < len(rest):
ch = rest[i]
if ch == "(":
depth += 1
ready = False
elif ch == "[":
depth += 1
ready = depth == 2
elif ch in ")]":
depth -= 1
if depth <= 0:
break
ready = depth == 1
elif ch.isspace():
pass
elif ch == ":":
ready = False
elif ready and depth in (1, 2):
token_chars = [ch]
i += 1
while i < len(rest) and not rest[i].isspace() and rest[i] not in "()[]":
token_chars.append(rest[i])
i += 1
out.append("".join(token_chars))
ready = False
continue
else:
ready = False
i += 1
return out
def clojure_ns_to_relative_path(ns: str) -> str:
"""Clojure's own real namespace-to-file convention: dots become path
separators (like every other dotted-path family member), but a
namespace segment's hyphens become underscores in the filename --
`my-app.core` resolves to `my_app/core.clj`, not `my-app/core.clj` --
a real, different convention from Lua/Elixir/D, so it gets its own
conversion rather than a third mode threaded through
`dotted_to_relative_path`.
"""
return "/".join(segment.replace("-", "_") for segment in ns.split("."))
_ADA_WITH_PREFIXES = ("limited private with ", "private with ", "limited with ", "with ")
def ada_with_targets(source: str) -> list[str]:
"""Every package named by a `with X.Y;` clause in `source` --
comma-separated multi-package form (`with Ada.Text_IO, Ada.Strings;`)
is real Ada syntax, split the same way D's own `import a, b;` already
is. `limited with`/`private with` (visibility variants of the
identical clause) are stripped to the same plain form first.
"""
out: list[str] = []
for line in source.splitlines():
stripped = line.strip()
rest = None
for prefix in _ADA_WITH_PREFIXES:
if stripped.startswith(prefix):
rest = stripped[len(prefix) :]
break
if rest is None or ";" not in rest:
continue
names_part = rest.split(";", 1)[0]
for name in names_part.split(","):
name = name.strip()
if name and name[0].isalpha():
out.append(name)
return out
def ada_dotted_to_filename_stem(dotted: str) -> str:
"""GNAT's own real default file-naming convention for a `with`ed
package: lowercase, every "." between a dotted package name's own
segments becomes "-".
"""
return dotted.lower().replace(".", "-")
def godot_project_root(root: Path) -> Path | None:
"""Finds the nearest ancestor directory (`root` itself, its parent, or
its grandparent -- the identical search depth every other
project-anchor family here already uses) containing a `project.godot`
file.
"""
candidates = [root]
if root.parent != root:
candidates.append(root.parent)
if root.parent.parent != root.parent:
candidates.append(root.parent.parent)
for directory in candidates:
if (directory / "project.godot").is_file():
return directory
return None
def gdscript_targets(source: str) -> list[str]:
"""Every `.gd`-resolvable path referenced by
`preload(...)`/`load(...)`/`extends "..."` in `source`. `preload`/
`load` also load non-script resources (`.tscn`, `.tres`, `.png`,
...) -- real GDScript, but not a first-party *code* dependency this
graph tracks, so [`ends_in_gd_module`] filters to `.gd` targets only.
"""
out: list[str] = []
for line in source.splitlines():
for keyword in ("preload(", "load(", "extends "):
idx = line.find(keyword)
if idx == -1:
continue
token = extract_path_token(line[idx + len(keyword) :], False)
if token is not None and ends_in_gd_module(token):
out.append(token)
break
return out
def ends_in_gd_module(specifier: str) -> bool:
return Path(specifier).suffix.lower() == ".gd"
def resolve_gdscript_target(
specifier: str, base_dir: Path, project_root: Path | None, canonical_lookup: dict[Path, Path]
) -> Path | None:
normalized = specifier.replace("\\", "/")
if normalized.startswith("res://"):
if project_root is None:
return None
return _lookup_candidates([project_root / normalized[len("res://") :]], canonical_lookup)
return _lookup_candidates([base_dir / normalized], canonical_lookup)
def ocaml_opens(source: str) -> list[str]:
"""Every top-level module name referenced by a real `open ModuleName`
in `source`, filtered to genuinely capitalized names (a lowercase
identifier after `open ` would not be a real module reference at
all). Only the first dotted segment is kept for a qualified `open
Foo.Bar` (a nested submodule access, not a second file to resolve).
"""
out: list[str] = []
for line in source.splitlines():
trimmed = line.lstrip()
if not trimmed.startswith("open "):
continue
rest = trimmed[len("open ") :]
name = ""
for ch in rest:
if ch.isalnum() or ch in "_.":
name += ch
else:
break
first_segment = name.split(".")[0] if name else ""
if first_segment and first_segment[0].isupper():
out.append(first_segment)
return out
def ocaml_module_name_to_stem(module_name: str) -> str:
"""OCaml/ReScript's own real module-name-to-filename convention: the
module name is simply the filename stem, capitalized -- resolving
backwards just lowercases it.
"""
return module_name.lower()
def terraform_module_sources(source: str) -> list[str]:
"""Every local (`./`/`../`-prefixed) `source = "..."` value in
`source` -- reuses `extract_quoted_imports`'s own keyword-scan
machinery with an ad-hoc `QuotedFamily` rather than a `QUOTED_
FAMILIES` entry, since the *extraction* shape fits perfectly but the
*resolution* shape (a directory, not a single file) does not.
"""
return extract_quoted_imports(
source, QuotedFamily(("source = ", "source="), starts_with_dot, False, ())
)
def resolve_terraform_module_targets(base_dir: Path, specifier: str, files: list[Path]) -> list[Path]:
"""Resolves a local module `source` specifier to every `.tf` file in
the target directory -- canonicalizes both sides first (unlike Go's
own import paths, a real Terraform `source` commonly contains `../`
segments, which a plain path join never collapses).
"""
target_dir = base_dir / specifier.replace("\\", "/")
try:
canonical_target = target_dir.resolve(strict=True)
except OSError:
return []
out: list[Path] = []
for f in files:
if f.suffix != ".tf":
continue
try:
if f.parent.resolve(strict=True) == canonical_target:
out.append(f)
except OSError:
continue
return out
def scss_import_specifiers(source: str) -> list[str]:
"""Every quoted `@use "..."`/`@import "..."` specifier in `source` --
reuses `extract_quoted_imports`'s own keyword-scan machinery with an
ad-hoc `QuotedFamily`, the identical "extraction shape fits,
resolution shape doesn't" reason `terraform_module_sources` already
does the same thing.
"""
return extract_quoted_imports(source, QuotedFamily(("@use ", "@import "), always_resolvable, False, ()))
def resolve_scss_import(specifier: str, base_dir: Path, canonical_lookup: dict[Path, Path]) -> Path | None:
"""Tries the specifier as-is, then with `.scss`/`.sass` appended (the
plain-filename case), then the identical two attempts again with an
underscore prepended to the file's own basename (the partial-filename
case) -- first match wins, mirroring the priority a real Sass
compiler itself uses.
"""
joined = base_dir / specifier.replace("\\", "/")
candidates = [joined]
for ext in ("scss", "sass"):
candidates.append(_with_extension_appended(joined, ext))
partial = joined.with_name(f"_{joined.name}")
candidates.append(partial)
for ext in ("scss", "sass"):
candidates.append(_with_extension_appended(partial, ext))
return _lookup_candidates(candidates, canonical_lookup)
_BAZEL_WORKSPACE_MARKERS = ("WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel")
_BAZEL_BUILD_NAMES = ("BUILD", "BUILD.bazel", "WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel")
def is_bazel_build_filename(filename: str) -> bool:
return filename in _BAZEL_BUILD_NAMES
_CMAKE_LIST_NAME = "CMakeLists.txt"
def is_cmake_list_name(filename: str) -> bool:
return filename == _CMAKE_LIST_NAME
_MAKEFILE_NAMES = ("Makefile", "makefile", "GNUmakefile")
def is_makefile_name(filename: str) -> bool:
return filename in _MAKEFILE_NAMES
def bazel_workspace_root(root: Path) -> Path | None:
"""Finds the nearest ancestor directory (`root` itself, its parent, or
its grandparent -- the identical search depth `find_go_module_prefix`
already uses for `go.mod`) containing a `WORKSPACE`, `WORKSPACE.bazel`,
or `MODULE.bazel` file -- the anchor a `//`-prefixed absolute Bazel
label resolves against. A lone `BUILD`/`BUILD.bazel` doesn't anchor a
workspace on its own (every package has one; only the repo's actual
root does), so it's deliberately not checked here.
"""
candidates = [root]
if root.parent != root:
candidates.append(root.parent)
if root.parent.parent != root.parent:
candidates.append(root.parent.parent)
for directory in candidates:
for marker in _BAZEL_WORKSPACE_MARKERS:
if (directory / marker).is_file():
return directory
return None
def bazel_load_labels(source: str) -> list[str]:
"""Every label named by a `load(...)` call's first argument -- e.g.
`load("//tools/build:defs.bzl", "my_macro")` yields
`"//tools/build:defs.bzl"`. A real, stated scope limit: the label
must share a line with `load(` itself (true of the overwhelming
majority of real Bazel code) -- a label on its own following line is
not found.
"""
out: list[str] = []
for line in source.splitlines():
idx = line.find("load(")
if idx == -1:
continue
token = extract_path_token(line[idx + len("load(") :], False)
if token is not None:
out.append(token)
return out
def resolve_bazel_label(
label: str, file: Path, workspace_root: Path | None, canonical_lookup: dict[Path, Path]
) -> Path | None:
"""Resolves one Bazel label from `bazel_load_labels` to a file.
`@repo//...`-prefixed external-repository references are never
first-party and never resolved. `//pkg/path:file.bzl` resolves
against `workspace_root` (`None` if no workspace marker was found --
left unresolved rather than guessed). `:file.bzl` resolves relative
to `file`'s own directory -- Bazel's own "same package" convention.
"""
if label.startswith("@"):
return None
if label.startswith("//"):
if workspace_root is None:
return None
rest = label[2:]
if ":" not in rest:
return None
package_path, _, target = rest.partition(":")
if not target:
return None
candidate = workspace_root / package_path / target if package_path else workspace_root / target
elif label.startswith(":"):
target = label[1:]
if not target:
return None
candidate = file.parent / target
else:
return None
return _lookup_candidates([candidate], canonical_lookup)
def gleam_project_root(root: Path) -> Path | None:
"""Finds the nearest ancestor directory (root itself, its parent, or
its grandparent -- the identical search depth `bazel_workspace_root`/
`find_go_module_prefix` already use) containing a `gleam.toml`
manifest -- the anchor a Gleam import path resolves against.
"""
candidates = [root]
if root.parent != root:
candidates.append(root.parent)
if root.parent.parent != root.parent:
candidates.append(root.parent.parent)
for directory in candidates:
if (directory / "gleam.toml").is_file():
return directory
return None
def gleam_import_targets(source: str) -> list[str]:
"""Every `import a/b/c` module path in `source`. A `.{Type, function}`
unqualified-import suffix and a trailing ` as alias` are both stripped
first (they name what's imported *from* the module, or a local
rebinding, not the module path itself); an external-package import
(`import gleam/io`, `import gleeunit`) is textually identical to a
first-party one -- `resolve_gleam_import`'s file-existence check is
what tells them apart, not this extractor.
"""
out: list[str] = []
for line in source.splitlines():
trimmed = line.strip()
if not trimmed.startswith("import "):
continue
rest = trimmed[len("import ") :]
rest = rest.split(".{", 1)[0]
rest = rest.split(" as ", 1)[0]
path_chars: list[str] = []
for ch in rest.strip():
if ch.isalnum() or ch in "_/":
path_chars.append(ch)
else:
break
path = "".join(path_chars)
if path:
out.append(path)
return out
def resolve_gleam_import(
path: str, project_root: Path | None, canonical_lookup: dict[Path, Path]
) -> Path | None:
"""Resolves one Gleam import path against the discovered project
root's `src/` directory -- `import a/b/c` names
`<project_root>/src/a/b/c.gleam` directly, no case conversion or
dotted-to-slash translation needed, since Gleam's own import syntax
already uses `/` as its path separator. `project_root` is `None` when
no `gleam.toml` was found -- left unresolved rather than guessed.
"""
if project_root is None:
return None
candidate = project_root / "src" / f"{path}.gleam"
return _lookup_candidates([candidate], canonical_lookup)
def nix_import_specifiers(source: str) -> list[str]:
"""Every real, resolvable `import <path>` target in `source`. Reuses
`extract_path_token`'s bareword scan directly (Nix's own argument is
never quoted, so the quoted-string branches simply never fire). Only a
specifier starting with `.` survives `starts_with_dot`'s filter --
excludes `import <nixpkgs>` (angle-bracket `NIX_PATH` search), `import
pkgs` (a plain variable reference), and `import (fetchTarball { ... })`
(an arbitrary expression) for free, none of which start with `.`.
"""
out: list[str] = []
for line in source.splitlines():
idx = line.find("import ")
if idx == -1:
continue
rest = line[idx + len("import ") :]
specifier = extract_path_token(rest, True)
if specifier is not None and starts_with_dot(specifier):
out.append(specifier)
return out
def resolve_nix_import(
base_dir: Path, specifier: str, canonical_lookup: dict[Path, Path]
) -> Path | None:
"""Resolves one Nix `import` specifier -- deliberately not
`resolve_relative_specifier`, the shared helper every quoted-relative-
path family above uses; see this section's own comment for why real
Nix semantics don't fit that helper's "extension-appended, then
`index.<ext>`" candidate order. Tries the literal joined path first
(the common, explicit-extension form -- `import ./foo.nix`), then
`<joined>/default.nix` (the real directory-import convention --
`import ./pkgs` where `./pkgs/default.nix` is the actual target) --
and nothing else: no extension-appended candidate, because real Nix
doesn't try one either.
"""
normalized = specifier.replace("\\", "/")
joined = base_dir / normalized
candidates = [joined, joined / "default.nix"]
return _lookup_candidates(candidates, canonical_lookup)
class DependencyGraph:
def __init__(self) -> None:
self.imports: dict[Path, set[Path]] = {}
self.imported_by: dict[Path, set[Path]] = {}
def file_count(self) -> int:
files: set[Path] = set(self.imports.keys()) | set(self.imported_by.keys())
return len(files)
def imports_of(self, file: Path) -> set[Path]:
return set(self.imports.get(file, set()))
def blast_radius(self, changed: list[Path]) -> set[Path]:
"""Every file that transitively imports something from any file
in `changed` (reverse-BFS), plus `changed` itself.
"""
visited: set[Path] = set(changed)
queue: deque[Path] = deque(changed)
while queue:
file = queue.popleft()
for dependent in self.imported_by.get(file, set()):
if dependent not in visited:
visited.add(dependent)
queue.append(dependent)
return visited
def _record_edge(self, source: Path, target: Path) -> None:
if source == target:
return
self.imports.setdefault(source, set()).add(target)
self.imported_by.setdefault(target, set()).add(source)
def _walk_source_files(directory: Path, out: list[Path]) -> None:
try:
entries = list(directory.iterdir())
except OSError:
return
for entry in entries:
name = entry.name
if entry.is_dir():
if not name.startswith(".") and name not in SKIPPED_DIR_NAMES:
_walk_source_files(entry, out)
elif (
is_recognized_source_extension(entry.suffix[1:].lower())
or is_bazel_build_filename(name)
or is_cmake_list_name(name)
or is_makefile_name(name)
):
out.append(entry)
def collect_source_files(root: Path) -> list[Path]:
out: list[Path] = []
_walk_source_files(root, out)
return out
def _canonical_lookup_of(files: list[Path]) -> dict[Path, Path]:
lookup: dict[Path, Path] = {}
for file in files:
try:
lookup[file.resolve()] = file
except OSError:
continue
return lookup
def _effective_source(file: Path, source: str, extension: str) -> str:
"""A Vue SFC's real import statements live inside its <script>
block(s), and an Astro component's live inside its `---`-fenced
frontmatter -- extract the real script first for those two, use the
file's own text unchanged for every other quoted-relative-path
language.
"""
if extension in ("vue", "svelte"):
return vue_script_blocks(source)
if extension == "astro":
return astro_frontmatter_block(source)
return source
def build(root: Path) -> DependencyGraph:
files = collect_source_files(root)
graph = DependencyGraph()
canonical_lookup = _canonical_lookup_of(files)
rust_files = [f for f in files if f.suffix == ".rs"]
module_paths = module_path_map(root, rust_files)
go_prefix = find_go_module_prefix(root)
bazel_root = bazel_workspace_root(root)
gleam_root = gleam_project_root(root)
godot_root = godot_project_root(root)
sources: dict[Path, str] = {}
for file in files:
try:
sources[file] = file.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
package_of: dict[Path, str] = {}
declared_names_of: dict[Path, str] = {}
for file, source in sources.items():
ext = file.suffix[1:].lower()
if ext in ("java", "kt", "kts", "scala", "groovy", "gvy", "hx"):
pkg = jvm_package_of(source)
if pkg is not None:
package_of[file] = pkg
elif ext in (
"cs", "hs", "purs", "idr", "elm", "agda", "vb", "f90", "f95", "f03", "f08",
"pas", "pp", "dpr", "fs", "fsx",
):
name = declared_name_of(source, ext)
if name is not None:
declared_names_of[file] = name
for file, source in sources.items():
extension = file.suffix[1:].lower()
base_dir = file.parent
if extension == "rs":
own_module = module_paths.get(file)
if own_module is not None:
for used_path in use_paths(source):
resolved = resolve(used_path, own_module)
if resolved is None:
continue
target = longest_prefix_match(resolved, module_paths)
if target is not None:
graph._record_edge(file, target)
continue
if is_cmake_list_name(file.name):
effective_extension = "cmake"
elif is_makefile_name(file.name):
effective_extension = "mk"
else:
effective_extension = extension
family = QUOTED_FAMILIES.get(effective_extension)
if family is not None:
effective_source = _effective_source(file, source, extension)
for specifier in extract_quoted_imports(effective_source, family):
target = resolve_relative_specifier(
base_dir, specifier, family.resolve_extensions, canonical_lookup
)
if target is not None:
graph._record_edge(file, target)
if extension == "py":
for imp in python_relative_imports(source):
for target in resolve_python_relative(file, imp, canonical_lookup):
graph._record_edge(file, target)
if extension == "go":
for import_path in go_import_paths(source):
for target in resolve_go_import(import_path, go_prefix, root, files):
graph._record_edge(file, target)
if extension in ("java", "kt", "kts", "scala", "groovy", "gvy", "hx"):
for dotted in jvm_import_targets(source):
for target in resolve_jvm_import(dotted, package_of):
graph._record_edge(file, target)
if extension in (
"cs", "hs", "purs", "idr", "elm", "agda", "vb", "f90", "f95", "f03", "f08",
"pas", "pp", "dpr", "fs", "fsx",
):
for name in declared_import_names(source, extension):
for target in resolve_declared_name(name, declared_names_of):
graph._record_edge(file, target)
if extension == "lua":
for specifier in lua_require_paths(source):
if not specifier.startswith(".") and "/" not in specifier:
relative = dotted_to_relative_path(specifier, False)
target = resolve_dotted_best_effort(relative, root, ("lua",), canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension in ("ex", "exs"):
for module_name in elixir_module_refs(source):
relative = dotted_to_relative_path(module_name, True)
target = resolve_dotted_best_effort(relative, root, ("ex", "exs"), canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension == "d":
for dotted in d_import_targets(source):
relative = dotted_to_relative_path(dotted, False)
target = resolve_dotted_best_effort(relative, root, ("d",), canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension == "bzl" or is_bazel_build_filename(file.name):
for label in bazel_load_labels(source):
target = resolve_bazel_label(label, file, bazel_root, canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension == "gleam":
for path in gleam_import_targets(source):
target = resolve_gleam_import(path, gleam_root, canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension == "nix":
for specifier in nix_import_specifiers(source):
target = resolve_nix_import(base_dir, specifier, canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension in ("clj", "cljs", "cljc"):
for ns in clojure_ns_requires(source):
relative = clojure_ns_to_relative_path(ns)
target = resolve_dotted_best_effort(
relative, root, ("clj", "cljs", "cljc"), canonical_lookup
)
if target is not None:
graph._record_edge(file, target)
if extension in ("adb", "ads"):
for dotted in ada_with_targets(source):
stem = ada_dotted_to_filename_stem(dotted)
target = resolve_dotted_best_effort(stem, root, ("ads", "adb"), canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension == "gd":
for specifier in gdscript_targets(source):
target = resolve_gdscript_target(specifier, base_dir, godot_root, canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension in ("ml", "mli", "res", "resi"):
for module_name in ocaml_opens(source):
stem = ocaml_module_name_to_stem(module_name)
target = resolve_dotted_best_effort(stem, root, ("ml", "mli", "res", "resi"), canonical_lookup)
if target is not None:
graph._record_edge(file, target)
if extension in ("tf", "tfvars"):
for specifier in terraform_module_sources(source):
for target in resolve_terraform_module_targets(base_dir, specifier, files):
graph._record_edge(file, target)
if extension in ("scss", "sass"):
for specifier in scss_import_specifiers(source):
target = resolve_scss_import(specifier, base_dir, canonical_lookup)
if target is not None:
graph._record_edge(file, target)
return graph
SKIPPED_DIR_NAMES = {
".git",
"node_modules",
"target",
"dist",
"build",
".venv",
"venv",
"__pycache__",
".next",
".cache",
}
_KEYWORDS_BY_EXTENSION: dict[str, tuple[str, ...]] = {
"rs": ("fn ", "struct ", "enum ", "trait "),
"py": ("def ", "class "),
"js": ("function ", "class "),
"jsx": ("function ", "class "),
"mjs": ("function ", "class "),
"cjs": ("function ", "class "),
"ts": ("function ", "class ", "interface ", "type "),
"tsx": ("function ", "class ", "interface ", "type "),
"go": ("func ", "type "),
"java": ("class ", "interface ", "enum "),
"c": ("struct ", "enum ", "typedef "),
"h": ("struct ", "enum ", "typedef "),
"cpp": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"cc": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"cxx": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"hpp": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"hh": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"cu": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"cuh": ("struct ", "enum ", "class ", "namespace ", "typedef "),
"cs": ("class ", "interface ", "enum ", "struct ", "namespace "),
"rb": ("def ", "class ", "module "),
"php": ("function ", "class ", "interface ", "trait "),
"swift": ("func ", "class ", "struct ", "enum ", "protocol "),
"kt": ("fun ", "class ", "interface ", "object ", "enum class "),
"kts": ("fun ", "class ", "interface ", "object ", "enum class "),
"scala": ("def ", "class ", "trait ", "object ", "case class "),
"dart": ("class ", "enum ", "mixin ", "extension ", "typedef "),
"m": ("@interface ", "@implementation ", "@protocol "),
"mm": ("@interface ", "@implementation ", "@protocol "),
"r": ('setClass(', 'setGeneric(', 'setMethod('),
"pl": ("sub ", "package "),
"pm": ("sub ", "package "),
"lua": ("function ",),
"sh": ("function ",),
"bash": ("function ",),
"zsh": ("function ",),
"ps1": ("function ",),
"psm1": ("function ",),
"fish": ("function ",),
"tcl": ("proc ",),
"hack": ("function ", "class ", "interface ", "trait ", "enum ", "type ", "newtype "),
"hhi": ("function ", "class ", "interface ", "trait ", "enum ", "type ", "newtype "),
"raku": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"rakumod": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"rakutest": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"p6": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"pl6": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"pm6": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"nqp": ("sub ", "class ", "role ", "grammar ", "module ", "enum ", "subset ", "unit module ", "unit class "),
"bal": ("function ", "type ", "class ", "enum ", "service "),
"lean": ("theorem ", "lemma ", "def ", "structure ", "inductive ", "class ", "instance ", "namespace ", "abbrev ", "axiom "),
"hlean": ("theorem ", "lemma ", "def ", "structure ", "inductive ", "class ", "instance ", "namespace ", "abbrev ", "axiom "),
"qs": ("operation ", "function ", "newtype ", "namespace ", "struct "),
"nut": ("function ", "class ", "local "),
"wren": ("class ", "var "),
"awk": ("function ",),
"groovy": ("class ", "interface ", "trait ", "enum ", "def "),
"gvy": ("class ", "interface ", "trait ", "enum ", "def "),
"hs": ("data ", "type ", "newtype ", "class ", "instance "),
"ex": ("def ", "defmodule ", "defp ", "defmacro ", "defprotocol ", "defimpl "),
"exs": ("def ", "defmodule ", "defp ", "defmacro ", "defprotocol ", "defimpl "),
"erl": ("-module(",),
"clj": ("(defn ", "(def ", "(defmacro ", "(defprotocol ", "(defrecord "),
"cljs": ("(defn ", "(def ", "(defmacro ", "(defprotocol ", "(defrecord "),
"cljc": ("(defn ", "(def ", "(defmacro ", "(defprotocol ", "(defrecord "),
"fs": ("let ", "type ", "module "),
"fsx": ("let ", "type ", "module "),
"res": ("let ", "type ", "module "),
"resi": ("let ", "type ", "module "),
"re": ("let ", "type ", "module "),
"rei": ("let ", "type ", "module "),
"ml": ("let ", "type ", "module ", "class "),
"mli": ("let ", "type ", "module ", "class "),
"lisp": ("(defun ", "(defvar ", "(defclass ", "(defmacro ", "(defpackage "),
"lsp": ("(defun ", "(defvar ", "(defclass ", "(defmacro ", "(defpackage "),
"scm": ("(define ", "(define-syntax ", "(define-record-type "),
"ss": ("(define ", "(define-syntax ", "(define-record-type "),
"rkt": ("(define ", "(struct ", "(define-struct "),
"elm": ("type ",),
"jl": ("function ", "struct ", "mutable struct ", "module ", "abstract type "),
"vb": ("Class ", "Module ", "Structure ", "Interface ", "Sub ", "Function "),
"cob": ("PROGRAM-ID. ",),
"cbl": ("PROGRAM-ID. ",),
"f90": (
"subroutine ", "function ", "module ", "program ",
"SUBROUTINE ", "FUNCTION ", "MODULE ", "PROGRAM ",
),
"f95": (
"subroutine ", "function ", "module ", "program ",
"SUBROUTINE ", "FUNCTION ", "MODULE ", "PROGRAM ",
),
"f03": (
"subroutine ", "function ", "module ", "program ",
"SUBROUTINE ", "FUNCTION ", "MODULE ", "PROGRAM ",
),
"f08": (
"subroutine ", "function ", "module ", "program ",
"SUBROUTINE ", "FUNCTION ", "MODULE ", "PROGRAM ",
),
"adb": ("procedure ", "function ", "package ", "type "),
"ads": ("procedure ", "function ", "package ", "type "),
"abap": ("CLASS ", "FORM ", "FUNCTION ", "METHOD "),
"sas": ("%macro ", "data ", "proc "),
"cls": ("class ", "interface ", "enum ", "trigger "),
"trigger": ("class ", "interface ", "enum ", "trigger "),
"cr": ("def ", "class ", "module ", "struct ", "enum "),
"nim": ("proc ", "func ", "type ", "template ", "macro "),
"zig": ("fn ",),
"sol": (
"contract ", "interface ", "library ", "function ", "struct ", "enum ", "modifier ",
),
"pas": ("procedure ", "function ", "unit ", "program "),
"pp": ("procedure ", "function ", "unit ", "program "),
"dpr": ("procedure ", "function ", "unit ", "program "),
"v": ("module ", "function ", "task ", "class "),
"sv": ("module ", "function ", "task ", "class "),
"svh": ("module ", "function ", "task ", "class "),
"vhd": ("entity ", "architecture ", "procedure ", "function ", "package "),
"vhdl": ("entity ", "architecture ", "procedure ", "function ", "package "),
"sql": (
"CREATE TABLE ", "CREATE VIEW ", "CREATE FUNCTION ", "CREATE PROCEDURE ",
"create table ", "create view ", "create function ", "create procedure ",
),
"gd": ("func ", "class_name "),
"graphql": ("type ", "interface ", "enum ", "input ", "scalar ", "union "),
"gql": ("type ", "interface ", "enum ", "input ", "scalar ", "union "),
"proto": ("message ", "service ", "enum "),
"thrift": ("struct ", "service ", "enum ", "exception ", "union ", "typedef "),
"jsonnet": ("local ",),
"libsonnet": ("local ",),
"dhall": ("let ",),
"pls": (
"CREATE OR REPLACE PACKAGE ", "CREATE OR REPLACE PROCEDURE ",
"CREATE OR REPLACE FUNCTION ", "CREATE OR REPLACE TRIGGER ",
"CREATE PACKAGE ", "CREATE PROCEDURE ", "CREATE FUNCTION ", "CREATE TRIGGER ",
"create or replace package ", "create or replace procedure ",
"create or replace function ", "create or replace trigger ",
"create package ", "create procedure ", "create function ", "create trigger ",
),
"plb": (
"CREATE OR REPLACE PACKAGE ", "CREATE OR REPLACE PROCEDURE ",
"CREATE OR REPLACE FUNCTION ", "CREATE OR REPLACE TRIGGER ",
"CREATE PACKAGE ", "CREATE PROCEDURE ", "CREATE FUNCTION ", "CREATE TRIGGER ",
"create or replace package ", "create or replace procedure ",
"create or replace function ", "create or replace trigger ",
"create package ", "create procedure ", "create function ", "create trigger ",
),
"idr": ("data ", "module ", "interface ", "implementation ", "record "),
"purs": ("data ", "type ", "newtype ", "class ", "instance ", "module "),
"agda": ("data ", "record ", "module ", "postulate "),
"gleam": ("fn ", "type ", "const "),
"bzl": ("def ",),
"wgsl": ("fn ", "struct ", "const "),
"mojo": ("def ", "fn ", "struct "),
"hx": ("class ", "interface ", "enum ", "typedef ", "function "),
"d": ("struct ", "class ", "interface ", "enum "),
"sml": ("structure ", "signature ", "functor ", "datatype ", "fun ", "exception "),
"vala": ("class ", "interface ", "struct ", "enum ", "namespace ", "delegate "),
"cmake": ("function(", "macro(", "FUNCTION(", "MACRO("),
"pro": (":- module(",),
"vy": ("def ", "event ", "struct ", "interface "),
"move": ("module ", "struct ", "fun "),
"capnp": ("struct ", "interface ", "enum "),
"fbs": ("table ", "struct ", "enum ", "union "),
"nu": ("def ",),
"coffee": ("class ",),
"scss": ("@mixin ", "@function "),
"sass": ("@mixin ", "@function "),
"vim": ("function! ", "function "),
"asm": ("global ", "extern "),
"nasm": ("global ", "extern "),
"inc": ("global ", "extern "),
"pug": ("mixin ",),
"vbs": ("Sub ", "Function ", "Class "),
"el": ("(defun ", "(defvar ", "(defmacro ", "(defcustom ", "(defgroup ", "(defface "),
"scad": ("module ", "function "),
"smk": ("rule ", "def "),
"nf": ("process ", "workflow "),
"as": ("class ", "function ", "interface ", "package "),
"pde": ("void ", "class "),
"yar": ("rule ",),
"yara": ("rule ",),
"jq": ("def ",),
"bicep": ("resource ", "module ", "param ", "output ", "func "),
"applescript": ("on ", "script ", "property "),
"cfm": ("function ",),
"cfml": ("function ",),
"typ": ("#let ",),
"hlsl": ("struct ", "cbuffer "),
"hlsli": ("struct ", "cbuffer "),
"fx": ("struct ", "cbuffer "),
"fxh": ("struct ", "cbuffer "),
"cginc": ("struct ", "cbuffer "),
"glsl": ("void ",),
"vert": ("void ",),
"frag": ("void ",),
"geom": ("void ",),
"tesc": ("void ",),
"tese": ("void ",),
"gdshader": ("void ",),
"gdshaderinc": ("void ",),
"ino": ("void ", "struct ", "enum ", "class "),
"cairo": ("fn ", "struct ", "enum ", "trait ", "impl ", "mod "),
"chpl": ("proc ", "iter ", "module ", "record ", "class "),
"nsi": ("Section ", "Function ", "!macro ", "!define ", "Var "),
"nsh": ("Section ", "Function ", "!macro ", "!define ", "Var "),
"kconfig": ("config ", "menuconfig ", "menu ", "choice", "source "),
}
_DECLARATION_MODIFIERS = (
"pub ", "export ", "async ", "default ", "public ", "private ", "protected ", "internal ",
"static ", "final ", "abstract ", "sealed ", "open ", "fileprivate ", "override ", "local ",
"Public ", "Private ", "Protected ", "Friend ", "Shared ", "MustInherit ", "NotInheritable ",
"Overridable ", "NotOverridable ", "Partial ",
)
def _strip_declaration_modifiers(line: str) -> str:
stripped = True
while stripped:
stripped = False
for modifier in _DECLARATION_MODIFIERS:
if line.startswith(modifier):
line = line[len(modifier):]
stripped = True
return line
def _r_assign_function_symbol(line: str) -> str | None:
"""R's idiomatic function assignment -- `name <- function(...)` (or
the less common `name = function(...)`) -- which has no leading
keyword at all. More failure-prone than a keyword match by nature:
an unusual assignment shape can miss it.
"""
if "<-" in line:
idx = line.index("<-")
name_part, rest = line[:idx], line[idx + 2:]
elif "=" in line:
idx = line.index("=")
before, after = line[:idx], line[idx + 1:]
if before.endswith(("<", ">", "!", "=")) or after.startswith("="):
return None
name_part, rest = before, after
else:
return None
name = name_part.strip()
if not name or not all(c.isalnum() or c in "_." for c in name):
return None
if rest.lstrip().startswith("function"):
return name
return None
def _shell_posix_function_symbol(line: str) -> str | None:
"""Shell's POSIX function form -- `name() { ... }` or `name()` with
the brace on its own next line -- which has no leading keyword,
unlike the `function name { ... }` form the keyword table matches.
"""
body = line.rstrip()
if body.endswith("{"):
body = body[:-1].rstrip()
if not body.endswith("()"):
return None
name = body[:-2].strip()
if not name or not all(c.isalnum() or c in "_-." for c in name):
return None
return name
def _extra_heuristic_symbol(extension: str, line: str) -> str | None:
"""A per-extension heuristic tried only when the normal keyword-table
match found nothing for a given line -- the "real, stated gaps"
languages that have no leading keyword for at least one construct.
"""
if extension == "r":
return _r_assign_function_symbol(line)
if extension in ("sh", "bash", "zsh"):
return _shell_posix_function_symbol(line)
return None
def extract_symbols(content: str, extension: str) -> list[str]:
"""Extracts top-level symbol declarations from `content`, given a file
`extension` (without the leading dot, e.g. `"rs"`) -- a per-line
heuristic, not a real parser (see module doc's honest-scope note).
Returns an empty list for an unrecognized extension.
"""
keywords = _KEYWORDS_BY_EXTENSION.get(extension)
if not keywords:
return []
symbols: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
stripped_line = _strip_declaration_modifiers(raw_line)
matched = False
for keyword in keywords:
if raw_line.startswith(keyword):
rest = raw_line[len(keyword):]
elif stripped_line.startswith(keyword):
rest = stripped_line[len(keyword):]
else:
continue
if extension in ("scm", "ss", "rkt") and keyword == "(define " and rest.startswith("("):
rest = rest[1:]
if rest.startswith('"'):
name = rest[1:].split('"', 1)[0]
else:
raw_name = ""
for ch in rest:
if ch.isalnum() or ch in "_$.-":
raw_name += ch
else:
break
name = raw_name.rstrip(".")
if name:
symbols.append(name)
matched = True
break
if not matched:
extra = _extra_heuristic_symbol(extension, stripped_line)
if extra:
symbols.append(extra)
return symbols
def yaml_top_level_keys(content: str) -> list[str]:
"""Extracts YAML "symbols": top-level (unindented) mapping keys --
`key:` at column 0, skipping list items (`- `), comments (`#`), and
document/section markers (`---`/`...`). Nested keys aren't walked --
same top-level-only convention `extract_symbols` applies to code.
Covers `docker-compose.yml`, Kubernetes manifests, GitHub
Actions/GitLab CI, Ansible playbooks, and Helm `values.yaml` equally,
since they're all just YAML.
"""
keys: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
line = raw_line.rstrip()
if not line or line.startswith("#") or line.startswith("---") or line.startswith("...") or line.startswith("-"):
continue
if ":" not in line:
continue
key = line.split(":", 1)[0].strip().strip("\"'")
if not key or " " in key:
continue
keys.append(key)
return keys
def _json_brace_delta(line: str) -> int:
"""The net `{`/`[`-depth change contributed by one line, ignoring any
brace/bracket character inside a quoted string value.
"""
delta = 0
in_string = False
chars = iter(line)
for ch in chars:
if in_string:
if ch == "\\":
next(chars, None)
elif ch == '"':
in_string = False
continue
if ch == '"':
in_string = True
elif ch in "{[":
delta += 1
elif ch in "}]":
delta -= 1
return delta
def json_top_level_keys(content: str) -> list[str]:
"""Extracts a JSON file's direct top-level object keys -- a `"key":`
line seen while a running brace-depth counter is exactly 1, i.e.
directly inside the root `{`. Depth, not indentation, is the signal
-- a fixed indent threshold would conflate a depth-1 key in a
4-space file with a depth-2 key in a 2-space file. A minified
single-line JSON file yields nothing -- the opening `{` and its keys
share one line, so depth is still 0 at the moment this heuristic
would need to see 1.
"""
keys: list[str] = []
depth = 0
for raw_line in content.splitlines():
line = raw_line.strip()
if depth == 1 and line.startswith('"'):
rest = line[1:]
if '"' in rest:
key, after = rest.split('"', 1)
if key and after.lstrip().startswith(":"):
keys.append(key)
depth += _json_brace_delta(line)
return keys
def _xml_split_tag(s: str) -> tuple[str, bool]:
"""Finds this tag's closing `>`, quote-aware so a `>` inside a quoted
attribute value (`<tag attr="a > b">`) doesn't end the tag early.
Returns the text after the `>` and whether the tag was self-closing
(`/>`, the character immediately before that `>` was `/`).
"""
quote: str | None = None
prev: str | None = None
for i, ch in enumerate(s):
if quote is not None:
if ch == quote:
quote = None
prev = ch
continue
if ch in ('"', "'"):
quote = ch
elif ch == ">":
return s[i + 1:], prev == "/"
prev = ch
return "", False
def _xml_skip_past(s: str, terminator: str) -> str:
"""Consumes `s` up to and including the first occurrence of
`terminator`, returning what follows it (or "" if it never appears).
"""
idx = s.find(terminator)
if idx == -1:
return ""
return s[idx + len(terminator):]
def xml_top_level_elements(content: str) -> list[str]:
"""Extracts an XML file's direct children of its root element --
`pom.xml` yields `groupId`/`artifactId`/`dependencies`/`build`/...
straight off `<project>`, an Android manifest yields `application`/
`uses-permission`/... off `<manifest>`, a `.csproj` yields
`PropertyGroup`/`ItemGroup` off `<Project>`. Unlike every other
extractor here, this isn't line-based (XML's structure is nesting
depth, not indentation or even line breaks at all -- a real, common
convention for a minified `.csproj`) -- it scans the whole content as
one character stream, tracking element-nesting depth via a
quote-aware tag scan (`_xml_split_tag`) so a `>` inside a quoted
attribute value never miscounts. Comments (`<!--...-->`),
`<![CDATA[...]]>` sections, and `<?...?>` processing instructions are
skipped outright, never scanned for fake tags inside them. Depth-2-
and-deeper elements aren't walked, same top-level-only convention as
every other extractor here. A `<!DOCTYPE ...>` with an internal
subset is a real, stated gap: this heuristic stops at the *first*
unquoted `>`, not the subset's real outer one -- vanishingly rare in
real repo XML, not attempted here.
"""
names: list[str] = []
depth = 0
rest = content
while True:
lt = rest.find("<")
if lt == -1:
break
rest = rest[lt + 1:]
if rest.startswith("?"):
rest = _xml_skip_past(rest[1:], "?>")
elif rest.startswith("!--"):
rest = _xml_skip_past(rest[3:], "-->")
elif rest.startswith("![CDATA["):
rest = _xml_skip_past(rest[8:], "]]>")
elif rest.startswith("!"):
rest = _xml_skip_past(rest[1:], ">")
elif rest.startswith("/"):
after_tag, _ = _xml_split_tag(rest[1:])
rest = after_tag
depth = max(0, depth - 1)
else:
name_end = len(rest)
for i, ch in enumerate(rest):
if ch.isspace() or ch in ("/", ">"):
name_end = i
break
name = rest[:name_end]
after_tag, self_closing = _xml_split_tag(rest)
if name and depth == 1:
names.append(name)
if not self_closing:
depth += 1
rest = after_tag
return names
def toml_symbols(content: str) -> list[str]:
"""Extracts TOML "symbols": `[section]`/`[[array-of-tables]]` headers,
plus every `key = value` assignment line (TOML doesn't require, or
conventionally use, indentation under a section the way YAML/JSON
do). Covers `Cargo.toml`, `pyproject.toml`, and similar config
equally.
"""
symbols: list[str] = []
for raw_line in content.splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("[[") and line.endswith("]]"):
symbols.append(line[2:-2].strip())
continue
if line.startswith("[") and line.endswith("]"):
symbols.append(line[1:-1].strip())
continue
if "=" in line:
key = line.split("=", 1)[0].strip().strip("\"'")
if key and " " not in key:
symbols.append(key)
return symbols
def dockerfile_stages(content: str) -> list[str]:
"""Extracts a Dockerfile's build-stage names -- `FROM <image> AS
<name>` (case-insensitive `AS`, matching Docker's own parser) -- the
structural unit of a multi-stage Dockerfile. An unnamed
`FROM <image>` stage is listed by its image reference instead.
"""
stages: list[str] = []
for raw_line in content.splitlines():
line = raw_line.strip()
rest = None
if line.startswith("FROM "):
rest = line[len("FROM "):]
elif line.startswith("from "):
rest = line[len("from "):]
if rest is None:
continue
lower = rest.lower()
as_idx = lower.find(" as ")
if as_idx != -1:
name = rest[as_idx + 4:].strip()
if name:
stages.append(name)
continue
image = rest.split()[0] if rest.split() else ""
if image:
stages.append(image)
return stages
def makefile_targets(content: str) -> list[str]:
"""Extracts a Makefile's target names -- `target: prerequisites` at
column 0 (recipe lines under a target are tab-indented, so the
existing "unindented only" convention already excludes them
correctly). Skips variable assignments and meta-targets (`.PHONY`,
...).
"""
targets: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t") or raw_line.startswith("#"):
continue
line = raw_line.rstrip()
if line.startswith("."):
continue
if ":" not in line:
continue
colon = line.index(":")
before, after = line[:colon], line[colon + 1:].lstrip()
if after.startswith("="):
continue
if not before or "=" in before or "$" in before:
continue
targets.extend(before.split())
return targets
_TERRAFORM_TWO_ARG_KEYWORDS = ("resource", "data")
_TERRAFORM_ONE_ARG_KEYWORDS = ("module", "variable", "output", "provider")
def terraform_symbols(content: str) -> list[str]:
"""Extracts Terraform/HCL top-level block symbols -- `resource
"type" "name"`, `data "type" "name"`, `module "name"`, `variable
"name"`, `output "name"`, `provider "name"`, and a bare `locals`.
`resource`/`data` render dotted (`aws_s3_bucket.my_bucket`),
matching Terraform's own addressing convention.
"""
symbols: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
line = raw_line.rstrip()
parts = line.split(" ", 1)
keyword = parts[0]
rest = parts[1] if len(parts) > 1 else ""
quoted_args = rest.split('"')[1::2]
if keyword in _TERRAFORM_TWO_ARG_KEYWORDS and len(quoted_args) >= 2:
symbols.append(f"{quoted_args[0]}.{quoted_args[1]}")
elif keyword in _TERRAFORM_ONE_ARG_KEYWORDS and quoted_args:
symbols.append(quoted_args[0])
elif keyword == "locals" and line.endswith("{"):
symbols.append("locals")
return symbols
def _is_dockerfile_name(filename: str) -> bool:
return filename == "Dockerfile" or filename.startswith("Dockerfile.")
def _is_makefile_name(filename: str) -> bool:
return filename in ("Makefile", "makefile", "GNUmakefile")
def _is_bazel_build_name(filename: str) -> bool:
"""`BUILD`/`BUILD.bazel`/`WORKSPACE`/`WORKSPACE.bazel`/`MODULE.bazel`
-- Bazel's own convention for its canonical, extension-less file
kinds, same filename-based dispatch already established for
Dockerfile/Makefile. `MODULE.bazel` (batch D, E31-T24) is Bazel's
modern bzlmod dependency-declaration file -- its `module(...)`/
`bazel_dep(...)` calls have the same `name = "..."` attribute every
other rule macro does, so `starlark_build_targets` covers it with no
new code, just the filename recognized.
"""
return filename in ("BUILD", "BUILD.bazel", "WORKSPACE", "WORKSPACE.bazel", "MODULE.bazel")
def _is_justfile_name(filename: str) -> bool:
"""`justfile`/`Justfile`/`.justfile` -- `just`'s own real, extension-
less canonical entry-point filenames (batch I, E31-T29), the
identical "canonical filename, no extension" shape Makefile/
Dockerfile/BUILD already have.
"""
return filename in ("justfile", "Justfile", ".justfile")
def _is_dotenv_name(filename: str) -> bool:
"""`.env`/`.env.local`/`.env.production`/etc. -- dotenv's own filename
convention (E31-T22's "500 file kinds" push): unlike most formats
there is no single fixed extension, the leading `.env` *is* the
format marker.
"""
return filename == ".env" or filename.startswith(".env.")
def _is_editorconfig_name(filename: str) -> bool:
"""`.editorconfig` -- EditorConfig's own filename convention
(E31-T22). Its body is genuinely INI-shaped (`root = true` plus
`[glob]` sections), so `ini_section_headers` is reused rather than
duplicated.
"""
return filename == ".editorconfig"
def _is_cmake_list_name(filename: str) -> bool:
"""`CMakeLists.txt` -- CMake's own canonical, extension-less
build-file name (batch E, E31-T25), mirroring Dockerfile/Makefile/
`_is_bazel_build_name`'s established filename-based dispatch shape.
Only the canonical exact-case spelling is matched -- CMake tooling
itself requires this exact case on a case-sensitive filesystem, so
there's no real-world lowercase variant to add the way Makefile's
genuinely has.
"""
return filename == "CMakeLists.txt"
def cue_symbols(content: str) -> list[str]:
"""Extracts a CUE file's top-level field/definition names -- `key:` or
`#Definition:` at column 0. CUE's own comment syntax is `//` (not
`#` -- `#` opens a definition identifier in CUE, the opposite of
YAML/TOML), so this is not just `yaml_top_level_keys` reused: that
would treat every CUE definition as a comment and silently drop it.
"""
symbols: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
line = raw_line.rstrip()
if not line or line.startswith("//") or line.startswith("package "):
continue
if ":" not in line:
continue
key = line.split(":", 1)[0].strip().strip("\"'")
if not key or " " in key:
continue
symbols.append(key)
return symbols
def starlark_build_targets(content: str) -> list[str]:
"""Extracts a Bazel `BUILD`/`WORKSPACE`/`MODULE.bazel` file's declared
target names -- the value of each rule macro call's `name = "..."`
attribute, the one attribute every real Bazel rule has in common (the
rule macro itself -- `go_library`/`cc_binary`/`bazel_dep`/etc. -- is
an unbounded, plugin-defined vocabulary with no fixed keyword list).
Not indentation-scoped -- `name = ` is conventionally indented one
level inside its rule call, not at column 0 -- and, as of E31-T24, not
scoped to "the first token on its trimmed line" either: a real,
self-caught gap found while wiring up `MODULE.bazel` support, whose
idiomatic `bazel_dep(name = "rules_rust", version = "0.52.0")`
one-liner put `name` mid-line, which the original line-start-only
match silently never found. Now scans the whole line for a
whole-word `name` (checked on both sides, so `srcs = ["username.py"]`'s
embedded substring doesn't false-match).
"""
names: list[str] = []
for raw_line in content.splitlines():
rest = raw_line
while True:
idx = rest.find("name")
if idx == -1:
break
before = rest[:idx]
after = rest[idx + len("name"):]
word_boundary_before = not (before and (before[-1].isalnum() or before[-1] == "_"))
word_boundary_after = not (after and (after[0].isalnum() or after[0] == "_"))
if word_boundary_before and word_boundary_after:
candidate = after.lstrip()
if candidate.startswith("="):
eq_rest = candidate[1:].lstrip()
quote = None
if eq_rest.startswith('"'):
quote = '"'
elif eq_rest.startswith("'"):
quote = "'"
if quote is not None:
after_quote = eq_rest[1:]
end = after_quote.find(quote)
if end > 0:
names.append(after_quote[:end])
rest = after
return names
def odin_symbols(content: str) -> list[str]:
"""Extracts Odin's top-level `name :: proc`/`name :: struct`/`name ::
enum`/`name :: union` declarations (E31-T22, freshness-checked
2026-08-09). Odin's constant-declaration operator `::` puts the name
*before* the keyword (`Player :: struct {...}`), the opposite of every
language `_KEYWORDS_BY_EXTENSION` matches, so this can't be a
keyword-table entry no matter which side is picked as "the keyword."
A bare constant (`Max :: 100`) is deliberately not captured -- only
the four declaration forms above are structural units this map
surfaces.
"""
symbols: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
line = raw_line.rstrip()
if "::" not in line:
continue
name, rest = line.split("::", 1)
name = name.strip()
if not name or not all(c.isalnum() or c == "_" for c in name):
continue
rest = rest.lstrip()
for keyword in ("proc", "struct", "enum", "union"):
if rest.startswith(keyword):
after = rest[len(keyword) :]
if not after or not (after[0].isalnum() or after[0] == "_"):
symbols.append(name)
break
return symbols
def ini_section_headers(content: str) -> list[str]:
"""Extracts an INI-style file's `[section]` header names (`.ini`,
`.cfg`, `.conf`, and `.editorconfig` -- see `_is_editorconfig_name`)
-- the one structural unit every real INI dialect reliably has. A
`key = value` pair outside (or inside) a section is not itself a
symbol; a `;` or `#` comment line is skipped.
"""
sections: list[str] = []
for raw_line in content.splitlines():
line = raw_line.strip()
if not line or line.startswith(";") or line.startswith("#"):
continue
if not line.startswith("["):
continue
rest = line[1:]
if not rest.endswith("]"):
continue
name = rest[:-1].strip()
if name:
sections.append(name)
return sections
def dotenv_keys(content: str) -> list[str]:
"""Extracts a `.env`-family file's declared variable names
(`KEY=value`, `export KEY=value`) -- see `_is_dotenv_name`. The value
itself (often a real secret) is deliberately never included, only the
name.
"""
keys: list[str] = []
for raw_line in content.splitlines():
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export ") :]
if "=" not in line:
continue
key = line.split("=", 1)[0].strip()
if key and all(c.isalnum() or c == "_" for c in key):
keys.append(key)
return keys
def properties_top_level_namespaces(content: str) -> list[str]:
"""Extracts a Java/Spring-style `.properties` file's top-level dotted
namespaces (batch E, E31-T25) -- `server.port=8080`/
`logging.level.root=DEBUG` yields `server`/`logging` (deduplicated,
first-seen order), not every individual key the way `dotenv_keys`
returns for a flat `.env` file. A real `.properties` file (Spring
Boot's `application.properties`, a Java `log4j.properties`, Android's
`gradle.properties`) commonly carries hundreds of keys under a
handful of real namespaces -- the namespace is the useful orientation
"symbol" here, an individual key isn't. `#` and `!` are both valid
Java `.properties` line-comment markers (unlike `.env`'s `#`-only
convention); `:` is accepted as a key/value separator alongside `=`;
a key with no dot at all is returned whole.
"""
namespaces: list[str] = []
for raw_line in content.splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or line.startswith("!"):
continue
key_end = len(line)
for sep in ("=", ":"):
idx = line.find(sep)
if idx != -1:
key_end = min(key_end, idx)
key = line[:key_end].strip()
if not key:
continue
namespace = key.split(".", 1)[0]
if namespace not in namespaces:
namespaces.append(namespace)
return namespaces
_LATEX_HEADING_KEYWORDS = (
"\\chapter{",
"\\chapter*{",
"\\section{",
"\\section*{",
"\\subsection{",
"\\subsection*{",
"\\subsubsection{",
"\\subsubsection*{",
)
def latex_section_headings(content: str) -> list[str]:
"""Extracts a `.tex` document's sectioning-command titles (batch G,
E31-T27) -- `\\chapter{`/`\\section{`/`\\subsection{`/`\\subsubsection{`,
each also in its starred, unnumbered form (`\\section*{...}`, a real,
common spelling for "Abstract"/"References"/etc.). A dedicated
extractor rather than a `_KEYWORDS_BY_EXTENSION` row: a section title
is prose, not an identifier, so the generic name-capture would
silently truncate a real multi-word title at its first space --
this instead brace-depth-tracks to the real matching `}`, so a title
containing its own nested braces (`\\section{Intro and
\\emph{Motivation}}`, a common inline-formatting shape) is captured
whole. Single-line titles only -- a title split across multiple
source lines isn't captured.
"""
headings: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith(" ") or raw_line.startswith("\t"):
continue
line = raw_line.rstrip()
for keyword in _LATEX_HEADING_KEYWORDS:
if not line.startswith(keyword):
continue
rest = line[len(keyword) :]
depth = 1
end = None
for i, c in enumerate(rest):
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
end = i
break
if end is not None:
title = rest[:end].strip()
if title:
headings.append(title)
break
return headings
def markdown_headings(content: str) -> list[str]:
"""Extracts a Markdown file's top-level ATX heading text (batch G,
E31-T27) -- `# Heading` through `###### Heading`, the full remaining
line text (not truncated to a first identifier-shaped word, same
"prose, not an identifier" reasoning as `latex_section_headings`).
Fence-aware: a line inside a ``` / ~~~ fenced code block is never
read as a heading, even if it starts with `#` (a `#`-prefixed shell
comment inside a fenced bash example is one of the single most
common real strings in any README that would otherwise false-match).
Trailing `#`s some Markdown styles use to close a heading
(`# Title #`) are trimmed.
"""
headings: list[str] = []
fence: str | None = None
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
if fence is not None:
if trimmed.startswith(fence) and len(trimmed) - len(trimmed.lstrip(fence)) >= 3:
fence = None
continue
if trimmed.startswith("```") or trimmed.startswith("~~~"):
fence = trimmed[0]
continue
hashes = len(trimmed) - len(trimmed.lstrip("#"))
if hashes == 0 or hashes > 6:
continue
rest = trimmed[hashes:]
if not rest.startswith(" "):
continue
title = rest.strip().rstrip("#").strip()
if title:
headings.append(title)
return headings
def nix_let_bindings(content: str) -> list[str]:
"""Extracts a Nix file's own top-level `let ... in` block binding names
(batch H, E31-T28). Nix declarations are assignment-shaped (`name =
value;`), not the single-leading-keyword-per-declaration shape
`_KEYWORDS_BY_EXTENSION` otherwise assumes -- the same "name-first"
gap Odin's `name :: proc` form has -- so this is a dedicated
extractor, not a table row.
Deliberately narrow, real scope, stated plainly rather than guessed
at more broadly: only bindings directly inside the file's *outermost*
`let ... in` block are captured. `let`/`in` depth is tracked by a
simple counter -- a line that trims to exactly `let` increments it,
one that trims to exactly `in` decrements it (matching real
`nixpkgs-fmt`/`alejandra` formatter convention -- each keyword alone
on its own line) -- and only lines at depth exactly 1 are scanned for
a binding, so a real, line-separated nested `let ... in` (depth 2 for
its own body) correctly contributes none of *its* bindings to the
result, and depth correctly drops back to 1 afterward so the outer
block's remaining bindings are still captured. An *inline* nested
`let x = 1; in x + 1;` on the same line as other content never
matches either exact-line check, so it doesn't affect depth at all --
the real top-level binding it's part of is still captured normally.
A Nix file's own outermost attribute-set keys (`{ foo = ...; }`,
outside any `let`) are **not** extracted: reliably finding that set's
true depth-1 boundary without a real parser means tracking brace
nesting through string interpolation too (`"${foo}"` contains a
`{`/`}` pair that must *not* count) -- exactly the kind of guess this
module's own "not a real parser" honest-scope note says not to
attempt, so it's a real, stated gap here instead.
`inherit`/`inherit (...)` bindings, which name an existing value
rather than assign a new expression, don't match the `name = value;`
shape this heuristic scans for and are correctly never captured (no
special-casing needed -- an `inherit x y;` line's leading identifier-
shaped token, `inherit` itself, is followed by `x`, not `=`).
"""
names: list[str] = []
depth = 0
for raw_line in content.splitlines():
trimmed = raw_line.strip()
if trimmed == "let":
depth += 1
continue
if trimmed == "in":
depth = max(0, depth - 1)
continue
if depth != 1 or not trimmed or trimmed.startswith("#"):
continue
name_chars: list[str] = []
for ch in trimmed:
if ch.isalnum() or ch in "_'-":
name_chars.append(ch)
else:
break
name = "".join(name_chars)
if not name:
continue
rest = trimmed[len(name) :].lstrip()
if rest.startswith("==") or not rest.startswith("="):
continue
if name not in names:
names.append(name)
return names
def justfile_recipes(content: str) -> list[str]:
"""A `justfile`'s own real recipe names (batch I, E31-T29) -- a
recipe is a bareword at column 0 (no leading whitespace, unlike its
own indented body) followed eventually by a `:` that isn't `:=` (a
variable assignment, a different real `just` construct this doesn't
capture). Attribute lines (`[no-cd]`, `[private]`, ...) and comments
are skipped; a leading `@` (a real `just` "quiet recipe" prefix) is
stripped first so the recipe name itself is still found.
"""
out: list[str] = []
for line in content.splitlines():
if not line or line[0].isspace():
continue
trimmed = line.lstrip("@")
if trimmed.startswith("#") or trimmed.startswith("["):
continue
colon_idx = trimmed.find(":")
if colon_idx == -1 or trimmed[colon_idx:].startswith(":="):
continue
name_chars: list[str] = []
for ch in trimmed[:colon_idx]:
if ch.isalnum() or ch in "_-":
name_chars.append(ch)
else:
break
if name_chars:
out.append("".join(name_chars))
return out
_BIBTEX_PSEUDO_ENTRIES = ("comment", "string", "preamble")
def bibtex_entry_keys(content: str) -> list[str]:
"""A BibTeX/BibLaTeX file's own real entry citekeys (batch I,
E31-T29) -- `@EntryType{citekey, ...}`, the identifier a LaTeX
document's own `\\cite{citekey}` actually references. The three real
BibTeX pseudo-entry types (`@comment`, `@string`, `@preamble`) never
name a citable work, so they're excluded rather than surfaced as if
they were one.
"""
out: list[str] = []
for line in content.splitlines():
stripped = line.lstrip()
if not stripped.startswith("@"):
continue
rest = stripped[1:]
brace_idx = rest.find("{")
if brace_idx == -1:
continue
entry_type = rest[:brace_idx]
if entry_type.lower() in _BIBTEX_PSEUDO_ENTRIES:
continue
key_chars: list[str] = []
for ch in rest[brace_idx + 1 :]:
if ch.isspace() or ch in ",}":
break
key_chars.append(ch)
if key_chars:
out.append("".join(key_chars))
return out
_RST_UNDERLINE_CHARS = set("=-`:'\"~^_*+#<>.")
def rst_headings(content: str) -> list[str]:
"""reStructuredText's own real "setext"-style section titles (batch
I, E31-T29): a line of title text immediately followed by a line made
entirely of one repeated punctuation character, at least as long as
the title itself -- the real docutils convention (which punctuation
character means which heading *level* is document-specific, decided
by order of first appearance, not fixed by the character itself, so
every level is captured the same way rather than guessing a
hierarchy). A title line is required to contain at least one
alphanumeric character, which also means a heading's own optional
overline (the identical punctuation-only shape) is never mistaken for
title text.
"""
lines = content.splitlines()
out: list[str] = []
for title_line, underline_line in zip(lines, lines[1:]):
title = title_line.strip()
underline = underline_line.strip()
if not title or not any(ch.isalnum() for ch in title):
continue
if len(underline) < len(title):
continue
marker = underline[0]
if marker not in _RST_UNDERLINE_CHARS:
continue
if all(ch == marker for ch in underline):
out.append(title)
return out
def asciidoc_headings(content: str) -> list[str]:
"""AsciiDoc's own real ATX-style section-title syntax (batch I,
E31-T29) -- one or more leading `=` characters, a space, then the
title text, the identical shape `markdown_headings`'s `#` already is,
just AsciiDoc's own marker character. Fence-aware the same way that
function is: a delimited block (`----`, an open block `--`, or a
literal block `....`) can just as easily contain a line starting with
`=` that isn't a real heading.
"""
out: list[str] = []
fence: str | None = None
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
if fence is not None:
if trimmed == fence:
fence = None
continue
if trimmed in ("----", "....", "--"):
fence = trimmed
continue
equals = len(trimmed) - len(trimmed.lstrip("="))
if equals == 0 or equals > 6:
continue
rest = trimmed[equals:]
if not rest.startswith(" "):
continue
title = rest.strip()
if title:
out.append(title)
return out
def csv_header_columns(content: str, delimiter: str = ",") -> list[str]:
"""Extracts a CSV/TSV file's header row -- the first non-empty line's
column names, split on the file's own delimiter. No quoted-field or
embedded-delimiter handling (a real CSV parser's job, not a repo-map
heuristic's).
"""
for line in content.splitlines():
if line.strip():
return [c.strip().strip('"') for c in line.split(delimiter) if c.strip().strip('"')]
return []
def vue_script_blocks(source: str) -> str:
"""Extracts and concatenates every `<script ...>...</script>` block's
inner text from a Vue single-file component -- the only part of a
`.vue` file with real top-level declarations (`<template>`/`<style>`
never do). Returns an empty string if no script block is present.
Reused as-is for Svelte (batch A, `E31-T19`): a `.svelte` component
uses the identical `<script>` HTML-tag convention Vue does, and this
extraction was never actually Vue-specific -- it just looks for a
literal `<script`/`</script>` pair.
"""
out: list[str] = []
rest = source
while True:
open_start = rest.find("<script")
if open_start == -1:
break
after_open = rest[open_start:]
tag_end = after_open.find(">")
if tag_end == -1:
break
body_start = tag_end + 1
close_idx = after_open.find("</script>", body_start)
if close_idx == -1:
break
out.append(after_open[body_start:close_idx])
out.append("\n")
rest = after_open[close_idx + len("</script>") :]
return "".join(out)
def astro_frontmatter_block(source: str) -> str:
"""Extracts an Astro component's frontmatter block -- the real,
TypeScript-capable code between the file's opening `---` fence and
its closing `---` fence, each on its own line at column 0. Returns an
empty string if there's no frontmatter, or an opening fence with no
matching close.
"""
lines = source.splitlines(keepends=True)
if not lines or lines[0].rstrip("\r\n") != "---":
return ""
offset = len(lines[0])
body_start = offset
for line in lines[1:]:
if line.rstrip("\r\n") == "---":
return source[body_start:offset]
offset += len(line)
return ""
def _is_snakefile_name(filename: str) -> bool:
"""`Snakefile` -- Snakemake's canonical, extension-less workflow-file
name (batch K, E31-T35), the identical "reuse the extension-keyed
entry rather than duplicate it" shape `_is_cmake_list_name` already
established for `CMakeLists.txt` reusing `.cmake`'s row. Only the
canonical exact-case spelling is matched -- Snakemake's own docs use
this one spelling; there's no real lowercase convention the way
`Makefile`/`makefile` genuinely both occur in the wild.
"""
return filename == "Snakefile"
def gherkin_titles(content: str) -> list[str]:
"""Gherkin's own `Feature:`/`Rule:`/`Scenario:`/`Scenario Outline:`/
`Background:`/`Example:` line titles (batch K, E31-T35) -- prose text
after the keyword, not a single identifier, the same reasoning
`latex_section_headings`/`markdown_headings`/`rst_headings`/
`asciidoc_headings` already established (the keyword table's own
single-word name-capture would truncate "Feature: User can reset
their password" down to just "User").
Unlike this module's code extractors, indented lines are *not*
skipped: Gherkin's grammar carries no syntactic meaning in
indentation -- `Scenario:`/`Background:` lines are conventionally
indented two spaces under their `Feature:` purely for human
readability, and skipping them would silently drop every scenario
title, the file's own most useful "symbols."
"""
keywords = (
"Feature: ", "Rule: ", "Scenario Outline: ", "Scenario: ", "Background: ", "Example: ",
)
out: list[str] = []
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
for keyword in keywords:
if trimmed.startswith(keyword):
title = trimmed[len(keyword):].strip()
if title:
out.append(title)
break
return out
def batch_labels(content: str) -> list[str]:
"""Batch/`cmd.exe` script labels (batch L, E31-T36) -- `:label_name`,
the closest thing a `.bat`/`.cmd` file has to a named subroutine
(jumped to via `goto label_name`, entered/returned from via
`call :label_name`). Not a keyword-table row: a label is a bare
`:`-prefixed identifier, not `keyword<space>name`. The widespread
`:: comment` convention is never mistaken for a real label here:
stripping one leading `:` from `:: text` leaves a second `:` as the
very next character, which isn't an identifier character, so the
captured name is empty and the line is skipped -- no special case
needed.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
if not raw_line.startswith(":"):
continue
name = ""
for ch in raw_line[1:]:
if ch.isalnum() or ch in "_-":
name += ch
else:
break
if name:
out.append(name)
return out
def rexx_labels(content: str) -> list[str]:
"""REXX script labels (batch L, E31-T36) -- `LabelName:` alone on its
own line, the language's real subroutine-entry-point syntax (invoked
via `CALL LabelName`), mirroring `batch_labels`'s colon-adjacent-
identifier shape on the opposite side of the colon. Deliberately
requires the whole trimmed line to be nothing but the identifier plus
its trailing `:` -- REXX's grammar allows a label to share a line
with a following instruction, but that shape is rare in real scripts
and indistinguishable at this single-line-heuristic level from an
ordinary statement that merely contains a colon (a `SELECT`/`WHEN`
clause, say) -- left uncaptured rather than risking a false match.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.rstrip()
if not trimmed.endswith(":") or len(trimmed) < 2:
continue
name = trimmed[:-1]
if all(ch.isalnum() or ch == "_" for ch in name):
out.append(name)
return out
def qml_functions_and_signals(content: str) -> list[str]:
"""QML functions and signals (batch L, E31-T36) -- `function
name(...) { ... }` / `signal name(...)`. Deliberately not a
keyword-table row despite fitting that table's shape exactly: a real
QML file's grammar wraps its *entire* body in one root object block
(`Item { ... }`/`Rectangle { ... }`/...), so a `function`/`signal`
declaration sits at least one indent level deep in virtually every
real file -- the "only unindented lines count" convention would
silently produce an empty result for almost every real `.qml` file,
the identical false-negative-by-construction bug Batch K's own
Gherkin extractor caught, just triggered by indentation depth here.
`property` declarations are deliberately not captured: the declared
name isn't the first token after the keyword (`property int count:
0` -- the type comes first), which needs a different capture rule
than the two keywords here share -- a real, narrower, honest scope.
"""
out: list[str] = []
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
for keyword in ("function ", "signal "):
if trimmed.startswith(keyword):
name = ""
for ch in trimmed[len(keyword):]:
if ch.isalnum() or ch == "_":
name += ch
else:
break
if name:
out.append(name)
break
return out
def wat_named_functions(content: str) -> list[str]:
"""WebAssembly Text named functions (batch L, E31-T36) -- `(func
$name ...)`, following the exact same "indentation isn't a top-level
signal here" reasoning `qml_functions_and_signals` documents: a real
`.wat`/`.wast` file is conventionally one single outer `(module ...)`
form wrapping the entire file. Anonymous functions exported only via
an inline `(export "name")` clause, and functions referenced only by
numeric index, are both left uncaptured -- a real, narrower scope
than a full parser, the same tradeoff `gherkin_titles` accepts.
"""
out: list[str] = []
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
if trimmed.startswith("(func $"):
name = ""
for ch in trimmed[len("(func $"):]:
if ch.isalnum() or ch in "_-.":
name += ch
else:
break
if name:
out.append(name)
return out
def fortran_fixed_form_declarations(content: str) -> list[str]:
"""Fixed-form Fortran (`.f`/`.f77`/`.for`/`.fpp`) `SUBROUTINE`/
`FUNCTION`/`MODULE`/`PROGRAM` declarations (batch M, E31-T37) -- the
exact same keyword set (both cases) the free-form `f90`-family row
already uses; fixed- and free-form share declaration syntax.
What's new, and why this isn't one more extension on that row:
classic fixed-form's column rule requires real statements to start
at column 7 or later (columns 1-5 are the statement-label field,
column 6 the continuation marker), so a real declaration is *never*
actually unindented -- the "only unindented lines count" convention
would silently return an empty result for virtually every real
fixed-form file, the same design bug QML/WebAssembly Text already
caught for batch L. Comment lines are safe even with indentation
ignored: a real fixed-form comment's column 1 is `C`/`c`/`*`, not
whitespace, so `lstrip` never turns one into a keyword-led line.
"""
keywords = (
"subroutine ", "function ", "module ", "program ",
"SUBROUTINE ", "FUNCTION ", "MODULE ", "PROGRAM ",
)
out: list[str] = []
for raw_line in content.splitlines():
trimmed = raw_line.lstrip()
for keyword in keywords:
if trimmed.startswith(keyword):
name = ""
for ch in trimmed[len(keyword):]:
if ch.isalnum() or ch == "_":
name += ch
else:
break
if name:
out.append(name)
break
return out
def autohotkey_hotkeys(content: str) -> list[str]:
"""AutoHotkey (`.ahk`) hotkey/hotstring `Trigger::` definitions
(batch M, E31-T37) -- a top-level `TriggerText::` line (`^j::`,
`F1::`), the language's own primary orientation aid for a real
script the way a Makefile's targets or REXX's labels are for theirs.
Deliberately *not* attempted: AutoHotkey's other real top-level
construct, a user-defined function (`MyFunc(a, b) {`), has no
leading keyword at all to key off -- indistinguishable from
`if (x > 5) {`-shaped control flow by this table's model. So this
captures hotkeys/hotstrings only -- a real, honest, partial
extraction, the same call already made for Processing's `void`-only
coverage.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.rstrip()
if trimmed.startswith(";"):
continue
idx = trimmed.find("::")
if idx == -1:
continue
trigger = trimmed[:idx].strip()
if trigger:
out.append(trigger)
return out
def m4_macro_definitions(content: str) -> list[str]:
"""M4 macro definitions: `AC_DEFUN(`, `m4_define(`, `define(` at top level.
Mirrors the engine's `m4_macro_definitions` (batch N, `E31-T40`; ported
`E31-T42`): unindented lines only -- a `define(` nested inside another
macro's body arrives indented and is skipped -- and the macro name may
arrive in either quoting convention (`[name]` or `` `name' ``), so one
leading `[` or backtick is stripped before the name is read.
"""
prefixes = ("AC_DEFUN(", "m4_define(", "define(")
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.lstrip()
for prefix in prefixes:
if not trimmed.startswith(prefix):
continue
rest = trimmed[len(prefix):]
if rest[:1] in ("[", "`"):
rest = rest[1:]
name = ""
for ch in rest:
if not (ch.isalnum() or ch == "_"):
break
name += ch
if name:
out.append(name)
break
return out
def xquery_functions(content: str) -> list[str]:
"""XQuery function declarations: unindented `declare function ` lines.
Mirrors the engine's `xquery_functions` (batch N, `E31-T40`; ported
`E31-T42`): the captured name keeps its namespace prefix
(`local:greet`) -- colons, hyphens, and dots are all legal in a QName,
so all three stay in the capture set alongside `_`.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.lstrip()
if not trimmed.startswith("declare function "):
continue
rest = trimmed[len("declare function "):]
name = ""
for ch in rest:
if not (ch.isalnum() or ch in "_:-."):
break
name += ch
if name:
out.append(name)
return out
def css_selectors(content: str) -> list[str]:
"""CSS/LESS top-level selectors: unindented lines ending in `{`.
Mirrors the engine's `css_selectors` (batch O, `E31-T43`; ported
`E31-T44`): the raw, unstripped text before a rule's opening brace,
split on commas -- `.header`, `@media (max-width: 600px)`, `:root`,
and a LESS mixin *definition* `.flex-center()` are each kept
verbatim, parens included. That raw-text model is exactly why LESS
mixins needed no disambiguation pass (the gap batch J declined):
`.flex-center()` and `.flex-center` are simply two different
strings. Indented nested rules are skipped; a mixin *call*
(semicolon-terminated, no brace at all) still yields nothing -- the
honest, narrower gap that survived the engine's Batch O fix.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.strip()
if not trimmed.endswith("{"):
continue
before_brace = trimmed[:-1].strip()
if not before_brace:
continue
for part in before_brace.split(","):
name = part.strip()
if name:
out.append(name)
return out
def smalltalk_class_definitions(content: str) -> list[str]:
"""Smalltalk class definitions: unindented `Receiver subclass: Name`.
Mirrors the engine's `smalltalk_class_definitions` (batch O,
`E31-T43`; ported `E31-T44`): Pharo/Squeak's classic
`Object subclass: #Animal` (the name a symbol literal) and GNU
Smalltalk's bracket form `Object subclass: Animal [ ... ]` both
match -- both dialects share the identical `subclass: ` keyword text
right after the receiver. Method definitions are message-pattern-
based (`bark`, `add: x to: y`) with no leading keyword at all -- the
same honest "not every declaration fits this table" gap Prolog's
predicate clauses and Haskell's name-first functions already have.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.lstrip()
idx = trimmed.find("subclass: ")
if idx == -1:
continue
rest = trimmed[idx + len("subclass: "):].lstrip()
rest = rest.removeprefix("#")
name = ""
for ch in rest:
if not (ch.isalnum() or ch == "_"):
break
name += ch
if name:
out.append(name)
return out
def handlebars_block_and_partial_names(content: str) -> list[str]:
"""Handlebars/Mustache block helpers and partial includes.
Mirrors the engine's `handlebars_block_and_partial_names` (batch O,
`E31-T43`; ported `E31-T44`): block-helper openings (`{{#name}}`,
including the partial-block form `{{#> name}}`) and partial includes
(`{{> name}}`, `{{>name}}`) -- the two real structural units a
template actually declares. Deliberately *not* line-anchored like
this module's other dedicated extractors: tags are valid anywhere
inline within a line of surrounding HTML, so this scans the raw
content for the two literal prefixes instead of assuming one tag per
unindented line. Plain `{{value}}` interpolation and `{{/close}}`
tags are deliberately not symbols -- they don't introduce a new
named structural unit the way an opening block or a partial include
does.
"""
out: list[str] = []
for prefix in ("{{#", "{{>"):
start = 0
while True:
idx = content.find(prefix, start)
if idx == -1:
break
start = idx + len(prefix)
rest = content[start:].removeprefix(">").lstrip()
name = ""
for ch in rest:
if not (ch.isalnum() or ch in "_-./"):
break
name += ch
if name:
out.append(name)
return out
def _template_tag_names(content: str, keywords: tuple[str, ...]) -> list[str]:
"""Shared `{% keyword name %}` scan for the Jinja/Twig and Liquid
extractors below: for every `{%` in the raw content (not
line-anchored -- a template tag is valid anywhere inline in the
surrounding markup, the same reason `handlebars_block_and_partial_names`
isn't), skip the optional whitespace-control `-`, then take the
identifier that follows the first matching keyword. Not part of the
engine's public surface either (there it is the inlined body of two
sibling functions); factored here so the two ports stay verifiably
identical to each other.
"""
out: list[str] = []
start = 0
while True:
idx = content.find("{%", start)
if idx == -1:
break
start = idx + 2
rest = content[start:].lstrip()
rest = rest.removeprefix("-").lstrip()
for keyword in keywords:
if rest.startswith(keyword):
after = rest[len(keyword):].lstrip()
name = ""
for ch in after:
if not (ch.isalnum() or ch == "_"):
break
name += ch
if name:
out.append(name)
break
return out
def jinja_style_block_and_macro_names(content: str) -> list[str]:
"""Jinja2/Twig `{% block name %}` and `{% macro name(...) %}` names.
Mirrors the engine's `jinja_style_block_and_macro_names` (batch P,
`E31-T45`; ported `L5-T01`): both languages' own real named,
reusable structural units. Shared by both extensions rather than
each getting its own: Twig's `{% %}`/`{{ }}` delimiters and its
`block`/`macro`/`extends`/`include` keywords were modeled directly
on Django/Jinja-style templates -- a real shared lineage, not a
coincidental keyword collision. Handles the whitespace-control tag
variants (`{%-`/`-%}`) both languages support.
Liquid (`.liquid`) looks like a third member of this family at a
glance -- the identical `{% %}` delimiters -- but deliberately does
NOT reuse this extractor: Liquid has no `block`/`macro`/template-
inheritance model at all, so every real Liquid file would silently
come back empty. See `liquid_assign_and_capture_names` instead.
Honest scope: a raw textual scan, not a real parser, so a tag written
inside a `{% comment %}`/`{% endcomment %}` pair is still picked up
as if it were live -- the same class of limitation `css_selectors`
already has for `/* */` comments.
"""
return _template_tag_names(content, ("block ", "macro "))
def liquid_assign_and_capture_names(content: str) -> list[str]:
"""Liquid `{% assign name = ... %}` and `{% capture name %}` names.
Mirrors the engine's `liquid_assign_and_capture_names` (batch P,
`E31-T45`; ported `L5-T01`): Liquid's own real named-variable
constructs. See `jinja_style_block_and_macro_names` for why Liquid
gets this separate extractor despite the shared `{% %}` delimiter
syntax -- reusing the Jinja/Twig extractor would have been a silent
no-op for every real Liquid file, not a genuine shared mechanism the
way `.less` reusing `css_selectors` is.
"""
return _template_tag_names(content, ("assign ", "capture "))
def _scriptlet_keyword_names(content: str, keyword: str) -> list[str]:
"""Shared by `erb_embedded_ruby_def_names` and
`ejs_embedded_js_function_names` below (mirrors the engine's private
`scriptlet_keyword_names`): both ERB and EJS wrap a general-purpose
scripting language in `<% %>` tags rather than having template-
native named constructs of their own, so the real extractable symbol
is whatever the *embedded* language's own definition keyword
produces -- this finds each `<% ... %>` tag's contents and looks for
`keyword` inside it. The output/whitespace-control tag variants
(`<%=`, `<%-`, `-%>`, `_%>`) need no special handling since none of
them move the closing `%>`. A word-boundary check on the character
right before a match guards against Ruby's own `undef name` (which
textually contains `def `) or a bareword like `somedef ` being
mistaken for a definition -- a genuine false-positive class, not a
hypothetical one.
"""
out: list[str] = []
search_from = 0
while True:
rel_start = content.find("<%", search_from)
if rel_start == -1:
break
start = rel_start + 2
rel_end = content.find("%>", start)
if rel_end == -1:
break
inner = content[start:rel_end]
kw_idx = -1
while True:
kw_idx = inner.find(keyword, kw_idx + 1)
if kw_idx == -1:
break
preceded_by_word_char = kw_idx > 0 and (
inner[kw_idx - 1].isalnum() or inner[kw_idx - 1] == "_"
)
if preceded_by_word_char:
continue
after = inner[kw_idx + len(keyword):].lstrip()
name = ""
for ch in after:
if not (ch.isalnum() or ch == "_"):
break
name += ch
if name:
out.append(name)
break
search_from = rel_end + 2
return out
def erb_embedded_ruby_def_names(content: str) -> list[str]:
"""Ruby `def name` inside ERB (`.erb`) scriptlet tags.
Mirrors the engine's `erb_embedded_ruby_def_names` (batch P,
`E31-T45`; ported `L5-T01`). Real ERB view templates rarely define
named methods, but ERB used as a general Ruby templating tool --
Rake generators, config-file templating -- often does.
`<%= render partial: "..." %>` is deliberately left out: an
edge-resolution problem, not a symbol.
"""
return _scriptlet_keyword_names(content, "def ")
def ejs_embedded_js_function_names(content: str) -> list[str]:
"""JS `function name` inside EJS (`.ejs`) scriptlet tags.
Mirrors the engine's `ejs_embedded_js_function_names` (batch P,
`E31-T45`; ported `L5-T01`) -- identical `<% %>` tag delimiters to
ERB, a different embedded language and keyword, one shared scan.
"""
return _scriptlet_keyword_names(content, "function ")
def robot_keyword_and_test_case_names(content: str) -> list[str]:
"""Robot Framework (`.robot`) keyword and test-case names.
Mirrors the engine's `robot_keyword_and_test_case_names` (batch P,
`E31-T45`; ported `L5-T01`): the name is whatever unindented line
follows directly under a `*** Keywords ***` or `*** Test Cases ***`
section header (RF's plain-text cell format separates a name from
inline arguments with two-or-more spaces, the same convention this
splits on); the steps implementing each one are indented underneath.
`*** Settings ***`/`*** Variables ***` sections and anything before
the first section header are deliberately not scanned. Robot's own
pipe-delimited cell format is a real, stated gap.
"""
out: list[str] = []
in_target_section = False
for raw_line in content.splitlines():
trimmed = raw_line.strip()
if trimmed.startswith("***"):
upper = trimmed.upper()
in_target_section = "KEYWORDS" in upper or "TEST CASE" in upper
continue
if not in_target_section or not trimmed:
continue
if raw_line.startswith((" ", "\t")):
continue
name = trimmed.split(" ", 1)[0].strip()
if name:
out.append(name)
return out
_SHARED_EXTENSION_CLAIMS: dict[str, tuple[tuple[str, bool, tuple[str, ...]], ...]] = {
"h": (("c", True, ("#include <stdio.h>", "#include <stdlib.h>", "#include <string.h>", "typedef struct")), ("cpp", False, ("template <", "template<", "namespace ", "class ", "public:", "virtual ", "std::", "#include <string>", "#include <vector>", "extern \"C\"")), ("m", False, ("#import", "@interface", "@implementation", "@protocol", "@class ", "@end", "NS_ASSUME_NONNULL", "NSString")),),
"hh": (("cpp", True, ("template <", "template<", "namespace ", "class ", "public:", "virtual ", "std::", "#include <string>", "#include <vector>", "extern \"C\"")), ("hack", False, ("<?hh", "<<__", "async function ", "HH\\", "shape(", "vec<", "dict<", "keyset<", "Awaitable<", "$", "public function ", "namespace ", "function ")),),
"m": (("m", True, ("#import", "@interface", "@implementation", "@protocol", "@class ", "@end", "NS_ASSUME_NONNULL", "NSString")), ("matlab", False, ("function ", "classdef ", "%%", "%{", "disp(", "fprintf(", "zeros(", "ones(", "numel(", "elseif ", "end % ")), ("wl", False, ("(* ", "BeginPackage[", "EndPackage[", "Module[", "Block[", "Print[", "Manipulate[", "Plot[", "::usage", "] := ")),),
"pl": (("pl", True, ("use strict", "use warnings", "my $", "my @", "my %", "sub ", "=~", "@_", "#!/usr/bin/perl", "#!/usr/bin/env perl")), ("pro", False, (":- ", "?- ", ":-\n", "halt.", "consult(")), ("raku", False, ("use v6", "unit module ", "unit class ", "sub MAIN", "say ", "multi sub ", "multi method ", "is export", "my %", "->")),),
"pm": (("pl", True, ("use strict", "use warnings", "my $", "my @", "my %", "sub ", "=~", "@_", "#!/usr/bin/perl", "#!/usr/bin/env perl")), ("raku", False, ("use v6", "unit module ", "unit class ", "sub MAIN", "say ", "multi sub ", "multi method ", "is export", "my %", "->")),),
"pp": (("pas", True, ("program ", "unit ", "procedure ", "function ", "uses ", "begin\n", "end.", "interface\n", "implementation\n")), ("puppet", False, ("ensure =>", "ensure=>", "class ", "node ", "define ", "include ", "$::", "file {", "package {", "service {", "exec {", "notify {")),),
"pro": (("pro", True, (":- ", "?- ", ":-\n", "halt.", "consult(")), ("pri", False, ("TEMPLATE", "SOURCES", "HEADERS", "QT +=", "CONFIG +=", "TARGET")),),
"sql": (("sql", True, ("CREATE TABLE", "SELECT ", "INSERT INTO", "ALTER TABLE", "CREATE INDEX")), ("pls", False, ("CREATE OR REPLACE PACKAGE", "PACKAGE BODY", "CREATE OR REPLACE PROCEDURE", "CREATE OR REPLACE FUNCTION", "CREATE OR REPLACE TRIGGER", "DBMS_OUTPUT", "EXCEPTION\n", " WHEN OTHERS", "END;", "IS\nBEGIN", "AS\nBEGIN", "PRAGMA ")),),
}
_SNIFF_HEAD_BYTES = 8 * 1024
def _dispatch_key_for(extension: str, content: str) -> str:
"""The row a shared extension dispatches to (engine `lang::sniff::dispatch_key_for`, L1-T01).
Owner and every secondary claim are scored by distinct hints found in
the first 8 KiB; the highest wins and ties go to the owner, so a
marker-free body classifies exactly as before.
"""
claims = _SHARED_EXTENSION_CLAIMS.get(extension)
if not claims:
return extension
head = content[:_SNIFF_HEAD_BYTES]
best_key, best_score = claims[0][0], -1
for key, is_owner, hints in claims:
score = sum(1 for h in hints if h and h in head)
if score > best_score or (is_owner and score == best_score):
best_key, best_score = key, score
return best_key
def matlab_definitions(content: str) -> list[str]:
"""MATLAB `function [out] = name(args)` / `function name(args)` and `classdef Name` (L1-T02)."""
out: list[str] = []
for raw in content.splitlines():
if raw.startswith((" ", "\t")):
continue
line = raw.rstrip()
if line.startswith("function "):
head = line[len("function "):].split("(")[0]
target = head.rsplit("=", 1)[-1].strip()
elif line.startswith("classdef "):
rest = line[len("classdef "):].strip()
if rest.startswith("("):
rest = rest.split(")", 1)[1] if ")" in rest else ""
target = rest.strip()
else:
continue
name = _ident_prefix(target)
if name:
out.append(name)
return out
def puppet_definitions(content: str) -> list[str]:
"""Puppet `class a::b`, `define a::b`, `node 'name'`, `type`, `plan`, `function` (L1-T02)."""
out: list[str] = []
for raw in content.splitlines():
if raw.startswith((" ", "\t")):
continue
for kw in ("class ", "define ", "node ", "type ", "plan ", "function "):
if raw.startswith(kw):
rest = raw[len(kw):].lstrip().lstrip("'\"")
name = "".join(_takewhile(rest, lambda c: c.isalnum() or c in "_:.-"))
if name:
out.append(name)
break
return out
def wolfram_definitions(content: str) -> list[str]:
"""Wolfram `name[args] :=`, `name[args] =`, `name::usage`, `BeginPackage["Ctx`"]` (L1-T02)."""
out: list[str] = []
for raw in content.splitlines():
if raw.startswith((" ", "\t", "(*")):
continue
line = raw.rstrip()
if line.startswith('BeginPackage["'):
ctx = line[len('BeginPackage["'):].split('"')[0]
if ctx:
out.append(ctx)
continue
op = line.find(":=")
if op < 0:
op = line.find("::usage")
if op < 0:
eq = line.find(" = ")
br = line.find("[")
op = eq if (eq >= 0 and br >= 0 and br < eq) else -1
if op < 0:
continue
name = "".join(_takewhile(line[:op], lambda c: c.isalnum() or c in "$`"))
if name and name not in out:
out.append(name)
return out
def tla_definitions(content: str) -> list[str]:
"""TLA+ module header, THEOREM/LEMMA/ASSUME, CONSTANT(S)/VARIABLE(S), `Name ==` (L1-T02)."""
out: list[str] = []
def ident(s: str) -> str:
return "".join(_takewhile(s.lstrip(), lambda c: c.isalnum() or c in "_!"))
for raw in content.splitlines():
if raw.startswith((" ", "\t", "\\*")):
continue
line = raw.rstrip()
if line.startswith("----") and "MODULE " in line:
name = ident(line.split("MODULE ", 1)[1])
if name:
out.append(name)
continue
keyword_line = False
for kw in ("THEOREM ", "LEMMA ", "ASSUME ", "CONSTANTS ", "CONSTANT ", "VARIABLES ", "VARIABLE "):
if line.startswith(kw):
keyword_line = True
for part in line[len(kw):].split(","):
name = ident(part)
if name and name not in out:
out.append(name)
if keyword_line:
continue
op = line.find(" == ")
if op >= 0:
name = ident(line[:op])
if name and name not in out:
out.append(name)
return out
def stylus_top_level_names(content: str) -> list[str]:
"""Stylus unindented variables, mixins and selectors (braces are optional) (L1-T02)."""
out: list[str] = []
for raw in content.splitlines():
if raw.startswith((" ", "\t")):
continue
line = raw.rstrip()
if not line or line.startswith(("//", "/*", "@", "}")):
continue
name = "".join(_takewhile(line, lambda c: c.isalnum() or c in "_-$.#:")).rstrip(":")
if name and name not in out:
out.append(name)
return out
def _ident_prefix(s: str) -> str:
return "".join(_takewhile(s, lambda c: c.isalnum() or c == "_"))
def _takewhile(s: str, pred) -> list[str]:
out: list[str] = []
for c in s:
if not pred(c):
break
out.append(c)
return out
def lookml_block_names(content: str) -> list[str]:
"""LookML top-level block names -- `view: orders {`, `explore: trips {`.
Mirrors the engine's `lookml_block_names` (batch P's second landing,
`E31-T46`; ported `L5-T01`): an unindented `key: name {` line
declares the file's own structural unit, and the *name* (not the
key) is the orientation symbol. Nested `dimension:`/`measure:`
blocks are indented inside their view in every real LookML file, so
the unindented-only rule keeps this honestly top-level. `include:
"*.view.lkml"` lines carry no brace and are skipped -- an include is
a resolver concern, and its wildcard form doesn't name one file.
"""
out: list[str] = []
for raw_line in content.splitlines():
if raw_line.startswith((" ", "\t")):
continue
trimmed = raw_line.strip()
if not trimmed.endswith("{"):
continue
before_brace = trimmed[:-1]
if ":" not in before_brace:
continue
key, name_part = before_brace.split(":", 1)
if not key or not all(ch.isalnum() or ch == "_" for ch in key):
continue
name = ""
for ch in name_part.strip():
if not (ch.isalnum() or ch == "_"):
break
name += ch
if name:
out.append(name)
return out
def _dedup_ordered(values: list[str]) -> list[str]:
"""First-occurrence-wins dedup, matching the engine's `dedup`."""
seen: set[str] = set()
out: list[str] = []
for v in values:
if v not in seen:
seen.add(v)
out.append(v)
return out
def _ident_before_paren(text: str) -> str | None:
head = text.split("(")[0].rstrip()
if not head:
return None
name = head.replace("*", " ").replace("&", " ").split(" ")[-1]
if name and all(c.isalnum() or c == "_" for c in name):
return name
return None
def stata_programs(content: str) -> list[str]:
"""Stata `.do`/`.ado`/`.mata` (L6-T05): `program [define] name`, and
Mata `function name(`. `capture`/`cap` prefixes are stripped first;
`program drop|list|dir` are commands, not definitions, so they are
excluded by name."""
out: list[str] = []
for line in content.splitlines():
trimmed = line.strip()
for prefix in ("capture ", "cap "):
if trimmed.startswith(prefix):
trimmed = trimmed[len(prefix):].strip()
if trimmed.startswith("*") or trimmed.startswith("//"):
continue
rest = None
for prefix in ("program ", "prog "):
if trimmed.startswith(prefix):
rest = trimmed[len(prefix):]
break
if rest is not None:
for define in ("define ", "def "):
if rest.startswith(define):
rest = rest[len(define):]
break
rest = rest.strip()
name = rest.replace(",", " ").split(" ")[0]
if name and name not in ("drop", "list", "dir"):
out.append(name)
continue
idx = trimmed.find("function ")
if idx != -1 and (idx == 0 or trimmed[idx - 1] == " "):
name = trimmed[idx + len("function "):].split("(")[0].strip()
if name:
out.append(name)
return _dedup_ordered(out)
def devicetree_nodes(content: str) -> list[str]:
"""Devicetree `.dts`/`.dtsi`/`.overlay` (L6-T06): every labelled node
(`label: node@addr {` -> `label`), every overlay reference
(`&label {` -> `&label`), and the root's unlabelled children
(`name {` at depth 1)."""
out: list[str] = []
depth = 0
for line in content.splitlines():
trimmed = line.strip()
if (
trimmed.startswith("//")
or trimmed.startswith("#")
or trimmed.startswith("*")
or trimmed.startswith("/*")
):
continue
if trimmed.endswith("{"):
head = trimmed[:-1].strip()
if ":" in head:
label = head.split(":", 1)[0].strip()
if label and " " not in label:
out.append(label)
elif head.startswith("&"):
out.append("&" + head[1:].strip())
elif depth == 1 and head and head != "/":
out.append(head.split("@")[0])
depth += 1
depth = max(0, depth - trimmed.count("};"))
return _dedup_ordered(out)
def kconfig_symbols(content: str) -> list[str]:
"""`Kconfig` (L6-T06): `config`/`menuconfig` symbol names and
`menu`/`mainmenu` titles."""
out: list[str] = []
for line in content.splitlines():
trimmed = line.strip()
for keyword, label in (
("config ", "config"),
("menuconfig ", "config"),
("menu ", "menu"),
("mainmenu ", "menu"),
):
if trimmed.startswith(keyword):
name = trimmed[len(keyword):].strip().strip('"')
if name:
out.append(f"{label} {name}")
return _dedup_ordered(out)
def _godot_attr(head: str, key: str) -> str | None:
idx = head.find(key + "=")
if idx == -1:
return None
rest = head[idx + len(key) + 1:]
if rest.startswith('"'):
return rest[1:].split('"')[0]
return rest.replace("]", " ").split(" ")[0]
def godot_scene_nodes(content: str) -> list[str]:
"""Godot `.tscn`/`.tres`/`.escn` (L6-T06): `[node name="X" type="Y"]`
-> `Y X` (`node X` when the type is inherited), `[sub_resource
type="X" id="Y"]` -> `X Y`, and `[gd_resource type="X"]` -> `X`."""
out: list[str] = []
for line in content.splitlines():
trimmed = line.strip()
if not (trimmed.startswith("[") and trimmed.endswith("]")):
continue
head = trimmed[1:-1]
if head.startswith("node "):
rest = head[len("node "):]
name = _godot_attr(rest, "name") or ""
kind = _godot_attr(rest, "type") or "node"
if name:
out.append(f"{kind} {name}")
elif head.startswith("sub_resource "):
rest = head[len("sub_resource "):]
kind, ident = _godot_attr(rest, "type"), _godot_attr(rest, "id")
if kind and ident:
out.append(f"{kind} {ident}")
elif head.startswith("gd_resource "):
kind = _godot_attr(head[len("gd_resource "):], "type")
if kind:
out.append(kind)
return _dedup_ordered(out)
def unity_asset_names(content: str) -> list[str]:
"""Unity YAML assets (L6-T06): every `m_Name:`, labelled by the
document's own object kind (`GameObject`, `Material`, ...)."""
out: list[str] = []
kind = ""
for line in content.splitlines():
if (
line
and not line[0].isspace()
and line.endswith(":")
and not line.startswith("-")
and not line.startswith("%")
):
kind = line[:-1]
trimmed = line.strip()
if trimmed.startswith("m_Name:"):
value = trimmed[len("m_Name:"):].strip()
if value:
out.append(f"{kind} {value}" if kind else value)
return _dedup_ordered(out)
def qmake_symbols(content: str) -> list[str]:
"""qmake `.pri`/`.prf` (L6-T06): `TARGET`/`TEMPLATE` keep their value;
every other assigned upper-case variable is a symbol by name."""
out: list[str] = []
for line in content.splitlines():
trimmed = line.strip()
if trimmed.startswith("#") or "=" not in trimmed:
continue
lhs, rhs = trimmed.split("=", 1)
name = lhs.rstrip("+-*~").strip()
if not name or not all(c.isupper() or c == "_" or c == "." for c in name):
continue
if name in ("TARGET", "TEMPLATE"):
out.append(f"{name} {rhs.strip().rstrip(chr(92)).strip()}")
else:
out.append(name)
return _dedup_ordered(out)
def metal_functions(content: str) -> list[str]:
"""Metal `.metal` (L6-T06/T07): `kernel`/`vertex`/`fragment` entry
points labelled by stage, plus `struct` names."""
out: list[str] = []
for line in content.splitlines():
trimmed = line.strip()
if trimmed.startswith("//"):
continue
for stage in ("kernel ", "vertex ", "fragment "):
if trimmed.startswith(stage):
name = _ident_before_paren(trimmed[len(stage):])
if name:
out.append(f"{stage.strip()} {name}")
if trimmed.startswith("struct "):
rest = trimmed[len("struct "):]
name = rest.replace("{", " ").replace(":", " ").split(" ")[0].strip()
if name:
out.append(f"struct {name}")
return _dedup_ordered(out)
def symbols_for_file(filename: str, extension: str | None, content: str) -> list[str]:
"""The single dispatch point `walk`/`generate` use to decide how to
extract a file's symbols -- filename-based checks first
(`Dockerfile`/`Makefile` have no extension at all to dispatch on),
then the config-format extensions with their own dedicated
extractor, then Vue/Astro (whose real script text has to be pulled
out of surrounding template markup first, via `vue_script_blocks`/
`astro_frontmatter_block`, run through the same `"ts"` keyword table
a plain `.ts` file uses -- inheriting that table's own stated gap: a
`const foo = () => {}` arrow-function binding, idiomatic in both, has
no leading keyword and isn't caught), then the general keyword-table
path `extract_symbols` already covers.
"""
if _is_dockerfile_name(filename):
return dockerfile_stages(content)
if _is_makefile_name(filename):
return makefile_targets(content)
if _is_bazel_build_name(filename):
return starlark_build_targets(content)
if _is_dotenv_name(filename):
return dotenv_keys(content)
if _is_editorconfig_name(filename):
return ini_section_headers(content)
if _is_cmake_list_name(filename):
return extract_symbols(content, "cmake")
if _is_snakefile_name(filename):
return extract_symbols(content, "smk")
if _is_justfile_name(filename):
return justfile_recipes(content)
if extension in ("yaml", "yml", "sls", "cwl"):
return yaml_top_level_keys(content)
if extension == "json":
return json_top_level_keys(content)
if extension == "toml":
return toml_symbols(content)
if extension in ("tf", "tfvars", "hcl"):
return terraform_symbols(content)
if extension == "cue":
return cue_symbols(content)
if extension in ("do", "ado", "mata"):
return stata_programs(content)
if extension in ("dts", "dtsi", "overlay"):
return devicetree_nodes(content)
if extension in ("tscn", "tres", "escn"):
return godot_scene_nodes(content)
if extension in (
"unity",
"prefab",
"anim",
"controller",
"cubemap",
"flare",
"guiskin",
"physicsmaterial",
"rendertexture",
):
return unity_asset_names(content)
if extension in ("pri", "prf"):
return qmake_symbols(content)
if extension == "metal":
return metal_functions(content)
if extension in ("ini", "cfg", "conf"):
return ini_section_headers(content)
if extension == "csv":
return csv_header_columns(content, ",")
if extension == "tsv":
return csv_header_columns(content, "\t")
if extension == "odin":
return odin_symbols(content)
if extension in ("xml", "xslt", "xsl"):
return xml_top_level_elements(content)
if extension == "properties":
return properties_top_level_namespaces(content)
if extension == "mk":
return makefile_targets(content)
if extension == "tex":
return latex_section_headings(content)
if extension == "md":
return markdown_headings(content)
if extension == "nix":
return nix_let_bindings(content)
if extension == "bib":
return bibtex_entry_keys(content)
if extension == "rst":
return rst_headings(content)
if extension == "adoc":
return asciidoc_headings(content)
if extension == "feature":
return gherkin_titles(content)
if extension in ("bat", "cmd"):
return batch_labels(content)
if extension in ("rexx", "pprx", "rex"):
return rexx_labels(content)
if extension == "qml":
return qml_functions_and_signals(content)
if extension in ("wast", "wat"):
return wat_named_functions(content)
if extension in ("f", "f77", "for", "fpp"):
return fortran_fixed_form_declarations(content)
if extension == "ahk":
return autohotkey_hotkeys(content)
if extension in ("m4", "mc"):
return m4_macro_definitions(content)
if extension in ("xquery", "xq", "xql", "xqm", "xqy"):
return xquery_functions(content)
if extension in ("css", "less"):
return css_selectors(content)
if extension == "st":
return smalltalk_class_definitions(content)
if extension in ("hbs", "handlebars", "mustache"):
return handlebars_block_and_partial_names(content)
if extension in ("jinja", "jinja2", "j2", "twig"):
return jinja_style_block_and_macro_names(content)
if extension == "liquid":
return liquid_assign_and_capture_names(content)
if extension == "erb":
return erb_embedded_ruby_def_names(content)
if extension == "ejs":
return ejs_embedded_js_function_names(content)
if extension == "robot":
return robot_keyword_and_test_case_names(content)
if extension == "lkml":
return lookml_block_names(content)
if extension is not None:
extension = _dispatch_key_for(extension, content)
if extension == "matlab":
return matlab_definitions(content)
if extension == "puppet":
return puppet_definitions(content)
if extension in ("wl", "wlt", "nb", "mathematica"):
return wolfram_definitions(content)
if extension == "tla":
return tla_definitions(content)
if extension == "styl":
return stylus_top_level_names(content)
if extension in ("vue", "svelte"):
return extract_symbols(vue_script_blocks(content), "ts")
if extension == "astro":
return extract_symbols(astro_frontmatter_block(content), "ts")
if extension is not None:
return extract_symbols(content, extension)
return []
def extension_of(path: Path) -> str | None:
suffix = path.suffix
return suffix[1:].lower() if suffix else None
@dataclass
class FileMap:
path: str
symbols: list[str] = field(default_factory=list)
def walk(root: Path, *, max_depth: int) -> list[Path]:
"""Lists files under `root` up to `max_depth` directory levels deep
(0 = files directly in `root`), skipping `SKIPPED_DIR_NAMES`. Sorted
for deterministic output.
"""
files: list[Path] = []
root = root.resolve()
for path in sorted(root.rglob("*")):
if any(part in SKIPPED_DIR_NAMES for part in path.relative_to(root).parts[:-1]):
continue
if not path.is_file():
continue
depth = len(path.relative_to(root).parts) - 1
if depth > max_depth:
continue
files.append(path)
return files
def generate(root: Path, *, max_depth: int = 6) -> list[FileMap]:
"""Builds the repo map: every scannable file under `root` (subject to
`walk`'s skip-list and depth cap) paired with its extracted top-level
symbols. Files with an unrecognized extension -- or no extension at
all -- are still listed (empty symbol list unless `symbols_for_file`
has dedicated filename-based dispatch, as it does for `Dockerfile`/
`Makefile`) -- the tree shape itself is part of the orientation
value, and a file is never silently dropped from it.
"""
root = root.resolve()
maps: list[FileMap] = []
for path in walk(root, max_depth=max_depth):
extension = extension_of(path)
try:
content = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
maps.append(FileMap(path=str(path.relative_to(root))))
continue
symbols = symbols_for_file(path.name, extension, content)
maps.append(FileMap(path=str(path.relative_to(root)), symbols=symbols))
return maps
def render_text(maps: list[FileMap]) -> str:
if not maps:
return "(no scannable files found)"
lines = []
for m in maps:
if m.symbols:
lines.append(f"{m.path}: {', '.join(m.symbols)}")
else:
lines.append(m.path)
return "\n".join(lines)
@dataclass
class DiagramNode:
file: Path
relative: str
symbols: list[str] = field(default_factory=list)
def is_diagram_worthy(name: str, extension: str | None) -> bool:
"""Mirrors the real engine's own `is_diagram_worthy` (`E31-T30`): a
file counts as node-worthy if `repo_map` would extract real symbols
from it — either by extension (`is_recognized_source_extension`,
itself derived from repo-map's own registry) or by one of the
canonical extension-less/dotfile names repo-map dispatches on
filename alone. Ported logic uses the exact same predicates
`symbols_for_file` itself already dispatches on, so nothing here can
silently drift out of sync with what a node actually renders.
"""
if extension is not None and is_recognized_source_extension(extension):
return True
return (
_is_dockerfile_name(name)
or _is_makefile_name(name)
or _is_bazel_build_name(name)
or _is_cmake_list_name(name)
or _is_justfile_name(name)
or _is_dotenv_name(name)
or _is_editorconfig_name(name)
)
def _extension_of(path: Path) -> str | None:
ext = path.suffix.lstrip(".")
return ext.lower() if ext else None
def _walk_diagram_nodes(directory: Path, root: Path, out: list[DiagramNode]) -> None:
try:
entries = sorted(directory.iterdir(), key=lambda p: p.name)
except OSError:
return
for entry in entries:
name = entry.name
is_recognized_dotfile = _is_dotenv_name(name) or _is_editorconfig_name(name) or _is_justfile_name(name)
if name.startswith(".") and not is_recognized_dotfile:
continue
if entry.is_dir():
if name not in SKIPPED_DIR_NAMES:
_walk_diagram_nodes(entry, root, out)
continue
extension = _extension_of(entry)
if not is_diagram_worthy(name, extension):
continue
try:
content = entry.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
continue
symbols = symbols_for_file(name, extension, content)
out.append(DiagramNode(file=entry, relative=entry.relative_to(root).as_posix(), symbols=symbols))
def build_diagram(root: Path) -> tuple[list[DiagramNode], list[tuple[Path, Path]]]:
"""Walks `root`, collecting one `DiagramNode` per file in a repo-map-
recognized language (`is_diagram_worthy`), then pairs the discovered
nodes with dependency-graph's own resolved import edges (`build`,
ported above) — node coverage (90 languages) is wider than edge
coverage (60), by design; see the module docstring.
"""
nodes: list[DiagramNode] = []
_walk_diagram_nodes(root, root, nodes)
nodes.sort(key=lambda n: n.relative)
graph = build(root)
edges: list[tuple[Path, Path]] = []
for node in nodes:
targets = sorted(graph.imports_of(node.file), key=lambda p: p.as_posix())
for target in targets:
edges.append((node.file, target))
return nodes, edges
def neighborhood(
focus: list[Path], nodes: list[DiagramNode], edges: list[tuple[Path, Path]]
) -> tuple[list[DiagramNode], list[tuple[Path, Path]]]:
"""Restricts `nodes`/`edges` to `focus` plus each focus file's direct
(one-hop, not transitive) importers and imports — a diagram-scoping
tool, not dependency-graph's own transitive blast-radius query.
"""
focus_set = set(focus)
keep = set(focus_set)
kept_edges: list[tuple[Path, Path]] = []
for source, target in edges:
if source in focus_set or target in focus_set:
keep.add(source)
keep.add(target)
kept_edges.append((source, target))
kept_nodes = [n for n in nodes if n.file in keep]
return kept_nodes, kept_edges
_SANITIZE_RE = re.compile(r"[^A-Za-z0-9_]")
def sanitize_id(relative: str) -> str:
"""A Mermaid-safe node identifier for a relative file path — Mermaid
class/flowchart IDs can't contain `/`, `.`, or `::`.
"""
return "n_" + _SANITIZE_RE.sub("_", relative)
def file_label(relative: str) -> str:
return relative.rsplit("/", 1)[-1]
def _member_lines(node: DiagramNode, max_members: int) -> list[str]:
shown = node.symbols[:max_members]
lines = [f" +{name}" for name in shown]
remaining = len(node.symbols) - len(shown)
if remaining > 0:
lines.append(f" +… ({remaining} more)")
return lines
def render_class_diagram(nodes: list[DiagramNode], edges: list[tuple[Path, Path]], *, max_members: int) -> str:
lines = ["classDiagram"]
ids: dict[Path, str] = {}
for node in nodes:
node_id = sanitize_id(node.relative)
ids[node.file] = node_id
lines.append(f' class {node_id}["{file_label(node.relative)}"] {{')
lines.extend(_member_lines(node, max_members))
lines.append(" }")
for source, target in edges:
source_id, target_id = ids.get(source), ids.get(target)
if source_id is not None and target_id is not None:
lines.append(f" {source_id} ..> {target_id}")
return "\n".join(lines)
def render_block_diagram(nodes: list[DiagramNode], edges: list[tuple[Path, Path]]) -> str:
"""A simpler boxes-and-arrows view (Mermaid `flowchart`) with no member
detail — files grouped into a subgraph per top-level directory, for a
tree too large for `render_class_diagram`'s per-file interface detail
to stay readable.
"""
lines = ["flowchart TD"]
by_dir: dict[str, list[DiagramNode]] = {}
root_nodes: list[DiagramNode] = []
for node in nodes:
parts = node.relative.split("/")
if len(parts) == 1:
root_nodes.append(node)
else:
by_dir.setdefault("/".join(parts[:-1]), []).append(node)
ids: dict[Path, str] = {n.file: sanitize_id(n.relative) for n in nodes}
for node in root_nodes:
lines.append(f' {ids[node.file]}["{file_label(node.relative)}"]')
for directory in sorted(by_dir):
lines.append(f' subgraph {sanitize_id(directory)}["{directory}/"]')
for node in by_dir[directory]:
lines.append(f' {ids[node.file]}["{file_label(node.relative)}"]')
lines.append(" end")
for source, target in edges:
source_id, target_id = ids.get(source), ids.get(target)
if source_id is not None and target_id is not None:
lines.append(f" {source_id} --> {target_id}")
return "\n".join(lines)
def render_json(nodes: list[DiagramNode], edges: list[tuple[Path, Path]], root: Path) -> str:
payload = {
"nodes": [{"path": n.relative, "symbols": n.symbols} for n in nodes],
"edges": [
{"from": s.relative_to(root).as_posix(), "to": t.relative_to(root).as_posix()} for s, t in edges
],
}
return json.dumps(payload, indent=2)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Render a source tree's import graph + top-level symbols as a Mermaid class or block diagram."
)
parser.add_argument("root", help="Source directory to scan")
parser.add_argument("--style", choices=["class", "block"], default="class", help="Diagram style (default: class)")
parser.add_argument(
"--focus",
help="Comma-separated file path(s), relative to root, to scope the diagram to (that file plus its direct "
"imports and importers) instead of the whole tree",
)
parser.add_argument(
"--max-members",
type=int,
default=12,
help="Max symbols shown per block before truncating (class style only, default 12)",
)
parser.add_argument(
"--json", action="store_true", help="Print the underlying node/edge data as JSON instead of a diagram"
)
args = parser.parse_args(argv)
root = Path(args.root)
if not root.is_dir():
print(f"dependency-diagram: {args.root!r} is not a directory", file=sys.stderr)
return 1
nodes, edges = build_diagram(root)
if args.focus:
focus_files = [root / p.strip() for p in args.focus.split(",") if p.strip()]
known = {n.file for n in nodes}
missing = [f for f in focus_files if f not in known]
if missing:
rel_missing = ", ".join(str(f.relative_to(root)) for f in missing)
print(f"dependency-diagram: --focus file(s) not found under {args.root}: {rel_missing}", file=sys.stderr)
return 1
nodes, edges = neighborhood(focus_files, nodes, edges)
if args.json:
print(render_json(nodes, edges, root))
return 0
if args.style == "block":
print(render_block_diagram(nodes, edges))
else:
print(render_class_diagram(nodes, edges, max_members=args.max_members))
return 0
if __name__ == "__main__":
sys.exit(main())