From 6757a60912d3c9e83bb5e2c95583f9df48a6f535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Ribaudo?= Date: Wed, 14 Dec 2022 19:38:57 +0100 Subject: [PATCH] Rewrite `transform-block-scoping` plugin (#15200) * Add test for `const` with `tdz` * Rewrite block-scoping plugin * Update block-scoping fixtures * Update other fixtures * Fix `let` shadowing variable read in a sibling scope * Update fixtures * Update Babel 8 fixtures * Add minNodeVersion * Fix block scoped vars shadowing globals * Review by JLHwung * minNodeVersion to class fields test --- .../misc/regression-2892/output.js | 64 +- .../output.js | 16 +- .../src/annex-B_3_3.ts | 127 ++ .../src/index.ts | 1145 +++-------------- .../src/loop.ts | 334 +++++ .../src/tdz.ts | 145 --- .../src/validation.ts | 204 +++ .../input.js | 0 .../output.js | 0 .../input.js | 0 .../options.json | 0 .../output.js | 0 .../input.js | 0 .../output.js | 0 .../input.js | 0 .../output.js | 0 .../input.js | 0 .../output.js | 0 .../input.js | 0 .../options.json | 0 .../output.js | 14 +- .../general/annex-B_3_3-in-class/exec.js | 17 + .../general/annex-B_3_3-in-class/input.js | 17 + .../general/annex-B_3_3-in-class/output.js | 14 + .../annex-B_3_3-in-module-expression/input.js | 11 + .../options.json | 7 + .../output.js | 10 + .../input.mjs | 0 .../output.mjs | 0 .../{issue-10046 => annex-B_3_3}/input.js | 0 .../{issue-10046 => annex-B_3_3}/output.js | 0 .../general/block-not-shadow-global/input.js | 15 + .../general/block-not-shadow-global/output.js | 28 + .../block-not-shadow-outer-variable/exec.js | 10 + .../block-not-shadow-outer-variable/input.js | 6 + .../block-not-shadow-outer-variable/output.js | 9 + .../closure-in-generator-or-async/exec.js | 36 + .../closure-in-generator-or-async/input.js | 23 + .../options.json | 6 + .../closure-in-generator-or-async/output.js | 39 + .../for-break-continue-closure/output.js | 22 +- .../general/for-const-closure/output.js | 4 +- .../test/fixtures/general/hoisting/output.js | 3 +- .../general/issue-10046-strict/input.js | 11 - .../general/issue-10046-strict/output.js | 10 - .../test/fixtures/general/issue-10339/exec.js | 2 +- .../fixtures/general/issue-10339/output.js | 4 +- .../fixtures/general/issue-1051/output.js | 21 +- .../fixtures/general/issue-4363/output.js | 8 +- .../general/issue-8128-for-of-after/output.js | 7 +- .../issue-8128-for-of-loose-after/output.js | 7 +- .../test/fixtures/general/issue-973/output.js | 4 +- .../general/loop-closure-in-class/exec.js | 10 + .../general/loop-closure-in-class/input.js | 5 + .../loop-closure-in-class/options.json | 3 + .../general/loop-closure-in-class/output.js | 8 + .../general/loops-and-no-loops/output.js | 15 +- .../fixtures/general/superswitch/output.js | 32 +- .../general/switch-callbacks/output.js | 25 +- .../wrap-closure-shadow-variables/output.js | 4 +- .../test/fixtures/tdz/const-readonly/exec.js | 33 + .../test/fixtures/tdz/const-readonly/input.js | 6 + .../fixtures/tdz/const-readonly/output.js | 7 + .../test/fixtures/tdz/exported-fn/output.mjs | 2 +- .../function-call-maybe-real-after/output.js | 2 +- .../output.js | 2 +- .../tdz/function-call-maybe/output.js | 3 +- .../function-call-nested-function/output.js | 3 +- .../output.js | 2 +- .../test/fixtures/tdz/function-ref/output.js | 3 +- .../fixtures/tdz/update-expression/output.js | 3 +- .../test/fixtures/regression/T6755/output.js | 32 +- .../output.js | 2 +- .../destructuring-empty-in-for/output.js | 24 +- .../empty-array-pattern/output.js | 34 +- .../destructuring/parameters/output.js | 16 +- .../output.js | 1 - .../test/fixtures/regression/4219/output.js | 14 +- .../test/fixtures/regression/6733/output.js | 22 +- .../test/fixtures/regression/T7041/output.js | 10 +- .../complex-options-babel-7/output.js | 38 +- .../absoluteRuntime/complex-options/output.js | 38 +- .../true-corejs3-proposals/output.js | 22 +- .../true-corejs3-stable/output.js | 22 +- .../output.js | 4 +- .../safari-block-scoping-safari-9/output.js | 4 +- .../entry-shippedProposals/output.js | 22 +- .../usage-destructuring-for-x/output.mjs | 4 +- .../corejs2-babel-7/usage-for-of/output.mjs | 4 +- .../usage-regenerator-used-async/output.mjs | 12 +- .../output.mjs | 12 +- .../usage-shippedProposals/output.js | 24 +- .../corejs2/entry-shippedProposals/output.js | 22 +- .../corejs2/usage-shippedProposals/output.js | 24 +- .../usage-destructuring-for-x/output.mjs | 4 +- .../corejs3-babel-7/usage-for-of/output.mjs | 4 +- .../usage-regenerator-used-async/output.mjs | 12 +- .../output.mjs | 12 +- .../plugins-integration/issue-15012/output.js | 20 +- .../plugins-integration/issue-15170/output.js | 34 +- .../shippedProposals/output.js | 22 +- packages/babel-traverse/src/scope/index.ts | 30 +- 102 files changed, 1538 insertions(+), 1575 deletions(-) create mode 100644 packages/babel-plugin-transform-block-scoping/src/annex-B_3_3.ts create mode 100644 packages/babel-plugin-transform-block-scoping/src/loop.ts delete mode 100644 packages/babel-plugin-transform-block-scoping/src/tdz.ts create mode 100644 packages/babel-plugin-transform-block-scoping/src/validation.ts rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-async-generator => annex-B_3_3-async-generator}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-async-generator => annex-B_3_3-async-generator}/output.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-async => annex-B_3_3-async}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-async => annex-B_3_3-async}/options.json (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-async => annex-B_3_3-async}/output.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-const => annex-B_3_3-collision-const}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-const => annex-B_3_3-collision-const}/output.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-let => annex-B_3_3-collision-let}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-let => annex-B_3_3-collision-let}/output.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-var => annex-B_3_3-collision-var}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-collision-var => annex-B_3_3-collision-var}/output.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-generator => annex-B_3_3-generator}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-generator => annex-B_3_3-generator}/options.json (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-generator => annex-B_3_3-generator}/output.js (52%) create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/exec.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/output.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/options.json create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/output.js rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-module => annex-B_3_3-module}/input.mjs (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046-module => annex-B_3_3-module}/output.mjs (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046 => annex-B_3_3}/input.js (100%) rename packages/babel-plugin-transform-block-scoping/test/fixtures/general/{issue-10046 => annex-B_3_3}/output.js (100%) create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/output.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/exec.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/output.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/exec.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/options.json create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/output.js delete mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/input.js delete mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/output.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/exec.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/options.json create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/output.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/exec.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/input.js create mode 100644 packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/output.js diff --git a/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js b/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js index 95cf1ea90be7..247c9685a7ea 100644 --- a/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js +++ b/packages/babel-core/test/fixtures/transformation/misc/regression-2892/output.js @@ -14,14 +14,12 @@ var Foo = /*#__PURE__*/function () { var _bar = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { var baz; return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - baz = 0; - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + baz = 0; + case 1: + case "end": + return _context.stop(); } }, _callee); })); @@ -41,33 +39,29 @@ function _foo() { _foo = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee3() { var bar, _bar2; return babelHelpers.regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _bar2 = function _bar4() { - _bar2 = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee2() { - var baz; - return babelHelpers.regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - baz = {}; - case 1: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - return _bar2.apply(this, arguments); - }; - bar = function _bar3() { - return _bar2.apply(this, arguments); - }; - case 2: - case "end": - return _context3.stop(); - } + while (1) switch (_context3.prev = _context3.next) { + case 0: + _bar2 = function _bar4() { + _bar2 = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee2() { + var baz; + return babelHelpers.regeneratorRuntime().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + baz = {}; + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _bar2.apply(this, arguments); + }; + bar = function _bar3() { + return _bar2.apply(this, arguments); + }; + case 2: + case "end": + return _context3.stop(); } }, _callee3); })); diff --git a/packages/babel-plugin-proposal-class-properties/test/fixtures/private/1-helpermemberexpressionfunction/output.js b/packages/babel-plugin-proposal-class-properties/test/fixtures/private/1-helpermemberexpressionfunction/output.js index 924024b08a8d..4b826532c38b 100644 --- a/packages/babel-plugin-proposal-class-properties/test/fixtures/private/1-helpermemberexpressionfunction/output.js +++ b/packages/babel-plugin-proposal-class-properties/test/fixtures/private/1-helpermemberexpressionfunction/output.js @@ -12,9 +12,7 @@ var D = /*#__PURE__*/function () { babelHelpers.createClass(D, [{ key: "f", value: function f() { - for (var el of babelHelpers.classPrivateFieldGet(this, _arr)) { - ; - } + for (var el of babelHelpers.classPrivateFieldGet(this, _arr)); } }]); return D; @@ -33,9 +31,7 @@ var C = /*#__PURE__*/function () { babelHelpers.createClass(C, [{ key: "m", value: function m() { - for (babelHelpers.classPrivateFieldDestructureSet(this, _p).value of []) { - ; - } + for (babelHelpers.classPrivateFieldDestructureSet(this, _p).value of []); } }]); return C; @@ -54,9 +50,7 @@ var E = /*#__PURE__*/function () { babelHelpers.createClass(E, [{ key: "f", value: function f() { - for (babelHelpers.classPrivateFieldDestructureSet(this, _arr2).value of [1, 2]) { - ; - } + for (babelHelpers.classPrivateFieldDestructureSet(this, _arr2).value of [1, 2]); } }]); return E; @@ -75,9 +69,7 @@ var F = /*#__PURE__*/function () { babelHelpers.createClass(F, [{ key: "g", value: function g() { - for (babelHelpers.classPrivateFieldDestructureSet(this, _ar).value in [1, 2, 3]) { - ; - } + for (babelHelpers.classPrivateFieldDestructureSet(this, _ar).value in [1, 2, 3]); } }]); return F; diff --git a/packages/babel-plugin-transform-block-scoping/src/annex-B_3_3.ts b/packages/babel-plugin-transform-block-scoping/src/annex-B_3_3.ts new file mode 100644 index 000000000000..346c1bdcbc74 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/src/annex-B_3_3.ts @@ -0,0 +1,127 @@ +import { types as t } from "@babel/core"; +import type { NodePath, Visitor, Scope } from "@babel/traverse"; + +// Whenever a function declaration in a nested block scope +// doesn't conflict with a block-scoped binding from an outer +// scope, we transform it to a variable declaration. +// +// This implements the Annex B.3.3 behavior. +// +// TODO(Babel 8): Figure out how this should interact with +// the transform-block-scoped functions plugin (it feels +// wrong to handle this transform here), and what we want +// to do with Anned B behavior in general. + +// To avoid confusing block-scoped variables transformed to +// var with original vars, this transformation happens in two +// different places: +// 1. For functions that "conflict" with var-variables, in +// the VariableDeclaration visitor. +// 2. For functions that don't conflict with any variable, +// in the FunctionDeclaration visitor. + +export const annexB33FunctionsVisitor: Visitor = { + VariableDeclaration(path) { + if (isStrict(path)) return; + if (path.node.kind !== "var") return; + + const varScope = + path.scope.getFunctionParent() || path.scope.getProgramParent(); + // eslint-disable-next-line @typescript-eslint/no-use-before-define + varScope.path.traverse(functionsToVarVisitor, { + names: Object.keys(path.getBindingIdentifiers()), + }); + }, + + // NOTE: These two visitors target the same nodes as the + // block-scoped-functions plugin + + BlockStatement(path) { + if (isStrict(path)) return; + if (t.isFunction(path.parent, { body: path.node })) return; + transformStatementList(path.get("body")); + }, + + SwitchCase(path) { + if (isStrict(path)) return; + transformStatementList(path.get("consequent")); + }, +}; + +function transformStatementList(paths: NodePath[]) { + outer: for (const path of paths) { + if (!path.isFunctionDeclaration()) continue; + // Annex B.3.3 only applies to plain functions. + 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: NodePath, +) { + const { + node, + parentPath: { scope }, + } = path; + + const { id } = node; + scope.removeOwnBinding(id.name); + node.id = null; + + const varNode = t.variableDeclaration("var", [ + t.variableDeclarator(id, t.toExpression(node)), + ]); + // @ts-expect-error undocumented property + varNode._blockHoist = 2; + + const [varPath] = path.replaceWith(varNode); + scope.registerDeclaration(varPath); +} + +const functionsToVarVisitor: Visitor<{ names: string[] }> = { + Scope(path, { names }) { + for (const name of names) { + const binding = path.scope.getOwnBinding(name); + if (binding && binding.kind === "hoisted") { + maybeTransformBlockScopedFunction( + binding.path as NodePath, + ); + } + } + }, + "Expression|Declaration"(path) { + path.skip(); + }, +}; + +export function isVarScope(scope: Scope) { + return scope.path.isFunctionParent() || scope.path.isProgram(); +} + +function isStrict(path: NodePath) { + return !!path.find(({ node }) => { + if (t.isProgram(node)) { + if (node.sourceType === "module") return true; + } else if (t.isClass(node)) { + return true; + } else if (!t.isBlockStatement(node)) { + return false; + } + + return node.directives?.some( + directive => directive.value.value === "use strict", + ); + }); +} diff --git a/packages/babel-plugin-transform-block-scoping/src/index.ts b/packages/babel-plugin-transform-block-scoping/src/index.ts index d0cc2d707794..9b578fcf5409 100644 --- a/packages/babel-plugin-transform-block-scoping/src/index.ts +++ b/packages/babel-plugin-transform-block-scoping/src/index.ts @@ -1,11 +1,15 @@ import { declare } from "@babel/helper-plugin-utils"; -import type { NodePath, Visitor, Scope, Binding } from "@babel/traverse"; -import { skipTDZChecks, visitor as tdzVisitor } from "./tdz"; -import type { TDZVisitorState } from "./tdz"; -import { traverse, template, types as t } from "@babel/core"; -import type { PluginPass } from "@babel/core"; - -const DONE = new WeakSet(); +import type { NodePath, Scope, Visitor } from "@babel/traverse"; +import { type PluginPass, types as t, traverse } from "@babel/core"; + +import { + getLoopBodyBindings, + getUsageInBody, + isVarInLoopHead, + wrapLoopBody, +} from "./loop"; +import { validateUsage } from "./validation"; +import { annexB33FunctionsVisitor, isVarScope } from "./annex-B_3_3"; export interface Options { tdz?: boolean; @@ -26,1001 +30,224 @@ export default declare((api, opts: Options) => { return { name: "transform-block-scoping", - visitor: { - VariableDeclaration(path) { - const { node, parent, scope } = path; - if (!isBlockScoped(node)) return; - convertBlockScopedToVar(path, null, parent, scope, true); + visitor: traverse.visitors.merge([ + // TODO: Consider adding an option to control Annex B behavior. + annexB33FunctionsVisitor, + { + Loop(path: NodePath, 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; + }; + + const body = path.get("body"); + let bodyScope: Scope | null; + 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: string[] = []; + const updatedBindingsUsages: Map[]> = + new Map(); - // @ts-expect-error todo(flow->ts): avoid mutations - if (node._tdzThis) { - const nodes: t.Node[] = [node]; + if (headPath && isBlockScoped(headPath.node)) { + const names = Object.keys(headPath.getBindingIdentifiers()); - for (let i = 0; i < node.declarations.length; i++) { - const decl = node.declarations[i]; - const assign = t.assignmentExpression( - "=", - t.cloneNode(decl.id), - decl.init || scope.buildUndefinedNode(), - ); - skipTDZChecks.add(assign); - nodes.push(t.expressionStatement(assign)); - decl.init = this.addHelper("temporalUndefined"); - } + for (const name of names) { + if (bodyScope?.hasOwnBinding(name)) continue; // shadowed - // @ts-expect-error todo(flow->ts): avoid mutations - node._blockHoist = 2; + const { usages, capturedInClosure, hasConstantViolations } = + getUsageInBody(headPath.scope.getOwnBinding(name), path); - if (path.isCompletionRecord()) { - // ensure we don't break completion record semantics by returning - // the initialiser of the last declarator - nodes.push(t.expressionStatement(scope.buildUndefinedNode())); + if (capturedInClosure) { + markNeedsBodyWrap(); + captured.push(name); + } + if (isForStatement && hasConstantViolations) { + updatedBindingsUsages.set(name, usages); + } + } } - path.replaceWithMultiple(nodes); - } - }, + if (needsBodyWrap) { + const varPath = wrapLoopBody(path, captured, updatedBindingsUsages); + + if (headPath?.isVariableDeclaration()) { + // If we wrap the loop body, we transform the var + // declaration in the loop head now, to avoid + // invalid references that break other plugins: + // + // for (let head of x) { + // let i = head; + // setTimeout(() => i); + // } + // + // would become + // + // function _loop() { + // let i = head; + // setTimeout(() => i); + // } + // for (let head of x) _loop(); + // + // which references `head` in a scope where it's not visible. + transformBlockScopedVariable(headPath, state, tdzEnabled); + } + + varPath.get("declarations.0.init").unwrapFunctionEnvironment(); + } + }, - Loop(path: NodePath, state) { - const { parent, scope } = path; - path.ensureBlock(); - const blockScoping = new BlockScoping( - path, - path.get("body"), - parent, - scope, - throwIfClosureRequired, - tdzEnabled, - state, - ); - const replace = blockScoping.run(); - if (replace) path.replaceWith(replace); - }, + VariableDeclaration(path, state) { + transformBlockScopedVariable(path, state, tdzEnabled); + }, - CatchClause(path, state) { - const { parent, scope } = path; - const blockScoping = new BlockScoping( - null, - path.get("body"), - parent, - scope, - throwIfClosureRequired, - tdzEnabled, - state, - ); - blockScoping.run(); - }, + // Class declarations are block-scoped: if there is + // a class declaration in a nested block that conflicts + // with an outer block-scoped binding, rename it. + // TODO: Should this be moved to the classes plugin? + ClassDeclaration(path) { + const { id } = path.node; + if (!id) return; - "BlockStatement|SwitchStatement|Program"( - path: NodePath, - state, - ) { - if (!ignoreBlock(path)) { - const blockScoping = new BlockScoping( - null, - path, - path.parent, - path.scope, - throwIfClosureRequired, - tdzEnabled, - state, - ); - blockScoping.run(); - } + const { scope } = path.parentPath; + if ( + !isVarScope(scope) && + scope.parent.hasBinding(id.name, { noUids: true }) + ) { + path.scope.rename(id.name); + } + }, }, - }, + ]), }; }); -function ignoreBlock( - path: NodePath, -) { - return t.isLoop(path.parent) || t.isCatchClause(path.parent); -} - -const buildRetCheck = template.statement(` - if (typeof RETURN === "object") return RETURN.v; -`); - -function isBlockScoped(node: t.Node): node is t.VariableDeclaration { - if (!t.isVariableDeclaration(node)) return false; - if ( - // @ts-expect-error Fixme: document symbol properties - node[t.BLOCK_SCOPED_SYMBOL] - ) { - return true; - } - - if (node.kind !== "let" && node.kind !== "const" && node.kind !== "using") { - return false; - } - - return true; -} - -/** - * If there is a loop ancestor closer than the closest function, we - * consider ourselves to be in a loop. - */ -function isInLoop(path: NodePath) { - const loopOrFunctionParent = path.find( - path => path.isLoop() || path.isFunction(), - ); - - return loopOrFunctionParent?.isLoop(); -} - -function convertBlockScopedToVar( - path: NodePath, - node: t.VariableDeclaration, - parent: t.Node, - scope: Scope, - moveBindingsToParent = false, -) { - if (!node) { - node = path.node; - } - - // https://github.com/babel/babel/issues/255 - if (isInLoop(path) && !t.isFor(parent)) { - for (let i = 0; i < node.declarations.length; i++) { - const declar = node.declarations[i]; - declar.init = declar.init || scope.buildUndefinedNode(); - } - } - - // @ts-expect-error todo(flow->ts): avoid mutations - node[t.BLOCK_SCOPED_SYMBOL] = true; - node.kind = "var"; - - // Move bindings from current block scope to function scope. - if (moveBindingsToParent) { - const parentScope = scope.getFunctionParent() || scope.getProgramParent(); - for (const name of Object.keys(path.getBindingIdentifiers())) { - const binding = scope.getOwnBinding(name); - if (binding) binding.kind = "var"; - scope.moveBindingTo(name, parentScope); - } - } -} - -function isVar(node: t.Node): node is t.VariableDeclaration { - return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); -} - -interface LetReferenceVisitorState extends TDZVisitorState { - loopDepth: number; - closurify: boolean; -} - -const letReferenceFunctionVisitor = traverse.visitors.merge([ - { - ReferencedIdentifier(path, state) { - const ref = state.letReferences.get(path.node.name); - - // not a part of our scope - if (!ref) return; - - // this scope has a variable with the same name so it couldn't belong - // to our let scope - const localBinding = path.scope.getBindingIdentifier(path.node.name); - if (localBinding && localBinding !== ref) return; - - state.closurify = true; - }, - }, - tdzVisitor, -] as Visitor[]); - -const letReferenceBlockVisitor = traverse.visitors.merge([ - { - Loop: { - enter(path, state) { - state.loopDepth++; - }, - exit(path, state) { - state.loopDepth--; - }, - }, - FunctionParent(path, state) { - // References to block-scoped variables only require added closures if it's - // possible for the code to run more than once -- otherwise it is safe to - // simply rename the variables. - if (state.loopDepth > 0) { - path.traverse(letReferenceFunctionVisitor, state); - } else { - path.traverse(tdzVisitor, state); - } - return path.skip(); - }, - }, - tdzVisitor, -] as Visitor[]); - -const hoistVarDeclarationsVisitor: Visitor = { - enter(path, self) { - if (path.isForStatement()) { - const { node } = path; - if (isVar(node.init)) { - const nodes = self.pushDeclar(node.init); - if (nodes.length === 1) { - node.init = nodes[0]; - } else { - node.init = t.sequenceExpression(nodes); - } - } - } else if (path.isForInStatement() || path.isForOfStatement()) { - const { node } = path; - if (isVar(node.left)) { - self.pushDeclar(node.left); - node.left = node.left.declarations[0].id; +const conflictingFunctionsVisitor: Visitor<{ names: string[] }> = { + Scope(path, { names }) { + for (const name of names) { + const binding = path.scope.getOwnBinding(name); + if (binding && binding.kind === "hoisted") { + path.scope.rename(name); } - } else if (isVar(path.node)) { - path.replaceWithMultiple( - self.pushDeclar(path.node).map(expr => t.expressionStatement(expr)), - ); - } else if (path.isFunction()) { - return path.skip(); } }, -}; - -type LoopVisitorState = { - inSwitchCase: boolean; - hasBreakContinue: boolean; - innerLabels: string[]; - hasReturn: boolean; - ignoreLabeless: boolean; - loopIgnored: WeakSet; - isLoop: boolean; - map: Map; -}; - -const loopLabelVisitor: Visitor = { - LabeledStatement({ node }, state) { - state.innerLabels.push(node.label.name); - }, -}; - -interface ContinuationVisitorState { - returnStatements: NodePath[]; - reassignments: { [k: string]: boolean | undefined }; - outsideReferences: Map; -} - -const continuationVisitor: Visitor = { - enter(path, state) { - if (path.isAssignmentExpression() || path.isUpdateExpression()) { - for (const name of Object.keys(path.getBindingIdentifiers())) { - if ( - state.outsideReferences.get(name) !== - path.scope.getBindingIdentifier(name) - ) { - continue; - } - state.reassignments[name] = true; - } - } else if (path.isReturnStatement()) { - state.returnStatements.push(path); - } - }, -}; - -function loopNodeTo(node: t.Node) { - if (t.isBreakStatement(node)) { - return "break"; - } else if (t.isContinueStatement(node)) { - return "continue"; - } -} - -const loopVisitor: Visitor = { - Loop(path, state) { - const oldIgnoreLabeless = state.ignoreLabeless; - state.ignoreLabeless = true; - path.traverse(loopVisitor, state); - state.ignoreLabeless = oldIgnoreLabeless; - path.skip(); - }, - - Function(path) { - path.skip(); - }, - - SwitchCase(path, state) { - const oldInSwitchCase = state.inSwitchCase; - state.inSwitchCase = true; - path.traverse(loopVisitor, state); - state.inSwitchCase = oldInSwitchCase; + "Expression|Declaration"(path) { path.skip(); }, - - "BreakStatement|ContinueStatement|ReturnStatement"( - path: NodePath, - state, - ) { - const { node, scope } = path; - if (state.loopIgnored.has(node)) return; - - let replace; - let loopText = loopNodeTo(node); - - if (loopText) { - if (t.isReturnStatement(node)) { - throw new Error( - "Internal error: unexpected return statement with `loopText`", - ); - } - if (node.label) { - // we shouldn't be transforming this because it exists somewhere inside - if (state.innerLabels.indexOf(node.label.name) >= 0) { - return; - } - - loopText = `${loopText}|${node.label.name}`; - } else { - // we shouldn't be transforming these statements because - // they don't refer to the actual loop we're scopifying - if (state.ignoreLabeless) return; - - // break statements mean something different in this context - if (t.isBreakStatement(node) && state.inSwitchCase) return; - } - - state.hasBreakContinue = true; - state.map.set(loopText, node); - replace = t.stringLiteral(loopText); - } - - if (t.isReturnStatement(node)) { - state.hasReturn = true; - replace = t.objectExpression([ - t.objectProperty( - t.identifier("v"), - node.argument || scope.buildUndefinedNode(), - ), - ]); - } - - if (replace) { - replace = t.returnStatement(replace); - state.loopIgnored.add(replace); - path.skip(); - path.replaceWith(t.inherits(replace, node)); - } - }, }; -function isStrict(path: NodePath) { - return !!path.find(({ node }) => { - if (t.isProgram(node)) { - if (node.sourceType === "module") return true; - } else if (!t.isBlockStatement(node)) return false; - - return node.directives.some( - directive => directive.value.value === "use strict", - ); - }); -} - -class BlockScoping { - private parent: t.Node; - private state: PluginPass; - private scope: Scope; - private throwIfClosureRequired: boolean; - private tdzEnabled: boolean; - private blockPath: NodePath; - private block: t.Block | t.SwitchStatement; - private outsideLetReferences: Map; - private hasLetReferences: boolean; - private letReferences: Map; - private body: t.Statement[]; - // todo(flow->ts) add more specific type - private loopParent: t.Node; - private loopLabel: t.Identifier; - private loopPath: NodePath; - private loop: t.Loop; - private has: LoopVisitorState; - constructor( - loopPath: NodePath | undefined | null, - blockPath: NodePath, - parent: t.Node, - scope: Scope, - throwIfClosureRequired: boolean, - tdzEnabled: boolean, - state: PluginPass, - ) { - this.parent = parent; - this.scope = scope; - this.state = state; - this.throwIfClosureRequired = throwIfClosureRequired; - this.tdzEnabled = tdzEnabled; - - this.blockPath = blockPath; - this.block = blockPath.node; - - this.outsideLetReferences = new Map(); - this.hasLetReferences = false; - this.letReferences = new Map(); - this.body = []; - - if (loopPath) { - this.loopParent = loopPath.parent; - this.loopLabel = - t.isLabeledStatement(this.loopParent) && this.loopParent.label; - this.loopPath = loopPath; - this.loop = loopPath.node; - } - } - - /** - * Start the ball rolling. - */ - - run() { - const block = this.block; - if (DONE.has(block)) return; - DONE.add(block); - - const needsClosure = this.getLetReferences(); - - this.checkConstants(); - - // this is a block within a `Function/Program` so we can safely leave it be - if (t.isFunction(this.parent) || t.isProgram(this.block)) { - this.updateScopeInfo(); - return; - } - - // we can skip everything - if (!this.hasLetReferences) return; - - if (needsClosure) { - this.wrapClosure(); - } else { - this.remap(); - } - - this.updateScopeInfo(needsClosure); - - if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { - return t.labeledStatement(this.loopLabel, this.loop); - } - } - - checkConstants() { - const constBindings = new Map(); - - // In some cases, there are two different scopes: for example, - // for (const x of y) {} has a scope for the loop head and one - // for the body. - for (const scope of new Set([this.scope, this.blockPath.scope])) { - for (const name of Object.keys(scope.bindings)) { - const binding = scope.bindings[name]; - if (binding.kind === "const") constBindings.set(name, binding); - } - } +function transformBlockScopedVariable( + path: NodePath, + state: PluginPass, + tdzEnabled: boolean, +) { + if (!isBlockScoped(path.node)) return; - const { state } = this; + const dynamicTDZNames = validateUsage(path, state, tdzEnabled); - for (const [name, binding] of constBindings) { - for (const violation of binding.constantViolations) { - const readOnlyError = state.addHelper("readOnlyError"); - const throwNode = t.callExpression(readOnlyError, [ - t.stringLiteral(name), - ]); + path.node.kind = "var"; - if (violation.isAssignmentExpression()) { - const { operator } = violation.node; - if (operator === "=") { - violation.replaceWith( - t.sequenceExpression([violation.get("right").node, throwNode]), - ); - } else if (["&&=", "||=", "??="].includes(operator)) { - violation.replaceWith( - t.logicalExpression( - // @ts-expect-error todo(flow->ts) - operator.slice(0, -1), - violation.get("left").node, - t.sequenceExpression([violation.get("right").node, throwNode]), - ), - ); - } else { - violation.replaceWith( - t.sequenceExpression([ - t.binaryExpression( - // @ts-expect-error todo(flow->ts) - operator.slice(0, -1), - violation.get("left").node, - violation.get("right").node, - ), - throwNode, - ]), - ); - } - } else if (violation.isUpdateExpression()) { - violation.replaceWith( - t.sequenceExpression([ - t.unaryExpression("+", violation.get("argument").node), - throwNode, - ]), - ); - } else if (violation.isForXStatement()) { - // @ts-expect-error TS requires explicit annotation of "violation" - violation.ensureBlock(); - violation - .get("left") - .replaceWith( - t.variableDeclaration("var", [ - t.variableDeclarator( - violation.scope.generateUidIdentifier(name), - ), - ]), - ); - // @ts-expect-error todo(flow->ts): possible bug "for(…) switch(){}" - violation.node.body.body.unshift(t.expressionStatement(throwNode)); - } - } - } + const bindingNames = Object.keys(path.getBindingIdentifiers()); + for (const name of bindingNames) { + path.scope.getOwnBinding(name).kind = "var"; } - updateScopeInfo(wrappedInClosure?: boolean) { - const blockScope = this.blockPath.scope; - - const parentScope = - blockScope.getFunctionParent() || blockScope.getProgramParent(); - const letRefs = this.letReferences; - - for (const key of letRefs.keys()) { - const ref = letRefs.get(key); - const binding = blockScope.getBinding(ref.name); - if (!binding) continue; - if (binding.kind === "let" || binding.kind === "const") { - binding.kind = "var"; - - if (wrappedInClosure) { - if (blockScope.hasOwnBinding(ref.name)) { - blockScope.removeBinding(ref.name); - } - } else { - blockScope.moveBindingTo(ref.name, parentScope); - } - } - } - } - - remap() { - const letRefs = this.letReferences; - const outsideLetRefs = this.outsideLetReferences; - const scope = this.scope; - const blockPathScope = this.blockPath.scope; - - // alright, so since we aren't wrapping this block in a closure - // we have to check if any of our let variables collide with - // those in upper scopes and then if they do, generate a uid - // for them and replace all references with it - - for (const key of letRefs.keys()) { - // just an Identifier node we collected in `getLetReferences` - // this is the defining identifier of a declaration - const ref = letRefs.get(key); - - // todo: could skip this if the colliding binding is in another function - if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { - const binding = scope.getOwnBinding(key); - if (binding) { - const parentBinding = scope.parent.getOwnBinding(key); - if ( - binding.kind === "hoisted" && - // @ts-expect-error todo(flow->ts) - !binding.path.node.async && - // @ts-expect-error todo(flow->ts) - !binding.path.node.generator && - (!parentBinding || isVar(parentBinding.path.parent)) && - !isStrict(binding.path.parentPath) - ) { - continue; - } - // The same identifier might have been bound separately in the block scope and - // the enclosing scope (e.g. loop or catch statement), so we should handle both - // individually - scope.rename(ref.name); - } - - if (blockPathScope.hasOwnBinding(key)) { - blockPathScope.rename(ref.name); - } - } - } - - for (const key of outsideLetRefs.keys()) { - const ref = letRefs.get(key); - // check for collisions with a for loop's init variable and the enclosing scope's bindings - // https://github.com/babel/babel/issues/8498 - if (isInLoop(this.blockPath) && blockPathScope.hasOwnBinding(key)) { - blockPathScope.rename(ref.name); - } - } - } - - wrapClosure() { - if (this.throwIfClosureRequired) { - throw this.blockPath.buildCodeFrameError( - "Compiling let/const in this block would add a closure " + - "(throwIfClosureRequired).", - ); - } - const block = this.block; - - const outsideRefs = this.outsideLetReferences; - - // remap loop heads with colliding variables - if (this.loop) { - // nb: clone outsideRefs keys since the map is modified within the loop - for (const name of Array.from(outsideRefs.keys())) { - const id = outsideRefs.get(name); - - if ( - this.scope.hasGlobal(id.name) || - this.scope.parentHasBinding(id.name) - ) { - outsideRefs.delete(id.name); - this.letReferences.delete(id.name); - - this.scope.rename(id.name); - - this.letReferences.set(id.name, id); - outsideRefs.set(id.name, id); - } - } - } - - // if we're inside of a for loop then we search to see if there are any - // `break`s, `continue`s, `return`s etc - this.has = this.checkLoop(); - - // hoist let references to retain scope - this.hoistVarDeclarations(); - - // turn outsideLetReferences into an array - const args = Array.from(outsideRefs.values(), node => t.cloneNode(node)); - const params = args.map(id => t.cloneNode(id)); - - const isSwitch = block.type === "SwitchStatement"; - - // build the closure that we're going to wrap the block with, possible wrapping switch(){} - const fn = t.functionExpression( - null, - params, - t.blockStatement(isSwitch ? [block] : block.body), - ) as t.FunctionExpression & { params: t.Identifier[] }; - - // continuation - this.addContinuations(fn); - - let call: t.CallExpression | t.YieldExpression | t.AwaitExpression = - t.callExpression(t.nullLiteral(), args); - let basePath = ".callee"; - - // handle generators - const hasYield = traverse.hasType( - fn.body, - "YieldExpression", - t.FUNCTION_TYPES, - ); - if (hasYield) { - fn.generator = true; - call = t.yieldExpression(call, true); - basePath = ".argument" + basePath; - } - - // handlers async functions - const hasAsync = traverse.hasType( - fn.body, - "AwaitExpression", - t.FUNCTION_TYPES, - ); - if (hasAsync) { - fn.async = true; - call = t.awaitExpression(call); - basePath = ".argument" + basePath; - } - - let placeholderPath; - let index; - if (this.has.hasReturn || this.has.hasBreakContinue) { - const ret = this.scope.generateUid("ret"); - - this.body.push( - t.variableDeclaration("var", [ - t.variableDeclarator(t.identifier(ret), call), - ]), - ); - placeholderPath = "declarations.0.init" + basePath; - index = this.body.length - 1; - - this.buildHas(ret); - } else { - this.body.push(t.expressionStatement(call)); - placeholderPath = "expression" + basePath; - index = this.body.length - 1; - } - - let callPath: NodePath; - // replace the current block body with the one we're going to build - if (isSwitch) { - const { parentPath, listKey, key } = this.blockPath; - - this.blockPath.replaceWithMultiple(this.body); - callPath = parentPath.get(listKey)[(key as number) + index]; - } else { - block.body = this.body; - callPath = this.blockPath.get("body")[index]; - } - - const placeholder = callPath.get(placeholderPath) as NodePath; - - let fnPath; - if (this.loop) { - const loopId = this.scope.generateUid("loop"); - const p = this.loopPath.insertBefore( - t.variableDeclaration("var", [ - t.variableDeclarator(t.identifier(loopId), fn), - ]), - ); - - placeholder.replaceWith(t.identifier(loopId)); - fnPath = p[0].get("declarations.0.init"); - } else { - placeholder.replaceWith(fn); - fnPath = placeholder; + if ( + (isInLoop(path) && !isVarInLoopHead(path)) || + dynamicTDZNames.length > 0 + ) { + for (const decl of path.node.declarations) { + // We explicitly add `void 0` to cases like + // for (;;) { let a; } + // to make sure that `a` doesn't keep the value from + // the previous iteration. + decl.init ??= path.scope.buildUndefinedNode(); } - - // Ensure "this", "arguments", and "super" continue to work in the wrapped function. - fnPath.unwrapFunctionEnvironment(); } - /** - * If any of the outer let variables are reassigned then we need to rename them in - * the closure so we can get direct access to the outer variable to continue the - * iteration with bindings based on each iteration. - * - * Reference: https://github.com/babel/babel/issues/1078 - */ - - addContinuations(fn: t.FunctionExpression & { params: t.Identifier[] }) { - const state: ContinuationVisitorState = { - reassignments: {}, - returnStatements: [], - outsideReferences: this.outsideLetReferences, - }; - - this.scope.traverse(fn, continuationVisitor, state); - - for (let i = 0; i < fn.params.length; i++) { - const param = fn.params[i]; - if (!state.reassignments[param.name]) continue; - - const paramName = param.name; - const newParamName = this.scope.generateUid(param.name); - fn.params[i] = t.identifier(newParamName); - - this.scope.rename(paramName, newParamName, fn); - - state.returnStatements.forEach(returnStatement => { - returnStatement.insertBefore( - t.expressionStatement( - t.assignmentExpression( - "=", - t.identifier(paramName), - t.identifier(newParamName), - ), - ), - ); - }); - - // assign outer reference as it's been modified internally and needs to be retained - fn.body.body.push( - t.expressionStatement( - t.assignmentExpression( - "=", - t.identifier(paramName), - t.identifier(newParamName), - ), - ), - ); - } + const blockScope = path.scope; + let varScope = blockScope.getFunctionParent(); + let isProgramScope = false; + if (!varScope) { + varScope = blockScope.getProgramParent(); + isProgramScope = true; } - getLetReferences() { - const block = this.block; - - const declarators = []; - - if (this.loop) { - // @ts-expect-error todo(flow->ts) add check for loop type - const init = this.loop.left || this.loop.init; - if (isBlockScoped(init)) { - declarators.push(init); - const names = t.getBindingIdentifiers(init); - for (const name of Object.keys(names)) { - this.outsideLetReferences.set(name, names[name]); - } - } - } - - const addDeclarationsFromChild = ( - path: NodePath, - node: t.Statement | t.SwitchCase, - ) => { + if (varScope !== blockScope) { + for (const name of bindingNames) { + let newName = name; if ( - t.isClassDeclaration(node) || - t.isFunctionDeclaration(node) || - isBlockScoped(node) + // We pass `noUids` true because, if `name` was a generated + // UID, it has been used to declare the current variable in + // a nested scope and thus we don't need to assume that it + // may be declared (but not registered yet) in an upper one. + blockScope.parent.hasBinding(name, { noUids: true }) || + blockScope.parent.hasGlobal(name) || + (isProgramScope && varScope.hasGlobal(name)) ) { - if (isBlockScoped(node)) { - convertBlockScopedToVar( - path as NodePath, - node, - block, - this.scope, - ); - } - if (node.type === "VariableDeclaration") { - for (let i = 0; i < node.declarations.length; i++) { - declarators.push(node.declarations[i]); - } - } else { - declarators.push(node); - } + newName = blockScope.generateUid(name); + blockScope.rename(name, newName); } - if (t.isLabeledStatement(node)) { - addDeclarationsFromChild(path.get("body"), node.body); - } - }; - - if (block.type === "SwitchStatement") { - const declarPaths = (this.blockPath as NodePath).get( - "cases", - ); - for (let i = 0; i < block.cases.length; i++) { - const consequents = block.cases[i].consequent; - for (let j = 0; j < consequents.length; j++) { - const declar = consequents[j]; - addDeclarationsFromChild(declarPaths[i], declar); - } - } - } else { - const declarPaths = (this.blockPath as NodePath).get("body"); - for (let i = 0; i < block.body.length; i++) { - addDeclarationsFromChild(declarPaths[i], declarPaths[i].node); - } + blockScope.moveBindingTo(newName, varScope); } - - // - for (let i = 0; i < declarators.length; i++) { - const declar = declarators[i]; - // Passing true as the third argument causes t.getBindingIdentifiers - // to return only the *outer* binding identifiers of this - // declaration, rather than (for example) mistakenly including the - // parameters of a function declaration. Fixes #4880. - const keys = t.getBindingIdentifiers(declar, false, true); - for (const key of Object.keys(keys)) { - this.letReferences.set(key, keys[key]); - } - this.hasLetReferences = true; - } - - // no let references so we can just quit - if (!this.hasLetReferences) return; - - const state: LetReferenceVisitorState = { - letReferences: this.letReferences, - closurify: false, - loopDepth: 0, - tdzEnabled: this.tdzEnabled, - addHelper: name => this.state.addHelper(name), - }; - - if (isInLoop(this.blockPath)) { - state.loopDepth++; - } - - // traverse through this block, stopping on functions and checking if they - // contain any local let references - this.blockPath.traverse(letReferenceBlockVisitor, state); - - return state.closurify; } - /** - * If we're inside of a loop then traverse it and check if it has one of - * the following node types `ReturnStatement`, `BreakStatement`, - * `ContinueStatement` and replace it with a return value that we can track - * later on. - */ - - checkLoop() { - const state: LoopVisitorState = { - hasBreakContinue: false, - ignoreLabeless: false, - inSwitchCase: false, - innerLabels: [], - hasReturn: false, - isLoop: !!this.loop, - map: new Map(), - loopIgnored: new WeakSet(), - }; - - this.blockPath.traverse(loopLabelVisitor, state); - this.blockPath.traverse(loopVisitor, state); - - return state; - } - - /** - * Hoist all let declarations in this block to before it so they retain scope - * once we wrap everything in a closure. - */ + blockScope.path.traverse(conflictingFunctionsVisitor, { + names: bindingNames, + }); - hoistVarDeclarations() { - this.blockPath.traverse(hoistVarDeclarationsVisitor, this); + for (const name of dynamicTDZNames) { + path.scope.push({ + id: t.identifier(name), + init: state.addHelper("temporalUndefined"), + }); } +} - /** - * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with - * their declarations hoisted to before the closure wrapper. - */ - - pushDeclar(node: t.VariableDeclaration): Array { - const declars = []; - const names = t.getBindingIdentifiers(node); - for (const name of Object.keys(names)) { - declars.push(t.variableDeclarator(names[name])); - } - - this.body.push(t.variableDeclaration(node.kind, declars)); - - const replace = []; - - for (let i = 0; i < node.declarations.length; i++) { - const declar = node.declarations[i]; - if (!declar.init) continue; +function isLetOrConst(kind: string): kind is "let" | "const" { + return kind === "let" || kind === "const"; +} - const expr = t.assignmentExpression( - "=", - t.cloneNode(declar.id), - t.cloneNode(declar.init), - ); - replace.push(t.inherits(expr, declar)); - } +function isInLoop(path: NodePath): boolean { + if (!path.parentPath) return false; + if (path.parentPath.isLoop()) return true; + if (path.parentPath.isFunctionParent()) return false; + return isInLoop(path.parentPath); +} - return replace; +function isBlockScoped(node: t.Node): node is t.VariableDeclaration { + if (!t.isVariableDeclaration(node)) return false; + if ( + // @ts-expect-error Fixme: document symbol properties + node[t.BLOCK_SCOPED_SYMBOL] + ) { + return true; } - buildHas(ret: string) { - const body = this.body; - const has = this.has; - - if (has.hasBreakContinue) { - for (const key of has.map.keys()) { - body.push( - t.ifStatement( - t.binaryExpression("===", t.identifier(ret), t.stringLiteral(key)), - has.map.get(key), - ), - ); - } - } - - // typeof ret === "object" - if (has.hasReturn) { - body.push( - buildRetCheck({ - RETURN: t.identifier(ret), - }), - ); - } + if (!isLetOrConst(node.kind) && node.kind !== "using") { + return false; } + + return true; } diff --git a/packages/babel-plugin-transform-block-scoping/src/loop.ts b/packages/babel-plugin-transform-block-scoping/src/loop.ts new file mode 100644 index 000000000000..05c5908e631d --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/src/loop.ts @@ -0,0 +1,334 @@ +import { template, types as t } from "@babel/core"; +import type { NodePath, Visitor, Binding } from "@babel/traverse"; + +interface LoopBodyBindingsState { + blockScoped: Binding[]; +} + +const collectLoopBodyBindingsVisitor: Visitor = { + "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); + } + } + }, +}; + +export function getLoopBodyBindings(loopPath: NodePath) { + const state: LoopBodyBindingsState = { blockScoped: [] }; + loopPath.traverse(collectLoopBodyBindingsVisitor, state); + return state.blockScoped; +} + +export function getUsageInBody(binding: Binding, loopPath: NodePath) { + // UpdateExpressions are counted both as a reference and a mutation, + // so we need to de-duplicate them. + 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 as NodePath | null; + }); + + 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 as NodePath; + }); + + return { + capturedInClosure, + hasConstantViolations: constantViolations.length > 0, + usages: references.concat(constantViolations), + }; +} + +function relativeLoopLocation(path: NodePath, loopPath: NodePath) { + 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.", + ); +} + +interface CompletionsAndVarsState { + breaksContinues: NodePath[]; + returns: NodePath[]; + labelsStack: string[]; + labellessContinueTargets: number; + labellessBreakTargets: number; + + vars: NodePath[]; + loopNode: t.Loop; +} + +const collectCompletionsAndVarsVisitor: Visitor = { + 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: NodePath, + 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); + }, +}; + +export function wrapLoopBody( + loopPath: NodePath, + captured: string[], + updatedBindingsUsages: Map[]>, +) { + const loopNode = loopPath.node; + const state: CompletionsAndVarsState = { + breaksContinues: [], + returns: [], + labelsStack: [], + labellessBreakTargets: 0, + labellessContinueTargets: 0, + vars: [], + loopNode, + }; + loopPath.traverse(collectCompletionsAndVarsVisitor, state); + + const callArgs = []; + const closureParams = []; + const updater = []; + for (const name of captured) { + callArgs.push(t.identifier(name)); + + const updatedUsage = updatedBindingsUsages.get(name); + if (!updatedUsage) { + // Not updated, re-use the same name + closureParams.push(t.identifier(name)); + continue; + } + + const innerName = loopPath.scope.generateUid(name); + 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)); + } + + const id = loopPath.scope.generateUid("loop"); + const fn = t.functionExpression( + null, + closureParams, + t.toBlock(loopNode.body), + ); + let call: t.Expression = t.callExpression(t.identifier(id), callArgs); + + const fnParent = loopPath.findParent(p => p.isFunction()); + if (fnParent) { + const { async, generator } = fnParent.node as t.Function; + fn.async = async; + fn.generator = generator; + if (generator) call = t.yieldExpression(call, true); + else if (async) call = t.awaitExpression(call); + } + + const updaterNode = + updater.length > 0 + ? t.expressionStatement(t.sequenceExpression(updater)) + : null; + if (updaterNode) fn.body.body.push(updaterNode); + + // NOTE: Calling .insertBefore on the loop path might cause the + // loop to be moved in the AST. For example, in + // if (true) for (let x of y) ... + // .insertBefore will replace the loop with a block: + // if (true) { var _loop = ...; for (let x of y) ... } + // All subsequent operations in this function on the loop node + // must not assume that loopPath still represents the loop. + // TODO: Consider using a function declaration + const [varPath] = loopPath.insertBefore( + t.variableDeclaration("var", [t.variableDeclarator(t.identifier(id), fn)]), + ) as [NodePath]; + + const bodyStmts: t.Statement[] = []; + + const varNames: string[] = []; + for (const varPath of state.vars) { + const assign = []; + for (const decl of varPath.node.declarations) { + varNames.push(...Object.keys(t.getBindingIdentifiers(decl.id))); + if (decl.init) { + assign.push(t.assignmentExpression("=", decl.id, decl.init)); + } + } + if (assign.length > 0) { + let replacement: t.Node = + assign.length === 1 ? assign[0] : t.sequenceExpression(assign); + if ( + !t.isForStatement(varPath.parent, { init: varPath.node }) && + !t.isForXStatement(varPath.parent, { left: varPath.node }) + ) { + replacement = t.expressionStatement(replacement); + } + varPath.replaceWith(replacement); + } else { + varPath.remove(); + } + } + if (varNames.length) { + bodyStmts.push( + t.variableDeclaration( + "var", + varNames.map(name => t.variableDeclarator(t.identifier(name))), + ), + ); + } + + if (state.breaksContinues.length === 0 && state.returns.length === 0) { + bodyStmts.push(t.expressionStatement(call)); + } else { + const completionId = loopPath.scope.generateUid("ret"); + bodyStmts.push( + t.variableDeclaration("var", [ + t.variableDeclarator(t.identifier(completionId), call), + ]), + ); + + const injected = new Set(); + 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.returnStatement(t.stringLiteral(name))); + if (updaterNode) path.insertBefore(t.cloneNode(updaterNode)); + + if (injected.has(name)) continue; + injected.add(name); + + bodyStmts.push( + template.statement.ast` + if ( + ${t.identifier(completionId)} === ${t.stringLiteral(name)} + ) ${node} + `, + ); + } + if (state.returns.length) { + 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 (typeof ${t.identifier(completionId)} === "object") + return ${t.identifier(completionId)}.v; + `, + ); + } + } + + loopNode.body = t.blockStatement(bodyStmts); + + return varPath; +} + +export function isVarInLoopHead(path: NodePath) { + if (t.isForStatement(path.parent)) return path.key === "init"; + if (t.isForXStatement(path.parent)) return path.key === "left"; + return false; +} + +function filterMap(list: T[], fn: (item: T) => U | null) { + const result: U[] = []; + for (const item of list) { + const mapped = fn(item); + if (mapped) result.push(mapped); + } + return result; +} diff --git a/packages/babel-plugin-transform-block-scoping/src/tdz.ts b/packages/babel-plugin-transform-block-scoping/src/tdz.ts deleted file mode 100644 index b329d4df6cd9..000000000000 --- a/packages/babel-plugin-transform-block-scoping/src/tdz.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { types as t, type PluginPass } from "@babel/core"; -import type { NodePath, Scope, Visitor } from "@babel/traverse"; - -function getTDZStatus(refPath: NodePath, bindingPath: NodePath) { - const executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); - - if (executionStatus === "before") { - return "outside"; - } else if (executionStatus === "after") { - return "inside"; - } else { - return "maybe"; - } -} - -export const skipTDZChecks = new WeakSet(); - -function buildTDZAssert( - status: "maybe" | "inside", - node: t.Identifier | t.JSXIdentifier, - state: TDZVisitorState, -) { - if (status === "maybe") { - const clone = t.cloneNode(node); - skipTDZChecks.add(clone); - return t.callExpression(state.addHelper("temporalRef"), [ - // @ts-expect-error Fixme: we may need to handle JSXIdentifier - clone, - t.stringLiteral(node.name), - ]); - } else { - return t.callExpression(state.addHelper("tdz"), [ - t.stringLiteral(node.name), - ]); - } -} - -function isReference( - node: t.Identifier | t.JSXIdentifier, - scope: Scope, - state: TDZVisitorState, -) { - const declared = state.letReferences.get(node.name); - if (!declared) return false; - - // declared node is different in this scope - return scope.getBindingIdentifier(node.name) === declared; -} - -type TDZReplacement = { status: "maybe" | "inside"; node: t.Expression }; -function getTDZReplacement( - path: NodePath, - state: TDZVisitorState, -): TDZReplacement | undefined; -function getTDZReplacement( - path: NodePath, - state: TDZVisitorState, - id: t.Identifier | t.JSXIdentifier, -): TDZReplacement | undefined; -function getTDZReplacement( - path: NodePath, - state: TDZVisitorState, - id: t.Identifier | t.JSXIdentifier = path.node as any, -): TDZReplacement | undefined { - if (!isReference(id, path.scope, state)) return; - - if (skipTDZChecks.has(id)) return; - skipTDZChecks.add(id); - - const bindingPath = path.scope.getBinding(id.name).path; - - if (bindingPath.isFunctionDeclaration()) return; - - const status = getTDZStatus(path, bindingPath); - if (status === "outside") return; - - if (status === "maybe") { - // add tdzThis to parent variable declarator so it's exploded - // @ts-expect-error todo(flow->ts): avoid mutations - bindingPath.parent._tdzThis = true; - } - - return { status, node: buildTDZAssert(status, id, state) }; -} - -export interface TDZVisitorState { - tdzEnabled: boolean; - addHelper: PluginPass["addHelper"]; - letReferences: Map; -} - -export const visitor: Visitor = { - ReferencedIdentifier(path, state) { - if (!state.tdzEnabled) return; - if (path.parentPath.isUpdateExpression()) return; - // It will be handled after transforming the loop - if (path.parentPath.isFor({ left: path.node })) return; - - const replacement = getTDZReplacement(path, state); - if (!replacement) return; - - path.replaceWith(replacement.node); - }, - - UpdateExpression(path, state) { - if (!state.tdzEnabled) return; - - const { node } = path; - if (skipTDZChecks.has(node)) return; - skipTDZChecks.add(node); - - const arg = path.get("argument"); - if (!arg.isIdentifier()) return; - - const replacement = getTDZReplacement(path, state, arg.node); - if (!replacement) return; - - if (replacement.status === "maybe") { - path.insertBefore(replacement.node); - } else { - path.replaceWith(replacement.node); - } - }, - - AssignmentExpression(path, state) { - if (!state.tdzEnabled) return; - - const { node } = path; - if (skipTDZChecks.has(node)) return; - skipTDZChecks.add(node); - - const nodes = []; - const ids = path.getBindingIdentifiers(); - - for (const name of Object.keys(ids)) { - const replacement = getTDZReplacement(path, state, ids[name]); - if (replacement) { - nodes.push(t.expressionStatement(replacement.node)); - if (replacement.status === "inside") break; - } - } - - if (nodes.length > 0) path.insertBefore(nodes); - }, -}; diff --git a/packages/babel-plugin-transform-block-scoping/src/validation.ts b/packages/babel-plugin-transform-block-scoping/src/validation.ts new file mode 100644 index 000000000000..bb48efa8a7eb --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/src/validation.ts @@ -0,0 +1,204 @@ +import { types as t, type PluginPass } from "@babel/core"; +import type { Binding, NodePath } from "@babel/traverse"; + +export function validateUsage( + path: NodePath, + state: PluginPass, + tdzEnabled: boolean, +) { + const dynamicTDZNames = []; + + for (const name of Object.keys(path.getBindingIdentifiers())) { + const binding = path.scope.getBinding(name); + if (tdzEnabled) { + if (injectTDZChecks(binding, state)) dynamicTDZNames.push(name); + } + if (path.node.kind === "const") { + disallowConstantViolations(name, binding, state); + } + } + + return dynamicTDZNames; +} + +function disallowConstantViolations( + name: string, + binding: Binding, + state: PluginPass, +) { + for (const violation of binding.constantViolations) { + const readOnlyError = state.addHelper("readOnlyError"); + const throwNode = t.callExpression(readOnlyError, [t.stringLiteral(name)]); + + if (violation.isAssignmentExpression()) { + const { operator, left, right } = violation.node; + if (operator === "=") { + const exprs = [right]; + exprs.push(throwNode); + violation.replaceWith(t.sequenceExpression(exprs)); + } else if (["&&=", "||=", "??="].includes(operator)) { + violation.replaceWith( + t.logicalExpression( + // @ts-expect-error todo: give a better type to operator + operator.slice(0, -1), + left, + t.sequenceExpression([right, throwNode]), + ), + ); + } else { + violation.replaceWith( + t.sequenceExpression([ + t.binaryExpression( + // @ts-expect-error todo: give a better type to operator + operator.slice(0, -1), + left, + right, + ), + throwNode, + ]), + ); + } + } else if (violation.isUpdateExpression()) { + violation.replaceWith( + t.sequenceExpression([ + t.unaryExpression("+", violation.get("argument").node), + throwNode, + ]), + ); + } else if (violation.isForXStatement()) { + violation.ensureBlock(); + violation + .get("left") + .replaceWith( + t.variableDeclaration("var", [ + t.variableDeclarator(violation.scope.generateUidIdentifier(name)), + ]), + ); + violation.node.body.body.unshift(t.expressionStatement(throwNode)); + } + } +} + +function getTDZStatus(refPath: NodePath, bindingPath: NodePath) { + 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: "maybe" | "inside", + node: t.Identifier | t.JSXIdentifier, + state: PluginPass, +) { + if (status === "maybe") { + const clone = t.cloneNode(node); + skipTDZChecks.add(clone); + return t.callExpression(state.addHelper("temporalRef"), [ + // @ts-expect-error Fixme: we may need to handle JSXIdentifier + clone, + t.stringLiteral(node.name), + ]); + } else { + return t.callExpression(state.addHelper("tdz"), [ + t.stringLiteral(node.name), + ]); + } +} + +type TDZReplacement = { status: "maybe" | "inside"; node: t.Expression }; +function getTDZReplacement( + path: NodePath, + state: PluginPass, +): TDZReplacement | undefined; +function getTDZReplacement( + path: NodePath, + state: PluginPass, + id: t.Identifier | t.JSXIdentifier, +): TDZReplacement | undefined; +function getTDZReplacement( + path: NodePath, + state: PluginPass, + id: t.Identifier | t.JSXIdentifier = path.node as any, +): TDZReplacement | undefined { + if (skipTDZChecks.has(id)) return; + skipTDZChecks.add(id); + + const bindingPath = path.scope.getBinding(id.name).path; + + if (bindingPath.isFunctionDeclaration()) return; + + const status = getTDZStatus(path, bindingPath); + if (status === "outside") return; + + if (status === "maybe") { + // add tdzThis to parent variable declarator so it's exploded + // @ts-expect-error todo(flow->ts): avoid mutations + bindingPath.parent._tdzThis = true; + } + + return { status, node: buildTDZAssert(status, id, state) }; +} + +function injectTDZChecks(binding: Binding, state: PluginPass) { + 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()) { + // arg is an identifier referencing the current binding + const arg = path.get("argument") as NodePath; + + 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(t.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 as NodePath[]) { + if (path.parentPath.isUpdateExpression()) continue; + // It will be handled after transforming the loop + 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; +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async-generator/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async-generator/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async-generator/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async-generator/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async-generator/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async-generator/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async-generator/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async-generator/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/options.json b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/options.json similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/options.json rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/options.json diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-async/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-async/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-const/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-const/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-const/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-const/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-const/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-const/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-const/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-const/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-let/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-let/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-let/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-let/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-let/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-let/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-let/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-let/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-var/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-var/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-var/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-var/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-var/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-var/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-collision-var/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-collision-var/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/options.json b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/options.json similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/options.json rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/options.json diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/output.js similarity index 52% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/output.js index 890482ff355d..e28b19cdd0d0 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-generator/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-generator/output.js @@ -1,14 +1,12 @@ if (true) { var _run = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", true); - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.abrupt("return", true); + case 1: + case "end": + return _context.stop(); } }, _callee); }); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/exec.js new file mode 100644 index 000000000000..b7308d71d5a0 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/exec.js @@ -0,0 +1,17 @@ +class A { + m() { + if (true) { + function f() { + return true; + } + } + + function g() { + return f(); + } + + return g(); + } +} + +expect(new A().m).toThrow(ReferenceError); \ No newline at end of file diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/input.js new file mode 100644 index 000000000000..b7308d71d5a0 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/input.js @@ -0,0 +1,17 @@ +class A { + m() { + if (true) { + function f() { + return true; + } + } + + function g() { + return f(); + } + + return g(); + } +} + +expect(new A().m).toThrow(ReferenceError); \ No newline at end of file diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/output.js new file mode 100644 index 000000000000..5e870864f2b0 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-class/output.js @@ -0,0 +1,14 @@ +class A { + m() { + if (true) { + var _f = function () { + return true; + }; + } + function g() { + return f(); + } + return g(); + } +} +expect(new A().m).toThrow(ReferenceError); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/input.js new file mode 100644 index 000000000000..04519fd7a1ee --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/input.js @@ -0,0 +1,11 @@ +const m = module { + if (true) { + function f() { + return true; + } + } + + function g() { + return f(); + } +}; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/options.json b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/options.json new file mode 100644 index 000000000000..19328f031d2e --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/options.json @@ -0,0 +1,7 @@ +{ + "plugins": [ + "transform-block-scoping", + "transform-block-scoped-functions", + "syntax-module-blocks" + ] +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/output.js new file mode 100644 index 000000000000..b583fee7d2fc --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-in-module-expression/output.js @@ -0,0 +1,10 @@ +var m = module { + if (true) { + var _f = function () { + return true; + }; + } + function g() { + return f(); + } +}; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-module/input.mjs b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-module/input.mjs similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-module/input.mjs rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-module/input.mjs diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-module/output.mjs b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-module/output.mjs similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-module/output.mjs rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3-module/output.mjs diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3/input.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046/input.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3/input.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3/output.js similarity index 100% rename from packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046/output.js rename to packages/babel-plugin-transform-block-scoping/test/fixtures/general/annex-B_3_3/output.js diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/input.js new file mode 100644 index 000000000000..d0d3db172019 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/input.js @@ -0,0 +1,15 @@ +{ a; } +{ let a; } + +(function () { + { b; } + { let b; } +})(); + +{ c = 0; } +{ let c; } + +(function () { + { d = 0; } + { let d; } +}) \ No newline at end of file diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/output.js new file mode 100644 index 000000000000..eb2ad37b81c8 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-global/output.js @@ -0,0 +1,28 @@ +{ + a; +} +{ + var _a; +} +(function () { + { + b; + } + { + var _b; + } +})(); +{ + c = 0; +} +{ + var _c; +} +(function () { + { + d = 0; + } + { + var _d; + } +}); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/exec.js new file mode 100644 index 000000000000..4d9f382acffc --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/exec.js @@ -0,0 +1,10 @@ +let a = 1; + +function f() { + let res; + { res = a; } + { let a = 2; } + return res; +} + +expect(f()).toBe(1); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/input.js new file mode 100644 index 000000000000..26e62d470aa7 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/input.js @@ -0,0 +1,6 @@ +let a = 1; + +function f() { + { console.log(a); } + { let a = 2; } +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/output.js new file mode 100644 index 000000000000..c61338dfd325 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/block-not-shadow-outer-variable/output.js @@ -0,0 +1,9 @@ +var a = 1; +function f() { + { + console.log(a); + } + { + var _a = 2; + } +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/exec.js new file mode 100644 index 000000000000..ea10cf3b383e --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/exec.js @@ -0,0 +1,36 @@ +function* a() { + do { + let x = yield "iteration"; + var fn = () => x; + } while (false); + return fn; +} + +async function b() { + do { + let x = await "iteration"; + var fn = () => x; + } while (false); + return fn; +} + +async function* c() { + do { + let x = yield "iteration"; + var fn = () => x; + } while (false); + return fn; +} + +return (async () => { + let it = a(); + expect(it.next().value).toBe("iteration"); + expect(it.next("foo").value()).toBe("foo"); + + expect((await b())()).toBe("iteration"); + + it = c(); + expect((await it.next()).value).toBe("iteration"); + expect((await it.next("foo")).value()).toBe("foo"); +})(); + diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/input.js new file mode 100644 index 000000000000..bdee9b6b638d --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/input.js @@ -0,0 +1,23 @@ +function* a() { + do { + let x = yield "iteration"; + var fn = () => x; + } while (false); + return fn; +} + +async function b() { + do { + let x = await "iteration"; + var fn = () => x; + } while (false); + return fn; +} + +async function* c() { + do { + let x = yield "iteration"; + var fn = () => x; + } while (false); + return fn; +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/options.json b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/options.json new file mode 100644 index 000000000000..cc5c84937e83 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/options.json @@ -0,0 +1,6 @@ +{ + "minNodeVersion": "10.0.0", + "parserOpts": { + "allowReturnOutsideFunction": true + } +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/output.js new file mode 100644 index 000000000000..38820e647c6f --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/closure-in-generator-or-async/output.js @@ -0,0 +1,39 @@ +function* a() { + var _loop = function* () { + var x = yield "iteration"; + fn = function () { + return x; + }; + }; + do { + var fn; + yield* _loop(); + } while (false); + return fn; +} +async function b() { + var _loop2 = async function () { + var x = await "iteration"; + fn = function () { + return x; + }; + }; + do { + var fn; + await _loop2(); + } while (false); + return fn; +} +async function* c() { + var _loop3 = async function* () { + var x = yield "iteration"; + fn = function () { + return x; + }; + }; + do { + var fn; + yield* _loop3(); + } while (false); + return fn; +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-break-continue-closure/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-break-continue-closure/output.js index 063b9a8a1a5d..4c201717d9f3 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-break-continue-closure/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-break-continue-closure/output.js @@ -1,21 +1,21 @@ -for (var a of [1]) { +var _loop = function () { switch (true) { case true: { - var _ret = function () { - var b = 1; - (function () { - return b; - }); - if (true) return "break"; - return "continue"; - }(); - if (_ret === "break") break; - if (_ret === "continue") continue; + var b = 1; + (function () { + return b; + }); + if (true) break; + return "continue"; } case false: { throw new Error("unreachable"); } } +}; +for (var a of [1]) { + var _ret = _loop(); + if (_ret === "continue") continue; } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-const-closure/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-const-closure/output.js index 1ed6687913d8..e4f9cabb7fa1 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-const-closure/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/for-const-closure/output.js @@ -1,9 +1,9 @@ -var _loop = function (i) { +var _loop = function () { var l = i; setTimeout(function () { console.log(l); }, 1); }; for (var i = 0; i < 5; i++) { - _loop(i); + _loop(); } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/hoisting/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/hoisting/output.js index faace9331c8f..389258c3f917 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/hoisting/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/hoisting/output.js @@ -14,8 +14,7 @@ var _iterator = babelHelpers.createForOfIteratorHelper(nums), try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var i = _step.value; - var x; - var f; + var x, f; _loop(i); } } catch (err) { diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/input.js deleted file mode 100644 index 26283df2072e..000000000000 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/input.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -if (true) { - function run() { - return true; - } -} - -function test() { - return run(); -} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/output.js deleted file mode 100644 index 6ad0f6e042a7..000000000000 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10046-strict/output.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; - -if (true) { - var _run = function () { - return true; - }; -} -function test() { - return run(); -} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/exec.js index 3468fe3d5f77..a5d4e1b69153 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/exec.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/exec.js @@ -34,5 +34,5 @@ return transformAsync(code, { // The body should be wrapped into closure expect(forOfPath.get("body").scope.bindings).toEqual({}); - expect(Object.keys(functionPath.scope.bindings)).toEqual(["foo", "bar", "qux", "quux"]); + expect(Object.keys(functionPath.scope.bindings)).toEqual(["foo", "qux", "quux"]); }); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/output.js index cf098a1279ed..2b5c3ad548c4 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-10339/output.js @@ -1,5 +1,5 @@ var _excluded = ["foo"]; -var _loop = function (foo, bar) { +var _loop = function (foo) { () => foo; var [qux] = bar; try {} catch (e) { @@ -11,5 +11,5 @@ for (var _ref of {}) { foo } = _ref, bar = babelHelpers.objectWithoutPropertiesLoose(_ref, _excluded); - _loop(foo, bar); + _loop(foo); } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-1051/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-1051/output.js index fb91eb6a1f5b..88b179fe5a75 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-1051/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-1051/output.js @@ -1,17 +1,18 @@ foo.func1 = function () { if (cond1) { - for (;;) { + var _loop = function () { if (cond2) { - var _ret = function () { - function func2() {} - function func3() {} - func4(function () { - func2(); - }); - return "break"; - }(); - if (_ret === "break") break; + var func2 = function () {}; + var func3 = function () {}; + func4(function () { + func2(); + }); + return "break"; } + }; + for (;;) { + var _ret = _loop(); + if (_ret === "break") break; } } }; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-4363/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-4363/output.js index 27b56c755aff..154257d21821 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-4363/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-4363/output.js @@ -1,7 +1,7 @@ function WithoutCurlyBraces() { var _this = this; if (true) { - var _loop = function (k) { + var _loop = function () { function foo() { return this; } @@ -11,14 +11,14 @@ function WithoutCurlyBraces() { console.log(_this, k); // => undefined }; for (var k in kv) { - _loop(k); + _loop(); } } } function WithCurlyBraces() { var _this2 = this; if (true) { - var _loop2 = function (k) { + var _loop2 = function () { function foo() { return this; } @@ -28,7 +28,7 @@ function WithCurlyBraces() { console.log(_this2, k); // => 777 }; for (var k in kv) { - _loop2(k); + _loop2(); } } } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-after/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-after/output.js index 7bac9d960dae..68232a272bd7 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-after/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-after/output.js @@ -1,9 +1,8 @@ -var _loop = function (_result) { - _result = otherValue; +var _loop = function (result) { + result = otherValue; fn(() => { - _result; + result; }); - result = _result; }; var _iterator = babelHelpers.createForOfIteratorHelper(results), _step; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-loose-after/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-loose-after/output.js index 9d70f34ace47..2ee87f99c1c4 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-loose-after/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-8128-for-of-loose-after/output.js @@ -1,9 +1,8 @@ -var _loop = function (_result) { - _result = otherValue; +var _loop = function (result) { + result = otherValue; fn(() => { - _result; + result; }); - result = _result; }; for (var _iterator = babelHelpers.createForOfIteratorHelperLoose(results), _step; !(_step = _iterator()).done;) { var result = _step.value; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-973/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-973/output.js index ac1f86f82d26..dc5b6312db7f 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-973/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/issue-973/output.js @@ -1,8 +1,8 @@ var arr = []; for (var i = 0; i < 10; i++) { - var _loop = function (_i) { + var _loop = function (i) { arr.push(function () { - return _i; + return i; }); }; for (var _i = 0; _i < 10; _i++) { diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/exec.js new file mode 100644 index 000000000000..fb0aa668e016 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/exec.js @@ -0,0 +1,10 @@ +let run = []; + +for (let i = 0; i < 2; i++) { + run.push(class C { + x = i; + }); +} + +expect(new run[0]().x).toBe(0); +expect(new run[1]().x).toBe(1); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/input.js new file mode 100644 index 000000000000..f6a35700916a --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/input.js @@ -0,0 +1,5 @@ +for (let i = 0; i < 2; i++) { + class C { + x = i; + } +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/options.json b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/options.json new file mode 100644 index 000000000000..22b476c4bb57 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/options.json @@ -0,0 +1,3 @@ +{ + "minNodeVersion": "12.0.0" +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/output.js new file mode 100644 index 000000000000..54716df47a75 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loop-closure-in-class/output.js @@ -0,0 +1,8 @@ +var _loop = function (i) { + class C { + x = i; + } +}; +for (var i = 0; i < 2; i++) { + _loop(i); +} diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loops-and-no-loops/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loops-and-no-loops/output.js index 93ecbcf3debb..27e677a0f297 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loops-and-no-loops/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/loops-and-no-loops/output.js @@ -11,15 +11,16 @@ function foo() { function bar() { var x = 5; console.log(x); - for (var i = 0; i < 7; i++) { + var _loop = function () { { - (function () { - var x = i; - setTimeout(function () { - return x; - }, 0); - })(); + var _x2 = i; + setTimeout(function () { + return _x2; + }, 0); } + }; + for (var i = 0; i < 7; i++) { + _loop(); } } function baz() { diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/superswitch/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/superswitch/output.js index a77c5e60fba0..6cd4d3beb30f 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/superswitch/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/superswitch/output.js @@ -1,24 +1,24 @@ function foo() { - while (true) { + var _loop = function () { switch (2) { case 0: { - var _ret = function () { - if (true) { - return { - v: void 0 - }; - } - var stuff = new Map(); - var data = 0; - stuff.forEach(function () { - var d = data; - }); - return "break"; - }(); - if (_ret === "break") break; - if (typeof _ret === "object") return _ret.v; + if (true) { + return { + v: void 0 + }; + } + var stuff = new Map(); + var data = 0; + stuff.forEach(function () { + var d = data; + }); + break; } } + }; + while (true) { + var _ret = _loop(); + if (typeof _ret === "object") return _ret.v; } } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/switch-callbacks/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/switch-callbacks/output.js index 8fb934fddc0d..fc0ec97c6104 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/switch-callbacks/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/switch-callbacks/output.js @@ -1,16 +1,17 @@ function fn() { + var _loop = function () { + switch (true) { + default: + var foo = 4; + if (true) { + var bar = function () { + return foo; + }; + console.log(bar()); + } + } + }; while (true) { - (function () { - switch (true) { - default: - var foo = 4; - if (true) { - var bar = function () { - return foo; - }; - console.log(bar()); - } - } - })(); + _loop(); } } diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/wrap-closure-shadow-variables/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/wrap-closure-shadow-variables/output.js index 479f6fb6bed0..54c2002a1bc3 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/general/wrap-closure-shadow-variables/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/general/wrap-closure-shadow-variables/output.js @@ -1,7 +1,7 @@ var a = 1; -var _loop = function (_a) { +var _loop = function (a) { items.forEach(function (item) { - return _a; + return a; }); }; for (var _a = 1; _a < 100; _a++) { diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/exec.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/exec.js new file mode 100644 index 000000000000..a6e62ae4a275 --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/exec.js @@ -0,0 +1,33 @@ +function callNow(f) { + f(); +} + +function callLater(f) { + return () => f(); +} + +expect(() => { + const x = 0; + x = 1; +}).toThrow(TypeError); + +expect(() => { + x = 1; + const x = 0; +}).toThrow(ReferenceError); + +expect(() => { + callNow(() => { + x = 1; + }); + const x = 0; +}).toThrow(ReferenceError); + + +expect(() => { + const call = callLater(() => { + x = 1; + }); + const x = 0; + call(); +}).toThrow(TypeError); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/input.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/input.js new file mode 100644 index 000000000000..7fe459dc020c --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/input.js @@ -0,0 +1,6 @@ +maybeCallLater(function () { + x = 2; +}); + +const x = 0; +x = 1; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/output.js new file mode 100644 index 000000000000..8e2d0677006e --- /dev/null +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/const-readonly/output.js @@ -0,0 +1,7 @@ +var x = babelHelpers.temporalUndefined; +maybeCallLater(function () { + babelHelpers.temporalRef(x, "x"); + 2, babelHelpers.readOnlyError("x"); +}); +var x = 0; +1, babelHelpers.readOnlyError("x"); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/exported-fn/output.mjs b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/exported-fn/output.mjs index 91973e43b39c..ab96117494f7 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/exported-fn/output.mjs +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/exported-fn/output.mjs @@ -4,7 +4,7 @@ import { foo } from "somewhere"; // foo might call "bar" foo(); babelHelpers.tdz("a"); -a = void 0; +var a = void 0; a; export function bar() { return babelHelpers.temporalRef(a, "a"); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-real-after/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-real-after/output.js index 6a3b66e61ef3..b1aab47c351f 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-real-after/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-real-after/output.js @@ -3,5 +3,5 @@ function f() { babelHelpers.temporalRef(x, "x"); } Math.random() === 2 && f(); -x = void 0; +var x = void 0; f(); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-value-assign/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-value-assign/output.js index 11ac40452ab5..18d7caef760f 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-value-assign/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe-value-assign/output.js @@ -3,5 +3,5 @@ function f() { babelHelpers.temporalRef(x, "x"); } Math.random() === 2 && f(); -x = 3; +var x = 3; expect(x).toBe(3); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe/output.js index 91f0962b3797..086875906670 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-maybe/output.js @@ -3,5 +3,4 @@ function f() { babelHelpers.temporalRef(x, "x"); } Math.random() && f(); -x = void 0; -void 0; +var x = void 0; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-nested-function/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-nested-function/output.js index 60691c5a669a..a06382502536 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-nested-function/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-nested-function/output.js @@ -5,5 +5,4 @@ function f() { }; } f(); -x = void 0; -void 0; +var x = void 0; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-recursive-reference/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-recursive-reference/output.js index 9b46db08d8de..e7b9c478f45f 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-recursive-reference/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-call-recursive-reference/output.js @@ -6,5 +6,5 @@ function f(i) { }; } var g = f(1); -x = void 0; +var x = void 0; g(); diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-ref/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-ref/output.js index 53af740eaa8a..8ee73c67a45e 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-ref/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/function-ref/output.js @@ -3,5 +3,4 @@ function f() { babelHelpers.temporalRef(x, "x"); } maybeCall(f); -x = void 0; -void 0; +var x = void 0; diff --git a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/update-expression/output.js b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/update-expression/output.js index 8e99961fe95c..e9b7407330c0 100644 --- a/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/update-expression/output.js +++ b/packages/babel-plugin-transform-block-scoping/test/fixtures/tdz/update-expression/output.js @@ -11,5 +11,4 @@ babelHelpers.tdz("x"); babelHelpers.tdz("x"); babelHelpers.tdz("x").p++; ++babelHelpers.tdz("x").p; -x = void 0; -void 0; +var x = void 0; diff --git a/packages/babel-plugin-transform-classes/test/fixtures/regression/T6755/output.js b/packages/babel-plugin-transform-classes/test/fixtures/regression/T6755/output.js index 599d404f1c58..7f1f222d4d22 100644 --- a/packages/babel-plugin-transform-classes/test/fixtures/regression/T6755/output.js +++ b/packages/babel-plugin-transform-classes/test/fixtures/regression/T6755/output.js @@ -6,15 +6,13 @@ var Example = /*#__PURE__*/function () { _proto.test1 = /*#__PURE__*/function () { var _test = babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return Promise.resolve(2); - case 2: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return Promise.resolve(2); + case 2: + case "end": + return _context.stop(); } }, _callee); })); @@ -25,15 +23,13 @@ var Example = /*#__PURE__*/function () { }(); _proto.test2 = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function test2() { return babelHelpers.regeneratorRuntime().wrap(function test2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return 3; - case 2: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return 3; + case 2: + case "end": + return _context2.stop(); } }, test2); }); diff --git a/packages/babel-plugin-transform-classes/test/fixtures/spec/name-collisions-with-class-ref-in-constructor/output.js b/packages/babel-plugin-transform-classes/test/fixtures/spec/name-collisions-with-class-ref-in-constructor/output.js index 9fa611a9300b..c021e36ca25a 100644 --- a/packages/babel-plugin-transform-classes/test/fixtures/spec/name-collisions-with-class-ref-in-constructor/output.js +++ b/packages/babel-plugin-transform-classes/test/fixtures/spec/name-collisions-with-class-ref-in-constructor/output.js @@ -20,7 +20,7 @@ var Foo = /*#__PURE__*/function (_Base) { babelHelpers.classCallCheck(this, Foo); _this = _super.call(this); if (true) { - var _Foo2; + var _Foo; babelHelpers.get((_thisSuper = babelHelpers.assertThisInitialized(_this), babelHelpers.getPrototypeOf(Foo.prototype)), "method", _thisSuper).call(_thisSuper); } return _this; diff --git a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/destructuring-empty-in-for/output.js b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/destructuring-empty-in-for/output.js index f75ff1967a0d..43e3ae6b2617 100644 --- a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/destructuring-empty-in-for/output.js +++ b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/destructuring-empty-in-for/output.js @@ -1,19 +1,7 @@ -for (var x in y) { - for (;;) { - babelHelpers.objectDestructuringEmpty(x); - } -} -for (var _x in y) { - for (babelHelpers.objectDestructuringEmpty(_x);;) { - ; - } -} -for (var _x2 in y) { - for (; _x3 = _x2, babelHelpers.objectDestructuringEmpty(_x3), _x3; _x4 = _x2, babelHelpers.objectDestructuringEmpty(_x4), _x4) { - var _x3, _x4; - babelHelpers.objectDestructuringEmpty(_x2); - } -} -for (babelHelpers.objectDestructuringEmpty(0); 0;) { - ; +for (var x in y) for (;;) babelHelpers.objectDestructuringEmpty(x); +for (var _x in y) for (babelHelpers.objectDestructuringEmpty(_x);;); +for (var _x2 in y) for (; _x3 = _x2, babelHelpers.objectDestructuringEmpty(_x3), _x3; _x4 = _x2, babelHelpers.objectDestructuringEmpty(_x4), _x4) { + var _x3, _x4; + babelHelpers.objectDestructuringEmpty(_x2); } +for (babelHelpers.objectDestructuringEmpty(0); 0;); diff --git a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/empty-array-pattern/output.js b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/empty-array-pattern/output.js index 9f8606f40f82..ee148ec32f10 100644 --- a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/empty-array-pattern/output.js +++ b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/empty-array-pattern/output.js @@ -13,14 +13,12 @@ var _foo = "foo", _foo2 = babelHelpers.slicedToArray(_foo, 0); var _ref7 = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - throw new Error("Should not throw"); - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + throw new Error("Should not throw"); + case 1: + case "end": + return _context.stop(); } }, _callee); })(), @@ -36,12 +34,10 @@ var _Symbol$iterator5 = { var _Symbol$iterator7 = { [Symbol.iterator]: /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee2() { return babelHelpers.regeneratorRuntime().async(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + case "end": + return _context2.stop(); } }, _callee2, null, null, Promise); }) @@ -72,12 +68,10 @@ var _Symbol$iterator11 = { var _Symbol$iterator13 = { [Symbol.iterator]: () => /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee3() { return babelHelpers.regeneratorRuntime().async(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - case "end": - return _context3.stop(); - } + while (1) switch (_context3.prev = _context3.next) { + case 0: + case "end": + return _context3.stop(); } }, _callee3, null, null, Promise); }) diff --git a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/parameters/output.js b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/parameters/output.js index 6ca6f3d9b786..05b134bfae61 100644 --- a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/parameters/output.js +++ b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/parameters/output.js @@ -1,12 +1,12 @@ function somethingAdvanced(_ref, p2, p3) { - var _ref$topLeft = _ref.topLeft; - _ref$topLeft = _ref$topLeft === void 0 ? {} : _ref$topLeft; - var x1 = _ref$topLeft.x, - y1 = _ref$topLeft.y, - _ref$bottomRight = _ref.bottomRight; - _ref$bottomRight = _ref$bottomRight === void 0 ? {} : _ref$bottomRight; - var x2 = _ref$bottomRight.x, - y2 = _ref$bottomRight.y; + var _ref$topLeft = _ref.topLeft, + _ref$topLeft2 = _ref$topLeft === void 0 ? {} : _ref$topLeft, + x1 = _ref$topLeft2.x, + y1 = _ref$topLeft2.y, + _ref$bottomRight = _ref.bottomRight, + _ref$bottomRight2 = _ref$bottomRight === void 0 ? {} : _ref$bottomRight, + x2 = _ref$bottomRight2.x, + y2 = _ref$bottomRight2.y; } function unpackObject(_ref2) { var title = _ref2.title, diff --git a/packages/babel-plugin-transform-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/output.js b/packages/babel-plugin-transform-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/output.js index 3eea2ab3acb1..322079b52d31 100644 --- a/packages/babel-plugin-transform-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/output.js +++ b/packages/babel-plugin-transform-parameters/test/fixtures/parameters/rest-member-expression-deoptimisation/output.js @@ -122,7 +122,6 @@ function forOf() { try { for (_iterator.s(); !(_step = _iterator.n()).done;) { rest[0] = _step.value; - ; } } catch (err) { _iterator.e(err); diff --git a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/4219/output.js b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/4219/output.js index 82761a0b4dca..8be6fac70480 100644 --- a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/4219/output.js +++ b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/4219/output.js @@ -2,14 +2,12 @@ function test(fn) { return /*#__PURE__*/babelHelpers.asyncToGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { var _args = arguments; return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - return _context.abrupt("return", fn.apply(void 0, _args)); - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.abrupt("return", fn.apply(void 0, _args)); + case 1: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/6733/output.js b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/6733/output.js index b210d94c1019..b43c97b1c0b7 100644 --- a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/6733/output.js +++ b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/6733/output.js @@ -8,18 +8,16 @@ var _marked = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(_callee); function _callee() { var x; return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return 5; - case 2: - x = _context.sent; - return _context.abrupt("return", 5); - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return 5; + case 2: + x = _context.sent; + return _context.abrupt("return", 5); + case 4: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/T7041/output.js b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/T7041/output.js index e97ea9dd7ab2..f5ab7caad83d 100644 --- a/packages/babel-plugin-transform-regenerator/test/fixtures/regression/T7041/output.js +++ b/packages/babel-plugin-transform-regenerator/test/fixtures/regression/T7041/output.js @@ -2,12 +2,10 @@ var _marked = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(fn); Object.keys({}); function fn() { return babelHelpers.regeneratorRuntime().wrap(function fn$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options-babel-7/output.js b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options-babel-7/output.js index 27d61826ce9a..d8825266feab 100644 --- a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options-babel-7/output.js +++ b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options-babel-7/output.js @@ -5,14 +5,12 @@ function test() { function _test() { _test = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - console.log('test'); - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + console.log('test'); + case 1: + case "end": + return _context.stop(); } }, _callee); })); @@ -24,19 +22,17 @@ function main() { function _main() { _main = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.t0 = console; - _context2.next = 3; - return test(); - case 3: - _context2.t1 = _context2.sent; - _context2.t0.log.call(_context2.t0, _context2.t1); - case 5: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.t0 = console; + _context2.next = 3; + return test(); + case 3: + _context2.t1 = _context2.sent; + _context2.t0.log.call(_context2.t0, _context2.t1); + case 5: + case "end": + return _context2.stop(); } }, _callee2); })); diff --git a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options/output.js b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options/output.js index 910667bdfa60..df3c1672da1d 100644 --- a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options/output.js +++ b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/complex-options/output.js @@ -5,14 +5,12 @@ function test() { function _test() { _test = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - console.log('test'); - case 1: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + console.log('test'); + case 1: + case "end": + return _context.stop(); } }, _callee); })); @@ -24,19 +22,17 @@ function main() { function _main() { _main = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.t0 = console; - _context2.next = 3; - return test(); - case 3: - _context2.t1 = _context2.sent; - _context2.t0.log.call(_context2.t0, _context2.t1); - case 5: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.t0 = console; + _context2.next = 3; + return test(); + case 3: + _context2.t1 = _context2.sent; + _context2.t0.log.call(_context2.t0, _context2.t1); + case 5: + case "end": + return _context2.stop(); } }, _callee2); })); diff --git a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-proposals/output.js b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-proposals/output.js index f987908caebe..0a975dcae4f5 100644 --- a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-proposals/output.js +++ b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-proposals/output.js @@ -3,18 +3,16 @@ var _marked = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(makeIterator); _mapInstanceProperty(Array); function makeIterator() { return babelHelpers.regeneratorRuntime().wrap(function makeIterator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return 1; - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return 1; + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-stable/output.js b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-stable/output.js index 600e85fadc7c..68f24aa7f7c4 100644 --- a/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-stable/output.js +++ b/packages/babel-plugin-transform-runtime/test/fixtures/absoluteRuntime/true-corejs3-stable/output.js @@ -3,18 +3,16 @@ var _marked = /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(makeIterator); _mapInstanceProperty(Array); function makeIterator() { return babelHelpers.regeneratorRuntime().wrap(function makeIterator$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return 1; - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return 1; + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-10-no-bugfixes/output.js b/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-10-no-bugfixes/output.js index 68be3013aef3..fb68d02b4534 100644 --- a/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-10-no-bugfixes/output.js +++ b/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-10-no-bugfixes/output.js @@ -1,7 +1,5 @@ e => { - for (var _e of []) { - ; - } + for (var _e of []); }; { var a; diff --git a/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-9/output.js b/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-9/output.js index 68be3013aef3..fb68d02b4534 100644 --- a/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-9/output.js +++ b/packages/babel-preset-env/test/fixtures/bugfixes/safari-block-scoping-safari-9/output.js @@ -1,7 +1,5 @@ e => { - for (var _e of []) { - ; - } + for (var _e of []); }; { var a; diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/entry-shippedProposals/output.js b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/entry-shippedProposals/output.js index 10a3de361f7e..9ac110459603 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/entry-shippedProposals/output.js +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/entry-shippedProposals/output.js @@ -167,18 +167,16 @@ function agf() { function _agf() { _agf = babelHelpers.wrapAsyncGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return babelHelpers.awaitAsyncGenerator(1); - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return babelHelpers.awaitAsyncGenerator(1); + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-destructuring-for-x/output.mjs b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-destructuring-for-x/output.mjs index ada758b4d766..db886903c3eb 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-destructuring-for-x/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-destructuring-for-x/output.mjs @@ -2,6 +2,4 @@ import "core-js/modules/es6.string.iterator.js"; import "core-js/modules/es6.object.to-string.js"; import "core-js/modules/es6.array.iterator.js"; import "core-js/modules/web.dom.iterable.js"; -for (var [a, b] in c) { - ; -} +for (var [a, b] in c); diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-for-of/output.mjs b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-for-of/output.mjs index 9559a2bdb051..ffa9501cb023 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-for-of/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-for-of/output.mjs @@ -2,6 +2,4 @@ import "core-js/modules/es6.string.iterator.js"; import "core-js/modules/es6.object.to-string.js"; import "core-js/modules/es6.array.iterator.js"; import "core-js/modules/web.dom.iterable.js"; -for (var a of b) { - ; -} +for (var a of b); diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-async/output.mjs b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-async/output.mjs index 575205486c5d..4a8fe1d0b8f2 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-async/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-async/output.mjs @@ -1,5 +1,5 @@ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } import "core-js/modules/es6.object.to-string.js"; import "core-js/modules/es6.promise.js"; import "core-js/modules/es6.object.define-property.js"; @@ -22,12 +22,10 @@ function a() { function _a() { _a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-generator/output.mjs b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-generator/output.mjs index 42b99541f24e..acfa897185b3 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-generator/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-regenerator-used-generator/output.mjs @@ -13,16 +13,14 @@ import "core-js/modules/es6.function.name.js"; import "core-js/modules/es6.object.set-prototype-of.js"; import "core-js/modules/es6.promise.js"; import "core-js/modules/es6.array.slice.js"; -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } var _marked = /*#__PURE__*/_regeneratorRuntime().mark(a); function a() { return _regeneratorRuntime().wrap(function a$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-shippedProposals/output.js b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-shippedProposals/output.js index a21b792e51b6..c74a179679b1 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-shippedProposals/output.js +++ b/packages/babel-preset-env/test/fixtures/corejs2-babel-7/usage-shippedProposals/output.js @@ -22,7 +22,7 @@ require("core-js/modules/es6.object.to-string.js"); require("core-js/modules/es6.promise.js"); require("core-js/modules/es6.symbol.js"); require("core-js/modules/es7.symbol.async-iterator.js"); -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } @@ -54,18 +54,16 @@ function agf() { function _agf() { _agf = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return _awaitAsyncGenerator(1); - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _awaitAsyncGenerator(1); + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs2/entry-shippedProposals/output.js b/packages/babel-preset-env/test/fixtures/corejs2/entry-shippedProposals/output.js index 10a3de361f7e..9ac110459603 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2/entry-shippedProposals/output.js +++ b/packages/babel-preset-env/test/fixtures/corejs2/entry-shippedProposals/output.js @@ -167,18 +167,16 @@ function agf() { function _agf() { _agf = babelHelpers.wrapAsyncGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return babelHelpers.awaitAsyncGenerator(1); - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return babelHelpers.awaitAsyncGenerator(1); + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs2/usage-shippedProposals/output.js b/packages/babel-preset-env/test/fixtures/corejs2/usage-shippedProposals/output.js index a21b792e51b6..c74a179679b1 100644 --- a/packages/babel-preset-env/test/fixtures/corejs2/usage-shippedProposals/output.js +++ b/packages/babel-preset-env/test/fixtures/corejs2/usage-shippedProposals/output.js @@ -22,7 +22,7 @@ require("core-js/modules/es6.object.to-string.js"); require("core-js/modules/es6.promise.js"); require("core-js/modules/es6.symbol.js"); require("core-js/modules/es7.symbol.async-iterator.js"); -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } @@ -54,18 +54,16 @@ function agf() { function _agf() { _agf = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return _awaitAsyncGenerator(1); - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return _awaitAsyncGenerator(1); + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-destructuring-for-x/output.mjs b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-destructuring-for-x/output.mjs index cdd64287d00b..fdaf49bd8ca2 100644 --- a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-destructuring-for-x/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-destructuring-for-x/output.mjs @@ -1,6 +1,4 @@ import "core-js/modules/es.string.iterator.js"; import "core-js/modules/es.array.iterator.js"; import "core-js/modules/web.dom-collections.iterator.js"; -for (var [a, b] in c) { - ; -} +for (var [a, b] in c); diff --git a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-for-of/output.mjs b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-for-of/output.mjs index 66763d8a5ae5..e6d9893c281a 100644 --- a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-for-of/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-for-of/output.mjs @@ -1,6 +1,4 @@ import "core-js/modules/es.string.iterator.js"; import "core-js/modules/es.array.iterator.js"; import "core-js/modules/web.dom-collections.iterator.js"; -for (var a of b) { - ; -} +for (var a of b); diff --git a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-async/output.mjs b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-async/output.mjs index 083b67e132fe..25433d6353b5 100644 --- a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-async/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-async/output.mjs @@ -1,5 +1,5 @@ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } import "core-js/modules/es.object.to-string.js"; import "core-js/modules/es.promise.js"; import "core-js/modules/es.object.define-property.js"; @@ -29,12 +29,10 @@ function a() { function _a() { _a = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-generator/output.mjs b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-generator/output.mjs index 886a7be92258..53acc6fe56a2 100644 --- a/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-generator/output.mjs +++ b/packages/babel-preset-env/test/fixtures/corejs3-babel-7/usage-regenerator-used-generator/output.mjs @@ -20,16 +20,14 @@ import "core-js/modules/es.object.set-prototype-of.js"; import "core-js/modules/es.promise.js"; import "core-js/modules/es.array.reverse.js"; import "core-js/modules/es.array.slice.js"; -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } var _marked = /*#__PURE__*/_regeneratorRuntime().mark(a); function a() { return _regeneratorRuntime().wrap(function a$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _marked); } diff --git a/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15012/output.js b/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15012/output.js index c273d4c8d716..ec8d0421b6e9 100644 --- a/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15012/output.js +++ b/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15012/output.js @@ -2,12 +2,10 @@ function f(_ref) { var _ref2 = babelHelpers.slicedToArray(_ref, 0); return /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + case "end": + return _context.stop(); } }, _callee); })(); @@ -16,12 +14,10 @@ function g() { var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : fn(); return /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee2() { return babelHelpers.regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + case "end": + return _context2.stop(); } }, _callee2); })(); diff --git a/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15170/output.js b/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15170/output.js index 5097fb4f42f9..eb549fd35d17 100644 --- a/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15170/output.js +++ b/packages/babel-preset-env/test/fixtures/plugins-integration/issue-15170/output.js @@ -5,16 +5,14 @@ x = /*#__PURE__*/function () { function x(_x2) { var _args = arguments; return babelHelpers.regeneratorRuntime().wrap(function x$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - return _context.delegateYield(_x.apply(this, _args), "t0", 1); - case 1: - return _context.abrupt("return", _context.t0); - case 2: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.delegateYield(_x.apply(this, _args), "t0", 1); + case 1: + return _context.abrupt("return", _context.t0); + case 2: + case "end": + return _context.stop(); } }, _marked, this); } @@ -24,15 +22,13 @@ x = /*#__PURE__*/function () { return x; }( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee(x) { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - babelHelpers.newArrowCheck(this, _this); - return _context2.abrupt("return", 0); - case 2: - case "end": - return _context2.stop(); - } + while (1) switch (_context2.prev = _context2.next) { + case 0: + babelHelpers.newArrowCheck(this, _this); + return _context2.abrupt("return", 0); + case 2: + case "end": + return _context2.stop(); } }, _callee, this); })); diff --git a/packages/babel-preset-env/test/fixtures/preset-options-babel-7/shippedProposals/output.js b/packages/babel-preset-env/test/fixtures/preset-options-babel-7/shippedProposals/output.js index a009005f3712..630a7a74f5ae 100644 --- a/packages/babel-preset-env/test/fixtures/preset-options-babel-7/shippedProposals/output.js +++ b/packages/babel-preset-env/test/fixtures/preset-options-babel-7/shippedProposals/output.js @@ -17,18 +17,16 @@ function agf() { function _agf() { _agf = babelHelpers.wrapAsyncGenerator( /*#__PURE__*/babelHelpers.regeneratorRuntime().mark(function _callee() { return babelHelpers.regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return babelHelpers.awaitAsyncGenerator(1); - case 2: - _context.next = 4; - return 2; - case 4: - case "end": - return _context.stop(); - } + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return babelHelpers.awaitAsyncGenerator(1); + case 2: + _context.next = 4; + return 2; + case 4: + case "end": + return _context.stop(); } }, _callee); })); diff --git a/packages/babel-traverse/src/scope/index.ts b/packages/babel-traverse/src/scope/index.ts index 292eecfda496..3e96bccd3801 100644 --- a/packages/babel-traverse/src/scope/index.ts +++ b/packages/babel-traverse/src/scope/index.ts @@ -1235,18 +1235,34 @@ export default class Scope { return !!this.getOwnBinding(name); } - hasBinding(name: string, noGlobals?: boolean) { + // By default, we consider generated UIDs as bindings. + // This is because they are almost always used to declare variables, + // and since the scope isn't always up-to-date it's better to assume that + // there is a variable with that name. The `noUids` option can be used to + // turn off this behavior, for example if you know that the generate UID + // was used to declare a variable in a different scope. + hasBinding( + name: string, + opts?: boolean | { noGlobals?: boolean; noUids?: boolean }, + ) { if (!name) return false; if (this.hasOwnBinding(name)) return true; - if (this.parentHasBinding(name, noGlobals)) return true; - if (this.hasUid(name)) return true; - if (!noGlobals && Scope.globals.includes(name)) return true; - if (!noGlobals && Scope.contextVariables.includes(name)) return true; + { + // TODO: Only accept the object form. + if (typeof opts === "boolean") opts = { noGlobals: opts }; + } + if (this.parentHasBinding(name, opts)) return true; + if (!opts?.noUids && this.hasUid(name)) return true; + if (!opts?.noGlobals && Scope.globals.includes(name)) return true; + if (!opts?.noGlobals && Scope.contextVariables.includes(name)) return true; return false; } - parentHasBinding(name: string, noGlobals?: boolean) { - return this.parent?.hasBinding(name, noGlobals); + parentHasBinding( + name: string, + opts?: { noGlobals?: boolean; noUids?: boolean }, + ) { + return this.parent?.hasBinding(name, opts); } /**