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(health): promote Scala to Full tier (LanguageNodeMap + perf dialect) (#745)

Raghav Chamadiyaa9f8dd8eb593
diff --git a/README.md b/README.md
index f9ed45fef..74b2b1213 100644
--- a/README.md
+++ b/README.md
@@ -328,7 +328,7 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
## Supported languages
-**15 languages parsed to AST · 9 at the Full tier · framework-aware across all of them.**
+**15 languages parsed to AST · 10 at the Full tier · framework-aware across all of them.**
<p>
<strong>Full tier &nbsp;</strong>
@@ -341,13 +341,13 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
<img src="https://img.shields.io/badge/Rust-000000?style=flat-square&logo=rust&logoColor=white" alt="Rust" />
<img src="https://img.shields.io/badge/C++-00599C?style=flat-square&logo=cplusplus&logoColor=white" alt="C++" />
<img src="https://img.shields.io/badge/C%23-512BD4?style=flat-square&logo=csharp&logoColor=white" alt="C#" />
+ <img src="https://img.shields.io/badge/Scala-DC322F?style=flat-square&logo=scala&logoColor=white" alt="Scala" />
</p>
<p>
<strong>Good tier &nbsp;</strong>
<img src="https://img.shields.io/badge/C-A8B9CC?style=flat-square&logo=c&logoColor=black" alt="C" />
<img src="https://img.shields.io/badge/Ruby-CC342D?style=flat-square&logo=ruby&logoColor=white" alt="Ruby" />
<img src="https://img.shields.io/badge/Swift-F05138?style=flat-square&logo=swift&logoColor=white" alt="Swift" />
- <img src="https://img.shields.io/badge/Scala-DC322F?style=flat-square&logo=scala&logoColor=white" alt="Scala" />
<img src="https://img.shields.io/badge/PHP-777BB4?style=flat-square&logo=php&logoColor=white" alt="PHP" />
<img src="https://img.shields.io/badge/Dart-0175C2?style=flat-square&logo=dart&logoColor=white" alt="Dart" />
&nbsp;<strong>· Partial &nbsp;</strong>
@@ -356,8 +356,8 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
| Tier | Languages | What works |
|------|-----------|------------|
-| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers; framework-aware edges; per-language dynamic-hint extractors; **code-health markers** |
-| **Good** | C · Ruby · Swift · Scala · PHP · Dart | AST parsing, import resolution, named bindings, call resolution, heritage (mixins / derive / extensions / traits), docstrings; dedicated workspace-aware resolvers; Rails / Laravel / TYPO3 / Flutter framework edges; dynamic-hint extractors; Dart adds code-health + perf markers |
+| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers; framework-aware edges; per-language dynamic-hint extractors; **code-health markers** |
+| **Good** | C · Ruby · Swift · PHP · Dart | AST parsing, import resolution, named bindings, call resolution, heritage (mixins / derive / extensions / traits), docstrings; dedicated workspace-aware resolvers; Rails / Laravel / TYPO3 / Flutter framework edges; dynamic-hint extractors; Dart adds code-health + perf markers |
| **SQL / dbt** | `.sql` via sqlglot (postgres, mysql, tsql, clickhouse, ...) | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage edges: model-level DAG, hotspots, co-change, ownership |
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | Included in the file tree; special handlers extract endpoints / targets where applicable |
| **Git-blame only** | Objective-C · Elixir · Erlang · Zig · Julia · Clojure · Haskell · OCaml · F# · … | Tracked in git history (blame, hotspots, co-change); no AST parsing yet |
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index dd70c968f..9a36724cb 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -1,7 +1,7 @@
# Language Support
repowise parses **15 languages to a full AST**, resolves imports and call
-graphs across them, and scores **9 at the Full tier** with code-health markers.
+graphs across them, and scores **10 at the Full tier** with code-health markers.
Everything else in your repo is still tracked through git history and appears in
the wiki. This page is the "what works for my language today" reference.
@@ -19,8 +19,8 @@ produce meaningful output.
| Tier | Languages | What works |
|------|-----------|------------|
-| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
-| **Good** | C · Ruby · Swift · Scala · PHP · Dart | Everything above except code-health markers (C, Ruby, Swift, Scala, PHP; Dart *does* get health markers). Dedicated workspace resolvers and framework edges per language |
+| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
+| **Good** | C · Ruby · Swift · PHP · Dart | Everything above except code-health markers (C, Ruby, Swift, PHP; Dart *does* get health markers). Dedicated workspace resolvers and framework edges per language |
| **SQL / dbt** | `.sql` via sqlglot | Tables / views / functions / procedures as symbols with wiki pages; dbt projects get real `ref()` / `source()` lineage |
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · Terraform · Markdown · Shell | In the file tree and wiki; special handlers extract endpoints / targets where applicable |
| **Lightweight** | Elixir · Clojure · Haskell · Lean 4 · Erlang · F# | Regex-tier file-level import graph (no symbols/calls). Honest file-to-file dependencies, no symbol-level claims |
@@ -33,7 +33,7 @@ produce meaningful output.
|-------|:----:|:----:|:-----------:|:----------:|:-------------:|
| File discovery & git history | ✅ | ✅ | ✅ | ✅ | ✅ |
| AST symbol extraction | ✅ | ✅ | - | - | - |
-| Import resolution | ✅ | ✅¹ | regex | - | - |
+| Import resolution | ✅¹ | ✅ | regex | - | - |
| Call graph edges | ✅ | ✅ | - | - | - |
| Heritage (extends/implements) | ✅ | ✅ | - | - | - |
| Named bindings | ✅ | ✅ | - | - | - |
@@ -41,8 +41,9 @@ produce meaningful output.
| Dead code detection | ✅ | ✅ | ✅ | ✅ | - |
| Semantic search & wiki pages | ✅ | ✅ | ✅ | ✅ | ✅ |
-¹ Scala's import resolution is partial (build-file fallback via SBT/Mill); the
-other Good languages resolve imports fully.
+¹ Scala's import resolution is partial (shared JVM index with SBT/Mill
+build-file fallback); every other Full and Good language resolves imports
+fully.
² See [code-health coverage](#code-health-coverage), a language is only "Full"
once it clears the health checklist.
@@ -65,10 +66,11 @@ extractors, and code-health markers.
| **Rust** | `.rs` | `use crate::` / `super::` / `self::` with `Cargo.toml` |
| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `#include` via `compile_commands.json` + CMake / Bazel workspace header maps, header↔implementation pairing |
| **C#** | `.cs` | `using` / `global using` / `using static` / aliases with `.csproj` / `.sln` resolution; MSBuild project graph; `partial` class linking |
+| **Scala** | `.scala` | `import pkg.Foo`, brace/wildcard/package imports via the shared JVM index (cross-language with Java/Kotlin); SBT / Mill build parsing as fallback (partial import resolution¹) |
-All nine also support three-tier call resolution (same-file, cross-file, global
+All ten also support three-tier call resolution (same-file, cross-file, global
stem match) and docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc,
-Doxygen, XML doc).
+Scaladoc, Doxygen, XML doc).
**Framework-aware edges** connect routes to handlers, DI registrations to
implementations, and ORM entities to relationships:
@@ -101,7 +103,6 @@ PHP trait use, Dart mixins). Dedicated workspace resolvers per language.
| **C** | `.c` | `#include` via `compile_commands.json` (shares C++ grammar) |
| **Ruby** | `.rb` | `require` / `require_relative` with `$LOAD_PATH` probing, Gemfile externals, RSpec mirror edges, Rails / Zeitwerk autoloading |
| **Swift** | `.swift` | `import` with SPM `Package.swift` target → directory mapping; intra-module type references; `@main` entry points |
-| **Scala** | `.scala` | `import pkg.Foo`, brace/wildcard/package imports via the shared JVM index; SBT / Mill build parsing as fallback (partial import resolution) |
| **PHP** | `.php` | `use Foo\Bar\Baz` with composer.json PSR-4 longest-prefix resolution; Laravel, TYPO3 edges |
| **Dart** | `.dart` | `import` / `export` / `part` URIs; `package:` via every `pubspec.yaml`; Flutter route tables and `runApp()` edges; **code-health markers** |
@@ -174,6 +175,7 @@ is "Full" vs "Good".
| Kotlin | ✅ | ✅ | ✅ | later | later |
| C++ | ✅ | ✅ | ✅ | later | later |
| Dart | ✅ | n/a³ | ✅ | later | ✅ |
+| Scala | ✅ | ✅ | ✅⁴ | later | ✅⁵ |
¹ Go methods attach to a type via an external receiver rather than nesting in a
class body, so class-level metrics aren't computable; Go gets the function- and
@@ -182,6 +184,14 @@ assertion-level markers.
O(1), so it would be a guaranteed false positive).
³ Dart assertion smells cover `assert` statements only; `expect()` calls have no
call-node type to key on.
+⁴ Plain `assert(...)` and munit/JUnit-style `assert*` calls are counted;
+ScalaTest's infix DSL (`x shouldBe y`) has no assert-prefixed callee and is not.
+⁵ Rides the JVM sink lexicon (JDBC / JPA / Spring-Data interop) plus
+Scala-native boundaries (`scala.io.Source`, os-lib, sttp / http4s, Slick /
+doobie). Scala-specific markers: `"...".r` regex recompile in a loop and
+`Await.result` / `Thread.sleep` inside a `Future`-returning def
+(`blocking_sync_in_async`). Combinator iteration (`.map` / `.foreach`) is not
+loop-tracked yet; loops are `while` / `do-while` / for-comprehensions.
The **performance** signal (`io_in_loop`, `string_concat_in_loop`,
`resource_construction_in_loop`, language-specific markers like Go
@@ -197,6 +207,7 @@ where a dialect isn't wired yet. Per-marker mechanics and precision hazards:
| Language | Target tier | Status |
|----------|------------|--------|
| Dart | Good | Shipped: AST, health control-flow + class facts, perf dialect, Flutter edges. Next: riverpod/get_it dynamic hints, dataflow dialect |
+| Scala | Full (health) | Shipped: complexity/class/assertion markers + perf dialect (JVM lexicon, `.r` recompile, sync-over-Future). Next: dataflow dialect, combinator (`.map`/`.foreach`) loop tracking |
| Kotlin / C++ | Full (health) | Perf + dataflow dialects pending; everything else shipped |
| C# | Full (health) | Dataflow dialect pending; perf shipped |
| Elixir | Good | Lightweight tier shipped; AST upgrade planned (`tree-sitter-elixir` available) |
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index b7af8b842..c2c333ffb 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -304,7 +304,7 @@ per-language plugin pattern, registered in a dict exactly like `resolvers/`:
complexity, and per-function markers; optional `class_kinds` /
`self_identifiers` / `member_access_kinds` add class-level metrics (LCOM4,
god-class), and `assert_kinds` / `assert_call_kinds` add assertion-block
- smells. Ships for the 9 Full languages plus Dart. See `complexity/README.md`.
+ smells. Ships for the 10 Full languages plus Dart. See `complexity/README.md`.
- **`analysis/health/perf/dialects/`** (`PERF_DIALECTS`), the **performance**
signal. A `PerfDialect` owns callee extraction (the per-grammar seam), the
execution-sink lexicon (`sink_kind`), the constant-loop / string-concat /
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index 913078b43..f4be202a6 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -165,9 +165,9 @@ positive. (Languages without an `expression_statement` wrapper — e.g.
Kotlin, where the call node sits directly in the statement list — are
handled too: the call node is matched as the statement itself.)
-Ships control-flow + assertion mappings for **all nine full-tier
-languages** — Python, TypeScript, JavaScript, Go, Java, Kotlin, Rust, C++,
-C# — plus the `tsx`/`jsx` aliases; class-level (LCOM4 / god-class)
-mappings for all of those except **Go** (methods attach to a type via an
-external receiver, so there is no single grouping node). Adding more
+Ships control-flow + assertion mappings for **all ten full-tier
+languages** (Python, TypeScript, JavaScript, Go, Java, Kotlin, Rust, C++,
+C#, Scala) plus the `tsx`/`jsx` aliases and Dart; class-level (LCOM4 /
+god-class) mappings for all of those except **Go** (methods attach to a type
+via an external receiver, so there is no single grouping node). Adding more
languages — any tier — is purely additive in `languages.py`.
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 48a3f9712..d28cb3075 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
@@ -64,6 +64,12 @@ def _find_assigned_lambda_name(node: Node) -> str | None:
name = parent.child_by_field_name("name")
if name is not None and name.text is not None:
return _node_text(name)
+ if parent.type in {"val_definition", "var_definition"}:
+ # Scala ``val f = (x: Int) => ...``: the bound name is the
+ # ``pattern`` field (only simple identifier patterns are named).
+ pattern = parent.child_by_field_name("pattern")
+ if pattern is not None and pattern.type == "identifier" and pattern.text is not None:
+ return _node_text(pattern)
if parent.type in {"assignment_expression", "assignment_pattern"}:
left = parent.child_by_field_name("left")
if left is None:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
index e480485eb..ac6ffc2db 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -51,9 +51,11 @@ _ELSE_IF_NODE_KINDS = frozenset(
# Branch nodes that are a decision point (count toward CCN) but do NOT open a
# nesting level: a comprehension filter (``[x for x in xs if a]``) and a match
# ``case ... if guard:`` both parse as ``if_clause`` and sit inline, not as a
-# nested block. Treating them as flat keeps ``max_nesting`` / ``cognitive``
-# honest — they were only added to ``branch_kinds`` for the CCN count.
-_FLAT_BRANCH_KINDS = frozenset({"if_clause"})
+# nested block; Scala's ``guard`` (for-comprehension filter / match-case guard)
+# is the same inline shape. Treating them as flat keeps ``max_nesting`` /
+# ``cognitive`` honest — they were only added to ``branch_kinds`` for the CCN
+# count.
+_FLAT_BRANCH_KINDS = frozenset({"if_clause", "guard"})
def _is_elif_continuation(node: Node) -> bool:
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 c1e207675..d78dfeff8 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -25,10 +25,10 @@ names to the walker's abstract categories:
test-assertion runs (test-quality smells). Opt-in per
language via ``assert_kinds`` / ``assert_call_kinds``.
-Control-flow maps cover all nine full-tier languages — Python, TypeScript,
-JavaScript, Go, Java, Kotlin, Rust, C++, C# — plus their aliases; class-level
-maps cover all of those except Go (no class-grouping node). Adding a language —
-either tier — is purely additive here.
+Control-flow maps cover all ten full-tier languages (Python, TypeScript,
+JavaScript, Go, Java, Kotlin, Rust, C++, C#, Scala) plus their aliases and
+Dart; class-level maps cover all of those except Go (no class-grouping node).
+Adding a language, at either tier, is purely additive here.
Two cross-language heuristic limits worth noting (both degrade to "no signal",
never a false positive): (1) instance members accessed without an explicit
@@ -538,6 +538,69 @@ _CSHARP = LanguageNodeMap(
)
+_SCALA = LanguageNodeMap(
+ # ``function_definition`` is a ``def`` with a body (expression or block);
+ # abstract ``def``s parse as ``function_declaration`` (no body, nothing to
+ # measure). ``given_definition`` is deliberately NOT a function kind: a
+ # ``given ... with {}`` instance nests real ``function_definition`` members,
+ # and function collection stops descending at a function boundary, so
+ # mapping ``given`` would swallow its methods; leaving it unmapped lets the
+ # traversal find them individually (alias givens are values, not bodies).
+ function_kinds=frozenset({"function_definition"}),
+ # A partial-function literal (``{ case n => ... }``) is a ``case_block``,
+ # shared with ``match`` / ``catch``, so it cannot be a lambda kind without
+ # every match arm block becoming a module-level entry; its cases still
+ # count via ``case_kinds`` and its body rolls up into the enclosing def.
+ lambda_kinds=frozenset({"lambda_expression"}),
+ # Scala ``if`` is an expression; ``guard`` covers both for-comprehension
+ # filters (``for (i <- xs if i > 0)``) and match-case guards
+ # (``case n if n > 0``), each an inline decision point (flat, see
+ # ``_FLAT_BRANCH_KINDS``).
+ branch_kinds=frozenset({"if_expression", "guard"}),
+ # A for-comprehension is a loop for nesting/CCN purposes even though it
+ # desugars to flatMap: this matches developer intuition.
+ loop_kinds=frozenset({"for_expression", "while_expression", "do_while_expression"}),
+ try_kinds=frozenset({"try_expression"}),
+ # ``catch`` takes a ``case_block``; each handler is a ``case_clause`` that
+ # already counts via ``case_kinds`` (per-handler parity with Python's
+ # per-``except`` counting). Mapping ``catch_clause`` too would double-count
+ # every single-case catch.
+ catch_kinds=frozenset(),
+ switch_kinds=frozenset({"match_expression"}),
+ case_kinds=frozenset({"case_clause"}),
+ boolean_operator_kinds=frozenset(),
+ # ``&&`` / ``||`` are ``operator_identifier`` tokens inside a generic
+ # ``infix_expression``, the text sniff. The sniffer also matches ``and`` /
+ # ``or`` operator text (ScalaTest matcher DSL combinators), which are
+ # genuine boolean combinators when used infix, so the shared behavior is
+ # acceptable here.
+ boolean_operator_text_kinds=frozenset({"infix_expression"}),
+ # ``object`` (singletons / companions), ``trait``, and Scala 3 ``enum``
+ # bodies all group methods the same way a class body does; case classes
+ # are plain ``class_definition``s.
+ class_kinds=frozenset(
+ {"class_definition", "object_definition", "trait_definition", "enum_definition"}
+ ),
+ # Self-type aliases (``self =>``) are skipped: bare and aliased implicit
+ # receivers degrade to the LCOM4 "no signal" valve, same documented limit
+ # as Kotlin.
+ self_identifiers=frozenset({"this"}),
+ # ``field_expression`` (fields ``value`` / ``field``) covers both
+ # ``this.field`` and ``this.method()`` (the latter nests one inside a
+ # ``call_expression``).
+ member_access_kinds=frozenset({"field_expression"}),
+ # Plain ``assert(...)`` and munit/JUnit-style ``assertEquals(...)`` are
+ # calls; ScalaTest's infix DSL (``x shouldBe y``) has no assert-prefixed
+ # callee and is a documented gap (under-signal, safe).
+ assert_call_kinds=frozenset({"call_expression"}),
+ # ``instance_expression`` is ``new Foo(...)``, needed so a constructor at
+ # an I/O boundary inside a loop is caught (JVM interop, as in Java).
+ call_kinds=frozenset({"call_expression", "instance_expression"}),
+ # Scala has no async syntax; the perf dialect's ``is_async_fn`` sniffs a
+ # declared ``Future[...]`` return type instead.
+)
+
+
LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"python": _PY,
"typescript": _TS,
@@ -551,6 +614,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"cpp": _CPP,
"csharp": _CSHARP,
"dart": _DART,
+ "scala": _SCALA,
}
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
index 6ec243f16..cef36508d 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
@@ -54,6 +54,9 @@ _LOOP_STMT_MARKER_KINDS = frozenset(
"membership_test_against_list_in_loop",
# Phase 7d — language-specific statement markers.
"goroutine_in_unbounded_loop",
+ # Scala ``"...".r`` is a bare ``field_expression`` (not a call), so its
+ # regex-recompile form arrives through the statement hook.
+ "regex_compile_in_loop",
}
)
# Markers for a call that is its OWN iteration construct (``.reduce``), a perf
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 8983ee79e..1fd1ca6d0 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
@@ -20,6 +20,7 @@ from . import go as _go
from . import java as _java
from . import python as _python
from . import rust as _rust
+from . import scala as _scala
from . import ts_js as _ts_js
from .base import PERF_DIALECTS, BasePerfDialect
@@ -37,6 +38,7 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (
("csharp", _csharp.DIALECT),
("rust", _rust.DIALECT),
("dart", _dart.DIALECT),
+ ("scala", _scala.DIALECT),
)
for _tag, _dialect in _REGISTER:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/scala.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/scala.py
new file mode 100644
index 000000000..ebfec2480
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/scala.py
@@ -0,0 +1,354 @@
+"""Scala ``PerfDialect``.
+
+Rides the JVM lexicon: Scala call sites hit ``java.*`` interop verbatim, so the
+Java dialect's sink tables are imported as the base and extended with the
+Scala-native boundary libraries (``scala.io.Source``, os-lib, sttp / http4s,
+Slick / doobie).
+
+Flagship: ``"...".r`` recompiling a ``java.util.regex.Pattern`` on every loop
+iteration - the top Scala perf footgun - plus ``Await.result`` inside a
+``Future``-returning ``def`` (thread-pool starvation), the Scala spelling of
+sync-in-async: the language has no ``async`` keyword, so ``is_async_fn`` sniffs
+the declared ``Future[...]`` return type instead of a modifier token.
+
+Grammar seams: a ``call_expression`` carries a ``function`` field whose member
+form is a ``field_expression`` (fields ``value`` / ``field``), so the generic
+base extraction works; only ``new Foo(...)`` (``instance_expression``, no
+``function`` field) needs a dedicated arm. ``x += "..."`` is a plain
+``infix_expression`` whose ``operator`` child carries the ``+=`` text - not a
+compound-assignment node type - so ``is_string_concat`` is overridden outright,
+and it additionally requires a same-file ``var x = "<string>"`` binding so a
+``+=`` onto a mutable *collection* of strings never fires.
+
+Documented ceiling: idiomatic Scala iterates via ``.map`` / ``.foreach`` whose
+bodies are lambdas - a new execution scope where the walker resets
+``loop_depth`` - so combinator-driven iteration produces no loop markers. Loops
+here are ``while`` / ``do-while`` / for-comprehensions, pending the shared
+block-iteration answer (02_ruby precedent). Caps recall, not precision.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .base import BasePerfDialect
+from .java import (
+ _SPRING_DERIVED,
+ AMBIGUOUS_DB,
+ FILES_METHODS,
+ FS_CONSTRUCTORS,
+ JAVA_LOCK_METHODS,
+ JAVA_RESOURCE_CTORS,
+ JDBC_METHODS,
+ JPA_METHODS,
+ NET_CONSTRUCTORS,
+ SPRING_REPO_METHODS,
+)
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+# ``scala.io.Source`` factories, split by boundary.
+SOURCE_FS_METHODS: frozenset[str] = frozenset({"fromFile", "fromInputStream", "fromResource"})
+SOURCE_NET_METHODS: frozenset[str] = frozenset({"fromURL"})
+# lihaoyi os-lib round-trips (``os.read(path)`` / ``os.walk(dir)``). The bare
+# ``os`` root is not seeded in the io_kind table (it would collide with
+# Python's stdlib ``os`` cross-ecosystem), so the gate lives here: receiver
+# exactly ``os`` + a distinctive method name.
+OS_LIB_FS_METHODS: frozenset[str] = frozenset(
+ {"read", "write", "list", "walk", "copy", "move", "remove", "makeDir", "stat", "exists"}
+)
+# ``os.proc(...)`` spawns a subprocess (the ``.call()`` finisher rides on it).
+OS_LIB_SUBPROCESS_METHODS: frozenset[str] = frozenset({"proc"})
+# doobie's ``query.transact(xa)`` - distinctive enough to classify ungated.
+DOOBIE_METHODS: frozenset[str] = frozenset({"transact"})
+# Slick's ``db.run(action)`` - ``run`` is generic, so it is gated on file-level
+# db evidence like the shared AMBIGUOUS_DB stratum.
+SLICK_AMBIGUOUS_DB: frozenset[str] = frozenset({"run"})
+# http4s client verbs, gated on network evidence (``expect`` collides with the
+# test-assertion vocabulary when un-gated).
+HTTP4S_METHODS: frozenset[str] = frozenset({"expect", "fetch"})
+# ``Await.result`` / ``Await.ready`` block a thread; ``Thread.sleep`` stalls it.
+_AWAIT_METHODS: frozenset[str] = frozenset({"result", "ready"})
+
+_STRING_KINDS: frozenset[str] = frozenset({"string", "interpolated_string_expression"})
+
+
+def _last_type_segment(node: Node) -> str | None:
+ """Constructed type name of an ``instance_expression`` (``new a.b.Foo[T]``
+ -> ``Foo``): the last ``type_identifier`` before any type arguments."""
+ stack = [c for c in node.children if c.is_named]
+ while stack:
+ cur = stack.pop(0)
+ if cur.type == "type_identifier" and cur.text:
+ return cur.text.decode("utf-8", "replace").split(".")[-1]
+ if cur.type in ("generic_type", "stable_type_identifier"):
+ stack = [c for c in cur.children if c.is_named] + stack
+ return None
+
+
+class ScalaPerfDialect(BasePerfDialect):
+ language = "scala"
+ markers = frozenset(
+ {
+ "io_in_loop",
+ "string_concat_in_loop",
+ "regex_compile_in_loop",
+ "resource_construction_in_loop",
+ "lock_in_loop",
+ "blocking_sync_in_async",
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
+ }
+ )
+
+ # -- callee extraction ----------------------------------------------------
+
+ def callee_method_name(self, call_node: Node) -> str | None:
+ if call_node.type == "instance_expression":
+ return _last_type_segment(call_node)
+ return super().callee_method_name(call_node)
+
+ def callee_root_name(self, call_node: Node) -> str | None:
+ if call_node.type == "instance_expression":
+ return _last_type_segment(call_node)
+ return super().callee_root_name(call_node)
+
+ def callee_is_attribute(self, call_node: Node) -> bool:
+ if call_node.type == "instance_expression":
+ return True # a constructor sink (``new FileInputStream``)
+ return super().callee_is_attribute(call_node)
+
+ # -- lexicon --------------------------------------------------------------
+
+ def sink_kind(
+ self,
+ root: str,
+ method: str,
+ *,
+ awaited: bool,
+ is_attribute: bool,
+ io_names: dict[str, str],
+ has_db_import: bool,
+ ) -> str | None:
+ root_kind = io_names.get(root)
+ db_ev = has_db_import or root_kind == "db"
+ net_ev = root_kind == "network" or "network" in io_names.values()
+
+ # JVM interop - verbatim from the Java lexicon.
+ if method in FS_CONSTRUCTORS:
+ return "filesystem"
+ if method in NET_CONSTRUCTORS:
+ return "network"
+ if method in JDBC_METHODS or method in JPA_METHODS or method in SPRING_REPO_METHODS:
+ return "db"
+ if _SPRING_DERIVED.match(method):
+ return "db"
+ if root == "Files" and method in FILES_METHODS:
+ return "filesystem"
+ if method == "exec" and root == "Runtime":
+ return "subprocess"
+
+ # Scala-native boundaries.
+ if root == "Source" and method in SOURCE_FS_METHODS:
+ return "filesystem"
+ if root == "Source" and method in SOURCE_NET_METHODS:
+ return "network"
+ if root == "os" and is_attribute:
+ if method in OS_LIB_FS_METHODS:
+ return "filesystem"
+ if method in OS_LIB_SUBPROCESS_METHODS:
+ return "subprocess"
+ if method in DOOBIE_METHODS and is_attribute:
+ return "db"
+ if method == "send" and net_ev: # sttp ``request.send(backend)``
+ return "network"
+ if method in HTTP4S_METHODS and is_attribute and net_ev:
+ return "network"
+ if is_attribute and db_ev and (method in AMBIGUOUS_DB or method in SLICK_AMBIGUOUS_DB):
+ return "db"
+ return None
+
+ # -- loops ----------------------------------------------------------------
+
+ @staticmethod
+ def _first_enumerator_iterable(node: Node) -> Node | None:
+ """The iterable expression of a for-comprehension's first enumerator
+ (``for (i <- items ...)`` -> the ``items`` node)."""
+ # NB: ``child_by_field_name("enumerators")`` returns the ``(`` token -
+ # the grammar stamps the field on the delimiters too - so look the
+ # named node up by type.
+ enums = next((c for c in node.children if c.type == "enumerators"), None)
+ if enums is None:
+ return None
+ first = next((c for c in enums.children if c.type == "enumerator"), None)
+ if first is None:
+ return None
+ named = [c for c in first.children if c.is_named and c.type != "guard"]
+ return named[1] if len(named) >= 2 else None
+
+ def is_constant_loop(self, node: Node) -> bool:
+ # ``for (i <- 1 to 3)`` / ``0 until N-literal`` - a compile-time bound,
+ # not a data-dependent multiplier.
+ if node.type != "for_expression":
+ return False
+ it = self._first_enumerator_iterable(node)
+ if it is None or it.type != "infix_expression":
+ return False
+ op = it.child_by_field_name("operator")
+ if op is None or op.text not in (b"to", b"until"):
+ return False
+ left = it.child_by_field_name("left")
+ right = it.child_by_field_name("right")
+ return (
+ left is not None
+ and right is not None
+ and left.type == "integer_literal"
+ and right.type == "integer_literal"
+ )
+
+ def is_iteration_loop(self, node: Node) -> bool:
+ # Only a for-comprehension multiplies over a collection; ``while`` /
+ # ``do-while`` are cursors (pagination / retry), not data multipliers.
+ return node.type == "for_expression"
+
+ def loop_iterable_name(self, node: Node) -> str | None:
+ if node.type != "for_expression":
+ return None
+ return self._dotted_path(self._first_enumerator_iterable(node))
+
+ # -- string concat ----------------------------------------------------------
+
+ def is_string_concat(self, node: Node) -> bool:
+ """``acc += "<lit>"`` or ``acc = acc + "<lit>"`` where ``acc`` is a
+ same-file ``var`` initialized to a string.
+
+ The var-binding gate is load-bearing: ``+=`` in Scala also appends to
+ mutable collections (``buf += "x"`` on a ``ListBuffer[String]`` is
+ amortized O(1)), so without it every builder append would false-fire.
+ """
+ left: Node | None
+ if node.type == "infix_expression":
+ op = node.child_by_field_name("operator")
+ if op is None or op.text != b"+=":
+ return False
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ elif node.type == "assignment_expression":
+ left = next((c for c in node.children if c.is_named), None)
+ right = node.children[-1] if node.children else None
+ # ``acc = acc + "<lit>"``: RHS is an infix ``+`` whose left operand
+ # re-reads the assignment target.
+ if (
+ right is None
+ or right.type != "infix_expression"
+ or (op := right.child_by_field_name("operator")) is None
+ or op.text != b"+"
+ or left is None
+ or (rl := right.child_by_field_name("left")) is None
+ or rl.text != left.text
+ ):
+ return False
+ right = right.child_by_field_name("right")
+ else:
+ return False
+ if left is None or left.type != "identifier" or left.text is None:
+ return False
+ if right is None or right.type not in _STRING_KINDS:
+ return False
+ return self._is_string_var(node, left.text)
+
+ @staticmethod
+ def _is_string_var(node: Node, name: bytes) -> bool:
+ """True when the file carries ``var <name> = "<string literal>"``."""
+ root = node
+ while root.parent is not None:
+ root = root.parent
+ stack = [root]
+ while stack:
+ cur = stack.pop()
+ if cur.type == "var_definition":
+ pattern = cur.child_by_field_name("pattern")
+ value = cur.child_by_field_name("value")
+ if (
+ pattern is not None
+ and pattern.text == name
+ and value is not None
+ and value.type in _STRING_KINDS
+ ):
+ return True
+ stack.extend(cur.children)
+ return False
+
+ # -- sync-over-Future -------------------------------------------------------
+
+ def is_async_fn(self, node: Node) -> bool:
+ # No ``async`` keyword - a ``def`` whose declared return type is
+ # ``Future[...]`` is the async execution context. Undeclared return
+ # types are not inferred (precision over recall).
+ ret = node.child_by_field_name("return_type")
+ if ret is None or ret.text is None:
+ return False
+ return ret.text.decode("utf-8", "replace").startswith("Future")
+
+ def blocking_sync_api(self, root: str, method: str) -> str | None:
+ if root == "Await" and method in _AWAIT_METHODS:
+ return f"Await.{method}"
+ if root == "Thread" and method == "sleep":
+ return "Thread.sleep"
+ return None
+
+ # -- extra loop markers -------------------------------------------------------
+
+ def loop_call_marker(
+ self, root: str, method: str, node: Node, list_names: frozenset[str]
+ ) -> str | None:
+ if node.type == "instance_expression":
+ return "resource_construction_in_loop" if method in JAVA_RESOURCE_CTORS else None
+ # ``x.synchronized { ... }`` taken every iteration is a contention site;
+ # ``lock.lock()`` is the java.util.concurrent form.
+ if method == "synchronized" and self.callee_is_attribute(node):
+ return "lock_in_loop"
+ if method in JAVA_LOCK_METHODS and self.callee_is_attribute(node):
+ return "lock_in_loop"
+ # ``Pattern.compile(...)`` recompiled per iteration (JVM interop; match
+ # on the receiver's LAST segment so an FQN receiver still resolves).
+ if method != "compile":
+ return None
+ fn = node.child_by_field_name("function")
+ recv = fn.child_by_field_name("value") if fn is not None else None
+ if recv is not None and recv.text:
+ last = recv.text.decode("utf-8", "replace").split(".")[-1]
+ return "regex_compile_in_loop" if last == "Pattern" else None
+ return "regex_compile_in_loop" if root == "Pattern" else None
+
+ def loop_stmt_marker(self, node: Node, list_names: frozenset[str]) -> str | None:
+ # ``"<lit>".r`` is a bare ``field_expression`` (StringOps.r compiles a
+ # fresh ``Pattern`` on every call) - the top Scala regex footgun. Only
+ # a literal receiver fires (a name bound outside the loop is the same
+ # bug but not provably a string here).
+ if node.type != "field_expression":
+ return None
+ field = node.child_by_field_name("field")
+ value = node.child_by_field_name("value")
+ if (
+ field is not None
+ and field.text == b"r"
+ and value is not None
+ and value.type in _STRING_KINDS
+ ):
+ return "regex_compile_in_loop"
+ return None
+
+ def is_lock_scope(self, node: Node) -> bool:
+ # ``x.synchronized { ... }`` - the block argument is the held region
+ # (the walker raises lock_depth for block-typed children only, which
+ # excludes the receiver expression).
+ if node.type != "call_expression":
+ return False
+ return self.callee_method_name(node) == "synchronized"
+
+
+DIALECT = ScalaPerfDialect()
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
index e7d13212c..dda980c94 100644
--- a/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
+++ b/packages/core/src/repowise/core/ingestion/external_systems/io_kind.py
@@ -67,6 +67,9 @@ _DB_NAMES: frozenset[str] = frozenset({
# Dart / Flutter (pub package names; ``package:sqflite/...`` resolves via
# the interior segment).
"sqflite", "postgres", "mysql1", "mongo_dart", "drift",
+ # Scala (root package as imported: ``import slick.jdbc...`` -> ``slick``,
+ # ``import doobie._`` -> ``doobie``; Quill imports as ``io.getquill``).
+ "slick", "doobie", "scalikejdbc", "anorm", "io.getquill",
})
_NETWORK_NAMES: frozenset[str] = frozenset({
@@ -88,6 +91,10 @@ _NETWORK_NAMES: frozenset[str] = frozenset({
# Dart / Flutter (``package:http`` doubles as Node's stdlib ``http`` —
# both are network boundaries).
"http", "dio", "chopper",
+ # Scala (root packages / progressive dotted prefixes: ``import
+ # sttp.client3._`` -> ``sttp``; ``import org.http4s...`` -> ``org.http4s``;
+ # ``import akka.http.scaladsl...`` -> ``akka.http``).
+ "sttp", "org.http4s", "akka.http", "play.api.libs.ws",
})
_FILESYSTEM_NAMES: frozenset[str] = frozenset({
@@ -104,6 +111,11 @@ _FILESYSTEM_NAMES: frozenset[str] = frozenset({
# Dart (``dart:io`` hosts File/Directory; Process is method-gated in the
# perf dialect rather than classified wholesale as subprocess).
"dart:io",
+ # Scala (``import scala.io.Source`` -> the ``scala.io`` dotted prefix;
+ # lihaoyi's os-lib root package ``os`` is deliberately NOT seeded; the
+ # bare name would collide with Python's stdlib ``os`` cross-ecosystem, so
+ # the Scala perf dialect method-gates it instead).
+ "scala.io",
})
_SUBPROCESS_NAMES: frozenset[str] = frozenset({
diff --git a/tests/fixtures/lang_samples/scala/assertions.scala b/tests/fixtures/lang_samples/scala/assertions.scala
new file mode 100644
index 000000000..c13f90b33
--- /dev/null
+++ b/tests/fixtures/lang_samples/scala/assertions.scala
@@ -0,0 +1,28 @@
+// Fixtures for assertion-block detection (munit / plain-assert style calls).
+//
+// ScalaTest's infix DSL (`x shouldBe y`) has no assert-prefixed callee and is
+// the documented detection gap - not exercised here.
+
+class AssertionsSpec {
+ def testManyAsserts(): Unit = {
+ val x = compute()
+ assert(x == 1)
+ assert(x != 2)
+ assertEquals(x, 1)
+ assertNotEquals(x, 2)
+ assert(x > 0)
+ }
+
+ def testFewAsserts(): Unit = {
+ val x = compute()
+ assert(x == 1)
+ val y = x + 1
+ assert(y == 2)
+ }
+
+ private def compute(): Int = 1
+
+ private def assertEquals(a: Int, b: Int): Unit = ()
+
+ private def assertNotEquals(a: Int, b: Int): Unit = ()
+}
diff --git a/tests/fixtures/lang_samples/scala/classes.scala b/tests/fixtures/lang_samples/scala/classes.scala
new file mode 100644
index 000000000..b3b71c5fe
--- /dev/null
+++ b/tests/fixtures/lang_samples/scala/classes.scala
@@ -0,0 +1,69 @@
+// Fixtures for class-level (LCOM4 / god-class) walker tests.
+//
+// Scala accesses instance members WITHOUT a receiver idiomatically; these
+// fixtures use an explicit `this.` so the member-access node type is
+// exercised. The implicit-receiver case is the documented "no signal" path.
+
+class Cohesive {
+ var total = 0
+ var count = 0
+
+ def add(n: Int): Unit = {
+ this.total += n
+ this.count += 1
+ }
+
+ def average(): Int = {
+ if (this.count != 0) this.total / this.count else 0
+ }
+
+ def reset(): Unit = {
+ this.total = 0
+ this.count = 0
+ }
+
+ def describe(): Int = {
+ this.count
+ }
+}
+
+class Splintered {
+ var a = 0
+ var b = 0
+
+ def setA(v: Int): Unit = {
+ this.a = v
+ }
+
+ def getA(): Int = {
+ this.a
+ }
+
+ def setB(v: Int): Unit = {
+ this.b = v
+ }
+
+ def getB(): Int = {
+ this.b
+ }
+
+ def loner(): Int = {
+ 42
+ }
+}
+
+object Registry {
+ def lookup(key: String): Int = {
+ key.length
+ }
+
+ def register(key: String): String = {
+ key.trim
+ }
+}
+
+trait Shape {
+ def area(): Double = {
+ 0.0
+ }
+}
diff --git a/tests/fixtures/lang_samples/scala/nested.scala b/tests/fixtures/lang_samples/scala/nested.scala
new file mode 100644
index 000000000..ab09db2a3
--- /dev/null
+++ b/tests/fixtures/lang_samples/scala/nested.scala
@@ -0,0 +1,56 @@
+// Fixtures for control-flow walker tests (nesting, CCN, guards, match).
+
+object Nested {
+ def deeplyNested(items: List[Int]): Int = {
+ var total = 0
+ for (a <- items) {
+ if (a > 0) {
+ for (b <- items) {
+ if (b > 1) {
+ while (total < 10) {
+ total += 1
+ }
+ }
+ }
+ }
+ }
+ total
+ }
+
+ def manyBranches(a: Int, b: Int): Int = {
+ if (a == 1) { return 1 }
+ else if (a == 2) { return 2 }
+ else if (a == 3) { return 3 }
+ else if (a == 4) { return 4 }
+ else if (a == 5) { return 5 }
+ if (a > 10 && b > 0 || b < -5) { return 6 }
+ 0
+ }
+
+ def matchGuards(n: Int): String = {
+ n match {
+ case 0 => "zero"
+ case x if x > 100 => "big"
+ case x if x < -100 => "small"
+ case _ => "mid"
+ }
+ }
+
+ def flatMatch(n: Int): String = {
+ n match {
+ case 0 => "zero"
+ case 1 => "one"
+ case _ => "other"
+ }
+ }
+
+ def forGuard(items: List[Int]): Int = {
+ var n = 0
+ for (i <- items if i > 0) {
+ n += i
+ }
+ n
+ }
+
+ def shallow(x: Int): Int = x + 1
+}
diff --git a/tests/fixtures/lang_samples/scala/perf_io_in_loop.scala b/tests/fixtures/lang_samples/scala/perf_io_in_loop.scala
new file mode 100644
index 000000000..8f52a394a
--- /dev/null
+++ b/tests/fixtures/lang_samples/scala/perf_io_in_loop.scala
@@ -0,0 +1,96 @@
+// Perf-dialect fixture: sinks in loops, regex recompiles, string concat,
+// sync-over-Future, lock contention - plus the negatives that must stay quiet
+// (hoisted regex, constant-bound loop, plain helper calls, collection `+=`).
+
+package fixtures
+
+import java.util.regex.Pattern
+
+import scala.concurrent.{Await, Future}
+import scala.concurrent.duration.Duration
+import scala.io.Source
+
+object PerfIoInLoop {
+ def readAll(paths: List[String]): List[String] = {
+ var out = List.empty[String]
+ for (p <- paths) {
+ val src = Source.fromFile(p) // io_in_loop (filesystem)
+ out = out :+ src.mkString
+ }
+ out
+ }
+
+ def matrix(rows: List[List[String]]): Unit = {
+ for (row <- rows) {
+ for (cell <- row) {
+ Source.fromFile(cell) // io_in_loop + nested_loop_with_io
+ }
+ }
+ }
+
+ def regexInLoop(lines: List[String]): Int = {
+ var n = 0
+ for (line <- lines) {
+ val re = "a+b".r // regex_compile_in_loop (StringOps.r)
+ val p = Pattern.compile("x+y") // regex_compile_in_loop (JVM interop)
+ if (re.findFirstIn(line).isDefined) n += 1
+ }
+ n
+ }
+
+ def hoistedRegex(lines: List[String]): Int = {
+ val re = "a+b".r // hoisted - no hit
+ var n = 0
+ for (line <- lines) {
+ if (re.findFirstIn(line).isDefined) n += 1
+ }
+ n
+ }
+
+ def concat(items: List[String]): String = {
+ var acc = ""
+ var i = 0
+ while (i < items.length) {
+ acc += "chunk" // string_concat_in_loop (var String binding)
+ i += 1
+ }
+ acc
+ }
+
+ def bufferAppend(items: List[String]): Unit = {
+ val buf = scala.collection.mutable.ListBuffer.empty[String]
+ for (item <- items) {
+ buf += "chunk" // NOT flagged - `buf` has no `var = "<string>"` binding
+ }
+ }
+
+ def slow(fut: Future[Int]): Future[Int] = {
+ val x = Await.result(fut, Duration.Inf) // blocking_sync_in_async
+ Future.successful(x + 1)
+ }
+
+ def constantBound(): Int = {
+ var n = 0
+ for (i <- 1 to 3) {
+ Source.fromFile("f.txt") // constant-bound loop - not data-dependent
+ n += 1
+ }
+ n
+ }
+
+ def locked(items: List[String], lock: AnyRef): Unit = {
+ for (item <- items) {
+ lock.synchronized { // lock_in_loop
+ process(item)
+ }
+ }
+ }
+
+ def helperInLoop(items: List[String]): Unit = {
+ for (item <- items) {
+ process(item) // a plain helper call is not a sink
+ }
+ }
+
+ private def process(s: String): Unit = ()
+}
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index 42df56c83..2c7004550 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -420,3 +420,60 @@ def test_dart_assertion_blocks():
assert many.assertion_blocks[0][2] == 5
few = _find(results, "testFewAsserts")
assert few is not None and few.assertion_blocks == []
+
+
+def test_scala_nesting_and_ccn():
+ results = _walk("scala/nested.scala", "scala")
+ deep = _find(results, "deeplyNested")
+ assert deep is not None
+ assert deep.max_nesting >= 4, f"expected >=4 nesting, got {deep.max_nesting}"
+ many = _find(results, "manyBranches")
+ assert many is not None
+ # 6 ifs + 2 boolean operators over the base path.
+ assert many.ccn >= 9, f"expected CCN >= 9, got {many.ccn}"
+ shallow = _find(results, "shallow")
+ assert shallow is not None and shallow.max_nesting == 0
+ assert shallow.param_count == 1
+
+
+def test_scala_match_and_guards():
+ results = _walk("scala/nested.scala", "scala")
+ guarded = _find(results, "matchGuards")
+ assert guarded is not None
+ # 4 cases + 2 guards (guards make the match non-flat, so arms count).
+ assert guarded.ccn == 7, f"expected CCN 7, got {guarded.ccn}"
+ flat = _find(results, "flatMatch")
+ assert flat is not None
+ # A flat match counts once for the dispatch, not per arm.
+ assert flat.ccn == 2, f"expected CCN 2, got {flat.ccn}"
+ for_guard = _find(results, "forGuard")
+ assert for_guard is not None
+ # for-comprehension (loop) + inline guard; the guard is flat (no nesting).
+ assert for_guard.ccn == 3, f"expected CCN 3, got {for_guard.ccn}"
+ assert for_guard.max_nesting == 1
+
+
+def test_scala_class_cohesion():
+ classes = _walk_classes("scala/classes.scala", "scala")
+ cohesive = classes.get("Cohesive")
+ splintered = classes.get("Splintered")
+ assert cohesive is not None and splintered is not None
+ assert cohesive.lcom4 == 1
+ assert splintered.lcom4 == 3
+ assert splintered.method_count == 5
+ assert splintered.field_count == 2
+ # ``object`` and ``trait`` bodies group methods like a class body.
+ registry = classes.get("Registry")
+ assert registry is not None and registry.method_count == 2
+ shape = classes.get("Shape")
+ assert shape is not None and shape.method_count == 1
+
+
+def test_scala_assertion_blocks():
+ results = _walk("scala/assertions.scala", "scala")
+ many = _find(results, "testManyAsserts")
+ assert many is not None
+ assert many.assertion_blocks, "expected a run of assert calls"
+ assert many.assertion_blocks[0][2] == 5
+ few = _find(results, "testFewAsserts")
+ assert few is not None and few.assertion_blocks == []
diff --git a/tests/unit/health/test_perf_dialects.py b/tests/unit/health/test_perf_dialects.py
index 8e2dd8add..6cff9030a 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -602,3 +602,125 @@ def test_dart_string_concat_reset_per_iteration_not_flagged():
"}\n"
)
assert not any(k == "string_concat_in_loop" for k, _ in _hits("dart", src))
+
+
+# ---------------------------------------------------------------------------
+# Scala
+# ---------------------------------------------------------------------------
+
+
+def test_scala_fixture_counts():
+ fc = _walk("scala/perf_io_in_loop.scala", "scala")
+ counts = _kinds(fc.perf_hits)
+ # Source.fromFile in readAll + in matrix's inner loop.
+ assert counts["io_in_loop"] == 2
+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {"filesystem"}
+ assert counts["nested_loop_with_io"] == 1
+ # ``"a+b".r`` (StringOps) + ``Pattern.compile`` (JVM interop); the hoisted
+ # ``.r`` outside the loop stays quiet.
+ assert counts["regex_compile_in_loop"] == 2
+ assert counts["string_concat_in_loop"] == 1
+ assert counts["lock_in_loop"] == 1
+ assert counts["blocking_sync_in_async"] == 1
+ # The constant-bound ``1 to 3`` loop and the plain helper call do not fire.
+ assert counts["resource_construction_in_loop"] == 0
+
+
+_SCALA_CASES = [
+ (
+ "import slick.jdbc.PostgresProfile.api._\n"
+ "object A { def m(ids: List[Long], db: Database): Unit = {\n"
+ " for (id <- ids) { db.run(query(id)) }\n"
+ "} }\n",
+ [("io_in_loop", "db")],
+ "Slick db.run WITH a db import passes the file-level gate",
+ ),
+ (
+ "object A { def m(ids: List[Long], job: Runner): Unit = {\n"
+ " for (id <- ids) { job.run(id) }\n"
+ "} }\n",
+ [],
+ "ambiguous run() with NO db import is gated out",
+ ),
+ (
+ "object A { def m(ids: List[Long], xa: Any): Unit = {\n"
+ " for (id <- ids) { query(id).transact(xa) }\n"
+ "} }\n",
+ [("io_in_loop", "db")],
+ "doobie .transact is distinctive enough to fire ungated",
+ ),
+ (
+ "import sttp.client3._\n"
+ "object A { def m(reqs: List[Req], backend: Backend): Unit = {\n"
+ " for (r <- reqs) { r.send(backend) }\n"
+ "} }\n",
+ [("io_in_loop", "network")],
+ "sttp request.send WITH a network import",
+ ),
+ (
+ "object A { def m(msgs: List[Msg], actor: Actor): Unit = {\n"
+ " for (m <- msgs) { actor.send(m) }\n"
+ "} }\n",
+ [],
+ "generic .send with NO network import is gated out",
+ ),
+ (
+ "object A { def m(paths: List[String]): Unit = {\n"
+ " for (p <- paths) { os.read(p) }\n"
+ "} }\n",
+ [("io_in_loop", "filesystem")],
+ "os-lib os.read is method-gated (no import needed)",
+ ),
+ (
+ "import scala.concurrent.Future\n"
+ "object A { def m(): Future[Int] = {\n"
+ " Thread.sleep(100)\n"
+ " Future.successful(1)\n"
+ "} }\n",
+ [("blocking_sync_in_async", "Thread.sleep")],
+ "Thread.sleep inside a Future-returning def",
+ ),
+ (
+ "import scala.concurrent.Await\n"
+ "object A { def m(fut: Fut): Int = {\n"
+ " Await.result(fut, d)\n"
+ "} }\n",
+ [],
+ "Await.result in a NON-Future def is not sync-over-async",
+ ),
+ (
+ "object A { def m(items: List[String]): String = {\n"
+ ' var acc = ""\n'
+ " var i = 0\n"
+ " while (i < items.length) {\n"
+ ' acc = acc + "x"\n'
+ " i += 1\n"
+ " }\n"
+ " acc\n"
+ "} }\n",
+ [("string_concat_in_loop", "")],
+ "`acc = acc + \"lit\"` reassignment form on a string var",
+ ),
+]
+
+
[email protected]("src,expected,note", _SCALA_CASES, ids=[c[2] for c in _SCALA_CASES])
+def test_scala_cases(src, expected, note):
+ assert _hits("scala", src) == sorted(expected), note
+
+
+def test_scala_same_collection_nested_loop_fact():
+ # Two nested for-comprehensions over the SAME collection record the
+ # centrality-gated ``nested_loop_quadratic`` fact (not a raw hit).
+ src = (
+ "object A { def m(items: List[Int]): Unit = {\n"
+ " for (a <- items) {\n"
+ " for (b <- items) {\n"
+ " combine(a, b)\n"
+ " }\n"
+ " }\n"
+ "} }\n"
+ )
+ fc = walk_file("t.scala", "scala", src.encode())
+ assert any(f.nested_loop_line for f in fc.perf_fn_facts)
+ assert not any(h.kind == "nested_loop_quadratic" for h in fc.perf_hits)