@babel/plugin-transform-block-scoping
Version:
Compile ES2015 block scoping (const and let) to ES5
779 lines (774 loc) • 27.8 kB
JavaScript
import { declare } from '@babel/helper-plugin-utils';
import { types, template } from '@babel/core';
const collectLoopBodyBindingsVisitor = {
"Expression|Declaration"(path) {
path.skip();
},
Loop(path, state) {
path.skip();
if (!path.isForStatement()) return;
const init = path.get("init");
if (!init.isVariableDeclaration() || init.node.kind === "var") return;
const isUsing = init.node.kind === "using" || init.node.kind === "await using";
for (const name of Object.keys(init.getBindingIdentifiers())) {
const binding = path.scope.getOwnBinding(name);
if (!binding) continue;
if (isUsing) {
state.blockScoped.push(binding);
continue;
}
const capturedInHeadClosure = [...binding.referencePaths, ...binding.constantViolations].some(ref => {
const {
inHead,
inClosure
} = relativeLoopLocation(ref, path);
return inHead && inClosure;
});
if (capturedInHeadClosure) state.blockScoped.push(binding);
}
},
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;
let capturedInHeadClosure = false;
const headUsages = [];
const constantViolations = binding.constantViolations.flatMap(path => {
const {
inBody,
inHead,
inClosure
} = relativeLoopLocation(path, loopPath);
const id = path.isUpdateExpression() ? path.get("argument") : path.isAssignmentExpression() ? path.get("left") : null;
if (id) seen.add(id.node);
const ids = id?.getBindingIdentifierPaths(true)[binding.identifier.name] ?? [];
if (inHead) {
capturedInHeadClosure ||= inClosure;
headUsages.push(...ids);
return [];
}
if (!inBody) return [];
capturedInClosure ||= inClosure;
return ids;
});
const references = filterMap(binding.referencePaths, path => {
if (seen.has(path.node)) return null;
const {
inBody,
inHead,
inClosure
} = relativeLoopLocation(path, loopPath);
if (inHead) {
capturedInHeadClosure ||= inClosure;
headUsages.push(path);
return null;
}
if (!inBody) return null;
capturedInClosure ||= inClosure;
return path;
});
return {
capturedInClosure,
hasConstantViolations: constantViolations.length > 0,
usages: references.concat(constantViolations),
capturedInHeadClosure,
headUsages
};
}
function moveCapturingTestAndUpdateIntoBody(loopPath) {
const init = loopPath.get("init");
if (!init.isVariableDeclaration() || init.node.kind !== "let") return;
let testCaptures = false;
let updateCaptures = false;
for (const name of Object.keys(init.getBindingIdentifiers())) {
const binding = loopPath.scope.getOwnBinding(name);
if (!binding?.constantViolations.length) continue;
for (const ref of [...binding.referencePaths, ...binding.constantViolations]) {
const {
inTest,
inUpdate,
inClosure
} = relativeLoopLocation(ref, loopPath);
testCaptures ||= inTest && inClosure;
updateCaptures ||= inUpdate && inClosure;
}
}
if (!testCaptures && !updateCaptures) return;
makeAnnexBAssignmentsExplicit(loopPath);
const {
node
} = loopPath;
const bodyStmts = [];
if (updateCaptures && node.update) {
const first = loopPath.scope.generateUid("first");
init.node.declarations.push(types.variableDeclarator(types.identifier(first), types.booleanLiteral(true)));
bodyStmts.push(types.ifStatement(types.unaryExpression("!", types.identifier(first)), types.expressionStatement(node.update)));
node.update = types.assignmentExpression("=", types.identifier(first), types.booleanLiteral(false));
}
if (node.test) {
bodyStmts.push(types.ifStatement(types.unaryExpression("!", node.test), types.breakStatement()));
node.test = null;
}
if (!types.isEmptyStatement(node.body)) bodyStmts.push(node.body);
node.body = types.blockStatement(bodyStmts);
loopPath.scope.crawl();
}
function makeAnnexBAssignmentsExplicit(loopPath) {
const declarations = [];
loopPath.get("body").traverse({
Function(path) {
if (path.isFunctionDeclaration() && (path.parentPath.isBlockStatement() || path.parentPath.isSwitchCase()) && path.node.id && !path.node.generator && !path.node.async && !path.isInStrictMode() && !hasLexicalConflict(loopPath, path.node.id.name)) {
declarations.push(path);
}
path.skip();
}
});
if (declarations.length === 0) return;
const names = new Set();
const renamed = new Map();
for (const path of declarations) {
const name = path.node.id.name;
names.add(name);
const declScope = path.scope.parent;
if (!renamed.has(declScope)) renamed.set(declScope, new Set());
if (!renamed.get(declScope).has(name)) {
renamed.get(declScope).add(name);
declScope.rename(name);
}
path.insertAfter(types.expressionStatement(types.assignmentExpression("=", types.identifier(name), types.cloneNode(path.node.id))));
}
const body = types.toBlock(loopPath.node.body);
body.body.unshift(types.variableDeclaration("var", Array.from(names, name => types.variableDeclarator(types.identifier(name)))));
loopPath.node.body = body;
}
function hasLexicalConflict(loopPath, name) {
const binding = loopPath.scope.getBinding(name);
return !!binding && binding.kind !== "var" && binding.kind !== "hoisted";
}
function relativeLoopLocation(path, loopPath) {
const bodyPath = loopPath.get("body");
const headPath = loopPath.isForStatement() ? loopPath.get("init") : null;
const testPath = loopPath.isForStatement() ? loopPath.get("test") : null;
const updatePath = loopPath.isForStatement() ? loopPath.get("update") : null;
let inClosure = false;
for (let currPath = path; currPath; currPath = currPath.parentPath) {
if (currPath.isFunction() || currPath.isClass() || currPath.isMethod()) {
inClosure = true;
}
const location = {
inBody: false,
inHead: false,
inTest: false,
inUpdate: false,
inClosure
};
if (currPath === bodyPath) {
return {
...location,
inBody: true
};
} else if (headPath && currPath === headPath) {
return {
...location,
inHead: true
};
} else if (testPath?.node && currPath === testPath) {
return {
...location,
inTest: true
};
} else if (updatePath?.node && currPath === updatePath) {
return {
...location,
inUpdate: true
};
} else if (currPath === loopPath) {
return location;
}
}
throw new Error("Internal Babel error: path is not in loop. Please report this as a bug.");
}
function wrapLoopBody(loopPath, captured, updatedBindingsUsages, pluginPass) {
const loopNode = loopPath.node;
const state = {
breaksContinues: [],
returns: [],
labelsStack: [],
labellessBreakTargets: 0,
labellessContinueTargets: 0,
vars: [],
loopNode,
hasTryFinally: false
};
loopPath.traverse({
FunctionParent(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);
},
TryStatement(path, state) {
if (path.node.finalizer) {
state.hasTryFinally = true;
}
},
VariableDeclaration(path, state) {
if (path.parent === state.loopNode && isVarInLoopHead(path)) return;
if (path.node.kind === "var") state.vars.push(path);
}
}, 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.blockStatement([]));
let init = fn;
let call = types.callExpression(types.identifier(id), callArgs);
const fnParent = loopPath.findParent(p => p.isFunctionParent());
let wrappedAsyncGenerators;
let isWrappedAsyncGenerator = false;
if (fnParent) {
wrappedAsyncGenerators = pluginPass.file.get("@babel/plugin-transform-async-generator-functions/wrapped_async_generators");
if (state.hasTryFinally && fnParent.isFunction() && fnParent.node.generator && wrappedAsyncGenerators?.has(fnParent.node.body)) {
isWrappedAsyncGenerator = true;
fn.generator = true;
init = types.callExpression(pluginPass.addHelper("wrapAsyncGenerator"), [fn]);
call = types.yieldExpression(types.callExpression(pluginPass.addHelper("asyncGeneratorDelegate"), [call]), true);
} else {
const {
async = false,
generator = false
} = 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;
const [varPath] = loopPath.insertBefore(types.variableDeclaration("var", [types.variableDeclarator(types.identifier(id), init)]));
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));
} else if (types.isForXStatement(varPath.parent, {
left: varPath.node
})) {
assign.push(decl.id);
}
}
if (assign.length > 0) {
const replacement = assign.length === 1 ? assign[0] : types.sequenceExpression(assign);
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 || types.buildUndefinedNode();
path.replaceWith(template.statement.ast`
return { v: ${arg} };
`);
}
bodyStmts.push(template.statement.ast`
if (${types.identifier(completionId)}) return ${types.identifier(completionId)}.v;
`);
}
}
const loopBlockBody = types.toBlock(loopNode.body);
loopNode.body = types.blockStatement(bodyStmts);
fn.body = loopBlockBody;
if (isWrappedAsyncGenerator) {
wrappedAsyncGenerators.add(loopBlockBody);
}
if (updaterNode) loopBlockBody.body.push(updaterNode);
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 isVarInForStatementInit(path) {
return path.parentPath.isForStatement() && path.key === "init";
}
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 isEvaluatedAfterLoopHead(refPath, bindingPath) {
if (!bindingPath.isVariableDeclarator()) return false;
const declPath = bindingPath.parentPath;
if (!isVarInLoopHead(declPath)) return false;
const loop = declPath.parent;
const afterHead = [loop.body];
if (types.isForStatement(loop)) {
if (loop.test) afterHead.push(loop.test);
if (loop.update) afterHead.push(loop.update);
}
return !!refPath.find(p => afterHead.includes(p.node));
}
function getTDZStatus(refPath, bindingPath) {
if (isEvaluatedAfterLoopHead(refPath, bindingPath)) return "outside";
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.getAssignmentIdentifiers();
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.isForXStatement({
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 index = declare((api, opts) => {
api.assertVersion("^7.0.0-0 || ^8.0.0");
const {
throwIfClosureRequired = false,
tdz: tdzEnabled = false
} = opts;
if (typeof throwIfClosureRequired !== "boolean") {
throw new Error(`.throwIfClosureRequired must be a boolean, or undefined`);
}
if (typeof tdzEnabled !== "boolean") {
throw new Error(`.tdz must be a boolean, or undefined`);
}
return {
name: "transform-block-scoping",
visitor: {
Loop(path, state) {
const isForStatement = path.isForStatement();
const headPath = isForStatement ? path.get("init") : path.isForXStatement() ? path.get("left") : null;
let needsBodyWrap = false;
const markNeedsBodyWrap = () => {
if (throwIfClosureRequired) {
throw path.buildCodeFrameError("Compiling let/const in this block would add a closure " + "(throwIfClosureRequired).");
}
needsBodyWrap = true;
};
if (path.isForStatement()) moveCapturingTestAndUpdateIntoBody(path);
const body = path.get("body");
let bodyScope;
if (body.isBlockStatement()) {
bodyScope = body.scope;
}
const bindings = getLoopBodyBindings(path);
for (const binding of bindings) {
const {
capturedInClosure
} = getUsageInBody(binding, path);
if (capturedInClosure) markNeedsBodyWrap();
}
const captured = [];
const updatedBindingsUsages = new Map();
if (headPath && isBlockScoped(headPath)) {
const names = Object.keys(headPath.getBindingIdentifiers());
const headScope = headPath.scope;
for (let name of names) {
if (bodyScope?.hasOwnBinding(name)) continue;
let binding = headScope.getOwnBinding(name);
if (!binding) {
headScope.crawl();
binding = headScope.getOwnBinding(name);
}
const {
usages,
capturedInClosure,
hasConstantViolations,
capturedInHeadClosure,
headUsages
} = getUsageInBody(binding, path);
if (headScope.parent.hasBinding(name) || headScope.parent.hasGlobal(name)) {
const newName = headScope.generateUid(name);
headScope.rename(name, newName);
name = newName;
}
if (capturedInHeadClosure && binding.constantViolations.length) {
const headName = headScope.generateUid(name);
const declarationIds = binding.path.get("id").getBindingIdentifierPaths(true)[name];
for (const usage of [...declarationIds, ...headUsages]) {
usage.replaceWith(types.identifier(headName));
}
headPath.pushContainer("declarations", types.variableDeclarator(types.identifier(name), types.identifier(headName)));
headScope.crawl();
}
if (capturedInClosure) {
markNeedsBodyWrap();
captured.push(name);
}
if (isForStatement && hasConstantViolations) {
updatedBindingsUsages.set(name, usages);
}
}
}
if (needsBodyWrap) {
const varPath = wrapLoopBody(path, captured, updatedBindingsUsages, state);
if (headPath?.isVariableDeclaration()) {
let loopPath = varPath.getSibling(varPath.key + 1);
while (loopPath.isLabeledStatement()) {
loopPath = loopPath.get("body");
}
loopPath.scope.crawl();
transformBlockScopedVariable(loopPath.get(isForStatement ? "init" : "left"), state, tdzEnabled);
}
const initPath = varPath.get("declarations.0.init");
const fnPath = initPath.isCallExpression() ? initPath.get("arguments.0") : initPath;
fnPath.unwrapFunctionEnvironment();
}
},
VariableDeclaration(path, state) {
transformBlockScopedVariable(path, state, tdzEnabled);
},
ClassDeclaration(path) {
const {
id
} = path.node;
if (!id) return;
const {
scope
} = path.parentPath;
if (!isVarScope(scope) && scope.parent.hasBinding(id.name, {
noUids: true
})) {
path.scope.rename(id.name);
}
}
}
};
});
const conflictingFunctionsVisitor = {
Scope(path, {
names
}) {
for (const name of names) {
const binding = path.scope.getOwnBinding(name);
if (binding?.kind === "hoisted") {
path.scope.rename(name);
}
}
},
"Expression|Declaration"(path) {
path.skip();
}
};
function transformBlockScopedVariable(path, state, tdzEnabled) {
if (!isBlockScoped(path)) return;
const dynamicTDZNames = validateUsage(path, state, tdzEnabled);
path.node.kind = "var";
const bindingNames = Object.keys(path.getBindingIdentifiers());
for (const name of bindingNames) {
const binding = path.scope.getOwnBinding(name);
if (!binding) continue;
binding.kind = "var";
}
const isLoopBodyDeclaration = isInLoop(path) && !isVarInLoopHead(path);
const isNestedForStatementInit = isVarInForStatementInit(path) && isInLoop(path.parentPath);
const shouldInitLoopDeclaration = isLoopBodyDeclaration || isNestedForStatementInit;
if (shouldInitLoopDeclaration || dynamicTDZNames.length > 0) {
for (const decl of path.node.declarations) {
decl.init ??= types.buildUndefinedNode();
}
}
const blockScope = path.scope;
const varScope = blockScope.getFunctionParent() || blockScope.getProgramParent();
if (varScope !== blockScope) {
for (const name of bindingNames) {
let newName = name;
if (blockScope.parent.hasBinding(name, {
noUids: true
}) || blockScope.parent.hasGlobal(name)) {
newName = blockScope.generateUid(name);
blockScope.rename(name, newName);
}
blockScope.moveBindingTo(newName, varScope);
}
}
blockScope.path.traverse(conflictingFunctionsVisitor, {
names: bindingNames
});
const tdzScope = isVarInLoopHead(path) ? path.scope.parent : path.scope;
for (const name of dynamicTDZNames) {
tdzScope.push({
id: types.identifier(name),
init: state.addHelper("temporalUndefined")
});
}
}
function isLetOrConst(kind) {
return kind === "let" || kind === "const";
}
function isInLoop(path) {
if (!path.parentPath) return false;
if (path.parentPath.isLoop()) return true;
if (path.parentPath.isFunctionParent()) return false;
return isInLoop(path.parentPath);
}
function isBlockScoped(path) {
const {
node
} = path;
if (!types.isVariableDeclaration(node)) return false;
const {
kind
} = node;
if (kind === "using" || kind === "await using") {
throw path.buildCodeFrameError(`The ${kind} declaration should be first transformed by \`@babel/plugin-transform-explicit-resource-management\`.`);
} else if (!isLetOrConst(kind)) {
return false;
}
return true;
}
function isVarScope(scope) {
return scope.path.isFunctionParent() || scope.path.isProgram();
}
export { index as default, isVarScope };