diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go index d25c14a5fff44..5d5cd88174dbe 100644 --- a/tsc/internal/checker/nodebuilderimpl.go +++ b/tsc/internal/checker/nodebuilderimpl.go @@ -720,12 +720,24 @@ func (b *NodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFl return b.f.NewImportTypeNode(isTypeOf, lit, attributes, nonRootParts, typeParameterNodes) } - splitNode := getTopmostIndexedAccessType(nonRootParts.AsIndexedAccessTypeNode()) - qualifier := splitNode.ObjectType.AsTypeReferenceNode().TypeName - return b.f.NewIndexedAccessTypeNode( - b.f.NewImportTypeNode(isTypeOf, lit, attributes, qualifier, typeParameterNodes), - splitNode.IndexType, - ) + var rebuild func(node *ast.Node) *ast.Node + rebuild = func(node *ast.Node) *ast.Node { + indexedAccess := node.AsIndexedAccessTypeNode() + var objectType *ast.Node + switch { + case ast.IsIndexedAccessTypeNode(indexedAccess.ObjectType): + objectType = rebuild(indexedAccess.ObjectType) + case ast.IsParenthesizedTypeNode(indexedAccess.ObjectType): + // (typeof A.B)[...] becomes typeof import("...").A.B[...] + qualifier := indexedAccess.ObjectType.Type().AsTypeQueryNode().ExprName + objectType = b.f.NewImportTypeNode(true /*isTypeOf*/, lit, attributes, qualifier, typeParameterNodes) + default: + qualifier := indexedAccess.ObjectType.AsTypeReferenceNode().TypeName + objectType = b.f.NewImportTypeNode(isTypeOf, lit, attributes, qualifier, typeParameterNodes) + } + return b.f.NewIndexedAccessTypeNode(objectType, indexedAccess.IndexType) + } + return rebuild(nonRootParts) } @@ -740,13 +752,6 @@ func (b *NodeBuilderImpl) symbolToTypeNode(symbol *ast.Symbol, mask ast.SymbolFl return b.f.NewTypeReferenceNode(entityName, typeArguments) } -func getTopmostIndexedAccessType(node *ast.IndexedAccessTypeNode) *ast.IndexedAccessTypeNode { - if ast.IsIndexedAccessTypeNode(node.ObjectType) { - return getTopmostIndexedAccessType(node.ObjectType.AsIndexedAccessTypeNode()) - } - return node -} - func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index int, stopper int, overrideTypeArguments *ast.NodeList) *ast.Node { typeParameterNodes := overrideTypeArguments if index != (len(chain) - 1) { @@ -791,6 +796,7 @@ func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index } } + exportName := symbolName if len(symbolName) == 0 { var name *ast.Node for _, d := range symbol.Declarations() { @@ -810,6 +816,7 @@ func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index return lhs } symbolName = b.getNameOfSymbolAsWritten(symbol) + exportName = symbol.Name() } b.ctx.approximateLength += len(symbolName) + 1 @@ -830,11 +837,24 @@ func (b *NodeBuilderImpl) createAccessFromSymbolChain(chain []*ast.Symbol, index ) } + if index > stopper && !scanner.IsIdentifierText(exportName, core.LanguageVariantStandard) { + // Type names can't reference exports with string literal names, so these + // chains reach a value, as in (typeof ns)["a b"] + lhs := b.createAccessFromSymbolChain(chain, index-1, stopper, overrideTypeArguments) + if !ast.IsIndexedAccessTypeNode(lhs) { + lhs = b.f.NewParenthesizedTypeNode(b.f.NewTypeQueryNode(lhs, nil)) + } + return b.f.NewIndexedAccessTypeNode(lhs, b.f.NewLiteralTypeNode(b.newStringLiteral(exportName))) + } + identifier := b.newIdentifier(symbolName, symbol) b.e.AddEmitFlags(identifier, printer.EFNoAsciiEscaping) if index > stopper { lhs := b.createAccessFromSymbolChain(chain, index-1, stopper, overrideTypeArguments) + if ast.IsIndexedAccessTypeNode(lhs) { + return b.f.NewIndexedAccessTypeNode(lhs, b.f.NewLiteralTypeNode(b.newStringLiteral(exportName))) + } if b.ctx.flags&nodebuilder.FlagsUseInstantiationExpressions != 0 && index < len(chain)-1 && typeParameterNodes != nil && len(typeParameterNodes.Nodes) != 0 { b.e.SetDisplayTypeArguments(identifier, typeParameterNodes) } diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 204062db49de0..d602beb832cde 100644 --- a/tsc/internal/checker/symbolaccessibility.go +++ b/tsc/internal/checker/symbolaccessibility.go @@ -8,6 +8,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/collections" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/printer" + "github.com/microsoft/TypeScript/tsc/internal/scanner" ) func (c *Checker) IsTypeSymbolAccessible(typeSymbol *ast.Symbol, enclosingDeclaration *ast.Node) bool { @@ -262,8 +263,10 @@ func (c *Checker) buildExternalModuleContainerIndex() { } container := c.getSymbolOfDeclaration(file.AsNode()) index.moduleOrder[container] = len(index.moduleOrder) - for _, exported := range c.getExportsOfSymbol(container).All() { - index.add(c.getResolvedTarget(exported), container) + for name, exported := range c.getExportsOfSymbol(container).All() { + if isIdentifierExportName(name) { + index.add(c.getResolvedTarget(exported), container) + } } if exportEquals := container.Exports().Get(ast.InternalSymbolNameExportEquals); exportEquals != nil { index.add(c.getResolvedTarget(exportEquals), container) @@ -401,6 +404,13 @@ func (c *Checker) getContainersOfSymbol(symbol *ast.Symbol, enclosingDeclaration return append(bestContainers, alternativeContainers...) } +// isIdentifierExportName reports whether an export can be written as the +// qualifier of an import type, such as `b` in `import("a").b`. Exports with +// string literal names, such as `export { x as "a b" }`, cannot. +func isIdentifierExportName(name string) bool { + return scanner.IsIdentifierText(name, core.LanguageVariantStandard) +} + func (c *Checker) getAliasForSymbolInContainer(container *ast.Symbol, symbol *ast.Symbol) *ast.Symbol { if container == c.getParentOfSymbol(symbol) { // fast path, `symbol` is either already the alias or isn't aliased @@ -416,12 +426,12 @@ func (c *Checker) getAliasForSymbolInContainer(container *ast.Symbol, symbol *as } exports := c.getExportsOfSymbol(container) quick, ok := exports.Lookup(symbol.Name()) - if ok && quick != nil && c.getSymbolIfSameReference(quick, symbol) != nil { + if ok && quick != nil && isIdentifierExportName(quick.Name()) && c.getSymbolIfSameReference(quick, symbol) != nil { return quick } var candidates []*ast.Symbol - for _, exported := range exports.All() { - if c.getSymbolIfSameReference(exported, symbol) != nil { + for name, exported := range exports.All() { + if isIdentifierExportName(name) && c.getSymbolIfSameReference(exported, symbol) != nil { candidates = append(candidates, exported) } } @@ -632,7 +642,10 @@ func (c *Checker) trySymbolTable( (isLocalNameLookup && !core.Some(symbolFromSymbolTable.Declarations(), isNamespaceReexportDeclaration) || !isLocalNameLookup) && // While exports are generally considered to be in scope, export-specifier declared symbols are _not_ // See similar comment in `resolveName` for details - (ignoreQualification || len(getDeclarationsOfKind(symbolFromSymbolTable, ast.KindExportSpecifier)) == 0) { + (ignoreQualification || len(getDeclarationsOfKind(symbolFromSymbolTable, ast.KindExportSpecifier)) == 0) && + // A qualified type name can only reference exports with identifier names; + // values can use element access, as in `ns["a b"]` + (!ignoreQualification || ctx.meaning&ast.SymbolFlagsValue == ast.SymbolFlagsValue || isIdentifierExportName(symbolFromSymbolTable.Name())) { resolvedImportedSymbol := c.resolveAlias(symbolFromSymbolTable) candidate := c.getCandidateListForSymbol(ctx, symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) if len(candidate) > 0 { diff --git a/tsc/internal/fourslash/fourslash.go b/tsc/internal/fourslash/fourslash.go index a70264613d833..a2ab16512790d 100644 --- a/tsc/internal/fourslash/fourslash.go +++ b/tsc/internal/fourslash/fourslash.go @@ -4763,6 +4763,10 @@ func (f *FourslashTest) BaselineAutoImportsCompletions(t *testing.T, markerNames // string | *Marker | *RangeMarker type MarkerOrRangeOrName = any +// renameBaselinePlaceholder is an identifier, so rename edits take the same form +// as renames to an ordinary new name. +const renameBaselinePlaceholder = "RENAME_PLACEHOLDER" + func (f *FourslashTest) VerifyBaselineRename( t *testing.T, preferences *lsutil.UserPreferences, @@ -4806,7 +4810,7 @@ func (f *FourslashTest) verifyBaselineRename( Uri: lsconv.FileNameToDocumentURI(f.activeFilename), }, Position: f.currentCaretPosition, - NewName: "?", + NewName: renameBaselinePlaceholder, } result := f.sendRequest(t, lsproto.TextDocumentRenameInfo, params) @@ -4843,7 +4847,7 @@ func (f *FourslashTest) verifyBaselineRename( endMarker: "RENAME|]", startMarkerPrefix: func(span documentSpan) *string { text := spanToText[span] - prefixAndSuffix := strings.Split(text, "?") + prefixAndSuffix := strings.Split(text, renameBaselinePlaceholder) if prefixAndSuffix[0] != "" { return new("/*START PREFIX*/" + prefixAndSuffix[0]) } @@ -4851,7 +4855,7 @@ func (f *FourslashTest) verifyBaselineRename( }, endMarkerSuffix: func(span documentSpan) *string { text := spanToText[span] - prefixAndSuffix := strings.Split(text, "?") + prefixAndSuffix := strings.Split(text, renameBaselinePlaceholder) if prefixAndSuffix[1] != "" { return new(prefixAndSuffix[1] + "/*END SUFFIX*/") } diff --git a/tsc/internal/fourslash/tests/autoCloseTag_test.go b/tsc/internal/fourslash/tests/autoCloseTag_test.go index d40d5f5028d56..e35c6e5126a5e 100644 --- a/tsc/internal/fourslash/tests/autoCloseTag_test.go +++ b/tsc/internal/fourslash/tests/autoCloseTag_test.go @@ -71,3 +71,16 @@ const x =

"9": new(""), }) } + +func TestAutoCloseTagEscapedName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @noLib: true +// @Filename: /a.tsx +const x = /*0*/;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyJsxClosingTag(t, map[string]*string{ + "0": new(``), + }) +} diff --git a/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go b/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go index ad2b8144d44b9..21ee5c88cbfab 100644 --- a/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go +++ b/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go @@ -169,3 +169,21 @@ func TestAutoImportQuotedModuleSpecifier(t *testing.T) { } } } + +func TestAutoImportJSDocCommentTerminator(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @allowJs: true +// @checkJs: true +// @Filename: /dir*/mod.js +export {}; +/** @typedef {number} T */ +// @Filename: /b.js +/** @type {T} */ +const x = 0;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.GoToFile(t, "/b.js") + f.VerifyImportFixAtPosition(t, []string{`/** @type {import("./dir*\/mod").T} */ +const x = 0;`}, nil /*preferences*/) +} diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index 8c9a3eed4de50..4706fb6204e42 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -5,6 +5,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/fourslash" . "github.com/microsoft/TypeScript/tsc/internal/fourslash/tests/util" + "github.com/microsoft/TypeScript/tsc/internal/ls" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/testutil" ) @@ -122,3 +123,95 @@ function baz(x = 0) { }, }) } + +func TestJSDocParamCompletionsWithCommentTerminators(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @filename: file.js +// @allowJs: true +/** + * @/*1*/ + */ +function f(a = "*/", b = { "*/": 1 }) {} +/** + * @/*2*/ + */ +function g({ "*/": c }) {} +/** + * @/*3*/ + */ +function h({ "*/": { x } }) {}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "1", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + "param {string} [a] ", + "param {*} [b] ", + }, + }, + }) + f.VerifyCompletions(t, "2", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + "param {*} param0 ", + }, + }, + }) + f.VerifyCompletions(t, "3", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + "param {*} param0 ", + }, + }, + }) +} + +func TestJSDocStringCompletionWithCommentTerminator(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @allowJs: true +// @checkJs: true +// @Filename: /types.ts +export interface Obj { "a*/b": number } +// @Filename: /user.js +/** @type {import("./types").Obj["[|a/*1*/|]"]} */ +let a;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "1", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Exact: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "a*/b", + Kind: new(lsproto.CompletionItemKindField), + SortText: new(string(ls.SortTextLocationPriority)), + InsertText: new(`a*\/b`), + TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ + TextEdit: &lsproto.TextEdit{ + NewText: `a*\/b`, + Range: f.Ranges()[0].LSRange, + }, + }, + }, + }, + }, + }) +} diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index 22bed95d6eb6d..308ac0327b7ab 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -30,3 +30,59 @@ type ClickEventSupport = ListenActionable<{ Click: 'some-click-event-payload' }> Index: 0, }) } + +func TestCodeFixClassImplementInterfaceNonIdentifierNames(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /node_modules/dep/index.d.ts +export type I = { [K in "c\\u0064"]: number }; +// @Filename: /a.ts +import { I } from "dep"; +class C implements I {}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.GoToFile(t, "/a.ts") + f.VerifyCodeFix(t, fourslash.VerifyCodeFixOptions{ + Description: "Implement interface 'I'", + NewFileContent: `import { I } from "dep"; +class C implements I { + "c\\u0064": number; +}`, + Index: 0, + }) +} + +func TestCodeFixClassImplementInterfaceMappedNumericKeys(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `type I = { [K in 0 | -1]: number }; +class C implements I {}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCodeFix(t, fourslash.VerifyCodeFixOptions{ + Description: "Implement interface 'I'", + NewFileContent: `type I = { [K in 0 | -1]: number }; +class C implements I { + [-1]: number; + 0: number; +}`, + Index: 0, + }) +} + +func TestCodeFixClassImplementInterfaceIntersectedMappedNonIdentifier(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `type I = { [K in "a b"]: string | number } & { [K in "a b"]: number }; +class C implements I {}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCodeFix(t, fourslash.VerifyCodeFixOptions{ + Description: "Implement interface 'I'", + NewFileContent: `type I = { [K in "a b"]: string | number } & { [K in "a b"]: number }; +class C implements I { + "a b": number; +}`, + Index: 0, + }) +} diff --git a/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go b/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go index c4d9276e593c8..3c1e3da12d9ca 100644 --- a/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go +++ b/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go @@ -31,3 +31,26 @@ export const z = 42;`, Index: 0, }) } + +func TestCodeFixMissingTypeAnnotationOnExportsNonIdentifierProperty(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @isolatedDeclarations: true +// @declaration: true +function foo() { + return { 0: 1, "a\\u0062": 1 }; +} +export const { 0: x, "a\\u0062": y } = foo();` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCodeFix(t, fourslash.VerifyCodeFixOptions{ + Description: "Extract binding expressions to variable", + NewFileContent: `function foo() { + return { 0: 1, "a\\u0062": 1 }; +} +const dest = foo(); +export const x: number = dest[0]; +export const y: number = dest["a\\u0062"];`, + Index: 0, + }) +} diff --git a/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go b/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go index f1c128a58dd33..910876806ce98 100644 --- a/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go +++ b/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go @@ -38,3 +38,23 @@ let x: AAA = new BBB()` let x: AAA = new BBB()`, }, nil /*preferences*/) } + +func TestCodeFixPromoteTypeOnlyStringName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @module: esnext +// @Filename: /m.ts +class K {} +export { K as "a\\u0062" }; +export const b = 1; +// @Filename: /a.ts +import { b, type "a\\u0062" as A } from "./m"; +b; +new A();` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.GoToFile(t, "/a.ts") + f.VerifyImportFixAtPosition(t, []string{`import { "a\\u0062" as A, b } from "./m"; +b; +new A();`}, nil /*preferences*/) +} diff --git a/tsc/internal/fourslash/tests/completionFilterText3_test.go b/tsc/internal/fourslash/tests/completionFilterText3_test.go index 38f5d894e718d..b1e4a15e52f16 100644 --- a/tsc/internal/fourslash/tests/completionFilterText3_test.go +++ b/tsc/internal/fourslash/tests/completionFilterText3_test.go @@ -151,3 +151,31 @@ if (true) { }, }) } + +func TestCompletionPropertyAccessLineSeparator(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = "declare const o: { \"a\\u2028b\": number };\no[|.|]/*1*/" + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "1", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "a\u2028b", + InsertText: new(`["a\u2028b"]`), + TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ + TextEdit: &lsproto.TextEdit{ + NewText: `["a\u2028b"]`, + Range: f.Ranges()[0].LSRange, + }, + }, + }, + }, + }, + }) +} diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go index db38662ac299d..130cfda520549 100644 --- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go +++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go @@ -232,7 +232,7 @@ f(/*argument*/);` }, Items: &fourslash.CompletionsExpectedItems{ Includes: []fourslash.CompletionsExpectedItem{ - &lsproto.CompletionItem{Label: `"\ud800"`, CommitCharacters: &[]string{}}, + &lsproto.CompletionItem{Label: `"\uD800"`, CommitCharacters: &[]string{}}, }, }, }) diff --git a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index 3b95ff4724941..e899d5368ed6b 100644 --- a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go +++ b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go @@ -59,3 +59,95 @@ export function Index() { }`), }) } + +func TestCompletionsImport_jsxOpeningTagImportDefaultNonASCII(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @module: commonjs +// @jsx: react +// @Filename: /中文.tsx +export default function (props: any) {} +// @Filename: /index.tsx +export function Index() { + return <中/**/ +}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "中文", + Data: &lsproto.CompletionItemData{ + AutoImport: &lsproto.AutoImportFix{ + ModuleSpecifier: "./中文", + }, + }, + AdditionalTextEdits: fourslash.AnyTextEdits, + SortText: new(string(ls.SortTextAutoImportSuggestions)), + }, + }, + }, + }) + f.VerifyApplyCodeActionFromCompletion(t, new(""), &fourslash.ApplyCodeActionFromCompletionOptions{ + Name: "中文", + Source: "./中文", + Description: "Add import from \"./中文\"", + NewFileContent: new(`import 中文 from "./中文"; + +export function Index() { + return <中 +}`), + }) +} + +func TestCompletionsImport_jsxOpeningTagNamedNonASCII(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @module: commonjs +// @jsx: react +// @Filename: /cake.tsx +export function 蛋糕(props: any) {} +// @Filename: /index.tsx +export function Index() { + return <蛋/**/ +}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "蛋糕", + Data: &lsproto.CompletionItemData{ + AutoImport: &lsproto.AutoImportFix{ + ModuleSpecifier: "./cake", + }, + }, + AdditionalTextEdits: fourslash.AnyTextEdits, + SortText: new(string(ls.SortTextAutoImportSuggestions)), + }, + }, + }, + }) + f.VerifyApplyCodeActionFromCompletion(t, new(""), &fourslash.ApplyCodeActionFromCompletionOptions{ + Name: "蛋糕", + Source: "./cake", + Description: "Add import from \"./cake\"", + NewFileContent: new(`import { 蛋糕 } from "./cake"; + +export function Index() { + return <蛋 +}`), + }) +} diff --git a/tsc/internal/fourslash/tests/completionsOverridingMethod22_test.go b/tsc/internal/fourslash/tests/completionsOverridingMethod22_test.go index e69a69fef7137..fed35c4c22e4d 100644 --- a/tsc/internal/fourslash/tests/completionsOverridingMethod22_test.go +++ b/tsc/internal/fourslash/tests/completionsOverridingMethod22_test.go @@ -39,7 +39,7 @@ abstract class ExtBase implements ExtShape { Includes: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ Label: "$returnPromise", - TextEdit: InsertReplaceTextEdit("public \\$returnPromise(id: number): Promise {\n}", f.Ranges()[0].LSRange), + TextEdit: InsertReplaceTextEdit("public $returnPromise(id: number): Promise {\n}", f.Ranges()[0].LSRange), FilterText: new("$returnPromise"), SortText: new(string(ls.SortTextLocationPriority)), AdditionalTextEdits: fourslash.AnyTextEdits, diff --git a/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go new file mode 100644 index 0000000000000..e94450748fa3d --- /dev/null +++ b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go @@ -0,0 +1,126 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + . "github.com/microsoft/TypeScript/tsc/internal/fourslash/tests/util" + "github.com/microsoft/TypeScript/tsc/internal/ls" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" + "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" + "github.com/microsoft/TypeScript/tsc/internal/testutil" +) + +func TestCompletionsSnippetEscaping(t *testing.T) { + t.Parallel() + const content = `// @strict: true +interface I { + "a\\b"(): void; + "c$d"(): void; + m(x: "a\\b"): void; +} +class C implements I { + /*c*/ +} +const o: I = { + /*o*/ +}; +declare const s: "a\\b" | "x"; +switch (s) { + case/*s*/ +}` + preferences := &lsutil.UserPreferences{ + IncludeCompletionsWithClassMemberSnippets: core.TSTrue, + IncludeCompletionsWithObjectLiteralMethodSnippets: core.TSTrue, + } + for _, snippet := range []bool{true, false} { + name := "plain" + var insertTextFormat *lsproto.InsertTextFormat + classMemberM := `m(x: "a\\b"): void {` + "\n}" + classMember := `"c$d"(): void {` + "\n}" + objectMethodA := `"a\\b"() {` + "\n}," + objectMethodC := `"c$d"() {` + "\n}," + if snippet { + name = "snippet" + insertTextFormat = new(lsproto.InsertTextFormatSnippet) + classMemberM = `m(x: "a\\\\b"): void {` + "\n $0\n}" + classMember = `"c\$d"(): void {` + "\n $0\n}" + objectMethodA = `"a\\\\b"() {` + "\n $0\n}," + objectMethodC = `"c\$d"() {` + "\n $0\n}," + } + t.Run(name, func(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + f, done := fourslash.NewFourslash(t, fourslash.GetDefaultCapabilitiesWithOptions(&fourslash.ClientCapabilitiesOptions{ + CompletionItem: &lsproto.ClientCompletionItemOptions{SnippetSupport: new(snippet)}, + }), content) + defer done() + f.VerifyCompletions(t, "c", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &[]string{}, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "m", + InsertText: new(classMemberM), + InsertTextFormat: insertTextFormat, + }, + &lsproto.CompletionItem{ + Label: "c$d", + InsertText: new(classMember), + InsertTextFormat: insertTextFormat, + }, + }, + }, + UserPreferences: preferences, + }) + f.VerifyCompletions(t, "o", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: `"a\\b"()`, + SortText: new("11\x00\"a\\\\b\"\x001"), + InsertText: new(objectMethodA), + InsertTextFormat: insertTextFormat, + }, + &lsproto.CompletionItem{ + Label: "c$d()", + SortText: new("11\x00c$d\x001"), + InsertText: new(objectMethodC), + InsertTextFormat: insertTextFormat, + }, + }, + }, + UserPreferences: preferences, + }) + if snippet { + f.VerifyCompletions(t, "s", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: `case "a\\b": ...`, + InsertText: new(`case "a\\\\b":$1` + "\n" + `case "x":$2`), + SortText: new(string(ls.SortTextGlobalsOrKeywords)), + InsertTextFormat: new(lsproto.InsertTextFormatSnippet), + }, + }, + }, + }) + } + }) + } +} diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go new file mode 100644 index 0000000000000..6098bf47a6f59 --- /dev/null +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -0,0 +1,122 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + "github.com/microsoft/TypeScript/tsc/internal/testutil" +) + +func TestGetEditsForFileRename_escapedSpecifier(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = "// @Filename: /tsconfig.json\n" + + "{ \"files\": [\"application/app.ts\", \"libraries/old/a';process.exit(7);'\\\"`${b}.d.ts\"] }\n" + + "// @Filename: /libraries/old/a';process.exit(7);'\"`${b}.d.ts\n" + + "export declare const X: number;\n" + + "// @Filename: /application/app.ts\n" + + "import { X } from '../libraries/old/a\\';process.exit(7);\\'\"`${b}';\n" + + "import { X as Y } from \"../libraries/old/a';process.exit(7);'\\\"`${b}\";\n" + + "const Z = import(`../libraries/old/a';process.exit(7);'\"\\`\\${b}`);\n" + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/libraries/old", "/libraries/new", map[string]string{ + "/application/app.ts": "import { X } from '../libraries/new/a\\';process.exit(7);\\'\"`${b}';\n" + + "import { X as Y } from \"../libraries/new/a';process.exit(7);'\\\"`${b}\";\n" + + "const Z = import(`../libraries/new/a';process.exit(7);'\"\\`\\${b}`);\n", + "/tsconfig.json": "{ \"files\": [\"application/app.ts\", \"libraries/new/a';process.exit(7);'\\\"`${b}.d.ts\"] }", + }, nil /*preferences*/) +} + +func TestGetEditsForFileRename_escapedNewDirectoryName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /tsconfig.json +{ "files": ["a.ts", "old/b.ts"] } +// @Filename: /a.ts +/// +/// +import b1 from "./old/b"; +import b2 from './old/b'; +export default 0; +// @Filename: /old/b.ts +export default 0;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/old", "/n'e\"w", map[string]string{ + "/a.ts": `/// +/// +import b1 from "./n'e\"w/b"; +import b2 from './n\'e"w/b'; +export default 0;`, + "/tsconfig.json": `{ "files": ["a.ts", "n'e\"w/b.ts"] }`, + }, nil /*preferences*/) +} + +func TestGetEditsForFileRename_configStringJSONEscapes(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /tsconfig.json +{ "files": ["a.ts", "old/b.ts"] } +// @Filename: /a.ts +/// +/// +import b1 from "./old/b"; +import b2 from './old/b'; +export default 0; +// @Filename: /old/b.ts +export default 0;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/old", "/v\vt", map[string]string{ + "/a.ts": "/// \n" + + "/// \n" + + "import b1 from \"./v\\vt/b\";\n" + + "import b2 from './v\\vt/b';\n" + + "export default 0;", + "/tsconfig.json": `{ "files": ["a.ts", "v\u000bt/b.ts"] }`, + }, nil /*preferences*/) +} + +func TestGetEditsForFileRename_jsDocCommentTerminator(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /tsconfig.json +{ "compilerOptions": { "allowJs": true, "checkJs": true } } +// @Filename: /pkg*/a.js +export class Foo {} +// @Filename: /src/index.js +/** @type {import("../pkg*\/a.js").Foo} */ +const x = null;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/src/index.js", "/src/sub/index.js", map[string]string{ + "/src/sub/index.js": `/** @type {import("../../pkg*\/a.js").Foo} */ +const x = null;`, + }, nil /*preferences*/) +} + +func TestGetEditsForFileRename_referenceDirectiveOtherQuote(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /tsconfig.json +{ "files": ["a.ts", "old/b.ts"] } +// @Filename: /a.ts +/// +/// +import b1 from "./old/b"; +import b2 from './old/b'; +export default 0; +// @Filename: /old/b.ts +export default 0;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyWillRenameFilesEdits(t, "/old", "/n\"ew", map[string]string{ + "/a.ts": `/// +/// +import b1 from "./n\"ew/b"; +import b2 from './n"ew/b'; +export default 0;`, + "/tsconfig.json": `{ "files": ["a.ts", "n\"ew/b.ts"] }`, + }, nil /*preferences*/) +} diff --git a/tsc/internal/fourslash/tests/importStatementCompletions_braces_test.go b/tsc/internal/fourslash/tests/importStatementCompletions_braces_test.go index 239d7c6eb8239..f551ba243b7f5 100644 --- a/tsc/internal/fourslash/tests/importStatementCompletions_braces_test.go +++ b/tsc/internal/fourslash/tests/importStatementCompletions_braces_test.go @@ -34,7 +34,7 @@ func verifyImportStatementFilterText(t *testing.T, typed string) { &lsproto.CompletionItem{ Label: "foo", InsertText: new(text), - FilterText: new(text), + FilterText: new(`import { foo } from "./mod";`), Data: &lsproto.CompletionItemData{ AutoImport: &lsproto.AutoImportFix{ModuleSpecifier: "./mod"}, }, @@ -59,3 +59,40 @@ func TestImportStatementCompletions_bracePrefix(t *testing.T) { defer testutil.RecoverAndFail(t, "Panic on fourslash test") verifyImportStatementFilterText(t, "import { fo/**/") } + +func TestImportStatementCompletions_dollarName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = "// @Filename: /mod.ts\nexport const $foo = 0;\n// @Filename: /index.ts\n[|import $f/**/|]" + f, done := fourslash.NewFourslash(t, fourslash.GetDefaultCapabilitiesWithOptions(&fourslash.ClientCapabilitiesOptions{ + CompletionItem: &lsproto.ClientCompletionItemOptions{ + SnippetSupport: new(true), + }, + }), content) + defer done() + + const text = `import { \$foo$1 } from "./mod";` + f.VerifyCompletions(t, "", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &[]string{}, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "$foo", + InsertText: new(text), + FilterText: new(`import { $foo } from "./mod";`), + Data: &lsproto.CompletionItemData{ + AutoImport: &lsproto.AutoImportFix{ModuleSpecifier: "./mod"}, + }, + InsertTextFormat: new(lsproto.InsertTextFormatSnippet), + TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ + TextEdit: &lsproto.TextEdit{NewText: text, Range: f.Ranges()[0].LSRange}, + }, + }, + }, + }, + }) +} diff --git a/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go b/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go index c2b173dae770d..cbb48e6db009d 100644 --- a/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go +++ b/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go @@ -50,3 +50,40 @@ export const foo = 0; }, }) } + +func TestImportStatementCompletions_noSnippetDollarName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /mod.ts +export const f$oo = 0; +// @Filename: /index0.ts +[|import f/**/|]` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyCompletions(t, "", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &[]string{}, + EditRange: Ignored, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + &lsproto.CompletionItem{ + Label: "f$oo", + InsertText: new("import { f$oo } from \"./mod\";"), + Data: &lsproto.CompletionItemData{ + AutoImport: &lsproto.AutoImportFix{ + ModuleSpecifier: "./mod", + }, + }, + TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ + TextEdit: &lsproto.TextEdit{ + NewText: "import { f$oo } from \"./mod\";", + Range: f.Ranges()[0].LSRange, + }, + }, + }, + }, + }, + }) +} diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go new file mode 100644 index 0000000000000..148838f2589d6 --- /dev/null +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -0,0 +1,189 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" + "github.com/microsoft/TypeScript/tsc/internal/testutil" +) + +func TestRenameEscapesStringLiterals(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = "// @Filename: /a.ts\n" + + "const obj = { \"foo\": 1 };\n" + + "obj[\"/*1*/foo\"];\n" + + "obj['foo'];\n" + + "obj[`foo`];\n" + + "// @Filename: /b.ts\n" + + "const foo = { 0: true };\n" + + "foo[/*2*/0];\n" + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyRename(t, "1", "it's \"${x}\"\\", map[string]string{ + "/a.ts": `const obj = { "it's \"${x}\"\\": 1 }; +obj["it's \"${x}\"\\"]; +obj['it\'s "${x}"\\']; +obj[` + "`it's \"\\${x}\"\\\\`];", + }) + f.VerifyRename(t, "2", `a"b`, map[string]string{ + "/b.ts": "const foo = { \"a\\\"b\": true };\n" + + "foo[\"a\\\"b\"];\n", + }) +} + +func TestRenameNumericPropertyNameToNumber(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = "// @Filename: /a.ts\n" + + "const foo = { 0: true };\n" + + "foo[/*1*/0];\n" + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyRename(t, "1", "1", map[string]string{ + "/a.ts": "const foo = { 1: true };\n" + + "foo[\"1\"];\n", + }) +} + +func TestRenameEmptyStringExportName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /a.ts +const foo = 1; +export { foo as "/*1*/" };` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyRename(t, "1", `a"b`, map[string]string{ + "/a.ts": `const foo = 1; +export { foo as "a\"b" };`, + }) +} + +func TestRenameToNonIdentifierWithAliases(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /a.ts +const foo = 1; +export { /*1*/foo }; +const o = { "/*2*/x": 1 }; +const { x } = o; +// @Filename: /b.ts +import { foo } from "./a"; +foo; +const o2 = { foo }; +export { foo }; +// @Filename: /c.ts +export { foo } from "./a"; +// @Filename: /d.ts +import { foo as bar } from "./a"; +bar;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + defer f.ConfigureWithReset(t, lsutil.UserPreferences{ProvidePrefixAndSuffixTextForRename: core.TSTrue})() + f.VerifyRename(t, "1", "a-b", map[string]string{ + "/a.ts": `const foo = 1; +export { foo as "a-b" }; +const o = { "x": 1 }; +const { x } = o;`, + "/b.ts": `import { "a-b" as foo } from "./a"; +foo; +const o2 = { foo }; +export { foo };`, + "/c.ts": `export { "a-b" as foo } from "./a";`, + "/d.ts": `import { "a-b" as bar } from "./a"; +bar;`, + }) + f.VerifyRename(t, "2", "c-d", map[string]string{ + "/a.ts": `const foo = 1; +export { foo as "a-b" }; +const o = { "c-d": 1 }; +const { "c-d": x } = o;`, + }) +} + +func TestRenameToNonIdentifierInJSDocImport(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @allowJs: true +// @checkJs: true +// @Filename: /a.ts +export interface /*1*/Foo {} +// @Filename: /b.js +/** @import { Foo } from "./a" */ +/** @type {Foo} */ +let x;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + defer f.ConfigureWithReset(t, lsutil.UserPreferences{ProvidePrefixAndSuffixTextForRename: core.TSTrue})() + f.VerifyRename(t, "1", "a*/b", map[string]string{ + "/a.ts": `export interface a*/b {}`, + "/b.js": `/** @import { "a*\/b" as Foo } from "./a" */ +/** @type {Foo} */ +let x;`, + }) +} + +func TestRenameStringNamedReExportWithAliases(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /a.ts +const x = 1; +export { x as "/*1*/a b" }; +// @Filename: /b.ts +export { "a b" } from "./a"; +// @Filename: /c.ts +const y = 1; +export { y as "d e" }; +// @Filename: /d.ts +export { "/*2*/d e" } from "./c";` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + defer f.ConfigureWithReset(t, lsutil.UserPreferences{ProvidePrefixAndSuffixTextForRename: core.TSTrue})() + f.VerifyRename(t, "1", "c", map[string]string{ + "/a.ts": `const x = 1; +export { x as "c" };`, + "/b.ts": `export { "c" as "a b" } from "./a";`, + }) + f.VerifyRename(t, "2", "f", map[string]string{ + "/d.ts": `export { "d e" as "f" } from "./c";`, + }) +} + +func TestRenameStringLiteralInJsxAttribute(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /a.tsx +// @jsx: preserve +declare function C(props: { kind: "foo" | "bar" }): any; +const k: "foo" | "bar" = "/*1*/foo"; +; +;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyRename(t, "1", `a\"b`, map[string]string{ + "/a.tsx": `declare function C(props: { kind: "foo" | "bar" }): any; +const k: "a\\\"b" | "bar" = "a\\\"b"; +; +;`, + }) +} + +func TestRenameNamespaceExportToNonIdentifier(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /dep.ts +export const x = 1; +// @Filename: /a.ts +export * as /*1*/ns from "./dep"; +// @Filename: /b.ts +import { ns as bar } from "./a";` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyRename(t, "1", "a-b", map[string]string{ + "/a.ts": `export * as "a-b" from "./dep";`, + "/b.ts": `import { "a-b" as bar } from "./a";`, + }) +} diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go index 60121e38d1f0e..87aaf7c94638f 100644 --- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go +++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go @@ -184,7 +184,7 @@ const b = ; Items: &fourslash.CompletionsExpectedItems{ Includes: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ - Label: `"\ud800"`, + Label: `"\uD800"`, InsertText: new(`{"\uD800"}`), CommitCharacters: &[]string{}, }, diff --git a/tsc/internal/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 59271fd360b3a..d54e95b4afc97 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "unicode" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -22,7 +23,6 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/modulespecifiers" - "github.com/microsoft/TypeScript/tsc/internal/printer" "github.com/microsoft/TypeScript/tsc/internal/scanner" "github.com/microsoft/TypeScript/tsc/internal/stringutil" "github.com/microsoft/TypeScript/tsc/internal/tspath" @@ -147,12 +147,8 @@ func addImportType(f *Fix, file *ast.SourceFile, preferences lsutil.UserPreferen if f.UsagePosition == nil { panic("UsagePosition must be set for JSDoc type import fix") } - quotePreference := lsutil.GetQuotePreference(file, preferences) - quoteChar := printer.QuoteCharDoubleQuote - if quotePreference == lsutil.QuotePreferenceSingle { - quoteChar = printer.QuoteCharSingleQuote - } - importTypePrefix := fmt.Sprintf("import(%c%s%c).", quoteChar, printer.EscapeString(f.ModuleSpecifier, quoteChar), quoteChar) + quoteChar := lsutil.GetQuotePreference(file, preferences).QuoteChar() + importTypePrefix := "import(" + lsutil.QuoteString(f.ModuleSpecifier, quoteChar) + ")." tracker.InsertText(file, *f.UsagePosition, importTypePrefix) return diagnostics.Change_0_to_1.Localize(locale, f.Name, importTypePrefix+f.Name) } @@ -603,10 +599,10 @@ func (v *View) GetFixes(export *Export, forJSX bool, isValidTypeOnlyUseSite bool addAsTypeOnly := getAddAsTypeOnly(isValidTypeOnlyUseSite, export, v.program.Options()) name := export.Name() - startsWithUpper := unicode.IsUpper(rune(name[0])) - if forJSX && !startsWithUpper { + if forJSX && scanner.IsIntrinsicJsxName(name) { if export.IsRenameable() { - name = fmt.Sprintf("%c%s", unicode.ToUpper(rune(name[0])), name[1:]) + first, size := utf8.DecodeRuneInString(name) + name = string(unicode.ToUpper(first)) + name[size:] } else { return nil } @@ -1134,7 +1130,7 @@ func promoteFromTypeOnly( // Create a synthetic specifier with isTypeOnly=false to compute sorted position var propertyName *ast.Node if spec.PropertyName != nil { - propertyName = changes.NodeFactory.NewIdentifier(spec.PropertyName.Text()).AsIdentifier().AsNode() + propertyName = changes.NodeFactory.DeepCloneNode(spec.PropertyName) } newSpecifier := changes.NodeFactory.NewImportSpecifier( false, // isTypeOnly = false diff --git a/tsc/internal/ls/autoimport/view.go b/tsc/internal/ls/autoimport/view.go index 9a6046c746d53..fc7cd71962449 100644 --- a/tsc/internal/ls/autoimport/view.go +++ b/tsc/internal/ls/autoimport/view.go @@ -2,7 +2,6 @@ package autoimport import ( "slices" - "unicode" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/checker" @@ -191,7 +190,7 @@ outer: if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { continue } - if forJSX && !(unicode.IsUpper(rune(name[0])) || e.IsRenameable()) { + if forJSX && scanner.IsIntrinsicJsxName(name) && !e.IsRenameable() { continue } target := e.ExportID diff --git a/tsc/internal/ls/codeactions_fixmissingtypeannotation.go b/tsc/internal/ls/codeactions_fixmissingtypeannotation.go index 7318ce1830bf9..6e64bf7141f43 100644 --- a/tsc/internal/ls/codeactions_fixmissingtypeannotation.go +++ b/tsc/internal/ls/codeactions_fixmissingtypeannotation.go @@ -759,9 +759,13 @@ func (f *isolatedDeclarationsFixer) extractBindingElements( *newNodes = append(*newNodes, compVarStmt) accessExpr = factory.NewElementAccessExpression(baseExpr, nil, identifierForComputedProperty.AsNode(), ast.NodeFlagsNone) } else if be.PropertyName != nil { - // Use property name text (handles identifiers, string literals, numeric literals) propText := be.PropertyName.Text() - accessExpr = factory.NewPropertyAccessExpression(baseExpr, nil, factory.NewIdentifier(propText), ast.NodeFlagsNone) + if ast.IsIdentifier(be.PropertyName) || scanner.IsIdentifierText(propText, core.LanguageVariantStandard) { + accessExpr = factory.NewPropertyAccessExpression(baseExpr, nil, factory.NewIdentifier(propText), ast.NodeFlagsNone) + } else { + // String and numeric literal names that aren't identifiers need an element access. + accessExpr = factory.NewElementAccessExpression(baseExpr, nil, factory.DeepCloneNode(be.PropertyName), ast.NodeFlagsNone) + } } else if ast.IsIdentifier(name) { accessExpr = factory.NewPropertyAccessExpression(baseExpr, nil, factory.NewIdentifier(name.Text()), ast.NodeFlagsNone) } else { diff --git a/tsc/internal/ls/codeactions_missingmemberfixer.go b/tsc/internal/ls/codeactions_missingmemberfixer.go index 4f1cf6caf0a36..a50f2ee9d2033 100644 --- a/tsc/internal/ls/codeactions_missingmemberfixer.go +++ b/tsc/internal/ls/codeactions_missingmemberfixer.go @@ -2,6 +2,7 @@ package ls import ( "strconv" + "strings" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/checker" @@ -13,6 +14,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ls/change" "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/nodebuilder" + "github.com/microsoft/TypeScript/tsc/internal/scanner" ) type preserveOptionalFlags int @@ -61,7 +63,7 @@ func (f *missingMemberFixer) createMemberFromSymbol(symbol *ast.Symbol, enclosin if declaration != nil { kind = declaration.Kind } - declarationName := createDeclarationName(f.changeTracker.NodeFactory, f.typeChecker, symbol, declaration) + declarationName := createDeclarationName(f.changeTracker.NodeFactory, f.typeChecker, symbol, declaration, quotePreference) modifiers := f.createModifiers(symbol, declaration) flags := nodebuilder.FlagsNoTruncation @@ -486,22 +488,37 @@ func createDummyParameters(factory *ast.NodeFactory, argCount int, names []strin return factory.NewNodeList(parameters) } -func createDeclarationName(factory *ast.NodeFactory, typeChecker *checker.Checker, symbol *ast.Symbol, declaration *ast.Node) *ast.PropertyName { +func createDeclarationName(factory *ast.NodeFactory, typeChecker *checker.Checker, symbol *ast.Symbol, declaration *ast.Node, quotePreference lsutil.QuotePreference) *ast.PropertyName { if symbol != nil && symbol.CheckFlags()&ast.CheckFlagsMapped != 0 { nameType := typeChecker.GetNameTypeOfSymbol(symbol) + if nameType != nil && nameType.Flags()&checker.TypeFlagsNumberLiteral != 0 { + // Numeric keys keep numeric syntax; a negative key needs a computed name, as in [-1]. + name := checker.GetPropertyNameFromType(nameType) + if digits, ok := strings.CutPrefix(name, "-"); ok { + return factory.NewComputedPropertyName(factory.NewPrefixUnaryExpression(ast.KindMinusToken, factory.NewNumericLiteral(digits, ast.TokenFlagsNone))) + } + return factory.NewNumericLiteral(name, ast.TokenFlagsNone) + } if nameType != nil && checker.IsTypeUsableAsPropertyName(nameType) { - return factory.NewIdentifier(checker.GetPropertyNameFromType(nameType)) + return createPropertyNameFromText(factory, checker.GetPropertyNameFromType(nameType), quotePreference) } } if declaration != nil && declaration.Name() != nil { return declaration.Name().Clone(factory) } if symbol != nil { - return factory.NewIdentifier(symbol.Name()) + return createPropertyNameFromText(factory, symbol.Name(), quotePreference) } return nil } +func createPropertyNameFromText(factory *ast.NodeFactory, name string, quotePreference lsutil.QuotePreference) *ast.PropertyName { + if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { + return factory.NewStringLiteral(name, core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone)) + } + return factory.NewIdentifier(name) +} + func createPropertyName(factory *ast.NodeFactory, node *ast.Node, quotePreference lsutil.QuotePreference) *ast.PropertyName { if ast.IsIdentifier(node) && node.Text() == "constructor" { tokenFlags := ast.TokenFlagsNone diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index 9affd8602168a..e00294b3439e7 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -2062,8 +2062,19 @@ func (l *LanguageService) getCompletionEntriesFromSymbols( isSnippet, ) // The edit range covers the whole import statement typed so far, and clients match that text against the - // filter text, so it has to be the statement being inserted (as in Strada), not just the bare name. + // filter text, so it has to be the statement being inserted (as in Strada) without any snippet syntax. filterText = insertText + if isSnippet { + filterText, _ = getInsertTextAndReplacementSpanForImportCompletion( + autoImport.Fix, + autoimport.GetImportKindForImportStatement(file, autoImport.Export, l.GetProgram()), + data.importStatementCompletion, + useSemicolons, + file, + preferences, + false, /*isSnippet*/ + ) + } sortText = SortTextLocationPriority } @@ -2142,13 +2153,14 @@ func completionNameForLiteral( func getInsertTextAndReplacementSpanForImportCompletion(fix *autoimport.Fix, importKind lsproto.ImportKind, importStatementCompletion *importStatementCompletionInfo, useSemicolons bool, file *ast.SourceFile, preferences lsutil.UserPreferences, isSnippet bool) (insertText string, replacementSpan *lsproto.Range) { quotedModuleSpecifier := quote(file, preferences, fix.ModuleSpecifier) + name := fix.Name if isSnippet { - quotedModuleSpecifier = escapeSnippetText(strings.ReplaceAll(quotedModuleSpecifier, `\`, `\\`)) + quotedModuleSpecifier = escapeSnippetText(quotedModuleSpecifier) + name = escapeSnippetText(name) } tabStop := core.IfElse(isSnippet, "$1", "") suffix := core.IfElse(useSemicolons, ";", "") topLevelTypeOnlyText := core.IfElse(importStatementCompletion.isTopLevelTypeOnly, " "+scanner.TokenToString(ast.KindTypeKeyword)+" ", " ") - name := escapeSnippetText(fix.Name) replacementSpan = importStatementCompletion.replacementSpan switch importKind { @@ -2214,7 +2226,7 @@ func (l *LanguageService) createCompletionItem( var labelDetails *lsproto.CompletionItemLabelDetails preferences := l.UserPreferences() if data.completionKind == CompletionKindString { - escaped := printer.EscapeString(name, stringCompletionQuoteChar(contextToken)) + escaped := lsutil.EscapeString(name, lsutil.QuoteCharOfLiteral(contextToken)) if escaped != name { insertText = escaped } @@ -2492,13 +2504,12 @@ type memberCompletionEntry struct { } func (l *LanguageService) getEntryForObjectLiteralMethodCompletion(ctx context.Context, typeChecker *checker.Checker, symbol *ast.Symbol, enclosingDeclaration *ast.Node, file *ast.SourceFile) *symbolOriginInfoObjectLiteralMethod { + isSnippet := clientSupportsItemSnippet(ctx) snippetPrinter := createSnippetPrinter(printer.PrinterOptions{ RemoveComments: true, NewLine: core.GetNewLineKind(l.FormatOptions().NewLineCharacter), Target: l.GetProgram().Options().GetEmitScriptTarget(), - }, nil /*emitContext*/) - - isSnippet := clientSupportsItemSnippet(ctx) + }, nil /*emitContext*/, isSnippet) method := l.createObjectLiteralMethod(snippetPrinter, typeChecker, symbol, enclosingDeclaration, file, isSnippet) if method == nil { return nil @@ -2747,7 +2758,7 @@ func (l *LanguageService) getEntryForMemberCompletion(ctx context.Context, typeC RemoveComments: true, NewLine: core.GetNewLineKind(newLine), Target: l.GetProgram().Options().GetEmitScriptTarget(), - }, changeTracker.EmitContext) + }, changeTracker.EmitContext, isSnippet) var decoratedNode *ast.Node if len(presentModifiers.decorators) > 0 { @@ -3750,8 +3761,10 @@ func areIntersectedTypesAvoidingStringReduction(typeChecker *checker.Checker, t1 return t1.IsString() && typeChecker.IsEmptyAnonymousObjectType(t2) } +var snippetTextEscaper = strings.NewReplacer(`\`, `\\`, `$`, `\$`) + func escapeSnippetText(text string) string { - return strings.ReplaceAll(text, `$`, `\$`) + return snippetTextEscaper.Replace(text) } func isNamedImportsOrExports(node *ast.Node) bool { @@ -6348,7 +6361,9 @@ func getJSDocParamAnnotation( // Target: options.Target, }, printer.PrintHandlers{}, *emitContext) (*emitContext).SetEmitFlags(typeNode, printer.EFSingleLine) - t = p.Emit(typeNode, file) + if typeText := p.Emit(typeNode, file); isSafeInJSDocTag(typeText) { + t = typeText + } } } } @@ -6377,9 +6392,15 @@ func getJSDocParamAnnotation( } } +// isSafeInJSDocTag reports whether text can be written into a single-line +// JSDoc tag without ending the comment or breaking the line. +func isSafeInJSDocTag(text string) bool { + return !strings.Contains(text, "*/") && !stringutil.ContainsLineBreak(text) +} + func getJSDocParamNameWithInitializer(paramName string, initializer *ast.Expression) string { initializerText := strings.TrimSpace(scanner.GetTextOfNode(initializer)) - if strings.Contains(initializerText, "\n") || len(initializerText) > 80 { + if !isSafeInJSDocTag(initializerText) || len(initializerText) > 80 { return fmt.Sprintf("[%s]", paramName) } return fmt.Sprintf("[%s=%s]", paramName, initializerText) @@ -6521,7 +6542,7 @@ func jsDocParamElementWorker( } else { propertyName = element.Name().Text() } - if propertyName == "" { + if propertyName == "" || !isSafeInJSDocTag(propertyName) { return nil } paramName := fmt.Sprintf("%s.%s", path, propertyName) @@ -6542,7 +6563,7 @@ func jsDocParamElementWorker( } } else if element.PropertyName() != nil { // `{ b: {...} }` or `{ b: [...] }` propertyName, _ := ast.TryGetTextOfPropertyName(element.PropertyName()) - if propertyName == "" { + if propertyName == "" || !isSafeInJSDocTag(propertyName) { return nil } return jsDocParamPatternWorker( @@ -6701,7 +6722,7 @@ func (l *LanguageService) getExhaustiveCaseSnippets( printer := createSnippetPrinter(printer.PrinterOptions{ RemoveComments: true, NewLine: core.GetNewLineKind(newLineChar), - }, nil /*emitContext*/) + }, nil /*emitContext*/, true /*escapeText*/) printNode := func(node *ast.Node) string { return printer.printAndFormatNode(ctx, node, file) } insertText := strings.Join(core.MapIndex(newClauses, func(clause *ast.Node, i int) string { if clientSupportsItemSnippet(ctx) { @@ -6863,7 +6884,9 @@ func (p *snippetPrinter) printAndFormatNodeWithSettings(ctx context.Context, nod return core.ApplyBulkEdits(syntheticFile.Text(), allChanges) } -func createSnippetPrinter(options printer.PrinterOptions, emitContext *printer.EmitContext) *snippetPrinter { +// createSnippetPrinter creates a printer whose output is snippet-escaped when +// escapeText is set. Tab stops from snippet elements are written either way. +func createSnippetPrinter(options printer.PrinterOptions, emitContext *printer.EmitContext, escapeText bool) *snippetPrinter { if emitContext == nil { emitContext = printer.NewEmitContext() } @@ -6871,6 +6894,7 @@ func createSnippetPrinter(options printer.PrinterOptions, emitContext *printer.E printer := printer.NewPrinter(options, baseWriter.GetPrintHandlers(), emitContext) writer := &snippetEmitTextWriter{ ChangeTrackerWriter: baseWriter, + escapeText: escapeText, } return &snippetPrinter{ baseWriter: baseWriter, @@ -6884,7 +6908,8 @@ func createSnippetPrinter(options printer.PrinterOptions, emitContext *printer.E // Override base writer methods to perform snippet escaping. type snippetEmitTextWriter struct { *printer.ChangeTrackerWriter - escapes []core.TextChange + escapeText bool + escapes []core.TextChange } func (w *snippetEmitTextWriter) Write(s string) { @@ -6916,6 +6941,10 @@ func (w *snippetEmitTextWriter) WriteSymbol(text string, symbol *ast.Symbol) { // generate a set of changes that can be applied to the unescaped text // to escape it post-formatting. func (w *snippetEmitTextWriter) escapingWrite(s string, write func()) { + if !w.escapeText { + write() + return + } escaped := escapeSnippetText(s) if escaped != s { start := w.GetTextPos() diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index b3c1ca5e6eeb4..2180e94673fd0 100644 --- a/tsc/internal/ls/file_rename.go +++ b/tsc/internal/ls/file_rename.go @@ -3,6 +3,7 @@ package ls import ( "context" "slices" + "strings" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/checker" @@ -11,9 +12,11 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/debug" "github.com/microsoft/TypeScript/tsc/internal/ls/change" "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" + "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/modulespecifiers" "github.com/microsoft/TypeScript/tsc/internal/scanner" + "github.com/microsoft/TypeScript/tsc/internal/stringutil" "github.com/microsoft/TypeScript/tsc/internal/tsoptions" "github.com/microsoft/TypeScript/tsc/internal/tspath" ) @@ -196,7 +199,8 @@ func tryUpdateConfigString(configFile *ast.SourceFile, configDir tspath.RootedDi textRange := core.NewTextRange(scanner.GetTokenPosOfNode(element, configFile, false)+1, element.End()-1) lspRange, fidelity := converters.ToLSPRange(configFile, textRange) debug.Assert(fidelity.IsExact(), "config files are not content-mapped") - changeTracker.ReplaceRangeWithText(configFile, lspRange, relativePathFromDirectory(configDir, updated, caseSensitivity).AsString()) + newText := escapeJSONString(relativePathFromDirectory(configDir, updated, caseSensitivity).AsString(), lsutil.QuoteCharOfLiteral(element)) + changeTracker.ReplaceRangeWithText(configFile, lspRange, newText) return true } @@ -236,14 +240,16 @@ func (l *LanguageService) updateImportsForFileRename(program *compiler.Program, } updated := l.updateRelativePath(oldToNew, oldFileName, newImportFromPath, tspath.ToModuleSpecifier(ref.FileName)) if updated.AsString() != ref.FileName { - changeTracker.ReplaceTextRangeWithText(sourceFile, ref.TextRange, updated.AsString()) + if textRange, newText, ok := getReferencePathEdit(sourceFile, ref, updated.AsString()); ok { + changeTracker.ReplaceTextRangeWithText(sourceFile, textRange, newText) + } } } for _, importStringLiteral := range sourceFile.Imports() { updated := l.getUpdatedImportSpecifier(program, checker, sourceFile, importStringLiteral, oldToNew, movedFiles, newImportFromPath, fileMoved, moduleSpecifierPreferences) if updated != "" && updated != importStringLiteral.Text() { - changeTracker.ReplaceTextRangeWithText(sourceFile, createStringTextRange(sourceFile, importStringLiteral), updated) + changeTracker.ReplaceTextRangeWithText(sourceFile, createStringTextRange(sourceFile, importStringLiteral), lsutil.EscapeString(updated, lsutil.QuoteCharOfLiteral(importStringLiteral))) } } } @@ -358,6 +364,28 @@ func createStringTextRange(sourceFile *ast.SourceFile, node *ast.LiteralLikeNode return core.NewTextRange(scanner.GetTokenPosOfNode(node, sourceFile, false)+1, node.End()-1) } +// Reference directive paths have no escape syntax. A path containing the +// directive's quote is written with the other quote character instead, and a +// path containing both quotes or a line terminator cannot be written at all. +func getReferencePathEdit(sourceFile *ast.SourceFile, ref *ast.FileReference, path string) (core.TextRange, string, bool) { + if stringutil.ContainsLineBreak(path) { + return core.TextRange{}, "", false + } + text := sourceFile.Text() + quote := text[ref.Pos()-1] + if !strings.ContainsRune(path, rune(quote)) { + return ref.TextRange, path, true + } + otherQuote := byte('"') + if quote == '"' { + otherQuote = '\'' + } + if strings.ContainsRune(path, rune(otherQuote)) || ref.End() >= len(text) || text[ref.End()] != quote { + return core.TextRange{}, "", false + } + return core.NewTextRange(ref.Pos()-1, ref.End()+1), string(otherQuote) + path + string(otherQuote), true +} + func getTsConfigObjectLiteralExpression(tsConfigSourceFile *ast.SourceFile) *ast.ObjectLiteralExpression { if tsConfigSourceFile != nil && tsConfigSourceFile.Statements != nil && len(tsConfigSourceFile.Statements.Nodes) > 0 { expression := tsConfigSourceFile.Statements.Nodes[0].Expression() diff --git a/tsc/internal/ls/lsutil/utilities.go b/tsc/internal/ls/lsutil/utilities.go index bd85ec586f839..d1588322cbeea 100644 --- a/tsc/internal/ls/lsutil/utilities.go +++ b/tsc/internal/ls/lsutil/utilities.go @@ -8,6 +8,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/astnav" "github.com/microsoft/TypeScript/tsc/internal/compiler" "github.com/microsoft/TypeScript/tsc/internal/core" + "github.com/microsoft/TypeScript/tsc/internal/printer" "github.com/microsoft/TypeScript/tsc/internal/scanner" "github.com/microsoft/TypeScript/tsc/internal/tspath" ) @@ -88,6 +89,37 @@ func ShouldUseUriStyleNodeCoreModules(file *ast.SourceFile, program *compiler.Pr return program.UsesUriStyleNodeCoreModules() } +// EscapeString escapes s for the contents of a string literal delimited by +// quoteChar. It also escapes comment terminators, so the literal is safe to +// write anywhere, including in a JSDoc comment. +func EscapeString(s string, quoteChar printer.QuoteChar) string { + return strings.ReplaceAll(printer.EscapeString(s, quoteChar), "*/", `*\/`) +} + +// QuoteString returns s as a string literal delimited by quoteChar. +func QuoteString(s string, quoteChar printer.QuoteChar) string { + return string(quoteChar) + EscapeString(s, quoteChar) + string(quoteChar) +} + +// QuoteCharOfLiteral returns the quote character delimiting a string literal +// or a template literal without substitutions. +func QuoteCharOfLiteral(node *ast.StringLiteralLike) printer.QuoteChar { + if node.Kind == ast.KindNoSubstitutionTemplateLiteral { + return printer.QuoteCharBacktick + } + if node.AsStringLiteral().TokenFlags&ast.TokenFlagsSingleQuote != 0 { + return printer.QuoteCharSingleQuote + } + return printer.QuoteCharDoubleQuote +} + +func (q QuotePreference) QuoteChar() printer.QuoteChar { + if q == QuotePreferenceSingle { + return printer.QuoteCharSingleQuote + } + return printer.QuoteCharDoubleQuote +} + func QuotePreferenceFromString(str *ast.StringLiteral) QuotePreference { if str.TokenFlags&ast.TokenFlagsSingleQuote != 0 { return QuotePreferenceSingle diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 3415142ae6545..a5ab9f3980a09 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -11,11 +11,13 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/compiler" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/diagnostics" + "github.com/microsoft/TypeScript/tsc/internal/jsnum" "github.com/microsoft/TypeScript/tsc/internal/locale" "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" "github.com/microsoft/TypeScript/tsc/internal/module" + "github.com/microsoft/TypeScript/tsc/internal/scanner" "github.com/microsoft/TypeScript/tsc/internal/spanmap" "github.com/microsoft/TypeScript/tsc/internal/tspath" ) @@ -110,28 +112,54 @@ func (l *LanguageService) symbolAndEntriesToRename(ctx context.Context, params * return lsproto.WorkspaceEditOrNull{}, nil } - entries := core.FlatMap(data.SymbolsAndEntries, func(s *SymbolAndEntries) []*ReferenceEntry { return s.references }) var mappedEdits []mappedRenameEdit ch, done := program.GetTypeChecker(ctx) defer done() quotePreference := lsutil.GetQuotePreference(sourceFile, l.UserPreferences()) useAliasesForRename := l.UserPreferences().ProvidePrefixAndSuffixTextForRename.IsTrueOrUnknown() + renameToNonIdentifier := useAliasesForRename && !scanner.IsIdentifierText(params.NewName, core.LanguageVariantStandard) + + var entries []*ReferenceEntry + for _, symbolAndEntries := range data.SymbolsAndEntries { + // A non-identifier name cannot be bound as a local, so `import { foo }` becomes + // `import { "new-name" as foo }` and uses of the local `foo` are left alone. + if renameToNonIdentifier && symbolAndEntries.definition != nil && symbolAndEntries.definition.symbol != nil { + if spec := ast.GetDeclarationOfKind(symbolAndEntries.definition.symbol, ast.KindImportSpecifier); spec != nil && spec.PropertyName() == nil && !isRenamingImportSpecifierLocal(data.OriginalNode, spec, ch) { + for _, entry := range symbolAndEntries.references { + if entry.kind != entryKindRange && entry.node != nil && ast.GetReparsedNodeForNode(entry.node) == spec.Name() { + entries = append(entries, entry) + } + } + continue + } + } + entries = append(entries, symbolAndEntries.references...) + } for _, entry := range entries { uri := l.getFileNameOfEntry(entry) if l.UserPreferences().AllowRenameOfImportPath != core.TSTrue && entry.node != nil && ast.IsStringLiteralLike(entry.node) && ast.TryGetImportFromModuleSpecifier(entry.node) != nil { continue } + var jsxAttributeText string + if entry.kind != entryKindRange && entry.node != nil && ast.IsStringLiteral(entry.node) && ast.IsJsxAttribute(entry.node.Parent) { + // JSX attribute strings have no escapes, so a name the quotes cannot hold replaces the whole initializer. + jsxAttributeText = l.getJsxAttributeTextForRename(entry, params.NewName) + } rng, ok := l.renameEditRange(entry) if !ok { // The occurrence lies outside a verbatim span of a content-mapped file, so it cannot be // written back to the original text. Skip it and keep renaming the remaining occurrences. continue } + newText := jsxAttributeText + if newText == "" { + newText = l.getTextForRename(data.OriginalNode, entry, params.NewName, ch, quotePreference, useAliasesForRename) + } textEdit := &lsproto.TextEdit{ Range: rng, - NewText: l.getTextForRename(data.OriginalNode, entry, params.NewName, ch, quotePreference, useAliasesForRename), + NewText: newText, } mappedEdits = append(mappedEdits, mappedRenameEdit{uri: uri, edit: textEdit}) } @@ -146,6 +174,22 @@ func (l *LanguageService) symbolAndEntriesToRename(ctx context.Context, params * }, nil } +// getJsxAttributeTextForRename returns the text for a renamed JSX attribute string. When its quotes +// can contain the new name, the edit keeps the entry's range inside the quotes; otherwise the entry's +// range widens to the whole string so the edit can replace the initializer. +func (l *LanguageService) getJsxAttributeTextForRename(entry *ReferenceEntry, newName string) string { + sourceFile := ast.GetSourceFileOfNode(entry.node) + start := scanner.GetTokenPosOfNode(entry.node, sourceFile, false /*includeJSDoc*/) + if jsxAttributeStringCanContain(newName, sourceFile.Text()[start]) { + return newName + } + textRange := core.NewTextRange(start, entry.node.End()) + entry.sourceFile = sourceFile + entry.textRange = &textRange + entry.lspRange = nil + return jsxAttributeInitializerText(sourceFile, l.UserPreferences(), newName) +} + // renameEditRange returns the LSP range at which a rename occurrence should be edited. For occurrences in // content-mapped files it maps the transformed range strictly, returning ok=false when the occurrence is // not fully within a single verbatim span, so the caller can skip an edit that cannot be applied to the @@ -380,6 +424,7 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere kind := entry.kind parent := node.Parent name := originalNode.Text() + propertyText := quoteNonIdentifierName(newText, quotePreference) isShorthandAssignment := ast.IsShorthandPropertyAssignment(parent) switch { case isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.Name() == node && parent.AsBindingElement().DotDotDotToken == nil): @@ -387,7 +432,7 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere return name + ": " + newText } if kind == entryKindSearchedPropertyFoundLocal { - return newText + ": " + name + return propertyText + ": " + name } // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. @@ -396,44 +441,105 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere if ast.IsObjectLiteralExpression(grandParent) && ast.IsBinaryExpression(grandParent.Parent) && ast.IsModuleExportsAccessExpression(grandParent.Parent.AsBinaryExpression().Left) { return name + ": " + newText } - return newText + ": " + name + return propertyText + ": " + name } return name + ": " + newText case ast.IsImportSpecifier(parent) && parent.PropertyName() == nil: // If the original symbol was using this alias, just rename the alias. - var originalSymbol *ast.Symbol - if ast.IsExportSpecifier(originalNode.Parent) { - originalSymbol = ch.GetExportSpecifierLocalTargetSymbol(originalNode.Parent) - } else { - originalSymbol = ch.GetSymbolAtLocation(originalNode) - } - if originalSymbol != nil && slices.Contains(originalSymbol.Declarations(), parent) { + if isRenamingImportSpecifierLocal(originalNode, parent, ch) { return name + " as " + newText } + if propertyText != newText { + return propertyText + " as " + name + } return newText case ast.IsExportSpecifier(parent) && parent.PropertyName() == nil: // If the symbol for the node is same as declared node symbol use prefix text - if originalNode == entry.node || ch.GetSymbolAtLocation(originalNode) == ch.GetSymbolAtLocation(entry.node) { - return name + " as " + newText + usePrefix := originalNode == entry.node || ch.GetSymbolAtLocation(originalNode) == ch.GetSymbolAtLocation(entry.node) + if ast.IsStringLiteralLike(node) { + // For `export { "a b" } from "m"`, the edit range covers the literal's contents + // between its quotes, so the text closes and reopens them around " as ". + quoteChar := lsutil.QuoteCharOfLiteral(node) + exportName, localName := newText, name + if usePrefix { + exportName, localName = name, newText + } + return stringLiteralRenameText(node, lsutil.EscapeString(exportName, quoteChar)+string(quoteChar)+" as "+string(quoteChar)+lsutil.EscapeString(localName, quoteChar)) } - return newText + " as " + name + if usePrefix { + return name + " as " + propertyText + } + return propertyText + " as " + name } } + if entry.kind != entryKindRange && ast.IsStringLiteralLike(entry.node) { + return stringLiteralRenameText(entry.node, lsutil.EscapeString(newText, lsutil.QuoteCharOfLiteral(entry.node))) + } + // If the node is a numerical indexing literal, then add quotes around the property access. if entry.kind != entryKindRange && ast.IsNumericLiteral(entry.node) && ast.IsAccessExpression(entry.node.Parent) { - quote := getQuoteFromPreference(quotePreference) - return quote + newText + quote + return lsutil.QuoteString(newText, quotePreference.QuoteChar()) + } + + // A numeric property name, as in `{ 0: x }`, keeps a new name that is a non-negative number + // and must be quoted when the new name is not an identifier. + if entry.kind != entryKindRange && ast.IsNumericLiteral(entry.node) && ast.IsDeclarationName(entry.node) { + if !strings.HasPrefix(newText, "-") && jsnum.IsNumericLiteralName(newText) { + return newText + } + return quoteNonIdentifierName(newText, quotePreference) + } + + if entry.kind != entryKindRange && ast.IsIdentifier(entry.node) && isModuleExportNameOfSpecifier(entry.node) { + return quoteNonIdentifierName(newText, quotePreference) } return newText } -func getQuoteFromPreference(quotePreference lsutil.QuotePreference) string { - if quotePreference == lsutil.QuotePreferenceSingle { - return "'" +func isRenamingImportSpecifierLocal(originalNode *ast.Node, importSpecifier *ast.Node, ch *checker.Checker) bool { + var originalSymbol *ast.Symbol + if ast.IsExportSpecifier(originalNode.Parent) { + originalSymbol = ch.GetExportSpecifierLocalTargetSymbol(originalNode.Parent) + } else { + originalSymbol = ch.GetSymbolAtLocation(originalNode) + } + return originalSymbol != nil && slices.Contains(originalSymbol.Declarations(), importSpecifier) +} + +// isModuleExportNameOfSpecifier reports whether node names a module export, which may be +// written as a string literal: `a` in `import { a as b }` and `export { b as a }`, and both +// names in `export { a as b } from "m"`. +func isModuleExportNameOfSpecifier(node *ast.Node) bool { + parent := node.Parent + switch { + case ast.IsImportSpecifier(parent): + return parent.PropertyName() == node + case ast.IsExportSpecifier(parent): + return parent.Name() == node || parent.Parent.Parent.AsExportDeclaration().ModuleSpecifier != nil + case ast.IsNamespaceExport(parent): + return true + } + return false +} + +func quoteNonIdentifierName(name string, quotePreference lsutil.QuotePreference) string { + if scanner.IsIdentifierText(name, core.LanguageVariantStandard) { + return name + } + return lsutil.QuoteString(name, quotePreference.QuoteChar()) +} + +// stringLiteralRenameText returns the edit text that gives a string literal the +// already escaped contents. The rename range of an empty literal includes its +// quotes, so the text includes them too. +func stringLiteralRenameText(node *ast.StringLiteralLike, contents string) string { + if node.End()-scanner.GetTokenPosOfNode(node, ast.GetSourceFileOfNode(node), false /*includeJSDoc*/) <= 2 { + quoteChar := string(lsutil.QuoteCharOfLiteral(node)) + return quoteChar + contents + quoteChar } - return `"` + return contents } func getRenameInfoError(ctx context.Context, message *diagnostics.Message) RenameInfo { diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go index aa9b9a8b193c7..5968fec081ce4 100644 --- a/tsc/internal/ls/string_completions.go +++ b/tsc/internal/ls/string_completions.go @@ -21,7 +21,6 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/module" "github.com/microsoft/TypeScript/tsc/internal/modulespecifiers" "github.com/microsoft/TypeScript/tsc/internal/packagejson" - "github.com/microsoft/TypeScript/tsc/internal/printer" "github.com/microsoft/TypeScript/tsc/internal/scanner" "github.com/microsoft/TypeScript/tsc/internal/stringutil" "github.com/microsoft/TypeScript/tsc/internal/tsoptions" @@ -149,7 +148,7 @@ func (l *LanguageService) convertStringLiteralCompletions( } case completion.fromTypes != nil: completion := completion.fromTypes - quoteChar := stringCompletionQuoteChar(contextToken) + quoteChar := lsutil.QuoteCharOfLiteral(contextToken) isJsxAttribute := ast.IsJsxAttribute(contextToken.Parent) items := core.MapNonNil(completion.types, func(t *checker.StringLiteralType) *CompletionItem { value := t.AsLiteralType().Value().(string) @@ -158,7 +157,7 @@ func (l *LanguageService) convertStringLiteralCompletions( filterText := "" replacementSpan := l.getReplacementRangeForContextToken(file, contextToken, position) if !isJsxAttribute { - name = printer.EscapeString(value, quoteChar) + name = lsutil.EscapeString(value, quoteChar) } else if !jsxAttributeStringCanContain(value, byte(quoteChar)) { // JSX attribute strings have no escape sequences, so replace the // string with an expression container holding the value. @@ -240,11 +239,7 @@ func jsxAttributeStringCanContain(value string, quoteChar byte) bool { } func jsxExpressionContainerText(file *ast.SourceFile, preferences lsutil.UserPreferences, value string) string { - quoteChar := printer.QuoteCharDoubleQuote - if lsutil.GetQuotePreference(file, preferences) == lsutil.QuotePreferenceSingle { - quoteChar = printer.QuoteCharSingleQuote - } - return "{" + string(quoteChar) + printer.EscapeString(value, quoteChar) + string(quoteChar) + "}" + return "{" + lsutil.QuoteString(value, lsutil.GetQuotePreference(file, preferences).QuoteChar()) + "}" } func jsxAttributeInitializerText(file *ast.SourceFile, preferences lsutil.UserPreferences, value string) string { @@ -260,16 +255,6 @@ func jsxAttributeInitializerText(file *ast.SourceFile, preferences lsutil.UserPr return jsxExpressionContainerText(file, preferences, value) } -func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.QuoteChar { - if contextToken.Kind == ast.KindNoSubstitutionTemplateLiteral { - return printer.QuoteCharBacktick - } - if contextToken.AsStringLiteral().TokenFlags&ast.TokenFlagsSingleQuote != 0 { - return printer.QuoteCharSingleQuote - } - return printer.QuoteCharDoubleQuote -} - func (l *LanguageService) convertPathCompletions( ctx context.Context, completion *pathCompletions, @@ -289,7 +274,7 @@ func (l *LanguageService) convertPathCompletions( } insertText := "" if contextToken != nil { - escaped := printer.EscapeString(pathCompletion.name, stringCompletionQuoteChar(contextToken)) + escaped := lsutil.EscapeString(pathCompletion.name, lsutil.QuoteCharOfLiteral(contextToken)) if escaped != pathCompletion.name { insertText = escaped } diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index fca86ea0ac5ee..ca2b3392b29ec 100644 --- a/tsc/internal/ls/utilities.go +++ b/tsc/internal/ls/utilities.go @@ -17,6 +17,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" "github.com/microsoft/TypeScript/tsc/internal/ls/lsutil" "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" + "github.com/microsoft/TypeScript/tsc/internal/printer" "github.com/microsoft/TypeScript/tsc/internal/scanner" "github.com/microsoft/TypeScript/tsc/internal/spanmap" "github.com/microsoft/TypeScript/tsc/internal/stringutil" @@ -25,6 +26,10 @@ import ( var quoteReplacer = strings.NewReplacer("'", `\'`, `\"`, `"`) +// JSON leaves line and paragraph separators raw, but they are invisible in +// source and terminate string literals before ES2019. +var lineSeparatorReplacer = strings.NewReplacer("\u2028", `\u2028`, "\u2029", `\u2029`) + func IsInString(sourceFile *ast.SourceFile, position int, previousToken *ast.Node) bool { if previousToken != nil && ast.IsStringTextContainingNode(previousToken) { start := astnav.GetStartOfNode(previousToken, sourceFile, false /*includeJSDoc*/) @@ -311,15 +316,21 @@ func (l *LanguageService) createLspPosition(position int, file *ast.SourceFile) func quote(file *ast.SourceFile, preferences lsutil.UserPreferences, text string) string { // Editors can pass in undefined or empty string - we want to infer the preference in those cases. - quotePreference := lsutil.GetQuotePreference(file, preferences) - quoted := `"` + mapLoneSurrogates(text, func(s string) string { + return lsutil.QuoteString(text, lsutil.GetQuotePreference(file, preferences).QuoteChar()) +} + +// escapeJSONString escapes text for a string literal delimited by quoteChar +// using only escapes that both JSON and JavaScript accept, for JSON files +// such as tsconfig.json. +func escapeJSONString(text string, quoteChar printer.QuoteChar) string { + escaped := mapLoneSurrogates(text, func(s string) string { quoted, _ := core.StringifyJson(s, "" /*prefix*/, "" /*indent*/) - return stringutil.StripQuotes(quoted) - }) + `"` - if quotePreference == lsutil.QuotePreferenceSingle { - quoted = "'" + quoteReplacer.Replace(stringutil.StripQuotes(quoted)) + "'" + return lineSeparatorReplacer.Replace(stringutil.StripQuotes(quoted)) + }) + if quoteChar == printer.QuoteCharSingleQuote { + escaped = quoteReplacer.Replace(escaped) } - return quoted + return escaped } // mapLoneSurrogates applies f to the text between the lone surrogates in s and diff --git a/tsc/internal/stringutil/util.go b/tsc/internal/stringutil/util.go index dc3d89386113c..feae5b5bd5e6b 100644 --- a/tsc/internal/stringutil/util.go +++ b/tsc/internal/stringutil/util.go @@ -68,6 +68,10 @@ func IsLineBreak(ch rune) bool { return false } +func ContainsLineBreak(s string) bool { + return strings.IndexFunc(s, IsLineBreak) >= 0 +} + func IsDigit(ch rune) bool { return ch >= '0' && ch <= '9' } diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt new file mode 100644 index 0000000000000..8049d591521e4 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt @@ -0,0 +1,39 @@ +main.ts(2,14): error TS4023: Exported variable 'v' has or is using name 'A' from external module "dep" but cannot be named. +main2.ts(2,14): error TS4023: Exported variable 'x' has or is using name 'Foo.I' from external module "ns" but cannot be named. + + +==== dep.ts (0 errors) ==== + interface A { x: number } + interface C { y: number } + export { A as "a b", C as "a c", C as Ok }; + +==== mid.ts (0 errors) ==== + import { "a b" as B, "a c" as C } from "./dep"; + export declare function f(): B; + export declare function g(): C; + +==== main.ts (1 errors) ==== + import { f, g } from "./mid"; + export const v = f(); + ~ +!!! error TS4023: Exported variable 'v' has or is using name 'A' from external module "dep" but cannot be named. + export const w = g(); + +==== ns.ts (0 errors) ==== + namespace Foo { + export interface I {} + } + class Foo {} + export class Bar { + method(): Foo.I { + return {}; + } + } + export { Foo as "f o" }; + +==== main2.ts (1 errors) ==== + import { Bar } from "./ns"; + export const x = new Bar().method(); + ~ +!!! error TS4023: Exported variable 'x' has or is using name 'Foo.I' from external module "ns" but cannot be named. + \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js new file mode 100644 index 0000000000000..e1fe0d2c775f5 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js @@ -0,0 +1,79 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportName.ts] //// + +//// [dep.ts] +interface A { x: number } +interface C { y: number } +export { A as "a b", C as "a c", C as Ok }; + +//// [mid.ts] +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; + +//// [main.ts] +import { f, g } from "./mid"; +export const v = f(); +export const w = g(); + +//// [ns.ts] +namespace Foo { + export interface I {} +} +class Foo {} +export class Bar { + method(): Foo.I { + return {}; + } +} +export { Foo as "f o" }; + +//// [main2.ts] +import { Bar } from "./ns"; +export const x = new Bar().method(); + + +//// [dep.js] +export {}; +//// [mid.js] +export {}; +//// [main.js] +import { f, g } from "./mid"; +export const v = f(); +export const w = g(); +//// [ns.js] +class Foo { +} +export class Bar { + method() { + return {}; + } +} +export { Foo as "f o" }; +//// [main2.js] +import { Bar } from "./ns"; +export const x = new Bar().method(); + + +//// [dep.d.ts] +interface A { + x: number; +} +interface C { + y: number; +} +export { A as "a b", C as "a c", C as Ok }; +//// [mid.d.ts] +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; +//// [ns.d.ts] +declare namespace Foo { + interface I { + } +} +declare class Foo { +} +export declare class Bar { + method(): Foo.I; +} +export { Foo as "f o" }; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols new file mode 100644 index 0000000000000..a17f4aca33a12 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols @@ -0,0 +1,80 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportName.ts] //// + +=== dep.ts === +interface A { x: number } +>A : Symbol(A, Decl(dep.ts, 0, 0)) +>x : Symbol(A.x, Decl(dep.ts, 0, 13)) + +interface C { y: number } +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>y : Symbol(C.y, Decl(dep.ts, 1, 13)) + +export { A as "a b", C as "a c", C as Ok }; +>A : Symbol(A, Decl(dep.ts, 0, 0)) +>"a b" : Symbol("a b", Decl(dep.ts, 2, 8)) +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>"a c" : Symbol("a c", Decl(dep.ts, 2, 20)) +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>Ok : Symbol(Ok, Decl(dep.ts, 2, 32)) + +=== mid.ts === +import { "a b" as B, "a c" as C } from "./dep"; +>B : Symbol(B, Decl(mid.ts, 0, 8)) +>C : Symbol(C, Decl(mid.ts, 0, 20)) + +export declare function f(): B; +>f : Symbol(f, Decl(mid.ts, 0, 47)) +>B : Symbol(B, Decl(mid.ts, 0, 8)) + +export declare function g(): C; +>g : Symbol(g, Decl(mid.ts, 1, 31)) +>C : Symbol(C, Decl(mid.ts, 0, 20)) + +=== main.ts === +import { f, g } from "./mid"; +>f : Symbol(f, Decl(main.ts, 0, 8)) +>g : Symbol(g, Decl(main.ts, 0, 11)) + +export const v = f(); +>v : Symbol(v, Decl(main.ts, 1, 12)) +>f : Symbol(f, Decl(main.ts, 0, 8)) + +export const w = g(); +>w : Symbol(w, Decl(main.ts, 2, 12)) +>g : Symbol(g, Decl(main.ts, 0, 11)) + +=== ns.ts === +namespace Foo { +>Foo : Symbol(Foo, Decl(ns.ts, 0, 0), Decl(ns.ts, 2, 1)) + + export interface I {} +>I : Symbol(I, Decl(ns.ts, 0, 15)) +} +class Foo {} +>Foo : Symbol(Foo, Decl(ns.ts, 0, 0), Decl(ns.ts, 2, 1)) + +export class Bar { +>Bar : Symbol(Bar, Decl(ns.ts, 3, 12)) + + method(): Foo.I { +>method : Symbol(Bar.method, Decl(ns.ts, 4, 18)) +>Foo : Symbol(Foo, Decl(ns.ts, 0, 0), Decl(ns.ts, 2, 1)) +>I : Symbol(Foo.I, Decl(ns.ts, 0, 15)) + + return {}; + } +} +export { Foo as "f o" }; +>Foo : Symbol(Foo, Decl(ns.ts, 0, 0), Decl(ns.ts, 2, 1)) +>"f o" : Symbol("f o", Decl(ns.ts, 9, 8)) + +=== main2.ts === +import { Bar } from "./ns"; +>Bar : Symbol(Bar, Decl(main2.ts, 0, 8)) + +export const x = new Bar().method(); +>x : Symbol(x, Decl(main2.ts, 1, 12)) +>new Bar().method : Symbol(Bar.method, Decl(ns.ts, 4, 18)) +>Bar : Symbol(Bar, Decl(main2.ts, 0, 8)) +>method : Symbol(Bar.method, Decl(ns.ts, 4, 18)) + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types new file mode 100644 index 0000000000000..de5403933b981 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types @@ -0,0 +1,77 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportName.ts] //// + +=== dep.ts === +interface A { x: number } +>x : number + +interface C { y: number } +>y : number + +export { A as "a b", C as "a c", C as Ok }; +>A : any +>"a b" : any +>C : any +>"a c" : any +>C : any +>Ok : any + +=== mid.ts === +import { "a b" as B, "a c" as C } from "./dep"; +>B : any +>C : any + +export declare function f(): B; +>f : () => B + +export declare function g(): C; +>g : () => C + +=== main.ts === +import { f, g } from "./mid"; +>f : () => A +>g : () => import("./dep.js").Ok + +export const v = f(); +>v : A +>f() : A +>f : () => A + +export const w = g(); +>w : import("./dep").Ok +>g() : import("./dep").Ok +>g : () => import("./dep").Ok + +=== ns.ts === +namespace Foo { + export interface I {} +} +class Foo {} +>Foo : Foo + +export class Bar { +>Bar : Bar + + method(): Foo.I { +>method : () => Foo.I +>Foo : any + + return {}; +>{} : {} + } +} +export { Foo as "f o" }; +>Foo : typeof Foo +>"f o" : typeof Foo + +=== main2.ts === +import { Bar } from "./ns"; +>Bar : typeof Bar + +export const x = new Bar().method(); +>x : Foo.I +>new Bar().method() : Foo.I +>new Bar().method : () => Foo.I +>new Bar() : Bar +>Bar : typeof Bar +>method : () => Foo.I + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js new file mode 100644 index 0000000000000..3fa53652dc570 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js @@ -0,0 +1,25 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts] //// + +//// [a.d.ts] +interface A { x: number } +export { A as Ok }; + +//// [index.d.ts] +export { Ok as "a b" } from "./src/internal/a"; + +//// [index.d.ts] +import { Ok } from "dep/src/internal/a"; +export declare function f(): Ok; + +//// [main.ts] +import { f } from "mid"; +export const v = f(); + + +//// [main.js] +import { f } from "mid"; +export const v = f(); + + +//// [main.d.ts] +export declare const v: import("dep/src/internal/a").Ok; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.symbols b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.symbols new file mode 100644 index 0000000000000..105486787d1ae --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.symbols @@ -0,0 +1,32 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts] //// + +=== node_modules/dep/src/internal/a.d.ts === +interface A { x: number } +>A : Symbol(A, Decl(a.d.ts, 0, 0)) +>x : Symbol(A.x, Decl(a.d.ts, 0, 13)) + +export { A as Ok }; +>A : Symbol(A, Decl(a.d.ts, 0, 0)) +>Ok : Symbol(Ok, Decl(a.d.ts, 1, 8)) + +=== node_modules/dep/index.d.ts === +export { Ok as "a b" } from "./src/internal/a"; +>Ok : Symbol(Ok, Decl(a.d.ts, 1, 8)) +>"a b" : Symbol("a b", Decl(index.d.ts, 0, 8)) + +=== node_modules/mid/index.d.ts === +import { Ok } from "dep/src/internal/a"; +>Ok : Symbol(Ok, Decl(index.d.ts, 0, 8)) + +export declare function f(): Ok; +>f : Symbol(f, Decl(index.d.ts, 0, 40)) +>Ok : Symbol(Ok, Decl(index.d.ts, 0, 8)) + +=== main.ts === +import { f } from "mid"; +>f : Symbol(f, Decl(main.ts, 0, 8)) + +export const v = f(); +>v : Symbol(v, Decl(main.ts, 1, 12)) +>f : Symbol(f, Decl(main.ts, 0, 8)) + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types new file mode 100644 index 0000000000000..a745ccaffd1de --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts] //// + +=== node_modules/dep/src/internal/a.d.ts === +interface A { x: number } +>x : number + +export { A as Ok }; +>A : any +>Ok : any + +=== node_modules/dep/index.d.ts === +export { Ok as "a b" } from "./src/internal/a"; +>Ok : any +>"a b" : any + +=== node_modules/mid/index.d.ts === +import { Ok } from "dep/src/internal/a"; +>Ok : any + +export declare function f(): Ok; +>f : () => Ok + +=== main.ts === +import { f } from "mid"; +>f : () => import("dep/src/internal/a.js").Ok + +export const v = f(); +>v : import("dep/src/internal/a").Ok +>f() : import("dep/src/internal/a").Ok +>f : () => import("dep/src/internal/a").Ok + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.errors.txt b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.errors.txt new file mode 100644 index 0000000000000..dcba19d327615 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.errors.txt @@ -0,0 +1,77 @@ +/main1.ts(3,14): error TS4023: Exported variable 'v' has or is using name 'A' from external module "/dep" but cannot be named. +/main5.ts(3,14): error TS4023: Exported variable 'e' has or is using name 'E' from external module "/values" but cannot be named. + + +==== /dep.ts (0 errors) ==== + interface A { x: number } + interface C { y: number } + export { A as "a b", C as "a c", C as Ok }; + +==== /mid.ts (0 errors) ==== + import { "a b" as B, "a c" as C } from "./dep"; + export declare function f(): B; + export declare function g(): C; + +==== /main1.ts (1 errors) ==== + import * as dep from "./dep"; + import { f } from "./mid"; + export const v = f(); + ~ +!!! error TS4023: Exported variable 'v' has or is using name 'A' from external module "/dep" but cannot be named. + +==== /main2.ts (0 errors) ==== + import * as dep from "./dep"; + import { g } from "./mid"; + export const w = g(); + +==== /inner.ts (0 errors) ==== + export declare function foo(): void; + +==== /values.ts (0 errors) ==== + declare const sym: unique symbol; + declare function fn(): void; + declare enum E { A } + declare namespace N { const z: number; } + export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; + export * as "x y" from "./inner"; + +==== /valuesMid.ts (0 errors) ==== + import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; + export declare const fnRef: typeof F; + export declare const enumMember: E.A; + export declare const nested: typeof N.z; + export declare const viaNamespace: typeof X.foo; + +==== /main3.ts (0 errors) ==== + import * as values from "./values"; + export const k = { [values["s t"]]: 1 }; + export const a = values["c d"].A; + +==== /main4.ts (0 errors) ==== + import * as values from "./values"; + import { fnRef, nested, viaNamespace } from "./valuesMid"; + export const f = fnRef; + export const n = nested; + export const x = viaNamespace; + +==== /main5.ts (1 errors) ==== + import * as values from "./values"; + import { enumMember } from "./valuesMid"; + export const e = enumMember; + ~ +!!! error TS4023: Exported variable 'e' has or is using name 'E' from external module "/values" but cannot be named. + +==== /statics.ts (0 errors) ==== + export declare class S { static readonly "a b": unique symbol; } + export declare namespace M { + class D { static readonly "c d": unique symbol; } + } + +==== /staticsMid.ts (0 errors) ==== + import { S, M } from "./statics"; + export const obj = { s: S["a b"], d: M.D["c d"] } as const; + +==== /main6.ts (0 errors) ==== + import { obj } from "./staticsMid"; + export const o = obj; + \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js new file mode 100644 index 0000000000000..509390e6510c2 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js @@ -0,0 +1,177 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts] //// + +//// [dep.ts] +interface A { x: number } +interface C { y: number } +export { A as "a b", C as "a c", C as Ok }; + +//// [mid.ts] +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; + +//// [main1.ts] +import * as dep from "./dep"; +import { f } from "./mid"; +export const v = f(); + +//// [main2.ts] +import * as dep from "./dep"; +import { g } from "./mid"; +export const w = g(); + +//// [inner.ts] +export declare function foo(): void; + +//// [values.ts] +declare const sym: unique symbol; +declare function fn(): void; +declare enum E { A } +declare namespace N { const z: number; } +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +export * as "x y" from "./inner"; + +//// [valuesMid.ts] +import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; +export declare const fnRef: typeof F; +export declare const enumMember: E.A; +export declare const nested: typeof N.z; +export declare const viaNamespace: typeof X.foo; + +//// [main3.ts] +import * as values from "./values"; +export const k = { [values["s t"]]: 1 }; +export const a = values["c d"].A; + +//// [main4.ts] +import * as values from "./values"; +import { fnRef, nested, viaNamespace } from "./valuesMid"; +export const f = fnRef; +export const n = nested; +export const x = viaNamespace; + +//// [main5.ts] +import * as values from "./values"; +import { enumMember } from "./valuesMid"; +export const e = enumMember; + +//// [statics.ts] +export declare class S { static readonly "a b": unique symbol; } +export declare namespace M { + class D { static readonly "c d": unique symbol; } +} + +//// [staticsMid.ts] +import { S, M } from "./statics"; +export const obj = { s: S["a b"], d: M.D["c d"] } as const; + +//// [main6.ts] +import { obj } from "./staticsMid"; +export const o = obj; + + +//// [dep.js] +export {}; +//// [mid.js] +export {}; +//// [main1.js] +import { f } from "./mid"; +export const v = f(); +//// [main2.js] +import { g } from "./mid"; +export const w = g(); +//// [inner.js] +export {}; +//// [values.js] +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +import * as _a from "./inner"; +export { _a as "x y" }; +//// [valuesMid.js] +export {}; +//// [main3.js] +import * as values from "./values"; +export const k = { [values["s t"]]: 1 }; +export const a = values["c d"].A; +//// [main4.js] +import { fnRef, nested, viaNamespace } from "./valuesMid"; +export const f = fnRef; +export const n = nested; +export const x = viaNamespace; +//// [main5.js] +import { enumMember } from "./valuesMid"; +export const e = enumMember; +//// [statics.js] +export {}; +//// [staticsMid.js] +import { S, M } from "./statics"; +export const obj = { s: S["a b"], d: M.D["c d"] }; +//// [main6.js] +import { obj } from "./staticsMid"; +export const o = obj; + + +//// [dep.d.ts] +interface A { + x: number; +} +interface C { + y: number; +} +export { A as "a b", C as "a c", C as Ok }; +//// [mid.d.ts] +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; +//// [main2.d.ts] +import * as dep from "./dep"; +export declare const w: dep.Ok; +//// [inner.d.ts] +export declare function foo(): void; +//// [values.d.ts] +declare const sym: unique symbol; +declare function fn(): void; +declare enum E { + A +} +declare namespace N { + const z: number; +} +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +export * as "x y" from "./inner"; +//// [valuesMid.d.ts] +import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; +export declare const fnRef: typeof F; +export declare const enumMember: E.A; +export declare const nested: typeof N.z; +export declare const viaNamespace: typeof X.foo; +//// [main3.d.ts] +import * as values from "./values"; +export declare const k: { + [values["s t"]]: number; +}; +export declare const a = values["c d"].A; +//// [main4.d.ts] +import * as values from "./values"; +export declare const f: (typeof values)["f g"]; +export declare const n: number; +export declare const x: (typeof values)["x y"]["foo"]; +//// [statics.d.ts] +export declare class S { + static readonly "a b": unique symbol; +} +export declare namespace M { + class D { + static readonly "c d": unique symbol; + } +} +//// [staticsMid.d.ts] +import { S, M } from "./statics"; +export declare const obj: { + readonly s: (typeof S)["a b"]; + readonly d: (typeof M.D)["c d"]; +}; +//// [main6.d.ts] +export declare const o: { + readonly s: typeof import("./statics").S["a b"]; + readonly d: typeof import("./statics").M.D["c d"]; +}; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols new file mode 100644 index 0000000000000..8d4fdcfdfaa61 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols @@ -0,0 +1,201 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts] //// + +=== /dep.ts === +interface A { x: number } +>A : Symbol(A, Decl(dep.ts, 0, 0)) +>x : Symbol(A.x, Decl(dep.ts, 0, 13)) + +interface C { y: number } +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>y : Symbol(C.y, Decl(dep.ts, 1, 13)) + +export { A as "a b", C as "a c", C as Ok }; +>A : Symbol(A, Decl(dep.ts, 0, 0)) +>"a b" : Symbol("a b", Decl(dep.ts, 2, 8)) +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>"a c" : Symbol("a c", Decl(dep.ts, 2, 20)) +>C : Symbol(C, Decl(dep.ts, 0, 25)) +>Ok : Symbol(Ok, Decl(dep.ts, 2, 32)) + +=== /mid.ts === +import { "a b" as B, "a c" as C } from "./dep"; +>B : Symbol(B, Decl(mid.ts, 0, 8)) +>C : Symbol(C, Decl(mid.ts, 0, 20)) + +export declare function f(): B; +>f : Symbol(f, Decl(mid.ts, 0, 47)) +>B : Symbol(B, Decl(mid.ts, 0, 8)) + +export declare function g(): C; +>g : Symbol(g, Decl(mid.ts, 1, 31)) +>C : Symbol(C, Decl(mid.ts, 0, 20)) + +=== /main1.ts === +import * as dep from "./dep"; +>dep : Symbol(dep, Decl(main1.ts, 0, 6)) + +import { f } from "./mid"; +>f : Symbol(f, Decl(main1.ts, 1, 8)) + +export const v = f(); +>v : Symbol(v, Decl(main1.ts, 2, 12)) +>f : Symbol(f, Decl(main1.ts, 1, 8)) + +=== /main2.ts === +import * as dep from "./dep"; +>dep : Symbol(dep, Decl(main2.ts, 0, 6)) + +import { g } from "./mid"; +>g : Symbol(g, Decl(main2.ts, 1, 8)) + +export const w = g(); +>w : Symbol(w, Decl(main2.ts, 2, 12)) +>g : Symbol(g, Decl(main2.ts, 1, 8)) + +=== /inner.ts === +export declare function foo(): void; +>foo : Symbol(foo, Decl(inner.ts, 0, 0)) + +=== /values.ts === +declare const sym: unique symbol; +>sym : Symbol(sym, Decl(values.ts, 0, 13)) + +declare function fn(): void; +>fn : Symbol(fn, Decl(values.ts, 0, 33)) + +declare enum E { A } +>E : Symbol(E, Decl(values.ts, 1, 28)) +>A : Symbol(E.A, Decl(values.ts, 2, 16)) + +declare namespace N { const z: number; } +>N : Symbol(N, Decl(values.ts, 2, 20)) +>z : Symbol(z, Decl(values.ts, 3, 27)) + +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +>sym : Symbol(sym, Decl(values.ts, 0, 13)) +>"s t" : Symbol("s t", Decl(values.ts, 4, 8)) +>fn : Symbol(fn, Decl(values.ts, 0, 33)) +>"f g" : Symbol("f g", Decl(values.ts, 4, 22)) +>E : Symbol(E, Decl(values.ts, 1, 28)) +>"c d" : Symbol("c d", Decl(values.ts, 4, 35)) +>N : Symbol(N, Decl(values.ts, 2, 20)) +>"n m" : Symbol("n m", Decl(values.ts, 4, 47)) + +export * as "x y" from "./inner"; +>"x y" : Symbol("x y", Decl(values.ts, 5, 6)) + +=== /valuesMid.ts === +import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; +>F : Symbol(F, Decl(valuesMid.ts, 0, 8)) +>E : Symbol(E, Decl(valuesMid.ts, 0, 20)) +>N : Symbol(N, Decl(valuesMid.ts, 0, 32)) +>X : Symbol(X, Decl(valuesMid.ts, 0, 44)) + +export declare const fnRef: typeof F; +>fnRef : Symbol(fnRef, Decl(valuesMid.ts, 1, 20)) +>F : Symbol(F, Decl(valuesMid.ts, 0, 8)) + +export declare const enumMember: E.A; +>enumMember : Symbol(enumMember, Decl(valuesMid.ts, 2, 20)) +>E : Symbol(E, Decl(valuesMid.ts, 0, 20)) +>A : Symbol(E.A, Decl(values.ts, 2, 16)) + +export declare const nested: typeof N.z; +>nested : Symbol(nested, Decl(valuesMid.ts, 3, 20)) +>N.z : Symbol(N.z, Decl(values.ts, 3, 27)) +>N : Symbol(N, Decl(valuesMid.ts, 0, 32)) +>z : Symbol(N.z, Decl(values.ts, 3, 27)) + +export declare const viaNamespace: typeof X.foo; +>viaNamespace : Symbol(viaNamespace, Decl(valuesMid.ts, 4, 20)) +>X.foo : Symbol(X.foo, Decl(inner.ts, 0, 0)) +>X : Symbol(X, Decl(valuesMid.ts, 0, 44)) +>foo : Symbol(X.foo, Decl(inner.ts, 0, 0)) + +=== /main3.ts === +import * as values from "./values"; +>values : Symbol(values, Decl(main3.ts, 0, 6)) + +export const k = { [values["s t"]]: 1 }; +>k : Symbol(k, Decl(main3.ts, 1, 12)) +>[values["s t"]] : Symbol([values["s t"]], Decl(main3.ts, 1, 18)) +>values : Symbol(values, Decl(main3.ts, 0, 6)) +>"s t" : Symbol(values["s t"], Decl(values.ts, 4, 8)) + +export const a = values["c d"].A; +>a : Symbol(a, Decl(main3.ts, 2, 12)) +>values["c d"].A : Symbol(E.A, Decl(values.ts, 2, 16)) +>values : Symbol(values, Decl(main3.ts, 0, 6)) +>"c d" : Symbol(values["c d"], Decl(values.ts, 4, 35)) +>A : Symbol(E.A, Decl(values.ts, 2, 16)) + +=== /main4.ts === +import * as values from "./values"; +>values : Symbol(values, Decl(main4.ts, 0, 6)) + +import { fnRef, nested, viaNamespace } from "./valuesMid"; +>fnRef : Symbol(fnRef, Decl(main4.ts, 1, 8)) +>nested : Symbol(nested, Decl(main4.ts, 1, 15)) +>viaNamespace : Symbol(viaNamespace, Decl(main4.ts, 1, 23)) + +export const f = fnRef; +>f : Symbol(f, Decl(main4.ts, 2, 12)) +>fnRef : Symbol(fnRef, Decl(main4.ts, 1, 8)) + +export const n = nested; +>n : Symbol(n, Decl(main4.ts, 3, 12)) +>nested : Symbol(nested, Decl(main4.ts, 1, 15)) + +export const x = viaNamespace; +>x : Symbol(x, Decl(main4.ts, 4, 12)) +>viaNamespace : Symbol(viaNamespace, Decl(main4.ts, 1, 23)) + +=== /main5.ts === +import * as values from "./values"; +>values : Symbol(values, Decl(main5.ts, 0, 6)) + +import { enumMember } from "./valuesMid"; +>enumMember : Symbol(enumMember, Decl(main5.ts, 1, 8)) + +export const e = enumMember; +>e : Symbol(e, Decl(main5.ts, 2, 12)) +>enumMember : Symbol(enumMember, Decl(main5.ts, 1, 8)) + +=== /statics.ts === +export declare class S { static readonly "a b": unique symbol; } +>S : Symbol(S, Decl(statics.ts, 0, 0)) +>"a b" : Symbol(S["a b"], Decl(statics.ts, 0, 24)) + +export declare namespace M { +>M : Symbol(M, Decl(statics.ts, 0, 64)) + + class D { static readonly "c d": unique symbol; } +>D : Symbol(D, Decl(statics.ts, 1, 28)) +>"c d" : Symbol(D["c d"], Decl(statics.ts, 2, 13)) +} + +=== /staticsMid.ts === +import { S, M } from "./statics"; +>S : Symbol(S, Decl(staticsMid.ts, 0, 8)) +>M : Symbol(M, Decl(staticsMid.ts, 0, 11)) + +export const obj = { s: S["a b"], d: M.D["c d"] } as const; +>obj : Symbol(obj, Decl(staticsMid.ts, 1, 12)) +>s : Symbol(s, Decl(staticsMid.ts, 1, 20)) +>S : Symbol(S, Decl(staticsMid.ts, 0, 8)) +>"a b" : Symbol(S["a b"], Decl(statics.ts, 0, 24)) +>d : Symbol(d, Decl(staticsMid.ts, 1, 33)) +>M.D : Symbol(M.D, Decl(statics.ts, 1, 28)) +>M : Symbol(M, Decl(staticsMid.ts, 0, 11)) +>D : Symbol(M.D, Decl(statics.ts, 1, 28)) +>"c d" : Symbol(M.D["c d"], Decl(statics.ts, 2, 13)) +>const : Symbol(const) + +=== /main6.ts === +import { obj } from "./staticsMid"; +>obj : Symbol(obj, Decl(main6.ts, 0, 8)) + +export const o = obj; +>o : Symbol(o, Decl(main6.ts, 1, 12)) +>obj : Symbol(obj, Decl(main6.ts, 0, 8)) + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types new file mode 100644 index 0000000000000..0bde67d671f54 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types @@ -0,0 +1,205 @@ +//// [tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts] //// + +=== /dep.ts === +interface A { x: number } +>x : number + +interface C { y: number } +>y : number + +export { A as "a b", C as "a c", C as Ok }; +>A : any +>"a b" : any +>C : any +>"a c" : any +>C : any +>Ok : any + +=== /mid.ts === +import { "a b" as B, "a c" as C } from "./dep"; +>B : any +>C : any + +export declare function f(): B; +>f : () => B + +export declare function g(): C; +>g : () => C + +=== /main1.ts === +import * as dep from "./dep"; +>dep : typeof dep + +import { f } from "./mid"; +>f : () => A + +export const v = f(); +>v : A +>f() : A +>f : () => A + +=== /main2.ts === +import * as dep from "./dep"; +>dep : typeof dep + +import { g } from "./mid"; +>g : () => dep.Ok + +export const w = g(); +>w : dep.Ok +>g() : dep.Ok +>g : () => dep.Ok + +=== /inner.ts === +export declare function foo(): void; +>foo : () => void + +=== /values.ts === +declare const sym: unique symbol; +>sym : unique symbol + +declare function fn(): void; +>fn : () => void + +declare enum E { A } +>E : E +>A : E.A + +declare namespace N { const z: number; } +>N : typeof N +>z : number + +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +>sym : unique symbol +>"s t" : unique symbol +>fn : () => void +>"f g" : () => void +>E : typeof E +>"c d" : typeof E +>N : typeof N +>"n m" : typeof N + +export * as "x y" from "./inner"; +>"x y" : typeof import("./inner") + +=== /valuesMid.ts === +import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; +>F : () => void +>E : typeof E +>N : typeof N +>X : typeof X + +export declare const fnRef: typeof F; +>fnRef : () => void +>F : () => void + +export declare const enumMember: E.A; +>enumMember : E +>E : any + +export declare const nested: typeof N.z; +>nested : number +>N.z : number +>N : typeof N +>z : number + +export declare const viaNamespace: typeof X.foo; +>viaNamespace : () => void +>X.foo : () => void +>X : typeof X +>foo : () => void + +=== /main3.ts === +import * as values from "./values"; +>values : typeof values + +export const k = { [values["s t"]]: 1 }; +>k : { [values["s t"]]: number; } +>{ [values["s t"]]: 1 } : { [values["s t"]]: number; } +>[values["s t"]] : number +>values["s t"] : unique symbol +>values : typeof values +>"s t" : "s t" +>1 : 1 + +export const a = values["c d"].A; +>a : E.A +>values["c d"].A : E +>values["c d"] : (typeof values)["c d"] +>values : typeof values +>"c d" : "c d" +>A : E + +=== /main4.ts === +import * as values from "./values"; +>values : typeof values + +import { fnRef, nested, viaNamespace } from "./valuesMid"; +>fnRef : () => void +>nested : number +>viaNamespace : () => void + +export const f = fnRef; +>f : () => void +>fnRef : () => void + +export const n = nested; +>n : number +>nested : number + +export const x = viaNamespace; +>x : () => void +>viaNamespace : () => void + +=== /main5.ts === +import * as values from "./values"; +>values : typeof values + +import { enumMember } from "./valuesMid"; +>enumMember : E + +export const e = enumMember; +>e : E +>enumMember : E + +=== /statics.ts === +export declare class S { static readonly "a b": unique symbol; } +>S : S +>"a b" : unique symbol + +export declare namespace M { +>M : typeof M + + class D { static readonly "c d": unique symbol; } +>D : D +>"c d" : unique symbol +} + +=== /staticsMid.ts === +import { S, M } from "./statics"; +>S : typeof S +>M : typeof M + +export const obj = { s: S["a b"], d: M.D["c d"] } as const; +>obj : { readonly s: unique symbol; readonly d: unique symbol; } +>{ s: S["a b"], d: M.D["c d"] } as const : { readonly s: unique symbol; readonly d: unique symbol; } +>{ s: S["a b"], d: M.D["c d"] } : { readonly s: unique symbol; readonly d: unique symbol; } +>s : unique symbol +>S["a b"] : unique symbol +>S : typeof S +>"a b" : "a b" +>d : unique symbol +>M.D["c d"] : unique symbol +>M.D : typeof M.D +>M : typeof M +>D : typeof M.D +>"c d" : "c d" + +=== /main6.ts === +import { obj } from "./staticsMid"; +>obj : { readonly s: unique symbol; readonly d: unique symbol; } + +export const o = obj; +>o : { readonly s: unique symbol; readonly d: unique symbol; } +>obj : { readonly s: unique symbol; readonly d: unique symbol; } + diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRename.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRename.baseline index f2d2a4b2f90ed..c4fbb70495920 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRename.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRename.baseline @@ -90,7 +90,7 @@ Config File Names:: "line": 2, "character": 29 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameStartingAtDefinition.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameStartingAtDefinition.baseline index b8780b52250c7..fbffe97600378 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameStartingAtDefinition.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameStartingAtDefinition.baseline @@ -128,7 +128,7 @@ Config File Names:: "line": 0, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameTargetDoesNotExist.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameTargetDoesNotExist.baseline index e07f777f116a4..15a692da2896b 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameTargetDoesNotExist.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameTargetDoesNotExist.baseline @@ -90,7 +90,7 @@ Config File Names:: "line": 2, "character": 38 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirect.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirect.baseline index ae0a38b1747e8..054f95617e115 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirect.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirect.baseline @@ -280,7 +280,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEdit.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEdit.baseline index 38a74d79d7436..bf4d9132e0d32 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEdit.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEdit.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -1364,7 +1364,7 @@ Projects:: "line": 3, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEditEnd.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEditEnd.baseline index b421d6bff3b38..e21c4f25fd4e0 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEditEnd.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEditEnd.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -917,7 +917,7 @@ Projects:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferences.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferences.baseline index 2a7b7244c1c40..a9b1be211d09a 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferences.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferences.baseline @@ -138,7 +138,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEdit.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEdit.baseline index 6f33464894543..730991775be89 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEdit.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEdit.baseline @@ -99,7 +99,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -1226,7 +1226,7 @@ Projects:: "line": 3, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEditEnd.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEditEnd.baseline index 2815b8011e786..58069fa343638 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEditEnd.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithProjectReferencesEditEnd.baseline @@ -99,7 +99,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -779,7 +779,7 @@ Projects:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMaps.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMaps.baseline index 3ee427c76ca97..4d44d1f015cf5 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMaps.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMaps.baseline @@ -280,7 +280,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEdit.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEdit.baseline index d6ed813c2cf5f..4f202745d9d66 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEdit.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEdit.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -1341,7 +1341,7 @@ Projects:: "line": 3, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEditEnd.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEditEnd.baseline index 468fcbfc59ca8..30511c8d4c4df 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEditEnd.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsEditEnd.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -894,7 +894,7 @@ Projects:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolution.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolution.baseline index e6fc31ef1bd73..fa5a75235f3e7 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolution.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolution.baseline @@ -280,7 +280,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEdit.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEdit.baseline index 5100b33126200..43e8ecbdb62fe 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEdit.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEdit.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -1371,7 +1371,7 @@ Projects:: "line": 3, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEditEnd.baseline b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEditEnd.baseline index 0eb4e7f4fc0d3..9ef26e6cfac3c 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEditEnd.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/declarationMapsRenameWithSourceMapsNotSolutionEditEnd.baseline @@ -241,7 +241,7 @@ Config File Names:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } @@ -924,7 +924,7 @@ Projects:: "line": 2, "character": 16 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/renameAncestorProjectRefMangement.baseline b/tsc/testdata/baselines/reference/fourslash/state/renameAncestorProjectRefMangement.baseline index 2980575549b44..c440fd04df480 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/renameAncestorProjectRefMangement.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/renameAncestorProjectRefMangement.baseline @@ -147,7 +147,7 @@ Config File Names:: "line": 0, "character": 9 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/baselines/reference/fourslash/state/renameInCommonFile.baseline b/tsc/testdata/baselines/reference/fourslash/state/renameInCommonFile.baseline index ce325f3d57b40..1d3d57cd0be7d 100644 --- a/tsc/testdata/baselines/reference/fourslash/state/renameInCommonFile.baseline +++ b/tsc/testdata/baselines/reference/fourslash/state/renameInCommonFile.baseline @@ -180,7 +180,7 @@ Config File Names:: "line": 0, "character": 13 }, - "newName": "?" + "newName": "RENAME_PLACEHOLDER" } } diff --git a/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportName.ts b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportName.ts new file mode 100644 index 0000000000000..f6344faa32fc3 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportName.ts @@ -0,0 +1,34 @@ +// @declaration: true +// @module: esnext +// @target: esnext + +// @filename: dep.ts +interface A { x: number } +interface C { y: number } +export { A as "a b", C as "a c", C as Ok }; + +// @filename: mid.ts +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; + +// @filename: main.ts +import { f, g } from "./mid"; +export const v = f(); +export const w = g(); + +// @filename: ns.ts +namespace Foo { + export interface I {} +} +class Foo {} +export class Bar { + method(): Foo.I { + return {}; + } +} +export { Foo as "f o" }; + +// @filename: main2.ts +import { Bar } from "./ns"; +export const x = new Bar().method(); diff --git a/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts new file mode 100644 index 0000000000000..4cffb3f202e83 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts @@ -0,0 +1,18 @@ +// @declaration: true +// @module: esnext +// @target: esnext + +// @filename: node_modules/dep/src/internal/a.d.ts +interface A { x: number } +export { A as Ok }; + +// @filename: node_modules/dep/index.d.ts +export { Ok as "a b" } from "./src/internal/a"; + +// @filename: node_modules/mid/index.d.ts +import { Ok } from "dep/src/internal/a"; +export declare function f(): Ok; + +// @filename: main.ts +import { f } from "mid"; +export const v = f(); diff --git a/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts new file mode 100644 index 0000000000000..c6960ddf02472 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts @@ -0,0 +1,69 @@ +// @declaration: true +// @Filename: /dep.ts +interface A { x: number } +interface C { y: number } +export { A as "a b", C as "a c", C as Ok }; + +// @Filename: /mid.ts +import { "a b" as B, "a c" as C } from "./dep"; +export declare function f(): B; +export declare function g(): C; + +// @Filename: /main1.ts +import * as dep from "./dep"; +import { f } from "./mid"; +export const v = f(); + +// @Filename: /main2.ts +import * as dep from "./dep"; +import { g } from "./mid"; +export const w = g(); + +// @Filename: /inner.ts +export declare function foo(): void; + +// @Filename: /values.ts +declare const sym: unique symbol; +declare function fn(): void; +declare enum E { A } +declare namespace N { const z: number; } +export { sym as "s t", fn as "f g", E as "c d", N as "n m" }; +export * as "x y" from "./inner"; + +// @Filename: /valuesMid.ts +import { "f g" as F, "c d" as E, "n m" as N, "x y" as X } from "./values"; +export declare const fnRef: typeof F; +export declare const enumMember: E.A; +export declare const nested: typeof N.z; +export declare const viaNamespace: typeof X.foo; + +// @Filename: /main3.ts +import * as values from "./values"; +export const k = { [values["s t"]]: 1 }; +export const a = values["c d"].A; + +// @Filename: /main4.ts +import * as values from "./values"; +import { fnRef, nested, viaNamespace } from "./valuesMid"; +export const f = fnRef; +export const n = nested; +export const x = viaNamespace; + +// @Filename: /main5.ts +import * as values from "./values"; +import { enumMember } from "./valuesMid"; +export const e = enumMember; + +// @Filename: /statics.ts +export declare class S { static readonly "a b": unique symbol; } +export declare namespace M { + class D { static readonly "c d": unique symbol; } +} + +// @Filename: /staticsMid.ts +import { S, M } from "./statics"; +export const obj = { s: S["a b"], d: M.D["c d"] } as const; + +// @Filename: /main6.ts +import { obj } from "./staticsMid"; +export const o = obj;