Skip to content

Allow references to const enums when provably emitted via preserveConstEnums #57996

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34722,7 +34722,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
return objectType;
}

if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression)) {
if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression) && !isUseOfPreservedConstEnum(node, objectType)) {
error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
return errorType;
}
Expand Down Expand Up @@ -40836,7 +40836,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
(node.parent.kind === SyntaxKind.TypeQuery && (node.parent as TypeQueryNode).exprName === node)) ||
(node.parent.kind === SyntaxKind.ExportSpecifier); // We allow reexporting const enums

if (!ok) {
if (!ok && !isUseOfPreservedConstEnum(node, type)) {
error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
}

Expand All @@ -40856,15 +40856,27 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
/*excludeGlobals*/ true,
)
) {
Debug.assert(!!(type.symbol.flags & SymbolFlags.ConstEnum));
const constEnumDeclaration = type.symbol.valueDeclaration as EnumDeclaration;
const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
if (constEnumDeclaration.flags & NodeFlags.Ambient && !isValidTypeOnlyAliasUseSite(node) && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
if (!isUseOfPreservedConstEnum(node, type)) {
error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
}
}
}

function isUseOfPreservedConstEnum(use: Node, enumType: Type) {
Debug.assert(!!(enumType.symbol.flags & SymbolFlags.ConstEnum));
const constEnumDeclaration = enumType.symbol.valueDeclaration as EnumDeclaration;
if (constEnumDeclaration.flags & NodeFlags.Ambient && isValidTypeOnlyAliasUseSite(use)) {
return true;
}
const otherFile = getSourceFileOfNode(constEnumDeclaration);
if (!otherFile.isDeclarationFile) {
// This file can only have come from the current project.
return shouldPreserveConstEnums(compilerOptions);
}
const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(otherFile.resolvedPath);
return redirect && shouldPreserveConstEnums(redirect.commandLine.options);
}

function checkParenthesizedExpression(node: ParenthesizedExpression, checkMode?: CheckMode): Type {
if (hasJSDocNodes(node)) {
if (isJSDocSatisfiesExpression(node)) {
Expand Down
43 changes: 43 additions & 0 deletions src/testRunner/unittests/tsc/projectReferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,47 @@ describe("unittests:: tsc:: projectReferences::", () => {
}),
commandLineArgs: ["--p", "src/project", "--pretty", "false"],
});

verifyTsc({
scenario: "projectReferences",
subScenario: "referencing ambient const enum as value from referenced project with preserveConstEnums",
fs: () =>
loadProjectFromFiles({
"/src/utils/index.ts": "export const enum E { A = 1 }",
"/src/utils/index.d.ts": "export declare const enum E { A = 1 }",
"/src/utils/tsconfig.json": jsonToReadableText({
compilerOptions: {
composite: true,
declaration: true,
preserveConstEnums: true,
},
}),
"/src/utilsNonPreserved/index.ts": "export const enum E2 { A = 1 }",
"/src/utilsNonPreserved/index.d.ts": "export declare const enum E2 { A = 1 }",
"/src/utilsNonPreserved/tsconfig.json": jsonToReadableText({
compilerOptions: {
composite: true,
declaration: true,
preserveConstEnums: false,
},
}),
"/src/project/index.ts": `
import { E } from "../utils";
import { E2 } from "../utilsNonPreserved";

E; declare const x: E; E[x];

E2; declare const y: E2; E2[y];
`,
"/src/project/tsconfig.json": jsonToReadableText({
compilerOptions: {
isolatedModules: true,
},
references: [
{ path: "../utils" },
],
}),
}),
commandLineArgs: ["--p", "src/project"],
});
});
48 changes: 48 additions & 0 deletions src/testRunner/unittests/tsserver/projectReferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,54 @@ function foo() {
baselineTsserverLogs("projectReferences", `referencing const enum from referenced project with preserveConstEnums`, session);
});

