GitNexus/gitnexus/test/unit/scope-resolution/resolve-same-namespace-inheritance-base.test.ts
Abhigyan Patwari c30449394b
fix(scope): bind same-package inheritance bases when the simple name is reused elsewhere (#3659)
* fix(scope): bind same-namespace inheritance bases before sibling visibility exists

Cause: same-package / same-namespace visibility (`populateNamespaceSiblings`)
is populated after the inheritance pre-pass and `buildMro`. A base written
without an import (`class C extends B`, B in another file of the package)
could bind only through the workspace-unique simple-name fallback, which any
other package declaring a `B` defeats: no EXTENDS edge, an empty MRO, and
lost calls through inherited members. In the combined lang-resolution corpus
`java-grandparent-resolution` `c.greet().save()` dropped because
`java-unrelated-method-collision` declares default-package A and B.

Moving the sibling hook ahead of the pre-pass was measured and rejected. It
retargeted correct edges and minted wrong ones, because the sibling channels
carry candidates the pre-pass must not see: C# global-namespace types are
consulted at every scope (same-file `Cat : Animal` bound another fixture's
global Animal), namespace buckets merge across source roots with no
proximity order (PHP, C#), and a qualified `extends app.base.Box` bound
through a same-package `app.Box`.

Fix: an optional `ScopeResolver.resolveImplicitInheritanceBase`, consulted by
the pre-pass only when the shared chain bound nothing, the base was written
bare (no qualifier, name capture at the start of the base expression), and
no import claims the name. It adds edges and never retargets one.
`resolveSameNamespaceInheritanceBase` picks the candidate in the deriving
class's namespace, nearest by shared path prefix, refusing a tie. Java and
Kotlin answer from their package facts, C# from the exact `namespacePrefix`.

Corpus A/B (main vs this, same corpus): EXTENDS/IMPLEMENTS +42, all within
their own fixture, 0 removed. CALLS: six `super.save()` edges keep their
target but are now MRO-dispatched (`global`, as in isolation), one moves off
another fixture's BaseModel.Save onto its own, and 7 are new (both
grandparent `greet` calls, a default-method `validate`, the new fixtures).
Receiver bench: call drops 128 -> 127, all kinds 192 -> 191, shape arm
unchanged. Scope-capture fingerprints re-baselined for the added fixtures
only (parked, --check passes on the old ones).

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

* fix(java): resolve a duplicated package+type import to the importer's own root

Cause: `buildJavaPackageIndex` kept the first file declaring each
package+type. One repository can hold several build modules or sample
projects that each declare `models.User`, so every `import models.User;`
bound whichever copy was parsed first, a wrong IMPORTS edge at full
confidence that carries the receiver types behind it. In the combined
lang-resolution corpus 24 fixtures declare `models.User`, and e.g.
`java-heritage` UserService.processUser called
`java-assignment-chain/models/User.save`.

Fix: the index keeps every declaring file in a sparse `duplicateTypes` map
(only colliding pairs, so a normal workspace pays nothing), and a type import
resolves to the declaring file sharing the longest leading path with the
importer (its own module or source root). A tie, or an unknown importer,
refuses rather than guessing. Wildcard imports are unchanged.

Corpus A/B (previous commit vs this, same corpus): 40 CALLS edges that
crossed into another fixture's User/Repo/Address/UserService are gone, 55
CALLS/ACCESSES edges now land in their own fixture (0 cross-fixture), and
`java-parent-resolution` User IMPLEMENTS Serializable moves off
`java-heritage` onto its own interface. Receiver-unresolved drops unchanged;
import-target and receiver benches pass. Scope-capture java fingerprint
re-baselined for the added fixture only (parked, --check passes on the old
one).

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

* fix(scope): respect base candidate visibility

* fix(scope): match written JVM base arity

---------

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

97 lines
4.1 KiB
TypeScript

/**
* Unit coverage for `resolveSameNamespaceInheritanceBase`, the shared body of
* `ScopeResolver.resolveImplicitInheritanceBase`. The inheritance pre-pass runs
* before same-namespace sibling bindings exist, so this is what binds
* `class C extends B` to the `B` of C's own namespace when another namespace
* also declares a `B`. Rules pinned here:
*
* - only candidates sharing the deriving class's namespace count
* - an unknown namespace (deriving class or candidate) never matches
* - several same-namespace candidates: nearest by shared leading path
* segments wins, a tie at that distance refuses
* - the deriving class itself and non-class-like defs are never answers
*
* Drives the function through a minimal cast `ScopeResolutionIndexes` (only
* `qualifiedNames` / `defs`, the accessors it reads).
*/
import { describe, it, expect } from 'vitest';
import type { SymbolDefinition } from 'gitnexus-shared';
import { resolveSameNamespaceInheritanceBase } from '../../../src/core/ingestion/scope-resolution/scope/walkers.js';
import type { ScopeResolutionIndexes } from '../../../src/core/ingestion/model/scope-resolution-indexes.js';
const BASE = 'B';
const DERIVING_FILE = 'app/src/main/java/com/acme/core/C.java';
interface Candidate {
readonly nodeId: string;
readonly filePath: string;
readonly type?: string;
}
/** `filePath -> namespace`; a path missing from the table has no known namespace. */
const NAMESPACES: Readonly<Record<string, string>> = {
[DERIVING_FILE]: 'com.acme.core',
'app/src/main/java/com/acme/core/B.java': 'com.acme.core',
'app/src/test/java/com/acme/core/B.java': 'com.acme.core',
'lib/src/main/java/com/acme/core/B.java': 'com.acme.core',
'tools/src/main/java/com/acme/core/B.java': 'com.acme.core',
'app/src/main/java/com/acme/legacy/B.java': 'com.acme.legacy',
};
function resolve(
candidates: readonly Candidate[],
derivingFile = DERIVING_FILE,
): string | undefined {
const defs = new Map<string, SymbolDefinition>();
for (const c of candidates) {
defs.set(c.nodeId, {
nodeId: c.nodeId,
filePath: c.filePath,
type: c.type ?? 'Class',
} as SymbolDefinition);
}
const ids = candidates.map((c) => c.nodeId);
const scopes = {
qualifiedNames: { get: (name: string) => (name === BASE ? ids : []) },
defs: { get: (id: string) => defs.get(id) },
} as unknown as ScopeResolutionIndexes;
const deriving = { nodeId: 'd:self', filePath: derivingFile, type: 'Class' } as SymbolDefinition;
return resolveSameNamespaceInheritanceBase(
BASE,
deriving,
scopes,
(def) => NAMESPACES[def.filePath],
)?.nodeId;
}
const CORE_B = { nodeId: 'd:core', filePath: 'app/src/main/java/com/acme/core/B.java' };
const LEGACY_B = { nodeId: 'd:legacy', filePath: 'app/src/main/java/com/acme/legacy/B.java' };
const TEST_ROOT_B = { nodeId: 'd:test', filePath: 'app/src/test/java/com/acme/core/B.java' };
const LIB_B = { nodeId: 'd:lib', filePath: 'lib/src/main/java/com/acme/core/B.java' };
const TOOLS_B = { nodeId: 'd:tools', filePath: 'tools/src/main/java/com/acme/core/B.java' };
describe('resolveSameNamespaceInheritanceBase', () => {
it.each<[string, readonly Candidate[], string | undefined]>([
['binds the one candidate in its own namespace', [LEGACY_B, CORE_B], 'd:core'],
['declines when no candidate shares its namespace', [LEGACY_B], undefined],
['prefers the nearest of several same-namespace candidates', [LIB_B, TEST_ROOT_B], 'd:test'],
['refuses a tie at the nearest distance', [LIB_B, TOOLS_B], undefined],
[
'never answers with a candidate whose namespace is unknown',
[{ nodeId: 'd:unknown', filePath: 'gen/B.java' }],
undefined,
],
[
'never answers with the deriving class itself',
[{ nodeId: 'd:self', filePath: DERIVING_FILE }],
undefined,
],
['ignores a non-class-like def', [{ ...CORE_B, type: 'Method' }], undefined],
])('%s', (_title, candidates, expected) => {
expect(resolve(candidates)).toBe(expected);
});
it('declines when the deriving class has no known namespace', () => {
expect(resolve([CORE_B], 'gen/C.java')).toBeUndefined();
});
});