diff --git "a/TypeScript_2/solution/solution.patch" "b/TypeScript_2/solution/solution.patch" new file mode 100644 --- /dev/null +++ "b/TypeScript_2/solution/solution.patch" @@ -0,0 +1,6680 @@ +diff --git a/src/compiler/_namespaces/ts.ts b/src/compiler/_namespaces/ts.ts +index 5a01767f9..34d731e88 100644 +--- a/src/compiler/_namespaces/ts.ts ++++ b/src/compiler/_namespaces/ts.ts +@@ -33,6 +33,8 @@ export * from "../visitorPublic"; + export * from "../sourcemap"; + export * from "../transformers/utilities"; + export * from "../transformers/destructuring"; ++export * from "../transformers/classThis"; ++export * from "../transformers/namedEvaluation"; + export * from "../transformers/taggedTemplate"; + export * from "../transformers/ts"; + export * from "../transformers/classFields"; +diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts +index 4ebea0c52..21122302c 100644 +--- a/src/compiler/binder.ts ++++ b/src/compiler/binder.ts +@@ -3727,7 +3727,7 @@ function isExecutableStatement(s: Statement): boolean { + // Don't remove statements that can validly be used before they appear. + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && + // `var x;` may declare a variable used above +- !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.Let | NodeFlags.Const)) && s.declarationList.declarations.some(d => !d.initializer)); ++ !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.BlockScoped)) && s.declarationList.declarations.some(d => !d.initializer)); + } + + function isPurelyTypeDeclaration(s: Statement): boolean { +diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts +index bbda1c576..31a927d63 100644 +--- a/src/compiler/checker.ts ++++ b/src/compiler/checker.ts +@@ -609,7 +609,6 @@ import { + isKnownSymbol, + isLateVisibilityPaintedStatement, + isLeftHandSideExpression, +- isLet, + isLineBreak, + isLiteralComputedPropertyDeclarationName, + isLiteralExpression, +@@ -734,7 +733,6 @@ import { + isValidESSymbolDeclaration, + isValidTypeOnlyAliasUseSite, + isValueSignatureDeclaration, +- isVarConst, + isVariableDeclaration, + isVariableDeclarationInitializedToBareOrAccessedRequire, + isVariableDeclarationInVariableStatement, +@@ -1471,6 +1469,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ + var apparentArgumentCount: number | undefined; + ++ var lastGetCombinedNodeFlagsNode: Node | undefined; ++ var lastGetCombinedNodeFlagsResult = NodeFlags.None; ++ var lastGetCombinedModifierFlagsNode: Declaration | undefined; ++ var lastGetCombinedModifierFlagsResult = ModifierFlags.None; ++ + // for public members that accept a Node or one of its subtypes, we must guard against + // synthetic nodes created during transformations by calling `getParseTreeNode`. + // for most of these, we perform the guard only on `checker` to avoid any possible +@@ -2115,6 +2118,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + var deferredGlobalImportMetaType: ObjectType; + var deferredGlobalImportMetaExpressionType: ObjectType; + var deferredGlobalImportCallOptionsType: ObjectType | undefined; ++ var deferredGlobalDisposableType: ObjectType | undefined; ++ var deferredGlobalAsyncDisposableType: ObjectType | undefined; + var deferredGlobalExtractSymbol: Symbol | undefined; + var deferredGlobalOmitSymbol: Symbol | undefined; + var deferredGlobalAwaitedSymbol: Symbol | undefined; +@@ -2395,7 +2400,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function isDeprecatedDeclaration(declaration: Declaration) { +- return !!(getCombinedNodeFlags(declaration) & NodeFlags.Deprecated); ++ return !!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Deprecated); + } + + function addDeprecatedSuggestion(location: Node, declarations: Node[], deprecatedEntity: string) { +@@ -8682,7 +8687,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + ? symbol.parent?.valueDeclaration && isSourceFile(symbol.parent?.valueDeclaration) + ? NodeFlags.Const // exports are immutable in es6, which is what we emulate and check; so it's safe to mark all exports as `const` (there's no difference to consumers, but it allows unique symbol type declarations) + : undefined +- : isConstVariable(symbol) ++ : isConstantVariable(symbol) + ? NodeFlags.Const + : NodeFlags.Let; + const name = (needsPostExportDefault || !(symbol.flags & SymbolFlags.Property)) ? localName : getUnusedName(localName, symbol); +@@ -9957,7 +9962,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + const parent = getDeclarationContainer(node); + // If the node is not exported or it is not ambient module element (except import declaration) +- if (!(getCombinedModifierFlags(node as Declaration) & ModifierFlags.Export) && ++ if (!(getCombinedModifierFlagsCached(node as Declaration) & ModifierFlags.Export) && + !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && parent.flags & NodeFlags.Ambient)) { + return isGlobalSourceFile(parent); + } +@@ -10483,11 +10488,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + if ((noImplicitAny || isInJSFile(declaration)) && + isVariableDeclaration(declaration) && !isBindingPattern(declaration.name) && +- !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { ++ !(getCombinedModifierFlagsCached(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { + // If --noImplicitAny is on or the declaration is in a Javascript file, + // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. +- if (!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { ++ if (!(getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array +@@ -15836,6 +15841,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return (deferredGlobalIteratorReturnResultType ||= getGlobalType("IteratorReturnResult" as __String, /*arity*/ 1, reportErrors)) || emptyGenericType; + } + ++ function getGlobalDisposableType(reportErrors: boolean) { ++ return (deferredGlobalDisposableType ||= getGlobalType("Disposable" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; ++ } ++ ++ function getGlobalAsyncDisposableType(reportErrors: boolean) { ++ return (deferredGlobalAsyncDisposableType ||= getGlobalType("AsyncDisposable" as __String, /*arity*/ 0, reportErrors)) || emptyObjectType; ++ } ++ + function getGlobalTypeOrUndefined(name: __String, arity = 0): ObjectType | undefined { + const symbol = getGlobalSymbol(name, SymbolFlags.Type, /*diagnostic*/ undefined); + return symbol && getTypeOfGlobalSymbol(symbol, arity) as GenericType; +@@ -17316,7 +17329,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (isCallLikeExpression(parent)) { + return isCallOrNewExpression(parent) && isIdentifier(node) && hasMatchingArgument(parent, node); + } +- return every(symbol.declarations, d => !isFunctionLike(d) || !!(getCombinedNodeFlags(d) & NodeFlags.Deprecated)); ++ return every(symbol.declarations, d => !isFunctionLike(d) || isDeprecatedDeclaration(d)); + } + return true; + } +@@ -25475,7 +25488,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + function tryGetNameFromEntityNameExpression(node: EntityNameOrEntityNameExpression) { + const symbol = resolveEntityName(node, SymbolFlags.Value, /*ignoreErrors*/ true); +- if (!symbol || !(isConstVariable(symbol) || (symbol.flags & SymbolFlags.EnumMember))) return undefined; ++ if (!symbol || !(isConstantVariable(symbol) || (symbol.flags & SymbolFlags.EnumMember))) return undefined; + + const declaration = symbol.valueDeclaration; + if (declaration === undefined) return undefined; +@@ -26490,7 +26503,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + case SyntaxKind.Identifier: + if (!isThisInTypeQuery(node)) { + const symbol = getResolvedSymbol(node as Identifier); +- return isConstVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); ++ return isConstantVariable(symbol) || isParameterOrCatchClauseVariable(symbol) && !isSymbolAssigned(symbol); + } + break; + case SyntaxKind.PropertyAccessExpression: +@@ -26674,7 +26687,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + // A matching dotted name might also be an expando property on a function *expression*, + // in which case we continue control flow analysis back to the function's declaration +- if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConst(node))) { ++ if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike(node))) { + const init = getDeclaredExpandoInitializer(node); + if (init && (init.kind === SyntaxKind.FunctionExpression || init.kind === SyntaxKind.ArrowFunction)) { + return getTypeAtFlowNode(flow.antecedent); +@@ -26983,7 +26996,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + else if (isIdentifier(expr)) { + const symbol = getResolvedSymbol(expr); +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration!; + // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' + if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && +@@ -27575,7 +27588,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // up to five levels of aliased conditional expressions that are themselves declared as const variables. + if (!isMatchingReference(reference, expr) && inlineLevel < 5) { + const symbol = getResolvedSymbol(expr as Identifier); +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration; + if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) { + inlineLevel++; +@@ -27691,8 +27704,8 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function isConstVariable(symbol: Symbol) { +- return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; ++ function isConstantVariable(symbol: Symbol) { ++ return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant) !== 0; + } + + function parameterInitializerContainsUndefined(declaration: ParameterDeclaration): boolean { +@@ -27847,7 +27860,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // destructuring from the narrowed parent type. + if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { + const parent = declaration.parent.parent; +- if (parent.kind === SyntaxKind.VariableDeclaration && getCombinedNodeFlags(declaration) & NodeFlags.Const || parent.kind === SyntaxKind.Parameter) { ++ if (parent.kind === SyntaxKind.VariableDeclaration && getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant || parent.kind === SyntaxKind.Parameter) { + const links = getNodeLinks(parent); + if (!(links.flags & NodeCheckFlags.InCheckIdentifier)) { + links.flags |= NodeCheckFlags.InCheckIdentifier; +@@ -28053,7 +28066,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // analysis to include the immediately enclosing function. + while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || + flowContainer.kind === SyntaxKind.ArrowFunction || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && +- (isConstVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { ++ (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameter && !isSymbolAssigned(localOrExportSymbol))) { + flowContainer = getControlFlowContainer(flowContainer); + } + // We only look for uninitialized variables in strict null checking mode, and only when we can analyze +@@ -31083,7 +31096,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getDeclarationNodeFlagsFromSymbol(s: Symbol): NodeFlags { +- return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : 0; ++ return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0; + } + + /** +@@ -31611,7 +31624,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) { + error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText)); + } +- if (indexInfo.declaration && getCombinedNodeFlags(indexInfo.declaration) & NodeFlags.Deprecated) { ++ if (indexInfo.declaration && isDeprecatedDeclaration(indexInfo.declaration)) { + addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText as string); + } + } +@@ -31716,7 +31729,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + && !isOptionalPropertyDeclaration(valueDeclaration) + && !(isAccessExpression(node) && isAccessExpression(node.expression)) + && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) +- && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlags(valueDeclaration) & ModifierFlags.Static) ++ && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & ModifierFlags.Static) + && (compilerOptions.useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) { + diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName); + } +@@ -34241,7 +34254,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + let name: Expression | BindingName | undefined; + let decl: Node | undefined; + if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { +- if (!isInJSFile(node) && !(isVarConst(node.parent) && isFunctionLikeDeclaration(node))) { ++ if (!isInJSFile(node) && !(isVarConstLike(node.parent) && isFunctionLikeDeclaration(node))) { + return undefined; + } + name = node.parent.name; +@@ -36079,7 +36092,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) + return !!(getCheckFlags(symbol) & CheckFlags.Readonly || + symbol.flags & SymbolFlags.Property && getDeclarationModifierFlagsFromSymbol(symbol) & ModifierFlags.Readonly || +- symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const || ++ symbol.flags & SymbolFlags.Variable && getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Constant || + symbol.flags & SymbolFlags.Accessor && !(symbol.flags & SymbolFlags.SetAccessor) || + symbol.flags & SymbolFlags.EnumMember || + some(symbol.declarations, isReadonlyAssignmentDeclaration) +@@ -36185,11 +36198,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return undefinedWideningType; + } + +- function checkAwaitExpressionGrammar(node: AwaitExpression): void { ++ function checkAwaitGrammar(node: AwaitExpression | VariableDeclarationList): boolean { + // Grammar checking ++ let hasError = false; + const container = getContainingFunctionOrClassStaticBlock(node); + if (container && isClassStaticBlockDeclaration(container)) { +- error(node, Diagnostics.Await_expression_cannot_be_used_inside_a_class_static_block); ++ // NOTE: We report this regardless as to whether there are parse diagnostics. ++ const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : ++ Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block; ++ error(node, message); ++ hasError = true; + } + else if (!(node.flags & NodeFlags.AwaitContext)) { + if (isInTopLevelContext(node)) { +@@ -36198,9 +36216,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + let span: TextSpan | undefined; + if (!isEffectiveExternalModule(sourceFile, compilerOptions)) { + span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); +- const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, +- Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); ++ const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : ++ Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module; ++ const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + diagnostics.add(diagnostic); ++ hasError = true; + } + switch (moduleKind) { + case ModuleKind.Node16: +@@ -36210,6 +36230,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + diagnostics.add( + createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level) + ); ++ hasError = true; + break; + } + // fallthrough +@@ -36222,11 +36243,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // fallthrough + default: + span ??= getSpanOfTokenAtPosition(sourceFile, node.pos); +- diagnostics.add( +- createFileDiagnostic(sourceFile, span.start, span.length, +- Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher +- ) +- ); ++ const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher : ++ Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher; ++ diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message)); ++ hasError = true; + break; + } + } +@@ -36236,23 +36256,30 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const sourceFile = getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); +- const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); ++ const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules; ++ const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message); + if (container && container.kind !== SyntaxKind.Constructor && (getFunctionFlags(container) & FunctionFlags.Async) === 0) { + const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async); + addRelatedInfo(diagnostic, relatedInfo); + } + diagnostics.add(diagnostic); ++ hasError = true; + } + } + } + +- if (isInParameterInitializerBeforeContainingFunction(node)) { ++ if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) { ++ // NOTE: We report this regardless as to whether there are parse diagnostics. + error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer); ++ hasError = true; + } ++ ++ return hasError; + } + + function checkAwaitExpression(node: AwaitExpression): Type { +- addLazyDiagnostic(() => checkAwaitExpressionGrammar(node)); ++ addLazyDiagnostic(() => checkAwaitGrammar(node)); + + const operandType = checkExpression(node.expression); + const awaitedType = checkAwaitedType(operandType, /*withAlias*/ true, node, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); +@@ -37536,7 +37563,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function widenTypeInferredFromInitializer(declaration: HasExpressionInitializer, type: Type) { +- const widened = getCombinedNodeFlags(declaration) & NodeFlags.Const || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); ++ const widened = getCombinedNodeFlagsCached(declaration) & NodeFlags.Constant || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + if (isInJSFile(declaration)) { + if (isEmptyLiteralType(widened)) { + reportImplicitAny(declaration, anyType); +@@ -39031,7 +39058,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function getEffectiveDeclarationFlags(n: Declaration, flagsToCheck: ModifierFlags): ModifierFlags { +- let flags = getCombinedModifierFlags(n); ++ let flags = getCombinedModifierFlagsCached(n); + + // children of classes (even ambient classes) should not be marked as ambient or export + // because those flags have no useful semantics there. +@@ -40590,7 +40617,11 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + else if (isVariableDeclaration(declaration)) { +- addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); ++ const blockScopeKind = getCombinedNodeFlagsCached(declaration) & NodeFlags.BlockScoped; ++ const name = getNameOfDeclaration(declaration); ++ if (blockScopeKind !== NodeFlags.Using && blockScopeKind !== NodeFlags.AwaitUsing || !name || !isIdentifierThatStartsWithUnderscore(name)) { ++ addToGroup(unusedVariables, declaration.parent, declaration, getNodeId); ++ } + } + else { + const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration); +@@ -40943,7 +40974,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // } + + // skip block-scoped variables and parameters +- if ((getCombinedNodeFlags(node) & NodeFlags.BlockScoped) !== 0 || isParameterDeclaration(node)) { ++ if ((getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped) !== 0 || isParameterDeclaration(node)) { + return; + } + +@@ -41119,7 +41150,24 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && + !!symbol.exports?.size; + if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== SyntaxKind.ForInStatement) { +- checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined); ++ const initializerType = checkExpressionCached(initializer); ++ checkTypeAssignableToAndOptionallyElaborate(initializerType, type, node, initializer, /*headMessage*/ undefined); ++ const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped; ++ if (blockScopeKind === NodeFlags.AwaitUsing) { ++ const globalAsyncDisposableType = getGlobalAsyncDisposableType(/*reportErrors*/ true); ++ const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); ++ if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) { ++ const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]); ++ checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined); ++ } ++ } ++ else if (blockScopeKind === NodeFlags.Using) { ++ const globalDisposableType = getGlobalDisposableType(/*reportErrors*/ true); ++ if (globalDisposableType !== emptyObjectType) { ++ const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]); ++ checkTypeAssignableTo(initializerType, optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined); ++ } ++ } + } + } + if (symbol.declarations && symbol.declarations.length > 1) { +@@ -41208,10 +41256,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return checkVariableLikeDeclaration(node); + } + ++ function checkVariableDeclarationList(node: VariableDeclarationList) { ++ const blockScopeKind = getCombinedNodeFlags(node) & NodeFlags.BlockScoped; ++ if (blockScopeKind === NodeFlags.Using || blockScopeKind === NodeFlags.AwaitUsing) { ++ checkExternalEmitHelpers(node, ExternalEmitHelpers.AddDisposableResourceAndDisposeResources); ++ } ++ ++ forEach(node.declarations, checkSourceElement); ++ } ++ + function checkVariableStatement(node: VariableStatement) { + // Grammar checking +- if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedLetOrConstStatement(node); +- forEach(node.declarationList.declarations, checkSourceElement); ++ if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); ++ checkVariableDeclarationList(node.declarationList); + } + + function checkExpressionStatement(node: ExpressionStatement) { +@@ -41393,7 +41450,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + if (node.initializer) { + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { +- forEach((node.initializer as VariableDeclarationList).declarations, checkVariableDeclaration); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + checkExpression(node.initializer); +@@ -41414,7 +41471,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + const container = getContainingFunctionOrClassStaticBlock(node); + if (node.awaitModifier) { + if (container && isClassStaticBlockDeclaration(container)) { +- grammarErrorOnNode(node.awaitModifier, Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block); ++ grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block); + } + else { + const functionFlags = getFunctionFlags(container); +@@ -41435,7 +41492,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference. + // Then check that the RHS is assignable to it. + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { +- checkForInOrForOfVariableDeclaration(node); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + const varExpr = node.initializer; +@@ -41486,7 +41543,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (variable && isBindingPattern(variable.name)) { + error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); + } +- checkForInOrForOfVariableDeclaration(node); ++ checkVariableDeclarationList(node.initializer as VariableDeclarationList); + } + else { + // In a 'for-in' statement of the form +@@ -41522,15 +41579,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + } + +- function checkForInOrForOfVariableDeclaration(iterationStatement: ForInOrOfStatement): void { +- const variableDeclarationList = iterationStatement.initializer as VariableDeclarationList; +- // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. +- if (variableDeclarationList.declarations.length >= 1) { +- const decl = variableDeclarationList.declarations[0]; +- checkVariableDeclaration(decl); +- } +- } +- + function checkRightHandSideOfForOf(statement: ForOfStatement): Type { + const use = statement.awaitModifier ? IterationUse.ForAwaitOf : IterationUse.ForOf; + return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression); +@@ -43776,7 +43824,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (symbol.flags & SymbolFlags.EnumMember) { + return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration as EnumMember); + } +- if (isConstVariable(symbol)) { ++ if (isConstantVariable(symbol)) { + const declaration = symbol.valueDeclaration as VariableDeclaration | undefined; + if (declaration && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) { + return evaluate(declaration.initializer, declaration); +@@ -46648,7 +46696,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean { +- if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { ++ if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike(node)) { + return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); + } + return false; +@@ -47138,6 +47186,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + case ExternalEmitHelpers.CreateBinding: return ["__createBinding"]; + case ExternalEmitHelpers.SetFunctionName: return ["__setFunctionName"]; + case ExternalEmitHelpers.PropKey: return ["__propKey"]; ++ case ExternalEmitHelpers.AddDisposableResourceAndDisposeResources: return ["__addDisposableResource", "__disposeResources"]; + default: return Debug.fail("Unrecognized helper"); + } + } +@@ -47161,6 +47210,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters); + } + ++ const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & NodeFlags.BlockScoped : NodeFlags.None; + let lastStatic: Node | undefined, lastDeclare: Node | undefined, lastAsync: Node | undefined, lastOverride: Node | undefined, firstDecorator: Decorator | undefined; + let flags = ModifierFlags.None; + let sawExportBeforeDecorators = false; +@@ -47391,6 +47441,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + else if (node.kind === SyntaxKind.Parameter) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export"); ++ } + flags |= ModifierFlags.Export; + break; + case SyntaxKind.DefaultKeyword: +@@ -47398,6 +47454,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (container.kind === SyntaxKind.ModuleDeclaration && !isAmbientModule(container)) { + return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default"); ++ } + else if (!(flags & ModifierFlags.Export)) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default"); + } +@@ -47423,6 +47485,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + else if (node.kind === SyntaxKind.Parameter) { + return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare"); + } ++ else if (blockScopeKind === NodeFlags.Using) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare"); ++ } ++ else if (blockScopeKind === NodeFlags.AwaitUsing) { ++ return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare"); ++ } + else if ((node.parent.flags & NodeFlags.Ambient) && node.parent.kind === SyntaxKind.ModuleBlock) { + return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); + } +@@ -47594,9 +47662,12 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return findFirstModifierExcept(node, SyntaxKind.AbstractKeyword); + case SyntaxKind.ClassExpression: + case SyntaxKind.InterfaceDeclaration: +- case SyntaxKind.VariableStatement: + case SyntaxKind.TypeAliasDeclaration: + return find(node.modifiers, isModifier); ++ case SyntaxKind.VariableStatement: ++ return node.declarationList.flags & NodeFlags.Using ? ++ findFirstModifierExcept(node, SyntaxKind.AwaitKeyword) : ++ find(node.modifiers, isModifier); + case SyntaxKind.EnumDeclaration: + return findFirstModifierExcept(node, SyntaxKind.ConstKeyword); + default: +@@ -48445,7 +48516,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + initializer.kind === SyntaxKind.TrueKeyword || initializer.kind === SyntaxKind.FalseKeyword || + isBigIntLiteralExpression(initializer) + ); +- const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); ++ const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && (isVarConstLike(node)); + if (isConstOrReadonly && !node.type) { + if (isInvalidInitializer) { + return grammarErrorOnNode(initializer, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); +@@ -48458,21 +48529,37 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + } + + function checkGrammarVariableDeclaration(node: VariableDeclaration) { ++ const nodeFlags = getCombinedNodeFlagsCached(node); ++ const blockScopeKind = nodeFlags & NodeFlags.BlockScoped; ++ if (isBindingPattern(node.name)) { ++ switch (blockScopeKind) { ++ case NodeFlags.AwaitUsing: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "await using"); ++ case NodeFlags.Using: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_may_not_have_binding_patterns, "using"); ++ } ++ } ++ + if (node.parent.parent.kind !== SyntaxKind.ForInStatement && node.parent.parent.kind !== SyntaxKind.ForOfStatement) { +- if (node.flags & NodeFlags.Ambient) { ++ if (nodeFlags & NodeFlags.Ambient) { + checkAmbientInitializer(node); + } + else if (!node.initializer) { + if (isBindingPattern(node.name) && !isBindingPattern(node.parent)) { + return grammarErrorOnNode(node, Diagnostics.A_destructuring_declaration_must_have_an_initializer); + } +- if (isVarConst(node)) { +- return grammarErrorOnNode(node, Diagnostics.const_declarations_must_be_initialized); ++ switch (blockScopeKind) { ++ case NodeFlags.AwaitUsing: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "await using"); ++ case NodeFlags.Using: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "using"); ++ case NodeFlags.Const: ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_must_be_initialized, "const"); + } + } + } + +- if (node.exclamationToken && (node.parent.parent.kind !== SyntaxKind.VariableStatement || !node.type || node.initializer || node.flags & NodeFlags.Ambient)) { ++ if (node.exclamationToken && (node.parent.parent.kind !== SyntaxKind.VariableStatement || !node.type || node.initializer || nodeFlags & NodeFlags.Ambient)) { + const message = node.initializer + ? Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions + : !node.type +@@ -48486,8 +48573,6 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + checkESModuleMarker(node.name); + } + +- const checkLetConstNames = (isLet(node) || isVarConst(node)); +- + // 1. LexicalDeclaration : LetOrConst BindingList ; + // It is a Syntax Error if the BoundNames of BindingList contains "let". + // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding +@@ -48495,7 +48580,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + + // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code + // and its Identifier is eval or arguments +- return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); ++ return !!blockScopeKind && checkGrammarNameInLetOrConstDeclarations(node.name); + } + + function checkESModuleMarker(name: Identifier | BindingPattern): boolean { +@@ -48541,6 +48626,19 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + if (!declarationList.declarations.length) { + return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); + } ++ ++ const blockScopeFlags = declarationList.flags & NodeFlags.BlockScoped; ++ if ((blockScopeFlags === NodeFlags.Using || blockScopeFlags === NodeFlags.AwaitUsing) && isForInStatement(declarationList.parent)) { ++ return grammarErrorOnNode(declarationList, ++ blockScopeFlags === NodeFlags.Using ? ++ Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_using_declaration : ++ Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_an_await_using_declaration); ++ } ++ ++ if (blockScopeFlags === NodeFlags.AwaitUsing) { ++ return checkAwaitGrammar(declarationList); ++ } ++ + return false; + } + +@@ -48561,13 +48659,16 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return true; + } + +- function checkGrammarForDisallowedLetOrConstStatement(node: VariableStatement) { ++ function checkGrammarForDisallowedBlockScopedVariableStatement(node: VariableStatement) { + if (!allowLetAndConstDeclarations(node.parent)) { +- if (isLet(node.declarationList)) { +- return grammarErrorOnNode(node, Diagnostics.let_declarations_can_only_be_declared_inside_a_block); +- } +- else if (isVarConst(node.declarationList)) { +- return grammarErrorOnNode(node, Diagnostics.const_declarations_can_only_be_declared_inside_a_block); ++ const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & NodeFlags.BlockScoped; ++ if (blockScopeKind) { ++ const keyword = blockScopeKind === NodeFlags.Let ? "let" : ++ blockScopeKind === NodeFlags.Const ? "const" : ++ blockScopeKind === NodeFlags.Using ? "using" : ++ blockScopeKind === NodeFlags.AwaitUsing ? "await using" : ++ Debug.fail("Unknown BlockScope flag"); ++ return grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, keyword); + } + } + } +@@ -48991,6 +49092,34 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { + return name ? name : + isComputedPropertyName(node) && isEntityNameExpression(node.expression) ? tryGetNameFromEntityNameExpression(node.expression) : undefined; + } ++ ++ function getCombinedModifierFlagsCached(node: Declaration) { ++ // we hold onto the last node and result to speed up repeated lookups against the same node. ++ if (lastGetCombinedModifierFlagsNode === node) { ++ return lastGetCombinedModifierFlagsResult; ++ } ++ ++ lastGetCombinedModifierFlagsNode = node; ++ lastGetCombinedModifierFlagsResult = getCombinedModifierFlags(node); ++ return lastGetCombinedModifierFlagsResult; ++ } ++ ++ function getCombinedNodeFlagsCached(node: Node) { ++ // we hold onto the last node and result to speed up repeated lookups against the same node. ++ if (lastGetCombinedNodeFlagsNode === node) { ++ return lastGetCombinedNodeFlagsResult; ++ } ++ lastGetCombinedNodeFlagsNode = node; ++ lastGetCombinedNodeFlagsResult = getCombinedNodeFlags(node); ++ return lastGetCombinedNodeFlagsResult; ++ } ++ ++ function isVarConstLike(node: VariableDeclaration | VariableDeclarationList) { ++ const blockScopeKind = getCombinedNodeFlagsCached(node) & NodeFlags.BlockScoped; ++ return blockScopeKind === NodeFlags.Const || ++ blockScopeKind === NodeFlags.Using || ++ blockScopeKind === NodeFlags.AwaitUsing; ++ } + } + + function isNotAccessor(declaration: Declaration): boolean { +diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts +index 408fa9968..53c8e61ff 100644 +--- a/src/compiler/commandLineParser.ts ++++ b/src/compiler/commandLineParser.ts +@@ -218,6 +218,7 @@ const libEntries: [string, string][] = [ + ["esnext.symbol", "lib.es2019.symbol.d.ts"], + ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], + ["esnext.intl", "lib.esnext.intl.d.ts"], ++ ["esnext.disposable", "lib.esnext.disposable.d.ts"], + ["esnext.bigint", "lib.es2020.bigint.d.ts"], + ["esnext.string", "lib.es2022.string.d.ts"], + ["esnext.promise", "lib.es2021.promise.d.ts"], +diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json +index 8ba018241..bda674e96 100644 +--- a/src/compiler/diagnosticMessages.json ++++ b/src/compiler/diagnosticMessages.json +@@ -451,18 +451,14 @@ + "category": "Error", + "code": 1149 + }, +- "'const' declarations must be initialized.": { ++ "'{0}' declarations must be initialized.": { + "category": "Error", + "code": 1155 + }, +- "'const' declarations can only be declared inside a block.": { ++ "'{0}' declarations can only be declared inside a block.": { + "category": "Error", + "code": 1156 + }, +- "'let' declarations can only be declared inside a block.": { +- "category": "Error", +- "code": 1157 +- }, + "Unterminated template literal.": { + "category": "Error", + "code": 1160 +@@ -1601,6 +1597,26 @@ + "category": "Error", + "code": 1490 + }, ++ "'{0}' modifier cannot appear on a 'using' declaration.": { ++ "category": "Error", ++ "code": 1491 ++ }, ++ "'{0}' declarations may not have binding patterns.": { ++ "category": "Error", ++ "code": 1492 ++ }, ++ "The left-hand side of a 'for...in' statement cannot be a 'using' declaration.": { ++ "category": "Error", ++ "code": 1493 ++ }, ++ "The left-hand side of a 'for...in' statement cannot be an 'await using' declaration.": { ++ "category": "Error", ++ "code": 1494 ++ }, ++ "'{0}' modifier cannot appear on an 'await using' declaration.": { ++ "category": "Error", ++ "code": 1495 ++ }, + + "The types of '{0}' are incompatible between these types.": { + "category": "Error", +@@ -3623,6 +3639,26 @@ + "category": "Error", + "code": 2849 + }, ++ "The initializer of a 'using' declaration must be either an object with a '[Symbol.dispose]()' method, or be 'null' or 'undefined'.": { ++ "category": "Error", ++ "code": 2850 ++ }, ++ "The initializer of an 'await using' declaration must be either an object with a '[Symbol.asyncDispose]()' or '[Symbol.dispose]()' method, or be 'null' or 'undefined'.": { ++ "category": "Error", ++ "code": 2851 ++ }, ++ "'await using' statements are only allowed within async functions and at the top levels of modules.": { ++ "category": "Error", ++ "code": 2852 ++ }, ++ "'await using' statements are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module.": { ++ "category": "Error", ++ "code": 2853 ++ }, ++ "Top-level 'await using' statements are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.": { ++ "category": "Error", ++ "code": 2854 ++ }, + + "Import declaration '{0}' is using private name '{1}'.": { + "category": "Error", +@@ -7757,11 +7793,11 @@ + "category": "Error", + "code": 18036 + }, +- "Await expression cannot be used inside a class static block.": { ++ "'await' expression cannot be used inside a class static block.": { + "category": "Error", + "code": 18037 + }, +- "'For await' loops cannot be used inside a class static block.": { ++ "'for await' loops cannot be used inside a class static block.": { + "category": "Error", + "code": 18038 + }, +@@ -7820,5 +7856,9 @@ + "Its type '{0}' is not a valid JSX element type.": { + "category": "Error", + "code": 18053 ++ }, ++ "'await using' statements cannot be used inside a class static block.": { ++ "category": "Error", ++ "code": 18054 + } + } +diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts +index 6f34ec688..a58223868 100644 +--- a/src/compiler/emitter.ts ++++ b/src/compiler/emitter.ts +@@ -254,8 +254,10 @@ import { + isUnparsedNode, + isUnparsedPrepend, + isUnparsedSource, ++ isVarAwaitUsing, + isVarConst, + isVariableStatement, ++ isVarUsing, + JSDoc, + JSDocAugmentsTag, + JSDocCallbackTag, +@@ -3685,7 +3687,18 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri + } + + function emitVariableDeclarationList(node: VariableDeclarationList) { +- writeKeyword(isLet(node) ? "let" : isVarConst(node) ? "const" : "var"); ++ if (isVarAwaitUsing(node)) { ++ writeKeyword("await"); ++ writeSpace(); ++ writeKeyword("using"); ++ } ++ else { ++ const head = isLet(node) ? "let" : ++ isVarConst(node) ? "const" : ++ isVarUsing(node) ? "using" : ++ "var"; ++ writeKeyword(head); ++ } + writeSpace(); + emitList(node, node.declarations, ListFormat.VariableDeclarationList); + } +diff --git a/src/compiler/factory/emitHelpers.ts b/src/compiler/factory/emitHelpers.ts +index e14652a3a..d73ca9767 100644 +--- a/src/compiler/factory/emitHelpers.ts ++++ b/src/compiler/factory/emitHelpers.ts +@@ -136,6 +136,9 @@ export interface EmitHelperFactory { + createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; + createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression; + createClassPrivateFieldInHelper(state: Identifier, receiver: Expression): Expression; ++ // 'using' helpers ++ createAddDisposableResourceHelper(envBinding: Expression, value: Expression, async: boolean): Expression; ++ createDisposeResourcesHelper(envBinding: Expression): Expression; + } + + /** @internal */ +@@ -183,7 +186,10 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel + // Class Fields Helpers + createClassPrivateFieldGetHelper, + createClassPrivateFieldSetHelper, +- createClassPrivateFieldInHelper ++ createClassPrivateFieldInHelper, ++ // 'using' helpers ++ createAddDisposableResourceHelper, ++ createDisposeResourcesHelper, + }; + + /** +@@ -666,6 +672,20 @@ export function createEmitHelperFactory(context: TransformationContext): EmitHel + context.requestEmitHelper(classPrivateFieldInHelper); + return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /*typeArguments*/ undefined, [state, receiver]); + } ++ ++ function createAddDisposableResourceHelper(envBinding: Expression, value: Expression, async: boolean): Expression { ++ context.requestEmitHelper(addDisposableResourceHelper); ++ return factory.createCallExpression( ++ getUnscopedHelperName("__addDisposableResource"), ++ /*typeArguments*/ undefined, ++ [envBinding, value, async ? factory.createTrue() : factory.createFalse()] ++ ); ++ } ++ ++ function createDisposeResourcesHelper(envBinding: Expression) { ++ context.requestEmitHelper(disposeResourcesHelper); ++ return factory.createCallExpression(getUnscopedHelperName("__disposeResources"), /*typeArguments*/ undefined, [envBinding]); ++ } + } + + /** @internal */ +@@ -1367,6 +1387,71 @@ export const classPrivateFieldInHelper: UnscopedEmitHelper = { + };` + }; + ++/** ++ * @internal ++ */ ++export const addDisposableResourceHelper: UnscopedEmitHelper = { ++ name: "typescript:addDisposableResource", ++ importName: "__addDisposableResource", ++ scoped: false, ++ text: ` ++ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { ++ if (value !== null && value !== void 0) { ++ if (typeof value !== "object") throw new TypeError("Object expected."); ++ var dispose; ++ if (async) { ++ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); ++ dispose = value[Symbol.asyncDispose]; ++ } ++ if (dispose === void 0) { ++ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); ++ dispose = value[Symbol.dispose]; ++ } ++ if (typeof dispose !== "function") throw new TypeError("Object not disposable."); ++ env.stack.push({ value: value, dispose: dispose, async: async }); ++ } ++ else if (async) { ++ env.stack.push({ async: true }); ++ } ++ return value; ++ };` ++}; ++ ++/** ++ * @internal ++ */ ++export const disposeResourcesHelper: UnscopedEmitHelper = { ++ name: "typescript:disposeResources", ++ importName: "__disposeResources", ++ scoped: false, ++ text: ` ++ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) { ++ return function (env) { ++ function fail(e) { ++ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; ++ env.hasError = true; ++ } ++ function next() { ++ while (env.stack.length) { ++ var rec = env.stack.pop(); ++ try { ++ var result = rec.dispose && rec.dispose.call(rec.value); ++ if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); ++ } ++ catch (e) { ++ fail(e); ++ } ++ } ++ if (env.hasError) throw env.error; ++ } ++ return next(); ++ }; ++ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { ++ var e = new Error(message); ++ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; ++ });` ++}; ++ + let allUnscopedEmitHelpers: ReadonlyMap | undefined; + + /** @internal */ +@@ -1399,7 +1484,9 @@ export function getAllUnscopedEmitHelpers() { + classPrivateFieldSetHelper, + classPrivateFieldInHelper, + createBindingHelper, +- setModuleDefaultHelper ++ setModuleDefaultHelper, ++ addDisposableResourceHelper, ++ disposeResourcesHelper, + ], helper => helper.name)); + } + +diff --git a/src/compiler/factory/nodeConverters.ts b/src/compiler/factory/nodeConverters.ts +index 1541d56bf..bc12cb58c 100644 +--- a/src/compiler/factory/nodeConverters.ts ++++ b/src/compiler/factory/nodeConverters.ts +@@ -6,6 +6,7 @@ import { + BindingOrAssignmentPattern, + Block, + cast, ++ ClassDeclaration, + ConciseBody, + Debug, + Expression, +@@ -17,6 +18,8 @@ import { + isBindingElement, + isBindingPattern, + isBlock, ++ isDefaultModifier, ++ isExportModifier, + isExpression, + isIdentifier, + isObjectBindingPattern, +@@ -39,6 +42,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + return { + convertToFunctionBlock, + convertToFunctionExpression, ++ convertToClassExpression, + convertToArrayAssignmentElement, + convertToObjectAssignmentElement, + convertToAssignmentPattern, +@@ -59,7 +63,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + function convertToFunctionExpression(node: FunctionDeclaration) { + if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); + const updated = factory.createFunctionExpression( +- getModifiers(node), ++ getModifiers(node)?.filter(modifier => !isExportModifier(modifier) && !isDefaultModifier(modifier)), + node.asteriskToken, + node.name, + node.typeParameters, +@@ -75,6 +79,22 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + return updated; + } + ++ function convertToClassExpression(node: ClassDeclaration) { ++ const updated = factory.createClassExpression( ++ node.modifiers?.filter(modifier => !isExportModifier(modifier) && !isDefaultModifier(modifier)), ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ node.members ++ ); ++ setOriginalNode(updated, node); ++ setTextRange(updated, node); ++ if (getStartsOnNewLine(node)) { ++ setStartsOnNewLine(updated, /*newLine*/ true); ++ } ++ return updated; ++ } ++ + function convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement) { + if (isBindingElement(element)) { + if (element.dotDotDotToken) { +@@ -163,6 +183,7 @@ export function createNodeConverters(factory: NodeFactory): NodeConverters { + export const nullNodeConverters: NodeConverters = { + convertToFunctionBlock: notImplemented, + convertToFunctionExpression: notImplemented, ++ convertToClassExpression: notImplemented, + convertToArrayAssignmentElement: notImplemented, + convertToObjectAssignmentElement: notImplemented, + convertToAssignmentPattern: notImplemented, +diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts +index 638ff1547..9dd48e043 100644 +--- a/src/compiler/factory/nodeFactory.ts ++++ b/src/compiler/factory/nodeFactory.ts +@@ -134,6 +134,8 @@ import { + Identifier, + idText, + IfStatement, ++ ImmediatelyInvokedArrowFunction, ++ ImmediatelyInvokedFunctionExpression, + ImportClause, + ImportDeclaration, + ImportEqualsDeclaration, +@@ -991,6 +993,7 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + createExportDefault, + createExternalModuleExport, + createTypeCheck, ++ createIsNotTypeCheck, + createMethodCall, + createGlobalMethodCall, + createFunctionBindCall, +@@ -1322,6 +1325,10 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + TransformFlags.ContainsES2018; + break; + ++ case SyntaxKind.UsingKeyword: ++ transformFlags = TransformFlags.ContainsESNext; ++ break; ++ + case SyntaxKind.PublicKeyword: + case SyntaxKind.PrivateKeyword: + case SyntaxKind.ProtectedKeyword: +@@ -4178,6 +4185,9 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + TransformFlags.ContainsES2015 | + TransformFlags.ContainsBlockScopedBinding; + } ++ if (flags & NodeFlags.Using) { ++ node.transformFlags |= TransformFlags.ContainsESNext; ++ } + return node; + } + +@@ -6314,8 +6324,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + } + + // compound nodes +- function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; +- function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): ImmediatelyInvokedFunctionExpression; ++ function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedFunctionExpression; + function createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + return createCallExpression( + createFunctionExpression( +@@ -6332,8 +6342,8 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + ); + } + +- function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ function createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + function createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param?: ParameterDeclaration, paramValue?: Expression) { + return createCallExpression( + createArrowFunction( +@@ -6375,9 +6385,15 @@ export function createNodeFactory(flags: NodeFactoryFlags, baseFactory: BaseNode + // + + function createTypeCheck(value: Expression, tag: TypeOfTag) { +- return tag === "undefined" +- ? factory.createStrictEquality(value, createVoidZero()) +- : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); ++ return tag === "null" ? factory.createStrictEquality(value, createNull()) : ++ tag === "undefined" ? factory.createStrictEquality(value, createVoidZero()) : ++ factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag)); ++ } ++ ++ function createIsNotTypeCheck(value: Expression, tag: TypeOfTag) { ++ return tag === "null" ? factory.createStrictInequality(value, createNull()) : ++ tag === "undefined" ? factory.createStrictInequality(value, createVoidZero()) : ++ factory.createStrictInequality(createTypeOfExpression(value), createStringLiteral(tag)); + } + + function createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]) { +@@ -7585,10 +7601,12 @@ export function createSourceMapSource(fileName: string, text: string, skipTrivia + // Utilities + + export function setOriginalNode(node: T, original: Node | undefined): T { +- node.original = original; +- if (original) { +- const emitNode = original.emitNode; +- if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); ++ if (node.original !== original) { ++ node.original = original; ++ if (original) { ++ const emitNode = original.emitNode; ++ if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); ++ } + } + return node; + } +@@ -7596,7 +7614,7 @@ export function setOriginalNode(node: T, original: Node | undefi + function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefined) { + const { + flags, +- internalFlags, ++ internalFlags, + leadingComments, + trailingComments, + commentRange, +@@ -7606,24 +7624,95 @@ function mergeEmitNode(sourceEmitNode: EmitNode, destEmitNode: EmitNode | undefi + helpers, + startsOnNewLine, + snippetElement, ++ classThis, ++ assignedName, + } = sourceEmitNode; + if (!destEmitNode) destEmitNode = {} as EmitNode; +- // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later. +- if (leadingComments) destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); +- if (trailingComments) destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); +- if (flags) destEmitNode.flags = flags; +- if (internalFlags) destEmitNode.internalFlags = internalFlags & ~InternalEmitFlags.Immutable; +- if (commentRange) destEmitNode.commentRange = commentRange; +- if (sourceMapRange) destEmitNode.sourceMapRange = sourceMapRange; +- if (tokenSourceMapRanges) destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!); +- if (constantValue !== undefined) destEmitNode.constantValue = constantValue; ++ ++ // NOTE: We should have one or more lines here for each property in EmitNode, even if the line ++ // consists only of a comment indicating the property does not merge ++ ++ // `flags` overwrites the destination ++ if (flags) { ++ destEmitNode.flags = flags; ++ } ++ ++ // `internalFlags` overwrites the destination. We do not copy over the immutability of the source. ++ if (internalFlags) { ++ destEmitNode.internalFlags = internalFlags & ~InternalEmitFlags.Immutable; ++ } ++ ++ // `annotatedNodes` are not merged as they should only present on the parse tree node of a `SourceFile`. ++ ++ // `leadingComments` are concatenated with any existing leading comments on the destination ++ if (leadingComments) { ++ // We use `.slice()` in case `destEmitNode.leadingComments` is pushed to later ++ destEmitNode.leadingComments = addRange(leadingComments.slice(), destEmitNode.leadingComments); ++ } ++ ++ // `trailingComments` are concatenated with any existing trailing comments on the destination ++ if (trailingComments) { ++ // We use `.slice()` in case `destEmitNode.trailingComments` is pushed to later ++ destEmitNode.trailingComments = addRange(trailingComments.slice(), destEmitNode.trailingComments); ++ } ++ ++ // `commentRange` overwrites the destination ++ if (commentRange) { ++ destEmitNode.commentRange = commentRange; ++ } ++ ++ // `sourceMapRange` overwrites the destination ++ if (sourceMapRange) { ++ destEmitNode.sourceMapRange = sourceMapRange; ++ } ++ ++ // `tokenSourceMapRanges` are merged with the destination ++ if (tokenSourceMapRanges) { ++ destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges!); ++ } ++ ++ // `constantValue` overwrites the destination ++ if (constantValue !== undefined) { ++ destEmitNode.constantValue = constantValue; ++ } ++ ++ // `externalHelpersModuleName` is not merged ++ // `externalHelpers` is not merged ++ ++ // `helpers` are merged into the destination + if (helpers) { + for (const helper of helpers) { + destEmitNode.helpers = appendIfUnique(destEmitNode.helpers, helper); + } + } +- if (startsOnNewLine !== undefined) destEmitNode.startsOnNewLine = startsOnNewLine; +- if (snippetElement !== undefined) destEmitNode.snippetElement = snippetElement; ++ ++ // `startsOnNewLine` overwrites the destination ++ if (startsOnNewLine !== undefined) { ++ destEmitNode.startsOnNewLine = startsOnNewLine; ++ } ++ ++ // `snippetElement` overwrites the destination ++ if (snippetElement !== undefined) { ++ destEmitNode.snippetElement = snippetElement; ++ } ++ ++ // `typeNode` is not merged as it only applies to comment emit for a variable declaration. ++ // TODO: `typeNode` should overwrite the destination ++ ++ // `classThis` overwrites the destination ++ if (classThis) { ++ destEmitNode.classThis = classThis; ++ } ++ ++ // `assignedName` overwrites the destination ++ if (assignedName) { ++ destEmitNode.assignedName = assignedName; ++ } ++ ++ // `identifierTypeArguments` are not merged as they only apply to an Identifier in quick info ++ // `autoGenerate` is not merged as it only applies to a specific generated Identifier/PrivateIdentifier ++ // `generatedImportReference` is not merged as it only applies to an Identifier ++ + return destEmitNode; + } + +diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts +index 2e2721ead..bac8f690e 100644 +--- a/src/compiler/factory/utilities.ts ++++ b/src/compiler/factory/utilities.ts +@@ -178,6 +178,7 @@ import { + Token, + TransformFlags, + TypeNode, ++ WrappedExpression + } from "../_namespaces/ts"; + + // Compound nodes +@@ -655,6 +656,8 @@ export function isOuterExpression(node: Node, kinds = OuterExpressionKinds.All): + return false; + } + ++/** @internal */ ++export function skipOuterExpressions(node: WrappedExpression): T; + /** @internal */ + export function skipOuterExpressions(node: Expression, kinds?: OuterExpressionKinds): Expression; + /** @internal */ +diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts +index f49b48bb4..436fb04ef 100644 +--- a/src/compiler/parser.ts ++++ b/src/compiler/parser.ts +@@ -6816,7 +6816,9 @@ namespace Parser { + + let initializer!: VariableDeclarationList | Expression; + if (token() !== SyntaxKind.SemicolonToken) { +- if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword) { ++ if (token() === SyntaxKind.VarKeyword || token() === SyntaxKind.LetKeyword || token() === SyntaxKind.ConstKeyword || ++ token() === SyntaxKind.UsingKeyword && lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf) || ++ token() === SyntaxKind.AwaitKeyword && lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf)) { + initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true); + } + else { +@@ -7052,6 +7054,10 @@ namespace Parser { + case SyntaxKind.ClassKeyword: + case SyntaxKind.EnumKeyword: + return true; ++ case SyntaxKind.UsingKeyword: ++ return isUsingDeclaration(); ++ case SyntaxKind.AwaitKeyword: ++ return isAwaitUsingDeclaration(); + + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we +@@ -7118,6 +7124,7 @@ namespace Parser { + case SyntaxKind.StaticKeyword: + nextToken(); + continue; ++ + default: + return false; + } +@@ -7135,6 +7142,7 @@ namespace Parser { + case SyntaxKind.OpenBraceToken: + case SyntaxKind.VarKeyword: + case SyntaxKind.LetKeyword: ++ case SyntaxKind.UsingKeyword: + case SyntaxKind.FunctionKeyword: + case SyntaxKind.ClassKeyword: + case SyntaxKind.EnumKeyword: +@@ -7200,6 +7208,41 @@ namespace Parser { + return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuring); + } + ++ function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLineDisallowOf() { ++ return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(/*disallowOf*/ true); ++ } ++ ++ function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf?: boolean) { ++ nextToken(); ++ if (disallowOf && token() === SyntaxKind.OfKeyword) return false; ++ return (isBindingIdentifier() || token() === SyntaxKind.OpenBraceToken) && !scanner.hasPrecedingLineBreak(); ++ } ++ ++ function isUsingDeclaration() { ++ // 'using' always starts a lexical declaration if followed by an identifier. We also eagerly parse ++ // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out ++ // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `using[x]`). ++ return lookAhead(nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine); ++ } ++ ++ function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLineDisallowOf() { ++ return nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(/*disallowOf*/ true); ++ } ++ ++ function nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine(disallowOf?: boolean) { ++ if (nextToken() === SyntaxKind.UsingKeyword) { ++ return nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf); ++ } ++ return false; ++ } ++ ++ function isAwaitUsingDeclaration() { ++ // 'await using' always starts a lexical declaration if followed by an identifier. We also eagerly parse ++ // |ObjectBindingPattern| so that we can report a grammar error during check. We don't parse out ++ // |ArrayBindingPattern| since it potentially conflicts with element access (i.e., `await using[x]`). ++ return lookAhead(nextTokenIsUsingKeywordThenBindingIdentifierOrStartOfObjectDestructuringOnSameLine); ++ } ++ + function parseStatement(): Statement { + switch (token()) { + case SyntaxKind.SemicolonToken: +@@ -7213,6 +7256,16 @@ namespace Parser { + return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + } + break; ++ case SyntaxKind.AwaitKeyword: ++ if (isAwaitUsingDeclaration()) { ++ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); ++ } ++ break; ++ case SyntaxKind.UsingKeyword: ++ if (isUsingDeclaration()) { ++ return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); ++ } ++ break; + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*modifiers*/ undefined); + case SyntaxKind.ClassKeyword: +@@ -7317,6 +7370,8 @@ namespace Parser { + case SyntaxKind.VarKeyword: + case SyntaxKind.LetKeyword: + case SyntaxKind.ConstKeyword: ++ case SyntaxKind.UsingKeyword: ++ case SyntaxKind.AwaitKeyword: + return parseVariableStatement(pos, hasJSDoc, modifiersIn); + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(pos, hasJSDoc, modifiersIn); +@@ -7473,6 +7528,14 @@ namespace Parser { + case SyntaxKind.ConstKeyword: + flags |= NodeFlags.Const; + break; ++ case SyntaxKind.UsingKeyword: ++ flags |= NodeFlags.Using; ++ break; ++ case SyntaxKind.AwaitKeyword: ++ Debug.assert(isAwaitUsingDeclaration()); ++ flags |= NodeFlags.AwaitUsing; ++ nextToken(); ++ break; + default: + Debug.fail(); + } +diff --git a/src/compiler/program.ts b/src/compiler/program.ts +index c095ebb6e..36571405c 100644 +--- a/src/compiler/program.ts ++++ b/src/compiler/program.ts +@@ -1392,7 +1392,7 @@ export const plainJSErrors: Set = new Set([ + Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, + Diagnostics.Duplicate_label_0.code, + Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code, +- Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code, ++ Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block.code, + Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, + Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, + Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, +@@ -1422,14 +1422,14 @@ export const plainJSErrors: Set = new Set([ + Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, + Diagnostics._0_modifier_cannot_be_used_here.code, + Diagnostics._0_modifier_must_precede_1_modifier.code, +- Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code, +- Diagnostics.const_declarations_must_be_initialized.code, ++ Diagnostics._0_declarations_can_only_be_declared_inside_a_block.code, ++ Diagnostics._0_declarations_must_be_initialized.code, + Diagnostics.extends_clause_already_seen.code, +- Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, + Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + Diagnostics.Class_constructor_may_not_be_a_generator.code, + Diagnostics.Class_constructor_may_not_be_an_accessor.code, + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + // Type errors + Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code, + ]); +diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts +index 9f539aec4..c2d945a02 100644 +--- a/src/compiler/scanner.ts ++++ b/src/compiler/scanner.ts +@@ -194,6 +194,7 @@ export const textToKeywordObj: MapLike = { + undefined: SyntaxKind.UndefinedKeyword, + unique: SyntaxKind.UniqueKeyword, + unknown: SyntaxKind.UnknownKeyword, ++ using: SyntaxKind.UsingKeyword, + var: SyntaxKind.VarKeyword, + void: SyntaxKind.VoidKeyword, + while: SyntaxKind.WhileKeyword, +diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts +index a6bf29119..f8c1ee5d5 100644 +--- a/src/compiler/transformer.ts ++++ b/src/compiler/transformer.ts +@@ -72,7 +72,7 @@ import { + transformNodeModule, + transformSystemModule, + transformTypeScript, +- VariableDeclaration, ++ VariableDeclaration + } from "./_namespaces/ts"; + import * as performance from "./_namespaces/ts.performance"; + +@@ -131,11 +131,6 @@ function getScriptTransformers(compilerOptions: CompilerOptions, customTransform + if (compilerOptions.experimentalDecorators) { + transformers.push(transformLegacyDecorators); + } +- else if (languageVersion < ScriptTarget.ESNext || !useDefineForClassFields) { +- transformers.push(transformESDecorators); +- } +- +- transformers.push(transformClassFields); + + if (getJSXTransformEnabled(compilerOptions)) { + transformers.push(transformJsx); +@@ -145,6 +140,12 @@ function getScriptTransformers(compilerOptions: CompilerOptions, customTransform + transformers.push(transformESNext); + } + ++ if (!compilerOptions.experimentalDecorators && (languageVersion < ScriptTarget.ESNext || !useDefineForClassFields)) { ++ transformers.push(transformESDecorators); ++ } ++ ++ transformers.push(transformClassFields); ++ + if (languageVersion < ScriptTarget.ES2021) { + transformers.push(transformES2021); + } +diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts +index f038aa3d3..07adbf4b1 100644 +--- a/src/compiler/transformers/classFields.ts ++++ b/src/compiler/transformers/classFields.ts +@@ -20,6 +20,8 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasClassThisAssignment, ++ classHasExplicitlyAssignedName, + ClassLikeDeclaration, + classOrConstructorParameterIsDecorated, + ClassStaticBlockDeclaration, +@@ -44,7 +46,7 @@ import { + filter, + find, + findComputedPropertyNameCacheAssignment, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + flattenCommaList, + ForStatement, + GeneratedIdentifier, +@@ -80,14 +82,16 @@ import { + isArrowFunction, + isAssignmentExpression, + isAutoAccessorPropertyDeclaration, +- isBindingName, ++ isBlock, + isCallChain, + isCallToHelper, ++ isCatchClause, + isClassDeclaration, + isClassElement, + isClassExpression, +- isClassLike, ++ isClassNamedEvaluationHelperBlock, + isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, + isCommaExpression, + isCompoundAssignment, + isComputedPropertyName, +@@ -96,7 +100,6 @@ import { + isElementAccessExpression, + isExportOrDefaultModifier, + isExpression, +- isExpressionStatement, + isForInitializer, + isGeneratedIdentifier, + isGeneratedPrivateIdentifier, +@@ -104,6 +107,7 @@ import { + isGetAccessorDeclaration, + isHeritageClause, + isIdentifier, ++ isIdentifierText, + isInitializedProperty, + isLeftHandSideExpression, + isMethodDeclaration, +@@ -127,7 +131,6 @@ import { + isPropertyAssignment, + isPropertyDeclaration, + isPropertyName, +- isPropertyNameLiteral, + isSetAccessor, + isSetAccessorDeclaration, + isShorthandPropertyAssignment, +@@ -138,9 +141,11 @@ import { + isStatement, + isStatic, + isStaticModifier, ++ isStringLiteral, + isSuperProperty, + isTemplateLiteral, + isThisProperty, ++ isTryStatement, + isVoidExpression, + LeftHandSideExpression, + LexicalEnvironment, +@@ -153,6 +158,7 @@ import { + moveRangePos, + newPrivateEnvironment, + Node, ++ NodeArray, + NodeCheckFlags, + NodeFactory, + nodeIsSynthesized, +@@ -161,7 +167,6 @@ import { + OuterExpressionKinds, + ParameterDeclaration, + ParenthesizedExpression, +- PartiallyEmittedExpression, + PostfixUnaryExpression, + PrefixUnaryExpression, + PrivateEnvironment, +@@ -203,6 +208,7 @@ import { + ThisExpression, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, + tryCast, + tryGetTextOfPropertyName, + unescapeLeadingUnderscores, +@@ -217,7 +223,7 @@ import { + visitNodes, + Visitor, + visitParameterList, +- VisitResult, ++ VisitResult + } from "../_namespaces/ts"; + + const enum ClassPropertySubstitutionFlags { +@@ -462,7 +468,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.ClassDeclaration: + return visitClassDeclaration(node as ClassDeclaration); + case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, /*referencedName*/ undefined); ++ return visitClassExpression(node as ClassExpression); + case SyntaxKind.ClassStaticBlockDeclaration: + case SyntaxKind.PropertyDeclaration: + return Debug.fail("Use `classElementVisitor` instead."); +@@ -490,7 +496,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.BinaryExpression: + return visitBinaryExpression(node as BinaryExpression, /*discarded*/ false); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + case SyntaxKind.CallExpression: + return visitCallExpression(node as CallExpression); + case SyntaxKind.ExpressionStatement: +@@ -499,6 +505,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitTaggedTemplateExpression(node as TaggedTemplateExpression); + case SyntaxKind.ForStatement: + return visitForStatement(node as ForStatement); ++ case SyntaxKind.ThisKeyword: ++ return visitThisExpression(node as ThisExpression); + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + // If we are descending into a new scope, clear the current class element +@@ -527,19 +535,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitEachChild(node, visitor, context); + } + +- function namedEvaluationVisitor(node: Node, referencedName: Expression): VisitResult { +- switch (node.kind) { +- case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, referencedName); +- default: +- return visitor(node); +- } +- } +- + /** + * Visits a node in an expression whose result is discarded. + */ +@@ -553,7 +548,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + default: + return visitor(node); + } +@@ -692,9 +687,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updatePropertyAssignment(node, name, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -713,13 +706,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + return statement; + } + +- function getAssignedNameOfIdentifier(name: Identifier, initializer: Expression) { +- const originalClass = getOriginalNode(initializer, isClassLike); +- return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, ModifierFlags.Default) ? +- factory.createStringLiteral("default") : +- factory.createStringLiteralFromNode(name); +- } +- + function visitVariableDeclaration(node: VariableDeclaration) { + // 14.3.1.2 RS: Evaluation + // LexicalBinding : BindingIdentifier Initializer +@@ -736,10 +722,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateVariableDeclaration(node, name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -763,18 +746,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- /*dotDotDotToken*/ undefined, +- name, +- /*questionToken*/ undefined, +- /*type*/ undefined, +- initializer +- ); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -798,11 +770,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const propertyName = visitNode(node.propertyName, visitor, isPropertyName); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBindingElement(node, /*dotDotDotToken*/ undefined, propertyName, name, initializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -819,10 +787,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // is `""`. + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = factory.createStringLiteral(node.isExportEquals ? "" : "default"); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- const expression = visitNode(node.expression, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateExportAssignment(node, modifiers, expression); ++ node = transformNamedEvaluation(context, node, /*ignoreEmptyStringLiteral*/ true, node.isExportEquals ? "" : "default"); + } + + return visitEachChild(node, visitor, context); +@@ -1023,15 +988,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- return factory.updatePropertyDeclaration( +- node, +- visitNodes(node.modifiers, modifierVisitor, isModifier), +- name, +- /*questionOrExclamationToken*/ undefined, +- /*type*/ undefined, +- visitNode(node.initializer, child => namedEvaluationVisitor(child, referencedName), isExpression) +- ); ++ node = transformNamedEvaluation(context, node); + } + + return factory.updatePropertyDeclaration( +@@ -1052,8 +1009,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + + const expr = getPropertyNameExpressionIfNeeded( + node.name, +- /*shouldHoist*/ !!node.initializer || useDefineForClassFields, +- /*captureReferencedName*/ isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)); ++ /*shouldHoist*/ !!node.initializer || useDefineForClassFields); + if (expr) { + getPendingExpressions().push(...flattenCommaList(expr)); + } +@@ -1448,6 +1404,21 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + if (shouldTransformPrivateElementsOrClassStaticBlocks) { ++ if (isClassThisAssignmentBlock(node)) { ++ const result = visitNode(node.body.statements[0].expression, visitor, isExpression); ++ // If the generated `_classThis` assignment is a noop (i.e., `_classThis = _classThis`), we can ++ // eliminate the expression ++ if (isAssignmentExpression(result, /*excludeCompoundAssignment*/ true) && ++ result.left === result.right) { ++ return undefined; ++ } ++ return result; ++ } ++ ++ if (isClassNamedEvaluationHelperBlock(node)) { ++ return visitNode(node.body.statements[0].expression, visitor, isExpression); ++ } ++ + startLexicalEnvironment(); + let statements = setCurrentClassElementAnd( + node, +@@ -1457,9 +1428,10 @@ export function transformClassFields(context: TransformationContext): (x: Source + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + + const iife = factory.createImmediatelyInvokedArrowFunction(statements); ++ setOriginalNode(skipParentheses(iife.expression), node); ++ addEmitFlags(skipParentheses(iife.expression), EmitFlags.AdviseOnEmitNode); + setOriginalNode(iife, node); + setTextRange(iife, node); +- addEmitFlags(iife, EmitFlags.AdviseOnEmitNode); + return iife; + } + } +@@ -1467,14 +1439,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + function isAnonymousClassNeedingAssignedName(node: AnonymousFunctionDefinition) { + if (isClassExpression(node) && !node.name) { + const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); +- const classStaticBlock = find(staticPropertiesOrClassStaticBlocks, isClassStaticBlockDeclaration); +- if (classStaticBlock) { +- for (const statement of classStaticBlock.body.statements) { +- if (isExpressionStatement(statement) && +- isCallToHelper(statement.expression, "___setFunctionName" as __String)) { +- return false; +- } +- } ++ if (some(staticPropertiesOrClassStaticBlocks, isClassNamedEvaluationHelperBlock)) { ++ return false; + } + + const hasTransformableStatics = +@@ -1536,10 +1502,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const left = visitNode(node.left, visitor, isExpression); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right); ++ node = transformNamedEvaluation(context, node); ++ Debug.assertNode(node, isAssignmentExpression); + } + + const left = skipOuterExpressions(node.left, OuterExpressionKinds.PartiallyEmittedExpressions | OuterExpressionKinds.Parentheses); +@@ -1645,7 +1609,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return factory.updateCommaListExpression(node, elements); + } + +- function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + // 8.4.5 RS: NamedEvaluation + // ParenthesizedExpression : `(` Expression `)` + // ... +@@ -1653,42 +1617,11 @@ export function transformClassFields(context: TransformationContext): (x: Source + + const visitorFunc: Visitor = + discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : + visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updateParenthesizedExpression(node, expression); + } + +- function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean, referencedName: Expression | undefined) { +- // Emulates 8.4.5 RS: NamedEvaluation +- +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; +- const expression = visitNode(node.expression, visitorFunc, isExpression); +- return factory.updatePartiallyEmittedExpression(node, expression); +- } +- +- function visitReferencedPropertyName(node: PropertyName) { +- if (isPropertyNameLiteral(node) || isPrivateIdentifier(node)) { +- const referencedName = factory.createStringLiteralFromNode(node); +- const name = visitNode(node, visitor, isPropertyName); +- return { referencedName, name }; +- } +- +- if (isPropertyNameLiteral(node.expression) && !isIdentifier(node.expression)) { +- const referencedName = factory.createStringLiteralFromNode(node.expression); +- const name = visitNode(node, visitor, isPropertyName); +- return { referencedName, name }; +- } +- +- const referencedName = factory.createTempVariable(hoistVariableDeclaration); +- const key = emitHelpers().createPropKeyHelper(visitNode(node.expression, visitor, isExpression)); +- const assignment = factory.createAssignment(referencedName, key); +- const name = factory.updateComputedPropertyName(node, injectPendingExpressions(assignment)); +- return { referencedName, name }; +- } + + function createPrivateIdentifierAssignment(info: PrivateIdentifierInfo, receiver: Expression, right: Expression, operator: AssignmentOperator): Expression { + receiver = visitNode(receiver, visitor, isExpression); +@@ -1750,6 +1683,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + facts |= ClassFacts.ClassWasDecorated; + } ++ if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { ++ facts |= ClassFacts.NeedsClassConstructorReference; ++ } + let containsPublicInstanceFields = false; + let containsInitializedPublicInstanceFields = false; + let containsInstancePrivateElements = false; +@@ -1820,7 +1756,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return visitEachChild(node, visitor, context); + } + +- function visitInNewClassLexicalEnvironment(node: T, referencedName: Expression | undefined, visitor: (node: T, facts: ClassFacts, referencedName: Expression | undefined) => U) { ++ function visitInNewClassLexicalEnvironment(node: T, visitor: (node: T, facts: ClassFacts) => U) { + const savedCurrentClassContainer = currentClassContainer; + const savedPendingExpressions = pendingExpressions; + const savedLexicalEnvironment = lexicalEnvironment; +@@ -1834,6 +1770,22 @@ export function transformClassFields(context: TransformationContext): (x: Source + if (name && isIdentifier(name)) { + getPrivateIdentifierEnvironment().data.className = name; + } ++ else if (node.emitNode?.assignedName) { ++ if (isStringLiteral(node.emitNode.assignedName)) { ++ // If the class name was assigned from a string literal based on an Identifier, use the Identifier ++ // as the prefix. ++ if (node.emitNode.assignedName.textSourceNode && ++ isIdentifier(node.emitNode.assignedName.textSourceNode)) { ++ getPrivateIdentifierEnvironment().data.className = node.emitNode.assignedName.textSourceNode; ++ } ++ // If the class name was assigned from a string literal that is a valid identifier, create an ++ // identifier from it. ++ else if (isIdentifierText(node.emitNode.assignedName.text, languageVersion)) { ++ const prefixName = factory.createIdentifier(node.emitNode.assignedName.text); ++ getPrivateIdentifierEnvironment().data.className = prefixName; ++ } ++ } ++ } + } + + if (shouldTransformPrivateElementsOrClassStaticBlocks) { +@@ -1855,7 +1807,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + enableSubstitutionForClassStaticThisOrSuperReference(); + } + +- const result = visitor(node, facts, referencedName); ++ const result = visitor(node, facts); + endClassLexicalEnvironment(); + Debug.assert(lexicalEnvironment === savedLexicalEnvironment); + currentClassContainer = savedCurrentClassContainer; +@@ -1865,7 +1817,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + } + + function visitClassDeclaration(node: ClassDeclaration) { +- return visitInNewClassLexicalEnvironment(node, /*referencedName*/ undefined, visitClassDeclarationInNewClassLexicalEnvironment); ++ return visitInNewClassLexicalEnvironment(node, visitClassDeclarationInNewClassLexicalEnvironment); + } + + function visitClassDeclarationInNewClassLexicalEnvironment(node: ClassDeclaration, facts: ClassFacts) { +@@ -1952,11 +1904,11 @@ export function transformClassFields(context: TransformationContext): (x: Source + return statements; + } + +- function visitClassExpression(node: ClassExpression, referencedName: Expression | undefined): Expression { +- return visitInNewClassLexicalEnvironment(node, referencedName, visitClassExpressionInNewClassLexicalEnvironment); ++ function visitClassExpression(node: ClassExpression): Expression { ++ return visitInNewClassLexicalEnvironment(node, visitClassExpressionInNewClassLexicalEnvironment); + } + +- function visitClassExpressionInNewClassLexicalEnvironment(node: ClassExpression, facts: ClassFacts, referencedName: Expression | undefined): Expression { ++ function visitClassExpressionInNewClassLexicalEnvironment(node: ClassExpression, facts: ClassFacts): Expression { + // If this class expression is a transformation of a decorated class declaration, + // then we want to output the pendingExpressions as statements, not as inlined + // expressions with the class statement. +@@ -2002,7 +1954,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); + const heritageClauses = visitNodes(node.heritageClauses, heritageClauseVisitor, isHeritageClause); + const { members, prologue } = transformClassMembers(node); +- let classExpression = factory.updateClassExpression( ++ const classExpression = factory.updateClassExpression( + node, + modifiers, + node.name, +@@ -2025,7 +1977,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + isPrivateIdentifierClassElementDeclaration(node) || + shouldTransformInitializers && isInitializedProperty(node)); + +- if (hasTransformableStatics || some(pendingExpressions) || referencedName) { ++ if (hasTransformableStatics || some(pendingExpressions)) { + if (isDecoratedClassDeclaration) { + Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); + +@@ -2034,30 +1986,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + addRange(pendingStatements, map(pendingExpressions, factory.createExpressionStatement)); + } + +- if (referencedName) { +- if (shouldTransformPrivateElementsOrClassStaticBlocks) { +- const setNameExpression = emitHelpers().createSetFunctionNameHelper(temp ?? node.emitNode?.classThis ?? factory.getInternalName(node), referencedName); +- pendingStatements.push(factory.createExpressionStatement(setNameExpression)); +- } +- else { +- const setNameExpression = emitHelpers().createSetFunctionNameHelper(factory.createThis(), referencedName); +- classExpression = factory.updateClassExpression( +- classExpression, +- classExpression.modifiers, +- classExpression.name, +- classExpression.typeParameters, +- classExpression.heritageClauses, [ +- factory.createClassStaticBlockDeclaration( +- factory.createBlock([ +- factory.createExpressionStatement(setNameExpression) +- ]) +- ), +- ...classExpression.members +- ] +- ); +- } +- } +- + if (some(staticPropertiesOrClassStaticBlocks)) { + addPropertyOrClassStaticBlockStatements(pendingStatements, staticPropertiesOrClassStaticBlocks, node.emitNode?.classThis ?? factory.getInternalName(node)); + } +@@ -2086,9 +2014,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + + // Add any pending expressions leftover from elided or relocated computed property names + addRange(expressions, pendingExpressions); +- if (referencedName) { +- expressions.push(emitHelpers().createSetFunctionNameHelper(temp, referencedName)); +- } + addRange(expressions, generateInitializedPropertyExpressionsOrClassStaticBlock(staticPropertiesOrClassStaticBlocks, temp)); + expressions.push(factory.cloneNode(temp)); + } +@@ -2115,6 +2040,17 @@ export function transformClassFields(context: TransformationContext): (x: Source + return undefined; + } + ++ function visitThisExpression(node: ThisExpression) { ++ if (shouldTransformThisInStaticInitializers && currentClassElement && ++ isClassStaticBlockDeclaration(currentClassElement) && ++ lexicalEnvironment?.data) { ++ const { classThis, classConstructor } = lexicalEnvironment.data; ++ return classThis ?? classConstructor ?? node; ++ } ++ ++ return node; ++ } ++ + function transformClassMembers(node: ClassDeclaration | ClassExpression) { + const shouldTransformPrivateStaticElementsInClass = !!(getInternalEmitFlags(node) & InternalEmitFlags.TransformPrivateStaticElements); + +@@ -2197,9 +2133,16 @@ export function transformClassFields(context: TransformationContext): (x: Source + // and return a new array. + if (syntheticConstructor || syntheticStaticBlock) { + let membersArray: ClassElement[] | undefined; ++ const classThisAssignmentBlock = find(members, isClassThisAssignmentBlock); ++ const classNamedEvaluationHelperBlock = find(members, isClassNamedEvaluationHelperBlock); ++ membersArray = append(membersArray, classThisAssignmentBlock); ++ membersArray = append(membersArray, classNamedEvaluationHelperBlock); + membersArray = append(membersArray, syntheticConstructor); + membersArray = append(membersArray, syntheticStaticBlock); +- membersArray = addRange(membersArray, members); ++ const remainingMembers = classThisAssignmentBlock || classNamedEvaluationHelperBlock ? ++ filter(members, member => member !== classThisAssignmentBlock && member !== classNamedEvaluationHelperBlock) : ++ members; ++ membersArray = addRange(membersArray, remainingMembers); + members = setTextRange(factory.createNodeArray(membersArray), /*location*/ node.members); + } + +@@ -2256,6 +2199,66 @@ export function transformClassFields(context: TransformationContext): (x: Source + ); + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[], constructor: ConstructorDeclaration) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ statementOffset = superStatementIndex + 1; ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements, ++ constructor); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ ++ // Add the property initializers. Transforms this: ++ // ++ // public x = 1; ++ // ++ // Into this: ++ // ++ // constructor() { ++ // this.x = 1; ++ // } ++ // ++ // If we do useDefineForClassFields, they'll be converted elsewhere. ++ // We instead *remove* them from the transformed output at this stage. ++ ++ // parameter-property assignments should occur immediately after the prologue and `super()`, ++ // so only count the statements that immediately follow. ++ while (statementOffset < statementsIn.length) { ++ const statement = statementsIn[statementOffset]; ++ if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { ++ statementOffset++; ++ } ++ else { ++ break; ++ } ++ } ++ ++ addRange(statementsOut, initializerStatements); ++ } ++ ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset)); ++ } ++ + function transformConstructorBody(node: ClassDeclaration | ClassExpression, constructor: ConstructorDeclaration | undefined, isDerivedClass: boolean) { + const instanceProperties = getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); + let properties = instanceProperties; +@@ -2274,45 +2277,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + resumeLexicalEnvironment(); + + const needsSyntheticConstructor = !constructor && isDerivedClass; +- let indexOfFirstStatementAfterSuperAndPrologue = 0; +- let prologueStatementCount = 0; +- let superStatementIndex = -1; ++ let statementOffset = 0; + let statements: Statement[] = []; + +- if (constructor?.body?.statements) { +- prologueStatementCount = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); +- superStatementIndex = findSuperStatementIndex(constructor.body.statements, prologueStatementCount); +- +- // If there was a super call, visit existing statements up to and including it +- if (superStatementIndex >= 0) { +- indexOfFirstStatementAfterSuperAndPrologue = superStatementIndex + 1; +- statements = [ +- ...statements.slice(0, prologueStatementCount), +- ...visitNodes(constructor.body.statements, visitor, isStatement, prologueStatementCount, indexOfFirstStatementAfterSuperAndPrologue - prologueStatementCount), +- ...statements.slice(prologueStatementCount), +- ]; +- } +- else if (prologueStatementCount >= 0) { +- indexOfFirstStatementAfterSuperAndPrologue = prologueStatementCount; +- } +- } +- +- if (needsSyntheticConstructor) { +- // Add a synthetic `super` call: +- // +- // super(...arguments); +- // +- statements.push( +- factory.createExpressionStatement( +- factory.createCallExpression( +- factory.createSuper(), +- /*typeArguments*/ undefined, +- [factory.createSpreadElement(factory.createIdentifier("arguments"))] +- ) +- ) +- ); +- } +- + // Add the property initializers. Transforms this: + // + // public x = 1; +@@ -2323,42 +2290,68 @@ export function transformClassFields(context: TransformationContext): (x: Source + // this.x = 1; + // } + // +- // If we do useDefineForClassFields, they'll be converted elsewhere. +- // We instead *remove* them from the transformed output at this stage. +- let parameterPropertyDeclarationCount = 0; +- if (constructor?.body) { +- // parameter-property assignments should occur immediately after the prologue and `super()`, +- // so only count the statements that immediately follow. +- for (let i = indexOfFirstStatementAfterSuperAndPrologue; i < constructor.body.statements.length; i++) { +- const statement = constructor.body.statements[i]; +- if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { +- parameterPropertyDeclarationCount++; +- } +- else { +- break; +- } +- } +- if (parameterPropertyDeclarationCount > 0) { +- indexOfFirstStatementAfterSuperAndPrologue += parameterPropertyDeclarationCount; +- } +- } +- ++ const initializerStatements: Statement[] = []; + const receiver = factory.createThis(); ++ + // private methods can be called in property initializers, they should execute first. +- addInstanceMethodStatements(statements, privateMethodsAndAccessors, receiver); ++ addInstanceMethodStatements(initializerStatements, privateMethodsAndAccessors, receiver); + if (constructor) { + const parameterProperties = filter(instanceProperties, prop => isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); + const nonParameterProperties = filter(properties, prop => !isParameterPropertyDeclaration(getOriginalNode(prop), constructor)); +- addPropertyOrClassStaticBlockStatements(statements, parameterProperties, receiver); +- addPropertyOrClassStaticBlockStatements(statements, nonParameterProperties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, parameterProperties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, nonParameterProperties, receiver); + } + else { +- addPropertyOrClassStaticBlockStatements(statements, properties, receiver); ++ addPropertyOrClassStaticBlockStatements(initializerStatements, properties, receiver); + } + +- // Add existing statements after the initial prologues and super call +- if (constructor) { +- addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatementAfterSuperAndPrologue)); ++ if (constructor?.body) { ++ statementOffset = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); ++ const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, statementOffset); ++ if (superStatementIndices.length) { ++ transformConstructorBodyWorker( ++ statements, ++ constructor.body.statements, ++ statementOffset, ++ superStatementIndices, ++ /*superPathDepth*/ 0, ++ initializerStatements, ++ constructor ++ ); ++ } ++ else { ++ // parameter-property assignments should occur immediately after the prologue and `super()`, ++ // so only count the statements that immediately follow. ++ while (statementOffset < constructor.body.statements.length) { ++ const statement = constructor.body.statements[statementOffset]; ++ if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) { ++ statementOffset++; ++ } ++ else { ++ break; ++ } ++ } ++ addRange(statements, initializerStatements); ++ addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, statementOffset)); ++ } ++ } ++ else { ++ if (needsSyntheticConstructor) { ++ // Add a synthetic `super` call: ++ // ++ // super(...arguments); ++ // ++ statements.push( ++ factory.createExpressionStatement( ++ factory.createCallExpression( ++ factory.createSuper(), ++ /*typeArguments*/ undefined, ++ [factory.createSpreadElement(factory.createIdentifier("arguments"))] ++ ) ++ ) ++ ); ++ } ++ addRange(statements, initializerStatements); + } + + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); +@@ -2406,7 +2399,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + + function transformPropertyOrClassStaticBlock(property: PropertyDeclaration | ClassStaticBlockDeclaration, receiver: LeftHandSideExpression) { + const expression = isClassStaticBlockDeclaration(property) ? +- transformClassStaticBlockDeclaration(property) : ++ setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : + transformProperty(property, receiver); + if (!expression) { + return undefined; +@@ -2451,7 +2444,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + function generateInitializedPropertyExpressionsOrClassStaticBlock(propertiesOrClassStaticBlocks: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) { + const expressions: Expression[] = []; + for (const property of propertiesOrClassStaticBlocks) { +- const expression = isClassStaticBlockDeclaration(property) ? transformClassStaticBlockDeclaration(property) : transformProperty(property, receiver); ++ const expression = isClassStaticBlockDeclaration(property) ? ++ setCurrentClassElementAnd(property, transformClassStaticBlockDeclaration, property) : ++ setCurrentClassElementAnd(property, () => transformProperty(property, receiver), /*arg*/ undefined); + if (!expression) { + continue; + } +@@ -2490,17 +2485,8 @@ export function transformClassFields(context: TransformationContext): (x: Source + // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name) + const emitAssignment = !useDefineForClassFields; + +- let referencedName: Expression | undefined; + if (isNamedEvaluation(property, isAnonymousClassNeedingAssignedName)) { +- if (isPropertyNameLiteral(property.name) || isPrivateIdentifier(property.name)) { +- referencedName = factory.createStringLiteralFromNode(property.name); +- } +- else if (isPropertyNameLiteral(property.name.expression) && !isIdentifier(property.name.expression)) { +- referencedName = factory.createStringLiteralFromNode(property.name.expression); +- } +- else { +- referencedName = factory.getGeneratedNameForNode(property.name); +- } ++ property = transformNamedEvaluation(context, property); + } + + const propertyName = +@@ -2514,10 +2500,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + currentClassElement = property; + } + +- const initializerVisitor: Visitor = +- referencedName ? child => namedEvaluationVisitor(child, referencedName!) : +- visitor; +- + if (isPrivateIdentifier(propertyName) && shouldTransformClassElementToWeakMap(property as PrivateIdentifierPropertyDeclaration)) { + const privateIdentifierInfo = accessPrivateIdentifier(propertyName); + if (privateIdentifierInfo) { +@@ -2526,7 +2508,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return createPrivateInstanceFieldInitializer( + factory, + receiver, +- visitNode(property.initializer, initializerVisitor, isExpression), ++ visitNode(property.initializer, visitor, isExpression), + privateIdentifierInfo.brandCheckIdentifier + ); + } +@@ -2534,7 +2516,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return createPrivateStaticFieldInitializer( + factory, + privateIdentifierInfo.variableName, +- visitNode(property.initializer, initializerVisitor, isExpression) ++ visitNode(property.initializer, visitor, isExpression) + ); + } + } +@@ -2555,7 +2537,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + return undefined; + } + +- let initializer = visitNode(property.initializer, initializerVisitor, isExpression); ++ let initializer = visitNode(property.initializer, visitor, isExpression); + if (isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && isIdentifier(propertyName)) { + // A parameter-property declaration always overrides the initializer. The only time a parameter-property + // declaration *should* have an initializer is when decorators have added initializers that need to run before +@@ -2666,10 +2648,10 @@ export function transformClassFields(context: TransformationContext): (x: Source + * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations + * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator) + */ +- function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean, captureReferencedName: boolean): Expression | undefined { ++ function getPropertyNameExpressionIfNeeded(name: PropertyName, shouldHoist: boolean): Expression | undefined { + if (isComputedPropertyName(name)) { + const cacheAssignment = findComputedPropertyNameCacheAssignment(name); +- let expression = visitNode(name.expression, visitor, isExpression); ++ const expression = visitNode(name.expression, visitor, isExpression); + const innerExpression = skipPartiallyEmittedExpressions(expression); + const inlinable = isSimpleInlineableExpression(innerExpression); + const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); +@@ -2681,9 +2663,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + else { + hoistVariableDeclaration(generatedName); + } +- if (captureReferencedName) { +- expression = emitHelpers().createPropKeyHelper(expression); +- } + return factory.createAssignment(generatedName, expression); + } + return (inlinable || isIdentifier(innerExpression)) ? undefined : expression; +@@ -3024,10 +3003,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const left = visitDestructuringAssignmentTarget(node.left); +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right) as AssignmentExpression; ++ node = transformNamedEvaluation(context, node); + } + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { + const left = visitDestructuringAssignmentTarget(node.left); +@@ -3092,9 +3068,7 @@ export function transformClassFields(context: TransformationContext): (x: Source + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); +- const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateShorthandPropertyAssignment(node, node.name, objectAssignmentInitializer); ++ node = transformNamedEvaluation(context, node); + } + + return visitEachChild(node, visitor, context); +@@ -3240,9 +3214,6 @@ export function transformClassFields(context: TransformationContext): (x: Source + lexicalEnvironment?.data && + !noSubstitution.has(node)) { + const { facts, classConstructor, classThis } = lexicalEnvironment.data; +- if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { +- return factory.createParenthesizedExpression(factory.createVoidZero()); +- } + const substituteThis = shouldSubstituteThisWithClassThis ? classThis ?? classConstructor : classConstructor; + if (substituteThis) { + return setTextRange( +@@ -3253,6 +3224,9 @@ export function transformClassFields(context: TransformationContext): (x: Source + node + ); + } ++ if (facts & ClassFacts.ClassWasDecorated && legacyDecorators) { ++ return factory.createParenthesizedExpression(factory.createVoidZero()); ++ } + } + return node; + } +diff --git a/src/compiler/transformers/classThis.ts b/src/compiler/transformers/classThis.ts +new file mode 100644 +index 000000000..b03cd6814 +--- /dev/null ++++ b/src/compiler/transformers/classThis.ts +@@ -0,0 +1,148 @@ ++import { ++ AssignmentExpression, ++ Block, ++ ClassLikeDeclaration, ++ ClassStaticBlockDeclaration, ++ EqualsToken, ++ ExpressionStatement, ++ getOrCreateEmitNode, ++ Identifier, ++ isAssignmentExpression, ++ isClassDeclaration, ++ isClassStaticBlockDeclaration, ++ isExpressionStatement, ++ isIdentifier, ++ Node, ++ NodeArray, ++ NodeFactory, ++ setSourceMapRange, ++ setTextRange, ++ some, ++ Statement, ++ SyntaxKind, ++ ThisExpression ++} from "../_namespaces/ts"; ++ ++/** ++ * Creates a class `static {}` block used to assign the static `this` to a `_classThis` (or similar) variable. ++ * ++ * @param classThis The identifier to use for the captured static `this` reference, usually with the name `_classThis`. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function createClassThisAssignmentBlock(factory: NodeFactory, classThis: Identifier, thisExpression = factory.createThis()): ClassThisAssignmentBlock { ++ // produces: ++ // ++ // static { _classThis = this; } ++ // ++ ++ const expression = factory.createAssignment(classThis, thisExpression); ++ const statement = factory.createExpressionStatement(expression); ++ const body = factory.createBlock([statement], /*multiLine*/ false); ++ const block = factory.createClassStaticBlockDeclaration(body); ++ ++ // We use `emitNode.classThis` to indicate this is a `_classThis` assignment helper block ++ // and to stash the variable used for `_classThis`. ++ getOrCreateEmitNode(block).classThis = classThis; ++ ++ return block as ClassThisAssignmentBlock; ++} ++ ++/** @internal */ ++export type ClassThisAssignmentBlock = ClassStaticBlockDeclaration & { ++ readonly body: Block & { ++ readonly statements: NodeArray & readonly [ ++ ExpressionStatement & { ++ readonly expression: AssignmentExpression & { ++ readonly left: Identifier; ++ readonly right: ThisExpression; ++ }; ++ } ++ ]; ++ }; ++}; ++ ++/** ++ * Gets whether a node is a `static {}` block containing only a single assignment of the static `this` to the `_classThis` ++ * (or similar) variable stored in the `classthis` property of the block's `EmitNode`. ++ * @internal ++ */ ++export function isClassThisAssignmentBlock(node: Node): node is ClassThisAssignmentBlock { ++ if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { ++ return false; ++ } ++ ++ const statement = node.body.statements[0]; ++ return isExpressionStatement(statement) && ++ isAssignmentExpression(statement.expression, /*excludeCompoundAssignment*/ true) && ++ isIdentifier(statement.expression.left) && ++ node.emitNode?.classThis === statement.expression.left && ++ statement.expression.right.kind === SyntaxKind.ThisKeyword; ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a `static {}` block containing only a single assignment to a ++ * `_classThis` (or similar) variable. ++ * @internal ++ */ ++export function classHasClassThisAssignment(node: ClassLikeDeclaration) { ++ return !!node.emitNode?.classThis && some(node.members, isClassThisAssignmentBlock); ++} ++ ++/** ++ * Injects a class `static {}` block containing only an assignment of the static `this` to a `_classThis` (or similar) ++ * variable. ++ * ++ * @param classThis The identifier to use for the captured static `this` reference, usually with the name `_classThis`. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, ++ classThis: Identifier, thisExpression?: ThisExpression): Extract>; ++export function injectClassThisAssignmentIfMissing(factory: NodeFactory, node: T, ++ classThis: Identifier, thisExpression?: ThisExpression) { ++ ++ // given: ++ // ++ // class C { ++ // } ++ // ++ // produces: ++ // ++ // class C { ++ // static { _classThis = this; } ++ // } ++ ++ if (classHasClassThisAssignment(node)) { ++ return node; ++ } ++ ++ const staticBlock = createClassThisAssignmentBlock(factory, classThis, thisExpression); ++ if (node.name) { ++ setSourceMapRange(staticBlock.body.statements[0], node.name); ++ } ++ ++ const members = factory.createNodeArray([staticBlock, ...node.members]); ++ setTextRange(members, node.members); ++ ++ const updatedNode = isClassDeclaration(node) ? ++ factory.updateClassDeclaration( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members) : ++ factory.updateClassExpression( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members); ++ ++ getOrCreateEmitNode(updatedNode).classThis = classThis; ++ return updatedNode; ++} +diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts +index 4be05fd79..e94128e8e 100644 +--- a/src/compiler/transformers/declarations.ts ++++ b/src/compiler/transformers/declarations.ts +@@ -150,7 +150,9 @@ import { + isTypeParameterDeclaration, + isTypeQueryNode, + isUnparsedSource, ++ isVarAwaitUsing, + isVariableDeclaration, ++ isVarUsing, + last, + LateBoundDeclaration, + LateVisibilityPaintedStatement, +@@ -217,6 +219,7 @@ import { + unescapeLeadingUnderscores, + UnparsedSource, + VariableDeclaration, ++ VariableDeclarationList, + VariableStatement, + visitArray, + visitEachChild, +@@ -1763,7 +1766,19 @@ export function transformDeclarations(context: TransformationContext) { + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; + const nodes = visitNodes(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); + if (!length(nodes)) return; +- return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes)); ++ ++ const modifiers = factory.createNodeArray(ensureModifiers(input)); ++ let declList: VariableDeclarationList; ++ if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { ++ declList = factory.createVariableDeclarationList(nodes, NodeFlags.Const); ++ setOriginalNode(declList, input.declarationList); ++ setTextRange(declList, input.declarationList); ++ setCommentRange(declList, input.declarationList); ++ } ++ else { ++ declList = factory.updateVariableDeclarationList(input.declarationList, nodes); ++ } ++ return factory.updateVariableStatement(input, modifiers, declList); + } + + function recreateBindingPattern(d: BindingPattern): VariableDeclaration[] { +diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts +index a6e9222b4..5e2b895a2 100644 +--- a/src/compiler/transformers/es2015.ts ++++ b/src/compiler/transformers/es2015.ts +@@ -39,11 +39,12 @@ import { + elementAt, + EmitFlags, + EmitHint, +- emptyArray, ++ every, + Expression, + ExpressionStatement, + ExpressionWithTypeArguments, + filter, ++ findSuperStatementIndexPath, + first, + firstOrUndefined, + flatten, +@@ -112,11 +113,13 @@ import { + isIterationStatement, + isLabeledStatement, + isModifier, ++ isNumericLiteral, + isObjectLiteralElementLike, ++ isObjectLiteralExpression, + isOmittedExpression, + isPackedArrayLiteral, + isPrivateIdentifier, +- isPrologueDirective, ++ isPropertyAssignment, + isPropertyDeclaration, + isPropertyName, + isReturnStatement, +@@ -129,6 +132,7 @@ import { + isVariableDeclaration, + isVariableDeclarationList, + isVariableStatement, ++ isVoidExpression, + isWithStatement, + IterationStatement, + LabeledStatement, +@@ -186,7 +190,6 @@ import { + SwitchStatement, + SyntaxKind, + TaggedTemplateExpression, +- takeWhile, + TemplateExpression, + TextRange, + TokenFlags, +@@ -205,7 +208,7 @@ import { + VisitResult, + VoidExpression, + WhileStatement, +- YieldExpression, ++ YieldExpression + } from "../_namespaces/ts"; + + const enum ES2015SubstitutionFlags { +@@ -1188,6 +1191,190 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + return block; + } + ++ function transformConstructorBodyWorker( ++ prologueOut: Statement[], ++ statementsOut: Statement[], ++ statementsIn: NodeArray, ++ statementOffset: number, ++ superPath: readonly number[], ++ superPathDepth: number, ++ constructor: ConstructorDeclaration & { body: FunctionBody }, ++ isDerivedClass: boolean, ++ hasSynthesizedSuper: boolean, ++ isFirstStatement: boolean, ++ ): boolean { ++ let mayReplaceThis = false; ++ ++ const superStatementIndex = superPathDepth < superPath.length ? superPath[superPathDepth] : -1; ++ const leadingStatementsEnd = superStatementIndex >= 0 ? superStatementIndex : statementsIn.length; ++ ++ // find the index of the first statement material to evaluation ++ if (isFirstStatement && superStatementIndex >= 0) { ++ let firstMaterialIndex = statementOffset; ++ while (isFirstStatement && firstMaterialIndex < superStatementIndex) { ++ const statement = constructor.body.statements[firstMaterialIndex]; ++ if (!isUninitializedVariableStatement(statement) && !isUsingDeclarationStateVariableStatement(statement)) break; ++ firstMaterialIndex++; ++ } ++ ++ isFirstStatement = superStatementIndex === firstMaterialIndex; ++ } ++ ++ // visit everything prior to the statement containing `super()`. ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, leadingStatementsEnd - statementOffset)); ++ ++ const superStatement = superStatementIndex >= 0 ? statementsIn[superStatementIndex] : undefined; ++ if (superStatement && isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ mayReplaceThis = transformConstructorBodyWorker( ++ prologueOut, ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ constructor, ++ isDerivedClass, ++ hasSynthesizedSuper, ++ isFirstStatement); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ const superCall = superStatement && getSuperCallFromStatement(superStatement); ++ let superCallExpression: Expression | undefined; ++ if (hasSynthesizedSuper) { ++ superCallExpression = createDefaultSuperCallOrThis(); ++ hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; ++ } ++ else if (superCall) { ++ superCallExpression = visitSuperCallInBody(superCall); ++ hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; ++ } ++ ++ if (isDerivedClass || superCallExpression) { ++ if (superCallExpression && ++ superStatementIndex === statementsIn.length - 1 && ++ !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) { ++ // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the ++ // following representation: ++ // ++ // ``` ++ // // es2015 (source) ++ // class C extends Base { ++ // constructor() { ++ // super("foo"); ++ // } ++ // } ++ // ++ // // es5 (transformed) ++ // var C = (function (_super) { ++ // function C() { ++ // return _super.call(this, "foo") || this; ++ // } ++ // return C; ++ // })(Base); ++ // ``` ++ ++ const superCall = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); ++ const returnStatement = factory.createReturnStatement(superCallExpression); ++ setCommentRange(returnStatement, getCommentRange(superCall)); ++ setEmitFlags(superCall, EmitFlags.NoComments); ++ statementsOut.push(returnStatement); ++ return false; ++ } ++ else { ++ // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: ++ // ++ // ``` ++ // // es2015 (source) ++ // class C extends Base { ++ // constructor() { ++ // super("foo"); ++ // this.x = 1; ++ // } ++ // } ++ // ++ // // es5 (transformed) ++ // var C = (function (_super) { ++ // function C() { ++ // var _this = _super.call(this, "foo") || this; ++ // _this.x = 1; ++ // return _this; ++ // } ++ // return C; ++ // })(Base); ++ // ``` ++ ++ // If the super() call is the first statement, we can directly create and assign its result to `_this` ++ if (isFirstStatement) { ++ insertCaptureThisForNode(statementsOut, constructor, superCallExpression || createActualThis()); ++ } ++ // Since the `super()` call isn't the first statement, it's split across 1-2 statements: ++ // * A prologue `var _this = this;`, in case the constructor accesses this before super() ++ // * If it exists, a reassignment to that `_this` of the super() call ++ else { ++ insertCaptureThisForNode(prologueOut, constructor, createActualThis()); ++ if (superCallExpression) { ++ addSuperThisCaptureThisForNode(statementsOut, superCallExpression); ++ } ++ } ++ ++ mayReplaceThis = true; ++ } ++ } ++ else { ++ // If a class is not derived from a base class or does not have a call to `super()`, `this` is only ++ // captured when necessitated by an arrow function capturing the lexical `this`: ++ // ++ // ``` ++ // // es2015 ++ // class C {} ++ // ++ // // es5 ++ // var C = (function () { ++ // function C() { ++ // } ++ // return C; ++ // })(); ++ // ``` ++ insertCaptureThisForNodeIfNeeded(prologueOut, constructor); ++ } ++ } ++ ++ // visit everything following the statement containing `super()`. ++ if (superStatementIndex >= 0) { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ ++ return mayReplaceThis; ++ } ++ ++ function isUninitializedVariableStatement(node: Statement) { ++ return isVariableStatement(node) && every(node.declarationList.declarations, decl => isIdentifier(decl.name) && !decl.initializer); ++ } ++ ++ function isUsingDeclarationStateVariableStatement(node: Statement) { ++ if (!isVariableStatement(node) || node.declarationList.declarations.length !== 1) return false; ++ const varDecl = node.declarationList.declarations[0]; ++ if (!isIdentifier(varDecl.name) || !varDecl.initializer) return false; ++ const initializer = varDecl.initializer; ++ if (!isObjectLiteralExpression(initializer) || initializer.properties.length !== 3) return false; ++ const [stackProp, errorProp, hasErrorProp] = initializer.properties; ++ if (!isPropertyAssignment(stackProp) || !isIdentifier(stackProp.name) || idText(stackProp.name) !== "stack" || !isArrayLiteralExpression(stackProp.initializer)) return false; ++ if (!isPropertyAssignment(errorProp) || !isIdentifier(errorProp.name) || idText(errorProp.name) !== "error" || !isVoidExpression(errorProp.initializer) || !isNumericLiteral(errorProp.initializer.expression)) return false; ++ if (!isPropertyAssignment(hasErrorProp) || !isIdentifier(hasErrorProp.name) || idText(hasErrorProp.name) !== "hasError" || hasErrorProp.initializer.kind !== SyntaxKind.FalseKeyword) return false; ++ return true; ++ } ++ + /** + * Transforms the body of a constructor declaration of a class. + * +@@ -1226,134 +1413,40 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + + // In derived classes, there may be code before the necessary super() call + // We'll remove pre-super statements to be tacked on after the rest of the body +- const existingPrologue = takeWhile(constructor.body.statements, isPrologueDirective); +- const { superCall, superStatementIndex } = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue); +- const postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1; +- +- // If a super call has already been synthesized, +- // we're going to assume that we should just transform everything after that. +- // The assumption is that no prior step in the pipeline has added any prologue directives. +- let statementOffset = postSuperStatementsStart; +- if (!hasSynthesizedSuper) statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false); +- if (!hasSynthesizedSuper) statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ undefined); +- +- // If there already exists a call to `super()`, visit the statement directly +- let superCallExpression: Expression | undefined; +- if (hasSynthesizedSuper) { +- superCallExpression = createDefaultSuperCallOrThis(); +- } +- else if (superCall) { +- superCallExpression = visitSuperCallInBody(superCall); +- } +- +- if (superCallExpression) { ++ const standardPrologueEnd = factory.copyStandardPrologue(constructor.body.statements, prologue, /*statementOffset*/ 0); ++ const superStatementIndices = findSuperStatementIndexPath(constructor.body.statements, standardPrologueEnd); ++ if (hasSynthesizedSuper || superStatementIndices.length > 0) { + hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper; + } + ++ const mayReplaceThis = transformConstructorBodyWorker( ++ prologue, ++ statements, ++ constructor.body.statements, ++ standardPrologueEnd, ++ superStatementIndices, ++ /*superPathDepth*/ 0, ++ constructor, ++ isDerivedClass, ++ hasSynthesizedSuper, ++ /*isFirstStatement*/ true // NOTE: this will be recalculated inside of transformConstructorBodyWorker ++ ); ++ + // Add parameter defaults at the beginning of the output, with prologue statements + addDefaultValueAssignmentsIfNeeded(prologue, constructor); + addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); +- +- // visit the remaining statements +- addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset)); +- ++ insertCaptureNewTargetIfNeeded(prologue, constructor); + factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); +- insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); + +- if (isDerivedClass || superCallExpression) { +- if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) { +- // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the +- // following representation: +- // +- // ``` +- // // es2015 (source) +- // class C extends Base { +- // constructor() { +- // super("foo"); +- // } +- // } +- // +- // // es5 (transformed) +- // var C = (function (_super) { +- // function C() { +- // return _super.call(this, "foo") || this; +- // } +- // return C; +- // })(Base); +- // ``` +- const superCall = cast(cast(superCallExpression, isBinaryExpression).left, isCallExpression); +- const returnStatement = factory.createReturnStatement(superCallExpression); +- setCommentRange(returnStatement, getCommentRange(superCall)); +- setEmitFlags(superCall, EmitFlags.NoComments); +- statements.push(returnStatement); +- } +- else { +- // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor: +- // +- // ``` +- // // es2015 (source) +- // class C extends Base { +- // constructor() { +- // super("foo"); +- // this.x = 1; +- // } +- // } +- // +- // // es5 (transformed) +- // var C = (function (_super) { +- // function C() { +- // var _this = _super.call(this, "foo") || this; +- // _this.x = 1; +- // return _this; +- // } +- // return C; +- // })(Base); +- // ``` +- +- // If the super() call is the first statement, we can directly create and assign its result to `_this` +- if (superStatementIndex <= existingPrologue.length) { +- insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); +- } +- // Since the `super()` call isn't the first statement, it's split across 1-2 statements: +- // * A prologue `var _this = this;`, in case the constructor accesses this before super() +- // * If it exists, a reassignment to that `_this` of the super() call +- else { +- insertCaptureThisForNode(prologue, constructor, createActualThis()); +- if (superCallExpression) { +- insertSuperThisCaptureThisForNode(statements, superCallExpression); +- } +- } +- +- if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { +- statements.push(factory.createReturnStatement(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel))); +- } +- } +- } +- else { +- // If a class is not derived from a base class or does not have a call to `super()`, `this` is only +- // captured when necessitated by an arrow function capturing the lexical `this`: +- // +- // ``` +- // // es2015 +- // class C {} +- // +- // // es5 +- // var C = (function () { +- // function C() { +- // } +- // return C; +- // })(); +- // ``` +- insertCaptureThisForNodeIfNeeded(prologue, constructor); ++ if (mayReplaceThis && !isSufficientlyCoveredByReturnStatements(constructor.body)) { ++ statements.push(factory.createReturnStatement(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel))); + } + + const body = factory.createBlock( + setTextRange( + factory.createNodeArray( + [ +- ...existingPrologue, + ...prologue, +- ...(superStatementIndex <= existingPrologue.length ? emptyArray : visitNodes(constructor.body.statements, visitor, isStatement, existingPrologue.length, superStatementIndex - existingPrologue.length)), + ...statements + ] + ), +@@ -1366,24 +1459,6 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + return body; + } + +- function findSuperCallAndStatementIndex(originalBodyStatements: NodeArray, existingPrologue: Statement[]) { +- for (let i = existingPrologue.length; i < originalBodyStatements.length; i += 1) { +- const superCall = getSuperCallFromStatement(originalBodyStatements[i]); +- if (superCall) { +- // With a super() call, split the statements into pre-super() and 'body' (post-super()) +- return { +- superCall, +- superStatementIndex: i, +- }; +- } +- } +- +- // Since there was no super() call found, consider all statements to be in the main 'body' (post-super()) +- return { +- superStatementIndex: -1, +- }; +- } +- + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier +@@ -1758,7 +1833,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + * @param statements Statements in the constructor body. + * @param superExpression Existing `super()` call for the constructor. + */ +- function insertSuperThisCaptureThisForNode(statements: Statement[], superExpression: Expression): void { ++ function addSuperThisCaptureThisForNode(statements: Statement[], superExpression: Expression): void { + enableSubstitutionsForCapturedThis(); + const assignSuperExpression = factory.createExpressionStatement( + factory.createBinaryExpression( +@@ -1767,7 +1842,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + superExpression + ) + ); +- insertStatementAfterCustomPrologue(statements, assignSuperExpression); ++ statements.push(assignSuperExpression); + setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent); + } + +@@ -1789,7 +1864,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + insertStatementAfterCustomPrologue(statements, captureThisStatement); + } + +- function insertCaptureNewTargetIfNeeded(statements: Statement[], node: FunctionLikeDeclaration, copyOnWrite: boolean): Statement[] { ++ function insertCaptureNewTargetIfNeeded(statements: Statement[], node: FunctionLikeDeclaration): Statement[] { + if (hierarchyFacts & HierarchyFacts.NewTarget) { + let newTarget: Expression; + switch (node.kind) { +@@ -1853,11 +1928,6 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + ); + + setEmitFlags(captureNewTargetStatement, EmitFlags.NoComments | EmitFlags.CustomPrologue); +- +- if (copyOnWrite) { +- statements = statements.slice(); +- } +- + insertStatementAfterCustomPrologue(statements, captureNewTargetStatement); + } + +@@ -2232,7 +2302,7 @@ export function transformES2015(context: TransformationContext): (x: SourceFile + } + + factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); +- insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false); ++ insertCaptureNewTargetIfNeeded(prologue, node); + insertCaptureThisForNodeIfNeeded(prologue, node); + + // If we added any final generated statements, this must be a multi-line block +diff --git a/src/compiler/transformers/esDecorators.ts b/src/compiler/transformers/esDecorators.ts +index cdb69e629..d68dda028 100644 +--- a/src/compiler/transformers/esDecorators.ts ++++ b/src/compiler/transformers/esDecorators.ts +@@ -18,6 +18,7 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasDeclaredOrExplicitlyAssignedName, + ClassLikeDeclaration, + classOrConstructorParameterIsDecorated, + ClassStaticBlockDeclaration, +@@ -36,7 +37,7 @@ import { + Expression, + ExpressionStatement, + findComputedPropertyNameCacheAssignment, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + firstOrUndefined, + forEachEntry, + ForStatement, +@@ -46,11 +47,9 @@ import { + getAllDecoratorsOfClassElement, + getCommentRange, + getEffectiveBaseTypeNode, +- getEmitScriptTarget, + getFirstConstructorWithBody, + getHeritageClause, + getNonAssignmentOperatorForCompoundAssignment, +- getOrCreateEmitNode, + getOriginalNode, + getSourceMapRange, + hasAccessorModifier, +@@ -60,6 +59,8 @@ import { + HeritageClause, + Identifier, + idText, ++ injectClassNamedEvaluationHelperBlockIfMissing, ++ injectClassThisAssignmentIfMissing, + InternalEmitFlags, + isAmbientPropertyDeclaration, + isArrayBindingOrAssignmentElement, +@@ -70,15 +71,18 @@ import { + isAutoAccessorPropertyDeclaration, + isBindingName, + isBlock, ++ isCatchClause, + isClassElement, + isClassExpression, + isClassLike, ++ isClassNamedEvaluationHelperBlock, + isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, + isCompoundAssignment, + isComputedPropertyName, + isDestructuringAssignment, + isElementAccessExpression, +- isEmptyStringLiteral, ++ isExportModifier, + isExpression, + isForInitializer, + isFunctionExpression, +@@ -118,6 +122,7 @@ import { + isStringLiteral, + isSuperProperty, + isTemplateLiteral, ++ isTryStatement, + LeftHandSideExpression, + map, + MethodDeclaration, +@@ -156,6 +161,7 @@ import { + setSourceMapRange, + setTextRange, + ShorthandPropertyAssignment, ++ singleOrMany, + skipOuterExpressions, + skipParentheses, + some, +@@ -168,6 +174,7 @@ import { + ThisExpression, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, + tryCast, + VariableDeclaration, + visitCommaListElements, +@@ -177,6 +184,7 @@ import { + visitNodes, + Visitor, + VisitResult, ++ WrappedExpression + } from "../_namespaces/ts"; + + // Class/Decorator evaluation order, as it pertains to this transformer: +@@ -280,9 +288,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + hoistVariableDeclaration, + } = context; + +- const compilerOptions = context.getCompilerOptions(); +- const languageVersion = getEmitScriptTarget(compilerOptions); +- + let top: LexicalEnvironmentStackEntry | undefined; + let classInfo: ClassInfo | undefined; + let classThis: Identifier | undefined; +@@ -412,7 +417,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.ClassDeclaration: + return visitClassDeclaration(node as ClassDeclaration); + case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, /*referencedName*/ undefined); ++ return visitClassExpression(node as ClassExpression); + case SyntaxKind.Constructor: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.ClassStaticBlockDeclaration: +@@ -440,9 +445,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ false); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false); + case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, /*referencedName*/ undefined); ++ return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false); + case SyntaxKind.CallExpression: + return visitCallExpression(node as CallExpression); + case SyntaxKind.TaggedTemplateExpression: +@@ -510,19 +515,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + +- function namedEvaluationVisitor(node: Node, referencedName: Expression): VisitResult { +- switch (node.kind) { +- case SyntaxKind.PartiallyEmittedExpression: +- return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ false, referencedName); +- case SyntaxKind.ClassExpression: +- return visitClassExpression(node as ClassExpression, referencedName); +- default: +- return visitor(node); +- } +- } +- + function discardedValueVisitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.PrefixUnaryExpression: +@@ -533,7 +525,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + case SyntaxKind.CommaListExpression: + return visitCommaListExpression(node as CommaListExpression, /*discarded*/ true); + case SyntaxKind.ParenthesizedExpression: +- return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true, /*referencedName*/ undefined); ++ return visitParenthesizedExpression(node as ParenthesizedExpression, /*discarded*/ true); + default: + return visitor(node); + } +@@ -583,14 +575,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + for (const member of node.members) { + if (isNamedClassElement(member) && nodeOrChildIsDecorated(/*useLegacyDecorators*/ false, member, node)) { + if (hasStaticModifier(member)) { +- staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + } + else { +- instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + } + } + if (isClassStaticBlockDeclaration(member)) { +- hasStaticInitializers = true; ++ if (!isClassNamedEvaluationHelperBlock(member)) { ++ hasStaticInitializers = true; ++ } + } + else if (isPropertyDeclaration(member)) { + if (hasStaticModifier(member)) { +@@ -637,9 +631,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + return false; + } + +- function transformClassLike(node: ClassLikeDeclaration, className: Expression) { ++ function transformClassLike(node: ClassLikeDeclaration) { + startLexicalEnvironment(); + ++ // When a class has class decorators we end up transforming it into a statement that would otherwise give it an ++ // assigned name. If the class doesn't have an assigned name, we'll give it an assigned name of `""`) ++ if (!classHasDeclaredOrExplicitlyAssignedName(node) && classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, node)) { ++ node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, factory.createStringLiteral("")); ++ } ++ + const classReference = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false, /*ignoreAssignedName*/ true); + const classInfo = createClassInfo(node); + const classDefinitionStatements: Statement[] = []; +@@ -658,10 +658,15 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // of the mutated class. + // - Since a class decorator can add extra initializers, we must define a variable to keep track of + // extra initializers. +- classInfo.classDecoratorsName = factory.createUniqueName("_classDecorators", GeneratedIdentifierFlags.Optimistic); +- classInfo.classDescriptorName = factory.createUniqueName("_classDescriptor", GeneratedIdentifierFlags.Optimistic); +- classInfo.classExtraInitializersName = factory.createUniqueName("_classExtraInitializers", GeneratedIdentifierFlags.Optimistic); +- classInfo.classThis = factory.createUniqueName("_classThis", GeneratedIdentifierFlags.Optimistic); ++ classInfo.classDecoratorsName = factory.createUniqueName("_classDecorators", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ classInfo.classDescriptorName = factory.createUniqueName("_classDescriptor", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ classInfo.classExtraInitializersName = factory.createUniqueName("_classExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); ++ // We do not mark _classThis as FileLevel if it may be reused by class private fields, which requires the ++ // ability access the captured `_classThis` of outer scopes. ++ const needsUniqueClassThis = some(node.members, member => (isPrivateIdentifierClassElementDeclaration(member) || isAutoAccessorPropertyDeclaration(member)) && hasStaticModifier(member)); ++ classInfo.classThis = factory.createUniqueName("_classThis", needsUniqueClassThis ? ++ GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.ReservedInNestedScopes : ++ GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + classDefinitionStatements.push( + createLet(classInfo.classDecoratorsName, factory.createArrayLiteralExpression(classDecorators)), + createLet(classInfo.classDescriptorName), +@@ -681,7 +686,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + const extendsElement = extendsClause && firstOrUndefined(extendsClause.types); + const extendsExpression = extendsElement && visitNode(extendsElement.expression, visitor, isExpression); + if (extendsExpression) { +- classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic); ++ classInfo.classSuper = factory.createUniqueName("_classSuper", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + + // Ensure we do not give the class or function an assigned name due to the variable by prefixing it + // with `0, `. +@@ -707,15 +712,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + // 3. The name of the class is assigned. + // +- // If the class did not have a name, set the assigned name as if from NamedEvaluation. +- // We don't need to use the assigned name if it consists of the empty string and the transformed class +- // expression won't get its name from any other source (such as the variable we create to handle +- // class decorators) +- const needsSetNameHelper = !getOriginalNode(node, isClassLike)?.name && (classDecorators || !isStringLiteral(className) || !isEmptyStringLiteral(className)); +- if (needsSetNameHelper) { +- const setNameExpr = emitHelpers().createSetFunctionNameHelper(factory.createThis(), className); +- leadingBlockStatements = append(leadingBlockStatements, factory.createExpressionStatement(setNameExpr)); +- } ++ // If the class did not have a name, the caller should have performed injectClassNamedEvaluationHelperBlockIfMissing ++ // prior to calling this function if a name was needed. + + // 4. For each member: + // a. Member Decorators are evaluated +@@ -841,11 +839,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (classInfo.classDescriptorName && classInfo.classDecoratorsName && classInfo.classExtraInitializersName && classInfo.classThis) { + leadingBlockStatements ??= []; + ++ // produces: + // __esDecorate(null, _classDescriptor = { value: this }, _classDecorators, { kind: "class", name: this.name }, _classExtraInitializers); +- const valueProperty = factory.createPropertyAssignment("value", factory.createThis()); ++ const valueProperty = factory.createPropertyAssignment("value", renamedClassThis); + const classDescriptor = factory.createObjectLiteralExpression([valueProperty]); + const classDescriptorAssignment = factory.createAssignment(classInfo.classDescriptorName, classDescriptor); +- const classNameReference = factory.createPropertyAccessExpression(factory.createThis(), "name"); ++ const classNameReference = factory.createPropertyAccessExpression(renamedClassThis, "name"); + const esDecorateHelper = emitHelpers().createESDecorateHelper( + factory.createNull(), + classDescriptorAssignment, +@@ -858,6 +857,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + setSourceMapRange(esDecorateStatement, moveRangePastDecorators(node)); + leadingBlockStatements.push(esDecorateStatement); + ++ // produces: + // C = _classThis = _classDescriptor.value; + const classDescriptorValueReference = factory.createPropertyAccessExpression(classInfo.classDescriptorName, "value"); + const classThisAssignment = factory.createAssignment(classInfo.classThis, classDescriptorValueReference); +@@ -889,43 +889,60 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + trailingBlockStatements = undefined; + } + +- let newMembers: readonly ClassElement[] = members; ++ // prepare a leading `static {}` block, if necessary ++ // ++ // produces: ++ // class C { ++ // static { ... } ++ // ... ++ // } ++ const leadingStaticBlock = leadingBlockStatements && ++ factory.createClassStaticBlockDeclaration(factory.createBlock(leadingBlockStatements, /*multiLine*/ true)); + +- // insert a leading `static {}` block, if necessary +- if (leadingBlockStatements) { +- // class C { +- // static { ... } +- // ... +- // } +- const leadingStaticBlockBody = factory.createBlock(leadingBlockStatements, /*multiLine*/ true); +- const leadingStaticBlock = factory.createClassStaticBlockDeclaration(leadingStaticBlockBody); +- if (shouldTransformPrivateStaticElementsInClass) { +- // We use `InternalEmitFlags.TransformPrivateStaticElements` as a marker on a class static block +- // to inform the classFields transform that it shouldn't rename `this` to `_classThis` in the +- // transformed class static block. +- setInternalEmitFlags(leadingStaticBlock, InternalEmitFlags.TransformPrivateStaticElements); +- } +- newMembers = [leadingStaticBlock, ...newMembers]; ++ if (leadingStaticBlock && shouldTransformPrivateStaticElementsInClass) { ++ // We use `InternalEmitFlags.TransformPrivateStaticElements` as a marker on a class static block ++ // to inform the classFields transform that it shouldn't rename `this` to `_classThis` in the ++ // transformed class static block. ++ setInternalEmitFlags(leadingStaticBlock, InternalEmitFlags.TransformPrivateStaticElements); + } + +- // append the synthetic constructor, if necessary +- if (syntheticConstructor) { +- newMembers = [...newMembers, syntheticConstructor]; +- } ++ // prepare a trailing `static {}` block, if necessary ++ // ++ // produces: ++ // class C { ++ // ... ++ // static { ... } ++ // } ++ const trailingStaticBlock = trailingBlockStatements && ++ factory.createClassStaticBlockDeclaration(factory.createBlock(trailingBlockStatements, /*multiLine*/ true)); + +- // append a trailing `static {}` block, if necessary +- if (trailingBlockStatements) { +- // class C { +- // ... +- // static { ... } +- // } +- const trailingStaticBlockBody = factory.createBlock(trailingBlockStatements, /*multiLine*/ true); +- const trailingStaticBlock = factory.createClassStaticBlockDeclaration(trailingStaticBlockBody); +- newMembers = [...newMembers, trailingStaticBlock]; +- } ++ if (leadingStaticBlock || syntheticConstructor || trailingStaticBlock) { ++ const newMembers: ClassElement[] = []; ++ ++ // add the NamedEvaluation helper block, if needed ++ const existingNamedEvaluationHelperBlockIndex = members.findIndex(isClassNamedEvaluationHelperBlock); ++ ++ // add the leading `static {}` block ++ if (leadingStaticBlock) { ++ // add the `static {}` block after any existing NamedEvaluation helper block, if one exists. ++ addRange(newMembers, members, 0, existingNamedEvaluationHelperBlockIndex + 1); ++ newMembers.push(leadingStaticBlock); ++ addRange(newMembers, members, existingNamedEvaluationHelperBlockIndex + 1); ++ } ++ else { ++ addRange(newMembers, members); ++ } ++ ++ // append the synthetic constructor, if necessary ++ if (syntheticConstructor) { ++ newMembers.push(syntheticConstructor); ++ } ++ ++ // append a trailing `static {}` block, if necessary ++ if (trailingStaticBlock) { ++ newMembers.push(trailingStaticBlock); ++ } + +- // Update members with newly added members. +- if (newMembers !== members) { + members = setTextRange(factory.createNodeArray(newMembers), members); + } + +@@ -935,6 +952,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // We use `var` instead of `let` so we can leverage NamedEvaluation to define the class name + // and still be able to ensure it is initialized prior to any use in `static {}`. + ++ // produces: + // (() => { + // let _classDecorators = [...]; + // let _classDescriptor; +@@ -955,6 +973,10 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // })(); + + classExpression = factory.createClassExpression(/*modifiers*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, heritageClauses, members); ++ if (classInfo.classThis) { ++ classExpression = injectClassThisAssignmentIfMissing(factory, classExpression, classInfo.classThis); ++ } ++ + const classReferenceDeclaration = factory.createVariableDeclaration(classReference, /*exclamationToken*/ undefined, /*type*/ undefined, classExpression); + const classReferenceVarDeclList = factory.createVariableDeclarationList([classReferenceDeclaration]); + const returnExpr = classInfo.classThis ? factory.createAssignment(classReference, classInfo.classThis) : classReference; +@@ -964,6 +986,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + ); + } + else { ++ // produces: + // return ; + classExpression = factory.createClassExpression(/*modifiers*/ undefined, node.name, /*typeParameters*/ undefined, heritageClauses, members); + classDefinitionStatements.push(factory.createReturnStatement(classExpression)); +@@ -979,7 +1002,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + + setOriginalNode(classExpression, node); +- getOrCreateEmitNode(classExpression).classThis = classInfo.classThis; + return factory.createImmediatelyInvokedArrowFunction(factory.mergeLexicalEnvironment(classDefinitionStatements, lexicalEnvironment)); + } + +@@ -990,37 +1012,64 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitClassDeclaration(node: ClassDeclaration): VisitResult { + if (isDecoratedClassLike(node)) { +- if (hasSyntacticModifier(node, ModifierFlags.Export) && +- hasSyntacticModifier(node, ModifierFlags.Default)) { +- // export default (() => { ... })(); +- const originalClass = getOriginalNode(node, isClassLike) ?? node; +- const className = originalClass.name ? factory.createStringLiteralFromNode(originalClass.name) : factory.createStringLiteral("default"); +- const iife = transformClassLike(node, className); +- const statement = factory.createExportDefault(iife); +- setOriginalNode(statement, node); +- setCommentRange(statement, getCommentRange(node)); +- setSourceMapRange(statement, moveRangePastDecorators(node)); +- return statement; ++ const statements: Statement[] = []; ++ const originalClass = getOriginalNode(node, isClassLike) ?? node; ++ const className = originalClass.name ? factory.createStringLiteralFromNode(originalClass.name) : factory.createStringLiteral("default"); ++ const isExport = hasSyntacticModifier(node, ModifierFlags.Export); ++ const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); ++ if (!node.name) { ++ node = injectClassNamedEvaluationHelperBlockIfMissing(context, node, className); ++ } ++ if (isExport && isDefault) { ++ const iife = transformClassLike(node); ++ if (node.name) { ++ // let C = (() => { ... })(); ++ // export default C; ++ const varDecl = factory.createVariableDeclaration(factory.getLocalName(node), /*exclamationToken*/ undefined, /*type*/ undefined, iife); ++ setOriginalNode(varDecl, node); ++ ++ const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); ++ const varStatement = factory.createVariableStatement(/*modifiers*/ undefined, varDecls); ++ statements.push(varStatement); ++ ++ const exportStatement = factory.createExportDefault(factory.getDeclarationName(node)); ++ setOriginalNode(exportStatement, node); ++ setCommentRange(exportStatement, getCommentRange(node)); ++ setSourceMapRange(exportStatement, moveRangePastDecorators(node)); ++ statements.push(exportStatement); ++ } ++ else { ++ // export default (() => { ... })(); ++ const exportStatement = factory.createExportDefault(iife); ++ setOriginalNode(exportStatement, node); ++ setCommentRange(exportStatement, getCommentRange(node)); ++ setSourceMapRange(exportStatement, moveRangePastDecorators(node)); ++ statements.push(exportStatement); ++ } + } + else { + // let C = (() => { ... })(); + Debug.assertIsDefined(node.name, "A class declaration that is not a default export must have a name."); +- const iife = transformClassLike(node, factory.createStringLiteralFromNode(node.name)); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- // When we transform to ES5/3 this will be moved inside an IIFE and should reference the name +- // without any block-scoped variable collision handling +- const declName = languageVersion <= ScriptTarget.ES2015 ? +- factory.getInternalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true) : +- factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); ++ const iife = transformClassLike(node); ++ const modifierVisitorNoExport = isExport ? ((node: ModifierLike) => isExportModifier(node) ? undefined : modifierVisitor(node)) : modifierVisitor; ++ const modifiers = visitNodes(node.modifiers, modifierVisitorNoExport, isModifier); ++ const declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true); + const varDecl = factory.createVariableDeclaration(declName, /*exclamationToken*/ undefined, /*type*/ undefined, iife); + setOriginalNode(varDecl, node); + + const varDecls = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); +- const statement = factory.createVariableStatement(modifiers, varDecls); +- setOriginalNode(statement, node); +- setCommentRange(statement, getCommentRange(node)); +- return statement; ++ const varStatement = factory.createVariableStatement(modifiers, varDecls); ++ setOriginalNode(varStatement, node); ++ setCommentRange(varStatement, getCommentRange(node)); ++ statements.push(varStatement); ++ if (isExport) { ++ // export { C }; ++ const exportStatement = factory.createExternalModuleExport(declName); ++ setOriginalNode(exportStatement, node); ++ statements.push(exportStatement); ++ } + } ++ return singleOrMany(statements); + } + else { + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +@@ -1032,10 +1081,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + +- function visitClassExpression(node: ClassExpression, referencedName: Expression | undefined) { ++ function visitClassExpression(node: ClassExpression) { + if (isDecoratedClassLike(node)) { +- const className = node.name ? factory.createStringLiteralFromNode(node.name) : referencedName ?? factory.createStringLiteral(""); +- const iife = transformClassLike(node, className); ++ const iife = transformClassLike(node); + setOriginalNode(iife, node); + return iife; + } +@@ -1072,6 +1120,37 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + } + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[]) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ addRange(statementsOut, initializerStatements); ++ } ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ + function visitConstructorDeclaration(node: ConstructorDeclaration) { + enterClassElement(node); + const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +@@ -1084,11 +1163,9 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (initializerStatements) { + const statements: Statement[] = []; + const nonPrologueStart = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor); +- const superStatementIndex = findSuperStatementIndex(node.body.statements, nonPrologueStart); +- if (superStatementIndex >= 0) { +- addRange(statements, visitNodes(node.body.statements, visitor, isStatement, nonPrologueStart, superStatementIndex + 1 - nonPrologueStart)); +- addRange(statements, initializerStatements); +- addRange(statements, visitNodes(node.body.statements, visitor, isStatement, superStatementIndex + 1)); ++ const superStatementIndices = findSuperStatementIndexPath(node.body.statements, nonPrologueStart); ++ if (superStatementIndices.length > 0) { ++ transformConstructorBodyWorker(statements, node.body.statements, nonPrologueStart, superStatementIndices, 0, initializerStatements); + } + else { + addRange(statements, initializerStatements); +@@ -1119,7 +1196,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + TNode extends MethodDeclaration | PropertyDeclaration | GetAccessorDeclaration | SetAccessorDeclaration, + >( + member: TNode, +- useNamedEvaluation: boolean, + classInfo: ClassInfo | undefined, + createDescriptor?: (node: TNode & { readonly name: PrivateIdentifier }, modifiers: ModifiersArray | undefined) => Expression + ) { +@@ -1131,12 +1207,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + if (!classInfo) { + const modifiers = visitNodes(member.modifiers, modifierVisitor, isModifier); + enterName(); +- if (useNamedEvaluation) { +- ({ referencedName, name } = visitReferencedPropertyName(member.name)); +- } +- else { +- name = visitPropertyName(member.name); +- } ++ name = visitPropertyName(member.name); + exitName(); + return { modifiers, referencedName, name, initializersName, descriptorName, thisArg }; + } +@@ -1215,8 +1286,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + }; + + const extraInitializers = isStatic(member) ? +- classInfo.staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic) : +- classInfo.instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic); ++ classInfo.staticExtraInitializersName ??= factory.createUniqueName("_staticExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel) : ++ classInfo.instanceExtraInitializersName ??= factory.createUniqueName("_instanceExtraInitializers", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel); + + if (isMethodOrAccessor(member)) { + // __esDecorate(this, null, _static_member_decorators, { kind: "method", name: "...", static: true, private: false, access: { ... } }, _staticExtraInitializers); +@@ -1278,12 +1349,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + if (name === undefined) { + enterName(); +- if (useNamedEvaluation) { +- ({ referencedName, name } = visitReferencedPropertyName(member.name)); +- } +- else { +- name = visitPropertyName(member.name); +- } ++ name = visitPropertyName(member.name); + exitName(); + } + +@@ -1298,7 +1364,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitMethodDeclaration(node: MethodDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createMethodDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createMethodDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createMethodDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1313,7 +1379,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitGetAccessorDeclaration(node: GetAccessorDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createGetAccessorDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createGetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createGetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1328,7 +1394,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + + function visitSetAccessorDeclaration(node: SetAccessorDeclaration) { + enterClassElement(node); +- const { modifiers, name, descriptorName } = partialTransformClassElement(node, /*useNamedEvaluation*/ false, classInfo, createSetAccessorDescriptorObject); ++ const { modifiers, name, descriptorName } = partialTransformClassElement(node, classInfo, createSetAccessorDescriptorObject); + if (descriptorName) { + exitClassElement(); + return finishClassElement(createSetAccessorDescriptorForwarder(modifiers, name, descriptorName), node); +@@ -1344,14 +1410,30 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + function visitClassStaticBlockDeclaration(node: ClassStaticBlockDeclaration) { + enterClassElement(node); + +- if (classInfo) classInfo.hasStaticInitializers = true; +- const result = visitEachChild(node, visitor, context); ++ let result: ClassStaticBlockDeclaration; ++ if (isClassNamedEvaluationHelperBlock(node)) { ++ result = visitEachChild(node, visitor, context); ++ } ++ else if (isClassThisAssignmentBlock(node)) { ++ const savedClassThis = classThis; ++ classThis = undefined; ++ result = visitEachChild(node, visitor, context); ++ classThis = savedClassThis; ++ } ++ else { ++ if (classInfo) classInfo.hasStaticInitializers = true; ++ result = visitEachChild(node, visitor, context); ++ } + + exitClassElement(); + return result; + } + + function visitPropertyDeclaration(node: PropertyDeclaration) { ++ if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); ++ } ++ + enterClassElement(node); + + // TODO(rbuckton): We support decorating `declare x` fields with legacyDecorators, but we currently don't +@@ -1366,15 +1448,11 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _functionObject_.[[ClassFieldInitializerName]]. + // ... + +- const useNamedEvaluation = isNamedEvaluation(node, isAnonymousClassNeedingAssignedName); +- const { modifiers, name, referencedName, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, useNamedEvaluation, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : undefined); ++ const { modifiers, name, initializersName, descriptorName, thisArg } = partialTransformClassElement(node, classInfo, hasAccessorModifier(node) ? createAccessorPropertyDescriptorObject : undefined); + + startLexicalEnvironment(); + +- let initializer = referencedName ? +- visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression): +- visitNode(node.initializer, visitor, isExpression); +- ++ let initializer = visitNode(node.initializer, visitor, isExpression); + if (initializersName) { + initializer = emitHelpers().createRunInitializersHelper( + thisArg ?? factory.createThis(), +@@ -1542,32 +1620,20 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. + // ... + +- let updated: ParameterDeclaration; + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- updated = factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- /*dotDotDotToken*/ undefined, +- name, +- /*questionToken*/ undefined, +- /*type*/ undefined, +- initializer); +- } +- else { +- updated = factory.updateParameterDeclaration( +- node, +- /*modifiers*/ undefined, +- node.dotDotDotToken, +- visitNode(node.name, visitor, isBindingName), +- /*questionToken*/ undefined, +- /*type*/ undefined, +- visitNode(node.initializer, visitor, isExpression) +- ); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + ++ const updated = factory.updateParameterDeclaration( ++ node, ++ /*modifiers*/ undefined, ++ node.dotDotDotToken, ++ visitNode(node.name, visitor, isBindingName), ++ /*questionToken*/ undefined, ++ /*type*/ undefined, ++ visitNode(node.initializer, visitor, isExpression) ++ ); ++ + if (updated !== node) { + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. +@@ -1583,6 +1649,16 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + return isClassExpression(node) && !node.name && isDecoratedClassLike(node); + } + ++ function canIgnoreEmptyStringLiteralInAssignedName(node: WrappedExpression) { ++ // The IIFE produced for `(@dec class {})` will result in an assigned name of the form ++ // `var class_1 = class { };`, and thus the empty string cannot be ignored. However, The IIFE ++ // produced for `(class { @dec x; })` will not result in an assigned name since it ++ // transforms to `return class { };`, and thus the empty string *can* be ignored. ++ ++ const innerExpression = skipOuterExpressions(node); ++ return isClassExpression(innerExpression) && !innerExpression.name && !classOrConstructorParameterIsDecorated(/*useLegacyDecorators*/ false, innerExpression); ++ } ++ + function visitForStatement(node: ForStatement) { + return factory.updateForStatement( + node, +@@ -1632,10 +1708,8 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- const left = visitNode(node.left, visitor, isExpression); +- const right = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBinaryExpression(node, left, node.operatorToken, right); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); ++ return visitEachChild(node, visitor, context); + } + + if (isSuperProperty(node.left) && classThis && classSuper) { +@@ -1818,9 +1892,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const { referencedName, name } = visitReferencedPropertyName(node.name); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updatePropertyAssignment(node, name, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1842,10 +1914,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateVariableDeclaration(node, name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1869,11 +1938,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.initializer); +- const propertyName = visitNode(node.propertyName, visitor, isPropertyName); +- const name = visitNode(node.name, visitor, isBindingName); +- const initializer = visitNode(node.initializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateBindingElement(node, /*dotDotDotToken*/ undefined, propertyName, name, initializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.initializer)); + } + + return visitEachChild(node, visitor, context); +@@ -1919,15 +1984,12 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { +- const assignmentTarget = visitDestructuringAssignmentTarget(node.left); +- let initializer: Expression; + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.left, node.right); +- initializer = visitNode(node.right, node => namedEvaluationVisitor(node, assignedName), isExpression); +- } +- else { +- initializer = visitNode(node.right, visitor, isExpression); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.right)); + } ++ ++ const assignmentTarget = visitDestructuringAssignmentTarget(node.left); ++ const initializer = visitNode(node.right, visitor, isExpression); + return factory.updateBinaryExpression(node, assignmentTarget, node.operatorToken, initializer) as ArrayAssignmentElement; + } + else { +@@ -1989,10 +2051,7 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // ... + + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const assignedName = getAssignedNameOfIdentifier(node.name, node.objectAssignmentInitializer); +- const name = visitNode(node.name, visitor, isIdentifier); +- const objectAssignmentInitializer = visitNode(node.objectAssignmentInitializer, node => namedEvaluationVisitor(node, assignedName), isExpression); +- return factory.updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.objectAssignmentInitializer)); + } + + return visitEachChild(node, visitor, context); +@@ -2033,40 +2092,28 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + // a. Let _value_ be ? NamedEvaluation of |AssignmentExpression| with argument `"default"`. + // ... + +- // NOTE: Since emit for `export =` translates to `module.exports = ...`, the assigned nameof the class +- // is `""`. +- + if (isNamedEvaluation(node, isAnonymousClassNeedingAssignedName)) { +- const referencedName = factory.createStringLiteral(node.isExportEquals ? "" : "default"); +- const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifier); +- const expression = visitNode(node.expression, node => namedEvaluationVisitor(node, referencedName), isExpression); +- return factory.updateExportAssignment(node, modifiers, expression); ++ node = transformNamedEvaluation(context, node, canIgnoreEmptyStringLiteralInAssignedName(node.expression)); + } + + return visitEachChild(node, visitor, context); + } + +- function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitParenthesizedExpression(node: ParenthesizedExpression, discarded: boolean) { + // 8.4.5 RS: NamedEvaluation + // ParenthesizedExpression : `(` Expression `)` + // ... + // 2. Return ? NamedEvaluation of |Expression| with argument _name_. + +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; ++ const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updateParenthesizedExpression(node, expression); + } + +- function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean, referencedName: Expression | undefined) { ++ function visitPartiallyEmittedExpression(node: PartiallyEmittedExpression, discarded: boolean) { + // Emulates 8.4.5 RS: NamedEvaluation + +- const visitorFunc: Visitor = +- discarded ? discardedValueVisitor : +- referencedName ? node => namedEvaluationVisitor(node, referencedName) : +- visitor; ++ const visitorFunc: Visitor = discarded ? discardedValueVisitor : visitor; + const expression = visitNode(node.expression, visitorFunc, isExpression); + return factory.updatePartiallyEmittedExpression(node, expression); + } +@@ -2132,7 +2179,6 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + const prefix = kind === "get" || kind === "set" ? kind : undefined; + const functionName = factory.createStringLiteralFromNode(name, /*isSingleQuote*/ undefined); + const namedFunction = emitHelpers().createSetFunctionNameHelper(func, functionName, prefix); +- + const method = factory.createPropertyAssignment(factory.createIdentifier(kind), namedFunction); + setOriginalNode(method, original); + setSourceMapRange(method, moveRangePastDecorators(original)); +@@ -2325,11 +2371,4 @@ export function transformESDecorators(context: TransformationContext): (x: Sourc + ]) + ); + } +- +- function getAssignedNameOfIdentifier(name: Identifier, initializer: Expression) { +- const originalClass = getOriginalNode(initializer, isClassLike); +- return originalClass && !originalClass.name && hasSyntacticModifier(originalClass, ModifierFlags.Default) ? +- factory.createStringLiteral("default") : +- factory.createStringLiteralFromNode(name); +- } + } +diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts +index 730958dae..d20cdd511 100644 +--- a/src/compiler/transformers/esnext.ts ++++ b/src/compiler/transformers/esnext.ts +@@ -1,33 +1,875 @@ + import { ++ addEmitHelpers, ++ addRange, ++ append, ++ arrayFrom, ++ BindingElement, ++ Block, + Bundle, ++ CaseOrDefaultClause, + chainBundle, ++ ClassDeclaration, ++ Debug, ++ EmitFlags, ++ ExportAssignment, ++ ExportSpecifier, ++ Expression, ++ ForOfStatement, ++ ForStatement, ++ GeneratedIdentifierFlags, ++ getEmitFlags, ++ hasSyntacticModifier, ++ Identifier, ++ IdentifierNameMap, ++ isArray, ++ isBindingPattern, ++ isBlock, ++ isCaseClause, ++ isCustomPrologue, ++ isExpression, ++ isGeneratedIdentifier, ++ isIdentifier, ++ isLocalName, ++ isNamedEvaluation, ++ isOmittedExpression, ++ isPrologueDirective, ++ isSourceFile, ++ isStatement, ++ isVariableDeclarationList, ++ isVariableStatement, ++ ModifierFlags, + Node, ++ NodeFlags, ++ setCommentRange, ++ setEmitFlags, ++ setOriginalNode, ++ setSourceMapRange, ++ setTextRange, ++ skipOuterExpressions, + SourceFile, ++ Statement, ++ SwitchStatement, ++ SyntaxKind, + TransformationContext, + TransformFlags, ++ transformNamedEvaluation, ++ VariableDeclaration, ++ VariableDeclarationList, ++ VariableStatement, ++ visitArray, + visitEachChild, +- VisitResult, ++ visitNode, ++ visitNodes, ++ VisitResult + } from "../_namespaces/ts"; + ++const enum UsingKind { ++ None, ++ Sync, ++ Async, ++} ++ + /** @internal */ + export function transformESNext(context: TransformationContext): (x: SourceFile | Bundle) => SourceFile | Bundle { +- return chainBundle(context, transformSourceFile); +- +- function transformSourceFile(node: SourceFile) { +- if (node.isDeclarationFile) { +- return node; +- } +- +- return visitEachChild(node, visitor, context); +- } +- +- function visitor(node: Node): VisitResult { +- if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { +- return node; +- } +- switch (node.kind) { +- default: +- return visitEachChild(node, visitor, context); +- } +- } ++ const { ++ factory, ++ getEmitHelperFactory: emitHelpers, ++ hoistVariableDeclaration, ++ startLexicalEnvironment, ++ endLexicalEnvironment, ++ } = context; ++ ++ let exportBindings: IdentifierNameMap; ++ let exportVars: VariableDeclaration[]; ++ let defaultExportBinding: Identifier | undefined; ++ let exportEqualsBinding: Identifier | undefined; ++ ++ return chainBundle(context, transformSourceFile); ++ ++ function transformSourceFile(node: SourceFile) { ++ if (node.isDeclarationFile) { ++ return node; ++ } ++ ++ const visited = visitNode(node, visitor, isSourceFile); ++ addEmitHelpers(visited, context.readEmitHelpers()); ++ exportVars = undefined!; ++ exportBindings = undefined!; ++ defaultExportBinding = undefined; ++ return visited; ++ } ++ ++ function visitor(node: Node): VisitResult { ++ if ((node.transformFlags & TransformFlags.ContainsESNext) === 0) { ++ return node; ++ } ++ ++ switch (node.kind) { ++ case SyntaxKind.SourceFile: ++ return visitSourceFile(node as SourceFile); ++ ++ case SyntaxKind.Block: ++ return visitBlock(node as Block); ++ ++ case SyntaxKind.ForStatement: ++ return visitForStatement(node as ForStatement); ++ ++ case SyntaxKind.ForOfStatement: ++ return visitForOfStatement(node as ForOfStatement); ++ ++ case SyntaxKind.SwitchStatement: ++ return visitSwitchStatement(node as SwitchStatement); ++ ++ default: ++ return visitEachChild(node, visitor, context); ++ } ++ } ++ ++ function visitSourceFile(node: SourceFile): SourceFile { ++ const usingKind = getUsingKindOfStatements(node.statements); ++ if (usingKind) { ++ // Imports and exports must stay at the top level. This means we must hoist all imports, exports, and ++ // top-level function declarations and bindings out of the `try` statements we generate. For example: ++ // ++ // given: ++ // ++ // import { w } from "mod"; ++ // const x = expr1; ++ // using y = expr2; ++ // const z = expr3; ++ // export function f() { ++ // console.log(z); ++ // } ++ // ++ // produces: ++ // ++ // import { x } from "mod"; // <-- preserved ++ // const x = expr1; // <-- preserved ++ // var y, z; // <-- hoisted ++ // export function f() { // <-- hoisted ++ // console.log(z); ++ // } ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // try { ++ // y = __addDisposableResource(env_1, expr2, false); ++ // z = expr3; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResource(env_1); ++ // } ++ // ++ // In this transformation, we hoist `y`, `z`, and `f` to a new outer statement list while moving all other ++ // statements in the source file into the `try` block, which is the same approach we use for System module ++ // emit. Unlike System module emit, we attempt to preserve all statements prior to the first top-level ++ // `using` to isolate the complexity of the transformed output to only where it is necessary. ++ startLexicalEnvironment(); ++ ++ exportBindings = new IdentifierNameMap(); ++ exportVars = []; ++ ++ const prologueCount = countPrologueStatements(node.statements); ++ const topLevelStatements: Statement[] = []; ++ addRange(topLevelStatements, visitArray(node.statements, visitor, isStatement, 0, prologueCount)); ++ ++ // Collect and transform any leading statements up to the first `using` or `await using`. This preserves ++ // the original statement order much as is possible. ++ let pos = prologueCount; ++ while (pos < node.statements.length) { ++ const statement = node.statements[pos]; ++ if (getUsingKind(statement) !== UsingKind.None) { ++ if (pos > prologueCount) { ++ addRange(topLevelStatements, visitNodes(node.statements, visitor, isStatement, prologueCount, pos - prologueCount)); ++ } ++ break; ++ } ++ pos++; ++ } ++ ++ Debug.assert(pos < node.statements.length, "Should have encountered at least one 'using' statement."); ++ ++ // transform the rest of the body ++ const envBinding = createEnvBinding(); ++ const bodyStatements = transformUsingDeclarations(node.statements, pos, node.statements.length, envBinding, topLevelStatements); ++ ++ // add `export {}` declarations for any hoisted bindings. ++ if (exportBindings.size) { ++ append(topLevelStatements, factory.createExportDeclaration( ++ /*modifiers*/ undefined, ++ /*isTypeOnly*/ false, ++ factory.createNamedExports(arrayFrom(exportBindings.values())) ++ )); ++ } ++ ++ addRange(topLevelStatements, endLexicalEnvironment()); ++ if (exportVars.length) { ++ topLevelStatements.push(factory.createVariableStatement( ++ factory.createModifiersFromModifierFlags(ModifierFlags.Export), ++ factory.createVariableDeclarationList( ++ exportVars, ++ NodeFlags.Let ++ ) ++ )); ++ } ++ addRange(topLevelStatements, createDownlevelUsingStatements(bodyStatements, envBinding, usingKind === UsingKind.Async)); ++ ++ if (exportEqualsBinding) { ++ topLevelStatements.push(factory.createExportAssignment( ++ /*modifiers*/ undefined, ++ /*isExportEquals*/ true, ++ exportEqualsBinding ++ )); ++ } ++ ++ return factory.updateSourceFile(node, topLevelStatements); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitBlock(node: Block): VisitResult { ++ const usingKind = getUsingKindOfStatements(node.statements); ++ if (usingKind) { ++ const prologueCount = countPrologueStatements(node.statements); ++ const envBinding = createEnvBinding(); ++ return factory.updateBlock( ++ node, ++ [ ++ ...visitArray(node.statements, visitor, isStatement, 0, prologueCount), ++ ...createDownlevelUsingStatements( ++ transformUsingDeclarations(node.statements, prologueCount, node.statements.length, envBinding, /*topLevelStatements*/ undefined), ++ envBinding, ++ usingKind === UsingKind.Async, ++ ) ++ ] ++ ); ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitForStatement(node: ForStatement): VisitResult { ++ if (node.initializer && isUsingVariableDeclarationList(node.initializer)) { ++ // given: ++ // ++ // for (using x = expr; cond; incr) { ... } ++ // ++ // produces a shallow transformation to: ++ // ++ // { ++ // using x = expr; ++ // for (; cond; incr) { ... } ++ // } ++ // ++ // before handing the shallow transformation back to the visitor for an in-depth transformation. ++ return visitNode( ++ factory.createBlock([ ++ factory.createVariableStatement(/*modifiers*/ undefined, node.initializer), ++ factory.updateForStatement( ++ node, ++ /*initializer*/ undefined, ++ node.condition, ++ node.incrementor, ++ node.statement ++ ) ++ ]), ++ visitor, ++ isStatement ++ ); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitForOfStatement(node: ForOfStatement) { ++ if (isUsingVariableDeclarationList(node.initializer)) { ++ // given: ++ // ++ // for (using x of y) { ... } ++ // ++ // produces a shallow transformation to: ++ // ++ // for (const x_1 of y) { ++ // using x = x; ++ // ... ++ // } ++ // ++ // before handing the shallow transformation back to the visitor for an in-depth transformation. ++ const forInitializer = node.initializer; ++ Debug.assertNode(forInitializer, isUsingVariableDeclarationList); ++ Debug.assert(forInitializer.declarations.length === 1, "ForInitializer may only have one declaration"); ++ ++ const forDecl = forInitializer.declarations[0]; ++ Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); ++ ++ const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === UsingKind.Async; ++ const temp = factory.getGeneratedNameForNode(forDecl.name); ++ const usingVar = factory.updateVariableDeclaration(forDecl, forDecl.name, /*exclamationToken*/ undefined, /*type*/ undefined, temp); ++ const usingVarList = factory.createVariableDeclarationList([usingVar], isAwaitUsing ? NodeFlags.AwaitUsing : NodeFlags.Using); ++ const usingVarStatement = factory.createVariableStatement(/*modifiers*/ undefined, usingVarList); ++ return visitNode( ++ factory.updateForOfStatement( ++ node, ++ node.awaitModifier, ++ factory.createVariableDeclarationList([ ++ factory.createVariableDeclaration(temp) ++ ], NodeFlags.Const), ++ node.expression, ++ isBlock(node.statement) ? ++ factory.updateBlock(node.statement, [ ++ usingVarStatement, ++ ...node.statement.statements ++ ]) : ++ factory.createBlock([ ++ usingVarStatement, ++ node.statement ++ ], /*multiLine*/ true) ++ ), ++ visitor, ++ isStatement ++ ); ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitCaseOrDefaultClause(node: CaseOrDefaultClause, envBinding: Identifier) { ++ if (getUsingKindOfStatements(node.statements) !== UsingKind.None) { ++ if (isCaseClause(node)) { ++ return factory.updateCaseClause( ++ node, ++ visitNode(node.expression, visitor, isExpression), ++ transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) ++ ); ++ } ++ else { ++ return factory.updateDefaultClause( ++ node, ++ transformUsingDeclarations(node.statements, /*start*/ 0, node.statements.length, envBinding, /*topLevelStatements*/ undefined) ++ ); ++ } ++ } ++ return visitEachChild(node, visitor, context); ++ } ++ ++ function visitSwitchStatement(node: SwitchStatement) { ++ // given: ++ // ++ // switch (expr) { ++ // case expr: ++ // using res = expr; ++ // } ++ // ++ // produces: ++ // ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // try { ++ // switch(expr) { ++ // case expr: ++ // const res = __addDisposableResource(env_1, expr, false); ++ // } ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ const usingKind = getUsingKindOfCaseOrDefaultClauses(node.caseBlock.clauses); ++ if (usingKind) { ++ const envBinding = createEnvBinding(); ++ return createDownlevelUsingStatements( ++ [ ++ factory.updateSwitchStatement( ++ node, ++ visitNode(node.expression, visitor, isExpression), ++ factory.updateCaseBlock( ++ node.caseBlock, ++ node.caseBlock.clauses.map(clause => visitCaseOrDefaultClause(clause, envBinding)) ++ ) ++ ) ++ ], ++ envBinding, ++ usingKind === UsingKind.Async, ++ ); ++ } ++ ++ return visitEachChild(node, visitor, context); ++ } ++ ++ /** ++ * Transform `using` declarations in a statement list. ++ */ ++ function transformUsingDeclarations(statementsIn: readonly Statement[], start: number, end: number, envBinding: Identifier, topLevelStatements: Statement[] | undefined) { ++ const statements: Statement[] = []; ++ ++ for (let i = start; i < end; i++) { ++ const statement = statementsIn[i]; ++ const usingKind = getUsingKind(statement); ++ if (usingKind) { ++ Debug.assertNode(statement, isVariableStatement); ++ const declarations: VariableDeclaration[] = []; ++ for (let declaration of statement.declarationList.declarations) { ++ if (!isIdentifier(declaration.name)) { ++ // Since binding patterns are a grammar error, we reset `declarations` so we don't process this as a `using`. ++ declarations.length = 0; ++ break; ++ } ++ ++ // perform a shallow transform for any named evaluation ++ if (isNamedEvaluation(declaration)) { ++ declaration = transformNamedEvaluation(context, declaration); ++ } ++ ++ const initializer = visitNode(declaration.initializer, visitor, isExpression) ?? factory.createVoidZero(); ++ declarations.push(factory.updateVariableDeclaration( ++ declaration, ++ declaration.name, ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ emitHelpers().createAddDisposableResourceHelper( ++ envBinding, ++ initializer, ++ usingKind === UsingKind.Async ++ ) ++ )); ++ } ++ ++ // Only replace the statement if it was valid. ++ if (declarations.length) { ++ const varList = factory.createVariableDeclarationList(declarations, NodeFlags.Const); ++ setOriginalNode(varList, statement.declarationList); ++ setTextRange(varList, statement.declarationList); ++ hoistOrAppendNode(factory.updateVariableStatement(statement, /*modifiers*/ undefined, varList)); ++ continue; ++ } ++ } ++ ++ const result = visitor(statement); ++ if (isArray(result)) { ++ result.forEach(hoistOrAppendNode); ++ } ++ else if (result) { ++ hoistOrAppendNode(result); ++ } ++ } ++ ++ return statements; ++ ++ function hoistOrAppendNode(node: Node) { ++ Debug.assertNode(node, isStatement); ++ append(statements, hoist(node)); ++ } ++ ++ function hoist(node: Statement) { ++ if (!topLevelStatements) return node; ++ ++ switch (node.kind) { ++ case SyntaxKind.ImportDeclaration: ++ case SyntaxKind.ImportEqualsDeclaration: ++ case SyntaxKind.ExportDeclaration: ++ case SyntaxKind.FunctionDeclaration: ++ return hoistImportOrExportOrHoistedDeclaration(node, topLevelStatements); ++ case SyntaxKind.ExportAssignment: ++ return hoistExportAssignment(node as ExportAssignment); ++ case SyntaxKind.ClassDeclaration: ++ return hoistClassDeclaration(node as ClassDeclaration); ++ case SyntaxKind.VariableStatement: ++ return hoistVariableStatement(node as VariableStatement); ++ } ++ ++ return node; ++ } ++ } ++ ++ function hoistImportOrExportOrHoistedDeclaration(node: Statement, topLevelStatements: Statement[]) { ++ // NOTE: `node` has already been visited ++ topLevelStatements.push(node); ++ return undefined; ++ } ++ ++ function hoistExportAssignment(node: ExportAssignment) { ++ return node.isExportEquals ? hoistExportEquals(node) : hoistExportDefault(node); ++ } ++ ++ function hoistExportDefault(node: ExportAssignment) { ++ // NOTE: `node` has already been visited ++ if (defaultExportBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ // given: ++ // ++ // export default expr; ++ // ++ // produces: ++ // ++ // // top level ++ // var default_1; ++ // export { default_1 as default }; ++ // ++ // // body ++ // default_1 = expr; ++ ++ defaultExportBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); ++ ++ // give a class or function expression an assigned name, if needed. ++ let expression = node.expression; ++ let innerExpression = skipOuterExpressions(expression); ++ if (isNamedEvaluation(innerExpression)) { ++ innerExpression = transformNamedEvaluation(context, innerExpression, /*ignoreEmptyStringLiteral*/ false, "default"); ++ expression = factory.restoreOuterExpressions(expression, innerExpression); ++ } ++ ++ const assignment = factory.createAssignment(defaultExportBinding, expression); ++ return factory.createExpressionStatement(assignment); ++ } ++ ++ function hoistExportEquals(node: ExportAssignment) { ++ // NOTE: `node` has already been visited ++ if (exportEqualsBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ // given: ++ // ++ // export = expr; ++ // ++ // produces: ++ // ++ // // top level ++ // var default_1; ++ // ++ // try { ++ // // body ++ // default_1 = expr; ++ // } ... ++ // ++ // // top level suffix ++ // export = default_1; ++ ++ exportEqualsBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistVariableDeclaration(exportEqualsBinding); ++ ++ // give a class or function expression an assigned name, if needed. ++ const assignment = factory.createAssignment(exportEqualsBinding, node.expression); ++ return factory.createExpressionStatement(assignment); ++ } ++ ++ function hoistClassDeclaration(node: ClassDeclaration) { ++ // NOTE: `node` has already been visited ++ if (!node.name && defaultExportBinding) { ++ // invalid case of multiple `export default` declarations. Don't assert here, just pass it through ++ return node; ++ } ++ ++ const isExported = hasSyntacticModifier(node, ModifierFlags.Export); ++ const isDefault = hasSyntacticModifier(node, ModifierFlags.Default); ++ ++ // When hoisting a class declaration at the top level of a file containing a top-level `using` statement, we ++ // must first convert it to a class expression so that we can hoist the binding outside of the `try`. ++ let expression: Expression = factory.converters.convertToClassExpression(node); ++ if (node.name) { ++ // given: ++ // ++ // using x = expr; ++ // class C {} ++ // ++ // produces: ++ // ++ // var x, C; ++ // const env_1 = { ... }; ++ // try { ++ // x = __addDisposableResource(env_1, expr, false); ++ // C = class {}; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ // If the class is exported, we also produce an `export { C };` ++ hoistBindingIdentifier(factory.getLocalName(node), isExported && !isDefault, /*exportAlias*/ undefined, node); ++ expression = factory.createAssignment(factory.getDeclarationName(node), expression); ++ if (isNamedEvaluation(expression)) { ++ expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false); ++ } ++ setOriginalNode(expression, node); ++ setSourceMapRange(expression, node); ++ setCommentRange(expression, node); ++ } ++ ++ if (isDefault && !defaultExportBinding) { ++ // In the case of a default export, we create a temporary variable that we export as the default and then ++ // assign to that variable. ++ // ++ // given: ++ // ++ // using x = expr; ++ // export default class C {} ++ // ++ // produces: ++ // ++ // export { default_1 as default }; ++ // var x, C, default_1; ++ // const env_1 = { ... }; ++ // try { ++ // x = __addDisposableResource(env_1, expr, false); ++ // default_1 = C = class {}; ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ // ++ // Though we will never reassign `default_1`, this most closely matches the specified runtime semantics. ++ defaultExportBinding = factory.createUniqueName("_default", GeneratedIdentifierFlags.ReservedInNestedScopes | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.Optimistic); ++ hoistBindingIdentifier(defaultExportBinding, /*isExport*/ true, "default", node); ++ expression = factory.createAssignment(defaultExportBinding, expression); ++ if (isNamedEvaluation(expression)) { ++ expression = transformNamedEvaluation(context, expression, /*ignoreEmptyStringLiteral*/ false, "default"); ++ } ++ setOriginalNode(expression, node); ++ } ++ ++ return factory.createExpressionStatement(expression); ++ } ++ ++ function hoistVariableStatement(node: VariableStatement) { ++ // NOTE: `node` has already been visited ++ let expressions: Expression[] | undefined; ++ const isExported = hasSyntacticModifier(node, ModifierFlags.Export); ++ for (const variable of node.declarationList.declarations) { ++ hoistBindingElement(variable, isExported, variable); ++ if (variable.initializer) { ++ expressions = append(expressions, hoistInitializedVariable(variable)); ++ } ++ } ++ if (expressions) { ++ const statement = factory.createExpressionStatement(factory.inlineExpressions(expressions)); ++ setOriginalNode(statement, node); ++ setCommentRange(statement, node); ++ setSourceMapRange(statement, node); ++ return statement; ++ } ++ return undefined; ++ } ++ ++ function hoistInitializedVariable(node: VariableDeclaration) { ++ // NOTE: `node` has already been visited ++ Debug.assertIsDefined(node.initializer); ++ let target: Expression; ++ if (isIdentifier(node.name)) { ++ target = factory.cloneNode(node.name); ++ setEmitFlags(target, getEmitFlags(target) & ~(EmitFlags.LocalName | EmitFlags.ExportName | EmitFlags.InternalName)); ++ } ++ else { ++ target = factory.converters.convertToAssignmentPattern(node.name); ++ } ++ ++ const assignment = factory.createAssignment(target, node.initializer); ++ setOriginalNode(assignment, node); ++ setCommentRange(assignment, node); ++ setSourceMapRange(assignment, node); ++ return assignment; ++ } ++ ++ function hoistBindingElement(node: VariableDeclaration | BindingElement, isExportedDeclaration: boolean, original: Node | undefined) { ++ // NOTE: `node` has already been visited ++ if (isBindingPattern(node.name)) { ++ for (const element of node.name.elements) { ++ if (!isOmittedExpression(element)) { ++ hoistBindingElement(element, isExportedDeclaration, original); ++ } ++ } ++ } ++ else { ++ hoistBindingIdentifier(node.name, isExportedDeclaration, /*exportAlias*/ undefined, original); ++ } ++ } ++ ++ function hoistBindingIdentifier(node: Identifier, isExport: boolean, exportAlias: string | Identifier | undefined, original: Node | undefined) { ++ // NOTE: `node` has already been visited ++ const name = isGeneratedIdentifier(node) ? node : factory.cloneNode(node); ++ if (isExport) { ++ if (exportAlias === undefined && !isLocalName(name)) { ++ const varDecl = factory.createVariableDeclaration(name); ++ if (original) { ++ setOriginalNode(varDecl, original); ++ } ++ exportVars.push(varDecl); ++ return; ++ } ++ ++ const localName = exportAlias !== undefined ? name : undefined; ++ const exportName = exportAlias !== undefined ? exportAlias : name; ++ const specifier = factory.createExportSpecifier(/*isTypeOnly*/ false, localName, exportName); ++ if (original) { ++ setOriginalNode(specifier, original); ++ } ++ exportBindings.set(name, specifier); ++ } ++ hoistVariableDeclaration(name); ++ } ++ ++ function createEnvBinding() { ++ return factory.createUniqueName("env"); ++ } ++ ++ function createDownlevelUsingStatements(bodyStatements: readonly Statement[], envBinding: Identifier, async: boolean) { ++ const statements: Statement[] = []; ++ ++ // produces: ++ // ++ // const env_1 = { stack: [], error: void 0, hasError: false }; ++ // ++ const envObject = factory.createObjectLiteralExpression([ ++ factory.createPropertyAssignment("stack", factory.createArrayLiteralExpression()), ++ factory.createPropertyAssignment("error", factory.createVoidZero()), ++ factory.createPropertyAssignment("hasError", factory.createFalse()) ++ ]); ++ const envVar = factory.createVariableDeclaration(envBinding, /*exclamationToken*/ undefined, /*type*/ undefined, envObject); ++ const envVarList = factory.createVariableDeclarationList([envVar], NodeFlags.Const); ++ const envVarStatement = factory.createVariableStatement(/*modifiers*/ undefined, envVarList); ++ statements.push(envVarStatement); ++ ++ // when `async` is `false`, produces: ++ // ++ // try { ++ // ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // __disposeResources(env_1); ++ // } ++ ++ // when `async` is `true`, produces: ++ // ++ // try { ++ // ++ // } ++ // catch (e_1) { ++ // env_1.error = e_1; ++ // env_1.hasError = true; ++ // } ++ // finally { ++ // const result_1 = __disposeResources(env_1); ++ // if (result_1) { ++ // await result_1; ++ // } ++ // } ++ ++ // Unfortunately, it is necessary to use two properties to indicate an error because `throw undefined` is legal ++ // JavaScript. ++ const tryBlock = factory.createBlock(bodyStatements, /*multiLine*/ true); ++ const bodyCatchBinding = factory.createUniqueName("e"); ++ const catchClause = factory.createCatchClause( ++ bodyCatchBinding, ++ factory.createBlock([ ++ factory.createExpressionStatement( ++ factory.createAssignment( ++ factory.createPropertyAccessExpression(envBinding, "error"), ++ bodyCatchBinding) ++ ), ++ factory.createExpressionStatement( ++ factory.createAssignment( ++ factory.createPropertyAccessExpression(envBinding, "hasError"), ++ factory.createTrue()) ++ ), ++ ], /*multiLine*/ true) ++ ); ++ ++ let finallyBlock: Block; ++ if (async) { ++ const result = factory.createUniqueName("result"); ++ finallyBlock = factory.createBlock([ ++ factory.createVariableStatement( ++ /*modifiers*/ undefined, ++ factory.createVariableDeclarationList([ ++ factory.createVariableDeclaration( ++ result, ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ emitHelpers().createDisposeResourcesHelper(envBinding) ++ ) ++ ], NodeFlags.Const) ++ ), ++ factory.createIfStatement(result, factory.createExpressionStatement(factory.createAwaitExpression(result))) ++ ], /*multiLine*/ true); ++ } ++ else { ++ finallyBlock = factory.createBlock([ ++ factory.createExpressionStatement( ++ emitHelpers().createDisposeResourcesHelper(envBinding) ++ ) ++ ], /*multiLine*/ true); ++ } ++ ++ const tryStatement = factory.createTryStatement(tryBlock, catchClause, finallyBlock); ++ statements.push(tryStatement); ++ ++ return statements; ++ } ++} ++ ++function countPrologueStatements(statements: readonly Statement[]) { ++ for (let i = 0; i < statements.length; i++) { ++ if (!isPrologueDirective(statements[i]) && !isCustomPrologue(statements[i])) { ++ return i; ++ } ++ } ++ return 0; ++} ++ ++function isUsingVariableDeclarationList(node: Node): node is VariableDeclarationList & { _usingBrand: any } { ++ return isVariableDeclarationList(node) && getUsingKindOfVariableDeclarationList(node) !== UsingKind.None; ++} ++ ++function getUsingKindOfVariableDeclarationList(node: VariableDeclarationList) { ++ return (node.flags & NodeFlags.BlockScoped) === NodeFlags.AwaitUsing ? UsingKind.Async : ++ (node.flags & NodeFlags.BlockScoped) === NodeFlags.Using ? UsingKind.Sync : ++ UsingKind.None; ++} ++ ++function getUsingKindOfVariableStatement(node: VariableStatement) { ++ return getUsingKindOfVariableDeclarationList(node.declarationList); ++} ++ ++function getUsingKind(statement: Statement): UsingKind { ++ return isVariableStatement(statement) ? getUsingKindOfVariableStatement(statement) : UsingKind.None; ++} ++ ++function getUsingKindOfStatements(statements: readonly Statement[]): UsingKind { ++ let result = UsingKind.None; ++ for (const statement of statements) { ++ const usingKind = getUsingKind(statement); ++ if (usingKind === UsingKind.Async) return UsingKind.Async; ++ if (usingKind > result) result = usingKind; ++ } ++ return result; ++} ++ ++function getUsingKindOfCaseOrDefaultClauses(clauses: readonly CaseOrDefaultClause[]): UsingKind { ++ let result = UsingKind.None; ++ for (const clause of clauses) { ++ const usingKind = getUsingKindOfStatements(clause.statements); ++ if (usingKind === UsingKind.Async) return UsingKind.Async; ++ if (usingKind > result) result = usingKind; ++ } ++ return result; + } +diff --git a/src/compiler/transformers/legacyDecorators.ts b/src/compiler/transformers/legacyDecorators.ts +index f175fe71a..87b3b162c 100644 +--- a/src/compiler/transformers/legacyDecorators.ts ++++ b/src/compiler/transformers/legacyDecorators.ts +@@ -55,7 +55,6 @@ import { + isStatic, + map, + MethodDeclaration, +- Modifier, + ModifierFlags, + moveRangePastModifiers, + Node, +@@ -373,39 +372,29 @@ export function transformLegacyDecorators(context: TransformationContext): (x: S + + // let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference + // or decoratedClassAlias if the class contain self-reference. +- const varDecl = factory.createVariableDeclaration( +- declName, +- /*exclamationToken*/ undefined, +- /*type*/ undefined, +- classAlias && !assignClassAliasInStaticBlock ? factory.createAssignment(classAlias, classExpression) : classExpression +- ); ++ const varInitializer = classAlias && !assignClassAliasInStaticBlock ? factory.createAssignment(classAlias, classExpression) : classExpression; ++ const varDecl = factory.createVariableDeclaration(declName, /*exclamationToken*/ undefined, /*type*/ undefined, varInitializer); + setOriginalNode(varDecl, node); + +- let varModifiers: Modifier[] | undefined; +- if (isExport && !isDefault) { +- varModifiers = factory.createModifiersFromModifierFlags(ModifierFlags.Export); +- } ++ const varDeclList = factory.createVariableDeclarationList([varDecl], NodeFlags.Let); ++ const varStatement = factory.createVariableStatement(/*modifiers*/ undefined, varDeclList); ++ setOriginalNode(varStatement, node); ++ setTextRange(varStatement, location); ++ setCommentRange(varStatement, node); + +- const statement = factory.createVariableStatement( +- varModifiers, +- factory.createVariableDeclarationList([ +- varDecl +- ], NodeFlags.Let) +- ); +- setOriginalNode(statement, node); +- setTextRange(statement, location); +- setCommentRange(statement, node); +- +- const statements: Statement[] = [statement]; ++ const statements: Statement[] = [varStatement]; + addRange(statements, decorationStatements); + addConstructorDecorationStatement(statements, node); + +- if (isExport && isDefault) { +- statements.push(factory.createExportAssignment( +- /*modifiers*/ undefined, +- /*isExportEquals*/ false, +- declName +- )); ++ if (isExport) { ++ if (isDefault) { ++ const exportStatement = factory.createExportDefault(declName); ++ statements.push(exportStatement); ++ } ++ else { ++ const exportStatement = factory.createExternalModuleExport(factory.getDeclarationName(node)); ++ statements.push(exportStatement); ++ } + } + + return statements; +diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts +index fc95446ce..b6339fcc1 100644 +--- a/src/compiler/transformers/module/module.ts ++++ b/src/compiler/transformers/module/module.ts +@@ -59,6 +59,7 @@ import { + hasJsonModuleEmitEnabled, + hasSyntacticModifier, + Identifier, ++ IdentifierNameMap, + idText, + IfStatement, + ImportCall, +@@ -86,6 +87,7 @@ import { + isExpression, + isExternalModule, + isExternalModuleImportEqualsDeclaration, ++ isFileLevelReservedGeneratedIdentifier, + isForInitializer, + isFunctionExpression, + isGeneratedIdentifier, +@@ -224,7 +226,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + + currentSourceFile = node; +- currentModuleInfo = collectExternalModuleInfo(context, node, resolver, compilerOptions); ++ currentModuleInfo = collectExternalModuleInfo(context, node); + moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo; + + // Perform the transformation. +@@ -668,22 +670,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile + function topLevelVisitor(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: +- return visitImportDeclaration(node as ImportDeclaration); ++ return visitTopLevelImportDeclaration(node as ImportDeclaration); + + case SyntaxKind.ImportEqualsDeclaration: +- return visitImportEqualsDeclaration(node as ImportEqualsDeclaration); ++ return visitTopLevelImportEqualsDeclaration(node as ImportEqualsDeclaration); + + case SyntaxKind.ExportDeclaration: +- return visitExportDeclaration(node as ExportDeclaration); ++ return visitTopLevelExportDeclaration(node as ExportDeclaration); + + case SyntaxKind.ExportAssignment: +- return visitExportAssignment(node as ExportAssignment); +- +- case SyntaxKind.FunctionDeclaration: +- return visitFunctionDeclaration(node as FunctionDeclaration); +- +- case SyntaxKind.ClassDeclaration: +- return visitClassDeclaration(node as ClassDeclaration); ++ return visitTopLevelExportAssignment(node as ExportAssignment); + + default: + return topLevelNestedVisitor(node); +@@ -1358,7 +1354,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitImportDeclaration(node: ImportDeclaration): VisitResult { ++ function visitTopLevelImportDeclaration(node: ImportDeclaration): VisitResult { + let statements: Statement[] | undefined; + const namespaceDeclaration = getNamespaceDeclarationNode(node); + if (moduleKind !== ModuleKind.AMD) { +@@ -1470,7 +1466,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { ++ function visitTopLevelImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { + Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); + + let statements: Statement[] | undefined; +@@ -1538,7 +1534,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param The node to visit. + */ +- function visitExportDeclaration(node: ExportDeclaration): VisitResult { ++ function visitTopLevelExportDeclaration(node: ExportDeclaration): VisitResult { + if (!node.moduleSpecifier) { + // Elide export declarations with no module specifier as they are handled + // elsewhere. +@@ -1648,7 +1644,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * + * @param node The node to visit. + */ +- function visitExportAssignment(node: ExportAssignment): VisitResult { ++ function visitTopLevelExportAssignment(node: ExportAssignment): VisitResult { + if (node.isExportEquals) { + return undefined; + } +@@ -1878,20 +1874,21 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + ++ const seen = new IdentifierNameMap(); + if (importClause.name) { +- statements = appendExportsOfDeclaration(statements, importClause); ++ statements = appendExportsOfDeclaration(statements, seen, importClause); + } + + const namedBindings = importClause.namedBindings; + if (namedBindings) { + switch (namedBindings.kind) { + case SyntaxKind.NamespaceImport: +- statements = appendExportsOfDeclaration(statements, namedBindings); ++ statements = appendExportsOfDeclaration(statements, seen, namedBindings); + break; + + case SyntaxKind.NamedImports: + for (const importBinding of namedBindings.elements) { +- statements = appendExportsOfDeclaration(statements, importBinding, /*liveBinding*/ true); ++ statements = appendExportsOfDeclaration(statements, seen, importBinding, /*liveBinding*/ true); + } + + break; +@@ -1915,7 +1912,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + +- return appendExportsOfDeclaration(statements, decl); ++ return appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + + /** +@@ -1974,7 +1971,7 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + } + else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { +- statements = appendExportsOfDeclaration(statements, decl); ++ statements = appendExportsOfDeclaration(statements, new IdentifierNameMap(), decl); + } + + return statements; +@@ -1994,13 +1991,14 @@ export function transformModule(context: TransformationContext): (x: SourceFile + return statements; + } + ++ const seen = new IdentifierNameMap(); + if (hasSyntacticModifier(decl, ModifierFlags.Export)) { + const exportName = hasSyntacticModifier(decl, ModifierFlags.Default) ? factory.createIdentifier("default") : factory.getDeclarationName(decl); +- statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl); ++ statements = appendExportStatement(statements, seen, exportName, factory.getLocalName(decl), /*location*/ decl); + } + + if (decl.name) { +- statements = appendExportsOfDeclaration(statements, decl); ++ statements = appendExportsOfDeclaration(statements, seen, decl); + } + + return statements; +@@ -2014,12 +2012,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * appended. + * @param decl The declaration to export. + */ +- function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, liveBinding?: boolean): Statement[] | undefined { ++ function appendExportsOfDeclaration(statements: Statement[] | undefined, seen: IdentifierNameMap, decl: Declaration, liveBinding?: boolean): Statement[] | undefined { + const name = factory.getDeclarationName(decl); +- const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(idText(name)); ++ const exportSpecifiers = currentModuleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { +- statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ undefined, liveBinding); ++ statements = appendExportStatement(statements, seen, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /*allowComments*/ undefined, liveBinding); + } + } + return statements; +@@ -2037,8 +2035,11 @@ export function transformModule(context: TransformationContext): (x: SourceFile + * @param location The location to use for source maps and comments for the export. + * @param allowComments Whether to allow comments on the export. + */ +- function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { +- statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); ++ function appendExportStatement(statements: Statement[] | undefined, seen: IdentifierNameMap, exportName: Identifier, expression: Expression, location?: TextRange, allowComments?: boolean, liveBinding?: boolean): Statement[] | undefined { ++ if (!seen.has(exportName)) { ++ seen.set(exportName, true); ++ statements = append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding)); ++ } + return statements; + } + +@@ -2341,12 +2342,12 @@ export function transformModule(context: TransformationContext): (x: SourceFile + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // +- // - We do not substitute generated identifiers for any reason. ++ // - We do not substitute generated identifiers unless they are file-level reserved names. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) +- && !isGeneratedIdentifier(node.left) ++ && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) + && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { +@@ -2395,6 +2396,16 @@ export function transformModule(context: TransformationContext): (x: SourceFile + } + } + } ++ else if (isFileLevelReservedGeneratedIdentifier(name)) { ++ const exportSpecifiers = currentModuleInfo?.exportSpecifiers.get(name); ++ if (exportSpecifiers) { ++ const exportedNames: Identifier[] = []; ++ for (const exportSpecifier of exportSpecifiers) { ++ exportedNames.push(exportSpecifier.name); ++ } ++ return exportedNames; ++ } ++ } + } + } + +diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts +index 4e2d9b954..b83bf5244 100644 +--- a/src/compiler/transformers/module/system.ts ++++ b/src/compiler/transformers/module/system.ts +@@ -64,6 +64,7 @@ import { + isExpression, + isExternalModule, + isExternalModuleImportEqualsDeclaration, ++ isFileLevelReservedGeneratedIdentifier, + isForInitializer, + isGeneratedIdentifier, + isHeritageClause, +@@ -84,7 +85,9 @@ import { + isSpreadElement, + isStatement, + isStringLiteral, ++ isVarAwaitUsing, + isVariableDeclarationList, ++ isVarUsing, + LabeledStatement, + map, + MetaProperty, +@@ -198,7 +201,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + // see comment to 'substitutePostfixUnaryExpression' for more details + + // Collect information about the external module and dependency groups. +- moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node, resolver, compilerOptions); ++ moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(context, node); + + // Make sure that the name of the 'exports' function does not conflict with + // existing identifiers. +@@ -845,20 +848,44 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + return visitNode(node, visitor, isStatement); + } + +- let expressions: Expression[] | undefined; +- const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export); +- for (const variable of node.declarationList.declarations) { +- if (variable.initializer) { +- expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); +- } +- else { +- hoistBindingElement(variable); ++ let statements: Statement[] | undefined; ++ // `using` and `await using` declarations cannot be hoisted directly, so we will hoist the variable name ++ // as a normal variable, and declare it as a temp variable that remains as a `using` to ensure the correct ++ // lifetime. ++ if (isVarUsing(node.declarationList) || isVarAwaitUsing(node.declarationList)) { ++ const modifiers = visitNodes(node.modifiers, modifierVisitor, isModifierLike); ++ const declarations: VariableDeclaration[] = []; ++ for (const variable of node.declarationList.declarations) { ++ declarations.push(factory.updateVariableDeclaration( ++ variable, ++ factory.getGeneratedNameForNode(variable.name), ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ transformInitializedVariable(variable, /*isExportedDeclaration*/ false) ++ )); + } ++ ++ const declarationList = factory.updateVariableDeclarationList( ++ node.declarationList, ++ declarations ++ ); ++ statements = append(statements, factory.updateVariableStatement(node, modifiers, declarationList)); + } ++ else { ++ let expressions: Expression[] | undefined; ++ const isExportedDeclaration = hasSyntacticModifier(node, ModifierFlags.Export); ++ for (const variable of node.declarationList.declarations) { ++ if (variable.initializer) { ++ expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); ++ } ++ else { ++ hoistBindingElement(variable); ++ } ++ } + +- let statements: Statement[] | undefined; +- if (expressions) { +- statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node)); ++ if (expressions) { ++ statements = append(statements, setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node)); ++ } + } + + statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false); +@@ -1114,7 +1141,7 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + } + + const name = factory.getDeclarationName(decl); +- const exportSpecifiers = moduleInfo.exportSpecifiers.get(idText(name)); ++ const exportSpecifiers = moduleInfo.exportSpecifiers.get(name); + if (exportSpecifiers) { + for (const exportSpecifier of exportSpecifiers) { + if (exportSpecifier.name.escapedText !== excludeName) { +@@ -1894,12 +1921,12 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + // When we see an assignment expression whose left-hand side is an exported symbol, + // we should ensure all exports of that symbol are updated with the correct value. + // +- // - We do not substitute generated identifiers for any reason. ++ // - We do not substitute generated identifiers unless they are file-level reserved names. + // - We do not substitute identifiers tagged with the LocalName flag. + // - We only substitute identifiers that are exported at the top level. + if (isAssignmentOperator(node.operatorToken.kind) + && isIdentifier(node.left) +- && !isGeneratedIdentifier(node.left) ++ && (!isGeneratedIdentifier(node.left) || isFileLevelReservedGeneratedIdentifier(node.left)) + && !isLocalName(node.left)) { + const exportedNames = getExports(node.left); + if (exportedNames) { +@@ -1939,6 +1966,16 @@ export function transformSystemModule(context: TransformationContext): (x: Sourc + + exportedNames = addRange(exportedNames, moduleInfo?.exportedBindings[getOriginalNodeId(valueDeclaration)]); + } ++ else if (isGeneratedIdentifier(name) && isFileLevelReservedGeneratedIdentifier(name)) { ++ const exportSpecifiers = moduleInfo?.exportSpecifiers.get(name); ++ if (exportSpecifiers) { ++ const exportedNames: Identifier[] = []; ++ for (const exportSpecifier of exportSpecifiers) { ++ exportedNames.push(exportSpecifier.name); ++ } ++ return exportedNames; ++ } ++ } + return exportedNames; + } + +diff --git a/src/compiler/transformers/namedEvaluation.ts b/src/compiler/transformers/namedEvaluation.ts +new file mode 100644 +index 000000000..5af5d9078 +--- /dev/null ++++ b/src/compiler/transformers/namedEvaluation.ts +@@ -0,0 +1,478 @@ ++import { ++ __String, ++ AnonymousFunctionDefinition, ++ BinaryExpression, ++ BindingElement, ++ Block, ++ CallExpression, ++ cast, ++ ClassLikeDeclaration, ++ ClassStaticBlockDeclaration, ++ ExportAssignment, ++ Expression, ++ ExpressionStatement, ++ findIndex, ++ getOrCreateEmitNode, ++ getOriginalNode, ++ hasSyntacticModifier, ++ Identifier, ++ isCallToHelper, ++ isClassDeclaration, ++ isClassExpression, ++ isClassStaticBlockDeclaration, ++ isClassThisAssignmentBlock, ++ isEmptyStringLiteral, ++ isExpressionStatement, ++ isFunctionDeclaration, ++ isIdentifier, ++ isPrivateIdentifier, ++ isPropertyNameLiteral, ++ isStringLiteral, ++ ModifierFlags, ++ NamedEvaluation, ++ Node, ++ NodeArray, ++ NodeFactory, ++ ParameterDeclaration, ++ PropertyAssignment, ++ PropertyDeclaration, ++ PropertyName, ++ setSourceMapRange, ++ setTextRange, ++ ShorthandPropertyAssignment, ++ skipOuterExpressions, ++ some, ++ Statement, ++ StringLiteral, ++ SyntaxKind, ++ TransformationContext, ++ VariableDeclaration, ++ WrappedExpression ++} from "../_namespaces/ts"; ++ ++/** ++ * Gets a string literal to use as the assigned name of an anonymous class or function declaration. ++ * @internal ++ */ ++export function getAssignedNameOfIdentifier(factory: NodeFactory, name: Identifier, expression: WrappedExpression): StringLiteral { ++ const original = getOriginalNode(skipOuterExpressions(expression)); ++ if ((isClassDeclaration(original) || isFunctionDeclaration(original)) && ++ !original.name && hasSyntacticModifier(original, ModifierFlags.Default)) { ++ return factory.createStringLiteral("default"); ++ } ++ return factory.createStringLiteralFromNode(name); ++} ++ ++function getAssignedNameOfPropertyName(context: TransformationContext, name: PropertyName, assignedNameText: string | undefined) { ++ const { factory } = context; ++ if (assignedNameText !== undefined) { ++ const assignedName = factory.createStringLiteral(assignedNameText); ++ return { assignedName, name }; ++ } ++ ++ if (isPropertyNameLiteral(name) || isPrivateIdentifier(name)) { ++ const assignedName = factory.createStringLiteralFromNode(name); ++ return { assignedName, name }; ++ } ++ ++ if (isPropertyNameLiteral(name.expression) && !isIdentifier(name.expression)) { ++ const assignedName = factory.createStringLiteralFromNode(name.expression); ++ return { assignedName, name }; ++ } ++ ++ const assignedName = factory.getGeneratedNameForNode(name); ++ context.hoistVariableDeclaration(assignedName); ++ ++ const key = context.getEmitHelperFactory().createPropKeyHelper(name.expression); ++ const assignment = factory.createAssignment(assignedName, key); ++ const updatedName = factory.updateComputedPropertyName(name, assignment); ++ return { assignedName, name: updatedName }; ++} ++ ++/** ++ * Creates a class `static {}` block used to dynamically set the name of a class. ++ * ++ * @param assignedName The expression used to resolve the assigned name at runtime. This expression should not produce ++ * side effects. ++ * @param thisExpression Overrides the expression to use for the actual `this` reference. This can be used to provide an ++ * expression that has already had its `EmitFlags` set or may have been tracked to prevent substitution. ++ * @internal ++ */ ++export function createClassNamedEvaluationHelperBlock(context: TransformationContext, assignedName: Expression, thisExpression: Expression = context.factory.createThis()): ClassNamedEvaluationHelperBlock { ++ // produces: ++ // ++ // static { __setFunctionName(this, "C"); } ++ // ++ ++ const { factory } = context; ++ const expression = context.getEmitHelperFactory().createSetFunctionNameHelper(thisExpression, assignedName); ++ const statement = factory.createExpressionStatement(expression); ++ const body = factory.createBlock([statement], /*multiLine*/ false); ++ const block = factory.createClassStaticBlockDeclaration(body); ++ ++ // We use `emitNode.assignedName` to indicate this is a NamedEvaluation helper block ++ // and to stash the expression used to resolve the assigned name. ++ getOrCreateEmitNode(block).assignedName = assignedName; ++ return block as ClassNamedEvaluationHelperBlock; ++} ++ ++/** @internal */ ++export type ClassNamedEvaluationHelperBlock = ClassStaticBlockDeclaration & { ++ readonly body: Block & { ++ readonly statements: NodeArray & readonly [ ++ ExpressionStatement & { ++ readonly expression: CallExpression & { ++ readonly expression: Identifier; ++ }; ++ } ++ ]; ++ }; ++}; ++ ++ ++/** ++ * Gets whether a node is a `static {}` block containing only a single call to the `__setFunctionName` helper where that ++ * call's second argument is the value stored in the `assignedName` property of the block's `EmitNode`. ++ * @internal ++ */ ++export function isClassNamedEvaluationHelperBlock(node: Node): node is ClassNamedEvaluationHelperBlock { ++ if (!isClassStaticBlockDeclaration(node) || node.body.statements.length !== 1) { ++ return false; ++ } ++ ++ const statement = node.body.statements[0]; ++ return isExpressionStatement(statement) && ++ isCallToHelper(statement.expression, "___setFunctionName" as __String) && ++ (statement.expression as CallExpression).arguments.length >= 2 && ++ (statement.expression as CallExpression).arguments[1] === node.emitNode?.assignedName; ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a `static {}` block containing only a single call to the ++ * `__setFunctionName` helper. ++ * @internal ++ */ ++export function classHasExplicitlyAssignedName(node: ClassLikeDeclaration): boolean { ++ return !!node.emitNode?.assignedName && some(node.members, isClassNamedEvaluationHelperBlock); ++} ++ ++/** ++ * Gets whether a `ClassLikeDeclaration` has a declared name or contains a `static {}` block containing only a single ++ * call to the `__setFunctionName` helper. ++ * @internal ++ */ ++export function classHasDeclaredOrExplicitlyAssignedName(node: ClassLikeDeclaration): boolean { ++ return !!node.name || classHasExplicitlyAssignedName(node); ++} ++ ++/** ++ * Injects a class `static {}` block used to dynamically set the name of a class, if one does not already exist. ++ * @internal ++ */ ++export function injectClassNamedEvaluationHelperBlockIfMissing( ++ context: TransformationContext, ++ node: T, ++ assignedName: Expression, ++ thisExpression?: Expression ++): Extract>; ++export function injectClassNamedEvaluationHelperBlockIfMissing( ++ context: TransformationContext, ++ node: ClassLikeDeclaration, ++ assignedName: Expression, ++ thisExpression?: Expression ++) { ++ // given: ++ // ++ // let C = class { ++ // }; ++ // ++ // produces: ++ // ++ // let C = class { ++ // static { __setFunctionName(this, "C"); } ++ // }; ++ ++ // NOTE: If the class has a `_classThis` assignment block, this helper will be injected after that block. ++ ++ if (classHasExplicitlyAssignedName(node)) { ++ return node; ++ } ++ ++ const { factory } = context; ++ const namedEvaluationBlock = createClassNamedEvaluationHelperBlock(context, assignedName, thisExpression); ++ if (node.name) { ++ setSourceMapRange(namedEvaluationBlock.body.statements[0], node.name); ++ } ++ ++ const insertionIndex = findIndex(node.members, isClassThisAssignmentBlock) + 1; ++ const leading = node.members.slice(0, insertionIndex); ++ const trailing = node.members.slice(insertionIndex); ++ const members = factory.createNodeArray([...leading, namedEvaluationBlock, ...trailing]); ++ setTextRange(members, node.members); ++ ++ node = isClassDeclaration(node) ? ++ factory.updateClassDeclaration( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members) : ++ factory.updateClassExpression( ++ node, ++ node.modifiers, ++ node.name, ++ node.typeParameters, ++ node.heritageClauses, ++ members); ++ ++ getOrCreateEmitNode(node).assignedName = assignedName; ++ return node; ++} ++ ++function finishTransformNamedEvaluation( ++ context: TransformationContext, ++ expression: WrappedExpression, ++ assignedName: Expression, ++ ignoreEmptyStringLiteral?: boolean, ++): Expression { ++ if (ignoreEmptyStringLiteral && isStringLiteral(assignedName) && isEmptyStringLiteral(assignedName)) { ++ return expression; ++ } ++ ++ const { factory } = context; ++ const innerExpression = skipOuterExpressions(expression); ++ ++ const updatedExpression = isClassExpression(innerExpression) ? ++ cast(injectClassNamedEvaluationHelperBlockIfMissing(context, innerExpression, assignedName), isClassExpression) : ++ context.getEmitHelperFactory().createSetFunctionNameHelper(innerExpression, assignedName); ++ ++ return factory.restoreOuterExpressions(expression, updatedExpression); ++} ++ ++function transformNamedEvaluationOfPropertyAssignment(context: TransformationContext, node: NamedEvaluation & PropertyAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.2.5.5 RS: PropertyDefinitionEvaluation ++ // PropertyAssignment : PropertyName `:` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and _isProtoSetter_ is *false*, then ++ // a. Let _popValue_ be ? NamedEvaluation of |AssignmentExpression| with argument _propKey_. ++ // ... ++ ++ const { factory } = context; ++ const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updatePropertyAssignment( ++ node, ++ name, ++ initializer); ++} ++ ++function transformNamedEvaluationOfShorthandAssignmentProperty(context: TransformationContext, node: NamedEvaluation & ShorthandPropertyAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.15.5.3 RS: PropertyDestructuringAssignmentEvaluation ++ // AssignmentProperty : IdentifierReference Initializer? ++ // ... ++ // 4. If |Initializer?| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _P_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.objectAssignmentInitializer); ++ const objectAssignmentInitializer = finishTransformNamedEvaluation(context, node.objectAssignmentInitializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateShorthandPropertyAssignment( ++ node, ++ node.name, ++ objectAssignmentInitializer); ++} ++ ++function transformNamedEvaluationOfVariableDeclaration(context: TransformationContext, node: NamedEvaluation & VariableDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 14.3.1.2 RS: Evaluation ++ // LexicalBinding : BindingIdentifier Initializer ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.2.1 RS: Evaluation ++ // VariableDeclaration : BindingIdentifier Initializer ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateVariableDeclaration( ++ node, ++ node.name, ++ node.exclamationToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfParameterDeclaration(context: TransformationContext, node: NamedEvaluation & ParameterDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 8.6.3 RS: IteratorBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 5. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.3.3 RS: KeyedBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 4. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateParameterDeclaration( ++ node, ++ node.modifiers, ++ node.dotDotDotToken, ++ node.name, ++ node.questionToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfBindingElement(context: TransformationContext, node: NamedEvaluation & BindingElement, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 8.6.3 RS: IteratorBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 5. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ // ++ // 14.3.3.3 RS: KeyedBindingInitialization ++ // SingleNameBinding : BindingIdentifier Initializer? ++ // ... ++ // 4. If |Initializer| is present and _v_ is *undefined*, then ++ // a. If IsAnonymousFunctionDefinition(|Initializer|) is *true*, then ++ // i. Set _v_ to ? NamedEvaluation of |Initializer| with argument _bindingId_. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.name, node.initializer); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateBindingElement( ++ node, ++ node.dotDotDotToken, ++ node.propertyName, ++ node.name, ++ initializer); ++} ++ ++function transformNamedEvaluationOfPropertyDeclaration(context: TransformationContext, node: NamedEvaluation & PropertyDeclaration, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 10.2.1.3 RS: EvaluateBody ++ // Initializer : `=` AssignmentExpression ++ // ... ++ // 3. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |Initializer| with argument _functionObject_.[[ClassFieldInitializerName]]. ++ // ... ++ ++ const { factory } = context; ++ const { assignedName, name } = getAssignedNameOfPropertyName(context, node.name, assignedNameText); ++ const initializer = finishTransformNamedEvaluation(context, node.initializer, assignedName, ignoreEmptyStringLiteral); ++ return factory.updatePropertyDeclaration( ++ node, ++ node.modifiers, ++ name, ++ node.questionToken ?? node.exclamationToken, ++ node.type, ++ initializer); ++} ++ ++function transformNamedEvaluationOfAssignmentExpression(context: TransformationContext, node: NamedEvaluation & BinaryExpression, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 13.15.2 RS: Evaluation ++ // AssignmentExpression : LeftHandSideExpression `=` AssignmentExpression ++ // 1. If |LeftHandSideExpression| is neither an |ObjectLiteral| nor an |ArrayLiteral|, then ++ // a. Let _lref_ be ? Evaluation of |LeftHandSideExpression|. ++ // b. If IsAnonymousFunctionDefinition(|AssignmentExpression|) and IsIdentifierRef of |LeftHandSideExpression| are both *true*, then ++ // i. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `&&=` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `||=` AssignmentExpression ++ // ... ++ // 5. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ // ++ // AssignmentExpression : LeftHandSideExpression `??=` AssignmentExpression ++ // ... ++ // 4. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true* and IsIdentifierRef of |LeftHandSideExpression| is *true*, then ++ // a. Let _rval_ be ? NamedEvaluation of |AssignmentExpression| with argument _lref_.[[ReferencedName]]. ++ // ... ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ getAssignedNameOfIdentifier(factory, node.left, node.right); ++ const right = finishTransformNamedEvaluation(context, node.right, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateBinaryExpression( ++ node, ++ node.left, ++ node.operatorToken, ++ right); ++} ++ ++function transformNamedEvaluationOfExportAssignment(context: TransformationContext, node: NamedEvaluation & ExportAssignment, ignoreEmptyStringLiteral?: boolean, assignedNameText?: string) { ++ // 16.2.3.7 RS: Evaluation ++ // ExportDeclaration : `export` `default` AssignmentExpression `;` ++ // 1. If IsAnonymousFunctionDefinition(|AssignmentExpression|) is *true*, then ++ // a. Let _value_ be ? NamedEvaluation of |AssignmentExpression| with argument `"default"`. ++ // ... ++ ++ // NOTE: Since emit for `export =` translates to `module.exports = ...`, the assigned name of the class or function ++ // is `""`. ++ ++ const { factory } = context; ++ const assignedName = assignedNameText !== undefined ? factory.createStringLiteral(assignedNameText) : ++ factory.createStringLiteral(node.isExportEquals ? "" : "default"); ++ const expression = finishTransformNamedEvaluation(context, node.expression, assignedName, ignoreEmptyStringLiteral); ++ return factory.updateExportAssignment( ++ node, ++ node.modifiers, ++ expression); ++} ++ ++/** ++ * Performs a shallow transformation of a `NamedEvaluation` node, such that a valid name will be assigned. ++ * @internal ++ */ ++export function transformNamedEvaluation(context: TransformationContext, node: T, ignoreEmptyStringLiteral?: boolean, assignedName?: string): Extract>; ++export function transformNamedEvaluation(context: TransformationContext, node: NamedEvaluation, ignoreEmptyStringLiteral?: boolean, assignedName?: string) { ++ switch (node.kind) { ++ case SyntaxKind.PropertyAssignment: ++ return transformNamedEvaluationOfPropertyAssignment(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.ShorthandPropertyAssignment: ++ return transformNamedEvaluationOfShorthandAssignmentProperty(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.VariableDeclaration: ++ return transformNamedEvaluationOfVariableDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.Parameter: ++ return transformNamedEvaluationOfParameterDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.BindingElement: ++ return transformNamedEvaluationOfBindingElement(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.PropertyDeclaration: ++ return transformNamedEvaluationOfPropertyDeclaration(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.BinaryExpression: ++ return transformNamedEvaluationOfAssignmentExpression(context, node, ignoreEmptyStringLiteral, assignedName); ++ case SyntaxKind.ExportAssignment: ++ return transformNamedEvaluationOfExportAssignment(context, node, ignoreEmptyStringLiteral, assignedName); ++ } ++} +diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts +index 6fec0b61b..8b97637c0 100644 +--- a/src/compiler/transformers/ts.ts ++++ b/src/compiler/transformers/ts.ts +@@ -41,7 +41,7 @@ import { + Expression, + ExpressionWithTypeArguments, + filter, +- findSuperStatementIndex, ++ findSuperStatementIndexPath, + flattenDestructuringAssignment, + FlattenLevel, + FunctionDeclaration, +@@ -79,6 +79,8 @@ import { + isAssertionExpression, + isBindingName, + isBindingPattern, ++ isBlock, ++ isCatchClause, + isClassElement, + isClassLike, + isComputedPropertyName, +@@ -118,6 +120,7 @@ import { + isSourceFile, + isStatement, + isTemplateLiteral, ++ isTryStatement, + JsxOpeningElement, + JsxSelfClosingElement, + LeftHandSideExpression, +@@ -194,7 +197,7 @@ import { + visitNode, + visitNodes, + visitParameterList, +- VisitResult, ++ VisitResult + } from "../_namespaces/ts"; + + /** +@@ -922,24 +925,19 @@ export function transformTypeScript(context: TransformationContext) { + const iife = factory.createImmediatelyInvokedArrowFunction(statements); + setInternalEmitFlags(iife, InternalEmitFlags.TypeScriptClassWrapper); + +- // export let C = (() => { ... })(); +- const modifiers = facts & ClassFacts.IsNamedExternalExport ? +- factory.createModifiersFromModifierFlags(ModifierFlags.Export) : +- undefined; +- + // let C = (() => { ... })(); +- const varStatement = factory.createVariableStatement( +- modifiers, +- factory.createVariableDeclarationList([ +- factory.createVariableDeclaration( +- factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), +- /*exclamationToken*/ undefined, +- /*type*/ undefined, +- iife +- ) +- ], NodeFlags.Let) ++ const varDecl = factory.createVariableDeclaration( ++ factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), ++ /*exclamationToken*/ undefined, ++ /*type*/ undefined, ++ iife + ); ++ setOriginalNode(varDecl, node); + ++ const varStatement = factory.createVariableStatement( ++ /*modifiers*/ undefined, ++ factory.createVariableDeclarationList([varDecl], NodeFlags.Let) ++ ); + setOriginalNode(varStatement, node); + setCommentRange(varStatement, node); + setSourceMapRange(varStatement, moveRangePastDecorators(node)); +@@ -963,10 +961,10 @@ export function transformTypeScript(context: TransformationContext) { + factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; + } +- if (facts & ClassFacts.IsNamedExternalExport && !promoteToIIFE) { ++ if (facts & ClassFacts.IsNamedExternalExport) { + return [ + statement, +- factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) ++ factory.createExternalModuleExport(factory.getDeclarationName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)) + ]; + } + } +@@ -1293,6 +1291,37 @@ export function transformTypeScript(context: TransformationContext) { + ); + } + ++ function transformConstructorBodyWorker(statementsOut: Statement[], statementsIn: NodeArray, statementOffset: number, superPath: readonly number[], superPathDepth: number, initializerStatements: readonly Statement[]) { ++ const superStatementIndex = superPath[superPathDepth]; ++ const superStatement = statementsIn[superStatementIndex]; ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, statementOffset, superStatementIndex - statementOffset)); ++ if (isTryStatement(superStatement)) { ++ const tryBlockStatements: Statement[] = []; ++ ++ transformConstructorBodyWorker( ++ tryBlockStatements, ++ superStatement.tryBlock.statements, ++ /*statementOffset*/ 0, ++ superPath, ++ superPathDepth + 1, ++ initializerStatements); ++ ++ const tryBlockStatementsArray = factory.createNodeArray(tryBlockStatements); ++ setTextRange(tryBlockStatementsArray, superStatement.tryBlock.statements); ++ ++ statementsOut.push(factory.updateTryStatement( ++ superStatement, ++ factory.updateBlock(superStatement.tryBlock, tryBlockStatements), ++ visitNode(superStatement.catchClause, visitor, isCatchClause), ++ visitNode(superStatement.finallyBlock, visitor, isBlock))); ++ } ++ else { ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex, 1)); ++ addRange(statementsOut, initializerStatements); ++ } ++ addRange(statementsOut, visitNodes(statementsIn, visitor, isStatement, superStatementIndex + 1)); ++ } ++ + function transformConstructorBody(body: Block, constructor: ConstructorDeclaration) { + const parametersWithPropertyAssignments = constructor && + filter(constructor.parameters, p => isParameterPropertyDeclaration(p, constructor)) as readonly ParameterPropertyDeclaration[] | undefined; +@@ -1305,15 +1334,7 @@ export function transformTypeScript(context: TransformationContext) { + resumeLexicalEnvironment(); + + const prologueStatementCount = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); +- const superStatementIndex = findSuperStatementIndex(body.statements, prologueStatementCount); +- +- // If there was a super call, visit existing statements up to and including it +- if (superStatementIndex >= 0) { +- addRange( +- statements, +- visitNodes(body.statements, visitor, isStatement, prologueStatementCount, superStatementIndex + 1 - prologueStatementCount), +- ); +- } ++ const superPath = findSuperStatementIndexPath(body.statements, prologueStatementCount); + + // Transform parameters into property assignments. Transforms this: + // +@@ -1328,24 +1349,14 @@ export function transformTypeScript(context: TransformationContext) { + // } + // + const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); +- +- // If there is a super() call, the parameter properties go immediately after it +- if (superStatementIndex >= 0) { +- addRange(statements, parameterPropertyAssignments); ++ if (superPath.length) { ++ transformConstructorBodyWorker(statements, body.statements, prologueStatementCount, superPath, /*superPathDepth*/ 0, parameterPropertyAssignments); + } +- // Since there was no super() call, parameter properties are the first statements in the constructor after any prologue statements + else { +- statements = [ +- ...statements.slice(0, prologueStatementCount), +- ...parameterPropertyAssignments, +- ...statements.slice(prologueStatementCount), +- ]; ++ addRange(statements, parameterPropertyAssignments); ++ addRange(statements, visitNodes(body.statements, visitor, isStatement, prologueStatementCount)); + } + +- // Add remaining statements from the body, skipping the super() call if it was found and any (already added) prologue statements +- const start = superStatementIndex >= 0 ? superStatementIndex + 1 : prologueStatementCount; +- addRange(statements, visitNodes(body.statements, visitor, isStatement, start)); +- + // End the lexical environment. + statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); + const block = factory.createBlock(setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); +diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts +index c094a8dc0..d01206af9 100644 +--- a/src/compiler/transformers/utilities.ts ++++ b/src/compiler/transformers/utilities.ts +@@ -12,20 +12,19 @@ import { + ClassExpression, + ClassLikeDeclaration, + ClassStaticBlockDeclaration, +- CompilerOptions, + CompoundAssignmentOperator, + CoreTransformationContext, + createExternalHelpersImportDeclarationIfNeeded, +- createMultiMap, + Decorator, +- EmitResolver, + ExportAssignment, + ExportDeclaration, + ExportSpecifier, + Expression, + filter, ++ formatGeneratedName, + FunctionDeclaration, + FunctionLikeDeclaration, ++ GeneratedIdentifierFlags, + getAllAccessorDeclarations, + getDecorators, + getFirstConstructorWithBody, +@@ -53,6 +52,7 @@ import { + isIdentifier, + isKeyword, + isLocalName, ++ isMemberName, + isMethodOrAccessor, + isNamedExports, + isNamedImports, +@@ -62,6 +62,7 @@ import { + isStatic, + isStringLiteralLike, + isSuperCall, ++ isTryStatement, + LogicalOperatorOrHigher, + map, + MethodDeclaration, +@@ -83,8 +84,9 @@ import { + SuperCall, + SyntaxKind, + TransformationContext, ++ unorderedRemoveItem, + VariableDeclaration, +- VariableStatement, ++ VariableStatement + } from "../_namespaces/ts"; + + /** @internal */ +@@ -97,7 +99,7 @@ export function getOriginalNodeId(node: Node) { + export interface ExternalModuleInfo { + externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; // imports of other external modules + externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers +- exportSpecifiers: Map; // file-local export specifiers by name (no reexports) ++ exportSpecifiers: IdentifierNameMap; // file-local export specifiers by name (no reexports) + exportedBindings: Identifier[][]; // exported names of local declarations + exportedNames: Identifier[] | undefined; // all exported names in the module, both local and reexported + exportEquals: ExportAssignment | undefined; // an export= declaration if one was present +@@ -159,9 +161,11 @@ export function getImportNeedsImportDefaultHelper(node: ImportDeclaration): bool + } + + /** @internal */ +-export function collectExternalModuleInfo(context: TransformationContext, sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo { ++export function collectExternalModuleInfo(context: TransformationContext, sourceFile: SourceFile): ExternalModuleInfo { ++ const resolver = context.getEmitResolver(); ++ const compilerOptions = context.getCompilerOptions(); + const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; +- const exportSpecifiers = createMultiMap(); ++ const exportSpecifiers = new IdentifierNameMultiMap(); + const exportedBindings: Identifier[][] = []; + const uniqueExports = new Map(); + let exportedNames: Identifier[] | undefined; +@@ -298,7 +302,7 @@ export function collectExternalModuleInfo(context: TransformationContext, source + if (!uniqueExports.get(idText(specifier.name))) { + const name = specifier.propertyName || specifier.name; + if (!node.moduleSpecifier) { +- exportSpecifiers.add(idText(name), specifier); ++ exportSpecifiers.add(name, specifier); + } + + const decl = resolver.getReferencedImportDeclaration(name) +@@ -348,6 +352,83 @@ function multiMapSparseArrayAdd(map: V[][], key: number, value: V): V[] { + return values; + } + ++/** @internal */ ++export class IdentifierNameMap { ++ private readonly _map = new Map(); ++ ++ get size() { ++ return this._map.size; ++ } ++ ++ has(key: Identifier) { ++ return this._map.has(IdentifierNameMap.toKey(key)); ++ } ++ ++ get(key: Identifier) { ++ return this._map.get(IdentifierNameMap.toKey(key)); ++ } ++ ++ set(key: Identifier, value: V) { ++ this._map.set(IdentifierNameMap.toKey(key), value); ++ return this; ++ } ++ ++ delete(key: Identifier): boolean { ++ return this._map?.delete(IdentifierNameMap.toKey(key)) ?? false; ++ } ++ ++ clear(): void { ++ this._map.clear(); ++ } ++ ++ values() { ++ return this._map.values(); ++ } ++ ++ private static toKey(name: Identifier | PrivateIdentifier): string { ++ if (isGeneratedPrivateIdentifier(name) || isGeneratedIdentifier(name)) { ++ const autoGenerate = name.emitNode.autoGenerate; ++ if ((autoGenerate.flags & GeneratedIdentifierFlags.KindMask) === GeneratedIdentifierFlags.Node) { ++ const node = getNodeForGeneratedName(name); ++ const baseName = isMemberName(node) && node !== name ? IdentifierNameMap.toKey(node) : `(generated@${getNodeId(node)})`; ++ return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, IdentifierNameMap.toKey); ++ } ++ else { ++ const baseName = `(auto@${autoGenerate.id})`; ++ return formatGeneratedName(/*privateName*/ false, autoGenerate.prefix, baseName, autoGenerate.suffix, IdentifierNameMap.toKey); ++ } ++ } ++ if (isPrivateIdentifier(name)) { ++ return idText(name).slice(1); ++ } ++ return idText(name); ++ } ++} ++ ++/** @internal */ ++export class IdentifierNameMultiMap extends IdentifierNameMap { ++ add(key: Identifier, value: V): V[] { ++ let values = this.get(key); ++ if (values) { ++ values.push(value); ++ } ++ else { ++ this.set(key, values = [value]); ++ } ++ return values; ++ } ++ ++ remove(key: Identifier, value: V) { ++ const values = this.get(key); ++ if (values) { ++ unorderedRemoveItem(values, value); ++ if (!values.length) { ++ this.delete(key); ++ } ++ } ++ } ++} ++ + /** + * Used in the module transformer to check if an expression is reasonably without sideeffect, + * and thus better to copy into multiple places rather than to cache in a temporary variable +@@ -417,21 +498,34 @@ export function getSuperCallFromStatement(statement: Statement): SuperCall | und + : undefined; + } + +-/** +- * @returns The index (after prologue statements) of a super call, or -1 if not found. +- * +- * @internal +- */ +-export function findSuperStatementIndex(statements: NodeArray, indexAfterLastPrologueStatement: number) { +- for (let i = indexAfterLastPrologueStatement; i < statements.length; i += 1) { ++function findSuperStatementIndexPathWorker(statements: NodeArray, start: number, indices: number[]) { ++ for (let i = start; i < statements.length; i += 1) { + const statement = statements[i]; +- + if (getSuperCallFromStatement(statement)) { +- return i; ++ indices.unshift(i); ++ return true; ++ } ++ else if (isTryStatement(statement) && findSuperStatementIndexPathWorker(statement.tryBlock.statements, 0, indices)) { ++ indices.unshift(i); ++ return true; + } + } + +- return -1; ++ return false; ++} ++ ++/** ++ * Finds a path of indices to navigate to a `super()` call, descending only through `try` statements. ++ * ++ * @returns An array of indicies to walk down through `try` statements, with the last element being the index of ++ * the statement containing `super()`. Otherwise, an empty array if `super()` was not found. ++ * ++ * @internal ++ */ ++export function findSuperStatementIndexPath(statements: NodeArray, start: number) { ++ const indices: number[] = []; ++ findSuperStatementIndexPathWorker(statements, start, indices); ++ return indices; + } + + /** +diff --git a/src/compiler/types.ts b/src/compiler/types.ts +index a5edcc4a7..06d4d1799 100644 +--- a/src/compiler/types.ts ++++ b/src/compiler/types.ts +@@ -218,6 +218,7 @@ export const enum SyntaxKind { + UndefinedKeyword, + UniqueKeyword, + UnknownKeyword, ++ UsingKeyword, + FromKeyword, + GlobalKeyword, + BigIntKeyword, +@@ -663,6 +664,7 @@ export type KeywordSyntaxKind = + | SyntaxKind.UndefinedKeyword + | SyntaxKind.UniqueKeyword + | SyntaxKind.UnknownKeyword ++ | SyntaxKind.UsingKeyword + | SyntaxKind.VarKeyword + | SyntaxKind.VoidKeyword + | SyntaxKind.WhileKeyword +@@ -791,25 +793,27 @@ export const enum NodeFlags { + None = 0, + Let = 1 << 0, // Variable declaration + Const = 1 << 1, // Variable declaration +- NestedNamespace = 1 << 2, // Namespace declaration +- Synthesized = 1 << 3, // Node was synthesized during transformation +- Namespace = 1 << 4, // Namespace declaration +- OptionalChain = 1 << 5, // Chained MemberExpression rooted to a pseudo-OptionalExpression +- ExportContext = 1 << 6, // Export context (initialized by binding) +- ContainsThis = 1 << 7, // Interface contains references to "this" +- HasImplicitReturn = 1 << 8, // If function implicitly returns on one of codepaths (initialized by binding) +- HasExplicitReturn = 1 << 9, // If function has explicit reachable return on one of codepaths (initialized by binding) +- GlobalAugmentation = 1 << 10, // Set if module declaration is an augmentation for the global scope +- HasAsyncFunctions = 1 << 11, // If the file has async functions (initialized by binding) +- DisallowInContext = 1 << 12, // If node was parsed in a context where 'in-expressions' are not allowed +- YieldContext = 1 << 13, // If node was parsed in the 'yield' context created when parsing a generator +- DecoratorContext = 1 << 14, // If node was parsed as part of a decorator +- AwaitContext = 1 << 15, // If node was parsed in the 'await' context created when parsing an async function +- DisallowConditionalTypesContext = 1 << 16, // If node was parsed in a context where conditional types are not allowed +- ThisNodeHasError = 1 << 17, // If the parser encountered an error when parsing the code that created this node +- JavaScriptFile = 1 << 18, // If node was parsed in a JavaScript +- ThisNodeOrAnySubNodesHasError = 1 << 19, // If this node or any of its children had an error +- HasAggregatedChildData = 1 << 20, // If we've computed data from children and cached it in this node ++ Using = 1 << 2, // Variable declaration ++ AwaitUsing = Const | Using, // Variable declaration (NOTE: on a single node these flags would otherwise be mutually exclusive) ++ NestedNamespace = 1 << 3, // Namespace declaration ++ Synthesized = 1 << 4, // Node was synthesized during transformation ++ Namespace = 1 << 5, // Namespace declaration ++ OptionalChain = 1 << 6, // Chained MemberExpression rooted to a pseudo-OptionalExpression ++ ExportContext = 1 << 7, // Export context (initialized by binding) ++ ContainsThis = 1 << 8, // Interface contains references to "this" ++ HasImplicitReturn = 1 << 9, // If function implicitly returns on one of codepaths (initialized by binding) ++ HasExplicitReturn = 1 << 10, // If function has explicit reachable return on one of codepaths (initialized by binding) ++ GlobalAugmentation = 1 << 11, // Set if module declaration is an augmentation for the global scope ++ HasAsyncFunctions = 1 << 12, // If the file has async functions (initialized by binding) ++ DisallowInContext = 1 << 13, // If node was parsed in a context where 'in-expressions' are not allowed ++ YieldContext = 1 << 14, // If node was parsed in the 'yield' context created when parsing a generator ++ DecoratorContext = 1 << 15, // If node was parsed as part of a decorator ++ AwaitContext = 1 << 16, // If node was parsed in the 'await' context created when parsing an async function ++ DisallowConditionalTypesContext = 1 << 17, // If node was parsed in a context where conditional types are not allowed ++ ThisNodeHasError = 1 << 18, // If the parser encountered an error when parsing the code that created this node ++ JavaScriptFile = 1 << 19, // If node was parsed in a JavaScript ++ ThisNodeOrAnySubNodesHasError = 1 << 20, // If this node or any of its children had an error ++ HasAggregatedChildData = 1 << 21, // If we've computed data from children and cached it in this node + + // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid + // walking the tree if the flags are not set. However, these flags are just a approximation +@@ -820,17 +824,18 @@ export const enum NodeFlags { + // removal, it is likely that users will add the import anyway. + // The advantage of this approach is its simplicity. For the case of batch compilation, + // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used. +- /** @internal */ PossiblyContainsDynamicImport = 1 << 21, +- /** @internal */ PossiblyContainsImportMeta = 1 << 22, ++ /** @internal */ PossiblyContainsDynamicImport = 1 << 22, ++ /** @internal */ PossiblyContainsImportMeta = 1 << 23, + +- JSDoc = 1 << 23, // If node was parsed inside jsdoc +- /** @internal */ Ambient = 1 << 24, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. +- /** @internal */ InWithStatement = 1 << 25, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) +- JsonFile = 1 << 26, // If node was parsed in a Json +- /** @internal */ TypeCached = 1 << 27, // If a type was cached for node at any point +- /** @internal */ Deprecated = 1 << 28, // If has '@deprecated' JSDoc tag ++ JSDoc = 1 << 24, // If node was parsed inside jsdoc ++ /** @internal */ Ambient = 1 << 25, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier. ++ /** @internal */ InWithStatement = 1 << 26, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`) ++ JsonFile = 1 << 27, // If node was parsed in a Json ++ /** @internal */ TypeCached = 1 << 28, // If a type was cached for node at any point ++ /** @internal */ Deprecated = 1 << 29, // If has '@deprecated' JSDoc tag + +- BlockScoped = Let | Const, ++ BlockScoped = Let | Const | Using, ++ Constant = Const | Using, + + ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn, + ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions, +@@ -7945,10 +7950,11 @@ export interface SourceMapSource { + } + + /** @internal */ ++// NOTE: Any new properties should be accounted for in `mergeEmitNode` in factory/nodeFactory.ts + export interface EmitNode { +- annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. + flags: EmitFlags; // Flags that customize emit + internalFlags: InternalEmitFlags; // Internal flags that customize emit ++ annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup. + leadingComments?: SynthesizedComment[]; // Synthesized leading comments + trailingComments?: SynthesizedComment[]; // Synthesized trailing comments + commentRange?: TextRange; // The text range to use when emitting leading or trailing comments +@@ -7961,7 +7967,8 @@ export interface EmitNode { + startsOnNewLine?: boolean; // If the node should begin on a new line + snippetElement?: SnippetElement; // Snippet element of the node + typeNode?: TypeNode; // VariableDeclaration type +- classThis?: Identifier; // Identifier that points to the final class constructor after decorators are applied ++ classThis?: Identifier; // Identifier that points to a captured static `this` for a class which may be updated after decorators are applied ++ assignedName?: Expression; // Expression used as the assigned name of a class or function + identifierTypeArguments?: NodeArray; // Only defined on synthesized identifiers. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help. + autoGenerate: AutoGenerateInfo | undefined; // Used for auto-generated identifiers and private identifiers. + generatedImportReference?: ImportSpecifier; // Reference to the generated import specifier this identifier refers to +@@ -8093,9 +8100,10 @@ export const enum ExternalEmitHelpers { + CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports) + SetFunctionName = 1 << 23, // __setFunctionName (used by class fields and ECMAScript decorators) + PropKey = 1 << 24, // __propKey (used by class fields and ECMAScript decorators) ++ AddDisposableResourceAndDisposeResources = 1 << 25, // __addDisposableResource and __disposeResources (used by ESNext transformations) + + FirstEmitHelper = Extends, +- LastEmitHelper = PropKey, ++ LastEmitHelper = AddDisposableResourceAndDisposeResources, + + // Helpers included by ES2015 for..of + ForOfIncludes = Values, +@@ -8190,7 +8198,8 @@ export type WrappedExpression = + | T + ; + +-export type TypeOfTag = "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; ++/** @internal */ ++export type TypeOfTag = "null" | "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function"; + + /** @internal */ + export interface CallBinding { +@@ -8237,6 +8246,7 @@ export interface ParenthesizerRules { + export interface NodeConverters { + convertToFunctionBlock(node: ConciseBody, multiLine?: boolean): Block; + convertToFunctionExpression(node: FunctionDeclaration): FunctionExpression; ++ convertToClassExpression(node: ClassDeclaration): ClassExpression; + convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement): Expression; + convertToObjectAssignmentElement(element: ObjectBindingOrAssignmentElement): ObjectLiteralElementLike; + convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern; +@@ -8254,11 +8264,15 @@ export interface GeneratedNamePart { + suffix?: string; + } + ++export type ImmediatelyInvokedFunctionExpression = CallExpression & { readonly expression: FunctionExpression; }; ++export type ImmediatelyInvokedArrowFunction = CallExpression & { readonly expression: ParenthesizedExpression & { readonly expression: ArrowFunction; }; }; ++ + export interface NodeFactory { + /** @internal */ readonly parenthesizer: ParenthesizerRules; + /** @internal */ readonly converters: NodeConverters; + /** @internal */ readonly baseFactory: BaseNodeFactory; + /** @internal */ readonly flags: NodeFactoryFlags; ++ + createNodeArray(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray; + + // +@@ -8877,8 +8891,8 @@ export interface NodeFactory { + + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression; + createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression; +- createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): ImmediatelyInvokedArrowFunction; ++ createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): ImmediatelyInvokedArrowFunction; + + + createVoidZero(): VoidExpression; +@@ -8886,6 +8900,7 @@ export interface NodeFactory { + createExternalModuleExport(exportName: Identifier): ExportDeclaration; + + /** @internal */ createTypeCheck(value: Expression, tag: TypeOfTag): Expression; ++ /** @internal */ createIsNotTypeCheck(value: Expression, tag: TypeOfTag): Expression; + /** @internal */ createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]): CallExpression; + /** @internal */ createGlobalMethodCall(globalObjectName: string, globalMethodName: string, argumentsList: readonly Expression[]): CallExpression; + /** @internal */ createFunctionBindCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression; +diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts +index c681495ed..44a62be7e 100644 +--- a/src/compiler/utilities.ts ++++ b/src/compiler/utilities.ts +@@ -52,6 +52,7 @@ import { + ClassDeclaration, + ClassElement, + ClassExpression, ++ classHasDeclaredOrExplicitlyAssignedName, + ClassLikeDeclaration, + ClassStaticBlockDeclaration, + combinePaths, +@@ -2335,14 +2336,36 @@ export function isDeclarationReadonly(declaration: Declaration): boolean { + return !!(getCombinedModifierFlags(declaration) & ModifierFlags.Readonly && !isParameterPropertyDeclaration(declaration, declaration.parent)); + } + +-/** @internal */ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of an `await using` declaration. ++ * @internal ++ */ ++export function isVarAwaitUsing(node: VariableDeclaration | VariableDeclarationList): boolean { ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.AwaitUsing; ++} ++ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `using` declaration. ++ * @internal ++ */ ++export function isVarUsing(node: VariableDeclaration | VariableDeclarationList): boolean { ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Using; ++} ++ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `const` declaration. ++ * @internal ++ */ + export function isVarConst(node: VariableDeclaration | VariableDeclarationList): boolean { +- return !!(getCombinedNodeFlags(node) & NodeFlags.Const); ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Const; + } + +-/** @internal */ ++/** ++ * Gets whether a bound `VariableDeclaration` or `VariableDeclarationList` is part of a `let` declaration. ++ * @internal ++ */ + export function isLet(node: Node): boolean { +- return !!(getCombinedNodeFlags(node) & NodeFlags.Let); ++ return (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === NodeFlags.Let; + } + + /** @internal */ +@@ -5104,8 +5127,12 @@ export function isAnonymousFunctionDefinition(node: Expression, cb?: (node: Anon + node = skipOuterExpressions(node); + switch (node.kind) { + case SyntaxKind.ClassExpression: ++ if (classHasDeclaredOrExplicitlyAssignedName(node as ClassExpression)) { ++ return false; ++ } ++ break; + case SyntaxKind.FunctionExpression: +- if ((node as ClassExpression | FunctionExpression).name) { ++ if ((node as FunctionExpression).name) { + return false; + } + break; +@@ -5171,7 +5198,8 @@ export type NamedEvaluation = + | ParameterDeclaration & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } + | BindingElement & { readonly name: Identifier, readonly dotDotDotToken: undefined, readonly initializer: WrappedExpression } + | PropertyDeclaration & { readonly initializer: WrappedExpression } +- | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } ++ | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } ++ | AssignmentExpression & { readonly left: Identifier, readonly right: WrappedExpression } + | ExportAssignment & { readonly expression: WrappedExpression } + ; + +diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts +index 4d0220bdf..62be65647 100644 +--- a/src/compiler/utilitiesPublic.ts ++++ b/src/compiler/utilitiesPublic.ts +@@ -68,6 +68,7 @@ import { + FunctionLikeDeclaration, + FunctionTypeNode, + GeneratedIdentifier, ++ GeneratedIdentifierFlags, + GeneratedPrivateIdentifier, + GetAccessorDeclaration, + getAssignmentDeclarationKind, +@@ -604,7 +605,11 @@ export function getCombinedNodeFlagsAlwaysIncludeJSDoc(node: Declaration): Modif + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + export function getCombinedNodeFlags(node: Node): NodeFlags { +- return getCombinedFlags(node, n => n.flags); ++ return getCombinedFlags(node, getNodeFlags); ++} ++ ++function getNodeFlags(node: Node) { ++ return node.flags; + } + + /** @internal */ +@@ -1533,6 +1538,14 @@ export function isGeneratedPrivateIdentifier(node: Node): node is GeneratedPriva + return isPrivateIdentifier(node) && node.emitNode?.autoGenerate !== undefined; + } + ++/** @internal */ ++export function isFileLevelReservedGeneratedIdentifier(node: GeneratedIdentifier) { ++ const flags = node.emitNode.autoGenerate.flags; ++ return !!(flags & GeneratedIdentifierFlags.FileLevel) ++ && !!(flags & GeneratedIdentifierFlags.Optimistic) ++ && !!(flags & GeneratedIdentifierFlags.ReservedInNestedScopes); ++} ++ + // Private Identifiers + /** @internal */ + export function isPrivateIdentifierClassElementDeclaration(node: Node): node is PrivateClassElementDeclaration { +diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts +index 30eaf070b..efec17999 100644 +--- a/src/lib/esnext.d.ts ++++ b/src/lib/esnext.d.ts +@@ -1,2 +1,3 @@ + /// + /// ++/// +diff --git a/src/lib/esnext.disposable.d.ts b/src/lib/esnext.disposable.d.ts +new file mode 100644 +index 000000000..318b7395a +--- /dev/null ++++ b/src/lib/esnext.disposable.d.ts +@@ -0,0 +1,167 @@ ++/// ++ ++interface SymbolConstructor { ++ /** ++ * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. ++ */ ++ readonly dispose: unique symbol; ++ ++ /** ++ * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. ++ */ ++ readonly asyncDispose: unique symbol; ++} ++ ++interface Disposable { ++ [Symbol.dispose](): void; ++} ++ ++interface AsyncDisposable { ++ [Symbol.asyncDispose](): PromiseLike; ++} ++ ++interface SuppressedError extends Error { ++ error: any; ++ suppressed: any; ++} ++ ++interface SuppressedErrorConstructor extends ErrorConstructor { ++ new (error: any, suppressed: any, message?: string): SuppressedError; ++ (error: any, suppressed: any, message?: string): SuppressedError; ++ readonly prototype: SuppressedError; ++} ++declare var SuppressedError: SuppressedErrorConstructor; ++ ++interface DisposableStack { ++ /** ++ * Returns a value indicating whether this stack has been disposed. ++ */ ++ readonly disposed: boolean; ++ /** ++ * Disposes each resource in the stack in the reverse order that they were added. ++ */ ++ dispose(): void; ++ /** ++ * Adds a disposable resource to the stack, returning the resource. ++ * @param value The resource to add. `null` and `undefined` will not be added, but will be returned. ++ * @returns The provided {@link value}. ++ */ ++ use(value: T): T; ++ /** ++ * Adds a value and associated disposal callback as a resource to the stack. ++ * @param value The value to add. ++ * @param onDispose The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value` ++ * as the first parameter. ++ * @returns The provided {@link value}. ++ */ ++ adopt(value: T, onDispose: (value: T) => void): T; ++ /** ++ * Adds a callback to be invoked when the stack is disposed. ++ */ ++ defer(onDispose: () => void): void; ++ /** ++ * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. ++ * @example ++ * ```ts ++ * class C { ++ * #res1: Disposable; ++ * #res2: Disposable; ++ * #disposables: DisposableStack; ++ * constructor() { ++ * // stack will be disposed when exiting constructor for any reason ++ * using stack = new DisposableStack(); ++ * ++ * // get first resource ++ * this.#res1 = stack.use(getResource1()); ++ * ++ * // get second resource. If this fails, both `stack` and `#res1` will be disposed. ++ * this.#res2 = stack.use(getResource2()); ++ * ++ * // all operations succeeded, move resources out of `stack` so that they aren't disposed ++ * // when constructor exits ++ * this.#disposables = stack.move(); ++ * } ++ * ++ * [Symbol.dispose]() { ++ * this.#disposables.dispose(); ++ * } ++ * } ++ * ``` ++ */ ++ move(): DisposableStack; ++ [Symbol.dispose](): void; ++ readonly [Symbol.toStringTag]: string; ++} ++ ++interface DisposableStackConstructor { ++ new(): DisposableStack; ++ readonly prototype: DisposableStack; ++} ++declare var DisposableStack: DisposableStackConstructor; ++ ++interface AsyncDisposableStack { ++ /** ++ * Returns a value indicating whether this stack has been disposed. ++ */ ++ readonly disposed: boolean; ++ /** ++ * Disposes each resource in the stack in the reverse order that they were added. ++ */ ++ disposeAsync(): Promise; ++ /** ++ * Adds a disposable resource to the stack, returning the resource. ++ * @param value The resource to add. `null` and `undefined` will not be added, but will be returned. ++ * @returns The provided {@link value}. ++ */ ++ use(value: T): T; ++ /** ++ * Adds a value and associated disposal callback as a resource to the stack. ++ * @param value The value to add. ++ * @param onDisposeAsync The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value` ++ * as the first parameter. ++ * @returns The provided {@link value}. ++ */ ++ adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T; ++ /** ++ * Adds a callback to be invoked when the stack is disposed. ++ */ ++ defer(onDisposeAsync: () => PromiseLike | void): void; ++ /** ++ * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. ++ * @example ++ * ```ts ++ * class C { ++ * #res1: Disposable; ++ * #res2: Disposable; ++ * #disposables: DisposableStack; ++ * constructor() { ++ * // stack will be disposed when exiting constructor for any reason ++ * using stack = new DisposableStack(); ++ * ++ * // get first resource ++ * this.#res1 = stack.use(getResource1()); ++ * ++ * // get second resource. If this fails, both `stack` and `#res1` will be disposed. ++ * this.#res2 = stack.use(getResource2()); ++ * ++ * // all operations succeeded, move resources out of `stack` so that they aren't disposed ++ * // when constructor exits ++ * this.#disposables = stack.move(); ++ * } ++ * ++ * [Symbol.dispose]() { ++ * this.#disposables.dispose(); ++ * } ++ * } ++ * ``` ++ */ ++ move(): AsyncDisposableStack; ++ [Symbol.asyncDispose](): Promise; ++ readonly [Symbol.toStringTag]: string; ++} ++ ++interface AsyncDisposableStackConstructor { ++ new(): AsyncDisposableStack; ++ readonly prototype: AsyncDisposableStack; ++} ++declare var AsyncDisposableStack: AsyncDisposableStackConstructor; +diff --git a/src/lib/libs.json b/src/lib/libs.json +index a7a07d9d2..260379879 100644 +--- a/src/lib/libs.json ++++ b/src/lib/libs.json +@@ -68,6 +68,7 @@ + "es2023.array", + "es2023.collection", + "esnext.intl", ++ "esnext.disposable", + "decorators", + "decorators.legacy", + // Default libraries +diff --git a/src/services/codefixes/addEmptyExportDeclaration.ts b/src/services/codefixes/addEmptyExportDeclaration.ts +index d4020fea8..b490c66af 100644 +--- a/src/services/codefixes/addEmptyExportDeclaration.ts ++++ b/src/services/codefixes/addEmptyExportDeclaration.ts +@@ -11,6 +11,7 @@ import { + registerCodeFix({ + errorCodes: [ + Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ++ Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, + ], + getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { +diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts +index f12ba12e3..ee1f5f73a 100644 +--- a/src/services/codefixes/fixAwaitInSyncFunction.ts ++++ b/src/services/codefixes/fixAwaitInSyncFunction.ts +@@ -29,6 +29,7 @@ import { + const fixId = "fixAwaitInSyncFunction"; + const errorCodes = [ + Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ++ Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code + ]; +diff --git a/src/services/codefixes/fixModuleAndTargetOptions.ts b/src/services/codefixes/fixModuleAndTargetOptions.ts +index 9a223fa10..0cc3e489a 100644 +--- a/src/services/codefixes/fixModuleAndTargetOptions.ts ++++ b/src/services/codefixes/fixModuleAndTargetOptions.ts +@@ -20,6 +20,7 @@ import { + registerCodeFix({ + errorCodes: [ + Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ++ Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, + ], + getCodeActions: function getCodeActionsToFixModuleAndTarget(context) {