GitNexus/gitnexus/test/unit/scope-resolution/selected-call-propagation.test.ts
Gergő Magyar ef126ea207
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
refactor(scope-resolution): put import visibility behind one interface (#3908)
* test(java): pin on-demand import behaviour to JLS scenarios

Fourteen scenarios for `import pkg.*;` taken from JLS SE 21 (7.5.2,
6.4.1, 6.5.5.1, 6.5.4.2, 6.6.1), each asserting the exact CALLS, EXTENDS
and IMPORTS edges the resolver emits today. Nine agree with the JLS. Five
are labelled as known semantic gaps (a name supplied by one on-demand
package resolves only for the class link, accessibility is not applied,
member types of a class are not imported on demand); they are pinned so a
change of import representation cannot move them by accident, not
endorsed.

Baseline for the import-group memory work, which must leave every row
unchanged.

Refs #3695

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(scope-resolution): put import visibility behind one interface

`ScopeResolutionIndexes.imports` was a public map of edge arrays, so every
reader depended on one stored edge per imported file. It is now an
`ImportVisibility`: the only way to ask what a scope imports, with one
operation per question a reader has.

- `edgesAt`: the imports a reader can select by name, definition or kind
- `reaches` / `reachesDirectory`: does this scope import that file or any
  file of that directory
- `membership`: the same question asked repeatedly at one scope
- `forEachTarget`: every imported file in statement order, with the edge
  that describes how it is imported
- `scopes`: every scope finalize recorded

`createEagerImportVisibility` implements it over the edge map finalize
already produces; storage is unchanged.

All 26 readers of the map are migrated to the operation they need. The
two file-grounding checks ask `reaches`; inheritance disambiguation asks
`reaches` and `reachesDirectory`; File->File IMPORTS emission and the Java
on-demand fallback use `forEachTarget`; unique-name property narrowing
asks a cached `membership` per importing scope instead of building a set
of imported files for every file up front; readers that select by name or
kind, and each language's own provider code, use `edgesAt`.

No intended semantic change. Test fixtures that built an index by hand
wrap their edge map with the eager implementation; no expected result
changes. The import-emission benchmark gains `--map-input` for an emitter
that predates the interface.

Refs #3695

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(scope-resolution): contract suite for ImportVisibility and a graph-identity helper

The contract is checked against a description of each import relation
(per scope, the statements as written and the files each resolves to),
not against any implementation's storage: 11 hand-written relations and
60 from a seeded generator, covering duplicates, overlaps, self-targets,
unresolved targets, empty lists and explicit imports interleaved with
wildcards. Each case compares scope order, recorded-versus-absent scopes,
the imports selectable by name, definition or kind, ordered targets with
the metadata a consumer reads, and every membership answer. A second
implementation runs the same cases by passing its builder.

`graphIdentity` gives a canonical form of a knowledge graph (node ids,
labels and properties; relationship ids, types, endpoints and properties)
for comparing two runs. It normalizes storage order only.

Refs #3695

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(scope-resolution): address review notes on the contract tests

- The duplicate-target coverage check compared target arrays by identity.
  It now compares them by content, which is what "the same list written
  twice" means.
- The contract helper's header named a function that does not exist; it
  now says how to run the cases against an implementation.
- The JLS scenario comment said every importer uses `T` three ways; S12
  and S14 do not, and the comment says so.

Tests and comments only.

Refs #3695

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 19:47:00 +00:00

278 lines
9.1 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import {
buildDefIndex,
buildMethodDispatchIndex,
buildModuleScopeIndex,
buildQualifiedNameIndex,
buildScopeTree,
type BindingRef,
type CallResultAssignmentSite,
type ParsedFile,
type ReferenceSite,
type Scope,
type SymbolDefinition,
type TypeRef,
} from 'gitnexus-shared';
import { createKnowledgeGraph } from '../../../src/core/graph/graph.js';
import { createSemanticModel } from '../../../src/core/ingestion/model/semantic-model.js';
import type { ScopeResolutionIndexes } from '../../../src/core/ingestion/model/scope-resolution-indexes.js';
import { createCalleeIdAccumulator } from '../../../src/core/ingestion/scope-resolution/graph-bridge/callee-id-sink.js';
import { buildGraphNodeLookup } from '../../../src/core/ingestion/scope-resolution/graph-bridge/node-lookup.js';
import { emitReceiverBoundCalls } from '../../../src/core/ingestion/scope-resolution/passes/receiver-bound-calls.js';
import {
callResultBindingKey,
selectedCallKey,
} from '../../../src/core/ingestion/scope-resolution/passes/provider-call-outcome.js';
import { applyPreciseCallResultBindings } from '../../../src/core/ingestion/scope-resolution/pipeline/run.js';
import type { ResolutionOutcome } from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js';
import { buildWorkspaceResolutionIndex } from '../../../src/core/ingestion/scope-resolution/workspace-index.js';
import { createEagerImportVisibility } from 'gitnexus-shared';
function chainFixture(reverse: boolean) {
const count = 24;
const filePath = 'chain.code';
const caller: SymbolDefinition = {
nodeId: 'caller',
filePath,
type: 'Function',
qualifiedName: 'main',
};
const owners: SymbolDefinition[] = Array.from({ length: count }, (_, i) => ({
nodeId: `owner:${i}`,
filePath,
type: 'Class',
qualifiedName: `Owner${i}`,
}));
const methods: SymbolDefinition[] = owners.map((owner, i) => ({
nodeId: `method:${i}`,
filePath,
type: 'Method',
ownerId: owner.nodeId,
qualifiedName: `${owner.qualifiedName}.${i + 1 < count ? `next${i}` : 'finish'}`,
parameterCount: 0,
parameterTypes: [],
}));
const module: Scope = {
id: 'module',
parent: null,
kind: 'Module',
filePath,
range: { startLine: 0, startCol: 0, endLine: 100, endCol: 0 },
ownedDefs: owners,
imports: [],
typeBindings: new Map(),
bindings: new Map(
owners.map((owner) => [owner.qualifiedName!, [{ def: owner, origin: 'local' }]]),
),
};
const bindings = new Map<string, readonly BindingRef[]>();
const typeBindings = new Map<string, TypeRef>();
for (let i = 0; i < count; i++) {
// The producer join must clear every speculative inferred binding except
// the explicitly typed chain root before reference resolution.
typeBindings.set(`value${i}`, {
rawName: `Owner${i}`,
declaredAtScope: module.id,
source: i === 0 ? 'parameter-annotation' : 'assignment-inferred',
});
bindings.set(`value${i}`, [
{
def: { nodeId: `value:${i}`, filePath, type: 'Variable', qualifiedName: `value${i}` },
origin: 'local',
},
]);
}
const scope: Scope = {
id: 'function',
parent: module.id,
kind: 'Function',
filePath,
range: { startLine: 1, startCol: 0, endLine: 90, endCol: 0 },
ownedDefs: [caller],
imports: [],
typeBindings,
bindings,
};
const sites: ReferenceSite[] = methods.map((method, i) => ({
inScope: scope.id,
kind: 'call',
callForm: 'member',
arity: 0,
name: method.qualifiedName!.split('.').at(-1)!,
explicitReceiver: { name: `value${i}` },
atRange: { startLine: i + 2, startCol: 0, endLine: i + 2, endCol: 15 },
}));
const assignments: CallResultAssignmentSite[] = sites.slice(0, -1).map((site, i) => ({
callSite: site.atRange,
inScope: scope.id,
lhs: `value${i + 1}`,
}));
const defs = [caller, ...owners, ...methods];
const parsed: ParsedFile = {
filePath,
moduleScope: module.id,
scopes: [module, scope],
localDefs: defs,
parsedImports: [],
referenceSites: reverse ? [...sites].reverse() : sites,
callResultAssignmentSites: assignments,
};
const scopes = {
scopeTree: buildScopeTree(parsed.scopes),
defs: buildDefIndex(defs),
qualifiedNames: buildQualifiedNameIndex(defs),
moduleScopes: buildModuleScopeIndex([{ filePath, moduleScopeId: module.id }]),
methodDispatch: buildMethodDispatchIndex({
owners: [],
computeMro: () => [],
implementsOf: () => [],
}),
imports: createEagerImportVisibility(new Map()),
bindings: new Map(),
bindingAugmentations: new Map(),
workspaceFqnBindings: new Map(),
workspaceTypeBindings: new Map(),
namespaceFqnBindings: new Map(),
namespaceTypeBindings: new Map(),
accessibleNamespacesByScope: new Map(),
referenceSites: sites,
sccs: [],
} as unknown as ScopeResolutionIndexes;
const graph = createKnowledgeGraph();
for (const def of defs)
graph.addNode({
id: def.nodeId,
label: def.type,
properties: {
name: def.qualifiedName!.split('.').at(-1)!,
qualifiedName: def.qualifiedName,
filePath,
parameterCount: def.parameterCount,
parameterTypes: def.parameterTypes,
},
});
const nodeLookup = buildGraphNodeLookup(graph);
const model = createSemanticModel();
for (const [i, method] of methods.entries())
model.methods.register(owners[i]!.nodeId, sites[i]!.name, method);
const workspace = {
...buildWorkspaceResolutionIndex([parsed]),
declaredReturnTypeByCallableId: new Map(
methods.slice(0, -1).map((method, i) => [
method.nodeId,
{
rawName: `Owner${i + 1}`,
declaredAtScope: module.id,
source: 'return-annotation' as const,
},
]),
),
};
const selected = new Map<string, SymbolDefinition | null>();
const pending = new Map<string, string>();
const outcomes: ResolutionOutcome[] = [];
const calleeIds = createCalleeIdAccumulator();
const byProducer = new Map(
assignments.map((assignment) => [selectedCallKey(filePath, assignment.callSite), assignment]),
);
const clearCount = applyPreciseCallResultBindings(
[parsed],
scopes,
workspace,
calleeIds,
nodeLookup,
model,
true,
selected,
);
let selections = 0;
const run = (unknownRoot: boolean) =>
emitReceiverBoundCalls(
graph,
scopes,
[parsed],
nodeLookup,
new Set(),
{
isSuperReceiver: () => false,
arityCompatibility: () => 'compatible',
resolveReceiverMember: (owner) => {
selections++;
const definition = methods.find((method) => method.ownerId === owner.nodeId)!;
return unknownRoot && owner.nodeId === owners[0]!.nodeId
? { kind: 'unknown', candidateIds: [definition.nodeId], candidateSetComplete: true }
: { kind: 'resolved', definition };
},
},
workspace,
model,
{
selectedCalls: selected,
pendingCallReceivers: pending,
callResultProducers: new Map(
assignments.map((assignment) => [
callResultBindingKey(scope.id, assignment.lhs),
assignment,
]),
),
onSelectedCall: (key) => {
const assignment = byProducer.get(key);
if (assignment === undefined) return;
// Deliver the exact dependency slice to the same return-binding join
// used by the orchestrator; no workspace scan per selected producer.
applyPreciseCallResultBindings(
[{ ...parsed, callResultAssignmentSites: [assignment] }],
scopes,
workspace,
calleeIds,
nodeLookup,
model,
true,
selected,
);
},
recordResolutionOutcome: (outcome) => outcomes.push(outcome),
},
);
return {
count,
clearCount,
graph,
methods,
outcomes,
pending,
selected,
typeBindings,
run,
selections: () => selections,
};
}
describe('selected call dependency propagation', () => {
it.each([false, true])(
'resolves a long assignment chain in one receiver pass (reverse=%s)',
(reverse) => {
const f = chainFixture(reverse);
expect(f.clearCount).toBe(f.count - 1);
f.run(false);
expect(
[...f.graph.iterRelationshipsByType('CALLS')].map((edge) => edge.targetId).sort(),
).toEqual(f.methods.map((method) => method.nodeId).sort());
expect(f.selections()).toBe(f.count);
expect(f.pending.size).toBe(0);
expect(f.typeBindings.get(`value${f.count - 1}`)?.declaredAtScope).toBe('module');
},
);
it.each([false, true])('keeps a long unknown-origin chain suppressed (reverse=%s)', (reverse) => {
const f = chainFixture(reverse);
f.run(true);
expect([...f.graph.iterRelationshipsByType('CALLS')]).toEqual([]);
expect(f.selections()).toBe(1);
expect(f.pending.size).toBe(f.count - 1);
expect(f.typeBindings.size).toBe(1);
expect(f.outcomes).toContainEqual(
expect.objectContaining({ reason: 'receiver-unresolved', name: 'finish' }),
);
});
});