mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* docs(plans): add Java overload repair plan * fix(java): resolve overloads by JLS phases Select complete overload families before shared pruning so strict, loose and variable-arity applicability preserve Java call targets. Keep unsupported or ambiguous families terminal and persist their omission boundaries so impact counts cannot imply complete coverage. Preserve declared return types, synthetic members and bounded runtime dispatch. Memoize inheritance walks to avoid exponential diamond work. Fixes #3789 * refactor(java): simplify overload capture paths Reuse record accessor captures and require suppression identity context. Remove redundant cache-layout assertions and test-history comments. Populate real overload receipts in the accuracy fixture so its exact control matches the production metadata contract. * docs: remove implementation plan from PR Exclude the planning document from the published change. * fix(java): honor enclosing protected access * docs(mcp): qualify overload coverage (#3791) * perf(java): bound overload ingestion costs Index method facts and lexical bindings, and avoid repeated native child and callable-definition scans. Add measured cold, warm, and edited scaling checks at 128, 512, and 2048 units. Refs #3789 * refactor(java): simplify overload lookup state Index diagnostic candidates once to bound lookup work linearly, preserving scope and first-match precedence. Keep local bindings out of the field index and remove redundant metadata. Refs #3789 * fix(java): correct replay diagnostics and CI Repeated impact queries exhausted the persistence test's 128 MiB buffer pool. Give the reader 512 MiB and reject partial results before checking callers. Coalesce receiver replay diagnostics by full source-site identity while compacting resolved drops in one linear pass. This removes 51 duplicate receipts without merging distinct calls at the same start position. Refresh the Java capture fingerprints after attributing every difference to return types, var initializers, and seven new fixture files. Keep the 1.5 scaling budget. Receiver calls move 140 -> 141: two new fixture sites and one existing chain newly resolved. Shape states are unchanged; origin counts reflect selected return types instead of earlier guesses. Refs #3789 * ci(java): enforce overload scaling benchmark Run the 54-analysis correctness and scaling check in the existing scope-resolution benchmark job. Upload its report with that job's measurements so regressions fail CI instead of relying on manual runs. Refs #3789 * test(java): clarify overload coverage (#3791) Separate unmodeled call-argument coverage from Java accessibility and confirm the accessible Object overload with an executed javac oracle. Give incomplete-attribution cases distinct titles: JSON formatting drops undefined properties and made three test identities collide in CI. * perf(scope): skip unmatched value names Reject impossible callable names before parsing definition positions or allocating positional keys. Keep the exact file/line/name admission and ambiguity rules unchanged. The callable-value-flow benchmark overhead drops from 1.747-1.883 locally to 1.210-1.271, below the unchanged 1.9 budget. Target fingerprints and cardinalities are identical. Refs #3791 * fix(java): resolve types from static imports Map package-qualified model names to scope-index keys before resolving explicit static member-type imports. Preserve uncertainty for missing or conflicting imports. Verify Number selection after boxing long and preserve the imported source type identity, with an executed javac oracle for both targets. Refs #3791 --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
437 lines
14 KiB
TypeScript
437 lines
14 KiB
TypeScript
import { afterEach, describe, expect, it } from 'vitest';
|
|
import {
|
|
buildDefIndex,
|
|
buildMethodDispatchIndex,
|
|
buildQualifiedNameIndex,
|
|
buildScopeTree,
|
|
type Range,
|
|
type Scope,
|
|
type SymbolDefinition,
|
|
} from 'gitnexus-shared';
|
|
import { createSemanticModel } from '../../../../src/core/ingestion/model/semantic-model.js';
|
|
import type { ScopeResolutionIndexes } from '../../../../src/core/ingestion/model/scope-resolution-indexes.js';
|
|
import {
|
|
captureJavaOverloadFacts,
|
|
clearJavaOverloadFacts,
|
|
setJavaOverloadFacts,
|
|
} from '../../../../src/core/ingestion/languages/java/overload-argument-facts.js';
|
|
import { resolveJavaReceiverMember } from '../../../../src/core/ingestion/languages/java/overload-resolution.js';
|
|
import { getJavaParser } from '../../../../src/core/ingestion/languages/java/query.js';
|
|
|
|
function resolveSynthetic(
|
|
signatures: readonly { count: number; types?: readonly string[] }[],
|
|
arity = 1,
|
|
) {
|
|
const filePath = 'Synthetic.java';
|
|
const range: Range = { startLine: 1, startCol: 0, endLine: 10, endCol: 0 };
|
|
const atRange: Range = { startLine: 5, startCol: 0, endLine: 5, endCol: 12 };
|
|
const owner: SymbolDefinition = {
|
|
nodeId: 'Class:Synthetic.java:Pair',
|
|
filePath,
|
|
type: 'Class',
|
|
qualifiedName: 'Pair',
|
|
declarationRange: range,
|
|
};
|
|
const methods: SymbolDefinition[] = signatures.map((signature, index) => ({
|
|
nodeId: `Method:Synthetic.java:Pair.setValue#${index}`,
|
|
filePath,
|
|
type: 'Method',
|
|
ownerId: owner.nodeId,
|
|
qualifiedName: 'Pair.setValue',
|
|
parameterCount: signature.count,
|
|
parameterTypes: signature.types === undefined ? undefined : [...signature.types],
|
|
isSynthetic: true,
|
|
}));
|
|
const classScope: Scope = {
|
|
id: 'class',
|
|
kind: 'Class',
|
|
parent: 'module',
|
|
filePath,
|
|
range,
|
|
ownedDefs: [owner, ...methods],
|
|
imports: [],
|
|
bindings: new Map(),
|
|
typeBindings: new Map(),
|
|
};
|
|
const moduleScope: Scope = {
|
|
...classScope,
|
|
id: 'module',
|
|
kind: 'Module',
|
|
parent: null,
|
|
ownedDefs: [],
|
|
};
|
|
const definitions = [owner, ...methods];
|
|
const scopes = {
|
|
scopeTree: buildScopeTree([moduleScope, classScope]),
|
|
defs: buildDefIndex(definitions),
|
|
qualifiedNames: buildQualifiedNameIndex(definitions),
|
|
methodDispatch: buildMethodDispatchIndex({
|
|
owners: [owner.nodeId],
|
|
computeMro: () => [],
|
|
implementsOf: () => [],
|
|
}),
|
|
} as ScopeResolutionIndexes;
|
|
const model = createSemanticModel();
|
|
for (const method of methods) model.methods.register(owner.nodeId, 'setValue', method);
|
|
setJavaOverloadFacts(filePath, {
|
|
version: 1,
|
|
packageName: '',
|
|
imports: [],
|
|
types: [
|
|
{
|
|
name: 'Pair',
|
|
simpleName: 'Pair',
|
|
kind: 'class_declaration',
|
|
range,
|
|
visible: range,
|
|
bases: [],
|
|
typeParameters: [],
|
|
},
|
|
],
|
|
methods: [],
|
|
calls: [
|
|
{
|
|
name: 'setValue',
|
|
range: atRange,
|
|
arguments: Array.from({ length: arity }, () => ({
|
|
kind: 'typed',
|
|
spelling: 'int',
|
|
at: atRange,
|
|
})),
|
|
receiverIsValue: true,
|
|
staticContext: false,
|
|
},
|
|
],
|
|
});
|
|
return resolveJavaReceiverMember(
|
|
owner,
|
|
'setValue',
|
|
{ inScope: classScope.id, kind: 'call', callForm: 'member', name: 'setValue', atRange, arity },
|
|
scopes,
|
|
model,
|
|
);
|
|
}
|
|
|
|
function hierarchyFixture(
|
|
declarations: readonly string[],
|
|
bases: readonly string[],
|
|
conversion?: {
|
|
argumentType: string;
|
|
parameterTypes: readonly [string, string];
|
|
},
|
|
) {
|
|
const filePath = 'Hierarchy.java';
|
|
const parameterTypes = conversion?.parameterTypes ?? ['Long', 'String'];
|
|
const source = `${declarations.join('\n')}
|
|
class Owner ${bases.length === 0 ? '' : `implements ${bases.join(', ')}`} {
|
|
public void pick(${parameterTypes[0]} value) {}
|
|
public void pick(${parameterTypes[1]} value) {}
|
|
void run(${conversion === undefined ? '' : `${conversion.argumentType} value`}) {
|
|
pick(${conversion === undefined ? '1L' : 'value'});
|
|
}
|
|
}`;
|
|
const facts = captureJavaOverloadFacts(getJavaParser().parse(source).rootNode)!;
|
|
let baseReads = 0;
|
|
for (const type of facts.types) {
|
|
const declaredBases = type.bases;
|
|
Object.defineProperty(type, 'bases', {
|
|
get() {
|
|
baseReads++;
|
|
return declaredBases;
|
|
},
|
|
});
|
|
}
|
|
const owners: SymbolDefinition[] = facts.types.map((type) => ({
|
|
nodeId: `${type.kind === 'interface_declaration' ? 'Interface' : 'Class'}:${filePath}:${type.name}`,
|
|
filePath,
|
|
type: type.kind === 'interface_declaration' ? 'Interface' : 'Class',
|
|
qualifiedName: type.name,
|
|
declarationRange: type.range,
|
|
}));
|
|
const owner = owners.find((definition) => definition.qualifiedName === 'Owner')!;
|
|
const methods: SymbolDefinition[] = facts.methods
|
|
.filter((method) => method.name === 'pick')
|
|
.map((method, index) => ({
|
|
nodeId: `Method:${filePath}:Owner.pick#${index}`,
|
|
filePath,
|
|
type: 'Method',
|
|
ownerId: owner.nodeId,
|
|
qualifiedName: 'Owner.pick',
|
|
declarationRange: method.range,
|
|
parameterCount: method.parameterTypes.length,
|
|
parameterTypes: [...method.parameterTypes],
|
|
}));
|
|
const classScope: Scope = {
|
|
id: 'class',
|
|
kind: 'Class',
|
|
parent: 'module',
|
|
filePath,
|
|
range: owner.declarationRange!,
|
|
ownedDefs: [owner, ...methods],
|
|
imports: [],
|
|
bindings: new Map(),
|
|
typeBindings: new Map(),
|
|
};
|
|
const moduleScope: Scope = { ...classScope, id: 'module', kind: 'Module', parent: null };
|
|
const definitions = [...owners, ...methods];
|
|
const scopes = {
|
|
scopeTree: buildScopeTree([moduleScope, classScope]),
|
|
defs: buildDefIndex(definitions),
|
|
qualifiedNames: buildQualifiedNameIndex(definitions),
|
|
// Only Owner declares methods. The captured bases supply the independent
|
|
// hierarchy-completeness proof; no inherited-member lookup is needed.
|
|
methodDispatch: buildMethodDispatchIndex({
|
|
owners: owners.map((definition) => definition.nodeId),
|
|
computeMro: () => [],
|
|
implementsOf: () => [],
|
|
}),
|
|
} as ScopeResolutionIndexes;
|
|
const model = createSemanticModel();
|
|
for (const method of methods) model.methods.register(owner.nodeId, 'pick', method);
|
|
setJavaOverloadFacts(filePath, facts);
|
|
const call = facts.calls.find((site) => site.name === 'pick')!;
|
|
return {
|
|
baseReads: () => baseReads,
|
|
resolve: () =>
|
|
resolveJavaReceiverMember(
|
|
owner,
|
|
'pick',
|
|
{
|
|
inScope: classScope.id,
|
|
kind: 'call',
|
|
callForm: 'member',
|
|
name: 'pick',
|
|
atRange: call.range,
|
|
arity: 1,
|
|
},
|
|
scopes,
|
|
model,
|
|
),
|
|
};
|
|
}
|
|
|
|
afterEach(clearJavaOverloadFacts);
|
|
|
|
describe('Java overload fact lookup work', () => {
|
|
it.each(['none', 'method', 'nested'])(
|
|
'bounds declaration reads across independent families (generics=%s)',
|
|
(generics) => {
|
|
const size = 64;
|
|
const generic = generics !== 'none';
|
|
const filePath = 'Wide.java';
|
|
const source = `class Wide${generics === 'nested' ? '<String>' : ''} { ${Array.from(
|
|
{ length: size },
|
|
(_, i) => `
|
|
void pick${i}(Object value) {}
|
|
void pick${i}(String value) {}
|
|
${generic ? '<String>' : ''} void run${i}(${generic ? 'String value' : ''}) { pick${i}(${generic ? 'value' : '"text"'}); }
|
|
`,
|
|
).join('\n')} }`;
|
|
const facts = captureJavaOverloadFacts(getJavaParser().parse(source).rootNode)!;
|
|
const owner: SymbolDefinition = {
|
|
nodeId: `Class:${filePath}:Wide`,
|
|
filePath,
|
|
type: 'Class',
|
|
qualifiedName: 'Wide',
|
|
declarationRange: facts.types[0]!.range,
|
|
};
|
|
const methods: SymbolDefinition[] = facts.methods
|
|
.filter((fact) => fact.name.startsWith('pick'))
|
|
.map((fact) => ({
|
|
nodeId: `Method:${filePath}:Wide.${fact.name}#1~${fact.parameterTypes[0]}`,
|
|
filePath,
|
|
type: 'Method',
|
|
ownerId: owner.nodeId,
|
|
qualifiedName: `Wide.${fact.name}`,
|
|
declarationRange: fact.range,
|
|
parameterCount: 1,
|
|
parameterTypes: [...fact.parameterTypes],
|
|
}));
|
|
const classScope: Scope = {
|
|
id: 'class',
|
|
kind: 'Class',
|
|
parent: 'module',
|
|
filePath,
|
|
range: owner.declarationRange!,
|
|
ownedDefs: [owner, ...methods],
|
|
imports: [],
|
|
bindings: new Map(),
|
|
typeBindings: new Map(),
|
|
};
|
|
const definitions = [owner, ...methods];
|
|
const scopes = {
|
|
scopeTree: buildScopeTree([
|
|
{ ...classScope, id: 'module', kind: 'Module', parent: null },
|
|
classScope,
|
|
]),
|
|
defs: buildDefIndex(definitions),
|
|
qualifiedNames: buildQualifiedNameIndex(definitions),
|
|
methodDispatch: buildMethodDispatchIndex({
|
|
owners: [owner.nodeId],
|
|
computeMro: () => [],
|
|
implementsOf: () => [],
|
|
}),
|
|
} as ScopeResolutionIndexes;
|
|
const model = createSemanticModel();
|
|
for (const method of methods)
|
|
model.methods.register(owner.nodeId, method.qualifiedName!.split('.')[1]!, method);
|
|
setJavaOverloadFacts(filePath, facts);
|
|
let reads = 0;
|
|
for (const fact of facts.methods)
|
|
for (const key of ['name', 'range', 'typeParameters'] as const) {
|
|
const value = fact[key];
|
|
Object.defineProperty(fact, key, {
|
|
get() {
|
|
reads++;
|
|
return value;
|
|
},
|
|
});
|
|
}
|
|
for (const call of facts.calls) {
|
|
expect(
|
|
resolveJavaReceiverMember(
|
|
owner,
|
|
call.name,
|
|
{
|
|
inScope: 'class',
|
|
kind: 'call',
|
|
callForm: 'member',
|
|
name: call.name,
|
|
atRange: call.range,
|
|
arity: 1,
|
|
},
|
|
scopes,
|
|
model,
|
|
),
|
|
).toMatchObject(
|
|
generic
|
|
? { kind: 'unknown' }
|
|
: { kind: 'resolved', definition: { parameterTypes: ['String'] } },
|
|
);
|
|
}
|
|
expect(reads).toBeLessThanOrEqual(facts.methods.length * 20);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe('Java overload families with synthetic signature metadata', () => {
|
|
it.each([
|
|
{ label: 'missing', types: undefined },
|
|
{ label: 'empty', types: [] },
|
|
{ label: 'inconsistent', types: ['int', 'int'] },
|
|
])(
|
|
'retains singleton compatibility with $label types for one declared parameter',
|
|
({ types }) => {
|
|
expect(resolveSynthetic([{ count: 1, types }])).toBeUndefined();
|
|
},
|
|
);
|
|
|
|
it('keeps an overloaded family unknown when one formal signature is unavailable', () => {
|
|
expect(resolveSynthetic([{ count: 1 }, { count: 1, types: ['int'] }])).toMatchObject({
|
|
kind: 'unknown',
|
|
candidateSetComplete: true,
|
|
});
|
|
});
|
|
|
|
it('still rejects a call whose arity differs from the known declaration arity', () => {
|
|
expect(resolveSynthetic([{ count: 1 }], 0)).toMatchObject({ kind: 'inapplicable' });
|
|
});
|
|
});
|
|
|
|
describe('Java inherited overload inventory bounds', () => {
|
|
it.each([12, 16])(
|
|
'checks a depth-%i diamond without expanding every inheritance path',
|
|
(depth) => {
|
|
const declarations = ['interface A0 {}', 'interface B0 {}'];
|
|
for (let level = 1; level <= depth; level++) {
|
|
declarations.push(
|
|
`interface A${level} extends A${level - 1}, B${level - 1} {}`,
|
|
`interface B${level} extends A${level - 1}, B${level - 1} {}`,
|
|
);
|
|
}
|
|
const fixture = hierarchyFixture(declarations, [`A${depth}`, `B${depth}`]);
|
|
expect(fixture.resolve()).toMatchObject({
|
|
kind: 'resolved',
|
|
definition: { parameterTypes: ['Long'] },
|
|
});
|
|
expect(fixture.baseReads()).toBeLessThanOrEqual((declarations.length + 1) * 2);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
['C1', 'C63'],
|
|
['C63', 'C1'],
|
|
])('does not reuse a shallow proof past the depth bound (%s, %s)', (first, second) => {
|
|
const declarations = ['interface C0 {}'];
|
|
for (let level = 1; level <= 63; level++)
|
|
declarations.push(`interface C${level} extends C${level - 1} {}`);
|
|
const fixture = hierarchyFixture(declarations, [first, second]);
|
|
expect(fixture.resolve()).toMatchObject({
|
|
kind: 'unknown',
|
|
candidateSetComplete: false,
|
|
});
|
|
});
|
|
|
|
it('retains cyclic-hierarchy uncertainty across repeated inventory requests', () => {
|
|
const fixture = hierarchyFixture(
|
|
['interface Left extends Right {}', 'interface Right extends Left {}'],
|
|
['Left'],
|
|
);
|
|
for (let attempt = 0; attempt < 2; attempt++)
|
|
expect(fixture.resolve()).toMatchObject({ kind: 'unknown', candidateSetComplete: false });
|
|
});
|
|
});
|
|
|
|
describe('Java source subtype conversion bounds', () => {
|
|
const conversion = { argumentType: 'Argument', parameterTypes: ['Unrelated', 'Object'] as const };
|
|
|
|
it.each([12, 16])(
|
|
'checks an unrelated formal through a depth-%i diamond once per type',
|
|
(depth) => {
|
|
const declarations = ['interface A0 {}', 'interface B0 {}'];
|
|
for (let level = 1; level <= depth; level++) {
|
|
declarations.push(
|
|
`interface A${level} extends A${level - 1}, B${level - 1} {}`,
|
|
`interface B${level} extends A${level - 1}, B${level - 1} {}`,
|
|
);
|
|
}
|
|
declarations.push(`class Argument implements A${depth}, B${depth} {}`, 'class Unrelated {}');
|
|
const fixture = hierarchyFixture(declarations, [], conversion);
|
|
expect(fixture.resolve()).toMatchObject({
|
|
kind: 'resolved',
|
|
definition: { parameterTypes: ['Object'] },
|
|
});
|
|
expect(fixture.baseReads()).toBeLessThanOrEqual((declarations.length + 1) * 2);
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
['C1', 'C63'],
|
|
['C63', 'C1'],
|
|
])(
|
|
'does not reuse a shallow subtype rejection beyond the depth bound (%s, %s)',
|
|
(first, second) => {
|
|
const declarations = ['interface C0 {}'];
|
|
for (let level = 1; level <= 63; level++)
|
|
declarations.push(`interface C${level} extends C${level - 1} {}`);
|
|
declarations.push(`class Argument implements ${first}, ${second} {}`, 'class Unrelated {}');
|
|
const fixture = hierarchyFixture(declarations, [], conversion);
|
|
expect(fixture.resolve()).toMatchObject({ kind: 'unknown', candidateSetComplete: true });
|
|
},
|
|
);
|
|
|
|
it('retains cyclic subtype uncertainty instead of selecting the Object fallback', () => {
|
|
const fixture = hierarchyFixture(
|
|
[
|
|
'interface Left extends Right {}',
|
|
'interface Right extends Left {}',
|
|
'class Argument implements Left {}',
|
|
'class Unrelated {}',
|
|
],
|
|
[],
|
|
conversion,
|
|
);
|
|
for (let attempt = 0; attempt < 2; attempt++)
|
|
expect(fixture.resolve()).toMatchObject({ kind: 'unknown', candidateSetComplete: true });
|
|
});
|
|
});
|