"""dependency-graph — a first-party import graph over a source tree in any
of 60 languages with a real resolver (up from 50, `E31-T28`),
ported from PinkyAI's `dependency_graph` engine module (see README.md
"Provenance"). Extended (this port's own E31-T15-driven sync pass) from
its original Rust-only scope to match the engine's own broadened scope,
and again (E31-T19 roadmap Batch A) with Svelte, Tcl, Fish, and CUDA.
`is_recognized_source_extension` also walks — but does not yet resolve
edges for — Batch A's remaining schema/config formats (GraphQL, Protobuf,
Thrift, Dhall, CUE, PL/SQL; Jsonnet no longer belongs on this list, see
the `E31-T29` paragraph below), same honest "recognized node, no resolver
yet" gap Swift already has. Batch B/C (`E31-T22`) added
WGSL and Mojo to that same walked-not-resolved set (WGSL has no import
construct in its own spec; Mojo's `import` reuses Python syntax but not
certainly Python's resolution semantics this early in its own 1.0 beta)
— Odin isn't walked at all yet (its `import "core:fmt"` names a
collection:package pair, the same "no per-file signal" shape as Swift,
and it has no `repo_map` keyword-table entry to derive recognition from
in the first place). An earlier pass also confirmed this port's own
`RECOGNIZED_EXTENSIONS` already correctly included `.cue` — a real drift
the Rust engine's *own* derived registry had (fixed there that same
session; this hand-maintained Python set was already right).
**`E31-T23`, this pass: ten more languages got a real resolver, plus one
recognition gap fixed.** R's `source(...)`, Julia's `include(...)`,
Zig's `@import(...)`, Solidity's `import`, and Erlang's `-include(...)`
joined the quoted-relative-path family; PureScript, Idris, Elm, and Agda
(via `open import`) joined the declared-qualified-name family Haskell
already used, since all four declare a file's own qualified name the
identical `module X.Y where`/`exposing (..)` way Haskell does. Racket's
quoted `(require "...")` form joined too — its far more common unquoted
collection-path form (`(require racket/base)`) is filtered out for free,
never even extracted, since `extract_path_token` only ever reads a quoted
or bareword-allowed token and Racket's family sets `allow_bareword=False`.
Along the way, wiring up Erlang's real `-include("widget.hrl")` targets
surfaced a genuine, separate gap: `.hrl` (Erlang's header convention —
`-record`/`-define` declarations shared across modules) had no
`repo_map` keyword-table arm at all, unlike `.erl` itself, so it was
never in `RECOGNIZED_EXTENSIONS` — fixed alongside the resolver, or every
real Erlang include would have resolved to a file this port never
collected as a node in the first place.
**`E31-T24`, this pass: a brand-new Bazel/Starlark family, plus Haxe and
D joining existing families.** `load("//path:file.bzl", ...)` in
`BUILD`/`BUILD.bazel`/`WORKSPACE`/`WORKSPACE.bazel`/`MODULE.bazel`/`.bzl`
closes a gap stated and deferred twice in earlier batches: a label's
resolution shape is workspace-root-relative, not relative to the
importing file's own directory, closer to Go's module-root-relative
family than the quoted-relative-path one — see `bazel_workspace_root`/
`bazel_load_labels`/`resolve_bazel_label`. Haxe (requiring the identical
top-of-file `package a.b;` declaration plus filename convention
Java/Kotlin do) joined the JVM package+filename family; D's `import
a.b;` joined the dotted-path best-effort family (its own package-
directory convention is already lowercase, so no case conversion is
needed, unlike Elixir's). Standard ML and Vala are walked as graph
nodes (`RECOGNIZED_EXTENSIONS`) but never produce an edge — a real,
stated "no per-file signal" gap: SML's real module linking happens
through its own Compilation Manager or `.mlb` files, never a source-
level import resolving to a file; Vala's `using` only ever names an
*external* namespace, never a first-party cross-file import.
**`E31-T25`, this pass: Gleam gets a real family at last, plus AWK,
CMake, and Prolog join the quoted-relative-path family.** Gleam's own
gap note ("no `go.mod`-style declared root to anchor against") was
re-examined this pass and found wrong: `gleam.toml` genuinely is that
root, the identical shape `go.mod`/`WORKSPACE` already anchor Go/Bazel
against — see `gleam_project_root`/`gleam_import_targets`/
`resolve_gleam_import`. AWK's `@include "file.awk"` (a real `gawk`
extension), CMake's `include(...)` (bareword or quoted,
extension-optional — reused verbatim for `CMakeLists.txt` itself via
`is_cmake_list_name`'s filename-based override), and Prolog's
`use_module(...)`/`consult(...)`/`ensure_loaded(...)` (`.pro`, not
Prolog's own more common `.pl` — already claimed by Perl in this same
table, a real, stated scope-narrowing) all join `QUOTED_FAMILIES`.
**`E31-T26`, this pass: GNU Make's own `include` directive, plus a
longstanding module-doc drift fixed.** `include`/`-include`/`sinclude`
(one keyword, `"include "`, covers all three real spellings for free —
see `QUOTED_FAMILIES["mk"]`) joins the quoted-relative-path family,
scoped deliberately to a same-directory bareword sibling only — see
`is_makefile_include_sibling`'s own docstring for why a subdirectory
target is a real, stated gap rather than a guess (real GNU Make resolves
against its own current working directory, not the including file's
directory the way CMake's `include()` does). `Makefile`/`makefile`/
`GNUmakefile` reuse `.mk`'s own family via `is_makefile_name`'s
filename-based override, the identical shape `CMakeLists.txt` already
established for `.cmake`. Separately: `repo_map`'s own real Dockerfile/
Makefile symbol extraction (`dockerfile_stages`/`makefile_targets`)
turned out to *predate* this whole `E31-T19`–`E31-T25` language-coverage
series entirely — a real doc-drift bug, not a code bug, this batch found
and fixed in that module's own header (see its "Language coverage"
paragraph): every one of those five prior batches' doc revisions carried
forward a stale "still gets a bare path entry" claim for both filenames
without re-checking it.
**`E31-T27`, this pass: LaTeX's own `\\input`/`\\include` join the
family, plus a real shared-code extension.** One keyword list,
`\\input{`/`\\include{`, covers both real LaTeX file-inclusion macros
(curly-brace-delimited rather than quoted or parenthesized, extension
optional since real LaTeX itself appends `.tex` when omitted). This
needed `extract_path_token`'s own bareword scan to learn a new stop
character, `}` — verified safe for every existing bareword-tolerant
language, since none of their own real path specifiers ever legitimately
contain a literal `}`. `repo_map` gains its own dedicated
`latex_section_headings` extractor (a section title is prose, not an
identifier, so the generic keyword table would truncate a real
multi-word title) plus a fence-aware `markdown_headings` extractor for
`.md` files — the eighth "toward 500 file kinds" format.
**`E31-T28`, this pass: Nix gets its own dedicated family, not a
`QUOTED_FAMILIES` row.** Nix path literals (`./foo.nix`) are never
quoted, so extraction reuses `extract_path_token`'s bareword scan
directly. Resolution is the real reason this can't reuse
`resolve_relative_specifier`: real Nix has no "try appending the
extension" fallback at all (checked against Nix's own language
reference, not assumed by analogy) — `import ./foo` where only
`./foo.nix` exists on disk (and `./foo` isn't a directory) is a hard
error in real Nix, not a resolvable reference. What real Nix *does*
support is `import ./some-dir` resolving to `./some-dir/default.nix` —
a directory-index convention, but with a fixed filename different from
every other family's `index.<ext>` fallback, so `resolve_nix_import` is
its own small dedicated resolver instead. `repo_map` gains its own
dedicated `nix_let_bindings` extractor (Nix declarations are
assignment-shaped, `name = value;`, not a leading keyword) scoped
honestly to a file's own top-level `let ... in` block bindings — its
outermost attribute-set keys, outside any `let`, are a real, stated gap
(see that function's own docstring).
**`E31-T29`, this pass: ten more languages in one batch, mirroring the
engine's own Batch I.** Clojure's `(:require [my.app.utils :as u]
my.app.bare)` joins the dotted-path best-effort family (`lua_require_paths`
et al.'s neighborhood) with its own real filename convention — a
namespace segment's hyphens become underscores, not the shared
dots-to-slashes conversion alone (`clojure_ns_to_relative_path`) — and
its own real paren/bracket depth tracking, since a `:require` clause
commonly spans several lines (`clojure_ns_requires`), the same
depth-tracking-over-boolean-flag lesson `E31-T28`'s Nix `let`-block
extractor already learned. Common Lisp's `(load "utils.lisp")`, Verilog/
SystemVerilog's `` `include "file.vh" ``, and Jsonnet's `import
"file.libsonnet"` (a real, self-caught correction — Jsonnet was wrongly
lumped in with the schema/config formats above by category, without
actually checking its own import syntax) all join `QUOTED_FAMILIES`.
F#'s `open`, VB.NET's `Imports`, Fortran's `use`, and Pascal/Delphi's
`uses` all join the declared-qualified-name family (`declared_name_of`/
`declared_import_names`) — Fortran module names have no dots at all, the
only member of this family where that's true, and Pascal's own `uses`
clause commonly wraps across several lines with no keyword repeated on
the continuation ones, needing its own line-tracking helper
(`pascal_uses_targets`). Ada and GDScript each get a genuinely dedicated
family: Ada's `with Package.Name;` resolves through GNAT's own real
lowercase-hyphenated filename convention (`ada_dotted_to_filename_stem`),
reusing `resolve_dotted_best_effort` unchanged since GNAT projects don't
nest source files by package the way Java does; GDScript's
`preload`/`load`/`extends "res://..."` resolve against a discovered
`project.godot` project root (`gdscript_targets`/`resolve_gdscript_target`),
closer to the Go/Bazel/Gleam anchor-then-resolve shape than a plain
relative path. `.vh` (Verilog's own real header-file convention) needed
its own `RECOGNIZED_EXTENSIONS` addition, the same asymmetric "resolver
exists, node-walk didn't" gap `.hrl` already had — a real, self-caught
gap this batch's own fixture testing found (a `.svh` header resolved
fine; an otherwise identical `.vh` one silently didn't).
**Honest scope, narrower than what a "code review graph" might suggest,
stated up front.** This is a first-party *import*-declaration graph and
reverse-BFS blast radius. No call graph, no inheritance edges, no
test-coverage correlation, no semantic search, across any language.
**Why "multi-language" doesn't mean "one shared resolver."** Every
language resolves an import specifier to a file differently — see the
engine module's own doc for the full reasoning. This port keeps that same
discipline: one real resolution family per language shape, documented
below, rather than a single generic resolver that would silently
mis-report blast radius for a language it doesn't actually fit.
**A further, deliberate simplification from the source for this
standalone port:** the source extracts Rust `use` declarations with a
real `tree-sitter`/`tree-sitter-rust` grammar. This port uses a
hand-written brace-depth scanner over plain text instead, to stay
dependency-free (no `tree-sitter` pip package) — the same
"regex/heuristic, not a real parser" tradeoff `repo-map`'s own symbol
extraction already makes for every language it covers. It does not
distinguish real code from an import-shaped string sitting inside a
comment or a string literal; a real parser doesn't have that gap.
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
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
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Build a first-party, multi-language import graph and query blast radius."
)
parser.add_argument("root", help="Source directory to build the graph over (e.g. a crate's src/)")
parser.add_argument("--blast-radius", help="Comma-separated changed file paths (relative to root) to query")
parser.add_argument("--json", action="store_true", help="Print output as JSON instead of text")
args = parser.parse_args(argv)
root = Path(args.root)
graph = build(root)
if args.blast_radius:
changed = [root / p.strip() for p in args.blast_radius.split(",") if p.strip()]
radius = graph.blast_radius(changed)
rel = sorted(str(p.relative_to(root)) for p in radius)
if args.json:
print(json.dumps(rel, indent=2))
else:
print(f"Blast radius of {len(changed)} changed file(s): {len(rel)} file(s) total")
for r in rel:
print(f" {r}")
return 0
if args.json:
print(json.dumps({"file_count": graph.file_count()}, indent=2))
else:
print(f"dependency-graph: {graph.file_count()} file(s) with recorded import edges under {args.root}")
for file in sorted(graph.imports, key=str):
targets = sorted(str(t.relative_to(root)) for t in graph.imports[file])
print(f" {file.relative_to(root)} -> {', '.join(targets)}")
return 0
if __name__ == "__main__":
sys.exit(main())