From d91a554033c8ce0ea2b2538b0e86abf5a81eac76 Mon Sep 17 00:00:00 2001 From: magic-akari Date: Mon, 25 Sep 2023 12:02:09 +0800 Subject: [PATCH] fix(es/compat): Skip function scope in `block-scoped-fns` pass (#7975) **Related issue:** - Closes: #2793 --- .../fixture/issues-2xxx/2793/input/.swcrc | 5 + .../fixture/issues-2xxx/2793/input/index.js | 34 ++ .../fixture/issues-2xxx/2793/output/index.js | 27 + .../issues-3xxx/3417/1/output/index.ts | 6 +- .../issues-6xxx/6345/1/output/index.js | 10 +- ...mberThatUsesClassTypeParameter.1.normal.js | 2 +- ...assStaticFunctionOfTheSameName.1.normal.js | 4 +- ...assStaticFunctionOfTheSameName.1.normal.js | 4 +- ...nctionUsingClassPrivateStatics.1.normal.js | 4 +- ...ExportedFunctionThatShareAName.1.normal.js | 6 +- ...ExportedFunctionThatShareAName.1.normal.js | 6 +- ...rameterAndReturnTypeAnnotation.1.normal.js | 12 +- ...TypesInParameterTypeAnnotation.1.normal.js | 12 +- ...bleTypesInReturnTypeAnnotation.1.normal.js | 12 +- ...oduleWithSameNameAndCommonRoot.1.normal.js | 8 +- ...uleWithSameNameAndCommonRoot.2.minified.js | 17 +- ...SameNameAndDifferentCommonRoot.1.normal.js | 4 +- ...ctionWithSameNameAndCommonRoot.1.normal.js | 16 +- ...ionWithSameNameAndCommonRoot.2.minified.js | 20 +- ...xportedAndNonExportedFunctions.1.normal.js | 22 +- ...ExportedLocalVarsOfTheSameName.1.normal.js | 4 +- ...ExportedLocalVarsOfTheSameName.1.normal.js | 4 +- ...SameNameAndDifferentCommonRoot.1.normal.js | 4 +- ...thTheSameNameAndSameCommonRoot.1.normal.js | 4 +- .../arrowFunctionExpressions.1.normal.js | 4 +- ...rsingAsAmbientExternalModule02.1.normal.js | 4 +- ...ntCompatWithDiscriminatedUnion.1.normal.js | 20 +- ...CompatWithDiscriminatedUnion.2.minified.js | 11 +- ...gnaturesWithOptionalParameters.1.normal.js | 20 +- ...gnmentCompatWithNumericIndexer.1.normal.js | 24 +- ...nmentCompatWithNumericIndexer2.1.normal.js | 4 +- ...nmentCompatWithNumericIndexer3.1.normal.js | 12 +- ...ignmentCompatWithStringIndexer.1.normal.js | 18 +- ...gnmentCompatWithStringIndexer2.1.normal.js | 18 +- ...gnmentCompatWithStringIndexer3.1.normal.js | 12 +- ...wFunctionCapturesArguments_es5.1.normal.js | 2 +- ...clarationCapturesArguments_es5.1.normal.js | 2 +- ...owFunctionWhenUsingArguments19.1.normal.js | 8 +- ...clarationBindingPatterns01_ES5.1.normal.js | 14 +- ...nBindingPatterns01_ES5iterable.1.normal.js | 14 +- .../enumAssignability.1.normal.js | 14 +- .../errorSuperPropertyAccess.1.normal.js | 4 +- ...peWithAnnotationAndInitializer.1.normal.js | 6 +- ...nnotationAndInvalidInitializer.1.normal.js | 16 +- .../everyTypeWithInitializer.1.normal.js | 6 +- .../exportAssignmentMergedModule.1.normal.js | 8 +- .../tsc-references/exportCodeGen.1.normal.js | 24 +- .../exportImportAlias.1.normal.js | 4 +- .../exportImportAlias.2.minified.js | 15 +- .../fixSignatureCaching.1.normal.js | 110 ++--- .../fixSignatureCaching.2.minified.js | 82 +-- .../tsc-references/forStatements.1.normal.js | 6 +- ...rStatementsMultipleInvalidDecl.1.normal.js | 6 +- ...WithGenericSignatureArguments2.1.normal.js | 68 +-- ...oadedConstructorTypedArguments.1.normal.js | 22 +- ...dedConstructorTypedArguments.2.minified.js | 12 +- ...adedConstructorTypedArguments2.1.normal.js | 22 +- ...edConstructorTypedArguments2.2.minified.js | 6 +- ...erloadedFunctionTypedArguments.1.normal.js | 22 +- ...loadedFunctionTypedArguments.2.minified.js | 28 +- ...rloadedFunctionTypedArguments2.1.normal.js | 22 +- ...oadedFunctionTypedArguments2.2.minified.js | 8 +- ...thFunctionTypedMemberArguments.1.normal.js | 34 +- .../ifDoWhileStatements.1.normal.js | 12 +- .../importStatements.1.normal.js | 6 +- .../importStatementsInterfaces.1.normal.js | 4 +- ...TypeParameterShadowingOuterOne.1.normal.js | 8 +- ...idMultipleVariableDeclarations.1.normal.js | 6 +- .../tsc-references/localTypes1.1.normal.js | 16 +- .../tsc-references/localTypes2.1.normal.js | 12 +- .../tsc-references/localTypes3.1.normal.js | 12 +- .../tsc-references/localTypes4.1.normal.js | 12 +- ...oduleWithStatementsOfEveryKind.1.normal.js | 12 +- .../nonInstantiatedModule.1.normal.js | 4 +- ...InitializersForwardReferencing.1.normal.js | 6 +- .../tsc-references/parserModule1.1.normal.js | 22 +- .../parserModule1.2.minified.js | 21 +- .../parserRealSource1.1.normal.js | 126 ++--- .../parserRealSource1.2.minified.js | 19 +- .../parserRealSource12.1.normal.js | 208 ++++---- .../parserRealSource12.2.minified.js | 143 +++--- .../parserRealSource14.1.normal.js | 204 ++++---- .../parserRealSource14.2.minified.js | 389 ++++++++------- .../parserRealSource2.1.normal.js | 44 +- .../parserRealSource5.1.normal.js | 22 +- .../parserRealSource6.1.normal.js | 166 +++---- .../parserRealSource6.2.minified.js | 165 ++++--- .../parserRealSource8.1.normal.js | 134 ++--- .../parserRealSource8.2.minified.js | 224 +++++---- ...eTypesUsedAsFunctionParameters.1.normal.js | 8 +- .../restTuplesFromContextualTypes.1.normal.js | 2 +- .../spellingUncheckedJS.1.normal.js | 4 +- .../subtypesOfTypeParameter.1.normal.js | 16 +- ...fTypeParameterWithConstraints2.1.normal.js | 8 +- .../switchStatements.1.normal.js | 4 +- .../thisTypeAndConstraints.1.normal.js | 4 +- .../tsc-references/thisTypeErrors.1.normal.js | 4 +- .../throwStatements.1.normal.js | 6 +- .../typeFromPropertyAssignment20.1.normal.js | 4 +- .../typeFromPropertyAssignment29.1.normal.js | 8 +- ...typeFromPropertyAssignment29.2.minified.js | 11 +- .../typeFromPropertyAssignment36.1.normal.js | 26 +- ...typeFromPropertyAssignment36.2.minified.js | 9 +- .../typeGuardsDefeat.1.normal.js | 4 +- .../typeGuardsInFunction.1.normal.js | 6 +- ...typeOfThisInFunctionExpression.1.normal.js | 4 +- ...UsedAsTypeParameterConstraint2.1.normal.js | 16 +- ...UsedAsTypeParameterConstraint4.1.normal.js | 8 +- ...metersAreIdenticalToThemselves.1.normal.js | 4 +- ...rametersAvailableInNestedScope.1.normal.js | 4 +- ...ametersAvailableInNestedScope2.1.normal.js | 4 +- ...ametersAvailableInNestedScope3.1.normal.js | 12 +- ...rappedAndRecursiveConstraints3.1.normal.js | 4 +- ...rappedAndRecursiveConstraints4.1.normal.js | 4 +- .../full/d3-time-format/1/output/index.js | 125 ++--- .../full/firebase/dist/1/output/index.js | 340 +++++++------ .../vercel/full/next-33088/output/index.js | 6 +- .../react-instantsearch/2/output/index.js | 467 +++++++++--------- .../react-instantsearch/1/output/index.js | 118 ++--- .../src/es2015/block_scoped_fn.rs | 130 +++-- .../src/es2015/mod.rs | 6 +- 121 files changed, 2257 insertions(+), 2095 deletions(-) create mode 100644 crates/swc/tests/fixture/issues-2xxx/2793/input/.swcrc create mode 100644 crates/swc/tests/fixture/issues-2xxx/2793/input/index.js create mode 100644 crates/swc/tests/fixture/issues-2xxx/2793/output/index.js diff --git a/crates/swc/tests/fixture/issues-2xxx/2793/input/.swcrc b/crates/swc/tests/fixture/issues-2xxx/2793/input/.swcrc new file mode 100644 index 00000000000..088bc6e5217 --- /dev/null +++ b/crates/swc/tests/fixture/issues-2xxx/2793/input/.swcrc @@ -0,0 +1,5 @@ +{ + "jsc": { + "target": "es5" + } +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/issues-2xxx/2793/input/index.js b/crates/swc/tests/fixture/issues-2xxx/2793/input/index.js new file mode 100644 index 00000000000..1bf416efcc1 --- /dev/null +++ b/crates/swc/tests/fixture/issues-2xxx/2793/input/index.js @@ -0,0 +1,34 @@ +function foo() {} + +function foo() { + function bar() {} +} + +/////////////////// +{ + function foo() {} +} + +{ + { + function foo() {} + } +} + +if (true) { + function foo() {} +} + +try { + function foo() {} +} catch (e) { + function foo() {} +} finally { + function foo() {} +} + +switch (x) { + default: { + function foo() {} + } +} diff --git a/crates/swc/tests/fixture/issues-2xxx/2793/output/index.js b/crates/swc/tests/fixture/issues-2xxx/2793/output/index.js new file mode 100644 index 00000000000..b936b579e62 --- /dev/null +++ b/crates/swc/tests/fixture/issues-2xxx/2793/output/index.js @@ -0,0 +1,27 @@ +function foo() {} +function foo() { + function bar() {} +} +/////////////////// +{ + var foo1 = function foo1() {}; +}{ + { + var foo2 = function foo2() {}; + } +}if (true) { + var foo3 = function foo3() {}; +} +try { + var foo4 = function foo4() {}; +} catch (e) { + var foo5 = function foo5() {}; +} finally{ + var foo6 = function foo6() {}; +} +switch(x){ + default: + { + var foo7 = function foo7() {}; + } +} diff --git a/crates/swc/tests/fixture/issues-3xxx/3417/1/output/index.ts b/crates/swc/tests/fixture/issues-3xxx/3417/1/output/index.ts index 8a94f209917..df72eade923 100644 --- a/crates/swc/tests/fixture/issues-3xxx/3417/1/output/index.ts +++ b/crates/swc/tests/fixture/issues-3xxx/3417/1/output/index.ts @@ -1,9 +1,9 @@ export function selectRooms(building) { - var getRoomFloorMaterial = function getRoomFloorMaterial(_) { - return null; - }; var roomsByRow = {}; var rooms = building.rooms, walls = building.walls, levels = building.levels, roomsByLevel = building.roomsByLevel; + function getRoomFloorMaterial(_) { + return null; + } var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; try { var _loop = function() { diff --git a/crates/swc/tests/fixture/issues-6xxx/6345/1/output/index.js b/crates/swc/tests/fixture/issues-6xxx/6345/1/output/index.js index edca173f5ab..6b982ec2914 100644 --- a/crates/swc/tests/fixture/issues-6xxx/6345/1/output/index.js +++ b/crates/swc/tests/fixture/issues-6xxx/6345/1/output/index.js @@ -1,18 +1,18 @@ "use strict"; function a() {} var te = function() { - var n = function n(n) {}; + function n(n) {} var t = null; return { - init: function r(r) { - return t = new n(r); + init: function u(u) { + return t = new n(u); } }; }(); var he = function() { - var n = function n() { + function n() { a(); - }; + } ; var t = null; return { diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModuleMemberThatUsesClassTypeParameter.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModuleMemberThatUsesClassTypeParameter.1.normal.js index 8f1cd0ff4ae..3dff942d236 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModuleMemberThatUsesClassTypeParameter.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModuleMemberThatUsesClassTypeParameter.1.normal.js @@ -6,7 +6,7 @@ var clodule1 = function clodule1() { _class_call_check(this, clodule1); }; (function(clodule1) { - var f = function f(x) {}; + function f(x) {} })(clodule1 || (clodule1 = {})); var clodule2 = function clodule2() { "use strict"; diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndGenericClassStaticFunctionOfTheSameName.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndGenericClassStaticFunctionOfTheSameName.1.normal.js index c5f002623d3..5d60a7ba4e0 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndGenericClassStaticFunctionOfTheSameName.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndGenericClassStaticFunctionOfTheSameName.1.normal.js @@ -9,9 +9,9 @@ var clodule = /*#__PURE__*/ function() { return clodule; }(); (function(clodule) { - var fn = function fn(x, y) { + function fn(x, y) { return x; - }; + } // error: duplicate identifier expected clodule.fn = fn; })(clodule || (clodule = {})); diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndNonGenericClassStaticFunctionOfTheSameName.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndNonGenericClassStaticFunctionOfTheSameName.1.normal.js index c42cd2edbf4..7b52b86a6e3 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndNonGenericClassStaticFunctionOfTheSameName.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedGenericFunctionAndNonGenericClassStaticFunctionOfTheSameName.1.normal.js @@ -9,9 +9,9 @@ var clodule = /*#__PURE__*/ function() { return clodule; }(); (function(clodule) { - var fn = function fn(x, y) { + function fn(x, y) { return x; - }; + } // error: duplicate identifier expected clodule.fn = fn; })(clodule || (clodule = {})); diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedStaticFunctionUsingClassPrivateStatics.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedStaticFunctionUsingClassPrivateStatics.1.normal.js index e3f557f4ef8..681a6f0a2b8 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedStaticFunctionUsingClassPrivateStatics.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithModulesExportedStaticFunctionUsingClassPrivateStatics.1.normal.js @@ -11,9 +11,9 @@ var clodule = /*#__PURE__*/ function() { return clodule; }(); (function(clodule) { - var fn = function fn(x, y) { + function fn(x, y) { return clodule.sfn("a"); - }; + } // error: duplicate identifier expected clodule.fn = fn; })(clodule || (clodule = {})); diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndExportedFunctionThatShareAName.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndExportedFunctionThatShareAName.1.normal.js index b506243eff0..32b15043159 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndExportedFunctionThatShareAName.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndExportedFunctionThatShareAName.1.normal.js @@ -17,10 +17,9 @@ var Point = /*#__PURE__*/ function() { return Point; }(); (function(Point) { - var Origin = function Origin() { + function Origin() { return null; } //expected duplicate identifier error - ; Point.Origin = Origin; })(Point || (Point = {})); var A; @@ -43,10 +42,9 @@ var A; }(); A.Point = Point; (function(Point) { - var Origin = function Origin() { + function Origin() { return ""; } //expected duplicate identifier error - ; Point.Origin = Origin; })(Point = A.Point || (A.Point = {})); })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.1.normal.js b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.1.normal.js index edbb44ec1fe..9b8affbf72f 100644 --- a/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.1.normal.js +++ b/crates/swc/tests/tsc-references/ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.1.normal.js @@ -16,10 +16,9 @@ var Point = /*#__PURE__*/ function() { return Point; }(); (function(Point) { - var Origin = function Origin() { + function Origin() { return ""; } // not an error, since not exported - ; })(Point || (Point = {})); var A; (function(A) { @@ -40,9 +39,8 @@ var A; }(); A.Point = Point; (function(Point) { - var Origin = function Origin() { + function Origin() { return ""; } // not an error since not exported - ; })(Point = A.Point || (A.Point = {})); })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/ExportFunctionWithAccessibleTypesInParameterAndReturnTypeAnnotation.1.normal.js b/crates/swc/tests/tsc-references/ExportFunctionWithAccessibleTypesInParameterAndReturnTypeAnnotation.1.normal.js index fefec132b99..3df0ee2165c 100644 --- a/crates/swc/tests/tsc-references/ExportFunctionWithAccessibleTypesInParameterAndReturnTypeAnnotation.1.normal.js +++ b/crates/swc/tests/tsc-references/ExportFunctionWithAccessibleTypesInParameterAndReturnTypeAnnotation.1.normal.js @@ -2,12 +2,6 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var A; (function(A) { - var fromOrigin = function fromOrigin(p) { - return new Line({ - x: 0, - y: 0 - }, p); - }; var Point = function Point() { "use strict"; _class_call_check(this, Point); @@ -20,5 +14,11 @@ var A; this.end = end; }; A.Line = Line; + function fromOrigin(p) { + return new Line({ + x: 0, + y: 0 + }, p); + } A.fromOrigin = fromOrigin; })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInParameterTypeAnnotation.1.normal.js b/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInParameterTypeAnnotation.1.normal.js index 7da6abdf2e0..859559e57e1 100644 --- a/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInParameterTypeAnnotation.1.normal.js +++ b/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInParameterTypeAnnotation.1.normal.js @@ -2,12 +2,6 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var A; (function(A) { - var fromOrigin = function fromOrigin(p) { - return new Line({ - x: 0, - y: 0 - }, p); - }; var Point = function Point() { "use strict"; _class_call_check(this, Point); @@ -19,5 +13,11 @@ var A; this.end = end; }; A.Line = Line; + function fromOrigin(p) { + return new Line({ + x: 0, + y: 0 + }, p); + } A.fromOrigin = fromOrigin; })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInReturnTypeAnnotation.1.normal.js b/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInReturnTypeAnnotation.1.normal.js index d1dbc6ad0bf..7cde23f393f 100644 --- a/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInReturnTypeAnnotation.1.normal.js +++ b/crates/swc/tests/tsc-references/ExportFunctionWithInaccessibleTypesInReturnTypeAnnotation.1.normal.js @@ -2,12 +2,6 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var A; (function(A) { - var fromOrigin = function fromOrigin(p) { - return new Line({ - x: 0, - y: 0 - }, p); - }; var Point = function Point() { "use strict"; _class_call_check(this, Point); @@ -19,5 +13,11 @@ var A; this.start = start; this.end = end; }; + function fromOrigin(p) { + return new Line({ + x: 0, + y: 0 + }, p); + } A.fromOrigin = fromOrigin; })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.1.normal.js b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.1.normal.js index af68293f863..aae2c8e0158 100644 --- a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.1.normal.js +++ b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.1.normal.js @@ -1,12 +1,12 @@ //// [function.ts] var A; (function(A) { - var Point = function Point() { + function Point() { return { x: 0, y: 0 }; - }; + } A.Point = Point; })(A || (A = {})); //// [module.ts] @@ -29,12 +29,12 @@ var cl = A.Point.Origin; // not expected to be an error. //// [simple.ts] var B; (function(B) { - var Point = function Point() { + function Point() { return { x: 0, y: 0 }; - }; + } B.Point = Point; (function(Point) { Point.Origin = { diff --git a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.2.minified.js b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.2.minified.js index 887b1260c6c..ba1e3634483 100644 --- a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.2.minified.js +++ b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndCommonRoot.2.minified.js @@ -16,13 +16,16 @@ var A, A1; A.Point, A.Point(), A.Point.Origin; // not expected to be an error. //// [simple.ts] -var B, B1, Point; -Point = function() { - return { +var B; +!function(B) { + function Point() { + return { + x: 0, + y: 0 + }; + } + B.Point = Point, (Point = B.Point || (B.Point = {})).Origin = { x: 0, y: 0 }; -}, (B1 = B || (B = {})).Point = Point, (Point = B1.Point || (B1.Point = {})).Origin = { - x: 0, - y: 0 -}, B.Point, B.Point(), B.Point.Origin; +}(B || (B = {})), B.Point, B.Point(), B.Point.Origin; diff --git a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndDifferentCommonRoot.1.normal.js b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndDifferentCommonRoot.1.normal.js index 8012f901b15..231d289cf06 100644 --- a/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndDifferentCommonRoot.1.normal.js +++ b/crates/swc/tests/tsc-references/FunctionAndModuleWithSameNameAndDifferentCommonRoot.1.normal.js @@ -1,12 +1,12 @@ //// [function.ts] var A; (function(A) { - var Point = function Point() { + function Point() { return { x: 0, y: 0 }; - }; + } A.Point = Point; })(A || (A = {})); //// [module.ts] diff --git a/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.1.normal.js b/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.1.normal.js index d210795f8ef..11530163b4d 100644 --- a/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.1.normal.js +++ b/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.1.normal.js @@ -12,24 +12,18 @@ var A; //// [function.ts] var A; (function(A) { - var Point = function Point() { + function Point() { return { x: 0, y: 0 }; - }; + } // duplicate identifier error A.Point = Point; })(A || (A = {})); //// [simple.ts] var B; (function(B) { - var Point = function Point() { - return { - x: 0, - y: 0 - }; - }; var Point; (function(Point) { Point.Origin = { @@ -37,6 +31,12 @@ var B; y: 0 }; })(Point = B.Point || (B.Point = {})); + function Point() { + return { + x: 0, + y: 0 + }; + } // duplicate identifier error B.Point = Point; })(B || (B = {})); diff --git a/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.2.minified.js b/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.2.minified.js index 58e881c4a1d..1d05c3db084 100644 --- a/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.2.minified.js +++ b/crates/swc/tests/tsc-references/ModuleAndFunctionWithSameNameAndCommonRoot.2.minified.js @@ -13,13 +13,17 @@ var A; }; }; //// [simple.ts] -var B, B1, Point; -Point = function() { - return { +var B; +!function(B) { + var Point; + function Point() { + return { + x: 0, + y: 0 + }; + } + (Point = B.Point || (B.Point = {})).Origin = { x: 0, y: 0 - }; -}, (Point = (B1 = B || (B = {})).Point || (B1.Point = {})).Origin = { - x: 0, - y: 0 -}, B1.Point = Point; + }, B.Point = Point; +}(B || (B = {})); diff --git a/crates/swc/tests/tsc-references/ModuleWithExportedAndNonExportedFunctions.1.normal.js b/crates/swc/tests/tsc-references/ModuleWithExportedAndNonExportedFunctions.1.normal.js index 716e031a790..e49c0fb4b57 100644 --- a/crates/swc/tests/tsc-references/ModuleWithExportedAndNonExportedFunctions.1.normal.js +++ b/crates/swc/tests/tsc-references/ModuleWithExportedAndNonExportedFunctions.1.normal.js @@ -1,20 +1,20 @@ //// [ModuleWithExportedAndNonExportedFunctions.ts] var A; (function(A) { - var fn = function fn(s) { + function fn(s) { return true; - }; - var fng = function fng(s) { - return null; - }; - var fn2 = function fn2(s) { - return false; - }; - var fng2 = function fng2(s) { - return null; - }; + } A.fn = fn; + function fng(s) { + return null; + } A.fng = fng; + function fn2(s) { + return false; + } + function fng2(s) { + return null; + } })(A || (A = {})); // these should not be errors since the functions are exported var fn; diff --git a/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.1.normal.js b/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.1.normal.js index ff5928169fe..7fc298acfeb 100644 --- a/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.1.normal.js +++ b/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedAndNonExportedLocalVarsOfTheSameName.1.normal.js @@ -3,12 +3,12 @@ var A; (function(A) { var Utils; (function(Utils) { - var mirror = function mirror(p) { + function mirror(p) { return { x: p.y, y: p.x }; - }; + } Utils.mirror = mirror; })(Utils = A.Utils || (A.Utils = {})); A.Origin = { diff --git a/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.1.normal.js b/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.1.normal.js index 299d62c5f9e..8d6cf4b7ac7 100644 --- a/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.1.normal.js +++ b/crates/swc/tests/tsc-references/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.1.normal.js @@ -3,12 +3,12 @@ export var A; (function(A) { var Utils; (function(Utils) { - var mirror = function mirror(p) { + function mirror(p) { return { x: p.y, y: p.x }; - }; + } Utils.mirror = mirror; })(Utils = A.Utils || (A.Utils = {})); A.Origin = { diff --git a/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndDifferentCommonRoot.1.normal.js b/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndDifferentCommonRoot.1.normal.js index 96aa3833963..0fd5d446f50 100644 --- a/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndDifferentCommonRoot.1.normal.js +++ b/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndDifferentCommonRoot.1.normal.js @@ -5,12 +5,12 @@ var Root; (function(A) { var Utils; (function(Utils) { - var mirror = function mirror(p) { + function mirror(p) { return { x: p.y, y: p.x }; - }; + } Utils.mirror = mirror; })(Utils = A.Utils || (A.Utils = {})); })(A = Root.A || (Root.A = {})); diff --git a/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndSameCommonRoot.1.normal.js b/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndSameCommonRoot.1.normal.js index 9d1a58d0a31..0d433f098d3 100644 --- a/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndSameCommonRoot.1.normal.js +++ b/crates/swc/tests/tsc-references/TwoInternalModulesWithTheSameNameAndSameCommonRoot.1.normal.js @@ -3,12 +3,12 @@ var A; (function(A) { var Utils; (function(Utils) { - var mirror = function mirror(p) { + function mirror(p) { return { x: p.y, y: p.x }; - }; + } Utils.mirror = mirror; })(Utils = A.Utils || (A.Utils = {})); })(A || (A = {})); diff --git a/crates/swc/tests/tsc-references/arrowFunctionExpressions.1.normal.js b/crates/swc/tests/tsc-references/arrowFunctionExpressions.1.normal.js index b513f4767e7..3de25e43dc6 100644 --- a/crates/swc/tests/tsc-references/arrowFunctionExpressions.1.normal.js +++ b/crates/swc/tests/tsc-references/arrowFunctionExpressions.1.normal.js @@ -114,11 +114,11 @@ function someOtherFn() { } // Arrow function used in nested function in function function outerFn() { - var innerFn = function innerFn() { + function innerFn() { var arrowFn = function() {}; var p = arrowFn(); var p; - }; + } } // Arrow function used in nested function in arrow function var f = function(n) { diff --git a/crates/swc/tests/tsc-references/asiPreventsParsingAsAmbientExternalModule02.1.normal.js b/crates/swc/tests/tsc-references/asiPreventsParsingAsAmbientExternalModule02.1.normal.js index f2a9345543a..a9e6c72ed75 100644 --- a/crates/swc/tests/tsc-references/asiPreventsParsingAsAmbientExternalModule02.1.normal.js +++ b/crates/swc/tests/tsc-references/asiPreventsParsingAsAmbientExternalModule02.1.normal.js @@ -3,11 +3,11 @@ var declare; var module; var container; (function(container) { - "my external module" // this is just a string - ; declare // this is the identifier 'declare' ; module // this is the identifier 'module' ; + "my external module" // this is just a string + ; {} })(container || (container = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.1.normal.js index cbc1a4d2d63..f80acf45db6 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.1.normal.js @@ -51,23 +51,23 @@ var GH14865; var GH30170; // https://github.com/Microsoft/TypeScript/issues/30170 (function(GH30170) { - var draw = function draw(val) {}; - var drawWithColor = function drawWithColor(currentColor) { + function draw(val) {} + function drawWithColor(currentColor) { return draw({ color: currentColor }); - }; + } })(GH30170 || (GH30170 = {})); var GH12052; // https://github.com/Microsoft/TypeScript/issues/12052 (function(GH12052) { - var getAxisType = function getAxisType() { + function getAxisType() { if (1 == 1) { return "categorical"; } else { return "linear"; } - }; + } var bad = { type: getAxisType() }; @@ -79,16 +79,16 @@ var GH12052; var GH18421; // https://github.com/Microsoft/TypeScript/issues/18421 (function(GH18421) { - var makeNewThing = function makeNewThing(thingType) { + function makeNewThing(thingType) { return { type: thingType }; - }; + } })(GH18421 || (GH18421 = {})); var GH15907; // https://github.com/Microsoft/TypeScript/issues/15907 (function(GH15907) { - var dispatchAction = function dispatchAction(action) {}; + function dispatchAction(action) {} var active = true; dispatchAction({ type: active ? "disactivate" : "activate" @@ -97,11 +97,11 @@ var GH15907; var GH20889; // https://github.com/Microsoft/TypeScript/issues/20889 (function(GH20889) { - var foo = function foo(obj1) { + function foo(obj1) { var obj2 = { type: obj1.type }; - }; + } })(GH20889 || (GH20889 = {})); var GH39357; // https://github.com/microsoft/TypeScript/issues/39357 diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.2.minified.js b/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.2.minified.js index 8cdaf77612a..b1a1ba4a3b8 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.2.minified.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithDiscriminatedUnion.2.minified.js @@ -1,7 +1,7 @@ //// [assignmentCompatWithDiscriminatedUnion.ts] // see 'typeRelatedToDiscriminatedType' in checker.ts: // IteratorResult -var Example1, Example2, Example3, Example4, Example5, GH14865, GH30170, GH12052, GH18421, GH15907, GH20889, GH39357, b1, getAxisType; +var Example1, Example2, Example3, Example4, Example5, GH14865, GH30170, GH12052, GH18421, GH15907, GH20889, GH39357, b1; Example1 || (Example1 = {}), // S is assignable to T0 when S["done"] is true // S is assignable to T1 when S["done"] is false t = s, Example2 || (Example2 = {}), // S is assignable to T0 when S["a"] is 0 @@ -13,6 +13,9 @@ t = s, Example4 || (Example4 = {}), // S is assignable to T0 when S["a"] is 0 // S is *not* assignable to T2 when S["a"] is 2 as S is missing "c" t = s, Example5 || (Example5 = {}), // S *should* be assignable but the number of // combinations is too complex. -t = s, GH14865 || (GH14865 = {}), b1.type, GH30170 || (GH30170 = {}), GH12052 || (GH12052 = {}), (getAxisType = function() { - return "categorical"; -})(), getAxisType(), GH18421 || (GH18421 = {}), GH15907 || (GH15907 = {}), GH20889 || (GH20889 = {}), GH39357 || (GH39357 = {}), ("a" === b || "b" === b) && b; +t = s, GH14865 || (GH14865 = {}), b1.type, GH30170 || (GH30170 = {}), function(GH12052) { + function getAxisType() { + return "categorical"; + } + getAxisType(), getAxisType(); +}(GH12052 || (GH12052 = {})), GH18421 || (GH18421 = {}), GH15907 || (GH15907 = {}), GH20889 || (GH20889 = {}), GH39357 || (GH39357 = {}), ("a" === b || "b" === b) && b; diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithGenericCallSignaturesWithOptionalParameters.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithGenericCallSignaturesWithOptionalParameters.1.normal.js index 0725acb3bf2..ee7c4200dc4 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithGenericCallSignaturesWithOptionalParameters.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithGenericCallSignaturesWithOptionalParameters.1.normal.js @@ -67,7 +67,15 @@ var ClassTypeParam; })(ClassTypeParam || (ClassTypeParam = {})); var GenericSignaturesInvalid; (function(GenericSignaturesInvalid) { - var foo = function foo() { + var Base2 = function Base2() { + "use strict"; + _class_call_check(this, Base2); + }; + var Target = function Target() { + "use strict"; + _class_call_check(this, Target); + }; + function foo() { var b; var t; // all errors @@ -96,15 +104,7 @@ var GenericSignaturesInvalid; b.a5 = t.a3; b.a5 = t.a4; b.a5 = t.a5; - }; - var Base2 = function Base2() { - "use strict"; - _class_call_check(this, Base2); - }; - var Target = function Target() { - "use strict"; - _class_call_check(this, Target); - }; + } })(GenericSignaturesInvalid || (GenericSignaturesInvalid = {})); var GenericSignaturesValid; (function(GenericSignaturesValid) { diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer.1.normal.js index 3e745c34e52..777de94ea75 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer.1.normal.js @@ -16,18 +16,6 @@ a = b2; b2 = a; // error var Generics; (function(Generics) { - var foo = function foo() { - var a; - var b; - a = b; // error - b = a; // error - var b2; - a = b2; // error - b2 = a; // error - var b3; - a = b3; // ok - b3 = a; // ok - }; var A = function A() { "use strict"; _class_call_check(this, A); @@ -42,4 +30,16 @@ var Generics; } return B; }(A); + function foo() { + var a; + var b; + a = b; // error + b = a; // error + var b2; + a = b2; // error + b2 = a; // error + var b3; + a = b3; // ok + b3 = a; // ok + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer2.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer2.1.normal.js index 5e9c558ec99..276c3316225 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer2.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer2.1.normal.js @@ -9,7 +9,7 @@ a = b2; b2 = a; // error var Generics; (function(Generics) { - var foo = function foo() { + function foo() { var a; var b; a = b; // error @@ -20,5 +20,5 @@ var Generics; var b3; a = b3; // ok b3 = a; // ok - }; + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer3.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer3.1.normal.js index 8d81a76551c..4628c6b2707 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer3.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithNumericIndexer3.1.normal.js @@ -26,7 +26,11 @@ a = b2; // ok b2 = a; // error var Generics; (function(Generics) { - var foo = function foo() { + var A = function A() { + "use strict"; + _class_call_check(this, A); + }; + function foo() { var a; var b; a = b; // error @@ -34,9 +38,5 @@ var Generics; var b2; a = b2; // ok b2 = a; // ok - }; - var A = function A() { - "use strict"; - _class_call_check(this, A); - }; + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer.1.normal.js index 104011f76a1..46a20a2a43a 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer.1.normal.js @@ -16,15 +16,6 @@ a = b2; // ok b2 = a; // error var Generics; (function(Generics) { - var foo = function foo() { - var b3; - var a3; - a3 = b3; // error - b3 = a3; // error - var b4; - a3 = b4; // error - b4 = a3; // error - }; var A = function A() { "use strict"; _class_call_check(this, A); @@ -56,4 +47,13 @@ var Generics; var b2; a1 = b2; // ok b2 = a1; // error + function foo() { + var b3; + var a3; + a3 = b3; // error + b3 = a3; // error + var b4; + a3 = b4; // error + b4 = a3; // error + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer2.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer2.1.normal.js index f780b4520f6..4a2ed217a40 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer2.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer2.1.normal.js @@ -9,15 +9,6 @@ a = b2; // ok b2 = a; // error var Generics; (function(Generics) { - var foo = function foo() { - var b3; - var a3; - a3 = b3; // error - b3 = a3; // error - var b4; - a3 = b4; // error - b4 = a3; // error - }; var b1; var a1; a1 = b1; // ok @@ -25,4 +16,13 @@ var Generics; var b2; a1 = b2; // ok b2 = a1; // error + function foo() { + var b3; + var a3; + a3 = b3; // error + b3 = a3; // error + var b4; + a3 = b4; // error + b4 = a3; // error + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer3.1.normal.js b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer3.1.normal.js index 651a611a912..42d25b9c477 100644 --- a/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer3.1.normal.js +++ b/crates/swc/tests/tsc-references/assignmentCompatWithStringIndexer3.1.normal.js @@ -7,14 +7,14 @@ a = b1; // error b1 = a; // error var Generics; (function(Generics) { - var foo = function foo() { - var a; - var b; - a = b; // error - b = a; // error - }; var A = function A() { "use strict"; _class_call_check(this, A); }; + function foo() { + var a; + var b; + a = b; // error + b = a; // error + } })(Generics || (Generics = {})); diff --git a/crates/swc/tests/tsc-references/asyncArrowFunctionCapturesArguments_es5.1.normal.js b/crates/swc/tests/tsc-references/asyncArrowFunctionCapturesArguments_es5.1.normal.js index 8e0a22c76a8..9fa5c09dc29 100644 --- a/crates/swc/tests/tsc-references/asyncArrowFunctionCapturesArguments_es5.1.normal.js +++ b/crates/swc/tests/tsc-references/asyncArrowFunctionCapturesArguments_es5.1.normal.js @@ -9,7 +9,7 @@ var C = /*#__PURE__*/ function() { } var _proto = C.prototype; _proto.method = function method() { - var other = function other() {}; + function other() {} var _this = this, _arguments = arguments; var fn = function() { var _ref = _async_to_generator(function() { diff --git a/crates/swc/tests/tsc-references/asyncFunctionDeclarationCapturesArguments_es5.1.normal.js b/crates/swc/tests/tsc-references/asyncFunctionDeclarationCapturesArguments_es5.1.normal.js index cfd8fbb1585..36084218472 100644 --- a/crates/swc/tests/tsc-references/asyncFunctionDeclarationCapturesArguments_es5.1.normal.js +++ b/crates/swc/tests/tsc-references/asyncFunctionDeclarationCapturesArguments_es5.1.normal.js @@ -9,7 +9,7 @@ var C = /*#__PURE__*/ function() { } var _proto = C.prototype; _proto.method = function method() { - var other = function other() {}; + function other() {} function fn() { return _fn.apply(this, arguments); } diff --git a/crates/swc/tests/tsc-references/emitArrowFunctionWhenUsingArguments19.1.normal.js b/crates/swc/tests/tsc-references/emitArrowFunctionWhenUsingArguments19.1.normal.js index fbc6f71b213..079beff4609 100644 --- a/crates/swc/tests/tsc-references/emitArrowFunctionWhenUsingArguments19.1.normal.js +++ b/crates/swc/tests/tsc-references/emitArrowFunctionWhenUsingArguments19.1.normal.js @@ -1,6 +1,6 @@ //// [emitArrowFunctionWhenUsingArguments19.ts] function f() { - var g = function g() { + function g() { var _arguments = 10; // No capture in 'g', so no conflict. function h() { var _arguments1 = arguments; @@ -9,8 +9,8 @@ function f() { }; // Should trigger an '_arguments' capture into function 'h' foo(_arguments); // Error as this does not resolve to the user defined '_arguments' } - }; - var foo = function foo(x) { + } + function foo(x) { return 100; - }; + } } diff --git a/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5.1.normal.js b/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5.1.normal.js index b6c4b39db85..fb4425df05f 100644 --- a/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5.1.normal.js +++ b/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5.1.normal.js @@ -2,13 +2,6 @@ import { _ as _object_destructuring_empty } from "@swc/helpers/_/_object_destructuring_empty"; import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array"; (function() { - var f = function f() { - var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); - return function() { - var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); - return a; - }; - }; var a; var ref = _object_destructuring_empty(a); var ref1 = _object_destructuring_empty(a); @@ -23,6 +16,13 @@ import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array"; var ref7 = _object_destructuring_empty(a.p1), _a_p21 = _sliced_to_array(a.p2, 0); var ref8 = _object_destructuring_empty(a.p1), _a_p22 = _sliced_to_array(a.p2, 0); for(var ref9 = _object_destructuring_empty({}), ref10 = _object_destructuring_empty({}); false; void 0){} + function f() { + var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); + return function() { + var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); + return a; + }; + } })(); (function() { var ns = []; diff --git a/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5iterable.1.normal.js b/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5iterable.1.normal.js index b6fac17c83b..14f91faec7e 100644 --- a/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5iterable.1.normal.js +++ b/crates/swc/tests/tsc-references/emptyVariableDeclarationBindingPatterns01_ES5iterable.1.normal.js @@ -2,13 +2,6 @@ import { _ as _object_destructuring_empty } from "@swc/helpers/_/_object_destructuring_empty"; import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array"; (function() { - var f = function f() { - var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); - return function() { - var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); - return a; - }; - }; var a; var ref = _object_destructuring_empty(a); var ref1 = _object_destructuring_empty(a); @@ -23,6 +16,13 @@ import { _ as _sliced_to_array } from "@swc/helpers/_/_sliced_to_array"; var ref7 = _object_destructuring_empty(a.p1), _a_p21 = _sliced_to_array(a.p2, 0); var ref8 = _object_destructuring_empty(a.p1), _a_p22 = _sliced_to_array(a.p2, 0); for(var ref9 = _object_destructuring_empty({}), ref10 = _object_destructuring_empty({}); false; void 0){} + function f() { + var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); + return function() { + var ref = _object_destructuring_empty(arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : a), _ref = _sliced_to_array(arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : a, 0), _ref1 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : a, tmp = _ref1.p, ref1 = _object_destructuring_empty(tmp === void 0 ? a : tmp); + return a; + }; + } })(); (function() { var ns = []; diff --git a/crates/swc/tests/tsc-references/enumAssignability.1.normal.js b/crates/swc/tests/tsc-references/enumAssignability.1.normal.js index 4e8e3a040b9..8e22288d08b 100644 --- a/crates/swc/tests/tsc-references/enumAssignability.1.normal.js +++ b/crates/swc/tests/tsc-references/enumAssignability.1.normal.js @@ -19,13 +19,6 @@ var x = e; // ok x = f; // ok var Others; (function(Others) { - var foo = function foo(x, y, z) { - x = e; - y = e; - z = e; - var a = e; - var b = e; - }; var a = e; // ok var C = function C() { "use strict"; @@ -51,4 +44,11 @@ var Others; var o = e; var p = e; var q = e; + function foo(x, y, z) { + x = e; + y = e; + z = e; + var a = e; + var b = e; + } })(Others || (Others = {})); diff --git a/crates/swc/tests/tsc-references/errorSuperPropertyAccess.1.normal.js b/crates/swc/tests/tsc-references/errorSuperPropertyAccess.1.normal.js index 6e5d5b34cff..b6f795fdb0e 100644 --- a/crates/swc/tests/tsc-references/errorSuperPropertyAccess.1.normal.js +++ b/crates/swc/tests/tsc-references/errorSuperPropertyAccess.1.normal.js @@ -78,9 +78,9 @@ var SomeDerived1 = /*#__PURE__*/ function(SomeBase) { var x = _get(_get_prototype_of(SomeDerived1.prototype), "publicMember", this); }; _proto.fn2 = function fn2() { - var inner = function inner() { + function inner() { _get(_get_prototype_of(SomeDerived1.prototype), "publicFunc", this).call(this); - }; + } var x = { test: function test() { return _get(_get_prototype_of(SomeDerived1.prototype), "publicFunc", this).call(this); diff --git a/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInitializer.1.normal.js b/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInitializer.1.normal.js index 7ba25a0a476..217e844cc55 100644 --- a/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInitializer.1.normal.js +++ b/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInitializer.1.normal.js @@ -13,14 +13,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); var aNumber = 9.9; diff --git a/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInvalidInitializer.1.normal.js b/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInvalidInitializer.1.normal.js index 2a4ca750d81..560cf45459a 100644 --- a/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInvalidInitializer.1.normal.js +++ b/crates/swc/tests/tsc-references/everyTypeWithAnnotationAndInvalidInitializer.1.normal.js @@ -16,27 +16,27 @@ function F2(x) { } var M; (function(M) { - var _$F2 = function _$F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; - M.F2 = _$F2; + function F2(x) { + return x.toString(); + } + M.F2 = F2; })(M || (M = {})); var N; (function(N) { - var _$F2 = function _$F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; N.A = A; - N.F2 = _$F2; + function F2(x) { + return x.toString(); + } + N.F2 = F2; })(N || (N = {})); var aNumber = "this is a string"; var aString = 9.9; diff --git a/crates/swc/tests/tsc-references/everyTypeWithInitializer.1.normal.js b/crates/swc/tests/tsc-references/everyTypeWithInitializer.1.normal.js index ef94f9f83fd..783aaefc81e 100644 --- a/crates/swc/tests/tsc-references/everyTypeWithInitializer.1.normal.js +++ b/crates/swc/tests/tsc-references/everyTypeWithInitializer.1.normal.js @@ -13,14 +13,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); var aNumber = 9.9; diff --git a/crates/swc/tests/tsc-references/exportAssignmentMergedModule.1.normal.js b/crates/swc/tests/tsc-references/exportAssignmentMergedModule.1.normal.js index 7b42b8760dc..5bb09b8e557 100644 --- a/crates/swc/tests/tsc-references/exportAssignmentMergedModule.1.normal.js +++ b/crates/swc/tests/tsc-references/exportAssignmentMergedModule.1.normal.js @@ -2,16 +2,16 @@ "use strict"; var Foo; (function(Foo) { - var a = function a() { + function a() { return 5; - }; + } Foo.a = a; Foo.b = true; })(Foo || (Foo = {})); (function(Foo) { - var c = function c(a) { + function c(a) { return a; - }; + } Foo.c = c; var Test; (function(Test) { diff --git a/crates/swc/tests/tsc-references/exportCodeGen.1.normal.js b/crates/swc/tests/tsc-references/exportCodeGen.1.normal.js index cadcf5bfd14..63da83c7248 100644 --- a/crates/swc/tests/tsc-references/exportCodeGen.1.normal.js +++ b/crates/swc/tests/tsc-references/exportCodeGen.1.normal.js @@ -4,42 +4,42 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var A; (function(A) { - var lt12 = function lt12() { - return A.x < 12; - }; A.x = 12; + function lt12() { + return A.x < 12; + } })(A || (A = {})); var B; // should not fully qualify 'x' (function(B) { - var lt12 = function lt12() { - return x < 12; - }; var x = 12; + function lt12() { + return x < 12; + } })(B || (B = {})); var C; // not copied, since not exported (function(C) { - var no = function no() { + function no() { return false; - }; + } })(C || (C = {})); var D; // copies, since exported (function(D) { - var yes = function yes() { + function yes() { return true; - }; + } D.yes = yes; })(D || (D = {})); var E; // validate all exportable statements (function(E) { - var fn = function fn() {}; var Color; (function(Color) { Color[Color["Red"] = 0] = "Red"; })(Color = E.Color || (E.Color = {})); + function fn() {} E.fn = fn; var C = function C() { "use strict"; @@ -55,11 +55,11 @@ var F; // validate all exportable statements, // which are not exported (function(F) { - var fn = function fn() {}; var Color; (function(Color) { Color[Color["Red"] = 0] = "Red"; })(Color || (Color = {})); + function fn() {} var C = function C() { "use strict"; _class_call_check(this, C); diff --git a/crates/swc/tests/tsc-references/exportImportAlias.1.normal.js b/crates/swc/tests/tsc-references/exportImportAlias.1.normal.js index 4fc27e93e23..102aa2e0855 100644 --- a/crates/swc/tests/tsc-references/exportImportAlias.1.normal.js +++ b/crates/swc/tests/tsc-references/exportImportAlias.1.normal.js @@ -22,9 +22,9 @@ var c; var c; var X; (function(X) { - var Y = function Y() { + function Y() { return 42; - }; + } X.Y = Y; (function(Y) { var Point = function Point(x, y) { diff --git a/crates/swc/tests/tsc-references/exportImportAlias.2.minified.js b/crates/swc/tests/tsc-references/exportImportAlias.2.minified.js index 88cf65d9158..15be5055efe 100644 --- a/crates/swc/tests/tsc-references/exportImportAlias.2.minified.js +++ b/crates/swc/tests/tsc-references/exportImportAlias.2.minified.js @@ -1,13 +1,16 @@ //// [exportImportAlias.ts] // expect no errors here -var A, C, X, Z, K, M, A1, X1, Y, K1, L; +var A, C, X, Z, K, M, A1, K1, L; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; (A1 = A || (A = {})).x = "hello world", A1.Point = function Point(x, y) { _class_call_check(this, Point), this.x = x, this.y = y; -}, (C || (C = {})).a = A, C.a.x, new C.a.Point(0, 0), Y = function() { - return 42; -}, (X1 = X || (X = {})).Y = Y, (Y = X1.Y || (X1.Y = {})).Point = function Point(x, y) { - _class_call_check(this, Point), this.x = x, this.y = y; -}, (Z || (Z = {})).y = X.Y, Z.y(), new Z.y.Point(0, 0), K1 = K || (K = {}), L = function L(name) { +}, (C || (C = {})).a = A, C.a.x, new C.a.Point(0, 0), function(X) { + function Y() { + return 42; + } + X.Y = Y, (Y = X.Y || (X.Y = {})).Point = function Point(x, y) { + _class_call_check(this, Point), this.x = x, this.y = y; + }; +}(X || (X = {})), (Z || (Z = {})).y = X.Y, Z.y(), new Z.y.Point(0, 0), K1 = K || (K = {}), L = function L(name) { _class_call_check(this, L), this.name = name; }, K1.L = L, (L = K1.L || (K1.L = {})).y = 12, (M || (M = {})).D = K.L, new M.D("Hello"); diff --git a/crates/swc/tests/tsc-references/fixSignatureCaching.1.normal.js b/crates/swc/tests/tsc-references/fixSignatureCaching.1.normal.js index 91cdcb29804..8cc0a9db162 100644 --- a/crates/swc/tests/tsc-references/fixSignatureCaching.1.normal.js +++ b/crates/swc/tests/tsc-references/fixSignatureCaching.1.normal.js @@ -4,61 +4,6 @@ import { _ as _instanceof } from "@swc/helpers/_/_instanceof"; (function(define1, undefined) { define1(function() { "use strict"; - var equalIC = function equalIC(a, b) { - return a != null && b != null && a.toLowerCase() === b.toLowerCase(); - }; - var containsIC = function containsIC(array, value) { - var valueLC, i, len = array.length; - if (!len || !value) { - return false; - } - valueLC = value.toLowerCase(); - for(i = 0; i < len; ++i){ - if (valueLC === array[i].toLowerCase()) { - return true; - } - } - return false; - }; - var convertPropsToRegExp = function convertPropsToRegExp(object) { - for(var key in object){ - if (hasOwnProp.call(object, key)) { - object[key] = new RegExp(object[key], "i"); - } - } - }; - var MobileDetect = /** - * Constructor for MobileDetect object. - *
- * Such an object will keep a reference to the given user-agent string and cache most of the detect queries.
- *
- * Find information how to download and install: - * github.com/hgoebl/mobile-detect.js/ - *
- * - * @example
-     *     var md = new MobileDetect(window.navigator.userAgent);
-     *     if (md.mobile()) {
-     *         location.href = (md.mobileGrade() === 'A') ? '/mobile/' : '/lynx/';
-     *     }
-     * 
- * - * @param {string} userAgent typically taken from window.navigator.userAgent or http_header['User-Agent'] - * @param {number} [maxPhoneWidth=600] only for browsers specify a value for the maximum - * width of smallest device side (in logical "CSS" pixels) until a device detected as mobile will be handled - * as phone. - * This is only used in cases where the device cannot be classified as phone or tablet.
- * See Declaring Tablet Layouts - * for Android.
- * If you provide a value < 0, then this "fuzzy" check is disabled. - * @constructor - * @global - */ function MobileDetect(userAgent, maxPhoneWidth) { - this.ua = userAgent || ""; - this._cache = {}; - //600dp is typical 7" tablet minimum width - this.maxPhoneWidth = maxPhoneWidth || 600; - }; var impl = {}; impl.mobileDetectRules = { "phones": { @@ -349,6 +294,29 @@ import { _ as _instanceof } from "@swc/helpers/_/_instanceof"; isArray = "isArray" in Array ? function isArray(value) { return Object.prototype.toString.call(value) === "[object Array]"; } : Array.isArray; + function equalIC(a, b) { + return a != null && b != null && a.toLowerCase() === b.toLowerCase(); + } + function containsIC(array, value) { + var valueLC, i, len = array.length; + if (!len || !value) { + return false; + } + valueLC = value.toLowerCase(); + for(i = 0; i < len; ++i){ + if (valueLC === array[i].toLowerCase()) { + return true; + } + } + return false; + } + function convertPropsToRegExp(object) { + for(var key in object){ + if (hasOwnProp.call(object, key)) { + object[key] = new RegExp(object[key], "i"); + } + } + } (function init() { var key, values, value, i, len, verPos, mobileDetectRules = impl.mobileDetectRules; for(key in mobileDetectRules.props){ @@ -576,6 +544,38 @@ import { _ as _instanceof } from "@swc/helpers/_/_instanceof"; impl.getDeviceSmallerSide = function() { return window.screen.width < window.screen.height ? window.screen.width : window.screen.height; }; + /** + * Constructor for MobileDetect object. + *
+ * Such an object will keep a reference to the given user-agent string and cache most of the detect queries.
+ *
+ * Find information how to download and install: + * github.com/hgoebl/mobile-detect.js/ + *
+ * + * @example
+     *     var md = new MobileDetect(window.navigator.userAgent);
+     *     if (md.mobile()) {
+     *         location.href = (md.mobileGrade() === 'A') ? '/mobile/' : '/lynx/';
+     *     }
+     * 
+ * + * @param {string} userAgent typically taken from window.navigator.userAgent or http_header['User-Agent'] + * @param {number} [maxPhoneWidth=600] only for browsers specify a value for the maximum + * width of smallest device side (in logical "CSS" pixels) until a device detected as mobile will be handled + * as phone. + * This is only used in cases where the device cannot be classified as phone or tablet.
+ * See Declaring Tablet Layouts + * for Android.
+ * If you provide a value < 0, then this "fuzzy" check is disabled. + * @constructor + * @global + */ function MobileDetect(userAgent, maxPhoneWidth) { + this.ua = userAgent || ""; + this._cache = {}; + //600dp is typical 7" tablet minimum width + this.maxPhoneWidth = maxPhoneWidth || 600; + } MobileDetect.prototype = { constructor: MobileDetect, /** diff --git a/crates/swc/tests/tsc-references/fixSignatureCaching.2.minified.js b/crates/swc/tests/tsc-references/fixSignatureCaching.2.minified.js index fe6199893a0..093e12138c3 100644 --- a/crates/swc/tests/tsc-references/fixSignatureCaching.2.minified.js +++ b/crates/swc/tests/tsc-references/fixSignatureCaching.2.minified.js @@ -12,45 +12,7 @@ import { _ as _instanceof } from "@swc/helpers/_/_instanceof"; // please file a bug if you get this error! throw Error("unknown environment"); })()(function() { - var equalIC = function(a, b) { - return null != a && null != b && a.toLowerCase() === b.toLowerCase(); - }, containsIC = function(array, value) { - var valueLC, i, len = array.length; - if (!len || !value) return !1; - for(i = 0, valueLC = value.toLowerCase(); i < len; ++i)if (valueLC === array[i].toLowerCase()) return !0; - return !1; - }, convertPropsToRegExp = function(object) { - for(var key in object)hasOwnProp.call(object, key) && (object[key] = RegExp(object[key], "i")); - }, MobileDetect = /** - * Constructor for MobileDetect object. - *
- * Such an object will keep a reference to the given user-agent string and cache most of the detect queries.
- *
- * Find information how to download and install: - * github.com/hgoebl/mobile-detect.js/ - *
- * - * @example
-     *     var md = new MobileDetect(window.navigator.userAgent);
-     *     if (md.mobile()) {
-     *         location.href = (md.mobileGrade() === 'A') ? '/mobile/' : '/lynx/';
-     *     }
-     * 
- * - * @param {string} userAgent typically taken from window.navigator.userAgent or http_header['User-Agent'] - * @param {number} [maxPhoneWidth=600] only for browsers specify a value for the maximum - * width of smallest device side (in logical "CSS" pixels) until a device detected as mobile will be handled - * as phone. - * This is only used in cases where the device cannot be classified as phone or tablet.
- * See Declaring Tablet Layouts - * for Android.
- * If you provide a value < 0, then this "fuzzy" check is disabled. - * @constructor - * @global - */ function(userAgent, maxPhoneWidth) { - this.ua = userAgent || "", this._cache = {}, //600dp is typical 7" tablet minimum width - this.maxPhoneWidth = maxPhoneWidth || 600; - }, impl = {}; + var impl = {}; impl.mobileDetectRules = { phones: { iPhone: "\\biPhone\\b|\\biPod\\b", @@ -330,6 +292,48 @@ import { _ as _instanceof } from "@swc/helpers/_/_instanceof"; tabletPattern: /android|ipad|playbook|silk/i }; var isArray, hasOwnProp = Object.prototype.hasOwnProperty; + function equalIC(a, b) { + return null != a && null != b && a.toLowerCase() === b.toLowerCase(); + } + function containsIC(array, value) { + var valueLC, i, len = array.length; + if (!len || !value) return !1; + for(i = 0, valueLC = value.toLowerCase(); i < len; ++i)if (valueLC === array[i].toLowerCase()) return !0; + return !1; + } + function convertPropsToRegExp(object) { + for(var key in object)hasOwnProp.call(object, key) && (object[key] = RegExp(object[key], "i")); + } + /** + * Constructor for MobileDetect object. + *
+ * Such an object will keep a reference to the given user-agent string and cache most of the detect queries.
+ *
+ * Find information how to download and install: + * github.com/hgoebl/mobile-detect.js/ + *
+ * + * @example
+     *     var md = new MobileDetect(window.navigator.userAgent);
+     *     if (md.mobile()) {
+     *         location.href = (md.mobileGrade() === 'A') ? '/mobile/' : '/lynx/';
+     *     }
+     * 
+ * + * @param {string} userAgent typically taken from window.navigator.userAgent or http_header['User-Agent'] + * @param {number} [maxPhoneWidth=600] only for browsers specify a value for the maximum + * width of smallest device side (in logical "CSS" pixels) until a device detected as mobile will be handled + * as phone. + * This is only used in cases where the device cannot be classified as phone or tablet.
+ * See Declaring Tablet Layouts + * for Android.
+ * If you provide a value < 0, then this "fuzzy" check is disabled. + * @constructor + * @global + */ function MobileDetect(userAgent, maxPhoneWidth) { + this.ua = userAgent || "", this._cache = {}, //600dp is typical 7" tablet minimum width + this.maxPhoneWidth = maxPhoneWidth || 600; + } return impl.FALLBACK_PHONE = "UnknownPhone", impl.FALLBACK_TABLET = "UnknownTablet", impl.FALLBACK_MOBILE = "UnknownMobile", isArray = "isArray" in Array ? Array.isArray : function(value) { return "[object Array]" === Object.prototype.toString.call(value); }, isArray = "isArray" in Array ? function(value) { diff --git a/crates/swc/tests/tsc-references/forStatements.1.normal.js b/crates/swc/tests/tsc-references/forStatements.1.normal.js index f8ef23bf07d..6788d49bc52 100644 --- a/crates/swc/tests/tsc-references/forStatements.1.normal.js +++ b/crates/swc/tests/tsc-references/forStatements.1.normal.js @@ -13,14 +13,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); for(var aNumber = 9.9;;){} diff --git a/crates/swc/tests/tsc-references/forStatementsMultipleInvalidDecl.1.normal.js b/crates/swc/tests/tsc-references/forStatementsMultipleInvalidDecl.1.normal.js index b4f74dba8f1..32aa0f8c48f 100644 --- a/crates/swc/tests/tsc-references/forStatementsMultipleInvalidDecl.1.normal.js +++ b/crates/swc/tests/tsc-references/forStatementsMultipleInvalidDecl.1.normal.js @@ -25,14 +25,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); // all of these are errors diff --git a/crates/swc/tests/tsc-references/genericCallWithGenericSignatureArguments2.1.normal.js b/crates/swc/tests/tsc-references/genericCallWithGenericSignatureArguments2.1.normal.js index 6be119d513e..2c572e285a1 100644 --- a/crates/swc/tests/tsc-references/genericCallWithGenericSignatureArguments2.1.normal.js +++ b/crates/swc/tests/tsc-references/genericCallWithGenericSignatureArguments2.1.normal.js @@ -3,11 +3,16 @@ // the corresponding inferred type arguments to become fixed and no further candidate inferences are made for them. var onlyT; (function(onlyT) { - var foo = function foo(a, b) { + function foo(a, b) { var r; return r; - }; - var other2 = function other2(x) { + } + var r1 = foo(function(x) { + return 1; + }, function(x) { + return ""; + }); + function other2(x) { var r7 = foo(function(a) { return a; }, function(b) { @@ -16,12 +21,12 @@ var onlyT; // BUG 835518 var r9 = r7(new Date()); // should be ok var r10 = r7(1); // error - }; - var foo2 = function foo2(a, b) { + } + function foo2(a, b) { var r; return r; - }; - var other3 = function other3(x) { + } + function other3(x) { var r7 = foo2(function(a) { return a; }, function(b) { @@ -32,16 +37,7 @@ var onlyT; }, function(b) { return b; }); // valid, T is inferred to be Date - }; - var foo3 = function foo3(x, a, b) { - var r; - return r; - }; - var r1 = foo(function(x) { - return 1; - }, function(x) { - return ""; - }); + } var E; (function(E) { E[E["A"] = 0] = "A"; @@ -50,6 +46,10 @@ var onlyT; (function(F) { F[F["A"] = 0] = "A"; })(F || (F = {})); + function foo3(x, a, b) { + var r; + return r; + } var r7 = foo3(0, function(x) { return 0; }, function(x) { @@ -58,11 +58,16 @@ var onlyT; })(onlyT || (onlyT = {})); var TU; (function(TU) { - var foo = function foo(a, b) { + function foo(a, b) { var r; return r; - }; - var other2 = function other2(x) { + } + var r1 = foo(function(x) { + return 1; + }, function(x) { + return ""; + }); + function other2(x) { var r7 = foo(function(a) { return a; }, function(b) { @@ -70,12 +75,12 @@ var TU; }); var r9 = r7(new Date()); var r10 = r7(1); - }; - var foo2 = function foo2(a, b) { + } + function foo2(a, b) { var r; return r; - }; - var other3 = function other3(x) { + } + function other3(x) { var r7 = foo2(function(a) { return a; }, function(b) { @@ -86,16 +91,7 @@ var TU; }, function(b) { return b; }); - }; - var foo3 = function foo3(x, a, b) { - var r; - return r; - }; - var r1 = foo(function(x) { - return 1; - }, function(x) { - return ""; - }); + } var E; (function(E) { E[E["A"] = 0] = "A"; @@ -104,6 +100,10 @@ var TU; (function(F) { F[F["A"] = 0] = "A"; })(F || (F = {})); + function foo3(x, a, b) { + var r; + return r; + } var r7 = foo3(0, function(x) { return 0; }, function(x) { diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.1.normal.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.1.normal.js index 6e92812cb76..1fc14416937 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.1.normal.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.1.normal.js @@ -3,31 +3,31 @@ // Inferences are made quadratic-pairwise to and from these overload sets var NonGenericParameter; (function(NonGenericParameter) { - var foo4 = function foo4(cb) { - return new cb(null); - }; var a; + function foo4(cb) { + return new cb(null); + } var r = foo4(a); var b; var r2 = foo4(b); })(NonGenericParameter || (NonGenericParameter = {})); var GenericParameter; (function(GenericParameter) { - var foo5 = function foo5(cb) { + function foo5(cb) { return cb; - }; - var foo6 = function foo6(cb) { - return cb; - }; - var foo7 = function foo7(x, cb) { - return cb; - }; + } var a; var r5 = foo5(a); // new{} => string; new(x:number) => {} var b; var r7 = foo5(b); // new any => string; new(x:number) => any + function foo6(cb) { + return cb; + } var r8 = foo6(a); // error var r9 = foo6(b); // new any => string; new(x:any, y?:any) => string + function foo7(x, cb) { + return cb; + } var r13 = foo7(1, b); // new any => string; new(x:any, y?:any) => string var c; var c2; diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.2.minified.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.2.minified.js index 915447f7eb5..62e91390d39 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.2.minified.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments.2.minified.js @@ -1,13 +1,5 @@ //// [genericCallWithOverloadedConstructorTypedArguments.ts] // Function typed arguments with multiple signatures must be passed an implementation that matches all of them // Inferences are made quadratic-pairwise to and from these overload sets -var NonGenericParameter, GenericParameter, b, foo4, a, b1, c, c2, foo5, foo6, foo7; -NonGenericParameter || (NonGenericParameter = {}), (foo4 = function(cb) { - return new cb(null); -})(void 0), foo4(b), GenericParameter || (GenericParameter = {}), foo5 = function(cb) { - return cb; -}, foo6 = function(cb) { - return cb; -}, foo7 = function(x, cb) { - return cb; -}, foo5(a), foo5(b1), foo6(a), foo6(b1), foo7(1, b1), foo7(1, c), foo7(1, c2); +var NonGenericParameter, GenericParameter, b; +NonGenericParameter || (NonGenericParameter = {}), new (void 0)(null), new b(null), GenericParameter || (GenericParameter = {}); diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.1.normal.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.1.normal.js index fe23f6e0954..5209b190bd2 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.1.normal.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.1.normal.js @@ -3,28 +3,28 @@ // Inferences are made quadratic-pairwise to and from these overload sets var NonGenericParameter; (function(NonGenericParameter) { - var foo4 = function foo4(cb) { - return cb; - }; var a; + function foo4(cb) { + return cb; + } var b; var r3 = foo4(b); // ok })(NonGenericParameter || (NonGenericParameter = {})); var GenericParameter; (function(GenericParameter) { - var foo5 = function foo5(cb) { + function foo5(cb) { return cb; - }; - var foo6 = function foo6(cb) { - return cb; - }; - var foo7 = function foo7(x, cb) { - return cb; - }; + } var a; var r6 = foo5(a); // ok + function foo6(cb) { + return cb; + } var b; var r10 = foo6(b); // error + function foo7(x, cb) { + return cb; + } var r13 = foo7(1, a); // ok var c; var r14 = foo7(1, c); // ok diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.2.minified.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.2.minified.js index 0c60b36ba4a..b9c7df8de29 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.2.minified.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedConstructorTypedArguments2.2.minified.js @@ -1,7 +1,5 @@ //// [genericCallWithOverloadedConstructorTypedArguments2.ts] // Function typed arguments with multiple signatures must be passed an implementation that matches all of them // Inferences are made quadratic-pairwise to and from these overload sets -var NonGenericParameter, GenericParameter, a, c, foo7; -NonGenericParameter || (NonGenericParameter = {}), GenericParameter || (GenericParameter = {}), (foo7 = function(x, cb) { - return cb; -})(1, a), foo7(1, c); +var NonGenericParameter, GenericParameter; +NonGenericParameter || (NonGenericParameter = {}), GenericParameter || (GenericParameter = {}); diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.1.normal.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.1.normal.js index 0d192faefda..91f6c46224b 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.1.normal.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.1.normal.js @@ -3,10 +3,10 @@ // Inferences are made quadratic-pairwise to and from these overload sets var NonGenericParameter; (function(NonGenericParameter) { - var foo4 = function foo4(cb) { - return cb; - }; var a; + function foo4(cb) { + return cb; + } var r = foo4(a); var r2 = foo4(function(x) { return x; @@ -17,20 +17,17 @@ var NonGenericParameter; })(NonGenericParameter || (NonGenericParameter = {})); var GenericParameter; (function(GenericParameter) { - var foo5 = function foo5(cb) { + function foo5(cb) { return cb; - }; - var foo6 = function foo6(cb) { - return cb; - }; - var foo7 = function foo7(x, cb) { - return cb; - }; + } var r5 = foo5(function(x) { return x; }); // any => string (+1 overload) [inferences are made for T, but lambda not contextually typed]. T is any var a; var r7 = foo5(a); // any => string (+1 overload) + function foo6(cb) { + return cb; + } var r8 = foo6(function(x) { return x; }); // any => string (+1 overload) [inferences are made for T, but lambda not contextually typed]. T is any @@ -40,6 +37,9 @@ var GenericParameter; var r11 = foo6(function(x, y) { return ""; }); // any => string (+1 overload) + function foo7(x, cb) { + return cb; + } var r12 = foo7(1, function(x) { return x; }); // any => string (+1 overload) [inferences are made for T, but lambda not contextually typed] diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.2.minified.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.2.minified.js index c4a90f923db..26edf5c083b 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.2.minified.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments.2.minified.js @@ -1,29 +1,5 @@ //// [genericCallWithOverloadedFunctionTypedArguments.ts] // Function typed arguments with multiple signatures must be passed an implementation that matches all of them // Inferences are made quadratic-pairwise to and from these overload sets -var NonGenericParameter, GenericParameter, foo4, a, foo5, foo6, foo7; -NonGenericParameter || (NonGenericParameter = {}), (foo4 = function(cb) { - return cb; -})(void 0), foo4(function(x) { - return x; -}), foo4(function(x) { - return x; -}), GenericParameter || (GenericParameter = {}), foo5 = function(cb) { - return cb; -}, foo6 = function(cb) { - return cb; -}, foo7 = function(x, cb) { - return cb; -}, foo5(function(x) { - return x; -}), foo5(a), foo6(function(x) { - return x; -}), foo6(function(x) { - return ""; -}), foo6(function(x, y) { - return ""; -}), foo7(1, function(x) { - return x; -}), foo7(1, function(x) { - return ""; -}), foo7(1, a); +var NonGenericParameter, GenericParameter; +NonGenericParameter || (NonGenericParameter = {}), GenericParameter || (GenericParameter = {}); diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.1.normal.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.1.normal.js index 89b63a17205..546b8cdf997 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.1.normal.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.1.normal.js @@ -3,10 +3,10 @@ // Inferences are made quadratic-pairwise to and from these overload sets var NonGenericParameter; (function(NonGenericParameter) { - var foo4 = function foo4(cb) { - return cb; - }; var a; + function foo4(cb) { + return cb; + } var r3 = foo4(function(x) { var r; return r; @@ -14,21 +14,21 @@ var NonGenericParameter; })(NonGenericParameter || (NonGenericParameter = {})); var GenericParameter; (function(GenericParameter) { - var foo5 = function foo5(cb) { + function foo5(cb) { return cb; - }; - var foo6 = function foo6(cb) { - return cb; - }; - var foo7 = function foo7(x, cb) { - return cb; - }; + } var r6 = foo5(function(x) { return x; }); // ok + function foo6(cb) { + return cb; + } var r10 = foo6(function(x, y) { return ""; }); // error + function foo7(x, cb) { + return cb; + } var r13 = foo7(1, function(x) { return x; }); // ok diff --git a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.2.minified.js b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.2.minified.js index c5eeaf17cf9..a1a5b3d9bca 100644 --- a/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.2.minified.js +++ b/crates/swc/tests/tsc-references/genericCallWithOverloadedFunctionTypedArguments2.2.minified.js @@ -1,9 +1,5 @@ //// [genericCallWithOverloadedFunctionTypedArguments2.ts] // Function typed arguments with multiple signatures must be passed an implementation that matches all of them // Inferences are made quadratic-pairwise to and from these overload sets -var NonGenericParameter, GenericParameter, a, foo7; -NonGenericParameter || (NonGenericParameter = {}), GenericParameter || (GenericParameter = {}), (foo7 = function(x, cb) { - return cb; -})(1, function(x) { - return x; -}), foo7(1, a); +var NonGenericParameter, GenericParameter; +NonGenericParameter || (NonGenericParameter = {}), GenericParameter || (GenericParameter = {}); diff --git a/crates/swc/tests/tsc-references/genericClassWithFunctionTypedMemberArguments.1.normal.js b/crates/swc/tests/tsc-references/genericClassWithFunctionTypedMemberArguments.1.normal.js index 129c112a2be..0f9cd0d8e06 100644 --- a/crates/swc/tests/tsc-references/genericClassWithFunctionTypedMemberArguments.1.normal.js +++ b/crates/swc/tests/tsc-references/genericClassWithFunctionTypedMemberArguments.1.normal.js @@ -46,23 +46,6 @@ var ImmediatelyFix; })(ImmediatelyFix || (ImmediatelyFix = {})); var WithCandidates; (function(WithCandidates) { - var other = function other(t, u) { - var r10 = c.foo2(1, function(x) { - return ""; - }); // error - var r10 = c.foo2(1, function(x) { - return ""; - }); // string - var r11 = c3.foo3(1, function(x) { - return ""; - }, ""); // error - var r11b = c3.foo3(1, function(x) { - return ""; - }, 1); // error - var r12 = c3.foo3(1, function(a) { - return ""; - }, 1); // error - }; var C = /*#__PURE__*/ function() { "use strict"; function C() { @@ -114,4 +97,21 @@ var WithCandidates; return C3; }(); var c3; + function other(t, u) { + var r10 = c.foo2(1, function(x) { + return ""; + }); // error + var r10 = c.foo2(1, function(x) { + return ""; + }); // string + var r11 = c3.foo3(1, function(x) { + return ""; + }, ""); // error + var r11b = c3.foo3(1, function(x) { + return ""; + }, 1); // error + var r12 = c3.foo3(1, function(a) { + return ""; + }, 1); // error + } })(WithCandidates || (WithCandidates = {})); diff --git a/crates/swc/tests/tsc-references/ifDoWhileStatements.1.normal.js b/crates/swc/tests/tsc-references/ifDoWhileStatements.1.normal.js index c11aebce3b8..c519837463c 100644 --- a/crates/swc/tests/tsc-references/ifDoWhileStatements.1.normal.js +++ b/crates/swc/tests/tsc-references/ifDoWhileStatements.1.normal.js @@ -28,26 +28,26 @@ function F2(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); var N; (function(N) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; N.A = A; + function F2(x) { + return x.toString(); + } N.F2 = F2; })(N || (N = {})); // literals diff --git a/crates/swc/tests/tsc-references/importStatements.1.normal.js b/crates/swc/tests/tsc-references/importStatements.1.normal.js index ca2dc088d75..b691e0ed2bf 100644 --- a/crates/swc/tests/tsc-references/importStatements.1.normal.js +++ b/crates/swc/tests/tsc-references/importStatements.1.normal.js @@ -29,9 +29,9 @@ var D; })(D || (D = {})); var E; (function(E) { - var xDist = function xDist(x) { - return a.Origin.x - x.x; - }; var a = A; + function xDist(x) { + return a.Origin.x - x.x; + } E.xDist = xDist; })(E || (E = {})); diff --git a/crates/swc/tests/tsc-references/importStatementsInterfaces.1.normal.js b/crates/swc/tests/tsc-references/importStatementsInterfaces.1.normal.js index e6e8b1326e2..1ee46bc5ff3 100644 --- a/crates/swc/tests/tsc-references/importStatementsInterfaces.1.normal.js +++ b/crates/swc/tests/tsc-references/importStatementsInterfaces.1.normal.js @@ -19,8 +19,8 @@ var D; var E; // no code gen expected (function(E) { - var xDist = function xDist(x) { + function xDist(x) { return 0 - x.x; - }; + } E.xDist = xDist; })(E || (E = {})); diff --git a/crates/swc/tests/tsc-references/innerTypeParameterShadowingOuterOne.1.normal.js b/crates/swc/tests/tsc-references/innerTypeParameterShadowingOuterOne.1.normal.js index c3c9c7b1806..730f0ee3d87 100644 --- a/crates/swc/tests/tsc-references/innerTypeParameterShadowingOuterOne.1.normal.js +++ b/crates/swc/tests/tsc-references/innerTypeParameterShadowingOuterOne.1.normal.js @@ -2,18 +2,18 @@ // inner type parameters shadow outer ones of the same name // no errors expected function f() { - var g = function g() { + function g() { var x; x.toFixed(); - }; + } var x; x.getDate(); } function f2() { - var g = function g() { + function g() { var x; x.toFixed(); - }; + } var x; x.getDate(); } //function f2() { diff --git a/crates/swc/tests/tsc-references/invalidMultipleVariableDeclarations.1.normal.js b/crates/swc/tests/tsc-references/invalidMultipleVariableDeclarations.1.normal.js index 13bce2947d6..8628c740952 100644 --- a/crates/swc/tests/tsc-references/invalidMultipleVariableDeclarations.1.normal.js +++ b/crates/swc/tests/tsc-references/invalidMultipleVariableDeclarations.1.normal.js @@ -25,14 +25,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); // all of these are errors diff --git a/crates/swc/tests/tsc-references/localTypes1.1.normal.js b/crates/swc/tests/tsc-references/localTypes1.1.normal.js index 090278fbef4..57c69351662 100644 --- a/crates/swc/tests/tsc-references/localTypes1.1.normal.js +++ b/crates/swc/tests/tsc-references/localTypes1.1.normal.js @@ -21,7 +21,7 @@ function f1() { return a; } function f2() { - var g = function g() { + function g() { var E; (function(E) { E[E["A"] = 0] = "A"; @@ -37,7 +37,7 @@ function f2() { ]; a[0].x = 1; return a; - }; + } return g(); } function f3(b) { @@ -146,7 +146,11 @@ var A = /*#__PURE__*/ function() { return A; }(); function f6() { - var g = function g() { + var A = function A() { + "use strict"; + _class_call_check(this, A); + }; + function g() { var B = /*#__PURE__*/ function(A) { "use strict"; _inherits(B, A); @@ -175,10 +179,6 @@ function f6() { return x; } return h(); - }; - var A = function A() { - "use strict"; - _class_call_check(this, A); - }; + } return g(); } diff --git a/crates/swc/tests/tsc-references/localTypes2.1.normal.js b/crates/swc/tests/tsc-references/localTypes2.1.normal.js index e63d9faa4eb..617d30c6ffc 100644 --- a/crates/swc/tests/tsc-references/localTypes2.1.normal.js +++ b/crates/swc/tests/tsc-references/localTypes2.1.normal.js @@ -1,7 +1,7 @@ //// [localTypes2.ts] import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; function f1() { - var f = function f() { + function f() { var C = function C(x, y) { "use strict"; _class_call_check(this, C); @@ -9,14 +9,14 @@ function f1() { this.y = y; }; return C; - }; + } var C = f(); var v = new C(10, 20); var x = v.x; var y = v.y; } function f2() { - var f = function f(x) { + function f(x) { var C = function C(y) { "use strict"; _class_call_check(this, C); @@ -24,14 +24,14 @@ function f2() { this.x = x; }; return C; - }; + } var C = f(10); var v = new C(20); var x = v.x; var y = v.y; } function f3() { - var f = function f(x, y) { + function f(x, y) { var C = function C() { "use strict"; _class_call_check(this, C); @@ -39,7 +39,7 @@ function f3() { this.y = y; }; return C; - }; + } var C = f(10, 20); var v = new C(); var x = v.x; diff --git a/crates/swc/tests/tsc-references/localTypes3.1.normal.js b/crates/swc/tests/tsc-references/localTypes3.1.normal.js index 17bf71f28f7..70d282b97f4 100644 --- a/crates/swc/tests/tsc-references/localTypes3.1.normal.js +++ b/crates/swc/tests/tsc-references/localTypes3.1.normal.js @@ -1,7 +1,7 @@ //// [localTypes3.ts] import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; function f1() { - var f = function f() { + function f() { var C = function C(x, y) { "use strict"; _class_call_check(this, C); @@ -9,14 +9,14 @@ function f1() { this.y = y; }; return C; - }; + } var C = f(); var v = new C(10, "hello"); var x = v.x; var y = v.y; } function f2() { - var f = function f(x) { + function f(x) { var C = function C(y) { "use strict"; _class_call_check(this, C); @@ -24,14 +24,14 @@ function f2() { this.x = x; }; return C; - }; + } var C = f(10); var v = new C("hello"); var x = v.x; var y = v.y; } function f3() { - var f = function f(x, y) { + function f(x, y) { var C = function C() { "use strict"; _class_call_check(this, C); @@ -39,7 +39,7 @@ function f3() { this.y = y; }; return C; - }; + } var C = f(10, "hello"); var v = new C(); var x = v.x; diff --git a/crates/swc/tests/tsc-references/localTypes4.1.normal.js b/crates/swc/tests/tsc-references/localTypes4.1.normal.js index 8e019b2407b..af2981ee135 100644 --- a/crates/swc/tests/tsc-references/localTypes4.1.normal.js +++ b/crates/swc/tests/tsc-references/localTypes4.1.normal.js @@ -1,21 +1,21 @@ //// [localTypes4.ts] function f1() { - var f = // Type parameters are in scope in parameters and return types + // Type parameters are in scope in parameters and return types function f(x) { return undefined; - }; + } } function f2() { - var f = // Local types are not in scope in parameters and return types + // Local types are not in scope in parameters and return types function f(x) { return undefined; - }; + } } function f3() { - var f = // Type parameters and top-level local types are in same declaration space + // Type parameters and top-level local types are in same declaration space function f() { return undefined; - }; + } } function f4() { var v; diff --git a/crates/swc/tests/tsc-references/moduleWithStatementsOfEveryKind.1.normal.js b/crates/swc/tests/tsc-references/moduleWithStatementsOfEveryKind.1.normal.js index 99508f123bd..96b72da3cc3 100644 --- a/crates/swc/tests/tsc-references/moduleWithStatementsOfEveryKind.1.normal.js +++ b/crates/swc/tests/tsc-references/moduleWithStatementsOfEveryKind.1.normal.js @@ -4,9 +4,6 @@ import { _ as _inherits } from "@swc/helpers/_/_inherits"; import { _ as _create_super } from "@swc/helpers/_/_create_super"; var A; (function(A) { - var F = function F(s) { - return 2; - }; var A1 = function A() { "use strict"; _class_call_check(this, A); @@ -48,6 +45,9 @@ var A; Color[Color["Red"] = 1] = "Red"; })(Color || (Color = {})); var x = 12; + function F(s) { + return 2; + } var array = null; var fn = function(s) { return "hello " + s; @@ -60,9 +60,6 @@ var A; })(A || (A = {})); var Y; (function(Y) { - var F = function F(s) { - return 2; - }; var A = function A() { "use strict"; _class_call_check(this, A); @@ -108,6 +105,9 @@ var Y; Color[Color["Red"] = 1] = "Red"; })(Color = Y.Color || (Y.Color = {})); Y.x = 12; + function F(s) { + return 2; + } Y.F = F; Y.array = null; Y.fn = function(s) { diff --git a/crates/swc/tests/tsc-references/nonInstantiatedModule.1.normal.js b/crates/swc/tests/tsc-references/nonInstantiatedModule.1.normal.js index 3519a8a1273..be324086920 100644 --- a/crates/swc/tests/tsc-references/nonInstantiatedModule.1.normal.js +++ b/crates/swc/tests/tsc-references/nonInstantiatedModule.1.normal.js @@ -15,12 +15,12 @@ var M2; (function(M2) { var Point; (function(Point) { - var Origin = function Origin() { + function Origin() { return { x: 0, y: 0 }; - }; + } Point.Origin = Origin; })(Point = M2.Point || (M2.Point = {})); })(M2 || (M2 = {})); diff --git a/crates/swc/tests/tsc-references/parameterInitializersForwardReferencing.1.normal.js b/crates/swc/tests/tsc-references/parameterInitializersForwardReferencing.1.normal.js index 8dd7cd705b3..5df2955a634 100644 --- a/crates/swc/tests/tsc-references/parameterInitializersForwardReferencing.1.normal.js +++ b/crates/swc/tests/tsc-references/parameterInitializersForwardReferencing.1.normal.js @@ -21,11 +21,11 @@ function inside() { var _$b; } function outside() { - var inside = function inside() { + var b1; + function inside() { var a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : b1; var b2; - }; - var b1; + } } function defaultArgFunction() { var a = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : function() { diff --git a/crates/swc/tests/tsc-references/parserModule1.1.normal.js b/crates/swc/tests/tsc-references/parserModule1.1.normal.js index 03fbd3889aa..50ae80a27f3 100644 --- a/crates/swc/tests/tsc-references/parserModule1.1.normal.js +++ b/crates/swc/tests/tsc-references/parserModule1.1.normal.js @@ -1,27 +1,27 @@ //// [parserModule1.ts] export var CompilerDiagnostics; (function(CompilerDiagnostics) { - var Alert = function Alert(output) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { if (CompilerDiagnostics.diagnosticWriter) { CompilerDiagnostics.diagnosticWriter.Alert(output); } - }; - var debugPrint = function debugPrint(s) { + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { if (CompilerDiagnostics.debug) { Alert(s); } - }; - var assert = function assert(condition, s) { + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { if (CompilerDiagnostics.debug) { if (!condition) { Alert(s); } } - }; - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - CompilerDiagnostics.Alert = Alert; - CompilerDiagnostics.debugPrint = debugPrint; + } CompilerDiagnostics.assert = assert; })(CompilerDiagnostics || (CompilerDiagnostics = {})); diff --git a/crates/swc/tests/tsc-references/parserModule1.2.minified.js b/crates/swc/tests/tsc-references/parserModule1.2.minified.js index 6ac8b9a339a..3cfb0451257 100644 --- a/crates/swc/tests/tsc-references/parserModule1.2.minified.js +++ b/crates/swc/tests/tsc-references/parserModule1.2.minified.js @@ -1,11 +1,12 @@ //// [parserModule1.ts] -var CompilerDiagnostics, Alert; -var CompilerDiagnostics1; -export { CompilerDiagnostics1 as CompilerDiagnostics }; -CompilerDiagnostics = CompilerDiagnostics1 || (CompilerDiagnostics1 = {}), Alert = function(output) { - CompilerDiagnostics.diagnosticWriter && CompilerDiagnostics.diagnosticWriter.Alert(output); -}, CompilerDiagnostics.debug = !1, CompilerDiagnostics.diagnosticWriter = null, CompilerDiagnostics.analysisPass = 0, CompilerDiagnostics.Alert = Alert, CompilerDiagnostics.debugPrint = function(s) { - CompilerDiagnostics.debug && Alert(s); -}, CompilerDiagnostics.assert = function(condition, s) { - CompilerDiagnostics.debug && !condition && Alert(s); -}; +export var CompilerDiagnostics; +!function(CompilerDiagnostics) { + function Alert(output) { + CompilerDiagnostics.diagnosticWriter && CompilerDiagnostics.diagnosticWriter.Alert(output); + } + CompilerDiagnostics.debug = !1, CompilerDiagnostics.diagnosticWriter = null, CompilerDiagnostics.analysisPass = 0, CompilerDiagnostics.Alert = Alert, CompilerDiagnostics.debugPrint = function(s) { + CompilerDiagnostics.debug && Alert(s); + }, CompilerDiagnostics.assert = function(condition, s) { + CompilerDiagnostics.debug && !condition && Alert(s); + }; +}(CompilerDiagnostics || (CompilerDiagnostics = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource1.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource1.1.normal.js index 8165ff7abe9..97982e6e12e 100644 --- a/crates/swc/tests/tsc-references/parserRealSource1.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource1.1.normal.js @@ -5,82 +5,30 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var timeFunction = function timeFunction(logger, funcDescription, func) { - var start = +new Date(); - var result = func(); - var end = +new Date(); - logger.log(funcDescription + " completed in " + (end - start) + " msec"); - return result; - }; - var stringToLiteral = function stringToLiteral(value, length) { - var result = ""; - var addChar = function(index) { - var ch = value.charCodeAt(index); - switch(ch){ - case 0x09: - result += "\\t"; - break; - case 0x0a: - result += "\\n"; - break; - case 0x0b: - result += "\\v"; - break; - case 0x0c: - result += "\\f"; - break; - case 0x0d: - result += "\\r"; - break; - case 0x22: - result += '\\"'; - break; - case 0x27: - result += "\\'"; - break; - case 0x5c: - result += "\\"; - break; - default: - result += value.charAt(index); - } - }; - var tooLong = value.length > length; - if (tooLong) { - var mid = length >> 1; - for(var i = 0; i < mid; i++)addChar(i); - result += "(...)"; - for(var i = value.length - mid; i < value.length; i++)addChar(i); - } else { - length = value.length; - for(var i = 0; i < length; i++)addChar(i); - } - return result; - }; var CompilerDiagnostics; (function(CompilerDiagnostics) { - var Alert = function Alert(output) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { if (CompilerDiagnostics.diagnosticWriter) { CompilerDiagnostics.diagnosticWriter.Alert(output); } - }; - var debugPrint = function debugPrint(s) { + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { if (CompilerDiagnostics.debug) { Alert(s); } - }; - var assert = function assert(condition, s) { + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { if (CompilerDiagnostics.debug) { if (!condition) { Alert(s); } } - }; - CompilerDiagnostics.debug = false; - CompilerDiagnostics.diagnosticWriter = null; - CompilerDiagnostics.analysisPass = 0; - CompilerDiagnostics.Alert = Alert; - CompilerDiagnostics.debugPrint = debugPrint; + } CompilerDiagnostics.assert = assert; })(CompilerDiagnostics = TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); var NullLogger = /*#__PURE__*/ function() { @@ -169,6 +117,58 @@ var TypeScript; return BufferedLogger; }(); TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function(index) { + var ch = value.charCodeAt(index); + switch(ch){ + case 0x09: + result += "\\t"; + break; + case 0x0a: + result += "\\n"; + break; + case 0x0b: + result += "\\v"; + break; + case 0x0c: + result += "\\f"; + break; + case 0x0d: + result += "\\r"; + break; + case 0x22: + result += '\\"'; + break; + case 0x27: + result += "\\'"; + break; + case 0x5c: + result += "\\"; + break; + default: + result += value.charAt(index); + } + }; + var tooLong = value.length > length; + if (tooLong) { + var mid = length >> 1; + for(var i = 0; i < mid; i++)addChar(i); + result += "(...)"; + for(var i = value.length - mid; i < value.length; i++)addChar(i); + } else { + length = value.length; + for(var i = 0; i < length; i++)addChar(i); + } + return result; + } TypeScript.stringToLiteral = stringToLiteral; })(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource1.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource1.2.minified.js index 54636051638..73b680f03ee 100644 --- a/crates/swc/tests/tsc-references/parserRealSource1.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource1.2.minified.js @@ -2,15 +2,18 @@ // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// -var TypeScript, TypeScript1, CompilerDiagnostics, Alert, NullLogger, LoggerAdapter, BufferedLogger; +var TypeScript, TypeScript1, NullLogger, LoggerAdapter, BufferedLogger; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -CompilerDiagnostics = (TypeScript1 = TypeScript || (TypeScript = {})).CompilerDiagnostics || (TypeScript1.CompilerDiagnostics = {}), Alert = function(output) { - CompilerDiagnostics.diagnosticWriter && CompilerDiagnostics.diagnosticWriter.Alert(output); -}, CompilerDiagnostics.debug = !1, CompilerDiagnostics.diagnosticWriter = null, CompilerDiagnostics.analysisPass = 0, CompilerDiagnostics.Alert = Alert, CompilerDiagnostics.debugPrint = function(s) { - CompilerDiagnostics.debug && Alert(s); -}, CompilerDiagnostics.assert = function(condition, s) { - CompilerDiagnostics.debug && !condition && Alert(s); -}, NullLogger = function() { +!function(CompilerDiagnostics) { + function Alert(output) { + CompilerDiagnostics.diagnosticWriter && CompilerDiagnostics.diagnosticWriter.Alert(output); + } + CompilerDiagnostics.debug = !1, CompilerDiagnostics.diagnosticWriter = null, CompilerDiagnostics.analysisPass = 0, CompilerDiagnostics.Alert = Alert, CompilerDiagnostics.debugPrint = function(s) { + CompilerDiagnostics.debug && Alert(s); + }, CompilerDiagnostics.assert = function(condition, s) { + CompilerDiagnostics.debug && !condition && Alert(s); + }; +}((TypeScript1 = TypeScript || (TypeScript = {})).CompilerDiagnostics || (TypeScript1.CompilerDiagnostics = {})), NullLogger = function() { function NullLogger() { _class_call_check(this, NullLogger); } diff --git a/crates/swc/tests/tsc-references/parserRealSource12.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource12.1.normal.js index b736b924043..1cfa36516e3 100644 --- a/crates/swc/tests/tsc-references/parserRealSource12.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource12.1.normal.js @@ -5,12 +5,6 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var getAstWalkerFactory = function getAstWalkerFactory() { - if (!globalAstWalkerFactory) { - globalAstWalkerFactory = new AstWalkerFactory(); - } - return globalAstWalkerFactory; - }; var AstWalkOptions = /*#__PURE__*/ function() { "use strict"; function AstWalkOptions() { @@ -206,13 +200,20 @@ var TypeScript; }(); TypeScript.AstWalkerFactory = AstWalkerFactory; var globalAstWalkerFactory; + function getAstWalkerFactory() { + if (!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } TypeScript.getAstWalkerFactory = getAstWalkerFactory; var ChildrenWalkers; (function(ChildrenWalkers) { - var walkNone = function walkNone(preAst, parent, walker) { + function walkNone(preAst, parent, walker) { // Nothing to do - }; - var walkListChildren = function walkListChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { var len = preAst.members.length; if (walker.options.reverseSiblings) { for(var i = len - 1; i >= 0; i--){ @@ -227,16 +228,18 @@ var TypeScript; } } } - }; - var walkUnaryExpressionChildren = function walkUnaryExpressionChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { if (preAst.castTerm) { preAst.castTerm = walker.walk(preAst.castTerm, preAst); } if (preAst.operand) { preAst.operand = walker.walk(preAst.operand, preAst); } - }; - var walkBinaryExpressionChildren = function walkBinaryExpressionChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { if (walker.options.reverseSiblings) { if (preAst.operand2) { preAst.operand2 = walker.walk(preAst.operand2, preAst); @@ -252,13 +255,15 @@ var TypeScript; preAst.operand2 = walker.walk(preAst.operand2, preAst); } } - }; - var walkTypeReferenceChildren = function walkTypeReferenceChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { if (preAst.term) { preAst.term = walker.walk(preAst.term, preAst); } - }; - var walkCallExpressionChildren = function walkCallExpressionChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { if (!walker.options.reverseSiblings) { preAst.target = walker.walk(preAst.target, preAst); } @@ -268,8 +273,9 @@ var TypeScript; if (walker.options.reverseSiblings && walker.options.goNextSibling) { preAst.target = walker.walk(preAst.target, preAst); } - }; - var walkTrinaryExpressionChildren = function walkTrinaryExpressionChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { if (preAst.operand1) { preAst.operand1 = walker.walk(preAst.operand1, preAst); } @@ -279,8 +285,9 @@ var TypeScript; if (preAst.operand3 && walker.options.goNextSibling) { preAst.operand3 = walker.walk(preAst.operand3, preAst); } - }; - var walkFuncDeclChildren = function walkFuncDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { if (preAst.name) { preAst.name = walker.walk(preAst.name, preAst); } @@ -293,8 +300,9 @@ var TypeScript; if (preAst.bod && preAst.bod.members.length > 0 && walker.options.goNextSibling) { preAst.bod = walker.walk(preAst.bod, preAst); } - }; - var walkBoundDeclChildren = function walkBoundDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { if (preAst.id) { preAst.id = walker.walk(preAst.id, preAst); } @@ -304,13 +312,15 @@ var TypeScript; if (preAst.typeExpr && walker.options.goNextSibling) { preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); } - }; - var walkReturnStatementChildren = function walkReturnStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { if (preAst.returnExpression) { preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); } - }; - var walkForStatementChildren = function walkForStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { if (preAst.init) { preAst.init = walker.walk(preAst.init, preAst); } @@ -323,8 +333,9 @@ var TypeScript; if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkForInStatementChildren = function walkForInStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { preAst.lval = walker.walk(preAst.lval, preAst); if (walker.options.goNextSibling) { preAst.obj = walker.walk(preAst.obj, preAst); @@ -332,8 +343,9 @@ var TypeScript; if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkIfStatementChildren = function walkIfStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { preAst.cond = walker.walk(preAst.cond, preAst); if (preAst.thenBod && walker.options.goNextSibling) { preAst.thenBod = walker.walk(preAst.thenBod, preAst); @@ -341,84 +353,97 @@ var TypeScript; if (preAst.elseBod && walker.options.goNextSibling) { preAst.elseBod = walker.walk(preAst.elseBod, preAst); } - }; - var walkWhileStatementChildren = function walkWhileStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { preAst.cond = walker.walk(preAst.cond, preAst); if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkDoWhileStatementChildren = function walkDoWhileStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { preAst.cond = walker.walk(preAst.cond, preAst); if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkBlockChildren = function walkBlockChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { if (preAst.statements) { preAst.statements = walker.walk(preAst.statements, preAst); } - }; - var walkCaseStatementChildren = function walkCaseStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { if (preAst.expr) { preAst.expr = walker.walk(preAst.expr, preAst); } if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkSwitchStatementChildren = function walkSwitchStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { if (preAst.val) { preAst.val = walker.walk(preAst.val, preAst); } if (preAst.caseList && walker.options.goNextSibling) { preAst.caseList = walker.walk(preAst.caseList, preAst); } - }; - var walkTryChildren = function walkTryChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { if (preAst.body) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkTryCatchChildren = function walkTryCatchChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { if (preAst.tryNode) { preAst.tryNode = walker.walk(preAst.tryNode, preAst); } if (preAst.catchNode && walker.options.goNextSibling) { preAst.catchNode = walker.walk(preAst.catchNode, preAst); } - }; - var walkTryFinallyChildren = function walkTryFinallyChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { if (preAst.tryNode) { preAst.tryNode = walker.walk(preAst.tryNode, preAst); } if (preAst.finallyNode && walker.options.goNextSibling) { preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); } - }; - var walkFinallyChildren = function walkFinallyChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { if (preAst.body) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkCatchChildren = function walkCatchChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { if (preAst.param) { preAst.param = walker.walk(preAst.param, preAst); } if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkRecordChildren = function walkRecordChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { preAst.name = walker.walk(preAst.name, preAst); if (walker.options.goNextSibling && preAst.members) { preAst.members = walker.walk(preAst.members, preAst); } - }; - var walkNamedTypeChildren = function walkNamedTypeChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { walkRecordChildren(preAst, parent, walker); - }; - var walkClassDeclChildren = function walkClassDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { walkNamedTypeChildren(preAst, parent, walker); if (walker.options.goNextSibling && preAst.extendsList) { preAst.extendsList = walker.walk(preAst.extendsList, preAst); @@ -426,13 +451,15 @@ var TypeScript; if (walker.options.goNextSibling && preAst.implementsList) { preAst.implementsList = walker.walk(preAst.implementsList, preAst); } - }; - var walkScriptChildren = function walkScriptChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { if (preAst.bod) { preAst.bod = walker.walk(preAst.bod, preAst); } - }; - var walkTypeDeclChildren = function walkTypeDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { walkNamedTypeChildren(preAst, parent, walker); // walked arguments as part of members if (walker.options.goNextSibling && preAst.extendsList) { @@ -441,67 +468,40 @@ var TypeScript; if (walker.options.goNextSibling && preAst.implementsList) { preAst.implementsList = walker.walk(preAst.implementsList, preAst); } - }; - var walkModuleDeclChildren = function walkModuleDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { walkRecordChildren(preAst, parent, walker); - }; - var walkImportDeclChildren = function walkImportDeclChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { if (preAst.id) { preAst.id = walker.walk(preAst.id, preAst); } if (preAst.alias) { preAst.alias = walker.walk(preAst.alias, preAst); } - }; - var walkWithStatementChildren = function walkWithStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { if (preAst.expr) { preAst.expr = walker.walk(preAst.expr, preAst); } if (preAst.body && walker.options.goNextSibling) { preAst.body = walker.walk(preAst.body, preAst); } - }; - var walkLabelChildren = function walkLabelChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { //TODO: Walk "id"? - }; - var walkLabeledStatementChildren = function walkLabeledStatementChildren(preAst, parent, walker) { + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { preAst.labels = walker.walk(preAst.labels, preAst); if (walker.options.goNextSibling) { preAst.stmt = walker.walk(preAst.stmt, preAst); } - }; - ChildrenWalkers.walkNone = walkNone; - ChildrenWalkers.walkListChildren = walkListChildren; - ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; - ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; - ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; - ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; - ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; - ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; - ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; - ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; - ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; - ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; - ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; - ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; - ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; - ChildrenWalkers.walkBlockChildren = walkBlockChildren; - ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; - ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; - ChildrenWalkers.walkTryChildren = walkTryChildren; - ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; - ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; - ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; - ChildrenWalkers.walkCatchChildren = walkCatchChildren; - ChildrenWalkers.walkRecordChildren = walkRecordChildren; - ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; - ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; - ChildrenWalkers.walkScriptChildren = walkScriptChildren; - ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; - ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; - ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; - ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; - ChildrenWalkers.walkLabelChildren = walkLabelChildren; + } ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; })(ChildrenWalkers || (ChildrenWalkers = {})); })(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource12.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource12.2.minified.js index 809e1472bda..8a9041b8379 100644 --- a/crates/swc/tests/tsc-references/parserRealSource12.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource12.2.minified.js @@ -2,7 +2,7 @@ // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// -var TypeScript, TypeScript1, globalAstWalkerFactory, ChildrenWalkers, AstWalkOptions, AstWalker, AstWalkerFactory, ChildrenWalkers1, walkRecordChildren, walkNamedTypeChildren; +var TypeScript, TypeScript1, globalAstWalkerFactory, ChildrenWalkers, AstWalkOptions, AstWalker, AstWalkerFactory; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; TypeScript1 = TypeScript || (TypeScript = {}), AstWalkOptions = function() { function AstWalkOptions() { @@ -46,72 +46,75 @@ TypeScript1 = TypeScript || (TypeScript = {}), AstWalkOptions = function() { }, AstWalkerFactory; }(), TypeScript1.AstWalkerFactory = AstWalkerFactory, TypeScript1.getAstWalkerFactory = function() { return globalAstWalkerFactory || (globalAstWalkerFactory = new AstWalkerFactory()), globalAstWalkerFactory; -}, ChildrenWalkers1 = ChildrenWalkers || (ChildrenWalkers = {}), walkRecordChildren = function(preAst, parent, walker) { - preAst.name = walker.walk(preAst.name, preAst), walker.options.goNextSibling && preAst.members && (preAst.members = walker.walk(preAst.members, preAst)); -}, walkNamedTypeChildren = function(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); -}, ChildrenWalkers1.walkNone = function(preAst, parent, walker) { -// Nothing to do -}, ChildrenWalkers1.walkListChildren = function(preAst, parent, walker) { - var len = preAst.members.length; - if (walker.options.reverseSiblings) for(var i = len - 1; i >= 0; i--)walker.options.goNextSibling && (preAst.members[i] = walker.walk(preAst.members[i], preAst)); - else for(var i = 0; i < len; i++)walker.options.goNextSibling && (preAst.members[i] = walker.walk(preAst.members[i], preAst)); -}, ChildrenWalkers1.walkUnaryExpressionChildren = function(preAst, parent, walker) { - preAst.castTerm && (preAst.castTerm = walker.walk(preAst.castTerm, preAst)), preAst.operand && (preAst.operand = walker.walk(preAst.operand, preAst)); -}, ChildrenWalkers1.walkBinaryExpressionChildren = function(preAst, parent, walker) { - walker.options.reverseSiblings ? (preAst.operand2 && (preAst.operand2 = walker.walk(preAst.operand2, preAst)), preAst.operand1 && walker.options.goNextSibling && (preAst.operand1 = walker.walk(preAst.operand1, preAst))) : (preAst.operand1 && (preAst.operand1 = walker.walk(preAst.operand1, preAst)), preAst.operand2 && walker.options.goNextSibling && (preAst.operand2 = walker.walk(preAst.operand2, preAst))); -}, ChildrenWalkers1.walkTypeReferenceChildren = function(preAst, parent, walker) { - preAst.term && (preAst.term = walker.walk(preAst.term, preAst)); -}, ChildrenWalkers1.walkCallExpressionChildren = function(preAst, parent, walker) { - walker.options.reverseSiblings || (preAst.target = walker.walk(preAst.target, preAst)), preAst.arguments && walker.options.goNextSibling && (preAst.arguments = walker.walk(preAst.arguments, preAst)), walker.options.reverseSiblings && walker.options.goNextSibling && (preAst.target = walker.walk(preAst.target, preAst)); -}, ChildrenWalkers1.walkTrinaryExpressionChildren = function(preAst, parent, walker) { - preAst.operand1 && (preAst.operand1 = walker.walk(preAst.operand1, preAst)), preAst.operand2 && walker.options.goNextSibling && (preAst.operand2 = walker.walk(preAst.operand2, preAst)), preAst.operand3 && walker.options.goNextSibling && (preAst.operand3 = walker.walk(preAst.operand3, preAst)); -}, ChildrenWalkers1.walkFuncDeclChildren = function(preAst, parent, walker) { - preAst.name && (preAst.name = walker.walk(preAst.name, preAst)), preAst.arguments && preAst.arguments.members.length > 0 && walker.options.goNextSibling && (preAst.arguments = walker.walk(preAst.arguments, preAst)), preAst.returnTypeAnnotation && walker.options.goNextSibling && (preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst)), preAst.bod && preAst.bod.members.length > 0 && walker.options.goNextSibling && (preAst.bod = walker.walk(preAst.bod, preAst)); -}, ChildrenWalkers1.walkBoundDeclChildren = function(preAst, parent, walker) { - preAst.id && (preAst.id = walker.walk(preAst.id, preAst)), preAst.init && (preAst.init = walker.walk(preAst.init, preAst)), preAst.typeExpr && walker.options.goNextSibling && (preAst.typeExpr = walker.walk(preAst.typeExpr, preAst)); -}, ChildrenWalkers1.walkReturnStatementChildren = function(preAst, parent, walker) { - preAst.returnExpression && (preAst.returnExpression = walker.walk(preAst.returnExpression, preAst)); -}, ChildrenWalkers1.walkForStatementChildren = function(preAst, parent, walker) { - preAst.init && (preAst.init = walker.walk(preAst.init, preAst)), preAst.cond && walker.options.goNextSibling && (preAst.cond = walker.walk(preAst.cond, preAst)), preAst.incr && walker.options.goNextSibling && (preAst.incr = walker.walk(preAst.incr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkForInStatementChildren = function(preAst, parent, walker) { - preAst.lval = walker.walk(preAst.lval, preAst), walker.options.goNextSibling && (preAst.obj = walker.walk(preAst.obj, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkIfStatementChildren = function(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst), preAst.thenBod && walker.options.goNextSibling && (preAst.thenBod = walker.walk(preAst.thenBod, preAst)), preAst.elseBod && walker.options.goNextSibling && (preAst.elseBod = walker.walk(preAst.elseBod, preAst)); -}, ChildrenWalkers1.walkWhileStatementChildren = function(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkDoWhileStatementChildren = function(preAst, parent, walker) { - preAst.cond = walker.walk(preAst.cond, preAst), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkBlockChildren = function(preAst, parent, walker) { - preAst.statements && (preAst.statements = walker.walk(preAst.statements, preAst)); -}, ChildrenWalkers1.walkCaseStatementChildren = function(preAst, parent, walker) { - preAst.expr && (preAst.expr = walker.walk(preAst.expr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkSwitchStatementChildren = function(preAst, parent, walker) { - preAst.val && (preAst.val = walker.walk(preAst.val, preAst)), preAst.caseList && walker.options.goNextSibling && (preAst.caseList = walker.walk(preAst.caseList, preAst)); -}, ChildrenWalkers1.walkTryChildren = function(preAst, parent, walker) { - preAst.body && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkTryCatchChildren = function(preAst, parent, walker) { - preAst.tryNode && (preAst.tryNode = walker.walk(preAst.tryNode, preAst)), preAst.catchNode && walker.options.goNextSibling && (preAst.catchNode = walker.walk(preAst.catchNode, preAst)); -}, ChildrenWalkers1.walkTryFinallyChildren = function(preAst, parent, walker) { - preAst.tryNode && (preAst.tryNode = walker.walk(preAst.tryNode, preAst)), preAst.finallyNode && walker.options.goNextSibling && (preAst.finallyNode = walker.walk(preAst.finallyNode, preAst)); -}, ChildrenWalkers1.walkFinallyChildren = function(preAst, parent, walker) { - preAst.body && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkCatchChildren = function(preAst, parent, walker) { - preAst.param && (preAst.param = walker.walk(preAst.param, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkRecordChildren = walkRecordChildren, ChildrenWalkers1.walkNamedTypeChildren = walkNamedTypeChildren, ChildrenWalkers1.walkClassDeclChildren = function(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker), walker.options.goNextSibling && preAst.extendsList && (preAst.extendsList = walker.walk(preAst.extendsList, preAst)), walker.options.goNextSibling && preAst.implementsList && (preAst.implementsList = walker.walk(preAst.implementsList, preAst)); -}, ChildrenWalkers1.walkScriptChildren = function(preAst, parent, walker) { - preAst.bod && (preAst.bod = walker.walk(preAst.bod, preAst)); -}, ChildrenWalkers1.walkTypeDeclChildren = function(preAst, parent, walker) { - walkNamedTypeChildren(preAst, parent, walker), walker.options.goNextSibling && preAst.extendsList && (preAst.extendsList = walker.walk(preAst.extendsList, preAst)), walker.options.goNextSibling && preAst.implementsList && (preAst.implementsList = walker.walk(preAst.implementsList, preAst)); -}, ChildrenWalkers1.walkModuleDeclChildren = function(preAst, parent, walker) { - walkRecordChildren(preAst, parent, walker); -}, ChildrenWalkers1.walkImportDeclChildren = function(preAst, parent, walker) { - preAst.id && (preAst.id = walker.walk(preAst.id, preAst)), preAst.alias && (preAst.alias = walker.walk(preAst.alias, preAst)); -}, ChildrenWalkers1.walkWithStatementChildren = function(preAst, parent, walker) { - preAst.expr && (preAst.expr = walker.walk(preAst.expr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); -}, ChildrenWalkers1.walkLabelChildren = function(preAst, parent, walker) { -//TODO: Walk "id"? -}, ChildrenWalkers1.walkLabeledStatementChildren = function(preAst, parent, walker) { - preAst.labels = walker.walk(preAst.labels, preAst), walker.options.goNextSibling && (preAst.stmt = walker.walk(preAst.stmt, preAst)); -}; +}, function(ChildrenWalkers) { + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst), walker.options.goNextSibling && preAst.members && (preAst.members = walker.walk(preAst.members, preAst)); + } + ChildrenWalkers.walkNone = function(preAst, parent, walker) { + // Nothing to do + }, ChildrenWalkers.walkListChildren = function(preAst, parent, walker) { + var len = preAst.members.length; + if (walker.options.reverseSiblings) for(var i = len - 1; i >= 0; i--)walker.options.goNextSibling && (preAst.members[i] = walker.walk(preAst.members[i], preAst)); + else for(var i = 0; i < len; i++)walker.options.goNextSibling && (preAst.members[i] = walker.walk(preAst.members[i], preAst)); + }, ChildrenWalkers.walkUnaryExpressionChildren = function(preAst, parent, walker) { + preAst.castTerm && (preAst.castTerm = walker.walk(preAst.castTerm, preAst)), preAst.operand && (preAst.operand = walker.walk(preAst.operand, preAst)); + }, ChildrenWalkers.walkBinaryExpressionChildren = function(preAst, parent, walker) { + walker.options.reverseSiblings ? (preAst.operand2 && (preAst.operand2 = walker.walk(preAst.operand2, preAst)), preAst.operand1 && walker.options.goNextSibling && (preAst.operand1 = walker.walk(preAst.operand1, preAst))) : (preAst.operand1 && (preAst.operand1 = walker.walk(preAst.operand1, preAst)), preAst.operand2 && walker.options.goNextSibling && (preAst.operand2 = walker.walk(preAst.operand2, preAst))); + }, ChildrenWalkers.walkTypeReferenceChildren = function(preAst, parent, walker) { + preAst.term && (preAst.term = walker.walk(preAst.term, preAst)); + }, ChildrenWalkers.walkCallExpressionChildren = function(preAst, parent, walker) { + walker.options.reverseSiblings || (preAst.target = walker.walk(preAst.target, preAst)), preAst.arguments && walker.options.goNextSibling && (preAst.arguments = walker.walk(preAst.arguments, preAst)), walker.options.reverseSiblings && walker.options.goNextSibling && (preAst.target = walker.walk(preAst.target, preAst)); + }, ChildrenWalkers.walkTrinaryExpressionChildren = function(preAst, parent, walker) { + preAst.operand1 && (preAst.operand1 = walker.walk(preAst.operand1, preAst)), preAst.operand2 && walker.options.goNextSibling && (preAst.operand2 = walker.walk(preAst.operand2, preAst)), preAst.operand3 && walker.options.goNextSibling && (preAst.operand3 = walker.walk(preAst.operand3, preAst)); + }, ChildrenWalkers.walkFuncDeclChildren = function(preAst, parent, walker) { + preAst.name && (preAst.name = walker.walk(preAst.name, preAst)), preAst.arguments && preAst.arguments.members.length > 0 && walker.options.goNextSibling && (preAst.arguments = walker.walk(preAst.arguments, preAst)), preAst.returnTypeAnnotation && walker.options.goNextSibling && (preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst)), preAst.bod && preAst.bod.members.length > 0 && walker.options.goNextSibling && (preAst.bod = walker.walk(preAst.bod, preAst)); + }, ChildrenWalkers.walkBoundDeclChildren = function(preAst, parent, walker) { + preAst.id && (preAst.id = walker.walk(preAst.id, preAst)), preAst.init && (preAst.init = walker.walk(preAst.init, preAst)), preAst.typeExpr && walker.options.goNextSibling && (preAst.typeExpr = walker.walk(preAst.typeExpr, preAst)); + }, ChildrenWalkers.walkReturnStatementChildren = function(preAst, parent, walker) { + preAst.returnExpression && (preAst.returnExpression = walker.walk(preAst.returnExpression, preAst)); + }, ChildrenWalkers.walkForStatementChildren = function(preAst, parent, walker) { + preAst.init && (preAst.init = walker.walk(preAst.init, preAst)), preAst.cond && walker.options.goNextSibling && (preAst.cond = walker.walk(preAst.cond, preAst)), preAst.incr && walker.options.goNextSibling && (preAst.incr = walker.walk(preAst.incr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkForInStatementChildren = function(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst), walker.options.goNextSibling && (preAst.obj = walker.walk(preAst.obj, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkIfStatementChildren = function(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst), preAst.thenBod && walker.options.goNextSibling && (preAst.thenBod = walker.walk(preAst.thenBod, preAst)), preAst.elseBod && walker.options.goNextSibling && (preAst.elseBod = walker.walk(preAst.elseBod, preAst)); + }, ChildrenWalkers.walkWhileStatementChildren = function(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkDoWhileStatementChildren = function(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkBlockChildren = function(preAst, parent, walker) { + preAst.statements && (preAst.statements = walker.walk(preAst.statements, preAst)); + }, ChildrenWalkers.walkCaseStatementChildren = function(preAst, parent, walker) { + preAst.expr && (preAst.expr = walker.walk(preAst.expr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkSwitchStatementChildren = function(preAst, parent, walker) { + preAst.val && (preAst.val = walker.walk(preAst.val, preAst)), preAst.caseList && walker.options.goNextSibling && (preAst.caseList = walker.walk(preAst.caseList, preAst)); + }, ChildrenWalkers.walkTryChildren = function(preAst, parent, walker) { + preAst.body && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkTryCatchChildren = function(preAst, parent, walker) { + preAst.tryNode && (preAst.tryNode = walker.walk(preAst.tryNode, preAst)), preAst.catchNode && walker.options.goNextSibling && (preAst.catchNode = walker.walk(preAst.catchNode, preAst)); + }, ChildrenWalkers.walkTryFinallyChildren = function(preAst, parent, walker) { + preAst.tryNode && (preAst.tryNode = walker.walk(preAst.tryNode, preAst)), preAst.finallyNode && walker.options.goNextSibling && (preAst.finallyNode = walker.walk(preAst.finallyNode, preAst)); + }, ChildrenWalkers.walkFinallyChildren = function(preAst, parent, walker) { + preAst.body && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkCatchChildren = function(preAst, parent, walker) { + preAst.param && (preAst.param = walker.walk(preAst.param, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkRecordChildren = walkRecordChildren, ChildrenWalkers.walkNamedTypeChildren = function(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + }, ChildrenWalkers.walkClassDeclChildren = function(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker), walker.options.goNextSibling && preAst.extendsList && (preAst.extendsList = walker.walk(preAst.extendsList, preAst)), walker.options.goNextSibling && preAst.implementsList && (preAst.implementsList = walker.walk(preAst.implementsList, preAst)); + }, ChildrenWalkers.walkScriptChildren = function(preAst, parent, walker) { + preAst.bod && (preAst.bod = walker.walk(preAst.bod, preAst)); + }, ChildrenWalkers.walkTypeDeclChildren = function(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker), walker.options.goNextSibling && preAst.extendsList && (preAst.extendsList = walker.walk(preAst.extendsList, preAst)), walker.options.goNextSibling && preAst.implementsList && (preAst.implementsList = walker.walk(preAst.implementsList, preAst)); + }, ChildrenWalkers.walkModuleDeclChildren = function(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + }, ChildrenWalkers.walkImportDeclChildren = function(preAst, parent, walker) { + preAst.id && (preAst.id = walker.walk(preAst.id, preAst)), preAst.alias && (preAst.alias = walker.walk(preAst.alias, preAst)); + }, ChildrenWalkers.walkWithStatementChildren = function(preAst, parent, walker) { + preAst.expr && (preAst.expr = walker.walk(preAst.expr, preAst)), preAst.body && walker.options.goNextSibling && (preAst.body = walker.walk(preAst.body, preAst)); + }, ChildrenWalkers.walkLabelChildren = function(preAst, parent, walker) { + //TODO: Walk "id"? + }, ChildrenWalkers.walkLabeledStatementChildren = function(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst), walker.options.goNextSibling && (preAst.stmt = walker.walk(preAst.stmt, preAst)); + }; +}(ChildrenWalkers || (ChildrenWalkers = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource14.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource14.1.normal.js index 2efaa05e44b..cfb8e99761e 100644 --- a/crates/swc/tests/tsc-references/parserRealSource14.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource14.1.normal.js @@ -5,111 +5,17 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var lastOf = function lastOf(items) { + function lastOf(items) { return items === null || items.length === 0 ? null : items[items.length - 1]; - }; - var max = function max(a, b) { - return a >= b ? a : b; - }; - var min = function min(a, b) { - return a <= b ? a : b; - }; - var isValidAstNode = function isValidAstNode(ast) { - if (ast === null) return false; - if (ast.minChar === -1 || ast.limChar === -1) return false; - return true; - }; - var getAstPathToPosition = function getAstPathToPosition(script, pos) { - var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; - var lookInComments = function(comments) { - if (comments && comments.length > 0) { - for(var i = 0; i < comments.length; i++){ - var minChar = comments[i].minChar; - var limChar = comments[i].limChar; - if (!comments[i].isBlockComment) { - limChar++; // For single line comments, include 1 more character (for the newline) - } - if (pos >= minChar && pos < limChar) { - ctx.path.push(comments[i]); - } - } - } - }; - var pre = function pre(cur, parent, walker) { - if (isValidAstNode(cur)) { - // Add "cur" to the stack if it contains our position - // For "identifier" nodes, we need a special case: A position equal to "limChar" is - // valid, since the position corresponds to a caret position (in between characters) - // For example: - // bar - // 0123 - // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid - var inclusive = hasFlag(options, 1) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; // Special "EOF" case - var minChar = cur.minChar; - var limChar = cur.limChar + (inclusive ? 1 : 0); - if (pos >= minChar && pos < limChar) { - // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better - // than top of the stack. - var previous = ctx.path.ast(); - if (previous == null || cur.minChar >= previous.minChar && cur.limChar <= previous.limChar) { - ctx.path.push(cur); - } else { - //logger.log("TODO: Ignoring node because minChar, limChar not better than previous node in stack"); - } - } - // The AST walker skips comments, but we might be in one, so check the pre/post comments for this node manually - if (pos < limChar) { - lookInComments(cur.preComments); - } - if (pos >= minChar) { - lookInComments(cur.postComments); - } - if (!hasFlag(options, 2)) { - // Don't go further down the tree if pos is outside of [minChar, limChar] - walker.options.goChildren = minChar <= pos && pos <= limChar; - } - } - return cur; - }; - var ctx = new AstPathContext(); - TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); - return ctx.path; - }; - var getTokenizationOffset = function getTokenizationOffset(script, position) { - var bestOffset = 0; - var pre = function(cur, parent, walker) { - if (TypeScript.isValidAstNode(cur)) { - // Did we find a closer offset? - if (cur.minChar <= position) { - bestOffset = max(bestOffset, cur.minChar); - } - // Stop the walk if this node is not related to "minChar" - if (cur.minChar > position || cur.limChar < bestOffset) { - walker.options.goChildren = false; - } - } - return cur; - }; - TypeScript.getAstWalkerFactory().walk(script, pre); - return bestOffset; - }; - var walkAST = function walkAST(ast, callback) { - var pre = function pre(cur, parent, walker) { - var path = walker.state; - path.push(cur); - callback(path, walker); - return cur; - }; - var post = function post(cur, parent, walker) { - var path = walker.state; - path.pop(); - return cur; - }; - var path = new AstPath(); - TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); - }; + } TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } TypeScript.min = min; var AstPath = /*#__PURE__*/ function() { "use strict"; @@ -335,6 +241,11 @@ var TypeScript; // This is helpful as our tree don't have parents. // TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if (ast === null) return false; + if (ast.minChar === -1 || ast.limChar === -1) return false; + return true; + } TypeScript.isValidAstNode = isValidAstNode; var AstPathContext = function AstPathContext() { "use strict"; @@ -355,15 +266,104 @@ var TypeScript; //TODO: It would be nice to be able to get rid of this. GetAstPathOptions[GetAstPathOptions["DontPruneSearchBasedOnPosition"] = 2] = "DontPruneSearchBasedOnPosition"; })(GetAstPathOptions = TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + function getAstPathToPosition(script, pos) { + var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; + var lookInComments = function(comments) { + if (comments && comments.length > 0) { + for(var i = 0; i < comments.length; i++){ + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if (!comments[i].isBlockComment) { + limChar++; // For single line comments, include 1 more character (for the newline) + } + if (pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function pre(cur, parent, walker) { + if (isValidAstNode(cur)) { + // Add "cur" to the stack if it contains our position + // For "identifier" nodes, we need a special case: A position equal to "limChar" is + // valid, since the position corresponds to a caret position (in between characters) + // For example: + // bar + // 0123 + // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid + var inclusive = hasFlag(options, 1) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; // Special "EOF" case + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better + // than top of the stack. + var previous = ctx.path.ast(); + if (previous == null || cur.minChar >= previous.minChar && cur.limChar <= previous.limChar) { + ctx.path.push(cur); + } else { + //logger.log("TODO: Ignoring node because minChar, limChar not better than previous node in stack"); + } + } + // The AST walker skips comments, but we might be in one, so check the pre/post comments for this node manually + if (pos < limChar) { + lookInComments(cur.preComments); + } + if (pos >= minChar) { + lookInComments(cur.postComments); + } + if (!hasFlag(options, 2)) { + // Don't go further down the tree if pos is outside of [minChar, limChar] + walker.options.goChildren = minChar <= pos && pos <= limChar; + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } /// /// Return the stack of AST nodes containing "position" /// TypeScript.getAstPathToPosition = getAstPathToPosition; + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function(cur, parent, walker) { + if (TypeScript.isValidAstNode(cur)) { + // Did we find a closer offset? + if (cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + // Stop the walk if this node is not related to "minChar" + if (cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } // // Find a source text offset that is safe for lexing tokens at the given position. // This is used when "position" might be inside a comment or string, etc. // TypeScript.getTokenizationOffset = getTokenizationOffset; + function walkAST(ast, callback) { + var pre = function pre(cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function post(cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } /// /// Simple function to Walk an AST using a simple callback function. /// diff --git a/crates/swc/tests/tsc-references/parserRealSource14.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource14.2.minified.js index 49169e95819..a90525b17ea 100644 --- a/crates/swc/tests/tsc-references/parserRealSource14.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource14.2.minified.js @@ -2,197 +2,206 @@ // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// -var TypeScript, TypeScript1, lastOf, max, isValidAstNode, AstPath, AstPathContext, GetAstPathOptions; +var TypeScript; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -TypeScript1 = TypeScript || (TypeScript = {}), lastOf = function(items) { - return null === items || 0 === items.length ? null : items[items.length - 1]; -}, max = function(a, b) { - return a >= b ? a : b; -}, isValidAstNode = function(ast) { - return null !== ast && -1 !== ast.minChar && -1 !== ast.limChar; -}, TypeScript1.lastOf = lastOf, TypeScript1.max = max, TypeScript1.min = function(a, b) { - return a <= b ? a : b; -}, AstPath = function() { - function AstPath() { - _class_call_check(this, AstPath), this.asts = [], this.top = -1; +!function(TypeScript) { + function lastOf(items) { + return null === items || 0 === items.length ? null : items[items.length - 1]; } - var _proto = AstPath.prototype; - return _proto.clone = function() { - var clone = new AstPath(); - return clone.asts = this.asts.map(function(value) { - return value; - }), clone.top = this.top, clone; - }, _proto.pop = function() { - var head = this.ast(); - for(this.up(); this.asts.length > this.count();)this.asts.pop(); - return head; - }, _proto.push = function(ast) { - for(; this.asts.length > this.count();)this.asts.pop(); - this.top = this.asts.length, this.asts.push(ast); - }, _proto.up = function() { - if (this.top <= -1) throw Error("Invalid call to 'up'"); - this.top--; - }, _proto.down = function() { - if (this.top == this.ast.length - 1) throw Error("Invalid call to 'down'"); - this.top++; - }, _proto.nodeType = function() { - return null == this.ast() ? TypeScript1.NodeType.None : this.ast().nodeType; - }, _proto.ast = function() { - return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); - }, _proto.parent = function() { - return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); - }, _proto.count = function() { - return this.top + 1; - }, _proto.get = function(index) { - return this.asts[index]; - }, _proto.isNameOfClass = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.ClassDeclaration && this.parent().name === this.ast(); - }, _proto.isNameOfInterface = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.InterfaceDeclaration && this.parent().name === this.ast(); - }, _proto.isNameOfArgument = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.ArgDecl && this.parent().id === this.ast(); - }, _proto.isNameOfVariable = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.VarDecl && this.parent().id === this.ast(); - }, _proto.isNameOfModule = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.ModuleDeclaration && this.parent().name === this.ast(); - }, _proto.isNameOfFunction = function() { - return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript1.NodeType.Name && this.parent().nodeType === TypeScript1.NodeType.FuncDecl && this.parent().name === this.ast(); - }, _proto.isChildOfScript = function() { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.Script; - }, _proto.isChildOfModule = function() { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.ModuleDeclaration; - }, _proto.isChildOfClass = function() { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.ClassDeclaration; - }, _proto.isArgumentOfClassConstructor = function() { - var ast = lastOf(this.asts); - return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript1.NodeType.ClassDeclaration && this.asts[this.top - 2].isConstructor && this.asts[this.top - 2].arguments === this.asts[this.top - 1] && this.asts[this.top - 4].constructorDecl === this.asts[this.top - 2]; - }, _proto.isChildOfInterface = function() { - var ast = lastOf(this.asts); - return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.InterfaceDeclaration; - }, _proto.isTopLevelImplicitModule = function() { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript1.NodeType.ModuleDeclaration && TypeScript1.hasFlag(this.asts[this.top].modFlags, TypeScript1.ModuleFlags.IsWholeFile); - }, _proto.isBodyOfTopLevelImplicitModule = function() { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0] && TypeScript1.hasFlag(this.asts[this.top - 1].modFlags, TypeScript1.ModuleFlags.IsWholeFile); - }, _proto.isBodyOfScript = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Script && this.asts[this.top - 1].bod == this.asts[this.top - 0]; - }, _proto.isBodyOfSwitch = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Switch && this.asts[this.top - 1].caseList == this.asts[this.top - 0]; - }, _proto.isBodyOfModule = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; - }, _proto.isBodyOfClass = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ClassDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; - }, _proto.isBodyOfFunction = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.FuncDecl && this.asts[this.top - 1].bod == this.asts[this.top - 0]; - }, _proto.isBodyOfInterface = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.InterfaceDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; - }, _proto.isBodyOfBlock = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Block && this.asts[this.top - 1].statements == this.asts[this.top - 0]; - }, _proto.isBodyOfFor = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.For && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfCase = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Case && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfTry = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Try && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfCatch = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Catch && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfDoWhile = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.DoWhile && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfWhile = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.While && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfForIn = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ForIn && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfWith = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.With && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isBodyOfFinally = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Finally && this.asts[this.top - 1].body == this.asts[this.top - 0]; - }, _proto.isCaseOfSwitch = function() { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1]; - }, _proto.isDefaultCaseOfSwitch = function() { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1] && this.asts[this.top - 2].defaultCase == this.asts[this.top - 0]; - }, _proto.isListOfObjectLit = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; - }, _proto.isBodyOfObjectLit = function() { - return this.isListOfObjectLit(); - }, _proto.isEmptyListOfObjectLit = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0] && 0 == this.asts[this.top - 0].members.length; - }, _proto.isMemberOfObjectLit = function() { - return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.Member && this.asts[this.top - 2].operand == this.asts[this.top - 1]; - }, _proto.isNameOfMemberOfObjectLit = function() { - return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript1.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.Name && this.asts[this.top - 3].operand == this.asts[this.top - 2]; - }, _proto.isListOfArrayLit = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; - }, _proto.isTargetOfMember = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Member && this.asts[this.top - 1].operand1 === this.asts[this.top - 0]; - }, _proto.isMemberOfMember = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Member && this.asts[this.top - 1].operand2 === this.asts[this.top - 0]; - }, _proto.isItemOfList = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List; - //(this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; - }, _proto.isThenOfIf = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.If && this.asts[this.top - 1].thenBod == this.asts[this.top - 0]; - }, _proto.isElseOfIf = function() { - return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.If && this.asts[this.top - 1].elseBod == this.asts[this.top - 0]; - }, _proto.isBodyOfDefaultCase = function() { - return this.isBodyOfCase(); - }, _proto.isSingleStatementList = function() { - return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript1.NodeType.List && 1 === this.asts[this.top].members.length; - }, _proto.isArgumentListOfFunction = function() { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.FuncDecl && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; - }, _proto.isArgumentOfFunction = function() { - return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript1.NodeType.FuncDecl && this.asts[this.top - 2].arguments === this.asts[this.top - 1]; - }, _proto.isArgumentListOfCall = function() { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.Call && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; - }, _proto.isArgumentListOfNew = function() { - return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript1.NodeType.New && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; - }, _proto.isSynthesizedBlock = function() { - return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript1.NodeType.Block && !1 === this.asts[this.top - 0].isStatementBlock; - }, AstPath.reverseIndexOf = function(items, index) { - return null === items || items.length <= index ? null : items[items.length - index - 1]; - }, AstPath; -}(), TypeScript1.AstPath = AstPath, TypeScript1.isValidAstNode = isValidAstNode, AstPathContext = function AstPathContext() { - _class_call_check(this, AstPathContext), this.path = new TypeScript1.AstPath(); -}, TypeScript1.AstPathContext = AstPathContext, (GetAstPathOptions = TypeScript1.GetAstPathOptions || (TypeScript1.GetAstPathOptions = {}))[GetAstPathOptions.Default = 0] = "Default", GetAstPathOptions[GetAstPathOptions.EdgeInclusive = 1] = "EdgeInclusive", GetAstPathOptions[GetAstPathOptions.DontPruneSearchBasedOnPosition = 2] = "DontPruneSearchBasedOnPosition", TypeScript1.getAstPathToPosition = function(script, pos) { - var options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0, lookInComments = function(comments) { - if (comments && comments.length > 0) for(var i = 0; i < comments.length; i++){ - var minChar = comments[i].minChar, limChar = comments[i].limChar; - !comments[i].isBlockComment && limChar++, pos >= minChar && pos < limChar && ctx.path.push(comments[i]); + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.lastOf = lastOf, TypeScript.max = max, TypeScript.min = function(a, b) { + return a <= b ? a : b; + }; + var GetAstPathOptions, AstPath = function() { + function AstPath() { + _class_call_check(this, AstPath), this.asts = [], this.top = -1; } - }, ctx = new AstPathContext(); - return TypeScript1.getAstWalkerFactory().walk(script, function(cur, parent, walker) { - if (isValidAstNode(cur)) { - // Add "cur" to the stack if it contains our position - // For "identifier" nodes, we need a special case: A position equal to "limChar" is - // valid, since the position corresponds to a caret position (in between characters) - // For example: - // bar - // 0123 - // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid - var inclusive = hasFlag(options, 1) || cur.nodeType === TypeScript1.NodeType.Name || pos === script.limChar, minChar = cur.minChar, limChar = cur.limChar + (inclusive ? 1 : 0); // Special "EOF" case - if (pos >= minChar && pos < limChar) { - // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better - // than top of the stack. - var previous = ctx.path.ast(); - (null == previous || cur.minChar >= previous.minChar && cur.limChar <= previous.limChar) && ctx.path.push(cur); + var _proto = AstPath.prototype; + return _proto.clone = function() { + var clone = new AstPath(); + return clone.asts = this.asts.map(function(value) { + return value; + }), clone.top = this.top, clone; + }, _proto.pop = function() { + var head = this.ast(); + for(this.up(); this.asts.length > this.count();)this.asts.pop(); + return head; + }, _proto.push = function(ast) { + for(; this.asts.length > this.count();)this.asts.pop(); + this.top = this.asts.length, this.asts.push(ast); + }, _proto.up = function() { + if (this.top <= -1) throw Error("Invalid call to 'up'"); + this.top--; + }, _proto.down = function() { + if (this.top == this.ast.length - 1) throw Error("Invalid call to 'down'"); + this.top++; + }, _proto.nodeType = function() { + return null == this.ast() ? TypeScript.NodeType.None : this.ast().nodeType; + }, _proto.ast = function() { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }, _proto.parent = function() { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }, _proto.count = function() { + return this.top + 1; + }, _proto.get = function(index) { + return this.asts[index]; + }, _proto.isNameOfClass = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.ClassDeclaration && this.parent().name === this.ast(); + }, _proto.isNameOfInterface = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration && this.parent().name === this.ast(); + }, _proto.isNameOfArgument = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.ArgDecl && this.parent().id === this.ast(); + }, _proto.isNameOfVariable = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.VarDecl && this.parent().id === this.ast(); + }, _proto.isNameOfModule = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration && this.parent().name === this.ast(); + }, _proto.isNameOfFunction = function() { + return null !== this.ast() && null !== this.parent() && this.ast().nodeType === TypeScript.NodeType.Name && this.parent().nodeType === TypeScript.NodeType.FuncDecl && this.parent().name === this.ast(); + }, _proto.isChildOfScript = function() { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }, _proto.isChildOfModule = function() { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }, _proto.isChildOfClass = function() { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }, _proto.isArgumentOfClassConstructor = function() { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && this.asts[this.top - 2].isConstructor && this.asts[this.top - 2].arguments === this.asts[this.top - 1] && this.asts[this.top - 4].constructorDecl === this.asts[this.top - 2]; + }, _proto.isChildOfInterface = function() { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }, _proto.isTopLevelImplicitModule = function() { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag(this.asts[this.top].modFlags, TypeScript.ModuleFlags.IsWholeFile); + }, _proto.isBodyOfTopLevelImplicitModule = function() { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0] && TypeScript.hasFlag(this.asts[this.top - 1].modFlags, TypeScript.ModuleFlags.IsWholeFile); + }, _proto.isBodyOfScript = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && this.asts[this.top - 1].bod == this.asts[this.top - 0]; + }, _proto.isBodyOfSwitch = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].caseList == this.asts[this.top - 0]; + }, _proto.isBodyOfModule = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }, _proto.isBodyOfClass = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }, _proto.isBodyOfFunction = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 1].bod == this.asts[this.top - 0]; + }, _proto.isBodyOfInterface = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }, _proto.isBodyOfBlock = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && this.asts[this.top - 1].statements == this.asts[this.top - 0]; + }, _proto.isBodyOfFor = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfCase = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfTry = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfCatch = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfDoWhile = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfWhile = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfForIn = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfWith = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isBodyOfFinally = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }, _proto.isCaseOfSwitch = function() { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1]; + }, _proto.isDefaultCaseOfSwitch = function() { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1] && this.asts[this.top - 2].defaultCase == this.asts[this.top - 0]; + }, _proto.isListOfObjectLit = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; + }, _proto.isBodyOfObjectLit = function() { + return this.isListOfObjectLit(); + }, _proto.isEmptyListOfObjectLit = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0] && 0 == this.asts[this.top - 0].members.length; + }, _proto.isMemberOfObjectLit = function() { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 2].operand == this.asts[this.top - 1]; + }, _proto.isNameOfMemberOfObjectLit = function() { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && this.asts[this.top - 3].operand == this.asts[this.top - 2]; + }, _proto.isListOfArrayLit = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; + }, _proto.isTargetOfMember = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 1].operand1 === this.asts[this.top - 0]; + }, _proto.isMemberOfMember = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 1].operand2 === this.asts[this.top - 0]; + }, _proto.isItemOfList = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + //(this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }, _proto.isThenOfIf = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && this.asts[this.top - 1].thenBod == this.asts[this.top - 0]; + }, _proto.isElseOfIf = function() { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && this.asts[this.top - 1].elseBod == this.asts[this.top - 0]; + }, _proto.isBodyOfDefaultCase = function() { + return this.isBodyOfCase(); + }, _proto.isSingleStatementList = function() { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && 1 === this.asts[this.top].members.length; + }, _proto.isArgumentListOfFunction = function() { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }, _proto.isArgumentOfFunction = function() { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 2].arguments === this.asts[this.top - 1]; + }, _proto.isArgumentListOfCall = function() { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }, _proto.isArgumentListOfNew = function() { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }, _proto.isSynthesizedBlock = function() { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && !1 === this.asts[this.top - 0].isStatementBlock; + }, AstPath.reverseIndexOf = function(items, index) { + return null === items || items.length <= index ? null : items[items.length - index - 1]; + }, AstPath; + }(); + function isValidAstNode(ast) { + return null !== ast && -1 !== ast.minChar && -1 !== ast.limChar; + } + TypeScript.AstPath = AstPath, TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = function AstPathContext() { + _class_call_check(this, AstPathContext), this.path = new TypeScript.AstPath(); + }; + TypeScript.AstPathContext = AstPathContext, (GetAstPathOptions = TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {}))[GetAstPathOptions.Default = 0] = "Default", GetAstPathOptions[GetAstPathOptions.EdgeInclusive = 1] = "EdgeInclusive", GetAstPathOptions[GetAstPathOptions.DontPruneSearchBasedOnPosition = 2] = "DontPruneSearchBasedOnPosition", TypeScript.getAstPathToPosition = function(script, pos) { + var options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : 0, lookInComments = function(comments) { + if (comments && comments.length > 0) for(var i = 0; i < comments.length; i++){ + var minChar = comments[i].minChar, limChar = comments[i].limChar; + !comments[i].isBlockComment && limChar++, pos >= minChar && pos < limChar && ctx.path.push(comments[i]); } - pos < limChar && lookInComments(cur.preComments), pos >= minChar && lookInComments(cur.postComments), hasFlag(options, 2) || // Don't go further down the tree if pos is outside of [minChar, limChar] - (walker.options.goChildren = minChar <= pos && pos <= limChar); - } - return cur; - }, null, null, ctx), ctx.path; -}, TypeScript1.getTokenizationOffset = function(script, position) { - var bestOffset = 0; - return TypeScript1.getAstWalkerFactory().walk(script, function(cur, parent, walker) { - return TypeScript1.isValidAstNode(cur) && (cur.minChar <= position && (bestOffset = max(bestOffset, cur.minChar)), (cur.minChar > position || cur.limChar < bestOffset) && (walker.options.goChildren = !1)), cur; - }), bestOffset; -}, TypeScript1.walkAST = function(ast, callback) { - var path = new AstPath(); - TypeScript1.getAstWalkerFactory().walk(ast, function(cur, parent, walker) { - var path = walker.state; - return path.push(cur), callback(path, walker), cur; - }, function(cur, parent, walker) { - return walker.state.pop(), cur; - }, null, path); -}; + }, ctx = new AstPathContext(); + return TypeScript.getAstWalkerFactory().walk(script, function(cur, parent, walker) { + if (isValidAstNode(cur)) { + // Add "cur" to the stack if it contains our position + // For "identifier" nodes, we need a special case: A position equal to "limChar" is + // valid, since the position corresponds to a caret position (in between characters) + // For example: + // bar + // 0123 + // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid + var inclusive = hasFlag(options, 1) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar, minChar = cur.minChar, limChar = cur.limChar + (inclusive ? 1 : 0); // Special "EOF" case + if (pos >= minChar && pos < limChar) { + // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better + // than top of the stack. + var previous = ctx.path.ast(); + (null == previous || cur.minChar >= previous.minChar && cur.limChar <= previous.limChar) && ctx.path.push(cur); + } + pos < limChar && lookInComments(cur.preComments), pos >= minChar && lookInComments(cur.postComments), hasFlag(options, 2) || // Don't go further down the tree if pos is outside of [minChar, limChar] + (walker.options.goChildren = minChar <= pos && pos <= limChar); + } + return cur; + }, null, null, ctx), ctx.path; + }, TypeScript.getTokenizationOffset = function(script, position) { + var bestOffset = 0; + return TypeScript.getAstWalkerFactory().walk(script, function(cur, parent, walker) { + return TypeScript.isValidAstNode(cur) && (cur.minChar <= position && (bestOffset = max(bestOffset, cur.minChar)), (cur.minChar > position || cur.limChar < bestOffset) && (walker.options.goChildren = !1)), cur; + }), bestOffset; + }, TypeScript.walkAST = function(ast, callback) { + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, function(cur, parent, walker) { + var path = walker.state; + return path.push(cur), callback(path, walker), cur; + }, function(cur, parent, walker) { + return walker.state.pop(), cur; + }, null, path); + }; +}(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource2.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource2.1.normal.js index b80705a7142..f306d50bf64 100644 --- a/crates/swc/tests/tsc-references/parserRealSource2.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource2.1.normal.js @@ -4,29 +4,9 @@ /// var TypeScript; (function(TypeScript) { - var hasFlag = function hasFlag(val, flag) { + function hasFlag(val, flag) { return (val & flag) != 0; - }; - var ToDeclFlags = function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { - return fncOrVarOrSymbolOrModuleFlags; - }; - var flagsToString = function flagsToString(e, flags) { - var builder = ""; - for(var i = 1; i < 1 << 31; i = i << 1){ - if ((flags & i) != 0) { - for(var k in e){ - if (e[k] == i) { - if (builder.length > 0) { - builder += "|"; - } - builder += k; - break; - } - } - } - } - return builder; - }; + } TypeScript.hasFlag = hasFlag; var ErrorRecoverySet; (function(ErrorRecoverySet) { @@ -217,6 +197,9 @@ var TypeScript; SignatureFlags[SignatureFlags["IsStringIndexer"] = 2] = "IsStringIndexer"; SignatureFlags[SignatureFlags["IsNumberIndexer"] = 4] = "IsNumberIndexer"; })(SignatureFlags = TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } TypeScript.ToDeclFlags = ToDeclFlags; var TypeFlags; (function(TypeFlags) { @@ -257,5 +240,22 @@ var TypeScript; TypeScript.codeGenTarget = 0; TypeScript.moduleGenTarget = 0; TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for(var i = 1; i < 1 << 31; i = i << 1){ + if ((flags & i) != 0) { + for(var k in e){ + if (e[k] == i) { + if (builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } TypeScript.flagsToString = flagsToString; })(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource5.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource5.1.normal.js index 844a4a5ccb0..30e97e34bff 100644 --- a/crates/swc/tests/tsc-references/parserRealSource5.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource5.1.normal.js @@ -5,17 +5,6 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var prePrintAST = function prePrintAST(ast, parent, walker) { - var pc = walker.state; - ast.print(pc); - pc.increaseIndent(); - return ast; - }; - var postPrintAST = function postPrintAST(ast, parent, walker) { - var pc = walker.state; - pc.decreaseIndent(); - return ast; - }; var PrintContext = /*#__PURE__*/ function() { "use strict"; function PrintContext(outfile, parser) { @@ -60,6 +49,17 @@ var TypeScript; }(); // TODO: refactor indent logic for use in emit TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } TypeScript.postPrintAST = postPrintAST; })(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource6.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource6.1.normal.js index 8daa575581a..86637d661a6 100644 --- a/crates/swc/tests/tsc-references/parserRealSource6.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource6.1.normal.js @@ -5,7 +5,76 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var preFindMemberScope = function preFindMemberScope(ast, parent, walker) { + var TypeCollectionContext = function TypeCollectionContext(scopeChain, checker) { + "use strict"; + _class_call_check(this, TypeCollectionContext); + this.scopeChain = scopeChain; + this.checker = checker; + this.script = null; + }; + TypeScript.TypeCollectionContext = TypeCollectionContext; + var MemberScopeContext = function MemberScopeContext(flow, pos, matchFlag) { + "use strict"; + _class_call_check(this, MemberScopeContext); + this.flow = flow; + this.pos = pos; + this.matchFlag = matchFlag; + this.type = null; + this.ast = null; + this.options = new AstWalkOptions(); + }; + TypeScript.MemberScopeContext = MemberScopeContext; + var EnclosingScopeContext = /*#__PURE__*/ function() { + "use strict"; + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + _class_call_check(this, EnclosingScopeContext); + this.logger = logger; + this.script = script; + this.text = text; + this.pos = pos; + this.isMemberCompletion = isMemberCompletion; + this.scopeGetter = null; + this.objectLiteralScopeGetter = null; + this.scopeStartAST = null; + this.skipNextFuncDeclForClass = false; + this.deepestModuleDecl = null; + this.enclosingClassDecl = null; + this.enclosingObjectLit = null; + this.publicsOnly = true; + this.useFullAst = false; + } + var _proto = EnclosingScopeContext.prototype; + _proto.getScope = function getScope() { + return this.scopeGetter(); + }; + _proto.getObjectLiteralScope = function getObjectLiteralScope() { + return this.objectLiteralScopeGetter(); + }; + _proto.getScopeAST = function getScopeAST() { + return this.scopeStartAST; + }; + _proto.getScopePosition = function getScopePosition() { + return this.scopeStartAST.minChar; + }; + _proto.getScriptFragmentStartAST = function getScriptFragmentStartAST() { + return this.scopeStartAST; + }; + _proto.getScriptFragmentPosition = function getScriptFragmentPosition() { + return this.getScriptFragmentStartAST().minChar; + }; + _proto.getScriptFragment = function getScriptFragment() { + if (this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = this.isMemberCompletion ? this.pos : this.pos + 1; + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }; + return EnclosingScopeContext; + }(); + TypeScript.EnclosingScopeContext = EnclosingScopeContext; + function preFindMemberScope(ast, parent, walker) { var memScope = walker.state; if (hasFlag(ast.flags, memScope.matchFlag) && (memScope.pos < 0 || memScope.pos == ast.limChar)) { memScope.ast = ast; @@ -16,19 +85,22 @@ var TypeScript; memScope.options.stopWalk(); } return ast; - }; - var pushTypeCollectionScope = function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + } + TypeScript.preFindMemberScope = preFindMemberScope; + function pushTypeCollectionScope(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { var builder = new SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); var chain = new ScopeChain(container, context.scopeChain, builder); chain.thisType = thisType; chain.classType = classType; chain.moduleDecl = moduleDecl; context.scopeChain = chain; - }; - var popTypeCollectionScope = function popTypeCollectionScope(context) { + } + TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; + function popTypeCollectionScope(context) { context.scopeChain = context.scopeChain.previous; - }; - var preFindEnclosingScope = function preFindEnclosingScope(ast, parent, walker) { + } + TypeScript.popTypeCollectionScope = popTypeCollectionScope; + function preFindEnclosingScope(ast, parent, walker) { var context = walker.state; var minChar = ast.minChar; var limChar = ast.limChar; @@ -108,86 +180,14 @@ var TypeScript; walker.options.goChildren = false; } return ast; - }; - var findEnclosingScopeAt = function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { + } + TypeScript.preFindEnclosingScope = preFindEnclosingScope; + function findEnclosingScopeAt(logger, script, text, pos, isMemberCompletion) { var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context); if (context.scopeStartAST === null) return null; return context; - }; - var TypeCollectionContext = function TypeCollectionContext(scopeChain, checker) { - "use strict"; - _class_call_check(this, TypeCollectionContext); - this.scopeChain = scopeChain; - this.checker = checker; - this.script = null; - }; - TypeScript.TypeCollectionContext = TypeCollectionContext; - var MemberScopeContext = function MemberScopeContext(flow, pos, matchFlag) { - "use strict"; - _class_call_check(this, MemberScopeContext); - this.flow = flow; - this.pos = pos; - this.matchFlag = matchFlag; - this.type = null; - this.ast = null; - this.options = new AstWalkOptions(); - }; - TypeScript.MemberScopeContext = MemberScopeContext; - var EnclosingScopeContext = /*#__PURE__*/ function() { - "use strict"; - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - _class_call_check(this, EnclosingScopeContext); - this.logger = logger; - this.script = script; - this.text = text; - this.pos = pos; - this.isMemberCompletion = isMemberCompletion; - this.scopeGetter = null; - this.objectLiteralScopeGetter = null; - this.scopeStartAST = null; - this.skipNextFuncDeclForClass = false; - this.deepestModuleDecl = null; - this.enclosingClassDecl = null; - this.enclosingObjectLit = null; - this.publicsOnly = true; - this.useFullAst = false; - } - var _proto = EnclosingScopeContext.prototype; - _proto.getScope = function getScope() { - return this.scopeGetter(); - }; - _proto.getObjectLiteralScope = function getObjectLiteralScope() { - return this.objectLiteralScopeGetter(); - }; - _proto.getScopeAST = function getScopeAST() { - return this.scopeStartAST; - }; - _proto.getScopePosition = function getScopePosition() { - return this.scopeStartAST.minChar; - }; - _proto.getScriptFragmentStartAST = function getScriptFragmentStartAST() { - return this.scopeStartAST; - }; - _proto.getScriptFragmentPosition = function getScriptFragmentPosition() { - return this.getScriptFragmentStartAST().minChar; - }; - _proto.getScriptFragment = function getScriptFragment() { - if (this.scriptFragment == null) { - var ast = this.getScriptFragmentStartAST(); - var minChar = ast.minChar; - var limChar = this.isMemberCompletion ? this.pos : this.pos + 1; - this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }; - return EnclosingScopeContext; - }(); - TypeScript.EnclosingScopeContext = EnclosingScopeContext; - TypeScript.preFindMemberScope = preFindMemberScope; - TypeScript.pushTypeCollectionScope = pushTypeCollectionScope; - TypeScript.popTypeCollectionScope = popTypeCollectionScope; - TypeScript.preFindEnclosingScope = preFindEnclosingScope; + } // // Find the enclosing scope context from a position inside a script AST. // The "scopeStartAST" of the returned scope is always valid. diff --git a/crates/swc/tests/tsc-references/parserRealSource6.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource6.2.minified.js index 10a559adb25..ade1097e35f 100644 --- a/crates/swc/tests/tsc-references/parserRealSource6.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource6.2.minified.js @@ -2,86 +2,91 @@ // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// -var TypeScript, TypeScript1, preFindEnclosingScope, EnclosingScopeContext; +var TypeScript; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -TypeScript1 = TypeScript || (TypeScript = {}), preFindEnclosingScope = function(ast, parent, walker) { - var context = walker.state, minChar = ast.minChar, limChar = ast.limChar; - if (ast.nodeType == NodeType.Script && context.pos > limChar && (limChar = context.pos), minChar <= context.pos && limChar >= context.pos) { - switch(ast.nodeType){ - case NodeType.Script: - context.scopeGetter = function() { - return null === ast.bod ? null : ast.bod.enclosingScope; - }, context.scopeStartAST = ast; - break; - case NodeType.ClassDeclaration: - context.scopeGetter = function() { - return null === ast.type || null === ast.type.instanceType.containedScope ? null : ast.type.instanceType.containedScope; - }, context.scopeStartAST = ast, context.enclosingClassDecl = ast; - break; - case NodeType.ObjectLit: - // Only consider target-typed object literals - ast.targetType && (context.scopeGetter = function() { - return ast.targetType.containedScope; - }, context.objectLiteralScopeGetter = function() { - return ast.targetType.memberScope; - }, context.enclosingObjectLit = ast); - break; - case NodeType.ModuleDeclaration: - context.deepestModuleDecl = ast, context.scopeGetter = function() { - return null === ast.type ? null : ast.type.containedScope; - }, context.scopeStartAST = ast; - break; - case NodeType.InterfaceDeclaration: - context.scopeGetter = function() { - return null === ast.type ? null : ast.type.containedScope; - }, context.scopeStartAST = ast; - break; - case NodeType.FuncDecl: - context.skipNextFuncDeclForClass ? context.skipNextFuncDeclForClass = !1 : (context.scopeGetter = function() { - return(// The scope of a class constructor is hidden somewhere we don't expect :-S - ast.isConstructor && hasFlag(ast.fncFlags, FncFlags.ClassMethod) && ast.type && ast.type.enclosingType ? ast.type.enclosingType.constructorScope : ast.scopeType ? ast.scopeType.containedScope : ast.type ? ast.type.containedScope : null); - }, context.scopeStartAST = ast); +!function(TypeScript) { + TypeScript.TypeCollectionContext = function TypeCollectionContext(scopeChain, checker) { + _class_call_check(this, TypeCollectionContext), this.scopeChain = scopeChain, this.checker = checker, this.script = null; + }, TypeScript.MemberScopeContext = function MemberScopeContext(flow, pos, matchFlag) { + _class_call_check(this, MemberScopeContext), this.flow = flow, this.pos = pos, this.matchFlag = matchFlag, this.type = null, this.ast = null, this.options = new AstWalkOptions(); + }; + var EnclosingScopeContext = function() { + function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { + _class_call_check(this, EnclosingScopeContext), this.logger = logger, this.script = script, this.text = text, this.pos = pos, this.isMemberCompletion = isMemberCompletion, this.scopeGetter = null, this.objectLiteralScopeGetter = null, this.scopeStartAST = null, this.skipNextFuncDeclForClass = !1, this.deepestModuleDecl = null, this.enclosingClassDecl = null, this.enclosingObjectLit = null, this.publicsOnly = !0, this.useFullAst = !1; } - walker.options.goChildren = !0; - } else walker.options.goChildren = !1; - return ast; -}, TypeScript1.TypeCollectionContext = function TypeCollectionContext(scopeChain, checker) { - _class_call_check(this, TypeCollectionContext), this.scopeChain = scopeChain, this.checker = checker, this.script = null; -}, TypeScript1.MemberScopeContext = function MemberScopeContext(flow, pos, matchFlag) { - _class_call_check(this, MemberScopeContext), this.flow = flow, this.pos = pos, this.matchFlag = matchFlag, this.type = null, this.ast = null, this.options = new AstWalkOptions(); -}, EnclosingScopeContext = function() { - function EnclosingScopeContext(logger, script, text, pos, isMemberCompletion) { - _class_call_check(this, EnclosingScopeContext), this.logger = logger, this.script = script, this.text = text, this.pos = pos, this.isMemberCompletion = isMemberCompletion, this.scopeGetter = null, this.objectLiteralScopeGetter = null, this.scopeStartAST = null, this.skipNextFuncDeclForClass = !1, this.deepestModuleDecl = null, this.enclosingClassDecl = null, this.enclosingObjectLit = null, this.publicsOnly = !0, this.useFullAst = !1; + var _proto = EnclosingScopeContext.prototype; + return _proto.getScope = function() { + return this.scopeGetter(); + }, _proto.getObjectLiteralScope = function() { + return this.objectLiteralScopeGetter(); + }, _proto.getScopeAST = function() { + return this.scopeStartAST; + }, _proto.getScopePosition = function() { + return this.scopeStartAST.minChar; + }, _proto.getScriptFragmentStartAST = function() { + return this.scopeStartAST; + }, _proto.getScriptFragmentPosition = function() { + return this.getScriptFragmentStartAST().minChar; + }, _proto.getScriptFragment = function() { + if (null == this.scriptFragment) { + var ast = this.getScriptFragmentStartAST(), minChar = ast.minChar, limChar = this.isMemberCompletion ? this.pos : this.pos + 1; + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; + } + return this.scriptFragment; + }, EnclosingScopeContext; + }(); + function preFindEnclosingScope(ast, parent, walker) { + var context = walker.state, minChar = ast.minChar, limChar = ast.limChar; + if (ast.nodeType == NodeType.Script && context.pos > limChar && (limChar = context.pos), minChar <= context.pos && limChar >= context.pos) { + switch(ast.nodeType){ + case NodeType.Script: + context.scopeGetter = function() { + return null === ast.bod ? null : ast.bod.enclosingScope; + }, context.scopeStartAST = ast; + break; + case NodeType.ClassDeclaration: + context.scopeGetter = function() { + return null === ast.type || null === ast.type.instanceType.containedScope ? null : ast.type.instanceType.containedScope; + }, context.scopeStartAST = ast, context.enclosingClassDecl = ast; + break; + case NodeType.ObjectLit: + // Only consider target-typed object literals + ast.targetType && (context.scopeGetter = function() { + return ast.targetType.containedScope; + }, context.objectLiteralScopeGetter = function() { + return ast.targetType.memberScope; + }, context.enclosingObjectLit = ast); + break; + case NodeType.ModuleDeclaration: + context.deepestModuleDecl = ast, context.scopeGetter = function() { + return null === ast.type ? null : ast.type.containedScope; + }, context.scopeStartAST = ast; + break; + case NodeType.InterfaceDeclaration: + context.scopeGetter = function() { + return null === ast.type ? null : ast.type.containedScope; + }, context.scopeStartAST = ast; + break; + case NodeType.FuncDecl: + context.skipNextFuncDeclForClass ? context.skipNextFuncDeclForClass = !1 : (context.scopeGetter = function() { + return(// The scope of a class constructor is hidden somewhere we don't expect :-S + ast.isConstructor && hasFlag(ast.fncFlags, FncFlags.ClassMethod) && ast.type && ast.type.enclosingType ? ast.type.enclosingType.constructorScope : ast.scopeType ? ast.scopeType.containedScope : ast.type ? ast.type.containedScope : null); + }, context.scopeStartAST = ast); + } + walker.options.goChildren = !0; + } else walker.options.goChildren = !1; + return ast; } - var _proto = EnclosingScopeContext.prototype; - return _proto.getScope = function() { - return this.scopeGetter(); - }, _proto.getObjectLiteralScope = function() { - return this.objectLiteralScopeGetter(); - }, _proto.getScopeAST = function() { - return this.scopeStartAST; - }, _proto.getScopePosition = function() { - return this.scopeStartAST.minChar; - }, _proto.getScriptFragmentStartAST = function() { - return this.scopeStartAST; - }, _proto.getScriptFragmentPosition = function() { - return this.getScriptFragmentStartAST().minChar; - }, _proto.getScriptFragment = function() { - if (null == this.scriptFragment) { - var ast = this.getScriptFragmentStartAST(), minChar = ast.minChar, limChar = this.isMemberCompletion ? this.pos : this.pos + 1; - this.scriptFragment = TypeScript1.quickParse(this.logger, ast, this.text, minChar, limChar, null).Script; - } - return this.scriptFragment; - }, EnclosingScopeContext; -}(), TypeScript1.EnclosingScopeContext = EnclosingScopeContext, TypeScript1.preFindMemberScope = function(ast, parent, walker) { - var memScope = walker.state; - return hasFlag(ast.flags, memScope.matchFlag) && (memScope.pos < 0 || memScope.pos == ast.limChar) && (memScope.ast = ast, null == ast.type && memScope.pos >= 0 && memScope.flow.inScopeTypeCheck(ast, memScope.scope), memScope.type = ast.type, memScope.options.stopWalk()), ast; -}, TypeScript1.pushTypeCollectionScope = function(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { - var builder = new SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container), chain = new ScopeChain(container, context.scopeChain, builder); - chain.thisType = thisType, chain.classType = classType, chain.moduleDecl = moduleDecl, context.scopeChain = chain; -}, TypeScript1.popTypeCollectionScope = function(context) { - context.scopeChain = context.scopeChain.previous; -}, TypeScript1.preFindEnclosingScope = preFindEnclosingScope, TypeScript1.findEnclosingScopeAt = function(logger, script, text, pos, isMemberCompletion) { - var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); - return (TypeScript1.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context), null === context.scopeStartAST) ? null : context; -}; + TypeScript.EnclosingScopeContext = EnclosingScopeContext, TypeScript.preFindMemberScope = function(ast, parent, walker) { + var memScope = walker.state; + return hasFlag(ast.flags, memScope.matchFlag) && (memScope.pos < 0 || memScope.pos == ast.limChar) && (memScope.ast = ast, null == ast.type && memScope.pos >= 0 && memScope.flow.inScopeTypeCheck(ast, memScope.scope), memScope.type = ast.type, memScope.options.stopWalk()), ast; + }, TypeScript.pushTypeCollectionScope = function(container, valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, context, thisType, classType, moduleDecl) { + var builder = new SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container), chain = new ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType, chain.classType = classType, chain.moduleDecl = moduleDecl, context.scopeChain = chain; + }, TypeScript.popTypeCollectionScope = function(context) { + context.scopeChain = context.scopeChain.previous; + }, TypeScript.preFindEnclosingScope = preFindEnclosingScope, TypeScript.findEnclosingScopeAt = function(logger, script, text, pos, isMemberCompletion) { + var context = new EnclosingScopeContext(logger, script, text, pos, isMemberCompletion); + return (TypeScript.getAstWalkerFactory().walk(script, preFindEnclosingScope, null, null, context), null === context.scopeStartAST) ? null : context; + }; +}(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource8.1.normal.js b/crates/swc/tests/tsc-references/parserRealSource8.1.normal.js index 16292a0926b..71ba010a04a 100644 --- a/crates/swc/tests/tsc-references/parserRealSource8.1.normal.js +++ b/crates/swc/tests/tsc-references/parserRealSource8.1.normal.js @@ -5,27 +5,63 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; var TypeScript; (function(TypeScript) { - var pushAssignScope = function pushAssignScope(scope, context, type, classType, fnc) { + var AssignScopeContext = function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + "use strict"; + _class_call_check(this, AssignScopeContext); + this.scopeChain = scopeChain; + this.typeFlow = typeFlow; + this.modDeclChain = modDeclChain; + }; + TypeScript.AssignScopeContext = AssignScopeContext; + function pushAssignScope(scope, context, type, classType, fnc) { var chain = new ScopeChain(null, context.scopeChain, scope); chain.thisType = type; chain.classType = classType; chain.fnc = fnc; context.scopeChain = chain; - }; - var popAssignScope = function popAssignScope(context) { + } + TypeScript.pushAssignScope = pushAssignScope; + function popAssignScope(context) { context.scopeChain = context.scopeChain.previous; - }; - var instanceCompare = function instanceCompare(a, b) { + } + TypeScript.popAssignScope = popAssignScope; + function instanceCompare(a, b) { if (a == null || !a.isInstanceProperty()) { return b; } else { return a; } - }; - var instanceFilterStop = function instanceFilterStop(s) { + } + TypeScript.instanceCompare = instanceCompare; + function instanceFilterStop(s) { return s.isInstanceProperty(); - }; - var preAssignModuleScopes = function preAssignModuleScopes(ast, context) { + } + TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = /*#__PURE__*/ function() { + "use strict"; + function ScopeSearchFilter(select, stop) { + _class_call_check(this, ScopeSearchFilter); + this.select = select; + this.stop = stop; + this.result = null; + } + var _proto = ScopeSearchFilter.prototype; + _proto.reset = function reset() { + this.result = null; + }; + _proto.update = function update(b) { + this.result = this.select(this.result, b); + if (this.result) { + return this.stop(this.result); + } else { + return false; + } + }; + return ScopeSearchFilter; + }(); + TypeScript.ScopeSearchFilter = ScopeSearchFilter; + TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); + function preAssignModuleScopes(ast, context) { var moduleDecl = ast; var memberScope = null; var aggScope = null; @@ -49,8 +85,9 @@ var TypeScript; if (mod.symbol) { context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, moduleDecl.vars, mod.members.privateMembers, true); } - }; - var preAssignClassScopes = function preAssignClassScopes(ast, context) { + } + TypeScript.preAssignModuleScopes = preAssignModuleScopes; + function preAssignClassScopes(ast, context) { var classDecl = ast; var memberScope = null; var aggScope = null; @@ -76,8 +113,9 @@ var TypeScript; } else { ast.type = context.typeFlow.anyType; } - }; - var preAssignInterfaceScopes = function preAssignInterfaceScopes(ast, context) { + } + TypeScript.preAssignClassScopes = preAssignClassScopes; + function preAssignInterfaceScopes(ast, context) { var interfaceDecl = ast; var memberScope = null; var aggScope = null; @@ -92,8 +130,9 @@ var TypeScript; aggScope.addParentScope(context.scopeChain.scope); pushAssignScope(aggScope, context, null, null, null); interfaceType.containedScope = aggScope; - }; - var preAssignWithScopes = function preAssignWithScopes(ast, context) { + } + TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; + function preAssignWithScopes(ast, context) { var withStmt = ast; var withType = withStmt.type; var members = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())); @@ -108,8 +147,9 @@ var TypeScript; var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); pushAssignScope(withScope, context, null, null, null); withType.containedScope = withScope; - }; - var preAssignFuncDeclScopes = function preAssignFuncDeclScopes(ast, context) { + } + TypeScript.preAssignWithScopes = preAssignWithScopes; + function preAssignFuncDeclScopes(ast, context) { var funcDecl = ast; var container = null; var localContainer = null; @@ -256,8 +296,9 @@ var TypeScript; var thisType = funcDecl.isConstructor && hasFlag(funcDecl.fncFlags, FncFlags.ClassMethod) ? context.scopeChain.thisType : null; pushAssignScope(locals, context, thisType, null, funcDecl); } - }; - var preAssignCatchScopes = function preAssignCatchScopes(ast, context) { + } + TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; + function preAssignCatchScopes(ast, context) { var catchBlock = ast; if (catchBlock.param) { var catchTable = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())); // REVIEW: Should we be allocating a public table instead of a private one? @@ -265,8 +306,9 @@ var TypeScript; catchBlock.containedScope = catchLocals; pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); } - }; - var preAssignScopes = function preAssignScopes(ast, parent, walker) { + } + TypeScript.preAssignCatchScopes = preAssignCatchScopes; + function preAssignScopes(ast, parent, walker) { var context = walker.state; var go = true; if (ast) { @@ -291,8 +333,9 @@ var TypeScript; } walker.options.goChildren = go; return ast; - }; - var postAssignScopes = function postAssignScopes(ast, parent, walker) { + } + TypeScript.preAssignScopes = preAssignScopes; + function postAssignScopes(ast, parent, walker) { var context = walker.state; var go = true; if (ast) { @@ -325,49 +368,6 @@ var TypeScript; } walker.options.goChildren = go; return ast; - }; - var AssignScopeContext = function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - "use strict"; - _class_call_check(this, AssignScopeContext); - this.scopeChain = scopeChain; - this.typeFlow = typeFlow; - this.modDeclChain = modDeclChain; - }; - TypeScript.AssignScopeContext = AssignScopeContext; - TypeScript.pushAssignScope = pushAssignScope; - TypeScript.popAssignScope = popAssignScope; - TypeScript.instanceCompare = instanceCompare; - TypeScript.instanceFilterStop = instanceFilterStop; - var ScopeSearchFilter = /*#__PURE__*/ function() { - "use strict"; - function ScopeSearchFilter(select, stop) { - _class_call_check(this, ScopeSearchFilter); - this.select = select; - this.stop = stop; - this.result = null; - } - var _proto = ScopeSearchFilter.prototype; - _proto.reset = function reset() { - this.result = null; - }; - _proto.update = function update(b) { - this.result = this.select(this.result, b); - if (this.result) { - return this.stop(this.result); - } else { - return false; - } - }; - return ScopeSearchFilter; - }(); - TypeScript.ScopeSearchFilter = ScopeSearchFilter; - TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop); - TypeScript.preAssignModuleScopes = preAssignModuleScopes; - TypeScript.preAssignClassScopes = preAssignClassScopes; - TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes; - TypeScript.preAssignWithScopes = preAssignWithScopes; - TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes; - TypeScript.preAssignCatchScopes = preAssignCatchScopes; - TypeScript.preAssignScopes = preAssignScopes; + } TypeScript.postAssignScopes = postAssignScopes; })(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/parserRealSource8.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource8.2.minified.js index a4188ac8baa..fbc019f428f 100644 --- a/crates/swc/tests/tsc-references/parserRealSource8.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource8.2.minified.js @@ -2,114 +2,128 @@ // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. // See LICENSE.txt in the project root for complete license information. /// -var TypeScript, TypeScript1, pushAssignScope, popAssignScope, instanceCompare, instanceFilterStop, preAssignModuleScopes, preAssignClassScopes, preAssignInterfaceScopes, preAssignWithScopes, preAssignFuncDeclScopes, preAssignCatchScopes, ScopeSearchFilter; +var TypeScript; import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; -TypeScript1 = TypeScript || (TypeScript = {}), pushAssignScope = function(scope, context, type, classType, fnc) { - var chain = new ScopeChain(null, context.scopeChain, scope); - chain.thisType = type, chain.classType = classType, chain.fnc = fnc, context.scopeChain = chain; -}, popAssignScope = function(context) { - context.scopeChain = context.scopeChain.previous; -}, instanceCompare = function(a, b) { - return null != a && a.isInstanceProperty() ? a : b; -}, instanceFilterStop = function(s) { - return s.isInstanceProperty(); -}, preAssignModuleScopes = function(ast, context) { - var memberScope = null, aggScope = null; - ast.name && ast.mod && (ast.name.sym = ast.mod.symbol); - var mod = ast.mod; - // We're likely here because of error recovery - mod && (memberScope = new SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol), mod.memberScope = memberScope, context.modDeclChain.push(ast), context.typeFlow.checker.currentModDecl = ast, (aggScope = new SymbolAggregateScope(mod.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, null, null, null), mod.containedScope = aggScope, mod.symbol && context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, ast.vars, mod.members.privateMembers, !0)); -}, preAssignClassScopes = function(ast, context) { - var memberScope = null, aggScope = null; - ast.name && ast.type && (ast.name.sym = ast.type.symbol); - var classType = ast.type; - if (classType) { - classType.symbol, memberScope = context.typeFlow.checker.scopeOf(classType), (aggScope = new SymbolAggregateScope(classType.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), classType.containedScope = aggScope, classType.memberScope = memberScope; - var instanceType = classType.instanceType; - memberScope = context.typeFlow.checker.scopeOf(instanceType), instanceType.memberScope = memberScope, (aggScope = new SymbolAggregateScope(instanceType.symbol)).addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, instanceType, classType, null), instanceType.containedScope = aggScope; - } else ast.type = context.typeFlow.anyType; -}, preAssignInterfaceScopes = function(ast, context) { - var memberScope = null, aggScope = null; - ast.name && ast.type && (ast.name.sym = ast.type.symbol); - var interfaceType = ast.type; - memberScope = context.typeFlow.checker.scopeOf(interfaceType), interfaceType.memberScope = memberScope, (aggScope = new SymbolAggregateScope(interfaceType.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, null, null, null), interfaceType.containedScope = aggScope; -}, preAssignWithScopes = function(ast, context) { - var withType = ast.type, members = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), ambientMembers = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), withType = new Type(), withSymbol = new WithSymbol(ast.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); - withType.members = members, withType.ambientMembers = ambientMembers, withType.symbol = withSymbol, withType.setHasImplementation(), ast.type = withType; - var withScope = new TypeScript1.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); - pushAssignScope(withScope, context, null, null, null), withType.containedScope = withScope; -}, preAssignFuncDeclScopes = function(ast, context) { - var container = null, localContainer = null; - ast.type && (localContainer = ast.type.symbol); - var isStatic = hasFlag(ast.fncFlags, FncFlags.Static), parentScope = isStatic && null != context.scopeChain.fnc ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; - // if this is not a method, but enclosed by class, use constructor as - // the enclosing scope - // REVIEW: Some twisted logic here - this needs to be cleaned up once old classes are removed - // - if it's a new class, always use the contained scope, since we initialize the constructor scope below - if (context.scopeChain.thisType && (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod))) { - var instType = context.scopeChain.thisType; - // if the parent is the class constructor, use the constructor scope - parentScope = instType.typeFlags & TypeFlags.IsClass || hasFlag(ast.fncFlags, FncFlags.ClassMethod) ? context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == NodeType.FuncDecl && context.scopeChain.previous.scope.container.declAST.isConstructor ? instType.constructorScope : isStatic && context.scopeChain.classType ? context.scopeChain.classType.containedScope : instType.containedScope : !ast.isMethod() || isStatic ? instType.constructorScope : instType.containedScope, container = instType.symbol; - } else ast.isConstructor && context.scopeChain.thisType && // sets the container to the class type's symbol (which is shared by the instance type) - (container = context.scopeChain.thisType.symbol); - if (null == ast.type || hasFlag(ast.type.symbol.flags, SymbolFlags.TypeSetDuringScopeAssignment)) { - context.scopeChain.fnc && context.scopeChain.fnc.type && (container = context.scopeChain.fnc.type.symbol); - var funcScope = null, outerFnc = context.scopeChain.fnc, nameText = ast.name ? ast.name.actualText : null, fgSym = null; - isStatic ? (null == outerFnc.type.members && container.getType().memberScope && (outerFnc.type.members = container.type.memberScope.valueMembers), funcScope = context.scopeChain.fnc.type.memberScope, outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = ast) : funcScope = !ast.isConstructor && container && container.declAST && container.declAST.nodeType == NodeType.FuncDecl && container.declAST.isConstructor && !ast.isMethod() ? context.scopeChain.thisType.constructorScope : context.scopeChain.scope, nameText && "__missing" != nameText && !ast.isAccessor() && (fgSym = funcScope.findLocal(nameText, !1, !1)), context.typeFlow.checker.createFunctionSignature(ast, container, funcScope, fgSym, null == fgSym), (!ast.accessorSymbol && ast.fncFlags & FncFlags.ClassMethod && container && (!fgSym || fgSym.declAST.nodeType != NodeType.FuncDecl) && ast.isAccessor() || fgSym && fgSym.isAccessor()) && (ast.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(ast, fgSym, container.getType(), ast.isMethod() && isStatic, !0, funcScope, container)), ast.type.symbol.flags |= SymbolFlags.TypeSetDuringScopeAssignment; +!function(TypeScript) { + function pushAssignScope(scope, context, type, classType, fnc) { + var chain = new ScopeChain(null, context.scopeChain, scope); + chain.thisType = type, chain.classType = classType, chain.fnc = fnc, context.scopeChain = chain; } - // Overloads have no scope, so bail here - if (ast.name && ast.type && (ast.name.sym = ast.type.symbol), // Keep track of the original scope type, because target typing might override - // the "type" member. We need the original "Scope type" for completion list, etc. - ast.scopeType = ast.type, !ast.isOverload) { - var funcTable = new StringHashTable(), funcMembers = new ScopedMembers(new DualStringHashTable(funcTable, new StringHashTable())), ambientFuncTable = new StringHashTable(), ambientFuncMembers = new ScopedMembers(new DualStringHashTable(ambientFuncTable, new StringHashTable())), funcStaticTable = new StringHashTable(), funcStaticMembers = new ScopedMembers(new DualStringHashTable(funcStaticTable, new StringHashTable())), ambientFuncStaticTable = new StringHashTable(), ambientFuncStaticMembers = new ScopedMembers(new DualStringHashTable(ambientFuncStaticTable, new StringHashTable())); - // REVIEW: Is it a problem that this is being set twice for properties and constructors? - ast.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; - var locals = new SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer), statics = new SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); - if (ast.isConstructor && context.scopeChain.thisType && (context.scopeChain.thisType.constructorScope = locals), // basically, there are two problems - // - Above, for new classes, we were overwriting the constructor scope with the containing scope. This caused constructor params to be - // in scope everywhere - // - Below, we're setting the contained scope table to the same table we were overwriting the constructor scope with, which we need to - // fish lambda params, etc, out (see funcTable below) - // - // A good first approach to solving this would be to change addLocalsFromScope to take a scope instead of a table, and add to the - // constructor scope as appropriate - ast.symbols = funcTable, !ast.isSpecialFn()) { - var group = ast.type, signature = ast.signature; - ast.isConstructor || (group.containedScope = locals, locals.container = group.symbol, group.memberScope = statics, statics.container = group.symbol), ast.enclosingFnc = context.scopeChain.fnc, group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; - // for mapping when type checking - var fgSym = ast.type.symbol; - if ((ast.fncFlags & FncFlags.Signature) == FncFlags.None && ast.vars && (context.typeFlow.addLocalsFromScope(locals, fgSym, ast.vars, funcTable, !1), context.typeFlow.addLocalsFromScope(statics, fgSym, ast.statics, funcStaticTable, !1)), signature.parameters) for(var len = signature.parameters.length, i = 0; i < len; i++){ - var paramSym = signature.parameters[i]; - context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, !0); + function popAssignScope(context) { + context.scopeChain = context.scopeChain.previous; + } + function instanceCompare(a, b) { + return null != a && a.isInstanceProperty() ? a : b; + } + function instanceFilterStop(s) { + return s.isInstanceProperty(); + } + TypeScript.AssignScopeContext = function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { + _class_call_check(this, AssignScopeContext), this.scopeChain = scopeChain, this.typeFlow = typeFlow, this.modDeclChain = modDeclChain; + }, TypeScript.pushAssignScope = pushAssignScope, TypeScript.popAssignScope = popAssignScope, TypeScript.instanceCompare = instanceCompare, TypeScript.instanceFilterStop = instanceFilterStop; + var ScopeSearchFilter = function() { + function ScopeSearchFilter(select, stop) { + _class_call_check(this, ScopeSearchFilter), this.select = select, this.stop = stop, this.result = null; + } + var _proto = ScopeSearchFilter.prototype; + return _proto.reset = function() { + this.result = null; + }, _proto.update = function(b) { + return this.result = this.select(this.result, b), !!this.result && this.stop(this.result); + }, ScopeSearchFilter; + }(); + function preAssignModuleScopes(ast, context) { + var memberScope = null, aggScope = null; + ast.name && ast.mod && (ast.name.sym = ast.mod.symbol); + var mod = ast.mod; + // We're likely here because of error recovery + mod && (memberScope = new SymbolTableScope(mod.members, mod.ambientMembers, mod.enclosedTypes, mod.ambientEnclosedTypes, mod.symbol), mod.memberScope = memberScope, context.modDeclChain.push(ast), context.typeFlow.checker.currentModDecl = ast, (aggScope = new SymbolAggregateScope(mod.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, null, null, null), mod.containedScope = aggScope, mod.symbol && context.typeFlow.addLocalsFromScope(mod.containedScope, mod.symbol, ast.vars, mod.members.privateMembers, !0)); + } + function preAssignClassScopes(ast, context) { + var memberScope = null, aggScope = null; + ast.name && ast.type && (ast.name.sym = ast.type.symbol); + var classType = ast.type; + if (classType) { + classType.symbol, memberScope = context.typeFlow.checker.scopeOf(classType), (aggScope = new SymbolAggregateScope(classType.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), classType.containedScope = aggScope, classType.memberScope = memberScope; + var instanceType = classType.instanceType; + memberScope = context.typeFlow.checker.scopeOf(instanceType), instanceType.memberScope = memberScope, (aggScope = new SymbolAggregateScope(instanceType.symbol)).addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, instanceType, classType, null), instanceType.containedScope = aggScope; + } else ast.type = context.typeFlow.anyType; + } + function preAssignInterfaceScopes(ast, context) { + var memberScope = null, aggScope = null; + ast.name && ast.type && (ast.name.sym = ast.type.symbol); + var interfaceType = ast.type; + memberScope = context.typeFlow.checker.scopeOf(interfaceType), interfaceType.memberScope = memberScope, (aggScope = new SymbolAggregateScope(interfaceType.symbol)).addParentScope(memberScope), aggScope.addParentScope(context.scopeChain.scope), pushAssignScope(aggScope, context, null, null, null), interfaceType.containedScope = aggScope; + } + function preAssignWithScopes(ast, context) { + var withType = ast.type, members = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), ambientMembers = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), withType = new Type(), withSymbol = new WithSymbol(ast.minChar, context.typeFlow.checker.locationInfo.unitIndex, withType); + withType.members = members, withType.ambientMembers = ambientMembers, withType.symbol = withSymbol, withType.setHasImplementation(), ast.type = withType; + var withScope = new TypeScript.SymbolScopeBuilder(withType.members, withType.ambientMembers, null, null, context.scopeChain.scope, withType.symbol); + pushAssignScope(withScope, context, null, null, null), withType.containedScope = withScope; + } + function preAssignFuncDeclScopes(ast, context) { + var container = null, localContainer = null; + ast.type && (localContainer = ast.type.symbol); + var isStatic = hasFlag(ast.fncFlags, FncFlags.Static), parentScope = isStatic && null != context.scopeChain.fnc ? context.scopeChain.fnc.type.memberScope : context.scopeChain.scope; + // if this is not a method, but enclosed by class, use constructor as + // the enclosing scope + // REVIEW: Some twisted logic here - this needs to be cleaned up once old classes are removed + // - if it's a new class, always use the contained scope, since we initialize the constructor scope below + if (context.scopeChain.thisType && (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod))) { + var instType = context.scopeChain.thisType; + // if the parent is the class constructor, use the constructor scope + parentScope = instType.typeFlags & TypeFlags.IsClass || hasFlag(ast.fncFlags, FncFlags.ClassMethod) ? context.scopeChain.previous.scope.container && context.scopeChain.previous.scope.container.declAST && context.scopeChain.previous.scope.container.declAST.nodeType == NodeType.FuncDecl && context.scopeChain.previous.scope.container.declAST.isConstructor ? instType.constructorScope : isStatic && context.scopeChain.classType ? context.scopeChain.classType.containedScope : instType.containedScope : !ast.isMethod() || isStatic ? instType.constructorScope : instType.containedScope, container = instType.symbol; + } else ast.isConstructor && context.scopeChain.thisType && // sets the container to the class type's symbol (which is shared by the instance type) + (container = context.scopeChain.thisType.symbol); + if (null == ast.type || hasFlag(ast.type.symbol.flags, SymbolFlags.TypeSetDuringScopeAssignment)) { + context.scopeChain.fnc && context.scopeChain.fnc.type && (container = context.scopeChain.fnc.type.symbol); + var funcScope = null, outerFnc = context.scopeChain.fnc, nameText = ast.name ? ast.name.actualText : null, fgSym = null; + isStatic ? (null == outerFnc.type.members && container.getType().memberScope && (outerFnc.type.members = container.type.memberScope.valueMembers), funcScope = context.scopeChain.fnc.type.memberScope, outerFnc.innerStaticFuncs[outerFnc.innerStaticFuncs.length] = ast) : funcScope = !ast.isConstructor && container && container.declAST && container.declAST.nodeType == NodeType.FuncDecl && container.declAST.isConstructor && !ast.isMethod() ? context.scopeChain.thisType.constructorScope : context.scopeChain.scope, nameText && "__missing" != nameText && !ast.isAccessor() && (fgSym = funcScope.findLocal(nameText, !1, !1)), context.typeFlow.checker.createFunctionSignature(ast, container, funcScope, fgSym, null == fgSym), (!ast.accessorSymbol && ast.fncFlags & FncFlags.ClassMethod && container && (!fgSym || fgSym.declAST.nodeType != NodeType.FuncDecl) && ast.isAccessor() || fgSym && fgSym.isAccessor()) && (ast.accessorSymbol = context.typeFlow.checker.createAccessorSymbol(ast, fgSym, container.getType(), ast.isMethod() && isStatic, !0, funcScope, container)), ast.type.symbol.flags |= SymbolFlags.TypeSetDuringScopeAssignment; + } + // Overloads have no scope, so bail here + if (ast.name && ast.type && (ast.name.sym = ast.type.symbol), // Keep track of the original scope type, because target typing might override + // the "type" member. We need the original "Scope type" for completion list, etc. + ast.scopeType = ast.type, !ast.isOverload) { + var funcTable = new StringHashTable(), funcMembers = new ScopedMembers(new DualStringHashTable(funcTable, new StringHashTable())), ambientFuncTable = new StringHashTable(), ambientFuncMembers = new ScopedMembers(new DualStringHashTable(ambientFuncTable, new StringHashTable())), funcStaticTable = new StringHashTable(), funcStaticMembers = new ScopedMembers(new DualStringHashTable(funcStaticTable, new StringHashTable())), ambientFuncStaticTable = new StringHashTable(), ambientFuncStaticMembers = new ScopedMembers(new DualStringHashTable(ambientFuncStaticTable, new StringHashTable())); + // REVIEW: Is it a problem that this is being set twice for properties and constructors? + ast.unitIndex = context.typeFlow.checker.locationInfo.unitIndex; + var locals = new SymbolScopeBuilder(funcMembers, ambientFuncMembers, null, null, parentScope, localContainer), statics = new SymbolScopeBuilder(funcStaticMembers, ambientFuncStaticMembers, null, null, parentScope, null); + if (ast.isConstructor && context.scopeChain.thisType && (context.scopeChain.thisType.constructorScope = locals), // basically, there are two problems + // - Above, for new classes, we were overwriting the constructor scope with the containing scope. This caused constructor params to be + // in scope everywhere + // - Below, we're setting the contained scope table to the same table we were overwriting the constructor scope with, which we need to + // fish lambda params, etc, out (see funcTable below) + // + // A good first approach to solving this would be to change addLocalsFromScope to take a scope instead of a table, and add to the + // constructor scope as appropriate + ast.symbols = funcTable, !ast.isSpecialFn()) { + var group = ast.type, signature = ast.signature; + ast.isConstructor || (group.containedScope = locals, locals.container = group.symbol, group.memberScope = statics, statics.container = group.symbol), ast.enclosingFnc = context.scopeChain.fnc, group.enclosingType = isStatic ? context.scopeChain.classType : context.scopeChain.thisType; + // for mapping when type checking + var fgSym = ast.type.symbol; + if ((ast.fncFlags & FncFlags.Signature) == FncFlags.None && ast.vars && (context.typeFlow.addLocalsFromScope(locals, fgSym, ast.vars, funcTable, !1), context.typeFlow.addLocalsFromScope(statics, fgSym, ast.statics, funcStaticTable, !1)), signature.parameters) for(var len = signature.parameters.length, i = 0; i < len; i++){ + var paramSym = signature.parameters[i]; + context.typeFlow.checker.resolveTypeLink(locals, paramSym.parameter.typeLink, !0); + } + context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, ast.isSignature()); + } + if (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod)) { + var thisType = ast.isConstructor && hasFlag(ast.fncFlags, FncFlags.ClassMethod) ? context.scopeChain.thisType : null; + pushAssignScope(locals, context, thisType, null, ast); } - context.typeFlow.checker.resolveTypeLink(locals, signature.returnType, ast.isSignature()); - } - if (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod)) { - var thisType = ast.isConstructor && hasFlag(ast.fncFlags, FncFlags.ClassMethod) ? context.scopeChain.thisType : null; - pushAssignScope(locals, context, thisType, null, ast); } } -}, preAssignCatchScopes = function(ast, context) { - if (ast.param) { - var catchTable = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), catchLocals = new SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); // REVIEW: Should we be allocating a public table instead of a private one? - ast.containedScope = catchLocals, pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + function preAssignCatchScopes(ast, context) { + if (ast.param) { + var catchTable = new ScopedMembers(new DualStringHashTable(new StringHashTable(), new StringHashTable())), catchLocals = new SymbolScopeBuilder(catchTable, null, null, null, context.scopeChain.scope, context.scopeChain.scope.container); // REVIEW: Should we be allocating a public table instead of a private one? + ast.containedScope = catchLocals, pushAssignScope(catchLocals, context, context.scopeChain.thisType, context.scopeChain.classType, context.scopeChain.fnc); + } } -}, TypeScript1.AssignScopeContext = function AssignScopeContext(scopeChain, typeFlow, modDeclChain) { - _class_call_check(this, AssignScopeContext), this.scopeChain = scopeChain, this.typeFlow = typeFlow, this.modDeclChain = modDeclChain; -}, TypeScript1.pushAssignScope = pushAssignScope, TypeScript1.popAssignScope = popAssignScope, TypeScript1.instanceCompare = instanceCompare, TypeScript1.instanceFilterStop = instanceFilterStop, ScopeSearchFilter = function() { - function ScopeSearchFilter(select, stop) { - _class_call_check(this, ScopeSearchFilter), this.select = select, this.stop = stop, this.result = null; - } - var _proto = ScopeSearchFilter.prototype; - return _proto.reset = function() { - this.result = null; - }, _proto.update = function(b) { - return this.result = this.select(this.result, b), !!this.result && this.stop(this.result); - }, ScopeSearchFilter; -}(), TypeScript1.ScopeSearchFilter = ScopeSearchFilter, TypeScript1.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop), TypeScript1.preAssignModuleScopes = preAssignModuleScopes, TypeScript1.preAssignClassScopes = preAssignClassScopes, TypeScript1.preAssignInterfaceScopes = preAssignInterfaceScopes, TypeScript1.preAssignWithScopes = preAssignWithScopes, TypeScript1.preAssignFuncDeclScopes = preAssignFuncDeclScopes, TypeScript1.preAssignCatchScopes = preAssignCatchScopes, TypeScript1.preAssignScopes = function(ast, parent, walker) { - var context = walker.state, go = !0; - return ast && (ast.nodeType == NodeType.List ? ast.enclosingScope = context.scopeChain.scope : ast.nodeType == NodeType.ModuleDeclaration ? preAssignModuleScopes(ast, context) : ast.nodeType == NodeType.ClassDeclaration ? preAssignClassScopes(ast, context) : ast.nodeType == NodeType.InterfaceDeclaration ? preAssignInterfaceScopes(ast, context) : ast.nodeType == NodeType.With ? preAssignWithScopes(ast, context) : ast.nodeType == NodeType.FuncDecl ? preAssignFuncDeclScopes(ast, context) : ast.nodeType == NodeType.Catch ? preAssignCatchScopes(ast, context) : ast.nodeType == NodeType.TypeRef && (go = !1)), walker.options.goChildren = go, ast; -}, TypeScript1.postAssignScopes = function(ast, parent, walker) { - var context = walker.state, go = !0; - return ast && (ast.nodeType == NodeType.ModuleDeclaration ? (popAssignScope(context), context.modDeclChain.pop(), context.modDeclChain.length >= 1 && (context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1])) : ast.nodeType == NodeType.ClassDeclaration ? popAssignScope(context) : ast.nodeType == NodeType.InterfaceDeclaration ? popAssignScope(context) : ast.nodeType == NodeType.With ? popAssignScope(context) : ast.nodeType == NodeType.FuncDecl ? (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod)) && !ast.isOverload && popAssignScope(context) : ast.nodeType == NodeType.Catch ? ast.param && popAssignScope(context) : go = !1), walker.options.goChildren = go, ast; -}; + TypeScript.ScopeSearchFilter = ScopeSearchFilter, TypeScript.instanceFilter = new ScopeSearchFilter(instanceCompare, instanceFilterStop), TypeScript.preAssignModuleScopes = preAssignModuleScopes, TypeScript.preAssignClassScopes = preAssignClassScopes, TypeScript.preAssignInterfaceScopes = preAssignInterfaceScopes, TypeScript.preAssignWithScopes = preAssignWithScopes, TypeScript.preAssignFuncDeclScopes = preAssignFuncDeclScopes, TypeScript.preAssignCatchScopes = preAssignCatchScopes, TypeScript.preAssignScopes = function(ast, parent, walker) { + var context = walker.state, go = !0; + return ast && (ast.nodeType == NodeType.List ? ast.enclosingScope = context.scopeChain.scope : ast.nodeType == NodeType.ModuleDeclaration ? preAssignModuleScopes(ast, context) : ast.nodeType == NodeType.ClassDeclaration ? preAssignClassScopes(ast, context) : ast.nodeType == NodeType.InterfaceDeclaration ? preAssignInterfaceScopes(ast, context) : ast.nodeType == NodeType.With ? preAssignWithScopes(ast, context) : ast.nodeType == NodeType.FuncDecl ? preAssignFuncDeclScopes(ast, context) : ast.nodeType == NodeType.Catch ? preAssignCatchScopes(ast, context) : ast.nodeType == NodeType.TypeRef && (go = !1)), walker.options.goChildren = go, ast; + }, TypeScript.postAssignScopes = function(ast, parent, walker) { + var context = walker.state, go = !0; + return ast && (ast.nodeType == NodeType.ModuleDeclaration ? (popAssignScope(context), context.modDeclChain.pop(), context.modDeclChain.length >= 1 && (context.typeFlow.checker.currentModDecl = context.modDeclChain[context.modDeclChain.length - 1])) : ast.nodeType == NodeType.ClassDeclaration ? popAssignScope(context) : ast.nodeType == NodeType.InterfaceDeclaration ? popAssignScope(context) : ast.nodeType == NodeType.With ? popAssignScope(context) : ast.nodeType == NodeType.FuncDecl ? (!ast.isConstructor || hasFlag(ast.fncFlags, FncFlags.ClassMethod)) && !ast.isOverload && popAssignScope(context) : ast.nodeType == NodeType.Catch ? ast.param && popAssignScope(context) : go = !1), walker.options.goChildren = go, ast; + }; +}(TypeScript || (TypeScript = {})); diff --git a/crates/swc/tests/tsc-references/recursiveTypesUsedAsFunctionParameters.1.normal.js b/crates/swc/tests/tsc-references/recursiveTypesUsedAsFunctionParameters.1.normal.js index 9af09261ede..9a8fcfdd2bc 100644 --- a/crates/swc/tests/tsc-references/recursiveTypesUsedAsFunctionParameters.1.normal.js +++ b/crates/swc/tests/tsc-references/recursiveTypesUsedAsFunctionParameters.1.normal.js @@ -11,11 +11,11 @@ var MyList = function MyList() { function foo(x) {} function foo2(x) {} function other() { - var foo3 = function foo3(x) {}; - var foo4 = function foo4(x) {}; - var foo5 = function foo5(x) { + function foo3(x) {} + function foo4(x) {} + function foo5(x) { return null; - }; + } var list; var myList; var r = foo5(list); diff --git a/crates/swc/tests/tsc-references/restTuplesFromContextualTypes.1.normal.js b/crates/swc/tests/tsc-references/restTuplesFromContextualTypes.1.normal.js index ad742a6b6a3..3fdc3afac60 100644 --- a/crates/swc/tests/tsc-references/restTuplesFromContextualTypes.1.normal.js +++ b/crates/swc/tests/tsc-references/restTuplesFromContextualTypes.1.normal.js @@ -138,7 +138,6 @@ f3(function(a, b, c) { } }); function f4(t) { - var f = function f(cb) {}; (function() { for(var _len = arguments.length, x = new Array(_len), _key = 0; _key < _len; _key++){ x[_key] = arguments[_key]; @@ -159,6 +158,7 @@ function f4(t) { 1, 2 ].concat(_to_consumable_array(t))); + function f(cb) {} f(function() { for(var _len = arguments.length, x = new Array(_len), _key = 0; _key < _len; _key++){ x[_key] = arguments[_key]; diff --git a/crates/swc/tests/tsc-references/spellingUncheckedJS.1.normal.js b/crates/swc/tests/tsc-references/spellingUncheckedJS.1.normal.js index 5976604de3f..6877b6aabfa 100644 --- a/crates/swc/tests/tsc-references/spellingUncheckedJS.1.normal.js +++ b/crates/swc/tests/tsc-references/spellingUncheckedJS.1.normal.js @@ -7,12 +7,12 @@ import { _ as _create_super } from "@swc/helpers/_/_create_super"; export var inModule = 1; inmodule.toFixed(); function f() { - // @ts-expect-error - "this is fine"; var locals = 2 + true; locale.toFixed(); // @ts-expect-error localf.toExponential(); + // @ts-expect-error + "this is fine"; } var Classe = /*#__PURE__*/ function() { "use strict"; diff --git a/crates/swc/tests/tsc-references/subtypesOfTypeParameter.1.normal.js b/crates/swc/tests/tsc-references/subtypesOfTypeParameter.1.normal.js index e49def34350..c778d82489c 100644 --- a/crates/swc/tests/tsc-references/subtypesOfTypeParameter.1.normal.js +++ b/crates/swc/tests/tsc-references/subtypesOfTypeParameter.1.normal.js @@ -46,14 +46,6 @@ var c = function c() { })(c || (c = {})); // errors throughout function f2(x, y) { - var f17 = function f17(a) { - var r17 = true ? x : a; - var r17 = true ? a : x; - }; - var f18 = function f18(a) { - var r18 = true ? x : a; - var r18 = true ? a : x; - }; var r0 = true ? x : null; var r0 = true ? null : x; var u; @@ -102,6 +94,14 @@ function f2(x, y) { var ac; var r16 = true ? ac : x; var r16 = true ? x : ac; + function f17(a) { + var r17 = true ? x : a; + var r17 = true ? a : x; + } + function f18(a) { + var r18 = true ? x : a; + var r18 = true ? a : x; + } var r19 = true ? new Object() : x; // BCT is Object var r19 = true ? x : new Object(); // BCT is Object var r20 = true ? {} : x; // ok diff --git a/crates/swc/tests/tsc-references/subtypesOfTypeParameterWithConstraints2.1.normal.js b/crates/swc/tests/tsc-references/subtypesOfTypeParameterWithConstraints2.1.normal.js index b366a509ca5..e05e28b15ca 100644 --- a/crates/swc/tests/tsc-references/subtypesOfTypeParameterWithConstraints2.1.normal.js +++ b/crates/swc/tests/tsc-references/subtypesOfTypeParameterWithConstraints2.1.normal.js @@ -129,14 +129,14 @@ function f18(x) { var r16 = true ? x : ac; // ok } function f19(x) { - var f17 = function f17(a) { + function f17(a) { var r17 = true ? x : a; // ok var r17 = true ? a : x; // ok - }; - var f18 = function f18(a) { + } + function f18(a) { var r18 = true ? x : a; // ok var r18 = true ? a : x; // ok - }; + } } function f20(x) { var r19 = true ? new Object() : x; // ok diff --git a/crates/swc/tests/tsc-references/switchStatements.1.normal.js b/crates/swc/tests/tsc-references/switchStatements.1.normal.js index 18c47e9d371..ead8fdaad77 100644 --- a/crates/swc/tests/tsc-references/switchStatements.1.normal.js +++ b/crates/swc/tests/tsc-references/switchStatements.1.normal.js @@ -5,9 +5,9 @@ import { _ as _type_of } from "@swc/helpers/_/_type_of"; import { _ as _create_super } from "@swc/helpers/_/_create_super"; var M; (function(M) { - var fn = function fn(x) { + function fn(x) { return ""; - }; + } M.fn = fn; })(M || (M = {})); var x; diff --git a/crates/swc/tests/tsc-references/thisTypeAndConstraints.1.normal.js b/crates/swc/tests/tsc-references/thisTypeAndConstraints.1.normal.js index 416fe6833b6..dcb9ea4baa5 100644 --- a/crates/swc/tests/tsc-references/thisTypeAndConstraints.1.normal.js +++ b/crates/swc/tests/tsc-references/thisTypeAndConstraints.1.normal.js @@ -12,9 +12,9 @@ var A = /*#__PURE__*/ function() { return A; }(); function f(x) { - var g = function g(x) { + function g(x) { x = x.self(); - }; + } x = x.self(); } var B = /*#__PURE__*/ function() { diff --git a/crates/swc/tests/tsc-references/thisTypeErrors.1.normal.js b/crates/swc/tests/tsc-references/thisTypeErrors.1.normal.js index 882b160264a..0a3e1dc1037 100644 --- a/crates/swc/tests/tsc-references/thisTypeErrors.1.normal.js +++ b/crates/swc/tests/tsc-references/thisTypeErrors.1.normal.js @@ -38,9 +38,9 @@ var C3 = /*#__PURE__*/ function() { } var _proto = C3.prototype; _proto.f = function f() { - var g = function g(x) { + function g(x) { return undefined; - }; + } var x2 = { h: function h(x) { return undefined; diff --git a/crates/swc/tests/tsc-references/throwStatements.1.normal.js b/crates/swc/tests/tsc-references/throwStatements.1.normal.js index dc4aa5e7531..2872e97a9cb 100644 --- a/crates/swc/tests/tsc-references/throwStatements.1.normal.js +++ b/crates/swc/tests/tsc-references/throwStatements.1.normal.js @@ -15,14 +15,14 @@ function F(x) { } var M; (function(M) { - var F2 = function F2(x) { - return x.toString(); - }; var A = function A() { "use strict"; _class_call_check(this, A); }; M.A = A; + function F2(x) { + return x.toString(); + } M.F2 = F2; })(M || (M = {})); var aNumber = 9.9; diff --git a/crates/swc/tests/tsc-references/typeFromPropertyAssignment20.1.normal.js b/crates/swc/tests/tsc-references/typeFromPropertyAssignment20.1.normal.js index 5d322357ae4..7fdbdbceb39 100644 --- a/crates/swc/tests/tsc-references/typeFromPropertyAssignment20.1.normal.js +++ b/crates/swc/tests/tsc-references/typeFromPropertyAssignment20.1.normal.js @@ -2,9 +2,9 @@ !function outer(f) { return f; }(function inner() { - var Async = function Async() { + function Async() { this._trampolineEnabled = true; - }; + } Async.prototype.disableTrampolineIfNecessary = function dtin(b) { if (b) { this._trampolineEnabled = false; diff --git a/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.1.normal.js b/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.1.normal.js index f1118d704dc..a2c48a2bbb0 100644 --- a/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.1.normal.js +++ b/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.1.normal.js @@ -49,11 +49,11 @@ ExpandoMerge.p1 = 111; var n = ExpandoMerge.p1 + ExpandoMerge.p2 + ExpandoMerge.p3 + ExpandoMerge(1); var Ns; (function(Ns) { - var ExpandoNamespace = function ExpandoNamespace() {}; - var foo = function foo() { - return ExpandoNamespace; - }; + function ExpandoNamespace() {} ExpandoNamespace.p6 = 42; + function foo() { + return ExpandoNamespace; + } Ns.foo = foo; })(Ns || (Ns = {})); // Should not work in Typescript -- must be const diff --git a/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.2.minified.js b/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.2.minified.js index 4ab9a8e3779..68a7e05627b 100644 --- a/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.2.minified.js +++ b/crates/swc/tests/tsc-references/typeFromPropertyAssignment29.2.minified.js @@ -6,7 +6,7 @@ function ExpandoDecl(n) { ExpandoDecl.prop = 2, ExpandoDecl.m = function(n) { return n + 1; }, ExpandoDecl.prop, ExpandoDecl.m(12), ExpandoDecl(101).length; -var Ns, ExpandoNamespace, Ns1, ExpandoExpr = function(n) { +var Ns, ExpandoExpr = function(n) { return n.toString(); }; ExpandoExpr.prop = { @@ -24,9 +24,12 @@ function ExpandoMerge(n) { } ExpandoArrow.prop = 2, ExpandoArrow.m = function(n) { return n + 1; -}, ExpandoMerge.p1 = 111, (ExpandoMerge || (ExpandoMerge = {})).p2 = 222, (ExpandoMerge || (ExpandoMerge = {})).p3 = 333, ExpandoMerge.p1, ExpandoMerge.p2, ExpandoMerge.p3, ExpandoMerge(1), Ns = Ns1 || (Ns1 = {}), (ExpandoNamespace = function() {}).p6 = 42, Ns.foo = function() { - return ExpandoNamespace; -}; +}, ExpandoMerge.p1 = 111, (ExpandoMerge || (ExpandoMerge = {})).p2 = 222, (ExpandoMerge || (ExpandoMerge = {})).p3 = 333, ExpandoMerge.p1, ExpandoMerge.p2, ExpandoMerge.p3, ExpandoMerge(1), function(Ns) { + function ExpandoNamespace() {} + ExpandoNamespace.p6 = 42, Ns.foo = function() { + return ExpandoNamespace; + }; +}(Ns || (Ns = {})); // Should not work in Typescript -- must be const var ExpandoExpr2 = function(n) { return n.toString(); diff --git a/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.1.normal.js b/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.1.normal.js index 9e6d62f3fd4..cf4cf70a150 100644 --- a/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.1.normal.js +++ b/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.1.normal.js @@ -1,29 +1,29 @@ //// [typeFromPropertyAssignment36.ts] function f(b) { - var _$d = function _$d() {}; - _$d.e = 12; - _$d.e; + function d() {} + d.e = 12; + d.e; if (b) { - _$d.q = false; + d.q = false; } // error d.q might not be assigned - _$d.q; + d.q; if (b) { - _$d.q = false; + d.q = false; } else { - _$d.q = true; + d.q = true; } - _$d.q; + d.q; if (b) { - _$d.r = 1; + d.r = 1; } else { - _$d.r = 2; + d.r = 2; } - _$d.r; + d.r; if (b) { - _$d.s = "hi"; + d.s = "hi"; } - return _$d; + return d; } // OK to access possibly-unassigned properties outside the initialising scope var test = f(true).s; diff --git a/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.2.minified.js b/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.2.minified.js index c5d667da9bd..bccfefa2062 100644 --- a/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.2.minified.js +++ b/crates/swc/tests/tsc-references/typeFromPropertyAssignment36.2.minified.js @@ -1,8 +1,11 @@ //// [typeFromPropertyAssignment36.ts] function d() {} -((_$d = function() {}).e = 12, _$d.e, _$d.q = !1, // error d.q might not be assigned -_$d.q, _$d.q = !1, _$d.q, _$d.r = 1, _$d.r, _$d.s = "hi", _$d).s, d.e = 12, d.e, d.q, d.q = !0, d.q, d.r = 2, d.r; +(function(b) { + function d() {} + return d.e = 12, d.e, b && (d.q = !1), // error d.q might not be assigned + d.q, b ? d.q = !1 : d.q = !0, d.q, b ? d.r = 1 : d.r = 2, d.r, b && (d.s = "hi"), d; +})(!0).s, d.e = 12, d.e, d.q, d.q = !0, d.q, d.r = 2, d.r; // test function expressions too -var _$d, g = function() {}; +var g = function() {}; g.expando // error , g.both = 0, g.both; diff --git a/crates/swc/tests/tsc-references/typeGuardsDefeat.1.normal.js b/crates/swc/tests/tsc-references/typeGuardsDefeat.1.normal.js index f0c0b2e8f9c..3698a96f3ff 100644 --- a/crates/swc/tests/tsc-references/typeGuardsDefeat.1.normal.js +++ b/crates/swc/tests/tsc-references/typeGuardsDefeat.1.normal.js @@ -2,9 +2,9 @@ // Also note that it is possible to defeat a type guard by calling a function that changes the // type of the guarded variable. function foo(x) { - var f = function f() { + function f() { x = 10; - }; + } if (typeof x === "string") { f(); return x.length; // string diff --git a/crates/swc/tests/tsc-references/typeGuardsInFunction.1.normal.js b/crates/swc/tests/tsc-references/typeGuardsInFunction.1.normal.js index 0ccdd33e704..caa36a99733 100644 --- a/crates/swc/tests/tsc-references/typeGuardsInFunction.1.normal.js +++ b/crates/swc/tests/tsc-references/typeGuardsInFunction.1.normal.js @@ -16,7 +16,8 @@ function f(param) { } // local function declaration function f1(param) { - var f2 = function f2(param1) { + var var2; + function f2(param1) { // global vars in function declaration num = typeof var1 === "string" && var1.length; // string // variables from outer function declaration @@ -27,8 +28,7 @@ function f1(param) { var var3; num = typeof var3 === "string" && var3.length; // string num = typeof param1 === "string" && param1.length; // string - }; - var var2; + } } // Function expression function f2(param) { diff --git a/crates/swc/tests/tsc-references/typeOfThisInFunctionExpression.1.normal.js b/crates/swc/tests/tsc-references/typeOfThisInFunctionExpression.1.normal.js index a84a0c022c1..3993bd69bd5 100644 --- a/crates/swc/tests/tsc-references/typeOfThisInFunctionExpression.1.normal.js +++ b/crates/swc/tests/tsc-references/typeOfThisInFunctionExpression.1.normal.js @@ -27,10 +27,10 @@ var C = function C() { }; var M; (function(M) { - var fn = function fn() { + function fn() { var p = this; var p; - }; + } var t = function t() { var p = this; var p; diff --git a/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint2.1.normal.js b/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint2.1.normal.js index 1e636ac5e29..b54c139c984 100644 --- a/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint2.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint2.1.normal.js @@ -2,36 +2,36 @@ // Type parameters are in scope in their own and other type parameter lists // Nested local functions function foo(x, y) { - var bar = function bar() { + function bar() { function baz(a, b) { x = y; return y; } - }; + } } function foo2(x, y) { - var bar = function bar() { + function bar() { function baz(a, b) { x = y; return y; } - }; + } } var f = function f(x, y) { - var bar = function bar() { + function bar() { var g = function g(a, b) { x = y; return y; }; - }; + } }; var f2 = function f2(x, y) { - var bar = function bar() { + function bar() { var g = function baz(a, b) { x = y; return y; }; - }; + } }; var f3 = function(x, y) { var bar = function bar() { diff --git a/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint4.1.normal.js b/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint4.1.normal.js index df8b7a6dece..5c8e69643c4 100644 --- a/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint4.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParameterUsedAsTypeParameterConstraint4.1.normal.js @@ -15,20 +15,20 @@ var C = /*#__PURE__*/ function() { return C; }(); function foo(x, y) { - var bar = function bar() { + function bar() { function baz(a, b) { x = y; return y; } - }; + } } function foo2(x, y) { - var bar = function bar() { + function bar() { function baz(a, b) { x = y; return y; } - }; + } } var f3 = function(x, y) { var bar = function bar(r, s) { diff --git a/crates/swc/tests/tsc-references/typeParametersAreIdenticalToThemselves.1.normal.js b/crates/swc/tests/tsc-references/typeParametersAreIdenticalToThemselves.1.normal.js index af365d5ba45..cdae603e40b 100644 --- a/crates/swc/tests/tsc-references/typeParametersAreIdenticalToThemselves.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParametersAreIdenticalToThemselves.1.normal.js @@ -4,8 +4,8 @@ import { _ as _class_call_check } from "@swc/helpers/_/_class_call_check"; function foo1(x) {} function foo2(x) {} function foo3(x, y) { - var inner = function inner(x) {}; - var inner2 = function inner2(x) {}; + function inner(x) {} + function inner2(x) {} } var C = /*#__PURE__*/ function() { "use strict"; diff --git a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope.1.normal.js b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope.1.normal.js index 91f2a0c1bc2..90214c42f75 100644 --- a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope.1.normal.js @@ -11,10 +11,10 @@ var C = /*#__PURE__*/ function() { } var _proto = C.prototype; _proto.foo = function foo() { - var temp = function temp(a) { + function temp(a) { var y; return y; - }; + } return temp(null); }; return C; diff --git a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope2.1.normal.js b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope2.1.normal.js index 462741e92d0..52f55580afd 100644 --- a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope2.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope2.1.normal.js @@ -1,10 +1,10 @@ //// [typeParametersAvailableInNestedScope2.ts] function foo(x, y) { - var bar = function bar(z) { + function bar(z) { function baz(a) { var c; var d; var e; } - }; + } } diff --git a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope3.1.normal.js b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope3.1.normal.js index e01e404627e..3ebc59ea7a6 100644 --- a/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope3.1.normal.js +++ b/crates/swc/tests/tsc-references/typeParametersAvailableInNestedScope3.1.normal.js @@ -1,12 +1,12 @@ //// [typeParametersAvailableInNestedScope3.ts] function foo(v) { - var a = function a(a) { + function a(a) { return a; - }; - var b = function b() { + } + function b() { return v; - }; - var c = function c(v) { + } + function c(v) { function a(a) { return a; } @@ -17,7 +17,7 @@ function foo(v) { a: a, b: b }; - }; + } return { a: a, b: b, diff --git a/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints3.1.normal.js b/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints3.1.normal.js index ce0056dcfe8..75d9a122493 100644 --- a/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints3.1.normal.js +++ b/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints3.1.normal.js @@ -8,9 +8,9 @@ var C = /*#__PURE__*/ function() { } var _proto = C.prototype; _proto.foo = function foo(x) { - var bar = function bar(x) { + function bar(x) { return x; - }; + } return bar; }; return C; diff --git a/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints4.1.normal.js b/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints4.1.normal.js index a4cf219994a..4a700de039a 100644 --- a/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints4.1.normal.js +++ b/crates/swc/tests/tsc-references/wrappedAndRecursiveConstraints4.1.normal.js @@ -7,9 +7,9 @@ var C = /*#__PURE__*/ function() { } var _proto = C.prototype; _proto.foo = function foo(x) { - var bar = function bar(x) { + function bar(x) { return x; - }; + } return bar; }; return C; diff --git a/crates/swc/tests/vercel/full/d3-time-format/1/output/index.js b/crates/swc/tests/vercel/full/d3-time-format/1/output/index.js index 21d1937dfcf..7b4a9ebc282 100644 --- a/crates/swc/tests/vercel/full/d3-time-format/1/output/index.js +++ b/crates/swc/tests/vercel/full/d3-time-format/1/output/index.js @@ -26,48 +26,18 @@ function h(n, t, e) { }; } export default function v(e) { - var u = function(t, e) { - return function(r) { - var u, c, i, o = [], f = -1, a = 0, l = t.length; - for(n(r, Date) || (r = new Date(+r)); ++f < l;)37 === t.charCodeAt(f) && (o.push(t.slice(a, f)), null != (c = y[u = t.charAt(++f)]) ? u = t.charAt(++f) : c = "e" === u ? " " : "0", (i = e[u]) && (u = i(r, c)), o.push(u), a = f + 1); - return o.push(t.slice(a, f)), o.join(""); - }; - }, c = function(n, e) { - return function(u) { - var c, a, l = h(1900, void 0, 1); - if (o(l, n, u += "", 0) != u.length) return null; - // If a UNIX timestamp is specified, return it. - if ("Q" in l) return new Date(l.Q); - if ("s" in l) return new Date(1000 * l.s + ("L" in l ? l.L : 0)); - // Convert day-of-week and week-of-year to day-of-year. - if (!e || "Z" in l || (l.Z = 0), "p" in l && (l.H = l.H % 12 + 12 * l.p), void 0 === l.m && (l.m = "q" in l ? l.q : 0), "V" in l) { - if (l.V < 1 || l.V > 53) return null; - "w" in l || (l.w = 1), "Z" in l ? (c = (a = (c = s(h(l.y, 0, 1))).getUTCDay()) > 4 || 0 === a ? f.ceil(c) : f(c), c = i.offset(c, (l.V - 1) * 7), l.y = c.getUTCFullYear(), l.m = c.getUTCMonth(), l.d = c.getUTCDate() + (l.w + 6) % 7) : (c = (a = (c = g(h(l.y, 0, 1))).getDay()) > 4 || 0 === a ? r.ceil(c) : r(c), c = t.offset(c, (l.V - 1) * 7), l.y = c.getFullYear(), l.m = c.getMonth(), l.d = c.getDate() + (l.w + 6) % 7); - } else ("W" in l || "U" in l) && ("w" in l || (l.w = "u" in l ? l.u % 7 : "W" in l ? 1 : 0), a = "Z" in l ? s(h(l.y, 0, 1)).getUTCDay() : g(h(l.y, 0, 1)).getDay(), l.m = 0, l.d = "W" in l ? (l.w + 6) % 7 + 7 * l.W - (a + 5) % 7 : l.w + 7 * l.U - (a + 6) % 7); - return(// If a time zone is specified, all fields are interpreted as UTC and then - // offset according to the specified time zone. - "Z" in l ? (l.H += l.Z / 100 | 0, l.M += l.Z % 100, s(l)) : g(l)); - }; - }, o = function(n, t, e, r) { - for(var u, c, i = 0, o = t.length, f = e.length; i < o;){ - if (r >= f) return -1; - if (37 === (u = t.charCodeAt(i++))) { - if (!(c = nG[(u = t.charAt(i++)) in y ? t.charAt(i++) : u]) || (r = c(n, e, r)) < 0) return -1; - } else if (u != e.charCodeAt(r++)) return -1; - } - return r; - }, a = e.dateTime, l = e.date, v = e.time, C = e.periods, U = e.days, d = e.shortDays, D = e.months, x = e.shortMonths, nn = T(C), nx = m(C), nA = T(U), nV = m(U), nW = T(d), nj = m(d), nq = T(D), nQ = m(D), nX = T(x), n_ = m(x), nb = { + var u = e.dateTime, c = e.date, o = e.time, a = e.periods, l = e.days, v = e.shortDays, C = e.months, U = e.shortMonths, d = T(a), D = m(a), x = T(l), nn = m(l), nx = T(v), nA = m(v), nV = T(C), nW = m(C), nj = T(U), nq = m(U), nQ = { a: function(n) { - return d[n.getDay()]; + return v[n.getDay()]; }, A: function(n) { - return U[n.getDay()]; + return l[n.getDay()]; }, b: function(n) { - return x[n.getMonth()]; + return U[n.getMonth()]; }, B: function(n) { - return D[n.getMonth()]; + return C[n.getMonth()]; }, c: null, d: I, @@ -82,7 +52,7 @@ export default function v(e) { m: R, M: k, p: function(n) { - return C[+(n.getHours() >= 12)]; + return a[+(n.getHours() >= 12)]; }, q: function(n) { return 1 + ~~(n.getMonth() / 3); @@ -101,18 +71,18 @@ export default function v(e) { Y: ni, Z: nf, "%": nY - }, nB = { + }, nX = { a: function(n) { - return d[n.getUTCDay()]; + return v[n.getUTCDay()]; }, A: function(n) { - return U[n.getUTCDay()]; + return l[n.getUTCDay()]; }, b: function(n) { - return x[n.getUTCMonth()]; + return U[n.getUTCMonth()]; }, B: function(n) { - return D[n.getUTCMonth()]; + return C[n.getUTCMonth()]; }, c: null, d: na, @@ -127,7 +97,7 @@ export default function v(e) { m: ny, M: nC, p: function(n) { - return C[+(n.getUTCHours() >= 12)]; + return a[+(n.getUTCHours() >= 12)]; }, q: function(n) { return 1 + ~~(n.getUTCMonth() / 3); @@ -146,25 +116,25 @@ export default function v(e) { Y: nH, Z: nS, "%": nY - }, nG = { + }, n_ = { a: function(n, t, e) { - var r = nW.exec(t.slice(e)); - return r ? (n.w = nj.get(r[0].toLowerCase()), e + r[0].length) : -1; + var r = nx.exec(t.slice(e)); + return r ? (n.w = nA.get(r[0].toLowerCase()), e + r[0].length) : -1; }, A: function(n, t, e) { - var r = nA.exec(t.slice(e)); - return r ? (n.w = nV.get(r[0].toLowerCase()), e + r[0].length) : -1; + var r = x.exec(t.slice(e)); + return r ? (n.w = nn.get(r[0].toLowerCase()), e + r[0].length) : -1; }, b: function(n, t, e) { - var r = nX.exec(t.slice(e)); - return r ? (n.m = n_.get(r[0].toLowerCase()), e + r[0].length) : -1; + var r = nj.exec(t.slice(e)); + return r ? (n.m = nq.get(r[0].toLowerCase()), e + r[0].length) : -1; }, B: function(n, t, e) { - var r = nq.exec(t.slice(e)); - return r ? (n.m = nQ.get(r[0].toLowerCase()), e + r[0].length) : -1; + var r = nV.exec(t.slice(e)); + return r ? (n.m = nW.get(r[0].toLowerCase()), e + r[0].length) : -1; }, c: function(n, t, e) { - return o(n, a, t, e); + return nG(n, u, t, e); }, d: V, e: V, @@ -178,8 +148,8 @@ export default function v(e) { m: A, M: q, p: function(n, t, e) { - var r = nn.exec(t.slice(e)); - return r ? (n.p = nx.get(r[0].toLowerCase()), e + r[0].length) : -1; + var r = d.exec(t.slice(e)); + return r ? (n.p = D.get(r[0].toLowerCase()), e + r[0].length) : -1; }, q: Z, Q: B, @@ -191,38 +161,71 @@ export default function v(e) { w: w, W: L, x: function(n, t, e) { - return o(n, l, t, e); + return nG(n, c, t, e); }, X: function(n, t, e) { - return o(n, v, t, e); + return nG(n, o, t, e); }, y: Y, Y: S, Z: F, "%": b }; + function nb(t, e) { + return function(r) { + var u, c, i, o = [], f = -1, a = 0, l = t.length; + for(n(r, Date) || (r = new Date(+r)); ++f < l;)37 === t.charCodeAt(f) && (o.push(t.slice(a, f)), null != (c = y[u = t.charAt(++f)]) ? u = t.charAt(++f) : c = "e" === u ? " " : "0", (i = e[u]) && (u = i(r, c)), o.push(u), a = f + 1); + return o.push(t.slice(a, f)), o.join(""); + }; + } + function nB(n, e) { + return function(u) { + var c, o, a = h(1900, void 0, 1); + if (nG(a, n, u += "", 0) != u.length) return null; + // If a UNIX timestamp is specified, return it. + if ("Q" in a) return new Date(a.Q); + if ("s" in a) return new Date(1000 * a.s + ("L" in a ? a.L : 0)); + // Convert day-of-week and week-of-year to day-of-year. + if (!e || "Z" in a || (a.Z = 0), "p" in a && (a.H = a.H % 12 + 12 * a.p), void 0 === a.m && (a.m = "q" in a ? a.q : 0), "V" in a) { + if (a.V < 1 || a.V > 53) return null; + "w" in a || (a.w = 1), "Z" in a ? (c = (o = (c = s(h(a.y, 0, 1))).getUTCDay()) > 4 || 0 === o ? f.ceil(c) : f(c), c = i.offset(c, (a.V - 1) * 7), a.y = c.getUTCFullYear(), a.m = c.getUTCMonth(), a.d = c.getUTCDate() + (a.w + 6) % 7) : (c = (o = (c = g(h(a.y, 0, 1))).getDay()) > 4 || 0 === o ? r.ceil(c) : r(c), c = t.offset(c, (a.V - 1) * 7), a.y = c.getFullYear(), a.m = c.getMonth(), a.d = c.getDate() + (a.w + 6) % 7); + } else ("W" in a || "U" in a) && ("w" in a || (a.w = "u" in a ? a.u % 7 : "W" in a ? 1 : 0), o = "Z" in a ? s(h(a.y, 0, 1)).getUTCDay() : g(h(a.y, 0, 1)).getDay(), a.m = 0, a.d = "W" in a ? (a.w + 6) % 7 + 7 * a.W - (o + 5) % 7 : a.w + 7 * a.U - (o + 6) % 7); + return(// If a time zone is specified, all fields are interpreted as UTC and then + // offset according to the specified time zone. + "Z" in a ? (a.H += a.Z / 100 | 0, a.M += a.Z % 100, s(a)) : g(a)); + }; + } + function nG(n, t, e, r) { + for(var u, c, i = 0, o = t.length, f = e.length; i < o;){ + if (r >= f) return -1; + if (37 === (u = t.charCodeAt(i++))) { + if (!(c = n_[(u = t.charAt(i++)) in y ? t.charAt(i++) : u]) || (r = c(n, e, r)) < 0) return -1; + } else if (u != e.charCodeAt(r++)) return -1; + } + return r; + } return(// These recursive directive definitions must be deferred. - nb.x = u(l, nb), nb.X = u(v, nb), nb.c = u(a, nb), nB.x = u(l, nB), nB.X = u(v, nB), nB.c = u(a, nB), { + nQ.x = nb(c, nQ), nQ.X = nb(o, nQ), nQ.c = nb(u, nQ), nX.x = nb(c, nX), nX.X = nb(o, nX), nX.c = nb(u, nX), { format: function(n) { - var t = u(n += "", nb); + var t = nb(n += "", nQ); return t.toString = function() { return n; }, t; }, parse: function(n) { - var t = c(n += "", !1); + var t = nB(n += "", !1); return t.toString = function() { return n; }, t; }, utcFormat: function(n) { - var t = u(n += "", nB); + var t = nb(n += "", nX); return t.toString = function() { return n; }, t; }, utcParse: function(n) { - var t = c(n += "", !0); + var t = nB(n += "", !0); return t.toString = function() { return n; }, t; diff --git a/crates/swc/tests/vercel/full/firebase/dist/1/output/index.js b/crates/swc/tests/vercel/full/firebase/dist/1/output/index.js index ce29df0cd3a..7441a4da5b4 100644 --- a/crates/swc/tests/vercel/full/firebase/dist/1/output/index.js +++ b/crates/swc/tests/vercel/full/firebase/dist/1/output/index.js @@ -1,4 +1,4 @@ -var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@firebase/component"), a = require("@firebase/app"), o = require("@firebase/logger"), p = /*#__PURE__*/ function(e) { +var e, t = require("@firebase/util"), n = require("tslib"), r = require("@firebase/component"), i = require("@firebase/app"), a = require("@firebase/logger"), o = /*#__PURE__*/ function(e) { if (e && e.__esModule) return e; var t = Object.create(null); return e && Object.keys(e).forEach(function(n) { @@ -12,41 +12,43 @@ var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@fir }); } }), t.default = e, Object.freeze(t); -}(a), s = (Object.defineProperty((e = function(e, t) { - var n = this; - this._delegate = e, this.firebase = t, // add itself to container - a._addComponent(e, new i.Component("app-compat", function() { - return n; - }, "PUBLIC" /* PUBLIC */ )), this.container = e.container; -}).prototype, "automaticDataCollectionEnabled", { - get: function() { - return this._delegate.automaticDataCollectionEnabled; - }, - set: function(e) { - this._delegate.automaticDataCollectionEnabled = e; - }, - enumerable: !1, - configurable: !0 -}), Object.defineProperty(e.prototype, "name", { - get: function() { - return this._delegate.name; - }, - enumerable: !1, - configurable: !0 -}), Object.defineProperty(e.prototype, "options", { - get: function() { - return this._delegate.options; - }, - enumerable: !1, - configurable: !0 -}), e.prototype.delete = function() { - var e = this; - return new Promise(function(t) { - e._delegate.checkDestroyed(), t(); - }).then(function() { - return e.firebase.INTERNAL.removeApp(e.name), a.deleteApp(e._delegate); - }); -}, /** +}(i), p = /** @class */ function() { + function e(e, t) { + var n = this; + this._delegate = e, this.firebase = t, // add itself to container + i._addComponent(e, new r.Component("app-compat", function() { + return n; + }, "PUBLIC" /* PUBLIC */ )), this.container = e.container; + } + return Object.defineProperty(e.prototype, "automaticDataCollectionEnabled", { + get: function() { + return this._delegate.automaticDataCollectionEnabled; + }, + set: function(e) { + this._delegate.automaticDataCollectionEnabled = e; + }, + enumerable: !1, + configurable: !0 + }), Object.defineProperty(e.prototype, "name", { + get: function() { + return this._delegate.name; + }, + enumerable: !1, + configurable: !0 + }), Object.defineProperty(e.prototype, "options", { + get: function() { + return this._delegate.options; + }, + enumerable: !1, + configurable: !0 + }), e.prototype.delete = function() { + var e = this; + return new Promise(function(t) { + e._delegate.checkDestroyed(), t(); + }).then(function() { + return e.firebase.INTERNAL.removeApp(e.name), i.deleteApp(e._delegate); + }); + }, /** * Return a service instance associated with this app (creating it * on demand), identified by the passed instanceIdentifier. * @@ -60,14 +62,14 @@ var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@fir * The service name is passed to this already * @internal */ e.prototype._getService = function(e, t) { - void 0 === t && (t = a._DEFAULT_ENTRY_NAME), this._delegate.checkDestroyed(); - // Initialize instance if InstatiationMode is `EXPLICIT`. - var n, r = this._delegate.container.getProvider(e); - // getImmediate will always succeed because _getService is only called for registered components. - return r.isInitialized() || (null === (n = r.getComponent()) || void 0 === n ? void 0 : n.instantiationMode) !== "EXPLICIT" /* EXPLICIT */ || r.initialize(), r.getImmediate({ - identifier: t - }); -}, /** + void 0 === t && (t = i._DEFAULT_ENTRY_NAME), this._delegate.checkDestroyed(); + // Initialize instance if InstatiationMode is `EXPLICIT`. + var n, r = this._delegate.container.getProvider(e); + // getImmediate will always succeed because _getService is only called for registered components. + return r.isInitialized() || (null === (n = r.getComponent()) || void 0 === n ? void 0 : n.instantiationMode) !== "EXPLICIT" /* EXPLICIT */ || r.initialize(), r.getImmediate({ + identifier: t + }); + }, /** * Remove a service instance from the cache, so we will create a new instance for this service * when people try to get it again. * @@ -77,22 +79,23 @@ var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@fir * @param instanceIdentifier instance identifier in case multiple instances are allowed * @internal */ e.prototype._removeServiceInstance = function(e, t) { - void 0 === t && (t = a._DEFAULT_ENTRY_NAME), this._delegate.container// eslint-disable-next-line @typescript-eslint/no-explicit-any - .getProvider(e).clearInstance(t); -}, /** + void 0 === t && (t = i._DEFAULT_ENTRY_NAME), this._delegate.container// eslint-disable-next-line @typescript-eslint/no-explicit-any + .getProvider(e).clearInstance(t); + }, /** * @param component the component being added to this app's container * @internal */ e.prototype._addComponent = function(e) { - a._addComponent(this._delegate, e); -}, e.prototype._addOrOverwriteComponent = function(e) { - a._addOrOverwriteComponent(this._delegate, e); -}, e.prototype.toJSON = function() { - return { - name: this.name, - automaticDataCollectionEnabled: this.automaticDataCollectionEnabled, - options: this.options - }; -}, e), c = ((t = {})["no-app" /* NO_APP */ ] = "No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()", t["invalid-app-argument" /* INVALID_APP_ARGUMENT */ ] = "firebase.{$appName}() takes either no argument or a Firebase App instance.", t), u = new n.ErrorFactory("app-compat", "Firebase", c), l = /** + i._addComponent(this._delegate, e); + }, e.prototype._addOrOverwriteComponent = function(e) { + i._addOrOverwriteComponent(this._delegate, e); + }, e.prototype.toJSON = function() { + return { + name: this.name, + automaticDataCollectionEnabled: this.automaticDataCollectionEnabled, + options: this.options + }; + }, e; +}(), s = ((e = {})["no-app" /* NO_APP */ ] = "No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()", e["invalid-app-argument" /* INVALID_APP_ARGUMENT */ ] = "firebase.{$appName}() takes either no argument or a Firebase App instance.", e), c = new t.ErrorFactory("app-compat", "Firebase", s), u = /** * @license * Copyright 2019 Google LLC * @@ -114,117 +117,142 @@ var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@fir * assigned to the 'firebase' global. It may be called multiple times * in unit tests. */ function e() { - var t, i, a, o = (t = /** - * Get the App object for a given name (or DEFAULT). - */ function(e) { - if (e = e || p._DEFAULT_ENTRY_NAME, !n.contains(i, e)) throw u.create("no-app" /* NO_APP */ , { - appName: e - }); - return i[e]; - }, i = {}, // Inject a circular default export to allow Babel users who were previously - // using: - // - // import firebase from 'firebase'; - // which becomes: var firebase = require('firebase').default; - // - // instead of - // - // import * as firebase from 'firebase'; - // which becomes: var firebase = require('firebase'); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (a = { - // Hack to prevent Babel from modifying the object returned - // as the firebase namespace. - // @ts-ignore - __esModule: !0, - initializeApp: /** + var r = /** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** + * Because auth can't share code with other components, we attach the utility functions + * in an internal namespace to share code. + * This function return a firebase namespace object without + * any utility functions, so it can be shared between the regular firebaseNamespace and + * the lite version. + */ function(e) { + var n = {}, r = { + // Hack to prevent Babel from modifying the object returned + // as the firebase namespace. + // @ts-ignore + __esModule: !0, + initializeApp: /** * Create a new App instance (name must be unique). * * This function is idempotent. It can be called more than once and return the same instance using the same options and config. - */ function(e, t) { - void 0 === t && (t = {}); - var r = p.initializeApp(e, t); - if (n.contains(i, r.name)) return i[r.name]; - var o = new s(r, a); - return i[r.name] = o, o; - }, - // @ts-ignore - app: t, - registerVersion: p.registerVersion, - setLogLevel: p.setLogLevel, - onLog: p.onLog, - // @ts-ignore - apps: null, - SDK_VERSION: p.SDK_VERSION, - INTERNAL: { - registerComponent: function(e) { - var r = e.name, i = r.replace("-compat", ""); - if (p._registerComponent(e) && "PUBLIC" /* PUBLIC */ === e.type) { - // create service namespace for public components - // The Service namespace is an accessor function ... - var o = function(e) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (void 0 === e && (e = t()), "function" != typeof e[i]) // Invalid argument. - // This happens in the following case: firebase.storage('gs:/') - throw u.create("invalid-app-argument" /* INVALID_APP_ARGUMENT */ , { - appName: r - }); - // Forward service instance lookup to the FirebaseApp. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return e[i](); - }; - void 0 !== e.serviceProps && n.deepExtend(o, e.serviceProps), // eslint-disable-next-line @typescript-eslint/no-explicit-any - a[i] = o, // Patch the FirebaseAppImpl prototype - // eslint-disable-next-line @typescript-eslint/no-explicit-any - s.prototype[i] = // TODO: The eslint disable can be removed and the 'ignoreRestArgs' - // option added to the no-explicit-any rule when ESlint releases it. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function() { - for(var t = [], n = 0; n < arguments.length; n++)t[n] = arguments[n]; - return this._getService.bind(this, r).apply(this, e.multipleInstances ? t : []); - }; - } - return "PUBLIC" /* PUBLIC */ === e.type ? a[i] : null; + */ function(i, a) { + void 0 === a && (a = {}); + var p = o.initializeApp(i, a); + if (t.contains(n, p.name)) return n[p.name]; + var s = new e(p, r); + return n[p.name] = s, s; }, - removeApp: /** + // @ts-ignore + app: i, + registerVersion: o.registerVersion, + setLogLevel: o.setLogLevel, + onLog: o.onLog, + // @ts-ignore + apps: null, + SDK_VERSION: o.SDK_VERSION, + INTERNAL: { + registerComponent: function(n) { + var a = n.name, p = a.replace("-compat", ""); + if (o._registerComponent(n) && "PUBLIC" /* PUBLIC */ === n.type) { + // create service namespace for public components + // The Service namespace is an accessor function ... + var s = function(e) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (void 0 === e && (e = i()), "function" != typeof e[p]) // Invalid argument. + // This happens in the following case: firebase.storage('gs:/') + throw c.create("invalid-app-argument" /* INVALID_APP_ARGUMENT */ , { + appName: a + }); + // Forward service instance lookup to the FirebaseApp. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return e[p](); + }; + void 0 !== n.serviceProps && t.deepExtend(s, n.serviceProps), // eslint-disable-next-line @typescript-eslint/no-explicit-any + r[p] = s, // Patch the FirebaseAppImpl prototype + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e.prototype[p] = // TODO: The eslint disable can be removed and the 'ignoreRestArgs' + // option added to the no-explicit-any rule when ESlint releases it. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + function() { + for(var e = [], t = 0; t < arguments.length; t++)e[t] = arguments[t]; + return this._getService.bind(this, a).apply(this, n.multipleInstances ? e : []); + }; + } + return "PUBLIC" /* PUBLIC */ === n.type ? r[p] : null; + }, + removeApp: /** * Called by App.delete() - but before any services associated with the App * are deleted. */ function(e) { - delete i[e]; - }, - useAsService: // Map the requested service to a registered service name - // (used to map auth to serverAuth service when needed). - function(e, t) { - return "serverAuth" === t ? null : t; - }, - modularAPIs: p + delete n[e]; + }, + useAsService: // Map the requested service to a registered service name + // (used to map auth to serverAuth service when needed). + function(e, t) { + return "serverAuth" === t ? null : t; + }, + modularAPIs: o + } + }; + /** + * Get the App object for a given name (or DEFAULT). + */ function i(e) { + if (e = e || o._DEFAULT_ENTRY_NAME, !t.contains(n, e)) throw c.create("no-app" /* NO_APP */ , { + appName: e + }); + return n[e]; } - }).default = a, // firebase.apps is a read-only getter. - Object.defineProperty(a, "apps", { - get: /* + return(// Inject a circular default export to allow Babel users who were previously + // using: + // + // import firebase from 'firebase'; + // which becomes: var firebase = require('firebase').default; + // + // instead of + // + // import * as firebase from 'firebase'; + // which becomes: var firebase = require('firebase'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + r.default = r, // firebase.apps is a read-only getter. + Object.defineProperty(r, "apps", { + get: /* * Return an array of all the non-deleted FirebaseApps. */ function() { - // Make a copy so caller cannot mutate the apps list. - return Object.keys(i).map(function(e) { - return i[e]; - }); - } - }), // @ts-ignore - t.App = s, a); - return o.INTERNAL = r.__assign(r.__assign({}, o.INTERNAL), { + // Make a copy so caller cannot mutate the apps list. + return Object.keys(n).map(function(e) { + return n[e]; + }); + } + }), // @ts-ignore + i.App = e, r); + }(p); + return r.INTERNAL = n.__assign(n.__assign({}, r.INTERNAL), { createFirebaseNamespace: e, extendNamespace: /** * Patch the top-level firebase namespace with additional properties. * * firebase.INTERNAL.extendNamespace() */ function(e) { - n.deepExtend(o, e); + t.deepExtend(r, e); }, - createSubscribe: n.createSubscribe, - ErrorFactory: n.ErrorFactory, - deepExtend: n.deepExtend - }), o; -}(), d = new o.Logger("@firebase/app-compat"); + createSubscribe: t.createSubscribe, + ErrorFactory: t.ErrorFactory, + deepExtend: t.deepExtend + }), r; +}(), l = new a.Logger("@firebase/app-compat"); /** * @license * Copyright 2020 Google LLC @@ -242,12 +270,12 @@ var e, t, n = require("@firebase/util"), r = require("tslib"), i = require("@fir * limitations under the License. */ // Firebase Lite detection // eslint-disable-next-line @typescript-eslint/no-explicit-any -if (n.isBrowser() && void 0 !== self.firebase) { - d.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n "); +if (t.isBrowser() && void 0 !== self.firebase) { + l.warn("\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n "); // eslint-disable-next-line - var f = self.firebase.SDK_VERSION; - f && f.indexOf("LITE") >= 0 && d.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n "); + var d = self.firebase.SDK_VERSION; + d && d.indexOf("LITE") >= 0 && l.warn("\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n "); } // Register `app` package. -a.registerVersion("@firebase/app-compat", "0.1.5", void 0), module.exports = l; +i.registerVersion("@firebase/app-compat", "0.1.5", void 0), module.exports = u; //# sourceMappingURL=index.cjs.js.map diff --git a/crates/swc/tests/vercel/full/next-33088/output/index.js b/crates/swc/tests/vercel/full/next-33088/output/index.js index d2a9d1e01c9..845770e930b 100644 --- a/crates/swc/tests/vercel/full/next-33088/output/index.js +++ b/crates/swc/tests/vercel/full/next-33088/output/index.js @@ -8,9 +8,6 @@ export default function c() { hits: [] }), 2), o = c[0], u = c[1], l = e(i.useState("react"), 2), h = l[0], f = l[1]; return i.useEffect(function() { - "" !== h && function() { - e.apply(this, arguments); - }(); function e() { return (e = t(function() { return r(this, function(t) { @@ -33,6 +30,9 @@ export default function c() { }); })).apply(this, arguments); } + "" !== h && function() { + e.apply(this, arguments); + }(); }, [ h ]), /*#__PURE__*/ s(a, { diff --git a/crates/swc/tests/vercel/full/react-instantsearch/2/output/index.js b/crates/swc/tests/vercel/full/react-instantsearch/2/output/index.js index 04e13e75bce..905e0d82151 100644 --- a/crates/swc/tests/vercel/full/react-instantsearch/2/output/index.js +++ b/crates/swc/tests/vercel/full/react-instantsearch/2/output/index.js @@ -36,218 +36,31 @@ var f = function(e) { * @param {number} stalledSearchDelay - time (in ms) after the search is stalled * @return {InstantSearchManager} a new instance of InstantSearchManager */ export default function S(u) { - var o, l, S = u.indexName, v = u.initialState, x = u.searchClient, _ = u.resultsState, y = u.stalledSearchDelay, w = function(e) { - return O.getWidgets().filter(function(e) { - return !!e.getMetadata; - }).map(function(t) { - return t.getMetadata(e); - }); - }, F = function() { - var a = O.getWidgets().filter(function(e) { - return !!e.getSearchParameters; - }).filter(function(e) { - return !f(e) && !p(e); - }).reduce(function(e, t) { - return t.getSearchParameters(e); - }, j), n = O.getWidgets().filter(function(e) { - return !!e.getSearchParameters; - }).filter(function(e) { - var t = f(e) && m(e, S), r = p(e) && g(e, S); - return t || r; - })// We have to sort the `Index` widgets first so the `index` parameter - // is correctly set in the `reduce` function for the following widgets - .sort(h).reduce(function(e, t) { - return t.getSearchParameters(e); - }, a), s = O.getWidgets().filter(function(e) { - return !!e.getSearchParameters; - }).filter(function(e) { - var t = f(e) && !m(e, S), r = p(e) && !g(e, S); - return t || r; - })// We have to sort the `Index` widgets first so the `index` parameter - // is correctly set in the `reduce` function for the following widgets - .sort(h).reduce(function(a, n) { - var s = f(n) ? n.props.indexContextValue.targetedIndex : n.props.indexId, i = a[s] || []; - return r(t({}, a), e({}, s, i.concat(n))); - }, {}); - return { - mainParameters: n, - derivedParameters: Object.keys(s).map(function(e) { - return { - parameters: s[e].reduce(function(e, t) { - return t.getSearchParameters(e); - }, a), - indexId: e - }; - }) - }; - }, V = function() { - if (!C) { - var e = F(R.state), t = e.mainParameters, r = e.derivedParameters; - // We have to call `slice` because the method `detach` on the derived - // helpers mutates the value `derivedHelpers`. The `forEach` loop does - // not iterate on each value and we're not able to correctly clear the - // previous derived helpers (memory leak + useless requests). - R.derivedHelpers.slice().forEach(function(e) { - // Since we detach the derived helpers on **every** new search they - // won't receive intermediate results in case of a stalled search. - // Only the last result is dispatched by the derived helper because - // they are not detached yet: - // - // - a -> main helper receives results - // - ap -> main helper receives results - // - app -> main helper + derived helpers receive results - // - // The quick fix is to avoid to detach them on search but only once they - // received the results. But it means that in case of a stalled search - // all the derived helpers not detached yet register a new search inside - // the helper. The number grows fast in case of a bad network and it's - // not deterministic. - e.detach(); - }), r.forEach(function(e) { - var t = e.indexId, r = e.parameters; - R.derive(function() { - return r; - }).on("result", I({ - indexId: t - })).on("error", b); - }), R.setState(t), R.search(); - } - }, I = function(n) { - var s = n.indexId; - return function(n) { - var i = q.getState(), c = !R.derivedHelpers.length, u = i.results ? i.results : {}; - // Switching from mono index to multi index and vice versa must reset the - // results to an empty object, otherwise we keep reference of stalled and - // unused results. - u = !c && u.getFacetByName ? {} : u, u = c ? n.results : r(t({}, u), e({}, s, n.results)); - var o = q.getState(), l = o.isSearchStalled; - R.hasPendingRequests() || (clearTimeout(N), N = null, l = !1), o.resultsFacetValues; - var d = a(o, [ - "resultsFacetValues" - ]); - q.setState(r(t({}, d), { - results: u, - isSearchStalled: l, - searching: !1, - error: null - })); - }; - }, b = function(e) { - var n = e.error, s = q.getState(), i = s.isSearchStalled; - R.hasPendingRequests() || (clearTimeout(N), i = !1), s.resultsFacetValues; - var c = a(s, [ - "resultsFacetValues" - ]); - q.setState(r(t({}, c), { - isSearchStalled: i, - error: n, - searching: !1 - })); - }, A = function(a, n) { - // Algoliasearch API Client >= v4 - // Populate the cache with the data from the server - if (a.transporter) { - a.transporter.responsesCache.set({ - method: "search", - args: [ - n.reduce(function(e, t) { - return e.concat(t.rawResults.map(function(e) { - return { - indexName: e.index, - params: e.params - }; - })); - }, []) - ] - }, { - results: n.reduce(function(e, t) { - return e.concat(t.rawResults); - }, []) - }); - return; - } - // Algoliasearch API Client < v4 - // Prior to client v4 we didn't have a proper API to hydrate the client - // cache from the outside. The following code populates the cache with - // a single-index result. You can find more information about the - // computation of the key inside the client (see link below). - // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 - var s = "/1/indexes/*/queries_body_".concat(JSON.stringify({ - requests: n.reduce(function(e, t) { - return e.concat(t.rawResults.map(function(e) { - return { - indexName: e.index, - params: e.params - }; - })); - }, []) - })); - a.cache = r(t({}, a.cache), e({}, s, JSON.stringify({ - results: n.reduce(function(e, t) { - return e.concat(t.rawResults); - }, []) - }))); - }, P = function(a, n) { - // Algoliasearch API Client >= v4 - // Populate the cache with the data from the server - if (a.transporter) { - a.transporter.responsesCache.set({ - method: "search", - args: [ - n.rawResults.map(function(e) { - return { - indexName: e.index, - params: e.params - }; - }) - ] - }, { - results: n.rawResults - }); - return; - } - // Algoliasearch API Client < v4 - // Prior to client v4 we didn't have a proper API to hydrate the client - // cache from the outside. The following code populates the cache with - // a single-index result. You can find more information about the - // computation of the key inside the client (see link below). - // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 - var s = "/1/indexes/*/queries_body_".concat(JSON.stringify({ - requests: n.rawResults.map(function(e) { - return { - indexName: e.index, - params: e.params - }; - }) - })); - a.cache = r(t({}, a.cache), e({}, s, JSON.stringify({ - results: n.rawResults - }))); - }, R = s(x, S, t({}, c)); - d(x), R.on("search", function() { - N || (N = setTimeout(function() { - var e = q.getState(), n = (e.resultsFacetValues, a(e, [ + var o, l, S = u.indexName, v = u.initialState, x = u.searchClient, _ = u.resultsState, y = u.stalledSearchDelay, w = s(x, S, t({}, c)); + d(x), w.on("search", function() { + V || (V = setTimeout(function() { + var e = A.getState(), n = (e.resultsFacetValues, a(e, [ "resultsFacetValues" ])); - q.setState(r(t({}, n), { + A.setState(r(t({}, n), { isSearchStalled: !0 })); }, y)); - }).on("result", I({ + }).on("result", N({ indexId: S - })).on("error", b); - var C = !1, N = null, j = R.state, O = i(// Called whenever a widget has been rendered with new props. + })).on("error", j); + var F = !1, V = null, I = w.state, b = i(// Called whenever a widget has been rendered with new props. function() { - var e = w(q.getState().widgets); - q.setState(r(t({}, q.getState()), { + var e = P(A.getState().widgets); + A.setState(r(t({}, A.getState()), { metadata: e, searching: !0 })), // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. - V(); + C(); }); - !function(e, a) { - if (a && (e.transporter && !e._cacheHydrated || e._useCache && "function" == typeof e.addAlgoliaAgent)) { + !function(a, s) { + if (s && (a.transporter && !a._cacheHydrated || a._useCache && "function" == typeof a.addAlgoliaAgent)) { // Algoliasearch API Client >= v4 // To hydrate the client we need to populate the cache with the data from // the server (done in `hydrateSearchClientWithMultiIndexRequest` or @@ -255,12 +68,12 @@ var f = function(e) { // for us to compute the key the same way as `algoliasearch-client` we need // to populate it on a custom key and override the `search` method to // search on it first. - if (e.transporter && !e._cacheHydrated) { - e._cacheHydrated = !0; - var s = e.search; - e.search = function(a) { - for(var i = arguments.length, c = Array(i > 1 ? i - 1 : 0), u = 1; u < i; u++)c[u - 1] = arguments[u]; - var o = a.map(function(e) { + if (a.transporter && !a._cacheHydrated) { + a._cacheHydrated = !0; + var i = a.search; + a.search = function(e) { + for(var s = arguments.length, c = Array(s > 1 ? s - 1 : 0), u = 1; u < s; u++)c[u - 1] = arguments[u]; + var o = e.map(function(e) { var a, n; return r(t({}, e), { params: (a = e.params, n = function(e) { @@ -275,26 +88,106 @@ var f = function(e) { }).join("&")) }); }); - return e.transporter.responsesCache.get({ + return a.transporter.responsesCache.get({ method: "search", args: [ o ].concat(n(c)) }, function() { - return s.apply(void 0, [ - a + return i.apply(void 0, [ + e ].concat(n(c))); }); }; } - if (Array.isArray(a.results)) { - A(e, a.results); + if (Array.isArray(s.results)) { + !function(a, n) { + // Algoliasearch API Client >= v4 + // Populate the cache with the data from the server + if (a.transporter) { + a.transporter.responsesCache.set({ + method: "search", + args: [ + n.reduce(function(e, t) { + return e.concat(t.rawResults.map(function(e) { + return { + indexName: e.index, + params: e.params + }; + })); + }, []) + ] + }, { + results: n.reduce(function(e, t) { + return e.concat(t.rawResults); + }, []) + }); + return; + } + // Algoliasearch API Client < v4 + // Prior to client v4 we didn't have a proper API to hydrate the client + // cache from the outside. The following code populates the cache with + // a single-index result. You can find more information about the + // computation of the key inside the client (see link below). + // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 + var s = "/1/indexes/*/queries_body_".concat(JSON.stringify({ + requests: n.reduce(function(e, t) { + return e.concat(t.rawResults.map(function(e) { + return { + indexName: e.index, + params: e.params + }; + })); + }, []) + })); + a.cache = r(t({}, a.cache), e({}, s, JSON.stringify({ + results: n.reduce(function(e, t) { + return e.concat(t.rawResults); + }, []) + }))); + }(a, s.results); return; } - P(e, a); + !function(a, n) { + // Algoliasearch API Client >= v4 + // Populate the cache with the data from the server + if (a.transporter) { + a.transporter.responsesCache.set({ + method: "search", + args: [ + n.rawResults.map(function(e) { + return { + indexName: e.index, + params: e.params + }; + }) + ] + }, { + results: n.rawResults + }); + return; + } + // Algoliasearch API Client < v4 + // Prior to client v4 we didn't have a proper API to hydrate the client + // cache from the outside. The following code populates the cache with + // a single-index result. You can find more information about the + // computation of the key inside the client (see link below). + // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 + var s = "/1/indexes/*/queries_body_".concat(JSON.stringify({ + requests: n.rawResults.map(function(e) { + return { + indexName: e.index, + params: e.params + }; + }) + })); + a.cache = r(t({}, a.cache), e({}, s, JSON.stringify({ + results: n.rawResults + }))); + }(a, s); } }(x, _); - var q = (o = { + var A = (o = { widgets: void 0 === v ? {} : v, metadata: _ ? _.metadata.map(function(e) { return r(t({ @@ -341,28 +234,140 @@ var f = function(e) { }; } }); + function P(e) { + return b.getWidgets().filter(function(e) { + return !!e.getMetadata; + }).map(function(t) { + return t.getMetadata(e); + }); + } + function R() { + var a = b.getWidgets().filter(function(e) { + return !!e.getSearchParameters; + }).filter(function(e) { + return !f(e) && !p(e); + }).reduce(function(e, t) { + return t.getSearchParameters(e); + }, I), n = b.getWidgets().filter(function(e) { + return !!e.getSearchParameters; + }).filter(function(e) { + var t = f(e) && m(e, S), r = p(e) && g(e, S); + return t || r; + })// We have to sort the `Index` widgets first so the `index` parameter + // is correctly set in the `reduce` function for the following widgets + .sort(h).reduce(function(e, t) { + return t.getSearchParameters(e); + }, a), s = b.getWidgets().filter(function(e) { + return !!e.getSearchParameters; + }).filter(function(e) { + var t = f(e) && !m(e, S), r = p(e) && !g(e, S); + return t || r; + })// We have to sort the `Index` widgets first so the `index` parameter + // is correctly set in the `reduce` function for the following widgets + .sort(h).reduce(function(a, n) { + var s = f(n) ? n.props.indexContextValue.targetedIndex : n.props.indexId, i = a[s] || []; + return r(t({}, a), e({}, s, i.concat(n))); + }, {}); + return { + mainParameters: n, + derivedParameters: Object.keys(s).map(function(e) { + return { + parameters: s[e].reduce(function(e, t) { + return t.getSearchParameters(e); + }, a), + indexId: e + }; + }) + }; + } + function C() { + if (!F) { + var e = R(w.state), t = e.mainParameters, r = e.derivedParameters; + // We have to call `slice` because the method `detach` on the derived + // helpers mutates the value `derivedHelpers`. The `forEach` loop does + // not iterate on each value and we're not able to correctly clear the + // previous derived helpers (memory leak + useless requests). + w.derivedHelpers.slice().forEach(function(e) { + // Since we detach the derived helpers on **every** new search they + // won't receive intermediate results in case of a stalled search. + // Only the last result is dispatched by the derived helper because + // they are not detached yet: + // + // - a -> main helper receives results + // - ap -> main helper receives results + // - app -> main helper + derived helpers receive results + // + // The quick fix is to avoid to detach them on search but only once they + // received the results. But it means that in case of a stalled search + // all the derived helpers not detached yet register a new search inside + // the helper. The number grows fast in case of a bad network and it's + // not deterministic. + e.detach(); + }), r.forEach(function(e) { + var t = e.indexId, r = e.parameters; + w.derive(function() { + return r; + }).on("result", N({ + indexId: t + })).on("error", j); + }), w.setState(t), w.search(); + } + } + function N(n) { + var s = n.indexId; + return function(n) { + var i = A.getState(), c = !w.derivedHelpers.length, u = i.results ? i.results : {}; + // Switching from mono index to multi index and vice versa must reset the + // results to an empty object, otherwise we keep reference of stalled and + // unused results. + u = !c && u.getFacetByName ? {} : u, u = c ? n.results : r(t({}, u), e({}, s, n.results)); + var o = A.getState(), l = o.isSearchStalled; + w.hasPendingRequests() || (clearTimeout(V), V = null, l = !1), o.resultsFacetValues; + var d = a(o, [ + "resultsFacetValues" + ]); + A.setState(r(t({}, d), { + results: u, + isSearchStalled: l, + searching: !1, + error: null + })); + }; + } + function j(e) { + var n = e.error, s = A.getState(), i = s.isSearchStalled; + w.hasPendingRequests() || (clearTimeout(V), i = !1), s.resultsFacetValues; + var c = a(s, [ + "resultsFacetValues" + ]); + A.setState(r(t({}, c), { + isSearchStalled: i, + error: n, + searching: !1 + })); + } return { - store: q, - widgetsManager: O, + store: A, + widgetsManager: b, getWidgetsIds: function() { - return q.getState().metadata.reduce(function(e, t) { + return A.getState().metadata.reduce(function(e, t) { return void 0 !== t.id ? e.concat(t.id) : e; }, []); }, - getSearchParameters: F, + getSearchParameters: R, onSearchForFacetValues: function(a) { var n = a.facetName, s = a.query, i = a.maxFacetHits; - q.setState(r(t({}, q.getState()), { + A.setState(r(t({}, A.getState()), { searchingForFacetValues: !0 - })), R.searchForFacetValues(n, s, Math.max(1, Math.min(void 0 === i ? 10 : i, 100))).then(function(a) { + })), w.searchForFacetValues(n, s, Math.max(1, Math.min(void 0 === i ? 10 : i, 100))).then(function(a) { var i; - q.setState(r(t({}, q.getState()), { + A.setState(r(t({}, A.getState()), { error: null, searchingForFacetValues: !1, - resultsFacetValues: r(t({}, q.getState().resultsFacetValues), (e(i = {}, n, a.facetHits), e(i, "query", s), i)) + resultsFacetValues: r(t({}, A.getState().resultsFacetValues), (e(i = {}, n, a.facetHits), e(i, "query", s), i)) })); }, function(e) { - q.setState(r(t({}, q.getState()), { + A.setState(r(t({}, A.getState()), { searchingForFacetValues: !1, error: e })); @@ -377,33 +382,33 @@ var f = function(e) { }); }, onExternalStateUpdate: function(e) { - var a = w(e); - q.setState(r(t({}, q.getState()), { + var a = P(e); + A.setState(r(t({}, A.getState()), { widgets: e, metadata: a, searching: !0 - })), V(); + })), C(); }, transitionState: function(e) { - var t = q.getState().widgets; - return O.getWidgets().filter(function(e) { + var t = A.getState().widgets; + return b.getWidgets().filter(function(e) { return !!e.transitionState; }).reduce(function(e, r) { return r.transitionState(t, e); }, e); }, updateClient: function(e) { - d(e), R.setClient(e), V(); + d(e), w.setClient(e), C(); }, updateIndex: function(e) { - j = j.setIndex(e); + I = I.setIndex(e); // No need to trigger a new search here as the widgets will also update and trigger it if needed. }, clearCache: function() { - R.clearCache(), V(); + w.clearCache(), C(); }, skipSearch: function() { - C = !0; + F = !0; } }; } diff --git a/crates/swc/tests/vercel/loader-only/react-instantsearch/1/output/index.js b/crates/swc/tests/vercel/loader-only/react-instantsearch/1/output/index.js index 7533a60bce7..871003a0316 100644 --- a/crates/swc/tests/vercel/loader-only/react-instantsearch/1/output/index.js +++ b/crates/swc/tests/vercel/loader-only/react-instantsearch/1/output/index.js @@ -73,7 +73,7 @@ function serializeQueryParameters(parameters) { * @return {InstantSearchManager} a new instance of InstantSearchManager */ export default function createInstantSearchManager(param) { var indexName = param.indexName, _param_initialState = param.initialState, initialState = _param_initialState === void 0 ? {} : _param_initialState, searchClient = param.searchClient, resultsState = param.resultsState, stalledSearchDelay = param.stalledSearchDelay; - var createStore = function createStore(initialState) { + function createStore(initialState) { var state = initialState; var listeners = []; return { @@ -93,27 +93,46 @@ function serializeQueryParameters(parameters) { }; } }; - }; - var skipSearch = function skipSearch() { + } + var helper = algoliasearchHelper(searchClient, indexName, _object_spread({}, HIGHLIGHT_TAGS)); + addAlgoliaAgents(searchClient); + helper.on("search", handleNewSearch).on("result", handleSearchSuccess({ + indexId: indexName + })).on("error", handleSearchError); + var skip = false; + var stalledSearchTimer = null; + var initialSearchParameters = helper.state; + var widgetsManager = createWidgetsManager(onWidgetsUpdate); + hydrateSearchClient(searchClient, resultsState); + var store = createStore({ + widgets: initialState, + metadata: hydrateMetadata(resultsState), + results: hydrateResultsState(resultsState), + error: null, + searching: false, + isSearchStalled: true, + searchingForFacetValues: false + }); + function skipSearch() { skip = true; - }; - var updateClient = function updateClient(client) { + } + function updateClient(client) { addAlgoliaAgents(client); helper.setClient(client); search(); - }; - var clearCache = function clearCache() { + } + function clearCache() { helper.clearCache(); search(); - }; - var getMetadata = function getMetadata(state) { + } + function getMetadata(state) { return widgetsManager.getWidgets().filter(function(widget) { return Boolean(widget.getMetadata); }).map(function(widget) { return widget.getMetadata(state); }); - }; - var getSearchParameters = function getSearchParameters() { + } + function getSearchParameters() { var sharedParameters = widgetsManager.getWidgets().filter(function(widget) { return Boolean(widget.getSearchParameters); }).filter(function(widget) { @@ -157,8 +176,8 @@ function serializeQueryParameters(parameters) { mainParameters: mainParameters, derivedParameters: derivedParameters }; - }; - var search = function search() { + } + function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state), mainParameters = _getSearchParameters.mainParameters, derivedParameters = _getSearchParameters.derivedParameters; // We have to call `slice` because the method `detach` on the derived @@ -194,8 +213,8 @@ function serializeQueryParameters(parameters) { helper.setState(mainParameters); helper.search(); } - }; - var handleSearchSuccess = function handleSearchSuccess(param) { + } + function handleSearchSuccess(param) { var indexId = param.indexId; return function(event) { var state = store.getState(); @@ -227,8 +246,8 @@ function serializeQueryParameters(parameters) { error: null })); }; - }; - var handleSearchError = function handleSearchError(param) { + } + function handleSearchError(param) { var error = param.error; var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; @@ -244,8 +263,8 @@ function serializeQueryParameters(parameters) { error: error, searching: false })); - }; - var handleNewSearch = function handleNewSearch() { + } + function handleNewSearch() { if (!stalledSearchTimer) { var _setTimeout; _setTimeout = setTimeout(function() { @@ -257,8 +276,8 @@ function serializeQueryParameters(parameters) { })); }, stalledSearchDelay), stalledSearchTimer = _setTimeout, _setTimeout; } - }; - var hydrateSearchClient = function hydrateSearchClient(client, results) { + } + function hydrateSearchClient(client, results) { if (!results) { return; } @@ -304,8 +323,8 @@ function serializeQueryParameters(parameters) { return; } hydrateSearchClientWithSingleIndexRequest(client, results); - }; - var hydrateSearchClientWithMultiIndexRequest = function hydrateSearchClientWithMultiIndexRequest(client, results) { + } + function hydrateSearchClientWithMultiIndexRequest(client, results) { // Algoliasearch API Client >= v4 // Populate the cache with the data from the server if (client.transporter) { @@ -349,8 +368,8 @@ function serializeQueryParameters(parameters) { return acc.concat(result.rawResults); }, []) }))); - }; - var hydrateSearchClientWithSingleIndexRequest = function hydrateSearchClientWithSingleIndexRequest(client, results) { + } + function hydrateSearchClientWithSingleIndexRequest(client, results) { // Algoliasearch API Client >= v4 // Populate the cache with the data from the server if (client.transporter) { @@ -386,8 +405,8 @@ function serializeQueryParameters(parameters) { client.cache = _object_spread_props(_object_spread({}, client.cache), _define_property({}, key, JSON.stringify({ results: results.rawResults }))); - }; - var hydrateResultsState = function hydrateResultsState(results) { + } + function hydrateResultsState(results) { if (!results) { return null; } @@ -397,8 +416,8 @@ function serializeQueryParameters(parameters) { }, {}); } return new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(results.state), results.rawResults); - }; - var onWidgetsUpdate = // Called whenever a widget has been rendered with new props. + } + // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_object_spread_props(_object_spread({}, store.getState()), { @@ -408,16 +427,16 @@ function serializeQueryParameters(parameters) { // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); - }; - var transitionState = function transitionState(nextSearchState) { + } + function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function(widget) { return Boolean(widget.transitionState); }).reduce(function(res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); - }; - var onExternalStateUpdate = function onExternalStateUpdate(nextSearchState) { + } + function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_object_spread_props(_object_spread({}, store.getState()), { widgets: nextSearchState, @@ -425,8 +444,8 @@ function serializeQueryParameters(parameters) { searching: true })); search(); - }; - var onSearchForFacetValues = function onSearchForFacetValues(param) { + } + function onSearchForFacetValues(param) { var facetName = param.facetName, query = param.query, _param_maxFacetHits = param.maxFacetHits, maxFacetHits = _param_maxFacetHits === void 0 ? 10 : _param_maxFacetHits; // The values 1, 100 are the min / max values that the engine accepts. // see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits @@ -455,35 +474,16 @@ function serializeQueryParameters(parameters) { throw error; }); }); - }; - var updateIndex = function updateIndex(newIndex) { + } + function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); // No need to trigger a new search here as the widgets will also update and trigger it if needed. - }; - var getWidgetsIds = function getWidgetsIds() { + } + function getWidgetsIds() { return store.getState().metadata.reduce(function(res, meta) { return typeof meta.id !== "undefined" ? res.concat(meta.id) : res; }, []); - }; - var helper = algoliasearchHelper(searchClient, indexName, _object_spread({}, HIGHLIGHT_TAGS)); - addAlgoliaAgents(searchClient); - helper.on("search", handleNewSearch).on("result", handleSearchSuccess({ - indexId: indexName - })).on("error", handleSearchError); - var skip = false; - var stalledSearchTimer = null; - var initialSearchParameters = helper.state; - var widgetsManager = createWidgetsManager(onWidgetsUpdate); - hydrateSearchClient(searchClient, resultsState); - var store = createStore({ - widgets: initialState, - metadata: hydrateMetadata(resultsState), - results: hydrateResultsState(resultsState), - error: null, - searching: false, - isSearchStalled: true, - searchingForFacetValues: false - }); + } return { store: store, widgetsManager: widgetsManager, diff --git a/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs b/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs index 8ed89cc1d3d..d2f8f2c5510 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/block_scoped_fn.rs @@ -1,4 +1,4 @@ -use swc_common::{util::take::Take, Spanned, DUMMY_SP}; +use swc_common::{util::take::Take, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_utils::IdentUsageFinder; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; @@ -15,11 +15,22 @@ struct BlockScopedFns; impl VisitMut for BlockScopedFns { noop_visit_mut_type!(); - fn visit_mut_stmts(&mut self, items: &mut Vec) { - let mut stmts = Vec::with_capacity(items.len()); - let mut extra_stmts = Vec::with_capacity(items.len()); + fn visit_mut_function(&mut self, n: &mut Function) { + let Some(body) = &mut n.body else { return }; - for mut stmt in items.take() { + n.params.visit_mut_with(self); + + // skip function scope + body.visit_mut_children_with(self); + } + + fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) { + n.visit_mut_children_with(self); + + let mut stmts = Vec::with_capacity(n.stmts.len()); + let mut extra_stmts = Vec::with_capacity(n.stmts.len()); + + for stmt in n.stmts.take() { if let Stmt::Expr(ExprStmt { ref expr, .. }) = stmt { if let Expr::Lit(Lit::Str(..)) = &**expr { stmts.push(stmt); @@ -27,45 +38,36 @@ impl VisitMut for BlockScopedFns { } } - // This is to preserve function Class() - if stmt.span().is_dummy() { - extra_stmts.push(stmt) - } else { - match stmt { - Stmt::Decl(Decl::Fn(decl)) => { - if IdentUsageFinder::find(&decl.ident.to_id(), &decl.function) { - extra_stmts.push(Stmt::Decl(Decl::Fn(decl))); - continue; - } - stmts.push( - VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Let, - decls: vec![VarDeclarator { - span: DUMMY_SP, - name: decl.ident.clone().into(), - init: Some(Box::new(Expr::Fn(FnExpr { - ident: Some(decl.ident), - function: decl.function, - }))), - definite: false, - }], - declare: false, - } - .into(), - ) - } - _ => { - stmt.visit_mut_children_with(self); - extra_stmts.push(stmt) - } + if let Stmt::Decl(Decl::Fn(decl)) = stmt { + if IdentUsageFinder::find(&decl.ident.to_id(), &decl.function) { + extra_stmts.push(Stmt::Decl(Decl::Fn(decl))); + continue; } + stmts.push( + VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Let, + decls: vec![VarDeclarator { + span: DUMMY_SP, + name: decl.ident.clone().into(), + init: Some(Box::new(Expr::Fn(FnExpr { + ident: Some(decl.ident), + function: decl.function, + }))), + definite: false, + }], + declare: false, + } + .into(), + ) + } else { + extra_stmts.push(stmt) } } stmts.append(&mut extra_stmts); - *items = stmts + n.stmts = stmts } } @@ -120,6 +122,48 @@ name("Steve"); "# ); + test!( + ::swc_ecma_parser::Syntax::default(), + |_| block_scoped_functions(), + basic_2, + r#" + { + function foo() { + return function bar() { + { + function baz() {} + } + }; + function baz() {} + { + function bar() {} + { + function bar() {} + } + } + } + } + "#, + r#" + { + let foo = function foo() { + return function bar() { + { + let baz = function baz() {}; + } + }; + function baz() {} + { + let bar = function bar() {}; + { + let bar = function bar() {}; + } + } + }; + } + "# + ); + test!( ::swc_ecma_parser::Syntax::default(), |_| block_scoped_functions(), @@ -135,10 +179,10 @@ function foo(scope) { ", " function foo(scope) { - let startOperation = function startOperation(operation) { - scope.agentOperation = operation; - }; scope.startOperation = startOperation; + function startOperation(operation) { + scope.agentOperation = operation; + } } " ); @@ -219,9 +263,9 @@ function foo(scope) { }", "function foo() { 'use strict'; - let _interop_require_default = function _interop_require_default(obj) { + function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; - }; + } } " ); diff --git a/crates/swc_ecma_transforms_compat/src/es2015/mod.rs b/crates/swc_ecma_transforms_compat/src/es2015/mod.rs index c21204cf914..3d02714c4c8 100644 --- a/crates/swc_ecma_transforms_compat/src/es2015/mod.rs +++ b/crates/swc_ecma_transforms_compat/src/es2015/mod.rs @@ -230,10 +230,10 @@ function foo(scope) { ", " function foo(scope) { - let startOperation = function startOperation(operation) { - scope.agentOperation = operation; - }; scope.startOperation = startOperation; + function startOperation(operation) { + scope.agentOperation = operation; + } } " );