Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(languages): parse Elixir to a full AST and move it to Good (#2127)

Raghav Chamadiya01e50e2f8475
diff --git a/README.md b/README.md
index 87e2821bf..dc8b2135b 100644
--- a/README.md
+++ b/README.md
@@ -474,7 +474,7 @@ the orchestrators. Full matrix and the contributor recipe:
## Supported languages
-**22 languages parsed to AST · 39 on a five-rung ladder · framework-aware across
+**23 languages parsed to AST · 39 on a five-rung ladder · framework-aware across
all of them.**
"Do you support X" has five useful answers, not two, so languages land on a
@@ -508,6 +508,7 @@ ladder and every rung says what it buys you.
<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" />
<img src="https://img.shields.io/badge/VB.NET-945DB7?style=flat-square&logo=dotnet&logoColor=white" alt="VB.NET" />
+ <img src="https://img.shields.io/badge/Elixir-6E4A7E?style=flat-square&logo=elixir&logoColor=white" alt="Elixir" />
&nbsp;<strong>· Partial &nbsp;</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" />
@@ -519,10 +520,10 @@ 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** (7) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET | All of the above except the full health suite |
+| **Good** (8) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir | 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 |
+| **Lightweight** (7) | Clojure · Haskell · Lean 4 · Erlang · F# · HTML · QML | A real file-to-file import graph, and no symbol-level claims |
| **Structural** (9) | Objective-C · R · Zig · Julia · Elm · OCaml · Crystal · Nim · D | Git history: blame, hotspots, co-change, ownership, bug history |
**Every language ships in the open-source distribution.** None is gated behind
diff --git a/ROADMAP.md b/ROADMAP.md
index 40590f2b9..da66d4cb0 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 you
support X" has five different useful answers. Each rung is defined, with what it
buys you, in
[docs/layers/LANGUAGE_SUPPORT.md](docs/layers/LANGUAGE_SUPPORT.md). Today that
-ladder covers **39 languages, 22 of them parsed to a full AST**.
+ladder covers **39 languages, 23 of them parsed to a full AST**.
### New languages
@@ -48,7 +48,7 @@ ladder covers **39 languages, 22 of them parsed to a full AST**.
| **Apex** | Planned | Salesforce estates, where the org is often the least documented system a company runs. Apex is Java-shaped, and Lightning Web Components are already covered as JavaScript and HTML. |
| **Ada** | Exploring | Defense and aerospace, long-lived and thinly documented, and usually in the same estates asking about COBOL. |
| **Objective-C** | Planned | Currently Structural, meaning history only. The grammar is mature, so this is a climb up the ladder rather than new ground. |
-| **Elixir**, **F#** | Planned | Currently Lightweight, meaning file-to-file imports. Both grammars are already on PyPI, so these are AST upgrades rather than new ground. |
+| **F#** | Planned | Currently Lightweight, meaning file-to-file imports. The grammar is already on PyPI, so this is an AST upgrade rather than new ground. |
| **Template dialects** (Django/Jinja, ERB, Blade, Thymeleaf, Go templates) | Planned | Today they parse cleanly as HTML and yield nothing, because `{% extends "base.html" %}` is plain text to an HTML parser. A stated ceiling, not an oversight. |
### Deepening languages we already parse
@@ -61,6 +61,7 @@ ladder covers **39 languages, 22 of them parsed to a full AST**.
| C | Planned | It shares the C++ grammar for parsing but reaches no health walker map, so it gets graph coverage without markers |
| SQL / dbt | Planned | Column-level blast radius |
| Object Pascal | Planned | Assertion and performance markers, a dedicated `uses` resolver |
+| Elixir | Planned | Health markers, and a call-resolution strategy so a bare-name call reaches beyond its own file |
| Razor / Blazor | Planned | `@using` and `@inject` edges so component tags resolve through imports, `@code` members as symbols rather than call edges only |
### Need a language that is not here
diff --git a/docs/README.md b/docs/README.md
index 9873cad11..98e4a2cc9 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: 22 parsed to a full AST, 39 on the five-rung ladder |
+| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 23 parsed to a full AST, 39 on the five-rung ladder |
| [layers/WIKI.md](layers/WIKI.md) | The generated wiki: page types, what `update` re-renders, styles, output language |
## Scale it
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index 7f38e5d61..30feb1b7d 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -9,8 +9,12 @@ centralised `LanguageRegistry`; per-language extraction logic lives in
`extractors/`; per-language import resolution lives in `resolvers/`; per-language
call-resolution strategy lives behind a seam in `call_resolver.py`. Adding a
language means dropping one file into each relevant subpackage and registering it
-in that subpackage's dispatcher. No edits are needed to `parser.py`, `graph.py`,
-`traverser.py`, or any analysis core file.
+in that subpackage's dispatcher. No edits are needed to `graph.py`,
+`traverser.py`, or any analysis core file. `parser.py` holds a short per-language
+block for a handful of languages whose grammar shape the generic path cannot
+read (C++ qualified definitions, Dart mixins, Object Pascal out-of-line methods,
+[Elixir](#elixir)); each is a few lines calling into a helper, and a new language
+needs one only when it hits the same kind of wall.
---
@@ -28,7 +32,7 @@ in that subpackage's dispatcher. No edits are needed to `parser.py`, `graph.py`,
- [Call resolution](#call-resolution) · [the strategy seam](#the-per-language-strategy-seam) · [resolution origins](#resolution-origins) · [receiver typing](#receiver-typing) · [inherited dispatch](#inherited-dispatch)
- [The edge vocabulary](#the-edge-vocabulary)
- [Multi-language files (the SFC pattern)](#multi-language-files-the-sfc-pattern)
-- [Per-language mechanics](#per-language-mechanics) · [GDScript / Godot](#gdscript--godot) · [VB.NET](#vbnet) · [QML](#qml) · [Flutter widget trees](#flutter-widget-trees)
+- [Per-language mechanics](#per-language-mechanics) · [Elixir](#elixir) · [GDScript / Godot](#gdscript--godot) · [VB.NET](#vbnet) · [QML](#qml) · [Flutter widget trees](#flutter-widget-trees)
- [Optional language-specific passes](#optional-language-specific-passes)
- [The three code-health dialect registries](#the-three-code-health-dialect-registries)
- [Workspace contract extraction](#workspace-contract-extraction)
@@ -76,7 +80,7 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
C/C++: compile_commands.json include directories
Dart: package:/dart:/relative URIs via the pubspec name map +
library-name index (dotted part-of)
- Lightweight tier (Elixir/Clojure/Haskell/Lean 4/Erlang/F#):
+ Lightweight tier (Clojure/Haskell/Lean 4/Erlang/F#):
regex-extracted imports vs a declared-module-name index
dbt: ref()/source() vs a per-project model-name index
Other: stem-map fallback (filename matching)
@@ -673,6 +677,37 @@ The same steps would fit Astro components; only the locator changes.
The resolution shapes that are specific to one language and are not derivable
from the recipe above.
+### Elixir
+
+Elixir is the one language whose grammar gives every construct the same node
+kind. `defmodule`, `def`, `defp`, `alias`, `import`, `use` and every `@attribute`
+all parse as a `call` whose `target` field is an `identifier` holding the keyword
+text, and a definition head (`add(a, b)` in `def add(a, b)`) is a `call` too.
+Three consequences the recipe above does not cover:
+
+- **`symbol_node_types` maps `call` to a non-callable placeholder kind**, refined
+ per keyword afterwards. A `def` sits inside its `defmodule`'s `do_block`, so a
+ callable mapping would make the callable-ancestor filter drop every function in
+ every module. The real kind comes from `refine_elixir_call_kind`.
+- **Parent detection cannot use the generic nesting walk**, which reads a `name`
+ field an Elixir `call` does not have. The module name is the first argument of
+ the call to `defmodule`, read by `_elixir_module_parent`.
+- **A definition head and a module attribute are dropped from the call graph
+ structurally**, in `_elixir_call_is_definitional`, because a query predicate
+ sees a node's own text and never its parent. Without it every function calls
+ itself, and every `@doc "..."` calls `doc`. A typespec attribute (`@spec`,
+ `@type`, `@callback`) also drops the calls inside it, since its body is types;
+ every other attribute keeps them, so `@endpoint Application.compile_env(...)`
+ still mints its edge. Reserved keywords are dropped by name through the spec's
+ `builtin_calls`, which is where Kernel's guards sit too.
+
+`alias Foo.{Bar, Baz}` names two modules in one statement (a `dot` over a
+`tuple`), expanded per member in `extractors/bindings/elixir.py` before the
+dedup-by-statement-text the generic path applies. No heritage is emitted: `use`
+and `@behaviour` are the nearest things Elixir has to inheritance and neither is
+one, and both already produce a module dependency through the import and
+type-reference captures.
+
### GDScript / Godot
`preload(...)`, `load(...)` and `extends "res://..."` resolve as absolute paths
diff --git a/docs/business/COMMERCIAL.md b/docs/business/COMMERCIAL.md
index ecd33c494..e0d0ab344 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 22 languages, two-tier dependency graph, call
+ (tree-sitter AST across 23 languages, two-tier dependency graph, call
resolution, heritage extraction, Leiden communities, PageRank / betweenness /
SCC), Git (hotspots, ownership, co-change pairs, bus factor, significant
commits, contributor profiles, module health), Documentation (a wiki page per
@@ -99,22 +99,22 @@ All of the following ship in `pip install repowise` today, free for internal use
## 3. First-class language coverage
-Repowise parses **22 languages to a full AST** and places **39 on a five-rung
+Repowise parses **23 languages to a full AST** and places **39 on a five-rung
ladder**, so "do you support X" gets the rung as its answer rather than a yes or a
no. Both numbers matter and neither is worth quoting alone.
-The 22 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,
+The 23 are the top three rungs. At **Full tier sit 13** (Python, TypeScript,
JavaScript, Svelte, Vue, Java, Kotlin, Go, Rust, C++, **C#**, Scala, and Ruby) with
AST parsing, import resolution, named bindings, call resolution, heritage
extraction, multi-project workspace resolvers, framework-aware edges, per-language
-dynamic-hint extractors, and code-health markers. A further **7 at Good tier** (C,
-Swift, PHP, Dart, Object Pascal/Delphi, GDScript, VB.NET) get all of that except the full
+dynamic-hint extractors, and code-health markers. A further **8 at Good tier** (C,
+Swift, PHP, Dart, Object Pascal/Delphi, GDScript, VB.NET, Elixir) 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 are
handled by dedicated extractors on top of that.
-Below the AST line the ladder continues rather than stopping: **8 at Lightweight**
-(Elixir, Clojure, Haskell, Lean 4, Erlang, F#, HTML, QML) get a real file-to-file import
+Below the AST line the ladder continues rather than stopping: **7 at Lightweight**
+(Clojure, Haskell, Lean 4, Erlang, F#, HTML, QML) get a real file-to-file import
graph with no symbol-level claims, and **9 at Structural** (Objective-C, R, Zig,
Julia, Elm, OCaml, Crystal, Nim, D) get the git intelligence layer only: blame,
hotspots, co-change, ownership and bug history, with no parsing. Stating the rung
diff --git a/docs/layers/GRAPH.md b/docs/layers/GRAPH.md
index da9989018..c3aceef0e 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/22-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="22 languages" />
+ <img src="https://img.shields.io/badge/23-languages-F59520?style=flat-square&labelColor=0A0A0A" alt="23 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.md
index 1e2c3877d..1940e4519 100644
--- a/docs/layers/INTELLIGENCE_LAYERS.md
+++ b/docs/layers/INTELLIGENCE_LAYERS.md
@@ -43,7 +43,7 @@ requirement for the index.
## Graph Intelligence
tree-sitter parses your source into a **two-tier dependency graph**: file nodes
-and symbol nodes (functions, classes, methods). 22 languages parse to a full
+and symbol nodes (functions, classes, methods). 23 languages parse to a full
AST; see [`LANGUAGE_SUPPORT.md`](LANGUAGE_SUPPORT.md) for per-language tiers.
A **confidence-scored call resolver** handles import aliases, barrel
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index d64b16cdf..ac186c885 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -1,6 +1,6 @@
# Language Support
-**22 languages parsed to a full AST · 39 on the five-rung ladder ·
+**23 languages parsed to a full AST · 39 on the five-rung ladder ·
framework-aware across all of them.** "Do you support X" has five useful answers
rather than two, so every language lands on a rung and the rung says what it
buys you. Everything else in your repo still appears in the wiki and is tracked
@@ -32,6 +32,7 @@ reference.
<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" />
<img src="https://img.shields.io/badge/VB.NET-945DB7?style=flat-square&logo=dotnet&logoColor=white" alt="VB.NET" />
+ <img src="https://img.shields.io/badge/Elixir-6E4A7E?style=flat-square&logo=elixir&logoColor=white" alt="Elixir" />
&nbsp;<strong>· Partial &nbsp;</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" />
@@ -55,13 +56,13 @@ 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** (7) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript and VB.NET don't yet. GDScript has a dedicated import resolver and Godot-specific framework edges but no named bindings (see [Known gaps](../architecture/language-support.md#gdscript--godot)) |
+| **Good** (8) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript, VB.NET and Elixir don't yet. GDScript has a dedicated import resolver and Godot-specific framework edges but no named bindings (see [Known gaps](../architecture/language-support.md#gdscript--godot)) |
| **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 |
+| **Lightweight** (7) | 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 **22 languages parsed to a full AST**; all five are
+The first three rungs are the **23 languages parsed to a full AST**; all five are
the **39** on the ladder. Both numbers are worth stating and neither is worth
stating alone, so if you only take one thing from this page, take the rung your
language sits on rather than either count.
@@ -251,6 +252,7 @@ bindings and heritage, with a dedicated workspace resolver per language.
| **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, plus scene, autoload and `class_name` edges (see [GDScript / Godot](../architecture/language-support.md#gdscript--godot)) |
| **VB.NET** | `.vb` | `Imports` through the same MSBuild project index C# uses: `.vbproj` / `.sln` parsing, `<RootNamespace>`-aware namespace lookup, NuGet package references |
+| **Elixir** | `.ex` `.exs` | `alias` / `import` / `require` / `use` against a `defmodule` index, with the Mix `lib/foo/bar.ex` → `Foo.Bar` convention as the fallback; `alias Foo.{Bar, Baz}` names both modules (no heritage: `use` and `@behaviour` are not inheritance) |
---
@@ -297,7 +299,7 @@ meaningless.
### Lightweight tier
-Elixir, Clojure, Haskell, Lean 4, Erlang, F# and HTML get a real file-level
+Clojure, Haskell, Lean 4, Erlang, F# and HTML get a real file-level
import graph: imports extracted per language and resolved against a declared
module-name index. The knowledge graph runs in flow/sparse mode on the result:
honest file-to-file dependencies, no symbol-level claims. F# additionally honours
@@ -407,7 +409,8 @@ Per-language mechanics behind these:
| GDScript | Good | The health dialects (complexity, performance, dataflow) that would take it to Full; the grammar supports all three |
| Object Pascal | Good | Assertion and performance markers, a dedicated `uses` resolver |
| VB.NET | Good | Health markers, project-level `<Import Include=...>` as implicit imports |
-| Elixir · F# | Good | AST upgrade (both grammars are available on PyPI) |
+| Elixir | Good | Health markers, and a call-resolution strategy beyond same-file |
+| F# | Good | AST upgrade (the grammar is available on PyPI) |
| SQL / dbt | — | Column-level blast radius |
| Shell | — | Shebang detection for extensionless executables |
| HTML | Lightweight | A regex import tier for template dialects, gated on a framework manifest |
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index c4e3e3c29..ac729f22f 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -86,6 +86,15 @@ _IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})
# these calls resolve to is the id C# binds.
_INHERITED_LANGUAGES = frozenset({"kotlin", "python", "typescript", "swift", "csharp"})
+# Languages where a bare name is scoped lexically: it can only mean the
+# caller's own module, an explicit ``import``, or the prelude. ``alias`` /
+# ``require`` / ``use`` bind a module name, never a function name, so repo-wide
+# uniqueness is no evidence and only wildcard imports may merge names.
+_LEXICAL_BARE_NAME_LANGUAGES = frozenset({"elixir"})
+
+# The sentinel an import that binds a whole module's public names carries.
+_WILDCARD_IMPORTED_NAMES = ["*"]
+
# Ancestors within four hops: ``heritage_ancestors`` bounds expansion, not
# reach, so 3 reaches 4.
_MAX_ANCESTOR_EXPAND_DEPTH = 3
@@ -972,7 +981,7 @@ class CallResolver:
merged = self._merged_import_symbols.get(file_path)
if merged is None:
merged = {}
- for imported_file in sorted(self._import_targets.get(file_path, ())):
+ for imported_file in sorted(self._bare_name_import_sources(file_path)):
if imported_file.startswith("external:"):
continue
for name, sym_id in self._file_symbols.get(imported_file, {}).items():
@@ -980,6 +989,28 @@ class CallResolver:
self._merged_import_symbols[file_path] = merged
return merged
+ def _bare_name_import_sources(self, file_path: str) -> set[str]:
+ """The imported files a bare name in *file_path* may be looked up in.
+
+ Every language but the lexically-scoped ones can use its whole import
+ set: a name reaching this tier arrived through some import, and which
+ directive carried it is not knowable from the resolved file alone. For
+ a language in ``_LEXICAL_BARE_NAME_LANGUAGES`` it is knowable and it
+ matters, so only imports that bind a whole module's public names count.
+ """
+ targets = self._import_targets.get(file_path, set())
+ if self._language_of(file_path) not in _LEXICAL_BARE_NAME_LANGUAGES:
+ return targets
+ parsed = self._parsed_files.get(file_path)
+ if parsed is None:
+ return targets
+ return {
+ imp.resolved_file
+ for imp in parsed.imports
+ if imp.resolved_file in targets
+ and list(imp.imported_names) == _WILDCARD_IMPORTED_NAMES
+ }
+
def _merged_methods_for(self, file_path: str) -> dict[tuple[str, str], str]:
"""Merged ``{(class, method) → symbol_id}`` across imports (see above)."""
merged = self._merged_import_methods.get(file_path)
@@ -1380,7 +1411,11 @@ class CallResolver:
candidate: str,
) -> ResolvedCall | None:
"""Tier 3's gates, applied to the one symbol the name resolves to."""
- if target_name in get_builtin_methods(self._language_of(file_path) or ""):
+ language = self._language_of(file_path) or ""
+ if language in _LEXICAL_BARE_NAME_LANGUAGES:
+ # Repo-wide uniqueness says nothing about a lexically scoped name.
+ return None
+ if target_name in get_builtin_methods(language):
return None
if candidate in self._non_callable_ids:
# Refused here rather than by falling through, so "this tier can
diff --git a/packages/core/src/repowise/core/ingestion/extractors/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/__init__.py
index 823d93a8b..1c6164f7b 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/__init__.py
@@ -5,6 +5,7 @@ from .docstrings import extract_module_docstring, extract_symbol_docstring
from .helpers import (
extract_go_receiver_type,
node_text,
+ refine_elixir_call_kind,
refine_go_type_kind,
refine_kotlin_class_kind,
refine_pascal_type_kind,
@@ -23,6 +24,7 @@ __all__ = [
"extract_module_docstring",
"extract_symbol_docstring",
"node_text",
+ "refine_elixir_call_kind",
"refine_go_type_kind",
"refine_kotlin_class_kind",
"refine_pascal_type_kind",
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/elixir.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/elixir.py
new file mode 100644
index 000000000..3b9796051
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/elixir.py
@@ -0,0 +1,39 @@
+"""Elixir directive expansion: one module path per named module.
+
+``alias Foo.{Bar, Baz}`` is a single statement naming two modules, and a
+single ``@import.module`` capture cannot carry both. The grammar parses the
+brace group as a ``dot`` whose ``left`` is the base ``alias`` and whose
+``right`` is a ``tuple`` of member aliases, so the expansion is structural
+here where the regex tier does it with a brace-group pattern.
+"""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ..helpers import node_text
+
+
+def elixir_import_modules(module_node: Node, src: str) -> list[str]:
+ """Return every module path named by one alias/import/require/use.
+
+ Returns an empty list for a form with no Elixir module to resolve --
+ ``import :math`` (an Erlang atom module) and ``alias __MODULE__.Foo``
+ (a self-reference), matching what the regex tier already skips.
+ """
+ if module_node.type == "alias":
+ text = node_text(module_node, src).strip()
+ return [text] if text else []
+ if module_node.type != "dot":
+ return []
+ left = module_node.child_by_field_name("left")
+ right = module_node.child_by_field_name("right")
+ if left is None or right is None or left.type != "alias" or right.type != "tuple":
+ return []
+ base = node_text(left, src).strip()
+ if not base:
+ return []
+ members = [
+ node_text(child, src).strip() for child in right.named_children if child.type == "alias"
+ ]
+ return [f"{base}.{member}" for member in members if member]
diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
index 9200fc649..a0a45b84d 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
@@ -40,6 +40,34 @@ def _csharp_clean_xml_doc(text: str) -> str:
return " ".join(body.split())
+def _elixir_attribute_doc(node: Node, src: str, names: tuple[str, ...]) -> str | None:
+ """Return the string held by ``@doc`` / ``@moduledoc``, if *node* is one.
+
+ A doc attribute is a ``unary_operator`` whose operator is ``@`` and whose
+ operand is a call to ``doc``/``moduledoc`` with a single string argument.
+ ``@doc false`` marks a function as undocumented and carries no string, so
+ it yields nothing.
+ """
+ if node.type != "unary_operator":
+ return None
+ operator = node.child_by_field_name("operator")
+ if operator is None or operator.type != "@":
+ return None
+ operand = node.child_by_field_name("operand")
+ if operand is None or operand.type != "call":
+ return None
+ target = operand.child_by_field_name("target")
+ if target is None or node_text(target, src).strip() not in names:
+ return None
+ arguments = next((c for c in operand.named_children if c.type == "arguments"), None)
+ if arguments is None:
+ return None
+ for child in arguments.named_children:
+ if child.type == "string":
+ return clean_string_literal(node_text(child, src)) or None
+ return None
+
+
def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
"""Extract a module/file-level docstring or leading comment."""
if lang == "python":
@@ -117,6 +145,20 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
return clean_jsdoc(text)
elif child.type not in ("comment", "package_header", "import"):
break
+ elif lang == "elixir":
+ # @moduledoc sits inside the defmodule's do_block, not at file top.
+ for child in root.children:
+ if child.type != "call":
+ continue
+ block = next((c for c in child.named_children if c.type == "do_block"), None)
+ if block is None:
+ continue
+ for statement in block.named_children:
+ doc = _elixir_attribute_doc(statement, src, ("moduledoc",))
+ if doc:
+ return doc
+ break
+
elif lang == "ruby":
lines: list[str] = []
for child in root.children:
@@ -298,6 +340,23 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
# KDoc: /** ... */ block comment before declaration
return find_preceding_block_comment(def_node, src, "/**")
+ elif lang == "elixir":
+ # @doc is a preceding sibling, with no AST link to the def it
+ # documents. Other attributes (@impl, @spec) may sit between the two,
+ # so walk back over attributes and stop at the first real statement.
+ parent = def_node.parent
+ if parent is None:
+ return None
+ siblings = list(parent.named_children)
+ index = next((i for i, s in enumerate(siblings) if s.id == def_node.id), -1)
+ for previous in reversed(siblings[:index]):
+ if previous.type != "unary_operator":
+ return None
+ doc = _elixir_attribute_doc(previous, src, ("doc",))
+ if doc:
+ return doc
+ return None
+
elif lang == "ruby":
# RDoc/YARD: # comment lines before method/class
return _find_preceding_line_doc_comments(def_node, src, "#")
diff --git a/packages/core/src/repowise/core/ingestion/extractors/helpers.py b/packages/core/src/repowise/core/ingestion/extractors/helpers.py
index cd585d35f..020e36edb 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/helpers.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/helpers.py
@@ -59,6 +59,38 @@ def refine_kotlin_class_kind(class_node: Node) -> str:
return "class"
+# Elixir definition keyword -> SymbolKind. Every definition is a `call` node,
+# so the node type says nothing; the keyword in the call's target says all.
+_ELIXIR_DEFINITION_KINDS = {
+ "defmodule": "module",
+ "defprotocol": "interface",
+ "defimpl": "impl",
+ "def": "function",
+ "defp": "function",
+ "defdelegate": "function",
+ "defmacro": "macro",
+ "defmacrop": "macro",
+ "defguard": "macro",
+ "defguardp": "macro",
+}
+
+
+def refine_elixir_call_kind(call_node: Node, src: str) -> str:
+ """Refine the placeholder ``module`` kind for an Elixir ``call`` node.
+
+ ``LANGUAGE_CONFIGS["elixir"]`` maps the one node type Elixir has to
+ ``module`` rather than to a callable kind on purpose: a ``def`` nested in
+ a ``defmodule`` has a ``call`` ancestor, so a callable mapping would make
+ ``_has_callable_ancestor`` drop every function in every module. The real
+ kind is read back here, after that filter has run.
+ """
+ target = call_node.child_by_field_name("target")
+ if target is None:
+ return "module"
+ keyword = node_text(target, src).strip()
+ return _ELIXIR_DEFINITION_KINDS.get(keyword, "module")
+
+
def refine_pascal_type_kind(decl_type_node: Node) -> str:
"""Refine the generic ``class`` kind for Pascal ``declType`` nodes.
diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
index 544ef0f83..1e1cf1a4e 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/visibility.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py
@@ -69,6 +69,18 @@ def public_by_default(_name: str, _mods: list[str]) -> str:
return "public"
+# Elixir spells privacy in the definition keyword rather than in a modifier:
+# `defp` / `defmacrop` / `defguardp` are module-private, their unsuffixed
+# forms are public. elixir.scm captures the keyword as @symbol.modifiers.
+_ELIXIR_PRIVATE_KEYWORDS = frozenset({"defp", "defmacrop", "defguardp"})
+
+
+def elixir_visibility(_name: str, modifier_texts: list[str]) -> str:
+ if any(text.strip() in _ELIXIR_PRIVATE_KEYWORDS for text in modifier_texts):
+ return "private"
+ return "public"
+
+
def kotlin_visibility(_name: str, modifier_texts: list[str]) -> str:
combined = " ".join(modifier_texts).lower()
if "private" in combined:
@@ -515,4 +527,5 @@ VISIBILITY_FNS: dict[str, Callable[[str, list[str]], str]] = {
"swift": swift_visibility,
"scala": scala_visibility,
"php": php_visibility,
+ "elixir": elixir_visibility,
}
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index 15b7c28da..687aeaad3 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -15,6 +15,7 @@ from dataclasses import dataclass, field
from .extractors.visibility import (
csharp_visibility,
dart_visibility,
+ elixir_visibility,
go_visibility,
java_visibility,
kotlin_visibility,
@@ -390,6 +391,27 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
{"class_declaration", "interface_declaration", "trait_declaration", "enum_declaration"}
),
),
+ "elixir": LanguageConfig(
+ symbol_node_types={
+ # Elixir's one node kind for every definition. "module" is a
+ # placeholder, refined per keyword in refine_elixir_call_kind --
+ # but it must stay a NON-callable kind: a `def` sits inside its
+ # `defmodule`'s do_block, so a callable mapping here would make
+ # _has_callable_ancestor drop every function in every module.
+ "call": "module",
+ },
+ import_node_types=["call"],
+ export_node_types=[], # every public function is exported; no syntax
+ # `defp` / `defmacrop` / `defguardp` are private; elixir.scm captures
+ # the defining keyword as @symbol.modifiers so this can read it.
+ visibility_fn=elixir_visibility,
+ parent_extraction="nesting",
+ # Deliberately empty. The generic nesting walk reads a `name` field,
+ # which an Elixir `call` does not have; the module name lives in the
+ # call's first argument, so parent detection runs through
+ # _elixir_module_parent instead.
+ parent_class_types=frozenset(),
+ ),
"pascal": LanguageConfig(
symbol_node_types={
# declType wraps class/record/interface/helper/enum/set/array/alias
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py b/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
index 2adae8d1c..d224b17da 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
@@ -1,4 +1,21 @@
-"""LanguageSpec for elixir (extracted from the registry data table)."""
+"""LanguageSpec for Elixir.
+
+Grammar: tree-sitter-elixir (PyPI ``tree-sitter-elixir``, import name
+``tree_sitter_elixir``), the elixir-lang project's own grammar.
+
+Elixir has one node kind for everything a definition or a directive can be:
+``defmodule``, ``def``, ``defp``, ``alias``, ``import``, ``use`` and every
+``@attribute`` all parse as a ``call`` whose ``target`` is an ``identifier``
+holding the keyword text. That single fact shapes the whole entry -- see
+``queries/elixir.scm`` for the query side and ``LANGUAGE_CONFIGS["elixir"]``
+for why the node type maps to a non-callable placeholder kind.
+
+No heritage is emitted. ``use Foo`` and ``@behaviour Foo`` are the nearest
+things Elixir has to inheritance, but neither is one: ``use`` injects code at
+compile time and ``@behaviour`` promises a callback set, and both already
+produce a module dependency through the import and type-reference captures.
+An ``extends`` edge would say something about the code that is not true.
+"""
from ..spec import LanguageSpec
@@ -14,7 +31,31 @@ SPEC = LanguageSpec(
entry_point_patterns=("application.ex",),
manifest_files=("mix.exs",),
extensions=frozenset({".ex", ".exs"}),
- is_passthrough=True,
- # Lightweight regex resolver: alias/import/use/require → defmodule index.
+ grammar_package="tree_sitter_elixir",
+ scm_file="elixir.scm",
+ # Kept "partial", not raised: the AST tier feeds the same regex-built
+ # defmodule index the lightweight tier fed, so the resolver's reach did
+ # not change -- only the accuracy of what reaches it.
import_support="partial",
+ # Kernel macros and special forms. Every definition keyword is here
+ # because `def add(a, b)` parses as a call to `def`, and the control-flow
+ # and attribute names because `if`, `case` and `@doc "..."` are calls
+ # too; none of them is an edge in anyone's call graph. Ordinary Kernel
+ # functions a project could plausibly redefine (``apply``, ``send``,
+ # ``to_string``) are deliberately absent: this set is matched
+ # receiver-blind, so a name here deletes the call site outright.
+ builtin_calls=frozenset({
+ "defmodule", "def", "defp", "defmacro", "defmacrop", "defguard",
+ "defguardp", "defdelegate", "defstruct", "defexception",
+ "defprotocol", "defimpl", "defoverridable",
+ "alias", "import", "require", "use",
+ "quote", "unquote", "unquote_splicing",
+ "if", "unless", "case", "cond", "with", "for", "receive", "try",
+ "raise", "reraise", "throw", "fn", "super",
+ "is_atom", "is_binary", "is_bitstring", "is_boolean", "is_exception",
+ "is_float", "is_function", "is_integer", "is_list", "is_map",
+ "is_map_key", "is_nil", "is_number", "is_pid", "is_port",
+ "is_reference", "is_struct", "is_tuple",
+ }),
+ color_hex="#6E4A7E",
)
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 032f2a1f3..942111f45 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -45,10 +45,12 @@ from .extractors import (
extract_module_docstring,
extract_symbol_docstring,
node_text,
+ refine_elixir_call_kind,
refine_go_type_kind,
refine_kotlin_class_kind,
refine_pascal_type_kind,
)
+from .extractors.bindings.elixir import elixir_import_modules
from .extractors.bindings.python import expand_bare_relative_imports
from .extractors.bindings.ts_js import (
declarator_binds_callable,
@@ -81,6 +83,10 @@ from .parser_helpers import (
_collect_error_nodes,
_count_arguments,
_dedupe_pascal_interface_symbols,
+ _elixir_call_is_definitional,
+ _elixir_is_template_definition,
+ _elixir_module_parent,
+ _elixir_symbol_name,
_find_enclosing_symbol,
_has_callable_ancestor,
_head_type_identifier,
@@ -1232,6 +1238,15 @@ class ASTParser:
if not name:
continue
+ if file_info.language == "elixir":
+ # A `def` inside `quote do ... end` is macro body, not a
+ # definition of the module that writes it.
+ if _elixir_is_template_definition(def_node, src):
+ continue
+ # `defimpl Proto, for: Type` is named for the module the
+ # compiler generates, not for the protocol alone.
+ name = _elixir_symbol_name(def_node, name, src)
+
export_type = cpp_export_type_defs.get(def_node.id)
if export_type is not None and name != export_type.name:
# The ordinary struct/class query sees the same specifier, but
@@ -1297,6 +1312,14 @@ class ASTParser:
if kind == "class" and file_info.language == "pascal" and def_node.type == "declType":
kind = refine_pascal_type_kind(def_node)
+ # Elixir: every definition is a ``call``, so the node type cannot
+ # name the kind and the config maps it to a deliberately
+ # non-callable placeholder (see refine_elixir_call_kind). The
+ # keyword in the call's target is what actually says what was
+ # defined.
+ if file_info.language == "elixir" and def_node.type == "call":
+ kind = refine_elixir_call_kind(def_node, src)
+
# Dart: a function is a ``function_signature`` whose BODY is a
# sibling ``function_body`` node (members wrap the signature in
# ``method_signature``). Two consequences the generic path can't
@@ -1467,6 +1490,12 @@ class ASTParser:
if parent_name is None and file_info.language == "pascal" and name_nodes:
parent_name = _qualified_pascal_parent(name_nodes[0], src)
+ # Elixir: the enclosing ``defmodule`` is a ``call`` with no
+ # ``name`` field for the generic nesting walk to read, so the
+ # module name has to be dug out of its first argument.
+ if parent_name is None and file_info.language == "elixir":
+ parent_name = _elixir_module_parent(def_node, src)
+
# A ``field_declaration`` cannot occur outside a class body, so a
# missing parent means the class did not parse. Grammar recovery,
# not a member function.
@@ -1584,6 +1613,7 @@ class ASTParser:
imports: list[Import] = []
seen_raws: set[str] = set()
seen_pascal_units: set[str] = set()
+ seen_elixir_modules: set[str] = set()
for capture_dict in matches:
stmt_nodes = capture_dict.get("import.statement", [])
@@ -1647,6 +1677,35 @@ class ASTParser:
)
continue
+ # Elixir: `alias Foo.{Bar, Baz}` names two modules in one
+ # statement, so dedup by raw statement text (below) would drop all
+ # but the first. Deduped by module path instead, which is also
+ # what makes a module aliased twice in one file one dependency.
+ if file_info.language == "elixir":
+ raw = _node_text(stmt_node, src).split("\n", 1)[0].strip()
+ directive_node = stmt_node.child_by_field_name("target")
+ directive = _node_text(directive_node, src).strip() if directive_node else ""
+ for module_path in elixir_import_modules(module_nodes[0], src):
+ if module_path in seen_elixir_modules:
+ continue
+ seen_elixir_modules.add(module_path)
+ imports.append(
+ Import(
+ raw_statement=raw,
+ # `import Foo` pulls in every public function;
+ # alias/require/use bind the module itself, which
+ # is the same wildcard sentinel the regex tier
+ # writes for this language.
+ module_path=module_path,
+ imported_names=["*"] if directive == "import" else [],
+ is_relative=False,
+ resolved_file=None,
+ bindings=[],
+ is_reexport=False,
+ )
+ )
+ continue
+
raw = _node_text(stmt_node, src).strip()
if raw in seen_raws:
continue
@@ -1879,6 +1938,13 @@ class ASTParser:
if target_name in _call_builtins:
continue
+ # Elixir: a definition head (`add(a, b)` in `def add(a, b)`) and a
+ # module attribute (`@doc "..."`) are both ``call`` nodes, and no
+ # query predicate can see the parent that tells them apart. Left
+ # in, every function in the repo would call itself.
+ if file_info.language == "elixir" and _elixir_call_is_definitional(site_node, src):
+ continue
+
line = site_node.start_point[0] + 1
receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else None
if receiver_name and file_info.language == "php":
diff --git a/packages/core/src/repowise/core/ingestion/parser_helpers.py b/packages/core/src/repowise/core/ingestion/parser_helpers.py
index e6f515ba5..f26c5fdab 100644
--- a/packages/core/src/repowise/core/ingestion/parser_helpers.py
+++ b/packages/core/src/repowise/core/ingestion/parser_helpers.py
@@ -130,6 +130,224 @@ def _qualified_cpp_parent(name_node: Node, src: str) -> str | None:
return text.rsplit("::", 1)[-1] or None
+# Elixir keywords that DEFINE rather than call. Every one of them parses as a
+# `call` whose target identifier holds the keyword text, so the head it takes
+# (`add(a, b)` in `def add(a, b)`) is a `call` node too.
+_ELIXIR_DEFINITION_KEYWORDS = frozenset(
+ {
+ "def",
+ "defp",
+ "defmacro",
+ "defmacrop",
+ "defguard",
+ "defguardp",
+ "defdelegate",
+ "defmodule",
+ "defprotocol",
+ "defimpl",
+ "defexception",
+ "defstruct",
+ }
+)
+
+# Module attributes whose body is a type expression, not code. `@spec
+# add(integer(), integer()) :: integer()` holds three `call` nodes and calls
+# nothing; every other attribute (`@config Application.compile_env(…)`) holds
+# real code and keeps its edges.
+_ELIXIR_TYPESPEC_ATTRIBUTES = frozenset(
+ {"spec", "type", "typep", "opaque", "callback", "macrocallback"}
+)
+
+# Elixir keywords that own a nested definition -- the parent a `def` reports.
+# `defimpl` is here because its definitions belong to the implementation module
+# the compiler generates, not to whatever module the block happens to sit in.
+_ELIXIR_MODULE_KEYWORDS = frozenset({"defmodule", "defprotocol", "defimpl"})
+
+# Node kinds that hold a list of statements. Reaching one while walking out of
+# an expression means the enclosing statement has been left.
+_ELIXIR_STATEMENT_HOLDERS = frozenset({"do_block", "block", "source", "stab_clause"})
+
+
+def _elixir_call_target_name(call_node: Node, src: str) -> str | None:
+ """The keyword or function name in an Elixir ``call`` node's target."""
+ if call_node.type != "call":
+ return None
+ target = call_node.child_by_field_name("target")
+ if target is None or target.type != "identifier":
+ return None
+ return node_text(target, src).strip() or None
+
+
+def _elixir_call_is_definitional(node: Node, src: str) -> bool:
+ """True when an Elixir ``call`` node defines or describes, never invokes.
+
+ Two shapes reach the call queries and must not become graph edges, and
+ neither can be excluded by a query predicate, which sees only the node's
+ own text and not its parent:
+
+ * a definition head -- ``def add(a, b)`` puts ``add(a, b)`` in the
+ ``arguments`` of a call to ``def``, so the head reads as a call to the
+ function being defined (a self-edge on every function in the repo). The
+ ``when``-guard form wraps that head in a ``binary_operator`` first.
+ * a module attribute -- ``@doc "…"`` is a call to ``doc``, and any
+ ``@whatever value`` is a call to ``whatever``. Inside a typespec
+ attribute the body is types, so its calls are dropped too; inside any
+ other attribute the body is ordinary code and keeps its edges.
+ """
+ head = node
+ parent = head.parent
+ if parent is not None and parent.type == "binary_operator":
+ operator = parent.child_by_field_name("operator")
+ if (
+ operator is not None
+ and operator.type == "when"
+ and parent.child_by_field_name("left") is not None
+ and parent.child_by_field_name("left").id == head.id
+ ):
+ head, parent = parent, parent.parent
+ if parent is not None and parent.type == "arguments":
+ outer = parent.parent
+ named = parent.named_children
+ if (
+ outer is not None
+ and named
+ and named[0].id == head.id
+ and _elixir_call_target_name(outer, src) in _ELIXIR_DEFINITION_KEYWORDS
+ ):
+ return True
+
+ # Walk out to the `@` unary_operator that opens this statement. Bounded by
+ # the statement rather than by a hop count: a union return type nests one
+ # binary_operator per member, so `@spec f(t) :: a() | b() | c() | d()` sits
+ # deeper than any fixed budget and used to leak its type names as calls.
+ ancestor: Node | None = node
+ while ancestor is not None:
+ holder = ancestor.parent
+ if holder is None or holder.type in _ELIXIR_STATEMENT_HOLDERS:
+ return False
+ if holder.type == "unary_operator":
+ operator = holder.child_by_field_name("operator")
+ if operator is not None and operator.type == "@":
+ if ancestor.id == node.id:
+ return True
+ return _elixir_call_target_name(ancestor, src) in _ELIXIR_TYPESPEC_ATTRIBUTES
+ ancestor = holder
+ return False
+
+
+def _elixir_definition_alias(call_node: Node, src: str) -> str | None:
+ """The first ``alias`` argument of a definition call, i.e. its module name."""
+ arguments = next(
+ (child for child in call_node.named_children if child.type == "arguments"), None
+ )
+ if arguments is None or not arguments.named_children:
+ return None
+ first = arguments.named_children[0]
+ if first.type != "alias":
+ return None
+ return node_text(first, src).strip() or None
+
+
+def _elixir_defimpl_for_type(call_node: Node, src: str) -> str | None:
+ """The ``for:`` type of a ``defimpl Proto, for: Type`` block."""
+ arguments = next(
+ (child for child in call_node.named_children if child.type == "arguments"), None
+ )
+ if arguments is None:
+ return None
+ for child in arguments.named_children:
+ if child.type != "keywords":
+ continue
+ for pair in child.named_children:
+ key = pair.child_by_field_name("key")
+ value = pair.child_by_field_name("value")
+ if key is None or value is None:
+ continue
+ if node_text(key, src).strip().rstrip(":") == "for":
+ return node_text(value, src).strip() or None
+ return None
+
+
+def _elixir_enclosing_module_alias(node: Node, src: str) -> str | None:
+ """The nearest enclosing ``defmodule``/``defprotocol`` name."""
+ ancestor = node.parent
+ while ancestor is not None:
+ if _elixir_call_target_name(ancestor, src) in ("defmodule", "defprotocol"):
+ return _elixir_definition_alias(ancestor, src)
+ ancestor = ancestor.parent
+ return None
+
+
+def _elixir_defimpl_name(call_node: Node, src: str) -> str | None:
+ """The module name the compiler generates for a ``defimpl`` block.
+
+ ``defimpl Jason.Encoder, for: Tuple`` compiles to a module called
+ ``Jason.Encoder.Tuple``, and that name is used here. Without it the
+ definitions inside the block are attributed to whatever module encloses it,
+ where they read as unused exports of a module that never declared them, and
+ two implementations of one protocol in one file mint two symbols under one
+ id.
+
+ The ``for:``-less form is only legal inside a ``defmodule`` and implements
+ the protocol for that module, so the enclosing module supplies the type.
+ """
+ protocol = _elixir_definition_alias(call_node, src)
+ if protocol is None:
+ return None
+ target_type = _elixir_defimpl_for_type(call_node, src) or _elixir_enclosing_module_alias(
+ call_node, src
+ )
+ return f"{protocol}.{target_type}" if target_type else protocol
+
+
+def _elixir_symbol_name(def_node: Node, default_name: str, src: str) -> str:
+ """The name a captured Elixir definition carries.
+
+ Only ``defimpl`` differs from its captured text; everything else names
+ itself. See ``_elixir_defimpl_name``.
+ """
+ if _elixir_call_target_name(def_node, src) != "defimpl":
+ return default_name
+ return _elixir_defimpl_name(def_node, src) or default_name
+
+
+def _elixir_is_template_definition(def_node: Node, src: str) -> bool:
+ """True for a definition inside ``quote do ... end``.
+
+ A ``def`` in a ``quote`` block is the body of a macro: it defines nothing in
+ the module that writes it and everything in the module that later invokes
+ the macro, which is a module no parser can name. Captured as a symbol it
+ reads as a method of the wrong module, and then as an unused export of it.
+ """
+ ancestor = def_node.parent
+ while ancestor is not None:
+ if _elixir_call_target_name(ancestor, src) == "quote":
+ return True
+ ancestor = ancestor.parent
+ return False
+
+
+def _elixir_module_parent(def_node: Node, src: str) -> str | None:
+ """Return the enclosing ``defmodule``/``defprotocol`` name, or None.
+
+ The generic nesting walk in ``ASTParser._find_parent`` reads
+ ``ancestor.child_by_field_name("name")``, and an Elixir ``call`` has no
+ ``name`` field -- the module name is the first argument of a call to
+ ``defmodule``. Nesting is the only thing that says which module a
+ function belongs to, so without this every ``def`` reads as a free
+ function.
+ """
+ ancestor = def_node.parent
+ while ancestor is not None:
+ keyword = _elixir_call_target_name(ancestor, src)
+ if keyword in _ELIXIR_MODULE_KEYWORDS:
+ if keyword == "defimpl":
+ return _elixir_defimpl_name(ancestor, src)
+ return _elixir_definition_alias(ancestor, src)
+ ancestor = ancestor.parent
+ return None
+
+
def _qualified_pascal_parent(name_node: Node, src: str) -> str | None:
"""Return the owning class for a Pascal out-of-line method header.
@@ -949,6 +1167,20 @@ def _pascal_head_type_identifier(type_node: Node, src: str) -> str | None:
# Per-language head-identifier extractor for ``@param.type`` captures.
# Defaults to the C#-shaped extractor; languages with a differently-shaped
# type grammar register their own here.
+def _elixir_head_type_identifier(type_node: Node, src: str) -> str | None:
+ """Return the module name in an Elixir type position.
+
+ A captured type is always a whole ``alias`` leaf (``%Foo.Bar{}``,
+ ``@behaviour GenServer``), and the grammar keeps a dotted module name in
+ one node, so the head is the node's own text. No unwrapping to do, and no
+ generic-argument shape to recurse into -- unlike every other language
+ here, which is why the shared C#-shaped extractor cannot serve.
+ """
+ if type_node.type != "alias":
+ return None
+ return node_text(type_node, src).strip() or None
+
+
TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {
"go": _go_head_type_identifier,
"c": _c_head_type_identifier,
@@ -959,6 +1191,7 @@ TYPE_HEAD_EXTRACTORS: dict[str, Callable[[Node, str], str | None]] = {
"kotlin": _kotlin_head_type_identifier,
"rust": _rust_head_type_identifier,
"pascal": _pascal_head_type_identifier,
+ "elixir": _elixir_head_type_identifier,
}
diff --git a/packages/core/src/repowise/core/ingestion/queries/elixir.scm b/packages/core/src/repowise/core/ingestion/queries/elixir.scm
new file mode 100644
index 000000000..47661d9f4
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/queries/elixir.scm
@@ -0,0 +1,146 @@
+; =============================================================================
+; repowise: Elixir symbol, import and call queries
+; tree-sitter-elixir (elixir-lang/tree-sitter-elixir) >= 0.3.5
+; =============================================================================
+;
+; Node-shape reference (verified against the loaded grammar, which ships no
+; node-types.json; the field list is `key left operand operator quoted_end
+; quoted_start right target value`, and nothing else):
+;
+; Every definition and every directive is an ordinary `call` node whose
+; `target` field is an `identifier` holding the keyword text itself:
+; `defmodule`, `def`, `defp`, `alias`, `import`, `use`, `@doc`'s `doc`.
+; There is no `defmodule` / `def` / `alias` node kind, and no `name`,
+; `arguments` or `body` FIELD; `arguments` and `do_block` are unlabeled
+; children found by node kind.
+;
+; def add(a, b), do: a + b
+; call target:(identifier "def") arguments{ call{target:(identifier "add")
+; arguments(a, b)}, keywords{do: …} }
+; defp helper(x) when is_integer(x) do … end
+; call target:(identifier "defp") arguments{ binary_operator{
+; left: call helper(x), operator: "when", right: call is_integer(x)} }
+; do_block{…} ; sibling of arguments, not inside it
+; def no_args, do: :ok
+; call target:(identifier "def") arguments{ identifier "no_args", keywords }
+; alias Foo.{Bar, Baz}
+; call target:(identifier "alias") arguments{ dot{left:(alias "Foo"),
+; right:(tuple (alias "Bar") (alias "Baz"))} }
+; Baz.run(x) call target:(dot left:(alias "Baz") right:(identifier "run"))
+; Foo.Bar a single (alias) leaf; the grammar does not split a dotted
+; module name into a dot chain
+;
+; Because a definition head (`add(a, b)`) is itself a `call`, and because a
+; module attribute (`@doc "…"`, `@spec f(t) :: t`) is a `call` under a `@`
+; unary_operator, the call patterns below would mint an edge for each one.
+; Those two shapes are dropped by `_elixir_call_is_definitional` in
+; parser_helpers.py, which is structural, a predicate cannot see a parent.
+; Reserved keyword targets (`def`, `if`, `case`, …) are Kernel macros and are
+; dropped by name through the spec's `builtin_calls`.
+
+; ---------------------------------------------------------------
+; Modules, protocols and protocol implementations. @symbol.def is the
+; whole `call`, so the symbol's line range covers the do_block body.
+;
+; @symbol.name is the captured alias for the first two. A `defimpl` is
+; renamed in the parser to the module the compiler generates for it
+; (`defimpl Jason.Encoder, for: Tuple` -> `Jason.Encoder.Tuple`): the
+; protocol alias alone would give two implementations in one file the
+; same id, and would leave the block's own definitions attributed to
+; whatever module encloses it.
+; ---------------------------------------------------------------
+
+((call
+ target: (identifier) @symbol.modifiers
+ (arguments . (alias) @symbol.name)) @symbol.def
+ (#any-of? @symbol.modifiers "defmodule" "defprotocol" "defimpl"))
+
+; ---------------------------------------------------------------
+; Functions, macros and guards. Three head shapes:
+; def add(a, b) -> nested call
+; def helper(x) when is_integer(x) -> `when` binary_operator
+; def no_args -> bare identifier, no parens
+; The keyword lands on @symbol.modifiers, which is what tells
+; `defp`/`defmacrop`/`defguardp` apart from their public forms
+; (extractors/visibility.py) and what names the kind
+; (refine_elixir_call_kind).
+; ---------------------------------------------------------------
+
+((call
+ target: (identifier) @symbol.modifiers
+ (arguments . (call
+ target: (identifier) @symbol.name
+ (arguments) @symbol.params))) @symbol.def
+ (#any-of? @symbol.modifiers
+ "def" "defp" "defmacro" "defmacrop" "defguard" "defguardp" "defdelegate"))
+
+((call
+ target: (identifier) @symbol.modifiers
+ (arguments . (binary_operator
+ left: (call
+ target: (identifier) @symbol.name
+ (arguments) @symbol.params)
+ operator: "when"))) @symbol.def
+ (#any-of? @symbol.modifiers
+ "def" "defp" "defmacro" "defmacrop" "defguard" "defguardp" "defdelegate"))
+
+((call
+ target: (identifier) @symbol.modifiers
+ (arguments . (identifier) @symbol.name)) @symbol.def
+ (#any-of? @symbol.modifiers
+ "def" "defp" "defmacro" "defmacrop" "defguard" "defguardp" "defdelegate"))
+
+; ---------------------------------------------------------------
+; Imports -- alias / import / require / use all bind a compile-time
+; module reference, which is the edge the resolver wants; `use` also
+; injects code, which makes the dependency stronger, not weaker.
+;
+; One pattern covers both `alias Foo.Bar` (an `alias` leaf) and
+; `alias Foo.{Bar, Baz}` (a `dot` over a `tuple`); the brace group is
+; expanded to one Import per member in extractors/bindings/elixir.py,
+; because a single @import.module capture cannot name two modules.
+; Erlang-atom modules (`import :math`) match neither branch and are
+; skipped, the same as in the regex tier.
+; ---------------------------------------------------------------
+
+((call
+ target: (identifier) @_directive
+ (arguments . [(alias) (dot)] @import.module)) @import.statement
+ (#any-of? @_directive "alias" "import" "require" "use"))
+
+; ---------------------------------------------------------------
+; Call graph. `arguments` is optional so a parenless call
+; (`Logger.info "x"`) is captured too; a bare identifier is not a
+; call node at all and is correctly never captured, including as a
+; pipe target (`x |> baz`).
+; ---------------------------------------------------------------
+
+(call
+ target: (identifier) @call.target
+ (arguments)? @call.arguments) @call.site
+
+(call
+ target: (dot
+ left: (_) @call.receiver
+ right: (identifier) @call.target)
+ (arguments)? @call.arguments) @call.site
+
+; ---------------------------------------------------------------
+; Type references -- a module named in a position that is neither a
+; call nor a directive. Two shapes are unambiguous:
+; %Foo.Bar{a: 1} a struct literal names its defining module
+; @behaviour GenServer
+; Typespec bodies (`@spec f(Foo.t()) :: :ok`) are deliberately left
+; out: every type there is a `call` node, so capturing them would
+; need the same structural filter the call patterns need, for a
+; reference kind Elixir has no type-ref strategy for yet.
+; ---------------------------------------------------------------
+
+(map (struct (alias) @param.type))
+
+((unary_operator
+ operator: "@"
+ operand: (call
+ target: (identifier) @_attribute
+ (arguments . (alias) @param.type)))
+ (#any-of? @_attribute "behaviour" "behavior"))
diff --git a/pyproject.toml b/pyproject.toml
index 7c0b58619..e4a09b5c9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -54,6 +54,7 @@ dependencies = [
"tree-sitter-bash>=0.23,<1",
"tree-sitter-gdscript>=6.1,<7",
"tree-sitter-vb-dotnet>=0.3,<1",
+ "tree-sitter-elixir>=0.3.5,<1",
# 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 on
diff --git a/tests/unit/ingestion/parser/test_elixir.py b/tests/unit/ingestion/parser/test_elixir.py
new file mode 100644
index 000000000..a6fa05b1d
--- /dev/null
+++ b/tests/unit/ingestion/parser/test_elixir.py
@@ -0,0 +1,361 @@
+"""Unit tests for the Elixir language pipeline.
+
+Tests parse inline byte strings so no filesystem I/O is needed. Elixir's one
+hard fact drives most of what is asserted here: `defmodule`, `def`, `alias`
+and `@doc` are all the same node kind (`call`), so the tests pin that a
+definition never reads as a call to itself, that a keyword never reads as a
+call, and that a module attribute never does either -- see
+docs/architecture/language-support.md for the registration recipe.
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.parser import ASTParser
+from tests.unit.ingestion.parser._helpers import _make_file_info
+
+
+def _ex(path: str = "lib/calc.ex") -> object:
+ return _make_file_info(path, "elixir")
+
+
+MODULE_SOURCE = b'''\
+defmodule Calc.Core do
+ @moduledoc """
+ Adds numbers.
+ """
+ @behaviour Calc.Behaviour
+
+ alias Calc.{Rounding, Formatting}
+ alias Calc.Legacy.Adder, as: Adder
+ import Enum, only: [map: 2]
+ require Logger
+ use GenServer
+
+ defstruct [:total]
+
+ @doc "Adds two numbers."
+ @spec add(integer(), integer()) :: integer()
+ def add(a, b), do: a + b
+
+ defp normalise(value) when is_integer(value) do
+ Logger.info("normalising")
+ round_up(value)
+ value |> Rounding.apply()
+ %Calc.Total{value: value}
+ end
+
+ def zero, do: 0
+
+ defmacro trace(expression), do: expression
+
+ defguardp is_small(value) when value < 10
+end
+'''
+
+
+class TestElixirSymbols:
+ def test_module_and_function_kinds(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ kinds = {(s.name, s.kind) for s in result.symbols}
+ # Every one of these is the same tree-sitter node kind (`call`); the
+ # kind comes from the keyword in the call's target.
+ assert ("Calc.Core", "module") in kinds
+ assert ("add", "method") in kinds
+ assert ("normalise", "method") in kinds
+ assert ("zero", "method") in kinds
+ assert ("trace", "macro") in kinds
+ assert ("is_small", "macro") in kinds
+
+ def test_functions_take_the_enclosing_module_as_parent(self, parser: ASTParser) -> None:
+ # A `def` nested in a `defmodule` has a `call` ancestor. If the config
+ # mapped `call` to a callable kind, the callable-ancestor filter would
+ # drop every function here.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ parents = {s.name: s.parent_name for s in result.symbols}
+ assert parents["add"] == "Calc.Core"
+ assert parents["normalise"] == "Calc.Core"
+ assert parents["Calc.Core"] is None
+
+ def test_private_keywords_set_private_visibility(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ visibility = {s.name: s.visibility for s in result.symbols}
+ assert visibility["normalise"] == "private"
+ assert visibility["is_small"] == "private"
+ assert visibility["add"] == "public"
+
+ def test_zero_arity_and_guarded_heads_are_both_found(self, parser: ASTParser) -> None:
+ # `def zero` has a bare identifier head, `defp normalise(v) when ...`
+ # wraps its head in a `when` binary_operator, and `def add(a, b)` has
+ # the plain nested-call head. Three shapes, one concept.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ names = {s.name for s in result.symbols}
+ assert {"add", "normalise", "zero"} <= names
+
+ def test_nested_module_is_its_own_symbol(self, parser: ASTParser) -> None:
+ source = b"""\
+defmodule Outer do
+ defmodule Inner do
+ def run, do: :ok
+ end
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["Inner"].kind == "module"
+ assert by_name["Inner"].parent_name == "Outer"
+ assert by_name["run"].parent_name == "Inner"
+
+ def test_defimpl_is_named_for_the_module_the_compiler_generates(
+ self, parser: ASTParser
+ ) -> None:
+ # `defimpl Jason.Encoder, for: Tuple` compiles to a module called
+ # `Jason.Encoder.Tuple`. Named for the protocol alone, its `def`s were
+ # attributed to the enclosing module and read as unused exports of it.
+ source = b"""\
+defmodule Shop.Logs do
+ defimpl Jason.Encoder, for: Tuple do
+ def encode(value, opts), do: value
+ end
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["Jason.Encoder.Tuple"].kind == "impl"
+ assert by_name["Jason.Encoder.Tuple"].parent_name == "Shop.Logs"
+ assert by_name["encode"].parent_name == "Jason.Encoder.Tuple"
+
+ def test_two_impls_of_one_protocol_get_distinct_ids(self, parser: ASTParser) -> None:
+ source = b"""\
+defimpl Proto, for: Foo do
+ def run(x), do: x
+end
+
+defimpl Proto, for: Bar do
+ def run(x), do: x
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ ids = [s.id for s in result.symbols]
+ assert len(ids) == len(set(ids)), ids
+ assert {"Proto.Foo", "Proto.Bar"} <= {s.name for s in result.symbols}
+
+ def test_a_defimpl_without_for_takes_the_enclosing_module_as_its_type(
+ self, parser: ASTParser
+ ) -> None:
+ # The `for:`-less form is only legal inside a `defmodule` and
+ # implements the protocol for that module.
+ source = b"""\
+defmodule Selfish do
+ defimpl Inspect do
+ def inspect(value, opts), do: value
+ end
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ by_name = {s.name: s for s in result.symbols}
+ assert by_name["Inspect.Selfish"].parent_name == "Selfish"
+ assert by_name["inspect"].parent_name == "Inspect.Selfish"
+
+ def test_a_def_inside_quote_is_not_a_symbol(self, parser: ASTParser) -> None:
+ # A `def` in a `quote` block defines nothing in the module that writes
+ # it: it is macro body, injected into whichever module later calls the
+ # macro. Captured, it reads as a method of the wrong module.
+ source = b"""\
+defmodule Shop.Logs do
+ defmacro __using__(_opts) do
+ quote do
+ def injected(x), do: x
+ end
+ end
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ names = {s.name for s in result.symbols}
+ assert "injected" not in names
+ assert "__using__" in names
+
+ def test_protocol_is_an_interface(self, parser: ASTParser) -> None:
+ source = b"""\
+defprotocol Serialisable do
+ def dump(value)
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ kinds = {(s.name, s.kind) for s in result.symbols}
+ assert ("Serialisable", "interface") in kinds
+ assert ("dump", "method") in kinds
+
+
+class TestElixirImports:
+ def test_directives_become_imports(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ modules = [i.module_path for i in result.imports]
+ assert "Calc.Legacy.Adder" in modules
+ assert "Enum" in modules
+ assert "Logger" in modules
+ assert "GenServer" in modules
+
+ def test_multi_alias_yields_one_import_per_member(self, parser: ASTParser) -> None:
+ # `alias Calc.{Rounding, Formatting}` is one statement naming two
+ # modules; dedup by raw statement text would keep only the first.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ modules = [i.module_path for i in result.imports]
+ assert "Calc.Rounding" in modules
+ assert "Calc.Formatting" in modules
+
+ def test_import_binds_every_public_name(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ by_module = {i.module_path: i for i in result.imports}
+ assert by_module["Enum"].imported_names == ["*"]
+ # alias/require/use bind the module itself, not its functions.
+ assert by_module["Logger"].imported_names == []
+
+ def test_erlang_atom_module_is_skipped(self, parser: ASTParser) -> None:
+ # `:math` is an Erlang module: no Elixir file can ever resolve it.
+ result = parser.parse_file(_ex(), b"defmodule A do\n import :math\nend\n")
+ assert [i.module_path for i in result.imports] == []
+
+
+class TestElixirCalls:
+ def test_local_remote_and_pipe_targets(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ calls = {(c.receiver_name, c.target_name) for c in result.calls}
+ assert (None, "round_up") in calls
+ assert ("Logger", "info") in calls
+ # The right side of `|>` is already a call node, so it needs no
+ # pattern of its own.
+ assert ("Rounding", "apply") in calls
+
+ def test_definition_keywords_are_never_call_targets(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ targets = {c.target_name for c in result.calls}
+ reserved = {
+ "def",
+ "defp",
+ "defmodule",
+ "defmacro",
+ "defguardp",
+ "defstruct",
+ "alias",
+ "import",
+ "require",
+ "use",
+ }
+ assert not (targets & reserved)
+
+ def test_a_definition_head_is_not_a_call_to_itself(self, parser: ASTParser) -> None:
+ # `def add(a, b)` puts `add(a, b)` inside the arguments of a call to
+ # `def`, so the head reads as a call unless it is filtered out.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ assert not [c for c in result.calls if c.target_name in ("add", "normalise", "zero")]
+
+ def test_a_deep_union_typespec_still_leaks_nothing(self, parser: ASTParser) -> None:
+ # A union return type nests one binary_operator per member, so the type
+ # names sit deeper than any fixed ancestor budget. The walk is bounded
+ # by the statement instead.
+ source = b"""\
+defmodule A do
+ @spec f(integer()) ::
+ {:ok, integer()} | {:error, atom()} | {:maybe, list(integer())} | {:x, map()}
+ def f(x), do: x
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ assert result.calls == [], result.calls
+
+ def test_module_attributes_are_not_calls(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ targets = {c.target_name for c in result.calls}
+ assert not (targets & {"doc", "moduledoc", "spec", "behaviour"})
+
+ def test_typespec_bodies_are_not_calls(self, parser: ASTParser) -> None:
+ # `@spec add(integer(), integer()) :: integer()` holds three call
+ # nodes and invokes nothing.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ assert not [c for c in result.calls if c.target_name == "integer"]
+
+ def test_code_in_a_non_typespec_attribute_keeps_its_edges(self, parser: ASTParser) -> None:
+ # A module attribute computed at compile time is real code.
+ source = b"""\
+defmodule A do
+ @endpoint Application.compile_env(:app, :endpoint)
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ calls = {(c.receiver_name, c.target_name) for c in result.calls}
+ assert ("Application", "compile_env") in calls
+ assert "endpoint" not in {c.target_name for c in result.calls}
+
+ def test_guard_calls_resolve_as_ordinary_calls(self, parser: ASTParser) -> None:
+ # A guard can be a project's own `defguard`, so the edge is kept;
+ # Kernel's own guards are dropped by name through builtin_calls.
+ source = b"""\
+defmodule A do
+ def run(x) when is_small(x), do: x
+end
+"""
+ result = parser.parse_file(_ex(), source)
+ targets = {c.target_name for c in result.calls}
+ assert "is_small" in targets
+ assert "is_integer" not in targets
+
+ def test_calls_are_attributed_to_their_enclosing_function(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ info = next(c for c in result.calls if c.target_name == "info")
+ assert info.caller_symbol_id == "lib/calc.ex::Calc.Core::normalise"
+
+
+class TestElixirTypeReferences:
+ def test_struct_literal_and_behaviour_are_type_references(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ names = {t.type_name for t in result.type_refs}
+ assert "Calc.Total" in names
+ assert "Calc.Behaviour" in names
+
+ def test_a_type_position_never_becomes_a_call(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ targets = {c.target_name for c in result.calls}
+ assert "Calc.Total" not in targets
+ assert "Calc.Behaviour" not in targets
+
+
+class TestElixirDocstrings:
+ def test_moduledoc_becomes_the_module_docstring(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ assert result.docstring == "Adds numbers."
+
+ def test_doc_attaches_to_the_following_definition(self, parser: ASTParser) -> None:
+ # @doc and the def it documents are siblings with no AST link, and
+ # @spec sits between them here.
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ add = next(s for s in result.symbols if s.name == "add")
+ assert add.docstring == "Adds two numbers."
+
+ def test_an_undocumented_function_has_no_docstring(self, parser: ASTParser) -> None:
+ result = parser.parse_file(_ex(), MODULE_SOURCE)
+ zero = next(s for s in result.symbols if s.name == "zero")
+ assert zero.docstring is None
+
+
+class TestElixirEncoding:
+ def test_non_ascii_source_keeps_byte_accurate_names(self, parser: ASTParser) -> None:
+ # Function names, docs and string arguments are all multi-byte here,
+ # so any byte-offset slicing of the decoded source misaligns. The
+ # module alias stays ASCII on purpose: tree-sitter-elixir's `alias`
+ # rule accepts ASCII only, which is the grammar's limit, not ours.
+ source = """\
+defmodule Greeter do
+ @doc "Grüße, Welt"
+ def grüßen(name), do: "Hallo #{name}"
+
+ def caller, do: grüßen("Ünal")
+end
+""".encode()
+ result = parser.parse_file(_ex(), source)
+ names = {s.name for s in result.symbols}
+ assert "grüßen" in names
+ greeter = next(s for s in result.symbols if s.name == "grüßen")
+ assert greeter.docstring == "Grüße, Welt"
+ assert ("caller", "grüßen") in {
+ (c.caller_symbol_id.rsplit("::", 1)[-1], c.target_name) for c in result.calls
+ }
diff --git a/tests/unit/ingestion/test_elixir_bare_name_scope.py b/tests/unit/ingestion/test_elixir_bare_name_scope.py
new file mode 100644
index 000000000..7056a0891
--- /dev/null
+++ b/tests/unit/ingestion/test_elixir_bare_name_scope.py
@@ -0,0 +1,189 @@
+"""Elixir bare-name call scope.
+
+A bare, receiver-less name in Elixir can only mean the caller's own module, a
+module an explicit ``import`` brought in, or Kernel. ``alias`` / ``require`` /
+``use`` bind a module name and never a function name, so the resolver must not
+answer such a call from repo-wide uniqueness or from a non-import edge.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+from repowise.core.ingestion.call_resolver import CallResolver
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import parse_file
+
+
+def _file_info(rel: str, abs_: Path) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=str(abs_),
+ language="elixir",
+ size_bytes=abs_.stat().st_size,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _parse_all(tmp_path: Path, files: dict[str, str]) -> dict[str, ParsedFile]:
+ out: dict[str, ParsedFile] = {}
+ for rel, content in files.items():
+ abs_ = tmp_path / rel
+ abs_.parent.mkdir(parents=True, exist_ok=True)
+ abs_.write_text(content, encoding="utf-8")
+ out[rel] = parse_file(_file_info(rel, abs_), content.encode("utf-8"))
+ return out
+
+
+def _link(parsed: dict[str, ParsedFile], importer: str, module_path: str, target: str) -> None:
+ """Stamp the resolved file on one import, as GraphBuilder does before resolution."""
+ for imp in parsed[importer].imports:
+ if imp.module_path == module_path:
+ imp.resolved_file = target
+ return
+ raise AssertionError(f"no import of {module_path} in {importer}")
+
+
+def _edges(parsed, tmp_path, import_targets):
+ resolver = CallResolver(parsed, import_targets, repo_path=str(tmp_path))
+ return [
+ (rc.caller_id, rc.callee_id, rc.origin)
+ for path, pf in parsed.items()
+ for rc in resolver.resolve_file(path, pf.calls)
+ ]
+
+
+CONNECT = """\
+defmodule Shop.Tenants.Connect do
+ def connect(socket, params, opts), do: {socket, params, opts}
+end
+"""
+
+
+class TestAliasDoesNotImportFunctionNames:
+ def test_alias_never_answers_a_bare_call(self, tmp_path: Path) -> None:
+ # `alias Shop.Tenants.Connect` makes the capitalised module
+ # reachable as `Connect.foo`. It says nothing about a bare, lowercase
+ # `connect/3`, which here is Phoenix.ChannelTest's.
+ files = {
+ "lib/connect.ex": CONNECT,
+ "test/channel_test.exs": """\
+defmodule ChannelTest do
+ alias Shop.Tenants.Connect
+
+ def run do
+ connect(UserSocket, %{}, [])
+ end
+end
+""",
+ }
+ parsed = _parse_all(tmp_path, files)
+ _link(parsed, "test/channel_test.exs", "Shop.Tenants.Connect", "lib/connect.ex")
+ edges = _edges(
+ parsed, tmp_path, {"test/channel_test.exs": {"lib/connect.ex"}, "lib/connect.ex": set()}
+ )
+ assert not [e for e in edges if e[1].endswith("::connect")], edges
+
+ def test_an_explicit_import_does_answer_it(self, tmp_path: Path) -> None:
+ # The control: `import` is the one directive that brings bare function
+ # names into scope, and it must keep working.
+ files = {
+ "lib/connect.ex": CONNECT,
+ "test/channel_test.exs": """\
+defmodule ChannelTest do
+ import Shop.Tenants.Connect
+
+ def run do
+ connect(UserSocket, %{}, [])
+ end
+end
+""",
+ }
+ parsed = _parse_all(tmp_path, files)
+ _link(parsed, "test/channel_test.exs", "Shop.Tenants.Connect", "lib/connect.ex")
+ edges = _edges(
+ parsed, tmp_path, {"test/channel_test.exs": {"lib/connect.ex"}, "lib/connect.ex": set()}
+ )
+ assert (
+ "test/channel_test.exs::ChannelTest::run",
+ "lib/connect.ex::Shop.Tenants.Connect::connect",
+ "import_merged",
+ ) in edges, edges
+
+ def test_use_does_not_answer_it_either(self, tmp_path: Path) -> None:
+ # `use` runs a macro that may itself inject an `import`, which no
+ # parser can see. The honest answer is no edge, not a guessed one.
+ files = {
+ "lib/connect.ex": CONNECT,
+ "test/channel_test.exs": """\
+defmodule ChannelTest do
+ use Shop.Tenants.Connect
+
+ def run do
+ connect(UserSocket, %{}, [])
+ end
+end
+""",
+ }
+ parsed = _parse_all(tmp_path, files)
+ _link(parsed, "test/channel_test.exs", "Shop.Tenants.Connect", "lib/connect.ex")
+ edges = _edges(
+ parsed, tmp_path, {"test/channel_test.exs": {"lib/connect.ex"}, "lib/connect.ex": set()}
+ )
+ assert not [e for e in edges if e[1].endswith("::connect")], edges
+
+
+class TestGlobalUniqueRefusal:
+ def test_a_uniquely_named_function_elsewhere_is_not_the_answer(
+ self, tmp_path: Path
+ ) -> None:
+ # `execute` here is Ecto.Migration's macro, in scope through
+ # `use Ecto.Migration`. That exactly one app module also defines
+ # `execute` is a coincidence, not evidence.
+ files = {
+ "lib/telemetry.ex": """\
+defmodule Shop.Telemetry do
+ def execute(event), do: event
+end
+""",
+ "priv/migrations/20240919163303_add_payload.exs": """\
+defmodule Shop.Repo.Migrations.AddPayload do
+ use Ecto.Migration
+
+ def change do
+ execute("alter table messages add column payload jsonb")
+ end
+end
+""",
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _edges(parsed, tmp_path, {})
+ assert not [e for e in edges if e[1].endswith("::execute")], edges
+
+ def test_a_same_module_bare_call_still_resolves(self, tmp_path: Path) -> None:
+ # The refusals above must not reach the one tier Elixir's own scoping
+ # rules do license: a bare name defined in the caller's own module.
+ files = {
+ "lib/app.ex": """\
+defmodule Shop.Application do
+ def start(_type, _args) do
+ setup_region_mapping()
+ end
+
+ defp setup_region_mapping, do: :ok
+end
+""",
+ }
+ parsed = _parse_all(tmp_path, files)
+ edges = _edges(parsed, tmp_path, {})
+ assert (
+ "lib/app.ex::Shop.Application::start",
+ "lib/app.ex::Shop.Application::setup_region_mapping",
+ "same_file",
+ ) in edges, edges
diff --git a/tests/unit/ingestion/test_unparseable_language_sets.py b/tests/unit/ingestion/test_unparseable_language_sets.py
index 6cd4ece02..592205e32 100644
--- a/tests/unit/ingestion/test_unparseable_language_sets.py
+++ b/tests/unit/ingestion/test_unparseable_language_sets.py
@@ -68,10 +68,11 @@ def test_real_data_formats_are_in_the_set():
def test_passthrough_code_languages_are_not_in_the_set():
"""Languages awaiting a grammar are NOT "data".
- clojure/elixir/haskell are ``is_passthrough`` but real code: zero symbols
+ clojure/haskell are ``is_passthrough`` but real code: zero symbols
there is a gap in us, not a property of the file, so they must stay
- eligible for the analyses this set exempts.
+ eligible for the analyses this set exempts. Elixir used to sit here and
+ now parses to an AST, which is where a language in this state is headed.
"""
- for tag in ("clojure", "elixir", "haskell"):
+ for tag in ("clojure", "haskell"):
assert tag in REGISTRY.passthrough_languages(), tag
assert tag not in REGISTRY.unparseable_data_languages(), tag
diff --git a/uv.lock b/uv.lock
index 7d2b0bc3d..64e0a954f 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-elixir" },
{ name = "tree-sitter-gdscript" },
{ name = "tree-sitter-go" },
{ name = "tree-sitter-html" },
@@ -3181,6 +3182,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-elixir", specifier = ">=0.3.5,<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" },
@@ -4037,6 +4039,22 @@ 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-elixir"
+version = "0.3.5"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e8/83/0501ee426bcd40cf5f765ce66ff2e7136d438ff4e65aeb08991f9826d4e5/tree_sitter_elixir-0.3.5.tar.gz", hash = "sha256:ead089393b1ce732304e6b6fb0bc0ab79e3295663d697be025bd49f0f367b74d", size = 445087, upload-time = "2026-03-02T13:31:09.378Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2f/29/c2c2b028c49f3c08270dd01ee72a9e735d59c59499d0b7ed09f45157f6b8/tree_sitter_elixir-0.3.5-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:514078a2f68d27da9a1e6b6e9601b8456faba6260ecfa252e898a848c4f8584d", size = 163335, upload-time = "2026-03-02T13:31:00.053Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/d7/f0ad3de0b359a8a1f694268855bb34134c88774fa2276cb33413163c0403/tree_sitter_elixir-0.3.5-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:015f537731af690cfa238b0fb76a8af4f0d1a2c54a38563f159926d2967ce650", size = 174644, upload-time = "2026-03-02T13:31:01.198Z" },
+ { url = "https://files.pythonhosted.org/packages/31/35/78c94e164542ad08098b83cb7e046261f3ab2edade96e29727dd209bfa35/tree_sitter_elixir-0.3.5-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ebfe3491a3d00ac50b12a3bfcabb1c564f3809ed8a095099fe87f49d6b3987e6", size = 182857, upload-time = "2026-03-02T13:31:02.512Z" },
+ { url = "https://files.pythonhosted.org/packages/3c/50/69ed38e335d1228f6eb1c12707269fefb349710aaf0b6d4a730ea88b95c2/tree_sitter_elixir-0.3.5-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d1159057f914d4468fc53cb9d7e8369f8a7826e1d07765bb53fbf391e6058863", size = 184199, upload-time = "2026-03-02T13:31:03.512Z" },
+ { url = "https://files.pythonhosted.org/packages/82/8a/8233648868bf2432cb7ab85ffc4ac4b2b1cf4addf75d6a62bacd2dba6f73/tree_sitter_elixir-0.3.5-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:d6187b4d592bfb31760799ac6ddbb5a2457ba0a612de43d77bcbcd5f00cc49bf", size = 183571, upload-time = "2026-03-02T13:31:04.728Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/4a/f78454d228835a619db173f816090ab0c86f865987e2504280ced7fdbd5c/tree_sitter_elixir-0.3.5-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b5d5d8aa077ff244d24406b1fb5a17c03a2919c5183c51ca35654870d08b239b", size = 182618, upload-time = "2026-03-02T13:31:06.018Z" },
+ { url = "https://files.pythonhosted.org/packages/c6/a5/634b505a4c349becc753c1faef5350f32ca027297c16a45fb0942967db2a/tree_sitter_elixir-0.3.5-cp39-abi3-win_amd64.whl", hash = "sha256:c0b5df229405d42ba5c94254d92e414b1f200be8422561d243ae5b3558e84f76", size = 167219, upload-time = "2026-03-02T13:31:07.071Z" },
+ { url = "https://files.pythonhosted.org/packages/77/f2/711baae88f98e3a30efee9383fbcb603a3188c20941643c71d3d3b936d66/tree_sitter_elixir-0.3.5-cp39-abi3-win_arm64.whl", hash = "sha256:fee42b90962e1e131cc31720f3038410291b2196ed231e00c1721597fc0567df", size = 164003, upload-time = "2026-03-02T13:31:08.013Z" },
+]
+
[[package]]
name = "tree-sitter-gdscript"
version = "6.1.0"