Skip to content

Commit 7240833

Browse files
authored
Bind top-level declarations to the global scope where they are declared (#31)
1 parent 4e346d6 commit 7240833

1 file changed

Lines changed: 108 additions & 42 deletions

File tree

‎packages/javascript-kernel/src/executor.ts‎

Lines changed: 108 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -144,20 +144,20 @@ export class JavaScriptExecutor {
144144
module: true
145145
});
146146

147-
// Add top-level variables to global scope
148-
let codeAddToGlobalScope = this._addToGlobalScope(ast);
149-
150147
// Handle last statement / add return if needed
151148
const { withReturn, modifiedUserCode, extraReturnCode } =
152149
this._handleLastStatement(code, ast);
153-
let finalCode = modifiedUserCode;
154150

155-
// Handle import statements
156-
const importResult = this._rewriteImportStatements(finalCode, ast);
157-
finalCode = importResult.modifiedUserCode;
158-
codeAddToGlobalScope += importResult.codeAddToGlobalScope;
151+
// Handle import statements and top-level declarations
152+
const {
153+
modifiedUserCode: finalCode,
154+
codeAddToGlobalScope,
155+
hoistedCode
156+
} = this._rewriteTopLevelStatements(modifiedUserCode, ast);
159157

160-
const combinedCode = `
158+
// Put the hoisted code on the first line to keep line numbers. The ";"
159+
// stops a "use strict" directive, which would break the assignments
160+
const combinedCode = `;${hoistedCode}
161161
${finalCode}
162162
${codeAddToGlobalScope}
163163
${extraReturnCode}
@@ -1050,35 +1050,6 @@ export class JavaScriptExecutor {
10501050
return code.substring(0, start) + newCode + code.substring(end);
10511051
}
10521052

1053-
/**
1054-
* Add top-level variables to global scope.
1055-
*/
1056-
private _addToGlobalScope(ast: any): string {
1057-
const extraCode: string[] = [];
1058-
1059-
for (const node of ast.body) {
1060-
if (node.type === 'FunctionDeclaration') {
1061-
const name = node.id.name;
1062-
extraCode.push(this._addToGlobalThisCode(name));
1063-
} else if (node.type === 'ClassDeclaration') {
1064-
const name = node.id.name;
1065-
extraCode.push(this._addToGlobalThisCode(name));
1066-
} else if (node.type === 'VariableDeclaration') {
1067-
const declarations = node.declarations;
1068-
1069-
for (const declaration of declarations) {
1070-
const identifiers: string[] = [];
1071-
this._collectDeclaredIdentifiers(declaration.id, identifiers);
1072-
for (const name of identifiers) {
1073-
extraCode.push(this._addToGlobalThisCode(name));
1074-
}
1075-
}
1076-
}
1077-
}
1078-
1079-
return extraCode.join('\n');
1080-
}
1081-
10821053
/**
10831054
* Collect identifiers from a declaration pattern.
10841055
*/
@@ -1119,6 +1090,41 @@ export class JavaScriptExecutor {
11191090
}
11201091
}
11211092

1093+
/**
1094+
* Get the names declared by a function, class or variable declaration.
1095+
*/
1096+
private _declaredNames(node: any): string[] {
1097+
const names: string[] = [];
1098+
if (node.type === 'VariableDeclaration') {
1099+
for (const declaration of node.declarations) {
1100+
this._collectDeclaredIdentifiers(declaration.id, names);
1101+
}
1102+
} else if (
1103+
['FunctionDeclaration', 'ClassDeclaration'].includes(node.type)
1104+
) {
1105+
names.push(node.id.name);
1106+
}
1107+
return names;
1108+
}
1109+
1110+
/**
1111+
* Whether a node declares a global that cannot hold any value, like `name`
1112+
* or `location`.
1113+
*/
1114+
private _declaresBuiltinGlobal(node: any): boolean {
1115+
return this._declaredNames(node).some(name => {
1116+
let scope = this._globalScope;
1117+
while (scope) {
1118+
const descriptor = Object.getOwnPropertyDescriptor(scope, name);
1119+
if (descriptor) {
1120+
return descriptor.writable !== true;
1121+
}
1122+
scope = Object.getPrototypeOf(scope);
1123+
}
1124+
return false;
1125+
});
1126+
}
1127+
11221128
/**
11231129
* Handle the last statement to auto-return if it's an expression.
11241130
*/
@@ -1288,19 +1294,22 @@ export class JavaScriptExecutor {
12881294
}
12891295

