Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(languages): GDScript AST support at the Good tier (#1620)
Raghav Chamadiya6e96bb9a065c
diff --git a/README.md b/README.mdindex ec844cc6a..6b3d4856a 100644--- a/README.md+++ b/README.md@@ -473,7 +473,7 @@ the orchestrators. Full matrix and the contributor recipe:## Supported languages-**20 languages parsed to AST · 37 on a five-rung ladder · framework-aware across+**21 languages parsed to AST · 38 on a five-rung ladder · framework-aware acrossall of them.**"Do you support X" has five useful answers, not two, so languages land on a@@ -505,6 +505,7 @@ ladder and every rung says what it buys you.<img src="https://img.shields.io/badge/PHP-777BB4?style=flat-square&logo=php&logoColor=white" alt="PHP" /><img src="https://img.shields.io/badge/Dart-0175C2?style=flat-square&logo=dart&logoColor=white" alt="Dart" /><img src="https://img.shields.io/badge/Delphi-EE1F35?style=flat-square&logo=delphi&logoColor=white" alt="Object Pascal / Delphi" />+ <img src="https://img.shields.io/badge/GDScript-478CBF?style=flat-square&logo=godotengine&logoColor=white" alt="GDScript / Godot" /> <strong>· Partial </strong><img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" /><img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" />@@ -516,7 +517,7 @@ still doing real work rather than being ignored:| Rung | Languages | What you get ||---|---|---|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** |-| **Good** (5) | C · Swift · PHP · Dart · Object Pascal | All of the above except the full health suite |+| **Good** (6) | C · Swift · PHP · Dart · Object Pascal · GDScript | All of the above except the full health suite || **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution, Rojo and `.luaurc` aware. Razor: component symbols, `@code` and component-tag call edges, C# health markers; no import resolution yet || | | ⎯⎯ *tree-sitter parsing stops here; the rungs below come from git and imports* ⎯⎯ || **Lightweight** (8) | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# · HTML · QML | A real file-to-file import graph, and no symbol-level claims |diff --git a/ROADMAP.md b/ROADMAP.mdindex a14c1c7ba..a9fa252cc 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -34,7 +34,7 @@ Languages land on a five-rung ladder rather than a yes/no list, because "do yousupport X" has five different useful answers. Each rung is defined, with what itbuys you, in[docs/layers/LANGUAGE_SUPPORT.md](docs/layers/LANGUAGE_SUPPORT.md). Today that-ladder covers **37 languages, 20 of them parsed to a full AST**.+ladder covers **38 languages, 21 of them parsed to a full AST**.### New languagesdiff --git a/docs/README.md b/docs/README.mdindex acae69bd7..e12d196fc 100644--- a/docs/README.md+++ b/docs/README.md@@ -59,7 +59,7 @@ your agent in under five minutes, with no API key.| [layers/DECISIONS.md](layers/DECISIONS.md) | Architectural decisions mined from your repo and from your own agent sessions || [layers/DEAD_CODE.md](layers/DEAD_CODE.md) | Unreachable files, unused exports, and zombie packages by confidence tier || [layers/SECURITY.md](layers/SECURITY.md) | The local pattern scan: what the sixteen patterns catch, what they do not, and how far to trust the result |-| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 20 parsed to a full AST, 37 on the five-rung ladder |+| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 21 parsed to a full AST, 38 on the five-rung ladder || [layers/WIKI.md](layers/WIKI.md) | The generated wiki: page types, what `update` re-renders, styles, output language |## Scale itdiff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.mdindex cb2ed11c4..72d56e091 100644--- a/docs/business/COMMERCIAL.md+++ b/docs/business/COMMERCIAL.md@@ -42,7 +42,7 @@ scale, in a regulated or security-sensitive environment**:All of the following ship in `pip install repowise` today, free for internal use.- **[Five intelligence layers](../layers/INTELLIGENCE_LAYERS.md)**: Graph- (tree-sitter AST across 20 languages, two-tier dependency graph, call+ (tree-sitter AST across 21 languages, two-tier dependency graph, callresolution, heritage extraction, Leiden communities, PageRank / betweenness /SCC), Git (hotspots, ownership, co-change pairs, bus factor, significantcommits, contributor profiles, module health), Documentation (a wiki page per@@ -99,17 +99,18 @@ All of the following ship in `pip install repowise` today, free for internal use## 3. First-class language coverage-Repowise parses **20 languages to a full AST** and places **37 on a five-rung+Repowise parses **21 languages to a full AST** and places **38 on a five-rungladder**, so "do you support X" gets the rung as its answer rather than a yes or ano. Both numbers matter and neither is worth quoting alone.-The 20 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,+The 21 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,JavaScript, Svelte, Vue, Java, Kotlin, Go, Rust, C++, **C#**, Scala, and Ruby) withAST parsing, import resolution, named bindings, call resolution, heritageextraction, multi-project workspace resolvers, framework-aware edges, per-language-dynamic-hint extractors, and code-health markers. A further **5 at Good tier** (C,-Swift, PHP, Dart, Object Pascal/Delphi) get all of that except the full health-suite, and Luau and Razor/Blazor are partial. SQL/dbt, shell, HTML, and the config formats are+dynamic-hint extractors, and code-health markers. A further **6 at Good tier** (C,+Swift, PHP, Dart, Object Pascal/Delphi, GDScript) get all of that except the full health+suite, with GDScript also lacking framework edges and named bindings, and Luau+and Razor/Blazor are partial. SQL/dbt, shell, HTML, and the config formats arehandled by dedicated extractors on top of that.Below the AST line the ladder continues rather than stopping: **8 at Lightweight**diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.mdindex 587059565..117274ab9 100644--- a/docs/layers/GRAPH.md+++ b/docs/layers/GRAPH.md@@ -11,7 +11,7 @@ that **every edge carries its own evidence**.<p><img src="https://img.shields.io/badge/17-edge_types-3178C6?style=flat-square&labelColor=0A0A0A" alt="17 edge types" /><img src="https://img.shields.io/badge/29-resolution_origins-059669?style=flat-square&labelColor=0A0A0A" alt="29 resolution origins" />- <img src="https://img.shields.io/badge/20-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="20 languages" />+ <img src="https://img.shields.io/badge/21-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="21 languages" /><img src="https://img.shields.io/badge/22-framework_detectors-7F52FF?style=flat-square&labelColor=0A0A0A" alt="22 framework detectors" /><img src="https://img.shields.io/badge/0-LLM_calls-1E293B?style=flat-square&labelColor=0A0A0A" alt="zero LLM calls" /><img src="https://img.shields.io/badge/compiler_graded-7_of_7_cells_undominated-DC2626?style=flat-square&labelColor=0A0A0A" alt="no tool is both more precise and more complete, in 7 of 7 compiler-graded cells" />diff --git a/docs/layers/INTELLIGENCE_LAYERS.md b/docs/layers/INTELLIGENCE_LAYERS.mdindex 445bd12c7..e6e3f266d 100644--- a/docs/layers/INTELLIGENCE_LAYERS.md+++ b/docs/layers/INTELLIGENCE_LAYERS.md@@ -43,7 +43,7 @@ requirement for the index.## Graph Intelligencetree-sitter parses your source into a **two-tier dependency graph**: file nodes-and symbol nodes (functions, classes, methods). 20 languages parse to a full+and symbol nodes (functions, classes, methods). 21 languages parse to a fullAST; see [`LANGUAGE_SUPPORT.md`](LANGUAGE_SUPPORT.md) for per-language tiers.A **confidence-scored call resolver** handles import aliases, barreldiff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.mdindex 558fdd3d1..31b6f4092 100644--- a/docs/layers/LANGUAGE_SUPPORT.md+++ b/docs/layers/LANGUAGE_SUPPORT.md@@ -1,6 +1,6 @@# Language Support-**20 languages parsed to a full AST · 37 on the five-rung ladder ·+**21 languages parsed to a full AST · 38 on the five-rung ladder ·framework-aware across all of them.** "Do you support X" has five useful answersrather than two, so every language lands on a rung and the rung says what itbuys you. Everything else in your repo still appears in the wiki and is tracked@@ -30,6 +30,7 @@ reference.<img src="https://img.shields.io/badge/PHP-777BB4?style=flat-square&logo=php&logoColor=white" alt="PHP" /><img src="https://img.shields.io/badge/Dart-0175C2?style=flat-square&logo=dart&logoColor=white" alt="Dart" /><img src="https://img.shields.io/badge/Delphi-EE1F35?style=flat-square&logo=delphi&logoColor=white" alt="Object Pascal / Delphi" />+ <img src="https://img.shields.io/badge/GDScript-478CBF?style=flat-square&logo=godotengine&logoColor=white" alt="GDScript / Godot" /> <strong>· Partial </strong><img src="https://img.shields.io/badge/Luau-00A2FF?style=flat-square&logo=lua&logoColor=white" alt="Luau" /><img src="https://img.shields.io/badge/Razor-512BD4?style=flat-square&logo=blazor&logoColor=white" alt="Razor / Blazor" />@@ -53,14 +54,14 @@ produce meaningful output.| Tier | Languages | What you get ||------|-----------|--------------|| **Full** (13) | Python · TypeScript · JavaScript · Svelte · Vue · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | The whole pipeline: AST symbols, import resolution, a resolved call graph, heritage, docstrings, framework edges, **and code-health markers** |-| **Good** (5) | C · Swift · PHP · Dart · Object Pascal | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift and PHP don't yet |+| **Good** (6) | C · Swift · PHP · Dart · Object Pascal · GDScript | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP and GDScript don't yet. GDScript has a dedicated import resolver but no framework edges or named bindings (see [Known gaps](#gdscript-known-gaps)) || **Partial** (2) | Luau / Roblox · Razor / Blazor | Luau: AST symbols and `require()` resolution (Rojo / `.luaurc` aware), no health markers yet. Razor: a component symbol per file, call edges from `@code` blocks and component tags, C# health markers; no import resolution yet || | | ⎯⎯ *tree-sitter parsing stops here. The rungs below are derived from git and imports, not from an AST.* ⎯⎯ || **Lightweight** (8) | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# · HTML · QML | A real file-to-file import graph, no symbol-level claims || **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history only: blame, hotspots, co-change. No AST parsing |-The first three rungs are the **20 languages parsed to a full AST**; all five are-the **37** on the ladder. Both numbers are worth stating and neither is worth+The first three rungs are the **21 languages parsed to a full AST**; all five are+the **38** on the ladder. Both numbers are worth stating and neither is worthstating alone, so if you only take one thing from this page, take the rung yourlanguage sits on rather than either count.@@ -270,6 +271,78 @@ bindings and heritage, with a dedicated workspace resolver per language.| **PHP** | `.php` | `use Foo\Bar\Baz` with composer.json PSR-4 longest-prefix resolution; Laravel, TYPO3 edges || **Dart** | `.dart` | `import` / `export` / `part` URIs, `package:` via every `pubspec.yaml`, Flutter route tables and `runApp()` edges. **Health markers included** || **Object Pascal** | `.pas` `.pp` `.dpr` `.dpk` `.lpr` `.inc` | `uses` clauses via the generic unit-name → file-stem fallback; project files as entry points. **Health markers included** |+| **GDScript** | `.gd` | `preload(...)` / `load(...)` / `extends "res://..."` resolved as absolute paths from the nearest `project.godot`, so a repo holding many Godot projects keeps each project's `res://` namespace separate |++### GDScript known gaps++Both dialects parse: GDScript 4 (`@export var`) and GDScript 3 (`export var`,+`.method()` parent calls). On godotengine/godot-demo-projects, 459 of 461+`.gd` files parse with no error node and every `res://` path naming an indexed+script resolves; the two failures are the `$%UniqueName` form below.++- **A script without `class_name` gets no class symbol**, so its `extends`+ produces no symbol-level heritage edge. Synthesizing a name from the file+ stem would point the edge at a node that isn't in the graph. The+ `extends "res://..."` import edge is unaffected and carries the dependency.+- **`extends "res://base.gd"` is an import, not heritage.** A path is not a+ type name.+- **Engine methods on implicit `self`** (`get_node`, `emit_signal`, `connect`)+ are unresolved targets; only Godot's *global* scope is filtered as builtin.+ Same tradeoff as Pascal's framework calls. Note the builtin filter is+ receiver-blind, so a project method sharing a global's name (`hash`, `seed`,+ `str`) loses its call edge. `load` is excluded from the filter for exactly+ this reason, and the common engine API is listed separately so a bare+ `load(...)` or `queue_free()` is refused by the bare-name tier instead of+ binding to a lone project function of the same name.+- **`uid://` paths and `load(some_variable)` stay external.** The first needs+ the excluded `.uid` sidecars, the second needs dataflow. Neither is guessed.+ For the same reason, a scene's `[ext_resource]` that carries only a `uid://`+ and no `path` cannot be followed back to the script it names.+- **Signals share the `variable` kind** (no `signal` member in `SymbolKind`).+- **No framework edges and no named bindings.** Unlike C / Swift / PHP / Dart+ at this tier, there is no Godot framework-edge handler and no binding+ extractor, so every `Import` carries `bindings=[]`.+- **String and annotation dispatch is invisible**: `@rpc` methods invoked via+ `rpc("name")`, `connect(..., "method_name")`, GDScript 3 `setget` accessor+ names, and `$NodePath` / `%UniqueName` lookups produce no edges, so those+ methods read as unreferenced.+- **Annotation arguments are not imports.** `@icon("res://…")` and+ `class_name X, "res://icon.png"` reference real files that are not recorded.+- **Setter/getter bodies are not symbols**, so a call made inside one is+ attributed to the enclosing `variable` symbol: a `recompute()` in a setter+ leaves a call edge from the property, not from an accessor of its own.+- **Lambdas are not symbols.** A `lambda` is its own node type and may be a+ variable's value or a call argument, so callback-heavy code+ (`tween.finished.connect(func(): ...)`) is invisible to the symbol layer.+ A lambda bound to a variable still yields the *variable* as a symbol.+- **Code health: duplication markers DO run** (the clone tokenizer needs only a+ grammar), but complexity, performance and dataflow dialects are not+ registered, and that gap is what keeps GDScript at Good rather than Full.+- **Dead code reads Godot's wiring, not only imports.** A script registered+ under `[autoload]` in project.godot counts as an entry point, and a script a+ `.tscn` attaches to a node is never flagged, because neither reference is an+ import. Without that, 384 of the 461 `.gd` files in+ godotengine/godot-demo-projects read as unreachable; with it, 29 do. A file+ reached that way is exempt from the symbol-level passes too: a scene wires+ handlers by name (`[connection ... method="_on_pressed"]`) and that name+ appears in no script, which accounted for 522 of the 1,547 symbol findings+ on that corpus. **A script reached only through a `.tres` resource, an editor+ plugin manifest or `load()` on a computed path is still reported**, so the+ remaining output is narrower than the ladder tier implies.+- **Upstream grammar gap, reserved words:** calling a function named `export`+ or `onready` as a bare statement (`export()`) fails to parse, because the+ grammar still reserves those words at statement position for the GDScript 3+ `export var` / `onready var` forms. GDScript 4 respells those `@export` /+ `@onready`, making both legal identifiers again. `self.export()`,+ `var x = export()` and `func export()` all parse; only the bare call+ statement fails. Contained to+ the one file by tree-sitter error recovery. Seen once in 651 corpus files+ (Pixelorama's `ExportDialog.gd`).+- **Upstream grammar gap, `$%UniqueName`:** Godot accepts `$%Name` as shorthand+ for a scene-unique node lookup, but the grammar takes `$` and `%` as+ separate node-path forms and rejects the pair. `$Name`, `$Path/To/Node`+ and `%Name` all parse. Two occurrences in the 461-file corpus, in two+ files, and error recovery keeps the damage to the enclosing statement.---diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.pyindex 00cdc0cb7..58786477f 100644--- a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py@@ -24,6 +24,7 @@ from ..helpers import node_textfrom .cpp import _extract_cpp_heritagefrom .csharp import _extract_csharp_heritagefrom .dart import _extract_dart_heritage+from .gdscript import _extract_gdscript_heritagefrom .go import _extract_go_heritagefrom .java import _extract_java_heritagefrom .kotlin import _extract_kotlin_heritage@@ -62,6 +63,7 @@ HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {"scala": _extract_scala_heritage,"php": _extract_php_heritage,"pascal": _extract_pascal_heritage,+ "gdscript": _extract_gdscript_heritage,}diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/gdscript.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/gdscript.pynew file mode 100644index 000000000..321edef07--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/gdscript.py@@ -0,0 +1,99 @@+"""GDScript heritage extraction."""++from __future__ import annotations++from tree_sitter import Node++from ...models import HeritageRelation+from ...type_names import bare_type_name+from ..helpers import node_text+++def _parent_from_extends(extends_node: Node, src: str) -> str | None:+ """Return the parent type named by an ``extends_statement``.++ The grammar is ``"extends" choice($.string, $.type)`` with no field+ names, so the payload is located by child *type*:++ - ``(type)`` -> ``extends Node2D`` / ``extends Foo.Bar``. The text is+ the parent name, matched against symbol names by HeritageResolver.+ - ``(string)`` -> ``extends "res://base.gd"``. A *path*, not a name, so+ it is deliberately NOT emitted as a heritage relation: HeritageResolver+ matches ``parent_name`` against symbol names only, and a path never+ matches one. The same statement is already captured as an import by+ queries/gdscript.scm and resolved to a real file by resolvers/gdscript.py,+ which is where that dependency belongs.+ """+ for child in extends_node.named_children:+ if child.type == "type":+ text = node_text(child, src).strip()+ # `type` is choice(attribute, identifier, subscript), so a+ # qualified parent arrives dotted (`extends Inventory.BaseSlot`).+ # HeritageResolver matches bare symbol names, and the inner class+ # is indexed as `BaseSlot`, so the shared helper takes the last+ # segment, the same answer the C++ and C# extractors read from it.+ return bare_type_name(text) or None+ return None+++def _extract_gdscript_heritage(+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]+) -> None:+ """GDScript: ``extends Node2D`` / ``class_name Foo extends Bar`` /+ ``class Inner extends Baz:``.++ Two node types reach this function (see ``heritage_node_types`` in+ languages/specs/gdscript.py):++ ``class_definition`` -- an inner class. Usually carries its own+ ``extends`` field from the header form ``class Inner extends Baz:``,+ but the grammar also admits ``extends`` as a statement inside the+ class body, so that is checked as a fallback.++ ``class_name_statement`` -- the script-level class. The grammar gives it+ an optional ``extends`` field, which is populated only for the one-line+ form ``class_name Foo extends Bar``. Both of these are equally idiomatic+ and far more common::++ extends Node class_name Player+ class_name Player extends Node++ and in both the ``extends_statement`` is a *sibling* under ``source``,+ not a child. So when the field is absent, scan the file's top level for+ a standalone ``extends_statement``. A script may legally have only one,+ so the first hit is the answer.+ """+ extends_node = def_node.child_by_field_name("extends")++ if extends_node is None:+ # Where to look for a standalone `extends` depends on the node:+ # a class_name_statement's is a sibling under `source`, an inner+ # class's is a statement inside its own class_body (node-types.json+ # lists extends_statement among class_body's children, so the+ # header form is not the only way to spell it).+ scope = (+ def_node.parent+ if def_node.type == "class_name_statement"+ else def_node.child_by_field_name("body")+ )+ if scope is not None:+ for child in scope.named_children:+ if child.type == "extends_statement":+ extends_node = child+ break++ if extends_node is None:+ return++ parent_name = _parent_from_extends(extends_node, src)+ if not parent_name or parent_name == name:+ return++ out.append(+ HeritageRelation(+ child_name=name,+ parent_name=parent_name,+ kind="extends",+ line=line,+ )+ )diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.pyindex 089d76a38..e1a9432b1 100644--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py@@ -398,6 +398,40 @@ def _warmup_dart(ctx: ResolverContext) -> None:pf.file_info.is_entry_point = True+def _warmup_gdscript(ctx: ResolverContext) -> None:+ """Stamp the Godot scripts the engine loads without an import.++ An ``[autoload]`` entry in project.godot registers a script as a global+ singleton the engine instantiates at startup, so it is an entry point in+ the same sense ``main.py`` is. A script attached to a scene node is saved+ in the ``.tscn`` as an ext_resource, which is a reference no GDScript file+ makes: without this, every gameplay script in a Godot project reads as+ unreachable, because scenes -- not scripts -- are what a Godot game wires+ together.++ A repo with no project.godot and no scenes gets two empty sets, so this is+ a no-op on a loose bag of .gd files.+ """+ graph = getattr(ctx, "graph", None)+ if graph is None:+ return+ from .resolvers.gdscript import engine_loaded_scripts++ autoloads, scene_scripts = engine_loaded_scripts(ctx)+ parsed = getattr(ctx, "parsed_files", None) or {}+ for path in autoloads:+ node = graph.nodes.get(path)+ if node is not None:+ node["is_entry_point"] = True+ pf = parsed.get(path)+ if pf is not None and getattr(pf, "file_info", None) is not None:+ pf.file_info.is_entry_point = True+ for path in scene_scripts - autoloads:+ node = graph.nodes.get(path)+ if node is not None:+ node["is_never_flag"] = True++# Map language tag → (phase-event name, warmup function). The phase# name shows up in the CLI progress bar and in ``state.json`` timings.#@@ -416,6 +450,7 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {"c": ("graph.cpp_index", _warmup_cpp),"swift": ("graph.swift_entry", _warmup_swift),"dart": ("graph.dart_shells", _warmup_dart),+ "gdscript": ("graph.godot_scenes", _warmup_gdscript),}diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.pyindex cc8ae013e..317404da0 100644--- a/packages/core/src/repowise/core/ingestion/language_configs.py+++ b/packages/core/src/repowise/core/ingestion/language_configs.py@@ -400,6 +400,45 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {# guessed).parent_class_types=frozenset({"declType"}),),+ "gdscript": LanguageConfig(+ symbol_node_types={+ # `class_name Foo` names the script-level class. The node spans+ # only that statement, not the whole file -- GDScript has no+ # syntactic node for "the implicit outer class", so there is+ # nothing wider to point at.+ "class_name_statement": "class",+ "class_definition": "class", # inner `class Foo:` blocks+ "function_definition": "function",+ "constructor_definition": "function", # `func _init(...)`+ "variable_statement": "variable",+ "export_variable_statement": "variable", # GDScript 3 `export var`+ "onready_variable_statement": "variable", # GDScript 3 `onready var`+ "const_statement": "constant",+ "enum_definition": "enum",+ # Members of both named and anonymous enums. An anonymous+ # `enum {IDLE, RUNNING}` has no enum symbol at all, so without+ # this its members would vanish entirely.+ "enumerator": "constant",+ # No "signal"/"event" member in the SymbolKind literal. "variable"+ # is the same bucket Pascal's `declProp` and C#'s+ # `property_declaration` land in -- a declared member that is not+ # a callable of this class.+ "signal_statement": "variable",+ },+ # `preload(...)`/`load(...)` are ordinary calls; see queries/gdscript.scm.+ import_node_types=["call", "extends_statement"],+ export_node_types=[], # GDScript has no re-export syntax+ # GDScript's privacy convention is Python's, leading underscore and+ # all -- including the engine callbacks (`_ready`, `_process`), which+ # genuinely are not meant to be called by other scripts. Reusing+ # py_visibility rather than adding a byte-identical gdscript_visibility.+ visibility_fn=py_visibility,+ parent_extraction="nesting",+ # Only class_definition: `class_name_statement` is a sibling of the+ # members it logically owns, not their ancestor, so a script-level+ # func gets no parent -- which is correct, it belongs to the file.+ parent_class_types=frozenset({"class_definition"}),+ ),"luau": LanguageConfig(symbol_node_types={"function_declaration": "function",diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.pyindex dce9d849b..1362683af 100644--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py@@ -24,6 +24,7 @@ from .elixir import SPEC as _ELIXIRfrom .elm import SPEC as _ELMfrom .erlang import SPEC as _ERLANGfrom .fsharp import SPEC as _FSHARP+from .gdscript import SPEC as _GDSCRIPTfrom .go import SPEC as _GOfrom .graphql import SPEC as _GRAPHQLfrom .haskell import SPEC as _HASKELL@@ -101,6 +102,7 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (_SCALA,_DART,_PASCAL,+ _GDSCRIPT,# -----------------------------------------------------------------# Config / data / markup languages (passthrough — no AST)# -----------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/gdscript.py b/packages/core/src/repowise/core/ingestion/languages/specs/gdscript.pynew file mode 100644index 000000000..94b4115cb--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/specs/gdscript.py@@ -0,0 +1,179 @@+"""LanguageSpec for GDScript (Godot Engine).++Grammar: tree-sitter-gdscript (import name ``tree_sitter_gdscript``),+maintained by Preston Knopp+(https://github.com/PrestonKnopp/tree-sitter-gdscript), MIT.++``heritage_node_types`` covers both places a parent can be declared:+``class_name_statement`` (the script-level class, whose grammar carries an+optional ``extends`` field AND may be preceded by a standalone+``extends_statement`` sibling) and ``class_definition`` (inner classes,+which always carry their own ``extends`` field). See+extractors/heritage/gdscript.py for the sibling walk the first case needs.++A .gd file with no ``class_name`` declares an *anonymous* class. It gets no+class symbol and therefore no symbol-level heritage edge -- see the note in+queries/gdscript.scm on why a synthesized file-stem name would produce a+dangling graph node. Its ``extends "res://..."`` still yields a file-level+import edge, which is the edge that actually carries the dependency.+"""++from ..spec import LanguageSpec++SPEC = LanguageSpec(+ tag="gdscript",+ display_name="GDScript",+ extensions=frozenset({".gd"}),+ grammar_package="tree_sitter_gdscript",+ scm_file="gdscript.scm",+ heritage_node_types=frozenset({"class_name_statement", "class_definition"}),+ # Dedicated resolver: `res://` is an absolute path from the directory+ # holding project.godot, so resolution is exact rather than a stem guess.+ import_support="full",+ # project.godot both defines the res:// root for the resolver and marks+ # its directory as a package boundary -- godot-demo-projects is one repo+ # holding dozens of separate Godot projects, each with its own root.+ manifest_files=("project.godot",),+ # `.godot/` is the Godot 4 build/import cache and `.import/` its Godot 3+ # equivalent; both are full of generated files. Left unblocked, they+ # dominate any corpus measurement.+ blocked_dirs=(".godot", ".import"),+ # Godot re-imports assets from these and rewrites them without human+ # involvement.+ blocked_extensions=(".import", ".uid"),+ shebang_tokens=(),+ # @GlobalScope / @GDScript global functions plus the built-in *variant*+ # constructors (Vector2, Color, ...). Engine *classes* (Node, Sprite2D,+ # ...) are deliberately absent: those are referenced as receivers+ # (`Node.new()`), not as bare call targets, so listing them here would+ # buy nothing. Conservative on purpose, and it has to be: ASTParser's+ # builtin check is receiver-BLIND (`if target_name in _call_builtins` runs+ # before receiver_name is read), so a name listed here also deletes+ # `obj.name()` method edges. Anything plausible as a project method name+ # is therefore left out -- see `load` below.+ builtin_calls=frozenset({+ # Output / diagnostics. `breakpoint` is deliberately absent: it has a+ # dedicated breakpoint_statement node and never parses as a call.+ "print", "printerr", "printraw", "printt", "prints", "print_rich",+ "push_error", "push_warning", "assert",+ # Conversion / reflection+ "str", "int", "float", "bool", "char", "ord", "hash", "typeof",+ "type_string", "type_exists", "var_to_str", "str_to_var",+ "var_to_bytes", "bytes_to_var", "weakref", "is_instance_valid",+ "is_instance_id_valid", "instance_from_id", "len", "range",+ # `preload` is also captured as an import; excluded here so the call+ # graph does not gain a dangling node beside that edge. `load` is+ # deliberately NOT excluded despite being the same kind of global:+ # the filter is receiver-blind, and `load` is a common project and+ # engine method name (`ConfigFile.load`, `Image.load`, save+ # managers), so listing it would silently delete those call edges.+ "preload",+ # Not a global, but GDScript 4's bare `super()` parses as a plain+ # call whose target can never resolve to a project symbol.+ "super",+ # Math+ "abs", "absi", "absf", "min", "mini", "minf", "max", "maxi", "maxf",+ "clamp", "clampi", "clampf", "round", "roundi", "roundf", "floor",+ "floori", "floorf", "ceil", "ceili", "ceilf", "sign", "signi",+ "signf", "snapped", "snappedi", "snappedf", "fmod", "fposmod",+ "posmod", "wrap", "wrapi", "wrapf", "sqrt", "pow", "exp", "log",+ "sin", "cos", "tan", "asin", "acos", "atan", "atan2", "sinh",+ "cosh", "tanh", "deg_to_rad", "rad_to_deg", "linear_to_db",+ "db_to_linear", "lerp", "lerpf", "lerp_angle", "inverse_lerp",+ "remap", "smoothstep", "move_toward", "rotate_toward", "ease",+ "step_decimals", "nearest_po2", "pingpong", "is_equal_approx",+ "is_zero_approx", "is_nan", "is_inf", "is_finite",+ # Randomness+ "randi", "randf", "randfn", "randi_range", "randf_range",+ "randomize", "seed", "rand_from_seed",+ # Built-in variant constructors+ "Vector2", "Vector2i", "Vector3", "Vector3i", "Vector4", "Vector4i",+ "Rect2", "Rect2i", "Color", "Color8", "Plane", "Quaternion", "AABB",+ "Basis", "Transform2D", "Transform3D", "Projection", "Callable",+ "Signal", "StringName", "NodePath", "RID", "Dictionary", "Array",+ "PackedByteArray", "PackedInt32Array", "PackedInt64Array",+ "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray",+ "PackedVector2Array", "PackedVector3Array", "PackedColorArray",+ }),+ # The engine root types only, matching the Pascal `TObject` / Swift+ # `NSObject` precedent. Godot ships ~800 classes and enumerating them+ # would be arbitrary and stale within a release; an unlisted engine+ # parent costs nothing, because HeritageResolver drops any relation+ # whose parent name resolves to no symbol in the graph.+ builtin_parents=frozenset({+ "Object", "RefCounted", "Reference", "Resource", "Node",+ "CanvasItem", "Node2D", "Node3D", "Spatial", "Control",+ }),+ # The engine API a script calls on implicit `self`. Read only by the+ # bare-name tier in CallResolver, which answers a name declared exactly+ # once anywhere in the repo at 0.50 confidence: without this list, a+ # script's `queue_free()` or `emit_signal(...)` binds to whatever lone+ # project function happens to share the name. Unlike `builtin_calls`+ # above, listing a name here does NOT delete `obj.name()` member edges,+ # which is why the engine API belongs here and the global scope there.+ #+ # Rust's rule applies: a name the project plausibly declares and calls in+ # its own right stays off, because this tier is a guess but not always a+ # wrong one. That is why `play`, `stop`, `start`, `get`, `set`, `call`,+ # `update` and `reset` are absent despite all being engine methods.+ builtin_methods=frozenset({+ # Object: signals, deferred dispatch, reflection, lifetime+ "connect", "disconnect", "is_connected", "emit_signal", "has_signal",+ "call_deferred", "set_deferred", "callv", "has_method",+ "get_class", "is_class", "get_instance_id", "get_script", "set_script",+ "get_meta", "set_meta", "has_meta", "remove_meta", "notification",+ "free", "get_signal_list", "get_method_list", "get_property_list",+ "_init", "_notification", "_get", "_set", "_to_string",+ # Node: tree, children, groups, per-frame processing+ "queue_free", "add_child", "remove_child", "move_child", "reparent",+ "get_child", "get_children", "get_child_count",+ "get_node", "get_node_or_null", "find_child", "find_children",+ "get_parent", "get_owner", "get_tree", "get_window", "get_viewport",+ "is_inside_tree", "is_node_ready", "request_ready", "propagate_call",+ "add_to_group", "remove_from_group", "is_in_group", "get_groups",+ "set_process", "set_physics_process", "set_process_input",+ "set_process_unhandled_input", "set_process_mode", "print_tree",+ "duplicate", "rpc", "rpc_id", "set_multiplayer_authority",+ "is_multiplayer_authority", "get_multiplayer_authority",+ # Node callbacks the engine invokes, never another script+ "_ready", "_process", "_physics_process", "_enter_tree", "_exit_tree",+ "_input", "_unhandled_input", "_unhandled_key_input", "_shortcut_input",+ "_draw", "_gui_input", "_integrate_forces",+ "_get_configuration_warnings",+ # CanvasItem / Node2D / Node3D+ "queue_redraw", "hide", "show", "is_visible_in_tree", "look_at",+ "to_local", "to_global", "get_global_transform", "get_global_position",+ "draw_line", "draw_rect", "draw_circle", "draw_arc", "draw_polygon",+ "draw_colored_polygon", "draw_texture", "draw_texture_rect",+ "draw_string",+ # Physics bodies+ "move_and_slide", "move_and_collide", "is_on_floor", "is_on_wall",+ "is_on_ceiling", "get_slide_collision", "get_slide_collision_count",+ "apply_impulse", "apply_central_impulse", "apply_force",+ "set_collision_layer_value", "set_collision_mask_value",+ # Control+ "grab_focus", "release_focus", "has_focus", "get_rect",+ "get_global_rect", "set_anchors_preset",+ "add_theme_color_override", "add_theme_font_override",+ "add_theme_stylebox_override", "add_theme_constant_override",+ "get_theme_color", "get_theme_font", "get_theme_stylebox",+ # SceneTree+ "change_scene_to_file", "change_scene_to_packed", "reload_current_scene",+ "create_timer", "create_tween", "get_first_node_in_group",+ "get_nodes_in_group", "call_group", "set_group", "get_root",+ # Tween+ "tween_property", "tween_callback", "tween_interval", "tween_method",+ "set_trans", "set_ease", "set_loops",+ # PackedScene / ResourceLoader+ "instantiate", "instance", "take_over_path",+ "load_threaded_request", "load_threaded_get",+ # @GDScript globals. `load` is the one that matters: it is kept out of+ # `builtin_calls` so its argument still records an import, which leaves+ # this list as the only thing standing between a bare `load(...)` and a+ # project's own `func load(path)`. `preload` and `print` are already+ # dropped at the call site; listed for symmetry.+ "load", "preload", "print",+ }),+ # Godot's own brand blue.+ color_hex="#478CBF",+)diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex 73ce433fb..841b26039 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -41,6 +41,7 @@ LanguageTag = Literal["luau","dart","pascal",+ "gdscript",# Passthrough code languages (no AST parser yet — empty ParsedFile,# files enter the graph via the generic resolver). Before these tags# existed the traverser silently skipped such files as unknown, so e.g.diff --git a/packages/core/src/repowise/core/ingestion/queries/gdscript.scm b/packages/core/src/repowise/core/ingestion/queries/gdscript.scmnew file mode 100644index 000000000..1e43af674--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/gdscript.scm@@ -0,0 +1,235 @@+; =============================================================================+; repowise: GDScript (Godot) symbol, import and call queries+; tree-sitter-gdscript (PrestonKnopp/tree-sitter-gdscript) >= 6.1+; =============================================================================+;+; Node-shape reference for the constructs this file captures, read off+; src/node-types.json + grammar.js at 6.1.0 (not guessed -- every field name+; below is verified against those two files).+;+; NOT a complete inventory of the grammar. Deliberately absent, because+; nothing here matches them: `get_node` ($Path / %Unique), `annotation`+; (@export / @rpc / @icon and their arguments), `lambda`, and setget's+; `set_body` / `get_body`. Each is a documented gap in+; docs/layers/LANGUAGE_SUPPORT.md, not an oversight -- do not read the list+; below as "these are all the node types that exist".+;+; source := top-level; statements are DIRECT children+; (_compound_statement is an inlined rule, so+; function_definition / class_definition /+; enum_definition are children of `source`+; itself, not of a wrapper node)+; class_name_statement := name:(name) icon_path:(string)?+; extends:(extends_statement)?+; extends_statement := "extends" (string | type) -- NO field names+; class_definition := name:(name) extends:(extends_statement)?+; body:(class_body)+; function_definition := name:(name)? parameters:(parameters)+; return_type:(type)? body:(body)?+; constructor_definition := "func" "_init" parameters:(parameters) ...+; -- carries NO `name` field; the name is the+; anonymous "_init" token, captured as such+; variable_statement := name:(name) type:? value:? setget:? static:?+; export_variable_statement := GDScript 3 `export var x` (GDScript 4 spells+; it `@export var x`, which parses as an+; ordinary variable_statement carrying an+; `annotations` child -- both are covered)+; onready_variable_statement := GDScript 3 `onready var x`+; const_statement := name:(name) type:? value:(_expression)+; signal_statement := name:(name) parameters:(parameters)?+; enum_definition := name:(name)? body:(enumerator_list)+; call := (_primary_expression) arguments:(arguments)+; attribute_call := (identifier) arguments:(arguments)+; -- `obj.method()` parses as an `attribute`+; holding an attribute_call, NOT as `call`+; base_call := "." (identifier) arguments:(arguments)+;+; Full res:// import resolution lives in resolvers/gdscript.py; this file only+; emits the raw quoted path as @import.module. parser.py strips the quotes+; before the resolver sees it (`.strip("\"'` ")`), so `preload("res://a.gd")`+; arrives there as `res://a.gd`.++; ---------------------------------------------------------------+; Script-level class declaration -- `class_name Player`.+;+; A .gd file IS a class, but the class has a *name* only when the+; script declares one. Scripts without `class_name` therefore+; contribute no class symbol and no symbol-level heritage edge (the+; file-level import edge from `extends "res://..."` is unaffected).+; Documented as a known gap in docs/layers/LANGUAGE_SUPPORT.md+; rather than papered over with a synthesized file-stem name:+; HeritageResolver builds `child_id` as f"{path}::{child_name}"+; without checking that the symbol exists, so a synthesized name+; would emit an edge to a node that is not in the graph.+; ---------------------------------------------------------------++(source+ (class_name_statement+ name: (name) @symbol.name) @symbol.def)++; ---------------------------------------------------------------+; Inner classes -- `class Inner extends Node: ...`+; ---------------------------------------------------------------++(class_definition+ name: (name) @symbol.name) @symbol.def++; ---------------------------------------------------------------+; Functions. Not anchored to source/class_body: a GDScript 4 lambda+; is spelled `func` but parses as its own `lambda` node (which has+; its own `name` field for the `var cb = func on_done(): ...` form),+; so a `function_definition` can never nest inside another one.+; ---------------------------------------------------------------++(function_definition+ name: (name) @symbol.name+ parameters: (parameters) @symbol.params) @symbol.def++; `func _init(...)` is its own node type with no `name` field at all --+; the grammar spells `_init` as a literal token. Anonymous nodes are+; capturable, and node_text over the token yields exactly "_init".+(constructor_definition+ "_init" @symbol.name+ parameters: (parameters) @symbol.params) @symbol.def++; ---------------------------------------------------------------+; Members. These ARE anchored to `source` / `class_body`: unlike+; `func`, a `var`/`const`/`enum` is legal inside a function body and+; inside a lambda body. The parser's callable-ancestor filter catches+; the function-body case but not the lambda one (`lambda` is not a+; symbol node type, so it is not "callable" to that check), so the+; anchor is what keeps loop-local scratch variables out of the+; top-level symbol list.+; ---------------------------------------------------------------++(source+ (variable_statement+ name: (name) @symbol.name) @symbol.def)++(class_body+ (variable_statement+ name: (name) @symbol.name) @symbol.def)++; Only `source`-anchored: node-types.json gives class_body exactly+; {class_definition, const_statement, extends_statement,+; enum_definition, function_definition, pass_statement,+; signal_statement, variable_statement}, so the GDScript 3+; export/onready statement forms cannot appear inside a class body.+(source+ (export_variable_statement+ name: (name) @symbol.name) @symbol.def)++(source+ (onready_variable_statement+ name: (name) @symbol.name) @symbol.def)++(source+ (const_statement+ name: (name) @symbol.name) @symbol.def)++(class_body+ (const_statement+ name: (name) @symbol.name) @symbol.def)++(source+ (signal_statement+ name: (name) @symbol.name+ parameters: (parameters)? @symbol.params) @symbol.def)++(class_body+ (signal_statement+ name: (name) @symbol.name+ parameters: (parameters)? @symbol.params) @symbol.def)++; `name` is optional on enum_definition: `enum {A, B}` is anonymous and+; has no symbol of its own to name. Its *enumerators* are still real+; constants in the enclosing scope though, so they are captured+; separately below -- an anonymous enum is the idiomatic Godot spelling+; for a set of state/flag constants, and dropping it entirely would+; lose every one of them.+(source+ (enum_definition+ name: (name) @symbol.name) @symbol.def)++(class_body+ (enum_definition+ name: (name) @symbol.name) @symbol.def)++; Enumerators of both named and anonymous enums. `left` is the member+; identifier; `right` is the optional `= <expr>` value.+(enum_definition+ body: (enumerator_list+ (enumerator+ left: (identifier) @symbol.name) @symbol.def))++; ---------------------------------------------------------------+; Imports -- `preload("res://a.gd")`, `load("res://b.tscn")` and+; `extends "res://base.gd"`.+;+; Two single-`#eq?` patterns rather than one `#any-of?`: no query in+; this tree uses `#any-of?` yet, and `#eq?` is the form luau.scm has+; in production.+;+; Only string-literal arguments are captured. `load(some_var)` is+; unresolvable without dataflow, and emitting the variable's *name*+; as a module path would manufacture a wrong edge.+;+; The `.` anchors the string to the FIRST argument. Without it the+; pattern also matches a later string argument when the path itself+; is a variable -- `ResourceLoader.load(style, "DialogicStyle")` in+; dialogic passes a type hint as arg 2, which was being picked up as+; a module path.+; ---------------------------------------------------------------++(call+ (identifier) @_preload_fn+ arguments: (arguments . (string) @import.module)+ (#eq? @_preload_fn "preload")) @import.statement++(call+ (identifier) @_load_fn+ arguments: (arguments . (string) @import.module)+ (#eq? @_load_fn "load")) @import.statement++; `ResourceLoader.load("res://x.gd")` -- the standard idiom for a+; runtime (non-preload) fetch. It parses as an `attribute` holding an+; `attribute_call`, never as a bare `call`, so the pattern above cannot+; see it. Matched on the method name alone, so `image.load("res://a.png")`+; and `cfg.load("user://s.cfg")` are caught too; both are genuine+; resource references, and a non-res:// path resolves to an external+; node rather than a wrong edge.+(attribute+ (attribute_call+ (identifier) @_rl_fn+ arguments: (arguments . (string) @import.module))+ (#eq? @_rl_fn "load")) @import.statement++(extends_statement+ (string) @import.module) @import.statement++; ---------------------------------------------------------------+; Call graph+; ---------------------------------------------------------------++; Plain call -- `foo(...)`. Godot's global scope (`print`, `range`,+; `Vector2`, ...) is filtered out via the spec's builtin_calls.+(call+ (identifier) @call.target+ arguments: (arguments) @call.arguments) @call.site++; Method call -- `obj.method(...)`. The receiver is the FIRST child of+; the `attribute` node (anchored with `.`); `a.b.c()` therefore reports+; receiver `a`, which is the same simplification the other languages'+; receiver captures make.+(attribute+ . (_) @call.receiver+ (attribute_call+ (identifier) @call.target+ arguments: (arguments) @call.arguments)) @call.site++; GDScript 3 parent-method call -- `.method(...)`. The GDScript 4+; spelling `super.method(...)` parses as an ordinary attribute call+; with receiver `super` and is captured by the pattern above.+(base_call+ (identifier) @call.target+ arguments: (arguments) @call.arguments) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pyindex 7428329f3..8dcfbed9d 100644--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -12,6 +12,7 @@ from .dart import resolve_dart_importfrom .elixir import resolve_elixir_importfrom .erlang import resolve_erlang_importfrom .fsharp import resolve_fsharp_import+from .gdscript import resolve_gdscript_importfrom .generic import resolve_generic_importfrom .go import resolve_go_importfrom .haskell import resolve_haskell_import@@ -48,6 +49,8 @@ _RESOLVERS: dict[str, ResolverFn] = {"java": resolve_java_import,"kotlin": resolve_kotlin_import,"luau": resolve_luau_import,+ # res:// resolved against the nearest project.godot, not the repo root.+ "gdscript": resolve_gdscript_import,"ruby": resolve_ruby_import,"csharp": resolve_csharp_import,"swift": resolve_swift_import,diff --git a/packages/core/src/repowise/core/ingestion/resolvers/gdscript.py b/packages/core/src/repowise/core/ingestion/resolvers/gdscript.pynew file mode 100644index 000000000..56b573d5c--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/gdscript.py@@ -0,0 +1,249 @@+"""GDScript import resolution.++GDScript names dependencies three ways, all of which reach this function as+the raw quoted path after ``parser.py`` strips the surrounding quotes (see+queries/gdscript.scm)::++ preload("res://actors/player.gd")+ load("res://ui/menu.tscn")+ extends "res://actors/base_actor.gd"++``res://`` is an *absolute* path from the Godot project root -- the directory+holding ``project.godot`` -- not from the repo root. The two coincide in a+single-project repo and diverge in exactly the repo the validation corpus+leads with: ``godotengine/godot-demo-projects`` is one checkout containing+dozens of independent projects, each with its own ``project.godot`` and its+own ``res://`` namespace. Resolving against the repo root there would map+every project's ``res://player.gd`` onto whichever one sorted first.++So the resolver finds the *nearest* ``project.godot`` at or above the+importing file and resolves against that directory. A repo with no+``project.godot`` at all (a loose bag of scripts, or a plugin checked out+on its own) falls back to the repo root, which is the only sensible reading+of ``res://`` when the project boundary is not declared.++Unresolved paths are deliberately NOT stem-matched onto a same-named file+elsewhere in the repo: ``res://`` is exact by construction, so a miss means+the target genuinely is not indexed, and a wrong edge is worse than none.+They fall through to ``add_external_node`` so the reference still shows up.+"""++from __future__ import annotations++import re+from pathlib import PurePosixPath++from repowise.core.fs_walk import iter_glob++from .context import ResolverContext++_RES_PREFIX = "res://"++# Godot 4.4+ writes `uid://` references into scenes and, increasingly, into+# scripts. Resolving one needs the generated `.uid` sidecar files, which are+# build-cache artifacts the spec blocks from indexing. Recorded as external+# rather than guessed at.+_UID_PREFIX = "uid://"++# `user://` is the per-user writable data directory at runtime. It never+# points at a repo file.+_USER_PREFIX = "user://"+++def _project_roots(ctx: ResolverContext) -> tuple[str, ...]:+ """Repo-relative POSIX dirs holding a ``project.godot``, longest first.++ Built once per ``GraphBuilder.build()`` and stashed on the context, the+ same lazy-index pattern the dotnet/PHP/Kotlin resolvers use.++ Scanned from the filesystem rather than ``ctx.path_set``: ``project.godot``+ is an ini manifest with no language tag of its own, so it is not+ guaranteed to be among the indexed source files.+ """+ cached = getattr(ctx, "_gdscript_project_roots", None)+ if cached is not None:+ return cached++ roots: list[str] = []+ if ctx.repo_path is not None:+ for manifest in iter_glob(+ ctx.repo_path, "project.godot", prune_nested_git=ctx.prune_nested_git+ ):+ try:+ rel = manifest.relative_to(ctx.repo_path).parent+ except ValueError:+ continue+ rel_posix = rel.as_posix()+ roots.append("" if rel_posix == "." else rel_posix)++ # Longest first so the nearest enclosing project wins; the secondary sort+ # key keeps the order stable across runs (see ResolverContext.sorted_paths+ # on why resolver iteration order must not vary).+ result = tuple(sorted(set(roots), key=lambda r: (-len(r), r)))+ ctx._gdscript_project_roots = result # type: ignore[attr-defined]+ return result+++def _root_for(importer_path: str, ctx: ResolverContext) -> str:+ """Return the repo-relative project root governing *importer_path*."""+ for root in _project_roots(ctx):+ if not root:+ return ""+ if importer_path == root or importer_path.startswith(root + "/"):+ return root+ # No declared project boundary above this file: res:// is the repo root.+ return ""+++def resolve_gdscript_import(+ module_path: str,+ importer_path: str,+ ctx: ResolverContext,+) -> str | None:+ """Resolve a GDScript ``res://`` path to a repo-relative file path."""+ raw = module_path.strip()+ if not raw:+ return None++ if raw.startswith(_UID_PREFIX) or raw.startswith(_USER_PREFIX):+ return ctx.add_external_node(raw)++ if raw.startswith(_RES_PREFIX):+ relative = raw[len(_RES_PREFIX) :].lstrip("/")+ root = _root_for(importer_path, ctx)+ candidate = f"{root}/{relative}" if root else relative+ if candidate in ctx.path_set:+ return candidate+ return ctx.add_external_node(raw)++ # Godot also accepts a path relative to the importing script.+ candidate = _join_relative(PurePosixPath(importer_path).parent, raw)+ if candidate is not None and candidate in ctx.path_set:+ return candidate++ return ctx.add_external_node(raw)+++def _join_relative(base: PurePosixPath, relative: str) -> str | None:+ """Join *relative* onto *base*, collapsing ``.``/``..`` textually.++ Returns None if the path escapes above the repo root. Clamping the+ escape instead would fold ``../../vendor/shared/player.gd`` onto+ ``vendor/shared/player.gd`` and, if that unrelated file happened to+ exist, resolve to it -- a wrong edge, which this module's whole+ contract is to avoid.++ Not ``Path.resolve()``: resolution must not touch the filesystem (the+ target is looked up in ``ctx.path_set``, and in tests no such file+ exists on disk), and ``PurePosixPath`` keeps ``..`` segments literal.+ """+ parts: list[str] = [p for p in base.parts if p not in ("", ".")]+ for segment in relative.split("/"):+ if segment == "..":+ if not parts:+ return None+ parts.pop()+ elif segment not in ("", "."):+ parts.append(segment)+ return "/".join(parts)+++# ---------------------------------------------------------------------------+# Engine-loaded scripts+# ---------------------------------------------------------------------------+# Godot reaches a script two ways that are not imports and so leave no edge in+# the graph: an ``[autoload]`` entry in project.godot registers it as a global+# singleton, and a scene attaches it to a node, saved in the .tscn as a+# ``Script`` ext_resource. Read here so the dead-code pass does not report+# every gameplay script in a Godot project as unreachable.++# `[ext_resource type="Script" uid="uid://..." path="res://player.gd" id="5"]`.+# Matched on the path suffix rather than on `type="Script"`: attribute order is+# not fixed, a Godot 3 scene may omit the type, and a `.gd` ext_resource is a+# script whatever the header says. The editor writes double quotes; single+# quotes are accepted because a hand-edited or tool-generated scene may use+# them and the backreference keeps the pair matched.+_SCRIPT_RESOURCE_RE = re.compile(+ r"""\[ext_resource\b[^\]]*?\bpath=(["'])(res://.+?\.gd)\1"""+)++_AUTOLOAD_SECTION = "[autoload]"+++def _resolve_res(raw: str, owner_path: str, ctx: ResolverContext) -> str | None:+ """Return the indexed path *raw* names, or None if it is not indexed.++ Unlike :func:`resolve_gdscript_import` this never records an external+ node: a scene referencing an asset outside the index is not a dependency+ anyone asked to see, it is just a path that does not resolve.+ """+ relative = raw[len(_RES_PREFIX) :].lstrip("/")+ root = _root_for(owner_path, ctx)+ candidate = f"{root}/{relative}" if root else relative+ return candidate if candidate in ctx.path_set else None+++def _rel_posix(path, ctx: ResolverContext) -> str | None:+ if ctx.repo_path is None:+ return None+ try:+ return path.relative_to(ctx.repo_path).as_posix()+ except ValueError:+ return None+++def engine_loaded_scripts(+ ctx: ResolverContext,+) -> tuple[frozenset[str], frozenset[str]]:+ """Return ``(autoload singletons, scene-attached scripts)``.++ Both are sets of indexed repo-relative paths. A path that resolves to a+ file the index does not hold is dropped rather than guessed at, the same+ rule the import resolver follows.+ """+ if ctx.repo_path is None:+ return frozenset(), frozenset()++ autoloads: set[str] = set()+ for manifest in iter_glob(+ ctx.repo_path, "project.godot", prune_nested_git=ctx.prune_nested_git+ ):+ owner = _rel_posix(manifest, ctx)+ if owner is None:+ continue+ try:+ text = manifest.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ in_section = False+ for line in text.splitlines():+ stripped = line.strip()+ if stripped.startswith("["):+ in_section = stripped == _AUTOLOAD_SECTION+ continue+ if not in_section or "=" not in stripped:+ continue+ # `Global="*res://autoload/global.gd"` -- the leading `*` marks the+ # singleton as enabled and is not part of the path.+ value = stripped.split("=", 1)[1].strip().strip('"').lstrip("*")+ if not value.startswith(_RES_PREFIX) or not value.endswith(".gd"):+ continue+ resolved = _resolve_res(value, owner, ctx)+ if resolved is not None:+ autoloads.add(resolved)++ scene_scripts: set[str] = set()+ for scene in iter_glob(ctx.repo_path, "*.tscn", prune_nested_git=ctx.prune_nested_git):+ owner = _rel_posix(scene, ctx)+ if owner is None:+ continue+ try:+ text = scene.read_text(encoding="utf-8", errors="ignore")+ except OSError:+ continue+ for match in _SCRIPT_RESOURCE_RE.finditer(text):+ resolved = _resolve_res(match.group(2), owner, ctx)+ if resolved is not None:+ scene_scripts.add(resolved)++ return frozenset(autoloads), frozenset(scene_scripts)diff --git a/pyproject.toml b/pyproject.tomlindex b2b6551c3..126adb404 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -52,6 +52,7 @@ dependencies = ["tree-sitter-pascal>=0.11,<1","tree-sitter-luau>=1.2,<2","tree-sitter-bash>=0.23,<1",+ "tree-sitter-gdscript>=6.1,<7",# Markup grammars for single-file components: these locate <script> blocks# and markup expressions only; the JS inside them is parsed with the# TypeScript grammar (see sfc_source.py). There is no tree-sitter-vue ondiff --git a/tests/unit/ingestion/parser/test_gdscript.py b/tests/unit/ingestion/parser/test_gdscript.pynew file mode 100644index 000000000..220a26544--- /dev/null+++ b/tests/unit/ingestion/parser/test_gdscript.py@@ -0,0 +1,450 @@+"""Unit tests for the GDScript (Godot) language pipeline.++Tests parse inline byte strings so no filesystem I/O is needed. Covers+symbols (both GDScript 3 and GDScript 4 spellings), heritage in all three+positions it can appear, and imports from ``preload`` / ``load`` /+``extends "res://..."`` -- see docs/architecture/language-support.md's+"one .scm file + one LanguageConfig" recipe.++Import *resolution* is covered separately in+tests/unit/ingestion/test_gdscript_resolver.py, which needs no grammar.+"""++from __future__ import annotations++from pathlib import Path++import pytest++# tree-sitter-gdscript is a pinned dependency, so an absent grammar is a broken+# environment and must fail the suite rather than quietly skip it.+import tree_sitter_gdscript # noqa: F401++from repowise.core.ingestion.parser import ASTParser+from tests.unit.ingestion.parser._helpers import _make_file_info+++def _gd(path: str = "actors/player.gd") -> object:+ return _make_file_info(path, "gdscript")+++# GDScript 4 spelling: `@export`/`@onready` annotations on a plain `var`.+PLAYER_SOURCE = b'''\+extends "res://actors/base_actor.gd"+class_name Player++signal health_changed(old_value, new_value)++const MAX_HEALTH := 100+const Bullet = preload("res://weapons/bullet.gd")++enum State { IDLE, RUNNING, JUMPING }++@export var speed: float = 300.0+@onready var sprite = $Sprite2D+var health := MAX_HEALTH++class Inventory extends Resource:+\tvar slots := []++\tfunc add_item(item):+\t\tslots.append(item)++func _init():+\thealth = MAX_HEALTH++func _ready():+\tvar greeting = "hello"+\tprint(greeting)+\ttake_damage(0)++func take_damage(amount: int) -> void:+\thealth -= amount+\themit_signal("health_changed", health + amount, health)++static func clamp_health(value: int) -> int:+\treturn clamp(value, 0, MAX_HEALTH)+'''+++# GDScript 3 spelling: bare `export`/`onready` keywords, `.method()` super+# call, and `class_name X extends Y` folded onto one line.+LEGACY_SOURCE = b'''\+class_name Enemy extends KinematicBody2D++export var damage = 10+onready var timer = get_node("Timer")++func _ready():+\t.ready()+\tspawn()++func spawn():+\tpass+'''+++class TestGDScriptSymbols:+ def test_script_level_class_name(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert ("Player", "class") in {(s.name, s.kind) for s in result.symbols}++ def test_inner_class(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert ("Inventory", "class") in {(s.name, s.kind) for s in result.symbols}++ def test_functions_including_static(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ names = {s.name for s in result.symbols}+ assert {"_ready", "take_damage", "clamp_health"} <= names++ def test_constructor_is_captured_despite_having_no_name_field(+ self, parser: ASTParser+ ) -> None:+ # `func _init()` parses as `constructor_definition`, which carries no+ # `name` field at all -- the name is an anonymous "_init" token. If+ # the .scm ever stops capturing anonymous nodes this is the canary.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert "_init" in {s.name for s in result.symbols}++ def test_constants_variables_signals_and_enums(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ kinds = {(s.name, s.kind) for s in result.symbols}+ assert ("MAX_HEALTH", "constant") in kinds+ assert ("Bullet", "constant") in kinds+ assert ("State", "enum") in kinds+ # Enumerators are real constants in the enclosing scope.+ assert ("IDLE", "constant") in kinds+ assert ("health", "variable") in kinds+ # No "signal" member in the SymbolKind literal -- signals share the+ # "variable" bucket with Pascal properties and C# events.+ assert ("health_changed", "variable") in kinds++ def test_anonymous_enum_members_are_still_symbols(self, parser: ASTParser) -> None:+ # `enum {A, B}` has no enum symbol of its own, but its members are+ # the idiomatic Godot spelling for state/flag constants.+ result = parser.parse_file(_gd(), b"enum { IDLE, RUNNING }\n")+ assert {"IDLE", "RUNNING"} <= {s.name for s in result.symbols}++ def test_annotated_export_and_onready_vars(self, parser: ASTParser) -> None:+ # GDScript 4 `@export var` is an ordinary variable_statement carrying+ # an `annotations` child, not a distinct node type.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ names = {s.name for s in result.symbols}+ assert {"speed", "sprite"} <= names++ def test_gdscript_3_export_and_onready_keywords(self, parser: ASTParser) -> None:+ # The bare-keyword forms ARE distinct node types+ # (export_variable_statement / onready_variable_statement).+ result = parser.parse_file(_gd("actors/enemy.gd"), LEGACY_SOURCE)+ names = {s.name for s in result.symbols}+ assert {"damage", "timer"} <= names++ def test_function_local_variables_are_not_top_level_symbols(+ self, parser: ASTParser+ ) -> None:+ # `var greeting` lives inside _ready's body. A `var` is a+ # variable_statement wherever it appears, so without the source /+ # class_body anchor in the .scm every loop counter would surface.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert "greeting" not in {s.name for s in result.symbols}++ def test_inner_class_members_attribute_to_the_inner_class(+ self, parser: ASTParser+ ) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ add_item = next(s for s in result.symbols if s.name == "add_item")+ assert add_item.parent_name == "Inventory"++ def test_script_level_functions_have_no_parent(self, parser: ASTParser) -> None:+ # `class_name Player` is a *sibling* of the script's functions, not+ # their ancestor, so nesting-based parent extraction finds nothing --+ # which is the honest answer: they belong to the file.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ take_damage = next(s for s in result.symbols if s.name == "take_damage")+ assert take_damage.parent_name is None++ def test_underscore_prefixed_names_read_as_private(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ ready = next(s for s in result.symbols if s.name == "_ready")+ take_damage = next(s for s in result.symbols if s.name == "take_damage")+ assert ready.visibility == "private"+ assert take_damage.visibility == "public"+++class TestGDScriptHeritage:+ # A project type, not an engine one: engine roots like Node2D are in the+ # spec's builtin_parents and are filtered out before heritage is returned+ # (asserted separately below), which would mask the ordering behaviour.+ def test_standalone_extends_above_class_name(self, parser: ASTParser) -> None:+ # `extends X` on its own line is a SIBLING of class_name_statement,+ # not a child -- the extractor has to walk the file's top level to+ # find it. This ordering is the common one in real Godot code.+ result = parser.parse_file(_gd("actors/thing.gd"), b"extends BaseThing\nclass_name Thing\n")+ rels = {(r.child_name, r.parent_name, r.kind) for r in result.heritage}+ assert ("Thing", "BaseThing", "extends") in rels++ def test_extends_below_class_name(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd("actors/thing.gd"), b"class_name Thing\nextends BaseThing\n")+ rels = {(r.child_name, r.parent_name, r.kind) for r in result.heritage}+ assert ("Thing", "BaseThing", "extends") in rels++ def test_engine_root_parents_are_filtered_as_builtins(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd("actors/thing.gd"), b"extends Node2D\nclass_name Thing\n")+ assert result.heritage == []++ def test_inline_class_name_extends(self, parser: ASTParser) -> None:+ # `class_name Enemy extends KinematicBody2D` -- here the+ # extends_statement IS a child, via class_name_statement's field.+ result = parser.parse_file(_gd("actors/enemy.gd"), LEGACY_SOURCE)+ rels = {(r.child_name, r.parent_name, r.kind) for r in result.heritage}+ assert ("Enemy", "KinematicBody2D", "extends") in rels++ def test_inner_class_engine_parent_is_filtered(self, parser: ASTParser) -> None:+ # Named for what it actually checks: `Resource` is in builtin_parents,+ # so the relation is filtered rather than left dangling. The positive+ # inner-class case is the next test.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ rels = {(r.child_name, r.parent_name) for r in result.heritage}+ assert ("Inventory", "Resource") not in rels++ def test_inner_class_extends_written_inside_the_body(self, parser: ASTParser) -> None:+ # The grammar admits `extends` as a statement in the class body, not+ # only in the `class Inner extends X:` header.+ src = b"class_name Outer\n\nclass Inner:\n\textends SomeProjectType\n\tpass\n"+ result = parser.parse_file(_gd("a.gd"), src)+ rels = {(r.child_name, r.parent_name, r.kind) for r in result.heritage}+ assert ("Inner", "SomeProjectType", "extends") in rels++ def test_qualified_parent_keeps_its_last_segment(self, parser: ASTParser) -> None:+ # `extends Inventory.BaseSlot` must record `BaseSlot`; HeritageResolver+ # matches bare symbol names, so the dotted form would never resolve.+ src = b"class_name Slot\nextends Inventory.BaseSlot\n"+ result = parser.parse_file(_gd("a.gd"), src)+ assert {r.parent_name for r in result.heritage} == {"BaseSlot"}++ def test_inner_class_heritage_on_a_project_type_survives(+ self, parser: ASTParser+ ) -> None:+ src = b"class_name Outer\n\nclass Inner extends SomeProjectType:\n\tpass\n"+ result = parser.parse_file(_gd("a.gd"), src)+ rels = {(r.child_name, r.parent_name, r.kind) for r in result.heritage}+ assert ("Inner", "SomeProjectType", "extends") in rels++ def test_res_path_extends_is_an_import_not_a_heritage_relation(+ self, parser: ASTParser+ ) -> None:+ # A res:// path is not a type NAME, and HeritageResolver only ever+ # matches parent_name against symbol names -- emitting one would+ # create a relation that can never resolve. The dependency is+ # carried by the import edge instead.+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert all("res://" not in r.parent_name for r in result.heritage)+ assert "res://actors/base_actor.gd" in {i.module_path for i in result.imports}++ def test_script_without_class_name_yields_no_heritage(self, parser: ASTParser) -> None:+ # Documented ceiling: an anonymous script has no class symbol, so+ # there is no child name to hang a symbol-level edge on.+ result = parser.parse_file(_gd("a.gd"), b"extends Node2D\n\nfunc _ready():\n\tpass\n")+ assert result.heritage == []+++class TestGDScriptImports:+ def test_preload_load_and_extends_paths(self, parser: ASTParser) -> None:+ src = (+ b'extends "res://actors/base_actor.gd"\n'+ b'const Bullet = preload("res://weapons/bullet.gd")\n'+ b'var menu = load("res://ui/menu.tscn")\n'+ )+ result = parser.parse_file(_gd(), src)+ assert {i.module_path for i in result.imports} == {+ "res://actors/base_actor.gd",+ "res://weapons/bullet.gd",+ "res://ui/menu.tscn",+ }++ def test_quotes_are_stripped_before_the_resolver_sees_the_path(+ self, parser: ASTParser+ ) -> None:+ result = parser.parse_file(_gd(), b'const B = preload("res://b.gd")\n')+ assert result.imports[0].module_path == "res://b.gd"++ def test_non_literal_load_argument_is_not_an_import(self, parser: ASTParser) -> None:+ # `load(path_var)` needs dataflow to resolve; emitting the variable+ # name as a module path would manufacture a wrong edge.+ result = parser.parse_file(_gd(), b'var path = "res://x.gd"\nvar r = load(path)\n')+ assert result.imports == []++ def test_resourceloader_load_is_an_import(self, parser: ASTParser) -> None:+ # Parses as attribute -> attribute_call, never as a bare `call`, so+ # it needs its own pattern. The standard runtime-fetch idiom.+ result = parser.parse_file(_gd(), b'var s = ResourceLoader.load("res://a.gd")\n')+ assert {i.module_path for i in result.imports} == {"res://a.gd"}++ def test_type_hint_argument_is_not_mistaken_for_a_path(self, parser: ASTParser) -> None:+ # Real case from dialogic: ResourceLoader.load(style, "DialogicStyle")+ # passes the path as a variable and a TYPE HINT as the second+ # argument. Only the first argument may be read as a module path.+ result = parser.parse_file(+ _gd(), b'func f(style):\n\treturn ResourceLoader.load(style, "DialogicStyle")\n'+ )+ assert result.imports == []++ def test_load_as_a_method_name_still_makes_a_call_edge(self, parser: ASTParser) -> None:+ # The builtin filter is receiver-blind, so listing `load` in+ # builtin_calls would silently delete this edge.+ result = parser.parse_file(_gd(), b"func f():\n\tsave_manager.load(0)\n")+ assert ("load", "save_manager") in {+ (c.target_name, c.receiver_name) for c in result.calls+ }++ def test_preload_is_also_a_constant_symbol(self, parser: ASTParser) -> None:+ # `const X = preload(...)` is legitimately both a constant and an+ # import; the two captures are independent.+ result = parser.parse_file(_gd(), b'const Bullet = preload("res://weapons/bullet.gd")\n')+ assert ("Bullet", "constant") in {(s.name, s.kind) for s in result.symbols}+ assert len(result.imports) == 1+++class TestGDScriptCalls:+ def test_project_calls_are_recorded(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ assert "take_damage" in {c.target_name for c in result.calls}++ def test_godot_globals_are_excluded_as_builtins(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ targets = {c.target_name for c in result.calls}+ assert "print" not in targets+ assert "clamp" not in targets+ # preload is an import, and must not double as a call node.+ assert "preload" not in targets++ def test_gdscript_3_parent_call_is_recorded(self, parser: ASTParser) -> None:+ # `.ready()` in LEGACY_SOURCE -- the base_call pattern. Previously+ # advertised in the fixture header but asserted nowhere.+ result = parser.parse_file(_gd("actors/enemy.gd"), LEGACY_SOURCE)+ assert "ready" in {c.target_name for c in result.calls}++ def test_super_method_call_records_super_as_receiver(self, parser: ASTParser) -> None:+ src = b"func _ready():\n\tsuper._ready()\n\tsuper()\n"+ result = parser.parse_file(_gd("a.gd"), src)+ calls = {(c.target_name, c.receiver_name) for c in result.calls}+ assert ("_ready", "super") in calls+ # Bare `super()` can never resolve to a project symbol, so it is+ # filtered rather than left as a dangling call target.+ assert "super" not in {c.target_name for c in result.calls}++ def test_method_call_records_its_receiver(self, parser: ASTParser) -> None:+ result = parser.parse_file(_gd(), PLAYER_SOURCE)+ append = next((c for c in result.calls if c.target_name == "append"), None)+ assert append is not None+ assert append.receiver_name == "slots"+++class TestKnownGrammarGap:+ """Sentinel for the one upstream gap, so a grammar bump tells us it is fixed.++ tree-sitter-gdscript still reserves `export` / `onready` at statement+ position for the GDScript 3 `export var` / `onready var` forms. GDScript 4+ respells those `@export` / `@onready`, so both are ordinary identifiers+ again and `export()` is a legal call -- but a *bare* call statement fails+ to parse. Hit once in 651 corpus files (Pixelorama ExportDialog.gd:469).+ """++ @pytest.mark.parametrize("word", ["export", "onready"])+ def test_bare_call_statement_still_fails(self, parser: ASTParser, word: str) -> None:+ src = f"func f():\n\t{word}()\n".encode()+ result = parser.parse_file(_gd("a.gd"), src)+ assert result.parse_errors, (+ f"`{word}()` now parses -- the upstream grammar gap looks fixed. "+ "Drop this test and the matching bullet in LANGUAGE_SUPPORT.md."+ )++ @pytest.mark.parametrize(+ "src",+ [+ b"func export() -> void:\n\tpass\n",+ b"func f():\n\tself.export()\n",+ b"func f():\n\tvar x = export()\n",+ ],+ )+ def test_only_the_bare_statement_form_is_affected(+ self, parser: ASTParser, src: bytes+ ) -> None:+ assert parser.parse_file(_gd("a.gd"), src).parse_errors == []+++class TestGDScriptParsesCleanly:+ @pytest.mark.parametrize("source", [PLAYER_SOURCE, LEGACY_SOURCE])+ def test_no_parse_errors(self, parser: ASTParser, source: bytes) -> None:+ # The corpus gate is "no parse errors"; this is its unit-level+ # sentinel over both dialects.+ result = parser.parse_file(_gd(), source)+ assert result.parse_errors == []+++def _build_graph(repo: Path):+ """Parse every file under *repo* and return the built graph."""+ from repowise.core.ingestion import FileTraverser, GraphBuilder++ traverser = FileTraverser(repo)+ parser = ASTParser()+ builder = GraphBuilder(repo_path=repo)+ for fi in traverser.traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ return builder.build()+++def _call_targets(graph, source_file: str) -> set[str]:+ return {+ target+ for src, target, data in graph.edges(data=True)+ if data.get("edge_type") == "calls" and src.startswith(f"{source_file}::")+ }+++class TestEngineMethodsAreNotGuessedAt:+ """The bare-name tier must not answer an engine call with a project symbol.++ That tier binds a name declared exactly once anywhere in the repo, at 0.50+ confidence. Every implicit-`self` engine call is a bare name, so without+ ``builtin_methods`` a script's `load(...)` or `queue_free()` lands on+ whatever lone function shares the spelling.+ """++ def test_bare_load_does_not_bind_to_a_project_function_named_load(+ self, tmp_path: Path+ ) -> None:+ (tmp_path / "save_manager.gd").write_bytes(+ b"extends Node\nclass_name SaveManager\n\n"+ b"func load(path):\n\treturn path\n"+ )+ (tmp_path / "player.gd").write_bytes(+ b"extends Node\n\nfunc respawn():\n\tload(\"res://x.tscn\")\n"+ )+ graph = _build_graph(tmp_path)+ assert "save_manager.gd::load" in graph+ assert "save_manager.gd::load" not in _call_targets(graph, "player.gd")++ @pytest.mark.parametrize("name", ["queue_free", "emit_signal", "get_parent"])+ def test_other_engine_names_are_refused_too(self, tmp_path: Path, name: str) -> None:+ (tmp_path / "helper.gd").write_bytes(+ f"extends Node\n\nfunc {name}():\n\tpass\n".encode()+ )+ (tmp_path / "caller.gd").write_bytes(+ f"extends Node\n\nfunc act():\n\t{name}()\n".encode()+ )+ graph = _build_graph(tmp_path)+ assert f"helper.gd::{name}" not in _call_targets(graph, "caller.gd")++ def test_a_unique_project_function_still_resolves(self, tmp_path: Path) -> None:+ # The control: the tier is a guess, not a wrong one by construction,+ # and a name the engine does not own must still bind.+ (tmp_path / "damage.gd").write_bytes(+ b"extends Node\n\nfunc apply_falloff_damage(amount):\n\treturn amount\n"+ )+ (tmp_path / "caller.gd").write_bytes(+ b"extends Node\n\nfunc hit():\n\tapply_falloff_damage(5)\n"+ )+ graph = _build_graph(tmp_path)+ assert "damage.gd::apply_falloff_damage" in _call_targets(graph, "caller.gd")diff --git a/tests/unit/ingestion/test_gdscript_resolver.py b/tests/unit/ingestion/test_gdscript_resolver.pynew file mode 100644index 000000000..d9e3b4ed3--- /dev/null+++ b/tests/unit/ingestion/test_gdscript_resolver.py@@ -0,0 +1,235 @@+"""Unit tests for the GDScript import resolver.++The interesting behaviour is that ``res://`` is absolute from the *Godot+project* root -- the directory holding ``project.godot`` -- not the repo+root. A single repo can hold many projects (``godot-demo-projects``, the+tier-1 validation corpus, is exactly that shape), so these tests pin the+nearest-enclosing-project rule and the repo-root fallback.++Parser contract+---------------+``parser.py`` strips surrounding quotes from the captured ``@import.module``+text before calling a resolver, so these tests pass unquoted paths --+``preload("res://a.gd")`` reaches the resolver as ``res://a.gd``.++No grammar dependency here on purpose: this module must run even in a venv+without ``tree_sitter_gdscript``, so it carries no ``importorskip``.+"""++from __future__ import annotations++from pathlib import Path++import networkx as nx++from repowise.core.ingestion.resolvers.context import ResolverContext+from repowise.core.ingestion.resolvers.gdscript import (+ engine_loaded_scripts,+ resolve_gdscript_import,+)+++def _ctx(paths: set[str], repo_path: Path | None = None) -> ResolverContext:+ stem_map: dict[str, list[str]] = {}+ for p in paths:+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()+ stem_map.setdefault(stem, []).append(p)+ return ResolverContext(+ path_set=paths,+ stem_map=stem_map,+ graph=nx.DiGraph(),+ repo_path=repo_path,+ )+++def _write_project(root: Path, *relative_dirs: str) -> None:+ """Drop a minimal ``project.godot`` into each of *relative_dirs*."""+ for rel in relative_dirs:+ target = root / rel if rel else root+ target.mkdir(parents=True, exist_ok=True)+ (target / "project.godot").write_text("config_version=5\n", encoding="utf-8")+++class TestResPaths:+ def test_resolves_against_repo_root_when_project_is_at_root(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "")+ ctx = _ctx({"actors/player.gd", "actors/base.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("res://actors/base.gd", "actors/player.gd", ctx)+ assert got == "actors/base.gd"++ def test_resolves_against_repo_root_when_no_project_godot_exists(+ self, tmp_path: Path+ ) -> None:+ # A loose bag of scripts with no declared project boundary: the repo+ # root is the only sensible reading of res://.+ ctx = _ctx({"actors/player.gd", "actors/base.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("res://actors/base.gd", "actors/player.gd", ctx)+ assert got == "actors/base.gd"++ def test_leading_slashes_after_the_scheme_are_tolerated(self, tmp_path: Path) -> None:+ ctx = _ctx({"a.gd", "b.gd"}, repo_path=tmp_path)+ assert resolve_gdscript_import("res:///b.gd", "a.gd", ctx) == "b.gd"+++class TestMultiProjectRepo:+ """The godot-demo-projects shape: many projects, one checkout."""++ def test_nearest_project_root_wins(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "2d/platformer", "3d/voxel")+ paths = {+ "2d/platformer/player.gd",+ "2d/platformer/enemy.gd",+ "3d/voxel/player.gd",+ "3d/voxel/world.gd",+ }+ ctx = _ctx(paths, repo_path=tmp_path)++ # Both projects declare a res://player.gd. Each importer must reach+ # its OWN sibling, never the other project's same-named file.+ assert (+ resolve_gdscript_import("res://player.gd", "2d/platformer/enemy.gd", ctx)+ == "2d/platformer/player.gd"+ )+ assert (+ resolve_gdscript_import("res://player.gd", "3d/voxel/world.gd", ctx)+ == "3d/voxel/player.gd"+ )++ def test_deeper_project_shadows_an_outer_one(self, tmp_path: Path) -> None:+ # A demo project nested inside an outer project: the inner+ # project.godot is the res:// root for files beneath it.+ _write_project(tmp_path, "", "demos/inner")+ paths = {"shared.gd", "demos/inner/shared.gd", "demos/inner/main.gd"}+ ctx = _ctx(paths, repo_path=tmp_path)+ got = resolve_gdscript_import("res://shared.gd", "demos/inner/main.gd", ctx)+ assert got == "demos/inner/shared.gd"++ def test_file_outside_every_project_falls_back_to_repo_root(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "demos/inner")+ paths = {"tools/build.gd", "tools/helper.gd"}+ ctx = _ctx(paths, repo_path=tmp_path)+ got = resolve_gdscript_import("res://tools/helper.gd", "tools/build.gd", ctx)+ assert got == "tools/helper.gd"+++class TestRelativePaths:+ def test_sibling_relative_path(self, tmp_path: Path) -> None:+ ctx = _ctx({"actors/player.gd", "actors/base.gd"}, repo_path=tmp_path)+ assert resolve_gdscript_import("base.gd", "actors/player.gd", ctx) == "actors/base.gd"++ def test_dotdot_walks_up(self, tmp_path: Path) -> None:+ ctx = _ctx({"actors/player.gd", "lib/util.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("../lib/util.gd", "actors/player.gd", ctx)+ assert got == "lib/util.gd"++ def test_escaping_above_the_repo_root_is_external_not_clamped(+ self, tmp_path: Path+ ) -> None:+ # Clamping the `..` would fold this onto `vendor/shared/player.gd`+ # and resolve to that unrelated file. The real target is outside the+ # checkout, so the only correct answer is external.+ ctx = _ctx({"player.gd", "vendor/shared/player.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("../../vendor/shared/player.gd", "player.gd", ctx)+ assert got == "external:../../vendor/shared/player.gd"+++class TestUnresolved:+ def test_missing_target_becomes_external_not_a_stem_guess(self, tmp_path: Path) -> None:+ # `res://` is exact by construction, so a miss must NOT be rescued by+ # matching the filename somewhere else in the repo.+ ctx = _ctx({"a.gd", "somewhere/deep/base.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("res://actors/base.gd", "a.gd", ctx)+ assert got == "external:res://actors/base.gd"++ def test_uid_paths_are_external(self, tmp_path: Path) -> None:+ ctx = _ctx({"a.gd"}, repo_path=tmp_path)+ got = resolve_gdscript_import("uid://cxy8n1e0abcde", "a.gd", ctx)+ assert got == "external:uid://cxy8n1e0abcde"++ def test_user_paths_are_external(self, tmp_path: Path) -> None:+ ctx = _ctx({"a.gd"}, repo_path=tmp_path)+ assert resolve_gdscript_import("user://save.dat", "a.gd", ctx) == "external:user://save.dat"++ def test_empty_module_path_resolves_to_nothing(self, tmp_path: Path) -> None:+ ctx = _ctx({"a.gd"}, repo_path=tmp_path)+ assert resolve_gdscript_import(" ", "a.gd", ctx) is None+++class TestProjectRootScanIsCached:+ def test_roots_are_scanned_once_per_context(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "game")+ ctx = _ctx({"game/a.gd", "game/b.gd"}, repo_path=tmp_path)+ resolve_gdscript_import("res://b.gd", "game/a.gd", ctx)++ # Deleting the manifest after the first call must not change the+ # answer -- proof the scan result was cached on the context rather+ # than repeated per import (this runs once per file per build).+ (tmp_path / "game" / "project.godot").unlink()+ assert resolve_gdscript_import("res://b.gd", "game/a.gd", ctx) == "game/b.gd"+++AUTOLOAD_MANIFEST = """\+config_version=5++[autoload]++Global="*res://autoload/global.gd"+Music="res://autoload/music.gd"+Scene="*res://autoload/hud.tscn"+Missing="*res://autoload/gone.gd"+"""++SCENE = """\+[gd_scene format=3 uid="uid://dxq1b4cth265d"]++[ext_resource type="Script" uid="uid://e3f" path="res://bullets.gd" id="2"]+[ext_resource type="Texture2D" path="res://face.png" id="3"]+[ext_resource type="Script" path="res://absent.gd" id="4"]+[ext_resource type="Script" uid="uid://n0path" id="5"]+"""++SINGLE_QUOTED_SCENE = """\+[gd_scene format=3]++[ext_resource type='Script' path='res://bullets.gd' id='2']+"""+++class TestEngineLoadedScripts:+ """The two ways Godot reaches a script without importing it."""++ def test_autoload_entries_resolve_against_their_own_project(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "game")+ (tmp_path / "game" / "project.godot").write_text(AUTOLOAD_MANIFEST, encoding="utf-8")+ ctx = _ctx(+ {"game/autoload/global.gd", "game/autoload/music.gd", "game/player.gd"},+ repo_path=tmp_path,+ )+ autoloads, scenes = engine_loaded_scripts(ctx)+ # The leading `*` marks a singleton as enabled and is not part of the+ # path. `gone.gd` is not indexed and `hud.tscn` is not a script:+ # neither is guessed at, the rule the import resolver follows.+ assert autoloads == frozenset({"game/autoload/global.gd", "game/autoload/music.gd"})+ assert scenes == frozenset()++ def test_scene_script_resources_are_collected(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "game")+ (tmp_path / "game" / "shower.tscn").write_text(SCENE, encoding="utf-8")+ ctx = _ctx({"game/bullets.gd", "game/other.gd"}, repo_path=tmp_path)+ autoloads, scenes = engine_loaded_scripts(ctx)+ assert autoloads == frozenset()+ # `absent.gd` is not indexed, `face.png` is not a script, and the+ # `uid://`-only entry carries no path to resolve.+ assert scenes == frozenset({"game/bullets.gd"})++ def test_single_quoted_paths_are_accepted(self, tmp_path: Path) -> None:+ _write_project(tmp_path, "game")+ (tmp_path / "game" / "hand_edited.tscn").write_text(+ SINGLE_QUOTED_SCENE, encoding="utf-8"+ )+ ctx = _ctx({"game/bullets.gd"}, repo_path=tmp_path)+ assert engine_loaded_scripts(ctx)[1] == frozenset({"game/bullets.gd"})++ def test_no_godot_project_yields_nothing(self, tmp_path: Path) -> None:+ ctx = _ctx({"a.gd"}, repo_path=tmp_path)+ assert engine_loaded_scripts(ctx) == (frozenset(), frozenset())diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.pyindex 7d092164e..586eef065 100644--- a/tests/unit/ingestion/test_language_capabilities.py+++ b/tests/unit/ingestion/test_language_capabilities.py@@ -143,6 +143,9 @@ _FULL = {# dart promoted with the tree-sitter grammar (the regex tier stays as# the no-grammar fallback)."dart",+ # res:// is an absolute path from the nearest project.godot, so GDScript+ # import targets resolve exactly rather than through a stem guess.+ "gdscript","go","java","javascript",diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.pyindex 9a0b22455..2fc6b3d29 100644--- a/tests/unit/test_no_bare_type_name_copies.py+++ b/tests/unit/test_no_bare_type_name_copies.py@@ -91,6 +91,9 @@ _KNOWN: dict[str, int] = {# declaring the view. The trailing segment is the view function and the# head is a module path, so neither end is a type._PREFIX + "framework_edges/django.py": 1,+ # Takes the head of a blueprint variable such as `views.bp` to reach the+ # module that bound it, which is the opposite end from the shared helper.+ _PREFIX + "framework_edges/flask.py": 1,# Split a route handler's path to reach a function name, and keep the# prefix to resolve the package it came from. Neither wants a type._PREFIX + "framework_edges/rust.py": 1,diff --git a/uv.lock b/uv.lockindex 7594a3b89..f889c5e2d 100644--- a/uv.lock+++ b/uv.lock@@ -3084,6 +3084,7 @@ dependencies = [{ name = "tree-sitter-c-sharp" },{ name = "tree-sitter-cpp" },{ name = "tree-sitter-dart" },+ { name = "tree-sitter-gdscript" },{ name = "tree-sitter-go" },{ name = "tree-sitter-html" },{ name = "tree-sitter-java" },@@ -3179,6 +3180,7 @@ requires-dist = [{ name = "tree-sitter-c-sharp", specifier = ">=0.23,<1" },{ name = "tree-sitter-cpp", specifier = ">=0.23,<1" },{ name = "tree-sitter-dart", specifier = ">=0.1,<1" },+ { name = "tree-sitter-gdscript", specifier = ">=6.1,<7" },{ name = "tree-sitter-go", specifier = ">=0.23,<1" },{ name = "tree-sitter-html", specifier = ">=0.23,<1" },{ name = "tree-sitter-java", specifier = ">=0.23,<1" },@@ -4033,6 +4035,17 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f7/a7/e8af7fb56dfd0d39df6f96e180d47d822407a7c98edc485b0c18ddd7ee28/tree_sitter_dart-0.1.0-cp38-abi3-win_amd64.whl", hash = "sha256:ee1d5f2109d2a206583227cfc4e2b0890f48700a0796207c2eecb5c3d7f23f63", size = 128126, upload-time = "2026-06-21T16:01:57.878Z" },]+[[package]]+name = "tree-sitter-gdscript"+version = "6.1.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d5/61/d681398e5551b27b3ae32026665392f41f8ca2764847acecc727312e462e/tree_sitter_gdscript-6.1.0.tar.gz", hash = "sha256:33c4406a47ca5e3c436849d2a9b878a161b6f4fda305cf5620f60abebf5acf9e", size = 107803, upload-time = "2026-09-04T09:04:59.03Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f4/2c/eab1b3890a99c85f97638b55d9d5745746fb3afc4b392e2363c7f8ed7d03/tree_sitter_gdscript-6.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:c588efba0ae4e1aa385caadcc19b3854b1270a855337ba5e4df1da4bbf5c38d1", size = 52192, upload-time = "2026-09-04T09:04:55.645Z" },+ { url = "https://files.pythonhosted.org/packages/e6/96/f724d35e7dcb443f6c8b3bb73e8a211d96abed8d829078511cfa9af8b2b6/tree_sitter_gdscript-6.1.0-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:85558120e50ee87b6847bb81273f7a5c8fadcbc7d4ee531701f8ed403d8de33c", size = 76616, upload-time = "2026-09-04T09:04:56.771Z" },+ { url = "https://files.pythonhosted.org/packages/34/10/58b1ad211163473162648a96be4ed3c25d98dfc1b2f846802b99e540424d/tree_sitter_gdscript-6.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:b2b87ea4cf21b3c33a00406840936f073b0db344ac46215f88edb8f72c72c761", size = 51341, upload-time = "2026-09-04T09:04:57.985Z" },+]+[[package]]name = "tree-sitter-go"version = "0.25.0"