diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 204062db49de0..43e000160e208 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,9 @@ 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 name can only reference exports with identifier names + (!ignoreQualification || 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..8b3c424af13d1 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -30,3 +30,62 @@ 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 +interface Hidden { x: number } +export { Hidden as "a\\u0062" }; +export type I = { [K in "c\\u0064"]: Hidden }; +// @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": Hidden; +}`, + Index: 0, + }) +} + +func TestCodeFixClassImplementInterfaceMappedUniqueSymbolKey(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `declare const key: unique symbol; +type I = { [K in typeof key]: 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: `declare const key: unique symbol; +type I = { [K in typeof key]: number }; +class C implements I { + [key]: 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/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index 3b95ff4724941..d6c7e1eb97320 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: /eclair.tsx +export function éclair(props: any) {} +// @Filename: /index.tsx +export function Index() { + return <écl/**/ +}` + 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: "éclair", + Data: &lsproto.CompletionItemData{ + AutoImport: &lsproto.AutoImportFix{ + ModuleSpecifier: "./eclair", + }, + }, + AdditionalTextEdits: fourslash.AnyTextEdits, + SortText: new(string(ls.SortTextAutoImportSuggestions)), + }, + }, + }, + }) + f.VerifyApplyCodeActionFromCompletion(t, new(""), &fourslash.ApplyCodeActionFromCompletionOptions{ + Name: "éclair", + Source: "./eclair", + Description: "Add import from \"./eclair\"", + NewFileContent: new(`import { éclair } from "./eclair"; + +export function Index() { + return <écl +}`), + }) +} 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_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/organizeImportsAttributes4_test.go b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go index ad800f43a6e64..0921d584ead01 100644 --- a/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go +++ b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go @@ -34,3 +34,22 @@ export type G = A | B | C | D | E | F | Y | Z;`, nil, ) } + +func TestOrganizeImportsAttributesWithQuotes(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `import { A } from "./a" with { type: "x\" z:\"y" }; +import { B } from "./a" with { type: "x", z: "y" }; + +export type C = A | B;` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyOrganizeImports(t, + `import { A } from "./a" with { type: "x\" z:\"y" }; +import { B } from "./a" with { type: "x", z: "y" }; + +export type C = A | B;`, + lsproto.CodeActionKindSourceOrganizeImportsTs, + nil, + ) +} diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go new file mode 100644 index 0000000000000..e59726944329b --- /dev/null +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -0,0 +1,175 @@ +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 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 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 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 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/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 59271fd360b3a..82b6c65ad689d 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -6,7 +6,6 @@ import ( "fmt" "slices" "strings" - "unicode" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -152,7 +151,7 @@ func addImportType(f *Fix, file *ast.SourceFile, preferences lsutil.UserPreferen if quotePreference == lsutil.QuotePreferenceSingle { quoteChar = printer.QuoteCharSingleQuote } - importTypePrefix := fmt.Sprintf("import(%c%s%c).", quoteChar, printer.EscapeString(f.ModuleSpecifier, quoteChar), quoteChar) + importTypePrefix := fmt.Sprintf("import(%c%s%c).", quoteChar, lsutil.EscapeStringInComment(f.ModuleSpecifier, quoteChar), quoteChar) tracker.InsertText(file, *f.UsagePosition, importTypePrefix) return diagnostics.Change_0_to_1.Localize(locale, f.Name, importTypePrefix+f.Name) } @@ -603,10 +602,9 @@ 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:]) + name = strings.ToUpper(name[:1]) + name[1:] } else { return nil } @@ -1134,7 +1132,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..608b046b8172f 100644 --- a/tsc/internal/ls/codeactions_missingmemberfixer.go +++ b/tsc/internal/ls/codeactions_missingmemberfixer.go @@ -13,6 +13,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 +62,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, enclosingDeclaration, quotePreference) modifiers := f.createModifiers(symbol, declaration) flags := nodebuilder.FlagsNoTruncation @@ -486,22 +487,32 @@ 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, enclosingDeclaration *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.TypeFlagsUniqueESSymbol != 0 { + return factory.NewComputedPropertyName(typeChecker.SymbolToExpression(nameType.Symbol(), ast.SymbolFlagsValue, enclosingDeclaration, nodebuilder.FlagsNone)) + } 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..1da67d6d881ff 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -2142,13 +2142,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 +2215,7 @@ func (l *LanguageService) createCompletionItem( var labelDetails *lsproto.CompletionItemLabelDetails preferences := l.UserPreferences() if data.completionKind == CompletionKindString { - escaped := printer.EscapeString(name, stringCompletionQuoteChar(contextToken)) + escaped := escapeStringForNode(name, stringCompletionQuoteChar(contextToken), contextToken) if escaped != name { insertText = escaped } @@ -2492,13 +2493,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 +2747,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 +3750,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 +6350,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 +6381,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, "*/") && !strings.ContainsAny(text, "\r\n\u2028\u2029") +} + 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 +6531,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 +6552,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 +6711,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 +6873,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 +6883,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 +6897,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 +6930,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..ff9c2a1251783 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,8 +12,10 @@ 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/printer" "github.com/microsoft/TypeScript/tsc/internal/scanner" "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(), getStringLiteralQuoteChar(configFile, element)) + changeTracker.ReplaceRangeWithText(configFile, lspRange, newText) return true } @@ -236,14 +240,23 @@ 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) + quoteChar := getStringLiteralQuoteChar(sourceFile, importStringLiteral) + var newText string + if importStringLiteral.Flags&ast.NodeFlagsJSDoc != 0 { + newText = lsutil.EscapeStringInComment(updated, quoteChar) + } else { + newText = printer.EscapeString(updated, quoteChar) + } + changeTracker.ReplaceTextRangeWithText(sourceFile, createStringTextRange(sourceFile, importStringLiteral), newText) } } } @@ -358,6 +371,39 @@ func createStringTextRange(sourceFile *ast.SourceFile, node *ast.LiteralLikeNode return core.NewTextRange(scanner.GetTokenPosOfNode(node, sourceFile, false)+1, node.End()-1) } +func getStringLiteralQuoteChar(sourceFile *ast.SourceFile, node *ast.LiteralLikeNode) printer.QuoteChar { + switch sourceFile.Text()[scanner.GetTokenPosOfNode(node, sourceFile, false)] { + case '\'': + return printer.QuoteCharSingleQuote + case '`': + return printer.QuoteCharBacktick + default: + return printer.QuoteCharDoubleQuote + } +} + +// 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 strings.ContainsAny(path, "\r\n\u2028\u2029") { + 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..e375c9d878d7d 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,12 @@ func ShouldUseUriStyleNodeCoreModules(file *ast.SourceFile, program *compiler.Pr return program.UsesUriStyleNodeCoreModules() } +// EscapeStringInComment escapes s for a string literal delimited by quoteChar +// that appears inside a block comment, such as a JSDoc type. +func EscapeStringInComment(s string, quoteChar printer.QuoteChar) string { + return strings.ReplaceAll(printer.EscapeString(s, quoteChar), "*/", `*\/`) +} + func QuotePreferenceFromString(str *ast.StringLiteral) QuotePreference { if str.TokenFlags&ast.TokenFlagsSingleQuote != 0 { return QuotePreferenceSingle diff --git a/tsc/internal/ls/organizeimports.go b/tsc/internal/ls/organizeimports.go index d7a8390f2b607..39e81836b567a 100644 --- a/tsc/internal/ls/organizeimports.go +++ b/tsc/internal/ls/organizeimports.go @@ -3,6 +3,7 @@ package ls import ( "context" "slices" + "strconv" "strings" "github.com/microsoft/TypeScript/tsc/internal/ast" @@ -371,12 +372,10 @@ func getImportAttributesKey(attributes *ast.ImportAttributesNode) string { for _, attrNode := range attrNodes { attr := attrNode.AsImportAttribute() - key.WriteString(attr.Name().Text()) + key.WriteString(strconv.Quote(attr.Name().Text())) key.WriteString(":") if ast.IsStringLiteralLike(attr.Value.AsNode()) { - key.WriteString(`"`) - key.WriteString(attr.Value.Text()) - key.WriteString(`"`) + key.WriteString(strconv.Quote(attr.Value.Text())) } else { key.WriteString(attr.Value.AsNode().Text()) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 3415142ae6545..bf044a5b532b2 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -16,6 +16,8 @@ import ( "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/printer" + "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 the edit 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, keeping its +// quotes when they can contain the new name, and widens the entry's range to the whole string. +func (l *LanguageService) getJsxAttributeTextForRename(entry *ReferenceEntry, newName string) string { + sourceFile := ast.GetSourceFileOfNode(entry.node) + start := scanner.GetTokenPosOfNode(entry.node, sourceFile, false /*includeJSDoc*/) + textRange := core.NewTextRange(start, entry.node.End()) + entry.sourceFile = sourceFile + entry.textRange = &textRange + entry.lspRange = nil + quoteChar := sourceFile.Text()[start] + if jsxAttributeStringCanContain(newName, quoteChar) { + return string(quoteChar) + newName + string(quoteChar) + } + 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, entry.node) 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,120 @@ 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. + sourceFile := ast.GetSourceFileOfNode(node) + quoteChar := getStringLiteralQuoteChar(sourceFile, node) + quote := func(s string) string { + return string(quoteChar) + printer.EscapeString(s, quoteChar) + string(quoteChar) + } + text := quote(newText) + " as " + quote(name) + if usePrefix { + text = quote(name) + " as " + quote(newText) + } + if node.End()-scanner.GetTokenPosOfNode(node, sourceFile, false /*includeJSDoc*/) <= 2 { + return text + } + return text[1 : len(text)-1] } - return newText + " as " + name + if usePrefix { + return name + " as " + propertyText + } + return propertyText + " as " + name + } + } + + if entry.kind != entryKindRange && ast.IsStringLiteralLike(entry.node) { + sourceFile := ast.GetSourceFileOfNode(entry.node) + quoteChar := getStringLiteralQuoteChar(sourceFile, entry.node) + escaped := escapeStringForNode(newText, quoteChar, entry.node) + // The rename range of an empty string literal includes its quotes. + if entry.node.End()-scanner.GetTokenPosOfNode(entry.node, sourceFile, false /*includeJSDoc*/) <= 2 { + return string(quoteChar) + escaped + string(quoteChar) } + return escaped } // 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 + quoteChar := getQuoteFromPreference(quotePreference) + return string(quoteChar) + escapeStringForNode(newText, quoteChar, entry.node) + string(quoteChar) + } + + // A numeric property name, as in `{ 0: x }`, must be quoted when the new name is not an identifier. + if entry.kind != entryKindRange && ast.IsNumericLiteral(entry.node) && ast.IsDeclarationName(entry.node) { + return quoteNonIdentifierName(newText, quotePreference, entry.node) + } + + if entry.kind != entryKindRange && ast.IsIdentifier(entry.node) && isModuleExportNameOfSpecifier(entry.node) { + return quoteNonIdentifierName(newText, quotePreference, entry.node) } return newText } -func getQuoteFromPreference(quotePreference lsutil.QuotePreference) string { +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, node *ast.Node) string { + if scanner.IsIdentifierText(name, core.LanguageVariantStandard) { + return name + } + quoteChar := getQuoteFromPreference(quotePreference) + return string(quoteChar) + escapeStringForNode(name, quoteChar, node) + string(quoteChar) +} + +func escapeStringForNode(s string, quoteChar printer.QuoteChar, node *ast.Node) string { + if node.Flags&ast.NodeFlagsJSDoc != 0 { + return lsutil.EscapeStringInComment(s, quoteChar) + } + return printer.EscapeString(s, quoteChar) +} + +func getQuoteFromPreference(quotePreference lsutil.QuotePreference) printer.QuoteChar { if quotePreference == lsutil.QuotePreferenceSingle { - return "'" + return printer.QuoteCharSingleQuote } - return `"` + return printer.QuoteCharDoubleQuote } 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..56ed097f6e8a6 100644 --- a/tsc/internal/ls/string_completions.go +++ b/tsc/internal/ls/string_completions.go @@ -158,7 +158,7 @@ func (l *LanguageService) convertStringLiteralCompletions( filterText := "" replacementSpan := l.getReplacementRangeForContextToken(file, contextToken, position) if !isJsxAttribute { - name = printer.EscapeString(value, quoteChar) + name = escapeStringForNode(value, quoteChar, contextToken) } else if !jsxAttributeStringCanContain(value, byte(quoteChar)) { // JSX attribute strings have no escape sequences, so replace the // string with an expression container holding the value. diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index fca86ea0ac5ee..9d1ee2e937f5e 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,23 @@ 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 { + if lsutil.GetQuotePreference(file, preferences) == lsutil.QuotePreferenceSingle { + return "'" + escapeJSONString(text, printer.QuoteCharSingleQuote) + "'" + } + return `"` + escapeJSONString(text, printer.QuoteCharDoubleQuote) + `"` +} + +// escapeJSONString escapes text for a string literal delimited by quoteChar +// using only escapes that both JSON and JavaScript accept. +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/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt new file mode 100644 index 0000000000000..d0a9f74717389 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt @@ -0,0 +1,20 @@ +main.ts(2,14): error TS4023: Exported variable 'v' has or is using name 'A' from external module "dep" 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(); + \ 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..7d9d17b5db5c7 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js @@ -0,0 +1,40 @@ +//// [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(); + + +//// [dep.js] +export {}; +//// [mid.js] +export {}; +//// [main.js] +import { f, g } from "./mid"; +export const v = f(); +export const w = g(); + + +//// [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; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols new file mode 100644 index 0000000000000..0f783fbc25252 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols @@ -0,0 +1,45 @@ +//// [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)) + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types new file mode 100644 index 0000000000000..f70a07e37cc75 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types @@ -0,0 +1,43 @@ +//// [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 + 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..7536d57b88aee --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.errors.txt @@ -0,0 +1,25 @@ +/main1.ts(3,14): error TS4023: Exported variable 'v' has or is using name 'A' from external module "/dep" 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(); + \ 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..809db8044b2b7 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js @@ -0,0 +1,50 @@ +//// [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(); + + +//// [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(); + + +//// [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; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols new file mode 100644 index 0000000000000..0caf71f57df3e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols @@ -0,0 +1,54 @@ +//// [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)) + diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types new file mode 100644 index 0000000000000..e86a183636d7e --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types @@ -0,0 +1,52 @@ +//// [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 + 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..6e5e50b54bc46 --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportName.ts @@ -0,0 +1,18 @@ +// @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(); 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..c1bcfa21bca5d --- /dev/null +++ b/tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts @@ -0,0 +1,20 @@ +// @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();