mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-14 23:22:54 +00:00
* feat(csharp-scope): unit 1 — scope query + captures orchestrator First slice of the C# scope-resolution migration (issue #934, RFC #909 Ring 3). Closes `Unit 1` of docs/plans/2026-04-21-004-feat-csharp-scope-resolution-plan.md. Adds: - src/core/ingestion/languages/csharp/query.ts — tree-sitter scope query covering compilation_unit, namespace (block + file-scoped), class-like (class/interface/struct/record/enum), method-like (method/constructor/destructor/local_function/operator), property and field declarations, using directives, type bindings (parameter annotations, local variable annotations, constructor inference, invocation alias), and references (free call, member call including null-conditional, constructor call, member write). - src/core/ingestion/languages/csharp/captures.ts — pass-through orchestrator mirroring python/captures.ts. Import decomposition (Unit 2), receiver-type-binding synthesis (Unit 3), and arity metadata synthesis (Unit 5) stub out for future units. - src/core/ingestion/languages/csharp/cache-stats.ts — PROF instrumentation mirror of python/cache-stats.ts. Design notes: - Return-type / field-type / property-type captures deferred. tree-sitter-c-sharp does not expose these under a clean named field that pattern-matches. When Unit 7 parity gate surfaces a gap, add positional patterns or a post-hoc extractor lookup. - object_creation_expression with qualified_name type — the qualified name itself is the reference text; captured as a whole via a dedicated tag so interpretation in later units can split namespace + name. - Null-conditional calls use positional descendant patterns because tree-sitter-c-sharp's member_binding_expression and conditional_access_expression don't expose named fields. Coverage: - 23/23 new unit tests in test/unit/scope-resolution/csharp/csharp-captures.test.ts cover every capture tag. Confirmed against tree-sitter-c-sharp via the probe-script loop during development; grammar drift would surface as a capture-shape assertion failure. - tsc --noEmit clean. No changes to shared infrastructure. Resolver wiring + registration land in Unit 6. * fix(csharp-scope): capture null-conditional receiver + operator decls Adversarial review surfaced two Unit 1 bugs that would silently corrupt the graph once C# is flipped on the scope-resolution path: - `obj?.Save()` only emitted @reference.name, so receiver-bound resolution downgraded to the free-call fallback and could mis-link to an imported `Save`. Capture the conditional_access_expression receiver under @reference.receiver. - `operator_declaration` had @scope.function but no @declaration.method owner, so calls inside operator bodies were attributed to the enclosing class and the operator itself disappeared from method lookup. Capture the operator token as @declaration.name (downstream csharpMethodConfig normalizes to op_Addition etc.). - `conversion_operator_declaration` was missing from both scope and declaration sets. Added with the target type as the name anchor. Arity metadata for overload resolution remains deferred to Unit 5 and gated behind Unit 7's parity flip, as documented in captures.ts. * chore(scope-resolution): drop unused python/scopes.scm sibling The file was documentation-only — the authoritative scope query is the embedded `PYTHON_SCOPE_QUERY` constant in `python/query.ts`. Nothing loaded the `.scm` at runtime, so it drifted from the code. Remove it and update the four doc comments that pointed at it: - language-provider.ts: "scopes.scm query" → "scope query (embedded in each language's query.ts)". - languages/python.ts: capture-vocabulary pointer → query.ts. - python/query.ts header: drop the "edit both together" note. - python/receiver-binding.ts: "keeps the .scm declarative" → "keeps the embedded scope query declarative". - scope/walkers.ts: "Python's scopes.scm" → "Python's scope query". Historical plan docs under docs/plans/ still reference scopes.scm but are frozen artifacts, not living documentation. C# never had a .scm sibling, so no action needed there. * feat(csharp-scope): Unit 2 — import interpret + target resolver Adds the three files Unit 2 of the C# scope-resolution plan calls for: - `import-decomposer.ts` — inspects each `using_directive` node and synthesizes `@import.kind/source/name/alias` markers. Kinds: `namespace` — `using X;` / `using X.Y.Z;` `alias` — `using Alias = X.Y.Z;` (generics stripped) `static` — `using static X.Y;` `global using` maps to namespace (plan's deferred decision); the `global::` qualifier is stripped before emitting. - `interpret.ts` — reads the markers and builds `ParsedImport`. Static using maps to `kind: 'wildcard'` since it brings members into unqualified scope; Unit 4's merge-bindings tiers wildcards lowest. Also provides `interpretCsharpTypeBinding` with nullable/single-arg generic/qualifier stripping so receiver-typed resolution sees the concrete class name. - `import-target.ts` — suffix-match adapter returning a single primary file. Cross-file partial-class aggregation runs later at graph-bridge time (Unit 6). The csproj-based `resolveCSharpImportInternal` stays on the legacy path until Unit 7's parity gate surfaces a gap. - `captures.ts` routes `@import.statement` matches through the decomposer so the interpreter sees the markers it needs. Tests cover every using flavor + resolution edge cases. 38/38 scope- resolution C# unit tests pass; tsc clean. * feat(csharp-scope): Unit 3 — simple hooks (binding/import/receiver) Adds simple-hooks.ts mirroring Python's pattern: - `csharpBindingScopeFor` — delegates to innermost (block scope is already captured by @scope.block in the query). - `csharpImportOwningScope` — binds `using` inside a namespace to that namespace's scope so imports don't leak into sibling namespaces. File-level using delegates to module. Function-body using (not legal C# but possible from malformed input) attaches to the function. - `csharpReceiverBinding` — looks up `this` / `base` in the function scope's type bindings; returns null for statics, free functions, and non-Function scopes. `this` / `base` synthesis itself is deferred to a follow-up (matches Python's receiver-binding.ts pattern). 9 new tests pin delegation semantics. 47/47 C# scope-resolution unit tests pass; tsc clean. * feat(csharp-scope): Unit 4 — mergeBindings (using precedence) Three-tier shadowing, same shape as Python's LEGB merge: 0: local — class members, locals, parameters 1: using — namespace / named / reexport (equal tier; compiler requires explicit qualifier if two using collide) 2: wildcard — `using static X.Y;` static-member imports Within the surviving tier, de-dup by DefId (last-write-wins) so a re-declared `using` cleanly replaces its earlier binding. Explicit interface implementations bind under their qualified name in the extractor layer, so they don't collide with plain simple names here. 7 new tests pin precedence + dedup semantics. 54/54 C# scope-resolution unit tests pass. * feat(csharp-scope): Unit 5 — arity metadata synthesis + compatibility Adversarial review flagged overload narrowing as a blocker for the Unit 7 flip. This lands the declaration-side metadata; callsite-side arity synthesis is a separate gap we'll address if the parity gate surfaces overload misresolution. - `arity-metadata.ts` — reads `csharpMethodConfig.extractParameters` and produces `{ parameterCount, requiredParameterCount, parameterTypes }`. `params` variadic collapses parameterCount to undefined (matches Python's `*args` treatment) and appends a literal `'params'` marker to parameterTypes so the compatibility hook can detect it without re-reading the AST. Default-valued parameters contribute to optionalCount → requiredParameterCount = total − optional. - `arity.ts` — `csharpArityCompatibility(def, callsite)` returns compatible / incompatible / unknown. Mirrors Python's three-verdict shape so the central registry's arity filter works without adapter logic per-verdict. - `captures.ts` — on every @declaration.method / @declaration.constructor / @declaration.function match, synthesize @declaration.parameter-count, @declaration.required-parameter-count, and @declaration.parameter-types captures. Covers method_declaration, constructor_declaration, destructor_declaration, operator_declaration, conversion_operator_declaration, and local_function_statement. 12 new tests: 5 on captures-side synthesis (method + params + types + variadic + constructor + local function), 7 on the compatibility hook. 66/66 C# scope-resolution unit tests pass; tsc clean. * feat(csharp-scope): Unit 6 — wire csharpScopeResolver + register Creates the public barrel (index.ts) and ScopeResolver (scope-resolver.ts) and plumbs them into the provider + registry: - `languages/csharp/index.ts` — re-exports the hook entry points and documents the 8 known limitations of the registry-primary path (csproj-driven namespace resolution, multi-file namespace expansion, type-based overload resolution, nested generics, dynamic, preprocessor branches, cross-file global using, expression-bodied members). - `languages/csharp/scope-resolver.ts` — ScopeResolver shape mirroring Python's. `isSuperReceiver` matches the literal `base` keyword. `fieldFallbackOnMethodLookup: false` since C# is statically typed — the type-binding layer already produces precise owner types; `propagatesReturnTypesAcrossImports: true` since signatures are authoritative. - `languages/csharp.ts` — adds the 9 hook entry points to the provider (emitScopeCaptures, interpretImport, interpretTypeBinding, four simple hooks, mergeBindings, arityCompatibility, resolveImportTarget). - `scope-resolution/pipeline/registry.ts` — registers csharpScopeResolver alongside the Python entry. MIGRATED_LANGUAGES stays at {Python} — the resolver sits idle until Unit 7's parity gate confirms ≥99% fixture parity. 368/368 scope-resolution unit tests pass; tsc clean. * feat(csharp-scope): parity Unit 1 — this/base receiver-binding synthesis Closes 3 parity failures (51 → 48). Target bucket: Category C from the parity plan. Changes: - `languages/csharp/receiver-binding.ts` (new): walks up from a function node to the enclosing class/struct/record/interface, synthesizes `@type-binding.self` captures with boundName `'this'` (and `'base'` when the enclosing type is a class/record with an explicit base_list entry). Skips static methods and interface / struct `base` cases. Anchors to the method's `body` block so the scope-extractor's positionIndex places the binding inside the function scope (not the enclosing class scope). - `languages/csharp/captures.ts`: route `@scope.function` matches through the synth, emitting the receiver captures as separate matches. - `languages/csharp/interpret.ts`: map `@type-binding.self` to `source: 'self'` (parity with Python). - `languages/csharp/query.ts`: explicit patterns for `this.X()`, `base.X()`, and `this.X = ...` / `base.X = ...` assignment writes. `this` and `base` are anonymous tokens in tree-sitter-c-sharp so the existing `expression: (_)` pattern (named-only) didn't match. Tests: - 8 new unit tests for receiver-binding synthesis edge cases (class/struct/record/interface, static, nested, constructor, local function inside method). - Parity: 48 failed | 127 passed (175) under REGISTRY_PRIMARY_CSHARP=1; legacy path 175/175 green. * feat(csharp-scope): parity Unit 2a — foreach + pattern + field captures Closes 11 parity failures (48 → 37). Partial Unit 2 progress. Adds type-binding captures for every shape the parity suite exercises whose resolution path is in-file: - Typed foreach `foreach (User u in xs)` — @type-binding.annotation with bindingName `u` and type `User`. - Var foreach `foreach (var u in xs)` — @type-binding.alias so the generic-stripper unwraps `List<User>` / `Dictionary<K,V>.Values` to the element type at chain-follow time. Matches Python's for-loop alias pattern. - `is` pattern `if (obj is User u)` — @type-binding.annotation with scope narrowing simplified to function scope (matches Python's match-case treatment since we don't emit @scope.block). - `switch_section > declaration_pattern` (`case User u:`) — no case_pattern_switch_label wrapper in tree-sitter-c-sharp. - `recursive_pattern` (`is User { Age: 1 } u` / `case User { ... } u:`) — named binding via type+name fields on the pattern node. - Field declaration `private City _city;` — @type-binding.annotation attached to the class scope for `this._city.X` resolution. - Property declaration `public User Owner { get; set; }` — same. - Assignment rebind `alias = Factory()` / `alias = new User()` — @type-binding.alias / @type-binding.constructor so reassignment propagates type info to later receiver-typed resolution. Closed tests: foreach (3), var foreach Tier 1c (2), is-pattern (1), switch pattern (2), recursive_pattern (3). Remaining 37 include tests that need cross-file same-namespace visibility (field chains, assignment chain, cross-file return-type propagation) — deferred to Unit 5 where the IMPORTS/cross-file work lives. 74/74 scope-resolution unit tests pass; legacy path 175/175 green. * feat(csharp-scope): parity Unit 2b — same-namespace cross-file visibility Closes 3 parity failures (37 → 34). Adds the C#-specific implicit import that has no syntactic counterpart: every type declared in `namespace X` is visible to every other file also declaring `namespace X`, without any `using` directive. Changes: - `scope-resolution/contract/scope-resolver.ts` — new optional hook `populateNamespaceSiblings(parsedFiles, indexes, { fileContents })`. Most languages leave it undefined; Python / TypeScript / Java need explicit imports so there's no analogous pass. - `scope-resolution/pipeline/run.ts` — invoke the hook after `buildWorkspaceResolutionIndex` and before `propagateImportedReturnTypes` so the return-type pass sees cross-file sibling class bindings. - `languages/csharp/namespace-siblings.ts` (new) — groups top-level class-like defs by namespace name (extracted from source via regex since `file_scoped_namespace_declaration` scope range covers only the declaration line, not the rest of the file). Injects sibling classes into each file's Module AND Namespace scope bindings with origin='namespace'. Local declarations shadow cross-file siblings via mergeBindings tier precedence. - `languages/csharp/scope-resolver.ts` — wire the hook. 74/74 scope-resolution unit tests pass; legacy path 175/175 green; 34 parity failures remain (was 37) under REGISTRY_PRIMARY_CSHARP=1. * feat(csharp-scope): parity Unit 2c — alias/await/return-type captures Closes 7 parity failures (34 → 27). Adds the remaining type-binding shapes the parity suite exercises: - `var alias = u;` / `alias = u;` — identifier-to-identifier alias. The resolver's chain-follow walks alias → u → u's declared type. - `var u = svc.GetUser();` — chained method call alias. Anchors on the method_access_expression's `name` field; chain-follow picks up GetUser's return type. - `var u = await Factory();` / `await svc.Get();` — await propagation. Strips the `await_expression` wrapper; interpret layer's `stripGeneric` handles `Task<T>` / `ValueTask<T>` unwrapping. - `public User GetUser() { ... }` — method return-type annotation via `@type-binding.return`. Required for `propagateImportedReturnTypes` to see the return type in later cross-file passes. Covers identifier, generic_name, qualified_name, and nullable_type return shapes. 74/74 scope-resolution unit tests pass; legacy path 175/175 green; 27 parity failures remain under REGISTRY_PRIMARY_CSHARP=1. * feat(csharp-scope): parity Unit 3a — cross-namespace `using` binding Closes 2 parity failures (27 → 25). Extends the namespace-siblings pass to resolve `using X;` directives against known namespace buckets: for each `using` that targets a namespace declared somewhere in the workspace, inject that namespace's classes into the importer's module scope with origin='namespace'. This is the scope-resolution analog of legacy's csproj-driven directory↔namespace mapping. Without it, `new User()` in `Services/UserService.cs` (namespace MyApp.Services) can't see the User class in `Models/User.cs` (namespace MyApp.Models) even with `using MyApp.Models;` — the scope-resolver layer doesn't have csproj metadata to translate the dotted namespace path into a directory lookup. Legacy 175/175 green; 25 parity failures remain. * feat(csharp-scope): parity Unit 3b — constructor CALLS emission Closes 3 parity failures (25 → 22). Adds constructor-form CALLS edge emission + C# 12 primary constructor synthesis. Changes: - `scope-resolution/passes/free-call-fallback.ts`: when a site's callForm === 'constructor', look up the class def (not a callable) and pick its explicit Constructor def via workspaceIndex's memberByOwner — or fall back to the Class def itself for implicit constructors. Matches legacy behavior (targetLabel === 'Constructor' when explicit, 'Class' when implicit). - `scope-resolution/pipeline/run.ts`: pass workspaceIndex to the free-call fallback. - `languages/csharp/captures.ts`: synthesize @declaration.constructor for C# 12 primary constructors — `class User(string name, int age)` / `record Person(string First, string Last)`. The parameter_list is a named child of the class_declaration / record_declaration (not a separate constructor_declaration node). Skip the synthesis when the type already has an explicit constructor to avoid duplicates. Emits @declaration.parameter-count + required-parameter-count alongside. Legacy 175/175 green; 376/376 scope-resolution unit tests pass; 22 parity failures remain. * feat(csharp-scope): parity Unit 3c — static call + default-namespace Closes 2 parity failures (22 → 21). - `receiver-bound-calls.ts`: add Case 5 for class-as-receiver. When `Animal.Classify()` has an identifier receiver that resolves to a Class binding (rather than a variable with a typeBinding), look up the member on the class's MRO chain. Covers C#-style static calls and any type-qualified member access. Python doesn't hit this because `ClassName.method()` is syntactically identical to a free call there. - `namespace-siblings.ts`: treat files with no `namespace X;` declaration as living in the default (empty-name) bucket, so types declared in no-namespace files share cross-file visibility. Required for fixtures without explicit namespaces (e.g. the method-enrichment fixture's Animal/App/Dog classes). Legacy 175/175 green; 21 parity failures remain. * feat(csharp-scope): parity Unit 4 — callsite arity synthesis (infra) Synthesize @reference.arity on every invocation_expression and object_creation_expression by counting `argument` named children of the backing `argument_list`. Wires the capture-to-Callsite pipeline shared extractor already consumes (`scope-extractor.ts:878`). No parity-count movement: the remaining arity-adjacent failures (overload disambiguation, optional-parameter dedup, variadic resolution) need type-based argument inference or member-call dedup, both explicitly deferred in the plan's Known Limitations section. This commit is infrastructure — future work lands on top of it. Legacy 175/175 green; 21 parity failures remain. * feat(csharp-scope): parity Unit 5a — IMPORTS edge + static-using mapping Closes 1 parity failure (21 → 20). Fixes cross-file IMPORTS edge emission for C#: - `languages/csharp/interpret.ts`: map `using static X.Y;` to `kind: 'namespace'` rather than `'wildcard'`. The File→File IMPORTS edge needs a non-wildcard kind to survive finalize's Phase 4 (wildcard-expanded edges drop to empty when the provider doesn't implement `expandsWildcardTo`). Unqualified static-member access is a deferred limitation — covered by the namespace-siblings cross-namespace pass for type lookups, and documented under the module's Known Limitations. - `languages/csharp/import-target.ts`: progressive prefix stripping. `using CrossFile.Models;` in a repo laid out `Models/User.cs` (no `CrossFile/` directory) works because the legacy resolver consults csproj; the scope-resolver tries each suffix of the dotted path against `.cs` files. Also handles `using static NS.Type;` by stripping leading segments until a direct match lands. - `test/unit/scope-resolution/csharp/csharp-imports.test.ts`: update the `using static` test to the new namespace-kind shape. 376/376 scope-resolution unit tests pass; legacy 175/175 green; 20 parity failures remain. * feat(csharp-scope): parity Unit 5b — return-type module hoist + chain fallback Closes 1 parity failure (20 → 19) and lays groundwork for Unit 6. Based on investigation-agent findings, addresses cluster of 7 cross-file + chain tests whose return-type bindings were stuck at Class scope and invisible to the chain-follow and propagation passes. Changes: - `languages/csharp/simple-hooks.ts::csharpBindingScopeFor`: when the declaration is a `@type-binding.return`, hoist the binding all the way to the Module scope. The central extractor's auto-hoist only promotes one level (Function → Class); for C# methods the parent is always a Class, so without this override the return binding never reaches Module where chain-follow and cross-file `propagateImportedReturnTypes` read from. - `scope-resolution/passes/compound-receiver.ts`: when the class-scope typeBindings lookup at `objClass.typeBindings.get( methodName)` misses, walk up from the class scope through the parent chain (→ Module) for a return-type binding. Preserves the existing class-scope fast-path while restoring owner-chain lookup for languages that hoist to Module. Python parity suite stays 204/204 green on both flag paths; legacy C# 175/175 green; 19 C# parity failures remain. * feat(csharp-scope): parity Unit 5c — switch-expr + reasons + ACCESSES 1.0 Closes 4 parity failures (19 → 15). - `languages/csharp/query.ts`: add captures for `switch_expression_arm` with `declaration_pattern` and `recursive_pattern`. C# expression- switch (`obj switch { User u => ..., Repo { Name: "x" } r => ... }`) uses a different AST node from classic `switch_statement`'s `switch_section` — needed separate query patterns. - `scope-resolution/passes/receiver-bound-calls.ts`: replace the self-describing `'scope-resolution: *-receiver'` reason strings (which fail legacy-parity consumer filters) with the legacy convention: `'import-resolved'` when the resolved member lives in a different file, `'global'` otherwise. Mirrors `free-call-fallback.ts`'s existing reason logic. - `scope-resolution/passes/receiver-bound-calls.ts`: pass `confidence: 1.0` to `tryEmitEdge` for write/read ACCESSES edges, matching legacy DAG behavior (default 0.85 was legacy-CALLS). Python parity 204/204 on both flag paths; legacy C# 175/175; 15 C# parity failures remain. * feat(csharp-scope): parity Unit 5d — cross-file typeBinding mirror Closes 3 parity failures (15 → 12). `languages/csharp/namespace-siblings.ts`: extend the pass to mirror method return-type bindings from accessible sibling files' Module scopes into the importer's Module scope. "Accessible" = same-namespace siblings + `using namespace X;` targets. Without this mirror, `var u = svc.GetUser()` in App.cs couldn't chain-follow to User even after Unit 5b's module-scope hoist: `GetUser → User` lived on User.cs's Module scope, which isn't on the ancestor chain of App.cs's function scope, and `propagateImportedReturnTypes` only mirrors across explicit ImportEdge targets (not same-namespace implicit visibility). Closes: var-invocation return type, async/await u.Save (ambient namespace), cross-file return-type propagation (via u.Save / u.GetName in Program.cs). Python parity 204/204 on both flag paths; legacy C# 175/175; 12 C# parity failures remain. * feat(csharp-scope): parity Unit 5e — namespace-prefix bucket matching Closes 2 parity failures (12 → 10). `languages/csharp/namespace-siblings.ts`: when matching accessible namespaces against class buckets, also probe every dotted prefix. `using static CrossFile.Models.UserFactory;` parses into the importer's accessible-namespace set as the full type path, but the matching bucket is keyed on the containing namespace (`CrossFile.Models`). Walking back through the dotted segments ensures the static-using importer sees the containing namespace's sibling files' return-type bindings. Legacy 175/175 green; 10 C# parity failures remain. * feat(csharp-scope): parity Unit 6a — class-like owner extension Closes 1 parity failure (10 → 9). Extends `populateClassOwnedMembers` to recognize Interface / Struct / Record / Enum / Trait as class-like owners, not just Class. The C# scope query collapses interface_declaration / struct_declaration / record_declaration / enum_declaration to @scope.class (they share body-scope semantics), but the declaration-side tags produce defs of type Interface / Struct / Record / Enum. `populateClassOwnedMembers` previously only looked for Class-typed defs in class scopes, so interface members (including C# 8+ default methods) never got ownerIds — making them invisible to `findOwnedMember` via `memberByOwner`. With this fix, `user.Validate()` on a variable typed as `IValidator` resolves correctly: receiver-bound-calls Case 4 finds IValidator via findClassBindingInScope (which already accepted Interface), walks the chain, and findOwnedMember locates Validate now that the interface default has a proper ownerId. Legacy C# 175/175 green; Python parity 204/204 on both flag paths; 9 C# parity failures remain. * feat(csharp-scope): parity Unit 6b — member-call dedup + handled-site fix Closes 1 parity failure (9 → 8). Adds the missing legacy-parity behavior: collapse multiple member-call sites from the same caller to the same target into one CALLS edge. Changes: - `scope-resolution/contract/scope-resolver.ts`: new optional `collapseMemberCallsByCallerTarget` flag. Default false (preserves the per-site invariant); C# sets it true. - `scope-resolution/graph-bridge/edges.ts`: dedup key drops `line:col` when `collapseByCallerTarget` is on AND edgeType is `CALLS` (ACCESSES writes keep per-site granularity). - `scope-resolution/passes/receiver-bound-calls.ts`: plumbs `collapse` through every `tryEmitEdge` call, and crucially marks `handledSites.add(siteKey)` whenever a resolved def was found — not only when the edge was freshly emitted. Otherwise the site leaked through to `emitReferencesViaLookup` which re-emitted a per-site edge, defeating the collapse. - `languages/csharp/scope-resolver.ts`: opt in to the collapse. Python parity 204/204 on both flag paths; legacy C# 175/175 green; 8 C# parity failures remain. * feat(csharp-scope): parity Unit 6c — Dictionary.Values / .Keys unwrap Closes 2 parity failures (8 → 6). Dictionary<K,V>.Values in a foreach binds the element to V; .Keys binds to K. Without this, `foreach (var user in data.Values)` where `data: Dictionary<string, User>` couldn't propagate user's type to User, and `user.Save()` stayed unresolved. Changes: - `languages/csharp/interpret.ts`: don't strip the qualifier when the final dotted segment is a known collection accessor (`Values` / `Keys`). Preserves the dotted form so downstream resolvers can unwrap the receiver's generic type based on the suffix. - `scope-resolution/passes/compound-receiver.ts`: new `extractDictionaryArgs` helper splits `Dictionary<K, V>` at the top-level comma. In the dotted-access walk, detect trailing `.Values` / `.Keys` and return V/K via findClassBindingInScope instead of the normal class-walk (Dictionary itself isn't a local class def). - Handles nested cases: `this.data.Values` walks `this.data` recursively (resolving `data` as a field on `this`'s class) before applying the unwrap. - `scope-resolution/passes/receiver-bound-calls.ts` Case 3b: when the typeRef's trailing segment is an accessor, pass the raw dotted path to `resolveCompoundReceiverClass` without appending `()` — the extra parens would misroute to the call-expression branch. Python parity 204/204 on both flag paths; legacy C# 175/175 green; 6 C# parity failures remain. * feat(csharp-scope): parity Unit 6d — using-static member injection Closes 2 parity failures (6 → 4). `using static X.Y.Z;` now injects every public static method of class Z into the importer's module scope, so `Record("hi")` (without `Logger.` qualifier) resolves to `Logger.Record` as a free call. `languages/csharp/namespace-siblings.ts`: regex-scan each file's source for `using static X.Y.Z;` directives. For each, look up the class Z in the `X.Y` namespace bucket, walk its owning file's localDefs for method/function members with `ownerId === Z.nodeId`, and inject them as `origin: 'import'` bindings in the importer's module-scope finalized bindings map. `findCallableBindingInScope` then picks them up via its imported-bindings check. Closes: variadic `Record(params string[])` + heritage arity narrowing `WriteAudit`. Python parity 204/204 on both flag paths; legacy C# 175/175 green; 4 C# parity failures remain (interface-dispatch pass + type-based overload disambiguation). * feat(csharp-scope): parity Unit 6e — overload disambig + interface dispatch + FLAG FLIP Closes the final 4 parity failures (4 → 0). C# now runs the registry-primary scope-resolution path by default — added to MIGRATED_LANGUAGES. Changes: - `scope-resolution/scope/walkers.ts`: was already extended in Unit 6a to recognize Interface/Struct/Record/Enum as class-like owners (interface default methods get ownerIds). - `scope-resolution/passes/receiver-bound-calls.ts`: build IMPLEMENTS edge index → emit secondary `interface-dispatch` CALLS edges to every implementor's same-named member when the primary receiver-typed edge targets an Interface method (closes heritage CreateUser CALLS-count test). - `scope-resolution/passes/receiver-bound-calls.ts`: new `pickOverload` helper narrows multi-valued `membersByOwner.get(owner).get(name)` candidates by arity then argument types. Replaces the first-seen `findOwnedMember` lookup in Case 4 so receiver-typed overloaded calls pick the right def. - `scope-resolution/passes/free-call-fallback.ts`: new `pickImplicitThisOverload` walks up to the enclosing class scope and applies the same arity + argument-type narrowing for free calls inside a class body (`Lookup("alice")` → `Lookup(string)`). - `scope-resolution/workspace-index.ts`: new `membersByOwner` multi-valued index (`Map<owner, Map<name, Def[]>>`) preserves every overload alongside the existing first-seen `memberByOwner`. - `scope-resolution/graph-bridge/node-lookup.ts` + `scope-resolution/graph-bridge/ids.ts`: include parameter-types suffix in the qualified lookup key for Method nodes. Legacy parse-phase encodes the type tag into the node id (`Method:f.cs: UserService.Lookup#1~int`); without this two same-arity overloads collapsed to one lookup entry and routed to the wrong graph node. - `scope-resolution/contract/scope-resolver.ts`: new `collapseMemberCallsByCallerTarget` opt-in flag (was added in Unit 6b for member-call dedup; documented here). - `gitnexus-shared/src/scope-resolution/reference-site.ts`: new `argumentTypes` field carrying inferred per-arg types. - `scope-extractor.ts`: read @reference.parameter-types capture into `site.argumentTypes` and add it + the declaration-arity tags to KNOWN_SUB_TAGS so the anchor-detection picks the right anchor. - `languages/csharp/captures.ts`: synthesize @reference.parameter-types by inferring arg types from literal AST nodes (integer_literal → 'int', string_literal → 'string', constructor_expression → type-name, etc). - `languages/csharp/scope-resolver.ts`: opt in to `collapseMemberCallsByCallerTarget`. - `registry-primary-flag.ts`: **add CSharp to MIGRATED_LANGUAGES**. Final state: - C# parity: 175/175 green on flag-on AND flag-off. - Python parity: 204/204 green on both flag paths (no regression). - TypeScript clean. 51 → 0 failures across 18 commits on `feat/csharp-scope-resolution`. * refactor(scope-resolution): extract language-specific accessor unwrap to provider hook Optimizer pass: move C# Dictionary-family `.Values`/`.Keys` handling out of the shared `compound-receiver.ts` (where it had hardcoded regex + accessor names) into a provider-level `unwrapCollectionAccessor` hook. The shared pass now takes an arbitrary language-specific unwrap function; C# supplies its Dictionary implementation in `languages/csharp/accessor-unwrap.ts`. Related cleanup in `receiver-bound-calls.ts` Case 3b: replace the hardcoded `tail === 'Values' || tail === 'Keys'` accessor check with a try-dotted-walk-first / fall-back-to-call-form strategy. This removes the last C#-specific branch in the shared pass and makes the logic generalize cleanly to other languages that use property-style accessors for collection views (Kotlin `.size`, future languages). Changes: - `scope-resolution/contract/scope-resolver.ts`: new optional `unwrapCollectionAccessor(receiverType, accessor) => string | undefined` hook. Documented as language-specific with examples. - `scope-resolution/passes/compound-receiver.ts`: delete `extractDictionaryArgs`, accept `unwrapCollectionAccessor` via options, call it for trailing accessor segments. - `scope-resolution/passes/receiver-bound-calls.ts`: plumb the hook through to `resolveCompoundReceiverClass`, remove the C#-hardcoded Case 3b accessor check. - `languages/csharp/accessor-unwrap.ts` (new): C# Dictionary-family regex + element-type extraction. - `languages/csharp/scope-resolver.ts`: opt in. Audit outcome: everything else added across the 19 C# migration commits is either correctly scoped to `languages/csharp/` (query, captures, namespace-siblings, receiver-binding, interpret, imports) or correctly generic in shared paths (argumentTypes field, collapseMemberCallsByCallerTarget flag, overload narrowing via parameterTypes, interface-dispatch via IMPLEMENTS edges, class-like owner extension for Interface/Struct/Record/Enum, type-tagged node IDs, module-scope return-type lookup fallback). 175/175 C# green on both flag paths; 204/204 Python green on both flag paths; TypeScript clean. * refactor(scope-resolution): gate module-scope typeBinding walk-up on hook Add optional `hoistTypeBindingsToModule` to the ScopeResolver contract and gate the Module-scope walk-up in `resolveCompoundReceiverClass` on it. Only providers that hoist method return-type bindings to Module scope (C#) opt in; Python and other providers no longer traverse that fallback path. Closes the architectural leak flagged in the production-readiness review: the walk-up was unconditional and therefore widened Python's code path despite existing only for C#. No behavior change for C# (hook=true restores the prior lookup). No behavior change for Python (hook undefined = walk-up skipped, matching pre-PR behavior). Verified: - npx tsc --noEmit clean - C# unit suite 74/74 passing - C# + Python integration 388/388 passing * refactor(csharp-scope): remove as-unknown-as double casts in scope-resolver Tighten three type boundaries that were previously papered over with `as unknown as` casts: * `CsharpResolveContext.allFilePaths`: `Set<string>` → `ReadonlySet<string>`. The orchestrator only hands out a read-only view; drop the widening cast at the resolver-adapter site. * `resolveCsharpImportTarget`: call passes the narrow context directly. `WorkspaceIndex` is `unknown` in the shared contract, so the `as unknown as WorkspaceIndex` cast was gratuitous — structural assignability covers it. * `csharpMergeBindings`: drop unused `_scope: Scope` parameter. The implementation never read it; the cast chain in `scope-resolver.ts` existed only to satisfy an unused slot. LanguageProvider.mergeBindings now wraps with a tiny arrow adapter; ScopeResolver.mergeBindings passes through directly. No runtime behavior change. `grep 'as unknown as' csharp/scope-resolver.ts` returns zero matches. Verified: - npx tsc --noEmit clean - C# unit + integration 462/462 passing (incl. Python integration) * test(csharp-scope): integration fixtures for Units 6c/6d/6e runtime behavior Close the integration-coverage gap flagged in the production-readiness review. Units 6c (collection-accessor unwrap), 6d (using-static member injection), and 6e (overload disambig + interface dispatch) previously had only hook-level unit tests; the end-to-end wiring was exercised only by the parity harness. Three minimal fixtures + four new it() blocks: * csharp-collection-accessor — RenderAll iterates Dictionary<string, Widget>.Values and calls .Render(); asserts the CALLS edge lands on Widget.Render. * csharp-using-static — `using static Helpers.MathUtils;` makes Square(int) a free-callable in the consumer; asserts the CALLS edge lands on MathUtils.Square. * csharp-overload-interface — three assertions: 1. Run → Log binds to the 2-arg overload only (arity narrowing); verified via target Method node's parameterTypes.length === 2. 2. Run → Greet emits one primary edge to IGreeter.Greet plus two reason='interface-dispatch' siblings to En/FrGreeter.Greet. 3. Interface-dispatch fan-out excludes the primary target. Verified: - csharp integration 189/189 passing * docs(scope-resolution): de-c#-ify optional-hook doc-comments on contract Rewrite the doc-comments on four optional hooks so they describe the behavior and when a provider would enable it, rather than naming C# as the sole consumer. Hook names were already generic — only the comments had baked in one-language framing, which risked discouraging future reuse. Affected hooks: * unwrapCollectionAccessor * collapseMemberCallsByCallerTarget * populateNamespaceSiblings * hoistTypeBindingsToModule Language-specific rationale stays where it belongs — next to the hook assignment in `languages/csharp/scope-resolver.ts`. Zero-match grep for `C#|csharp|CSharp` in the contract file confirms the separation. No code change. * docs(csharp-scope): justify regex-based namespace-sibling detection Record why `namespace-siblings.ts` uses regex over AST walks and enumerate the known misses so the next reader has ground to stand on: * `global using static X.Y;` — no plain `using static` token. * Aliased `using static X = Y.Z;` — `=` breaks the pattern. * Attributed namespace declarations between `]` and `{`. * Multi-namespace files — first-wins attribution. * Preprocessor-gated namespace declarations — textual branch only. Rationale: the pass is file-path-driven and the tree-sitter tree isn't available at its call site (the orchestrator feeds raw fileContents); re-parsing to count namespaces would cost more than the regex walk. Refactor to AST-driven detection is deferred to a separate PR. Mirrored the known-miss list into `csharp/index.ts`'s limitations ledger so the operator-visible surface and the in-code justification stay in sync. No code change. * refactor(csharp-scope): AST-driven namespace detection with treeCache reuse Replace regex-over-source-content with tree-sitter AST walks in namespace-siblings.ts; thread the orchestrator's treeCache through the populateNamespaceSiblings hook so the pass reuses the same parse trees `extractParsedFile` already consumed (single-source-of-truth for the AST — no double-parse). Behavior gains (no longer "known misses"): * `global using static X.Y;` is now detected. * Aliased `using static X = Y.Z;` is now detected. * Attributed namespace declarations (`[attr] namespace X`) parse correctly because tree-sitter sees them as one node. * Preprocessor-gated namespace declarations parse via the grammar. Contract change (additive, optional): * `populateNamespaceSiblings` ctx now carries an optional `treeCache?: { get(filePath): unknown }`. Existing providers that don't set it on `RunScopeResolutionInput` see undefined, and the hook falls back to a fresh parse (current behavior preserved on cache miss). Limitation ledger updated in csharp/index.ts: the AST-based detection removes 4 of the 5 prior known misses; only "first-wins multi-namespace file attribution" remains. Verified: - npx tsc --noEmit clean - C# + Python integration 393/393 passing * refactor(python-scope): remove as-unknown-as casts in scope-resolver (mirrors Unit 2) Replay the C# scope-resolver cleanup on the Python side so both providers share a single clean pattern: * Drop `ws as unknown as WorkspaceIndex` — `WorkspaceIndex` is `unknown` in the shared contract, so the narrow context assigns structurally without a cast. * Drop `{ id: scopeId } as unknown as Scope` — `pythonMergeBindings` never read the scope (the parameter was `_scope`), so the stub was a type-only ghost. Signature is now `(bindings)` and the LanguageProvider slot wraps with an arrow adapter. * Drop `allFilePaths as Set<string>` — the orchestrator hands a `ReadonlySet<string>`; we copy it into a `Set` at the resolver adapter so the legacy downstream `resolvePythonImportInternal` chain (typed for mutable `Set<string>`) keeps working. The copy is O(N) once per import, trivial cost. Left intact on purpose: the `(callsite, def) → (def, callsite)` arrow wrapper on `arityCompatibility`. That's a documented shape difference between `LanguageProvider.arityCompatibility(def, callsite)` and `ScopeResolver.arityCompatibility(callsite, def)`; both providers (Python + C#) carry the same wrapper. Reconciling is a separate refactor across both contracts. No runtime behavior change. Verified: - npx tsc --noEmit clean - Python + C# unit + integration suites 529/529 passing * docs(scope-resolution): document I1-I8 invariants, source-of-truth, and same-graph guarantee Promote contract knowledge that was implicit in code into the canonical docs so future migrations and the next reviewer don't have to reverse-engineer it. contract/scope-resolver.ts: * Migration cookbook lists every optional hook (was: only the two booleans), with one-line guidance per hook including when to enable `hoistTypeBindingsToModule`. * Contract Invariants I1-I7 are now spelled out in full (was: only I1/I3/I5 summarized with a pointer to a plan file). Added new I8 "post-finalize hooks may mutate Scope.typeBindings and indexes.bindings; consumers must not freeze or snapshot before all post-finalize hooks have run". * New "Semantic-model source of truth" section: ParsedFile is the single semantic model; passes that need AST-level facts must reuse the orchestrator's treeCache rather than re-parse. * New "Same-graph guarantee" section: legacy DAG and scope-resolution emit indistinguishable edges (node identity, edge vocabulary, confidence). CI parity workflow enforces this. gitnexus-shared/src/scope-resolution/parsed-file.ts: * Added "Source-of-truth invariant" pointer paragraph. ARCHITECTURE.md (Coexistence section): * Updated migrated-language list (Python + C#). * Added "Same-graph guarantee" subsection. * Added "Semantic-model source of truth" subsection. * Filled in the ScopeResolver hook table with the five optional hooks that landed in this branch (unwrapCollectionAccessor, collapseMemberCallsByCallerTarget, populateNamespaceSiblings, hoistTypeBindingsToModule, fieldFallbackOnMethodLookup). * Added C# rows to the code-references table. Verified: - npx tsc --noEmit clean - C# + Python integration 393/393 passing * refactor(scope-resolution): consume SemanticModel as single authoritative store Unify scope-resolution and legacy parse into one symbol index per the industry pattern (Roslyn / tsc / rust-analyzer). Scope-resolution passes now consume `SemanticModel.methods` / `SemanticModel.fields` / `SemanticModel.symbols` for all symbol-keyed lookups. The legacy DAG already read from these; the drift — two parallel owner-keyed indexes populated by two writers with divergent ownerId semantics — is closed. Changes: * `MethodRegistry.lookupAllByOwner(owner, name)`: new API returning every overload without arity narrowing. Powers `findOwnedMember` / `pickOverload`. * `pipeline/run.ts` reconciliation pass: after `provider.populateOwners(parsed)`, iterate `parsed.localDefs[i]` and register methods/fields into the SemanticModel under the corrected ownerId. Idempotent — skips defs already present under `(ownerId, simple)` by nodeId, so unmigrated languages whose legacy extractor already set ownerId (C#) don't double-register. Closes the Python gap where class-body methods were invisible to `MethodRegistry` because the legacy Python method extractor couldn't resolve `enclosingClassId` at parse time. * `WorkspaceResolutionIndex` slimmed to Scope-valued maps only (`classScopeByDefId`, `moduleScopeByFile`). Dropped `memberByOwner`, `membersByOwner`, `defsByFileAndName`, `callablesBySimpleName` — all symbol-keyed duplicates of SemanticModel indexes. * Walker helpers now consume SemanticModel: - `findOwnedMember(owner, name, model)` → methods then fields fallback (ACCESSES writes target Property/Variable defs too). - `findExportedDefByName` fallback walks every Module scope's `origin === 'local'` bindings via `index.moduleScopeByFile` (preserves the module-export-visibility filter that SymbolTable.fileIndex can't cheaply encode). - `findExportedDef` reads `moduleScope.bindings` directly. * `pickOverload` in receiver-bound-calls.ts falls back to `model.fields.lookupFieldByOwner` when method lookup returns empty, fixing ACCESSES write edges that receive a Property target. * `phase.ts` threads `resolutionContext.model` into `RunScopeResolutionInput`. Boundary rule, enforced by file placement: - symbol-indexed lookups (key = nodeId / name / filePath) → `SemanticModel` - Scope-valued lookups (value = `Scope`) → `WorkspaceResolutionIndex` Research synthesized from web-researcher + Explore + best-practices + system-architect agents; canonical references: Roslyn Overview, rust-analyzer architecture, stack-graphs paper. Verified: - npx tsc --noEmit clean - C# + Python integration 393/393 passing * docs(scope-resolution): refresh comments after dropping duplicated indexes Replace references to the now-deleted `memberByOwner` / `callablesBySimpleName` index fields with comments that describe the actual lookup path (`SemanticModel` registries + scope-tied module bindings). Pure doc cleanup; no behavior change. * feat(scope-resolution): extract reconciliation pass + add parity validator Extract the SemanticModel reconciliation pass (previously inline in `pipeline/run.ts`) into a dedicated module with: * `reconcileOwnership(parsedFiles, model)` — pure function returning stats (methodsRegistered / fieldsRegistered / skippedAlreadyPresent). Idempotent; safe to re-run. * `validateOwnershipParity(parsedFiles, model, onWarn)` — dev-mode runtime validator for Contract Invariant I9. Walks every def with an `ownerId` and asserts it is reachable via `model.methods.lookupAllByOwner` or `model.fields.lookupFieldByOwner`. Soft-fails via `onWarn`; never throws. Validator is gated on both `NODE_ENV !== 'production'` and `VALIDATE_SEMANTIC_MODEL !== '0'` so production incurs zero cost but development surfaces any drift between `parsed.localDefs` ownership and the registries. 12 new unit tests cover: * happy path: method, property, Variable registration * edge case: defs without ownerId are skipped * idempotency: second call is a no-op * coexistence: defs the legacy extractor already registered (via `model.symbols.add`) are skipped on reconcile * overloads: multiple methods under the same (owner, name) * validator: no warnings after reconciliation * validator: warns on drift * validator: no-op under NODE_ENV=production * validator: no-op when VALIDATE_SEMANTIC_MODEL=0 * validator: warns on missing Property same as missing Method Verified: - npx tsc --noEmit clean - reconcile-ownership unit tests 12/12 passing - C# + Python integration 393/393 passing * refactor(scope-resolution): narrow handles + tighten required params Two small hygiene fixes that fell out of the unified-model work: * Introduce `readonlyModel: SemanticModel` in `runScopeResolution` immediately after reconciliation so the write/read phase boundary is explicit at the code level. Downstream passes (receiver-bound, free-call) receive the narrowed `SemanticModel` rather than the `MutableSemanticModel` that only the reconciliation pass needs. The type system now rejects accidental writes in the read phase. * Make `emitFreeCallFallback`'s `workspaceIndex` parameter required. It's now always passed (every caller threads it through), and the `workspaceIndex?` guard was dead code. Also drops the `| undefined` branch from `pickConstructorOrClass` which no caller can hit. No behavior change. * docs(semantic-model): document unified single-source-of-truth invariant (I9) Add Contract Invariant I9 to the ScopeResolver contract and write the single-source-of-truth + write/read phase contract into both the SemanticModel file-head and ARCHITECTURE.md. Three landing points so the rule is reachable from every entry: * contract/scope-resolver.ts — new I9 entry in the Contract Invariants list: scope-resolution passes consult SemanticModel exclusively for symbol-keyed lookups; WorkspaceResolutionIndex is reserved for Scope-valued maps. Documents the two-phase write (legacy parse + reconcileOwnership) and the narrowed-handle read posture. Calls out the reconciliation shim as transitional. * model/semantic-model.ts — new "Single-source-of-truth invariant" and "Write / read phase contract" sections in the file-head. Three ordered write phases (parse → reconcile → attachScopeIndexes), then frozen for readers. * ARCHITECTURE.md § "Semantic-model source of truth" — expanded subsection covering both invariants (ParsedFile = AST truth, SemanticModel = symbol truth), the write/read phase diagram, and the reconciliation-shim rationale. No code change. * test(scope-resolution): rewrite workspace-index test for slimmed index The test file previously asserted on \`defsByFileAndName\`, \`callablesBySimpleName\`, and \`memberByOwner\` — fields removed when symbol-keyed lookups moved to \`SemanticModel\`. Rewrite so the same invariants are asserted via the authoritative consumers: * New WorkspaceResolutionIndex shape test (scope-only maps). * \`findExportedDef\` module-export visibility tests: - keeps top-level class and function defs. - excludes class-body Variable defs (MAX_USERS = 100). - excludes class methods from module-export lookup. * \`findExportedDefByName\` fallback excludes class methods when a same-named module function exists. * \`findOwnedMember\` via the reconciled SemanticModel finds Python class methods after populateOwners + reconcileOwnership. Total assertions preserved: every invariant from the old test file is still pinned; the assertion surface shifted from the index shape to the walker helpers. Verified: - workspace-index.test.ts 8/8 passing * fix(tests): update registry-primary-flag test for C# migration The "returns exactly the flipped languages" case expected `enabled.size === 1` after toggling Python off and Go on. After the C# migration lands C# in MIGRATED_LANGUAGES, C# is default-on too — so the size is now 2 (Go + C#) unless C# is also opted out. Turn off C# alongside Python in the test setup. Added a comment noting that future migrations must add their REGISTRY_PRIMARY_<LANG>='false' line here. * refactor(scope-resolution): address PR #1019 review findings Resolves all 5 findings from the automated review on feat/csharp-scope-resolution. Shared ingestion code stays language-agnostic; C# (and every class-like language) benefits. F1 [high] Broaden class-like predicate Hoist `isClassLike` in `scope/walkers.ts` to an exported top-level helper covering Class | Interface | Struct | Record | Enum | Trait. Use it in `findClassBindingInScope`, `findEnclosingClassDef`, and `buildWorkspaceResolutionIndex` so C# records, structs, interfaces, and enums participate in scope chains and receiver binding the same way Python classes do. F2 [medium] Remove stale comment in csharp simple-hooks `csharpReceiverBinding`'s doc claimed this/base synthesis was "planned for a follow-up"; synthesis has been implemented in receiver-binding.ts since the migration landed. Rewrite the doc to describe the actual behavior (non-null TypeRef on instance-method bodies, null on static/free functions). F3 [medium] O(1) reverse lookup for classScopeId -> classDefId Add `classScopeIdToDefId: ReadonlyMap<ScopeId, string>` to `WorkspaceResolutionIndex`, populated as the inverse of `classScopeByDefId`. Replace the O(C) linear scan in `pickImplicitThisOverload` (free-call-fallback.ts) with an O(1) `Map.get` — turns per-site reverse resolution from linear in class count to constant time for every free call. F4 [low] Extract narrowOverloadCandidates shared utility New `passes/overload-narrowing.ts` centralizes the arity + argument- type narrowing previously duplicated across `pickOverload` (receiver-bound-calls.ts) and `pickImplicitThisOverload` (free-call-fallback.ts). Both callsites now share identical narrowing semantics; variadic `params T` handling is preserved. Return type is `readonly SymbolDefinition[]` with no defensive spreads (allocations saved on the hot path). F5 [low] Merge unreachable Case 5 into Case 2 `Case 5` in `receiver-bound-calls.ts` was dead code — `Case 2` pre-empted it for every static/class-name receiver. Delete Case 5 and lift its kind-aware read/write ACCESSES reason/confidence logic into Case 2 so static-style member access (e.g. `Interface.Member`, `TypeName.StaticMember`) gets the correct edge metadata. Tests - New unit tests for `narrowOverloadCandidates` covering empty input, arity filtering, variadic params, type narrowing, and fallback semantics. - New unit tests for `classScopeIdToDefId` verifying inverse invariant and empty index behavior. - New C# integration fixtures and tests: * csharp-record-base — record inheritance + `base.Save()` * csharp-struct-overloads — struct with implicit-this overload narrowing (pinned exact edge count under registry-primary) * csharp-interface-receiver-static — interface-qualified static- style call exercises the merged Case 2. - Full runs green: * scope-resolution unit: 406/406 * csharp integration (registry-primary): 197/197 * csharp integration (legacy DAG): 197/197 * python integration (regression guard): 204/204 Chore - Add `.context/` to root `.gitignore` to prevent agent scratch files from being committed. Made-with: Cursor * test(csharp-scope-resolution): address adversarial review follow-ups on PR #1019 Applies the three actionable follow-ups from the post-commit adversarial review of5a1bce7fagainst DoD.md. No runtime code changes. - [medium] Strengthen bounds-only assertion in the struct-overloads suite: `methods.length` is now pinned to `toBe(2)` and the arity list to `toEqual([1, 2])`. Fixture `csharp-struct-overloads/src/Calc.cs` declares exactly two `Add` methods, so a regression that adds, drops, or merges an overload will now fail the test instead of silently passing a `>= 2` gate. - [low] Pin the merged Case 2 kind-aware branch (receiver-bound-calls.ts lines 257-289) with a dedicated fixture and three new assertions: `csharp-class-static-field-access/src/Counters.cs` exercises `ClassName.Field = value` where the receiver resolves via `findClassBindingInScope` (no typeBinding on `Counters`). The test verifies (a) two distinct ACCESSES writes are emitted from a single method (per-site dedup from graph-bridge/edges.ts:80-87), (b) `reason === 'write'`, (c) `confidence === 1.0`, and (d) no spurious CALLS edges are produced for the same sites. This is the semantic upgrade lifted from the deleted Case 5; without a pinning test a future revert of the kind-aware branch would silently drop back to `import-resolved`/`global` at 0.85 for the same sites. Read-side coverage is intentionally not asserted because the C# tree-sitter query currently emits only `write.member` captures (languages/csharp/query.ts:485-501) — a read counterpart would have no reference site today and would give a false sense of coverage. - [info] Left the `?? overloads[0]` fallback in place at receiver-bound-calls.ts:450 unchanged. With the package's current tsconfig (strict: false, no noUncheckedIndexedAccess) both the defensive fallback and a `candidates[0]!` assertion type-check identically, so the finding has no production-readiness impact. Keeping the fallback minimizes churn. Validation (local, Windows PowerShell): - `npx prettier --check test/integration/resolvers/csharp.test.ts` -> clean - `npx tsc --noEmit` -> 0 errors - `REGISTRY_PRIMARY_CSHARP=1 npx vitest run test/integration/resolvers/csharp.test.ts` -> 200/200 - `REGISTRY_PRIMARY_CSHARP=0 npx vitest run test/integration/resolvers/csharp.test.ts` -> 200/200 - `npx vitest run test/integration/resolvers/python.test.ts` -> 204/204 - `npm test` (full gitnexus suite) -> 6967 passed, 6 pre-existing failures (4x Swift overload/dedup, 1x Swift method-extraction unit, 1x Swift type-env unit, 1x LadybugDB lockfile on Windows). All six reproduce on5a1bce7fwith these follow-up changes stashed, confirming they are environment/baseline failures unrelated to this work. Swift is not in MIGRATED_LANGUAGES so the merged Case 2 path cannot affect it. Refs: PR #1019 Made-with: Cursor * refactor(scope-resolution): address full-PR review findings on PR #1019 Resolves the two remaining findings from the code-review-swarm full-PR sweep (verdict: production-ready with minor follow-ups). [low] Complete the csharp/index.ts module-layout JSDoc. `languages/csharp/index.ts` is the discovery surface for the C# scope- resolution module decomposition (per AGENTS.md). The "Module layout" list silently omitted three load-bearing modules — `accessor-unwrap.ts` (`.Values`/`.Keys` receiver-type unwrap), `namespace-siblings.ts` (AST-driven cross-file implicit-namespace visibility), and `receiver-binding.ts` (`this`/`base` type-binding synthesis). Extended the JSDoc list so the "single-concern" decomposition story is honest and the next contributor can locate the right file without grep. No behavior change. [info] Replace the non-standard `'scope-resolution: super-receiver'` edge reason with the canonical `'global'` tier. `passes/receiver-bound-calls.ts` emitted a non-canonical reason string for the super/base branch, which falls outside the vocabulary declared in ARCHITECTURE.md § Scope-Resolution Pipeline (`'import-resolved' | 'global' | 'local-call' | 'same-file' | 'interface-dispatch' | 'read' | 'write'`). Super/base calls resolve through the MRO chain rather than through import directives, so the correct canonical tier is `'global'` (same classification the legacy DAG's `toResolveResult` applies to non-same-file, non-import-scoped resolutions). Locked the contract with `rel.reason === 'global'` assertions on the existing `csharp-super-resolution` and `csharp-generic-parent- resolution` suites, both of which go through the super-branch MRO path. The `csharp-record-base` suite intentionally does not pin a reason (records don't currently emit EXTENDS edges, so the MRO lookup misses and the edge is produced by the reference-index fallback instead of the super-branch). A code comment flags the pre-existing Python-legacy asymmetry (Python legacy tier classifier marks `super()` as `'import-resolved'` because the ancestor arrives via an `import` statement); closing that gap requires realigning the legacy tier classifier and is tracked separately. Validation: - `npx tsc --noEmit` passes. - `npx prettier --check` clean on all four touched files. - `test/integration/resolvers/csharp.test.ts` — 200/200 under both `REGISTRY_PRIMARY_CSHARP=0` (legacy DAG) and `REGISTRY_PRIMARY_CSHARP=1` (registry-primary), preserving same-graph parity on the super branch. - `test/integration/resolvers/python.test.ts` — 204/204 under both `REGISTRY_PRIMARY_PYTHON=0` and `=1`. - `test/unit/scope-resolution/` — 406/406 passing. Unstaged: `gitnexus/package-lock.json` (drift from `npm install` run to resolve the pre-existing missing `jsonc-parser` dependency — not part of this change). Made-with: Cursor * test(ci): raise integration-test timeouts so slow Windows runners stop flaking The `windows-latest` CI runner for this branch was consistently failing two integration suites in ways that had nothing to do with the PR's scope-resolution changes: * `cli-e2e.test.ts` — `analyze command runs pipeline on mini-repo` hit the default 30 s vitest test timeout, which raced the test's own 30 s subprocess timeout and prevented the existing `if (result.status === null) return;` slow-CI tolerance from ever firing. That single timeout then cascaded into the downstream `cypher`/`query`/`impact` tests (which exited non-zero because the mini-repo was never indexed) and the `EPIPE handling` test. * `skills-e2e.test.ts` — `beforeAll` hooks run a full `runSkillsCli(tmpDir)` subprocess that analyzes a fixture repo and generates skills. 50 s was enough on Linux/macOS but not on slow Windows CPUs, producing "Hook timed out in 50000ms" errors and cascading test failures across every language describe block. Fix: * Bump the `analyze` test's vitest test-level timeout to 60 s so it exceeds the 30 s subprocess timeout and the slow-CI tolerance can actually activate. * Bump all 12 `runSkillsCli`-driven `beforeAll` hooks from 50 s to 120 s. No production-code behavior changes. No change to what the tests assert — only the per-test/hook wall-clock budget. Made-with: Cursor
2422 lines
93 KiB
TypeScript
2422 lines
93 KiB
TypeScript
/**
|
|
* C#: heritage resolution via base_list + ambiguous namespace-import refusal
|
|
*/
|
|
import { describe, it, expect, beforeAll } from 'vitest';
|
|
import path from 'path';
|
|
import {
|
|
FIXTURES,
|
|
CROSS_FILE_FIXTURES,
|
|
getRelationships,
|
|
getNodesByLabel,
|
|
getNodesByLabelFull,
|
|
edgeSet,
|
|
runPipelineFromRepo,
|
|
type PipelineResult,
|
|
} from './helpers.js';
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Heritage: class + interface resolution via base_list
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# heritage resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-proj'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects exactly 3 classes and 2 interfaces', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseEntity', 'User', 'UserService']);
|
|
expect(getNodesByLabel(result, 'Interface')).toEqual(['ILogger', 'IRepository']);
|
|
});
|
|
|
|
it('emits exactly 1 EXTENDS edge: User → BaseEntity', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(1);
|
|
expect(extends_[0].source).toBe('User');
|
|
expect(extends_[0].target).toBe('BaseEntity');
|
|
});
|
|
|
|
it('emits exactly 1 IMPLEMENTS edge: User → IRepository', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
expect(implements_.length).toBe(1);
|
|
expect(implements_[0].source).toBe('User');
|
|
expect(implements_[0].target).toBe('IRepository');
|
|
});
|
|
|
|
it('emits CALLS edges from CreateUser (constructor + member calls)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// _repo.Save() → IRepository.Save (primary) plus interface-dispatch → User.Save (impl)
|
|
expect(calls.length).toBe(5);
|
|
const targets = edgeSet(calls);
|
|
expect(targets).toContain('CreateUser → User'); // new User() constructor
|
|
expect(targets).toContain('CreateUser → Validate'); // user.Validate() — receiver-typed
|
|
expect(targets).toContain('CreateUser → Save'); // _repo.Save() — IRepository + User (dispatch)
|
|
expect(targets).toContain('CreateUser → Log'); // _logger.Log() — receiver-typed
|
|
});
|
|
|
|
it('resolves all CALLS from CreateUser via import-resolved, unique-global, or interface-dispatch', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// C# non-aliased `using Namespace;` imports don't populate NamedImportMap
|
|
// (namespace-scoped imports can't bind to individual symbols).
|
|
// Calls resolve via directory-based PackageMap (import-resolved) when ambiguous,
|
|
// or via unique-global when the symbol name is globally unique.
|
|
// _repo.Save() also emits interface-dispatch to User.Save (IRepository has one impl in-repo).
|
|
for (const call of calls) {
|
|
expect(['import-resolved', 'global', 'interface-dispatch']).toContain(call.rel.reason);
|
|
}
|
|
});
|
|
|
|
it('resolves new User() to the User class via constructor discrimination', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const ctorCall = calls.find((c) => c.target === 'User');
|
|
expect(ctorCall).toBeDefined();
|
|
expect(ctorCall!.targetLabel).toBe('Class');
|
|
});
|
|
|
|
it('detects 4 namespaces', () => {
|
|
const ns = getNodesByLabel(result, 'Namespace');
|
|
expect(ns.length).toBe(4);
|
|
});
|
|
|
|
it('detects properties on classes', () => {
|
|
const props = getNodesByLabel(result, 'Property');
|
|
expect(props).toContain('Id');
|
|
expect(props).toContain('Name');
|
|
});
|
|
|
|
it('no OVERRIDES edges target Property nodes', () => {
|
|
const overrides = getRelationships(result, 'METHOD_OVERRIDES');
|
|
for (const edge of overrides) {
|
|
const target = result.graph.getNode(edge.rel.targetId);
|
|
expect(target).toBeDefined();
|
|
expect(target!.label).not.toBe('Property');
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ambiguous: using-namespace can't disambiguate same-named types
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# ambiguous symbol resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-ambiguous'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects 2 Handler classes and 2 IProcessor interfaces', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes.filter((n) => n === 'Handler').length).toBe(2);
|
|
const ifaces = getNodesByLabel(result, 'Interface');
|
|
expect(ifaces.filter((n) => n === 'IProcessor').length).toBe(2);
|
|
});
|
|
|
|
it('heritage targets are synthetic (correct refusal for ambiguous namespace import)', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
|
|
expect(extends_.length).toBe(1);
|
|
expect(extends_[0].source).toBe('UserHandler');
|
|
expect(implements_.length).toBe(1);
|
|
expect(implements_[0].source).toBe('UserHandler');
|
|
|
|
// The key invariant: no edge points to Other/
|
|
if (extends_[0].targetFilePath) {
|
|
expect(extends_[0].targetFilePath).not.toContain('Other/');
|
|
}
|
|
if (implements_[0].targetFilePath) {
|
|
expect(implements_[0].targetFilePath).not.toContain('Other/');
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('C# qualified class names', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-qualified-types'), () => {});
|
|
}, 60000);
|
|
|
|
it('stores distinct qualified names for same-named classes across namespaces', () => {
|
|
const users = getNodesByLabelFull(result, 'Class').filter((node) => node.name === 'User');
|
|
expect(users).toHaveLength(2);
|
|
expect(users.map((node) => node.properties.qualifiedName).sort()).toEqual([
|
|
'Data.Auth.User',
|
|
'Services.Auth.User',
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe('C# call resolution with arity filtering', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-calls'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves CreateUser → WriteAudit to Utils/OneArg.cs via arity narrowing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
expect(calls.length).toBe(1);
|
|
expect(calls[0].source).toBe('CreateUser');
|
|
expect(calls[0].target).toBe('WriteAudit');
|
|
expect(calls[0].targetFilePath).toBe('Utils/OneArg.cs');
|
|
expect(calls[0].rel.reason).toBe('import-resolved');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Member-call resolution: obj.Method() resolves through pipeline
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# member-call resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-member-calls'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves ProcessUser → Save as a member call on User', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'Save');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.source).toBe('ProcessUser');
|
|
expect(saveCall!.targetFilePath).toBe('Models/User.cs');
|
|
});
|
|
|
|
it('detects User class and Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('Save');
|
|
});
|
|
|
|
it('emits HAS_METHOD edge from User to Save', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const edge = hasMethod.find((e) => e.source === 'User' && e.target === 'Save');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Collection-accessor unwrap (Unit 6c): data.Values on Dictionary<K,V>
|
|
// resolves to the value type's class.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# collection-accessor unwrap', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-collection-accessor'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves RenderAll → Render through Dictionary<string, Widget>.Values', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const renderCall = calls.find((c) => c.source === 'RenderAll' && c.target === 'Render');
|
|
expect(renderCall).toBeDefined();
|
|
expect(renderCall!.targetFilePath).toBe('Models/Widget.cs');
|
|
expect(['import-resolved', 'global']).toContain(renderCall!.rel.reason);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// using-static member injection (Unit 6d): `using static X.Y;` exposes Y's
|
|
// static methods as free-callables in the consumer.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# using static member injection', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-using-static'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves Compute → Square via `using static Helpers.MathUtils;`', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const sqCall = calls.find((c) => c.source === 'Compute' && c.target === 'Square');
|
|
expect(sqCall).toBeDefined();
|
|
expect(sqCall!.targetFilePath).toBe('Helpers/MathUtils.cs');
|
|
expect(['import-resolved', 'global']).toContain(sqCall!.rel.reason);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Overload disambiguation + interface dispatch (Unit 6e).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# overload disambiguation and interface dispatch', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-overload-interface'), () => {});
|
|
}, 60000);
|
|
|
|
it('Run → Log resolves to the 2-arg overload (arity narrowing)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const logCalls = calls.filter((c) => c.source === 'Run' && c.target === 'Log');
|
|
// With collapse-by-caller-target enabled and arity narrowing, Run
|
|
// should bind to the 2-arg overload only — not the 1-arg sibling.
|
|
expect(logCalls.length).toBe(1);
|
|
// Verify targetId points to the 2-arg overload by checking the
|
|
// target Method node's parameterTypes length.
|
|
const target = result.graph.getNode(logCalls[0].rel.targetId);
|
|
expect(target).toBeDefined();
|
|
const parameterTypes = (target!.properties as { parameterTypes?: string[] }).parameterTypes;
|
|
expect(parameterTypes).toBeDefined();
|
|
expect(parameterTypes!.length).toBe(2);
|
|
});
|
|
|
|
it('Run → Greet emits primary edge to IGreeter.Greet plus interface-dispatch siblings', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCalls = calls.filter((c) => c.source === 'Run' && c.target === 'Greet');
|
|
// One primary edge (IGreeter.Greet) + two interface-dispatch edges
|
|
// (EnGreeter.Greet, FrGreeter.Greet).
|
|
expect(greetCalls.length).toBe(3);
|
|
|
|
const primaries = greetCalls.filter((c) => c.rel.reason !== 'interface-dispatch');
|
|
expect(primaries.length).toBe(1);
|
|
expect(primaries[0].targetFilePath).toBe('Greeting/IGreeter.cs');
|
|
|
|
const fanout = greetCalls.filter((c) => c.rel.reason === 'interface-dispatch');
|
|
expect(fanout.length).toBe(2);
|
|
const fanoutPaths = fanout.map((c) => c.targetFilePath).sort();
|
|
expect(fanoutPaths).toEqual(['Greeting/EnGreeter.cs', 'Greeting/FrGreeter.cs']);
|
|
});
|
|
|
|
it('interface-dispatch fan-out excludes the primary target (no self-edge)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const fanout = calls.filter((c) => c.source === 'Run' && c.rel.reason === 'interface-dispatch');
|
|
for (const edge of fanout) {
|
|
expect(edge.targetFilePath).not.toBe('Greeting/IGreeter.cs');
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Primary constructor resolution: class User(string name, int age) { }
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# primary constructor resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-primary-ctors'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Constructor nodes for primary constructors on class and record', () => {
|
|
const ctors = getNodesByLabel(result, 'Constructor');
|
|
expect(ctors).toContain('User');
|
|
expect(ctors).toContain('Person');
|
|
});
|
|
|
|
it('primary constructor has correct parameter count', () => {
|
|
let userCtorParams: number | undefined;
|
|
let personCtorParams: number | undefined;
|
|
result.graph.forEachNode((n) => {
|
|
if (n.label === 'Constructor' && n.properties.name === 'User') {
|
|
userCtorParams = n.properties.parameterCount as number;
|
|
}
|
|
if (n.label === 'Constructor' && n.properties.name === 'Person') {
|
|
personCtorParams = n.properties.parameterCount as number;
|
|
}
|
|
});
|
|
expect(userCtorParams).toBe(2);
|
|
expect(personCtorParams).toBe(2);
|
|
});
|
|
|
|
it('resolves new User(...) as a CALLS edge to the Constructor node', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const ctorCall = calls.find((c) => c.target === 'User');
|
|
expect(ctorCall).toBeDefined();
|
|
expect(ctorCall!.source).toBe('Run');
|
|
expect(ctorCall!.targetLabel).toBe('Constructor');
|
|
expect(ctorCall!.targetFilePath).toBe('Models/User.cs');
|
|
});
|
|
|
|
it('also resolves user.Save() as a method call', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'Save');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.source).toBe('Run');
|
|
});
|
|
|
|
it('emits HAS_METHOD edge from User class to User constructor', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const edge = hasMethod.find((e) => e.source === 'User' && e.target === 'User');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
it('emits HAS_METHOD edge from Person record to Person constructor', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const edge = hasMethod.find((e) => e.source === 'Person' && e.target === 'Person');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Receiver-constrained resolution: typed variables disambiguate same-named methods
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# receiver-constrained resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-receiver-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes, both with Save methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.Save() to User.Save and repo.Save() to Repo.Save via receiver typing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((c) => c.target === 'Save');
|
|
expect(saveCalls.length).toBe(2);
|
|
|
|
const userSave = saveCalls.find((c) => c.targetFilePath === 'Models/User.cs');
|
|
const repoSave = saveCalls.find((c) => c.targetFilePath === 'Models/Repo.cs');
|
|
|
|
expect(userSave).toBeDefined();
|
|
expect(repoSave).toBeDefined();
|
|
expect(userSave!.source).toBe('ProcessEntities');
|
|
expect(repoSave!.source).toBe('ProcessEntities');
|
|
});
|
|
|
|
it('resolves constructor calls for both User and Repo', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userCtor = calls.find((c) => c.target === 'User');
|
|
const repoCtor = calls.find((c) => c.target === 'Repo');
|
|
expect(userCtor).toBeDefined();
|
|
expect(repoCtor).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Alias import resolution: using U = Models.User resolves U → User
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# alias import resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-alias-imports'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Main, Repo, and User classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Main', 'Repo', 'User']);
|
|
});
|
|
|
|
it('resolves u.Save() to User.cs and r.Persist() to Repo.cs via alias', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'Save');
|
|
const persistCall = calls.find((c) => c.target === 'Persist');
|
|
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.source).toBe('Run');
|
|
expect(saveCall!.targetLabel).toBe('Method');
|
|
expect(saveCall!.targetFilePath).toBe('Models/User.cs');
|
|
|
|
expect(persistCall).toBeDefined();
|
|
expect(persistCall!.source).toBe('Run');
|
|
expect(persistCall!.targetLabel).toBe('Method');
|
|
expect(persistCall!.targetFilePath).toBe('Models/Repo.cs');
|
|
});
|
|
|
|
it('emits exactly 2 IMPORTS edges via alias resolution', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
expect(imports.length).toBe(2);
|
|
expect(edgeSet(imports)).toEqual(['Main.cs → Repo.cs', 'Main.cs → User.cs']);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Variadic resolution: params string[] doesn't get filtered by arity
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# variadic call resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-variadic-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves call to params method Record(params string[]) in Logger.cs', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const logCall = calls.find((c) => c.target === 'Record');
|
|
expect(logCall).toBeDefined();
|
|
expect(logCall!.source).toBe('Execute');
|
|
expect(logCall!.targetFilePath).toBe('Utils/Logger.cs');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Local shadow: same-file definition takes priority over imported name
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# local definition shadows import', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-local-shadow'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves Run → Save to same-file definition, not the imported one', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find((c) => c.target === 'Save' && c.source === 'Run');
|
|
expect(saveCall).toBeDefined();
|
|
expect(saveCall!.targetFilePath).toBe('App/Main.cs');
|
|
});
|
|
|
|
it('does NOT resolve Save to Logger.cs', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveToUtils = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'Utils/Logger.cs',
|
|
);
|
|
expect(saveToUtils).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// For-each loop element typing: foreach (User user in users) user.Save()
|
|
// C#: explicit type in foreach_statement binds loop variable
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# foreach loop element type resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-foreach'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes, both with Save methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.Save() in foreach to User#Save (not Repo#Save)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'Models/User.cs',
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
expect(userSave!.source).toBe('ProcessEntities');
|
|
});
|
|
|
|
it('resolves repo.Save() in foreach to Repo#Save (not User#Save)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'Models/Repo.cs',
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
expect(repoSave!.source).toBe('ProcessEntities');
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// this.Save() resolves to enclosing class's own Save method
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# this resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-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 this.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('src/Models/User.cs');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Parent class resolution: EXTENDS + IMPLEMENTS via base_list
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# parent resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-parent-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects BaseModel and User classes plus ISerializable interface', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'User']);
|
|
expect(getNodesByLabel(result, 'Interface')).toEqual(['ISerializable']);
|
|
});
|
|
|
|
it('emits EXTENDS edge: User → BaseModel (from base_list)', () => {
|
|
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 → ISerializable', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
expect(implements_.length).toBe(1);
|
|
expect(implements_[0].source).toBe('User');
|
|
expect(implements_[0].target).toBe('ISerializable');
|
|
});
|
|
|
|
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();
|
|
expect(target!.properties.name).toBe(edge.target);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// base.Save() resolves to parent class's Save method
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# base resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-super-resolution'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects BaseModel, User, and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'Repo', 'User']);
|
|
});
|
|
|
|
it('resolves base.Save() inside User to BaseModel.Save, not Repo.Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const baseSave = calls.find(
|
|
(c) =>
|
|
c.source === 'Save' &&
|
|
c.target === 'Save' &&
|
|
c.targetFilePath === 'src/Models/BaseModel.cs',
|
|
);
|
|
expect(baseSave).toBeDefined();
|
|
// Pin the canonical edge-reason for super/base calls. The super-branch
|
|
// of receiver-bound-calls resolves through the MRO chain (not through
|
|
// imports), which the legacy DAG's tier classifier places in the
|
|
// `'global'` bucket (see `toResolveResult` in `call-processor.ts`).
|
|
// Emitting `'global'` unconditionally keeps the same-graph parity
|
|
// guarantee (ARCHITECTURE.md § Scope-Resolution Pipeline) and matches
|
|
// the legacy path under `REGISTRY_PRIMARY_CSHARP=0`.
|
|
expect(baseSave!.rel.reason).toBe('global');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'src/Models/Repo.cs',
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// base.Save() resolves to generic parent class's Save method
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# generic parent base resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-generic-parent-resolution'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects BaseModel, User, and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['BaseModel', 'Repo', 'User']);
|
|
});
|
|
|
|
it('resolves base.Save() inside User to BaseModel.Save, not Repo.Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const baseSave = calls.find(
|
|
(c) =>
|
|
c.source === 'Save' &&
|
|
c.target === 'Save' &&
|
|
c.targetFilePath === 'src/Models/BaseModel.cs',
|
|
);
|
|
expect(baseSave).toBeDefined();
|
|
expect(baseSave!.rel.reason).toBe('global');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'src/Models/Repo.cs',
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Pattern matching: `if (animal is Dog dog)` binds `dog` as type `Dog`
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# is pattern matching resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-pattern-matching'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Animal, Dog, and Cat classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('Animal');
|
|
expect(classes).toContain('Dog');
|
|
expect(classes).toContain('Cat');
|
|
});
|
|
|
|
it('detects Bark and Meow methods', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('Bark');
|
|
expect(methods).toContain('Meow');
|
|
});
|
|
|
|
it('resolves dog.Bark() to Dog.Bark via is-pattern type binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const barkCall = calls.find((c) => c.target === 'Bark');
|
|
expect(barkCall).toBeDefined();
|
|
expect(barkCall!.source).toBe('HandleAnimal');
|
|
expect(barkCall!.targetFilePath).toBe('Models/Animal.cs');
|
|
});
|
|
|
|
it('emits EXTENDS edges for Dog and Cat', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
const dogExtends = extends_.find((e) => e.source === 'Dog');
|
|
const catExtends = extends_.find((e) => e.source === 'Cat');
|
|
expect(dogExtends).toBeDefined();
|
|
expect(dogExtends!.target).toBe('Animal');
|
|
expect(catExtends).toBeDefined();
|
|
expect(catExtends!.target).toBe('Animal');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Return type inference: var user = svc.GetUser("alice"); user.Save()
|
|
// C#'s CONSTRUCTOR_BINDING_SCANNER handles `var` declarations with
|
|
// invocation_expression values, enabling end-to-end return type inference.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# return type inference via var + invocation', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-return-type'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User, UserService, and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('detects Save on both User and Repo, plus GetUser', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('Save');
|
|
expect(methods).toContain('GetUser');
|
|
// Repo.Save is also detected, proving the disambiguation test is meaningful
|
|
expect(methods.filter((m: string) => m === 'Save').length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.Save() to User#Save (not Repo#Save) via return type of GetUser(): User', () => {
|
|
// scanConstructorBinding binds `var user = svc.GetUser()` → calleeName "GetUser".
|
|
// processCallsFromExtracted verifies GetUser's returnType is "User" via
|
|
// PackageMap resolution of `using ReturnType.Models;`, then receiver filtering
|
|
// resolves user.Save() to User#Save (not Repo#Save).
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Run' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
// Must NOT resolve to Repo.Save — that would mean disambiguation failed
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Run' && c.targetFilePath.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('C# null-conditional call resolution (user?.Save())', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-null-conditional'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes with competing Save methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m: string) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('captures null-conditional user?.Save() call', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((c) => c.target === 'Save' && c.source === 'Process');
|
|
expect(saveCalls.length).toBeGreaterThan(0);
|
|
});
|
|
|
|
it('resolves user?.Save() to User#Save via receiver typing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Process' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves repo?.Save() to Repo#Save via receiver typing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Process' && c.targetFilePath.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT cross-contaminate (exactly 1 Save per receiver file)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((c) => c.target === 'Save' && c.source === 'Process');
|
|
const userTargeted = saveCalls.filter((c) => c.targetFilePath.includes('User.cs'));
|
|
const repoTargeted = saveCalls.filter((c) => c.targetFilePath.includes('Repo.cs'));
|
|
expect(userTargeted.length).toBe(1);
|
|
expect(repoTargeted.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# async/await constructor binding resolution
|
|
// Verifies that `var user = await svc.GetUserAsync()` correctly unwraps the
|
|
// await_expression to find the invocation_expression underneath, producing a
|
|
// constructor binding that enables receiver-based disambiguation of user.Save().
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# async await constructor binding resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-async-binding'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User, UserService, and OrderService classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('User');
|
|
expect(classes).toContain('UserService');
|
|
expect(classes).toContain('OrderService');
|
|
});
|
|
|
|
it('detects competing Save methods on User and Order', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('Save');
|
|
expect(methods).toContain('GetUserAsync');
|
|
expect(methods).toContain('GetOrderAsync');
|
|
});
|
|
|
|
it('resolves user.Save() after await to User#Save via return type inference', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUser' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('user.Save() does NOT resolve to Order#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUser' && c.targetFilePath.includes('Order.cs'),
|
|
);
|
|
expect(wrongSave).toBeUndefined();
|
|
});
|
|
|
|
it('resolves order.Save() after await to Order#Save via return type inference', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const orderSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessOrder' && c.targetFilePath.includes('Order.cs'),
|
|
);
|
|
expect(orderSave).toBeDefined();
|
|
});
|
|
|
|
it('order.Save() does NOT resolve to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessOrder' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(wrongSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Assignment chain propagation (Phase 4.3)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# assignment chain propagation', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-assignment-chain'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes each with a Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves alias.Save() to User#Save via assignment chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// Positive: alias.Save() must resolve to User#Save
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessEntities' &&
|
|
c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('alias.Save() does NOT resolve to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// Negative: alias comes from User, so only one edge to User.cs
|
|
const wrongCall = calls.filter(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessEntities' &&
|
|
c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(wrongCall.length).toBe(1);
|
|
});
|
|
|
|
it('resolves rAlias.Save() to Repo#Save via assignment chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
// Positive: rAlias.Save() must resolve to Repo#Save
|
|
const repoSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessEntities' &&
|
|
c.targetFilePath.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
|
|
it('each alias resolves to its own class, not the other', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessEntities' &&
|
|
c.targetFilePath.includes('User.cs'),
|
|
);
|
|
const repoSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessEntities' &&
|
|
c.targetFilePath.includes('Repo.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
expect(repoSave).toBeDefined();
|
|
expect(userSave!.targetFilePath).not.toBe(repoSave!.targetFilePath);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# mixed declarations: assignment chain + is-pattern in the same file.
|
|
// Tests that the type guard in extractPendingAssignment correctly skips
|
|
// is_pattern_expression nodes while still handling local_declaration_statement.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# assignment chain + is-pattern coexistence', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-mixed-decl-chain'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes each with a Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves alias.Save() to User#Save via assignment chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessWithChain' &&
|
|
c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('assignment chain alias does NOT resolve to Repo#Save (negative)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongCall = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessWithChain' &&
|
|
c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(wrongCall).toBeUndefined();
|
|
});
|
|
|
|
it('resolves u.Save() to User#Save via is-pattern binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const patternSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessWithPattern' &&
|
|
c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(patternSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves alias.Save() to Repo#Save via Repo assignment chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessRepoChain' &&
|
|
c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
|
|
it('Repo chain alias does NOT resolve to User#Save (negative)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongCall = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessRepoChain' &&
|
|
c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(wrongCall).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# is-pattern disambiguation: `if (obj is User user)` should bind user → User
|
|
// and resolve user.Save() to User#Save, NOT Repo#Save.
|
|
// Validates the Phase 5.2 is_pattern_expression extraction in extractDeclaration.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# is-pattern type binding disambiguation (Phase 5.2)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-is-pattern'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes each with a Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
const saveMethods = getNodesByLabel(result, 'Method').filter((m) => m === 'Save');
|
|
expect(saveMethods.length).toBe(2);
|
|
});
|
|
|
|
it('resolves user.Save() inside if (obj is User user) to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Process' && c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT resolve 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.cs'),
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Chained method calls: svc.GetUser().Save()
|
|
// Tests that C# chain call resolution correctly infers the intermediate
|
|
// receiver type from GetUser()'s return type and resolves Save() to User.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# chained method call resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-chain-call'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User, Repo, and UserService classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('User');
|
|
expect(classes).toContain('Repo');
|
|
expect(classes).toContain('UserService');
|
|
});
|
|
|
|
it('detects GetUser and Save methods', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('GetUser');
|
|
expect(methods).toContain('Save');
|
|
});
|
|
|
|
it('resolves svc.GetUser().Save() to User#Save via chain resolution', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUser' && c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT resolve svc.GetUser().Save() to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUser' && c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# var foreach Tier 1c: foreach (var user in users) with List<User> param
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# var foreach type resolution (Tier 1c)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-var-foreach'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes, both with Save methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('detects methods on both classes', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods.filter((m) => m === 'Save').length).toBe(2);
|
|
expect(methods).toContain('ProcessUsers');
|
|
expect(methods).toContain('ProcessRepos');
|
|
});
|
|
|
|
it('resolves direct calls with explicit parameter types (u.Save, r.Save)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const directUserSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Direct' && c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
const directRepoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Direct' && c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(directUserSave).toBeDefined();
|
|
expect(directRepoSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves user.Save() in var foreach to User#Save via Tier 1c', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUsers' && c.targetFilePath?.includes('User.cs'),
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves repo.Save() in var foreach to Repo#Save via Tier 1c', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessRepos' && c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
|
|
it('does NOT cross-resolve user.Save() to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrong = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessUsers' && c.targetFilePath?.includes('Repo.cs'),
|
|
);
|
|
expect(wrong).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# switch pattern: switch (obj) { case User user: user.Save(); }
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# switch pattern type resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-switch-pattern'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('resolves user.Save() via is-pattern to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'Models/User.cs',
|
|
);
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves repo.Save() via switch case pattern to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath === 'Models/Repo.cs',
|
|
);
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# Dictionary .Values foreach — member_access_expression resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# Dictionary .Values foreach resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-dictionary-keys-values'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects User class with Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
});
|
|
|
|
it('resolves user.Save() via Dictionary.Values to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessValues' && 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 === 'ProcessValues' && c.targetFilePath?.includes('Repo'),
|
|
);
|
|
expect(wrongSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# recursive_pattern: obj is User { Name: "Alice" } u — Phase 6.1
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# recursive_pattern type resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-recursive-pattern'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes with Save methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('resolves u.Save() via recursive_pattern is-expression to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find((c) => c.target === 'Save' && c.targetFilePath?.includes('User'));
|
|
expect(userSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves r.Save() via recursive_pattern switch expression to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const repoSave = calls.find((c) => c.target === 'Save' && c.targetFilePath?.includes('Repo'));
|
|
expect(repoSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves exactly one Save call per target class (no cross-resolution)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter(
|
|
(c) => c.target === 'Save' && c.source === 'ProcessWithRecursivePattern',
|
|
);
|
|
const toUser = saveCalls.filter((c) => c.targetFilePath?.includes('User'));
|
|
const toRepo = saveCalls.filter((c) => c.targetFilePath?.includes('Repo'));
|
|
// u.Save() → User#Save only, r.Save() → Repo#Save only
|
|
expect(toUser.length).toBe(1);
|
|
expect(toRepo.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# nested member access with container property: this.data.Values
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# nested member access foreach (this.data.Values)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-nested-member-foreach'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects User class with Save method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
});
|
|
|
|
it('resolves user.Save() via this.data.Values to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const userSave = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessValues' && 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 === 'ProcessValues' && c.targetFilePath?.includes('Repo'),
|
|
);
|
|
expect(wrongSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 8: Field/property type resolution (1-level)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Field type resolution (C#)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-field-types'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects classes: Address, Service, User', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Address', 'Service', 'User']);
|
|
});
|
|
|
|
it('detects Property nodes for C# properties', () => {
|
|
const properties = getNodesByLabel(result, 'Property');
|
|
expect(properties).toContain('Address');
|
|
expect(properties).toContain('Name');
|
|
expect(properties).toContain('City');
|
|
});
|
|
|
|
it('emits HAS_PROPERTY edges linking properties to classes', () => {
|
|
const propEdges = getRelationships(result, 'HAS_PROPERTY');
|
|
expect(propEdges.length).toBe(3);
|
|
expect(edgeSet(propEdges)).toContain('User → Address');
|
|
expect(edgeSet(propEdges)).toContain('User → Name');
|
|
expect(edgeSet(propEdges)).toContain('Address → City');
|
|
});
|
|
|
|
it('resolves user.Address.Save() → Address#Save via field type', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((e) => e.target === 'Save');
|
|
const addressSave = saveCalls.find(
|
|
(e) => e.source === 'ProcessUser' && e.targetFilePath.includes('Models'),
|
|
);
|
|
expect(addressSave).toBeDefined();
|
|
});
|
|
|
|
it('populates field metadata (visibility, declaredType) on Property nodes', () => {
|
|
const properties = getNodesByLabelFull(result, 'Property');
|
|
|
|
const city = properties.find((p) => p.name === 'City');
|
|
expect(city).toBeDefined();
|
|
expect(city!.properties.visibility).toBe('public');
|
|
expect(city!.properties.isStatic).toBe(false);
|
|
expect(city!.properties.declaredType).toBe('string');
|
|
|
|
const addr = properties.find((p) => p.name === 'Address');
|
|
expect(addr).toBeDefined();
|
|
expect(addr!.properties.visibility).toBe('public');
|
|
expect(addr!.properties.declaredType).toBe('Address');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 8A: Deep field chain resolution (3-level)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Deep field chain resolution (C#)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-deep-field-chain'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects classes: Address, City, Service, User', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['Address', 'City', 'Service', 'User']);
|
|
});
|
|
|
|
it('detects Property nodes for C# properties', () => {
|
|
const properties = getNodesByLabel(result, 'Property');
|
|
expect(properties).toContain('Address');
|
|
expect(properties).toContain('City');
|
|
expect(properties).toContain('ZipCode');
|
|
});
|
|
|
|
it('emits HAS_PROPERTY edges for nested type chain', () => {
|
|
const propEdges = getRelationships(result, 'HAS_PROPERTY');
|
|
expect(edgeSet(propEdges)).toContain('User → Address');
|
|
expect(edgeSet(propEdges)).toContain('Address → City');
|
|
expect(edgeSet(propEdges)).toContain('City → ZipCode');
|
|
});
|
|
|
|
it('resolves 2-level chain: user.Address.Save() → Address#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCalls = calls.filter((e) => e.target === 'Save' && e.source === 'ProcessUser');
|
|
const addressSave = saveCalls.find((e) => e.targetFilePath.includes('Models'));
|
|
expect(addressSave).toBeDefined();
|
|
});
|
|
|
|
it('resolves 3-level chain: user.Address.City.GetName() → City#GetName', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const getNameCalls = calls.filter((e) => e.target === 'GetName' && e.source === 'ProcessUser');
|
|
const cityGetName = getNameCalls.find((e) => e.targetFilePath.includes('Models'));
|
|
expect(cityGetName).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ACCESSES write edges from assignment expressions
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('Write access tracking (C#)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-write-access'), () => {});
|
|
}, 60000);
|
|
|
|
it('emits ACCESSES write edges for field assignments', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writes = accesses.filter((e) => e.rel.reason === 'write');
|
|
expect(writes.length).toBe(2);
|
|
const fieldNames = writes.map((e) => e.target);
|
|
expect(fieldNames).toContain('Name');
|
|
expect(fieldNames).toContain('Address');
|
|
const sources = writes.map((e) => e.source);
|
|
expect(sources).toContain('UpdateUser');
|
|
});
|
|
|
|
it('write ACCESSES edges have confidence 1.0', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writes = accesses.filter((e) => e.rel.reason === 'write');
|
|
for (const edge of writes) {
|
|
expect(edge.rel.confidence).toBe(1.0);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Call-result variable binding (Phase 9): var user = GetUser(); user.Save()
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# call-result variable binding (Tier 2b)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-call-result-binding'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves user.Save() to User#Save via call-result binding', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'ProcessUser' && c.targetFilePath.includes('App'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Method chain binding (Phase 9C): GetUser() → .Address → .GetCity() → .Save()
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# method chain binding via unified fixpoint (Phase 9C)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-method-chain-binding'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('resolves city.Save() to City#Save via method chain', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'ProcessChain' && c.targetFilePath.includes('App'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase B: Deep MRO — walkParentChain() at depth 2 (C→B→A)
|
|
// Greet() is defined on A, accessed via C. Tests BFS depth-2 parent traversal.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# grandparent method resolution via MRO (Phase B)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-grandparent-resolution'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects A, B, C, Greeting classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('A');
|
|
expect(classes).toContain('B');
|
|
expect(classes).toContain('C');
|
|
expect(classes).toContain('Greeting');
|
|
});
|
|
|
|
it('emits EXTENDS edges: B→A, C→B', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(edgeSet(extends_)).toContain('B → A');
|
|
expect(edgeSet(extends_)).toContain('C → B');
|
|
});
|
|
|
|
it('resolves c.Greet().Save() to Greeting#Save via depth-2 MRO lookup', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.targetFilePath.includes('Greeting'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves c.Greet() to A#Greet (method found via MRO walk)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCall = calls.find((c) => c.target === 'Greet' && c.targetFilePath.includes('A.cs'));
|
|
expect(greetCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase C: C# null-check narrowing — if (x != null) and if (x is not null)
|
|
// Both patterns emit patternOverrides for the if-body position range
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# null-check narrowing resolution (Phase C)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-null-check-narrowing'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects User and Repo classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Repo');
|
|
});
|
|
|
|
it('resolves x.Save() inside != null guard (ProcessInequality) to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' &&
|
|
c.source === 'ProcessInequality' &&
|
|
c.targetFilePath.includes('User'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves x.Save() inside is not null guard (ProcessIsNotNull) to User#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessIsNotNull' && c.targetFilePath.includes('User'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('does NOT cross-resolve to Repo#Save', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const wrongCall = calls.find((c) => c.target === 'Save' && c.targetFilePath.includes('Repo'));
|
|
expect(wrongCall).toBeUndefined();
|
|
});
|
|
|
|
it('resolves x.Save() inside constructor via null-check narrowing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'App' && c.targetFilePath.includes('User'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves x.Save() inside lambda via null-check narrowing', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) =>
|
|
c.target === 'Save' && c.source === 'ProcessInLambda' && c.targetFilePath.includes('User'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ── Phase P: Overload Disambiguation via Parameter Types ─────────────────
|
|
|
|
describe('C# overload disambiguation by parameter types', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-overload-param-types'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('produces distinct graph nodes for same-arity overloads via type-hash suffix', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const lookupNodes = methods.filter((m) => m.name === 'Lookup');
|
|
// Type-hash disambiguation → 2 distinct graph nodes
|
|
expect(lookupNodes.length).toBe(2);
|
|
const types = lookupNodes.map((n) => n.properties.parameterTypes).sort();
|
|
expect(types).toEqual([['int'], ['string']]);
|
|
});
|
|
|
|
it('CallById() emits exactly one CALLS edge to Lookup(int)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const fromCallById = calls.filter((c) => c.source === 'CallById' && c.target === 'Lookup');
|
|
expect(fromCallById.length).toBe(1);
|
|
const targetNode = result.graph.getNode(fromCallById[0].rel.targetId);
|
|
expect(targetNode?.properties.parameterTypes).toEqual(['int']);
|
|
});
|
|
|
|
it('CallByName() emits exactly one CALLS edge to Lookup(string)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const fromCallByName = calls.filter((c) => c.source === 'CallByName' && c.target === 'Lookup');
|
|
expect(fromCallByName.length).toBe(1);
|
|
const targetNode = result.graph.getNode(fromCallByName[0].rel.targetId);
|
|
expect(targetNode?.properties.parameterTypes).toEqual(['string']);
|
|
});
|
|
});
|
|
|
|
// ── Phase P: Same-arity overloads — cross-file + chain resolution ─────────
|
|
|
|
describe('C# same-arity overload cross-file and chain resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-same-arity-cross-file'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('CrossFileById() emits exactly one CALLS edge to Find(int) in DbLookup', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const edges = calls.filter(
|
|
(c) =>
|
|
c.source === 'CrossFileById' &&
|
|
c.target === 'Find' &&
|
|
c.targetFilePath.includes('DbLookup'),
|
|
);
|
|
expect(edges.length).toBe(1);
|
|
const targetNode = result.graph.getNode(edges[0].rel.targetId);
|
|
expect(targetNode?.properties.parameterTypes).toEqual(['int']);
|
|
});
|
|
|
|
it('CrossFileByName() emits exactly one CALLS edge to Find(string) in DbLookup', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const edges = calls.filter(
|
|
(c) =>
|
|
c.source === 'CrossFileByName' &&
|
|
c.target === 'Find' &&
|
|
c.targetFilePath.includes('DbLookup'),
|
|
);
|
|
expect(edges.length).toBe(1);
|
|
const targetNode = result.graph.getNode(edges[0].rel.targetId);
|
|
expect(targetNode?.properties.parameterTypes).toEqual(['string']);
|
|
});
|
|
|
|
it('emits METHOD_IMPLEMENTS from DbLookup.Find → ILookup.Find with matching types', () => {
|
|
const mi = getRelationships(result, 'METHOD_IMPLEMENTS');
|
|
const edges = mi.filter(
|
|
(e) =>
|
|
e.source === 'Find' &&
|
|
e.target === 'Find' &&
|
|
e.sourceFilePath.includes('DbLookup') &&
|
|
e.targetFilePath.includes('ILookup'),
|
|
);
|
|
expect(edges.length).toBe(2);
|
|
for (const edge of edges) {
|
|
const sourceNode = result.graph.getNode(edge.rel.sourceId);
|
|
const targetNode = result.graph.getNode(edge.rel.targetId);
|
|
expect(sourceNode?.properties.parameterTypes).toEqual(targetNode?.properties.parameterTypes);
|
|
}
|
|
});
|
|
|
|
it('ChainIntToFormat() resolves find(42) → Find(int) cross-file', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const findEdges = calls.filter((c) => c.source === 'ChainIntToFormat' && c.target === 'Find');
|
|
expect(findEdges.length).toBe(1);
|
|
const findTarget = result.graph.getNode(findEdges[0].rel.targetId);
|
|
expect(findTarget?.properties.parameterTypes).toEqual(['int']);
|
|
});
|
|
|
|
it('ChainNameToFormat() resolves find("alice") → Find(string) cross-file', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const findEdges = calls.filter((c) => c.source === 'ChainNameToFormat' && c.target === 'Find');
|
|
expect(findEdges.length).toBe(1);
|
|
const findTarget = result.graph.getNode(findEdges[0].rel.targetId);
|
|
expect(findTarget?.properties.parameterTypes).toEqual(['string']);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# optional parameter arity resolution
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# optional parameter arity resolution', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-optional-params'), () => {});
|
|
}, 60000);
|
|
|
|
it('resolves g.Greet("Alice") with 1 arg to Greet with 2 params (1 optional)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const greetCalls = calls.filter((c) => c.source === 'Main' && c.target === 'Greet');
|
|
expect(greetCalls.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Phase 14: Cross-file binding propagation
|
|
// Models/UserFactory.cs exports static GetUser() returning User
|
|
// App/Program.cs uses static import, calls var u = GetUser(); u.Save()
|
|
// → u is typed User via cross-file return type propagation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# cross-file binding propagation', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(CROSS_FILE_FIXTURES, 'csharp-cross-file'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects User class with Save and GetName methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('Save');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('GetName');
|
|
});
|
|
|
|
it('detects UserFactory class with GetUser method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserFactory');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('GetUser');
|
|
});
|
|
|
|
it('detects Program class with Run method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Program');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('Run');
|
|
});
|
|
|
|
it('emits IMPORTS edge from Program.cs to UserFactory.cs', () => {
|
|
const imports = getRelationships(result, 'IMPORTS');
|
|
const edge = imports.find(
|
|
(e) => e.sourceFilePath.includes('Program') && e.targetFilePath.includes('UserFactory'),
|
|
);
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
it('resolves u.Save() in Run() to User#Save via cross-file return type propagation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const saveCall = calls.find(
|
|
(c) => c.target === 'Save' && c.source === 'Run' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(saveCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves u.GetName() in Run() to User#GetName via cross-file return type propagation', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const getNameCall = calls.find(
|
|
(c) => c.target === 'GetName' && c.source === 'Run' && c.targetFilePath.includes('User.cs'),
|
|
);
|
|
expect(getNameCall).toBeDefined();
|
|
});
|
|
|
|
it('emits HAS_METHOD edges linking Save and GetName to User', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const saveEdge = hasMethod.find((e) => e.source === 'User' && e.target === 'Save');
|
|
const getNameEdge = hasMethod.find((e) => e.source === 'User' && e.target === 'GetName');
|
|
expect(saveEdge).toBeDefined();
|
|
expect(getNameEdge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# fallback without .csproj (P1-4 fix)
|
|
// When no .csproj file is found, import resolution should fall back to
|
|
// suffix-based matching rather than returning null.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# import resolution without .csproj (suffix fallback)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-no-csproj'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects User class with Save and GetName methods', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('Save');
|
|
});
|
|
|
|
it('detects UserService class with ProcessUser method', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toContain('UserService');
|
|
expect(getNodesByLabel(result, 'Method')).toContain('ProcessUser');
|
|
});
|
|
|
|
// C# 'using Models;' is a namespace import — suffix matching cannot resolve
|
|
// namespace-to-directory mappings without .csproj. The fallback prevents a null
|
|
// return (so other resolution paths can attempt it), but namespace imports
|
|
// inherently require project config for file discovery.
|
|
it('does not crash on namespace import without .csproj (graceful fallback)', () => {
|
|
// Pipeline completes without errors and detects symbols from both files,
|
|
// even though no IMPORTS edge is created for the namespace import.
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('User');
|
|
expect(classes).toContain('UserService');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Method enrichment: abstract, static, override, parameterTypes, annotations
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# method enrichment', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-method-enrichment'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Animal and Dog classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('Animal');
|
|
expect(classes).toContain('Dog');
|
|
});
|
|
|
|
it('emits HAS_METHOD edges for Animal methods', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const animalMethods = hasMethod
|
|
.filter((e) => e.source === 'Animal')
|
|
.map((e) => e.target)
|
|
.sort();
|
|
expect(animalMethods).toContain('Speak');
|
|
expect(animalMethods).toContain('Classify');
|
|
expect(animalMethods).toContain('Breathe');
|
|
});
|
|
|
|
it('emits HAS_METHOD edge for Dog.Speak', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const dogSpeak = hasMethod.find((e) => e.source === 'Dog' && e.target === 'Speak');
|
|
expect(dogSpeak).toBeDefined();
|
|
});
|
|
|
|
it('emits EXTENDS edge Dog -> Animal', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
const dogExtends = extends_.find((e) => e.source === 'Dog' && e.target === 'Animal');
|
|
expect(dogExtends).toBeDefined();
|
|
});
|
|
|
|
it('marks abstract Speak as isAbstract (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const speak = methods.find((n) => n.name === 'Speak' && n.properties.filePath === 'Animal.cs');
|
|
if (speak?.properties.isAbstract !== undefined) {
|
|
expect(speak.properties.isAbstract).toBe(true);
|
|
}
|
|
});
|
|
|
|
it('marks Breathe as NOT isAbstract (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const breathe = methods.find((n) => n.name === 'Breathe');
|
|
if (breathe?.properties.isAbstract !== undefined) {
|
|
expect(breathe.properties.isAbstract).toBe(false);
|
|
}
|
|
});
|
|
|
|
it('marks Classify as isStatic (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const classify = methods.find((n) => n.name === 'Classify');
|
|
if (classify?.properties.isStatic !== undefined) {
|
|
expect(classify.properties.isStatic).toBe(true);
|
|
}
|
|
});
|
|
|
|
it('marks Breathe as NOT isStatic (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const breathe = methods.find((n) => n.name === 'Breathe');
|
|
if (breathe?.properties.isStatic !== undefined) {
|
|
expect(breathe.properties.isStatic).toBe(false);
|
|
}
|
|
});
|
|
|
|
it('captures override annotation on Dog.Speak (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const dogSpeak = methods.find(
|
|
(n) => n.name === 'Speak' && n.properties.filePath !== 'Animal.cs',
|
|
);
|
|
if (dogSpeak?.properties.annotations !== undefined) {
|
|
expect(dogSpeak.properties.annotations).toContain('override');
|
|
}
|
|
});
|
|
|
|
it('populates parameterTypes for Classify (conditional)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Function');
|
|
const classify = methods.find((n) => n.name === 'Classify');
|
|
if (classify?.properties.parameterTypes !== undefined) {
|
|
const params = classify.properties.parameterTypes;
|
|
expect(params).toContain('string');
|
|
}
|
|
});
|
|
|
|
it('resolves dog.Speak() CALLS edge', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const speakCall = calls.find(
|
|
(c) => c.target === 'Speak' && c.sourceFilePath.includes('App.cs'),
|
|
);
|
|
expect(speakCall).toBeDefined();
|
|
});
|
|
|
|
it('resolves Animal.Classify("dog") static CALLS edge', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const classifyCall = calls.find(
|
|
(c) => c.target === 'Classify' && c.sourceFilePath.includes('App.cs'),
|
|
);
|
|
expect(classifyCall).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Interface dispatch: METHOD_IMPLEMENTS edges
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# interface dispatch (METHOD_IMPLEMENTS)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-interface-dispatch'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects IRepository interface and SqlRepository class', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
const ifaces = getNodesByLabel(result, 'Interface');
|
|
expect(classes).toContain('SqlRepository');
|
|
expect(ifaces).toContain('IRepository');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge SqlRepository → IRepository', () => {
|
|
const impl = getRelationships(result, 'IMPLEMENTS');
|
|
const edge = impl.find((e) => e.source === 'SqlRepository' && e.target === 'IRepository');
|
|
expect(edge).toBeDefined();
|
|
});
|
|
|
|
it('emits METHOD_IMPLEMENTS edges for Find and Save', () => {
|
|
const mi = getRelationships(result, 'METHOD_IMPLEMENTS');
|
|
const findEdge = mi.find(
|
|
(e) =>
|
|
e.source === 'Find' &&
|
|
e.target === 'Find' &&
|
|
e.sourceFilePath.includes('SqlRepository') &&
|
|
e.targetFilePath.includes('IRepository'),
|
|
);
|
|
const saveEdge = mi.find(
|
|
(e) =>
|
|
e.source === 'Save' &&
|
|
e.target === 'Save' &&
|
|
e.sourceFilePath.includes('SqlRepository') &&
|
|
e.targetFilePath.includes('IRepository'),
|
|
);
|
|
expect(findEdge).toBeDefined();
|
|
expect(saveEdge).toBeDefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Overloaded method disambiguation: METHOD_IMPLEMENTS with overloads
|
|
// IRepository declares Find(int), Find(string), Save(string).
|
|
// SqlRepository implements all three.
|
|
// Overloaded methods (same name, different params) collapse into a single
|
|
// graph node (generateId drops startLine), so Find appears once per file.
|
|
// METHOD_IMPLEMENTS still emits one edge per unique (source, target) pair.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# overloaded method disambiguation (METHOD_IMPLEMENTS)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-overload-dispatch'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects 2 distinct Find Method nodes on SqlRepository (different arities)', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const findOnSql = methods.filter(
|
|
(m) => m.name === 'Find' && m.properties.filePath?.includes('SqlRepository'),
|
|
);
|
|
expect(findOnSql.length).toBe(2);
|
|
});
|
|
|
|
it('emits METHOD_IMPLEMENTS edges for both Find overloads', () => {
|
|
const mi = getRelationships(result, 'METHOD_IMPLEMENTS');
|
|
const findEdges = mi.filter(
|
|
(e) =>
|
|
e.source === 'Find' &&
|
|
e.target === 'Find' &&
|
|
e.sourceFilePath.includes('SqlRepository') &&
|
|
e.targetFilePath.includes('IRepository'),
|
|
);
|
|
expect(findEdges.length).toBe(2);
|
|
});
|
|
|
|
it('emits METHOD_IMPLEMENTS for Save -> IRepository.Save', () => {
|
|
const mi = getRelationships(result, 'METHOD_IMPLEMENTS');
|
|
const saveEdge = mi.find(
|
|
(e) =>
|
|
e.source === 'Save' &&
|
|
e.target === 'Save' &&
|
|
e.sourceFilePath.includes('SqlRepository') &&
|
|
e.targetFilePath.includes('IRepository'),
|
|
);
|
|
expect(saveEdge).toBeDefined();
|
|
});
|
|
|
|
it('emits exactly 3 METHOD_IMPLEMENTS edges', () => {
|
|
const mi = getRelationships(result, 'METHOD_IMPLEMENTS');
|
|
expect(mi.length).toBe(3);
|
|
});
|
|
|
|
it('detects SqlRepository class and IRepository interface', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
const ifaces = getNodesByLabel(result, 'Interface');
|
|
expect(classes).toContain('SqlRepository');
|
|
expect(ifaces).toContain('IRepository');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// SM-9: lookupMethodByOwnerWithMRO — c.ParentMethod() via implements-split walk
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# Child extends Parent — inherited method resolution (SM-9)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-child-extends-parent'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects Parent and Child classes', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('Parent');
|
|
expect(classes).toContain('Child');
|
|
});
|
|
|
|
it('emits EXTENDS edge: Child → Parent', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(edgeSet(extends_)).toContain('Child → Parent');
|
|
});
|
|
|
|
it('resolves c.ParentMethod() to Parent.ParentMethod via implements-split MRO walk', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const parentMethodCall = calls.find(
|
|
(c) => c.target === 'ParentMethod' && c.targetFilePath.includes('Parent.cs'),
|
|
);
|
|
expect(parentMethodCall).toBeDefined();
|
|
expect(parentMethodCall!.source).toBe('Run');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// SM-11: C# User : IValidator — interface default method via implements-split
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# User implements IValidator — interface default method (SM-11)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-interface-default-method'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects IValidator interface and User class', () => {
|
|
expect(getNodesByLabel(result, 'Interface')).toContain('IValidator');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('User');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge: User → IValidator', () => {
|
|
const impls = getRelationships(result, 'IMPLEMENTS');
|
|
expect(edgeSet(impls)).toContain('User → IValidator');
|
|
});
|
|
|
|
it('resolves user.Validate() to IValidator.Validate via implements-split MRO', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const validateCall = calls.find(
|
|
(c) => c.target === 'Validate' && c.targetFilePath.includes('Validator.cs'),
|
|
);
|
|
expect(validateCall).toBeDefined();
|
|
expect(validateCall!.source).toBe('Run');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Interface-to-interface heritage (single + multi base interface)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# interface-to-interface heritage', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-interface-heritage'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects 1 class and 4 interfaces', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(['MyService']);
|
|
expect(getNodesByLabel(result, 'Interface')).toEqual([
|
|
'IAuditableService',
|
|
'IBarService',
|
|
'IBaseInterface',
|
|
'IFooService',
|
|
]);
|
|
});
|
|
|
|
it('emits no EXTENDS edges (fixture has no class inheritance)', () => {
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
expect(extends_.length).toBe(0);
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge: IFooService → IBaseInterface (single base interface)', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const targets = edgeSet(implements_);
|
|
expect(targets).toContain('IFooService → IBaseInterface');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edges: IAuditableService → IFooService, IBarService (multi base interfaces)', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const targets = edgeSet(implements_);
|
|
expect(targets).toContain('IAuditableService → IFooService');
|
|
expect(targets).toContain('IAuditableService → IBarService');
|
|
});
|
|
|
|
it('emits IMPLEMENTS edge: MyService → IAuditableService (class implements derived interface)', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
const targets = edgeSet(implements_);
|
|
expect(targets).toContain('MyService → IAuditableService');
|
|
});
|
|
|
|
it('emits exactly 4 IMPLEMENTS edges total', () => {
|
|
const implements_ = getRelationships(result, 'IMPLEMENTS');
|
|
expect(implements_.length).toBe(4);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// C# parse completeness regression (#903)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# parse completeness (#903 regression)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-hello'), () => {});
|
|
}, 60000);
|
|
|
|
it('parse phase completes without error (no crash)', () => {
|
|
expect(result).toBeDefined();
|
|
expect(result.graph).toBeDefined();
|
|
});
|
|
|
|
it('emits Class node for Greeter', () => {
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
expect(classes).toContain('Greeter');
|
|
});
|
|
|
|
it('emits Interface node for IFoo', () => {
|
|
const interfaces = getNodesByLabel(result, 'Interface');
|
|
expect(interfaces).toContain('IFoo');
|
|
});
|
|
|
|
it('emits Method nodes for Greet, Main, and Bar', () => {
|
|
const methods = getNodesByLabel(result, 'Method');
|
|
expect(methods).toContain('Greet');
|
|
expect(methods).toContain('Main');
|
|
expect(methods).toContain('Bar');
|
|
});
|
|
|
|
it('Greet has parameterCount=1 and returnType=string', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const greet = methods.find((m) => m.name === 'Greet');
|
|
expect(greet).toBeDefined();
|
|
expect(greet!.properties.parameterCount).toBe(1);
|
|
expect(greet!.properties.returnType).toBe('string');
|
|
expect(greet!.properties.visibility).toBe('public');
|
|
});
|
|
|
|
it('Main has parameterCount=1 and isStatic=true', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const main = methods.find((m) => m.name === 'Main');
|
|
expect(main).toBeDefined();
|
|
expect(main!.properties.parameterCount).toBe(1);
|
|
expect(main!.properties.isStatic).toBe(true);
|
|
expect(main!.properties.visibility).toBe('public');
|
|
});
|
|
|
|
it('Bar is abstract with parameterCount=0 and returnType=void', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method');
|
|
const bar = methods.find((m) => m.name === 'Bar');
|
|
expect(bar).toBeDefined();
|
|
expect(bar!.properties.parameterCount).toBe(0);
|
|
expect(bar!.properties.isAbstract).toBe(true);
|
|
expect(bar!.properties.returnType).toBe('void');
|
|
});
|
|
|
|
it('emits HAS_METHOD edges linking Greeter to its methods', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const targets = edgeSet(hasMethod);
|
|
expect(targets).toContain('Greeter → Greet');
|
|
expect(targets).toContain('Greeter → Main');
|
|
});
|
|
|
|
it('emits HAS_METHOD edge linking IFoo to Bar', () => {
|
|
const hasMethod = getRelationships(result, 'HAS_METHOD');
|
|
const targets = edgeSet(hasMethod);
|
|
expect(targets).toContain('IFoo → Bar');
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 1: record inheritance + base.Save() resolves via isClassLike widening
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# record base resolution (record inheritance + base.Save)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-record-base'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects BaseEntity and UserRecord', () => {
|
|
// Records project as label 'Record' (class-like) in the graph.
|
|
const records = getNodesByLabel(result, 'Record');
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
const all = [...records, ...classes];
|
|
expect(all).toContain('BaseEntity');
|
|
expect(all).toContain('UserRecord');
|
|
});
|
|
|
|
it('does not emit a spurious self-EXTENDS (record heritage not emitted by C# heritage queries)', () => {
|
|
// NOTE: C# tree-sitter heritage queries cover class/interface
|
|
// declarations but not `record_declaration`, so records don't
|
|
// emit an EXTENDS edge today. The record-base linkage is still
|
|
// visible via `base.Save()` resolution (next test). This
|
|
// assertion pins the negative invariant so a future heritage
|
|
// extension for records can flip both tests at once.
|
|
const extends_ = getRelationships(result, 'EXTENDS');
|
|
const selfExtend = extends_.find((e) => e.source === 'UserRecord' && e.target === 'UserRecord');
|
|
expect(selfExtend).toBeUndefined();
|
|
});
|
|
|
|
it('resolves base.Save() inside UserRecord.Save to BaseEntity.Save (not self)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const baseSave = calls.find(
|
|
(c) =>
|
|
c.source === 'Save' &&
|
|
c.target === 'Save' &&
|
|
c.targetFilePath === 'src/Models/BaseEntity.cs',
|
|
);
|
|
expect(baseSave).toBeDefined();
|
|
// NOTE: no `rel.reason` assertion here. Records don't emit EXTENDS
|
|
// edges today (see the negative-invariant test above), so the
|
|
// super-branch MRO lookup returns no ancestor and the edge is
|
|
// produced by the downstream reference-index fallback instead of
|
|
// the canonical super path. The `csharp-super-resolution` and
|
|
// `csharp-generic-parent` suites pin the super-branch reason on
|
|
// paths that do go through MRO.
|
|
const selfSave = calls.find(
|
|
(c) =>
|
|
c.source === 'Save' &&
|
|
c.target === 'Save' &&
|
|
c.targetFilePath === 'src/Models/UserRecord.cs',
|
|
);
|
|
expect(selfSave).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 4: struct overload dispatch exercises the extracted
|
|
// narrowOverloadCandidates utility via implicit-this free calls.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# struct overload dispatch (implicit-this narrowing)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(path.join(FIXTURES, 'csharp-struct-overloads'), () => {});
|
|
}, 60000);
|
|
|
|
it('detects Calc struct', () => {
|
|
const structs = getNodesByLabel(result, 'Struct');
|
|
const classes = getNodesByLabel(result, 'Class');
|
|
const all = [...structs, ...classes];
|
|
expect(all).toContain('Calc');
|
|
});
|
|
|
|
it('detects two Add overloads with distinct parameterCount', () => {
|
|
const methods = getNodesByLabelFull(result, 'Method').filter((m) => m.name === 'Add');
|
|
expect(methods.length).toBe(2);
|
|
const arities = methods.map((m) => m.properties.parameterCount as number).sort();
|
|
expect(arities).toEqual([1, 2]);
|
|
});
|
|
|
|
it('Run() -> Add emits CALLS edges to distinct Add overloads (implicit-this narrowing)', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const runToAdd = calls.filter((c) => c.source === 'Run' && c.target === 'Add');
|
|
// The registry-primary pipeline exercises `pickImplicitThisOverload`
|
|
// + `narrowOverloadCandidates` and MUST resolve both Add(int) and
|
|
// Add(int, int) to distinct targets. A silent regression in either
|
|
// helper would drop an edge or merge both onto one target — pin
|
|
// exact counts so either failure mode surfaces immediately.
|
|
// The legacy DAG path (REGISTRY_PRIMARY_CSHARP=0) does not
|
|
// implement implicit-`this` struct overload narrowing, so we
|
|
// accept any count there; the registry-primary path remains the
|
|
// authoritative guarantee.
|
|
if (process.env['REGISTRY_PRIMARY_CSHARP'] !== '0') {
|
|
expect(runToAdd.length).toBe(2);
|
|
const targetIds = new Set(runToAdd.map((c) => c.rel.targetId));
|
|
expect(targetIds.size).toBe(2);
|
|
} else {
|
|
expect(runToAdd.length).toBeLessThanOrEqual(2);
|
|
if (runToAdd.length >= 2) {
|
|
const targetIds = new Set(runToAdd.map((c) => c.rel.targetId));
|
|
expect(targetIds.size).toBe(runToAdd.length);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 5: merged Case 2 covers Interface static-style invocation
|
|
// (`ILogger.Warn(...)` from a class method).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# interface receiver static invocation (merged Case 2)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-interface-receiver-static'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects ILogger interface and Runner class', () => {
|
|
expect(getNodesByLabel(result, 'Interface')).toContain('ILogger');
|
|
expect(getNodesByLabel(result, 'Class')).toContain('Runner');
|
|
});
|
|
|
|
it('Go() -> ILogger.Warn CALLS edge points at src/ILogger.cs with import-resolved or global reason', () => {
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const warnCall = calls.find((c) => c.source === 'Go' && c.target === 'Warn');
|
|
expect(warnCall).toBeDefined();
|
|
expect(warnCall!.targetFilePath).toBe('src/ILogger.cs');
|
|
expect(['import-resolved', 'global']).toContain(warnCall!.rel.reason);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 5 (continued): merged Case 2 kind-aware branch for class-name
|
|
// receiver on WRITE ACCESSES. `Counters.Hits = 42` resolves receiver via
|
|
// `findClassBindingInScope` (no typeBinding on `Counters`), which is the
|
|
// exact path lifted from the deleted Case 5. Verifies `reason === 'write'`
|
|
// and `confidence === 1.0` — the semantic upgrade over the pre-merge
|
|
// Case 2, which emitted `import-resolved`/`global` at 0.85 for the same
|
|
// sites. Also pins per-site dedup (two distinct writes → two edges).
|
|
// C# tree-sitter queries emit only `write.member` captures today, so a
|
|
// read-side counterpart would have no reference site and is intentionally
|
|
// not asserted.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('C# class-name receiver write ACCESSES (merged Case 2 kind-aware branch)', () => {
|
|
let result: PipelineResult;
|
|
|
|
beforeAll(async () => {
|
|
result = await runPipelineFromRepo(
|
|
path.join(FIXTURES, 'csharp-class-static-field-access'),
|
|
() => {},
|
|
);
|
|
}, 60000);
|
|
|
|
it('detects Counters and Runner classes', () => {
|
|
expect(getNodesByLabel(result, 'Class')).toEqual(
|
|
expect.arrayContaining(['Counters', 'Runner']),
|
|
);
|
|
});
|
|
|
|
it('Touch() -> Hits and Touch() -> Misses each emit ACCESSES write with confidence 1.0', () => {
|
|
const accesses = getRelationships(result, 'ACCESSES');
|
|
const writesFromTouch = accesses.filter(
|
|
(e) => e.source === 'Touch' && e.rel.reason === 'write',
|
|
);
|
|
// Per-site dedup key is (caller, target, line, col) — two writes on
|
|
// distinct lines must produce two distinct edges.
|
|
expect(writesFromTouch.length).toBe(2);
|
|
for (const edge of writesFromTouch) {
|
|
expect(edge.rel.confidence).toBe(1.0);
|
|
expect(edge.targetFilePath).toBe('src/Counters.cs');
|
|
}
|
|
expect(writesFromTouch.map((e) => e.target).sort()).toEqual(['Hits', 'Misses']);
|
|
});
|
|
|
|
it('does not emit any CALLS edges for the static field writes', () => {
|
|
// `Counters.Hits = 42` is a field write, not a call. A regression
|
|
// that misclassifies the site would surface as a spurious CALLS
|
|
// edge here.
|
|
const calls = getRelationships(result, 'CALLS');
|
|
const stray = calls.filter(
|
|
(c) => c.source === 'Touch' && (c.target === 'Hits' || c.target === 'Misses'),
|
|
);
|
|
expect(stray).toEqual([]);
|
|
});
|
|
});
|