it("referencing const enum as value from referenced project with preserveConstEnums", () => {
const projectLocation = `/user/username/projects/project`;
const utilsIndex: File = {
path: `${projectLocation}/src/utils/index.ts`,
content: "export const enum E { A = 1 }",
};
const utilsDeclaration: File = {
path: `${projectLocation}/src/utils/index.d.ts`,
content: "export declare const enum E { A = 1 }",
};
const utilsConfig: File = {
path: `${projectLocation}/src/utils/tsconfig.json`,
content: jsonToReadableText({ compilerOptions: { composite: true, declaration: true, preserveConstEnums: true } }),
};
const utilsNonPreservedIndex: File = {
path: `${projectLocation}/src/utilsNonPreserved/index.ts`,
content: "export const enum E2 { A = 1 }",
};
const utilsNonPreservedDeclaration: File = {
path: `${projectLocation}/src/utilsNonPreserved/index.d.ts`,
content: "export declare const enum E2 { A = 1 }",
};
const utilsNonPreservedConfig: File = {
path: `${projectLocation}/src/utilsNonPreserved/tsconfig.json`,
content: jsonToReadableText({ compilerOptions: { composite: true, declaration: true, preserveConstEnums: false } }),
};
const projectIndex: File = {
path: `${projectLocation}/src/project/index.ts`,
content: `
import { E } from "../utils";
import { E2 } from "../utilsNonPreserved";

E; declare const x: E; E[x];

E2; declare const y: E2; E2[y];
`,
};
const projectConfig: File = {
path: `${projectLocation}/src/project/tsconfig.json`,
content: jsonToReadableText({ compilerOptions: { isolatedModules: true }, references: [{ path: "../utils" }, { path: "../utilsNoPreserved" }] }),
};
const host = createServerHost([libFile, utilsIndex, utilsDeclaration, utilsConfig, utilsNonPreservedIndex, utilsNonPreservedDeclaration, utilsNonPreservedConfig, projectIndex, projectConfig]);
const session = new TestSession(host);
openFilesForSession([projectIndex], session);
verifyGetErrRequest({ session, files: [projectIndex] });
baselineTsserverLogs("projectReferences", `referencing const enum as value from referenced project with preserveConstEnums`, session);
});

describe("when references are monorepo like with symlinks", () => {
interface Packages {
bPackageJson: File;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
constEnumUsedAsValue.ts(9,1): error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.
constEnumUsedAsValue.ts(10,3): error TS2476: A const enum member can only be accessed using a string literal.


==== constEnumUsedAsValue.ts (2 errors) ====
const enum E {
A,
B,
C,
}

declare const x: E;

E;
~
!!! error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.
E[x];
~
!!! error TS2476: A const enum member can only be accessed using a string literal.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

//// [constEnumUsedAsValue.ts]
const enum E {
A,
B,
C,
}

declare const x: E;

E;
E[x];

//// [constEnumUsedAsValue.js]
"use strict";
E;
E[x];
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

=== constEnumUsedAsValue.ts ===
const enum E {
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

A,
>A : Symbol(E.A, Decl(constEnumUsedAsValue.ts, 0, 14))

B,
>B : Symbol(E.B, Decl(constEnumUsedAsValue.ts, 1, 6))

C,
>C : Symbol(E.C, Decl(constEnumUsedAsValue.ts, 2, 6))
}

declare const x: E;
>x : Symbol(x, Decl(constEnumUsedAsValue.ts, 6, 13))
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

E;
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

E[x];
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))
>x : Symbol(x, Decl(constEnumUsedAsValue.ts, 6, 13))

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

=== constEnumUsedAsValue.ts ===
const enum E {
>E : E
> : ^

A,
>A : E.A
> : ^^^

B,
>B : E.B
> : ^^^

C,
>C : E.C
> : ^^^
}

declare const x: E;
>x : E
> : ^

E;
>E : typeof E
> : ^^^^^^^^

E[x];
>E[x] : any
> : ^^^
>E : typeof E
> : ^^^^^^^^
>x : E
> : ^

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

//// [constEnumUsedAsValue.ts]
const enum E {
A,
B,
C,
}

declare const x: E;

E;
E[x];

//// [constEnumUsedAsValue.js]
"use strict";
var E;
(function (E) {
E[E["A"] = 0] = "A";
E[E["B"] = 1] = "B";
E[E["C"] = 2] = "C";
})(E || (E = {}));
E;
E[x];
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

=== constEnumUsedAsValue.ts ===
const enum E {
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

A,
>A : Symbol(E.A, Decl(constEnumUsedAsValue.ts, 0, 14))

B,
>B : Symbol(E.B, Decl(constEnumUsedAsValue.ts, 1, 6))

C,
>C : Symbol(E.C, Decl(constEnumUsedAsValue.ts, 2, 6))
}

declare const x: E;
>x : Symbol(x, Decl(constEnumUsedAsValue.ts, 6, 13))
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

E;
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))

E[x];
>E : Symbol(E, Decl(constEnumUsedAsValue.ts, 0, 0))
>x : Symbol(x, Decl(constEnumUsedAsValue.ts, 6, 13))

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//// [tests/cases/compiler/constEnumUsedAsValue.ts] ////

=== constEnumUsedAsValue.ts ===
const enum E {
>E : E
> : ^

A,
>A : E.A
> : ^^^

B,
>B : E.B
> : ^^^

C,
>C : E.C
> : ^^^
}

declare const x: E;
>x : E
> : ^

E;
>E : typeof E
> : ^^^^^^^^

E[x];
>E[x] : string
> : ^^^^^^
>E : typeof E
> : ^^^^^^^^
>x : E
> : ^

This file was deleted.

Loading