GitNexus/gitnexus/test/unit/scope-resolution/receiver-chain-fold.test.ts
Gergő Magyar cc0b5d54f7
fix(swift,dart): type chained receivers through hoisted return types (#3498) (#3666)
* fix(swift,dart): type chained receivers through hoisted return types (#3498)

Swift and Dart hoist every method's return-type binding out of the class
body onto the Module scope, as C# does, but neither set
hoistTypeBindingsToModule. The receiver walk therefore never looked
there, and svc.getUser().save() had no receiver type. Both now set it.

The flag alone was not safe. The hoisted bindings are keyed by bare
method name, so with class A { getUser() -> User } and
class B { getUser() -> Admin } in one file the Module scope keeps only
B's entry, and a.getUser().save() resolved to Admin.save. C# and
TypeScript already do this on main.

So there is a new ScopeResolver toggle, hoistedTypeBindingsRequireOwner,
which Swift and Dart also set. With it, the walk accepts a hoisted
binding only when its declaration anchor encloses the declaration of a
member of that name owned by the receiver's class. Otherwise it keeps
climbing, and declines if nothing passes. The four walk-ups in
compound-receiver.ts now share one helper.

The toggle is opt-in. With the guard on everywhere, TypeScript loses
correct edges where two same-named methods happen to return the same
type (11 rows in inferred-field-receiver-matrix), because the Module map
cannot hold both. Swift and Dart never had those edges.

Bench: swift plainChain, plainDeepChain, optionalChain and nonNullAssert
(INVISIBLE-GAP) and dart plainChain, plainDeepChain and optionalChain
(VISIBLE-GAP) now RESOLVE with correct targets. No other cell and no
count-arm figure moves. The inferred-field matrix gains correct
Inner.compute edges for Swift (3 rows) and Dart (7 Alien rows).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(scope): guard hoisted return ownership

* fix(scope): gate hoisted return replay checks

* fix(scope): preserve parameterized return replay

Keep exact callee return facts when ancestor candidates have matching
known parameter types, while refusing same-owner overload ties.

Refs #3666

* fix(scope): preserve known variadic return replay

Compare complete captured parameter vectors across distinct ancestor
owners, including variadic methods with unknown numeric arity. Keep
unknown Swift parameter slots instead of compressing them away.

Refs #3666

* test(swift): retain reviewed receiver fixtures

* fix(scope): retain unknown overload candidates

Keep unknown parameter slots possible without hiding conversion overloads.
Check return-owner precision without requiring valid calls to stay unresolved.

Refs #3498

* fix(scope): preserve conversion suppression

Keep explicit empty conversion results final when parameter metadata is
unknown. Add exact positive controls for receiver-fixture liveness.

Refs #3498

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:52:11 +00:00

354 lines
15 KiB
TypeScript

/**
* U6 — `foldReceiverChain` types a receiver from decoded structure rather than
* from its source text.
*
* The fold is called directly: U6 deliberately wires it into no resolution
* path (that is U10), so there is no pipeline behaviour to assert yet.
*/
import { describe, it, expect } from 'vitest';
import type { ScopeId } from 'gitnexus-shared';
import { createSemanticModel } from '../../../src/core/ingestion/model/semantic-model.js';
import { reconcileOwnership } from '../../../src/core/ingestion/scope-resolution/pipeline/reconcile-ownership.js';
import { typescriptScopeResolver } from '../../../src/core/ingestion/languages/typescript/scope-resolver.js';
import { csharpScopeResolver } from '../../../src/core/ingestion/languages/csharp/scope-resolver.js';
import { foldReceiverChain } from '../../../src/core/ingestion/scope-resolution/passes/compound-receiver.js';
import { decodeReceiverChain } from '../../../src/core/ingestion/utils/receiver-chain-codec.js';
import { buildScopeModel, type ScopeModelFixture } from '../../helpers/scope-model.js';
const SOURCE = `export class Address {
save(): void {}
}
export class User {
address: Address = new Address();
save(): void {}
}
export class Base {
inherited(): User {
return new User();
}
}
export class Item {
run(): void {}
}
export class Service extends Base {
getUser(): User {
return new User();
}
getUserAsync(): Promise<User> {
return Promise.resolve(new User());
}
getItems(): Item[] {
return [];
}
getMap(): Map<string, Item> {
return new Map();
}
}
// A class with NO member \`save\`, whose FIELD's type has one. The field
// fallback finds \`save\` by walking in here; the fold must not.
export class Holder {
user: User = new User();
}
// NOT a container: an ordinary class that happens to be subscriptable, with a
// member whose name COLLIDES with the element type's. Indexing it yields an
// \`Item\`, so \`grid[0].run()\` is \`Item.run\` — but an index step that folded
// on identity stayed on \`Grid\` and found \`Grid.run\` instead.
export class Grid {
run(): void {}
[i: number]: Item;
}
// Not subscriptable at all, and shares the member name too.
export class Plain {
run(): void {}
}
const svc: Service = new Service();
const holder: Holder = new Holder();
declare const grid: Grid;
declare const plain: Plain;
declare const repos: User[];
declare const nested: User[][];
declare const byId: Record<string, Item>;
`;
/** A built scope model plus the scope a fold starts in. */
interface FoldContext {
readonly fixture: ScopeModelFixture;
readonly inScope: ScopeId;
}
/** `foldReceiverChain`'s options bag. The interface itself is module-private
* in `compound-receiver`, so it is read off the function rather than
* re-declared (which would let the two drift). */
type FoldOptions = NonNullable<Parameters<typeof foldReceiverChain>[4]>;
const tsFixture = buildScopeModel(typescriptScopeResolver, SOURCE, 'main.ts');
const ctx: FoldContext = { fixture: tsFixture, inScope: tsFixture.moduleScope };
/**
* Fold `encoded` in `ctx`, under the language's own contract flags — exactly
* as the resolver pass would pass them. TypeScript hoists method return-type
* bindings out of the class body, so the fold needs that flag to find any of
* them; `elementTypeOf` is what an index step consults, and passing it here is
* what makes these tests measure the same fold `emitReceiverBoundCalls` runs.
*
* `overrides` replaces individual flags — used to exercise the OFF branch of
* `hoistTypeBindingsToModule` (which c, cobol, python and ruby actually run)
* and the no-`elementTypeOf` branch (which
* twelve of the fourteen do).
*/
function foldIn(ctx: FoldContext, encoded: string, overrides: FoldOptions = {}) {
const decoded = decodeReceiverChain(encoded);
expect(decoded).toBeDefined();
const model = createSemanticModel();
reconcileOwnership([ctx.fixture.parsed], model);
return foldReceiverChain(decoded!, ctx.inScope, ctx.fixture.scopes, ctx.fixture.index, {
fieldFallback: false,
lookupOwnedMethods: (owner, name) => model.methods.lookupAllByOwner(owner, name),
hoistTypeBindingsToModule: true,
elementTypeOf: ctx.fixture.resolver.elementTypeOf,
...overrides,
});
}
const fold = (encoded: string) => foldIn(ctx, encoded);
describe('foldReceiverChain', () => {
it('types a single call step through the method return type', () => {
expect(fold('2|svc|cgetUser')).toMatchObject({ qualifiedName: 'User', type: 'Class' });
});
it('types a mixed call/field chain, base-first', () => {
expect(fold('2|svc|cgetUser|faddress')).toMatchObject({
qualifiedName: 'Address',
type: 'Class',
});
});
it('types a step inherited through the MRO', () => {
expect(fold('2|svc|cinherited')).toMatchObject({ qualifiedName: 'User', type: 'Class' });
});
it('returns undefined when a step names no member of the previous class', () => {
expect(fold('2|svc|cgetUser|fnoSuchField')).toBeUndefined();
});
it('returns undefined when the base does not resolve', () => {
expect(fold('2|noSuchLocal|cgetUser')).toBeUndefined();
});
it('does not consult the field fallback', () => {
// `Holder` has no member `save` — only its field's TYPE does. The field
// fallback would walk Holder's fields, find `User.save` and answer: a
// guess, at O(fields x depth x names) per step. The fold declines.
expect(fold('2|holder|csave')).toBeUndefined();
});
it('declines a truncated chain even though the producer refuses to mint one', () => {
expect(fold('2|svc|cgetUser|~')).toBeUndefined();
});
it('declines a construction-selector step and leaves it to the cascade', () => {
// `Factory.new` denotes an INSTANCE of Factory, not the result of looking up
// a member named `new`. The cascade encodes that, together with the
// class-constant test that separates it from an instance method genuinely
// named `new`; a chain step records only a name, so the fold cannot make the
// distinction and must not try. Folding it turned a correct Ruby edge
// (`Factory.new.run` → `Factory#run`) into a wrong one (`Product.run`).
expect(foldIn(ctx, '2|svc|cnew', { constructionSyntax: { selector: 'new' } })).toBeUndefined();
});
it('does NOT climb to module scope when hoistTypeBindingsToModule is off', () => {
// The flag exists because TypeScript hoists a method's return-type binding
// OUT of the class body, so the fold must walk to Module scope to find it.
// Languages that do NOT hoist must not get that walk — climbing anyway is
// how an unrelated module-level binding of the same name gets picked up,
// which is exactly what the flag's own contract warns against. Same chain,
// opposite answers, so this pins the branch rather than the happy path.
expect(foldIn(ctx, '2|svc|cgetUser', { hoistTypeBindingsToModule: true })).toMatchObject({
qualifiedName: 'User',
});
expect(foldIn(ctx, '2|svc|cgetUser', { hoistTypeBindingsToModule: false })).toBeUndefined();
});
// `hoistedTypeBindingsRequireOwner` joins a hoisted binding to the member that
// declared it. `Service` declares `getUser`, so that binding joins. `inherited`
// is declared by `Base`, and this unit fixture builds no MRO, so the only way
// `Service` ever reached it was the name-keyed walk — which the toggle refuses
// and the default keeps (the pipeline reaches `Base` through the MRO instead).
it.each([
{ chain: '2|svc|cgetUser', requireOwner: true, expected: 'User' },
{ chain: '2|svc|cinherited', requireOwner: true, expected: undefined },
{ chain: '2|svc|cinherited', requireOwner: false, expected: 'User' },
])(
'folds $chain to $expected when hoistedTypeBindingsRequireOwner is $requireOwner',
({ chain, requireOwner, expected }) => {
const folded = foldIn(ctx, chain, { hoistedTypeBindingsRequireOwner: requireOwner });
expect(folded?.qualifiedName).toEqual(expected);
},
);
});
/**
* The `index` step. Every case here would have folded onto the CONTAINER before
* the step demanded positive evidence — `rawName` is `User` for both
* `repos: User[]` and `grid: Grid`, so identity could not tell an element from
* the thing that holds it.
*/
describe('foldReceiverChain — index step', () => {
it('declines a subscript on a non-container class whose member name collides with the element type', () => {
// `Grid` declares `[i: number]: Item` AND its own `run`. Identity kept the
// fold on `Grid`, so `grid[0].run()` emitted `Grid.run`; the element's owner
// is `Item`. The element type of a TypeScript index signature is not
// recorded anywhere the fold can read, so declining is the only sound
// answer — and it must never be the container.
expect(fold('2|grid|i')).toBeUndefined();
});
it('declines a subscript on a class that is not subscriptable at all', () => {
// `plain: Plain` reduces to nothing — `Plain` IS the written spelling — so
// there is no container evidence and `plain[0]` types to nothing. Identity
// answered `Plain`, which then owned every member looked up after it.
expect(fold('2|plain|i')).toBeUndefined();
});
it('resolves a genuine container whose spelling capture already reduced away', () => {
// `repos: User[]` binds to the bare `User`; only `declaredSpelling` still
// says `User[]`. This is the shape the feature exists for.
expect(fold('2|repos|i')).toMatchObject({ qualifiedName: 'User', type: 'Class' });
});
it('resolves a container spelling capture left intact', () => {
// A multi-arg generic survives TypeScript's capture-time normalization, so
// `rawName` IS the container here and the hook unwraps it to the value type.
expect(fold('2|byId|i')).toMatchObject({ qualifiedName: 'Item', type: 'Class' });
});
it('declines a nested container: ONE subscript leaves a container, not an element', () => {
// `nested: User[][]` reduces to the SAME `User` a single-level `User[]`
// produces — the strip loop runs to a fixed point. So one index step leaves
// `User[]`, and `nested[0].map(...)` is `Array.map`, never `User.map`.
// Identity answered `User` and handed the next member to the wrong owner.
expect(fold('2|nested|i')).toBeUndefined();
});
it('declines when the language answers no index route at all', () => {
// Twelve of the fourteen wired languages leave `elementTypeOf` undefined.
// They used to get identity — every index step in every one of them folded
// onto the container. Answering the route is now the price of index folding.
expect(foldIn(ctx, '2|repos|i', { elementTypeOf: undefined })).toBeUndefined();
});
it('declines when the hook names an element that binds to no class', () => {
expect(
foldIn(ctx, '2|repos|i', { elementTypeOf: () => 'NoSuchClassAnywhere' }),
).toBeUndefined();
});
it('declines an index step on a position that carries no declared type', () => {
// A static class-name base (`Service`) resolves to a def with NO type
// binding behind it, so there is no spelling to hand the hook.
expect(fold('2|Service|i')).toBeUndefined();
});
it('unwraps a container returned by a method, through the hoisted binding', () => {
// `getItems(): Item[]` — the return-type binding reduces to `Item` and only
// the spelling remembers `Item[]`. TypeScript hoists it out of the class
// body, so this also pins that `typeOfMemberOnClass` carries the spelling
// along the hoisted branch.
expect(fold('2|svc|cgetItems|i')).toMatchObject({ qualifiedName: 'Item', type: 'Class' });
});
it('treats await as identity, and does not require container evidence for it', () => {
// `getUserAsync(): Promise<User>` reduces to `User` at capture, and awaiting
// a non-thenable yields the value itself — both regimes agree, which is
// exactly why `await` may stay identity where `index` may not.
expect(fold('2|svc|cgetUserAsync|a')).toMatchObject({ qualifiedName: 'User', type: 'Class' });
});
});
/**
* P3: the hoisted branch of `typeOfMemberOnClass` returned `undefined` when a
* member's declared type named no class, while the primary branch deliberately
* carried the declared type forward for exactly that case. Ten languages set
* `hoistTypeBindingsToModule`, so the two branches disagreed about the same
* declared type depending only on where the binding happened to live.
*/
describe('foldReceiverChain — a member whose declared type names no class', () => {
it('unwraps it identically whether the binding is reached by base lookup or by the hoisted walk', () => {
// `Map<string, Item>` names no workspace class on either route.
expect(fold('2|byId|i')).toMatchObject({ qualifiedName: 'Item' });
expect(fold('2|svc|cgetMap|i')).toMatchObject({ qualifiedName: 'Item' });
});
it('still yields nothing when the chain ENDS on a type that named no class', () => {
// Carrying the declared type forward must not start answering with a class
// the position never had — only an unwrapping step may advance from here.
expect(fold('2|svc|cgetMap')).toBeUndefined();
expect(fold('2|svc|cgetMap|fnoSuchField')).toBeUndefined();
});
});
// ── C#: a real indexer, and the containers around it ────────────────────────
const CSHARP_SOURCE = `using System.Collections.Generic;
class Row {
public void Render() {}
}
class Table {
public Row this[int i] { get { return null; } }
public void Render() {}
}
class Cap {
void Entry(Table t, Dictionary<string, Row> rows, List<Row> items, Row bare) {
}
}
`;
const csFixture = buildScopeModel(csharpScopeResolver, CSHARP_SOURCE, 'main.cs');
// The parameter type bindings live in `Entry`'s own scope, so the fold must
// start there rather than at the module scope. Selected by the binding it
// must carry, not by position — every method body in the file is a Function
// scope and `Row.Render` comes first.
const csEntryScope = csFixture.parsed.scopes.find(
(s) =>
s.kind === 'Function' &&
csFixture.scopes.scopeTree.getScope(s.id)?.typeBindings.has('t') === true,
);
if (csEntryScope === undefined) throw new Error('no C# scope binding `t`');
const csCtx: FoldContext = { fixture: csFixture, inScope: csEntryScope.id as ScopeId };
describe('foldReceiverChain — C# indexer vs C# containers', () => {
it('declines a subscript on a class that declares an indexer', () => {
// `Table` has `public Row this[int i]` AND its own `Render`. `t[0].Render()`
// is `Row.Render`; identity made it `Table.Render`.
expect(foldIn(csCtx, '2|t|i')).toBeUndefined();
});
it('declines a subscript on a class with neither indexer nor container spelling', () => {
expect(foldIn(csCtx, '2|bare|i')).toBeUndefined();
});
it('resolves a dictionary subscript to the VALUE type', () => {
expect(foldIn(csCtx, '2|rows|i')).toMatchObject({ qualifiedName: 'Row', type: 'Class' });
});
it('resolves a list subscript whose spelling capture reduced away', () => {
// C#'s `stripGeneric` collapses `List<Row>` to `Row` at capture, so this
// cell depends entirely on the retained spelling.
expect(foldIn(csCtx, '2|items|i')).toMatchObject({ qualifiedName: 'Row', type: 'Class' });
});
});