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.

fix(health): correct the Elixir, F# and Objective-C complexity maps (#2225)

Raghav Chamadiya1223f30a1b05
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 7d2b7a03d..04511fb0e 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -58,7 +58,7 @@ 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** (10) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# · Objective-C | Everything above except the full health suite. Dart and Object Pascal *do* get health markers; C, Swift, PHP, GDScript, VB.NET, Elixir, F# and Objective-C 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** (10) | C · Swift · PHP · Dart · Object Pascal · GDScript · VB.NET · Elixir · F# · Objective-C | Everything above except the full health suite. Dart and Object Pascal *do* get health markers, and C, F# and Objective-C get the complexity-derived ones; 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** (6) | Clojure · Haskell · Lean 4 · Erlang · HTML · QML | A real file-to-file import graph, no symbol-level claims |
@@ -413,8 +413,8 @@ Per-language mechanics behind these:
| Object Pascal | Good | Assertion and performance markers, a dedicated `uses` resolver |
| VB.NET | Good | Health markers, project-level `<Import Include=...>` as implicit imports |
| Elixir | Good | Health markers, and a call-resolution strategy beyond same-file |
-| F# | Good | Health markers, and a resolver that reads the AST index instead of the declared-name regex |
-| Objective-C | Good | Health markers, a resolver that reads the Xcode project rather than file stems, and pairing a header with its implementation across files |
+| F# | Good | The health markers beyond complexity, and a resolver that reads the AST index instead of the declared-name regex |
+| Objective-C | Good | The health markers beyond complexity, a resolver that reads the Xcode project rather than file stems, and pairing a header with its implementation across files |
| 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/analysis/health/complexity/ast_utils.py b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
index 116c97114..a21f7816e 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/ast_utils.py
@@ -63,6 +63,31 @@ def _find_name(node: Node) -> str:
leaf = _pascal_unwrap_name(name)
if leaf.text is not None:
return leaf.text.decode("utf-8", errors="replace")
+ # F#: ``function_or_value_defn`` carries no ``name`` field and no direct
+ # identifier child — the name sits one hop down, under
+ # ``function_declaration_left`` (``let f x = ...`` → ``f``). Without this
+ # every F# row reported ``<anonymous>``, which is not much use in a report.
+ if node.type == "function_or_value_defn":
+ for child in node.children:
+ if child.type == "function_declaration_left":
+ for leaf in child.children:
+ if leaf.type == "identifier" and leaf.text is not None:
+ return leaf.text.decode("utf-8", errors="replace")
+ # F# members nest one level deeper again and qualify the name with the
+ # self identifier: ``member_defn → method_or_prop_defn → property_or_ident``
+ # holds ``this`` and ``M`` for ``member this.M(x)``. The method name is the
+ # last identifier, which also reads correctly for an unqualified ``member
+ # M(x)``, where it is the only one.
+ if node.type == "member_defn":
+ for child in node.children:
+ if child.type != "method_or_prop_defn":
+ continue
+ for grandchild in child.children:
+ if grandchild.type != "property_or_ident":
+ continue
+ names = [c for c in grandchild.children if c.type == "identifier" and c.text]
+ if names:
+ return names[-1].text.decode("utf-8", errors="replace")
# C / C++: the function name is not a direct child but nested inside a
# ``declarator`` chain (``function_definition → function_declarator →
# field_identifier``). Languages with a ``name`` field never reach here.
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index f071d8636..37bfc152a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -806,33 +806,30 @@ _PASCAL = LanguageNodeMap(
)
-_ELIXIR = LanguageNodeMap(
- function_kinds=frozenset({"call"}),
- lambda_kinds=frozenset(),
- branch_kinds=frozenset(),
- loop_kinds=frozenset(),
- try_kinds=frozenset(),
- catch_kinds=frozenset(),
- switch_kinds=frozenset(),
- case_kinds=frozenset(),
- boolean_operator_kinds=frozenset(),
- class_kinds=frozenset(),
- self_identifiers=frozenset(),
- member_access_kinds=frozenset(),
- assert_call_kinds=frozenset({"call"}),
- call_kinds=frozenset({"call"}),
-)
+# Elixir has no entry on purpose. tree-sitter-elixir gives ``defmodule``,
+# ``def``, ``defp`` and an ordinary call the same ``call`` node, told apart
+# only by the target's identifier text, which a set of node types cannot
+# express. Mapping ``call`` reports the module as the file's only function, so
+# until function kinds can carry a text predicate, no entry and no rows.
+# Known undercount, in the walker rather than this map: ``walk_file`` walks the
+# body node's children, so a body that IS one expression loses it and
+# ``let f x = if x > 0 then 1 else 2`` scores 1.
_FSHARP = LanguageNodeMap(
function_kinds=frozenset({"function_or_value_defn", "member_defn"}),
lambda_kinds=frozenset(),
branch_kinds=frozenset({"if_expression"}),
loop_kinds=frozenset({"for_expression", "while_expression"}),
try_kinds=frozenset({"try_expression"}),
+ # A ``with`` handler and a ``match`` arm are the same node types here, so
+ # one field has to serve both. ``case_kinds`` names ``rules``, the wrapper,
+ # which counts the dispatch once; naming ``rule``, the arm, would score a
+ # flat three-arm match 4 against Rust's 2. So a multi-handler ``with``
+ # counts 1 rather than one per clause.
catch_kinds=frozenset(),
switch_kinds=frozenset({"match_expression"}),
- case_kinds=frozenset(),
+ case_kinds=frozenset({"rules"}),
boolean_operator_kinds=frozenset(),
class_kinds=frozenset({"anon_type_defn", "record_type_defn", "union_type_defn", "enum_type_defn"}),
self_identifiers=frozenset(),
@@ -844,12 +841,21 @@ _FSHARP = LanguageNodeMap(
_OBJC = LanguageNodeMap(
- function_kinds=frozenset({"function_definition", "method_definition", "declaration"}),
- lambda_kinds=frozenset(),
+ # ``declaration`` covers every file-scope global and prototype here, so it
+ # is a local decl rather than a function kind, as in ``_C``. It is also a
+ # recursion boundary: as a function kind it stopped the walker descending
+ # into a declaration, so a ternary in an initialiser counted nothing.
+ function_kinds=frozenset({"function_definition", "method_definition"}),
+ # A file-scope block is a ``declaration``, so name the block itself to keep
+ # its complexity now that ``declaration`` is not a function kind.
+ lambda_kinds=frozenset({"block_literal"}),
branch_kinds=frozenset({"if_statement", "conditional_expression"}),
- loop_kinds=frozenset({"for_statement", "while_statement", "do_statement", "for_in_statement"}),
+ # Fast enumeration parses as ``for_statement``; there is no
+ # ``for_in_statement`` node in this grammar.
+ loop_kinds=frozenset({"for_statement", "while_statement", "do_statement"}),
try_kinds=frozenset({"try_statement"}),
- catch_kinds=frozenset(),
+ # TRY only opens a nesting level; CATCH is what adds to CCN.
+ catch_kinds=frozenset({"catch_clause"}),
switch_kinds=frozenset({"switch_statement"}),
case_kinds=frozenset({"case_statement"}),
boolean_operator_kinds=frozenset(),
@@ -896,7 +902,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"ruby": _RUBY,
"shell": _SHELL,
"pascal": _PASCAL,
- "elixir": _ELIXIR,
+ # No "elixir" entry on purpose. See the note above ``_FSHARP``.
"fsharp": _FSHARP,
"objectivec": _OBJC,
}
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 9bcee0b83..4dc048d93 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -99,7 +99,15 @@ log = structlog.get_logger(__name__)
# Not a licence to move a calibrated scoring weight — those are frozen
# independently of this stamp.
#
-# Current stamp: C gained a complexity node map. ``LANGUAGE_NODE_MAPS`` had no
+# Current stamp: F# and Objective-C gained working complexity node maps and
+# Elixir lost its broken one, so stored complexity changes for files in those
+# languages. It has to move for the cache too: ``HealthWalkCache`` keys on this
+# stamp and the file's bytes, neither of which a node-map change alters.
+#
+# v10: non-code files stopped being scored and the deduction was split into its
+# structure and history halves, stored per file.
+#
+# v9: C gained a complexity node map. ``LANGUAGE_NODE_MAPS`` had no
# ``c`` entry, so every C file scored as if it had no branches: ``max_ccn`` and
# the maintainability index were computed off an empty node set and persisted
# that way. The map is present now, so a C file's stored complexity metrics and
@@ -113,7 +121,7 @@ log = structlog.get_logger(__name__)
# forms. Files that were counted untested and are not become tested, which
# moves untested-hotspot findings and the scores that carry them, on every
# language with a prefix or spec convention rather than Ruby alone.
-HEALTH_ANALYZER_VERSION = 10
+HEALTH_ANALYZER_VERSION = 11
# Method-level smells that make the dataflow / Extract Method pass worthwhile.
# Only files carrying one of these get a CFG + def/use + reaching pass built.
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
index f088f07af..62fc04ec5 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/__init__.py
@@ -51,9 +51,11 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (
("ruby", _ruby.DIALECT),
("kotlin", _kotlin.DIALECT),
("cpp", _cpp.DIALECT),
- # NB: "c" shares the C++ grammar but has no ``LanguageNodeMap`` at all
- # (``get_language_map("c")`` is ``None``), so the health pass never reaches
- # a dialect for it. Registering it here would be dead configuration.
+ # NB: "c" shares the C++ grammar and now has its own ``LanguageNodeMap``,
+ # so it does reach the health pass for complexity. It is still absent here
+ # on purpose: no perf dialect has been written for it, and the coverage
+ # report names it as an unsupported language rather than pretending a
+ # detector ran.
)
for _tag, _dialect in _REGISTER:
diff --git a/tests/unit/health/test_language_node_maps.py b/tests/unit/health/test_language_node_maps.py
new file mode 100644
index 000000000..f0683d2ab
--- /dev/null
+++ b/tests/unit/health/test_language_node_maps.py
@@ -0,0 +1,266 @@
+"""Table-driven checks that a language node map says what the grammar means.
+
+A ``LanguageNodeMap`` is a set of node-type strings, so nothing about it fails
+loudly when it is wrong: naming a node type the grammar never emits is silently
+inert, and naming one that means something else silently produces confident
+wrong numbers. Importing cleanly proves neither. These tests run the real
+walker over small snippets and assert the function names and cyclomatic
+complexity that come back, which is the only thing that does.
+
+Each case is (label, source, expected rows), so adding a language is a table
+entry rather than a new test.
+
+Grammars are not all installed everywhere, so every case guards with
+``_require_language`` the way ``test_complexity_walker`` does.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.complexity import walk_file
+from repowise.core.analysis.health.complexity.languages import get_language_map
+
+
+def _require_language(language: str) -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+
+
+def _rows(language: str, source: str, suffix: str) -> dict[str, int]:
+ """Return ``{function name: ccn}`` from a real walk of *source*."""
+ fc = walk_file(f"sample.{suffix}", language, source.encode("utf-8"))
+ return {f.name: f.ccn for f in fc.functions}
+
+
+# --------------------------------------------------------------------------- #
+# Elixir: deliberately absent
+# --------------------------------------------------------------------------- #
+
+
+def test_elixir_has_no_complexity_map() -> None:
+ """The absence is load-bearing, so it is asserted rather than assumed.
+
+ tree-sitter-elixir emits ``call`` for ``defmodule``, ``def``, ``defp`` and
+ an ordinary call alike, told apart only by the target's identifier text,
+ which a set of node types cannot express. A map keyed on ``call`` reports
+ the module as the function and hides every real one.
+ """
+ assert get_language_map("elixir") is None
+
+
+def test_elixir_reports_nothing_rather_than_a_wrong_function() -> None:
+ """No rows is the honest degrade. One row named ``defmodule`` is not.
+
+ No grammar guard here on purpose: ``walk_file`` returns on the missing-map
+ check before it ever asks for a parser, so this holds either way.
+ """
+ source = "defmodule A do\n def one(x), do: x\nend\n\ndefmodule B do\n def two(y), do: y\nend\n"
+ fc = walk_file("sample.ex", "elixir", source.encode("utf-8"))
+ assert fc.functions == []
+
+
+# --------------------------------------------------------------------------- #
+# Objective-C
+# --------------------------------------------------------------------------- #
+
+_OBJC_CASES: list[tuple[str, str, dict[str, int]]] = [
+ (
+ "file-scope globals and prototypes are not functions",
+ """
+static int gCounter = 0;
+static NSString *gName = nil;
+int helper(int x);
+
+@implementation Ledger
+- (int)post:(int)amount { if (amount > 0) { return 1; } return 0; }
+@end
+""",
+ {"post": 2},
+ ),
+ (
+ "a catch clause adds a branch",
+ """
+@implementation L
+- (void)run {
+ @try { [self go]; }
+ @catch (NSException *e) { NSLog(@"x"); }
+}
+@end
+""",
+ {"run": 2},
+ ),
+ (
+ "fast enumeration counts as a loop",
+ """
+@implementation L
+- (int)count:(NSArray *)keys {
+ int n = 0;
+ for (NSString *k in keys) { n++; }
+ return n;
+}
+@end
+""",
+ {"count": 2},
+ ),
+ (
+ "a plain C function definition is still a function",
+ """
+int helper(int x) {
+ for (int i = 0; i < x; i++) { x += i; }
+ return x;
+}
+""",
+ {"helper": 2},
+ ),
+ (
+ "a ternary inside a declaration is reached",
+ """
+@implementation L
+- (int)pick:(int)n { int b = n > 0 ? 1 : 2; return b; }
+@end
+""",
+ {"pick": 2},
+ ),
+ (
+ "a block nested in a method rolls into that method",
+ """
+@implementation L
+- (void)run { void (^b)(void) = ^{ if (1) { NSLog(@"x"); } }; b(); }
+@end
+""",
+ {"run": 2},
+ ),
+ (
+ "a flat switch counts once for the dispatch",
+ """
+@implementation L
+- (int)pick:(int)n {
+ switch (n) { case 1: return 1; case 2: return 2; default: return 0; }
+}
+@end
+""",
+ {"pick": 2},
+ ),
+ (
+ "a switch whose arms carry control flow counts them",
+ """
+@implementation L
+- (int)pick:(int)n {
+ switch (n) {
+ case 1: { if (n > 0) { return 1; } return 5; }
+ case 2: { for (int i = 0; i < n; i++) { n += i; } return 2; }
+ default: return 0;
+ }
+}
+@end
+""",
+ {"pick": 6},
+ ),
+]
+
+
+ ("source", "expected"),
+ [(src, exp) for _, src, exp in _OBJC_CASES],
+ ids=[label for label, _, _ in _OBJC_CASES],
+)
+def test_objective_c_complexity(source: str, expected: dict[str, int]) -> None:
+ _require_language("objectivec")
+ assert _rows("objectivec", source, "m") == expected
+
+
+# --------------------------------------------------------------------------- #
+# F#
+# --------------------------------------------------------------------------- #
+
+_FSHARP_CASES: list[tuple[str, str, dict[str, int]]] = [
+ (
+ "every function is named rather than anonymous",
+ "let one x = x\nlet two y = y\n",
+ {"one": 1, "two": 1},
+ ),
+ (
+ "a branch and a loop each add one",
+ 'let f x =\n let y = 1\n if x > 0 then\n for i in 1..x do\n printfn "%d" i\n 0\n',
+ {"f": 3},
+ ),
+ (
+ "a flat match counts once for the dispatch, at any width",
+ 'let f x =\n match x with\n | 1 -> "a"\n | 2 -> "b"\n | _ -> "c"\n',
+ {"f": 2},
+ ),
+ (
+ "control flow inside a match arm counts on top of the dispatch",
+ 'let f x =\n match x with\n | 1 -> (if x > 5 then "a" else "b")\n'
+ ' | _ -> (for i in 1..x do printfn "%d" i\n "c")\n',
+ {"f": 4},
+ ),
+ (
+ "a with handler is a branch",
+ "let f x =\n try\n x\n with\n | _ -> 0\n",
+ {"f": 2},
+ ),
+]
+
+
+ ("source", "expected"),
+ [(src, exp) for _, src, exp in _FSHARP_CASES],
+ ids=[label for label, _, _ in _FSHARP_CASES],
+)
+def test_fsharp_complexity(source: str, expected: dict[str, int]) -> None:
+ _require_language("fsharp")
+ assert _rows("fsharp", source, "fs") == expected
+
+
+def test_fsharp_member_is_named_by_its_method_not_its_self_identifier() -> None:
+ """``member this.M(x)`` is ``M``, not ``this`` and not ``<anonymous>``."""
+ _require_language("fsharp")
+ source = "type T() =\n member this.M(x) =\n let y = 1\n if x > 0 then 1 else 2\n"
+ assert set(_rows("fsharp", source, "fs")) == {"M"}
+
+
+def test_fsharp_flat_match_agrees_with_rust() -> None:
+ """The dispatch is worth one branch in both, so the languages agree.
+
+ ``case_kinds`` names the ``rules`` wrapper rather than the ``rule`` arm. On
+ the arm, a three-arm match would score 4 against Rust's 2.
+ """
+ _require_language("fsharp")
+ _require_language("rust")
+ fsharp = 'let f x =\n match x with\n | 1 -> "a"\n | 2 -> "b"\n | _ -> "c"\n'
+ rust = 'fn f(x: i32) -> &str {\n match x {\n 1 => "a",\n 2 => "b",\n _ => "c",\n }\n}\n'
+ assert _rows("fsharp", fsharp, "fs")["f"] == _rows("rust", rust, "rs")["f"] == 2
+
+
+def test_fsharp_multi_handler_with_counts_once_not_per_clause() -> None:
+ """A documented departure, pinned so it is a decision rather than a surprise.
+
+ CATCH is meant to add one per clause. ``rules`` is a single node however
+ many handlers hang off it, and the alternative inflates every match.
+ """
+ _require_language("fsharp")
+ source = (
+ "let f x =\n try\n x\n with\n"
+ " | :? System.IO.IOException -> 1\n"
+ " | :? System.OverflowException -> 2\n"
+ " | _ -> 0\n"
+ )
+ assert _rows("fsharp", source, "fs") == {"f": 2}
+
+
+def test_fsharp_single_expression_body_is_a_known_undercount() -> None:
+ """Pinning current behaviour so a traversal fix is a deliberate change.
+
+ ``walk_file`` takes the ``body`` field and walks that node's children, so a
+ body that IS the branch is never visited. Correct for block-bodied
+ languages, wrong here. When the traversal root changes this should become
+ 2, and this test is the place that says so.
+ """
+ _require_language("fsharp")
+ assert _rows("fsharp", "let f x =\n if x > 0 then 1 else 2\n", "fs") == {"f": 1}
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index 18b1a519f..83fb1f859 100644
--- a/tests/unit/health/test_model_version_coupling.py
+++ b/tests/unit/health/test_model_version_coupling.py
@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (
# The three stamps as they stand together. Moving either identity model means
# moving the analyzer with it, and updating this tuple in the same commit.
-_STAMPS = (10, 2, 2)
+_STAMPS = (11, 2, 2)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None: