diff --git a/docs/languages/r-provider.md b/docs/languages/r-provider.md index 13d63efb78..df2b2247ce 100644 --- a/docs/languages/r-provider.md +++ b/docs/languages/r-provider.md @@ -37,7 +37,7 @@ Calls: - Free calls, `obj$method()` calls (receiver typed as above), R6 `self$method()` calls, and calls inside native pipe (`|>`) chains. - `self` in an R6 method is typed as the class: `self$m()` resolves through the class and its parents (`inherit =`) at the receiver-call confidence (0.85), never to a free function of that name. The class is the name the `R6Class` call is assigned to (`Child <- R6::R6Class(...)`, bare or `R6::`), and the method is a function in its `public`, `private` or `active` list. A closure inside a method sees the method's `self`. Where `self` is no R6 instance (a free function, a parameter called `self`, an `R6Class` call that is assigned to nothing, a `setRefClass` method) a `self$m()` call gets no edge and the resolution outcome is `receiver-owned-but-unbound`; a method that neither the class nor a parent defines (or a parent that is not indexed, as in `inherit = pkg::Base`) gets no edge and the outcome `member-lookup-ambiguous` (the closest label the shared pass offers for "member not found"). A file that binds `self` itself (`self <- Foo$new()` at top level) is exempt: its free functions read that object. - A call through a name that a function's formal or one of its `for` variables binds (`function(data, transform) transform(data)`) gets no edge, not even to a top-level function of that name. The scope publishes those names as lexical names: they stop the lookup and the unique-name fallback. Every named formal is a lexical name, whatever its default: a default (`n = 2`, `helper = NULL`) proves nothing about the argument a caller passes, which may be a function, so a call through the formal is never bound to a function of that name outside. A `for` loop outside every function binds nothing. -- An ordinary assignment in a function's own body is a lexical name too, when its value may be a function (`helper <- identity`, `helper = some_fn()`, `identity -> helper`): a call of the name in that function, or in a closure nested in it, gets no edge to a top-level function of the same name. A function literal (`helper <- function(y) 2`) is a real definition and the call resolves to it; a constant (`helper <- 2`, a string, `TRUE`) is skipped by R at a call, so the call still reaches the outer function; `<<-` and `->>` assign outward and bind nothing in the frame. A complex target binds its base (`names(x) <- v`, `x$a <- v` bind `x`, never the called name). The rule is flow-insensitive, a deliberate trade for a conservative result: a call written before the assignment, or under an `if` that may skip it, is left unresolved too. Not modelled: `assign()`, `delayedAssign()`, `list2env()`, `local()` and `with()`; a string target (`"helper" <- identity`); and module-level assignments (a top-level `helper <- identity` in the caller's own file still lets the unique-name fallback reach another file's `helper`). +- An ordinary assignment in a function's own body is a lexical name too, when its value may be a function (`helper <- identity`, `helper = some_fn()`, `identity -> helper`): a call of the name in that function, or in a closure nested in it, gets no edge to a top-level function of the same name. A function literal (`helper <- function(y) 2`) is a real definition and the call resolves to it; a constant (`helper <- 2`, a string, `TRUE`) is skipped by R at a call, so the call still reaches the outer function; `<<-` and `->>` assign outward and bind nothing in the frame. A complex target binds its base (`names(x) <- v`, `x$a <- v` bind `x`, never the called name). The rule is flow-insensitive, a deliberate trade for a conservative result: a call written before the assignment, or under an `if` that may skip it, is left unresolved too. Not modelled: `assign()`, `delayedAssign()`, `list2env()`, `local()` and `with()`; a string target (`"helper" <- identity`); and module-level assignments (a top-level `helper <- identity` in the caller's own file still lets the unique-name fallback reach another file's `helper`). A qualified call is decided by its qualifier alone: `function(f) mypkg::f()` and `helper <- identity; pkga::helper(x)` still bind `mypkg`'s `f` and `pkga`'s `helper` (the shared free-call pass resolves the qualifier before it applies a lexical name claim). - Named nested functions (closures) are indexed, and calls inside attribute to the nested function, which can shadow a top-level name; a nested function reads the lexical names of the function around it. Top-level script calls outside any function are attributed to the File node. - `pkg::fn()` and `pkg:::fn()`, decided by the qualifier (see [Resolution model](#resolution-model)). @@ -109,7 +109,6 @@ Not supported: - Package discovery is bounded (depth 3, 200 directories), so a package beyond the bound is treated like an unknown one. A package found only under `renv`, `packrat`, `revdep`, `.Rcheck`, a dot-directory or another directory the indexer ignores, or whose `DESCRIPTION` has a `Built:` field, is not a repository package. - A `pkg::name` whose package defines no `name` resolves only through a one-hop re-export (`export` plus `importFrom` of a repository package); a re-export through a second hop, through `exportPattern()` only, or through `import()` gets no edge. `pkg::name` used as a value is not qualifier-resolved. Call sites dropped for certainly-external, unknown-locality, duplicate-definition or not-exported qualifiers leave no recorded outcome, because the drop runs before outcomes exist. - When discovery may have missed a package, a `pkg::name` call gets no edge (it used to keep the name-based guess). A `library(pkg)` attaches no private or not-provably-exported name, and a bare call of a name whose NAMESPACE is unreadable or whose `exportPattern()` was cut short (`unknown`) still gets the 0.5 guess, because it is not proven private. A `library(ownpkg)` from inside the package loses the private names at the 0.85 tier too (they fall to the 0.5 guess, which is allowed for callers inside the package). A `source()` of a private package file does not reach its names through the guess: the guess is vetoed for callers outside the package tree, although R puts sourced names in the global environment. A class reached as a receiver type through a `library()` IMPORTS edge (`ResultSet$new()` then `rs$count()`) is not filtered by this rule. -- A function parameter or `for` variable named like the target of a `pkg::f()` call suppresses that call's `CALLS` edge: in `function(f) mypkg::f()` and `for (f in x) mypkg::f()` the call gets no edge to `mypkg`'s `f`, although R's `::` never consults local bindings. The cause is the shared free-call fallback, which refuses a call when a same-name non-callable local binding is in scope before the qualified lookup runs; fixing it means editing shared code, which this provider avoids. - Files in `R/` subdirectories are treated as package-owned, although R itself does not load them. - NAMESPACE is read from disk during analysis, but neither it nor `DESCRIPTION` is a parsed source file. After an edit to either alone, an incremental analyse (no `--force`) keeps stale manifest-derived data: the persisted `isExported` of symbols in unchanged `R/` files, a `CALLS` edge bound through an `importFrom()` whose target changed, a `pkg::fn` edge after a `Package:` rename, and a `library()`, `pkg::fn` or name-guess edge whose target's export status changed. A full analyse is correct and `analyze --force` recomputes it. This is a limitation of the shared incremental write path (only changed files are re-processed), not of R resolution; other language manifests that feed resolution can be affected in the same way. A stale `isExported` does not reach `rename`: the rename guard does not take the persisted flag as proof that a function is private, and reads the package's NAMESPACE again at plan time (see Rename). - A name written in backticks (`` `%+%` ``, `` `my fn` ``) keeps its backticks on the node, and a definition and its call resolve only when both spell the name alike: `` `helper`(x) `` against `helper <- function(...)` (or the reverse) gets no `CALLS` edge. NAMESPACE `export()`, `exportPattern()`, `importFrom()`, `pkg::name()` and `rename` match the symbol whichever way it is written. `importFrom(pkg, `%||%`)` binds a call spelled like the definition (`` `%||%`(x, y) ``), and a call spelled the other way gets the name-based guess instead. diff --git a/gitnexus/src/core/ingestion/languages/r/qualified-call.ts b/gitnexus/src/core/ingestion/languages/r/qualified-call.ts index f913d41a58..b2b0528a4a 100644 --- a/gitnexus/src/core/ingestion/languages/r/qualified-call.ts +++ b/gitnexus/src/core/ingestion/languages/r/qualified-call.ts @@ -22,10 +22,9 @@ * NAMESPACE, or exports the name) or the caller is inside the package's * directory tree ({@link rEnclosingPackageDir}). A `::` site naming a * private or not-provably-exported name from outside is dropped (R errors - * there). The fallback's earlier same-name check still wins when the caller has a - * non-callable binding of that name (a parameter or `for` variable named - * like the target): that site gets no edge (see the limits in - * docs/languages/r-provider.md); + * there). The fallback resolves the hook before it applies a lexical name claim, so a + * caller's parameter, `for` variable or local assignment of the same name does not + * suppress the edge: `::` never consults local bindings; * - `local` with two or more such definitions (same file or across files): * the site is dropped (every valid target is inside the named package, so * any edge would be provably wrong); diff --git a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts index 88ab0ff305..81f19b43fd 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts @@ -332,8 +332,7 @@ export type { ConstraintContext } from 'gitnexus-shared'; /** How a container's element was reached in the source. */ export type ElementAccessRoute = - | { readonly kind: 'index' } - | { readonly kind: 'accessor'; readonly name: string }; + { readonly kind: 'index' } | { readonly kind: 'accessor'; readonly name: string }; /** One structurally-detected implementor plus the receiver form in which it * satisfies the interface (see `detectInterfaceImplementations`). */ @@ -1446,11 +1445,16 @@ export interface ScopeResolver { * risk LOW with 0 affected processes). * * `emitFreeCallFallback` invokes this BEFORE the implicit-`this` and - * scope-chain lookups, so an explicit path outranks a lexical shadow. + * scope-chain lookups, so an explicit path outranks a lexical shadow. That + * includes a lexical NAME CLAIM (`lexicalNames`, a parameter or a local of the + * same name): the contract left open whether such a claim blocks the call + * before the hook runs, and it does not — a defined result for a site with + * `rawQualifiedName` bypasses the block, because the written path names the + * module and a local binding of the bare tail cannot be what it means. * Returning `undefined` (unqualified call, unknown module, or no such - * member in the named module) falls through to the unchanged chain — the - * hook is strictly additive and never removes an edge the prior tiers - * would have produced. + * member in the named module) falls through to the unchanged chain, name-claim + * block included — the hook never removes an edge the prior tiers would have + * produced. * * Languages whose qualified calls carry a value/type receiver (`x.foo()`, * `Type::foo()`) are served by the receiver-bound-calls pass and leave diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/free-call-fallback.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/free-call-fallback.ts index c3982d4c93..524c6ba7ab 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/free-call-fallback.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/free-call-fallback.ts @@ -257,7 +257,14 @@ export function emitFreeCallFallback( b.def.type === 'Struct' || b.def.type === 'Record', ))); - if (blocksCall) { + // A module-qualified free call (`mod::fn()`) names its module explicitly, so the path is + // evidence the lexical name claim is not: a local `fn` binds the bare tail, never `mod::fn`. + // The hook therefore runs before the block, and a defined hit bypasses it. + const qualifiedFnDef = + options.resolveQualifiedFreeCall !== undefined && site.rawQualifiedName !== undefined + ? options.resolveQualifiedFreeCall(site, parsed, scopes, workspaceIndex, allFilePaths()) + : undefined; + if (blocksCall && qualifiedFnDef === undefined) { options.recordSourceBinding?.(site, { status: 'blocked', targetDefIds: [], @@ -357,20 +364,9 @@ export function emitFreeCallFallback( // the caller's own file and emits a self-loop instead of the real // cross-module edge (#2730). Only fires when the language populated // `rawQualifiedName` AND provides the hook; `undefined` falls through to - // the unchanged chain, so this tier is strictly additive. - if ( - fnDef === undefined && - options.resolveQualifiedFreeCall !== undefined && - site.rawQualifiedName !== undefined - ) { - fnDef = options.resolveQualifiedFreeCall( - site, - parsed, - scopes, - workspaceIndex, - allFilePaths(), - ); - } + // the unchanged chain, so this tier is strictly additive. Resolved above, before the + // name-claim block, so that a hit also outranks a lexical name claim. + if (fnDef === undefined) fnDef = qualifiedFnDef; // Implicit-this overload narrowing: an unqualified call inside // a method body might be calling a sibling overload on the // enclosing class. When the workspace has multiple methods of diff --git a/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/composer.json b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/composer.json new file mode 100644 index 0000000000..ec48cfbb8b --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/composer.json @@ -0,0 +1 @@ +{ "autoload": { "psr-4": { "App\\": "src/" }, "files": ["lib/functions.php"] } } diff --git a/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/lib/functions.php b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/lib/functions.php new file mode 100644 index 0000000000..6c097b9b81 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-php/lib/functions.php @@ -0,0 +1,7 @@ + usize { + let dispatch = |n: usize| n + 1; + let _bumped = dispatch(1); + tools::dispatch(ctx, name) +} + +// A parameter of the same name. +fn with_parameter(ctx: &ToolCtx, name: &str, dispatch: usize) -> usize { + dispatch + tools::dispatch(ctx, name) +} + +// Control: no local binding. +fn plain(ctx: &ToolCtx, name: &str) -> usize { + tools::dispatch(ctx, name) +} + +fn main() { + let ctx = ToolCtx { depth: 0 }; + with_let(&ctx, "a"); + with_parameter(&ctx, "b", 1); + plain(&ctx, "c"); +} diff --git a/gitnexus/test/fixtures/lang-resolution/qualified-over-local-rust/src/tools.rs b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-rust/src/tools.rs new file mode 100644 index 0000000000..0a9ef13edc --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/qualified-over-local-rust/src/tools.rs @@ -0,0 +1,7 @@ +pub struct ToolCtx { + pub depth: usize, +} + +pub fn dispatch(ctx: &ToolCtx, name: &str) -> usize { + ctx.depth + name.len() +} diff --git a/gitnexus/test/fixtures/lang-resolution/r-assignment-locals/scripts/d.R b/gitnexus/test/fixtures/lang-resolution/r-assignment-locals/scripts/d.R index e0fcd6ade2..b9770b591e 100644 --- a/gitnexus/test/fixtures/lang-resolution/r-assignment-locals/scripts/d.R +++ b/gitnexus/test/fixtures/lang-resolution/r-assignment-locals/scripts/d.R @@ -30,3 +30,6 @@ d13_f <- function(x) { helper <- 2; helper(x) } d15_f <- function(x) { helper <<- identity; helper(x) } # d16: a nested closure reads the enclosing function's local d16_f <- function(x) { helper <- identity; d16_g <- function() helper(x); d16_g() } +# d17/d18: a parameter or a `for` variable of the qualified name does not hide the qualified call +d17_f <- function(x, helper) { pkga::helper(x) } +d18_f <- function(xs) { for (helper in xs) pkga::helper(1) } diff --git a/gitnexus/test/integration/resolvers/php-qualified-over-local.test.ts b/gitnexus/test/integration/resolvers/php-qualified-over-local.test.ts new file mode 100644 index 0000000000..d8fee3202b --- /dev/null +++ b/gitnexus/test/integration/resolvers/php-qualified-over-local.test.ts @@ -0,0 +1,42 @@ +/** + * PHP: a namespaced function call (`\Lib\make()`) beside an unresolved `use function Ext\make` and + * a same-named function of the caller's own namespace. + * + * The shared free-call pass now resolves a qualified site's hook before it applies a lexical name + * claim (unit-tested with a fake hook in `free-call-qualified-over-name-claim.test.ts`). PHP + * publishes no such claim for these declarations, so this fixture pins that its edges did not move + * with the reorder: the qualified call binds `Lib\make`, the unqualified control binds the + * namespace's own `make`. + */ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import path from 'path'; +import { FIXTURES, getRelationships, runPipelineFromRepo } from './helpers.js'; +import type { PipelineResult } from './helpers.js'; + +beforeAll(() => vi.stubEnv('GITNEXUS_WORKER_READY_TIMEOUT_MS', '60000')); +afterAll(() => vi.unstubAllEnvs()); + +let result: PipelineResult; +beforeAll(async () => { + result = await runPipelineFromRepo(path.join(FIXTURES, 'qualified-over-local-php'), () => {}); +}, 60000); + +const edgesFrom = (source: string) => + getRelationships(result, 'CALLS').filter( + (e) => e.source === source && e.sourceFilePath === 'src/Caller.php', + ); + +describe('PHP qualified function call beside same-named declarations', () => { + it('binds \\Lib\\make() to the library function, not the namespace-local make', () => { + const edges = edgesFrom('qualified'); + expect(edges).toHaveLength(1); + expect(edges[0]).toMatchObject({ target: 'make', targetFilePath: 'lib/functions.php' }); + expect(edges[0].rel.reason).toBe('import-resolved'); + }); + + it('control: the unqualified call binds the namespace-local make', () => { + const edges = edgesFrom('control'); + expect(edges).toHaveLength(1); + expect(edges[0]).toMatchObject({ target: 'make', targetFilePath: 'src/Caller.php' }); + }); +}); diff --git a/gitnexus/test/integration/resolvers/r-assignment-locals.test.ts b/gitnexus/test/integration/resolvers/r-assignment-locals.test.ts index f00d2d950c..a6e69c8510 100644 --- a/gitnexus/test/integration/resolvers/r-assignment-locals.test.ts +++ b/gitnexus/test/integration/resolvers/r-assignment-locals.test.ts @@ -81,11 +81,16 @@ describe('controls: assignments that do not bind a callable local', () => { }); describe('qualified calls inside a function that assigns the same name', () => { - // Needs the qualified hit to outrank the lexical name claim (the shared-pass step that follows). - it.fails('d11 `pkga::helper(x)` binds the package function and nothing else', () => { + // The qualified hit outranks the lexical name claim (shared pass: free-call-fallback). + it('d11 `pkga::helper(x)` binds the package function and nothing else', () => { expect(targets('d11_f')).toEqual([PKGA_HELPER]); }); + it('d17/d18 a parameter or a `for` variable of that name does not hide the qualified call either', () => { + expect(targets('d17_f')).toEqual([PKGA_HELPER]); + expect(targets('d18_f')).toEqual([PKGA_HELPER]); + }); + it('d12 neither `pkga::missing(x)` (not exported) nor the shadowed bare `missing(x)` gets an edge', () => { expect(targets('d12_f')).toEqual([]); }); diff --git a/gitnexus/test/integration/resolvers/rust-qualified-over-local.test.ts b/gitnexus/test/integration/resolvers/rust-qualified-over-local.test.ts new file mode 100644 index 0000000000..5a22cd3aab --- /dev/null +++ b/gitnexus/test/integration/resolvers/rust-qualified-over-local.test.ts @@ -0,0 +1,47 @@ +/** + * Rust: a module-qualified call (`tools::dispatch(..)`) beside a local binding of the same name. + * + * The shared free-call pass now resolves a qualified site's hook before it applies a lexical name + * claim, so a defined hit outranks the claim (unit-tested with a fake hook in + * `free-call-qualified-over-name-claim.test.ts`). Rust publishes no such claim for a `let` or a + * parameter, so this fixture pins that its edges did not move with the reorder: + * + * - the unshadowed control binds `tools::dispatch` (import-resolved, 0.85); + * - a caller with a `let dispatch = ..` or a `dispatch` parameter keeps the behaviour it had + * before the reorder. It gets no edge to tools.rs, which is a gap that comes from another pass + * and is pinned here so a later fix flips this test deliberately. + */ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import path from 'path'; +import { FIXTURES, getRelationships, runPipelineFromRepo } from './helpers.js'; +import type { PipelineResult } from './helpers.js'; + +beforeAll(() => vi.stubEnv('GITNEXUS_WORKER_READY_TIMEOUT_MS', '60000')); +afterAll(() => vi.unstubAllEnvs()); + +let result: PipelineResult; +beforeAll(async () => { + result = await runPipelineFromRepo(path.join(FIXTURES, 'qualified-over-local-rust'), () => {}); +}, 60000); + +const edgesFrom = (source: string) => + getRelationships(result, 'CALLS').filter( + (e) => e.source === source && e.sourceFilePath === 'src/main.rs', + ); + +describe('Rust qualified call beside a same-named local binding', () => { + it('control: tools::dispatch with no local binding binds tools.rs', () => { + const edges = edgesFrom('plain'); + expect(edges).toHaveLength(1); + expect(edges[0]).toMatchObject({ target: 'dispatch', targetFilePath: 'src/tools.rs' }); + expect(edges[0].rel.reason).toBe('import-resolved'); + }); + + it('a `let dispatch` caller is unchanged: no edge to tools.rs (gap of another pass)', () => { + expect(edgesFrom('with_let').map((e) => e.targetFilePath)).not.toContain('src/tools.rs'); + }); + + it('a `dispatch` parameter caller is unchanged: no edge to tools.rs (gap of another pass)', () => { + expect(edgesFrom('with_parameter')).toEqual([]); + }); +}); diff --git a/gitnexus/test/unit/r-rename-assigned-locals.test.ts b/gitnexus/test/unit/r-rename-assigned-locals.test.ts index 18addcffb4..a71f5564a0 100644 --- a/gitnexus/test/unit/r-rename-assigned-locals.test.ts +++ b/gitnexus/test/unit/r-rename-assigned-locals.test.ts @@ -85,8 +85,9 @@ describe('lockstep: the lexical names and the rename guard read the same assignm ? [{ name, fn, text: node.text }] : []; }); - // Cases the guard refuses for a reason other than an assigned name: d9 has a parameter, d15 a `<<-`. - const otherRule = new Set(['d9_f', 'd15_f']); + // Cases bound or refused for a reason other than an assigned name: d9 and d17 have a parameter, + // d18 a `for` variable, d15 a `<<-`. + const otherRule = new Set(['d9_f', 'd15_f', 'd17_f', 'd18_f']); it('finds every caller of the fixture', () => { expect(callers.map((c) => c.name)).toEqual( diff --git a/gitnexus/test/unit/scope-resolution/free-call-qualified-over-name-claim.test.ts b/gitnexus/test/unit/scope-resolution/free-call-qualified-over-name-claim.test.ts new file mode 100644 index 0000000000..63ddd790bf --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/free-call-qualified-over-name-claim.test.ts @@ -0,0 +1,236 @@ +/** + * A module-qualified free call (`mod::fn()`) names its module, so a lexical name claim for the + * bare tail (a local binding or parameter called `fn`) cannot be what the call means. The + * `resolveQualifiedFreeCall` hook therefore runs BEFORE the name-claim block, and a defined hit + * bypasses it. An undefined hit, a site without a written path and a language without the hook + * keep the block, so the reorder only ever adds an edge for a site the hook resolved. + * + * The hook is a fake: this pins the ordering in the shared pass, not any language. + */ +import { describe, it, expect } from 'vitest'; +import { + buildDefIndex, + buildMethodDispatchIndex, + buildModuleScopeIndex, + buildQualifiedNameIndex, + buildScopeTree, + type NodeLabel, + type ParsedFile, + type Range, + type ReferenceSite, + type Scope, + type SymbolDefinition, +} from 'gitnexus-shared'; +import { createKnowledgeGraph } from '../../../src/core/graph/graph.js'; +import type { ScopeResolutionIndexes } from '../../../src/core/ingestion/model/scope-resolution-indexes.js'; +import { buildGraphNodeLookup } from '../../../src/core/ingestion/scope-resolution/graph-bridge/node-lookup.js'; +import { emitFreeCallFallback } from '../../../src/core/ingestion/scope-resolution/passes/free-call-fallback.js'; +import { buildWorkspaceResolutionIndex } from '../../../src/core/ingestion/scope-resolution/workspace-index.js'; +import { createSemanticModel } from '../../../src/core/ingestion/model/semantic-model.js'; +import type { ScopeResolver } from '../../../src/core/ingestion/scope-resolution/contract/scope-resolver.js'; + +const CALLER_FILE = 'caller.src'; +const TARGET_FILE = 'target.src'; + +const range = (line: number): Range => ({ + startLine: line, + startCol: 2, + endLine: line, + endCol: 8, +}); + +const targetDef: SymbolDefinition = { + nodeId: 'def:helper', + filePath: TARGET_FILE, + type: 'Function', + qualifiedName: 'helper', +}; +const callerDef: SymbolDefinition = { + nodeId: 'def:main', + filePath: CALLER_FILE, + type: 'Function', + qualifiedName: 'main', +}; + +/** `helper()` or `target::helper()`: the second form carries the written path. */ +const site = (qualified: boolean): ReferenceSite => ({ + name: 'helper', + atRange: range(3), + inScope: 'scope:caller-mod', + kind: 'call', + callForm: 'free', + arity: 0, + ...(qualified ? { rawQualifiedName: 'target::helper' } : {}), +}); + +function mkScope( + id: string, + filePath: string, + ownedDefs: SymbolDefinition[], + lexicalNames?: ReadonlySet, +): Scope { + return { + id, + parent: null, + kind: 'Module', + range: { startLine: 1, startCol: 0, endLine: 100, endCol: 0 }, + filePath, + bindings: new Map(), + ownedDefs, + imports: [], + typeBindings: new Map(), + ...(lexicalNames === undefined ? {} : { lexicalNames }), + }; +} + +type Hook = NonNullable; + +function run(reference: ReferenceSite, hook: Hook | undefined, claimed = true) { + const callerScope = mkScope( + 'scope:caller-mod', + CALLER_FILE, + [callerDef], + claimed ? new Set(['helper']) : undefined, + ); + const targetScope = mkScope('scope:target-mod', TARGET_FILE, [targetDef]); + const callerParsed: ParsedFile = { + filePath: CALLER_FILE, + moduleScope: 'scope:caller-mod', + scopes: [callerScope], + parsedImports: [], + localDefs: [callerDef], + referenceSites: [reference], + }; + const targetParsed: ParsedFile = { + filePath: TARGET_FILE, + moduleScope: 'scope:target-mod', + scopes: [targetScope], + parsedImports: [], + localDefs: [targetDef], + referenceSites: [], + }; + const scopes = [callerScope, targetScope]; + const allDefs = [callerDef, targetDef]; + const indexes = { + scopeTree: buildScopeTree(scopes), + defs: buildDefIndex(allDefs), + qualifiedNames: buildQualifiedNameIndex(allDefs), + moduleScopes: buildModuleScopeIndex( + scopes.map((s) => ({ filePath: s.filePath, moduleScopeId: s.id })), + ), + methodDispatch: buildMethodDispatchIndex({ + owners: [], + computeMro: () => [], + implementsOf: () => [], + }), + imports: new Map(), + bindings: new Map(), + bindingAugmentations: new Map(), + workspaceFqnBindings: new Map(), + workspaceTypeBindings: new Map(), + namespaceFqnBindings: new Map(), + namespaceTypeBindings: new Map(), + accessibleNamespacesByScope: new Map(), + referenceSites: [], + sccs: [], + stats: { + totalFiles: 2, + totalEdges: 0, + linkedEdges: 0, + unresolvedEdges: 0, + sccCount: 0, + largestSccSize: 0, + ambiguousWildcardExports: [], + }, + } as unknown as ScopeResolutionIndexes; + const graph = createKnowledgeGraph(); + for (const [id, name, filePath] of [ + ['fn:main', 'main', CALLER_FILE], + ['fn:helper', 'helper', TARGET_FILE], + ] as const) { + graph.addNode({ + id, + label: 'Function' as NodeLabel, + properties: { name, filePath, qualifiedName: name }, + }); + } + const bindings: Array<{ status: string; basis?: string }> = []; + emitFreeCallFallback( + graph, + indexes, + [callerParsed, targetParsed], + buildGraphNodeLookup(graph), + { bySourceScope: new Map() }, + new Set(), + createSemanticModel(), + buildWorkspaceResolutionIndex([callerParsed, targetParsed]), + { + recordSourceBinding: (_site, binding) => bindings.push(binding), + ...(hook === undefined ? {} : { resolveQualifiedFreeCall: hook }), + }, + ); + return { + calls: graph.relationships.filter((r) => r.type === 'CALLS'), + bindings, + }; +} + +const hitHook = (): { hook: Hook; calls: number } => { + const state = { calls: 0 }; + const hook: Hook = () => { + state.calls++; + return targetDef; + }; + return { + hook, + get calls() { + return state.calls; + }, + }; +}; + +describe('the qualified hook outranks a lexical name claim', () => { + it('control: a name claim blocks an unqualified call', () => { + const { calls, bindings } = run(site(false), undefined); + expect(calls).toHaveLength(0); + expect(bindings.map((b) => b.basis)).toContain('lexical-name-claim'); + }); + + it('a defined hit for a qualified site bypasses the block and emits the edge', () => { + const probe = hitHook(); + const { calls, bindings } = run(site(true), probe.hook); + expect(calls).toHaveLength(1); + expect(calls[0]).toMatchObject({ + targetId: 'fn:helper', + confidence: 0.85, + reason: 'import-resolved', + }); + expect(bindings.map((b) => b.basis)).not.toContain('lexical-name-claim'); + expect(probe.calls).toBe(1); + }); + + it('an undefined hit leaves the block in place', () => { + const { calls, bindings } = run(site(true), () => undefined); + expect(calls).toHaveLength(0); + expect(bindings.map((b) => b.basis)).toContain('lexical-name-claim'); + }); + + it('a site with no written path never reaches the hook and stays blocked', () => { + const probe = hitHook(); + const { calls } = run(site(false), probe.hook); + expect(calls).toHaveLength(0); + expect(probe.calls).toBe(0); + }); + + it('a language without the hook keeps the block for a qualified site', () => { + const { calls } = run(site(true), undefined); + expect(calls).toHaveLength(0); + }); + + it('without a name claim the hook still resolves the site, once', () => { + const probe = hitHook(); + const { calls } = run(site(true), probe.hook, false); + expect(calls).toHaveLength(1); + expect(probe.calls).toBe(1); + }); +});