fix(resolution): treat import-reached unique constructors as precise

C++ #include and Rust re-exports do not mint a lexical class binding.
A unique type in an imported file (or imported directory) is therefore
a real bind, not a name guess, so those CALLS edges stay import-resolved.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Gergo Magyar 2026-09-10 09:44:08 +00:00
parent bed0fd7616
commit 86c58409f8
3 changed files with 82 additions and 26 deletions

View file

@ -44,7 +44,9 @@ import {
findAllCallableBindingsInScope,
findCallableBindingInScope,
findCallableBindingsAndAdlBlocker,
findClassBindingInScope,
findEnclosingClassDef,
isClassFileImportGrounded,
resolveInheritanceBaseInScope,
type CallableBindingCandidate,
} from '../scope/walkers.js';
@ -236,12 +238,13 @@ export function emitFreeCallFallback(
// Constructor child — Go refuses any `qualifiedName` containing `.`.
let globalFallbackVetoTarget: SymbolDefinition | undefined;
if (site.callForm === 'constructor') {
// Bare unique type names are guesses (`pickUniqueGlobalClass`).
// A written qualifier (`new pkg.Foo()`, `models.Box[T]{}`)
// licenses the unique QualifiedNameIndex hit — Go/Java strip
// the qualifier down to the simple tail, so lexical lookup
// misses and the unique name is how the type is recovered.
const classDef = resolveInheritanceBaseInScope(
// Lexical / written-qualifier first. A bare unique type with no
// import/#include evidence is a guess (JS `new UniqueWidget()`,
// Go unexported `uniqueWidget{}`). A unique type whose file is
// imported or sits in an imported directory is precise — C++
// `#include "user.h"` and Rust re-exports do not mint a lexical
// class binding, but they are not name guesses either.
let classDef = resolveInheritanceBaseInScope(
site.inScope,
site.name,
scopes,
@ -249,6 +252,24 @@ export function emitFreeCallFallback(
undefined,
{ uniqueQualifiedNameFallback: site.rawQualifiedName !== undefined },
);
if (classDef === undefined) {
classDef =
findClassBindingInScope(site.inScope, site.name, scopes, undefined, {
uniqueQualifiedNameFallback: true,
}) ??
(options.allowGlobalFallback === true
? pickUniqueGlobalClass(site.name, globalClassesBySimpleName)
: undefined);
if (
classDef !== undefined &&
classDef.type !== 'Interface' &&
site.rawQualifiedName === undefined &&
!isClassFileImportGrounded(site.inScope, classDef, scopes)
) {
fnDefFromGlobalNameFallback = true;
globalFallbackVetoTarget = classDef;
}
}
if (classDef !== undefined && classDef.type !== 'Interface') {
// Most languages link `Type(...)` to the explicit Constructor def
// when one exists (else the Class). Languages that model the call
@ -258,25 +279,6 @@ export function emitFreeCallFallback(
options.constructorCallTargetsClass === true
? classDef
: pickConstructorOrClass(classDef, workspaceIndex, scopes, site.arity);
} else if (options.allowGlobalFallback === true) {
// The constructed type may live in a sibling/imported file that is
// not in the call-site's lexical scope-chain bindings. Fall back to
// a unique workspace-wide Class def by simple name (gated on the
// same global-fallback opt-in as free calls). Then target the
// Class or its Constructor per the language's preference.
const globalClass = pickUniqueGlobalClass(site.name, globalClassesBySimpleName);
if (globalClass !== undefined) {
fnDef =
globalClass.type === 'Interface'
? undefined
: options.constructorCallTargetsClass === true
? globalClass
: pickConstructorOrClass(globalClass, workspaceIndex, scopes, site.arity);
if (fnDef !== undefined) {
fnDefFromGlobalNameFallback = true;
globalFallbackVetoTarget = globalClass;
}
}
}
}
// Module-qualified free call (`mod::fn()`): the source named the module

View file

@ -1555,6 +1555,33 @@ function dirnameOf(filePath: string): string {
return idx === -1 ? '' : filePath.slice(0, idx);
}
/**
* True when `classDef` lives in the caller's file, an imported file, or a
* file in an imported directory. Same evidence
* `resolveAmbiguousInheritanceBaseViaImports` uses for ambiguous names;
* applied to a UNIQUE class so `#include "user.h"` / a re-export directory
* counts as a precise constructor bind, not a bare unique-name guess.
*/
export function isClassFileImportGrounded(
startScope: ScopeId,
classDef: Pick<SymbolDefinition, 'filePath'>,
scopes: ScopeResolutionIndexes,
): boolean {
const callerModule = moduleScopeIdOf(startScope, scopes);
const callerFile = scopes.scopeTree.getScope(startScope)?.filePath;
if (callerFile !== undefined && classDef.filePath === callerFile) return true;
if (callerModule === null) return false;
const importEdges = scopes.imports.get(callerModule);
if (importEdges === undefined || importEdges.length === 0) return false;
const classDir = dirnameOf(classDef.filePath);
for (const edge of importEdges) {
if (edge.targetFile === null) continue;
if (edge.targetFile === classDef.filePath) return true;
if (classDir !== '' && dirnameOf(edge.targetFile) === classDir) return true;
}
return false;
}
/**
* Predicate for value-receiver bridge: the labels for which
* `reconcileOwnership` registers methods/fields under the def's

View file

@ -265,6 +265,7 @@ function runConstructor(
sites: readonly ReferenceSite[],
options: {
readonly bindImportedClass?: boolean;
readonly importTargetFile?: string;
readonly isGlobalNameFallbackPlausible?: () => boolean;
} = {},
) {
@ -307,7 +308,23 @@ function runConstructor(
computeMro: () => [],
implementsOf: () => [],
}),
imports: new Map(),
imports: new Map(
options.importTargetFile !== undefined
? [
[
'scope:caller-mod',
[
{
localName: 'UniqueWidget',
targetFile: options.importTargetFile,
targetExportedName: 'UniqueWidget',
kind: 'named' as const,
},
],
],
]
: [],
),
bindings: new Map(
options.bindImportedClass === true
? [
@ -393,4 +410,14 @@ describe('constructor-form unique-name hits are guesses, not import-resolved', (
expect(calls[0]!.reason).toBe('import-resolved');
expect(outcomes).toEqual([]);
});
it('treats a unique class as precise when an import reaches its file', () => {
const { calls, outcomes } = runConstructor([ctorGuessedSite(3)], {
importTargetFile: TARGET_FILE,
});
expect(calls).toHaveLength(1);
expect(calls[0]!.confidence).toBe(0.85);
expect(calls[0]!.reason).toBe('import-resolved');
expect(outcomes).toEqual([]);
});
});