Repository navigation
Expand file tree
/
Copy pathjavascriptSemanticAnalysis.structure.test.ts
More file actions
482 lines (458 loc) · 15.6 KB
/
Copy pathjavascriptSemanticAnalysis.structure.test.ts
File metadata and controls
482 lines (458 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import { describe, expect, it } from "vitest";
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
import {
programScope,
bindingById,
bindingsNamed,
onlyBinding,
topLevelBinding,
origin,
} from "./javascriptSemanticAnalysis.fixture.js";
describe("JavaScript semantic analysis: structure 1", () => {
it("resolves imports, require destructuring, aliases, assignments, and shadowing", () => {
const ir = analyzeJavaScriptSemantics(`
import { ipcRenderer as ir } from "electron";
const { ipcMain: bus } = require("electron");
const forwarded = bus;
let assigned;
assigned = ir;
ir.invoke("outside");
bus.handle("main", handler);
function local(ipcRenderer) {
const bus = require("./local-bus.js");
ipcRenderer.send("shadowed");
return bus;
}
`);
expect(ir.coverage).toEqual({
status: "complete",
omittedCount: 0,
});
expect(origin(topLevelBinding(ir, "ir"))).toEqual({
specifier: "electron",
importedPath: ["ipcRenderer"],
});
expect(origin(topLevelBinding(ir, "bus"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
resolutionMode: "require",
});
expect(origin(topLevelBinding(ir, "forwarded"))).toEqual({
specifier: "electron",
importedPath: ["ipcMain"],
resolutionMode: "require",
});
expect(topLevelBinding(ir, "assigned").provenance).toMatchObject({
status: "ambiguous",
origins: [{ specifier: "electron", importedPath: ["ipcRenderer"] }],
});
expect(ir.moduleLinks).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "require",
specifier: "electron",
importedName: "ipcMain",
localName: "bus",
}),
]),
);
const innerBus = bindingsNamed(ir, "bus").find(
({ scopeId }) => scopeId !== programScope(ir).scopeId,
);
expect(innerBus).toBeDefined();
if (innerBus === undefined) return;
expect(origin(innerBus)).toEqual({
specifier: "./local-bus.js",
importedPath: [],
resolutionMode: "require",
});
const shadow = onlyBinding(ir, "ipcRenderer");
expect(shadow.provenance).toEqual({
status: "local",
origins: [],
reason: null,
});
const shadowReference = ir.references.find(
({ name, bindingId, role }) =>
name === "ipcRenderer" &&
bindingId === shadow.bindingId &&
role === "read",
);
expect(shadowReference?.resolution).toBe("resolved");
expect(shadowReference?.bindingId).not.toBe(
topLevelBinding(ir, "ir").bindingId,
);
if (shadowReference === undefined || shadowReference.bindingId === null)
throw new Error("Missing shadow reference");
expect(bindingById(ir, shadowReference.bindingId)).toEqual(shadow);
expect(
ir.references.find(
({ location }) =>
location.start.line === shadowReference.location.start.line &&
location.start.column === shadowReference.location.start.column,
),
).toEqual(shadowReference);
});
it.each([
`function run(require) { const bus = require("electron").ipcMain; return bus; }`,
`function run() { const { ipcMain: bus } = require("electron"); function require() {} return bus; }`,
`{ const bus = require("electron").ipcMain; const require = localLoader; }`,
`import require from "./loader.js"; const bus = require("electron").ipcMain;`,
])(
"does not assign CommonJS origins to lexically shadowed require",
(source) => {
const ir = analyzeJavaScriptSemantics(source);
const bus = onlyBinding(ir, "bus");
expect(bus.provenance.origins).toEqual([]);
expect(ir.moduleLinks.filter(({ kind }) => kind === "require")).toEqual(
[],
);
},
);
it("propagates literal, template, object, conditional, and destructured values", () => {
const ir = analyzeJavaScriptSemantics(`
const prefix = "rea";
const suffix = "open";
const channel = \`${"${prefix}"}:${"${suffix}"}\`;
const options = {
channel,
mode: enabled ? "read" : "write",
};
const selected = options.channel;
const { mode } = options;
const [first] = ["zero", "one"];
`);
expect(topLevelBinding(ir, "channel").value).toEqual({
status: "literal",
value: "rea:open",
});
expect(topLevelBinding(ir, "selected").value).toEqual({
status: "literal",
value: "rea:open",
});
expect(topLevelBinding(ir, "mode").value).toEqual({
status: "union",
values: ["read", "write"],
});
expect(topLevelBinding(ir, "first").value).toEqual({
status: "literal",
value: "zero",
});
});
});
describe("JavaScript semantic analysis: loop lexical names", () => {
it.each([
`for (let value = "inside"; ready; step()) { consume(value); }`,
`for (const value of entries) { consume(value); }`,
`for (const value in entries) { consume(value); }`,
])("does not leak lexical loop bindings into the enclosing scope", (loop) => {
const ir = analyzeJavaScriptSemantics(`
const value = "outside";
${loop}
consume(value);
`);
expect(topLevelBinding(ir, "value").value).toEqual({
status: "literal",
value: "outside",
});
expect(bindingsNamed(ir, "value")).toHaveLength(2);
const reads = ir.references.filter(
({ name, role }) => name === "value" && role === "read",
);
expect(reads).toHaveLength(2);
expect(reads[0]?.bindingId).not.toBe(reads[1]?.bindingId);
expect(reads[1]?.bindingId).toBe(topLevelBinding(ir, "value").bindingId);
});
it("resolves closures inside a loop against the loop binding", () => {
const ir = analyzeJavaScriptSemantics(`
const value = "outside";
for (const value of entries) { callbacks.push(() => value); }
consume(value);
`);
const reads = ir.references.filter(
({ name, role }) => name === "value" && role === "read",
);
expect(reads).toHaveLength(2);
expect(reads[0]?.bindingId).not.toBe(
topLevelBinding(ir, "value").bindingId,
);
expect(reads[1]?.bindingId).toBe(topLevelBinding(ir, "value").bindingId);
expect(ir.closureCaptures).toContainEqual(
expect.objectContaining({
bindingId: reads[0]?.bindingId,
}),
);
});
it("keeps var loop declarations in the enclosing function", () => {
const ir = analyzeJavaScriptSemantics(`
function run() { for (var value of entries) { consume(value); } return value; }
`);
const binding = onlyBinding(ir, "value");
const callable = ir.callables.find(({ name }) => name === "run");
expect(binding.scopeId).toBe(callable?.bodyScopeId);
expect(
ir.references
.filter(({ name, role }) => name === "value" && role === "read")
.every(({ bindingId }) => bindingId === binding.bindingId),
).toBe(true);
});
});
describe("JavaScript semantic analysis: class expression lexical names", () => {
it("resolves named class expressions inside the class without changing the outer binding", () => {
const ir = analyzeJavaScriptSemantics(`
const Service = "outside";
const Wrapper = class Service {
create() { return new Service(); }
};
consume(Service);
`);
expect(bindingsNamed(ir, "Service")).toHaveLength(2);
expect(topLevelBinding(ir, "Service").value).toEqual({
status: "literal",
value: "outside",
});
const references = ir.references.filter(
({ name, role }) => name === "Service" && role === "read",
);
expect(references).toHaveLength(2);
expect(references[0]?.bindingId).not.toBe(references[1]?.bindingId);
expect(references[0]?.resolution).toBe("resolved");
const classScope = ir.scopes.find(({ kind }) => kind === "class");
expect(
bindingsNamed(ir, "Service").some(
({ scopeId }) => scopeId === classScope?.scopeId,
),
).toBe(true);
});
it("does not expose a named class expression outside its class", () => {
const ir = analyzeJavaScriptSemantics(`
const Wrapper = class Internal { create() { return new Internal(); } };
consume(Internal);
`);
const references = ir.references.filter(
({ name, role }) => name === "Internal" && role === "read",
);
expect(references.map(({ resolution }) => resolution)).toEqual([
"resolved",
"unbound",
]);
expect(topLevelBinding(ir, "Wrapper").provenance.status).toBe("local");
});
});
describe("JavaScript semantic analysis: structure 2", () => {
it("retains ESM, re-export, require, and CommonJS export relationships", () => {
const ir = analyzeJavaScriptSemantics(`
export { ipcRenderer as bridge } from "electron";
export * from "./wrapper.js";
export const localValue = 1;
const addon = require("./native.node");
module.exports.addon = addon;
export default function namedDefault() {}
`);
expect(ir.moduleLinks).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "re-export",
specifier: "electron",
importedName: "ipcRenderer",
exportedName: "bridge",
}),
expect.objectContaining({
kind: "re-export",
specifier: "./wrapper.js",
importedName: "*",
exportedName: "*",
}),
expect.objectContaining({
kind: "export",
localName: "localValue",
exportedName: "localValue",
}),
expect.objectContaining({
kind: "require",
specifier: "./native.node",
localName: "addon",
}),
expect.objectContaining({
kind: "commonjs-export",
localName: "addon",
exportedName: "addon",
}),
expect.objectContaining({
kind: "export",
localName: "namedDefault",
exportedName: "default",
}),
]),
);
});
it("does not invent export or method names from dynamic keys", () => {
const ir = analyzeJavaScriptSemantics(`
const key = resolveKey();
exports[key] = addon;
module.exports[key] = addon;
const target = { [key]() { return 1; } };
class Holder { [key]() { return 2; } }
`);
// The assignment is real, but its name is not knowable, so the only
// honest exported_name is the wildcard.
expect(
ir.moduleLinks
.filter(({ kind }) => kind === "commonjs-export")
.map(({ exportedName }) => exportedName),
).toEqual(["*", "*"]);
const names = ir.callables.map(({ name }) => name);
expect(names).not.toContain("key");
expect(names.filter((name) => name?.startsWith("[computed@")).length).toBe(
2,
);
});
it("resolves the value of a simple assignment expression exported through CommonJS", () => {
const ir = analyzeJavaScriptSemantics(`
function parse() { return { kind: "result" }; }
const holder = {};
module.exports = holder.value = parse;
`);
expect(ir.moduleLinks).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "commonjs-export",
localName: "parse",
exportedName: "default",
}),
]),
);
});
it.each(["parse", "default"])(
"does not export a %s property write to a replaced module.exports receiver",
(name) => {
const ir = analyzeJavaScriptSemantics(`
module.exports.${name} = (module.exports = () => ({ kind: "result" }));
`);
expect(ir.moduleLinks).toEqual([
expect.objectContaining({
kind: "commonjs-export",
exportedName: "default",
}),
]);
},
);
it("classifies destructuring and loop targets as writes, not reads", () => {
const ir = analyzeJavaScriptSemantics(`
let a, b, c;
({ a } = source);
[b] = list;
({ nested: { c } } = source);
for (a of list) {}
let d;
try { risky(); } catch ({ message }) { report(message); }
`);
const roles = (name: string): string[] =>
ir.references
.filter((reference) => reference.name === name)
.map(({ role }) => role);
expect(roles("a")).toEqual(["write", "write"]);
expect(roles("b")).toEqual(["write"]);
expect(roles("c")).toEqual(["write"]);
// A catch binding is a declaration, so its only later use is a read.
expect(roles("message")).toEqual(["read"]);
});
it("retains the read a compound assignment or update performs", () => {
const ir = analyzeJavaScriptSemantics(`
let total = 0;
total += 1;
total++;
total = 2;
const observed = total;
`);
const roles = ir.references
.filter(({ name }) => name === "total")
.map(({ role }) => role);
expect(roles).toEqual([
"read",
"write", // total += 1
"read",
"write", // total++
"write", // total = 2
"read", // const observed = total
]);
});
});
describe("JavaScript semantic analysis: dynamic and case scopes", () => {
it("marks with and eval as unresolved dynamic scope instead of staying silent", () => {
const ir = analyzeJavaScriptSemantics(`
function load(source) {
with (host) { consume(target); }
eval("var injected = 1;");
}
`);
const reasons = ir.frontiers
.filter(({ kind }) => kind === "dynamic-scope")
.map(({ reason }) => reason);
expect(reasons).toHaveLength(2);
expect(reasons.join("\n")).toContain("`with`");
expect(reasons.join("\n")).toContain("`eval`");
});
it("does not assign CommonJS exports to lexically shadowed module or exports", () => {
const ir = analyzeJavaScriptSemantics(`
function shadowed(module, exports) {
module.exports.value = 1;
exports.other = 2;
exports[key] = 3;
module.exports[key] = 4;
unrelated[key] = 5;
}
`);
expect(
ir.moduleLinks.filter(({ kind }) => kind === "commonjs-export"),
).toEqual([]);
});
it("shares one lexical scope across switch cases and isolates static blocks", () => {
const switchIr = analyzeJavaScriptSemantics(`
const kind = select();
switch (kind) {
case "a": let shared = 1; break;
case "b": shared = 2; break;
}
`);
// One declaration, one binding — and it belongs to a scope of its own, so
// it cannot leak past the switch statement.
const shared = switchIr.bindings.filter(({ name }) => name === "shared");
expect(shared).toHaveLength(1);
expect(shared[0]?.scopeId).not.toBe(
topLevelBinding(switchIr, "kind").scopeId,
);
const classIr = analyzeJavaScriptSemantics(`
class Holder {
static { let isolated = 1; }
static { let isolated = 2; }
}
`);
expect(
classIr.bindings.filter(({ name }) => name === "isolated"),
).toHaveLength(2);
});
it("keeps function, class, and method identities separate from bindings", () => {
const ir = analyzeJavaScriptSemantics(`
class Service {
run() {}
get value() { return 1; }
#privateMethod() {}
}
const arrow = () => 1;
const object = { method() {} };
`);
expect(ir.callables).toEqual(
expect.arrayContaining([
expect.objectContaining({ kind: "class", name: "Service" }),
expect.objectContaining({ kind: "method", name: "run" }),
expect.objectContaining({ kind: "method", name: "value" }),
expect.objectContaining({ kind: "method", name: "#privateMethod" }),
expect.objectContaining({ kind: "function", name: "arrow" }),
expect.objectContaining({ kind: "method", name: "method" }),
]),
);
expect(bindingsNamed(ir, "run")).toEqual([]);
expect(bindingsNamed(ir, "method")).toEqual([]);
});
});