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 Ruby to Full tier (LanguageNodeMap + perf dialect) (#749)

Raghav Chamadiya0f0774545ad7
diff --git a/README.md b/README.md
index 33539bc16..a7145c561 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 · 10 at the Full tier · framework-aware across all of them.**
+**15 languages parsed to AST · 11 at the Full tier · framework-aware across all of them.**
<p>
<strong>Full tier &nbsp;</strong>
@@ -342,11 +342,11 @@ Install from the Marketplace (search **Repowise**) or Open VSX, then run
<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" />
+ <img src="https://img.shields.io/badge/Ruby-CC342D?style=flat-square&logo=ruby&logoColor=white" alt="Ruby" />
</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/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" />
@@ -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# · 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 |
+| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | 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 · Swift · PHP · Dart | AST parsing, import resolution, named bindings, call resolution, heritage (mixins / derive / extensions / traits), docstrings; dedicated workspace-aware resolvers; 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 9a36724cb..c552d53f1 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 **10 at the Full tier** with code-health markers.
+graphs across them, and scores **11 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# · 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 |
+| **Full** | Python · TypeScript · JavaScript · Java · Kotlin · Go · Rust · C++ · C# · Scala · Ruby | AST parsing, import resolution, named bindings, call resolution, heritage, docstrings, framework-aware edges, dynamic-hint extractors, and **code-health markers** |
+| **Good** | C · Swift · PHP · Dart | Everything above except code-health markers (C, 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 |
@@ -67,10 +67,11 @@ extractors, and code-health markers.
| **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¹) |
+| **Ruby** | `.rb` | `require` / `require_relative` with `$LOAD_PATH` probing, Gemfile externals, RSpec mirror edges, Rails / Zeitwerk autoloading |
-All ten also support three-tier call resolution (same-file, cross-file, global
-stem match) and docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc,
-Scaladoc, Doxygen, XML doc).
+All eleven also support three-tier call resolution (same-file, cross-file,
+global stem match) and docstring extraction (Python, Ruby comments, JSDoc,
+GoDoc, Rustdoc, Javadoc, Scaladoc, Doxygen, XML doc).
**Framework-aware edges** connect routes to handlers, DI registrations to
implementations, and ORM entities to relationships:
@@ -78,6 +79,7 @@ implementations, and ORM entities to relationships:
| Language | Frameworks |
|----------|-----------|
| Python | Django, FastAPI, Flask, pytest fixtures |
+| Ruby | Rails (routes → controller actions, Zeitwerk autoloading), RSpec mirror edges |
| Java / Kotlin | Spring (stereotypes, `@RequestMapping`, Spring Data, `@Bean`), Jakarta / JPA, Quarkus, Micronaut, Android manifest |
| C# | ASP.NET (attribute + minimal API), EF Core, gRPC-dotnet, host-builder extension methods, CommunityToolkit MVVM |
| Go | net/http, gin, echo, chi, gRPC server registration |
@@ -95,13 +97,12 @@ aren't reported as unreachable. (Full per-language detail:
## Good tier
AST parsing, symbol extraction, import resolution, call resolution, named
-bindings, and heritage (Ruby mixins, Rust derive, Swift extension conformance,
-PHP trait use, Dart mixins). Dedicated workspace resolvers per language.
+bindings, and heritage (Swift extension conformance, PHP trait use, Dart
+mixins). Dedicated workspace resolvers per language.
| Language | Extensions | Import style |
|----------|-----------|--------------|
| **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 |
| **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** |
@@ -176,6 +177,7 @@ is "Full" vs "Good".
| C++ | ✅ | ✅ | ✅ | later | later |
| Dart | ✅ | n/a³ | ✅ | later | ✅ |
| Scala | ✅ | ✅ | ✅⁴ | later | ✅⁵ |
+| Ruby | ✅ | ✅⁶ | ✅⁷ | 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
@@ -192,6 +194,27 @@ 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.
+⁶ Class size / method-count / god-class facts only. LCOM4 deliberately sits at
+its "no signal" valve: idiomatic Ruby reaches state via receiver-less `@ivar`
+reads and bare sibling-method calls, so the only mappable shape (`self.member`)
+is too sparse to build an honest cohesion graph on. `@ivar` text grouping is a
+possible follow-up.
+⁷ Bare `assert` and minitest `assert_*` calls plus RSpec `expect(...)` chains
+are counted; minitest's `refute_*` family is not (no assert/expect prefix), and
+RSpec examples (`it ... do` blocks) are not methods, so assertion-run smells
+fire on minitest-style test methods only.
+⁸ **Loops include Ruby's real iteration idiom**: a combinator call with an
+inline block (`.each` / `.map` / `.times` / `find_each` …) counts as a loop
+scope — the block body is per-iteration, the receiver runs once, and
+literal-receiver bounds (`3.times`, `[1, 2].each`, `ALL_CAPS.each`) are
+constant-suppressed. ActiveRecord sinks are stratified: distinctive verbs
+(`find_by` / `pluck` / `update_all` / bang persistence `create!`…) fire
+ungated, `where` needs a constant-rooted receiver, and collision-prone verbs
+(`find` / `first` / `count` / `save`…) need a classified db `require` — which
+Zeitwerk-autoloaded Rails files rarely carry, a deliberate recall ceiling that
+keeps in-memory `Registry.find(name)` lookups silent. Backticks / `system` /
+`Open3` are subprocess sinks; `s += "…"` in a loop is flagged while `s << x`
+(amortized append) never is.
The **performance** signal (`io_in_loop`, `string_concat_in_loop`,
`resource_construction_in_loop`, language-specific markers like Go
@@ -207,7 +230,8 @@ 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 |
+| 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 via the shared `block_loop_body` hook Ruby established |
+| Ruby | Full (health) | Shipped: complexity/class/assertion markers + perf dialect with block-iteration loops (`.each`/`.map` blocks) and the stratified ActiveRecord N+1 lexicon. Next: dataflow dialect, LCOM4 via `@ivar` grouping |
| 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 c2c333ffb..c123663d2 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 10 Full languages plus Dart. See `complexity/README.md`.
+ smells. Ships for the 11 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 f4be202a6..4c9f8a583 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,12 @@ 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 ten full-tier
+Ships control-flow + assertion mappings for **all eleven full-tier
languages** (Python, TypeScript, JavaScript, Go, Java, Kotlin, Rust, C++,
-C#, Scala) plus the `tsx`/`jsx` aliases and Dart; class-level (LCOM4 /
+C#, Scala, Ruby) 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`.
+via an external receiver, so there is no single grouping node). Ruby maps
+`class_kinds` (size / god-class facts) but leaves `member_access_kinds`
+unmapped on purpose — receiver-less `@ivar` idiom — so its LCOM4 stays at the
+no-signal valve. Adding more languages — any tier — is purely additive in
+`languages.py`.
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 ac6ffc2db..346f4f9f7 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -45,17 +45,28 @@ _BODY_FIELD_NAMES = (
# chain continuation. Ternaries / ``if_element`` collection-``if`` are
# deliberately excluded — only statement-level if chains flatten.
_ELSE_IF_NODE_KINDS = frozenset(
- {"if_statement", "if_expression", "elif_clause", "if_let_expression"}
+ {"if_statement", "if_expression", "elif_clause", "elsif", "if_let_expression"}
)
# 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; 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"})
+# is the same inline shape, and Ruby's one-line modifier forms (``return x if
+# cond`` / ``x += 1 until done`` / ``x rescue nil``) are too. Treating them as
+# flat keeps ``max_nesting`` / ``cognitive`` honest — they were only added to
+# ``branch_kinds`` / ``loop_kinds`` / ``catch_kinds`` for the CCN count.
+_FLAT_BRANCH_KINDS = frozenset(
+ {
+ "if_clause",
+ "guard",
+ "if_modifier",
+ "unless_modifier",
+ "while_modifier",
+ "until_modifier",
+ "rescue_modifier",
+ }
+)
def _is_elif_continuation(node: Node) -> bool:
@@ -68,13 +79,14 @@ def _is_elif_continuation(node: Node) -> bool:
special-case. The AST shape differs per grammar:
- Python: a dedicated ``elif_clause`` node (always a continuation).
+ - Ruby: a dedicated ``elsif`` node (always a continuation).
- TypeScript / Rust / C++: the else-if is wrapped in an ``else_clause``.
- Java / Go / C# / Dart / Kotlin: the else-if node is the sibling that
immediately follows the parent ``if``'s ``else`` token.
"""
if node.type not in _ELSE_IF_NODE_KINDS:
return False
- if node.type == "elif_clause":
+ if node.type in ("elif_clause", "elsif"):
return True
parent = node.parent
if parent is None:
@@ -270,10 +282,15 @@ def _walk_function_body(
):
is_flat_match_arm = True
+ # ``node.is_named`` guards grammars (Ruby) whose keyword tokens share
+ # the node-type name of their parent node (an ``if`` node contains an
+ # unnamed ``if`` token of type ``"if"``): only the named node is the
+ # control-flow construct — without the guard every Ruby branch/loop
+ # would double-count.
if is_flat_match_arm:
# Flat match arms: no CCN increment, no nesting increment.
pass
- elif (
+ elif node.is_named and (
node.type in lmap.branch_kinds
or node.type in lmap.loop_kinds
or node.type in lmap.case_kinds
@@ -301,10 +318,10 @@ def _walk_function_body(
enclosing_construct=_enclosing_construct(node, lmap),
)
)
- elif node.type in lmap.try_kinds:
+ elif node.is_named and node.type in lmap.try_kinds:
# TRY opens a nesting level but does not branch on its own.
nesting_increment = 1
- elif node.type in lmap.switch_kinds:
+ elif node.is_named and node.type in lmap.switch_kinds:
# Detect flat match: all arms are simple single-expression arms.
if _is_flat_match(node, lmap):
flat_match_ids.add(node.id)
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 d78dfeff8..38c663139 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 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.
+Control-flow maps cover all eleven full-tier languages (Python, TypeScript,
+JavaScript, Go, Java, Kotlin, Rust, C++, C#, Scala, Ruby) 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
@@ -601,6 +601,69 @@ _SCALA = LanguageNodeMap(
)
+_RUBY = LanguageNodeMap(
+ # NB (grammar-wide): tree-sitter-ruby names keyword tokens after their
+ # parent node (an ``if`` node contains an unnamed ``if`` token of type
+ # ``"if"``); the walkers' ``is_named`` guards keep those tokens from
+ # double-counting.
+ function_kinds=frozenset({"method", "singleton_method"}),
+ # Only the ``->`` literal is a closure-shaped entry. ``block`` /
+ # ``do_block`` are deliberately NOT lambda kinds: Ruby code is block-heavy
+ # and every ``items.each do … end`` would otherwise read as a nested
+ # closure; block bodies roll up into the enclosing method instead.
+ # (``lambda { }`` / ``proc { }`` parse as plain calls with a block and
+ # likewise roll up.)
+ lambda_kinds=frozenset({"lambda"}),
+ # ``conditional`` is the ternary; the one-line modifier forms (``return x
+ # if cond``) are flat decision points (see ``_FLAT_BRANCH_KINDS``), as is
+ # the inline ``x rescue nil`` (``rescue_modifier`` — a catch shape, but an
+ # inline one, so it lives here with the other flat branches).
+ branch_kinds=frozenset(
+ {
+ "if",
+ "unless",
+ "elsif",
+ "if_modifier",
+ "unless_modifier",
+ "conditional",
+ "rescue_modifier",
+ }
+ ),
+ # ``loop do … end`` and ``.each``/``.map`` blocks are method calls, not
+ # loop nodes — the perf dialect recognises them via ``block_loop_body``;
+ # for CCN/nesting they roll up like any other block (documented choice:
+ # block-heavy Ruby would otherwise nest everything).
+ loop_kinds=frozenset({"while", "until", "for", "while_modifier", "until_modifier"}),
+ try_kinds=frozenset({"begin"}),
+ # A method-level ``rescue`` (no ``begin``) is the same ``rescue`` node
+ # nested directly in the method body — counted identically.
+ catch_kinds=frozenset({"rescue"}),
+ switch_kinds=frozenset({"case", "case_match"}),
+ case_kinds=frozenset({"when", "in_clause"}),
+ boolean_operator_kinds=frozenset(),
+ # ``&&`` / ``||`` / ``and`` / ``or`` are operator tokens inside a generic
+ # ``binary`` node — the text sniff.
+ boolean_operator_text_kinds=frozenset({"binary"}),
+ class_kinds=frozenset({"class", "module", "singleton_class"}),
+ self_identifiers=frozenset({"self"}),
+ # LCOM4 stays at its "no signal" valve: idiomatic Ruby reaches state via
+ # receiver-less ``@ivar`` reads and bare sibling-method calls, so the only
+ # mappable shape (an explicit ``self.member`` call) is too sparse to build
+ # an honest cohesion graph on — partial evidence would inflate LCOM4 into
+ # false ``low_cohesion`` hits. ``@ivar`` text grouping is the follow-up.
+ # Class size / method-count / max-CCN facts still work off ``class_kinds``.
+ member_access_kinds=frozenset(),
+ # minitest ``assert_equal`` / bare ``assert`` and RSpec ``expect(...)``
+ # are all ``call`` nodes and match the shared assert/expect prefix rule;
+ # minitest's ``refute_*`` family does not (under-signal, safe).
+ assert_call_kinds=frozenset({"call"}),
+ # ``subshell`` is a backtick command — its own node type, mapped so the
+ # perf dialect can classify it as a subprocess sink.
+ call_kinds=frozenset({"call", "subshell"}),
+ # Ruby has no async syntax; ``blocking_sync_in_async`` is n/a.
+)
+
+
LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"python": _PY,
"typescript": _TS,
@@ -615,6 +678,7 @@ LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {
"csharp": _CSHARP,
"dart": _DART,
"scala": _SCALA,
+ "ruby": _RUBY,
}
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 cef36508d..752d12c4c 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
@@ -22,6 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from ..perf.dialects import PERF_DIALECTS
+from ..perf.dialects.base import BasePerfDialect as BasePerfDialectClass
from ..perf.io_boundaries import collect_io_names
from .languages import LanguageNodeMap
from .models import PerfFnFacts, PerfHit
@@ -85,10 +86,11 @@ _LOOP_ITERABLE_CALL_MARKER_KINDS = frozenset({"pandas_iterrows_in_loop"})
_HOT_PATH_SINK_KINDS = frozenset({"subprocess", "filesystem"})
# Block node kinds that form the *body* of a lock construct (C# ``lock (x) {…}``
-# / Java ``synchronized (x) {…}``). Only the body runs with the lock held, so
-# ``lock_depth`` is raised for the body child only — a sink in the lock-object
-# expression (``synchronized(repo.find(id)){…}``) runs BEFORE the lock is taken.
-_LOCK_BODY_KINDS = frozenset({"block", "statement_block", "compound_statement"})
+# / Java ``synchronized (x) {…}`` / Ruby ``mutex.synchronize do … end``). Only
+# the body runs with the lock held, so ``lock_depth`` is raised for the body
+# child only — a sink in the lock-object expression
+# (``synchronized(repo.find(id)){…}``) runs BEFORE the lock is taken.
+_LOCK_BODY_KINDS = frozenset({"block", "statement_block", "compound_statement", "do_block"})
# Non-semantic wrapper nodes tree-sitter inserts between a ``call`` and its
# enclosing ``await`` — parenthesising an awaited call (``await (foo())``) adds a
@@ -124,17 +126,23 @@ def _perf_func_name(node: Node) -> str | None:
def _enclosing_loop_iterables(
- node: Node, dialect: BasePerfDialect, loop_kinds: frozenset[str], fn_kinds: frozenset[str]
+ node: Node,
+ dialect: BasePerfDialect,
+ loop_kinds: frozenset[str],
+ fn_kinds: frozenset[str],
+ block_loops: bool = False,
) -> set[str]:
"""Names of the collections every enclosing loop (up to the function bound)
iterates over — the lookup the same-collection ``nested_loop_quadratic``
- shape gate compares the inner loop's iterable against."""
+ shape gate compares the inner loop's iterable against. When the dialect
+ recognises block-iteration calls (*block_loops*), those count as enclosing
+ loops too (Ruby ``items.each do … end``)."""
names: set[str] = set()
cur = node.parent
for _ in range(64):
if cur is None or cur.type in fn_kinds:
break
- if cur.type in loop_kinds:
+ if cur.type in loop_kinds or (block_loops and dialect.block_loop_body(cur) is not None):
nm = dialect.loop_iterable_name(cur)
if nm:
names.add(nm)
@@ -191,6 +199,9 @@ def _collect_perf_hits(
fn_kinds = lmap.function_kinds
lambda_kinds = lmap.lambda_kinds
async_fn_kinds = lmap.async_function_kinds
+ # Block-iteration loops (Ruby ``items.each do … end``): only pay for the
+ # per-call-node hook when the dialect actually overrides it.
+ do_block_loop = type(dialect).block_loop_body is not BasePerfDialectClass.block_loop_body
hits: list[PerfHit] = []
# Per-enclosing-function accumulators keyed by the function's start line
@@ -226,9 +237,21 @@ def _collect_perf_hits(
node, loop_depth, in_async, func_name, func_start, lock_depth, outer_iter = stack.pop()
t = node.type
- is_loop = t in loop_kinds
+ # ``node.is_named`` guards grammars (Ruby) whose keyword tokens share
+ # the node-type name of their parent (a ``while`` node contains an
+ # unnamed ``while`` token) — only the named node is the loop.
+ is_loop = t in loop_kinds and node.is_named
+ # Block-iteration loop (Ruby ``items.each do … end``): the dialect
+ # recognises the call and returns the per-iteration body node; the
+ # receiver / arguments still run once (native loop-BODY scoping).
+ block_loop_body: Node | None = None
+ if not is_loop and do_block_loop and t in call_kinds:
+ block_loop_body = dialect.block_loop_body(node)
+ if block_loop_body is not None:
+ is_loop = True
if is_loop and dialect.is_constant_loop(node):
is_loop = False
+ block_loop_body = None
entering_fn = t in fn_kinds or t in lambda_kinds
is_async_fn = t in async_fn_kinds or (entering_fn and dialect.is_async_fn(node))
@@ -260,7 +283,9 @@ def _collect_perf_hits(
# loop iterates the same named collection as an enclosing loop
# (all-pairs O(n^2)) — which all four Phase-7c labelers converged on.
nm = dialect.loop_iterable_name(node)
- if nm and nm in _enclosing_loop_iterables(node, dialect, loop_kinds, fn_kinds):
+ if nm and nm in _enclosing_loop_iterables(
+ node, dialect, loop_kinds, fn_kinds, do_block_loop
+ ):
misc = _acc(next_start, next_func)[3]
if misc[0] == 0:
misc[0] = node.start_point[0] + 1
@@ -430,8 +455,11 @@ def _collect_perf_hits(
# inherit it. Set when entering the first loop (loop_depth 0 -> 1).
next_outer_iter = outer_iter if loop_depth >= 1 else dialect.is_iteration_loop(node)
# Only the loop BODY runs per-iteration; the ``for x in <iterable>``
- # header / ``while <cond>`` condition runs once.
- body = node.child_by_field_name("body")
+ # header / ``while <cond>`` condition runs once. For a block-
+ # iteration loop the body is the dialect-returned block node.
+ body = block_loop_body
+ if body is None:
+ body = node.child_by_field_name("body")
if body is not None:
# NB: tree-sitter Node wrappers are not singletons, so compare
# with ``==`` (identity by tree + byte range), never ``is``.
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 1fd1ca6d0..3f585b2de 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
@@ -19,6 +19,7 @@ from . import dart as _dart
from . import go as _go
from . import java as _java
from . import python as _python
+from . import ruby as _ruby
from . import rust as _rust
from . import scala as _scala
from . import ts_js as _ts_js
@@ -39,6 +40,7 @@ _REGISTER: tuple[tuple[str, BasePerfDialect], ...] = (
("rust", _rust.DIALECT),
("dart", _dart.DIALECT),
("scala", _scala.DIALECT),
+ ("ruby", _ruby.DIALECT),
)
for _tag, _dialect in _REGISTER:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
index 4bbe26f6f..1ea643d41 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
@@ -181,6 +181,27 @@ class BasePerfDialect:
"""True if this loop's bound is a compile-time constant (not N+1)."""
return False
+ def block_loop_body(self, node: Node) -> Node | None:
+ """The per-iteration body when *node* is a call-with-block the language
+ counts as a loop (Ruby ``items.each do |x| ... end``), else ``None``.
+
+ The shared answer to combinator/block iteration: languages whose real
+ loop idiom is a method call taking a block (Ruby ``.each``/``.map``,
+ and later Scala ``.foreach``, Kotlin ``forEach``, Dart ``forEach``)
+ override this to return the block node when the callee is a known
+ full-iteration combinator AND a block argument is present. The walker
+ then treats the call as a loop whose body is exactly the returned
+ node — the receiver and arguments still run once, mirroring the
+ loop-BODY scoping rule for native loops. Only *statically certain*
+ iteration counts: a combinator without an inline block (``.map(&:f)``)
+ returns ``None`` because there is no per-iteration body to scan.
+
+ Default ``None`` — a dialect that does not override this is
+ byte-for-byte unchanged (the walker skips the hook entirely unless it
+ is overridden).
+ """
+ return None
+
def is_iteration_loop(self, node: Node) -> bool:
"""True if this loop iterates a *collection* (a data multiplier), rather
than spinning a cursor (``while (hasMore)`` / ``for (;;)``).
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ruby.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ruby.py
new file mode 100644
index 000000000..db9e7d7a4
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ruby.py
@@ -0,0 +1,524 @@
+"""Ruby ``PerfDialect``.
+
+Owns the **block-iteration loop definition** (the shared design decision the
+plan assigns to Ruby): idiomatic Ruby iterates via combinator calls taking a
+block (``items.each do |x| … end`` / ``items.map { … }``), not ``while``/``for``
+nodes, so :meth:`block_loop_body` recognises a ``call`` whose method is a known
+full-iteration combinator AND that carries an inline block, and returns the
+block node as the per-iteration body. The walker then applies every loop rule
+(body scoping, constant-bound skip, nesting, same-collection quadratic gate)
+to it exactly as to a native loop. Scala (``.map``/``.foreach``), Kotlin and
+Dart backport this hook rather than re-deciding the question.
+
+Flagship: the canonical Rails N+1 — an ActiveRecord query inside ``.each``.
+The AR lexicon is stratified like Python's DBAPI strata: distinctive verbs
+(``find_by`` / ``pluck`` / ``update_all``…) fire ungated; ``where`` needs a
+constant-rooted receiver (a model class); generic collision-prone verbs
+(``find`` / ``first`` / ``count``…) additionally need file-level db evidence.
+Rails' Zeitwerk autoloading means most Rails files carry no ``require`` at
+all, so that evidence gate rarely opens there — a documented recall ceiling
+that keeps ``Plugin.find(name)``-style in-memory registries from false-firing.
+
+Grammar seams: a ``call`` node has ``receiver`` / ``method`` fields (no
+``function`` field, so all three callee hooks are overridden); backticks are a
+dedicated ``subshell`` node routed through a sentinel method name; ``x += y``
+is an ``operator_assignment`` whose ``+=`` operator token satisfies the base
+string-concat predicate, while ``s << x`` is a plain ``binary`` (amortized
+append — never flagged, by construction).
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .base import BasePerfDialect
+from .python import HTTP_VERBS
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+# Full-iteration combinators: a ``call`` with one of these methods AND an
+# inline block is a loop scope (the block body runs once per element).
+# Early-exit searches (``find`` / ``detect`` / ``any?``) are deliberately
+# absent — they may stop after one element, so flagging their bodies as
+# per-iteration would overclaim. ``loop`` is the unconditional-repeat form.
+ITERATION_BLOCK_METHODS: frozenset[str] = frozenset(
+ {
+ "each",
+ "each_with_index",
+ "each_with_object",
+ "each_slice",
+ "each_cons",
+ "each_pair",
+ "each_key",
+ "each_value",
+ "each_entry",
+ "each_line",
+ "each_char",
+ "each_byte",
+ "reverse_each",
+ "map",
+ "map!",
+ "flat_map",
+ "collect",
+ "collect!",
+ "filter_map",
+ "select",
+ "select!",
+ "filter",
+ "reject",
+ "reject!",
+ "partition",
+ "group_by",
+ "sort_by",
+ "min_by",
+ "max_by",
+ "sum",
+ "count",
+ "reduce",
+ "inject",
+ "times",
+ "upto",
+ "downto",
+ "step",
+ # ActiveRecord batch iteration — a loop AND a db sink in one call.
+ "find_each",
+ "find_in_batches",
+ "in_batches",
+ "loop",
+ }
+)
+
+# ``.times`` / ``.upto`` — data-independent when the receiver is a literal.
+_COUNTING_METHODS: frozenset[str] = frozenset({"times", "upto", "downto", "step"})
+
+# --- filesystem --------------------------------------------------------------
+_FILE_METHODS: frozenset[str] = frozenset(
+ {
+ "read",
+ "write",
+ "open",
+ "readlines",
+ "foreach",
+ "binread",
+ "binwrite",
+ "delete",
+ "unlink",
+ "rename",
+ "exist?",
+ "exists?",
+ "stat",
+ "mtime",
+ "size",
+ }
+)
+_IO_FS_METHODS: frozenset[str] = frozenset(
+ {"read", "write", "foreach", "readlines", "binread", "binwrite", "copy_stream"}
+)
+_DIR_METHODS: frozenset[str] = frozenset(
+ {
+ "glob",
+ "entries",
+ "children",
+ "each_child",
+ "foreach",
+ "mkdir",
+ "rmdir",
+ "delete",
+ "exist?",
+ "exists?",
+ }
+)
+_CSV_FS_METHODS: frozenset[str] = frozenset({"read", "foreach", "open"})
+
+# --- network -----------------------------------------------------------------
+_NET_HTTP_METHODS: frozenset[str] = frozenset(
+ {
+ "get",
+ "post",
+ "put",
+ "delete",
+ "patch",
+ "head",
+ "get_response",
+ "post_form",
+ "start",
+ "request",
+ "request_get",
+ "request_post",
+ }
+)
+# Distinctive HTTP-client constants — a verb on one of these is a round-trip.
+_HTTP_CLIENT_ROOTS: frozenset[str] = frozenset(
+ {"HTTParty", "Faraday", "RestClient", "Excon", "Typhoeus", "HTTP"}
+)
+
+# --- db ----------------------------------------------------------------------
+# Stratum 1 — distinctive ActiveRecord/Mongoid verbs: no stdlib/core collision,
+# fire ungated on any member call.
+_AR_UNAMBIGUOUS: frozenset[str] = frozenset(
+ {
+ "find_by",
+ "find_by!",
+ "find_each",
+ "find_in_batches",
+ "in_batches",
+ "find_or_create_by",
+ "find_or_create_by!",
+ "find_or_initialize_by",
+ "pluck",
+ "update_all",
+ "delete_all",
+ "destroy_all",
+ "insert_all",
+ "upsert_all",
+ "exists?",
+ # Bang persistence verbs — the raise-on-failure convention is
+ # ActiveRecord-distinctive (plain ``create``/``save`` collide with
+ # factory helpers and are left to the evidence-gated stratum below).
+ # ``obj.assoc.create!`` inside ``.each`` is the classic N+1 write.
+ "create!",
+ "save!",
+ "update!",
+ "destroy!",
+ }
+)
+# Raw-connection execution verbs (``conn.execute(sql)``) — the Python DBAPI
+# posture: unambiguous when called as a member.
+_DB_EXEC_METHODS: frozenset[str] = frozenset(
+ {
+ "execute",
+ "exec_query",
+ "exec_insert",
+ "exec_update",
+ "exec_delete",
+ "select_all",
+ "select_one",
+ "select_value",
+ "select_values",
+ }
+)
+# Stratum 2 — ``where`` needs a constant-rooted receiver (an AR model class /
+# Sequel ``DB`` handle); no Ruby core class responds to ``where``.
+# Stratum 3 — collision-prone verbs (Enumerable/Hash surface) additionally need
+# file-level db evidence (a classified db require), like Python's ambiguous
+# stratum.
+_AR_AMBIGUOUS: frozenset[str] = frozenset(
+ {"find", "first", "last", "all", "count", "sum", "take", "create", "save", "update", "destroy"}
+)
+
+# --- subprocess ----------------------------------------------------------------
+_OPEN3_METHODS: frozenset[str] = frozenset(
+ {
+ "capture2",
+ "capture2e",
+ "capture3",
+ "popen2",
+ "popen2e",
+ "popen3",
+ "pipeline",
+ "pipeline_r",
+ "pipeline_w",
+ "pipeline_rw",
+ }
+)
+_BARE_SUBPROCESS: frozenset[str] = frozenset({"system", "spawn", "exec"})
+
+# Sentinel routed through the callee hooks for backtick ``subshell`` nodes —
+# not a legal Ruby method name, so it can never collide.
+_SUBSHELL = "__subshell__"
+
+# Heavy-client constructors: building one per loop iteration opens a fresh
+# connection/session instead of reusing a hoisted one.
+_RESOURCE_NEW_ROOTS: frozenset[str] = frozenset(
+ {"Net::HTTP", "Faraday", "Redis", "Mongo::Client", "Mysql2::Client"}
+)
+_RESOURCE_CONNECT_ROOTS: frozenset[str] = frozenset({"PG", "Sequel", "Mysql2"})
+
+_REGEXP_CTOR_METHODS: frozenset[str] = frozenset({"new", "compile", "union"})
+
+_STRING_KINDS: frozenset[str] = frozenset({"string"})
+
+
+def _decode(node: Node | None) -> str | None:
+ if node is None or node.text is None:
+ return None
+ return node.text.decode("utf-8", "replace")
+
+
+class RubyPerfDialect(BasePerfDialect):
+ language = "ruby"
+ markers = frozenset(
+ {
+ "io_in_loop",
+ "string_concat_in_loop",
+ "regex_compile_in_loop",
+ "resource_construction_in_loop",
+ "lock_in_loop",
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
+ }
+ )
+
+ string_literal_kinds = _STRING_KINDS
+ aug_assign_kinds = frozenset({"operator_assignment"})
+
+ # -- callee extraction (receiver/method fields, no ``function`` field) -----
+
+ def callee_method_name(self, call_node: Node) -> str | None:
+ if call_node.type == "subshell":
+ return _SUBSHELL
+ return _decode(call_node.child_by_field_name("method"))
+
+ def callee_root_name(self, call_node: Node) -> str | None:
+ if call_node.type == "subshell":
+ return _SUBSHELL
+ recv = call_node.child_by_field_name("receiver")
+ if recv is None:
+ # Bare call: the root is its own name (``system("ls")`` -> system).
+ return _decode(call_node.child_by_field_name("method"))
+ # Walk down a chain (``Order.where(x).each`` -> the ``Order`` bottom).
+ for _ in range(8):
+ if recv.type != "call":
+ break
+ nxt = recv.child_by_field_name("receiver")
+ if nxt is None:
+ # Chain bottoms at a bare call (``helper().each``).
+ return _decode(recv.child_by_field_name("method"))
+ recv = nxt
+ if recv.type == "scope_resolution":
+ # Keep the full path — ``Net::HTTP`` / ``ActiveRecord::Base`` are
+ # the distinctive lexicon keys.
+ return _decode(recv)
+ if recv.type in ("identifier", "constant", "instance_variable", "self"):
+ return _decode(recv)
+ return None
+
+ def callee_is_attribute(self, call_node: Node) -> bool:
+ return call_node.child_by_field_name("receiver") is not None
+
+ # -- 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:
+ if method == _SUBSHELL:
+ return "subprocess"
+ # ``require`` binds lowercase feature segments (``net`` / ``httparty``)
+ # while call receivers are constants — normalise before the lookup.
+ root_kind = io_names.get(root) or io_names.get(root.split("::")[0].lower())
+ db_ev = has_db_import or root_kind == "db"
+ net_ev = root_kind == "network" or "network" in io_names.values()
+
+ # Subprocess first — distinctive shapes, no gate needed.
+ if root == "Open3" and method in _OPEN3_METHODS:
+ return "subprocess"
+ if root == "IO" and method == "popen":
+ return "subprocess"
+ if root in ("Process", "PTY") and method in ("spawn", "exec"):
+ return "subprocess"
+ if not is_attribute and method in _BARE_SUBPROCESS:
+ return "subprocess"
+ if root == "Kernel" and method in _BARE_SUBPROCESS:
+ return "subprocess"
+
+ # Filesystem — distinctive stdlib constants, before db so ``File.read``
+ # / ``Dir.exist?`` never reach the ambiguous strata.
+ if root == "File" and method in _FILE_METHODS:
+ return "filesystem"
+ if root == "IO" and method in _IO_FS_METHODS:
+ return "filesystem"
+ if root == "Dir" and method in _DIR_METHODS:
+ return "filesystem"
+ if root == "FileUtils": # the whole module is filesystem verbs
+ return "filesystem"
+ if root == "Find" and method == "find":
+ return "filesystem"
+ if root == "Tempfile" and method in ("new", "create", "open"):
+ return "filesystem"
+ if root == "CSV" and method in _CSV_FS_METHODS:
+ return "filesystem"
+ if method == "load_file": # ``YAML.load_file`` / ``JSON.load_file``
+ return "filesystem"
+ if not is_attribute and method == "open": # bare Kernel#open
+ return "filesystem"
+
+ # Network — distinctive client constants.
+ if root == "Net::HTTP" and method in _NET_HTTP_METHODS:
+ return "network"
+ if root in _HTTP_CLIENT_ROOTS and is_attribute and method in _NET_HTTP_METHODS:
+ return "network"
+ if root == "URI" and method == "open": # open-uri
+ return "network"
+ # Instance clients (``conn.get`` on a Faraday connection) need
+ # file-level network evidence — ``get``/``post`` are far too generic
+ # alone (Sinatra's route DSL is a bare ``get``, already excluded by
+ # ``is_attribute``).
+ if is_attribute and net_ev and method in HTTP_VERBS:
+ return "network"
+
+ # DB — the stratified ActiveRecord/Sequel lexicon (see module docstring).
+ if is_attribute and (method in _AR_UNAMBIGUOUS or method.startswith("find_by_")):
+ return "db"
+ if is_attribute and method in _DB_EXEC_METHODS:
+ return "db"
+ if is_attribute and method == "where" and root and root[0].isupper():
+ return "db"
+ if is_attribute and db_ev and (method in _AR_AMBIGUOUS or method == "where"):
+ return "db"
+ if is_attribute and db_ev and method == "run": # Sequel ``DB.run(sql)``
+ return "db"
+ return None
+
+ # -- block-iteration loops (the shared design decision) ---------------------
+
+ def block_loop_body(self, node: Node) -> Node | None:
+ if node.type != "call":
+ return None
+ block = node.child_by_field_name("block")
+ if block is None:
+ return None
+ method = _decode(node.child_by_field_name("method"))
+ return block if method in ITERATION_BLOCK_METHODS else None
+
+ def is_constant_loop(self, node: Node) -> bool:
+ """``for i in 1..3`` / ``[1, 2].each`` / ``3.times`` / ``ROLES.each`` —
+ compile-time-constant bounds, not data-dependent multipliers."""
+ if node.type == "for":
+ it = self._for_iterable(node)
+ return it is not None and self._is_constant_collection(it)
+ if node.type == "call":
+ recv = node.child_by_field_name("receiver")
+ return recv is not None and self._is_constant_collection(recv)
+ return False
+
+ @staticmethod
+ def _is_constant_collection(node: Node) -> bool:
+ if node.type in ("integer", "float", "string", "array", "range"):
+ if node.type == "range":
+ return all(c.type == "integer" for c in node.children if c.is_named)
+ return True
+ if node.type == "constant" and node.text is not None:
+ name = node.text.decode("utf-8", "replace")
+ return name.isupper() and len(name) > 1 # ALL_CAPS named constant
+ return False
+
+ @staticmethod
+ def _for_iterable(node: Node) -> Node | None:
+ """The iterable of a ``for x in xs`` loop (the ``in`` node's payload)."""
+ value = node.child_by_field_name("value")
+ if value is None:
+ return None
+ return next((c for c in value.children if c.is_named), None)
+
+ def is_iteration_loop(self, node: Node) -> bool:
+ # ``while`` / ``until`` (+ modifier forms) and ``loop do`` are cursors
+ # (pagination / retry), not data multipliers; ``for`` and the
+ # collection combinators iterate a collection.
+ if node.type == "for":
+ return True
+ if node.type == "call":
+ method = _decode(node.child_by_field_name("method"))
+ return method != "loop"
+ return False
+
+ def loop_iterable_name(self, node: Node) -> str | None:
+ if node.type == "for":
+ return self._dotted_path(self._for_iterable(node))
+ if node.type == "call":
+ method = _decode(node.child_by_field_name("method"))
+ if method in _COUNTING_METHODS or method == "loop":
+ return None # ``n.times`` iterates a count, not a collection
+ return self._dotted_path(node.child_by_field_name("receiver"))
+ return None
+
+ # -- string concat -----------------------------------------------------------
+
+ def _rhs_is_stringish(self, node: Node) -> bool:
+ # Same posture as the base predicate, but Ruby's binary-op node is
+ # ``binary`` (not ``binary_expression``): ``s += x + "\n"`` counts when
+ # a string literal is an operand.
+ right = node.child_by_field_name("right")
+ if right is None:
+ return False
+ if right.type in self.string_literal_kinds:
+ return True
+ if right.type == "binary":
+ return any(c.is_named and c.type in self.string_literal_kinds for c in right.children)
+ return False
+
+ def is_string_concat(self, node: Node) -> bool:
+ """``s += "<lit>"`` (a fresh String every pass — O(n^2)); ``s << x`` is
+ amortized append and parses as a plain ``binary``, so it can never
+ reach here. Mirrors the Python reset-per-iteration guard: an
+ accumulator plainly re-assigned inside the enclosing loop body is
+ bounded per iteration, not a cross-iteration accumulation.
+ """
+ if not super().is_string_concat(node):
+ return False
+ left = node.child_by_field_name("left")
+ if left is None or left.type != "identifier" or left.text is None:
+ return True # opaque / @ivar target -> keep the precision-first flag
+ name = left.text
+ cur = node.parent
+ while cur is not None:
+ body: Node | None = None
+ if cur.type in ("while", "until", "for"):
+ body = cur.child_by_field_name("body")
+ elif cur.type == "call":
+ body = self.block_loop_body(cur)
+ if body is not None and self._resets_name(body, name):
+ return False
+ cur = cur.parent
+ return True
+
+ @staticmethod
+ def _resets_name(body: Node, name: bytes) -> bool:
+ """True if *body* contains a plain ``name = …`` assignment (the
+ accumulator is reset each iteration)."""
+ stack: list[Node] = [body]
+ while stack:
+ n = stack.pop()
+ if n.type == "assignment":
+ lhs = n.child_by_field_name("left")
+ if lhs is not None and lhs.type == "identifier" and lhs.text == name:
+ return True
+ stack.extend(n.children)
+ return False
+
+ # -- extra loop markers --------------------------------------------------------
+
+ def loop_call_marker(
+ self, root: str, method: str, node: Node, list_names: frozenset[str]
+ ) -> str | None:
+ # ``Regexp.new(pattern)`` recompiles per iteration; ``/…/`` literals are
+ # compiled once by the VM and never fire.
+ if root == "Regexp" and method in _REGEXP_CTOR_METHODS:
+ return "regex_compile_in_loop"
+ if method == "new" and root in _RESOURCE_NEW_ROOTS:
+ return "resource_construction_in_loop"
+ if method == "connect" and root in _RESOURCE_CONNECT_ROOTS:
+ return "resource_construction_in_loop"
+ # ``mutex.synchronize { … }`` taken every iteration is a contention site.
+ if method == "synchronize" and self.callee_is_attribute(node):
+ return "lock_in_loop"
+ return None
+
+ def is_lock_scope(self, node: Node) -> bool:
+ # ``mutex.synchronize do … end`` — the block argument is the held
+ # region (the walker raises lock_depth for block-typed children only).
+ if node.type != "call":
+ return False
+ return self.callee_method_name(node) == "synchronize"
+
+
+DIALECT = RubyPerfDialect()
diff --git a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
index 9b7d85564..2bd1672f2 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
@@ -144,7 +144,21 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:
# ``import`` covers Python / TS / Java / Go import nodes; C# spells its
# import a ``using_directive`` (and Go an ``import_spec``), Rust a
# ``use_declaration`` — none of which contains the substring "import".
- if "import" in node.type or node.type in ("using_directive", "use_declaration"):
+ if node.type == "call" and language == "ruby":
+ # Ruby's import statement is a method call: ``require "net/http"``.
+ # Classify the quoted feature path; its segments bind lowercase
+ # (``net`` / ``httparty``), which the Ruby dialect normalises its
+ # constant receivers against. ``require_relative`` paths are local
+ # files and never classify — harmless to run through the table.
+ method = (
+ node.child_by_field_name("method") if hasattr(node, "child_by_field_name") else None
+ )
+ if method is not None and (method.text or b"") in (b"require", b"require_relative"):
+ kind, bound = _classify_import(node)
+ if kind is not None:
+ for name in bound:
+ names.setdefault(name, kind)
+ elif "import" in node.type or node.type in ("using_directive", "use_declaration"):
# Classify only the *leaf* import node. A Go grouped
# ``import ( "database/sql"; "regexp" )`` is an ``import_declaration``
# wrapping per-line ``import_spec`` leaves; classifying the wrapper
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 dda980c94..06ca4c7b1 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
@@ -70,6 +70,9 @@ _DB_NAMES: frozenset[str] = frozenset({
# Scala (root package as imported: ``import slick.jdbc...`` -> ``slick``,
# ``import doobie._`` -> ``doobie``; Quill imports as ``io.getquill``).
"slick", "doobie", "scalikejdbc", "anorm", "io.getquill",
+ # Ruby (require-feature names; ``pg`` / ``mysql2`` / ``redis`` above are
+ # shared with the Node ecosystem).
+ "activerecord", "active_record", "sequel", "mongoid", "sqlite3", "mongo",
})
_NETWORK_NAMES: frozenset[str] = frozenset({
@@ -95,6 +98,9 @@ _NETWORK_NAMES: frozenset[str] = frozenset({
# sttp.client3._`` -> ``sttp``; ``import org.http4s...`` -> ``org.http4s``;
# ``import akka.http.scaladsl...`` -> ``akka.http``).
"sttp", "org.http4s", "akka.http", "play.api.libs.ws",
+ # Ruby (require-feature names; ``require "net/http"`` resolves via its
+ # ``http`` segment above).
+ "httparty", "faraday", "rest-client", "rest_client", "typhoeus", "excon",
})
_FILESYSTEM_NAMES: frozenset[str] = frozenset({
@@ -116,6 +122,8 @@ _FILESYSTEM_NAMES: frozenset[str] = frozenset({
# bare name would collide with Python's stdlib ``os`` cross-ecosystem, so
# the Scala perf dialect method-gates it instead).
"scala.io",
+ # Ruby (require-feature names)
+ "fileutils", "tempfile",
})
_SUBPROCESS_NAMES: frozenset[str] = frozenset({
@@ -125,6 +133,8 @@ _SUBPROCESS_NAMES: frozenset[str] = frozenset({
"child_process", "node:child_process", "execa", "cross-spawn", "shelljs",
# Go (os/exec resolves via the interior segment ``exec``)
"os/exec",
+ # Ruby (require-feature names)
+ "open3", "pty",
})
_LOCK_NAMES: frozenset[str] = frozenset({
diff --git a/tests/fixtures/lang_samples/ruby/assertions.rb b/tests/fixtures/lang_samples/ruby/assertions.rb
new file mode 100644
index 000000000..e7fb0c2dc
--- /dev/null
+++ b/tests/fixtures/lang_samples/ruby/assertions.rb
@@ -0,0 +1,19 @@
+require "minitest/autorun"
+
+class TestFoo < Minitest::Test
+ def test_many_asserts
+ result = compute
+ assert_equal 1, result
+ assert result
+ assert_includes [1, 2], result
+ assert_equal 2, result + 1
+ assert_operator result, :<, 10
+ end
+
+ def test_few_asserts
+ result = compute
+ assert_equal 1, result
+ puts result
+ refute_nil result
+ end
+end
diff --git a/tests/fixtures/lang_samples/ruby/classes.rb b/tests/fixtures/lang_samples/ruby/classes.rb
new file mode 100644
index 000000000..c726ec213
--- /dev/null
+++ b/tests/fixtures/lang_samples/ruby/classes.rb
@@ -0,0 +1,53 @@
+# Class-metrics fixture: method counts / god-class facts work off class_kinds;
+# LCOM4 deliberately sits at its "no signal" valve for Ruby (receiver-less
+# @ivar idiom), so even the splintered class must report lcom4 == 1.
+
+class Cohesive
+ def initialize
+ @x = 0
+ end
+
+ def bump
+ @x += 1
+ end
+
+ def read
+ @x
+ end
+end
+
+class Splintered
+ def a
+ @x = 1
+ end
+
+ def b
+ @x
+ end
+
+ def c
+ @y = 1
+ end
+
+ def d
+ @y
+ end
+
+ def e
+ if @y
+ 42
+ else
+ 7
+ end
+ end
+end
+
+module Util
+ def self.helper_one
+ 1
+ end
+
+ def helper_two
+ 2
+ end
+end
diff --git a/tests/fixtures/lang_samples/ruby/nested.rb b/tests/fixtures/lang_samples/ruby/nested.rb
new file mode 100644
index 000000000..080683ad7
--- /dev/null
+++ b/tests/fixtures/lang_samples/ruby/nested.rb
@@ -0,0 +1,93 @@
+# Control-flow fixture for the Ruby complexity walker.
+
+def deeply_nested(x)
+ if x > 0
+ while x > 0
+ if x > 1
+ if x > 2
+ puts x
+ end
+ end
+ x -= 1
+ end
+ end
+end
+
+def many_branches(a, b)
+ return 0 if a.nil?
+ if a > 0 && b > 0
+ 1
+ elsif a > 0 || b > 0
+ 2
+ elsif a.zero?
+ 3
+ else
+ 4
+ end
+end
+
+def wordy(a, b)
+ a and b or a
+end
+
+def shallow(x)
+ x
+end
+
+def block_heavy(items)
+ items.each do |group|
+ group.map { |x| x * 2 }
+ end
+end
+
+def flat_case(x)
+ case x
+ when 1 then :one
+ when 2 then :two
+ else :many
+ end
+end
+
+def heavy_case(x)
+ case x
+ when 1
+ if x.odd?
+ :odd_one
+ end
+ when 2 then :two
+ when 3 then :three
+ end
+end
+
+def pattern_match(x)
+ case x
+ in { a: Integer => n }
+ n
+ in [b]
+ b
+ end
+end
+
+def risky_io(path)
+ begin
+ File.read(path)
+ rescue ArgumentError => e
+ puts e
+ rescue TypeError
+ puts "type"
+ ensure
+ puts "done"
+ end
+end
+
+def implicit_rescue
+ compute
+rescue StandardError
+ nil
+end
+
+def modifier_loops(x)
+ x += 1 until x > 10
+ x -= 1 while x > 0
+ x
+end
diff --git a/tests/fixtures/lang_samples/ruby/perf_io_in_loop.rb b/tests/fixtures/lang_samples/ruby/perf_io_in_loop.rb
new file mode 100644
index 000000000..c60d2efb2
--- /dev/null
+++ b/tests/fixtures/lang_samples/ruby/perf_io_in_loop.rb
@@ -0,0 +1,88 @@
+# Perf-dialect fixture: block-iteration loops, the sink lexicon, string
+# concat (+= flagged, << not), regex/resource construction, lock scopes.
+
+require "net/http"
+
+def sync_fetch_each(urls)
+ urls.each do |url|
+ Net::HTTP.get(URI(url))
+ end
+end
+
+def read_files(paths)
+ paths.map { |p| File.read(p) }
+end
+
+def nested_read(dirs)
+ dirs.each do |d|
+ Dir.glob(File.join(d, "*")).each do |f|
+ File.read(f)
+ end
+ end
+end
+
+def orders_report(ids)
+ ids.each do |id|
+ Order.where(id: id)
+ end
+end
+
+def constant_bound
+ 3.times do
+ File.read("config.txt")
+ end
+ [1, 2].each do |i|
+ File.read("f#{i}")
+ end
+end
+
+def build_report(lines)
+ out = ""
+ lines.each do |line|
+ out += "row: #{line}\n"
+ buf = +""
+ buf << line
+ end
+ out
+end
+
+def bounded_concat(lines)
+ lines.each do |line|
+ msg = "start"
+ msg += " more"
+ emit(msg)
+ end
+end
+
+def regex_scan(rows, pattern)
+ hoisted = Regexp.new(pattern)
+ rows.each do |row|
+ re = Regexp.new(pattern)
+ re.match?(row) && hoisted.match?(row)
+ end
+end
+
+def fresh_clients(hosts)
+ hosts.each do |h|
+ conn = Faraday.new(url: h)
+ conn.get("/health")
+ end
+end
+
+def shell_out(names)
+ names.each do |n|
+ `grep #{n} data.txt`
+ end
+end
+
+def locked_write(mutex, items)
+ items.each do |it|
+ mutex.synchronize do
+ File.write("log.txt", it)
+ end
+ end
+end
+
+def helper_calls(items)
+ items.each { |i| transform(i) }
+end
diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.py
index 2c7004550..7c02ec54c 100644
--- a/tests/unit/health/test_complexity_walker.py
+++ b/tests/unit/health/test_complexity_walker.py
@@ -477,3 +477,83 @@ def test_scala_assertion_blocks():
assert many.assertion_blocks[0][2] == 5
few = _find(results, "testFewAsserts")
assert few is not None and few.assertion_blocks == []
+
+
+def test_ruby_nesting_and_ccn():
+ results = _walk("ruby/nested.rb", "ruby")
+ deep = _find(results, "deeply_nested")
+ assert deep is not None
+ # if > while > if > if — keyword tokens must not double-count.
+ assert deep.ccn == 5, f"expected CCN 5, got {deep.ccn}"
+ assert deep.max_nesting == 4, f"expected nesting 4, got {deep.max_nesting}"
+ many = _find(results, "many_branches")
+ assert many is not None
+ # modifier-if + if + 2 elsif + && + || over the base path; elsif chains
+ # and the one-line modifier stay flat.
+ assert many.ccn == 7, f"expected CCN 7, got {many.ccn}"
+ assert many.max_nesting == 1, f"expected nesting 1, got {many.max_nesting}"
+ wordy = _find(results, "wordy")
+ assert wordy is not None and wordy.ccn == 3 # ``and`` / ``or`` count too
+ shallow = _find(results, "shallow")
+ assert shallow is not None and shallow.max_nesting == 0
+ assert shallow.param_count == 1
+ mods = _find(results, "modifier_loops")
+ assert mods is not None
+ assert mods.ccn == 3 # until_modifier + while_modifier
+ assert mods.max_nesting == 0 # one-line modifiers are flat
+
+
+def test_ruby_blocks_are_not_closures():
+ # ``.each do … end`` / ``.map { … }`` bodies roll up into the method:
+ # no nesting, no extra entries — the block-heavy-code decision.
+ results = _walk("ruby/nested.rb", "ruby")
+ blocky = _find(results, "block_heavy")
+ assert blocky is not None
+ assert blocky.ccn == 1 and blocky.max_nesting == 0
+ assert not any("anonymous" in r.name for r in results)
+
+
+def test_ruby_case_and_rescue():
+ results = _walk("ruby/nested.rb", "ruby")
+ flat = _find(results, "flat_case")
+ assert flat is not None
+ # A flat case counts once for the dispatch, not per ``when`` arm.
+ assert flat.ccn == 2, f"expected CCN 2, got {flat.ccn}"
+ heavy = _find(results, "heavy_case")
+ assert heavy is not None
+ # 3 when arms + the nested if.
+ assert heavy.ccn == 5, f"expected CCN 5, got {heavy.ccn}"
+ pat = _find(results, "pattern_match")
+ assert pat is not None
+ assert pat.ccn == 2, f"expected CCN 2, got {pat.ccn}" # flat case/in
+ risky = _find(results, "risky_io")
+ assert risky is not None
+ assert risky.ccn == 3, f"expected CCN 3, got {risky.ccn}" # 2 rescue arms
+ implicit = _find(results, "implicit_rescue")
+ assert implicit is not None
+ assert implicit.ccn == 2 # method-level rescue counts like a catch
+
+
+def test_ruby_class_metrics_and_lcom4_no_signal():
+ classes = _walk_classes("ruby/classes.rb", "ruby")
+ cohesive = classes.get("Cohesive")
+ splintered = classes.get("Splintered")
+ assert cohesive is not None and splintered is not None
+ assert splintered.method_count == 5
+ assert splintered.max_method_ccn == 2
+ # LCOM4 sits at the "no signal" valve for Ruby (receiver-less @ivar
+ # idiom): even a splintered class must NOT read as low-cohesion.
+ assert cohesive.lcom4 == 1
+ assert splintered.lcom4 == 1
+ util = classes.get("Util")
+ assert util is not None and util.method_count == 2 # def + def self.
+
+
+def test_ruby_assertion_blocks():
+ results = _walk("ruby/assertions.rb", "ruby")
+ many = _find(results, "test_many_asserts")
+ 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, "test_few_asserts")
+ 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 6cff9030a..ff5581aad 100644
--- a/tests/unit/health/test_perf_dialects.py
+++ b/tests/unit/health/test_perf_dialects.py
@@ -724,3 +724,127 @@ def test_scala_same_collection_nested_loop_fact():
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)
+
+
+# ---------------------------------------------------------------------------
+# Ruby
+# ---------------------------------------------------------------------------
+
+
+def test_ruby_fixture_counts():
+ fc = _walk("ruby/perf_io_in_loop.rb", "ruby")
+ counts = _kinds(fc.perf_hits)
+ # Net::HTTP.get + File.read (map) + Dir.glob + nested File.read +
+ # Order.where + conn.get (require-gated Faraday) + backticks + File.write.
+ assert counts["io_in_loop"] == 8
+ assert {h.detail for h in fc.perf_hits if h.kind == "io_in_loop"} == {
+ "network",
+ "filesystem",
+ "db",
+ "subprocess",
+ }
+ assert counts["nested_loop_with_io"] == 1
+ # In-loop Regexp.new fires; the hoisted one stays quiet.
+ assert counts["regex_compile_in_loop"] == 1
+ # ``out += "<lit>"`` fires; ``buf << line`` and the reset-per-iteration
+ # accumulator do not.
+ assert counts["string_concat_in_loop"] == 1
+ assert counts["resource_construction_in_loop"] == 1
+ assert counts["lock_in_loop"] == 1
+ assert counts["blocking_io_under_lock"] == 1
+ # The constant-bound 3.times / [1, 2].each loops contribute nothing.
+
+
+_RUBY_CASES = [
+ (
+ "def m(ids)\n ids.each do |id|\n Order.where(id: id)\n end\nend\n",
+ [("io_in_loop", "db")],
+ "AR .where on a constant receiver inside .each (the canonical N+1)",
+ ),
+ (
+ "def m(users)\n users.each do |u|\n u.posts.find_by(name: u.name)\n end\nend\n",
+ [("io_in_loop", "db")],
+ "distinctive find_by fires ungated on any member call",
+ ),
+ (
+ "def m(ids, repo)\n ids.each do |id|\n repo.find(id)\n end\nend\n",
+ [],
+ "ambiguous find() with NO db require is gated out",
+ ),
+ (
+ 'require "active_record"\n'
+ "def m(ids, repo)\n ids.each do |id|\n repo.find(id)\n end\nend\n",
+ [("io_in_loop", "db")],
+ "ambiguous find() WITH a db require passes the file-level gate",
+ ),
+ (
+ "def m(paths)\n paths.each do |p|\n get p\n end\nend\n",
+ [],
+ "bare get (Sinatra route DSL shape) is not a network sink",
+ ),
+ (
+ 'require "faraday"\n'
+ "def m(conn, urls)\n urls.each do |u|\n conn.get(u)\n end\nend\n",
+ [("io_in_loop", "network")],
+ "instance client verb WITH a network require",
+ ),
+ (
+ "def m(conn, urls)\n urls.each do |u|\n conn.get(u)\n end\nend\n",
+ [],
+ "instance client verb with NO network require is gated out",
+ ),
+ (
+ "def m(queue)\n loop do\n File.read(queue.pop)\n end\nend\n",
+ [("io_in_loop", "filesystem")],
+ "loop do ... end is an unconditional-repeat loop scope",
+ ),
+ (
+ "def m\n 3.times do\n File.read(\"x\")\n end\nend\n",
+ [],
+ "literal-receiver .times is a constant-bound loop",
+ ),
+ (
+ "def m(items)\n items.map(&:to_s)\n File.read(items.first.path)\nend\n",
+ [],
+ "a combinator WITHOUT an inline block is not a loop scope",
+ ),
+ (
+ "def m(rows)\n rows.each do |r|\n transform(r)\n end\nend\n",
+ [],
+ "a loop-nested plain helper call is not a sink",
+ ),
+]
+
+
[email protected]("src,expected,note", _RUBY_CASES, ids=[c[2] for c in _RUBY_CASES])
+def test_ruby_cases(src, expected, note):
+ assert _hits("ruby", src) == sorted(expected), note
+
+
+def test_ruby_backticks_are_subprocess():
+ src = "def m(names)\n names.each do |n|\n `grep #{n} log.txt`\n end\nend\n"
+ assert _hits("ruby", src) == [("io_in_loop", "subprocess")]
+
+
+def test_ruby_receiver_runs_once():
+ # The receiver chain of an iteration call runs ONCE — only the block body
+ # is per-iteration. ``Order.where(...)`` here must not be io_in_loop.
+ src = "def m\n Order.where(active: true).each do |o|\n transform(o)\n end\nend\n"
+ assert _hits("ruby", src) == []
+
+
+def test_ruby_same_collection_nested_block_loops_fact():
+ # Two nested .each blocks over the SAME collection record the
+ # centrality-gated ``nested_loop_quadratic`` fact (not a raw hit).
+ src = (
+ "def m(items)\n"
+ " items.each do |a|\n"
+ " items.each do |b|\n"
+ " combine(a, b)\n"
+ " end\n"
+ " end\n"
+ "end\n"
+ )
+ fc = walk_file("t.rb", "ruby", 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)