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 @@ -35,6 +35,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- A CodeGraph MCP server started in a folder with no index no longer starts its separate hang-watchdog process until the session first calls a tool or opens a project, so sessions that only list the tools, as many hosts open them, use less memory. Thanks @AiurArtanis for the report and @johnhldiver-beep for #3257. (#3250)
- A CodeGraph server whose project folder is deleted, like a removed git worktree, now exits within about half a minute, closing its file watcher and dropping its entry from `codegraph list`, instead of running until its last session ends and it times out. On Windows it also stops keeping that folder's index files from being deleted. Thanks @deniskern for the report and @johnhldiver-beep for #3259. (#3245)
- In JavaScript and TypeScript, `this.findAll()` in a class that wraps an imported helper of the same name now links to the class's own method instead of the imported helper. Thanks @inth3shadows for the report. (#2954)
- In JavaScript and TypeScript, a call written on `this`, like `this.cast()` or `this.validate()`, no longer links to a `const`, a `require` binding or a function declaration that only shares its name, in the same file or another, because what the call reaches is a property of the object.
- In TypeScript, a call on a parameter or local named like an import, like `stream.write()` inside `stream(c, async (stream) => …)`, now goes by that parameter or local, and a method called on an imported function no longer links to the function itself; the same mistake through `require` was already fixed in 1.6.3. Thanks @inth3shadows for the report. (#2953)
- In JavaScript and TypeScript, a call to a name that a function around the caller declares for itself, like a helper an inner arrow function calls, now links to that local declaration instead of the file's import of the same name. Thanks @inth3shadows for the report. (#2949)
- In JavaScript and TypeScript, a call to a helper declared inside a `describe(…)` block, or any other callback, now links to the helper that block declares instead of a same-named one from another block that happens to sit nearer. Thanks @inth3shadows for the report. (#2944)
Expand Down
140 changes: 140 additions & 0 deletions __tests__/js-this-call-binding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/**
* A JS/TS call written on `this` reads a property of the object, never a
* lexical binding. The extractor records `this.cast(x)` by the bare name
* `cast`, and since #3345 such a call skips the file's imports (so a class's
* own `cast` wins over `import { cast }`). Name matching then reached the
* file's own `const cast = require('./cast')`: a `calls` edge onto a
* constant, as in mongoose's `Query.prototype._castConditions`. A `function`
* declaration or a `const f = () => …` is a binding too: `this.validate()`
* in fastify's hooks is no call of `validation.js`'s `function validate`.
* A function assigned to a property (`app.set = function set (…)`) is a
* property, and `this.set()` still reaches it.
*/

import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { CodeGraph } from '../src';

describe('a call written on this never links a lexical binding', () => {
let dir: string;
let cg: CodeGraph | undefined;

beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-this-binding-'));
});

afterEach(() => {
cg?.close();
cg = undefined;
fs.rmSync(dir, { recursive: true, force: true });
});

async function index(files: Record<string, string>): Promise<CodeGraph> {
for (const [rel, body] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
fs.writeFileSync(path.join(dir, rel), body);
}
cg = await CodeGraph.init(dir, { index: true });
return cg;
}

/** `kind name@file:line` of every `calls` edge out of the file's nodes (the file itself included), by call line. */
function callsFrom(g: CodeGraph, file: string): string[] {
const sources = new Set([`file:${file}`, ...g.getNodesInFile(file).map((n) => n.id)]);
return [...sources]
.flatMap((id) => g.getOutgoingEdges(id).filter((e) => e.kind === 'calls'))
.map((e) => { const t = g.getNode(e.target)!; return `L${e.line} ${t.kind} ${t.qualifiedName}@${t.filePath}:${t.startLine}`; })
.sort();
}

it("leaves mongoose's this.cast() off the file's require binding", async () => {
const g = await index({
'lib/cast.js': 'module.exports = function cast (obj) { return obj }\n',
'lib/query.js': [
"'use strict'",
"const cast = require('./cast')",
'function Query () { this.model = null }',
'Query.prototype.cast = function (model) { return cast(model) }',
'Query.prototype._castConditions = function () { return this.cast(this.model) }',
'module.exports = Query',
'',
].join('\n'),
'lib/widget.js': [
"const cast = require('./cast')",
'class Widget {',
' run () { return this.cast(1) }',
' build () { return cast(2) }',
'}',
'module.exports = Widget',
'',
].join('\n'),
});
// The bare calls are the import's. `this.cast(…)` names no binding: in a
// prototype method it is the constructor's own `cast` (#3380), and in a
// class with no `cast` member it is nothing.
expect(callsFrom(g, 'lib/query.js')).toEqual(['L4 function cast@lib/cast.js:1', 'L5 method Query::cast@lib/query.js:4']);
expect(callsFrom(g, 'lib/widget.js')).toEqual(['L4 function cast@lib/cast.js:1']);
});

it('takes no declared function or local binding for this.m(), in this file or another', async () => {
const g = await index({
'lib/validation.js': 'function validate (s) { return !!s }\nmodule.exports = { validate }\n',
'lib/hooks.js': [
"const { validate } = require('./validation')",
'class Hooks {',
' add (fn) { this.validate(fn); return validate(fn) }',
'}',
'module.exports = Hooks',
'',
].join('\n'),
'src/finder.ts': [
'const makeFinder = () => (q: string) => [q]',
'const findAll = makeFinder()',
'export const helper = (x: number) => x',
'export class Repo {',
" list () { return this.findAll('x') }",
' twice () { return this.helper(2) }',
" plain () { return findAll('y') }",
'}',
'',
].join('\n'),
});
expect(callsFrom(g, 'lib/hooks.js')).toEqual(['L3 function validate@lib/validation.js:1']);
// `findAll('y')` calls the constant's value; `this.findAll()` and `this.helper()` name no binding.
expect(callsFrom(g, 'src/finder.ts')).toEqual(['L2 function makeFinder@src/finder.ts:1', 'L7 constant findAll@src/finder.ts:2']);
});

it('still reaches a function assigned to a property, and a class member', async () => {
const g = await index({
'lib/app.js': [
"var set = require('./set')",
'var app = exports = module.exports = {}',
'app.set = function set (setting, val) { return this }',
'app.enable = function enable (setting) { return this.set(setting, true) }',
'class Settings {',
' get (k) { return k }',
" load () { return this.get('a') }",
'}',
'',
].join('\n'),
'lib/set.js': 'module.exports = function set (o, k, v) { o[k] = v }\n',
// fastify's shape: a declared function the file hands to a property of its name.
'lib/instance.js': [
'function build () {',
' const fastify = {}',
' fastify.ready = ready',
' fastify.inject = inject',
' function ready (cb) { return cb }',
' function inject (cb) { return this.ready(cb) }',
' return fastify',
'}',
'module.exports = build',
'',
].join('\n'),
});
expect(callsFrom(g, 'lib/app.js')).toEqual(['L4 function set@lib/app.js:3', 'L7 method Settings::get@lib/app.js:6']);
expect(callsFrom(g, 'lib/instance.js')).toEqual(['L6 function build::ready@lib/instance.js:5']);
});
});
5 changes: 5 additions & 0 deletions src/resolution/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { isJsThisCall } from './name-matcher';
import { isVisibleCppMacro, clearCppMacroVisibility } from './cpp-macro-visibility';
import { isCppConstructorRef, matchCppConstructor } from './cpp-constructor';
import { isRefusedDeepThisTarget } from './name-matcher';
import { isLexicalBindingOfJsThisCall } from './name-matcher';
import { isCppDeclaredTypeRef, isCppSupertypeRef, matchCppDeclaredType, matchCppSupertype, clearCppSupertypeMemos } from './cpp-supertypes';
import { gateSwiftTypeTarget, clearSwiftTypeVisibility, swiftExtendedConformances } from './swift-type-visibility';
import { clearDartLibraryMemos } from './dart-libraries';
Expand Down Expand Up @@ -4470,6 +4471,10 @@ export class ReferenceResolver {
// through its package; as a struct here it read as an instantiation.
if (target && ref.language === 'go' && GO_TYPE_KINDS.has(target.kind) &&
!ref.referenceName.includes('.') && !isGoBareName(ref, this.context)) return null;
// A JS/TS call written on `this` reads a property of the object: a
// `const`/`let`/`var` or a `function` declaration is a lexical binding,
// never what `this.cast()` names (see isLexicalBindingOfJsThisCall).
if (target && isLexicalBindingOfJsThisCall(target, ref, this.context)) return null;
}

