@babel/plugin-transform-block-scoping
Advanced tools
Comparing version 7.22.5 to 8.0.0-alpha.0
@@ -1,10 +0,3 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.annexB33FunctionsVisitor = void 0; | ||
exports.isVarScope = isVarScope; | ||
var _core = require("@babel/core"); | ||
const annexB33FunctionsVisitor = { | ||
import { types as t } from "@babel/core"; | ||
export const annexB33FunctionsVisitor = { | ||
VariableDeclaration(path) { | ||
@@ -20,3 +13,3 @@ if (isStrict(path)) return; | ||
if (isStrict(path)) return; | ||
if (_core.types.isFunction(path.parent, { | ||
if (t.isFunction(path.parent, { | ||
body: path.node | ||
@@ -31,3 +24,2 @@ })) return; | ||
}; | ||
exports.annexB33FunctionsVisitor = annexB33FunctionsVisitor; | ||
function transformStatementList(paths) { | ||
@@ -64,3 +56,3 @@ outer: for (const path of paths) { | ||
node.id = null; | ||
const varNode = _core.types.variableDeclaration("var", [_core.types.variableDeclarator(id, _core.types.toExpression(node))]); | ||
const varNode = t.variableDeclaration("var", [t.variableDeclarator(id, t.toExpression(node))]); | ||
varNode._blockHoist = 2; | ||
@@ -85,3 +77,3 @@ const [varPath] = path.replaceWith(varNode); | ||
}; | ||
function isVarScope(scope) { | ||
export function isVarScope(scope) { | ||
return scope.path.isFunctionParent() || scope.path.isProgram(); | ||
@@ -93,11 +85,10 @@ } | ||
}) => { | ||
var _node$directives; | ||
if (_core.types.isProgram(node)) { | ||
if (t.isProgram(node)) { | ||
if (node.sourceType === "module") return true; | ||
} else if (_core.types.isClass(node)) { | ||
} else if (t.isClass(node)) { | ||
return true; | ||
} else if (!_core.types.isBlockStatement(node)) { | ||
} else if (!t.isBlockStatement(node)) { | ||
return false; | ||
} | ||
return (_node$directives = node.directives) == null ? void 0 : _node$directives.some(directive => directive.value.value === "use strict"); | ||
return node.directives?.some(directive => directive.value.value === "use strict"); | ||
}); | ||
@@ -104,0 +95,0 @@ } |
541
lib/index.js
@@ -1,13 +0,500 @@ | ||
"use strict"; | ||
import { declare } from '@babel/helper-plugin-utils'; | ||
import { types, template, traverse } from '@babel/core'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.default = void 0; | ||
var _helperPluginUtils = require("@babel/helper-plugin-utils"); | ||
var _core = require("@babel/core"); | ||
var _loop = require("./loop"); | ||
var _validation = require("./validation"); | ||
var _annexB_3_ = require("./annex-B_3_3"); | ||
var _default = (0, _helperPluginUtils.declare)((api, opts) => { | ||
const collectLoopBodyBindingsVisitor = { | ||
"Expression|Declaration|Loop"(path) { | ||
path.skip(); | ||
}, | ||
Scope(path, state) { | ||
if (path.isFunctionParent()) path.skip(); | ||
const { | ||
bindings | ||
} = path.scope; | ||
for (const name of Object.keys(bindings)) { | ||
const binding = bindings[name]; | ||
if (binding.kind === "let" || binding.kind === "const" || binding.kind === "hoisted") { | ||
state.blockScoped.push(binding); | ||
} | ||
} | ||
} | ||
}; | ||
function getLoopBodyBindings(loopPath) { | ||
const state = { | ||
blockScoped: [] | ||
}; | ||
loopPath.traverse(collectLoopBodyBindingsVisitor, state); | ||
return state.blockScoped; | ||
} | ||
function getUsageInBody(binding, loopPath) { | ||
const seen = new WeakSet(); | ||
let capturedInClosure = false; | ||
const constantViolations = filterMap(binding.constantViolations, path => { | ||
const { | ||
inBody, | ||
inClosure | ||
} = relativeLoopLocation(path, loopPath); | ||
if (!inBody) return null; | ||
capturedInClosure ||= inClosure; | ||
const id = path.isUpdateExpression() ? path.get("argument") : path.isAssignmentExpression() ? path.get("left") : null; | ||
if (id) seen.add(id.node); | ||
return id; | ||
}); | ||
const references = filterMap(binding.referencePaths, path => { | ||
if (seen.has(path.node)) return null; | ||
const { | ||
inBody, | ||
inClosure | ||
} = relativeLoopLocation(path, loopPath); | ||
if (!inBody) return null; | ||
capturedInClosure ||= inClosure; | ||
return path; | ||
}); | ||
return { | ||
capturedInClosure, | ||
hasConstantViolations: constantViolations.length > 0, | ||
usages: references.concat(constantViolations) | ||
}; | ||
} | ||
function relativeLoopLocation(path, loopPath) { | ||
const bodyPath = loopPath.get("body"); | ||
let inClosure = false; | ||
for (let currPath = path; currPath; currPath = currPath.parentPath) { | ||
if (currPath.isFunction() || currPath.isClass()) inClosure = true; | ||
if (currPath === bodyPath) { | ||
return { | ||
inBody: true, | ||
inClosure | ||
}; | ||
} else if (currPath === loopPath) { | ||
return { | ||
inBody: false, | ||
inClosure | ||
}; | ||
} | ||
} | ||
throw new Error("Internal Babel error: path is not in loop. Please report this as a bug."); | ||
} | ||
const collectCompletionsAndVarsVisitor = { | ||
Function(path) { | ||
path.skip(); | ||
}, | ||
LabeledStatement: { | ||
enter({ | ||
node | ||
}, state) { | ||
state.labelsStack.push(node.label.name); | ||
}, | ||
exit({ | ||
node | ||
}, state) { | ||
const popped = state.labelsStack.pop(); | ||
if (popped !== node.label.name) { | ||
throw new Error("Assertion failure. Please report this bug to Babel."); | ||
} | ||
} | ||
}, | ||
Loop: { | ||
enter(_, state) { | ||
state.labellessContinueTargets++; | ||
state.labellessBreakTargets++; | ||
}, | ||
exit(_, state) { | ||
state.labellessContinueTargets--; | ||
state.labellessBreakTargets--; | ||
} | ||
}, | ||
SwitchStatement: { | ||
enter(_, state) { | ||
state.labellessBreakTargets++; | ||
}, | ||
exit(_, state) { | ||
state.labellessBreakTargets--; | ||
} | ||
}, | ||
"BreakStatement|ContinueStatement"(path, state) { | ||
const { | ||
label | ||
} = path.node; | ||
if (label) { | ||
if (state.labelsStack.includes(label.name)) return; | ||
} else if (path.isBreakStatement() ? state.labellessBreakTargets > 0 : state.labellessContinueTargets > 0) { | ||
return; | ||
} | ||
state.breaksContinues.push(path); | ||
}, | ||
ReturnStatement(path, state) { | ||
state.returns.push(path); | ||
}, | ||
VariableDeclaration(path, state) { | ||
if (path.parent === state.loopNode && isVarInLoopHead(path)) return; | ||
if (path.node.kind === "var") state.vars.push(path); | ||
} | ||
}; | ||
function wrapLoopBody(loopPath, captured, updatedBindingsUsages) { | ||
const loopNode = loopPath.node; | ||
const state = { | ||
breaksContinues: [], | ||
returns: [], | ||
labelsStack: [], | ||
labellessBreakTargets: 0, | ||
labellessContinueTargets: 0, | ||
vars: [], | ||
loopNode | ||
}; | ||
loopPath.traverse(collectCompletionsAndVarsVisitor, state); | ||
const callArgs = []; | ||
const closureParams = []; | ||
const updater = []; | ||
for (const [name, updatedUsage] of updatedBindingsUsages) { | ||
callArgs.push(types.identifier(name)); | ||
const innerName = loopPath.scope.generateUid(name); | ||
closureParams.push(types.identifier(innerName)); | ||
updater.push(types.assignmentExpression("=", types.identifier(name), types.identifier(innerName))); | ||
for (const path of updatedUsage) path.replaceWith(types.identifier(innerName)); | ||
} | ||
for (const name of captured) { | ||
if (updatedBindingsUsages.has(name)) continue; | ||
callArgs.push(types.identifier(name)); | ||
closureParams.push(types.identifier(name)); | ||
} | ||
const id = loopPath.scope.generateUid("loop"); | ||
const fn = types.functionExpression(null, closureParams, types.toBlock(loopNode.body)); | ||
let call = types.callExpression(types.identifier(id), callArgs); | ||
const fnParent = loopPath.findParent(p => p.isFunction()); | ||
if (fnParent) { | ||
const { | ||
async, | ||
generator | ||
} = fnParent.node; | ||
fn.async = async; | ||
fn.generator = generator; | ||
if (generator) call = types.yieldExpression(call, true);else if (async) call = types.awaitExpression(call); | ||
} | ||
const updaterNode = updater.length > 0 ? types.expressionStatement(types.sequenceExpression(updater)) : null; | ||
if (updaterNode) fn.body.body.push(updaterNode); | ||
const [varPath] = loopPath.insertBefore(types.variableDeclaration("var", [types.variableDeclarator(types.identifier(id), fn)])); | ||
const bodyStmts = []; | ||
const varNames = []; | ||
for (const varPath of state.vars) { | ||
const assign = []; | ||
for (const decl of varPath.node.declarations) { | ||
varNames.push(...Object.keys(types.getBindingIdentifiers(decl.id))); | ||
if (decl.init) { | ||
assign.push(types.assignmentExpression("=", decl.id, decl.init)); | ||
} | ||
} | ||
if (assign.length > 0) { | ||
let replacement = assign.length === 1 ? assign[0] : types.sequenceExpression(assign); | ||
if (!types.isForStatement(varPath.parent, { | ||
init: varPath.node | ||
}) && !types.isForXStatement(varPath.parent, { | ||
left: varPath.node | ||
})) { | ||
replacement = types.expressionStatement(replacement); | ||
} | ||
varPath.replaceWith(replacement); | ||
} else { | ||
varPath.remove(); | ||
} | ||
} | ||
if (varNames.length) { | ||
varPath.pushContainer("declarations", varNames.map(name => types.variableDeclarator(types.identifier(name)))); | ||
} | ||
const labelNum = state.breaksContinues.length; | ||
const returnNum = state.returns.length; | ||
if (labelNum + returnNum === 0) { | ||
bodyStmts.push(types.expressionStatement(call)); | ||
} else if (labelNum === 1 && returnNum === 0) { | ||
for (const path of state.breaksContinues) { | ||
const { | ||
node | ||
} = path; | ||
const { | ||
type, | ||
label | ||
} = node; | ||
let name = type === "BreakStatement" ? "break" : "continue"; | ||
if (label) name += " " + label.name; | ||
path.replaceWith(types.addComment(types.returnStatement(types.numericLiteral(1)), "trailing", " " + name, true)); | ||
if (updaterNode) path.insertBefore(types.cloneNode(updaterNode)); | ||
bodyStmts.push(template.statement.ast` | ||
if (${call}) ${node} | ||
`); | ||
} | ||
} else { | ||
const completionId = loopPath.scope.generateUid("ret"); | ||
if (varPath.isVariableDeclaration()) { | ||
varPath.pushContainer("declarations", [types.variableDeclarator(types.identifier(completionId))]); | ||
bodyStmts.push(types.expressionStatement(types.assignmentExpression("=", types.identifier(completionId), call))); | ||
} else { | ||
bodyStmts.push(types.variableDeclaration("var", [types.variableDeclarator(types.identifier(completionId), call)])); | ||
} | ||
const injected = []; | ||
for (const path of state.breaksContinues) { | ||
const { | ||
node | ||
} = path; | ||
const { | ||
type, | ||
label | ||
} = node; | ||
let name = type === "BreakStatement" ? "break" : "continue"; | ||
if (label) name += " " + label.name; | ||
let i = injected.indexOf(name); | ||
const hasInjected = i !== -1; | ||
if (!hasInjected) { | ||
injected.push(name); | ||
i = injected.length - 1; | ||
} | ||
path.replaceWith(types.addComment(types.returnStatement(types.numericLiteral(i)), "trailing", " " + name, true)); | ||
if (updaterNode) path.insertBefore(types.cloneNode(updaterNode)); | ||
if (hasInjected) continue; | ||
bodyStmts.push(template.statement.ast` | ||
if (${types.identifier(completionId)} === ${types.numericLiteral(i)}) ${node} | ||
`); | ||
} | ||
if (returnNum) { | ||
for (const path of state.returns) { | ||
const arg = path.node.argument || path.scope.buildUndefinedNode(); | ||
path.replaceWith(template.statement.ast` | ||
return { v: ${arg} }; | ||
`); | ||
} | ||
bodyStmts.push(template.statement.ast` | ||
if (${types.identifier(completionId)}) return ${types.identifier(completionId)}.v; | ||
`); | ||
} | ||
} | ||
loopNode.body = types.blockStatement(bodyStmts); | ||
return varPath; | ||
} | ||
function isVarInLoopHead(path) { | ||
if (types.isForStatement(path.parent)) return path.key === "init"; | ||
if (types.isForXStatement(path.parent)) return path.key === "left"; | ||
return false; | ||
} | ||
function filterMap(list, fn) { | ||
const result = []; | ||
for (const item of list) { | ||
const mapped = fn(item); | ||
if (mapped) result.push(mapped); | ||
} | ||
return result; | ||
} | ||
function validateUsage(path, state, tdzEnabled) { | ||
const dynamicTDZNames = []; | ||
for (const name of Object.keys(path.getBindingIdentifiers())) { | ||
const binding = path.scope.getBinding(name); | ||
if (!binding) continue; | ||
if (tdzEnabled) { | ||
if (injectTDZChecks(binding, state)) dynamicTDZNames.push(name); | ||
} | ||
if (path.node.kind === "const") { | ||
disallowConstantViolations(name, binding, state); | ||
} | ||
} | ||
return dynamicTDZNames; | ||
} | ||
function disallowConstantViolations(name, binding, state) { | ||
for (const violation of binding.constantViolations) { | ||
const readOnlyError = state.addHelper("readOnlyError"); | ||
const throwNode = types.callExpression(readOnlyError, [types.stringLiteral(name)]); | ||
if (violation.isAssignmentExpression()) { | ||
const { | ||
operator, | ||
left, | ||
right | ||
} = violation.node; | ||
if (operator === "=") { | ||
const exprs = [right]; | ||
exprs.push(throwNode); | ||
violation.replaceWith(types.sequenceExpression(exprs)); | ||
} else if (["&&=", "||=", "??="].includes(operator)) { | ||
violation.replaceWith(types.logicalExpression(operator.slice(0, -1), left, types.sequenceExpression([right, throwNode]))); | ||
} else { | ||
violation.replaceWith(types.sequenceExpression([types.binaryExpression(operator.slice(0, -1), left, right), throwNode])); | ||
} | ||
} else if (violation.isUpdateExpression()) { | ||
violation.replaceWith(types.sequenceExpression([types.unaryExpression("+", violation.get("argument").node), throwNode])); | ||
} else if (violation.isForXStatement()) { | ||
violation.ensureBlock(); | ||
violation.get("left").replaceWith(types.variableDeclaration("var", [types.variableDeclarator(violation.scope.generateUidIdentifier(name))])); | ||
violation.node.body.body.unshift(types.expressionStatement(throwNode)); | ||
} | ||
} | ||
} | ||
function getTDZStatus(refPath, bindingPath) { | ||
const executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); | ||
if (executionStatus === "before") { | ||
return "outside"; | ||
} else if (executionStatus === "after") { | ||
return "inside"; | ||
} else { | ||
return "maybe"; | ||
} | ||
} | ||
const skipTDZChecks = new WeakSet(); | ||
function buildTDZAssert(status, node, state) { | ||
if (status === "maybe") { | ||
const clone = types.cloneNode(node); | ||
skipTDZChecks.add(clone); | ||
return types.callExpression(state.addHelper("temporalRef"), [clone, types.stringLiteral(node.name)]); | ||
} else { | ||
return types.callExpression(state.addHelper("tdz"), [types.stringLiteral(node.name)]); | ||
} | ||
} | ||
function getTDZReplacement(path, state, id = path.node) { | ||
if (skipTDZChecks.has(id)) return; | ||
skipTDZChecks.add(id); | ||
const bindingPath = path.scope.getBinding(id.name)?.path; | ||
if (!bindingPath || bindingPath.isFunctionDeclaration()) return; | ||
const status = getTDZStatus(path, bindingPath); | ||
if (status === "outside") return; | ||
if (status === "maybe") { | ||
bindingPath.parent._tdzThis = true; | ||
} | ||
return { | ||
status, | ||
node: buildTDZAssert(status, id, state) | ||
}; | ||
} | ||
function injectTDZChecks(binding, state) { | ||
const allUsages = new Set(binding.referencePaths); | ||
binding.constantViolations.forEach(allUsages.add, allUsages); | ||
let dynamicTdz = false; | ||
for (const path of binding.constantViolations) { | ||
const { | ||
node | ||
} = path; | ||
if (skipTDZChecks.has(node)) continue; | ||
skipTDZChecks.add(node); | ||
if (path.isUpdateExpression()) { | ||
const arg = path.get("argument"); | ||
const replacement = getTDZReplacement(path, state, arg.node); | ||
if (!replacement) continue; | ||
if (replacement.status === "maybe") { | ||
dynamicTdz = true; | ||
path.insertBefore(replacement.node); | ||
} else { | ||
path.replaceWith(replacement.node); | ||
} | ||
} else if (path.isAssignmentExpression()) { | ||
const nodes = []; | ||
const ids = path.getBindingIdentifiers(); | ||
for (const name of Object.keys(ids)) { | ||
const replacement = getTDZReplacement(path, state, ids[name]); | ||
if (replacement) { | ||
nodes.push(types.expressionStatement(replacement.node)); | ||
if (replacement.status === "inside") break; | ||
if (replacement.status === "maybe") dynamicTdz = true; | ||
} | ||
} | ||
if (nodes.length > 0) path.insertBefore(nodes); | ||
} | ||
} | ||
for (const path of binding.referencePaths) { | ||
if (path.parentPath.isUpdateExpression()) continue; | ||
if (path.parentPath.isFor({ | ||
left: path.node | ||
})) continue; | ||
const replacement = getTDZReplacement(path, state); | ||
if (!replacement) continue; | ||
if (replacement.status === "maybe") dynamicTdz = true; | ||
path.replaceWith(replacement.node); | ||
} | ||
return dynamicTdz; | ||
} | ||
const annexB33FunctionsVisitor = { | ||
VariableDeclaration(path) { | ||
if (isStrict(path)) return; | ||
if (path.node.kind !== "var") return; | ||
const varScope = path.scope.getFunctionParent() || path.scope.getProgramParent(); | ||
varScope.path.traverse(functionsToVarVisitor, { | ||
names: Object.keys(path.getBindingIdentifiers()) | ||
}); | ||
}, | ||
BlockStatement(path) { | ||
if (isStrict(path)) return; | ||
if (types.isFunction(path.parent, { | ||
body: path.node | ||
})) return; | ||
transformStatementList(path.get("body")); | ||
}, | ||
SwitchCase(path) { | ||
if (isStrict(path)) return; | ||
transformStatementList(path.get("consequent")); | ||
} | ||
}; | ||
function transformStatementList(paths) { | ||
outer: for (const path of paths) { | ||
if (!path.isFunctionDeclaration()) continue; | ||
if (path.node.async || path.node.generator) return; | ||
const { | ||
scope | ||
} = path.parentPath; | ||
if (isVarScope(scope)) return; | ||
const { | ||
name | ||
} = path.node.id; | ||
let currScope = scope; | ||
do { | ||
if (currScope.parent.hasOwnBinding(name)) continue outer; | ||
currScope = currScope.parent; | ||
} while (!isVarScope(currScope)); | ||
maybeTransformBlockScopedFunction(path); | ||
} | ||
} | ||
function maybeTransformBlockScopedFunction(path) { | ||
const { | ||
node, | ||
parentPath: { | ||
scope | ||
} | ||
} = path; | ||
const { | ||
id | ||
} = node; | ||
scope.removeOwnBinding(id.name); | ||
node.id = null; | ||
const varNode = types.variableDeclaration("var", [types.variableDeclarator(id, types.toExpression(node))]); | ||
varNode._blockHoist = 2; | ||
const [varPath] = path.replaceWith(varNode); | ||
scope.registerDeclaration(varPath); | ||
} | ||
const functionsToVarVisitor = { | ||
Scope(path, { | ||
names | ||
}) { | ||
for (const name of names) { | ||
const binding = path.scope.getOwnBinding(name); | ||
if (binding && binding.kind === "hoisted") { | ||
maybeTransformBlockScopedFunction(binding.path); | ||
} | ||
} | ||
}, | ||
"Expression|Declaration"(path) { | ||
path.skip(); | ||
} | ||
}; | ||
function isVarScope(scope) { | ||
return scope.path.isFunctionParent() || scope.path.isProgram(); | ||
} | ||
function isStrict(path) { | ||
return !!path.find(({ | ||
node | ||
}) => { | ||
if (types.isProgram(node)) { | ||
if (node.sourceType === "module") return true; | ||
} else if (types.isClass(node)) { | ||
return true; | ||
} else if (!types.isBlockStatement(node)) { | ||
return false; | ||
} | ||
return node.directives?.some(directive => directive.value.value === "use strict"); | ||
}); | ||
} | ||
var index = declare((api, opts) => { | ||
api.assertVersion(7); | ||
@@ -26,3 +513,3 @@ const { | ||
name: "transform-block-scoping", | ||
visitor: _core.traverse.visitors.merge([_annexB_3_.annexB33FunctionsVisitor, { | ||
visitor: traverse.visitors.merge([annexB33FunctionsVisitor, { | ||
Loop(path, state) { | ||
@@ -42,7 +529,7 @@ const isForStatement = path.isForStatement(); | ||
bodyScope = body.scope; | ||
const bindings = (0, _loop.getLoopBodyBindings)(path); | ||
const bindings = getLoopBodyBindings(path); | ||
for (const binding of bindings) { | ||
const { | ||
capturedInClosure | ||
} = (0, _loop.getUsageInBody)(binding, path); | ||
} = getUsageInBody(binding, path); | ||
if (capturedInClosure) markNeedsBodyWrap(); | ||
@@ -57,4 +544,3 @@ } | ||
for (let name of names) { | ||
var _bodyScope; | ||
if ((_bodyScope = bodyScope) != null && _bodyScope.hasOwnBinding(name)) continue; | ||
if (bodyScope?.hasOwnBinding(name)) continue; | ||
let binding = headScope.getOwnBinding(name); | ||
@@ -69,3 +555,3 @@ if (!binding) { | ||
hasConstantViolations | ||
} = (0, _loop.getUsageInBody)(binding, path); | ||
} = getUsageInBody(binding, path); | ||
if (headScope.parent.hasBinding(name) || headScope.parent.hasGlobal(name)) { | ||
@@ -86,4 +572,4 @@ const newName = headScope.generateUid(name); | ||
if (needsBodyWrap) { | ||
const varPath = (0, _loop.wrapLoopBody)(path, captured, updatedBindingsUsages); | ||
if (headPath != null && headPath.isVariableDeclaration()) { | ||
const varPath = wrapLoopBody(path, captured, updatedBindingsUsages); | ||
if (headPath?.isVariableDeclaration()) { | ||
transformBlockScopedVariable(headPath, state, tdzEnabled); | ||
@@ -105,3 +591,3 @@ } | ||
} = path.parentPath; | ||
if (!(0, _annexB_3_.isVarScope)(scope) && scope.parent.hasBinding(id.name, { | ||
if (!isVarScope(scope) && scope.parent.hasBinding(id.name, { | ||
noUids: true | ||
@@ -115,3 +601,2 @@ })) { | ||
}); | ||
exports.default = _default; | ||
const conflictingFunctionsVisitor = { | ||
@@ -134,3 +619,3 @@ Scope(path, { | ||
if (!isBlockScoped(path.node)) return; | ||
const dynamicTDZNames = (0, _validation.validateUsage)(path, state, tdzEnabled); | ||
const dynamicTDZNames = validateUsage(path, state, tdzEnabled); | ||
path.node.kind = "var"; | ||
@@ -143,6 +628,5 @@ const bindingNames = Object.keys(path.getBindingIdentifiers()); | ||
} | ||
if (isInLoop(path) && !(0, _loop.isVarInLoopHead)(path) || dynamicTDZNames.length > 0) { | ||
if (isInLoop(path) && !isVarInLoopHead(path) || dynamicTDZNames.length > 0) { | ||
for (const decl of path.node.declarations) { | ||
var _decl$init; | ||
(_decl$init = decl.init) != null ? _decl$init : decl.init = path.scope.buildUndefinedNode(); | ||
decl.init ??= path.scope.buildUndefinedNode(); | ||
} | ||
@@ -169,3 +653,3 @@ } | ||
path.scope.push({ | ||
id: _core.types.identifier(name), | ||
id: types.identifier(name), | ||
init: state.addHelper("temporalUndefined") | ||
@@ -185,4 +669,4 @@ }); | ||
function isBlockScoped(node) { | ||
if (!_core.types.isVariableDeclaration(node)) return false; | ||
if (node[_core.types.BLOCK_SCOPED_SYMBOL]) { | ||
if (!types.isVariableDeclaration(node)) return false; | ||
if (node[types.BLOCK_SCOPED_SYMBOL]) { | ||
return true; | ||
@@ -196,2 +680,3 @@ } | ||
export { index as default }; | ||
//# sourceMappingURL=index.js.map |
129
lib/loop.js
@@ -1,11 +0,2 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.getLoopBodyBindings = getLoopBodyBindings; | ||
exports.getUsageInBody = getUsageInBody; | ||
exports.isVarInLoopHead = isVarInLoopHead; | ||
exports.wrapLoopBody = wrapLoopBody; | ||
var _core = require("@babel/core"); | ||
import { template, types as t } from "@babel/core"; | ||
const collectLoopBodyBindingsVisitor = { | ||
@@ -28,3 +19,3 @@ "Expression|Declaration|Loop"(path) { | ||
}; | ||
function getLoopBodyBindings(loopPath) { | ||
export function getLoopBodyBindings(loopPath) { | ||
const state = { | ||
@@ -36,3 +27,3 @@ blockScoped: [] | ||
} | ||
function getUsageInBody(binding, loopPath) { | ||
export function getUsageInBody(binding, loopPath) { | ||
const seen = new WeakSet(); | ||
@@ -46,3 +37,3 @@ let capturedInClosure = false; | ||
if (!inBody) return null; | ||
capturedInClosure || (capturedInClosure = inClosure); | ||
capturedInClosure ||= inClosure; | ||
const id = path.isUpdateExpression() ? path.get("argument") : path.isAssignmentExpression() ? path.get("left") : null; | ||
@@ -59,3 +50,3 @@ if (id) seen.add(id.node); | ||
if (!inBody) return null; | ||
capturedInClosure || (capturedInClosure = inClosure); | ||
capturedInClosure ||= inClosure; | ||
return path; | ||
@@ -144,3 +135,3 @@ }); | ||
}; | ||
function wrapLoopBody(loopPath, captured, updatedBindingsUsages) { | ||
export function wrapLoopBody(loopPath, captured, updatedBindingsUsages) { | ||
const loopNode = loopPath.node; | ||
@@ -161,16 +152,16 @@ const state = { | ||
for (const [name, updatedUsage] of updatedBindingsUsages) { | ||
callArgs.push(_core.types.identifier(name)); | ||
callArgs.push(t.identifier(name)); | ||
const innerName = loopPath.scope.generateUid(name); | ||
closureParams.push(_core.types.identifier(innerName)); | ||
updater.push(_core.types.assignmentExpression("=", _core.types.identifier(name), _core.types.identifier(innerName))); | ||
for (const path of updatedUsage) path.replaceWith(_core.types.identifier(innerName)); | ||
closureParams.push(t.identifier(innerName)); | ||
updater.push(t.assignmentExpression("=", t.identifier(name), t.identifier(innerName))); | ||
for (const path of updatedUsage) path.replaceWith(t.identifier(innerName)); | ||
} | ||
for (const name of captured) { | ||
if (updatedBindingsUsages.has(name)) continue; | ||
callArgs.push(_core.types.identifier(name)); | ||
closureParams.push(_core.types.identifier(name)); | ||
callArgs.push(t.identifier(name)); | ||
closureParams.push(t.identifier(name)); | ||
} | ||
const id = loopPath.scope.generateUid("loop"); | ||
const fn = _core.types.functionExpression(null, closureParams, _core.types.toBlock(loopNode.body)); | ||
let call = _core.types.callExpression(_core.types.identifier(id), callArgs); | ||
const fn = t.functionExpression(null, closureParams, t.toBlock(loopNode.body)); | ||
let call = t.callExpression(t.identifier(id), callArgs); | ||
const fnParent = loopPath.findParent(p => p.isFunction()); | ||
@@ -184,7 +175,7 @@ if (fnParent) { | ||
fn.generator = generator; | ||
if (generator) call = _core.types.yieldExpression(call, true);else if (async) call = _core.types.awaitExpression(call); | ||
if (generator) call = t.yieldExpression(call, true);else if (async) call = t.awaitExpression(call); | ||
} | ||
const updaterNode = updater.length > 0 ? _core.types.expressionStatement(_core.types.sequenceExpression(updater)) : null; | ||
const updaterNode = updater.length > 0 ? t.expressionStatement(t.sequenceExpression(updater)) : null; | ||
if (updaterNode) fn.body.body.push(updaterNode); | ||
const [varPath] = loopPath.insertBefore(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(id), fn)])); | ||
const [varPath] = loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(t.identifier(id), fn)])); | ||
const bodyStmts = []; | ||
@@ -195,15 +186,15 @@ const varNames = []; | ||
for (const decl of varPath.node.declarations) { | ||
varNames.push(...Object.keys(_core.types.getBindingIdentifiers(decl.id))); | ||
varNames.push(...Object.keys(t.getBindingIdentifiers(decl.id))); | ||
if (decl.init) { | ||
assign.push(_core.types.assignmentExpression("=", decl.id, decl.init)); | ||
assign.push(t.assignmentExpression("=", decl.id, decl.init)); | ||
} | ||
} | ||
if (assign.length > 0) { | ||
let replacement = assign.length === 1 ? assign[0] : _core.types.sequenceExpression(assign); | ||
if (!_core.types.isForStatement(varPath.parent, { | ||
let replacement = assign.length === 1 ? assign[0] : t.sequenceExpression(assign); | ||
if (!t.isForStatement(varPath.parent, { | ||
init: varPath.node | ||
}) && !_core.types.isForXStatement(varPath.parent, { | ||
}) && !t.isForXStatement(varPath.parent, { | ||
left: varPath.node | ||
})) { | ||
replacement = _core.types.expressionStatement(replacement); | ||
replacement = t.expressionStatement(replacement); | ||
} | ||
@@ -216,10 +207,34 @@ varPath.replaceWith(replacement); | ||
if (varNames.length) { | ||
bodyStmts.push(_core.types.variableDeclaration("var", varNames.map(name => _core.types.variableDeclarator(_core.types.identifier(name))))); | ||
varPath.pushContainer("declarations", varNames.map(name => t.variableDeclarator(t.identifier(name)))); | ||
} | ||
if (state.breaksContinues.length === 0 && state.returns.length === 0) { | ||
bodyStmts.push(_core.types.expressionStatement(call)); | ||
const labelNum = state.breaksContinues.length; | ||
const returnNum = state.returns.length; | ||
if (labelNum + returnNum === 0) { | ||
bodyStmts.push(t.expressionStatement(call)); | ||
} else if (labelNum === 1 && returnNum === 0) { | ||
for (const path of state.breaksContinues) { | ||
const { | ||
node | ||
} = path; | ||
const { | ||
type, | ||
label | ||
} = node; | ||
let name = type === "BreakStatement" ? "break" : "continue"; | ||
if (label) name += " " + label.name; | ||
path.replaceWith(t.addComment(t.returnStatement(t.numericLiteral(1)), "trailing", " " + name, true)); | ||
if (updaterNode) path.insertBefore(t.cloneNode(updaterNode)); | ||
bodyStmts.push(template.statement.ast` | ||
if (${call}) ${node} | ||
`); | ||
} | ||
} else { | ||
const completionId = loopPath.scope.generateUid("ret"); | ||
bodyStmts.push(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(_core.types.identifier(completionId), call)])); | ||
const injected = new Set(); | ||
if (varPath.isVariableDeclaration()) { | ||
varPath.pushContainer("declarations", [t.variableDeclarator(t.identifier(completionId))]); | ||
bodyStmts.push(t.expressionStatement(t.assignmentExpression("=", t.identifier(completionId), call))); | ||
} else { | ||
bodyStmts.push(t.variableDeclaration("var", [t.variableDeclarator(t.identifier(completionId), call)])); | ||
} | ||
const injected = []; | ||
for (const path of state.breaksContinues) { | ||
@@ -234,32 +249,34 @@ const { | ||
let name = type === "BreakStatement" ? "break" : "continue"; | ||
if (label) name += "|" + label.name; | ||
path.replaceWith(_core.types.returnStatement(_core.types.stringLiteral(name))); | ||
if (updaterNode) path.insertBefore(_core.types.cloneNode(updaterNode)); | ||
if (injected.has(name)) continue; | ||
injected.add(name); | ||
bodyStmts.push(_core.template.statement.ast` | ||
if ( | ||
${_core.types.identifier(completionId)} === ${_core.types.stringLiteral(name)} | ||
) ${node} | ||
if (label) name += " " + label.name; | ||
let i = injected.indexOf(name); | ||
const hasInjected = i !== -1; | ||
if (!hasInjected) { | ||
injected.push(name); | ||
i = injected.length - 1; | ||
} | ||
path.replaceWith(t.addComment(t.returnStatement(t.numericLiteral(i)), "trailing", " " + name, true)); | ||
if (updaterNode) path.insertBefore(t.cloneNode(updaterNode)); | ||
if (hasInjected) continue; | ||
bodyStmts.push(template.statement.ast` | ||
if (${t.identifier(completionId)} === ${t.numericLiteral(i)}) ${node} | ||
`); | ||
} | ||
if (state.returns.length) { | ||
if (returnNum) { | ||
for (const path of state.returns) { | ||
const arg = path.node.argument || path.scope.buildUndefinedNode(); | ||
path.replaceWith(_core.template.statement.ast` | ||
path.replaceWith(template.statement.ast` | ||
return { v: ${arg} }; | ||
`); | ||
} | ||
bodyStmts.push(_core.template.statement.ast` | ||
if (typeof ${_core.types.identifier(completionId)} === "object") | ||
return ${_core.types.identifier(completionId)}.v; | ||
`); | ||
bodyStmts.push(template.statement.ast` | ||
if (${t.identifier(completionId)}) return ${t.identifier(completionId)}.v; | ||
`); | ||
} | ||
} | ||
loopNode.body = _core.types.blockStatement(bodyStmts); | ||
loopNode.body = t.blockStatement(bodyStmts); | ||
return varPath; | ||
} | ||
function isVarInLoopHead(path) { | ||
if (_core.types.isForStatement(path.parent)) return path.key === "init"; | ||
if (_core.types.isForXStatement(path.parent)) return path.key === "left"; | ||
export function isVarInLoopHead(path) { | ||
if (t.isForStatement(path.parent)) return path.key === "init"; | ||
if (t.isForXStatement(path.parent)) return path.key === "left"; | ||
return false; | ||
@@ -266,0 +283,0 @@ } |
@@ -1,9 +0,3 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.validateUsage = validateUsage; | ||
var _core = require("@babel/core"); | ||
function validateUsage(path, state, tdzEnabled) { | ||
import { types as t } from "@babel/core"; | ||
export function validateUsage(path, state, tdzEnabled) { | ||
const dynamicTDZNames = []; | ||
@@ -25,3 +19,3 @@ for (const name of Object.keys(path.getBindingIdentifiers())) { | ||
const readOnlyError = state.addHelper("readOnlyError"); | ||
const throwNode = _core.types.callExpression(readOnlyError, [_core.types.stringLiteral(name)]); | ||
const throwNode = t.callExpression(readOnlyError, [t.stringLiteral(name)]); | ||
if (violation.isAssignmentExpression()) { | ||
@@ -36,14 +30,14 @@ const { | ||
exprs.push(throwNode); | ||
violation.replaceWith(_core.types.sequenceExpression(exprs)); | ||
violation.replaceWith(t.sequenceExpression(exprs)); | ||
} else if (["&&=", "||=", "??="].includes(operator)) { | ||
violation.replaceWith(_core.types.logicalExpression(operator.slice(0, -1), left, _core.types.sequenceExpression([right, throwNode]))); | ||
violation.replaceWith(t.logicalExpression(operator.slice(0, -1), left, t.sequenceExpression([right, throwNode]))); | ||
} else { | ||
violation.replaceWith(_core.types.sequenceExpression([_core.types.binaryExpression(operator.slice(0, -1), left, right), throwNode])); | ||
violation.replaceWith(t.sequenceExpression([t.binaryExpression(operator.slice(0, -1), left, right), throwNode])); | ||
} | ||
} else if (violation.isUpdateExpression()) { | ||
violation.replaceWith(_core.types.sequenceExpression([_core.types.unaryExpression("+", violation.get("argument").node), throwNode])); | ||
violation.replaceWith(t.sequenceExpression([t.unaryExpression("+", violation.get("argument").node), throwNode])); | ||
} else if (violation.isForXStatement()) { | ||
violation.ensureBlock(); | ||
violation.get("left").replaceWith(_core.types.variableDeclaration("var", [_core.types.variableDeclarator(violation.scope.generateUidIdentifier(name))])); | ||
violation.node.body.body.unshift(_core.types.expressionStatement(throwNode)); | ||
violation.get("left").replaceWith(t.variableDeclaration("var", [t.variableDeclarator(violation.scope.generateUidIdentifier(name))])); | ||
violation.node.body.body.unshift(t.expressionStatement(throwNode)); | ||
} | ||
@@ -65,14 +59,13 @@ } | ||
if (status === "maybe") { | ||
const clone = _core.types.cloneNode(node); | ||
const clone = t.cloneNode(node); | ||
skipTDZChecks.add(clone); | ||
return _core.types.callExpression(state.addHelper("temporalRef"), [clone, _core.types.stringLiteral(node.name)]); | ||
return t.callExpression(state.addHelper("temporalRef"), [clone, t.stringLiteral(node.name)]); | ||
} else { | ||
return _core.types.callExpression(state.addHelper("tdz"), [_core.types.stringLiteral(node.name)]); | ||
return t.callExpression(state.addHelper("tdz"), [t.stringLiteral(node.name)]); | ||
} | ||
} | ||
function getTDZReplacement(path, state, id = path.node) { | ||
var _path$scope$getBindin; | ||
if (skipTDZChecks.has(id)) return; | ||
skipTDZChecks.add(id); | ||
const bindingPath = (_path$scope$getBindin = path.scope.getBinding(id.name)) == null ? void 0 : _path$scope$getBindin.path; | ||
const bindingPath = path.scope.getBinding(id.name)?.path; | ||
if (!bindingPath || bindingPath.isFunctionDeclaration()) return; | ||
@@ -115,3 +108,3 @@ const status = getTDZStatus(path, bindingPath); | ||
if (replacement) { | ||
nodes.push(_core.types.expressionStatement(replacement.node)); | ||
nodes.push(t.expressionStatement(replacement.node)); | ||
if (replacement.status === "inside") break; | ||
@@ -118,0 +111,0 @@ if (replacement.status === "maybe") dynamicTdz = true; |
{ | ||
"name": "@babel/plugin-transform-block-scoping", | ||
"version": "7.22.5", | ||
"version": "8.0.0-alpha.0", | ||
"description": "Compile ES2015 block scoping (const and let) to ES5", | ||
@@ -17,3 +17,3 @@ "repository": { | ||
"dependencies": { | ||
"@babel/helper-plugin-utils": "^7.22.5" | ||
"@babel/helper-plugin-utils": "^8.0.0-alpha.0" | ||
}, | ||
@@ -24,14 +24,18 @@ "keywords": [ | ||
"peerDependencies": { | ||
"@babel/core": "^7.0.0-0" | ||
"@babel/core": "^8.0.0-alpha.0" | ||
}, | ||
"devDependencies": { | ||
"@babel/core": "^7.22.5", | ||
"@babel/helper-plugin-test-runner": "^7.22.5", | ||
"@babel/traverse": "^7.22.5" | ||
"@babel/core": "^8.0.0-alpha.0", | ||
"@babel/helper-plugin-test-runner": "^8.0.0-alpha.0", | ||
"@babel/traverse": "^8.0.0-alpha.0" | ||
}, | ||
"engines": { | ||
"node": ">=6.9.0" | ||
"node": "^16.20.0 || ^18.16.0 || >=20.0.0" | ||
}, | ||
"author": "The Babel Team (https://babel.dev/team)", | ||
"type": "commonjs" | ||
"exports": { | ||
".": "./lib/index.js", | ||
"./package.json": "./package.json" | ||
}, | ||
"type": "module" | ||
} |
@@ -5,3 +5,3 @@ # @babel/plugin-transform-block-scoping | ||
See our website [@babel/plugin-transform-block-scoping](https://babeljs.io/docs/en/babel-plugin-transform-block-scoping) for more information. | ||
See our website [@babel/plugin-transform-block-scoping](https://babeljs.io/docs/babel-plugin-transform-block-scoping) for more information. | ||
@@ -8,0 +8,0 @@ ## Install |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
148954
1163
Yes
1
+ Added@babel/code-frame@8.0.0-alpha.13(transitive)
+ Added@babel/compat-data@8.0.0-alpha.13(transitive)
+ Added@babel/core@8.0.0-alpha.13(transitive)
+ Added@babel/generator@8.0.0-alpha.13(transitive)
+ Added@babel/helper-compilation-targets@8.0.0-alpha.13(transitive)
+ Added@babel/helper-plugin-utils@8.0.0-alpha.13(transitive)
+ Added@babel/helper-string-parser@8.0.0-alpha.13(transitive)
+ Added@babel/helper-validator-identifier@8.0.0-alpha.13(transitive)
+ Added@babel/helper-validator-option@8.0.0-alpha.13(transitive)
+ Added@babel/helpers@8.0.0-alpha.13(transitive)
+ Added@babel/parser@8.0.0-alpha.13(transitive)
+ Added@babel/template@8.0.0-alpha.13(transitive)
+ Added@babel/traverse@8.0.0-alpha.13(transitive)
+ Added@babel/types@8.0.0-alpha.13(transitive)
+ Addedglobals@15.12.0(transitive)
+ Addedjs-tokens@8.0.3(transitive)
+ Addedlru-cache@7.18.3(transitive)
+ Addedsemver@7.6.3(transitive)
- Removed@babel/code-frame@7.26.2(transitive)
- Removed@babel/compat-data@7.26.2(transitive)
- Removed@babel/core@7.26.0(transitive)
- Removed@babel/generator@7.26.2(transitive)
- Removed@babel/helper-compilation-targets@7.25.9(transitive)
- Removed@babel/helper-module-imports@7.25.9(transitive)
- Removed@babel/helper-module-transforms@7.26.0(transitive)
- Removed@babel/helper-plugin-utils@7.25.9(transitive)
- Removed@babel/helper-string-parser@7.25.9(transitive)
- Removed@babel/helper-validator-identifier@7.25.9(transitive)
- Removed@babel/helper-validator-option@7.25.9(transitive)
- Removed@babel/helpers@7.26.0(transitive)
- Removed@babel/parser@7.26.2(transitive)
- Removed@babel/template@7.25.9(transitive)
- Removed@babel/traverse@7.25.9(transitive)
- Removed@babel/types@7.26.0(transitive)
- Removedglobals@11.12.0(transitive)
- Removedjs-tokens@4.0.0(transitive)
- Removedlru-cache@5.1.1(transitive)
- Removedsemver@6.3.1(transitive)
- Removedyallist@3.1.1(transitive)