Skip to content
Merged
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 @@ -70,6 +70,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In C#, a method passed or stored as a value through its object, like `Task.Run(worker.Run)` or `Action later = worker.Run;`, now counts as a use of that method, so `codegraph callers` and impact show it. Thanks @Gobakabana for the report. (#2906)
- In Swift, an `if` or `while` whose condition is `try await f()` no longer breaks the method around it: the next member landed inside that method, and calls were recorded under names made of source text. Swift files are now read with a newer Swift grammar, which also parses more Swift 6 code without errors. Thanks @bob-codedaptive for the report. (#3212)
- In JavaScript and TypeScript, a call on a local variable declared after another one in the same statement, like `let n = 0, ob = make()`, or beside a default in a destructuring, like `const { ob = make() } = o`, links again when a variable of the same name outside the function holds a library's type, as it did before 1.6.3. Thanks @inth3shadows for the report and @mohitdixit02. (#3293)
- In JavaScript, a call to a member a required module of your project doesn't have, like `utils.missing()` after `const utils = require('./utils')`, no longer links to an unrelated class's method of that name. Thanks @inth3shadows for the report and @johnhldiver-beep. (#3272)

## [1.6.3] - 2026-11-17

Expand Down
118 changes: 118 additions & 0 deletions __tests__/require-missing-member.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* A member a required project module doesn't have links nothing (#3272).
*
* `const utils = require('./utils'); utils.missing()`, where `utils.js`
* exports no `missing`, linked to `missing` of an unrelated class elsewhere,
* the one method of that name, picked by name alone. The import resolver had
* read the module's exports and found none; a namespace import (`import * as
* utils`) and a package's binding were already kept from that guess, a local
* module's default binding was not. What the module does export under the
* name, or what its stated default (a class, an instance) has as a member,
* still links.
*/
import { describe, it, expect, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';

let roots: string[] = [];
let graphs: CodeGraph[] = [];

afterEach(() => {
for (const graph of graphs) graph.close();
graphs = [];
for (const root of roots) fs.rmSync(root, { recursive: true, force: true });
roots = [];
});

async function index(files: Record<string, string>): Promise<CodeGraph> {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-require-missing-'));
roots.push(root);
for (const [rel, content] of Object.entries(files)) {
const file = path.join(root, rel);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
}
const graph = await CodeGraph.init(root, { index: true });
graphs.push(graph);
return graph;
}

/** `caller -> file:qualifiedName` for every `calls` edge out of `file`. */
function callsFrom(graph: CodeGraph, file: string): string[] {
const out: string[] = [];
for (const node of graph.getNodesInFile(file)) {
for (const e of graph.getOutgoingEdges(node.id)) {
if (e.kind !== 'calls') continue;
const target = graph.getNode(e.target)!;
out.push(`${node.name} -> ${target.filePath}:${target.qualifiedName}`);
}
}
return out.sort();
}

const DECOY = 'export class Decoy { missing() { return 42; } render() { return 1; } create() { return 2; } }\n';

describe('a member of a required project module', () => {
it("links nothing when the module doesn't export it (#3272)", async () => {
const graph = await index({
// The issue's reproduction.
'main.js': "const utils = require('./utils');\nfunction run() { return utils.missing(); }\nmodule.exports = run;\n",
'utils.js': 'exports.known = function known() { return 1; };\n',
'decoy.js': DECOY,
// The same through a default import of the CommonJS module, from TypeScript.
'use.ts': "import utils from './utils';\nexport function go() { return utils.missing(); }\n",
});
expect(callsFrom(graph, 'main.js')).toEqual([]);
expect(callsFrom(graph, 'use.ts')).toEqual([]);
}, 120_000);

it('still links what the module exports, or what its stated default has', async () => {
const graph = await index({
'main.js':
"const utils = require('./utils');\nconst Widget = require('./widget');\nconst panel = require('./panel');\n" +
'function run() { return utils.missing(); }\n' +
'function make() { return Widget.create(); }\n' +
'function draw() { return panel.render(); }\n' +
'function lost() { return panel.missing(); }\n',
'utils.js': 'exports.known = function known() { return 1; };\nexports.missing = function missing() { return 2; };\n',
'widget.js': 'module.exports = class Widget {\n static create() { return new Widget(); }\n};\n',
'panel.js': 'class Panel {\n render() { return 3; }\n}\nmodule.exports = new Panel();\n',
'decoy.js': DECOY,
});
expect(callsFrom(graph, 'main.js')).toEqual([
'draw -> panel.js:Panel::render',
'make -> widget.js:Widget::create',
'run -> utils.js:missing',
]);
}, 120_000);

it('reads a parameter that shadows the module binding as itself, not as the module', async () => {
const graph = await index({
// The same function with and without a module binding of its parameter's name.
'shadowed.js': "const utils = require('./utils');\nfunction run(utils) { return utils.missing(); }\nmodule.exports = run;\n",
'plain.js': 'function run(utils) { return utils.missing(); }\nmodule.exports = run;\n',
'typed.ts':
"import utils from './utils';\nimport { Decoy } from './decoy';\n" +
'export function go(utils: Decoy) { return utils.missing(); }\n',
'utils.js': 'exports.known = function known() { return 1; };\n',
'decoy.js': DECOY,
});
// The parameter is read as any untyped receiver is; the module's lack of a `missing` says nothing of it.
expect(callsFrom(graph, 'plain.js')).not.toEqual([]);
expect(callsFrom(graph, 'shadowed.js')).toEqual(callsFrom(graph, 'plain.js'));
expect(callsFrom(graph, 'typed.ts')).toEqual(['go -> decoy.js:Decoy::missing']);
}, 120_000);

it('keeps the guess for a receiver no import binds, and a package binding linking nothing', async () => {
const graph = await index({
'package.json': JSON.stringify({ name: 'app', dependencies: { lodash: '^4.0.0' } }),
'main.js':
"const _ = require('lodash');\nfunction pick() { return _.missing(); }\n" +
'function anyone(thing) { return thing.missing(); }\nmodule.exports = { pick, anyone };\n',
'decoy.js': DECOY,
});
expect(callsFrom(graph, 'main.js').filter((c) => c.startsWith('pick'))).toEqual([]);
}, 120_000);
});
54 changes: 54 additions & 0 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28271,6 +28271,12 @@ function matchMethodCallOn(
(isImportedModuleReceiver(objectOrClass!, ref, context) || isImportedFunctionReceiver(objectOrClass!, ref, context))) {
return null;
}
// So is the default binding of a module of the project's own (#3272).
if (ref.referenceKind === 'calls' && JS_FAMILY.has(ref.language)) {
const ownModule = projectModuleDefaultBinding(objectOrClass!, ref, context);
const settled = ownModule ? projectModuleMemberCall(ownModule, methodName!, ref, context) : undefined;
if (settled !== undefined) return settled;
}

// A receiver written as a type name the project doesn't declare
// (`Exception.Create(…)` in Delphi, `Collections.sort(…)`) is a type from
Expand Down Expand Up @@ -28713,6 +28719,54 @@ function isImportedModuleReceiver(receiver: string, ref: UnresolvedRef, context:
return !!bound && context.getNodeById?.(bound.targetNodeId)?.kind === 'file';
}

/**
* The project module a member call's receiver is the default binding of,
* called on directly: `utils` in `utils.missing()` after `const utils =
* require('./utils')`, or a default import of the module. Null for any other
* receiver.
*/
function projectModuleDefaultBinding(receiver: string, ref: UnresolvedRef, context: ResolutionContext): string | null {
if (receiver.includes('.')) return null;
const binding = context.getImportMappings?.(ref.filePath, ref.language)?.find((m) => m.localName === receiver);
if (!binding?.isDefault || binding.isNamespace) return null;
// A parameter or local of the name in scope at the call is the receiver
// instead, as isImportBinding reads it (#2953).
if (isLocallyBoundJsName(receiver, ref.filePath, context) && jsBindingAroundReference(receiver, ref, context)) return null;
const file = context.resolveModuleFile?.(binding.source, ref.filePath, ref.language);
return file && (context.isIndexedFile?.(file) ?? context.fileExists(file)) ? file : null;
}

/** `module.exports = …`, not `module.exports.x = …`: the module states a default. */
const MODULE_EXPORTS_DEFAULT = /(?:^|[^\w$.])module\.exports\s*=(?![=>])\s*(new\s+([A-Za-z_$][\w$]*)\s*[(<;\r\n]|\{)?/m;
/** An ES module's default: `export default …`, `export { x as default }`, `export = …`. */
const ESM_DEFAULT_EXPORT_STATEMENT = /^[ \t]*export\s+(?:default\b|=)|\bas\s+default\b/m;

/**
* A member called on a project module's default binding that the import
* resolver didn't place (#3272), when that settles it: `undefined` leaves the
* call to the guesses below, as before. The resolver has read what the
* module exports under the name, so where the module states no default — a
* bag of `exports.x = …`, which the binding is the whole of — or states an
* object literal, whose members it reads, the member is none of the
* module's, and a method of some class elsewhere, picked by its name alone,
* is no answer: `utils.missing()` linked a `Decoy` class's `missing`. A
* default the module makes with `new` (`module.exports = new Panel()`) has
* the members of its class, which the module file declares or imports.
*/
function projectModuleMemberCall(file: string, methodName: string, ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null | undefined {
const source = context.readFile(file) ?? '';
const commonJs = source.includes('module.exports') ? MODULE_EXPORTS_DEFAULT.exec(source) : null;
const made = commonJs?.[2];
if (made) {
const language = context.getNodesInFile(file)[0]?.language ?? ref.language;
const declaring = tsImportedTypeFile(made, { ...ref, filePath: file, language }, context) ?? file;
return resolveMethodOnType(made, methodName, ref, context, 0.85, 'instance-method', declaring);
}
if (commonJs) return commonJs[1] === '{' ? null : undefined;
const esmDefault = (source.includes('default') || source.includes('export =')) && ESM_DEFAULT_EXPORT_STATEMENT.test(source);
return esmDefault ? undefined : null;
}

const JS_ASSIGNED_MEMBERS = new WeakMap<ResolutionContext, Map<string, ReadonlySet<string>>>();

/**
Expand Down