From ebff411e45f57a91a06da8e7f5e6faa43b4fc078 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:51:46 -0800 Subject: [PATCH 01/53] Add tests for file rename edits with quotes in paths These show that renaming a file or directory writes the updated module specifier into import strings, tsconfig strings and reference directives without escaping it, so a file name containing a quote produces broken code. --- ...ditsForFileRename_escapedSpecifier_test.go | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go 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..6f93b142cb55e --- /dev/null +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -0,0 +1,54 @@ +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*/) +} From 63debea2bbe5fde4adece2f3e89aa381d8a20f72 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:53:32 -0800 Subject: [PATCH 02/53] Escape module specifiers in file rename edits Renaming a file or directory rewrites import strings and tsconfig paths using the unescaped specifier text. A file name containing a quote, such as one shipped in a dependency's declaration files, then closes the string and turns the rest of the name into code in the importing file. Escape the new text for the quote used by each string literal. Reference directive paths have no escape syntax, so leave a directive unchanged when its new path contains the directive's quote or a line terminator. --- ...ditsForFileRename_escapedSpecifier_test.go | 18 ++++++------- tsc/internal/ls/file_rename.go | 27 ++++++++++++++++--- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 6f93b142cb55e..1ae79a3e8f99e 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -21,10 +21,10 @@ func TestGetEditsForFileRename_escapedSpecifier(t *testing.T) { 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\"] }", + "/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*/) } @@ -44,11 +44,11 @@ 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'; + "/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"] }`, + "/tsconfig.json": `{ "files": ["a.ts", "n'e\"w/b.ts"] }`, }, nil /*preferences*/) } diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index b3c1ca5e6eeb4..3a1c794d0bbdb 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" @@ -13,6 +14,7 @@ import ( "github.com/microsoft/TypeScript/tsc/internal/ls/lsconv" "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 +198,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 := printer.EscapeString(relativePathFromDirectory(configDir, updated, caseSensitivity).AsString(), getStringLiteralQuoteChar(configFile, element)) + changeTracker.ReplaceRangeWithText(configFile, lspRange, newText) return true } @@ -235,7 +238,7 @@ func (l *LanguageService) updateImportsForFileRename(program *compiler.Program, continue } updated := l.updateRelativePath(oldToNew, oldFileName, newImportFromPath, tspath.ToModuleSpecifier(ref.FileName)) - if updated.AsString() != ref.FileName { + if updated.AsString() != ref.FileName && canWriteReferencePath(sourceFile, ref, updated.AsString()) { changeTracker.ReplaceTextRangeWithText(sourceFile, ref.TextRange, updated.AsString()) } } @@ -243,7 +246,7 @@ func (l *LanguageService) updateImportsForFileRename(program *compiler.Program, for _, importStringLiteral := range sourceFile.Imports() { updated := l.getUpdatedImportSpecifier(program, checker, sourceFile, importStringLiteral, oldToNew, movedFiles, newImportFromPath, fileMoved, moduleSpecifierPreferences) if updated != "" && updated != importStringLiteral.Text() { - changeTracker.ReplaceTextRangeWithText(sourceFile, createStringTextRange(sourceFile, importStringLiteral), updated) + changeTracker.ReplaceTextRangeWithText(sourceFile, createStringTextRange(sourceFile, importStringLiteral), printer.EscapeString(updated, getStringLiteralQuoteChar(sourceFile, importStringLiteral))) } } } @@ -358,6 +361,24 @@ 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, so a path containing the +// directive's quote or a line terminator cannot be written into the comment. +func canWriteReferencePath(sourceFile *ast.SourceFile, ref *ast.FileReference, path string) bool { + quote := sourceFile.Text()[ref.Pos()-1] + return !strings.ContainsAny(path, string(quote)+"\r\n\u2028\u2029") +} + func getTsConfigObjectLiteralExpression(tsConfigSourceFile *ast.SourceFile) *ast.ObjectLiteralExpression { if tsConfigSourceFile != nil && tsConfigSourceFile.Statements != nil && len(tsConfigSourceFile.Statements.Nodes) > 0 { expression := tsConfigSourceFile.Statements.Nodes[0].Expression() From 10ba4db1db3d03e08bc8051091da908f3536d4f9 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:41 -0800 Subject: [PATCH 03/53] Add tests for comment terminators in JSDoc module specifiers Auto-import and file rename write module specifiers into JSDoc import types. These tests record the current output for a path containing */, which ends the comment early. --- .../autoImportQuotedModuleSpecifier_test.go | 18 ++++++++++++++++++ ...EditsForFileRename_escapedSpecifier_test.go | 18 ++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go b/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go index ad2b8144d44b9..8cc8b29f70a6b 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/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 1ae79a3e8f99e..29f0dd52faa21 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -52,3 +52,21 @@ export default 0;`, "/tsconfig.json": `{ "files": ["a.ts", "n'e\"w/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*/) +} From 596490ea1f548450e41f047cffe68de1cb3b197c Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:46:52 -0800 Subject: [PATCH 04/53] Escape comment terminators in JSDoc module specifiers Module specifiers written into JSDoc import types sit inside a block comment. A specifier containing */ ends the comment early, so the rest of the specifier and the remainder of the JSDoc become code. --- .../tests/autoImportQuotedModuleSpecifier_test.go | 2 +- .../getEditsForFileRename_escapedSpecifier_test.go | 2 +- tsc/internal/ls/autoimport/fix.go | 2 +- tsc/internal/ls/file_rename.go | 10 +++++++++- tsc/internal/ls/lsutil/utilities.go | 7 +++++++ 5 files changed, 19 insertions(+), 4 deletions(-) diff --git a/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go b/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go index 8cc8b29f70a6b..21ee5c88cbfab 100644 --- a/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go +++ b/tsc/internal/fourslash/tests/autoImportQuotedModuleSpecifier_test.go @@ -184,6 +184,6 @@ 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} */ + f.VerifyImportFixAtPosition(t, []string{`/** @type {import("./dir*\/mod").T} */ const x = 0;`}, nil /*preferences*/) } diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 29f0dd52faa21..76fa3eb3b325f 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -66,7 +66,7 @@ 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} */ + "/src/sub/index.js": `/** @type {import("../../pkg*\/a.js").Foo} */ const x = null;`, }, nil /*preferences*/) } diff --git a/tsc/internal/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 59271fd360b3a..16cf51ec38e33 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -152,7 +152,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) } diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index 3a1c794d0bbdb..b0d77673ad7cc 100644 --- a/tsc/internal/ls/file_rename.go +++ b/tsc/internal/ls/file_rename.go @@ -12,6 +12,7 @@ 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" @@ -246,7 +247,14 @@ func (l *LanguageService) updateImportsForFileRename(program *compiler.Program, 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), printer.EscapeString(updated, getStringLiteralQuoteChar(sourceFile, importStringLiteral))) + 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) } } } 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 From ba562d7601d7acbb652346177d5e216ba1f4f76f Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:41 -0800 Subject: [PATCH 05/53] Add a test for comment terminators in JSDoc @param completions JSDoc @param completions copy initializers, inferred types and destructured property names into the comment. This test records the current completions for text containing */. --- .../tests/basicJSDocCompletions_test.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index 8c9a3eed4de50..b0e1e793c4278 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -122,3 +122,43 @@ 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 }) {}` + 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 {{ "*/": number; }} [b={ "*/": 1 }] `, + }, + }, + }) + f.VerifyCompletions(t, "2", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + "param {object} param0 \n* @param {*} param0.*/ ", + }, + }, + }) +} From 525a497149ce36532df77e1d38492e6551f72dcd Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:49:33 -0800 Subject: [PATCH 06/53] Omit unsafe text from JSDoc @param completions JSDoc @param completions copy initializers, inferred types and destructured property names into the comment. Text containing */ or a line break ends the comment or the tag early, so such text is left out and the tag falls back to a plainer form. --- .../fourslash/tests/basicJSDocCompletions_test.go | 6 +++--- tsc/internal/ls/completions.go | 14 +++++++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index b0e1e793c4278..5dc933abf97c5 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -145,8 +145,8 @@ function g({ "*/": c }) {}` }, Items: &fourslash.CompletionsExpectedItems{ Includes: []fourslash.CompletionsExpectedItem{ - `param {string} [a="*/"] `, - `param {{ "*/": number; }} [b={ "*/": 1 }] `, + "param {string} [a] ", + "param {*} [b] ", }, }, }) @@ -157,7 +157,7 @@ function g({ "*/": c }) {}` }, Items: &fourslash.CompletionsExpectedItems{ Includes: []fourslash.CompletionsExpectedItem{ - "param {object} param0 \n* @param {*} param0.*/ ", + "param {*} param0 ", }, }, }) diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index 9affd8602168a..6b26c3b96b937 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -6348,7 +6348,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 +6379,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 +6529,7 @@ func jsDocParamElementWorker( } else { propertyName = element.Name().Text() } - if propertyName == "" { + if propertyName == "" || !isSafeInJSDocTag(propertyName) { return nil } paramName := fmt.Sprintf("%s.%s", path, propertyName) From d58386609eb267647a4f8f1803bade0d970ccaf1 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:42 -0800 Subject: [PATCH 07/53] Add tests for snippet escaping in member completions These tests record member, object literal method, exhaustive switch and import statement completions for names containing $ and backslashes, with and without client snippet support. --- .../tests/completionsSnippetEscaping_test.go | 126 ++++++++++++++++++ ...portStatementCompletions_noSnippet_test.go | 37 +++++ 2 files changed, 163 insertions(+) create mode 100644 tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go diff --git a/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go new file mode 100644 index 0000000000000..022cc23c9c4d3 --- /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/importStatementCompletions_noSnippet_test.go b/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go index c2b173dae770d..3fa79403fcfa7 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, + }, + }, + }, + }, + }, + }) +} From d12ed50f1ef0c7ca77a09671b36f664277e2121e Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:57:38 -0800 Subject: [PATCH 08/53] Skip snippet escaping in non-snippet completions Clients without snippet support insert completion text verbatim. Member and import statement completions escaped $ for snippets in that mode too, so names such as $returnPromise were inserted with a stray backslash. --- .../completionsOverridingMethod22_test.go | 2 +- .../tests/completionsSnippetEscaping_test.go | 4 ++-- ...portStatementCompletions_noSnippet_test.go | 4 ++-- tsc/internal/ls/completions.go | 24 ++++++++++++------- 4 files changed, 21 insertions(+), 13 deletions(-) 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 index 022cc23c9c4d3..8b1026fe09edc 100644 --- a/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go +++ b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go @@ -38,9 +38,9 @@ switch (s) { name := "plain" var insertTextFormat *lsproto.InsertTextFormat classMemberM := `m(x: "a\\b"): void {` + "\n}" - classMember := `"c\$d"(): void {` + "\n}" + classMember := `"c$d"(): void {` + "\n}" objectMethodA := `"a\\b"() {` + "\n}," - objectMethodC := `"c\$d"() {` + "\n}," + objectMethodC := `"c$d"() {` + "\n}," if snippet { name = "snippet" insertTextFormat = new(lsproto.InsertTextFormatSnippet) diff --git a/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go b/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go index 3fa79403fcfa7..cbb48e6db009d 100644 --- a/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go +++ b/tsc/internal/fourslash/tests/importStatementCompletions_noSnippet_test.go @@ -70,7 +70,7 @@ export const f$oo = 0; Includes: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ Label: "f$oo", - InsertText: new("import { f\\$oo } from \"./mod\";"), + InsertText: new("import { f$oo } from \"./mod\";"), Data: &lsproto.CompletionItemData{ AutoImport: &lsproto.AutoImportFix{ ModuleSpecifier: "./mod", @@ -78,7 +78,7 @@ export const f$oo = 0; }, TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ TextEdit: &lsproto.TextEdit{ - NewText: "import { f\\$oo } from \"./mod\";", + NewText: "import { f$oo } from \"./mod\";", Range: f.Ranges()[0].LSRange, }, }, diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index 6b26c3b96b937..d97cfdbcfd463 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, `\`, `\\`)) + 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 { @@ -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 { @@ -6709,7 +6709,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) { @@ -6871,7 +6871,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() } @@ -6879,6 +6881,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, @@ -6892,7 +6895,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) { @@ -6924,6 +6928,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() From f67a3035cdf202ebdef8be54c6f1a09cd5de6a58 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:42 -0800 Subject: [PATCH 09/53] Add a test for backslashes in JSX closing tag snippets This test records the closing tag snippet for a JSX tag name written with a Unicode escape. --- tsc/internal/fourslash/tests/autoCloseTag_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tsc/internal/fourslash/tests/autoCloseTag_test.go b/tsc/internal/fourslash/tests/autoCloseTag_test.go index d40d5f5028d56..129b054d3e103 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(``), + }) +} From 67abaf4050d9daf2db3fe55d292f2690b084ff78 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:59:57 -0800 Subject: [PATCH 10/53] Escape backslashes in snippet text Snippet syntax treats a backslash as an escape character, so a literal backslash must be written as \\. Snippet text containing a backslash, such as a string-named member or a JSX tag name with a Unicode escape, lost the backslash when the client expanded the snippet. --- tsc/internal/fourslash/tests/autoCloseTag_test.go | 2 +- .../fourslash/tests/completionsSnippetEscaping_test.go | 6 +++--- tsc/internal/ls/completions.go | 6 ++++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/autoCloseTag_test.go b/tsc/internal/fourslash/tests/autoCloseTag_test.go index 129b054d3e103..e35c6e5126a5e 100644 --- a/tsc/internal/fourslash/tests/autoCloseTag_test.go +++ b/tsc/internal/fourslash/tests/autoCloseTag_test.go @@ -81,6 +81,6 @@ const x = /*0*/;` f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) defer done() f.VerifyJsxClosingTag(t, map[string]*string{ - "0": new(``), + "0": new(``), }) } diff --git a/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go index 8b1026fe09edc..e94450748fa3d 100644 --- a/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go +++ b/tsc/internal/fourslash/tests/completionsSnippetEscaping_test.go @@ -44,9 +44,9 @@ switch (s) { if snippet { name = "snippet" insertTextFormat = new(lsproto.InsertTextFormatSnippet) - classMemberM = `m(x: "a\\b"): void {` + "\n $0\n}" + classMemberM = `m(x: "a\\\\b"): void {` + "\n $0\n}" classMember = `"c\$d"(): void {` + "\n $0\n}" - objectMethodA = `"a\\b"() {` + "\n $0\n}," + objectMethodA = `"a\\\\b"() {` + "\n $0\n}," objectMethodC = `"c\$d"() {` + "\n $0\n}," } t.Run(name, func(t *testing.T) { @@ -113,7 +113,7 @@ switch (s) { Includes: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ Label: `case "a\\b": ...`, - InsertText: new(`case "a\\b":$1` + "\n" + `case "x":$2`), + InsertText: new(`case "a\\\\b":$1` + "\n" + `case "x":$2`), SortText: new(string(ls.SortTextGlobalsOrKeywords)), InsertTextFormat: new(lsproto.InsertTextFormatSnippet), }, diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index d97cfdbcfd463..f16c9562fc26f 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -2144,7 +2144,7 @@ func getInsertTextAndReplacementSpanForImportCompletion(fix *autoimport.Fix, imp 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", "") @@ -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 { From 749922c7e1bd6b03169df1d0e7b842defe70a685 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:42 -0800 Subject: [PATCH 11/53] Add tests for new names in string literal rename edits These tests record rename edits for symbols referenced through string literals when the new name contains quotes, a backslash or snippet syntax, and for an empty string export name. --- .../fourslash/tests/renameEscaping_test.go | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 tsc/internal/fourslash/tests/renameEscaping_test.go diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go new file mode 100644 index 0000000000000..2bd251053418c --- /dev/null +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -0,0 +1,47 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + "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 };\n" + + "obj[\"it's \"${x}\"\\\"];\n" + + "obj['it's \"${x}\"\\'];\n" + + "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 };`, + }) +} From 5479fe50f563b935ca2e8cd534ca7363b12860be Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:04:15 -0800 Subject: [PATCH 12/53] Escape new names in string literal rename edits Renaming a symbol referenced through a string literal, such as an element access or a quoted property name, wrote the new name into the literal as-is. A name containing the literal's quote or a backslash then produced different strings or broken code. An empty literal's rename range also covers its quotes, so the new name lost its quotes entirely. --- .../fourslash/tests/renameEscaping_test.go | 12 ++++---- tsc/internal/ls/rename.go | 30 +++++++++++++++---- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 2bd251053418c..af699b2f73190 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -21,14 +21,14 @@ func TestRenameEscapesStringLiterals(t *testing.T) { 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 };\n" + - "obj[\"it's \"${x}\"\\\"];\n" + - "obj['it's \"${x}\"\\'];\n" + - "obj[`it's \"${x}\"\\`];", + "/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", + "foo[\"a\\\"b\"];\n", }) } @@ -42,6 +42,6 @@ export { foo as "/*1*/" };` defer done() f.VerifyRename(t, "1", `a"b`, map[string]string{ "/a.ts": `const foo = 1; -export { foo as a"b };`, +export { foo as "a\"b" };`, }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 3415142ae6545..745e971ddc818 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" ) @@ -420,20 +422,38 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere } } + 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) } return newText } -func getQuoteFromPreference(quotePreference lsutil.QuotePreference) string { +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 { From 11ef57d5103a0af0192dd02624882a81d0eb1cc8 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:43 -0800 Subject: [PATCH 13/53] Add a test for non-identifier mapped property names in member fixes This test records the implement interface fix for a mapped type whose key looks like an identifier escape and whose value type is only exported under a string name. --- ...ClassImplementInterfaceMappedType2_test.go | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index 22bed95d6eb6d..70ff96639d4df 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -30,3 +30,26 @@ 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: a\u0062; +}`, + Index: 0, + }) +} From 3c8afb7d5c4bbdca5f66156aa8fcf3f5d8b9250f Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:07:02 -0800 Subject: [PATCH 14/53] Quote non-identifier mapped property names in member fixes Implementing members of a mapped type wrote each key as an identifier. A key that isn't a valid identifier produced a syntax error, and a key that looks like an identifier escape, such as c\u0064, declared a member with a different name. --- .../codeFixClassImplementInterfaceMappedType2_test.go | 2 +- tsc/internal/ls/codeactions_missingmemberfixer.go | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index 70ff96639d4df..f580d4fd9eeaf 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -48,7 +48,7 @@ class C implements I {}` Description: "Implement interface 'I'", NewFileContent: `import { I } from "dep"; class C implements I { - c\u0064: a\u0062; + "c\\u0064": a\u0062; }`, Index: 0, }) diff --git a/tsc/internal/ls/codeactions_missingmemberfixer.go b/tsc/internal/ls/codeactions_missingmemberfixer.go index 4f1cf6caf0a36..5d98517f9c4f6 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, quotePreference) modifiers := f.createModifiers(symbol, declaration) flags := nodebuilder.FlagsNoTruncation @@ -486,11 +487,15 @@ func createDummyParameters(factory *ast.NodeFactory, argCount int, names []strin return factory.NewNodeList(parameters) } -func createDeclarationName(factory *ast.NodeFactory, typeChecker *checker.Checker, symbol *ast.Symbol, declaration *ast.Node) *ast.PropertyName { +func createDeclarationName(factory *ast.NodeFactory, typeChecker *checker.Checker, symbol *ast.Symbol, declaration *ast.Node, quotePreference lsutil.QuotePreference) *ast.PropertyName { if symbol != nil && symbol.CheckFlags()&ast.CheckFlagsMapped != 0 { nameType := typeChecker.GetNameTypeOfSymbol(symbol) if nameType != nil && checker.IsTypeUsableAsPropertyName(nameType) { - return factory.NewIdentifier(checker.GetPropertyNameFromType(nameType)) + name := checker.GetPropertyNameFromType(nameType) + if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { + return factory.NewStringLiteral(name, core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone)) + } + return factory.NewIdentifier(name) } } if declaration != nil && declaration.Name() != nil { From fb371932d4182ed7ffd47dc32f46de29e914b976 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:43 -0800 Subject: [PATCH 15/53] Add a test for literal names in binding extraction This test records the extract binding expressions fix for numeric and escape-like string property names. --- ...ixMissingTypeAnnotationOnExports14_test.go | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go b/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go index c4d9276e593c8..efc4896b3ff63 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, + }) +} From b9b9a0eef171998b7933f8dacec3cdaa4735a58a Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:11:31 -0800 Subject: [PATCH 16/53] Use element access for literal names in binding extraction Extracting a destructured export for isolatedDeclarations wrote each property name after a dot. Numeric names and string names that aren't identifiers produced invalid code or, for names that look like identifier escapes, read a different property. --- .../tests/codeFixMissingTypeAnnotationOnExports14_test.go | 4 ++-- tsc/internal/ls/codeactions_fixmissingtypeannotation.go | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go b/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go index efc4896b3ff63..3c1e3da12d9ca 100644 --- a/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go +++ b/tsc/internal/fourslash/tests/codeFixMissingTypeAnnotationOnExports14_test.go @@ -49,8 +49,8 @@ export const { 0: x, "a\\u0062": y } = foo();` return { 0: 1, "a\\u0062": 1 }; } const dest = foo(); -export const x: number = dest.0; -export const y: number = dest.a\u0062;`, +export const x: number = dest[0]; +export const y: number = dest["a\\u0062"];`, Index: 0, }) } 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 { From 8b8339993701a948b4494562bfd011d657055252 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:43 -0800 Subject: [PATCH 17/53] Add a test for string import names when promoting type-only imports This test records the import fix that promotes a type-only import of a string export name. --- ...odeFixPromoteTypeOnlyOrderingCrash_test.go | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go b/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go index f1c128a58dd33..0320f8df530da 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*/) +} From 3a6fb858dc8bd09cb55629385313d69858511fdf Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:12:23 -0800 Subject: [PATCH 18/53] Preserve string import names when promoting type-only imports Promoting a type-only import specifier rebuilt its imported name as an identifier. An import of a string export name then became an identifier, which is a syntax error or, for names that look like identifier escapes, an import of a different export. --- .../fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go | 2 +- tsc/internal/ls/autoimport/fix.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go b/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go index 0320f8df530da..910876806ce98 100644 --- a/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go +++ b/tsc/internal/fourslash/tests/codeFixPromoteTypeOnlyOrderingCrash_test.go @@ -54,7 +54,7 @@ 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"; + f.VerifyImportFixAtPosition(t, []string{`import { "a\\u0062" as A, b } from "./m"; b; new A();`}, nil /*preferences*/) } diff --git a/tsc/internal/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 16cf51ec38e33..27e9f53c46fe3 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -1134,7 +1134,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 From 6a0824069e09d0cbd8aad8256ff3c56480628238 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:44 -0800 Subject: [PATCH 19/53] Add a test for JSX auto-import names with multi-byte characters This test records that a default export named with a multi-byte first character is missing from JSX tag completions. --- ...sImport_jsxOpeningTagImportDefault_test.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index 3b95ff4724941..0077d9862fd93 100644 --- a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go +++ b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go @@ -59,3 +59,30 @@ 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{ + Excludes: []string{ + "中文", + }, + }, + }) +} From d95d81ba75cd41874bf3ca31bf3d222228cc1526 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:14:21 -0800 Subject: [PATCH 20/53] Decode the first character of JSX auto-import names as a rune JSX auto-import treated the first byte of an export name as a character when checking and applying capitalization. For names starting with a multi-byte character, the capitalized name became invalid UTF-8 and resolving the completion crashed. --- ...sImport_jsxOpeningTagImportDefault_test.go | 23 +++++++++++++++++-- tsc/internal/ls/autoimport/fix.go | 7 +++--- tsc/internal/ls/autoimport/view.go | 3 ++- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index 0077d9862fd93..eb97524437f33 100644 --- a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go +++ b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go @@ -80,9 +80,28 @@ export function Index() { EditRange: Ignored, }, Items: &fourslash.CompletionsExpectedItems{ - Excludes: []string{ - "中文", + 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 <中 +}`), + }) } diff --git a/tsc/internal/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index 27e9f53c46fe3..b7af89dfae91a 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "unicode" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -603,10 +604,10 @@ func (v *View) GetFixes(export *Export, forJSX bool, isValidTypeOnlyUseSite bool addAsTypeOnly := getAddAsTypeOnly(isValidTypeOnlyUseSite, export, v.program.Options()) name := export.Name() - startsWithUpper := unicode.IsUpper(rune(name[0])) - if forJSX && !startsWithUpper { + first, size := utf8.DecodeRuneInString(name) + if forJSX && !unicode.IsUpper(first) { if export.IsRenameable() { - name = fmt.Sprintf("%c%s", unicode.ToUpper(rune(name[0])), name[1:]) + name = string(unicode.ToUpper(first)) + name[size:] } else { return nil } diff --git a/tsc/internal/ls/autoimport/view.go b/tsc/internal/ls/autoimport/view.go index 9a6046c746d53..e210922380167 100644 --- a/tsc/internal/ls/autoimport/view.go +++ b/tsc/internal/ls/autoimport/view.go @@ -3,6 +3,7 @@ package autoimport import ( "slices" "unicode" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/checker" @@ -191,7 +192,7 @@ outer: if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { continue } - if forJSX && !(unicode.IsUpper(rune(name[0])) || e.IsRenameable()) { + if first, _ := utf8.DecodeRuneInString(name); forJSX && !(unicode.IsUpper(first) || e.IsRenameable()) { continue } target := e.ExportID From 055d8f1d636449e94dba1156d8beb98ea38096c3 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:44 -0800 Subject: [PATCH 21/53] Add a test for quotes in import attributes when organizing imports This test records organize imports for two imports whose attributes differ only in where a quoted value ends. --- .../tests/organizeImportsAttributes4_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go index ad800f43a6e64..2b23c19bd30a5 100644 --- a/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go +++ b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go @@ -34,3 +34,21 @@ 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, B } from "./a" with { type: "x\" z:\"y" }; + +export type C = A | B;`, + lsproto.CodeActionKindSourceOrganizeImportsTs, + nil, + ) +} From 80864bdf06d56a0fe01f85605239996968403349 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:15:40 -0800 Subject: [PATCH 22/53] Quote import attributes when grouping imports to organize Organize imports merges declarations whose attributes produce the same key. The key wrote attribute names and values without escaping, so an attribute value containing quotes could collide with a different set of attributes, and imports with different attributes were merged. --- .../fourslash/tests/organizeImportsAttributes4_test.go | 3 ++- tsc/internal/ls/organizeimports.go | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go index 2b23c19bd30a5..0921d584ead01 100644 --- a/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go +++ b/tsc/internal/fourslash/tests/organizeImportsAttributes4_test.go @@ -45,7 +45,8 @@ export type C = A | B;` f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) defer done() f.VerifyOrganizeImports(t, - `import { A, B } from "./a" with { type: "x\" z:\"y" }; + `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, 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()) } From dcd1ebee9ce2740ce58b9e66285e709200a64248 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:45 -0800 Subject: [PATCH 23/53] Add a test for line separators in quoted completion text This test records the element access completion for a property name containing U+2028. --- .../tests/completionFilterText3_test.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tsc/internal/fourslash/tests/completionFilterText3_test.go b/tsc/internal/fourslash/tests/completionFilterText3_test.go index 38f5d894e718d..befaba7116b5c 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, + }, + }, + }, + }, + }, + }) +} From 02e3a5c27d744e8275ea47b0aa09a199262135fd Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:17:15 -0800 Subject: [PATCH 24/53] Escape line separators in quoted completion text Completions that quote a name, such as element access completions for non-identifier properties, left U+2028 and U+2029 raw inside the string literal. The characters are invisible in source and end a string literal in engines before ES2019, which emit can target. --- tsc/internal/fourslash/tests/completionFilterText3_test.go | 4 ++-- tsc/internal/ls/utilities.go | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/tsc/internal/fourslash/tests/completionFilterText3_test.go b/tsc/internal/fourslash/tests/completionFilterText3_test.go index befaba7116b5c..b1e4a15e52f16 100644 --- a/tsc/internal/fourslash/tests/completionFilterText3_test.go +++ b/tsc/internal/fourslash/tests/completionFilterText3_test.go @@ -167,10 +167,10 @@ func TestCompletionPropertyAccessLineSeparator(t *testing.T) { Includes: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ Label: "a\u2028b", - InsertText: new("[\"a\u2028b\"]"), + InsertText: new(`["a\u2028b"]`), TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ TextEdit: &lsproto.TextEdit{ - NewText: "[\"a\u2028b\"]", + NewText: `["a\u2028b"]`, Range: f.Ranges()[0].LSRange, }, }, diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index fca86ea0ac5ee..afee6b18a9c16 100644 --- a/tsc/internal/ls/utilities.go +++ b/tsc/internal/ls/utilities.go @@ -25,6 +25,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*/) @@ -314,7 +318,7 @@ func quote(file *ast.SourceFile, preferences lsutil.UserPreferences, text string quotePreference := lsutil.GetQuotePreference(file, preferences) quoted := `"` + mapLoneSurrogates(text, func(s string) string { quoted, _ := core.StringifyJson(s, "" /*prefix*/, "" /*indent*/) - return stringutil.StripQuotes(quoted) + return lineSeparatorReplacer.Replace(stringutil.StripQuotes(quoted)) }) + `"` if quotePreference == lsutil.QuotePreferenceSingle { quoted = "'" + quoteReplacer.Replace(stringutil.StripQuotes(quoted)) + "'" From 982acfdb3c082c399d887b82be45d351efcca104 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:45 -0800 Subject: [PATCH 25/53] Add tests for non-identifier names in aliased rename edits These tests record renames to a-b with prefix and suffix text enabled, where the rename keeps local names by adding aliases. Rename baselines pass RENAME_PLACEHOLDER as the new name. It is an identifier, so those baselines don't depend on how renames to non-identifier names are written. --- tsc/internal/fourslash/fourslash.go | 10 +++-- .../fourslash/tests/renameEscaping_test.go | 44 +++++++++++++++++++ .../state/declarationMapsRename.baseline | 2 +- ...ionMapsRenameStartingAtDefinition.baseline | 2 +- ...ationMapsRenameTargetDoesNotExist.baseline | 2 +- ...eSourceOfProjectReferenceRedirect.baseline | 2 +- ...rceOfProjectReferenceRedirectEdit.baseline | 4 +- ...OfProjectReferenceRedirectEditEnd.baseline | 4 +- ...onMapsRenameWithProjectReferences.baseline | 2 +- ...psRenameWithProjectReferencesEdit.baseline | 4 +- ...enameWithProjectReferencesEditEnd.baseline | 4 +- ...clarationMapsRenameWithSourceMaps.baseline | 2 +- ...ationMapsRenameWithSourceMapsEdit.baseline | 4 +- ...onMapsRenameWithSourceMapsEditEnd.baseline | 4 +- ...psRenameWithSourceMapsNotSolution.baseline | 2 +- ...nameWithSourceMapsNotSolutionEdit.baseline | 4 +- ...eWithSourceMapsNotSolutionEditEnd.baseline | 4 +- ...renameAncestorProjectRefMangement.baseline | 2 +- .../state/renameInCommonFile.baseline | 2 +- 19 files changed, 76 insertions(+), 28 deletions(-) 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/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index af699b2f73190..961c390cfab42 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -3,7 +3,9 @@ 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" ) @@ -45,3 +47,45 @@ export { foo as "/*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 } from "./a"; +a-b; +const o2 = { foo: a-b }; +export { a-b as 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;`, + }) +} 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" } } From 36065c8eeaee1111d624bdbde2496582c9f1fc39 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:35:51 -0800 Subject: [PATCH 26/53] Quote non-identifier names in aliased rename edits When a rename adds an alias to keep a local name, the new name lands in an export name or property name slot. A new name that is not an identifier, such as `a-b`, produced `export { foo as a-b }` and `const { a-b: x } = o`, which do not parse. These slots accept string literals, so quote the new name there. An `import { foo }` cannot bind a non-identifier local at all, so it becomes `import { "a-b" as foo }` and uses of the local `foo` keep their name. --- .../fourslash/tests/renameEscaping_test.go | 18 ++--- tsc/internal/ls/rename.go | 75 ++++++++++++++++--- 2 files changed, 72 insertions(+), 21 deletions(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 961c390cfab42..2889084140b28 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -71,21 +71,21 @@ bar;` 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 }; +export { foo as "a-b" }; const o = { "x": 1 }; const { x } = o;`, - "/b.ts": `import { a-b } from "./a"; -a-b; -const o2 = { foo: a-b }; -export { a-b as foo };`, - "/c.ts": `export { a-b as foo } from "./a";`, - "/d.ts": `import { a-b as bar } from "./a"; + "/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 }; +export { foo as "a-b" }; const o = { "c-d": 1 }; -const { c-d: x } = o;`, +const { "c-d": x } = o;`, }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 745e971ddc818..c8d3c5c54e41f 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -112,13 +112,30 @@ 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) @@ -382,6 +399,7 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere kind := entry.kind parent := node.Parent name := originalNode.Text() + propertyText := quoteNonIdentifierName(newText, quotePreference) isShorthandAssignment := ast.IsShorthandPropertyAssignment(parent) switch { case isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.Name() == node && parent.AsBindingElement().DotDotDotToken == nil): @@ -389,7 +407,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. @@ -398,27 +416,24 @@ 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 + return name + " as " + propertyText } - return newText + " as " + name + return propertyText + " as " + name } } @@ -439,9 +454,45 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere return string(quoteChar) + escapeStringForNode(newText, quoteChar, entry.node) + string(quoteChar) } + if entry.kind != entryKindRange && ast.IsIdentifier(entry.node) && isModuleExportNameOfSpecifier(entry.node) { + return quoteNonIdentifierName(newText, quotePreference) + } + return newText } +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 + } + return false +} + +func quoteNonIdentifierName(name string, quotePreference lsutil.QuotePreference) string { + if scanner.IsIdentifierText(name, core.LanguageVariantStandard) { + return name + } + quoteChar := getQuoteFromPreference(quotePreference) + return string(quoteChar) + printer.EscapeString(name, quoteChar) + string(quoteChar) +} + func escapeStringForNode(s string, quoteChar printer.QuoteChar, node *ast.Node) string { if node.Flags&ast.NodeFlagsJSDoc != 0 { return lsutil.EscapeStringInComment(s, quoteChar) From 68bfda6151c4eb50fa9be432f37d9d8856900046 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:45 -0800 Subject: [PATCH 27/53] Add a test for string export names in declaration emit This test records declaration emit for types reachable only through exports with string literal names. --- .../declarationEmitNonIdentifierExportName.js | 86 +++++++++++++++++++ ...arationEmitNonIdentifierExportName.symbols | 45 ++++++++++ ...clarationEmitNonIdentifierExportName.types | 43 ++++++++++ .../declarationEmitNonIdentifierExportName.ts | 18 ++++ 4 files changed, 192 insertions(+) create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types create mode 100644 tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportName.ts diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js new file mode 100644 index 0000000000000..239915f304622 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js @@ -0,0 +1,86 @@ +//// [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; +//// [main.d.ts] +export declare const v: import("./dep").a b; +export declare const w: import("./dep").a c; + + +//// [DtsFileErrors] + + +main.d.ts(1,41): error TS2694: Namespace '"dep"' has no exported member 'a'. +main.d.ts(1,43): error TS1005: ',' expected. +main.d.ts(1,43): error TS7005: Variable 'b' implicitly has an 'any' type. +main.d.ts(2,41): error TS2694: Namespace '"dep"' has no exported member 'a'. +main.d.ts(2,43): error TS1005: ',' expected. +main.d.ts(2,43): error TS7005: Variable 'c' implicitly has an 'any' type. + + +==== dep.d.ts (0 errors) ==== + interface A { + x: number; + } + interface C { + y: number; + } + export { A as "a b", C as "a c", C as Ok }; + +==== mid.d.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.d.ts (6 errors) ==== + export declare const v: import("./dep").a b; + ~ +!!! error TS2694: Namespace '"dep"' has no exported member 'a'. + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS7005: Variable 'b' implicitly has an 'any' type. + export declare const w: import("./dep").a c; + ~ +!!! error TS2694: Namespace '"dep"' has no exported member 'a'. + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS7005: Variable 'c' implicitly has an 'any' type. + \ No newline at end of file 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..8974a04438007 --- /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 : () => import("./dep.js").a b +>g : () => import("./dep.js").a c + +export const v = f(); +>v : import("./dep").a b +>f() : import("./dep").a b +>f : () => import("./dep").a b + +export const w = g(); +>w : import("./dep").a c +>g() : import("./dep").a c +>g : () => import("./dep").a c + 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(); From 11b5d4c88c09e73bdfe504bfbca46c50d5f34cb7 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:47:20 -0800 Subject: [PATCH 28/53] Skip string export names when naming types through import types A type reachable only through an export with a string literal name, such as `export { A as "a b" }`, was printed as `import("./dep").a b`, which does not parse. Declaration emit wrote it out as is, and code fixes inserted it into user files. Import type qualifiers must be identifiers, so these exports cannot be used to name the type. When the module has another export of the same type with an identifier name, that name is used; otherwise the type is not nameable from outside the module, and declaration emit reports the usual error. --- tsc/internal/checker/symbolaccessibility.go | 14 ++++-- ...ClassImplementInterfaceMappedType2_test.go | 2 +- ...tionEmitNonIdentifierExportName.errors.txt | 20 ++++++++ .../declarationEmitNonIdentifierExportName.js | 46 ------------------- ...clarationEmitNonIdentifierExportName.types | 16 +++---- 5 files changed, 40 insertions(+), 58 deletions(-) create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.errors.txt diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 204062db49de0..9312921210391 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 { @@ -401,6 +402,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 +424,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) } } diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index f580d4fd9eeaf..f40ccacdd299f 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -48,7 +48,7 @@ class C implements I {}` Description: "Implement interface 'I'", NewFileContent: `import { I } from "dep"; class C implements I { - "c\\u0064": a\u0062; + "c\\u0064": Hidden; }`, Index: 0, }) 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 index 239915f304622..7d9d17b5db5c7 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.js @@ -38,49 +38,3 @@ export { A as "a b", C as "a c", C as Ok }; import { "a b" as B, "a c" as C } from "./dep"; export declare function f(): B; export declare function g(): C; -//// [main.d.ts] -export declare const v: import("./dep").a b; -export declare const w: import("./dep").a c; - - -//// [DtsFileErrors] - - -main.d.ts(1,41): error TS2694: Namespace '"dep"' has no exported member 'a'. -main.d.ts(1,43): error TS1005: ',' expected. -main.d.ts(1,43): error TS7005: Variable 'b' implicitly has an 'any' type. -main.d.ts(2,41): error TS2694: Namespace '"dep"' has no exported member 'a'. -main.d.ts(2,43): error TS1005: ',' expected. -main.d.ts(2,43): error TS7005: Variable 'c' implicitly has an 'any' type. - - -==== dep.d.ts (0 errors) ==== - interface A { - x: number; - } - interface C { - y: number; - } - export { A as "a b", C as "a c", C as Ok }; - -==== mid.d.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.d.ts (6 errors) ==== - export declare const v: import("./dep").a b; - ~ -!!! error TS2694: Namespace '"dep"' has no exported member 'a'. - ~ -!!! error TS1005: ',' expected. - ~ -!!! error TS7005: Variable 'b' implicitly has an 'any' type. - export declare const w: import("./dep").a c; - ~ -!!! error TS2694: Namespace '"dep"' has no exported member 'a'. - ~ -!!! error TS1005: ',' expected. - ~ -!!! error TS7005: Variable 'c' implicitly has an 'any' type. - \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types index 8974a04438007..f70a07e37cc75 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportName.types @@ -28,16 +28,16 @@ export declare function g(): C; === main.ts === import { f, g } from "./mid"; ->f : () => import("./dep.js").a b ->g : () => import("./dep.js").a c +>f : () => A +>g : () => import("./dep.js").Ok export const v = f(); ->v : import("./dep").a b ->f() : import("./dep").a b ->f : () => import("./dep").a b +>v : A +>f() : A +>f : () => A export const w = g(); ->w : import("./dep").a c ->g() : import("./dep").a c ->g : () => import("./dep").a c +>w : import("./dep").Ok +>g() : import("./dep").Ok +>g : () => import("./dep").Ok From 2e524bd9de4f827b0cf48abc1eef7dd05bdf5b41 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:48:04 -0800 Subject: [PATCH 29/53] Add a test for JSON escapes in tsconfig rename edits This test records the tsconfig edit for a directory renamed to a name containing a vertical tab. --- ...ditsForFileRename_escapedSpecifier_test.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 76fa3eb3b325f..02832519ab7ff 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -53,6 +53,31 @@ export default 0;`, }, 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\vt/b.ts"] }`, + }, nil /*preferences*/) +} + func TestGetEditsForFileRename_jsDocCommentTerminator(t *testing.T) { t.Parallel() defer testutil.RecoverAndFail(t, "Panic on fourslash test") From ed44555181cc80e7acdd42747846e2c7d76b8cc9 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:49:05 -0800 Subject: [PATCH 30/53] Use JSON escapes in tsconfig rename edits Config files are JSON, and JavaScript string escapes such as \v or \x00 are invalid there. Renaming a file to a name with such a character wrote a tsconfig.json that no longer parses. --- ...ditsForFileRename_escapedSpecifier_test.go | 2 +- tsc/internal/ls/file_rename.go | 2 +- tsc/internal/ls/utilities.go | 21 +++++++++++++------ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 02832519ab7ff..1698528ea7e93 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -74,7 +74,7 @@ export default 0;` "import b1 from \"./v\\vt/b\";\n" + "import b2 from './v\\vt/b';\n" + "export default 0;", - "/tsconfig.json": `{ "files": ["a.ts", "v\vt/b.ts"] }`, + "/tsconfig.json": `{ "files": ["a.ts", "v\u000bt/b.ts"] }`, }, nil /*preferences*/) } diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index b0d77673ad7cc..a44a11060f32e 100644 --- a/tsc/internal/ls/file_rename.go +++ b/tsc/internal/ls/file_rename.go @@ -199,7 +199,7 @@ 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") - newText := printer.EscapeString(relativePathFromDirectory(configDir, updated, caseSensitivity).AsString(), getStringLiteralQuoteChar(configFile, element)) + newText := escapeJSONString(relativePathFromDirectory(configDir, updated, caseSensitivity).AsString(), getStringLiteralQuoteChar(configFile, element)) changeTracker.ReplaceRangeWithText(configFile, lspRange, newText) return true } diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go index afee6b18a9c16..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" @@ -315,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 lineSeparatorReplacer.Replace(stringutil.StripQuotes(quoted)) - }) + `"` - if quotePreference == lsutil.QuotePreferenceSingle { - quoted = "'" + quoteReplacer.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 From b0a7fc26ee8b5caeb6bed0f113789e828a75d77c Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:49:25 -0800 Subject: [PATCH 31/53] Add a test for reference paths containing a quote A reference directive path has no escape syntax, so a path containing the directive's own quote is skipped during file rename edits. The other quote character could still delimit such a path. --- ...ditsForFileRename_escapedSpecifier_test.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 1698528ea7e93..1b5bbfb83f4b7 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -95,3 +95,28 @@ const x = null;` 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*/) +} From 465e41095eabb089c6bdc010d444792aad50603a Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:17 -0800 Subject: [PATCH 32/53] Switch quotes for reference paths containing a quote A file renamed to a name with a quote left every reference directive delimited by that quote pointing at the old path. When the path does not contain the other quote character, it can still be written by switching the directive to that quote. --- ...ditsForFileRename_escapedSpecifier_test.go | 2 +- tsc/internal/ls/file_rename.go | 31 ++++++++++++++----- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go index 1b5bbfb83f4b7..6098bf47a6f59 100644 --- a/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go +++ b/tsc/internal/fourslash/tests/getEditsForFileRename_escapedSpecifier_test.go @@ -112,7 +112,7 @@ export default 0;` f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) defer done() f.VerifyWillRenameFilesEdits(t, "/old", "/n\"ew", map[string]string{ - "/a.ts": `/// + "/a.ts": `/// /// import b1 from "./n\"ew/b"; import b2 from './n"ew/b'; diff --git a/tsc/internal/ls/file_rename.go b/tsc/internal/ls/file_rename.go index a44a11060f32e..ff9c2a1251783 100644 --- a/tsc/internal/ls/file_rename.go +++ b/tsc/internal/ls/file_rename.go @@ -239,8 +239,10 @@ func (l *LanguageService) updateImportsForFileRename(program *compiler.Program, continue } updated := l.updateRelativePath(oldToNew, oldFileName, newImportFromPath, tspath.ToModuleSpecifier(ref.FileName)) - if updated.AsString() != ref.FileName && canWriteReferencePath(sourceFile, ref, updated.AsString()) { - changeTracker.ReplaceTextRangeWithText(sourceFile, ref.TextRange, updated.AsString()) + if updated.AsString() != ref.FileName { + if textRange, newText, ok := getReferencePathEdit(sourceFile, ref, updated.AsString()); ok { + changeTracker.ReplaceTextRangeWithText(sourceFile, textRange, newText) + } } } @@ -380,11 +382,26 @@ func getStringLiteralQuoteChar(sourceFile *ast.SourceFile, node *ast.LiteralLike } } -// Reference directive paths have no escape syntax, so a path containing the -// directive's quote or a line terminator cannot be written into the comment. -func canWriteReferencePath(sourceFile *ast.SourceFile, ref *ast.FileReference, path string) bool { - quote := sourceFile.Text()[ref.Pos()-1] - return !strings.ContainsAny(path, string(quote)+"\r\n\u2028\u2029") +// 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 { From 432607cf6f2bad6061132c127b20d3586e582694 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:51:03 -0800 Subject: [PATCH 33/53] Add a test for JSX auto-import of non-ASCII component names JSX treats a tag name as intrinsic only when it starts with an ASCII lowercase letter or contains a hyphen. Auto-import instead requires an uppercase first character, so a component named with a non-ASCII lowercase letter is never offered. --- ...sImport_jsxOpeningTagImportDefault_test.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index eb97524437f33..99a98be7cd19a 100644 --- a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go +++ b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go @@ -105,3 +105,30 @@ export function Index() { }`), }) } + +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{ + Excludes: []string{ + "éclair", + }, + }, + }) +} From 725e17d1c3f1f83366aca3d4586720bdf36bc851 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:52:24 -0800 Subject: [PATCH 34/53] Use JSX intrinsic tag rules for auto-import names Auto-import should skip or capitalize an export name for a JSX tag only when JSX would read that name as an intrinsic element. Checking for an uppercase first character also rejected names starting with a non-ASCII lowercase letter, which JSX treats as components. --- ...sImport_jsxOpeningTagImportDefault_test.go | 23 +++++++++++++++++-- tsc/internal/ls/autoimport/fix.go | 7 ++---- tsc/internal/ls/autoimport/view.go | 4 +--- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go index 99a98be7cd19a..d6c7e1eb97320 100644 --- a/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go +++ b/tsc/internal/fourslash/tests/completionsImport_jsxOpeningTagImportDefault_test.go @@ -126,9 +126,28 @@ export function Index() { EditRange: Ignored, }, Items: &fourslash.CompletionsExpectedItems{ - Excludes: []string{ - "éclair", + 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/ls/autoimport/fix.go b/tsc/internal/ls/autoimport/fix.go index b7af89dfae91a..82b6c65ad689d 100644 --- a/tsc/internal/ls/autoimport/fix.go +++ b/tsc/internal/ls/autoimport/fix.go @@ -6,8 +6,6 @@ import ( "fmt" "slices" "strings" - "unicode" - "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -604,10 +602,9 @@ func (v *View) GetFixes(export *Export, forJSX bool, isValidTypeOnlyUseSite bool addAsTypeOnly := getAddAsTypeOnly(isValidTypeOnlyUseSite, export, v.program.Options()) name := export.Name() - first, size := utf8.DecodeRuneInString(name) - if forJSX && !unicode.IsUpper(first) { + if forJSX && scanner.IsIntrinsicJsxName(name) { if export.IsRenameable() { - name = string(unicode.ToUpper(first)) + name[size:] + name = strings.ToUpper(name[:1]) + name[1:] } else { return nil } diff --git a/tsc/internal/ls/autoimport/view.go b/tsc/internal/ls/autoimport/view.go index e210922380167..fc7cd71962449 100644 --- a/tsc/internal/ls/autoimport/view.go +++ b/tsc/internal/ls/autoimport/view.go @@ -2,8 +2,6 @@ package autoimport import ( "slices" - "unicode" - "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/checker" @@ -192,7 +190,7 @@ outer: if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { continue } - if first, _ := utf8.DecodeRuneInString(name); forJSX && !(unicode.IsUpper(first) || e.IsRenameable()) { + if forJSX && scanner.IsIntrinsicJsxName(name) && !e.IsRenameable() { continue } target := e.ExportID From 189cf98a15b009726919a0b2565267fea1d65ae1 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:57:18 -0800 Subject: [PATCH 35/53] Add a test for comment terminators in nested JSDoc @param names A property name containing */ in a nested destructuring pattern is still copied into the generated @param tags, where it ends the comment. --- .../tests/basicJSDocCompletions_test.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index 5dc933abf97c5..d3e83ae3251d4 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -135,7 +135,11 @@ function f(a = "*/", b = { "*/": 1 }) {} /** * @/*2*/ */ -function g({ "*/": c }) {}` +function g({ "*/": c }) {} +/** + * @/*3*/ + */ +function h({ "*/": { x } }) {}` f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) defer done() f.VerifyCompletions(t, "1", &fourslash.CompletionsExpectedList{ @@ -161,4 +165,15 @@ function g({ "*/": c }) {}` }, }, }) + f.VerifyCompletions(t, "3", &fourslash.CompletionsExpectedList{ + IsIncomplete: false, + ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{ + CommitCharacters: &DefaultCommitCharacters, + }, + Items: &fourslash.CompletionsExpectedItems{ + Includes: []fourslash.CompletionsExpectedItem{ + "param {object} param0 \n* @param {object} param0.*/ \n* @param {*} param0.*/.x ", + }, + }, + }) } From 2bcbf1b0aeabcf98005320b2e687857a3ee32e58 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:58:23 -0800 Subject: [PATCH 36/53] Omit unsafe nested property names from JSDoc @param completions Property names in nested destructuring patterns are copied into the generated @param tags the same way as top-level ones, so a name containing */ or a line break ends the comment or the tag early. --- tsc/internal/fourslash/tests/basicJSDocCompletions_test.go | 2 +- tsc/internal/ls/completions.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index d3e83ae3251d4..6c6343dfd93fe 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -172,7 +172,7 @@ function h({ "*/": { x } }) {}` }, Items: &fourslash.CompletionsExpectedItems{ Includes: []fourslash.CompletionsExpectedItem{ - "param {object} param0 \n* @param {object} param0.*/ \n* @param {*} param0.*/.x ", + "param {*} param0 ", }, }, }) diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index f16c9562fc26f..e5b82ec28be7c 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -6552,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( From 5444ad147a08d8ac31cc43bcae6b12f4304f5ecd Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:59:32 -0800 Subject: [PATCH 37/53] Add a test for string export names in re-exporting modules A module that re-exports a type only under a string literal name can still be chosen as the module an import type refers to, which prints the string name as the import type qualifier. --- ...rationEmitNonIdentifierExportNameBarrel.js | 55 +++++++++++++++++++ ...nEmitNonIdentifierExportNameBarrel.symbols | 32 +++++++++++ ...ionEmitNonIdentifierExportNameBarrel.types | 31 +++++++++++ ...rationEmitNonIdentifierExportNameBarrel.ts | 18 ++++++ 4 files changed, 136 insertions(+) create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types create mode 100644 tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameBarrel.ts diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js new file mode 100644 index 0000000000000..8079687a74993 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js @@ -0,0 +1,55 @@ +//// [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").a b; + + +//// [DtsFileErrors] + + +main.d.ts(1,39): error TS2694: Namespace '"node_modules/dep/index"' has no exported member 'a'. +main.d.ts(1,41): error TS1005: ',' expected. +main.d.ts(1,41): error TS7005: Variable 'b' implicitly has an 'any' type. + + +==== node_modules/dep/src/internal/a.d.ts (0 errors) ==== + interface A { x: number } + export { A as Ok }; + +==== node_modules/dep/index.d.ts (0 errors) ==== + export { Ok as "a b" } from "./src/internal/a"; + +==== node_modules/mid/index.d.ts (0 errors) ==== + import { Ok } from "dep/src/internal/a"; + export declare function f(): Ok; + +==== main.d.ts (3 errors) ==== + export declare const v: import("dep").a b; + ~ +!!! error TS2694: Namespace '"node_modules/dep/index"' has no exported member 'a'. + ~ +!!! error TS1005: ',' expected. + ~ +!!! error TS7005: Variable 'b' implicitly has an 'any' type. + \ No newline at end of file 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..101e1da0e1ea3 --- /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").a b + +export const v = f(); +>v : import("dep").a b +>f() : import("dep").a b +>f : () => import("dep").a b + 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(); From dc316a1b2166a78505089c85567a9281a64733cc Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:05:32 -0800 Subject: [PATCH 38/53] Skip string export names when indexing module containers Import type qualifiers must be identifiers, so a module exporting a type only under a string literal name cannot be used to name it. The container index used to find re-exporting modules included such modules, and one could be chosen over a module with a usable name. --- tsc/internal/checker/symbolaccessibility.go | 6 ++-- ...rationEmitNonIdentifierExportNameBarrel.js | 32 +------------------ ...ionEmitNonIdentifierExportNameBarrel.types | 8 ++--- 3 files changed, 9 insertions(+), 37 deletions(-) diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 9312921210391..2420d6b90a4b3 100644 --- a/tsc/internal/checker/symbolaccessibility.go +++ b/tsc/internal/checker/symbolaccessibility.go @@ -263,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) diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js index 8079687a74993..3fa53652dc570 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.js @@ -22,34 +22,4 @@ export const v = f(); //// [main.d.ts] -export declare const v: import("dep").a b; - - -//// [DtsFileErrors] - - -main.d.ts(1,39): error TS2694: Namespace '"node_modules/dep/index"' has no exported member 'a'. -main.d.ts(1,41): error TS1005: ',' expected. -main.d.ts(1,41): error TS7005: Variable 'b' implicitly has an 'any' type. - - -==== node_modules/dep/src/internal/a.d.ts (0 errors) ==== - interface A { x: number } - export { A as Ok }; - -==== node_modules/dep/index.d.ts (0 errors) ==== - export { Ok as "a b" } from "./src/internal/a"; - -==== node_modules/mid/index.d.ts (0 errors) ==== - import { Ok } from "dep/src/internal/a"; - export declare function f(): Ok; - -==== main.d.ts (3 errors) ==== - export declare const v: import("dep").a b; - ~ -!!! error TS2694: Namespace '"node_modules/dep/index"' has no exported member 'a'. - ~ -!!! error TS1005: ',' expected. - ~ -!!! error TS7005: Variable 'b' implicitly has an 'any' type. - \ No newline at end of file +export declare const v: import("dep/src/internal/a").Ok; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types index 101e1da0e1ea3..a745ccaffd1de 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameBarrel.types @@ -22,10 +22,10 @@ export declare function f(): Ok; === main.ts === import { f } from "mid"; ->f : () => import("dep").a b +>f : () => import("dep/src/internal/a.js").Ok export const v = f(); ->v : import("dep").a b ->f() : import("dep").a b ->f : () => import("dep").a b +>v : import("dep/src/internal/a").Ok +>f() : import("dep/src/internal/a").Ok +>f : () => import("dep/src/internal/a").Ok From 94f528cf2eb72d483edb7376e5a2c3a860f44f47 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:08:03 -0800 Subject: [PATCH 39/53] Quote numeric property names renamed to non-identifiers Renaming a numeric property such as 0 in { 0: x } wrote the new name unquoted, so a name that is not an identifier produced invalid code. Element accesses of the property were already quoted. --- tsc/internal/fourslash/tests/renameEscaping_test.go | 2 +- tsc/internal/ls/rename.go | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 2889084140b28..255a622ceb195 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -29,7 +29,7 @@ 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" + + "/b.ts": "const foo = { \"a\\\"b\": true };\n" + "foo[\"a\\\"b\"];\n", }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index c8d3c5c54e41f..2a7e78bceacb0 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -454,6 +454,11 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere 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) + } + if entry.kind != entryKindRange && ast.IsIdentifier(entry.node) && isModuleExportNameOfSpecifier(entry.node) { return quoteNonIdentifierName(newText, quotePreference) } From 484ee12c180d4dbbaec8a3bc29531ad1e769eec9 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:12:12 -0800 Subject: [PATCH 40/53] Add a test for alias renames of string-named re-exports Renaming the export behind export { "a b" } from "m" with prefix and suffix text enabled writes the alias clause inside the string literal, which changes the exported name and drops the original one. --- .../fourslash/tests/renameEscaping_test.go | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 255a622ceb195..1e44cb964d730 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -89,3 +89,29 @@ 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";`, + }) +} From c6ae0579e440d84bbbda4b36495045103512fe34 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:12:18 -0800 Subject: [PATCH 41/53] Quote both names when aliasing string-named re-exports In export { "a b" } from "m", the rename edit covers only the contents of the string literal. Adding an alias clause there put the whole clause inside one literal, so each name has to be written as its own literal within that range. --- .../fourslash/tests/renameEscaping_test.go | 4 ++-- tsc/internal/ls/rename.go | 20 ++++++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 1e44cb964d730..cd73fecd6bec0 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -109,9 +109,9 @@ export { "/*2*/d e" } from "./c";` 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";`, + "/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";`, + "/d.ts": `export { "d e" as "f" } from "./c";`, }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 2a7e78bceacb0..14d11e4e83a72 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -430,7 +430,25 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere 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) { + 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] + } + if usePrefix { return name + " as " + propertyText } return propertyText + " as " + name From 749a411b754a7c61d1060d45478f71122edcf915 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:13:05 -0800 Subject: [PATCH 42/53] Add a test for renaming string literals in JSX attributes JSX attribute strings have no backslash escapes, so the escapes added when renaming a string literal reference inside one change its value, and an escaped quote ends the attribute early. --- .../fourslash/tests/renameEscaping_test.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index cd73fecd6bec0..a6555438494b0 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -115,3 +115,22 @@ export { x as "c" };`, "/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"; +; +;`, + }) +} From fe6956fd9275d2ace5911a0bd4eddc50ec0ec36a Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:14:21 -0800 Subject: [PATCH 43/53] Write renamed JSX attribute strings without escapes JSX attribute strings are taken literally, so a renamed string literal reference inside one has to be written as raw text. When the attribute's quote cannot contain the new name, the other quote or an expression container is used instead. --- .../fourslash/tests/renameEscaping_test.go | 4 +-- tsc/internal/ls/rename.go | 27 ++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index a6555438494b0..db771fedb5ad4 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -130,7 +130,7 @@ const k: "foo" | "bar" = "/*1*/foo"; 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"; -; -;`, +; +;`, }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 14d11e4e83a72..44fa85c9faaf1 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -142,15 +142,24 @@ func (l *LanguageService) symbolAndEntriesToRename(ctx context.Context, params * 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}) } @@ -165,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 From c5a5d776d958894e213ae080916519dee1a8161c Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:14:43 -0800 Subject: [PATCH 44/53] Add a test for quoted names in renamed JSDoc imports Renaming an export to a name that is not an identifier quotes the name in import specifiers, and specifiers in a JSDoc @import tag are inside a comment that a */ in the name ends. --- .../fourslash/tests/renameEscaping_test.go | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index db771fedb5ad4..1bb4b19cce4f6 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -134,3 +134,25 @@ 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;`, + }) +} From 321a27ac4102d8811d0add441d793cd9c3ec63dd Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:15:26 -0800 Subject: [PATCH 45/53] Escape comment terminators in names quoted by JSDoc import renames A name quoted in a JSDoc @import specifier during rename is written inside a comment, so a */ in the name has to be escaped there the same way as in other string literals renamed within JSDoc. --- tsc/internal/fourslash/tests/renameEscaping_test.go | 2 +- tsc/internal/ls/rename.go | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index 1bb4b19cce4f6..d6e67a937af3f 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -151,7 +151,7 @@ let x;` 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" */ + "/b.js": `/** @import { "a*\/b" as Foo } from "./a" */ /** @type {Foo} */ let x;`, }) diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 44fa85c9faaf1..0a3b9e27bcea7 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -424,7 +424,7 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere kind := entry.kind parent := node.Parent name := originalNode.Text() - propertyText := quoteNonIdentifierName(newText, quotePreference) + propertyText := quoteNonIdentifierName(newText, quotePreference, entry.node) isShorthandAssignment := ast.IsShorthandPropertyAssignment(parent) switch { case isShorthandAssignment || (isObjectBindingElementWithoutPropertyName(parent) && parent.Name() == node && parent.AsBindingElement().DotDotDotToken == nil): @@ -499,11 +499,11 @@ func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *Refere // 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) + return quoteNonIdentifierName(newText, quotePreference, entry.node) } if entry.kind != entryKindRange && ast.IsIdentifier(entry.node) && isModuleExportNameOfSpecifier(entry.node) { - return quoteNonIdentifierName(newText, quotePreference) + return quoteNonIdentifierName(newText, quotePreference, entry.node) } return newText @@ -533,12 +533,12 @@ func isModuleExportNameOfSpecifier(node *ast.Node) bool { return false } -func quoteNonIdentifierName(name string, quotePreference lsutil.QuotePreference) string { +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) + printer.EscapeString(name, quoteChar) + string(quoteChar) + return string(quoteChar) + escapeStringForNode(name, quoteChar, node) + string(quoteChar) } func escapeStringForNode(s string, quoteChar printer.QuoteChar, node *ast.Node) string { From ffb21edb75e88fe7ec789dc0e6a8f7e07e16d430 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:19:16 -0800 Subject: [PATCH 46/53] Add a test for comment terminators in JSDoc string completions A property name containing "*/" completed inside a JSDoc type closes the comment early, leaving the rest of the name as source code. --- .../tests/basicJSDocCompletions_test.go | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index 6c6343dfd93fe..0fd7db9b200e0 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" ) @@ -177,3 +178,39 @@ function h({ "*/": { x } }) {}` }, }) } + +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)), + TextEdit: &lsproto.TextEditOrInsertReplaceEdit{ + TextEdit: &lsproto.TextEdit{ + NewText: "a*/b", + Range: f.Ranges()[0].LSRange, + }, + }, + }, + }, + }, + }) +} From 7ffa8ada879b773dacb5998d2400561d8c808c2e Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:20:17 -0800 Subject: [PATCH 47/53] Escape comment terminators in JSDoc string completions A string completion inside a JSDoc comment is written into the comment text, so an unescaped "*/" in the completed name ends the comment and turns the rest of the name into source code. --- .../fourslash/tests/basicJSDocCompletions_test.go | 9 +++++---- tsc/internal/ls/completions.go | 2 +- tsc/internal/ls/string_completions.go | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go index 0fd7db9b200e0..4706fb6204e42 100644 --- a/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go +++ b/tsc/internal/fourslash/tests/basicJSDocCompletions_test.go @@ -200,12 +200,13 @@ let a;` Items: &fourslash.CompletionsExpectedItems{ Exact: []fourslash.CompletionsExpectedItem{ &lsproto.CompletionItem{ - Label: "a*/b", - Kind: new(lsproto.CompletionItemKindField), - SortText: new(string(ls.SortTextLocationPriority)), + 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", + NewText: `a*\/b`, Range: f.Ranges()[0].LSRange, }, }, diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go index e5b82ec28be7c..1da67d6d881ff 100644 --- a/tsc/internal/ls/completions.go +++ b/tsc/internal/ls/completions.go @@ -2215,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 } 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. From 8bf3ea31b266efc1901a01cea6395419234b133d Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:22:10 -0800 Subject: [PATCH 48/53] Name unique-symbol mapped members with computed names A mapped property keyed by a unique symbol has an internal symbol name that is not usable in source. Writing that name as a string member declares an unrelated property, so the class still fails to implement the interface; the member needs a computed name referencing the symbol. --- ...ClassImplementInterfaceMappedType2_test.go | 19 +++++++++++++++++++ .../ls/codeactions_missingmemberfixer.go | 7 +++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index f40ccacdd299f..74a4f2e1c0aeb 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -53,3 +53,22 @@ class C implements I { 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, + }) +} diff --git a/tsc/internal/ls/codeactions_missingmemberfixer.go b/tsc/internal/ls/codeactions_missingmemberfixer.go index 5d98517f9c4f6..598e8ba0732f5 100644 --- a/tsc/internal/ls/codeactions_missingmemberfixer.go +++ b/tsc/internal/ls/codeactions_missingmemberfixer.go @@ -62,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, quotePreference) + declarationName := createDeclarationName(f.changeTracker.NodeFactory, f.typeChecker, symbol, declaration, enclosingDeclaration, quotePreference) modifiers := f.createModifiers(symbol, declaration) flags := nodebuilder.FlagsNoTruncation @@ -487,9 +487,12 @@ 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, quotePreference lsutil.QuotePreference) *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) { name := checker.GetPropertyNameFromType(nameType) if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { From a0ebe18ecca56cbedf7d932fb197ab2c941b944d Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:38:16 -0800 Subject: [PATCH 49/53] Add a test for string export names through namespace imports Declaration emit reaching a type through a namespace import can pick an export with a string literal name, producing a qualified name such as `dep."a b"` that does not parse. --- ...tNonIdentifierExportNameNamespaceImport.js | 88 +++++++++++++++++++ ...dentifierExportNameNamespaceImport.symbols | 54 ++++++++++++ ...nIdentifierExportNameNamespaceImport.types | 52 +++++++++++ ...tNonIdentifierExportNameNamespaceImport.ts | 20 +++++ 4 files changed, 214 insertions(+) create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.symbols create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types create mode 100644 tsc/testdata/tests/cases/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.ts diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js new file mode 100644 index 0000000000000..acd616866f126 --- /dev/null +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js @@ -0,0 +1,88 @@ +//// [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; +//// [main1.d.ts] +import * as dep from "./dep"; +export declare const v: dep."a b"; +//// [main2.d.ts] +import * as dep from "./dep"; +export declare const w: dep."a c"; + + +//// [DtsFileErrors] + + +/main1.d.ts(2,29): error TS1003: Identifier expected. +/main2.d.ts(2,29): error TS1003: Identifier expected. + + +==== /dep.d.ts (0 errors) ==== + interface A { + x: number; + } + interface C { + y: number; + } + export { A as "a b", C as "a c", C as Ok }; + +==== /mid.d.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.d.ts (1 errors) ==== + import * as dep from "./dep"; + export declare const v: dep."a b"; + ~~~~~ +!!! error TS1003: Identifier expected. + +==== /main2.d.ts (1 errors) ==== + import * as dep from "./dep"; + export declare const w: dep."a c"; + ~~~~~ +!!! error TS1003: Identifier expected. + \ No newline at end of file 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..7639f866fbef7 --- /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 : () => dep."a b" + +export const v = f(); +>v : dep."a b" +>f() : dep."a b" +>f : () => dep."a b" + +=== /main2.ts === +import * as dep from "./dep"; +>dep : typeof dep + +import { g } from "./mid"; +>g : () => dep."a c" + +export const w = g(); +>w : dep."a c" +>g() : dep."a c" +>g : () => dep."a c" + 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(); From ea49fb1c9e3485e19938fe3ca9fab490401f6f54 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:38:27 -0800 Subject: [PATCH 50/53] Skip string export names when qualifying through namespace imports A qualified name such as `dep.x` can only reference an export with an identifier name, so exports like `export { A as "a b" }` cannot name a type through a namespace import. Choosing one emits a declaration file that does not parse instead of falling back to another export or reporting that the type cannot be named. --- tsc/internal/checker/symbolaccessibility.go | 4 +- ...tifierExportNameNamespaceImport.errors.txt | 25 ++++++++++++ ...tNonIdentifierExportNameNamespaceImport.js | 40 +------------------ ...nIdentifierExportNameNamespaceImport.types | 16 ++++---- 4 files changed, 37 insertions(+), 48 deletions(-) create mode 100644 tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.errors.txt diff --git a/tsc/internal/checker/symbolaccessibility.go b/tsc/internal/checker/symbolaccessibility.go index 2420d6b90a4b3..43e000160e208 100644 --- a/tsc/internal/checker/symbolaccessibility.go +++ b/tsc/internal/checker/symbolaccessibility.go @@ -642,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/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 index acd616866f126..809db8044b2b7 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.js @@ -45,44 +45,6 @@ export { A as "a b", C as "a c", C as Ok }; import { "a b" as B, "a c" as C } from "./dep"; export declare function f(): B; export declare function g(): C; -//// [main1.d.ts] -import * as dep from "./dep"; -export declare const v: dep."a b"; //// [main2.d.ts] import * as dep from "./dep"; -export declare const w: dep."a c"; - - -//// [DtsFileErrors] - - -/main1.d.ts(2,29): error TS1003: Identifier expected. -/main2.d.ts(2,29): error TS1003: Identifier expected. - - -==== /dep.d.ts (0 errors) ==== - interface A { - x: number; - } - interface C { - y: number; - } - export { A as "a b", C as "a c", C as Ok }; - -==== /mid.d.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.d.ts (1 errors) ==== - import * as dep from "./dep"; - export declare const v: dep."a b"; - ~~~~~ -!!! error TS1003: Identifier expected. - -==== /main2.d.ts (1 errors) ==== - import * as dep from "./dep"; - export declare const w: dep."a c"; - ~~~~~ -!!! error TS1003: Identifier expected. - \ No newline at end of file +export declare const w: dep.Ok; diff --git a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types index 7639f866fbef7..e86a183636d7e 100644 --- a/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types +++ b/tsc/testdata/baselines/reference/compiler/declarationEmitNonIdentifierExportNameNamespaceImport.types @@ -31,22 +31,22 @@ import * as dep from "./dep"; >dep : typeof dep import { f } from "./mid"; ->f : () => dep."a b" +>f : () => A export const v = f(); ->v : dep."a b" ->f() : dep."a b" ->f : () => dep."a b" +>v : A +>f() : A +>f : () => A === /main2.ts === import * as dep from "./dep"; >dep : typeof dep import { g } from "./mid"; ->g : () => dep."a c" +>g : () => dep.Ok export const w = g(); ->w : dep."a c" ->g() : dep."a c" ->g : () => dep."a c" +>w : dep.Ok +>g() : dep.Ok +>g : () => dep.Ok From ab0e1d282f46cd8c983fe8af41c418c53abf17a4 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:41:15 -0800 Subject: [PATCH 51/53] Add a test for renaming namespace exports to non-identifiers A namespace export name may be a string literal, so a rename to a name that is not an identifier has to quote it; written bare, the export statement no longer parses. --- .../fourslash/tests/renameEscaping_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index d6e67a937af3f..f391dd940d12c 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -156,3 +156,20 @@ let x;` 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";`, + }) +} From b6adb492b0c4261ad9ba7a8bf78710db09dda368 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:41:54 -0800 Subject: [PATCH 52/53] Quote non-identifier names in renamed namespace exports The name in `export * as ns` is a module export name that may be a string literal, so renaming it to a non-identifier quotes the name in the same way as an export specifier. --- tsc/internal/fourslash/tests/renameEscaping_test.go | 2 +- tsc/internal/ls/rename.go | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tsc/internal/fourslash/tests/renameEscaping_test.go b/tsc/internal/fourslash/tests/renameEscaping_test.go index f391dd940d12c..e59726944329b 100644 --- a/tsc/internal/fourslash/tests/renameEscaping_test.go +++ b/tsc/internal/fourslash/tests/renameEscaping_test.go @@ -169,7 +169,7 @@ 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";`, + "/a.ts": `export * as "a-b" from "./dep";`, "/b.ts": `import { "a-b" as bar } from "./a";`, }) } diff --git a/tsc/internal/ls/rename.go b/tsc/internal/ls/rename.go index 0a3b9e27bcea7..bf044a5b532b2 100644 --- a/tsc/internal/ls/rename.go +++ b/tsc/internal/ls/rename.go @@ -529,6 +529,8 @@ func isModuleExportNameOfSpecifier(node *ast.Node) bool { 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 } From 97c34a48ef39b75184fac38851f6e75bba1b4a23 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:43:02 -0800 Subject: [PATCH 53/53] Quote non-identifier names of declarationless members in member fixes A property synthesized by intersecting mapped types has no declaration to copy its name from, so its name was written as an identifier even when it was not one, which crashed the printer. --- ...ixClassImplementInterfaceMappedType2_test.go | 17 +++++++++++++++++ .../ls/codeactions_missingmemberfixer.go | 15 +++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go index 74a4f2e1c0aeb..8b3c424af13d1 100644 --- a/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go +++ b/tsc/internal/fourslash/tests/codeFixClassImplementInterfaceMappedType2_test.go @@ -72,3 +72,20 @@ class C implements I { 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/ls/codeactions_missingmemberfixer.go b/tsc/internal/ls/codeactions_missingmemberfixer.go index 598e8ba0732f5..608b046b8172f 100644 --- a/tsc/internal/ls/codeactions_missingmemberfixer.go +++ b/tsc/internal/ls/codeactions_missingmemberfixer.go @@ -494,22 +494,25 @@ func createDeclarationName(factory *ast.NodeFactory, typeChecker *checker.Checke return factory.NewComputedPropertyName(typeChecker.SymbolToExpression(nameType.Symbol(), ast.SymbolFlagsValue, enclosingDeclaration, nodebuilder.FlagsNone)) } if nameType != nil && checker.IsTypeUsableAsPropertyName(nameType) { - name := checker.GetPropertyNameFromType(nameType) - if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) { - return factory.NewStringLiteral(name, core.IfElse(quotePreference == lsutil.QuotePreferenceSingle, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone)) - } - return factory.NewIdentifier(name) + 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