// A TypeScript interface or type alias is no value: nothing calls one or
Expand Down
44 changes: 44 additions & 0 deletions src/resolution/name-matcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4737,6 +4737,50 @@ function pythonValueNames(bound: { value: string; filePath: string; line: number
return pythonReceiverBinding(target.name, { ...ref, filePath: bound.filePath, line: bound.line, column: 0 }, context) !== 'local';
}

/**
* Whether `target` is a lexical binding, which a JS/TS call written on `this`
* never names. `this.cast(x)` (or `super.cast(x)`, or fields deep,
* `this.a.b.cast(x)`) is recorded by the bare name `cast` and reads a
* property of the object: no `const`/`let`/`var` (a `require` binding among
* them) and no `function` declaration, in this file or another, is that
* property. Since #3345 such a call skips the file's imports, so name matching
* reached the file's own `const cast = require('./cast')`. A function
* assigned to a property (`app.set = function set (…)`), an object literal's
* member and a class's member are properties, and stay answers, as does a
* declared function the calling file hands to a property of its name:
* fastify's `fastify.ready = ready`, then `this.ready()` in the instance's
* methods.
*/
export function isLexicalBindingOfJsThisCall(target: Node, ref: UnresolvedRef, context: ResolutionContext): boolean {
if (!JS_FAMILY.has(ref.language) || ref.referenceKind !== 'calls') return false;
if (target.kind === 'function') {
if (!isJsDeclaredFunction(target, context)) return false;
const name = target.name.replace(/\$/g, '\\$');
if (new RegExp(String.raw`\.\s*${name}\s*=\s*${name}(?![\w$])`).test(context.readFile(ref.filePath) ?? '')) return false;
} else if (target.kind !== 'constant' && target.kind !== 'variable') {
return false;
}
const written = bareCallReceiver(ref, context);
return written !== null && (written.receiver === 'self' || written.links.length > 0);
}

/**
* Whether a JS/TS function node binds its name lexically, as read where it
* starts: a `function` declaration (`export default async function m (…)`,
* `declare function m (…)`) or a `const`/`let`/`var` declarator's value
* (`const m = (…) =>`, `let m: Fn = function (…)`), not a function assigned
* to a property or written as an object's or a class's member.
*/
function isJsDeclaredFunction(n: Node, context: ResolutionContext): boolean {
const line = (context.getFileLines?.(n.filePath) ?? context.readFile(n.filePath)?.split(/\r?\n/))?.[n.startLine - 1];
if (line === undefined) return false;
// What a minified line holds before the function is read only as far back as a declarator reaches.
const head = line.slice(Math.max(0, n.startColumn - 200), n.startColumn);
if (n.startColumn <= 200 && /^\s*(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:async\s+)?$/.test(head) &&
/^(?:export\s+(?:default\s+)?)?(?:declare\s+)?(?:async\s+)?function\b/.test(line.slice(n.startColumn, n.startColumn + 64))) return true;
return /(?:^|[^\w$.])(?:const|let|var)\s+[\w$]+\s*(?::[^=]*)?=\s*(?:async\s*)?$/.test(head);
}

/** Whether a call recorded by its bare name is written on something other than the caller's own object. */
function isCollapsedNonRecursion(ref: UnresolvedRef, context: ResolutionContext): boolean {
const written = bareCallReceiver(ref, context);
Expand Down