Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- A fault in the native engine on one unusual file no longer stops indexing: that file is read by the fallback parser instead.
- Indexing a Rust project no longer hangs on a file whose `use` paths start with the very names they bring in, like `use a::{b, a};` in rustfmt's import-formatting tests; such projects, rustfmt itself included, now index in seconds.
- A Ruby file with a very long heredoc word, or a long string written right after `<<`, no longer stops indexing or a running server, and no longer makes every Ruby file after it fail to parse.
- TypeScript: a local set by a method call on a const imported from another file (`const parent = client.create()`) now takes the type that method returns, as it already did for a parameter or a const of the same file, so calls on it link to the right method. (#3572)


## [1.6.7] - 2026-11-30
Expand Down
89 changes: 89 additions & 0 deletions __tests__/ts-member-call-result-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,92 @@ describe('a local a member call fills in takes the type the member returns (#342
expect(calls(fresh.graph, 'run', 'area')).toEqual(synced);
}, 90_000);
});

describe('a member call on an imported const takes the type the member returns (#3572)', () => {
const TYPES = 'export type Client = {\n\tcreate: (o?: object) => Client;\n\textend: (o?: object) => Client;\n};\n';
const OTHER_EXTEND = 'export class Other {\n\textend(): number {\n\t\treturn 1;\n\t}\n}\n';
const CLIENT = "import type {Client} from './types';\n\nconst makeClient = (): Client => ({}) as Client;\n\nexport const client: Client = makeClient();\n";
const USE_CLIENT =
"import {client} from './client';\nimport type {Client} from './types';\n\n" +
'export function viaImport() {\n\tconst parent = client.create({});\n\treturn parent.extend({});\n}\n\n' +
'export function viaParam(c: Client) {\n\tconst parent = c.create({});\n\treturn parent.extend({});\n}\n';

it('links the call on the local as it does for a parameter', async () => {
const { graph } = await index({ 'src/types.ts': TYPES, 'src/other.ts': OTHER_EXTEND, 'src/client.ts': CLIENT, 'src/use.ts': USE_CLIENT });
expect(calls(graph, 'viaParam', 'extend')).toEqual(['Client::extend (src/types.ts:3) 0.9']);
expect(calls(graph, 'viaImport', 'extend')).toEqual(['Client::extend (src/types.ts:3) 0.9']);
});

it('reads nothing new for an imported const with no type written, or a `let` the module may reassign', async () => {
const { graph } = await index({
'src/types.ts': TYPES,
'src/other.ts': OTHER_EXTEND,
'src/client.ts': "import type {Client} from './types';\nconst makeClient = (): Client => ({}) as Client;\nexport const untyped = makeClient();\nexport let reassigned: Client = makeClient();\n",
'src/use.ts': "import {untyped, reassigned} from './client';\n" +
'export function viaUntyped() {\n\tconst parent = untyped.create({});\n\treturn parent.extend({});\n}\n' +
'export function viaLet() {\n\tconst parent = reassigned.create({});\n\treturn parent.extend({});\n}\n',
});
for (const fn of ['viaUntyped', 'viaLet']) expect(calls(graph, fn, 'extend'), fn).toEqual([]);
});

it('links a call on an imported const whose name is capitalized', async () => {
const { graph } = await index({
'src/types.ts': TYPES,
'src/other.ts': OTHER_EXTEND,
'src/client.ts': "import type {Client} from './types';\nconst makeClient = (): Client => ({}) as Client;\nexport const API: Client = makeClient();\n",
'src/use.ts': "import {API} from './client';\nexport function viaCapital() {\n\tconst parent = API.create({});\n\treturn parent.extend({});\n}\n",
});
expect(calls(graph, 'viaCapital', 'extend')).toEqual(['Client::extend (src/types.ts:3) 0.9']);
});

it('a sync re-reads a call through a member that returns its argument when the const changes type', async () => {
const files = {
'src/store.ts': 'export class Store {\n\tadd<T>(o: T): T {\n\t\treturn o;\n\t}\n}\nexport class Store2 {\n\tadd(o: object): number {\n\t\treturn 1;\n\t}\n}\n',
'src/widget.ts': 'export class Widget {\n\trender(): void {}\n}\nexport class Gadget {\n\trender(): void {}\n}\n',
'src/client.ts': "import {Store} from './store';\nexport const store: Store = new Store();\n",
'src/use.ts': "import {store} from './client';\nimport {Widget} from './widget';\nexport function f() {\n\tconst w = store.add(new Widget());\n\treturn w.render();\n}\n",
};
const { graph, root } = await index(files);
expect(calls(graph, 'f', 'render').map((c) => c.replace(/ [\d.]+$/, ''))).toEqual(['Widget::render (src/widget.ts:2)']);
const edited = "import {Store2} from './store';\nexport const store: Store2 = new Store2();\n";
write(root, { 'src/client.ts': edited });
await graph.sync();
const fresh = await index({ ...files, 'src/client.ts': edited });
expect(calls(fresh.graph, 'f', 'render')).toEqual([]);
expect(calls(graph, 'f', 'render')).toEqual(calls(fresh.graph, 'f', 'render'));
}, 90_000);

it('a sync re-reads a local the const once gave an outside value when the const changes type', async () => {
const files = {
'src/types.ts': 'export type Api = {\n\tget: () => Response;\n};\nexport class Body {\n\tjson(): object {\n\t\treturn {};\n\t}\n}\nexport type ProjApi = {\n\tget: () => Body;\n};\n',
'src/client.ts': "import type {Api} from './types';\nconst make = (): Api => ({}) as Api;\nexport const api: Api = make();\n",
'src/use.ts': "import {api} from './client';\nexport function g() {\n\tconst r = api.get();\n\treturn r.json();\n}\n",
};
const { graph, root } = await index(files);
expect(calls(graph, 'g', 'json')).toEqual([]);
const edited = "import type {ProjApi} from './types';\nconst make = (): ProjApi => ({}) as ProjApi;\nexport const api: ProjApi = make();\n";
write(root, { 'src/client.ts': edited });
await graph.sync();
const fresh = await index({ ...files, 'src/client.ts': edited });
expect(calls(fresh.graph, 'g', 'json')).not.toEqual([]);
expect(calls(graph, 'g', 'json')).toEqual(calls(fresh.graph, 'g', 'json'));
}, 90_000);

it('a sync re-reads the call when the file declaring the const changes its type', async () => {
const files = {
'src/types.ts': TYPES + 'export type Svc = {\n\tcreate: () => Svc;\n\textend: () => Svc;\n};\n',
'src/other.ts': OTHER_EXTEND,
'src/client.ts': CLIENT,
'src/use.ts': USE_CLIENT,
};
const { graph, root } = await index(files);
expect(calls(graph, 'viaImport', 'extend')).toEqual(['Client::extend (src/types.ts:3) 0.9']);
const edited = "import type {Svc} from './types';\n\nconst makeSvc = (): Svc => ({}) as Svc;\n\nexport const client: Svc = makeSvc();\n";
write(root, { 'src/client.ts': edited });
await graph.sync();
const synced = calls(graph, 'viaImport', 'extend');
expect(synced).toEqual(['Svc::extend (src/types.ts:7) 0.9']);
const fresh = await index({ ...files, 'src/client.ts': edited });
expect(calls(fresh.graph, 'viaImport', 'extend')).toEqual(synced);
}, 90_000);
});
91 changes: 79 additions & 12 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25155,6 +25155,8 @@ export function clearNameMatcherMemos(context: ResolutionContext): void {
AWAITED_TYPE_MEMO.delete(context);
AWAITED_FILES.delete(context);
TS_IMPORTED_TYPE_FILES.delete(context);
TS_IMPORTED_CONSTS.delete(context);
TS_IMPORTED_CONST_NODES.delete(context);
TS_NAMED_CLASSES.delete(context);
TS_AMBIENT_MODULE_FILES.delete(context);
TS_GLOBAL_SCOPES.delete(context);
Expand Down Expand Up @@ -27328,7 +27330,7 @@ function jsReceiverBindingReading(receiver: string, ref: UnresolvedRef, context:
* reading consulted, for a sync to re-open the answer when one of them
* changes (`typeFrom`).
*/
type JsReadElsewhere = JsBindingReading & { file: string; language: Language; bound: number; from: string[] };
type JsReadElsewhere = JsBindingReading & { file: string; language: Language; bound: number; from: string[]; via?: string };

/**
* Where the `(`, `[` or `{` at `open` closes in `code`, counting only those
Expand Down Expand Up @@ -27793,7 +27795,8 @@ export function jsReceiverTypeFile(receiver: string, ref: UnresolvedRef, context
if (!reading) return jsOutsideValueBinding(receiver, ref, context)?.from;
const decl: GoReceiverDecl = {};
if (inferLocalReceiverType(receiver, ref, context, decl) && decl.line !== undefined && decl.line >= reading.bound) return undefined;
return reading.file !== ref.filePath ? reading.file : reading.from[0];
// Through a const the file imports, the const's file decides the receiver (#3572).
return reading.via ?? (reading.file !== ref.filePath ? reading.file : reading.from[0]);
}

/**
Expand Down Expand Up @@ -28112,7 +28115,8 @@ function jsDeclaredFunctionParameterReading(
}

/** A type as a file of the project writes it (`raw`, on `line` of `file`, read as `language`), and every file the reading looked at (`from`); `args` when a declaration wrote it with type arguments, which `raw` leaves out. */
type TsTypeRead = { raw: string; file: string; language: Language; line: number; from: string[]; args?: boolean };
/** `via`: the file of a const the file imports that the reading went through (#3572). */
type TsTypeRead = { raw: string; file: string; language: Language; line: number; from: string[]; args?: boolean; via?: string };

/** Per context: `<file>\0<start line>\0<name>` → tsReturnedType's answer. */
const TS_RETURNED_TYPES = new WeakMap<ResolutionContext, Map<string, TsTypeRead | null>>();
Expand Down Expand Up @@ -28252,25 +28256,86 @@ function tsValueType(file: JsScopeFile, at: number, where: UnresolvedRef, contex
// the class's one static method of the name says it returns (#2946).
if (!site && /^[A-Z]/.test(head!)) {
const cls = tsNamedType(head!, { filePath: where.filePath, language: where.language, id: '' }, where, context);
if (!cls || cls === 'outside' || cls.kind !== 'class') return null;
const read = tsStaticReturnedType(cls, member!, where, context);
return read && { ...read, from: [...read.from, cls.filePath] };
if (cls && cls !== 'outside' && cls.kind === 'class') {
const read = tsStaticReturnedType(cls, member!, where, context);
return read && { ...read, from: [...read.from, cls.filePath] };
}
// `API.create()` on a const the file imports is read as one (#3572).
if (!jsFileImportsName(head!, where, context)) return null;
}
const reading = site ? jsBindingReading(head!, site, file) : null;
// A const the file imports is typed where it is declared (#3572).
const imported = site ? null : jsImportedConstReading(head!, at + lead, file, where, context);
const reading = site ? jsBindingReading(head!, site, file) : imported?.reading ?? null;
if (!reading) return null;
const there = imported?.there ?? where;
// What the reading stands on includes the const's own file (#3572).
const viaConst = (r: TsTypeRead | null): TsTypeRead | null =>
r && imported ? { ...r, from: [...r.from, there.filePath], via: r.via ?? there.filePath } : r;
const typeName = reading.raw.replace(/\s*<[\s\S]*$/, '');
const owner = tsNamedType(typeName, { filePath: where.filePath, language: where.language, id: '' }, where, context);
const owner = tsNamedType(typeName, { filePath: there.filePath, language: there.language, id: '' }, there, context);
if (owner === 'outside') return null;
if (owner?.kind === 'class') {
const methods = tsClassMethods(owner, member!, where, context, 0);
const methods = tsClassMethods(owner, member!, there, context, 0);
const args = tsTopLevelParts(code.slice(open + 1, close));
if (methods.length === 1 && tsReturnsItsArgument(methods[0]!, context) && args && args.length === 1) {
const inner = tsValueType(file, open + 1, where, context, walk, false);
return inner && { ...inner, from: [...inner.from, owner.filePath, methods[0]!.filePath] };
return viaConst(inner && { ...inner, from: [...inner.from, owner.filePath, methods[0]!.filePath] });
}
}
// `recv.make()`: what the one declaration of `make` on recv's type says it returns (#3422).
return tsMemberReturnedType(typeName, owner, member!, where, context);
return viaConst(tsMemberReturnedType(typeName, owner, member!, there, context));
}

/** Whether the file imports a binding of the name (importsBoundTo, not a pass over its imports). */
function jsFileImportsName(name: string, ref: UnresolvedRef, context: ResolutionContext): boolean {
const mappings = context.getImportMappings?.(ref.filePath, ref.language);
return !!mappings && importsBoundTo(mappings, name).length > 0;
}

/** Per context: an imported const's node id → its reading where it is declared, or null (#3572). */
const TS_IMPORTED_CONSTS = new WeakMap<ResolutionContext, Map<string, JsBindingReading | null>>();
/** Per context: `<file>\0<name>` → the project const the file's import of the name is, or null (#3572). */
const TS_IMPORTED_CONST_NODES = new WeakMap<ResolutionContext, Map<string, Node | null>>();

/**
* What a `const` the file imports by name from a project module says its
* value is (jsBindingReading), read at its declaration in that module, with
* a ref located there for the names its type is written with (#3572). Null
* for anything else: a `let` or `var` the module may reassign, a const with
* nothing written that says its value, an import from outside the project.
*/
function jsImportedConstReading(
name: string, at: number, file: JsScopeFile, ref: UnresolvedRef, context: ResolutionContext,
): { reading: JsBindingReading; there: UnresolvedRef } | null {
let memo = TS_IMPORTED_CONSTS.get(context);
if (!memo) TS_IMPORTED_CONSTS.set(context, (memo = new Map()));
// What the file's import of the name resolves to is asked once per file and name.
const key = `${ref.filePath}\0${name}`;
let found = TS_IMPORTED_CONST_NODES.get(context)?.get(key);
if (found === undefined) {
let nodes = TS_IMPORTED_CONST_NODES.get(context);
if (!nodes) TS_IMPORTED_CONST_NODES.set(context, (nodes = new Map()));
found = null;
if (jsFileImportsName(name, ref, context)) {
const line = jsLineOf(file, at);
const resolved = context.resolveImport?.({ ...ref, referenceName: name, referenceKind: 'calls', line, column: at - file.lineStarts[line - 1]! });
const node = resolved ? context.getNodeById?.(resolved.targetNodeId) : undefined;
if (node && node.kind === 'constant' && node.qualifiedName === node.name && ESM_FAMILY.has(node.language)) found = node;
}
nodes.set(key, found);
}
const node = found;
if (!node) return null;
let reading = memo.get(node.id);
if (reading === undefined) {
// The declaring file is read once per const, not once per call on it.
const declared = jsScopeFile(node.filePath, context);
const site = declared && jsBindingAt(node.name, declared, (declared.lineStarts[node.startLine - 1] ?? declared.code.length) + node.startColumn);
reading = declared && site && site.kind === 'declaration' && /^const\b/.test(declared.code.slice(site.decl ?? site.at, (site.decl ?? site.at) + 6))
? jsBindingReading(node.name, site, declared) : null;
memo.set(node.id, reading);
}
return reading && { reading, there: { ...ref, filePath: node.filePath, language: node.language, line: node.startLine, column: node.startColumn } };
}

/**
Expand Down Expand Up @@ -28299,6 +28364,7 @@ function jsCallResultReading(
language: read.language,
bound: jsLineOf(file, site.at),
from: [...new Set(read.from)].filter((f) => f !== ref.filePath),
...(read.via ? { via: read.via } : {}),
},
from: valueAt,
};
Expand Down Expand Up @@ -28558,7 +28624,8 @@ function jsLocalHoldsOutsideValue(
if (read && !read.args && /^[A-Za-z_$][\w$]*$/.test(read.raw) && !JS_BUILT_INS.has(read.raw) && !TS_PRIMITIVE_TYPES.has(read.raw)) {
const there: UnresolvedRef = { ...where, filePath: read.file, language: read.language };
is = tsImportedTypeFile(read.raw, there, context) === undefined && isUndeclaredTypeName(read.raw, there, context);
if (is) inner.from = [read.file, ...read.from].find((f) => f !== where.filePath);
// Through an imported const, its file is the one a sync waits for (#3572).
if (is) inner.from = read.via ?? [read.file, ...read.from].find((f) => f !== where.filePath);
}
}
if (inner.capped) {
Expand Down