12901296
/**
1291-
* Rewrite import statements to dynamic imports.
1297+
* Rewrite import statements to dynamic imports, and top-level declarations
1298+
* to assignments to the global scope.
12921299
*/
1293-
private _rewriteImportStatements(
1300+
private _rewriteTopLevelStatements(
12941301
code: string,
12951302
ast: any
12961303
): {
12971304
modifiedUserCode: string;
12981305
codeAddToGlobalScope: string;
1306+
hoistedCode: string;
12991307
} {
13001308
let modifiedUserCode = code;
13011309
let codeAddToGlobalScope = '';
1310+
const hoistedCode: string[] = [];
13021311

1303-
// Process imports in reverse order to maintain correct positions
1312+
// Process statements in reverse order to maintain correct positions
13041313
for (let i = ast.body.length - 1; i >= 0; i--) {
13051314
const node = ast.body[i];
13061315

@@ -1385,15 +1394,72 @@ export class JavaScriptExecutor {
13851394
newCodeOfNode
13861395
);
13871396
}
1397+
} else if (this._declaresBuiltinGlobal(node)) {
1398+
// Keep the declaration local, and copy it at the end like imports
1399+
for (const name of this._declaredNames(node)) {
1400+
codeAddToGlobalScope += this._addToGlobalThisCode(name);
1401+
}
1402+
} else if (node.type === 'FunctionDeclaration') {
1403+
// Assign the function before the code runs, using a hoisted factory
1404+
const factoryName = `__jsKernelFunction${i}`;
1405+
const functionCode = modifiedUserCode.substring(node.start, node.end);
1406+
modifiedUserCode = this._replaceCode(
1407+
modifiedUserCode,
1408+
node.start,
1409+
node.end,
1410+
`function ${factoryName}() { return ${functionCode} }`
1411+
);
1412+
hoistedCode.unshift(`${node.id.name} = ${factoryName}();`);
1413+
} else if (node.type === 'ClassDeclaration') {
1414+
const classCode = modifiedUserCode.substring(node.start, node.end);
1415+
modifiedUserCode = this._replaceCode(
1416+
modifiedUserCode,
1417+
node.start,
1418+
node.end,
1419+
`${node.id.name} = ${classCode};`
1420+
);
1421+
} else if (node.type === 'VariableDeclaration') {
1422+
modifiedUserCode = this._replaceCode(
1423+
modifiedUserCode,
1424+
node.start,
1425+
node.end,
1426+
this._rewriteVariableDeclaration(modifiedUserCode, node)
1427+
);
13881428
}
13891429
}
13901430

13911431
return {
13921432
modifiedUserCode,
1393-
codeAddToGlobalScope
1433+
codeAddToGlobalScope,
1434+
hoistedCode: hoistedCode.join(' ')
13941435
};
13951436
}
13961437

1438+
/**
1439+
* Rewrite a variable declaration to an assignment, e.g. `let a = 1, b;`
1440+
* to `a = 1, b = undefined;`.
1441+
*/
1442+
private _rewriteVariableDeclaration(code: string, node: any): string {
1443+
const declarations = node.declarations;
1444+
const lastDeclaration = declarations[declarations.length - 1];
1445+
1446+
// Wrap patterns in parentheses, and pad to keep the columns
1447+
const isPattern = declarations[0].id.type !== 'Identifier';
1448+
let newCode = (isPattern ? ';(' : '').padEnd(node.kind.length);
1449+
1450+
let position = node.start + node.kind.length;
1451+
for (const declaration of declarations) {
1452+
if (!declaration.init) {
1453+
newCode += `${code.substring(position, declaration.end)} = undefined`;
1454+
position = declaration.end;
1455+
}
1456+
}
1457+
newCode += code.substring(position, lastDeclaration.end);
1458+
newCode += isPattern ? ')' : '';
1459+
newCode += code.substring(lastDeclaration.end, node.end);
1460+
return newCode.endsWith(';') ? newCode : `${newCode};`;
1461+
}
1462+
13971463
/**
13981464
* Escape HTML special characters.
13991465
*/

0 commit comments

Comments
 (0)