"""repo-map — directory tree + top-level-symbol overview, ported from
PinkyAI's `repo_map` engine module (see README.md "Provenance").
**The idea.** Exploring an unfamiliar codebase one full read at a time
pays for every file's entire content just to learn its shape. A repo map
— a directory tree plus each source file's top-level symbols — gives that
same orientation for a fraction of the tokens, then a targeted read/grep
covers whatever the map says is actually relevant.
**Honest scope.** `extract_symbols` is a per-line regex heuristic keyed
on file extension — not a real parser for any of them. It catches
top-level, unindented declarations reliably; it does not resolve macros,
decorators that rewrite a definition's effective name, or symbols nested
inside another (a method inside another `impl`/class body is not
surfaced separately). `generate` skips common noise directories and caps
how deep it walks — a repo map is meant to be a cheap orientation aid,
not a substitute for reading the file it points you to once you know
which one you need.
**Language coverage: 129 languages, deliberately broad, deliberately
still not exhaustive.** See `_KEYWORDS_BY_EXTENSION` for the full table.
Adding another language is a one-line addition plus a test. A truly
unrecognized extension — or no extension at all and no dedicated
filename dispatch either (`README`, `LICENSE`, ...) — still gets a bare
path entry in the map, never silently dropped from the tree.
`Dockerfile`/`Makefile`/`BUILD`/`WORKSPACE`/`MODULE.bazel`/
`CMakeLists.txt` are *not* examples of that anymore, a real doc-drift
bug this batch (`E31-T26`) found and fixed: all have had real, dedicated
symbol extraction since an earlier language-coverage pass or an earlier
batch in this same series (see "handled outside the keyword table"
below) — this sentence simply never caught up, carried forward stale
across every one of `E31-T21` through `E31-T25`'s own revisions. (52 → 68: `E31-T19`'s roadmap Batch A -- Svelte, Fish, Tcl,
GraphQL, Protocol Buffers, Thrift, Jsonnet, Dhall, CUE, Starlark/Bazel,
PL/SQL, Idris, PureScript, Agda, CUDA, Gleam. 68 → 71: `E31-T22` closed
Batch B/C -- WGSL and Mojo, both freshness-checked 2026-08-09 (Mojo's
real `fn`→`def` deprecation was caught by that check, not assumed),
plus Odin via its own extractor -- see `odin_symbols`. Carbon stays
deferred, still pre-0.1 as of this check. Batch B's `.m`/`.v` extension
collisions were resolved by keeping the incumbent (Objective-C,
Verilog), stating MATLAB/Octave and V-lang unsupported for that reason.
71 → 75: Batch D (`E31-T24`, same day) adds Haxe, D, Standard ML, and
Vala -- all four mature, stable languages, chosen deliberately over
younger/moving-target candidates to keep this batch's own freshness
risk low. 75 → 78: Batch E (`E31-T25`, same day) adds AWK (`gawk`'s real
`function name(args) { ... }`, textually identical to the shell
family's own keyword), CMake (`.cmake` library files plus
`CMakeLists.txt` itself via filename dispatch -- both spellings, since
CMake commands are case-insensitive), and Prolog (`.pro`, a real but
deliberately partial extractor -- see "Real, stated gaps" below).) 78 →
79: Batch G (`E31-T27`, same day) adds LaTeX (`.tex`) -- see
`latex_section_headings`, a dedicated extractor rather than a
`_KEYWORDS_BY_EXTENSION` row, since a section title is prose, not an
identifier. 79 → 80: Batch H (`E31-T28`) adds Nix (`.nix`) -- see
`nix_let_bindings`, a dedicated extractor for the same "not a leading-
keyword shape" reason Odin's `name :: proc` form already needed one,
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). 80 → 90: Batch I
(`E31-T29`) adds ten more real, current languages/formats in one pass --
`_KEYWORDS_BY_EXTENSION` gains Vyper (`.vy`, Ethereum's second, simpler
smart-contract language, Python-shaped), Move (`.move`, Aptos/Sui/Diem's
smart-contract language), Cap'n Proto (`.capnp`) and FlatBuffers (`.fbs`,
both real schema IDLs, the same "schema format, still a real
leading-keyword shape" call already made for GraphQL/Protobuf/Thrift),
and Nushell (`.nu`, `def name [] { ... }`, its own real modern syntax,
not POSIX-shell-shaped); `.hcl` (standalone HCL -- Consul/Nomad/Packer
configs, not just Terraform) reuses `terraform_symbols` directly, the
identical language; and four dedicated extractors join Nix/LaTeX/
Markdown's ranks for the same "not a leading-keyword shape" reason:
`justfile`'s own real recipe names (`justfile_recipes` -- filename-
dispatched the same way `Makefile`/`Dockerfile` already are, including
its own real `.justfile` dotfile spelling), BibTeX's own real entry
citekeys (`bibtex_entry_keys`, `.bib` -- a citekey, not a field name, is
the useful "symbol" a bibliography entry has), reStructuredText's own
real "setext"-style underlined section titles (`rst_headings`, `.rst` --
a genuinely different heading convention from LaTeX's/Markdown's own
leading-marker one), and AsciiDoc's own real ATX-style `=`-prefixed
titles (`asciidoc_headings`, `.adoc` -- Markdown's `#` convention, just
AsciiDoc's own marker character, fence-aware the same way). 90 → 98:
Batch J (`E31-T30`) adds CoffeeScript, SCSS, Sass, Vim script,
Assembly/NASM, and Pug as real rows, plus Less as a stated no-signal
node -- the batch this docstring's own headline silently never counted:
the code and `SKILL.md` both moved to 98 while this line sat at "90," a
real three-way internal drift (code vs `SKILL.md` vs `README.md`) the
parity batch below found and fixed, the identical stale-claim shape the
engine's own `E31-T26`/`E31-T37` doc-drift catches already modeled.
98 → 117 in one parity pass (`E31-T38`): the engine's Batches K/L/M
(`E31-T35`/`E31-T36`/`E31-T37`) had moved the engine to 117 while this
port sat at 98, so all nineteen are ported together -- Batch K's
VBScript, Emacs Lisp, OpenSCAD, Snakemake (`.smk` plus `Snakefile`
itself by filename), Nextflow, Gherkin (see `gherkin_titles`), and XSLT
(both real spellings, reusing `xml_top_level_elements`); Batch L's
ActionScript, Processing (an honest `void`-only partial), Batchfile
(see `batch_labels`), REXX (see `rexx_labels`), QML (see
`qml_functions_and_signals`), and WebAssembly Text (see
`wat_named_functions`); Batch M's YARA, jq, Bicep, AppleScript,
fixed-form Fortran (see `fortran_fixed_form_declarations`), and
AutoHotkey (see `autohotkey_hotkeys`, an honest hotkey-only partial).
117 → 123 in the second parity pass (`E31-T42`): the engine's Batch N
(`E31-T40`) landed Typst, ColdFusion (joining the shell/AWK `function `
family), HLSL and GLSL (both honest keyword-row partials), M4 (see
`m4_macro_definitions`), and XQuery (see `xquery_functions`) while this
port sat at 117. This time no audit had to notice: the gap was surfaced
by `community-skills/tools/engine_parity.py` (`E31-T41`), the CI-runnable
checker `E31-T38` filed after closing the last gap by hand.
123 → 129 in the third parity pass (`E31-T44`): the engine's Batch O
(`E31-T43`) landed CSS and LESS (both via `css_selectors` -- and LESS's
mixin-definition gap, declined by batch J's honest note, closed through
that extractor's raw-text model rather than by a disambiguation pass),
ReasonML (joining the ReScript keyword row -- real shared lineage, not
a coincidental collision), Smalltalk (see `smalltalk_class_definitions`),
SaltStack (a `.sls` state file is literally YAML underneath its own
Jinja templating, so it joins the YAML arm), and Handlebars/Mustache
(see `handlebars_block_and_partial_names`, the first extractor here
that is deliberately not line-anchored). Again no audit had to notice:
`tools/engine_parity.py` (`E31-T41`) named all nine lagging extensions
on both surfaces the day Batch O landed -- the checker's second catch,
this time on schedule rather than as its own maiden run.
129 → 139 in the fourth parity pass (`L5-T01`, the L track's first
ticket): the engine's Batch P (`E31-T45`) landed Jinja2/Twig (see
`jinja_style_block_and_macro_names`, one extractor for a real shared
lineage), Liquid (see `liquid_assign_and_capture_names` -- deliberately
*not* the Jinja arm despite the shared `{% %}` delimiters, since Liquid
has no block/macro model and would silently come back empty), ERB and
EJS (see `erb_embedded_ruby_def_names`/`ejs_embedded_js_function_names`,
both riding on the shared `_scriptlet_keyword_names` scan of `<% %>`
tags), and Robot Framework (see `robot_keyword_and_test_case_names`);
its second landing (`E31-T46`) added Squirrel (`nut`, a keyword row),
Wren (`wren`, a keyword row -- its real quoted `import` is a
dependency-graph resolver, not a symbol), LookML (see
`lookml_block_names`), and CWL (a literal YAML document, so it joins the
YAML arm exactly as `.sls` did). Twelve extensions the checker named
red the day the engine landed them; this pass turned it green.
**Toward "500 file kinds," not just "100 languages": eight
non-programming-language formats now have dedicated extraction** --
INI-family `[section]` headers (`.ini`/`.cfg`/`.conf`, plus
`.editorconfig`'s identical shape -- see `ini_section_headers`), dotenv
variable names (`.env` and its `.env.*` siblings, value never included
-- see `dotenv_keys`), CSV/TSV header rows (see `csv_header_columns`,
both `E31-T22`), XML's direct-children-of-the-root element names
(`E31-T24` -- see `xml_top_level_elements`; covers `pom.xml`,
`.csproj`, Android manifests, and any other real, common XML config
format equally), and -- new this batch (`E31-T25`) -- `.properties`
files' top-level dotted namespaces, not every individual key (see
`properties_top_level_namespaces`; a real Spring Boot
`application.properties` can carry hundreds of keys under a handful of
real namespaces -- the namespace, not the key, is the useful
orientation "symbol" here), and -- new this batch (`E31-T26`) --
`.mk` files' target names, via the identical `makefile_targets`
extractor `Makefile` itself already used (a `.mk` file is Makefile
syntax either way -- a project's own convention for a file `include`d
by a top-level `Makefile`, not a different language), and -- new this
batch (`E31-T27`) -- Markdown's own ATX heading text (`#` through
`######`, see `markdown_headings`; fence-aware, so a `#`-prefixed shell
comment inside a fenced code example is never read as a heading).
**Three more, handled outside the keyword table: Vue, Astro, and
Svelte.** A `.vue`/`.astro`/`.svelte` file mixes template/markup with a
real script, which doesn't fit the keyword table's "one leading keyword
opens the whole file's worth of top-level declarations" model --
`symbols_for_file` special-cases all three directly instead: the script
text is pulled out first (`vue_script_blocks` -- reused as-is for Svelte,
since its extraction is markup-agnostic, not Vue-specific --
`astro_frontmatter_block`), then run through the same keyword table a
plain `.ts` file uses. `.cue` and `BUILD`/`WORKSPACE`/`.bzl` also sit
partly outside the plain keyword-table model -- see `cue_symbols` and
`starlark_build_targets`/`_is_bazel_build_name`. `CMakeLists.txt`
(`E31-T25`) is the identical shape one step further: extension-less
like `Dockerfile`/`Makefile`/`BUILD`, so `_is_cmake_list_name`
dispatches it by filename straight into the same `"cmake"`
`_KEYWORDS_BY_EXTENSION` entry `.cmake` library files already use -- no
new extractor at all, just the filename recognized. `Dockerfile` and
`Makefile` themselves belong in this same paragraph too, not the module
doc's own "unrecognized extension" sentence they were stuck in until
this batch (`E31-T26`) audited it and found the claim stale:
`_is_dockerfile_name`/`dockerfile_stages` extract a multi-stage build's
`FROM <image> AS <name>` stage names (an unnamed stage is listed by its
image reference instead), and `_is_makefile_name`/`makefile_targets`
extract a Makefile's `target: prerequisites` names at column 0 (recipe
lines are tab-indented, already excluded; `VAR := value` assignments
and `.PHONY`-style meta-targets are both filtered) -- both real and
already shipped from an earlier language-coverage pass, just never
folded into this doc's own accounting until now. `.mk` (`E31-T26`)
reuses `makefile_targets` directly, `Makefile`'s own extension-keyed
sibling the same way `.cmake` is `CMakeLists.txt`'s.
**Real, stated gaps** — languages/constructs where a leading keyword
genuinely doesn't exist, rather than one this module just hasn't been
taught yet:
- C/C++ free functions (no leading keyword). D (batch D, E31-T24) shares
this identical gap for the identical reason.
- R free functions assigned via `name <- function(...)`, caught by a
dedicated (more failure-prone) heuristic, `_r_assign_function_symbol`.
- Haskell/Elm function definitions (`name :: Type` / `name args = ...`,
no leading keyword) — only their type-level declarations are seen.
Idris, PureScript, and Agda (batch A, `E31-T19`) share this exact
name-first shape for their own function definitions, same reason.
- Erlang function clauses (no leading keyword, arity-based) — only the
`-module(name).` attribute is seen.
- Zig's `const Name = struct { ... }` and Delphi/Pascal's `TFoo =
class(...)` put the name *before* the keyword — the opposite order
this module's architecture assumes.
- Shell's `name() { ... }` POSIX form, caught by a dedicated heuristic,
`_shell_posix_function_symbol`, alongside the keyword-led form.
- Assembly and COBOL's full column-sensitive legacy dialects were
considered and deliberately excluded.
- Prolog (batch E, `E31-T25`) gets a real, deliberately *partial*
extractor -- `:- module(name, [...]).` -- not the full exclusion an
earlier pass's own note here once stated. A Prolog file's actual
bulk, name-first predicate clauses (`foo(X) :- bar(X).`), still has
no leading keyword at all and is still never caught, the identical
gap Haskell/Elm/Erlang's function clauses already have above.
Pure stdlib, no network call.
"""
from __future__ import annotations
import argparse
import json
import sys
from dataclasses import dataclass, field
from pathlib import Path
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)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Generate a directory + top-level-symbol overview.")
parser.add_argument("directory", help="Directory to map")
parser.add_argument("--max-depth", type=int, default=6, help="Max directory depth to walk (default 6)")
parser.add_argument("--json", action="store_true", help="Print the map as JSON instead of text")
args = parser.parse_args(argv)
root = Path(args.directory)
if not root.is_dir():
print(f"repo-map: {args.directory!r} is not a directory", file=sys.stderr)
return 1
maps = generate(root, max_depth=args.max_depth)
if args.json:
print(json.dumps([{"path": m.path, "symbols": m.symbols} for m in maps], indent=2))
else:
print(f"Repo map for {args.directory} (depth {args.max_depth}):\n")
print(render_text(maps))
return 0
if __name__ == "__main__":
sys.exit(main())