diff --git a/packages/typescript/enums/symbolFlags.d.ts b/packages/typescript/enums/symbolFlags.d.ts index 144db661698f7..915180ffc7dcc 100644 --- a/packages/typescript/enums/symbolFlags.d.ts +++ b/packages/typescript/enums/symbolFlags.d.ts @@ -34,12 +34,13 @@ export declare enum SymbolFlags { ReplaceableByMethod = 1 << 29, GlobalLookup = 1 << 30, NameProxy = 1 << 30, - All = (1 << 30) - 1, + ErasableEnum = 1 << 31, + All = ((1 << 30) - 1) | ErasableEnum, Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, - Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias, - Namespace = ValueModule | NamespaceModule | Enum, + Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | ErasableEnum, + Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | ErasableEnum, + Namespace = ValueModule | NamespaceModule | Enum | ErasableEnum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, FunctionScopedVariableExcludes = Value & ~FunctionScopedVariable, @@ -61,7 +62,7 @@ export declare enum SymbolFlags { TypeParameterExcludes = Type & ~TypeParameter, TypeAliasExcludes = Type, AliasExcludes = Alias, - ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias, + ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias | ErasableEnum, ExportHasLocal = Function | Class | Enum | ValueModule, BlockScoped = BlockScopedVariable | Class | Enum, PropertyOrAccessor = Property | Accessor, diff --git a/packages/typescript/enums/symbolFlags.js b/packages/typescript/enums/symbolFlags.js index f6829c2112dfd..297f5886f87a2 100644 --- a/packages/typescript/enums/symbolFlags.js +++ b/packages/typescript/enums/symbolFlags.js @@ -34,34 +34,35 @@ export var SymbolFlags; SymbolFlags[SymbolFlags["ReplaceableByMethod"] = 536870912] = "ReplaceableByMethod"; SymbolFlags[SymbolFlags["GlobalLookup"] = 1073741824] = "GlobalLookup"; SymbolFlags[SymbolFlags["NameProxy"] = 1073741824] = "NameProxy"; - SymbolFlags[SymbolFlags["All"] = 1073741823] = "All"; + SymbolFlags[SymbolFlags["ErasableEnum"] = -2147483648] = "ErasableEnum"; + SymbolFlags[SymbolFlags["All"] = -1073741825] = "All"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; - SymbolFlags[SymbolFlags["Value"] = 111551] = "Value"; - SymbolFlags[SymbolFlags["Type"] = 788968] = "Type"; - SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace"; + SymbolFlags[SymbolFlags["Value"] = -2147372097] = "Value"; + SymbolFlags[SymbolFlags["Type"] = -2146694680] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = -2147481728] = "Namespace"; SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; - SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes"; - SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes"; - SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes"; - SymbolFlags[SymbolFlags["PropertyExcludes"] = 13243] = "PropertyExcludes"; - SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes"; - SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes"; - SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes"; - SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes"; - SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; - SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; - SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = -2147372098] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = -2147372097] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = -2147372097] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = -2147470405] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = -2146583553] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = -2147372657] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = -2146584145] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = -2146694776] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = -2146584321] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = -2146583681] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = -2147372913] = "ValueModuleExcludes"; SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; - SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes"; - SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46011] = "GetAccessorExcludes"; - SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78779] = "SetAccessorExcludes"; - SymbolFlags[SymbolFlags["AccessorExcludes"] = 111547] = "AccessorExcludes"; - SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes"; - SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = -2147380289] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = -2147437637] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = -2147404869] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["AccessorExcludes"] = -2147372101] = "AccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = -2146956824] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = -2146694680] = "TypeAliasExcludes"; SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes"; - SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember"; + SymbolFlags[SymbolFlags["ModuleMember"] = -2144860173] = "ModuleMember"; SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped"; SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 7256e47c0da36..b88bb31051441 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2592,7 +2592,7 @@ export class Checker { snapshot: this.snapshotId, project: this.project.handle, name, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: !isNode && location ? (location as DocumentPosition).document : undefined, position: !isNode && location ? (location as DocumentPosition).position : undefined, @@ -2610,7 +2610,7 @@ export class Checker { const data = await this.client.apiRequest("getSymbolsInScope", { snapshot: this.snapshotId, project: this.project.handle, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: isNode ? undefined : (location as DocumentPosition).document, position: isNode ? undefined : (location as DocumentPosition).position, diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5534ffd53e1df..e29feb54db9f2 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4804,7 +4804,7 @@ export class Checker { snapshot: owner.snapshotId, project: owner.project.handle, name, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: !isNode && location ? (location as DocumentPosition).document : undefined, position: !isNode && location ? (location as DocumentPosition).position : undefined, @@ -4819,7 +4819,7 @@ export class Checker { snapshot: owner.snapshotId, project: owner.project.handle, name, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: !isNode && location ? (location as DocumentPosition).document : undefined, position: !isNode && location ? (location as DocumentPosition).position : undefined, @@ -4847,7 +4847,7 @@ export class Checker { const data = owner.client.apiRequest("getSymbolsInScope", { snapshot: owner.snapshotId, project: owner.project.handle, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: isNode ? undefined : (location as DocumentPosition).document, position: isNode ? undefined : (location as DocumentPosition).position, @@ -4860,7 +4860,7 @@ export class Checker { const data = yield* apiRequest("getSymbolsInScope", { snapshot: owner.snapshotId, project: owner.project.handle, - meaning, + meaning: meaning >>> 0, location: isNode ? getNodeRequestHandle(location as Node) : undefined, file: isNode ? undefined : (location as DocumentPosition).document, position: isNode ? undefined : (location as DocumentPosition).position, diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 3f303868a73cc..53b3c84a6fe50 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -8211,6 +8211,27 @@ function f() { `, }; + test("finds erasable enums in value and type scope queries", async () => { + await using api = spawnAPI({ + ...scopeFiles, + "/src/main.ts": `const Local: enum = { A: 1 }; export const E: enum = { A: 1 };`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + for (const meaning of [SymbolFlags.Value, SymbolFlags.Type, SymbolFlags.ErasableEnum]) { + const symbols = await project.checker.getSymbolsInScope(sourceFile, meaning); + const symbol = symbols.find(symbol => symbol.name === "E"); + assert.ok(symbol); + const local = symbols.find(symbol => symbol.name === "Local"); + assert.ok(local); + assert.notStrictEqual(local.flags & SymbolFlags.ErasableEnum, 0); + const resolved = await project.checker.resolveName("E", meaning, sourceFile); + assert.strictEqual(resolved?.name, "E"); + } + }); + test("returns symbols visible at a position", async () => { await using api = spawnAPI(scopeFiles); diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index c57ca53e905bc..7b196366c954e 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -7969,6 +7969,27 @@ function f() { `, }; + test("finds erasable enums in value and type scope queries", () => { + using api = spawnAPI({ + ...scopeFiles, + "/src/main.ts": `const Local: enum = { A: 1 }; export const E: enum = { A: 1 };`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + for (const meaning of [SymbolFlags.Value, SymbolFlags.Type, SymbolFlags.ErasableEnum]) { + const symbols = project.checker.getSymbolsInScope(sourceFile, meaning); + const symbol = symbols.find(symbol => symbol.name === "E"); + assert.ok(symbol); + const local = symbols.find(symbol => symbol.name === "Local"); + assert.ok(local); + assert.notStrictEqual(local.flags & SymbolFlags.ErasableEnum, 0); + const resolved = project.checker.resolveName("E", meaning, sourceFile); + assert.strictEqual(resolved?.name, "E"); + } + }); + test("returns symbols visible at a position", () => { using api = spawnAPI(scopeFiles); diff --git a/tsc/internal/api/enum_values_generated.go b/tsc/internal/api/enum_values_generated.go index 1697a479539a5..28d227adf5638 100644 --- a/tsc/internal/api/enum_values_generated.go +++ b/tsc/internal/api/enum_values_generated.go @@ -60,6 +60,7 @@ func main() { "ReplaceableByMethod": toInt32(ast.SymbolFlagsReplaceableByMethod), "GlobalLookup": toInt32(ast.SymbolFlagsGlobalLookup), "NameProxy": toInt32(ast.SymbolFlagsNameProxy), + "ErasableEnum": toInt32(ast.SymbolFlagsErasableEnum), "All": toInt32(ast.SymbolFlagsAll), "Enum": toInt32(ast.SymbolFlagsEnum), "Variable": toInt32(ast.SymbolFlagsVariable), diff --git a/tsc/internal/ast/symbolflags.go b/tsc/internal/ast/symbolflags.go index ca528c7693ab3..736f7dbd82a64 100644 --- a/tsc/internal/ast/symbolflags.go +++ b/tsc/internal/ast/symbolflags.go @@ -36,15 +36,16 @@ const ( SymbolFlagsModuleExports SymbolFlags = 1 << 27 // Symbol for CommonJS `module` of `module.exports` SymbolFlagsConstEnumOnlyModule SymbolFlags = 1 << 28 // Module contains only const enums or other modules with only const enums SymbolFlagsReplaceableByMethod SymbolFlags = 1 << 29 - SymbolFlagsGlobalLookup SymbolFlags = 1 << 30 // Flag to signal this is a global lookup (internal to NameResolver) - SymbolFlagsNameProxy SymbolFlags = 1 << 30 // Renamed symbol proxy (internal to symbol tables) - SymbolFlagsAll SymbolFlags = 1<<30 - 1 // All flags except SymbolFlagsGlobalLookup/NameProxy + SymbolFlagsGlobalLookup SymbolFlags = 1 << 30 // Flag to signal this is a global lookup (internal to NameResolver) + SymbolFlagsNameProxy SymbolFlags = 1 << 30 // Renamed symbol proxy (internal to symbol tables) + SymbolFlagsErasableEnum SymbolFlags = 1 << 31 // Variable with an associated nominal erasable enum type + SymbolFlagsAll SymbolFlags = (1<<30 - 1) | SymbolFlagsErasableEnum // All flags except SymbolFlagsGlobalLookup/NameProxy SymbolFlagsEnum = SymbolFlagsRegularEnum | SymbolFlagsConstEnum SymbolFlagsVariable = SymbolFlagsFunctionScopedVariable | SymbolFlagsBlockScopedVariable - SymbolFlagsValue = SymbolFlagsVariable | SymbolFlagsProperty | SymbolFlagsEnumMember | SymbolFlagsObjectLiteral | SymbolFlagsFunction | SymbolFlagsClass | SymbolFlagsEnum | SymbolFlagsValueModule | SymbolFlagsMethod | SymbolFlagsGetAccessor | SymbolFlagsSetAccessor - SymbolFlagsType = SymbolFlagsClass | SymbolFlagsInterface | SymbolFlagsEnum | SymbolFlagsEnumMember | SymbolFlagsTypeLiteral | SymbolFlagsTypeParameter | SymbolFlagsTypeAlias - SymbolFlagsNamespace = SymbolFlagsValueModule | SymbolFlagsNamespaceModule | SymbolFlagsEnum + SymbolFlagsValue = SymbolFlagsVariable | SymbolFlagsProperty | SymbolFlagsEnumMember | SymbolFlagsObjectLiteral | SymbolFlagsFunction | SymbolFlagsClass | SymbolFlagsEnum | SymbolFlagsValueModule | SymbolFlagsMethod | SymbolFlagsGetAccessor | SymbolFlagsSetAccessor | SymbolFlagsErasableEnum + SymbolFlagsType = SymbolFlagsClass | SymbolFlagsInterface | SymbolFlagsEnum | SymbolFlagsEnumMember | SymbolFlagsTypeLiteral | SymbolFlagsTypeParameter | SymbolFlagsTypeAlias | SymbolFlagsErasableEnum + SymbolFlagsNamespace = SymbolFlagsValueModule | SymbolFlagsNamespaceModule | SymbolFlagsEnum | SymbolFlagsErasableEnum SymbolFlagsModule = SymbolFlagsValueModule | SymbolFlagsNamespaceModule SymbolFlagsAccessor = SymbolFlagsGetAccessor | SymbolFlagsSetAccessor @@ -73,7 +74,7 @@ const ( SymbolFlagsTypeParameterExcludes = SymbolFlagsType & ^SymbolFlagsTypeParameter SymbolFlagsTypeAliasExcludes = SymbolFlagsType SymbolFlagsAliasExcludes = SymbolFlagsAlias - SymbolFlagsModuleMember = SymbolFlagsVariable | SymbolFlagsFunction | SymbolFlagsClass | SymbolFlagsInterface | SymbolFlagsEnum | SymbolFlagsModule | SymbolFlagsTypeAlias | SymbolFlagsAlias + SymbolFlagsModuleMember = SymbolFlagsVariable | SymbolFlagsFunction | SymbolFlagsClass | SymbolFlagsInterface | SymbolFlagsEnum | SymbolFlagsModule | SymbolFlagsTypeAlias | SymbolFlagsAlias | SymbolFlagsErasableEnum SymbolFlagsExportHasLocal = SymbolFlagsFunction | SymbolFlagsClass | SymbolFlagsEnum | SymbolFlagsValueModule SymbolFlagsBlockScoped = SymbolFlagsBlockScopedVariable | SymbolFlagsClass | SymbolFlagsEnum SymbolFlagsPropertyOrAccessor = SymbolFlagsProperty | SymbolFlagsAccessor diff --git a/tsc/internal/ast/utilities.go b/tsc/internal/ast/utilities.go index f178903372dc2..868bd79765af8 100644 --- a/tsc/internal/ast/utilities.go +++ b/tsc/internal/ast/utilities.go @@ -2330,12 +2330,19 @@ const ( func GetMeaningFromDeclaration(node *Node) SemanticMeaning { switch node.Kind { case KindVariableDeclaration: + if IsErasableEnumDeclaration(node) { + return SemanticMeaningAll + } + return SemanticMeaningValue + case KindPropertyAssignment: + if IsErasableEnumMember(node) { + return SemanticMeaningValue | SemanticMeaningType + } return SemanticMeaningValue case KindParameter, KindBindingElement, KindPropertyDeclaration, KindPropertySignature, - KindPropertyAssignment, KindShorthandPropertyAssignment, KindMethodDeclaration, KindMethodSignature, @@ -4709,3 +4716,53 @@ func IsStringLiteralLikeType(node *Node) bool { return node.Kind == KindLiteralType && IsStringLiteralLike(node.AsLiteralTypeNode().Literal) } + +// IsEnumTypeAnnotation recognizes the contextual enum annotation on a variable declaration. +func IsEnumTypeAnnotation(node *Node) bool { + return node != nil && IsTypeReferenceNode(node) && + IsIdentifier(node.AsTypeReferenceNode().TypeName) && + node.AsTypeReferenceNode().TypeName.Text() == "enum" && node.AsTypeReferenceNode().TypeArguments == nil +} + +func HasEnumTypeAnnotation(node *Node) bool { + return node != nil && IsVariableDeclaration(node) && IsEnumTypeAnnotation(node.Type()) +} + +func GetErasableEnumInitializer(node *Node) *Node { + if !HasEnumTypeAnnotation(node) || !IsIdentifier(node.Name()) || node.Parent == nil || node.Parent.Parent == nil || !IsVariableStatement(node.Parent.Parent) { + return nil + } + initializer := node.Initializer() + if initializer != nil { + initializer = SkipParentheses(initializer) + if IsObjectLiteralExpression(initializer) { + return initializer + } + } + return nil +} + +func IsErasableEnumDeclaration(node *Node) bool { return GetErasableEnumInitializer(node) != nil } + +func GetErasableEnumDeclaration(node *Node) *Node { + if node == nil || !IsObjectLiteralExpression(node) { + return nil + } + declaration := WalkUpParenthesizedExpressions(node.Parent) + if GetErasableEnumInitializer(declaration) == node { + return declaration + } + return nil +} + +func IsErasableEnumInitializer(node *Node) bool { + return GetErasableEnumDeclaration(node) != nil +} + +func IsErasableEnumMember(node *Node) bool { + return node != nil && IsPropertyAssignment(node) && IsErasableEnumInitializer(node.Parent) && !IsComputedPropertyName(node.Name()) && !IsErasableEnumPrototypeSetter(node) +} + +func IsErasableEnumPrototypeSetter(node *Node) bool { + return node != nil && IsPropertyAssignment(node) && IsErasableEnumInitializer(node.Parent) && !IsComputedPropertyName(node.Name()) && GetTextOfPropertyName(node.Name()) == "__proto__" +} diff --git a/tsc/internal/binder/binder.go b/tsc/internal/binder/binder.go index e1058bc33b043..bb9a100959d84 100644 --- a/tsc/internal/binder/binder.go +++ b/tsc/internal/binder/binder.go @@ -659,7 +659,13 @@ func (b *Binder) bind(node *ast.Node) bool { case ast.KindPropertyDeclaration, ast.KindPropertySignature: b.bindPropertyWorker(node) case ast.KindPropertyAssignment, ast.KindShorthandPropertyAssignment: - b.bindPropertyOrMethodOrAccessor(node, ast.SymbolFlagsProperty, ast.SymbolFlagsPropertyExcludes) + if ast.IsErasableEnumMember(node) { + owner := ast.GetErasableEnumDeclaration(node.Parent).Symbol() + member := b.declareSymbol(ast.GetExports(owner, &b.symbolExtraArena), owner, node, ast.SymbolFlagsEnumMember, ast.SymbolFlagsPropertyExcludes&^ast.SymbolFlagsEnumMember) + ast.GetMembers(node.Parent.Symbol(), &b.symbolExtraArena).Set(member.Name(), member) + } else { + b.bindPropertyOrMethodOrAccessor(node, ast.SymbolFlagsProperty, ast.SymbolFlagsPropertyExcludes) + } case ast.KindEnumMember: b.bindPropertyOrMethodOrAccessor(node, ast.SymbolFlagsEnumMember, ast.SymbolFlagsEnumMemberExcludes) case ast.KindCallSignature, ast.KindConstructSignature, ast.KindIndexSignature: @@ -1188,6 +1194,14 @@ func (b *Binder) bindVariableDeclarationOrBindingElement(node *ast.Node) { b.checkStrictModeEvalOrArguments(node, node.Name()) if name := node.Name(); name != nil && !ast.IsBindingPattern(name) { switch { + case ast.IsErasableEnumDeclaration(node): + // Erasable enums retain their variable binding and have a separate nominal type. + excludes := ast.SymbolFlagsValue | ast.SymbolFlagsType + if ast.IsBlockOrCatchScoped(node) { + b.bindBlockScopedDeclaration(node, ast.SymbolFlagsBlockScopedVariable|ast.SymbolFlagsErasableEnum, excludes) + } else { + b.declareSymbolAndAddToSymbolTable(node, ast.SymbolFlagsFunctionScopedVariable|ast.SymbolFlagsErasableEnum, excludes) + } case ast.IsVariableDeclarationInitializedToRequire(node): b.declareSymbolAndAddToSymbolTable(node, ast.SymbolFlagsAlias, ast.SymbolFlagsAliasExcludes) case ast.IsBlockOrCatchScoped(node): diff --git a/tsc/internal/binder/erasable_enum_test.go b/tsc/internal/binder/erasable_enum_test.go new file mode 100644 index 0000000000000..9d3fdb03f57b4 --- /dev/null +++ b/tsc/internal/binder/erasable_enum_test.go @@ -0,0 +1,88 @@ +package binder + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/parser" +) + +func TestErasableEnumSymbols(t *testing.T) { + t.Parallel() + for _, prefix := range []string{"", "export "} { + t.Run(prefix, func(t *testing.T) { + t.Parallel() + file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/main.ts"}, prefix+`const E: enum = { A: 1, B: "b" };`, core.ScriptKindTS) + BindSourceFile(file) + if len(file.Diagnostics()) != 0 || len(file.BindDiagnostics()) != 0 { + t.Fatalf("unexpected diagnostics: parse=%v, bind=%v", file.Diagnostics(), file.BindDiagnostics()) + } + declaration := file.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0] + literal := declaration.Initializer() + symbol := declaration.Symbol() + if symbol == literal.Symbol() || symbol.Flags() != ast.SymbolFlagsBlockScopedVariable|ast.SymbolFlagsErasableEnum || symbol.ValueDeclaration() != declaration { + t.Fatal("the variable must have its own erasable enum symbol") + } + if len(symbol.Declarations()) != 1 || literal.Symbol().Flags() != ast.SymbolFlagsObjectLiteral { + t.Fatal("the initializer must retain its ordinary object symbol") + } + for _, member := range literal.AsObjectLiteralExpression().Properties.Nodes { + if symbol.Exports().Get(member.Name().Text()) != member.Symbol() || member.Symbol().Parent() != symbol || member.Symbol().Flags() != ast.SymbolFlagsEnumMember { + t.Fatalf("member %s was not bound to the enum", member.Name().Text()) + } + } + if prefix != "" && file.Symbol.Exports().Get("E") != symbol { + t.Fatal("the module export must retain the erasable enum declaration symbol") + } + }) + } +} + +func TestErasableEnumCannotMergeValues(t *testing.T) { + t.Parallel() + for _, source := range []string{ + `const E: enum = { A: 1 }; enum E { B = 2 }`, + `enum E { B = 2 } const E: enum = { A: 1 };`, + `const E: enum = { A: 1 }; namespace E { export const B = 2; }`, + `export const E: enum = { A: 1 }; export enum E { B = 2 }`, + } { + t.Run(source, func(t *testing.T) { + t.Parallel() + file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/main.ts"}, source, core.ScriptKindTS) + BindSourceFile(file) + if len(file.Diagnostics()) != 0 { + t.Fatalf("unexpected parse diagnostics: %v", file.Diagnostics()) + } + if len(file.BindDiagnostics()) == 0 { + t.Fatal("expected duplicate declaration diagnostics") + } + }) + } +} + +func TestErasableEnumDuplicatePropertyBinding(t *testing.T) { + t.Parallel() + for _, properties := range []string{ + `A: 1, A: 2`, + `A: 1, ["A"]: 2`, + `["A"]: 1, A: 2`, + `A: 1, A`, + `A, A: 1`, + `A: 1, A() {}`, + } { + t.Run(properties, func(t *testing.T) { + t.Parallel() + file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/main.ts"}, `const A = 1; const E: enum = { `+properties+` };`, core.ScriptKindTS) + BindSourceFile(file) + if len(file.Diagnostics()) != 0 { + t.Fatal(file.Diagnostics()) + } + owner := file.Statements.Nodes[1].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0].Symbol() + member := owner.Exports().Get("A") + if member == nil || member.Parent() != owner || member.Flags() != ast.SymbolFlagsEnumMember { + t.Fatal("an explicit member must retain its erasable enum owner") + } + }) + } +} diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go index 14f8356152d83..8f51363778416 100644 --- a/tsc/internal/checker/checker.go +++ b/tsc/internal/checker/checker.go @@ -713,6 +713,8 @@ type Checker struct { signatureLinks nodeLinkStore[SignatureLinks] symbolNodeLinks nodeLinkStore[SymbolNodeLinks] typeNodeLinks nodeLinkStore[TypeNodeLinks] + erasableEnumLinks core.LinkStore[*ast.Symbol, ErasableEnumLinks] + erasableEnumMemberLinks core.LinkStore[*ast.Node, ErasableEnumMemberLinks] enumMemberLinks core.LinkStore[*ast.Node, EnumMemberLinks] assertionLinks core.LinkStore[*ast.Node, AssertionLinks] arrayLiteralLinks core.LinkStore[*ast.Node, ArrayLiteralLinks] @@ -1281,6 +1283,10 @@ func (c *Checker) getGlobalType(name string, arity int, reportErrors bool) *Type func getGlobalTypeDeclaration(symbol *ast.Symbol) *ast.Declaration { for _, declaration := range symbol.Declarations() { switch declaration.Kind { + case ast.KindVariableDeclaration: + if ast.IsErasableEnumDeclaration(declaration) { + return declaration + } case ast.KindClassDeclaration, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration, ast.KindTypeAliasDeclaration: return declaration } @@ -3080,7 +3086,8 @@ func (c *Checker) checkTypeReferenceNode(node *ast.Node) { } } c.checkSourceElements(node.TypeArguments()) - if !(isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent)) { + if !(isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent)) && + !(ast.IsEnumTypeAnnotation(node) && node.Parent != nil && ast.IsVariableDeclaration(node.Parent)) { c.checkTypeReferenceOrImport(node) } } @@ -5986,6 +5993,10 @@ func (c *Checker) checkVariableDeclaration(node *ast.Node) { defer tr.Push(tracing.PhaseCheck, "checkVariableDeclaration", map[string]any{"kind": node.Kind, "pos": node.Pos(), "end": node.End(), "path": ast.GetSourceFileOfNode(node).FileName()}, false)() } c.checkGrammarVariableDeclaration(node.AsVariableDeclaration()) + if ast.HasEnumTypeAnnotation(node) { + c.checkErasableEnumDeclaration(node) + return + } c.checkVariableLikeDeclaration(node) } @@ -7213,6 +7224,9 @@ func (c *Checker) getDeclarationSpaces(node *ast.Declaration) DeclarationSpaces } return result case ast.KindVariableDeclaration, ast.KindBindingElement, ast.KindFunctionDeclaration, ast.KindImportSpecifier: + if ast.IsErasableEnumDeclaration(node) { + return DeclarationSpacesExportType | DeclarationSpacesExportValue + } return DeclarationSpacesExportValue case ast.KindMethodSignature, ast.KindPropertySignature: return DeclarationSpacesExportType @@ -7983,6 +7997,9 @@ func (c *Checker) checkExpressionWorker(node *ast.Node, checkMode CheckMode) *Ty case ast.KindArrayLiteralExpression: return c.checkArrayLiteral(node, checkMode) case ast.KindObjectLiteralExpression: + if ast.IsErasableEnumInitializer(node) { + return c.checkErasableEnumInitializer(node) + } return c.checkObjectLiteral(node, checkMode) case ast.KindPropertyAccessExpression: return c.checkPropertyAccessExpression(node, checkMode, false /*writeOnly*/) @@ -10720,7 +10737,7 @@ func (c *Checker) checkCollisionsForDeclarationName(node *ast.Node, name *ast.No if node.Flags&ast.NodeFlagsAmbient == 0 { c.checkClassNameCollisionWithObject(name) } - } else if ast.IsEnumDeclaration(node) { + } else if ast.IsEnumDeclaration(node) || ast.IsErasableEnumDeclaration(node) { c.checkTypeNameIsReserved(name, diagnostics.Enum_name_cannot_be_0) } } @@ -13942,7 +13959,7 @@ func (c *Checker) isValidConstAssertionArgument(node *ast.Node) bool { if ast.IsEntityNameExpression(expr) { symbol = c.resolveEntityName(expr, ast.SymbolFlagsValue, true /*ignoreErrors*/, false, nil) } - return symbol != nil && symbol.Flags()&ast.SymbolFlagsEnum != 0 + return symbol != nil && symbol.Flags()&(ast.SymbolFlagsEnum|ast.SymbolFlagsErasableEnum) != 0 } return false } @@ -14516,6 +14533,8 @@ func (c *Checker) reportMergeSymbolError(target *ast.Symbol, source *ast.Symbol) isEitherBlockScoped := target.Flags()&ast.SymbolFlagsBlockScopedVariable != 0 || source.Flags()&ast.SymbolFlagsBlockScopedVariable != 0 var message *diagnostics.Message switch { + case (target.Flags()|source.Flags())&ast.SymbolFlagsErasableEnum != 0: + message = diagnostics.Duplicate_identifier_0 case isEitherEnum: message = diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations case isEitherBlockScoped: @@ -14602,6 +14621,9 @@ func getExcludedSymbolFlags(flags ast.SymbolFlags) ast.SymbolFlags { if flags&ast.SymbolFlagsProperty != 0 { result |= ast.SymbolFlagsPropertyExcludes } + if flags&ast.SymbolFlagsErasableEnum != 0 { + result |= ast.SymbolFlagsValue | ast.SymbolFlagsType + } if flags&ast.SymbolFlagsEnumMember != 0 { result |= ast.SymbolFlagsEnumMemberExcludes } @@ -17072,6 +17094,9 @@ func (c *Checker) isParameterOfContextSensitiveSignature(symbol *ast.Symbol) boo } func (c *Checker) getTypeOfVariableOrParameterOrPropertyWorker(symbol *ast.Symbol) *Type { + if symbol.Flags()&ast.SymbolFlagsErasableEnum != 0 { + return c.getErasableEnumValueType(symbol) + } // Handle prototype property if symbol.Flags()&ast.SymbolFlagsPrototype != 0 { return c.getTypeOfPrototypeProperty(symbol) @@ -23765,6 +23790,11 @@ func (c *Checker) getTypeFromTypeReference(node *ast.Node) *Type { // handle LS queries on the `const` in `x as const` by resolving to the type of `x` if isConstTypeReference(node) && ast.IsAssertionExpression(node.Parent) { links.resolvedType = c.checkExpressionCached(node.Parent.Expression()) + } else if ast.IsEnumTypeAnnotation(node) && ast.HasEnumTypeAnnotation(node.Parent) { + links.resolvedType = c.errorType + if ast.IsErasableEnumDeclaration(node.Parent) { + links.resolvedType = c.getErasableEnumValueType(c.getSymbolOfDeclaration(node.Parent)) + } } else if t := c.getIntendedTypeFromJSDocTypeReference(node); t != nil { links.resolvedType = t } else { @@ -24470,6 +24500,8 @@ func (c *Checker) getDeclaredTypeOfSymbol(symbol *ast.Symbol) *Type { func (c *Checker) tryGetDeclaredTypeOfSymbol(symbol *ast.Symbol) *Type { switch { + case symbol.Flags()&ast.SymbolFlagsErasableEnum != 0: + return c.getDeclaredTypeOfErasableEnum(symbol) case symbol.Flags()&(ast.SymbolFlagsClass|ast.SymbolFlagsInterface) != 0: return c.getDeclaredTypeOfClassOrInterface(symbol) case symbol.Flags()&ast.SymbolFlagsTypeParameter != 0: @@ -24730,7 +24762,7 @@ func (c *Checker) createComputedEnumType(symbol *ast.Symbol) *Type { func (c *Checker) getDeclaredTypeOfEnumMember(symbol *ast.Symbol) *Type { links := c.declaredTypeLinks.Get(symbol) if !(links.declaredType != nil) { - enumType := c.getDeclaredTypeOfEnum(c.getParentOfSymbol(symbol)) + enumType := c.getDeclaredTypeOfSymbol(c.getParentOfSymbol(symbol)) if links.declaredType == nil { links.declaredType = enumType } @@ -24840,6 +24872,9 @@ func (c *Checker) evaluateEntity(expr *ast.Node, location *ast.Node) evaluator.R } } if symbol.Flags()&ast.SymbolFlagsEnumMember != 0 { + if symbol.Parent().Flags()&ast.SymbolFlagsErasableEnum != 0 { + return c.evaluateErasableEnumMember(symbol, location) + } if location != nil { return c.evaluateEnumMember(expr, symbol, location) } @@ -24859,12 +24894,19 @@ func (c *Checker) evaluateEntity(expr *ast.Node, location *ast.Node) evaluator.R return evaluator.NewResult(nil, false, false, false) case ast.KindElementAccessExpression: root := expr.Expression() - if ast.IsEntityNameExpression(root) && ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression) { + argument := ast.SkipParentheses(expr.AsElementAccessExpression().ArgumentExpression) + if ast.IsEntityNameExpression(root) && ast.IsStringOrNumericLiteralLike(argument) { rootSymbol := c.resolveEntityName(root, ast.SymbolFlagsValue, true /*ignoreErrors*/, false, nil) - if rootSymbol != nil && rootSymbol.Flags()&ast.SymbolFlagsEnum != 0 { - name := expr.AsElementAccessExpression().ArgumentExpression.Text() + if rootSymbol != nil && rootSymbol.Flags()&(ast.SymbolFlagsEnum|ast.SymbolFlagsErasableEnum) != 0 { + if rootSymbol.Flags()&ast.SymbolFlagsErasableEnum == 0 && !ast.IsStringLiteralLike(expr.AsElementAccessExpression().ArgumentExpression) { + return evaluator.NewResult(nil, false, false, false) + } + name := argument.Text() member := rootSymbol.Exports().Get(name) if member != nil { + if member.Parent().Flags()&ast.SymbolFlagsErasableEnum != 0 { + return c.evaluateErasableEnumMember(member, location) + } if location != nil { return c.evaluateEnumMember(expr, member, location) } @@ -32497,6 +32539,9 @@ func (c *Checker) getSymbolAtLocation(node *ast.Node, ignoreErrors bool) *ast.Sy } if ast.IsIdentifier(node) { + if ast.IsEnumTypeAnnotation(parent) && ast.HasEnumTypeAnnotation(parent.Parent) { + return nil + } if isInRightSideOfImportOrExportAssignment(node) { return c.getSymbolOfNameOrPropertyAccessExpression(node) } else if ast.IsBindingElement(parent) && ast.IsObjectBindingPattern(grandParent) && node == parent.PropertyName() { diff --git a/tsc/internal/checker/emitresolver.go b/tsc/internal/checker/emitresolver.go index e4fad5c3f5b1f..391fab80bf759 100644 --- a/tsc/internal/checker/emitresolver.go +++ b/tsc/internal/checker/emitresolver.go @@ -112,6 +112,9 @@ func (r *EmitResolver) GetEnumMemberValue(node *ast.Node) evaluator.Result { r.checkerMu.Lock() defer r.checkerMu.Unlock() + if ast.IsErasableEnumMember(node) { + return r.checker.getErasableEnumMemberValue(node) + } r.checker.computeEnumMemberValues(node.Parent) if !r.checker.enumMemberLinks.Has(node) { return evaluator.NewResult(nil, false, false, false) diff --git a/tsc/internal/checker/erasable_enum_test.go b/tsc/internal/checker/erasable_enum_test.go new file mode 100644 index 0000000000000..607dbf7b94272 --- /dev/null +++ b/tsc/internal/checker/erasable_enum_test.go @@ -0,0 +1,56 @@ +package checker_test + +import ( + "strconv" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/compiler" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/tsoptions" + "github.com/microsoft/TypeScript/tsc/internal/tspath" + "github.com/microsoft/TypeScript/tsc/internal/vfs/vfstest" +) + +func TestErasableEnumCannotMergeAcrossFiles(t *testing.T) { + t.Parallel() + for _, other := range []string{ + `var E: enum = { B: 2 };`, + `enum E { B = 2 }`, + `namespace E { export const B = 2; }`, + } { + for _, reverse := range []bool{false, true} { + t.Run(other+strconv.FormatBool(reverse), func(t *testing.T) { + t.Parallel() + first, second := `var E: enum = { A: 1 };`, other + if reverse { + first, second = second, first + } + fs := vfstest.FromMap(map[string]string{ + "/first.ts": first, + "/second.ts": second, + "/tsconfig.json": `{"compilerOptions":{"noLib":true},"files":["first.ts","second.ts"]}`, + }, tspath.CaseSensitive) + parsed, errors := tsoptions.GetParsedCommandLineOfConfigFile("/tsconfig.json", &core.CompilerOptions{}, nil, tsoptions.NewDefaultParseConfigHost(fs), nil) + if len(errors) != 0 { + t.Fatal(errors) + } + p, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{Config: parsed, Host: compiler.NewCompilerHost(fs, "/", nil, nil, nil)}) + if err != nil { + t.Fatal(err) + } + for _, filename := range []string{"/first.ts", "/second.ts"} { + diagnostics := p.GetSemanticDiagnostics(t.Context(), p.GetSourceFile(tspath.RootedFilePathFromNormalized(filename))) + found := false + for _, diagnostic := range diagnostics { + if diagnostic.Code() == 2300 { + found = true + } + } + if !found { + t.Fatalf("expected duplicate declaration in %s; got %v", filename, diagnostics) + } + } + }) + } + } +} diff --git a/tsc/internal/checker/erasableenums.go b/tsc/internal/checker/erasableenums.go new file mode 100644 index 0000000000000..6d9e538a3d48d --- /dev/null +++ b/tsc/internal/checker/erasableenums.go @@ -0,0 +1,154 @@ +package checker + +import ( + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/diagnostics" + "github.com/microsoft/TypeScript/tsc/internal/evaluator" +) + +// ErasableEnumLinks keeps the ordinary object value separate from its nominal type. +type ErasableEnumLinks struct { + valueType *Type + declaredType *Type + checked bool +} + +type ErasableEnumMemberLinks struct { + value evaluator.Result + computed bool + computing bool +} + +func (c *Checker) checkErasableEnumDeclaration(node *ast.Node) { + if !ast.IsErasableEnumDeclaration(node) { + c.error(node.Type(), diagnostics.An_enum_annotation_requires_a_named_variable_in_a_variable_statement_with_an_object_literal_initializer) + if initializer := node.Initializer(); initializer != nil { + c.checkExpressionCached(initializer) + } + return + } + c.checkVariableLikeDeclaration(node) +} + +func (c *Checker) checkErasableEnumInitializer(node *ast.Node) *Type { + owner := c.getSymbolOfDeclaration(ast.GetErasableEnumDeclaration(node)) + info := c.getErasableEnumTypes(owner) + if info.checked { + return info.valueType + } + info.checked = true + c.checkGrammarObjectLiteralExpression(node.AsObjectLiteralExpression(), false) + for _, property := range node.AsObjectLiteralExpression().Properties.Nodes { + if c.isCanceled() { + break + } + if ast.IsSpreadAssignment(property) { + c.error(property, diagnostics.Spread_assignments_are_not_allowed_in_erasable_enums) + c.checkExpression(property.Expression()) + continue + } + if !ast.IsIdentifier(property.Name()) && !ast.IsStringLiteral(property.Name()) { + c.error(property.Name(), diagnostics.Erasable_enum_member_names_must_be_identifiers_or_string_literals) + } + if ast.IsErasableEnumPrototypeSetter(property) { + c.checkExpression(property.Initializer()) + if ast.SkipParentheses(property.Initializer()).Kind != ast.KindNullKeyword { + c.error(property.Initializer(), diagnostics.An_erasable_enum_prototype_setter_must_have_the_value_null) + } + continue + } + switch property.Kind { + case ast.KindPropertyAssignment: + c.checkPropertyAssignment(property, CheckModeNormal) + case ast.KindShorthandPropertyAssignment: + c.error(property, diagnostics.Erasable_enums_only_allow_property_assignments) + c.checkShorthandPropertyAssignment(property, false, CheckModeNormal) + continue + default: + c.error(property, diagnostics.Erasable_enums_only_allow_property_assignments) + c.checkSourceElement(property) + continue + } + if !ast.IsErasableEnumMember(property) { + continue + } + if c.getErasableEnumMemberValue(property).Value == nil { + c.error(property.Initializer(), diagnostics.Erasable_enum_member_initializers_must_be_constant_expressions) + } + } + return info.valueType +} + +func (c *Checker) getErasableEnumTypes(owner *ast.Symbol) *ErasableEnumLinks { + info := c.erasableEnumLinks.Get(owner) + if info.valueType != nil { + return info + } + info.valueType = c.newAnonymousType(owner, owner.Exports(), nil, nil, nil) + info.declaredType = c.errorType + declaration := owner.ValueDeclaration() + object := ast.GetErasableEnumInitializer(declaration) + if object == nil { + return info + } + var members []*Type + hasMembers := false + for _, property := range object.AsObjectLiteralExpression().Properties.Nodes { + if ast.IsErasableEnumPrototypeSetter(property) { + continue + } + hasMembers = true + if !ast.IsErasableEnumMember(property) { + continue + } + symbol := c.getSymbolOfDeclaration(property) + value := c.getErasableEnumMemberValue(property).Value + memberType := c.errorType + if value != nil { + memberType = c.getFreshTypeOfLiteralType(c.getEnumLiteralType(value, owner, symbol)) + members = append(members, memberType) + } + c.declaredTypeLinks.Get(symbol).declaredType = memberType + c.valueSymbolLinks.Get(symbol).resolvedType = memberType + } + if len(members) == 0 && hasMembers { + return info + } + info.declaredType = c.getUnionTypeEx(members, UnionReductionLiteral, &TypeAlias{symbol: owner}, nil) + if info.declaredType.flags&TypeFlagsUnion != 0 { + info.declaredType.flags |= TypeFlagsEnumLiteral + info.declaredType.symbol = owner + } + return info +} + +func (c *Checker) getErasableEnumValueType(owner *ast.Symbol) *Type { + return c.getErasableEnumTypes(owner).valueType +} + +func (c *Checker) getDeclaredTypeOfErasableEnum(owner *ast.Symbol) *Type { + return c.getErasableEnumTypes(owner).declaredType +} + +func (c *Checker) getErasableEnumMemberValue(property *ast.Node) evaluator.Result { + links := c.erasableEnumMemberLinks.Get(property) + if links.computed || links.computing { + return links.value + } + links.computing = true + initializer := property.Initializer() + if initializer != nil { + links.value = c.evaluate(initializer, property) + } + links.computing = false + links.computed = true + return links.value +} + +func (c *Checker) evaluateErasableEnumMember(symbol *ast.Symbol, location *ast.Node) evaluator.Result { + if location != nil && !c.isBlockScopedNameDeclaredBeforeUse(symbol.Parent().ValueDeclaration(), location) { + return evaluator.Result{} + } + value := c.getErasableEnumMemberValue(symbol.ValueDeclaration()) + return evaluator.NewResult(value.Value, value.IsSyntacticallyString, value.ResolvedOtherFiles, true /*hasExternalReferences*/) +} diff --git a/tsc/internal/checker/grammarchecks.go b/tsc/internal/checker/grammarchecks.go index 7282241c8bcee..dced0bf86dff7 100644 --- a/tsc/internal/checker/grammarchecks.go +++ b/tsc/internal/checker/grammarchecks.go @@ -1921,6 +1921,10 @@ func (c *Checker) checkGrammarProperty(node *ast.Node /*Union[PropertyDeclaratio } func (c *Checker) checkAmbientInitializer(node *ast.Node) bool { + // Erasable enums retain their member values in declaration files. + if ast.IsErasableEnumDeclaration(node) { + return false + } var initializer *ast.Expression var typeNode *ast.TypeNode switch node.Kind { diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index 2d2d01e83affa..644b549711718 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/internal/checker/nodebuilderimpl.go @@ -188,7 +188,7 @@ func (b *NodeBuilderImpl) isExpandableType(t *Type, isAlias bool) bool { return true } if objectFlags&ObjectFlagsAnonymous != 0 && t.symbol != nil && - t.symbol.Flags()&(ast.SymbolFlagsClass|ast.SymbolFlagsEnum|ast.SymbolFlagsValueModule|ast.SymbolFlagsFunction|ast.SymbolFlagsMethod) != 0 { + t.symbol.Flags()&(ast.SymbolFlagsClass|ast.SymbolFlagsEnum|ast.SymbolFlagsErasableEnum|ast.SymbolFlagsValueModule|ast.SymbolFlagsFunction|ast.SymbolFlagsMethod) != 0 { return true } return false @@ -2949,7 +2949,7 @@ func (b *NodeBuilderImpl) shouldEmitTypeOfSymbol(forceExpansion bool, forceClass if forceExpansion { return false, symbol } - nonFunctionResult := symbol.Flags()&ast.SymbolFlagsClass != 0 && !forceClassExpansion && b.ch.getBaseTypeVariableOfClass(symbol) == nil && !(symbol.ValueDeclaration() != nil && ast.IsClassLike(symbol.ValueDeclaration()) && b.ctx.flags&nodebuilder.FlagsWriteClassExpressionAsTypeLiteral != 0 && (!ast.IsClassDeclaration(symbol.ValueDeclaration()) || b.ch.IsSymbolAccessible(symbol, b.ctx.enclosingDeclaration, isInstanceType, false /*shouldComputeAliasesToMakeVisible*/).Accessibility != printer.SymbolAccessibilityAccessible)) || symbol.Flags()&(ast.SymbolFlagsEnum|ast.SymbolFlagsValueModule) != 0 + nonFunctionResult := symbol.Flags()&ast.SymbolFlagsClass != 0 && !forceClassExpansion && b.ch.getBaseTypeVariableOfClass(symbol) == nil && !(symbol.ValueDeclaration() != nil && ast.IsClassLike(symbol.ValueDeclaration()) && b.ctx.flags&nodebuilder.FlagsWriteClassExpressionAsTypeLiteral != 0 && (!ast.IsClassDeclaration(symbol.ValueDeclaration()) || b.ch.IsSymbolAccessible(symbol, b.ctx.enclosingDeclaration, isInstanceType, false /*shouldComputeAliasesToMakeVisible*/).Accessibility != printer.SymbolAccessibilityAccessible)) || symbol.Flags()&(ast.SymbolFlagsEnum|ast.SymbolFlagsErasableEnum|ast.SymbolFlagsValueModule) != 0 if nonFunctionResult { return true, symbol } diff --git a/tsc/internal/diagnostics/diagnosticMessages.generated.json b/tsc/internal/diagnostics/diagnosticMessages.generated.json index 300558dd1c833..ede92ebf76c96 100644 --- a/tsc/internal/diagnostics/diagnosticMessages.generated.json +++ b/tsc/internal/diagnostics/diagnosticMessages.generated.json @@ -1975,6 +1975,12 @@ "This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s__18139": "This relative import path is unsafe to rewrite because it appears not to match the content mapper's 'include', but does after resolution with 'rootDirs' and 'moduleSuffixes'.", "File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_content_mapper_s_include_18140": "File '{0}' has a registered content mapper extension but does not match any content mapper's 'include'.", "Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest_18141": "Content mapper '{0}' must specify 'extensions' in tsconfig or its package manifest.", + "An_erasable_enum_prototype_setter_must_have_the_value_null_18142": "An erasable enum prototype setter must have the value 'null'.", + "Erasable_enum_member_initializers_must_be_constant_expressions_18143": "Erasable enum member initializers must be constant expressions.", + "Spread_assignments_are_not_allowed_in_erasable_enums_18144": "Spread assignments are not allowed in erasable enums.", + "Erasable_enums_only_allow_property_assignments_18145": "Erasable enums only allow property assignments.", + "An_enum_annotation_requires_a_named_variable_in_a_variable_statement_with_an_object_literal_initiali_18146": "An 'enum' annotation requires a named variable in a variable statement with an object literal initializer.", + "Erasable_enum_member_names_must_be_identifiers_or_string_literals_18147": "Erasable enum member names must be identifiers or string literals.", "nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010": "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`.", "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001": "File is a CommonJS module; it may be converted to an ES module.", "This_constructor_function_may_be_converted_to_a_class_declaration_80002": "This constructor function may be converted to a class declaration.", diff --git a/tsc/internal/diagnostics/diagnosticMessages.json b/tsc/internal/diagnostics/diagnosticMessages.json index ecf6595ffd641..cd1ae31f61254 100644 --- a/tsc/internal/diagnostics/diagnosticMessages.json +++ b/tsc/internal/diagnostics/diagnosticMessages.json @@ -9019,5 +9019,29 @@ "File '{0}' has a registered content mapper extension but does not match any content mapper's 'include'.": { "category": "Error", "code": 18140 + }, + "An erasable enum prototype setter must have the value 'null'.": { + "category": "Error", + "code": 18142 + }, + "Erasable enum member initializers must be constant expressions.": { + "category": "Error", + "code": 18143 + }, + "Spread assignments are not allowed in erasable enums.": { + "category": "Error", + "code": 18144 + }, + "Erasable enums only allow property assignments.": { + "category": "Error", + "code": 18145 + }, + "An 'enum' annotation requires a named variable in a variable statement with an object literal initializer.": { + "category": "Error", + "code": 18146 + }, + "Erasable enum member names must be identifiers or string literals.": { + "category": "Error", + "code": 18147 } } diff --git a/tsc/internal/diagnostics/diagnostics_generated.go b/tsc/internal/diagnostics/diagnostics_generated.go index 0d016471319dd..5684ebec70be0 100644 --- a/tsc/internal/diagnostics/diagnostics_generated.go +++ b/tsc/internal/diagnostics/diagnostics_generated.go @@ -3954,6 +3954,18 @@ var File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_cont var Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest = &Message{code: 18141, category: CategoryError, key: "Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest_18141", text: "Content mapper '{0}' must specify 'extensions' in tsconfig or its package manifest."} +var An_erasable_enum_prototype_setter_must_have_the_value_null = &Message{code: 18142, category: CategoryError, key: "An_erasable_enum_prototype_setter_must_have_the_value_null_18142", text: "An erasable enum prototype setter must have the value 'null'."} + +var Erasable_enum_member_initializers_must_be_constant_expressions = &Message{code: 18143, category: CategoryError, key: "Erasable_enum_member_initializers_must_be_constant_expressions_18143", text: "Erasable enum member initializers must be constant expressions."} + +var Spread_assignments_are_not_allowed_in_erasable_enums = &Message{code: 18144, category: CategoryError, key: "Spread_assignments_are_not_allowed_in_erasable_enums_18144", text: "Spread assignments are not allowed in erasable enums."} + +var Erasable_enums_only_allow_property_assignments = &Message{code: 18145, category: CategoryError, key: "Erasable_enums_only_allow_property_assignments_18145", text: "Erasable enums only allow property assignments."} + +var An_enum_annotation_requires_a_named_variable_in_a_variable_statement_with_an_object_literal_initializer = &Message{code: 18146, category: CategoryError, key: "An_enum_annotation_requires_a_named_variable_in_a_variable_statement_with_an_object_literal_initiali_18146", text: "An 'enum' annotation requires a named variable in a variable statement with an object literal initializer."} + +var Erasable_enum_member_names_must_be_identifiers_or_string_literals = &Message{code: 18147, category: CategoryError, key: "Erasable_enum_member_names_must_be_identifiers_or_string_literals_18147", text: "Erasable enum member names must be identifiers or string literals."} + var X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler = &Message{code: 69010, category: CategoryMessage, key: "nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler_69010", text: "`nodenext` if `module` is `nodenext`; `node16` if `module` is `node16` or `node18`; otherwise, `bundler`."} var File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module = &Message{code: 80001, category: CategorySuggestion, key: "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module_80001", text: "File is a CommonJS module; it may be converted to an ES module."} @@ -6471,6 +6483,12 @@ var allMessages = [...]**Message{ &This_relative_import_path_is_unsafe_to_rewrite_because_it_appears_not_to_match_the_content_mapper_s_include_but_does_after_resolution_with_rootDirs_and_moduleSuffixes, &File_0_has_a_registered_content_mapper_extension_but_does_not_match_any_content_mapper_s_include, &Content_mapper_0_must_specify_extensions_in_tsconfig_or_its_package_manifest, + &An_erasable_enum_prototype_setter_must_have_the_value_null, + &Erasable_enum_member_initializers_must_be_constant_expressions, + &Spread_assignments_are_not_allowed_in_erasable_enums, + &Erasable_enums_only_allow_property_assignments, + &An_enum_annotation_requires_a_named_variable_in_a_variable_statement_with_an_object_literal_initializer, + &Erasable_enum_member_names_must_be_identifiers_or_string_literals, &X_nodenext_if_module_is_nodenext_node16_if_module_is_node16_or_node18_otherwise_bundler, &File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module, &This_constructor_function_may_be_converted_to_a_class_declaration, diff --git a/tsc/internal/ls/erasable_enum_test.go b/tsc/internal/ls/erasable_enum_test.go new file mode 100644 index 0000000000000..2a96a712a33f1 --- /dev/null +++ b/tsc/internal/ls/erasable_enum_test.go @@ -0,0 +1,67 @@ +package ls + +import ( + "fmt" + "slices" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/bundled" + "github.com/microsoft/TypeScript/tsc/internal/compiler" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" + "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" + "github.com/microsoft/TypeScript/tsc/internal/tsoptions" + "github.com/microsoft/TypeScript/tsc/internal/tspath" + "github.com/microsoft/TypeScript/tsc/internal/vfs/vfstest" + "gotest.tools/v3/assert" +) + +func TestErasableEnumReferencesAcrossMeanings(t *testing.T) { + t.Parallel() + for _, prefix := range []string{"", "export "} { + t.Run(prefix, func(t *testing.T) { + t.Parallel() + content := prefix + `const E: enum = { A: 1, B: 2 }; +const value: E = E.A; +let member: E.A = E.A;` + fs := bundled.WrapFS(vfstest.FromMap(map[string]string{ + "/repro.ts": content, + "/tsconfig.json": `{"compilerOptions":{"strict":true},"files":["repro.ts"]}`, + }, tspath.CaseSensitive)) + config, errors := tsoptions.GetParsedCommandLineOfConfigFile("/tsconfig.json", &core.CompilerOptions{}, nil, tsoptions.NewDefaultParseConfigHost(fs), nil) + assert.Equal(t, len(errors), 0) + program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{Config: config, Host: compiler.NewCompilerHost(fs, bundled.LibPath(), nil, nil, nil)}) + assert.NilError(t, err) + file := program.GetSourceFile("/repro.ts") + assert.Equal(t, len(program.GetSemanticDiagnostics(t.Context(), file)), 0) + converters := lsconv.NewConverters(lsproto.PositionEncodingKindUTF8, func(_ tspath.RootedFilePath) *lsconv.LSPLineMap { + return lsconv.ComputeLSPLineStarts(content) + }) + service := &LanguageService{program: program, converters: converters} + for _, name := range []rune{'E', 'A'} { + var want []int + for offset, character := range content { + if character == name { + want = append(want, offset) + } + } + for _, offset := range want { + t.Run(fmt.Sprintf("%c/%d", name, offset), func(t *testing.T) { + position, _ := converters.ToLSPPosition(file, core.TextPos(offset)) + data, ok := service.provideSymbolsAndEntries(t.Context(), "file:///repro.ts", position, false /*isRename*/, false /*implementations*/) + assert.Assert(t, ok) + var got []int + for _, symbol := range data.SymbolsAndEntries { + for _, reference := range symbol.references { + assert.Assert(t, reference.node != nil) + got = append(got, reference.node.End()-1) + } + } + slices.Sort(got) + assert.DeepEqual(t, got, want) + }) + } + } + }) + } +} diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index f8a73f0f1eabb..6fbc003dcc0ea 100644 --- a/tsc/internal/ls/utilities.go +++ b/tsc/internal/ls/utilities.go @@ -826,7 +826,7 @@ func getMeaningFromLocation(node *ast.Node) ast.SemanticMeaning { } return ast.SemanticMeaningNamespace case ast.IsDeclarationName(node): - return getMeaningFromDeclaration(parent) + return ast.GetMeaningFromDeclaration(parent) case ast.IsEntityName(node) && ast.IsJSDocNameReferenceContext(node): return ast.SemanticMeaningAll case isTypeReference(node): @@ -843,41 +843,6 @@ func getMeaningFromLocation(node *ast.Node) ast.SemanticMeaning { } } -func getMeaningFromDeclaration(node *ast.Node) ast.SemanticMeaning { - switch node.Kind { - case ast.KindVariableDeclaration, ast.KindParameter, ast.KindBindingElement, - ast.KindPropertyDeclaration, ast.KindPropertySignature, ast.KindPropertyAssignment, ast.KindShorthandPropertyAssignment, - ast.KindMethodDeclaration, ast.KindMethodSignature, ast.KindConstructor, ast.KindGetAccessor, ast.KindSetAccessor, - ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction, ast.KindCatchClause, ast.KindJsxAttribute: - return ast.SemanticMeaningValue - - case ast.KindTypeParameter, ast.KindInterfaceDeclaration, ast.KindTypeAliasDeclaration, ast.KindJSTypeAliasDeclaration, ast.KindTypeLiteral: - return ast.SemanticMeaningType - - case ast.KindEnumMember, ast.KindClassDeclaration: - return ast.SemanticMeaningValue | ast.SemanticMeaningType - - case ast.KindModuleDeclaration: - if ast.IsAmbientModule(node) { - return ast.SemanticMeaningNamespace | ast.SemanticMeaningValue - } else if ast.GetModuleInstanceState(node) == ast.ModuleInstanceStateInstantiated { - return ast.SemanticMeaningNamespace | ast.SemanticMeaningValue - } else { - return ast.SemanticMeaningNamespace - } - - case ast.KindEnumDeclaration, ast.KindNamedImports, ast.KindImportSpecifier, ast.KindImportEqualsDeclaration, ast.KindImportDeclaration, - ast.KindJSImportDeclaration, ast.KindExportAssignment, ast.KindExportDeclaration: - return ast.SemanticMeaningAll - - // An external module can be a Value - case ast.KindSourceFile: - return ast.SemanticMeaningNamespace | ast.SemanticMeaningValue - } - - return ast.SemanticMeaningAll -} - func getIntersectingMeaningFromDeclarations(node *ast.Node, symbol *ast.Symbol, defaultMeaning ast.SemanticMeaning) ast.SemanticMeaning { if node == nil { return defaultMeaning @@ -894,7 +859,7 @@ func getIntersectingMeaningFromDeclarations(node *ast.Node, symbol *ast.Symbol, // !!! TODO check if the port is correct and the for loop is needed iteration := func(m ast.SemanticMeaning) ast.SemanticMeaning { for _, declaration := range declarations { - declarationMeaning := getMeaningFromDeclaration(declaration) + declarationMeaning := ast.GetMeaningFromDeclaration(declaration) if declarationMeaning&m != 0 { m |= declarationMeaning diff --git a/tsc/internal/parser/erasable_enum_test.go b/tsc/internal/parser/erasable_enum_test.go new file mode 100644 index 0000000000000..e6ceb7899623b --- /dev/null +++ b/tsc/internal/parser/erasable_enum_test.go @@ -0,0 +1,42 @@ +package parser_test + +import ( + "slices" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/ast" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/parser" + "gotest.tools/v3/assert" +) + +func TestErasableEnumUsesOrdinaryObjectSyntax(t *testing.T) { + t.Parallel() + for _, initializer := range []string{ + `{ A: 1, B: "b", C: A + 1, }`, + `{ ...other, ["foo"]: 1, method() {}, get value() { return 1; }, A }`, + `{ A: true, B: () => 1, C: f() }`, + `({ A: 1 })`, + } { + t.Run(initializer, func(t *testing.T) { + t.Parallel() + var shapes [][]ast.Kind + for _, annotation := range []string{"", ": enum"} { + file := parser.ParseSourceFile(ast.SourceFileParseOptions{FileName: "/enum.ts"}, "const E"+annotation+" = "+initializer+";", core.ScriptKindTS) + assert.Equal(t, len(file.Diagnostics()), 0) + declaration := file.Statements.Nodes[0].AsVariableStatement().DeclarationList.AsVariableDeclarationList().Declarations.Nodes[0] + object := ast.SkipParentheses(declaration.Initializer()) + assert.Equal(t, object.Kind, ast.KindObjectLiteralExpression) + var kinds []ast.Kind + var visit ast.Visitor + visit = func(node *ast.Node) bool { + kinds = append(kinds, node.Kind) + return node.ForEachChild(visit) + } + visit(object) + shapes = append(shapes, kinds) + } + assert.Assert(t, slices.Equal(shapes[0], shapes[1])) + }) + } +} diff --git a/tsc/internal/transformers/declarations/transform.go b/tsc/internal/transformers/declarations/transform.go index 986d56b7b8f28..272d9023a0f62 100644 --- a/tsc/internal/transformers/declarations/transform.go +++ b/tsc/internal/transformers/declarations/transform.go @@ -835,6 +835,16 @@ func (tx *DeclarationTransformer) transformTypeParameterDeclaration(input *ast.T } func (tx *DeclarationTransformer) transformVariableDeclaration(input *ast.VariableDeclaration) *ast.Node { + if ast.IsErasableEnumDeclaration(input.AsNode()) { + literal := ast.GetErasableEnumInitializer(input.AsNode()).AsObjectLiteralExpression() + return tx.Factory().UpdateVariableDeclaration( + input, + tx.bindingNameVisitor.VisitNode(input.Name()), + nil, + input.Type, + tx.Factory().UpdateObjectLiteralExpression(literal, tx.transformErasableEnumProperties(literal.Properties), literal.MultiLine), + ) + } if tx.state.currentSourceFile.CommonJSModuleIndicator != nil && ast.IsVariableDeclarationInitializedToRequire(input.AsNode()) { return tx.transformCjsRequireVariableDeclaration(input) } @@ -2315,31 +2325,7 @@ func (tx *DeclarationTransformer) transformEnumDeclaration(input *ast.EnumDeclar tx.state.addDiagnostic(createDiagnosticForNode(m, diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations)) } - var newInitializer *ast.Node - switch value := enumValue.Value.(type) { - case jsnum.Number: - if value.IsInf() { - if value > 0 { - newInitializer = tx.Factory().NewIdentifier("Infinity") - } else { - newInitializer = tx.Factory().NewPrefixUnaryExpression(ast.KindMinusToken, tx.Factory().NewIdentifier("Infinity")) - } - } else if value.IsNaN() { - newInitializer = tx.Factory().NewIdentifier("NaN") - } else if value >= 0 { - newInitializer = tx.Factory().NewNumericLiteral(value.String(), ast.TokenFlagsNone) - } else { - newInitializer = tx.Factory().NewPrefixUnaryExpression( - ast.KindMinusToken, - tx.Factory().NewNumericLiteral((-value).String(), ast.TokenFlagsNone), - ) - } - case string: - newInitializer = tx.Factory().NewStringLiteral(value, ast.TokenFlagsNone) - default: - // nil - newInitializer = nil - } + newInitializer := tx.enumConstantInitializer(enumValue.Value) result := tx.Factory().UpdateEnumMember(m.AsEnumMember(), m.Name(), newInitializer) tx.preserveJsDoc(result, m) return result @@ -2347,6 +2333,60 @@ func (tx *DeclarationTransformer) transformEnumDeclaration(input *ast.EnumDeclar ) } +func (tx *DeclarationTransformer) transformErasableEnumProperties(properties *ast.NodeList) *ast.NodeList { + return tx.Factory().NewNodeList(core.MapNonNil(properties.Nodes, func(property *ast.Node) *ast.Node { + if ast.IsErasableEnumPrototypeSetter(property) { + return property + } + if !ast.IsErasableEnumMember(property) || tx.shouldStripInternal(property) { + return nil + } + value := tx.resolver.GetEnumMemberValue(property) + if tx.state.isolatedDeclarations && (value.Value == nil || value.HasExternalReferences) { + tx.state.addDiagnostic(createDiagnosticForNode(property, diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations)) + } + initializer := tx.enumConstantInitializer(value.Value) + if initializer == nil { + return nil + } + result := tx.Factory().NewPropertyAssignment(nil, property.Name(), nil, nil, initializer) + result.Loc = property.Loc + tx.EmitContext().SetOriginal(result, property) + tx.preserveJsDoc(result, property) + return result + })) +} + +func (tx *DeclarationTransformer) enumConstantInitializer(input any) *ast.Node { + var newInitializer *ast.Node + switch value := input.(type) { + case jsnum.Number: + if value.IsInf() { + if value > 0 { + newInitializer = tx.Factory().NewIdentifier("Infinity") + } else { + newInitializer = tx.Factory().NewPrefixUnaryExpression(ast.KindMinusToken, tx.Factory().NewIdentifier("Infinity")) + } + } else if value.IsNaN() { + newInitializer = tx.Factory().NewIdentifier("NaN") + } else if value >= 0 { + newInitializer = tx.Factory().NewNumericLiteral(value.String(), ast.TokenFlagsNone) + } else { + newInitializer = tx.Factory().NewPrefixUnaryExpression( + ast.KindMinusToken, + tx.Factory().NewNumericLiteral((-value).String(), ast.TokenFlagsNone), + ) + } + case string: + newInitializer = tx.Factory().NewStringLiteral(value, ast.TokenFlagsNone) + default: + // nil + newInitializer = nil + } + + return newInitializer +} + func (tx *DeclarationTransformer) ensureModifiers(node *ast.Node) *ast.ModifierList { currentFlags := ast.GetCombinedModifierFlags(tx.EmitContext().ParseNode(node)) & ast.ModifierFlagsAll newFlags := tx.ensureModifierFlags(node) diff --git a/tsc/internal/transpile/erasable_enum_test.go b/tsc/internal/transpile/erasable_enum_test.go new file mode 100644 index 0000000000000..92bddc44a232d --- /dev/null +++ b/tsc/internal/transpile/erasable_enum_test.go @@ -0,0 +1,109 @@ +package transpile + +import ( + "strings" + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/compiler" + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/tsoptions" + "github.com/microsoft/TypeScript/tsc/internal/tspath" + "github.com/microsoft/TypeScript/tsc/internal/vfs/vfstest" +) + +func TestEnumAnnotationErasesWithOrdinaryObjectSyntax(t *testing.T) { + t.Parallel() + input := `const E: enum = { __proto__: {}, ...other, ["foo"]: 1, 1: "one", method() {}, get value() { return 1; }, shorthand, Value: true };` + options := Options{ + CompilerOptions: &core.CompilerOptions{Target: core.ScriptTargetESNext, ErasableSyntaxOnly: core.TSTrue}, + ReportDiagnostics: true, + } + result := TranspileModule(t.Context(), input, options) + ordinary := TranspileModule(t.Context(), strings.Replace(input, ": enum", "", 1), options) + if len(result.Diagnostics) != 0 || len(ordinary.Diagnostics) != 0 { + t.Fatalf("unexpected diagnostics: annotated=%v, ordinary=%v", result.Diagnostics, ordinary.Diagnostics) + } + if result.OutputText != ordinary.OutputText { + t.Fatalf("enum annotation changed runtime output:\n%s\nordinary object:\n%s", result.OutputText, ordinary.OutputText) + } +} + +func TestErasableEnumDeclarationRoundTrip(t *testing.T) { + t.Parallel() + input := `const Local: enum = { Value: 1 }; +export const alias: typeof Local = Local; +export const E: enum = (({ __proto__: null, A: 1, B: "b", Shifted: 1 << 2 }));` + result := TranspileDeclaration(t.Context(), input, Options{}) + if len(result.Diagnostics) != 0 { + t.Fatal(result.Diagnostics) + } + fs := vfstest.FromMap(map[string]string{ + "/enum.d.ts": result.OutputText, + "/consumer.ts": `import { E, alias } from "./enum"; +let local: typeof alias.Value = alias.Value; +let value: E = E.A; +value = E.B; +let member: E.Shifted = 4; +E[1];`, + "/tsconfig.json": `{"compilerOptions":{"noLib":true,"strict":true},"files":["consumer.ts","enum.d.ts"]}`, + }, tspath.CaseSensitive) + config, errors := tsoptions.GetParsedCommandLineOfConfigFile("/tsconfig.json", &core.CompilerOptions{}, nil, tsoptions.NewDefaultParseConfigHost(fs), nil) + if len(errors) != 0 { + t.Fatal(errors) + } + program, err := compiler.NewProgram(t.Context(), compiler.ProgramOptions{Config: config, Host: compiler.NewCompilerHost(fs, "/", nil, nil, nil)}) + if err != nil { + t.Fatal(err) + } + for _, filename := range []tspath.RootedFilePath{"/enum.d.ts", "/consumer.ts"} { + file := program.GetSourceFile(filename) + if diagnostics := program.GetSyntacticDiagnostics(t.Context(), file); len(diagnostics) != 0 { + t.Fatalf("%s syntax: %v", filename, diagnostics) + } + diagnostics := program.GetSemanticDiagnostics(t.Context(), file) + if filename == "/enum.d.ts" { + if len(diagnostics) != 0 { + t.Fatalf("declaration diagnostics: %v\n%s", diagnostics, result.OutputText) + } + } else if len(diagnostics) != 1 || diagnostics[0].Code() != 7053 { + t.Fatalf("expected only numeric index diagnostic 7053, got %v\n%s", diagnostics, result.OutputText) + } + } +} + +func TestErasableEnumIsolatedDeclarationReferences(t *testing.T) { + t.Parallel() + input := `import { imported } from "./values"; +const local = 1; +export const E: enum = { Local: local, Imported: imported };` + result := TranspileDeclaration(t.Context(), input, Options{}) + if len(result.Diagnostics) != 2 { + t.Fatalf("expected isolated declaration errors for both references, got %v\n%s", result.Diagnostics, result.OutputText) + } + for _, diagnostic := range result.Diagnostics { + if diagnostic.Code() != 9020 { + t.Fatalf("expected isolated declaration diagnostic 9020, got %v", diagnostic) + } + } +} + +func TestErasableEnumExportReferences(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + input string + module core.ModuleKind + want string + }{ + {"commonjs", `export const E: enum = { A: 1 }; export const x = E;`, core.ModuleKindCommonJS, "exports.x = exports.E;"}, + {"namespace", `namespace N { export const E: enum = { A: 1 }; export const x = E; }`, core.ModuleKindESNext, "N.x = N.E;"}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + result := TranspileModule(t.Context(), test.input, Options{CompilerOptions: &core.CompilerOptions{Target: core.ScriptTargetESNext, Module: test.module}}) + if !strings.Contains(result.OutputText, test.want) { + t.Fatalf("output missing %q:\n%s", test.want, result.OutputText) + } + }) + } +} diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.errors.txt b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.errors.txt new file mode 100644 index 0000000000000..61b306c4a2892 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.errors.txt @@ -0,0 +1,60 @@ +erasableEnumBasics.ts(14,1): error TS2322: Type 'E.Flag' is not assignable to type 'E.Int'. +erasableEnumBasics.ts(18,1): error TS2322: Type '4' is not assignable to type 'E'. +erasableEnumBasics.ts(21,1): error TS2322: Type '"exists"' is not assignable to type 'E'. +erasableEnumBasics.ts(22,1): error TS2322: Type '"string"' is not assignable to type 'E'. +erasableEnumBasics.ts(24,1): error TS2322: Type 'Other.String' is not assignable to type 'E'. +erasableEnumBasics.ts(26,1): error TS2322: Type '"string"' is not assignable to type 'Other.String'. +erasableEnumBasics.ts(27,1): error TS2322: Type 'E.String' is not assignable to type 'Other.String'. +erasableEnumBasics.ts(28,1): error TS2322: Type 'undefined' is not assignable to type 'E'. + + +==== erasableEnumBasics.ts (8 errors) ==== + const existingValue = "exists"; + const E: enum = { + Existing: existingValue, + Int: 1, + String: "string", + Flag: 8, + }; + + // Members are assignable to their enum type and their own member type. + let value: E = E.Existing; + value = E.Int; + value = E.String; + let intMember: E.Int = E.Int; + intMember = E.Flag; // error: a different known member. + ~~~~~~~~~ +!!! error TS2322: Type 'E.Flag' is not assignable to type 'E.Int'. + + // Matching numeric literals are accepted, but other known literals are rejected. + value = 1; + value = 4; // error + ~~~~~ +!!! error TS2322: Type '4' is not assignable to type 'E'. + + // String members retain nominal types, including values from constant references. + value = "exists"; // error + ~~~~~ +!!! error TS2322: Type '"exists"' is not assignable to type 'E'. + value = "string"; // error + ~~~~~ +!!! error TS2322: Type '"string"' is not assignable to type 'E'. + const Other: enum = { String: "string" }; + value = Other.String; // error: members from different enums are incompatible. + ~~~~~ +!!! error TS2322: Type 'Other.String' is not assignable to type 'E'. + let other: Other = Other.String; + other = "string"; // error: a single-member enum is also nominal. + ~~~~~ +!!! error TS2322: Type '"string"' is not assignable to type 'Other.String'. + other = E.String; // error + ~~~~~ +!!! error TS2322: Type 'E.String' is not assignable to type 'Other.String'. + value = undefined; // error + ~~~~~ +!!! error TS2322: Type 'undefined' is not assignable to type 'E'. + + // Number expressions retain TypeScript's numeric enum compatibility. + value = E.Int | E.Flag; + intMember = E.Int | E.Flag; + \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.js b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.js new file mode 100644 index 0000000000000..3479dbee41f0f --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.js @@ -0,0 +1,67 @@ +//// [tests/cases/compiler/erasableEnumBasics.ts] //// + +//// [erasableEnumBasics.ts] +const existingValue = "exists"; +const E: enum = { + Existing: existingValue, + Int: 1, + String: "string", + Flag: 8, +}; + +// Members are assignable to their enum type and their own member type. +let value: E = E.Existing; +value = E.Int; +value = E.String; +let intMember: E.Int = E.Int; +intMember = E.Flag; // error: a different known member. + +// Matching numeric literals are accepted, but other known literals are rejected. +value = 1; +value = 4; // error + +// String members retain nominal types, including values from constant references. +value = "exists"; // error +value = "string"; // error +const Other: enum = { String: "string" }; +value = Other.String; // error: members from different enums are incompatible. +let other: Other = Other.String; +other = "string"; // error: a single-member enum is also nominal. +other = E.String; // error +value = undefined; // error + +// Number expressions retain TypeScript's numeric enum compatibility. +value = E.Int | E.Flag; +intMember = E.Int | E.Flag; + + +//// [erasableEnumBasics.js] +"use strict"; +const existingValue = "exists"; +const E = { + Existing: existingValue, + Int: 1, + String: "string", + Flag: 8, +}; +// Members are assignable to their enum type and their own member type. +let value = E.Existing; +value = E.Int; +value = E.String; +let intMember = E.Int; +intMember = E.Flag; // error: a different known member. +// Matching numeric literals are accepted, but other known literals are rejected. +value = 1; +value = 4; // error +// String members retain nominal types, including values from constant references. +value = "exists"; // error +value = "string"; // error +const Other = { String: "string" }; +value = Other.String; // error: members from different enums are incompatible. +let other = Other.String; +other = "string"; // error: a single-member enum is also nominal. +other = E.String; // error +value = undefined; // error +// Number expressions retain TypeScript's numeric enum compatibility. +value = E.Int | E.Flag; +intMember = E.Int | E.Flag; diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.symbols new file mode 100644 index 0000000000000..d40dfc0e6c50e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.symbols @@ -0,0 +1,121 @@ +//// [tests/cases/compiler/erasableEnumBasics.ts] //// + +=== erasableEnumBasics.ts === +const existingValue = "exists"; +>existingValue : Symbol(existingValue, Decl(erasableEnumBasics.ts, 0, 5)) + +const E: enum = { +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) + + Existing: existingValue, +>Existing : Symbol(E.Existing, Decl(erasableEnumBasics.ts, 1, 17)) +>existingValue : Symbol(existingValue, Decl(erasableEnumBasics.ts, 0, 5)) + + Int: 1, +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) + + String: "string", +>String : Symbol(E.String, Decl(erasableEnumBasics.ts, 3, 11)) + + Flag: 8, +>Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) + +}; + +// Members are assignable to their enum type and their own member type. +let value: E = E.Existing; +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>E.Existing : Symbol(E.Existing, Decl(erasableEnumBasics.ts, 1, 17)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Existing : Symbol(E.Existing, Decl(erasableEnumBasics.ts, 1, 17)) + +value = E.Int; +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>E.Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) + +value = E.String; +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>E.String : Symbol(E.String, Decl(erasableEnumBasics.ts, 3, 11)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>String : Symbol(E.String, Decl(erasableEnumBasics.ts, 3, 11)) + +let intMember: E.Int = E.Int; +>intMember : Symbol(intMember, Decl(erasableEnumBasics.ts, 12, 3)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E.Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) + +intMember = E.Flag; // error: a different known member. +>intMember : Symbol(intMember, Decl(erasableEnumBasics.ts, 12, 3)) +>E.Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) + +// Matching numeric literals are accepted, but other known literals are rejected. +value = 1; +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) + +value = 4; // error +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) + +// String members retain nominal types, including values from constant references. +value = "exists"; // error +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) + +value = "string"; // error +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) + +const Other: enum = { String: "string" }; +>Other : Symbol(Other, Decl(erasableEnumBasics.ts, 22, 5)) +>String : Symbol(Other.String, Decl(erasableEnumBasics.ts, 22, 21)) + +value = Other.String; // error: members from different enums are incompatible. +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>Other.String : Symbol(Other.String, Decl(erasableEnumBasics.ts, 22, 21)) +>Other : Symbol(Other, Decl(erasableEnumBasics.ts, 22, 5)) +>String : Symbol(Other.String, Decl(erasableEnumBasics.ts, 22, 21)) + +let other: Other = Other.String; +>other : Symbol(other, Decl(erasableEnumBasics.ts, 24, 3)) +>Other : Symbol(Other, Decl(erasableEnumBasics.ts, 22, 5)) +>Other.String : Symbol(Other.String, Decl(erasableEnumBasics.ts, 22, 21)) +>Other : Symbol(Other, Decl(erasableEnumBasics.ts, 22, 5)) +>String : Symbol(Other.String, Decl(erasableEnumBasics.ts, 22, 21)) + +other = "string"; // error: a single-member enum is also nominal. +>other : Symbol(other, Decl(erasableEnumBasics.ts, 24, 3)) + +other = E.String; // error +>other : Symbol(other, Decl(erasableEnumBasics.ts, 24, 3)) +>E.String : Symbol(E.String, Decl(erasableEnumBasics.ts, 3, 11)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>String : Symbol(E.String, Decl(erasableEnumBasics.ts, 3, 11)) + +value = undefined; // error +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>undefined : Symbol(undefined) + +// Number expressions retain TypeScript's numeric enum compatibility. +value = E.Int | E.Flag; +>value : Symbol(value, Decl(erasableEnumBasics.ts, 9, 3)) +>E.Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E.Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) + +intMember = E.Int | E.Flag; +>intMember : Symbol(intMember, Decl(erasableEnumBasics.ts, 12, 3)) +>E.Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Int : Symbol(E.Int, Decl(erasableEnumBasics.ts, 2, 28)) +>E.Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) +>E : Symbol(E, Decl(erasableEnumBasics.ts, 1, 5)) +>Flag : Symbol(E.Flag, Decl(erasableEnumBasics.ts, 4, 21)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.types b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.types new file mode 100644 index 0000000000000..77ba57a958f70 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumBasics.types @@ -0,0 +1,145 @@ +//// [tests/cases/compiler/erasableEnumBasics.ts] //// + +=== erasableEnumBasics.ts === +const existingValue = "exists"; +>existingValue : "exists" +>"exists" : "exists" + +const E: enum = { +>E : typeof E +>{ Existing: existingValue, Int: 1, String: "string", Flag: 8,} : typeof E + + Existing: existingValue, +>Existing : E.Existing +>existingValue : "exists" + + Int: 1, +>Int : E.Int +>1 : 1 + + String: "string", +>String : E.String +>"string" : "string" + + Flag: 8, +>Flag : E.Flag +>8 : 8 + +}; + +// Members are assignable to their enum type and their own member type. +let value: E = E.Existing; +>value : E +>E.Existing : E.Existing +>E : typeof E +>Existing : E.Existing + +value = E.Int; +>value = E.Int : E.Int +>value : E +>E.Int : E.Int +>E : typeof E +>Int : E.Int + +value = E.String; +>value = E.String : E.String +>value : E +>E.String : E.String +>E : typeof E +>String : E.String + +let intMember: E.Int = E.Int; +>intMember : E.Int +>E : any +>E.Int : E.Int +>E : typeof E +>Int : E.Int + +intMember = E.Flag; // error: a different known member. +>intMember = E.Flag : E.Flag +>intMember : E.Int +>E.Flag : E.Flag +>E : typeof E +>Flag : E.Flag + +// Matching numeric literals are accepted, but other known literals are rejected. +value = 1; +>value = 1 : 1 +>value : E +>1 : 1 + +value = 4; // error +>value = 4 : 4 +>value : E +>4 : 4 + +// String members retain nominal types, including values from constant references. +value = "exists"; // error +>value = "exists" : "exists" +>value : E +>"exists" : "exists" + +value = "string"; // error +>value = "string" : "string" +>value : E +>"string" : "string" + +const Other: enum = { String: "string" }; +>Other : typeof Other +>{ String: "string" } : typeof Other +>String : Other +>"string" : "string" + +value = Other.String; // error: members from different enums are incompatible. +>value = Other.String : Other.String +>value : E +>Other.String : Other.String +>Other : typeof Other +>String : Other.String + +let other: Other = Other.String; +>other : Other.String +>Other.String : Other.String +>Other : typeof Other +>String : Other.String + +other = "string"; // error: a single-member enum is also nominal. +>other = "string" : "string" +>other : Other.String +>"string" : "string" + +other = E.String; // error +>other = E.String : E.String +>other : Other.String +>E.String : E.String +>E : typeof E +>String : E.String + +value = undefined; // error +>value = undefined : undefined +>value : E +>undefined : undefined + +// Number expressions retain TypeScript's numeric enum compatibility. +value = E.Int | E.Flag; +>value = E.Int | E.Flag : number +>value : E +>E.Int | E.Flag : number +>E.Int : E.Int +>E : typeof E +>Int : E.Int +>E.Flag : E.Flag +>E : typeof E +>Flag : E.Flag + +intMember = E.Int | E.Flag; +>intMember = E.Int | E.Flag : number +>intMember : E.Int +>E.Int | E.Flag : number +>E.Int : E.Int +>E : typeof E +>Int : E.Int +>E.Flag : E.Flag +>E : typeof E +>Flag : E.Flag + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.js b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.js new file mode 100644 index 0000000000000..c6d63ac97207a --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.js @@ -0,0 +1,65 @@ +//// [tests/cases/compiler/erasableEnumConstants.ts] //// + +//// [values.ts] +export const text = "hello"; +export const count = 2; +// Numeric strings are string keys; indexing follows ordinary object rules. +export const Source: enum = { A: "source", B: 1, "1": "numeric" }; +//// [consumer.ts] +import { text, count, Source } from "./values"; +const Local: enum = { Value: "local" }; +// Parentheses are transparent for constant values and member references. +export const E: enum = { + __proto__: null, + Text: ((text)), + Count: (count) + 1, + ImportedMember: (Source.A), + ImportedIndex: Source[("B")], + NumericIndex: Source[(1)], + LocalMember: Local.Value, + LocalIndex: Local["Value"], +}; +export let value: E = E.Text; +export let member: E.ImportedMember = E.ImportedMember; + + +//// [values.js] +export const text = "hello"; +export const count = 2; +// Numeric strings are string keys; indexing follows ordinary object rules. +export const Source = { A: "source", B: 1, "1": "numeric" }; +//// [consumer.js] +import { text, count, Source } from "./values"; +const Local = { Value: "local" }; +// Parentheses are transparent for constant values and member references. +export const E = { + __proto__: null, + Text: ((text)), + Count: (count) + 1, + ImportedMember: (Source.A), + ImportedIndex: Source[("B")], + NumericIndex: Source[(1)], + LocalMember: Local.Value, + LocalIndex: Local["Value"], +}; +export let value = E.Text; +export let member = E.ImportedMember; + + +//// [values.d.ts] +export declare const text = "hello"; +export declare const count = 2; +export declare const Source: enum = { A: "source", B: 1, "1": "numeric" }; +//// [consumer.d.ts] +export declare const E: enum = { + __proto__: null, + Text: "hello", + Count: 3, + ImportedMember: "source", + ImportedIndex: 1, + NumericIndex: "numeric", + LocalMember: "local", + LocalIndex: "local" +}; +export declare let value: E; +export declare let member: E.ImportedMember; diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.symbols new file mode 100644 index 0000000000000..60d8da5c9454e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.symbols @@ -0,0 +1,82 @@ +//// [tests/cases/compiler/erasableEnumConstants.ts] //// + +=== values.ts === +export const text = "hello"; +>text : Symbol(text, Decl(values.ts, 0, 12)) + +export const count = 2; +>count : Symbol(count, Decl(values.ts, 1, 12)) + +// Numeric strings are string keys; indexing follows ordinary object rules. +export const Source: enum = { A: "source", B: 1, "1": "numeric" }; +>Source : Symbol(Source, Decl(values.ts, 3, 12)) +>A : Symbol(Source.A, Decl(values.ts, 3, 29)) +>B : Symbol(Source.B, Decl(values.ts, 3, 42)) +>"1" : Symbol(Source["1"], Decl(values.ts, 3, 48)) + +=== consumer.ts === +import { text, count, Source } from "./values"; +>text : Symbol(text, Decl(consumer.ts, 0, 8)) +>count : Symbol(count, Decl(consumer.ts, 0, 14)) +>Source : Symbol(Source, Decl(consumer.ts, 0, 21)) + +const Local: enum = { Value: "local" }; +>Local : Symbol(Local, Decl(consumer.ts, 1, 5)) +>Value : Symbol(Local.Value, Decl(consumer.ts, 1, 21)) + +// Parentheses are transparent for constant values and member references. +export const E: enum = { +>E : Symbol(E, Decl(consumer.ts, 3, 12)) + + __proto__: null, +>__proto__ : Symbol(__proto__, Decl(consumer.ts, 3, 24)) + + Text: ((text)), +>Text : Symbol(E.Text, Decl(consumer.ts, 4, 20)) +>text : Symbol(text, Decl(consumer.ts, 0, 8)) + + Count: (count) + 1, +>Count : Symbol(E.Count, Decl(consumer.ts, 5, 19)) +>count : Symbol(count, Decl(consumer.ts, 0, 14)) + + ImportedMember: (Source.A), +>ImportedMember : Symbol(E.ImportedMember, Decl(consumer.ts, 6, 23)) +>Source.A : Symbol(Source.A, Decl(values.ts, 3, 29)) +>Source : Symbol(Source, Decl(consumer.ts, 0, 21)) +>A : Symbol(Source.A, Decl(values.ts, 3, 29)) + + ImportedIndex: Source[("B")], +>ImportedIndex : Symbol(E.ImportedIndex, Decl(consumer.ts, 7, 31)) +>Source : Symbol(Source, Decl(consumer.ts, 0, 21)) + + NumericIndex: Source[(1)], +>NumericIndex : Symbol(E.NumericIndex, Decl(consumer.ts, 8, 33)) +>Source : Symbol(Source, Decl(consumer.ts, 0, 21)) + + LocalMember: Local.Value, +>LocalMember : Symbol(E.LocalMember, Decl(consumer.ts, 9, 30)) +>Local.Value : Symbol(Local.Value, Decl(consumer.ts, 1, 21)) +>Local : Symbol(Local, Decl(consumer.ts, 1, 5)) +>Value : Symbol(Local.Value, Decl(consumer.ts, 1, 21)) + + LocalIndex: Local["Value"], +>LocalIndex : Symbol(E.LocalIndex, Decl(consumer.ts, 10, 29)) +>Local : Symbol(Local, Decl(consumer.ts, 1, 5)) +>"Value" : Symbol(Local.Value, Decl(consumer.ts, 1, 21)) + +}; +export let value: E = E.Text; +>value : Symbol(value, Decl(consumer.ts, 13, 10)) +>E : Symbol(E, Decl(consumer.ts, 3, 12)) +>E.Text : Symbol(E.Text, Decl(consumer.ts, 4, 20)) +>E : Symbol(E, Decl(consumer.ts, 3, 12)) +>Text : Symbol(E.Text, Decl(consumer.ts, 4, 20)) + +export let member: E.ImportedMember = E.ImportedMember; +>member : Symbol(member, Decl(consumer.ts, 14, 10)) +>E : Symbol(E, Decl(consumer.ts, 3, 12)) +>ImportedMember : Symbol(E.ImportedMember, Decl(consumer.ts, 6, 23)) +>E.ImportedMember : Symbol(E.ImportedMember, Decl(consumer.ts, 6, 23)) +>E : Symbol(E, Decl(consumer.ts, 3, 12)) +>ImportedMember : Symbol(E.ImportedMember, Decl(consumer.ts, 6, 23)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.types b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.types new file mode 100644 index 0000000000000..1e659ac6973af --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumConstants.types @@ -0,0 +1,102 @@ +//// [tests/cases/compiler/erasableEnumConstants.ts] //// + +=== values.ts === +export const text = "hello"; +>text : "hello" +>"hello" : "hello" + +export const count = 2; +>count : 2 +>2 : 2 + +// Numeric strings are string keys; indexing follows ordinary object rules. +export const Source: enum = { A: "source", B: 1, "1": "numeric" }; +>Source : typeof Source +>{ A: "source", B: 1, "1": "numeric" } : typeof Source +>A : Source.A +>"source" : "source" +>B : Source.B +>1 : 1 +>"1" : (typeof Source)["1"] +>"numeric" : "numeric" + +=== consumer.ts === +import { text, count, Source } from "./values"; +>text : "hello" +>count : 2 +>Source : typeof Source + +const Local: enum = { Value: "local" }; +>Local : typeof Local +>{ Value: "local" } : typeof Local +>Value : Local +>"local" : "local" + +// Parentheses are transparent for constant values and member references. +export const E: enum = { +>E : typeof E +>{ __proto__: null, Text: ((text)), Count: (count) + 1, ImportedMember: (Source.A), ImportedIndex: Source[("B")], NumericIndex: Source[(1)], LocalMember: Local.Value, LocalIndex: Local["Value"],} : typeof E + + __proto__: null, +>__proto__ : null + + Text: ((text)), +>Text : E.Text +>((text)) : "hello" +>(text) : "hello" +>text : "hello" + + Count: (count) + 1, +>Count : E.Count +>(count) + 1 : number +>(count) : 2 +>count : 2 +>1 : 1 + + ImportedMember: (Source.A), +>ImportedMember : E.ImportedMember +>(Source.A) : Source.A +>Source.A : Source.A +>Source : typeof Source +>A : Source.A + + ImportedIndex: Source[("B")], +>ImportedIndex : E.ImportedIndex +>Source[("B")] : Source.B +>Source : typeof Source +>("B") : "B" +>"B" : "B" + + NumericIndex: Source[(1)], +>NumericIndex : E.NumericIndex +>Source[(1)] : (typeof Source)["1"] +>Source : typeof Source +>(1) : 1 +>1 : 1 + + LocalMember: Local.Value, +>LocalMember : E.LocalMember +>Local.Value : Local.Value +>Local : typeof Local +>Value : Local.Value + + LocalIndex: Local["Value"], +>LocalIndex : E.LocalMember +>Local["Value"] : Local.Value +>Local : typeof Local +>"Value" : "Value" + +}; +export let value: E = E.Text; +>value : E +>E.Text : E.Text +>E : typeof E +>Text : E.Text + +export let member: E.ImportedMember = E.ImportedMember; +>member : E.ImportedMember +>E : any +>E.ImportedMember : E.ImportedMember +>E : typeof E +>ImportedMember : E.ImportedMember + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.js b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.js new file mode 100644 index 0000000000000..d15587af993db --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.js @@ -0,0 +1,131 @@ +//// [tests/cases/compiler/erasableEnumErasure.ts] //// + +//// [erasableEnumErasure.ts] +const outer = 4; +const Numeric: enum = (({ + // Preserve member comments and ordinary JavaScript expressions. + First: /* Preserve initializer comments. */ (1), + Second: (outer + 1), + Shifted: outer << 1, +})); +const StringValues: enum = { + /** An enum member. */ + First: "first", + Second: "second", +}; +let numeric: Numeric = Numeric.First; +let member: Numeric.First = Numeric.First; +let text: StringValues = StringValues.Second; +const constMember = StringValues.First as const; +const constIndexed = StringValues["First"] as const; +const keys: keyof typeof StringValues = "First"; +const object: typeof StringValues = StringValues; +function narrow(value: StringValues) { + if (value === StringValues.First) { + const first: StringValues.First = value; + return first; + } + const second: StringValues.Second = value; + return second; +} +function scoped() { + const Local: enum = { Value: "local" }; + const value: Local.Value = Local.Value; + return value as string; +} +namespace Types { + export type Value = StringValues; +} + +var Variable: enum = { Value: 1 }; +const variable: Variable = Variable.Value; +declare const Ambient: enum = { A: 1, B: (0) }; +const ambient: Ambient = Ambient.B; + +// Enums without members have the never type, including prototype-only objects. +const Empty: enum = {}; +declare const empty: Empty; +const emptyValue: never = empty; +const PrototypeOnly: enum = { __proto__: null }; +declare const prototypeOnly: PrototypeOnly; +const prototypeOnlyValue: never = prototypeOnly; + + +//// [erasableEnumErasure.js] +"use strict"; +const outer = 4; +const Numeric = (({ + // Preserve member comments and ordinary JavaScript expressions. + First: /* Preserve initializer comments. */ (1), + Second: (outer + 1), + Shifted: outer << 1, +})); +const StringValues = { + /** An enum member. */ + First: "first", + Second: "second", +}; +let numeric = Numeric.First; +let member = Numeric.First; +let text = StringValues.Second; +const constMember = StringValues.First; +const constIndexed = StringValues["First"]; +const keys = "First"; +const object = StringValues; +function narrow(value) { + if (value === StringValues.First) { + const first = value; + return first; + } + const second = value; + return second; +} +function scoped() { + const Local = { Value: "local" }; + const value = Local.Value; + return value; +} +var Variable = { Value: 1 }; +const variable = Variable.Value; +const ambient = Ambient.B; +// Enums without members have the never type, including prototype-only objects. +const Empty = {}; +const emptyValue = empty; +const PrototypeOnly = { __proto__: null }; +const prototypeOnlyValue = prototypeOnly; + + +//// [erasableEnumErasure.d.ts] +declare const outer = 4; +declare const Numeric: enum = { + First: 1, + Second: 5, + Shifted: 8 +}; +declare const StringValues: enum = { + /** An enum member. */ + First: "first", + Second: "second" +}; +declare let numeric: Numeric; +declare let member: Numeric.First; +declare let text: StringValues; +declare const constMember: StringValues.First; +declare const constIndexed: StringValues.First; +declare const keys: keyof typeof StringValues; +declare const object: typeof StringValues; +declare function narrow(value: StringValues): StringValues; +declare function scoped(): string; +declare namespace Types { + type Value = StringValues; +} +declare var Variable: enum = { Value: 1 }; +declare const variable: Variable; +declare const Ambient: enum = { A: 1, B: 0 }; +declare const ambient: Ambient; +declare const Empty: enum = {}; +declare const empty: Empty; +declare const emptyValue: never; +declare const PrototypeOnly: enum = { __proto__: null }; +declare const prototypeOnly: PrototypeOnly; +declare const prototypeOnlyValue: never; diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.symbols new file mode 100644 index 0000000000000..05eea61126ec2 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.symbols @@ -0,0 +1,179 @@ +//// [tests/cases/compiler/erasableEnumErasure.ts] //// + +=== erasableEnumErasure.ts === +const outer = 4; +>outer : Symbol(outer, Decl(erasableEnumErasure.ts, 0, 5)) + +const Numeric: enum = (({ +>Numeric : Symbol(Numeric, Decl(erasableEnumErasure.ts, 1, 5)) + + // Preserve member comments and ordinary JavaScript expressions. + First: /* Preserve initializer comments. */ (1), +>First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) + + Second: (outer + 1), +>Second : Symbol(Numeric.Second, Decl(erasableEnumErasure.ts, 3, 52)) +>outer : Symbol(outer, Decl(erasableEnumErasure.ts, 0, 5)) + + Shifted: outer << 1, +>Shifted : Symbol(Numeric.Shifted, Decl(erasableEnumErasure.ts, 4, 24)) +>outer : Symbol(outer, Decl(erasableEnumErasure.ts, 0, 5)) + +})); +const StringValues: enum = { +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) + + /** An enum member. */ + First: "first", +>First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) + + Second: "second", +>Second : Symbol(StringValues.Second, Decl(erasableEnumErasure.ts, 9, 19)) + +}; +let numeric: Numeric = Numeric.First; +>numeric : Symbol(numeric, Decl(erasableEnumErasure.ts, 12, 3)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErasure.ts, 1, 5)) +>Numeric.First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErasure.ts, 1, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) + +let member: Numeric.First = Numeric.First; +>member : Symbol(member, Decl(erasableEnumErasure.ts, 13, 3)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErasure.ts, 1, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) +>Numeric.First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErasure.ts, 1, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErasure.ts, 1, 25)) + +let text: StringValues = StringValues.Second; +>text : Symbol(text, Decl(erasableEnumErasure.ts, 14, 3)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>StringValues.Second : Symbol(StringValues.Second, Decl(erasableEnumErasure.ts, 9, 19)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>Second : Symbol(StringValues.Second, Decl(erasableEnumErasure.ts, 9, 19)) + +const constMember = StringValues.First as const; +>constMember : Symbol(constMember, Decl(erasableEnumErasure.ts, 15, 5)) +>StringValues.First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) +>const : Symbol(const) + +const constIndexed = StringValues["First"] as const; +>constIndexed : Symbol(constIndexed, Decl(erasableEnumErasure.ts, 16, 5)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>"First" : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) +>const : Symbol(const) + +const keys: keyof typeof StringValues = "First"; +>keys : Symbol(keys, Decl(erasableEnumErasure.ts, 17, 5)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) + +const object: typeof StringValues = StringValues; +>object : Symbol(object, Decl(erasableEnumErasure.ts, 18, 5)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) + +function narrow(value: StringValues) { +>narrow : Symbol(narrow, Decl(erasableEnumErasure.ts, 18, 49)) +>value : Symbol(value, Decl(erasableEnumErasure.ts, 19, 16)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) + + if (value === StringValues.First) { +>value : Symbol(value, Decl(erasableEnumErasure.ts, 19, 16)) +>StringValues.First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) + + const first: StringValues.First = value; +>first : Symbol(first, Decl(erasableEnumErasure.ts, 21, 13)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>First : Symbol(StringValues.First, Decl(erasableEnumErasure.ts, 7, 28)) +>value : Symbol(value, Decl(erasableEnumErasure.ts, 19, 16)) + + return first; +>first : Symbol(first, Decl(erasableEnumErasure.ts, 21, 13)) + } + const second: StringValues.Second = value; +>second : Symbol(second, Decl(erasableEnumErasure.ts, 24, 9)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +>Second : Symbol(StringValues.Second, Decl(erasableEnumErasure.ts, 9, 19)) +>value : Symbol(value, Decl(erasableEnumErasure.ts, 19, 16)) + + return second; +>second : Symbol(second, Decl(erasableEnumErasure.ts, 24, 9)) +} +function scoped() { +>scoped : Symbol(scoped, Decl(erasableEnumErasure.ts, 26, 1)) + + const Local: enum = { Value: "local" }; +>Local : Symbol(Local, Decl(erasableEnumErasure.ts, 28, 9)) +>Value : Symbol(Local.Value, Decl(erasableEnumErasure.ts, 28, 25)) + + const value: Local.Value = Local.Value; +>value : Symbol(value, Decl(erasableEnumErasure.ts, 29, 9)) +>Local : Symbol(Local, Decl(erasableEnumErasure.ts, 28, 9)) +>Value : Symbol(Local.Value, Decl(erasableEnumErasure.ts, 28, 25)) +>Local.Value : Symbol(Local.Value, Decl(erasableEnumErasure.ts, 28, 25)) +>Local : Symbol(Local, Decl(erasableEnumErasure.ts, 28, 9)) +>Value : Symbol(Local.Value, Decl(erasableEnumErasure.ts, 28, 25)) + + return value as string; +>value : Symbol(value, Decl(erasableEnumErasure.ts, 29, 9)) +} +namespace Types { +>Types : Symbol(Types, Decl(erasableEnumErasure.ts, 31, 1)) + + export type Value = StringValues; +>Value : Symbol(Value, Decl(erasableEnumErasure.ts, 32, 17)) +>StringValues : Symbol(StringValues, Decl(erasableEnumErasure.ts, 7, 5)) +} + +var Variable: enum = { Value: 1 }; +>Variable : Symbol(Variable, Decl(erasableEnumErasure.ts, 36, 3)) +>Value : Symbol(Variable.Value, Decl(erasableEnumErasure.ts, 36, 22)) + +const variable: Variable = Variable.Value; +>variable : Symbol(variable, Decl(erasableEnumErasure.ts, 37, 5)) +>Variable : Symbol(Variable, Decl(erasableEnumErasure.ts, 36, 3)) +>Variable.Value : Symbol(Variable.Value, Decl(erasableEnumErasure.ts, 36, 22)) +>Variable : Symbol(Variable, Decl(erasableEnumErasure.ts, 36, 3)) +>Value : Symbol(Variable.Value, Decl(erasableEnumErasure.ts, 36, 22)) + +declare const Ambient: enum = { A: 1, B: (0) }; +>Ambient : Symbol(Ambient, Decl(erasableEnumErasure.ts, 38, 13)) +>A : Symbol(Ambient.A, Decl(erasableEnumErasure.ts, 38, 31)) +>B : Symbol(Ambient.B, Decl(erasableEnumErasure.ts, 38, 37)) + +const ambient: Ambient = Ambient.B; +>ambient : Symbol(ambient, Decl(erasableEnumErasure.ts, 39, 5)) +>Ambient : Symbol(Ambient, Decl(erasableEnumErasure.ts, 38, 13)) +>Ambient.B : Symbol(Ambient.B, Decl(erasableEnumErasure.ts, 38, 37)) +>Ambient : Symbol(Ambient, Decl(erasableEnumErasure.ts, 38, 13)) +>B : Symbol(Ambient.B, Decl(erasableEnumErasure.ts, 38, 37)) + +// Enums without members have the never type, including prototype-only objects. +const Empty: enum = {}; +>Empty : Symbol(Empty, Decl(erasableEnumErasure.ts, 42, 5)) + +declare const empty: Empty; +>empty : Symbol(empty, Decl(erasableEnumErasure.ts, 43, 13)) +>Empty : Symbol(Empty, Decl(erasableEnumErasure.ts, 42, 5)) + +const emptyValue: never = empty; +>emptyValue : Symbol(emptyValue, Decl(erasableEnumErasure.ts, 44, 5)) +>empty : Symbol(empty, Decl(erasableEnumErasure.ts, 43, 13)) + +const PrototypeOnly: enum = { __proto__: null }; +>PrototypeOnly : Symbol(PrototypeOnly, Decl(erasableEnumErasure.ts, 45, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErasure.ts, 45, 29)) + +declare const prototypeOnly: PrototypeOnly; +>prototypeOnly : Symbol(prototypeOnly, Decl(erasableEnumErasure.ts, 46, 13)) +>PrototypeOnly : Symbol(PrototypeOnly, Decl(erasableEnumErasure.ts, 45, 5)) + +const prototypeOnlyValue: never = prototypeOnly; +>prototypeOnlyValue : Symbol(prototypeOnlyValue, Decl(erasableEnumErasure.ts, 47, 5)) +>prototypeOnly : Symbol(prototypeOnly, Decl(erasableEnumErasure.ts, 46, 13)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.types b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.types new file mode 100644 index 0000000000000..6b6124f2d9c2e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErasure.types @@ -0,0 +1,193 @@ +//// [tests/cases/compiler/erasableEnumErasure.ts] //// + +=== erasableEnumErasure.ts === +const outer = 4; +>outer : 4 +>4 : 4 + +const Numeric: enum = (({ +>Numeric : typeof Numeric +>(({ // Preserve member comments and ordinary JavaScript expressions. First: /* Preserve initializer comments. */ (1), Second: (outer + 1), Shifted: outer << 1,})) : typeof Numeric +>({ // Preserve member comments and ordinary JavaScript expressions. First: /* Preserve initializer comments. */ (1), Second: (outer + 1), Shifted: outer << 1,}) : typeof Numeric +>{ // Preserve member comments and ordinary JavaScript expressions. First: /* Preserve initializer comments. */ (1), Second: (outer + 1), Shifted: outer << 1,} : typeof Numeric + + // Preserve member comments and ordinary JavaScript expressions. + First: /* Preserve initializer comments. */ (1), +>First : Numeric.First +>(1) : 1 +>1 : 1 + + Second: (outer + 1), +>Second : Numeric.Second +>(outer + 1) : number +>outer + 1 : number +>outer : 4 +>1 : 1 + + Shifted: outer << 1, +>Shifted : Numeric.Shifted +>outer << 1 : number +>outer : 4 +>1 : 1 + +})); +const StringValues: enum = { +>StringValues : typeof StringValues +>{ /** An enum member. */ First: "first", Second: "second",} : typeof StringValues + + /** An enum member. */ + First: "first", +>First : StringValues.First +>"first" : "first" + + Second: "second", +>Second : StringValues.Second +>"second" : "second" + +}; +let numeric: Numeric = Numeric.First; +>numeric : Numeric +>Numeric.First : Numeric.First +>Numeric : typeof Numeric +>First : Numeric.First + +let member: Numeric.First = Numeric.First; +>member : Numeric.First +>Numeric : any +>Numeric.First : Numeric.First +>Numeric : typeof Numeric +>First : Numeric.First + +let text: StringValues = StringValues.Second; +>text : StringValues +>StringValues.Second : StringValues.Second +>StringValues : typeof StringValues +>Second : StringValues.Second + +const constMember = StringValues.First as const; +>constMember : StringValues.First +>StringValues.First as const : StringValues.First +>StringValues.First : StringValues.First +>StringValues : typeof StringValues +>First : StringValues.First + +const constIndexed = StringValues["First"] as const; +>constIndexed : StringValues.First +>StringValues["First"] as const : StringValues.First +>StringValues["First"] : StringValues.First +>StringValues : typeof StringValues +>"First" : "First" + +const keys: keyof typeof StringValues = "First"; +>keys : "First" | "Second" +>StringValues : typeof StringValues +>"First" : "First" + +const object: typeof StringValues = StringValues; +>object : typeof StringValues +>StringValues : typeof StringValues +>StringValues : typeof StringValues + +function narrow(value: StringValues) { +>narrow : (value: StringValues) => StringValues +>value : StringValues + + if (value === StringValues.First) { +>value === StringValues.First : boolean +>value : StringValues +>StringValues.First : StringValues.First +>StringValues : typeof StringValues +>First : StringValues.First + + const first: StringValues.First = value; +>first : StringValues.First +>StringValues : any +>value : StringValues.First + + return first; +>first : StringValues.First + } + const second: StringValues.Second = value; +>second : StringValues.Second +>StringValues : any +>value : StringValues.Second + + return second; +>second : StringValues.Second +} +function scoped() { +>scoped : () => string + + const Local: enum = { Value: "local" }; +>Local : typeof Local +>{ Value: "local" } : typeof Local +>Value : Local +>"local" : "local" + + const value: Local.Value = Local.Value; +>value : Local.Value +>Local : any +>Local.Value : Local.Value +>Local : typeof Local +>Value : Local.Value + + return value as string; +>value as string : string +>value : Local.Value +} +namespace Types { + export type Value = StringValues; +>Value : StringValues +} + +var Variable: enum = { Value: 1 }; +>Variable : typeof Variable +>{ Value: 1 } : typeof Variable +>Value : Variable +>1 : 1 + +const variable: Variable = Variable.Value; +>variable : Variable.Value +>Variable.Value : Variable.Value +>Variable : typeof Variable +>Value : Variable.Value + +declare const Ambient: enum = { A: 1, B: (0) }; +>Ambient : typeof Ambient +>{ A: 1, B: (0) } : typeof Ambient +>A : Ambient.A +>1 : 1 +>B : Ambient.B +>(0) : 0 +>0 : 0 + +const ambient: Ambient = Ambient.B; +>ambient : Ambient +>Ambient.B : Ambient.B +>Ambient : typeof Ambient +>B : Ambient.B + +// Enums without members have the never type, including prototype-only objects. +const Empty: enum = {}; +>Empty : typeof Empty +>{} : typeof Empty + +declare const empty: Empty; +>empty : never + +const emptyValue: never = empty; +>emptyValue : never +>empty : never + +const PrototypeOnly: enum = { __proto__: null }; +>PrototypeOnly : typeof PrototypeOnly +>{ __proto__: null } : typeof PrototypeOnly +>__proto__ : null + +declare const prototypeOnly: PrototypeOnly; +>prototypeOnly : never + +const prototypeOnlyValue: never = prototypeOnly; +>prototypeOnlyValue : never +>prototypeOnly : never + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.errors.txt b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.errors.txt new file mode 100644 index 0000000000000..d9af1a1ff4c25 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.errors.txt @@ -0,0 +1,260 @@ +erasableEnumErrors.ts(2,34): error TS18004: No value exists in scope for the shorthand property 'missing'. Either declare one or provide an initializer. +erasableEnumErrors.ts(2,34): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(4,28): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(9,11): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(10,12): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(11,11): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(12,13): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(13,13): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(14,13): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(16,36): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(19,37): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(21,43): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(24,37): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(24,58): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(27,43): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(27,64): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(28,50): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(31,48): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(31,67): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(34,28): error TS18147: Erasable enum member names must be identifiers or string literals. +erasableEnumErrors.ts(35,29): error TS18147: Erasable enum member names must be identifiers or string literals. +erasableEnumErrors.ts(37,38): error TS18147: Erasable enum member names must be identifiers or string literals. +erasableEnumErrors.ts(38,38): error TS18147: Erasable enum member names must be identifiers or string literals. +erasableEnumErrors.ts(39,45): error TS2339: Property '__proto__' does not exist on type 'typeof ComputedPrototypeKey'. +erasableEnumErrors.ts(43,48): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(44,24): error TS18144: Spread assignments are not allowed in erasable enums. +erasableEnumErrors.ts(45,24): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(46,28): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(47,28): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(50,9): error TS2540: Cannot assign to 'First' because it is a read-only property. +erasableEnumErrors.ts(51,17): error TS7053: Element implicitly has an 'any' type because expression of type '1' can't be used to index type 'typeof Numeric'. + Property '1' does not exist on type 'typeof Numeric'. +erasableEnumErrors.ts(52,28): error TS2339: Property 'Unknown' does not exist on type 'typeof Numeric'. +erasableEnumErrors.ts(55,38): error TS2304: Cannot find name 'A'. +erasableEnumErrors.ts(55,38): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(56,40): error TS2448: Block-scoped variable 'SelfReference' used before its declaration. +erasableEnumErrors.ts(56,40): error TS2454: Variable 'SelfReference' is used before being assigned. +erasableEnumErrors.ts(56,40): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(57,41): error TS2454: Variable 'VarSelfReference' is used before being assigned. +erasableEnumErrors.ts(57,41): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(59,29): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(60,30): error TS18143: Erasable enum member initializers must be constant expressions. +erasableEnumErrors.ts(60,45): error TS2448: Block-scoped variable 'Immediate' used before its declaration. +erasableEnumErrors.ts(60,45): error TS2454: Variable 'Immediate' is used before being assigned. +erasableEnumErrors.ts(66,33): error TS1117: An object literal cannot have multiple properties with the same name. +erasableEnumErrors.ts(67,7): error TS2451: Cannot redeclare block-scoped variable 'Repeated'. +erasableEnumErrors.ts(68,7): error TS2451: Cannot redeclare block-scoped variable 'Repeated'. +erasableEnumErrors.ts(71,41): error TS18142: An erasable enum prototype setter must have the value 'null'. +erasableEnumErrors.ts(72,49): error TS18142: An erasable enum prototype setter must have the value 'null'. +erasableEnumErrors.ts(73,44): error TS18142: An erasable enum prototype setter must have the value 'null'. +erasableEnumErrors.ts(74,46): error TS18142: An erasable enum prototype setter must have the value 'null'. +erasableEnumErrors.ts(76,43): error TS2339: Property '__proto__' does not exist on type 'typeof NullPrototype'. +erasableEnumErrors.ts(78,36): error TS18145: Erasable enums only allow property assignments. +erasableEnumErrors.ts(81,20): error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. +erasableEnumErrors.ts(82,18): error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. +erasableEnumErrors.ts(83,26): error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. +erasableEnumErrors.ts(84,28): error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. + + +==== erasableEnumErrors.ts (56 errors) ==== + // Members require explicit property assignments, even for constant bindings. + const UnboundShorthand: enum = { missing }; + ~~~~~~~ +!!! error TS18004: No value exists in scope for the shorthand property 'missing'. Either declare one or provide an initializer. + ~~~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + const shorthandValue = 1; + const Shorthand: enum = ({ shorthandValue }); + ~~~~~~~~~~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + + // Member values must be compile-time string or number constants. + declare const symbolValue: unique symbol; + const Invalid: enum = { + True: true, + ~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + False: false, + ~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + Null: null, + ~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + Object: {}, + ~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + BigInt: 1n, + ~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + Symbol: symbolValue, + ~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + }; + const DynamicCall: enum = { Value: Math.random() }; + ~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const dynamicValue: DynamicCall = DynamicCall.Value; // no cascading type errors. + let mutable = 1; + const MutableValue: enum = { Value: mutable }; + ~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const dynamic = Math.random(); + const NonconstantBinding: enum = { Value: dynamic }; + ~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + declare const broadNumber: number; + declare const broadString: string; + const BroadValues: enum = { Number: broadNumber, String: broadString }; + ~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + ~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + + // Assertions and satisfies expressions block constant evaluation, including through references. + const AssertionBoundary: enum = ({ Value: 1 as number, Nested: (1 as number) + 1 }); + ~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + ~~~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const SatisfiesBoundary: enum = { Value: "value" satisfies string }; + ~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const asserted = 1 as number; + const checked = "value" satisfies string; + const ReferencedBoundaries: enum = { Asserted: asserted, Checked: checked }; + ~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + ~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + + // Names must be identifiers or strings; computed names are forbidden even when constant. + const NumericKey: enum = { 1: "one" }; + ~ +!!! error TS18147: Erasable enum member names must be identifiers or string literals. + const ComputedKey: enum = { ["foo"]: 1 }; + ~~~~~~~ +!!! error TS18147: Erasable enum member names must be identifiers or string literals. + const key = "Known"; + const ComputedKeyReference: enum = { [key]: 1 }; + ~~~~~ +!!! error TS18147: Erasable enum member names must be identifiers or string literals. + const ComputedPrototypeKey: enum = { ["__proto__"]: 1 }; + ~~~~~~~~~~~~~ +!!! error TS18147: Erasable enum member names must be identifiers or string literals. + const prototypeValue = ComputedPrototypeKey.__proto__; + ~~~~~~~~~ +!!! error TS2339: Property '__proto__' does not exist on type 'typeof ComputedPrototypeKey'. + + const Numeric: enum = { First: 1, Second: 2 }; + // Const assertions on member references still block constant evaluation in initializers. + const MemberAssertionBoundary: enum = { Value: Numeric.First as const }; + ~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const Spread: enum = { ...Numeric }; + ~~~~~~~~~~ +!!! error TS18144: Spread assignments are not allowed in erasable enums. + const Method: enum = { method() {} }; + ~~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + const Getter: enum = { get value() { return 1; } }; + ~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + const Setter: enum = { set value(value: number) {} }; + ~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + + // Members are readonly and numeric reverse mappings are absent. + Numeric.First = Numeric.Second; + ~~~~~ +!!! error TS2540: Cannot assign to 'First' because it is a read-only property. + const reverse = Numeric[1]; + ~~~~~~~~~~ +!!! error TS7053: Element implicitly has an 'any' type because expression of type '1' can't be used to index type 'typeof Numeric'. +!!! error TS7053: Property '1' does not exist on type 'typeof Numeric'. + const unknownKey = Numeric.Unknown; + ~~~~~~~ +!!! error TS2339: Property 'Unknown' does not exist on type 'typeof Numeric'. + + // Initializers use ordinary lexical bindings, without a scope for enum members. + const Unqualified: enum = { A: 1, B: A }; + ~ +!!! error TS2304: Cannot find name 'A'. + ~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const SelfReference: enum = { A: 1, B: SelfReference.A }; + ~~~~~~~~~~~~~ +!!! error TS2448: Block-scoped variable 'SelfReference' used before its declaration. +!!! related TS2728 erasableEnumErrors.ts:56:7: 'SelfReference' is declared here. + ~~~~~~~~~~~~~ +!!! error TS2454: Variable 'SelfReference' is used before being assigned. + ~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + var VarSelfReference: enum = { A: 1, B: VarSelfReference.A }; + ~~~~~~~~~~~~~~~~ +!!! error TS2454: Variable 'VarSelfReference' is used before being assigned. + ~~~~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + // Deferred callbacks avoid initialization errors; calls are still nonconstant. + const Deferred: enum = { A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 }; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + const Immediate: enum = { A: ((): number => Immediate.B)(), B: 1 }; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS18143: Erasable enum member initializers must be constant expressions. + ~~~~~~~~~ +!!! error TS2448: Block-scoped variable 'Immediate' used before its declaration. +!!! related TS2728 erasableEnumErrors.ts:60:7: 'Immediate' is declared here. + ~~~~~~~~~ +!!! error TS2454: Variable 'Immediate' is used before being assigned. + const OuterMember = 10; + const Lexical: enum = { OuterMember: 1, Value: OuterMember }; + const lexicalValue: Lexical.Value = 10; // ok: Value refers to the outer constant. + + // Duplicate keys follow object literal rules; bindings cannot be redeclared. + const Duplicate: enum = { A: 1, A: 2 }; + ~ +!!! error TS1117: An object literal cannot have multiple properties with the same name. + const Repeated: enum = { A: 1 }; + ~~~~~~~~ +!!! error TS2451: Cannot redeclare block-scoped variable 'Repeated'. + const Repeated: enum = { B: 2 }; + ~~~~~~~~ +!!! error TS2451: Cannot redeclare block-scoped variable 'Repeated'. + + // Only a null prototype setter is allowed, and it does not declare an enum member. + const PrototypeKey: enum = { __proto__: 1 }; + ~ +!!! error TS18142: An erasable enum prototype setter must have the value 'null'. + const QuotedPrototypeKey: enum = { "__proto__": 1 }; + ~ +!!! error TS18142: An erasable enum prototype setter must have the value 'null'. + const PrototypeObject: enum = { __proto__: {} }; + ~~ +!!! error TS18142: An erasable enum prototype setter must have the value 'null'. + const AssertedPrototype: enum = { __proto__: null as null }; + ~~~~~~~~~~~~ +!!! error TS18142: An erasable enum prototype setter must have the value 'null'. + const NullPrototype: enum = { __proto__: null, A: 1 }; + const nullPrototypeMember = NullPrototype.__proto__; + ~~~~~~~~~ +!!! error TS2339: Property '__proto__' does not exist on type 'typeof NullPrototype'. + const __proto__ = "own"; + const PrototypeShorthand: enum = { __proto__ }; + ~~~~~~~~~ +!!! error TS18145: Erasable enums only allow property assignments. + + // The annotation requires a named variable statement with an object literal initializer. + let NoInitializer: enum; + ~~~~ +!!! error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. + const NonObject: enum = 1; + ~~~~ +!!! error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. + const { Destructuring }: enum = { Destructuring: 1 }; + ~~~~ +!!! error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. + for (const ForInitializer: enum = { A: 1 }; false; ) {} + ~~~~ +!!! error TS18146: An 'enum' annotation requires a named variable in a variable statement with an object literal initializer. + \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.js b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.js new file mode 100644 index 0000000000000..51489307d6644 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.js @@ -0,0 +1,162 @@ +//// [tests/cases/compiler/erasableEnumErrors.ts] //// + +//// [erasableEnumErrors.ts] +// Members require explicit property assignments, even for constant bindings. +const UnboundShorthand: enum = { missing }; +const shorthandValue = 1; +const Shorthand: enum = ({ shorthandValue }); + +// Member values must be compile-time string or number constants. +declare const symbolValue: unique symbol; +const Invalid: enum = { + True: true, + False: false, + Null: null, + Object: {}, + BigInt: 1n, + Symbol: symbolValue, +}; +const DynamicCall: enum = { Value: Math.random() }; +const dynamicValue: DynamicCall = DynamicCall.Value; // no cascading type errors. +let mutable = 1; +const MutableValue: enum = { Value: mutable }; +const dynamic = Math.random(); +const NonconstantBinding: enum = { Value: dynamic }; +declare const broadNumber: number; +declare const broadString: string; +const BroadValues: enum = { Number: broadNumber, String: broadString }; + +// Assertions and satisfies expressions block constant evaluation, including through references. +const AssertionBoundary: enum = ({ Value: 1 as number, Nested: (1 as number) + 1 }); +const SatisfiesBoundary: enum = { Value: "value" satisfies string }; +const asserted = 1 as number; +const checked = "value" satisfies string; +const ReferencedBoundaries: enum = { Asserted: asserted, Checked: checked }; + +// Names must be identifiers or strings; computed names are forbidden even when constant. +const NumericKey: enum = { 1: "one" }; +const ComputedKey: enum = { ["foo"]: 1 }; +const key = "Known"; +const ComputedKeyReference: enum = { [key]: 1 }; +const ComputedPrototypeKey: enum = { ["__proto__"]: 1 }; +const prototypeValue = ComputedPrototypeKey.__proto__; + +const Numeric: enum = { First: 1, Second: 2 }; +// Const assertions on member references still block constant evaluation in initializers. +const MemberAssertionBoundary: enum = { Value: Numeric.First as const }; +const Spread: enum = { ...Numeric }; +const Method: enum = { method() {} }; +const Getter: enum = { get value() { return 1; } }; +const Setter: enum = { set value(value: number) {} }; + +// Members are readonly and numeric reverse mappings are absent. +Numeric.First = Numeric.Second; +const reverse = Numeric[1]; +const unknownKey = Numeric.Unknown; + +// Initializers use ordinary lexical bindings, without a scope for enum members. +const Unqualified: enum = { A: 1, B: A }; +const SelfReference: enum = { A: 1, B: SelfReference.A }; +var VarSelfReference: enum = { A: 1, B: VarSelfReference.A }; +// Deferred callbacks avoid initialization errors; calls are still nonconstant. +const Deferred: enum = { A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 }; +const Immediate: enum = { A: ((): number => Immediate.B)(), B: 1 }; +const OuterMember = 10; +const Lexical: enum = { OuterMember: 1, Value: OuterMember }; +const lexicalValue: Lexical.Value = 10; // ok: Value refers to the outer constant. + +// Duplicate keys follow object literal rules; bindings cannot be redeclared. +const Duplicate: enum = { A: 1, A: 2 }; +const Repeated: enum = { A: 1 }; +const Repeated: enum = { B: 2 }; + +// Only a null prototype setter is allowed, and it does not declare an enum member. +const PrototypeKey: enum = { __proto__: 1 }; +const QuotedPrototypeKey: enum = { "__proto__": 1 }; +const PrototypeObject: enum = { __proto__: {} }; +const AssertedPrototype: enum = { __proto__: null as null }; +const NullPrototype: enum = { __proto__: null, A: 1 }; +const nullPrototypeMember = NullPrototype.__proto__; +const __proto__ = "own"; +const PrototypeShorthand: enum = { __proto__ }; + +// The annotation requires a named variable statement with an object literal initializer. +let NoInitializer: enum; +const NonObject: enum = 1; +const { Destructuring }: enum = { Destructuring: 1 }; +for (const ForInitializer: enum = { A: 1 }; false; ) {} + + +//// [erasableEnumErrors.js] +"use strict"; +// Members require explicit property assignments, even for constant bindings. +const UnboundShorthand = { missing }; +const shorthandValue = 1; +const Shorthand = ({ shorthandValue }); +const Invalid = { + True: true, + False: false, + Null: null, + Object: {}, + BigInt: 1n, + Symbol: symbolValue, +}; +const DynamicCall = { Value: Math.random() }; +const dynamicValue = DynamicCall.Value; // no cascading type errors. +let mutable = 1; +const MutableValue = { Value: mutable }; +const dynamic = Math.random(); +const NonconstantBinding = { Value: dynamic }; +const BroadValues = { Number: broadNumber, String: broadString }; +// Assertions and satisfies expressions block constant evaluation, including through references. +const AssertionBoundary = ({ Value: 1, Nested: 1 + 1 }); +const SatisfiesBoundary = { Value: "value" }; +const asserted = 1; +const checked = "value"; +const ReferencedBoundaries = { Asserted: asserted, Checked: checked }; +// Names must be identifiers or strings; computed names are forbidden even when constant. +const NumericKey = { 1: "one" }; +const ComputedKey = { ["foo"]: 1 }; +const key = "Known"; +const ComputedKeyReference = { [key]: 1 }; +const ComputedPrototypeKey = { ["__proto__"]: 1 }; +const prototypeValue = ComputedPrototypeKey.__proto__; +const Numeric = { First: 1, Second: 2 }; +// Const assertions on member references still block constant evaluation in initializers. +const MemberAssertionBoundary = { Value: Numeric.First }; +const Spread = { ...Numeric }; +const Method = { method() { } }; +const Getter = { get value() { return 1; } }; +const Setter = { set value(value) { } }; +// Members are readonly and numeric reverse mappings are absent. +Numeric.First = Numeric.Second; +const reverse = Numeric[1]; +const unknownKey = Numeric.Unknown; +// Initializers use ordinary lexical bindings, without a scope for enum members. +const Unqualified = { A: 1, B: A }; +const SelfReference = { A: 1, B: SelfReference.A }; +var VarSelfReference = { A: 1, B: VarSelfReference.A }; +// Deferred callbacks avoid initialization errors; calls are still nonconstant. +const Deferred = { A: ((f) => 1)(() => Deferred.B), B: 1 }; +const Immediate = { A: (() => Immediate.B)(), B: 1 }; +const OuterMember = 10; +const Lexical = { OuterMember: 1, Value: OuterMember }; +const lexicalValue = 10; // ok: Value refers to the outer constant. +// Duplicate keys follow object literal rules; bindings cannot be redeclared. +const Duplicate = { A: 1, A: 2 }; +const Repeated = { A: 1 }; +const Repeated = { B: 2 }; +// Only a null prototype setter is allowed, and it does not declare an enum member. +const PrototypeKey = { __proto__: 1 }; +const QuotedPrototypeKey = { "__proto__": 1 }; +const PrototypeObject = { __proto__: {} }; +const AssertedPrototype = { __proto__: null }; +const NullPrototype = { __proto__: null, A: 1 }; +const nullPrototypeMember = NullPrototype.__proto__; +const __proto__ = "own"; +const PrototypeShorthand = { __proto__ }; +// The annotation requires a named variable statement with an object literal initializer. +let NoInitializer; +const NonObject = 1; +const { Destructuring } = { Destructuring: 1 }; +for (const ForInitializer = { A: 1 }; false;) { } diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.symbols new file mode 100644 index 0000000000000..1add0c6af0695 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.symbols @@ -0,0 +1,302 @@ +//// [tests/cases/compiler/erasableEnumErrors.ts] //// + +=== erasableEnumErrors.ts === +// Members require explicit property assignments, even for constant bindings. +const UnboundShorthand: enum = { missing }; +>UnboundShorthand : Symbol(UnboundShorthand, Decl(erasableEnumErrors.ts, 1, 5)) +>missing : Symbol(missing, Decl(erasableEnumErrors.ts, 1, 32)) + +const shorthandValue = 1; +>shorthandValue : Symbol(shorthandValue, Decl(erasableEnumErrors.ts, 2, 5)) + +const Shorthand: enum = ({ shorthandValue }); +>Shorthand : Symbol(Shorthand, Decl(erasableEnumErrors.ts, 3, 5)) +>shorthandValue : Symbol(shorthandValue, Decl(erasableEnumErrors.ts, 3, 26)) + +// Member values must be compile-time string or number constants. +declare const symbolValue: unique symbol; +>symbolValue : Symbol(symbolValue, Decl(erasableEnumErrors.ts, 6, 13)) + +const Invalid: enum = { +>Invalid : Symbol(Invalid, Decl(erasableEnumErrors.ts, 7, 5)) + + True: true, +>True : Symbol(Invalid.True, Decl(erasableEnumErrors.ts, 7, 23)) + + False: false, +>False : Symbol(Invalid.False, Decl(erasableEnumErrors.ts, 8, 15)) + + Null: null, +>Null : Symbol(Invalid.Null, Decl(erasableEnumErrors.ts, 9, 17)) + + Object: {}, +>Object : Symbol(Invalid.Object, Decl(erasableEnumErrors.ts, 10, 15)) + + BigInt: 1n, +>BigInt : Symbol(Invalid.BigInt, Decl(erasableEnumErrors.ts, 11, 15)) + + Symbol: symbolValue, +>Symbol : Symbol(Invalid.Symbol, Decl(erasableEnumErrors.ts, 12, 15)) +>symbolValue : Symbol(symbolValue, Decl(erasableEnumErrors.ts, 6, 13)) + +}; +const DynamicCall: enum = { Value: Math.random() }; +>DynamicCall : Symbol(DynamicCall, Decl(erasableEnumErrors.ts, 15, 5)) +>Value : Symbol(DynamicCall.Value, Decl(erasableEnumErrors.ts, 15, 27)) +>Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2025.float16.d.ts, --, --) ... and 1 more) +>random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) + +const dynamicValue: DynamicCall = DynamicCall.Value; // no cascading type errors. +>dynamicValue : Symbol(dynamicValue, Decl(erasableEnumErrors.ts, 16, 5)) +>DynamicCall : Symbol(DynamicCall, Decl(erasableEnumErrors.ts, 15, 5)) +>DynamicCall.Value : Symbol(DynamicCall.Value, Decl(erasableEnumErrors.ts, 15, 27)) +>DynamicCall : Symbol(DynamicCall, Decl(erasableEnumErrors.ts, 15, 5)) +>Value : Symbol(DynamicCall.Value, Decl(erasableEnumErrors.ts, 15, 27)) + +let mutable = 1; +>mutable : Symbol(mutable, Decl(erasableEnumErrors.ts, 17, 3)) + +const MutableValue: enum = { Value: mutable }; +>MutableValue : Symbol(MutableValue, Decl(erasableEnumErrors.ts, 18, 5)) +>Value : Symbol(MutableValue.Value, Decl(erasableEnumErrors.ts, 18, 28)) +>mutable : Symbol(mutable, Decl(erasableEnumErrors.ts, 17, 3)) + +const dynamic = Math.random(); +>dynamic : Symbol(dynamic, Decl(erasableEnumErrors.ts, 19, 5)) +>Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2025.float16.d.ts, --, --) ... and 1 more) +>random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) + +const NonconstantBinding: enum = { Value: dynamic }; +>NonconstantBinding : Symbol(NonconstantBinding, Decl(erasableEnumErrors.ts, 20, 5)) +>Value : Symbol(NonconstantBinding.Value, Decl(erasableEnumErrors.ts, 20, 34)) +>dynamic : Symbol(dynamic, Decl(erasableEnumErrors.ts, 19, 5)) + +declare const broadNumber: number; +>broadNumber : Symbol(broadNumber, Decl(erasableEnumErrors.ts, 21, 13)) + +declare const broadString: string; +>broadString : Symbol(broadString, Decl(erasableEnumErrors.ts, 22, 13)) + +const BroadValues: enum = { Number: broadNumber, String: broadString }; +>BroadValues : Symbol(BroadValues, Decl(erasableEnumErrors.ts, 23, 5)) +>Number : Symbol(BroadValues.Number, Decl(erasableEnumErrors.ts, 23, 27)) +>broadNumber : Symbol(broadNumber, Decl(erasableEnumErrors.ts, 21, 13)) +>String : Symbol(BroadValues.String, Decl(erasableEnumErrors.ts, 23, 48)) +>broadString : Symbol(broadString, Decl(erasableEnumErrors.ts, 22, 13)) + +// Assertions and satisfies expressions block constant evaluation, including through references. +const AssertionBoundary: enum = ({ Value: 1 as number, Nested: (1 as number) + 1 }); +>AssertionBoundary : Symbol(AssertionBoundary, Decl(erasableEnumErrors.ts, 26, 5)) +>Value : Symbol(AssertionBoundary.Value, Decl(erasableEnumErrors.ts, 26, 34)) +>Nested : Symbol(AssertionBoundary.Nested, Decl(erasableEnumErrors.ts, 26, 54)) + +const SatisfiesBoundary: enum = { Value: "value" satisfies string }; +>SatisfiesBoundary : Symbol(SatisfiesBoundary, Decl(erasableEnumErrors.ts, 27, 5)) +>Value : Symbol(SatisfiesBoundary.Value, Decl(erasableEnumErrors.ts, 27, 33)) + +const asserted = 1 as number; +>asserted : Symbol(asserted, Decl(erasableEnumErrors.ts, 28, 5)) + +const checked = "value" satisfies string; +>checked : Symbol(checked, Decl(erasableEnumErrors.ts, 29, 5)) + +const ReferencedBoundaries: enum = { Asserted: asserted, Checked: checked }; +>ReferencedBoundaries : Symbol(ReferencedBoundaries, Decl(erasableEnumErrors.ts, 30, 5)) +>Asserted : Symbol(ReferencedBoundaries.Asserted, Decl(erasableEnumErrors.ts, 30, 36)) +>asserted : Symbol(asserted, Decl(erasableEnumErrors.ts, 28, 5)) +>Checked : Symbol(ReferencedBoundaries.Checked, Decl(erasableEnumErrors.ts, 30, 56)) +>checked : Symbol(checked, Decl(erasableEnumErrors.ts, 29, 5)) + +// Names must be identifiers or strings; computed names are forbidden even when constant. +const NumericKey: enum = { 1: "one" }; +>NumericKey : Symbol(NumericKey, Decl(erasableEnumErrors.ts, 33, 5)) +>1 : Symbol(NumericKey[1], Decl(erasableEnumErrors.ts, 33, 26)) + +const ComputedKey: enum = { ["foo"]: 1 }; +>ComputedKey : Symbol(ComputedKey, Decl(erasableEnumErrors.ts, 34, 5)) +>["foo"] : Symbol(["foo"], Decl(erasableEnumErrors.ts, 34, 27)) +>"foo" : Symbol(["foo"], Decl(erasableEnumErrors.ts, 34, 27)) + +const key = "Known"; +>key : Symbol(key, Decl(erasableEnumErrors.ts, 35, 5)) + +const ComputedKeyReference: enum = { [key]: 1 }; +>ComputedKeyReference : Symbol(ComputedKeyReference, Decl(erasableEnumErrors.ts, 36, 5)) +>[key] : Symbol([key], Decl(erasableEnumErrors.ts, 36, 36)) +>key : Symbol(key, Decl(erasableEnumErrors.ts, 35, 5)) + +const ComputedPrototypeKey: enum = { ["__proto__"]: 1 }; +>ComputedPrototypeKey : Symbol(ComputedPrototypeKey, Decl(erasableEnumErrors.ts, 37, 5)) +>["__proto__"] : Symbol(["__proto__"], Decl(erasableEnumErrors.ts, 37, 36)) +>"__proto__" : Symbol(["__proto__"], Decl(erasableEnumErrors.ts, 37, 36)) + +const prototypeValue = ComputedPrototypeKey.__proto__; +>prototypeValue : Symbol(prototypeValue, Decl(erasableEnumErrors.ts, 38, 5)) +>ComputedPrototypeKey : Symbol(ComputedPrototypeKey, Decl(erasableEnumErrors.ts, 37, 5)) + +const Numeric: enum = { First: 1, Second: 2 }; +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErrors.ts, 40, 23)) +>Second : Symbol(Numeric.Second, Decl(erasableEnumErrors.ts, 40, 33)) + +// Const assertions on member references still block constant evaluation in initializers. +const MemberAssertionBoundary: enum = { Value: Numeric.First as const }; +>MemberAssertionBoundary : Symbol(MemberAssertionBoundary, Decl(erasableEnumErrors.ts, 42, 5)) +>Value : Symbol(MemberAssertionBoundary.Value, Decl(erasableEnumErrors.ts, 42, 39)) +>Numeric.First : Symbol(Numeric.First, Decl(erasableEnumErrors.ts, 40, 23)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErrors.ts, 40, 23)) +>const : Symbol(const) + +const Spread: enum = { ...Numeric }; +>Spread : Symbol(Spread, Decl(erasableEnumErrors.ts, 43, 5)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) + +const Method: enum = { method() {} }; +>Method : Symbol(Method, Decl(erasableEnumErrors.ts, 44, 5)) +>method : Symbol(method, Decl(erasableEnumErrors.ts, 44, 22)) + +const Getter: enum = { get value() { return 1; } }; +>Getter : Symbol(Getter, Decl(erasableEnumErrors.ts, 45, 5)) +>value : Symbol(value, Decl(erasableEnumErrors.ts, 45, 22)) + +const Setter: enum = { set value(value: number) {} }; +>Setter : Symbol(Setter, Decl(erasableEnumErrors.ts, 46, 5)) +>value : Symbol(value, Decl(erasableEnumErrors.ts, 46, 22)) +>value : Symbol(value, Decl(erasableEnumErrors.ts, 46, 33)) + +// Members are readonly and numeric reverse mappings are absent. +Numeric.First = Numeric.Second; +>Numeric.First : Symbol(Numeric.First, Decl(erasableEnumErrors.ts, 40, 23)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) +>First : Symbol(Numeric.First, Decl(erasableEnumErrors.ts, 40, 23)) +>Numeric.Second : Symbol(Numeric.Second, Decl(erasableEnumErrors.ts, 40, 33)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) +>Second : Symbol(Numeric.Second, Decl(erasableEnumErrors.ts, 40, 33)) + +const reverse = Numeric[1]; +>reverse : Symbol(reverse, Decl(erasableEnumErrors.ts, 50, 5)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) + +const unknownKey = Numeric.Unknown; +>unknownKey : Symbol(unknownKey, Decl(erasableEnumErrors.ts, 51, 5)) +>Numeric : Symbol(Numeric, Decl(erasableEnumErrors.ts, 40, 5)) + +// Initializers use ordinary lexical bindings, without a scope for enum members. +const Unqualified: enum = { A: 1, B: A }; +>Unqualified : Symbol(Unqualified, Decl(erasableEnumErrors.ts, 54, 5)) +>A : Symbol(Unqualified.A, Decl(erasableEnumErrors.ts, 54, 27)) +>B : Symbol(Unqualified.B, Decl(erasableEnumErrors.ts, 54, 33)) + +const SelfReference: enum = { A: 1, B: SelfReference.A }; +>SelfReference : Symbol(SelfReference, Decl(erasableEnumErrors.ts, 55, 5)) +>A : Symbol(SelfReference.A, Decl(erasableEnumErrors.ts, 55, 29)) +>B : Symbol(SelfReference.B, Decl(erasableEnumErrors.ts, 55, 35)) +>SelfReference.A : Symbol(SelfReference.A, Decl(erasableEnumErrors.ts, 55, 29)) +>SelfReference : Symbol(SelfReference, Decl(erasableEnumErrors.ts, 55, 5)) +>A : Symbol(SelfReference.A, Decl(erasableEnumErrors.ts, 55, 29)) + +var VarSelfReference: enum = { A: 1, B: VarSelfReference.A }; +>VarSelfReference : Symbol(VarSelfReference, Decl(erasableEnumErrors.ts, 56, 3)) +>A : Symbol(VarSelfReference.A, Decl(erasableEnumErrors.ts, 56, 30)) +>B : Symbol(VarSelfReference.B, Decl(erasableEnumErrors.ts, 56, 36)) +>VarSelfReference.A : Symbol(VarSelfReference.A, Decl(erasableEnumErrors.ts, 56, 30)) +>VarSelfReference : Symbol(VarSelfReference, Decl(erasableEnumErrors.ts, 56, 3)) +>A : Symbol(VarSelfReference.A, Decl(erasableEnumErrors.ts, 56, 30)) + +// Deferred callbacks avoid initialization errors; calls are still nonconstant. +const Deferred: enum = { A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 }; +>Deferred : Symbol(Deferred, Decl(erasableEnumErrors.ts, 58, 5)) +>A : Symbol(Deferred.A, Decl(erasableEnumErrors.ts, 58, 24)) +>f : Symbol(f, Decl(erasableEnumErrors.ts, 58, 30)) +>Deferred.B : Symbol(Deferred.B, Decl(erasableEnumErrors.ts, 58, 87)) +>Deferred : Symbol(Deferred, Decl(erasableEnumErrors.ts, 58, 5)) +>B : Symbol(Deferred.B, Decl(erasableEnumErrors.ts, 58, 87)) +>B : Symbol(Deferred.B, Decl(erasableEnumErrors.ts, 58, 87)) + +const Immediate: enum = { A: ((): number => Immediate.B)(), B: 1 }; +>Immediate : Symbol(Immediate, Decl(erasableEnumErrors.ts, 59, 5)) +>A : Symbol(Immediate.A, Decl(erasableEnumErrors.ts, 59, 25)) +>Immediate.B : Symbol(Immediate.B, Decl(erasableEnumErrors.ts, 59, 59)) +>Immediate : Symbol(Immediate, Decl(erasableEnumErrors.ts, 59, 5)) +>B : Symbol(Immediate.B, Decl(erasableEnumErrors.ts, 59, 59)) +>B : Symbol(Immediate.B, Decl(erasableEnumErrors.ts, 59, 59)) + +const OuterMember = 10; +>OuterMember : Symbol(OuterMember, Decl(erasableEnumErrors.ts, 60, 5)) + +const Lexical: enum = { OuterMember: 1, Value: OuterMember }; +>Lexical : Symbol(Lexical, Decl(erasableEnumErrors.ts, 61, 5)) +>OuterMember : Symbol(Lexical.OuterMember, Decl(erasableEnumErrors.ts, 61, 23)) +>Value : Symbol(Lexical.Value, Decl(erasableEnumErrors.ts, 61, 39)) +>OuterMember : Symbol(OuterMember, Decl(erasableEnumErrors.ts, 60, 5)) + +const lexicalValue: Lexical.Value = 10; // ok: Value refers to the outer constant. +>lexicalValue : Symbol(lexicalValue, Decl(erasableEnumErrors.ts, 62, 5)) +>Lexical : Symbol(Lexical, Decl(erasableEnumErrors.ts, 61, 5)) +>Value : Symbol(Lexical.Value, Decl(erasableEnumErrors.ts, 61, 39)) + +// Duplicate keys follow object literal rules; bindings cannot be redeclared. +const Duplicate: enum = { A: 1, A: 2 }; +>Duplicate : Symbol(Duplicate, Decl(erasableEnumErrors.ts, 65, 5)) +>A : Symbol(Duplicate.A, Decl(erasableEnumErrors.ts, 65, 25), Decl(erasableEnumErrors.ts, 65, 31)) +>A : Symbol(Duplicate.A, Decl(erasableEnumErrors.ts, 65, 25), Decl(erasableEnumErrors.ts, 65, 31)) + +const Repeated: enum = { A: 1 }; +>Repeated : Symbol(Repeated, Decl(erasableEnumErrors.ts, 66, 5)) +>A : Symbol(Repeated.A, Decl(erasableEnumErrors.ts, 66, 24)) + +const Repeated: enum = { B: 2 }; +>Repeated : Symbol(Repeated, Decl(erasableEnumErrors.ts, 67, 5)) +>B : Symbol(Repeated.B, Decl(erasableEnumErrors.ts, 67, 24)) + +// Only a null prototype setter is allowed, and it does not declare an enum member. +const PrototypeKey: enum = { __proto__: 1 }; +>PrototypeKey : Symbol(PrototypeKey, Decl(erasableEnumErrors.ts, 70, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 70, 28)) + +const QuotedPrototypeKey: enum = { "__proto__": 1 }; +>QuotedPrototypeKey : Symbol(QuotedPrototypeKey, Decl(erasableEnumErrors.ts, 71, 5)) +>"__proto__" : Symbol("__proto__", Decl(erasableEnumErrors.ts, 71, 34)) + +const PrototypeObject: enum = { __proto__: {} }; +>PrototypeObject : Symbol(PrototypeObject, Decl(erasableEnumErrors.ts, 72, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 72, 31)) + +const AssertedPrototype: enum = { __proto__: null as null }; +>AssertedPrototype : Symbol(AssertedPrototype, Decl(erasableEnumErrors.ts, 73, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 73, 33)) + +const NullPrototype: enum = { __proto__: null, A: 1 }; +>NullPrototype : Symbol(NullPrototype, Decl(erasableEnumErrors.ts, 74, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 74, 29)) +>A : Symbol(NullPrototype.A, Decl(erasableEnumErrors.ts, 74, 46)) + +const nullPrototypeMember = NullPrototype.__proto__; +>nullPrototypeMember : Symbol(nullPrototypeMember, Decl(erasableEnumErrors.ts, 75, 5)) +>NullPrototype : Symbol(NullPrototype, Decl(erasableEnumErrors.ts, 74, 5)) + +const __proto__ = "own"; +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 76, 5)) + +const PrototypeShorthand: enum = { __proto__ }; +>PrototypeShorthand : Symbol(PrototypeShorthand, Decl(erasableEnumErrors.ts, 77, 5)) +>__proto__ : Symbol(__proto__, Decl(erasableEnumErrors.ts, 77, 34)) + +// The annotation requires a named variable statement with an object literal initializer. +let NoInitializer: enum; +>NoInitializer : Symbol(NoInitializer, Decl(erasableEnumErrors.ts, 80, 3)) + +const NonObject: enum = 1; +>NonObject : Symbol(NonObject, Decl(erasableEnumErrors.ts, 81, 5)) + +const { Destructuring }: enum = { Destructuring: 1 }; +>Destructuring : Symbol(Destructuring, Decl(erasableEnumErrors.ts, 82, 7)) +>Destructuring : Symbol(Destructuring, Decl(erasableEnumErrors.ts, 82, 33)) + +for (const ForInitializer: enum = { A: 1 }; false; ) {} +>ForInitializer : Symbol(ForInitializer, Decl(erasableEnumErrors.ts, 83, 10)) +>A : Symbol(A, Decl(erasableEnumErrors.ts, 83, 35)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.types b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.types new file mode 100644 index 0000000000000..573d73699c8c2 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumErrors.types @@ -0,0 +1,408 @@ +//// [tests/cases/compiler/erasableEnumErrors.ts] //// + +=== erasableEnumErrors.ts === +// Members require explicit property assignments, even for constant bindings. +const UnboundShorthand: enum = { missing }; +>UnboundShorthand : typeof UnboundShorthand +>{ missing } : typeof UnboundShorthand +>missing : any + +const shorthandValue = 1; +>shorthandValue : 1 +>1 : 1 + +const Shorthand: enum = ({ shorthandValue }); +>Shorthand : typeof Shorthand +>({ shorthandValue }) : typeof Shorthand +>{ shorthandValue } : typeof Shorthand +>shorthandValue : number + +// Member values must be compile-time string or number constants. +declare const symbolValue: unique symbol; +>symbolValue : unique symbol + +const Invalid: enum = { +>Invalid : typeof Invalid +>{ True: true, False: false, Null: null, Object: {}, BigInt: 1n, Symbol: symbolValue,} : typeof Invalid + + True: true, +>True : any +>true : true + + False: false, +>False : any +>false : false + + Null: null, +>Null : any + + Object: {}, +>Object : any +>{} : {} + + BigInt: 1n, +>BigInt : any +>1n : 1n + + Symbol: symbolValue, +>Symbol : any +>symbolValue : unique symbol + +}; +const DynamicCall: enum = { Value: Math.random() }; +>DynamicCall : typeof DynamicCall +>{ Value: Math.random() } : typeof DynamicCall +>Value : any +>Math.random() : number +>Math.random : () => number +>Math : Math +>random : () => number + +const dynamicValue: DynamicCall = DynamicCall.Value; // no cascading type errors. +>dynamicValue : any +>DynamicCall.Value : any +>DynamicCall : typeof DynamicCall +>Value : any + +let mutable = 1; +>mutable : number +>1 : 1 + +const MutableValue: enum = { Value: mutable }; +>MutableValue : typeof MutableValue +>{ Value: mutable } : typeof MutableValue +>Value : any +>mutable : number + +const dynamic = Math.random(); +>dynamic : number +>Math.random() : number +>Math.random : () => number +>Math : Math +>random : () => number + +const NonconstantBinding: enum = { Value: dynamic }; +>NonconstantBinding : typeof NonconstantBinding +>{ Value: dynamic } : typeof NonconstantBinding +>Value : any +>dynamic : number + +declare const broadNumber: number; +>broadNumber : number + +declare const broadString: string; +>broadString : string + +const BroadValues: enum = { Number: broadNumber, String: broadString }; +>BroadValues : typeof BroadValues +>{ Number: broadNumber, String: broadString } : typeof BroadValues +>Number : any +>broadNumber : number +>String : any +>broadString : string + +// Assertions and satisfies expressions block constant evaluation, including through references. +const AssertionBoundary: enum = ({ Value: 1 as number, Nested: (1 as number) + 1 }); +>AssertionBoundary : typeof AssertionBoundary +>({ Value: 1 as number, Nested: (1 as number) + 1 }) : typeof AssertionBoundary +>{ Value: 1 as number, Nested: (1 as number) + 1 } : typeof AssertionBoundary +>Value : any +>1 as number : number +>1 : 1 +>Nested : any +>(1 as number) + 1 : number +>(1 as number) : number +>1 as number : number +>1 : 1 +>1 : 1 + +const SatisfiesBoundary: enum = { Value: "value" satisfies string }; +>SatisfiesBoundary : typeof SatisfiesBoundary +>{ Value: "value" satisfies string } : typeof SatisfiesBoundary +>Value : any +>"value" satisfies string : "value" +>"value" : "value" + +const asserted = 1 as number; +>asserted : number +>1 as number : number +>1 : 1 + +const checked = "value" satisfies string; +>checked : "value" +>"value" satisfies string : "value" +>"value" : "value" + +const ReferencedBoundaries: enum = { Asserted: asserted, Checked: checked }; +>ReferencedBoundaries : typeof ReferencedBoundaries +>{ Asserted: asserted, Checked: checked } : typeof ReferencedBoundaries +>Asserted : any +>asserted : number +>Checked : any +>checked : "value" + +// Names must be identifiers or strings; computed names are forbidden even when constant. +const NumericKey: enum = { 1: "one" }; +>NumericKey : typeof NumericKey +>{ 1: "one" } : typeof NumericKey +>1 : NumericKey +>"one" : "one" + +const ComputedKey: enum = { ["foo"]: 1 }; +>ComputedKey : typeof ComputedKey +>{ ["foo"]: 1 } : typeof ComputedKey +>["foo"] : number +>"foo" : "foo" +>1 : 1 + +const key = "Known"; +>key : "Known" +>"Known" : "Known" + +const ComputedKeyReference: enum = { [key]: 1 }; +>ComputedKeyReference : typeof ComputedKeyReference +>{ [key]: 1 } : typeof ComputedKeyReference +>[key] : number +>key : "Known" +>1 : 1 + +const ComputedPrototypeKey: enum = { ["__proto__"]: 1 }; +>ComputedPrototypeKey : typeof ComputedPrototypeKey +>{ ["__proto__"]: 1 } : typeof ComputedPrototypeKey +>["__proto__"] : number +>"__proto__" : "__proto__" +>1 : 1 + +const prototypeValue = ComputedPrototypeKey.__proto__; +>prototypeValue : any +>ComputedPrototypeKey.__proto__ : any +>ComputedPrototypeKey : typeof ComputedPrototypeKey +>__proto__ : any + +const Numeric: enum = { First: 1, Second: 2 }; +>Numeric : typeof Numeric +>{ First: 1, Second: 2 } : typeof Numeric +>First : Numeric.First +>1 : 1 +>Second : Numeric.Second +>2 : 2 + +// Const assertions on member references still block constant evaluation in initializers. +const MemberAssertionBoundary: enum = { Value: Numeric.First as const }; +>MemberAssertionBoundary : typeof MemberAssertionBoundary +>{ Value: Numeric.First as const } : typeof MemberAssertionBoundary +>Value : any +>Numeric.First as const : Numeric.First +>Numeric.First : Numeric.First +>Numeric : typeof Numeric +>First : Numeric.First + +const Spread: enum = { ...Numeric }; +>Spread : typeof Spread +>{ ...Numeric } : typeof Spread +>Numeric : typeof Numeric + +const Method: enum = { method() {} }; +>Method : typeof Method +>{ method() {} } : typeof Method +>method : () => void + +const Getter: enum = { get value() { return 1; } }; +>Getter : typeof Getter +>{ get value() { return 1; } } : typeof Getter +>value : number +>1 : 1 + +const Setter: enum = { set value(value: number) {} }; +>Setter : typeof Setter +>{ set value(value: number) {} } : typeof Setter +>value : number +>value : number + +// Members are readonly and numeric reverse mappings are absent. +Numeric.First = Numeric.Second; +>Numeric.First = Numeric.Second : Numeric.Second +>Numeric.First : any +>Numeric : typeof Numeric +>First : any +>Numeric.Second : Numeric.Second +>Numeric : typeof Numeric +>Second : Numeric.Second + +const reverse = Numeric[1]; +>reverse : any +>Numeric[1] : any +>Numeric : typeof Numeric +>1 : 1 + +const unknownKey = Numeric.Unknown; +>unknownKey : any +>Numeric.Unknown : any +>Numeric : typeof Numeric +>Unknown : any + +// Initializers use ordinary lexical bindings, without a scope for enum members. +const Unqualified: enum = { A: 1, B: A }; +>Unqualified : typeof Unqualified +>{ A: 1, B: A } : typeof Unqualified +>A : Unqualified +>1 : 1 +>B : any +>A : any + +const SelfReference: enum = { A: 1, B: SelfReference.A }; +>SelfReference : typeof SelfReference +>{ A: 1, B: SelfReference.A } : typeof SelfReference +>A : SelfReference +>1 : 1 +>B : any +>SelfReference.A : SelfReference.A +>SelfReference : typeof SelfReference +>A : SelfReference.A + +var VarSelfReference: enum = { A: 1, B: VarSelfReference.A }; +>VarSelfReference : typeof VarSelfReference +>{ A: 1, B: VarSelfReference.A } : typeof VarSelfReference +>A : VarSelfReference +>1 : 1 +>B : any +>VarSelfReference.A : VarSelfReference.A +>VarSelfReference : typeof VarSelfReference +>A : VarSelfReference.A + +// Deferred callbacks avoid initialization errors; calls are still nonconstant. +const Deferred: enum = { A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 }; +>Deferred : typeof Deferred +>{ A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 } : typeof Deferred +>A : any +>((f: () => number): number => 1)((): number => Deferred.B) : number +>((f: () => number): number => 1) : (f: () => number) => number +>(f: () => number): number => 1 : (f: () => number) => number +>f : () => number +>1 : 1 +>(): number => Deferred.B : () => number +>Deferred.B : Deferred.B +>Deferred : typeof Deferred +>B : Deferred.B +>B : Deferred +>1 : 1 + +const Immediate: enum = { A: ((): number => Immediate.B)(), B: 1 }; +>Immediate : typeof Immediate +>{ A: ((): number => Immediate.B)(), B: 1 } : typeof Immediate +>A : any +>((): number => Immediate.B)() : number +>((): number => Immediate.B) : () => number +>(): number => Immediate.B : () => number +>Immediate.B : Immediate.B +>Immediate : typeof Immediate +>B : Immediate.B +>B : Immediate +>1 : 1 + +const OuterMember = 10; +>OuterMember : 10 +>10 : 10 + +const Lexical: enum = { OuterMember: 1, Value: OuterMember }; +>Lexical : typeof Lexical +>{ OuterMember: 1, Value: OuterMember } : typeof Lexical +>OuterMember : Lexical.OuterMember +>1 : 1 +>Value : Lexical.Value +>OuterMember : 10 + +const lexicalValue: Lexical.Value = 10; // ok: Value refers to the outer constant. +>lexicalValue : Lexical.Value +>Lexical : any +>10 : 10 + +// Duplicate keys follow object literal rules; bindings cannot be redeclared. +const Duplicate: enum = { A: 1, A: 2 }; +>Duplicate : typeof Duplicate +>{ A: 1, A: 2 } : typeof Duplicate +>A : Duplicate.A +>1 : 1 +>A : Duplicate.A +>2 : 2 + +const Repeated: enum = { A: 1 }; +>Repeated : typeof Repeated +>{ A: 1 } : typeof Repeated +>A : Repeated +>1 : 1 + +const Repeated: enum = { B: 2 }; +>Repeated : typeof Repeated +>{ B: 2 } : typeof Repeated +>B : Repeated +>2 : 2 + +// Only a null prototype setter is allowed, and it does not declare an enum member. +const PrototypeKey: enum = { __proto__: 1 }; +>PrototypeKey : typeof PrototypeKey +>{ __proto__: 1 } : typeof PrototypeKey +>__proto__ : number +>1 : 1 + +const QuotedPrototypeKey: enum = { "__proto__": 1 }; +>QuotedPrototypeKey : typeof QuotedPrototypeKey +>{ "__proto__": 1 } : typeof QuotedPrototypeKey +>"__proto__" : number +>1 : 1 + +const PrototypeObject: enum = { __proto__: {} }; +>PrototypeObject : typeof PrototypeObject +>{ __proto__: {} } : typeof PrototypeObject +>__proto__ : {} +>{} : {} + +const AssertedPrototype: enum = { __proto__: null as null }; +>AssertedPrototype : typeof AssertedPrototype +>{ __proto__: null as null } : typeof AssertedPrototype +>__proto__ : null +>null as null : null + +const NullPrototype: enum = { __proto__: null, A: 1 }; +>NullPrototype : typeof NullPrototype +>{ __proto__: null, A: 1 } : typeof NullPrototype +>__proto__ : null +>A : NullPrototype +>1 : 1 + +const nullPrototypeMember = NullPrototype.__proto__; +>nullPrototypeMember : any +>NullPrototype.__proto__ : any +>NullPrototype : typeof NullPrototype +>__proto__ : any + +const __proto__ = "own"; +>__proto__ : "own" +>"own" : "own" + +const PrototypeShorthand: enum = { __proto__ }; +>PrototypeShorthand : typeof PrototypeShorthand +>{ __proto__ } : typeof PrototypeShorthand +>__proto__ : string + +// The annotation requires a named variable statement with an object literal initializer. +let NoInitializer: enum; +>NoInitializer : any + +const NonObject: enum = 1; +>NonObject : any +>1 : 1 + +const { Destructuring }: enum = { Destructuring: 1 }; +>Destructuring : any +>{ Destructuring: 1 } : { Destructuring: number; } +>Destructuring : number +>1 : 1 + +for (const ForInitializer: enum = { A: 1 }; false; ) {} +>ForInitializer : any +>{ A: 1 } : { A: number; } +>A : number +>1 : 1 +>false : false + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).js b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).js new file mode 100644 index 0000000000000..ef30787d14ce8 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).js @@ -0,0 +1,130 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +//// [enums.ts] +/** Public values. */ +export const Before = 0, Color: enum = { + Red: "red", + Blue: "blue", +}, After = 1; +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +export { Color as Shade }; +export enum Legacy { One = 1 } + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +export const alias = Local; +export function member() { + return Local.A; +} +export namespace Values { + export const E: enum = { A: 1, B: "b" }; + export const alias = E; + export const member: E.A = E.A; +} +//// [consumer.ts] +import { Color, Numeric, Shade } from "./enums"; +export const red: Color.Red = Color.Red as const; +export const shade: Shade = Color["Blue"] as const; +export const numeric: Numeric = Numeric.Shifted; +export function choose(color: Color): Color { + return color; +} +//// [references.ts] +import { Legacy } from "./enums"; +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +//// [folded.ts] +import { Legacy } from "./enums"; +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } + + +//// [enums.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Values = exports.alias = exports.Legacy = exports.Shade = exports.Numeric = exports.After = exports.Color = exports.Before = void 0; +exports.member = member; +/** Public values. */ +exports.Before = 0, exports.Color = { + Red: "red", + Blue: "blue", +}, exports.After = 1; +exports.Shade = exports.Color; +exports.Numeric = { One: 1, Shifted: 1 << 2 }; +var Legacy; +(function (Legacy) { + Legacy[Legacy["One"] = 1] = "One"; +})(Legacy || (exports.Legacy = Legacy = {})); +// Declaration emit retains reachable local types and prototype configuration. +const Local = { "__proto__": (null), A: 1, B: "b" }; +exports.alias = Local; +function member() { + return Local.A; +} +var Values; +(function (Values) { + Values.E = { A: 1, B: "b" }; + Values.alias = Values.E; + Values.member = Values.E.A; +})(Values || (exports.Values = Values = {})); +//// [consumer.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.numeric = exports.shade = exports.red = void 0; +exports.choose = choose; +const enums_1 = require("./enums"); +exports.red = enums_1.Color.Red; +exports.shade = enums_1.Color["Blue"]; +exports.numeric = enums_1.Numeric.Shifted; +function choose(color) { + return color; +} +//// [references.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FromLegacy = void 0; +const enums_1 = require("./enums"); +// Erased annotations preserve the import and runtime member accesses. +exports.FromLegacy = { Property: enums_1.Legacy.One, Index: enums_1.Legacy["One"] }; +//// [folded.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Folded = void 0; +// Traditional enum constant folding can still remove its otherwise unused import. +var Folded; +(function (Folded) { + Folded[Folded["One"] = 1] = "One"; +})(Folded || (exports.Folded = Folded = {})); + + +//// [enums.d.ts] +/** Public values. */ +export declare const Before = 0, Color: enum = { + Red: "red", + Blue: "blue" +}, After = 1; +export declare const Numeric: enum = { One: 1, Shifted: 4 }; +export { Color as Shade }; +export declare enum Legacy { + One = 1 +} +declare const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +export declare const alias: typeof Local; +export declare function member(): Local; +export declare namespace Values { + const E: enum = { A: 1, B: "b" }; + const alias: typeof E; + const member: E.A; +} +//// [consumer.d.ts] +import { Color, Numeric, Shade } from "./enums"; +export declare const red: Color.Red; +export declare const shade: Shade; +export declare const numeric: Numeric; +export declare function choose(color: Color): Color; +//// [references.d.ts] +export declare const FromLegacy: enum = { Property: 1, Index: 1 }; +//// [folded.d.ts] +export declare enum Folded { + One = 1 +} diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).symbols new file mode 100644 index 0000000000000..43ba08f61a1b4 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).symbols @@ -0,0 +1,134 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +=== enums.ts === +/** Public values. */ +export const Before = 0, Color: enum = { +>Before : Symbol(Before, Decl(enums.ts, 1, 12)) +>Color : Symbol(Color, Decl(enums.ts, 1, 24)) + + Red: "red", +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) + + Blue: "blue", +>Blue : Symbol(Color.Blue, Decl(enums.ts, 2, 15)) + +}, After = 1; +>After : Symbol(After, Decl(enums.ts, 4, 2)) + +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +>Numeric : Symbol(Numeric, Decl(enums.ts, 5, 12)) +>One : Symbol(Numeric.One, Decl(enums.ts, 5, 30)) +>Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) + +export { Color as Shade }; +>Color : Symbol(Color, Decl(enums.ts, 1, 24)) +>Shade : Symbol(Shade, Decl(enums.ts, 6, 8)) + +export enum Legacy { One = 1 } +>Legacy : Symbol(Legacy, Decl(enums.ts, 6, 26)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) +>"__proto__" : Symbol("__proto__", Decl(enums.ts, 10, 21)) +>A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +>B : Symbol(Local.B, Decl(enums.ts, 10, 48)) + +export const alias = Local; +>alias : Symbol(alias, Decl(enums.ts, 11, 12)) +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) + +export function member() { +>member : Symbol(member, Decl(enums.ts, 11, 27)) + + return Local.A; +>Local.A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) +>A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +} +export namespace Values { +>Values : Symbol(Values, Decl(enums.ts, 14, 1)) + + export const E: enum = { A: 1, B: "b" }; +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>B : Symbol(E.B, Decl(enums.ts, 16, 34)) + + export const alias = E; +>alias : Symbol(alias, Decl(enums.ts, 17, 16)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) + + export const member: E.A = E.A; +>member : Symbol(member, Decl(enums.ts, 18, 16)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>E.A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +} +=== consumer.ts === +import { Color, Numeric, Shade } from "./enums"; +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Shade : Symbol(Shade, Decl(consumer.ts, 0, 24)) + +export const red: Color.Red = Color.Red as const; +>red : Symbol(red, Decl(consumer.ts, 1, 12)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>Color.Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>const : Symbol(const) + +export const shade: Shade = Color["Blue"] as const; +>shade : Symbol(shade, Decl(consumer.ts, 2, 12)) +>Shade : Symbol(Shade, Decl(consumer.ts, 0, 24)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>"Blue" : Symbol(Color.Blue, Decl(enums.ts, 2, 15)) +>const : Symbol(const) + +export const numeric: Numeric = Numeric.Shifted; +>numeric : Symbol(numeric, Decl(consumer.ts, 3, 12)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Numeric.Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) + +export function choose(color: Color): Color { +>choose : Symbol(choose, Decl(consumer.ts, 3, 48)) +>color : Symbol(color, Decl(consumer.ts, 4, 23)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) + + return color; +>color : Symbol(color, Decl(consumer.ts, 4, 23)) +} +=== references.ts === +import { Legacy } from "./enums"; +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) + +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +>FromLegacy : Symbol(FromLegacy, Decl(references.ts, 2, 12)) +>Property : Symbol(FromLegacy.Property, Decl(references.ts, 2, 33)) +>Legacy.One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Index : Symbol(FromLegacy.Index, Decl(references.ts, 2, 55)) +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) +>"One" : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + +=== folded.ts === +import { Legacy } from "./enums"; +>Legacy : Symbol(Legacy, Decl(folded.ts, 0, 8)) + +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } +>Folded : Symbol(Folded, Decl(folded.ts, 0, 33)) +>One : Symbol(Folded.One, Decl(folded.ts, 2, 20)) +>Legacy.One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Legacy : Symbol(Legacy, Decl(folded.ts, 0, 8)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).types b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).types new file mode 100644 index 0000000000000..5c0719759a4fb --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=commonjs).types @@ -0,0 +1,149 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +=== enums.ts === +/** Public values. */ +export const Before = 0, Color: enum = { +>Before : 0 +>0 : 0 +>Color : typeof Color +>{ Red: "red", Blue: "blue",} : typeof Color + + Red: "red", +>Red : Color.Red +>"red" : "red" + + Blue: "blue", +>Blue : Color.Blue +>"blue" : "blue" + +}, After = 1; +>After : 1 +>1 : 1 + +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +>Numeric : typeof Numeric +>{ One: 1, Shifted: 1 << 2 } : typeof Numeric +>One : Numeric.One +>1 : 1 +>Shifted : Numeric.Shifted +>1 << 2 : number +>1 : 1 +>2 : 2 + +export { Color as Shade }; +>Color : typeof Color +>Shade : typeof Color + +export enum Legacy { One = 1 } +>Legacy : Legacy +>One : Legacy.One +>1 : 1 + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +>Local : typeof Local +>{ "__proto__": (null), A: 1, B: "b" } : typeof Local +>"__proto__" : null +>(null) : null +>A : Local.A +>1 : 1 +>B : Local.B +>"b" : "b" + +export const alias = Local; +>alias : typeof Local +>Local : typeof Local + +export function member() { +>member : () => Local + + return Local.A; +>Local.A : Local.A +>Local : typeof Local +>A : Local.A +} +export namespace Values { +>Values : typeof Values + + export const E: enum = { A: 1, B: "b" }; +>E : typeof E +>{ A: 1, B: "b" } : typeof E +>A : E.A +>1 : 1 +>B : E.B +>"b" : "b" + + export const alias = E; +>alias : typeof E +>E : typeof E + + export const member: E.A = E.A; +>member : E.A +>E : any +>E.A : E.A +>E : typeof E +>A : E.A +} +=== consumer.ts === +import { Color, Numeric, Shade } from "./enums"; +>Color : typeof Color +>Numeric : typeof Numeric +>Shade : typeof Color + +export const red: Color.Red = Color.Red as const; +>red : Color.Red +>Color : any +>Color.Red as const : Color.Red +>Color.Red : Color.Red +>Color : typeof Color +>Red : Color.Red + +export const shade: Shade = Color["Blue"] as const; +>shade : Color +>Color["Blue"] as const : Color.Blue +>Color["Blue"] : Color.Blue +>Color : typeof Color +>"Blue" : "Blue" + +export const numeric: Numeric = Numeric.Shifted; +>numeric : Numeric +>Numeric.Shifted : Numeric.Shifted +>Numeric : typeof Numeric +>Shifted : Numeric.Shifted + +export function choose(color: Color): Color { +>choose : (color: Color) => Color +>color : Color + + return color; +>color : Color +} +=== references.ts === +import { Legacy } from "./enums"; +>Legacy : typeof Legacy + +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +>FromLegacy : typeof FromLegacy +>{ Property: Legacy.One, Index: Legacy["One"] } : typeof FromLegacy +>Property : FromLegacy +>Legacy.One : Legacy +>Legacy : typeof Legacy +>One : Legacy +>Index : FromLegacy +>Legacy["One"] : Legacy +>Legacy : typeof Legacy +>"One" : "One" + +=== folded.ts === +import { Legacy } from "./enums"; +>Legacy : typeof Legacy + +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } +>Folded : Folded +>One : Folded.One +>Legacy.One : Legacy +>Legacy : typeof Legacy +>One : Legacy + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).js b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).js new file mode 100644 index 0000000000000..ded1112a72a41 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).js @@ -0,0 +1,116 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +//// [enums.ts] +/** Public values. */ +export const Before = 0, Color: enum = { + Red: "red", + Blue: "blue", +}, After = 1; +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +export { Color as Shade }; +export enum Legacy { One = 1 } + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +export const alias = Local; +export function member() { + return Local.A; +} +export namespace Values { + export const E: enum = { A: 1, B: "b" }; + export const alias = E; + export const member: E.A = E.A; +} +//// [consumer.ts] +import { Color, Numeric, Shade } from "./enums"; +export const red: Color.Red = Color.Red as const; +export const shade: Shade = Color["Blue"] as const; +export const numeric: Numeric = Numeric.Shifted; +export function choose(color: Color): Color { + return color; +} +//// [references.ts] +import { Legacy } from "./enums"; +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +//// [folded.ts] +import { Legacy } from "./enums"; +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } + + +//// [enums.js] +/** Public values. */ +export const Before = 0, Color = { + Red: "red", + Blue: "blue", +}, After = 1; +export const Numeric = { One: 1, Shifted: 1 << 2 }; +export { Color as Shade }; +export var Legacy; +(function (Legacy) { + Legacy[Legacy["One"] = 1] = "One"; +})(Legacy || (Legacy = {})); +// Declaration emit retains reachable local types and prototype configuration. +const Local = { "__proto__": (null), A: 1, B: "b" }; +export const alias = Local; +export function member() { + return Local.A; +} +export var Values; +(function (Values) { + Values.E = { A: 1, B: "b" }; + Values.alias = Values.E; + Values.member = Values.E.A; +})(Values || (Values = {})); +//// [consumer.js] +import { Color, Numeric } from "./enums"; +export const red = Color.Red; +export const shade = Color["Blue"]; +export const numeric = Numeric.Shifted; +export function choose(color) { + return color; +} +//// [references.js] +import { Legacy } from "./enums"; +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy = { Property: Legacy.One, Index: Legacy["One"] }; +//// [folded.js] +// Traditional enum constant folding can still remove its otherwise unused import. +export var Folded; +(function (Folded) { + Folded[Folded["One"] = 1] = "One"; +})(Folded || (Folded = {})); + + +//// [enums.d.ts] +/** Public values. */ +export declare const Before = 0, Color: enum = { + Red: "red", + Blue: "blue" +}, After = 1; +export declare const Numeric: enum = { One: 1, Shifted: 4 }; +export { Color as Shade }; +export declare enum Legacy { + One = 1 +} +declare const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +export declare const alias: typeof Local; +export declare function member(): Local; +export declare namespace Values { + const E: enum = { A: 1, B: "b" }; + const alias: typeof E; + const member: E.A; +} +//// [consumer.d.ts] +import { Color, Numeric, Shade } from "./enums"; +export declare const red: Color.Red; +export declare const shade: Shade; +export declare const numeric: Numeric; +export declare function choose(color: Color): Color; +//// [references.d.ts] +export declare const FromLegacy: enum = { Property: 1, Index: 1 }; +//// [folded.d.ts] +export declare enum Folded { + One = 1 +} diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).symbols b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).symbols new file mode 100644 index 0000000000000..43ba08f61a1b4 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).symbols @@ -0,0 +1,134 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +=== enums.ts === +/** Public values. */ +export const Before = 0, Color: enum = { +>Before : Symbol(Before, Decl(enums.ts, 1, 12)) +>Color : Symbol(Color, Decl(enums.ts, 1, 24)) + + Red: "red", +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) + + Blue: "blue", +>Blue : Symbol(Color.Blue, Decl(enums.ts, 2, 15)) + +}, After = 1; +>After : Symbol(After, Decl(enums.ts, 4, 2)) + +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +>Numeric : Symbol(Numeric, Decl(enums.ts, 5, 12)) +>One : Symbol(Numeric.One, Decl(enums.ts, 5, 30)) +>Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) + +export { Color as Shade }; +>Color : Symbol(Color, Decl(enums.ts, 1, 24)) +>Shade : Symbol(Shade, Decl(enums.ts, 6, 8)) + +export enum Legacy { One = 1 } +>Legacy : Symbol(Legacy, Decl(enums.ts, 6, 26)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) +>"__proto__" : Symbol("__proto__", Decl(enums.ts, 10, 21)) +>A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +>B : Symbol(Local.B, Decl(enums.ts, 10, 48)) + +export const alias = Local; +>alias : Symbol(alias, Decl(enums.ts, 11, 12)) +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) + +export function member() { +>member : Symbol(member, Decl(enums.ts, 11, 27)) + + return Local.A; +>Local.A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +>Local : Symbol(Local, Decl(enums.ts, 10, 5)) +>A : Symbol(Local.A, Decl(enums.ts, 10, 42)) +} +export namespace Values { +>Values : Symbol(Values, Decl(enums.ts, 14, 1)) + + export const E: enum = { A: 1, B: "b" }; +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>B : Symbol(E.B, Decl(enums.ts, 16, 34)) + + export const alias = E; +>alias : Symbol(alias, Decl(enums.ts, 17, 16)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) + + export const member: E.A = E.A; +>member : Symbol(member, Decl(enums.ts, 18, 16)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>E.A : Symbol(E.A, Decl(enums.ts, 16, 28)) +>E : Symbol(E, Decl(enums.ts, 16, 16)) +>A : Symbol(E.A, Decl(enums.ts, 16, 28)) +} +=== consumer.ts === +import { Color, Numeric, Shade } from "./enums"; +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Shade : Symbol(Shade, Decl(consumer.ts, 0, 24)) + +export const red: Color.Red = Color.Red as const; +>red : Symbol(red, Decl(consumer.ts, 1, 12)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>Color.Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Red : Symbol(Color.Red, Decl(enums.ts, 1, 40)) +>const : Symbol(const) + +export const shade: Shade = Color["Blue"] as const; +>shade : Symbol(shade, Decl(consumer.ts, 2, 12)) +>Shade : Symbol(Shade, Decl(consumer.ts, 0, 24)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>"Blue" : Symbol(Color.Blue, Decl(enums.ts, 2, 15)) +>const : Symbol(const) + +export const numeric: Numeric = Numeric.Shifted; +>numeric : Symbol(numeric, Decl(consumer.ts, 3, 12)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Numeric.Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) +>Numeric : Symbol(Numeric, Decl(consumer.ts, 0, 15)) +>Shifted : Symbol(Numeric.Shifted, Decl(enums.ts, 5, 38)) + +export function choose(color: Color): Color { +>choose : Symbol(choose, Decl(consumer.ts, 3, 48)) +>color : Symbol(color, Decl(consumer.ts, 4, 23)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) +>Color : Symbol(Color, Decl(consumer.ts, 0, 8)) + + return color; +>color : Symbol(color, Decl(consumer.ts, 4, 23)) +} +=== references.ts === +import { Legacy } from "./enums"; +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) + +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +>FromLegacy : Symbol(FromLegacy, Decl(references.ts, 2, 12)) +>Property : Symbol(FromLegacy.Property, Decl(references.ts, 2, 33)) +>Legacy.One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Index : Symbol(FromLegacy.Index, Decl(references.ts, 2, 55)) +>Legacy : Symbol(Legacy, Decl(references.ts, 0, 8)) +>"One" : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + +=== folded.ts === +import { Legacy } from "./enums"; +>Legacy : Symbol(Legacy, Decl(folded.ts, 0, 8)) + +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } +>Folded : Symbol(Folded, Decl(folded.ts, 0, 33)) +>One : Symbol(Folded.One, Decl(folded.ts, 2, 20)) +>Legacy.One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) +>Legacy : Symbol(Legacy, Decl(folded.ts, 0, 8)) +>One : Symbol(Legacy.One, Decl(enums.ts, 7, 20)) + diff --git a/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).types b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).types new file mode 100644 index 0000000000000..5c0719759a4fb --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/erasableEnumModules(module=esnext).types @@ -0,0 +1,149 @@ +//// [tests/cases/compiler/erasableEnumModules.ts] //// + +=== enums.ts === +/** Public values. */ +export const Before = 0, Color: enum = { +>Before : 0 +>0 : 0 +>Color : typeof Color +>{ Red: "red", Blue: "blue",} : typeof Color + + Red: "red", +>Red : Color.Red +>"red" : "red" + + Blue: "blue", +>Blue : Color.Blue +>"blue" : "blue" + +}, After = 1; +>After : 1 +>1 : 1 + +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +>Numeric : typeof Numeric +>{ One: 1, Shifted: 1 << 2 } : typeof Numeric +>One : Numeric.One +>1 : 1 +>Shifted : Numeric.Shifted +>1 << 2 : number +>1 : 1 +>2 : 2 + +export { Color as Shade }; +>Color : typeof Color +>Shade : typeof Color + +export enum Legacy { One = 1 } +>Legacy : Legacy +>One : Legacy.One +>1 : 1 + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +>Local : typeof Local +>{ "__proto__": (null), A: 1, B: "b" } : typeof Local +>"__proto__" : null +>(null) : null +>A : Local.A +>1 : 1 +>B : Local.B +>"b" : "b" + +export const alias = Local; +>alias : typeof Local +>Local : typeof Local + +export function member() { +>member : () => Local + + return Local.A; +>Local.A : Local.A +>Local : typeof Local +>A : Local.A +} +export namespace Values { +>Values : typeof Values + + export const E: enum = { A: 1, B: "b" }; +>E : typeof E +>{ A: 1, B: "b" } : typeof E +>A : E.A +>1 : 1 +>B : E.B +>"b" : "b" + + export const alias = E; +>alias : typeof E +>E : typeof E + + export const member: E.A = E.A; +>member : E.A +>E : any +>E.A : E.A +>E : typeof E +>A : E.A +} +=== consumer.ts === +import { Color, Numeric, Shade } from "./enums"; +>Color : typeof Color +>Numeric : typeof Numeric +>Shade : typeof Color + +export const red: Color.Red = Color.Red as const; +>red : Color.Red +>Color : any +>Color.Red as const : Color.Red +>Color.Red : Color.Red +>Color : typeof Color +>Red : Color.Red + +export const shade: Shade = Color["Blue"] as const; +>shade : Color +>Color["Blue"] as const : Color.Blue +>Color["Blue"] : Color.Blue +>Color : typeof Color +>"Blue" : "Blue" + +export const numeric: Numeric = Numeric.Shifted; +>numeric : Numeric +>Numeric.Shifted : Numeric.Shifted +>Numeric : typeof Numeric +>Shifted : Numeric.Shifted + +export function choose(color: Color): Color { +>choose : (color: Color) => Color +>color : Color + + return color; +>color : Color +} +=== references.ts === +import { Legacy } from "./enums"; +>Legacy : typeof Legacy + +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +>FromLegacy : typeof FromLegacy +>{ Property: Legacy.One, Index: Legacy["One"] } : typeof FromLegacy +>Property : FromLegacy +>Legacy.One : Legacy +>Legacy : typeof Legacy +>One : Legacy +>Index : FromLegacy +>Legacy["One"] : Legacy +>Legacy : typeof Legacy +>"One" : "One" + +=== folded.ts === +import { Legacy } from "./enums"; +>Legacy : typeof Legacy + +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One } +>Folded : Folded +>One : Folded.One +>Legacy.One : Legacy +>Legacy : typeof Legacy +>One : Legacy + diff --git a/tsc/testdata/tests/cases/compiler/erasableEnumBasics.ts b/tsc/testdata/tests/cases/compiler/erasableEnumBasics.ts new file mode 100644 index 0000000000000..3b447d1efe68a --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/erasableEnumBasics.ts @@ -0,0 +1,34 @@ +// @strict: true + +const existingValue = "exists"; +const E: enum = { + Existing: existingValue, + Int: 1, + String: "string", + Flag: 8, +}; + +// Members are assignable to their enum type and their own member type. +let value: E = E.Existing; +value = E.Int; +value = E.String; +let intMember: E.Int = E.Int; +intMember = E.Flag; // error: a different known member. + +// Matching numeric literals are accepted, but other known literals are rejected. +value = 1; +value = 4; // error + +// String members retain nominal types, including values from constant references. +value = "exists"; // error +value = "string"; // error +const Other: enum = { String: "string" }; +value = Other.String; // error: members from different enums are incompatible. +let other: Other = Other.String; +other = "string"; // error: a single-member enum is also nominal. +other = E.String; // error +value = undefined; // error + +// Number expressions retain TypeScript's numeric enum compatibility. +value = E.Int | E.Flag; +intMember = E.Int | E.Flag; diff --git a/tsc/testdata/tests/cases/compiler/erasableEnumConstants.ts b/tsc/testdata/tests/cases/compiler/erasableEnumConstants.ts new file mode 100644 index 0000000000000..0829d196fe642 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/erasableEnumConstants.ts @@ -0,0 +1,26 @@ +// @strict: true +// @target: esnext +// @module: esnext +// @isolatedModules: true +// @declaration: true +// @filename: values.ts +export const text = "hello"; +export const count = 2; +// Numeric strings are string keys; indexing follows ordinary object rules. +export const Source: enum = { A: "source", B: 1, "1": "numeric" }; +// @filename: consumer.ts +import { text, count, Source } from "./values"; +const Local: enum = { Value: "local" }; +// Parentheses are transparent for constant values and member references. +export const E: enum = { + __proto__: null, + Text: ((text)), + Count: (count) + 1, + ImportedMember: (Source.A), + ImportedIndex: Source[("B")], + NumericIndex: Source[(1)], + LocalMember: Local.Value, + LocalIndex: Local["Value"], +}; +export let value: E = E.Text; +export let member: E.ImportedMember = E.ImportedMember; diff --git a/tsc/testdata/tests/cases/compiler/erasableEnumErasure.ts b/tsc/testdata/tests/cases/compiler/erasableEnumErasure.ts new file mode 100644 index 0000000000000..17b68fb6bfcdb --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/erasableEnumErasure.ts @@ -0,0 +1,53 @@ +// @strict: true +// @erasableSyntaxOnly: true +// @target: esnext +// @declaration: true + +const outer = 4; +const Numeric: enum = (({ + // Preserve member comments and ordinary JavaScript expressions. + First: /* Preserve initializer comments. */ (1), + Second: (outer + 1), + Shifted: outer << 1, +})); +const StringValues: enum = { + /** An enum member. */ + First: "first", + Second: "second", +}; +let numeric: Numeric = Numeric.First; +let member: Numeric.First = Numeric.First; +let text: StringValues = StringValues.Second; +const constMember = StringValues.First as const; +const constIndexed = StringValues["First"] as const; +const keys: keyof typeof StringValues = "First"; +const object: typeof StringValues = StringValues; +function narrow(value: StringValues) { + if (value === StringValues.First) { + const first: StringValues.First = value; + return first; + } + const second: StringValues.Second = value; + return second; +} +function scoped() { + const Local: enum = { Value: "local" }; + const value: Local.Value = Local.Value; + return value as string; +} +namespace Types { + export type Value = StringValues; +} + +var Variable: enum = { Value: 1 }; +const variable: Variable = Variable.Value; +declare const Ambient: enum = { A: 1, B: (0) }; +const ambient: Ambient = Ambient.B; + +// Enums without members have the never type, including prototype-only objects. +const Empty: enum = {}; +declare const empty: Empty; +const emptyValue: never = empty; +const PrototypeOnly: enum = { __proto__: null }; +declare const prototypeOnly: PrototypeOnly; +const prototypeOnlyValue: never = prototypeOnly; diff --git a/tsc/testdata/tests/cases/compiler/erasableEnumErrors.ts b/tsc/testdata/tests/cases/compiler/erasableEnumErrors.ts new file mode 100644 index 0000000000000..7174f3874ca7b --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/erasableEnumErrors.ts @@ -0,0 +1,87 @@ +// @strict: true +// @target: esnext + +// Members require explicit property assignments, even for constant bindings. +const UnboundShorthand: enum = { missing }; +const shorthandValue = 1; +const Shorthand: enum = ({ shorthandValue }); + +// Member values must be compile-time string or number constants. +declare const symbolValue: unique symbol; +const Invalid: enum = { + True: true, + False: false, + Null: null, + Object: {}, + BigInt: 1n, + Symbol: symbolValue, +}; +const DynamicCall: enum = { Value: Math.random() }; +const dynamicValue: DynamicCall = DynamicCall.Value; // no cascading type errors. +let mutable = 1; +const MutableValue: enum = { Value: mutable }; +const dynamic = Math.random(); +const NonconstantBinding: enum = { Value: dynamic }; +declare const broadNumber: number; +declare const broadString: string; +const BroadValues: enum = { Number: broadNumber, String: broadString }; + +// Assertions and satisfies expressions block constant evaluation, including through references. +const AssertionBoundary: enum = ({ Value: 1 as number, Nested: (1 as number) + 1 }); +const SatisfiesBoundary: enum = { Value: "value" satisfies string }; +const asserted = 1 as number; +const checked = "value" satisfies string; +const ReferencedBoundaries: enum = { Asserted: asserted, Checked: checked }; + +// Names must be identifiers or strings; computed names are forbidden even when constant. +const NumericKey: enum = { 1: "one" }; +const ComputedKey: enum = { ["foo"]: 1 }; +const key = "Known"; +const ComputedKeyReference: enum = { [key]: 1 }; +const ComputedPrototypeKey: enum = { ["__proto__"]: 1 }; +const prototypeValue = ComputedPrototypeKey.__proto__; + +const Numeric: enum = { First: 1, Second: 2 }; +// Const assertions on member references still block constant evaluation in initializers. +const MemberAssertionBoundary: enum = { Value: Numeric.First as const }; +const Spread: enum = { ...Numeric }; +const Method: enum = { method() {} }; +const Getter: enum = { get value() { return 1; } }; +const Setter: enum = { set value(value: number) {} }; + +// Members are readonly and numeric reverse mappings are absent. +Numeric.First = Numeric.Second; +const reverse = Numeric[1]; +const unknownKey = Numeric.Unknown; + +// Initializers use ordinary lexical bindings, without a scope for enum members. +const Unqualified: enum = { A: 1, B: A }; +const SelfReference: enum = { A: 1, B: SelfReference.A }; +var VarSelfReference: enum = { A: 1, B: VarSelfReference.A }; +// Deferred callbacks avoid initialization errors; calls are still nonconstant. +const Deferred: enum = { A: ((f: () => number): number => 1)((): number => Deferred.B), B: 1 }; +const Immediate: enum = { A: ((): number => Immediate.B)(), B: 1 }; +const OuterMember = 10; +const Lexical: enum = { OuterMember: 1, Value: OuterMember }; +const lexicalValue: Lexical.Value = 10; // ok: Value refers to the outer constant. + +// Duplicate keys follow object literal rules; bindings cannot be redeclared. +const Duplicate: enum = { A: 1, A: 2 }; +const Repeated: enum = { A: 1 }; +const Repeated: enum = { B: 2 }; + +// Only a null prototype setter is allowed, and it does not declare an enum member. +const PrototypeKey: enum = { __proto__: 1 }; +const QuotedPrototypeKey: enum = { "__proto__": 1 }; +const PrototypeObject: enum = { __proto__: {} }; +const AssertedPrototype: enum = { __proto__: null as null }; +const NullPrototype: enum = { __proto__: null, A: 1 }; +const nullPrototypeMember = NullPrototype.__proto__; +const __proto__ = "own"; +const PrototypeShorthand: enum = { __proto__ }; + +// The annotation requires a named variable statement with an object literal initializer. +let NoInitializer: enum; +const NonObject: enum = 1; +const { Destructuring }: enum = { Destructuring: 1 }; +for (const ForInitializer: enum = { A: 1 }; false; ) {} diff --git a/tsc/testdata/tests/cases/compiler/erasableEnumModules.ts b/tsc/testdata/tests/cases/compiler/erasableEnumModules.ts new file mode 100644 index 0000000000000..77bd8e3abebae --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/erasableEnumModules.ts @@ -0,0 +1,41 @@ +// @strict: true +// @target: esnext +// @module: commonjs, esnext +// @declaration: true +// @filename: enums.ts +/** Public values. */ +export const Before = 0, Color: enum = { + Red: "red", + Blue: "blue", +}, After = 1; +export const Numeric: enum = { One: 1, Shifted: 1 << 2 }; +export { Color as Shade }; +export enum Legacy { One = 1 } + +// Declaration emit retains reachable local types and prototype configuration. +const Local: enum = { "__proto__": (null), A: 1, B: "b" }; +export const alias = Local; +export function member() { + return Local.A; +} +export namespace Values { + export const E: enum = { A: 1, B: "b" }; + export const alias = E; + export const member: E.A = E.A; +} +// @filename: consumer.ts +import { Color, Numeric, Shade } from "./enums"; +export const red: Color.Red = Color.Red as const; +export const shade: Shade = Color["Blue"] as const; +export const numeric: Numeric = Numeric.Shifted; +export function choose(color: Color): Color { + return color; +} +// @filename: references.ts +import { Legacy } from "./enums"; +// Erased annotations preserve the import and runtime member accesses. +export const FromLegacy: enum = { Property: Legacy.One, Index: Legacy["One"] }; +// @filename: folded.ts +import { Legacy } from "./enums"; +// Traditional enum constant folding can still remove its otherwise unused import. +export enum Folded { One = Legacy.One }