GitNexus/gitnexus/test/integration/resolvers/ruby.test.ts
Gergő Magyar 741a226ab8 feat: Phase 6 type resolution — for-loop Tier 1c, pattern matching, container descriptors, 10-language coverage (#318)
* feat: Phase 6 type resolution — pattern matching, for-loop Tier 1c, coverage completion

- Add patternBindingNodeTypes gate to LanguageTypeConfig for 50% perf improvement
- Expand ForLoopExtractor signature with optional declarationTypeNodes + scope
- Add extractElementTypeFromString shared utility for container type parsing
- Python match/case: extractPatternBinding for `case User() as u:` pattern
- C# refactor: move is_pattern_expression from extractDeclaration to extractPatternBinding
- Ruby: add extractPendingAssignment for assignment chain propagation
- TS/JS: add for-loop Tier 1c for `for (const user of users)` with User[] inference
- Python: add for-loop Tier 1c for `for user in users:` with type annotation inference
- Go: add for-loop Tier 1c for `for _, user := range users` with []User inference
- Fix 'Property' as any stale cast in call-processor.ts
- Add dual return-type string length cap (2048 pre-cap, 512 post-cap)
- Add chain call integration tests for C#, Go, Rust, Python, JS, C++
- Add Python match/case integration test fixtures
- 27 new extractElementTypeFromString unit tests
- 3 for-loop edge cases skipped (declarationTypeNodes scope key lookup)

* fix: address code review findings for Phase 6

- Add missing patternBindingNodeTypes to C# typeConfig (perf gate)
- Add 2048-char input length guard to extractElementTypeFromString
- Skip Python match/case integration tests (call extraction needs query updates)

* reorganise

* fix: Phase 1 bug fixes — Go range semantics, typed_parameter, bracket depth

- Go single-var range correctly returns early for slices/maps (index, not element)
- Go single-var range on channels correctly resolves element type
- Added map_type and channel_type to extractGoElementTypeFromTypeNode
- Added isChannelType helper for channel detection before skip decision
- Added 'typed_parameter' to TYPED_PARAMETER_TYPES for Python annotated params
- Fixed bracket depth tracking in extractElementTypeFromString — only match
  selected closeChar at depth 0, return undefined for mismatched brackets
- Un-skipped 3 prematurely skipped tests (TS local const, Python List/Sequence)
- Added tests for map range, single-var range semantics, bracket edge cases

* refactor: Phase 2 architecture — shared helper, required params, decoupled type nodes

- Extract resolveIterableElementType shared helper in shared.ts implementing
  3-strategy fallback (declarationTypeNodes → scopeEnv string → AST walk)
- Refactor TS, Python, Go extractors to use shared helper (eliminates 3x duplication)
- Make ForLoopExtractor params required (aligned with PatternBindingExtractor)
- Update Java, Kotlin, C# extractor signatures to accept required params
- Decouple declarationTypeNodes from scopeEnv — capture raw type annotation
  nodes BEFORE extractDeclaration for container types (User[], []User, List[User])
- Hybrid approach: direct name extraction + keysBefore fallback for multi-declarator
- Document declarationTypeNodes invariant change (superset of scopeEnv)

* feat: Phase 3 partial — Rust for-loop + C# var foreach Tier 1c

- Rust: add extractForLoopBinding with for_expression support
  - Handles &users, &mut users via reference_expression unwrapping
  - extractRustElementTypeFromTypeNode: generic_type, reference_type, slice/array
  - findRustParamElementType: AST walk with reference/mut pattern unwrapping
  - 4 unit tests (Vec<User>, &[User], range expr negative, no-annotation negative)

- C#: upgrade foreach to handle var (implicit_type) via Tier 1c
  - extractCSharpElementTypeFromTypeNode: generic_name, array_type, nullable_type
  - findCSharpParamElementType: AST walk to method_declaration parameters
  - 3 unit tests (var foreach, explicit type regression, no-annotation negative)

* feat: Phase 3 complete — all language gaps + pattern matching

Kotlin Tier 1c:
- Unannotated for-loop resolves via shared helper
- extractKotlinElementTypeFromTypeNode handles type_projection unwrapping
- findKotlinParamElementType walks to function_declaration

Java Tier 1c:
- var foreach resolves via shared helper
- extractJavaElementTypeFromTypeNode handles generic_type, array_type
- findJavaParamElementType walks to method_declaration

TypeScript:
- readonly User[] unwrapped via readonly_type → array_type recursion

C# switch patterns:
- declaration_pattern added to patternBindingNodeTypes
- extractPatternBinding handles standalone declaration_pattern (switch case/expr)

Rust match arms:
- match_arm added to patternBindingNodeTypes
- extractPatternBinding extended with match_arm → match_expression parent traversal

Python:
- as_pattern tries childForFieldName('alias') before positional fallback

Tests: 237 pass (was 224), 13 new tests added

* feat: Phase 4 — known limitation tests, match arm fix, final verification

- Fix Rust match_arm pattern extraction: unwrap match_pattern to get
  tuple_struct_pattern inside (tree-sitter-rust wraps in match_pattern node)
- Add first-writer-wins regression test for match arm scope leakage
- Add 5 documented skip tests for known limitations:
  - TS destructured for-of (tuple destructuring)
  - Python tuple unpacking in for-loops
  - TS instanceof narrowing (block-level scoping)
  - Rust for with .iter() (method call iterable)
  - Ruby block parameters (closure param inference)

Final: 238 passed, 5 skipped (documented limitations), tsc clean

* test: integration tests for all Phase 6 language gaps + fix Rust param pattern field

Integration test fixtures and tests (30 new tests, all with exact match + negative):

Rust for-loop (5 tests):
- for user in &users with Vec<User> → User#save, negative Repo#save
- for repo in &repos with Vec<Repo> → Repo#save, negative User#save

Rust match arm (5 tests):
- match opt { Some(user) => user.save() } → User#save, negative Repo#save
- if let Ok(repo) = res → Repo#save, negative User#save

C# var foreach (5 tests):
- foreach (var user in users) with List<User> → User#Save, negative Repo#Save
- foreach (var repo in repos) with List<Repo> → Repo#Save

C# switch pattern (4 tests):
- is User user → User#Save, case Repo repo → Repo#Save

Kotlin unannotated for (4 tests):
- for (user in users) with List<User> → user.save, negative repo.save

Go map range (3 tests):
- for _, user := range userMap with map[string]User → User#Save, negative

TypeScript readonly (4 tests):
- for (const user of users) with readonly User[] → user.save, negative

Bug fix: type-env.ts parameter branch now falls back to childForFieldName('pattern')
for Rust parameters (Rust uses 'pattern' not 'name' for parameter names)

* test: add assertion bodies to known limitation skip tests

Convert empty skip test stubs to proper tests with parse/buildTypeEnv/expect
assertions following the codebase convention (e.g., call-processor.test.ts:319).
Each skip test now documents the exact expected behavior, so removing .skip
will cause a meaningful failure when the limitation is eventually fixed.

Also clarify Python integration skip tests as call-extraction issues (not
type-env) and Swift integration skips as build-dep issues (self/super
resolution code already exists in type-env.ts).

* feat: resolve 4 known limitation skip tests + method-aware type arg selection

Unskip 4 of 5 type-env known limitations with full integration test coverage:

1. TS destructured for-of: handle array_pattern by binding last named child
   to element type. Fix Map<K,V> to return last generic arg (value type).
2. Python dict.items() loop: handle `call` iterables + `pattern_list` left
   side. Fix dict[K,V] extraction via type_parameter with last-arg heuristic.
   Unwrap `type` wrapper in extractPyElementTypeFromAnnotation.
3. TS instanceof narrowing: add extractPatternBinding for binary_expression
   with positional child access. First-writer-wins (not block-scoped).
4. Rust .iter() for-loops: handle call_expression in for_expression value
   node by extracting receiver from field_expression.

Method-aware type arg resolution:
- Add TypeArgPosition ('first'|'last') to resolveIterableElementType
- .keys()/.keySet()/.Keys → first type arg (key); all else → last (value)
- Thread position through all 3 strategy callbacks in TS/Rust/Python
- Add predefined_type to extractSimpleTypeName for TS primitives (string etc)

New fixtures: rust-iter-for-loop, typescript-destructured-for-of,
typescript-instanceof-narrowing, python-dict-items-loop.
248 unit tests pass (6 new), 1 skip (Ruby block params).

* feat: container descriptor table for generic type arg resolution

Replace simple KEY_METHODS heuristic with CONTAINER_DESCRIPTORS table
that maps 30+ container types across all languages to their type parameter
semantics per access method.

Key improvements:
- Container-aware resolution: HashMap.iter() correctly yields V (arity 2),
  while Vec.iter() yields T (arity 1) — same method, different semantics
- Cross-language coverage: Map/HashMap/BTreeMap/dict/Dict/Dictionary/
  ConcurrentHashMap + List/Vec/Set/HashSet/Queue/Deque/Stack etc.
- Method categorization: keyMethods (keys/keySet/Keys) vs valueMethods
  (values/get/pop/iter/first/last) per container type
- Fallback for unknown containers: still uses method name heuristic,
  so MyCache<K,V>.keys() correctly returns first arg
- Exported getContainerDescriptor() for future heritage-chain lookups

Each language extractor now passes containerTypeName from scopeEnv to
methodToTypeArgPosition for descriptor-aware resolution.

252 unit tests pass (4 new descriptor tests), 1 skip (Ruby).

* feat: method-aware for-loop extractors + integration tests for all languages

Upgrade 4 existing extractors + create 3 new ones for full cross-language
coverage of call_expression iterables and container descriptor resolution:

Upgraded (add call expr iterable + methodToTypeArgPosition):
- Java: method_invocation (data.keySet(), data.values())
- Kotlin: navigation_expression + call_expression (data.keys, data.values())
- C#: member_access_expression + invocation_expression (data.Keys, data.Values)
- Go: TypeArgPosition threading for Go 1.18+ generics

New for-loop extractors:
- C++: for_range_loop with auto& unwrapping, template_type + qualified_identifier
  (std::vector<User>) extraction, explicit vs auto type handling
- PHP: foreach_statement with simple/key-value/by-reference forms, PHPDoc
  @param priority over AST array type
- Ruby: for-in with YARD @param type resolution via comment parsing

Integration test fixtures + tests for all 6 languages:
- java-map-keys-values (Map.values() + List iteration)
- kotlin-map-keys-values (HashMap.values + List iteration)
- csharp-dictionary-keys-values (Dictionary.Values foreach)
- cpp-range-for (auto& + const auto& range-based for)
- php-foreach-loop (foreach with PHPDoc @param User[])
- ruby-for-in-loop (for-in with YARD @param Array<User>)

Bugs fixed during integration testing:
- C++: qualified_identifier (std::vector) not unwrapped to template_type
- PHP: extractParameter overwrote PHPDoc-derived types with bare 'array'

252 unit tests pass, 201 integration tests pass across 6 languages.

* fix: update extractElementTypeFromString tests for last-arg default

TypeArgPosition change (default 'last') broke 5 existing tests expecting
first arg from multi-arg generics. Updated expectations and added explicit
pos='first' tests for key type extraction.

* fix: rename C++ fixture files to correct case for case-sensitive CI

On case-sensitive filesystems (Linux/macOS CI), git tracked both the old
lowercase files (app.cpp, user.h) and the new uppercase files (App.cpp,
User.h) as separate files. The pipeline processed both, causing the old
app.cpp (with explicit User& type) to interfere with the new auto& test.

Removes old lowercase entries and re-adds with uppercase casing to match
the #include directives in the fixture.

* feat: PR #318 review findings — pattern bindings, member access iterables, structured bindings

Address all 7 genuine gaps identified in PR #318 deep code review:

- Kotlin: add extractKotlinPatternBinding for when/is (type_test AST node)
  with allowPatternBindingOverwrite for smart-cast semantics
- Java: add type_pattern branch for Java 17+ switch pattern variables
- TypeScript: explicit object_pattern skip in for-of (no false bindings)
- Cross-language: member access iterables (self.users, this.users, repo.users)
  across all 10 language extractors
- C++: structured_binding_declarator handling in range-for (last-child heuristic)
- Rust: closure_parameter added to TYPED_PARAMETER_TYPES
- PHP: normalizePhpType handles angle-bracket generics (Collection<User>)

Code review fixes applied:
- Remove 4 debug console.log statements (c-cpp.ts, call-processor.ts)
- Hoist KNOWN_CONTAINER_PROPS to module scope (csharp.ts)
- Guard keysBefore allocation behind typeNode check (type-env.ts)
- Add depth limits (50) to 7 recursive type extraction functions
- Add 2048-char length cap to extractSimpleTypeName
- Fix PHP/Ruby missing typeArgPos parameter in resolveIterableElementType

Integration test fixtures: kotlin-when-pattern, java-switch-pattern,
cpp-structured-binding, typescript-member-access-for-loop,
python-member-access-for-loop

* fix: position-indexed when/is bindings, Kotlin param extraction, HashMap.values for-loop

Three root causes for failing Kotlin integration tests:

1. When/is multi-arm resolution: flat scopeEnv stored only the last arm's
   type (last-writer-wins). Added PatternOverrides with AST range indexing
   so each when arm resolves to its narrowed type independently.

2. HashMap.values for-loop: navigation_expression without call_suffix was
   classified as bare property access (iterableName='values' instead of
   'data'). Now tries object-as-iterable + property-as-method first, with
   fallback to property-as-iterable for this.users patterns.

3. Kotlin parameter extraction: tree-sitter-kotlin parameter nodes use
   positional children (simple_identifier, user_type) not named fields
   (name, type). Added fallback to findChildByType in both
   extractKotlinParameter and extractTypeBinding.

Integration tests added for .keys/.values/Set/MutableMap iteration,
3-arm when/is, multi-call within arms, and when+else branch.

* feat: enhance PHP type resolution for generics and member access in foreach loops

* feat: Phase 6.1 type resolution gap closure — container descriptors, recursive_pattern, class fields

Add 13 missing container type descriptors (Collection, MutableMap, Stream, SortedSet, etc.)
to CONTAINER_DESCRIPTORS for correct element type extraction across C#, Kotlin, and Java.

Extend C# pattern binding to handle recursive_pattern (obj is User { Name: "Alice" } u)
in both is-expression and switch expression contexts.

Add TypeScript class field declaration support (public_field_definition) so for-loop
iteration over this.fieldName resolves element types from class field type annotations.
Includes file-scope fallback in resolveIterableElementType and nested member_expression
handling for this.field.method() patterns.

* docs: add type resolution system documentation with roadmap

Covers the full architecture, resolution tiers (0-2), scope model,
language feature matrix, container descriptors, pipeline integration,
and the Phase 7-9 roadmap for cross-scope propagation, field-type
resolution, and return-type-aware binding.

* feat: Phase 6.2 review findings — C# nested member foreach, C++ deref range-for, Java field_access

Close two gaps found during fourth-pass review of PR #318:

- C# foreach (var user in this.data.Values): nested member_access_expression
  now extracts intermediate property name for scopeEnv lookup
- C++ for (auto& user : *ptr): pointer_expression dereference now recognized
  as range-for iterable

Root causes fixed in shared infrastructure:
- extractSimpleTypeName: add template_type (C++) and generic_name (C#)
- extractGenericTypeArgs: add generic_name for consistency
- type-env.ts: unwrap variable_declaration wrapper in field_declaration
  for declarationTypeNodes capture (zero-allocation manual loop)

Additional review findings addressed:
- Java: add field_access handler for this.data.values() in method_invocation
- C++ pointer_expression: document limitation (*identifier only)
- TypeScript: fix stale comment about property_identifier

All 525 tests pass (278 unit + 247 integration).

* perf: optimize type resolution pipeline — worker threshold, skip graph phases, AST pruning

- Skip worker pool creation for small repos (<15 files or <512KB) — saves 100-400ms
- Add skipGraphPhases option to runPipelineFromRepo to skip MRO/community/process phases
- Add conservative SKIP_SUBTREE_TYPES for leaf-only AST nodes (string, comment, number)
- Pre-compute interestingNodeTypes set — single Set.has() replaces 3 checks per node
- Add fastStripNullable — skip full stripNullable for simple identifiers (90%+ case)
- Replace .children?.find() with manual for loops in extractFunctionName (no array alloc)
- Add hookTimeout: 120000 to vitest.config.ts for CI beforeAll hooks

* fix: review findings — remove template_string from SKIP_SUBTREE_TYPES, handle bare nullable keywords

- Remove template_string and concatenated_string from SKIP_SUBTREE_TYPES
  (template literals contain interpolated expressions with typed code)
- Add FAST_NULLABLE_KEYWORDS check to fastStripNullable for behavioral
  parity with stripNullable on bare null/undefined/void/None/nil
- Add explanatory comment on extractPendingAssignment scopeEnv guard

* feat: add type resolution system and roadmap documentation
2026-03-17 17:10:22 +00:00

848 lines
32 KiB
TypeScript

/**
* Ruby: require_relative imports, include heritage (mixins), attr_* properties,
* calls, member calls, ambiguous disambiguation, local shadow,
* constructor-inferred type resolution
*/
import { describe, it, expect, beforeAll } from 'vitest';
import path from 'path';
import {
FIXTURES, getRelationships, getNodesByLabel, edgeSet,
runPipelineFromRepo, type PipelineResult,
} from './helpers.js';
// ---------------------------------------------------------------------------
// Heritage: require_relative imports + include heritage + attr_* properties + calls
// ---------------------------------------------------------------------------
describe('Ruby require_relative, heritage & property resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-app'),
() => {},
);
}, 60000);
// --- Node detection ---
it('detects 3 classes', () => {
expect(getNodesByLabel(result, 'Class')).toEqual([
'BaseModel', 'User', 'UserService',
]);
});
it('detects 3 modules', () => {
expect(getNodesByLabel(result, 'Module')).toEqual(['Cacheable', 'Loggable', 'Serializable']);
});
it('detects methods on classes and modules', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('persist');
expect(methods).toContain('run_validations');
expect(methods).toContain('greet_user');
expect(methods).toContain('serialize_data');
expect(methods).toContain('create_user');
});
it('detects singleton method (def self.factory) as Method', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('factory');
});
it('emits CALLS from singleton method: factory → run_validations', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'factory' && e.target === 'run_validations');
expect(calls.length).toBe(1);
expect(calls[0].sourceLabel).toBe('Method');
});
// --- Import resolution via require_relative ---
it('resolves 5 require_relative imports to IMPORTS edges', () => {
const imports = getRelationships(result, 'IMPORTS');
const importEdges = edgeSet(imports);
expect(importEdges).toContain('user.rb → base_model.rb');
expect(importEdges).toContain('user.rb → serializable.rb');
expect(importEdges).toContain('user.rb → loggable.rb');
expect(importEdges).toContain('user.rb → cacheable.rb');
expect(importEdges).toContain('service.rb → user.rb');
});
it('resolves bare require to IMPORTS edge', () => {
const imports = getRelationships(result, 'IMPORTS');
const bareRequire = imports.find(e =>
e.sourceFilePath.includes('base_model.rb') &&
e.targetFilePath.includes('serializable.rb')
);
expect(bareRequire).toBeDefined();
});
// --- Heritage: include → IMPLEMENTS ---
it('emits IMPLEMENTS edge for include Serializable with reason "include"', () => {
const implements_ = getRelationships(result, 'IMPLEMENTS');
const edge = implements_.find(e => e.source === 'User' && e.target === 'Serializable');
expect(edge).toBeDefined();
expect(edge!.rel.reason).toBe('include');
});
it('emits IMPLEMENTS edge for extend Loggable with reason "extend"', () => {
const implements_ = getRelationships(result, 'IMPLEMENTS');
const edge = implements_.find(e => e.source === 'User' && e.target === 'Loggable');
expect(edge).toBeDefined();
expect(edge!.rel.reason).toBe('extend');
});
it('emits IMPLEMENTS edge for prepend Cacheable with reason "prepend"', () => {
const implements_ = getRelationships(result, 'IMPLEMENTS');
const edge = implements_.find(e => e.source === 'User' && e.target === 'Cacheable');
expect(edge).toBeDefined();
expect(edge!.rel.reason).toBe('prepend');
});
// --- Extends: class inheritance ---
it('emits EXTENDS edge: User → BaseModel', () => {
const extends_ = getRelationships(result, 'EXTENDS');
expect(extends_.length).toBeGreaterThanOrEqual(1);
const edges = edgeSet(extends_);
expect(edges).toContain('User → BaseModel');
});
// --- Property nodes: attr_accessor, attr_reader, attr_writer ---
it('creates Property nodes for attr_accessor :id and :created_at', () => {
const props = getNodesByLabel(result, 'Property');
expect(props).toContain('id');
expect(props).toContain('created_at');
});
it('creates Property nodes for attr_reader :name and attr_writer :email', () => {
const props = getNodesByLabel(result, 'Property');
expect(props).toContain('name');
expect(props).toContain('email');
});
it('emits HAS_METHOD from User to attr_reader :name', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const edge = hasMethod.find(e => e.source === 'User' && e.target === 'name');
expect(edge).toBeDefined();
});
it('emits HAS_METHOD from BaseModel to attr_accessor :id', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const edge = hasMethod.find(e => e.source === 'BaseModel' && e.target === 'id');
expect(edge).toBeDefined();
});
// --- Call resolution: method-level attribution ---
it('emits method-level CALLS: create_user → persist (member call)', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'create_user' && e.target === 'persist');
expect(calls.length).toBe(1);
expect(calls[0].sourceLabel).toBe('Method');
expect(calls[0].targetLabel).toBe('Method');
});
it('emits method-level CALLS: create_user → greet_user (member call)', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'create_user' && e.target === 'greet_user');
expect(calls.length).toBe(1);
expect(calls[0].sourceLabel).toBe('Method');
expect(calls[0].targetLabel).toBe('Method');
});
it('emits method-level CALLS: greet_user → persist (bare call)', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'greet_user' && e.target === 'persist');
expect(calls.length).toBe(1);
});
it('emits method-level CALLS: greet_user → serialize_data (bare call)', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'greet_user' && e.target === 'serialize_data');
expect(calls.length).toBe(1);
});
it('emits method-level CALLS: persist → run_validations (bare call)', () => {
const calls = getRelationships(result, 'CALLS')
.filter(e => e.source === 'persist' && e.target === 'run_validations');
expect(calls.length).toBe(1);
});
// --- Heritage edges point to real graph nodes ---
it('all heritage edges point to real graph nodes', () => {
for (const edge of [...getRelationships(result, 'EXTENDS'), ...getRelationships(result, 'IMPLEMENTS')]) {
const target = result.graph.getNode(edge.rel.targetId);
expect(target).toBeDefined();
}
});
// --- No OVERRIDES edges target Property nodes ---
it('no OVERRIDES edges target Property nodes', () => {
const overrides = getRelationships(result, 'OVERRIDES');
for (const edge of overrides) {
const target = result.graph.getNode(edge.rel.targetId);
expect(target).toBeDefined();
expect(target!.label).not.toBe('Property');
}
});
});
// ---------------------------------------------------------------------------
// Calls: arity-based disambiguation
// ---------------------------------------------------------------------------
describe('Ruby call resolution with arity filtering', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-calls'),
() => {},
);
}, 60000);
it('resolves run_task → write_audit to one_arg.rb via arity narrowing', () => {
const calls = getRelationships(result, 'CALLS');
const auditCall = calls.find(c => c.target === 'write_audit');
expect(auditCall).toBeDefined();
expect(auditCall!.source).toBe('run_task');
expect(auditCall!.targetFilePath).toContain('one_arg.rb');
expect(auditCall!.rel.reason).toBe('import-resolved');
});
});
// ---------------------------------------------------------------------------
// Member-call resolution: obj.method() resolves through pipeline
// ---------------------------------------------------------------------------
describe('Ruby member-call resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-member-calls'),
() => {},
);
}, 60000);
it('resolves process_user → persist_record as a member call on User', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c => c.target === 'persist_record');
expect(saveCall).toBeDefined();
expect(saveCall!.source).toBe('process_user');
expect(saveCall!.targetFilePath).toContain('user.rb');
});
it('detects User class and persist_record method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Method')).toContain('persist_record');
});
it('emits HAS_METHOD edge from User to persist_record', () => {
const hasMethod = getRelationships(result, 'HAS_METHOD');
const edge = hasMethod.find(e => e.source === 'User' && e.target === 'persist_record');
expect(edge).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Ambiguous: Handler in two dirs, require_relative disambiguates
// ---------------------------------------------------------------------------
describe('Ruby ambiguous symbol resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-ambiguous'),
() => {},
);
}, 60000);
it('detects 2 Handler classes', () => {
const classes = getNodesByLabel(result, 'Class');
expect(classes.filter(n => n === 'Handler').length).toBe(2);
expect(classes).toContain('UserHandler');
});
it('resolves EXTENDS to models/handler.rb (not other/handler.rb)', () => {
const extends_ = getRelationships(result, 'EXTENDS');
expect(extends_.length).toBe(1);
expect(extends_[0].source).toBe('UserHandler');
expect(extends_[0].target).toBe('Handler');
expect(extends_[0].targetFilePath).toBe('models/handler.rb');
});
it('import edge points to models/ not other/', () => {
const imports = getRelationships(result, 'IMPORTS');
expect(imports.length).toBe(1);
expect(imports[0].targetFilePath).toBe('models/handler.rb');
});
it('all heritage edges point to real graph nodes', () => {
for (const edge of getRelationships(result, 'EXTENDS')) {
const target = result.graph.getNode(edge.rel.targetId);
expect(target).toBeDefined();
}
});
});
// ---------------------------------------------------------------------------
// Local shadow: same-file definition takes priority over imported name
// ---------------------------------------------------------------------------
describe('Ruby local definition shadows import', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-local-shadow'),
() => {},
);
}, 60000);
it('resolves run_app → do_work to same-file definition, not the imported one', () => {
const calls = getRelationships(result, 'CALLS');
const doWorkCall = calls.find(c => c.target === 'do_work' && c.source === 'run_app');
expect(doWorkCall).toBeDefined();
expect(doWorkCall!.targetFilePath).toContain('app.rb');
});
});
// ---------------------------------------------------------------------------
// Constructor-inferred type resolution: user = User.new; user.save → User.save
// ---------------------------------------------------------------------------
describe('Ruby constructor-inferred type resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-constructor-type-inference'),
() => {},
);
}, 60000);
it('detects User, Repo, and AppService classes', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
expect(getNodesByLabel(result, 'Class')).toContain('AppService');
});
it('detects save on User and Repo, cleanup on all three', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods.filter(m => m === 'save').length).toBe(2);
expect(methods.filter(m => m === 'cleanup').length).toBe(3);
});
it('resolves user.save to models/user.rb via constructor-inferred type', () => {
const calls = getRelationships(result, 'CALLS');
const userSave = calls.find(c => c.target === 'save' && c.targetFilePath === 'models/user.rb');
expect(userSave).toBeDefined();
expect(userSave!.source).toBe('process_entities');
});
it('resolves repo.save to models/repo.rb via constructor-inferred type', () => {
const calls = getRelationships(result, 'CALLS');
const repoSave = calls.find(c => c.target === 'save' && c.targetFilePath === 'models/repo.rb');
expect(repoSave).toBeDefined();
expect(repoSave!.source).toBe('process_entities');
});
it('emits exactly 2 save CALLS edges (one per receiver type)', () => {
const calls = getRelationships(result, 'CALLS');
const saveCalls = calls.filter(c => c.target === 'save');
expect(saveCalls.length).toBe(2);
});
it('resolves self.process_entities to services/app.rb (unique method)', () => {
const calls = getRelationships(result, 'CALLS');
const selfCall = calls.find(c =>
c.source === 'greet' && c.target === 'process_entities'
);
expect(selfCall).toBeDefined();
expect(selfCall!.targetFilePath).toContain('app.rb');
});
it('resolves self.cleanup to services/app.rb, not models/user.rb or models/repo.rb', () => {
const calls = getRelationships(result, 'CALLS');
const selfCleanup = calls.find(c =>
c.source === 'greet' && c.target === 'cleanup'
);
expect(selfCleanup).toBeDefined();
expect(selfCleanup!.targetFilePath).toContain('app.rb');
});
});
// ---------------------------------------------------------------------------
// self.save resolves to enclosing class's own save method
// ---------------------------------------------------------------------------
describe('Ruby self resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-self-this-resolution'),
() => {},
);
}, 60000);
it('detects User and Repo classes, each with a save method', () => {
expect(getNodesByLabel(result, 'Class')).toEqual(['Repo', 'User']);
const saveMethods = getNodesByLabel(result, 'Method').filter(m => m === 'save');
expect(saveMethods.length).toBe(2);
});
it('resolves self.save inside User#process to User#save, not Repo#save', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c => c.target === 'save' && c.source === 'process');
expect(saveCall).toBeDefined();
expect(saveCall!.targetFilePath).toBe('lib/models/user.rb');
});
});
// ---------------------------------------------------------------------------
// Parent class resolution: < BaseModel + include Module
// ---------------------------------------------------------------------------
describe('Ruby parent resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-parent-resolution'),
() => {},
);
}, 60000);
it('detects BaseModel and User classes plus Serializable module', () => {
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'User']);
expect(getNodesByLabel(result, 'Module')).toEqual(['Serializable']);
});
it('emits EXTENDS edge: User < BaseModel', () => {
const extends_ = getRelationships(result, 'EXTENDS');
expect(extends_.length).toBe(1);
expect(extends_[0].source).toBe('User');
expect(extends_[0].target).toBe('BaseModel');
});
it('emits IMPLEMENTS edge: User includes Serializable', () => {
const implements_ = getRelationships(result, 'IMPLEMENTS');
const includeEdge = implements_.find(e => e.source === 'User' && e.target === 'Serializable');
expect(includeEdge).toBeDefined();
expect(includeEdge!.rel.reason).toBe('include');
});
});
// ---------------------------------------------------------------------------
// Ruby super: standalone keyword calls same-named method on parent
// ---------------------------------------------------------------------------
describe('Ruby super resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-super-resolution'),
() => {},
);
}, 60000);
it('detects BaseModel, User, and Repo classes', () => {
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'Repo', 'User']);
});
it('emits EXTENDS edge: User < BaseModel', () => {
const extends_ = getRelationships(result, 'EXTENDS');
expect(extends_.length).toBe(1);
expect(extends_[0].source).toBe('User');
expect(extends_[0].target).toBe('BaseModel');
});
it('detects save methods on all three classes', () => {
const saveMethods = getNodesByLabel(result, 'Method').filter(m => m === 'save');
expect(saveMethods.length).toBe(3);
});
});
// ---------------------------------------------------------------------------
// Ruby constant constructor: SERVICE = UserService.new; SERVICE.process
// ---------------------------------------------------------------------------
describe('Ruby constant constructor binding resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-constant-constructor'),
() => {},
);
}, 60000);
it('detects UserService class with process and validate methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
expect(getNodesByLabel(result, 'Method')).toContain('process');
expect(getNodesByLabel(result, 'Method')).toContain('validate');
});
it('resolves SERVICE.process() via constant constructor binding', () => {
const calls = getRelationships(result, 'CALLS');
const processCall = calls.find(c => c.target === 'process' && c.targetFilePath === 'models.rb');
expect(processCall).toBeDefined();
});
it('resolves SERVICE.validate() via constant constructor binding', () => {
const calls = getRelationships(result, 'CALLS');
const validateCall = calls.find(c => c.target === 'validate' && c.targetFilePath === 'models.rb');
expect(validateCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// YARD annotation type resolution: @param repo [UserRepo] → repo.save resolves
// ---------------------------------------------------------------------------
describe('Ruby YARD annotation type resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-yard-annotations'),
() => {},
);
}, 60000);
it('detects UserRepo, User, and UserService classes', () => {
expect(getNodesByLabel(result, 'Class')).toContain('UserRepo');
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
});
it('detects save, find_by_name, greet, and create methods', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('save');
expect(methods).toContain('find_by_name');
expect(methods).toContain('greet');
expect(methods).toContain('create');
});
it('resolves repo.save to UserRepo#save via YARD @param annotation', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c => c.target === 'save' && c.source === 'create');
expect(saveCall).toBeDefined();
expect(saveCall!.targetFilePath).toContain('models.rb');
});
it('resolves user.greet to User#greet via YARD @param annotation', () => {
const calls = getRelationships(result, 'CALLS');
const greetCall = calls.find(c => c.target === 'greet' && c.source === 'create');
expect(greetCall).toBeDefined();
expect(greetCall!.targetFilePath).toContain('models.rb');
});
});
// ---------------------------------------------------------------------------
// Namespaced constructor: svc = Models::UserService.new; svc.process()
// Tests scope_resolution receiver handling for Ruby namespaced classes.
// ---------------------------------------------------------------------------
describe('Ruby namespaced constructor resolution (Models::UserService.new)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-namespaced-constructor'),
() => {},
);
}, 60000);
it('detects UserService class with process and validate methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('process');
expect(methods).toContain('validate');
});
it('resolves svc.process() via namespaced constructor Models::UserService.new', () => {
const calls = getRelationships(result, 'CALLS');
const processCall = calls.find(c =>
c.target === 'process' && c.targetFilePath.includes('user_service.rb')
);
expect(processCall).toBeDefined();
});
it('resolves svc.validate() via namespaced constructor Models::UserService.new', () => {
const calls = getRelationships(result, 'CALLS');
const validateCall = calls.find(c =>
c.target === 'validate' && c.targetFilePath.includes('user_service.rb')
);
expect(validateCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Return type inference: user = get_user('alice'); user.save
// Ruby's scanConstructorBinding captures assignment nodes with call RHS.
// Combined with YARD @return annotation parsing, the pipeline resolves
// `user.save` to User#save (not Repo#save) via return type disambiguation.
// The fixture has BOTH User#save and Repo#save — fuzzy matching alone
// cannot disambiguate, so return type inference must be working.
// ---------------------------------------------------------------------------
describe('Ruby return type inference via function call', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-return-type'),
() => {},
);
}, 60000);
it('detects User and Repo classes', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
});
it('detects get_user and get_repo methods', () => {
expect(getNodesByLabel(result, 'Method')).toContain('get_user');
expect(getNodesByLabel(result, 'Method')).toContain('get_repo');
});
it('detects save method on both User and Repo (disambiguation required)', () => {
const methods = getNodesByLabel(result, 'Method');
// Both classes have save — fuzzy match alone cannot resolve this
expect(methods.filter(m => m === 'save').length).toBeGreaterThanOrEqual(2);
});
it('resolves user.save to User#save via YARD @return [User] on get_user()', () => {
// With both User#save and Repo#save in scope, resolving user.save
// requires return type inference: get_user() → @return [User] → user is User
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c =>
c.target === 'save' && c.source === 'process_user' && c.targetFilePath.includes('models.rb'),
);
expect(saveCall).toBeDefined();
});
it('resolves repo.save to Repo#save via YARD @return [Repo] on get_repo()', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c =>
c.target === 'save' && c.source === 'process_repo' && c.targetFilePath.includes('repo.rb'),
);
expect(saveCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Ruby constant LHS factory call: SERVICE = build_service() with YARD @return
// Verifies that constant assignments (uppercase LHS) from plain function calls
// are captured by scanConstructorBinding, not just identifier assignments.
// ---------------------------------------------------------------------------
describe('Ruby constant factory call resolution (SERVICE = build_service())', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-constant-factory-call'),
() => {},
);
}, 60000);
it('detects UserService and AdminService classes with process and validate methods', () => {
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
expect(getNodesByLabel(result, 'Class')).toContain('AdminService');
expect(getNodesByLabel(result, 'Method')).toContain('process');
expect(getNodesByLabel(result, 'Method')).toContain('validate');
});
it('resolves SERVICE.process() to UserService#process via constant factory call', () => {
const calls = getRelationships(result, 'CALLS');
const processCall = calls.find(c =>
c.target === 'process' && c.targetFilePath.includes('user_service.rb'),
);
expect(processCall).toBeDefined();
const wrongCall = calls.find(c =>
c.target === 'process' &&
c.sourceFilePath?.includes('app.rb') &&
c.targetFilePath.includes('admin_service.rb'),
);
expect(wrongCall).toBeUndefined();
});
it('resolves SERVICE.validate() to UserService#validate via constant factory call', () => {
const calls = getRelationships(result, 'CALLS');
const validateCall = calls.find(c =>
c.target === 'validate' && c.targetFilePath.includes('user_service.rb'),
);
expect(validateCall).toBeDefined();
const wrongCall = calls.find(c =>
c.target === 'validate' &&
c.sourceFilePath?.includes('app.rb') &&
c.targetFilePath.includes('admin_service.rb'),
);
expect(wrongCall).toBeUndefined();
});
});
describe('Ruby YARD generic type annotations (Hash<Symbol, User>)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-yard-generics'),
() => {},
);
}, 60000);
it('detects UserRepo, AdminRepo, and DataService classes', () => {
expect(getNodesByLabel(result, 'Class')).toContain('UserRepo');
expect(getNodesByLabel(result, 'Class')).toContain('AdminRepo');
expect(getNodesByLabel(result, 'Class')).toContain('DataService');
});
it('detects save and find_all on both repos, plus sync and audit methods', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('save');
expect(methods).toContain('find_all');
expect(methods).toContain('sync');
expect(methods).toContain('audit');
});
it('resolves repo.save in sync() to UserRepo#save via @param repo [UserRepo]', () => {
const calls = getRelationships(result, 'CALLS');
const saveCall = calls.find(c =>
c.target === 'save' && c.source === 'sync' && c.targetFilePath.includes('models.rb'),
);
expect(saveCall).toBeDefined();
});
it('does NOT resolve cache param to a class (Hash<Symbol, UserRepo> is a generic container)', () => {
// The @param cache [Hash<Symbol, UserRepo>] should extract type "Hash" — not "UserRepo".
// Since Hash is not a class in the fixture, no type binding is created for cache.
// This verifies the bracket-balanced split doesn't break on the inner comma.
const calls = getRelationships(result, 'CALLS');
// No calls should originate from cache.* since cache has no resolved type
const cacheCall = calls.find(c =>
c.source === 'sync' && c.target === 'save' && c.targetFilePath.includes('admin'),
);
expect(cacheCall).toBeUndefined();
});
it('resolves admin_repo.save in audit() to AdminRepo#save via alternate @param [AdminRepo] order', () => {
const calls = getRelationships(result, 'CALLS');
// audit() calls admin_repo.save — should resolve via the alternate YARD format
const saveCall = calls.find(c =>
c.target === 'save' && c.source === 'audit',
);
expect(saveCall).toBeDefined();
});
it('resolves admin_repo.find_all in audit() to AdminRepo#find_all', () => {
const calls = getRelationships(result, 'CALLS');
const findCall = calls.find(c =>
c.target === 'find_all' && c.source === 'audit',
);
expect(findCall).toBeDefined();
});
});
// ---------------------------------------------------------------------------
// Chained method calls: svc.get_user.save
// Tests that Ruby's `call` node uses `method` and `receiver` fields correctly
// for chain extraction — the tree-sitter-ruby grammar differs from other languages.
// ---------------------------------------------------------------------------
describe('Ruby chained method call resolution (Phase 5 review fix)', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-chain-call'),
() => {},
);
}, 60000);
it('detects User, Repo, UserService and App classes', () => {
const classes = getNodesByLabel(result, 'Class');
expect(classes).toContain('User');
expect(classes).toContain('Repo');
expect(classes).toContain('UserService');
expect(classes).toContain('App');
});
it('detects save methods on both User and Repo', () => {
const methods = getNodesByLabel(result, 'Method');
const saveMethods = methods.filter(m => m === 'save');
expect(saveMethods.length).toBe(2);
});
it('detects get_user method on UserService', () => {
const methods = getNodesByLabel(result, 'Method');
expect(methods).toContain('get_user');
});
it('resolves svc.get_user.save to User#save via chain resolution', () => {
const calls = getRelationships(result, 'CALLS');
const userSave = calls.find(c =>
c.target === 'save' &&
c.source === 'process' &&
c.targetFilePath?.includes('user.rb'),
);
expect(userSave).toBeDefined();
});
it('does NOT resolve svc.get_user.save to Repo#save', () => {
const calls = getRelationships(result, 'CALLS');
const repoSave = calls.find(c =>
c.target === 'save' &&
c.source === 'process' &&
c.targetFilePath?.includes('repo.rb'),
);
expect(repoSave).toBeUndefined();
});
});
// ---------------------------------------------------------------------------
// Ruby for-in loop: for user in users — YARD @param resolution
// ---------------------------------------------------------------------------
describe('Ruby for-in loop resolution', () => {
let result: PipelineResult;
beforeAll(async () => {
result = await runPipelineFromRepo(
path.join(FIXTURES, 'ruby-for-in-loop'),
() => {},
);
}, 60000);
it('detects User class with save method', () => {
expect(getNodesByLabel(result, 'Class')).toContain('User');
});
it('resolves user.save in for-in to User#save', () => {
const calls = getRelationships(result, 'CALLS');
const userSave = calls.find(c =>
c.target === 'save' && c.source === 'process_users' && c.targetFilePath?.includes('user'),
);
expect(userSave).toBeDefined();
});
it('does NOT resolve user.save to Repo#save (negative)', () => {
const calls = getRelationships(result, 'CALLS');
const wrongSave = calls.find(c =>
c.target === 'save' && c.source === 'process_users' && c.targetFilePath?.includes('repo'),
);
expect(wrongSave).toBeUndefined();
});
});