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 @@ -23,6 +23,7 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- In Python, a method called on a local bound from a call, like `made = make(q)` or `s = store.stage()`, now goes by the type the called function or method declares it returns: a `Path`, a `str` or another class from outside your project links nothing, where any project method that happened to share the name could, and one of your own classes links its own method even when other classes have one of that name. Thanks @inth3shadows for the reports and @johnhldiver-beep. (#3038, #3240)
- In Python, a `from x import name` written inside a function now applies to that function only, so calls of `name` in the rest of the file reach the file's own `def name` instead of the imported function, as a wrapper that imports the original it wraps expects. Thanks @inth3shadows for the report. (#3229)
- JavaScript and TypeScript event handlers registered with `on()` are now linked only from code that emits on the same emitter, and to the handler defined where they are registered, so two modules that each keep their own emitter and use the same event name no longer cross-link. Thanks @inth3shadows for the report. (#2973)
- In JavaScript, methods written the classic way, `Ctor.prototype.m = function () {…}` and a static `Ctor.m = function () {…}`, are now indexed as methods of their constructor, and the functions of a `module.exports = {…}` object as that module's exports, so `this.m()` inside them reaches the constructor's or the object's own `m` instead of an unrelated function of the same name elsewhere. Thanks @inth3shadows for the report. (#2966)
- In Rust, a call through a module that a glob `use` brings in, like `gzip::write()` in a test module with `use super::*`, or that a `use` inside the function names, now links to that module's function again. Thanks @Egrn for the report and @mohitdixit02. (#3253)
- In Rust, `codegraph_explore`'s blast radius now recognizes unit tests in a `#[cfg(test)]` module or a `tests.rs` file, instead of reporting "no tests found" for the functions they test. Thanks @moogiemode for the report and @maxmilian. (#3265)
- In Rust, a function or method passed as a value through its path, like `g.map(Graph::counts)` or `.map(Self::helper)`, now counts in its callers and impact the way a function passed by name already did, linked only when the path names it for certain: never another type's method of the same name, and never a method of a trait implementation, since which one Rust uses there depends on the type of the argument. Thanks @Egrn for the report and @inth3shadows. (#3254)
Expand Down
6 changes: 4 additions & 2 deletions __tests__/js-object-literal-members.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ describe.each(['native', 'wasm'].filter((backend) => backend === 'wasm' || kerne
expect(callees(g, 'c')).toEqual([]);
});

it('leaves CommonJS exports, prototypes, call arguments, data and minified bundles as they were', async () => {
it('leaves prototype literals, call arguments, data and minified bundles as they were', async () => {
const g = await index({
'shapes.js': [
'module.exports = { cjs() { return 1; } };',
Expand All @@ -293,10 +293,12 @@ describe.each(['native', 'wasm'].filter((backend) => backend === 'wasm' || kerne
'iife.js': '(function () { var e; if (!e) { e = { getItem: function () { return 1; } }; } })();\n',
});
// …and a plain name reassigned inside a function (a bundle's `e = {…}`) is a local.
for (const name of ['cjs', 'proto', 'ephemeral', 'onThis', 'b', 'c', 'd', 'getItem']) {
for (const name of ['proto', 'ephemeral', 'onThis', 'b', 'c', 'd', 'getItem']) {
expect(g.getNodesByName(name), name).toEqual([]);
}
expect(node(g, 'data').kind).toBe('constant');
// The module's own export object owns its members (#2966).
expect(node(g, 'module.exports::cjs').kind).toBe('function');
});

it('keeps a <script setup> literal\'s members under their owner', async () => {
Expand Down
11 changes: 6 additions & 5 deletions __tests__/js-prototype-member-guess.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* A JS file that gives an object a member itself, `Sha256.prototype.update =
* function…`, holds what the index has no node for. The one method of that
* name elsewhere is no likelier then: rails' `buffer.update(data)` in
* activestorage.js is its bundled sha256's, not the guides' turbo
* `History#update`.
* function…`, holds what the index has no node for when the file doesn't
* declare `Sha256` (a constructor it declares has its methods as nodes, #2966).
* The one method of that name elsewhere is no likelier then: rails'
* `buffer.update(data)` in activestorage.js is its bundled sha256's, not the
* guides' turbo `History#update`.
*/
import { describe, it, expect, afterAll, beforeAll } from 'vitest';
import * as fs from 'fs';
Expand All @@ -22,7 +23,7 @@ const FILES: Record<string, string> = {
}
`,
'app/bundle.js': `(function () {
function Sha256() {}
var Sha256 = window.Sha256;
Sha256.prototype.update = function (message) {
return this;
};
Expand Down
257 changes: 257 additions & 0 deletions __tests__/js-prototype-methods.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
/**
* The classic JavaScript ways to give a constructor its methods (#2966):
*
* function Hooks () {}
* Hooks.prototype.validate = function (hook, fn) {…} // a method
* Hooks.create = function () {…} // a static method
* module.exports = { inspect () {…}, toJSON () {…} } // the module's object
*
* None of them had a node: the calls inside were credited to the file, and a
* `this.validate()` between them linked by bare name to whatever else in the
* project is called `validate`, a function in another file or an interface's
* method in a `.d.ts`. Now a function assigned to `Ctor.prototype.m` or
* `Ctor.m`, `Ctor` a function or class the same scope declares, is method `m`
* of `Ctor` (`Ctor::m`, contained by it, static for `Ctor.m`), and the
* members of `module.exports = {…}` are the module's exported functions
* (`module.exports::m`). `this.m()` in any of them means the owner's own `m`,
* and `Ctor.m()` / `require('./x').m()` from another file reach them.
*/

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

const kernelBuilt = fs.existsSync(path.join(__dirname, '../codegraph-kernel/prebuilds',
`${process.platform}-${process.arch}`, 'codegraph-kernel.node'));

/** The issue's files, as written there. */
const ISSUE: Record<string, string> = {
'lib/hooks.js': [
"'use strict'",
'function Hooks () { this.list = [] }',
'Hooks.prototype.validate = function (hook, fn) { return typeof fn === \'function\' }',
'Hooks.prototype.add = function (hook, fn) {',
' this.validate(hook, fn) // line 5',
' this.list.push(fn)',
'}',
'module.exports = Hooks',
'',
].join('\n'),
'lib/validation.js': 'function validate (schema, data) { return true }\nmodule.exports = { validate }\n',
'lib/reply.js': [
'function Reply () {}',
'Reply.prototype.getHeader = function (k) { return k }',
"Reply.prototype.send = function () { return this.getHeader('content-type') } // line 3",
'module.exports = Reply',
'',
].join('\n'),
'lib/types.d.ts': 'export interface FastifyReply { getHeader(key: string): string | undefined; }\n',
'lib/model.js': [
'function Model () {}',
'Model.insertMany = async function insertMany (arr) { return arr }',
'Model.init = function init () { return Model.insertMany([]) }',
'module.exports = Model',
'',
].join('\n'),
'lib/other.js': 'class Cast { init () { return 1 } insertMany () { return 2 } }\n',
'test/model.test.js': [
"const Model = require('../lib/model')",
'async function t () { await Model.init(); await Model.insertMany([1]) }',
'',
].join('\n'),
'lib/context.js': [
'module.exports = {',
' inspect () { return this.toJSON() },',
' toJSON () { return {} }',
'}',
'',
].join('\n'),
'lib/application.js': 'class Application { toJSON () { return { app: 1 } } }\nmodule.exports = Application\n',
};

describe.each(['native', 'wasm'].filter((backend) => backend === 'wasm' || kernelBuilt))(
'constructor and module-object methods (%s, #2966)', (backend) => {
let dir: string;
let cg: CodeGraph | undefined;

beforeEach(() => {
vi.stubEnv('CODEGRAPH_KERNEL', backend === 'wasm' ? '0' : '1');
vi.stubEnv('CODEGRAPH_KERNEL_LANGS', 'all');
resetKernelForTests();
if (backend === 'native') expect(getKernel()).not.toBeNull();
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-2966-'));
});

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

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;
}

/** The one node with this qualified name (in `file`, when several share it). */
function node(g: CodeGraph, qualifiedName: string, file?: string) {
const found = g.getNodesByQualifiedName(qualifiedName).filter((n) => !file || n.filePath === file);
expect(found, qualifiedName).toHaveLength(1);
return found[0]!;
}
/** `qualifiedName@file` at the other end of a node's `calls` edges. */
const callees = (g: CodeGraph, qn: string, file?: string) =>
g.getOutgoingEdges(node(g, qn, file).id)
.filter((e) => e.kind === 'calls')
.map((e) => { const t = g.getNode(e.target)!; return `${t.qualifiedName}@${t.filePath}`; })
.sort();

it("indexes the issue's methods on their constructors, and links the calls between them there", async () => {
const g = await index(ISSUE);
for (const [qn, isStatic] of [
['Hooks::validate', false], ['Hooks::add', false], ['Reply::getHeader', false], ['Reply::send', false],
['Model::insertMany', true], ['Model::init', true],
] as const) {
const method = node(g, qn);
expect(method.kind, qn).toBe('method');
expect(method.isStatic ?? false, qn).toBe(isStatic);
// Contained by the constructor, as a class contains its methods.
const owner = g.getIncomingEdges(method.id).filter((e) => e.kind === 'contains').map((e) => g.getNode(e.source)!.qualifiedName);
expect(owner, qn).toEqual([qn.split('::')[0]]);
}
expect(node(g, 'Model::insertMany').isAsync).toBe(true);

expect(callees(g, 'Hooks::add')).toEqual(['Hooks::validate@lib/hooks.js']);
expect(callees(g, 'Reply::send')).toEqual(['Reply::getHeader@lib/reply.js']);
expect(callees(g, 'Model::init')).toEqual(['Model::insertMany@lib/model.js']);
expect(callees(g, 't')).toEqual(['Model::init@lib/model.js', 'Model::insertMany@lib/model.js']);
// The module's object owns its members, and `this.toJSON()` is its own.
for (const qn of ['module.exports::inspect', 'module.exports::toJSON']) {
expect(node(g, qn).kind, qn).toBe('function');
expect(node(g, qn).isExported, qn).toBe(true);
}
expect(callees(g, 'module.exports::inspect')).toEqual(['module.exports::toJSON@lib/context.js']);
// Nothing is credited to the files any more.
for (const file of ['lib/hooks.js', 'lib/reply.js', 'lib/context.js']) {
const calls = g.getOutgoingEdges(`file:${file}`).filter((e) => e.kind === 'calls');
expect(calls, file).toEqual([]);
}
});

it('takes every function shape, and a constructor in a wrapper or factory scope', async () => {
const g = await index({
'lib/queue.js': [
'(function (root) {',
' function Queue () { this.items = []; this.reset() }',
' Queue.prototype.reset = function () { this.items = [] }',
' Queue.prototype.push = async function (x) { this.items.push(x); return this.size() }',
' Queue.prototype.size = () => 0',
' Queue.prototype.drain = function* () { yield 1 }',
' Queue.from = function build (list) { return new Queue() }',
' root.Queue = Queue',
'})(this)',
'',
].join('\n'),
'lib/factory.js': [
'function makeStack () {',
' function Stack () {}',
' Stack.prototype.peek = function () { return this.top() }',
' Stack.prototype.top = function () { return 1 }',
' return Stack',
'}',
'class Widget {}',
'Widget.prototype.render = function () { return 1 }',
'Widget.create = function () { return new Widget() }',
'module.exports = { makeStack, Widget }',
'',
].join('\n'),
});
for (const qn of ['Queue::reset', 'Queue::push', 'Queue::size', 'Queue::drain', 'Queue::from',
'makeStack::Stack::peek', 'makeStack::Stack::top', 'Widget::render', 'Widget::create']) {
expect(node(g, qn).kind, qn).toBe('method');
}
// The static is named by the property callers use, not the expression's own name.
expect(g.getNodesByName('build')).toEqual([]);
expect(callees(g, 'Queue::push')).toEqual(['Queue::size@lib/queue.js']);
// The constructor's own `this.reset()` is its method.
expect(callees(g, 'Queue')).toEqual(['Queue::reset@lib/queue.js']);
expect(callees(g, 'makeStack::Stack::peek')).toEqual(['makeStack::Stack::top@lib/factory.js']);
});

it('leaves other assignment targets as they were', async () => {
const g = await index({
'lib/app.js': [
"const EventEmitter = require('events')",
'var app = exports = module.exports = {}',
'app.use = function use (fn) { return fn }',
'exports.handle = function (req) { return req }',
'EventEmitter.prototype.patched = function () { return 1 }',
'Later.prototype.early = function () { return 1 }',
'function Later () {}',
"Later.prototype['computed'] = function () { return 1 }",
'Later.prototype = { literal () { return 1 } }',
'',
].join('\n'),
});
// An object's member, a CommonJS export and an imported constructor keep
// the shape they had: a function named by its expression or export.
expect(node(g, 'use').kind).toBe('function');
expect(node(g, 'handle').kind).toBe('function');
for (const name of ['patched', 'early', 'computed', 'literal']) expect(g.getNodesByName(name), name).toEqual([]);
expect(g.getNodesByName('Later').map((n) => n.kind)).toEqual(['function']);
});

it('reaches a constructor\'s statics and the module object\'s members from another file', async () => {
const g = await index({
'lib/hooks.js': [
'function Hooks () {}',
'Hooks.create = function () { return new Hooks() }',
'Hooks.prototype.add = function () { return 1 }',
'module.exports = Hooks',
'',
].join('\n'),
'lib/context.js': 'const proto = module.exports = {\n inspect () { return 1 },\n toJSON () { return {} }\n}\n',
'lib/app.js': [
"const Hooks = require('./hooks')",
"const context = require('./context')",
"const { inspect } = require('./context')",
'function run () {',
' Hooks.create()',
' context.toJSON()',
' return inspect()',
'}',
'module.exports = { run }',
'',
].join('\n'),
});
expect(callees(g, 'run')).toEqual([
'Hooks::create@lib/hooks.js', 'module.exports::inspect@lib/context.js', 'module.exports::toJSON@lib/context.js',
]);
});

it('keeps this.m() on the constructor\'s own m where the file also imports an m', async () => {
const g = await index({
'lib/validation.js': 'function validate (s) { return !!s }\nmodule.exports = { validate }\n',
'lib/schemas.js': [
"const { validate } = require('./validation')",
'function Schemas () {}',
'Schemas.prototype.validate = function (s) { return validate(s) }',
'Schemas.prototype.add = function (s) { return this.validate(s) }',
'module.exports = Schemas',
'',
].join('\n'),
});
expect(callees(g, 'Schemas::add')).toEqual(['Schemas::validate@lib/schemas.js']);
// A bare call is still the import's.
expect(callees(g, 'Schemas::validate')).toEqual(['validate@lib/validation.js']);
});
});
41 changes: 40 additions & 1 deletion __tests__/kernel-tsjs-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,48 @@ describe.skipIf(!kernelBuilt)('kernel TS/JS extraction parity', () => {
expect(result.nodes.map((n) => n.qualifiedName)).toEqual(expect.arrayContaining([
'Api::read', 'Api::close', 'Api::gen', 'Api::quoted-key', 'Exported::save', 'Local::run', 'window.WS',
'window.WS::ws', 'App.utils::pad', 'dw_page::start', 'ns.late::go', 'self.handlers::click',
'module.exports::cjs',
]));
// A plain name reassigned inside a function is a local, not a namespace.
for (const name of ['cjs', 'proto', 'ephemeral', 'data', 'on']) expect(result.nodes.some((n) => n.name === name), name).toBe(false);
for (const name of ['proto', 'ephemeral', 'data', 'on']) expect(result.nodes.some((n) => n.name === name), name).toBe(false);
}
});

it.each([
['ts', 'typescript'], ['tsx', 'tsx'], ['js', 'javascript'], ['jsx', 'jsx'],
] as const)('a constructor\'s prototype and static functions are its methods: %s (#2966)', (ext, language) => {
const source = [
'/* é😀 */ function Hooks() { this.validate(); }',
'/** Checks a hook. */',
'Hooks.prototype.validate = function (hook) { return check(hook); };',
'Hooks.prototype.add = async function add(hook) { this.validate(hook); };',
'Hooks.prototype.size = () => 0;',
'Hooks.prototype.each = function* () { yield 1; };',
'Hooks.create = function build() { return new Hooks(); };',
'class Widget {}',
'Widget.prototype.render = function () { return 1; };',
'(function () { function Queue() {} Queue.prototype.push = function (x) { return x; }; })();',
'function factory() { function Stack() {} Stack.prototype.peek = function () { return 1; }; return Stack; }',
'app.use = function use() {};',
'exports.handle = function () {};',
'Later.prototype.early = function () {};',
'function Later() {}',
"Later.prototype['computed'] = function () {};",
'const proto = module.exports = { inspect() { return this.toJSON(); }, toJSON() { return {}; } };',
'function check(h) { return h; }',
'',
].join('\n');
for (const ending of ['\n', '\r\n']) {
const result = assertParity(`proto.${ext}`, source.replace(/\n/g, ending), language);
const methods = result.nodes.filter((n) => n.kind === 'method').map((n) => `${n.qualifiedName}${n.isStatic ? ' static' : ''}`);
expect(methods.sort()).toEqual([
'Hooks::add', 'Hooks::create static', 'Hooks::each', 'Hooks::size', 'Hooks::validate',
'Queue::push', 'Widget::render', 'factory::Stack::peek',
]);
expect(result.nodes.filter((n) => n.qualifiedName.startsWith('module.exports::')).map((n) => `${n.name} ${n.isExported}`))
.toEqual(['inspect true', 'toJSON true']);
for (const name of ['build', 'early', 'computed']) expect(result.nodes.some((n) => n.name === name), name).toBe(false);
expect(result.nodes.find((n) => n.qualifiedName === 'Hooks::validate')?.docstring).toContain('Checks a hook');
}
});

Expand Down
Loading