GitNexus/gitnexus/test/unit/scope-resolution/overload-narrowing.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

282 lines
12 KiB
TypeScript

/**
* Unit tests for `narrowOverloadCandidates` — the shared overload-
* narrowing utility used by `receiver-bound-calls.ts::pickOverload`
* (explicit receiver member call) and
* `free-call-fallback.ts::pickImplicitThisOverload` (implicit-`this`
* free call).
*
* The utility is pure (data in / data out), so tests build synthetic
* `SymbolDefinition` stubs — no fixtures, no pipeline.
*/
import { describe, it, expect } from 'vitest';
import type { SymbolDefinition } from 'gitnexus-shared';
import { narrowOverloadCandidates } from '../../../src/core/ingestion/scope-resolution/passes/overload-narrowing.js';
const mkDef = (overrides: Partial<SymbolDefinition> & { nodeId: string }): SymbolDefinition => ({
nodeId: overrides.nodeId,
filePath: overrides.filePath ?? 'x.cs',
type: overrides.type ?? 'Method',
...overrides,
});
describe('narrowOverloadCandidates — empty input', () => {
it('returns empty output for empty overload list', () => {
expect(narrowOverloadCandidates([], 1, ['int'])).toEqual([]);
expect(narrowOverloadCandidates([], undefined, undefined)).toEqual([]);
});
});
describe('narrowOverloadCandidates — definitive block declaration conversions', () => {
const prototype = mkDef({
nodeId: 'record:int',
type: 'Function',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['int'],
});
const conversionRankFn = (argument: string, parameter: string) =>
argument === parameter ? 0 : Number.POSITIVE_INFINITY;
it('rejects a known incompatible local prototype only when requested', () => {
expect(narrowOverloadCandidates([prototype], 1, ['Event'], { conversionRankFn })).toEqual([
prototype,
]);
expect(
narrowOverloadCandidates([prototype], 1, ['Event'], {
conversionRankFn,
incompatibleConversionsAreFinal: true,
}),
).toEqual([]);
});
it('preserves candidates when argument or parameter metadata is unknown', () => {
const unknown = { ...prototype, parameterTypes: undefined };
const hooks = { conversionRankFn, incompatibleConversionsAreFinal: true };
expect(narrowOverloadCandidates([prototype], 1, [''], hooks)).toEqual([prototype]);
expect(narrowOverloadCandidates([unknown], 1, ['Event'], hooks)).toEqual([unknown]);
});
});
describe('narrowOverloadCandidates — arity filtering', () => {
const add1 = mkDef({ nodeId: 'add:1', parameterCount: 1, requiredParameterCount: 1 });
const add2 = mkDef({ nodeId: 'add:2', parameterCount: 2, requiredParameterCount: 2 });
const add3 = mkDef({ nodeId: 'add:3', parameterCount: 3, requiredParameterCount: 3 });
it('passes all overloads through when argCount is undefined', () => {
const result = narrowOverloadCandidates([add1, add2, add3], undefined, undefined);
expect(result.map((d) => d.nodeId)).toEqual(['add:1', 'add:2', 'add:3']);
});
it('filters out overloads whose max is below argCount (non-variadic)', () => {
const result = narrowOverloadCandidates([add1, add2, add3], 2, undefined);
expect(result.map((d) => d.nodeId)).toEqual(['add:2']);
});
it('filters out overloads whose required-count exceeds argCount', () => {
const result = narrowOverloadCandidates([add1, add2, add3], 1, undefined);
expect(result.map((d) => d.nodeId)).toEqual(['add:1']);
});
it('accepts argCount above max when `params` variadic marker is present', () => {
const writeLine = mkDef({
nodeId: 'wl:1',
parameterCount: 2,
requiredParameterCount: 1,
parameterTypes: ['string', 'params object[]'],
});
const result = narrowOverloadCandidates([writeLine], 5, undefined);
expect(result.map((d) => d.nodeId)).toEqual(['wl:1']);
});
it('accepts argCount above max when bare `params` marker is present', () => {
const variadic = mkDef({
nodeId: 'v:1',
parameterCount: 1,
requiredParameterCount: 0,
parameterTypes: ['params'],
});
const result = narrowOverloadCandidates([variadic], 4, undefined);
expect(result.map((d) => d.nodeId)).toEqual(['v:1']);
});
it('returns empty when arity filter empties the set AND every candidate had definite bounds', () => {
// argCount=5 doesn't match any overload (none variadic, all have max < 5).
// Post-commit af9af4a9 (PR #1497 / U1): the empty result is now authoritative
// because every rejected candidate had defined `parameterCount` /
// `requiredParameterCount`. The old "always fall back to full list" rescue
// was deliberately removed so resolvers actually drop calls that are
// definitively arity-incompatible (e.g., PHP `f(int $req, ...$rest)`
// called with zero args).
const result = narrowOverloadCandidates([add1, add2, add3], 5, undefined);
expect(result.map((d) => d.nodeId)).toEqual([]);
});
// Note: the `anyUnknownBounds ? overloads : []` branch in
// narrowOverloadCandidates is structurally unreachable in this caller's
// shape — a candidate with both `parameterCount` and `requiredParameterCount`
// undefined always passes the arity filter (neither `argCount > max` nor
// `argCount < min` can fire), so `arityMatches.length` is always > 0
// whenever `anyUnknownBounds` is true. The branch is preserved in the
// source as a defensive guard for future refactors that might add
// additional rejection criteria in the filter.
});
describe('narrowOverloadCandidates — type narrowing', () => {
const byInt = mkDef({
nodeId: 'm:int',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['int'],
});
const byString = mkDef({
nodeId: 'm:string',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['string'],
});
it('picks the overload whose parameterTypes[i] equals argTypes[i]', () => {
const result = narrowOverloadCandidates([byInt, byString], 1, ['string']);
expect(result.map((d) => d.nodeId)).toEqual(['m:string']);
});
it('treats empty-string argTypes slot as "unknown" and matches every candidate', () => {
const result = narrowOverloadCandidates([byInt, byString], 1, ['']);
// Both candidates survive because "" is an unknown slot.
expect(result.map((d) => d.nodeId).sort()).toEqual(['m:int', 'm:string']);
});
it('retains an unknown parameter slot alongside an exact typed match', () => {
const unknown = { ...byInt, nodeId: 'm:unknown', parameterTypes: [''] };
const result = narrowOverloadCandidates([byInt, unknown, byString], 1, ['int']);
expect(result.map((d) => d.nodeId)).toEqual(['m:int', 'm:unknown']);
});
it('does not let an unknown parameter slot hide a viable conversion overload', () => {
const unknown = { ...byInt, nodeId: 'm:unknown', parameterTypes: [''] };
const byLong = { ...byInt, nodeId: 'm:long', parameterTypes: ['long'] };
const result = narrowOverloadCandidates([unknown, byLong], 1, ['int'], {
conversionRankFn: (argument, parameter) =>
argument === parameter ? 0 : argument === 'int' && parameter === 'long' ? 1 : Infinity,
});
expect(result.map((d) => d.nodeId)).toEqual(['m:unknown', 'm:long']);
});
it('keeps exact known-slot requirements when an exact overload exists', () => {
const exact = mkDef({
nodeId: 'm:exact',
parameterCount: 2,
requiredParameterCount: 2,
parameterTypes: ['int', 'long'],
});
const partial = { ...exact, nodeId: 'm:partial', parameterTypes: ['', 'double'] };
const result = narrowOverloadCandidates([exact, partial], 2, ['int', 'long'], {
conversionRankFn: (argument, parameter) =>
argument === parameter ? 0 : argument === 'long' && parameter === 'double' ? 1 : Infinity,
});
expect(result.map((d) => d.nodeId)).toEqual(['m:exact']);
});
it.each([
{ parameterTypes: ['', 'bool'], expected: ['m:exact', 'm:partial'] },
{ parameterTypes: ['', 'string'], expected: ['m:exact'] },
{ parameterTypes: ['string', ''], expected: ['m:exact'] },
])(
'keeps positional unknown slots without ignoring known mismatches: $parameterTypes',
({ parameterTypes, expected }) => {
const exact = mkDef({
nodeId: 'm:exact',
parameterCount: 2,
requiredParameterCount: 2,
parameterTypes: ['int', 'bool'],
});
const partial = { ...exact, nodeId: 'm:partial', parameterTypes };
const result = narrowOverloadCandidates([exact, partial], 2, ['int', 'bool']);
expect(result.map((d) => d.nodeId)).toEqual(expected);
},
);
it('falls through to arity-filtered candidates when type filter matches nothing', () => {
const result = narrowOverloadCandidates([byInt, byString], 1, ['bool']);
// Type mismatch against both — falls back to arity candidates.
expect(result.map((d) => d.nodeId).sort()).toEqual(['m:int', 'm:string']);
});
it('skips the type filter entirely when argTypes is undefined', () => {
const result = narrowOverloadCandidates([byInt, byString], 1, undefined);
expect(result.map((d) => d.nodeId).sort()).toEqual(['m:int', 'm:string']);
});
it('skips the type filter entirely when argTypes is empty', () => {
const result = narrowOverloadCandidates([byInt, byString], 1, []);
expect(result.map((d) => d.nodeId).sort()).toEqual(['m:int', 'm:string']);
});
it('disqualifies an overload with missing parameterTypes under type filter', () => {
const noTypes = mkDef({
nodeId: 'm:notypes',
parameterCount: 1,
requiredParameterCount: 1,
});
const result = narrowOverloadCandidates([byInt, noTypes], 1, ['int']);
expect(result.map((d) => d.nodeId)).toEqual(['m:int']);
});
});
describe('narrowOverloadCandidates — constraint filter monotonicity (issue #1579)', () => {
// Language-agnostic contract: when `constraintCompatibility` returns
// 'unknown' for every candidate, the filter must keep every candidate.
// Adding a predicate to the registry can only narrow correctly, never
// produce a wrong edge — this guarantees the worst-case behavior is
// today's "degrade not lie" suppression, not a regression.
const a = mkDef({
nodeId: 'a',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['T'],
templateConstraints: { dummy: true },
});
const b = mkDef({
nodeId: 'b',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['T'],
templateConstraints: { dummy: true },
});
it('keeps every candidate when constraintCompatibility returns unknown for all', () => {
const result = narrowOverloadCandidates([a, b], 1, ['int'], {
constraintCompatibility: () => 'unknown',
});
expect(result.map((d) => d.nodeId).sort()).toEqual(['a', 'b']);
});
it('drops only candidates the hook explicitly marks incompatible', () => {
const result = narrowOverloadCandidates([a, b], 1, ['int'], {
constraintCompatibility: (_callsite, def) =>
def.nodeId === 'a' ? 'incompatible' : 'compatible',
});
expect(result.map((d) => d.nodeId)).toEqual(['b']);
});
it('skips the constraint filter when hookCtx is omitted (pre-#1579 behavior preserved)', () => {
const result = narrowOverloadCandidates([a, b], 1, ['int']);
expect(result.map((d) => d.nodeId).sort()).toEqual(['a', 'b']);
});
it('skips the constraint filter for candidates without templateConstraints', () => {
const plain = mkDef({
nodeId: 'plain',
parameterCount: 1,
requiredParameterCount: 1,
parameterTypes: ['T'],
});
// Even though the hook would return 'incompatible' for everything, the
// candidate has no templateConstraints so the filter doesn't consult it.
const result = narrowOverloadCandidates([plain], 1, ['int'], {
constraintCompatibility: () => 'incompatible',
});
expect(result.map((d) => d.nodeId)).toEqual(['plain']);
});
});