Skip to content

Commit c5ecfe0

Browse files
authored
[TS] Support Node20 projects and scale forward function analysis (#450)
1 parent bd92091 commit c5ecfe0

5 files changed

Lines changed: 90 additions & 35 deletions

File tree

‎jacodb-ets/ts-frontend/package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎jacodb-ets/ts-frontend/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"test": "vitest run --testTimeout=15000"
1515
},
1616
"dependencies": {
17-
"typescript": "^5.4.5"
17+
"typescript": "5.9.3"
1818
},
1919
"devDependencies": {
2020
"@types/node": "^18.19.0",

‎jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts‎

Lines changed: 35 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -91,29 +91,31 @@ export class StmtLowerer {
9191
// snapshot captures BEFORE the captured variables are assigned. Hoist only the
9292
// declarations whose values are evaluated earlier in the same statement list;
9393
// a reference in a deferred closure body cannot force early capture.
94-
const hoisted = new Set<ts.Statement>();
94+
const declarations = new Map<ts.Symbol, { statement: ts.Statement; index: number }[]>();
9595
statements.forEach((statement, index) => {
96-
if (!ts.isFunctionDeclaration(statement) || statement.name === undefined) {
97-
return;
98-
}
99-
const functionSymbol = this.m.converter.symbolOf(statement.name);
100-
if (functionSymbol === undefined) {
101-
return;
102-
}
96+
if (!ts.isFunctionDeclaration(statement) || statement.name === undefined) return;
97+
const symbol = this.m.converter.symbolOf(statement.name);
98+
if (symbol === undefined) return;
10399

104-
for (let i = 0; i < index; i++) {
105-
const earlierStatement = statements[i];
106-
const uses = this.functionUses(earlierStatement, functionSymbol);
107-
if (uses.eager) {
108-
hoisted.add(statement);
109-
}
110-
if (uses.deferred) {
111-
// Capturing a function before its binding is assigned needs a
112-
// live binding cell, which the lifted environment cannot express.
113-
this.unsupportedForwardFunctionCaptures.add(earlierStatement);
114-
}
115-
}
100+
const existing = declarations.get(symbol) ?? [];
101+
existing.push({ statement, index });
102+
declarations.set(symbol, existing);
116103
});
104+
105+
const hoisted = new Set<ts.Statement>();
106+
if (declarations.size > 0) {
107+
statements.forEach((statement, index) => {
108+
// Collect all forward references in one traversal instead of rescanning
109+
// every earlier subtree separately for every later declaration.
110+
for (const [symbol, uses] of this.functionUses(statement, declarations)) {
111+
for (const declaration of declarations.get(symbol)!) {
112+
if (declaration.index <= index) continue;
113+
if (uses.eager) hoisted.add(declaration.statement);
114+
if (uses.deferred) this.unsupportedForwardFunctionCaptures.add(statement);
115+
}
116+
}
117+
});
118+
}
117119
for (const statement of statements) {
118120
if (hoisted.has(statement)) {
119121
this.lowerStatement(statement);
@@ -126,11 +128,13 @@ export class StmtLowerer {
126128
}
127129
}
128130

129-
private functionUses(node: ts.Node, functionSymbol: ts.Symbol): { eager: boolean; deferred: boolean } {
130-
let eager = false;
131-
let deferred = false;
131+
private functionUses(
132+
node: ts.Node,
133+
functionSymbols: ReadonlyMap<ts.Symbol, unknown>,
134+
): Map<ts.Symbol, { eager: boolean; deferred: boolean }> {
135+
const uses = new Map<ts.Symbol, { eager: boolean; deferred: boolean }>();
132136
const visit = (current: ts.Node, inDeferredBody: boolean): void => {
133-
if ((eager && deferred) || ts.isTypeNode(current)) {
137+
if (ts.isTypeNode(current)) {
134138
return;
135139
}
136140

@@ -178,9 +182,12 @@ export class StmtLowerer {
178182
const isValueReference = !isPropertyName && !isBindingName;
179183
if (isValueReference) {
180184
const referenceSymbol = this.m.converter.symbolOf(current);
181-
if (referenceSymbol === functionSymbol) {
182-
if (inDeferredBody) deferred = true;
183-
else eager = true;
185+
const isScopeFunction = referenceSymbol !== undefined && functionSymbols.has(referenceSymbol);
186+
if (isScopeFunction) {
187+
const referenceUses = uses.get(referenceSymbol) ?? { eager: false, deferred: false };
188+
if (inDeferredBody) referenceUses.deferred = true;
189+
else referenceUses.eager = true;
190+
uses.set(referenceSymbol, referenceUses);
184191
return;
185192
}
186193
}
@@ -190,7 +197,7 @@ export class StmtLowerer {
190197
};
191198

192199
visit(node, false);
193-
return { eager, deferred };
200+
return uses;
194201
}
195202

196203
private immediatelyCalledFunction(expression: ts.Expression): ts.ArrowFunction | ts.FunctionExpression | undefined {

‎jacodb-ets/ts-frontend/test/cli.spec.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,36 @@ describe("parseArgs", () => {
5656
});
5757

5858
describe("project mode", () => {
59+
it("supports Node20 projects with relative TypeScript extension imports", () => {
60+
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "ets-frontend-node20-"));
61+
tempDirs.push(projectDir);
62+
fs.writeFileSync(path.join(projectDir, "package.json"), JSON.stringify({ type: "module" }));
63+
fs.writeFileSync(path.join(projectDir, "tsconfig.json"), JSON.stringify({
64+
compilerOptions: {
65+
module: "node20", moduleResolution: "nodenext", rewriteRelativeImportExtensions: true,
66+
noEmit: true, allowImportingTsExtensions: true,
67+
},
68+
files: ["index.ts", "dependency.ts"],
69+
}));
70+
fs.writeFileSync(path.join(projectDir, "dependency.ts"), "export class Dependency { value = 7; }");
71+
fs.writeFileSync(path.join(projectDir, "index.ts"),
72+
'import { Dependency } from "./dependency.ts"; export class Client extends Dependency {}');
73+
74+
const inputs = resolveProjectInputs(projectDir);
75+
const outputDir = path.join(projectDir, "ir");
76+
const result = main(["--project", projectDir, outputDir]);
77+
78+
expect(inputs.options.module).toBe(ts.ModuleKind.Node20);
79+
expect(inputs.options.rewriteRelativeImportExtensions).toBe(true);
80+
expect(result).toBe(0);
81+
const file = JSON.parse(fs.readFileSync(path.join(outputDir, "index.ts.json"), "utf8"));
82+
expect(file.importInfos).toContainEqual(expect.objectContaining({ importFrom: "./dependency.ts" }));
83+
expect(file.classes).toContainEqual(expect.objectContaining({
84+
signature: expect.objectContaining({ name: "Client" }),
85+
superClassName: "Dependency",
86+
}));
87+
});
88+
5989
it("keeps an imported class alias while rejecting a mutable namespace property", () => {
6090
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "ets-frontend-class-alias-"));
6191
tempDirs.push(projectDir);

‎jacodb-ets/ts-frontend/test/closures.spec.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
import { describe, expect, it } from "vitest";
1+
import { describe, expect, it, vi } from "vitest";
22
import { ClassCategory } from "../src/dto/constants";
33
import { AssignStmtDto, StmtDto } from "../src/dto/stmts";
4+
import { buildEtsFile } from "../src/lowering/fileBuilder";
45
import { serializeEtsFile } from "../src/serialize";
56
import { validateEtsFile } from "../src/validate";
67
import { consumers } from "./array-test-consumers";
7-
import { defaultMethod, lower, methodByName, singleBlockStmts } from "./util";
8+
import { compile, defaultMethod, lower, methodByName, singleBlockStmts } from "./util";
89

910
function allStmts(source: string): StmtDto[] {
1011
const { file } = lower(source);
@@ -15,6 +16,23 @@ function allStmts(source: string): StmtDto[] {
1516
}
1617

1718
describe("closures", () => {
19+
it("does not repeatedly resolve sibling function subtrees for forward references", () => {
20+
const declarations = Array.from({ length: 200 }, (_, index) =>
21+
`function sibling${index}() { return input; }`).join("\n");
22+
const { program, sourceFile, checker } = compile(`function outer(input: number) { ${declarations} }`);
23+
const resolutions = vi.spyOn(checker, "getSymbolAtLocation");
24+
25+
try {
26+
const file = buildEtsFile(program, sourceFile, { projectName: "proj", fileName: "test.ts" });
27+
28+
expect(validateEtsFile(file)).toEqual([]);
29+
// One identifier per sibling must not cause a quadratic number of checker lookups.
30+
expect(resolutions.mock.calls.length).toBeLessThan(5_000);
31+
} finally {
32+
resolutions.mockRestore();
33+
}
34+
});
35+
1836
it("lifts arrow functions into %AM methods with FunctionType use-site locals", () => {
1937
const { file } = lower(`
2038
let arr = [1, 2, 3];

0 commit comments

Comments
 (0)