Skip to content

Fix more LS escaping related bugs - #65665

Open
Jake Bailey (jakebailey) wants to merge 53 commits into
microsoft:mainfrom
jakebailey:fix-ls-edit-escaping
Open

Jake Bailey (jakebailey) wants to merge 53 commits into
microsoft:mainfrom
jakebailey:fix-ls-edit-escaping

Conversation

@jakebailey

Copy link
Copy Markdown
Member

More stuff similar to the last PR but in other areas.

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.
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.
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.
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.
JSDoc @PARAM completions copy initializers, inferred types and
destructured property names into the comment. This test records the
current completions for text containing */.
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.
These tests record member, object literal method, exhaustive switch and
import statement completions for names containing $ and backslashes,
with and without client snippet support.
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.
This test records the closing tag snippet for a JSX tag name written
with a Unicode escape.
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.
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.
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.
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.
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.
This test records the extract binding expressions fix for numeric and
escape-like string property names.
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.
This test records the import fix that promotes a type-only import of a
string export name.
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.
This test records that a default export named with a multi-byte first
character is missing from JSX tag completions.
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.
This test records organize imports for two imports whose attributes
differ only in where a quoted value ends.
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.
This test records the element access completion for a property name
containing U+2028.
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.
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.
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.
This test records declaration emit for types reachable only through
exports with string literal names.
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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved escaping and name-handling defects can produce invalid code or JSON, break JSDoc comments, and alter or leave stale renamed references.

9 open issues
What changed in this PR

This PR hardens escaping in TypeScript’s language service so generated edits preserve unusual names and string contents across renames, completions, imports, and code fixes. It also updates compiler alias selection for non-identifier export names.

Changes:

  • Adds context-aware escaping for strings, snippets, JSDoc text, and file-rename edits.
  • Improves handling of quoted names, mapped properties, destructuring, and Unicode JSX auto-imports.
  • Adds regression tests and updates rename baselines to use an identifier placeholder.
File Description
tsc/​testdata/​tests/​cases/​compiler/​declarationEmitNonIdentifierExportName.ts Tests quoted exports and identifier alias fallback.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​renameInCommonFile.baseline Updates logged rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​renameAncestorProjectRefMangement.baseline Updates project-reference rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMapsNotSolutionEditEnd.baseline Updates rename placeholder after end edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMapsNotSolutionEdit.baseline Updates rename placeholder after edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMapsNotSolution.baseline Updates source-map rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMapsEditEnd.baseline Updates rename placeholder after end edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMapsEdit.baseline Updates rename placeholder after edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithSourceMaps.baseline Updates source-map rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithProjectReferencesEditEnd.baseline Updates project-reference rename placeholder after end edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithProjectReferencesEdit.baseline Updates project-reference rename placeholder after edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithProjectReferences.baseline Updates project-reference rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEditEnd.baseline Updates redirect-disabled rename placeholder after end edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithDisableSourceOfProjectReferenceRedirectEdit.baseline Updates redirect-disabled rename placeholder after edits.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameWithDisableSourceOfProjectReferenceRedirect.baseline Updates redirect-disabled rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameTargetDoesNotExist.baseline Updates missing-target rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRenameStartingAtDefinition.baseline Updates definition-origin rename placeholder.
tsc/​testdata/​baselines/​reference/​fourslash/​state/​declarationMapsRename.baseline Updates declaration-map rename placeholder.
tsc/​testdata/​baselines/​reference/​compiler/​declarationEmitNonIdentifierExportName.types Records inferred alias types.
tsc/​testdata/​baselines/​reference/​compiler/​declarationEmitNonIdentifierExportName.symbols Records quoted export symbols.
tsc/​testdata/​baselines/​reference/​compiler/​declarationEmitNonIdentifierExportName.js Records JavaScript and declaration output.
tsc/​testdata/​baselines/​reference/​compiler/​declarationEmitNonIdentifierExportName.errors.txt Records the unnameable-export diagnostic.
tsc/​internal/​ls/​utilities.go Escapes line separators in generated quoted strings.
tsc/​internal/​ls/​rename.go Adds string escaping and non-identifier alias handling.
tsc/​internal/​ls/​organizeimports.go Quotes import-attribute grouping keys to avoid collisions.
tsc/​internal/​ls/​lsutil/​utilities.go Adds comment-safe string escaping.
tsc/​internal/​ls/​file_rename.go Escapes replacement paths and guards reference directives.
tsc/​internal/​ls/​completions.go Separates snippet escaping and guards generated JSDoc text.
tsc/​internal/​ls/​codeactions_missingmemberfixer.go Quotes non-identifier mapped member names.
tsc/​internal/​ls/​codeactions_fixmissingtypeannotation.go Uses element access for non-identifier binding properties.
tsc/​internal/​ls/​autoimport/​view.go Decodes Unicode initials for JSX completion filtering.
tsc/​internal/​ls/​autoimport/​fix.go Escapes JSDoc imports and preserves quoted import names.
tsc/​internal/​fourslash/​tests/​renameEscaping_test.go Adds literal and non-identifier rename cases.
tsc/​internal/​fourslash/​tests/​organizeImportsAttributes4_test.go Tests quoted import-attribute values.
tsc/​internal/​fourslash/​tests/​importStatementCompletions_noSnippet_test.go Tests plain-text imports containing dollar signs.
tsc/​internal/​fourslash/​tests/​getEditsForFileRename_escapedSpecifier_test.go Tests escaped paths and JSDoc file-renaming edits.
tsc/​internal/​fourslash/​tests/​completionsSnippetEscaping_test.go Tests snippet and plain-text completion escaping.
tsc/​internal/​fourslash/​tests/​completionsOverridingMethod22_test.go Updates plain-text dollar-sign completion output.
tsc/​internal/​fourslash/​tests/​completionsImport_jsxOpeningTagImportDefault_test.go Adds a non-ASCII JSX default-import case.
tsc/​internal/​fourslash/​tests/​completionFilterText3_test.go Tests line-separator property completion escaping.
tsc/​internal/​fourslash/​tests/​codeFixPromoteTypeOnlyOrderingCrash_test.go Tests promotion of quoted type-only imports.
tsc/​internal/​fourslash/​tests/​codeFixMissingTypeAnnotationOnExports14_test.go Tests extraction of non-identifier binding properties.
tsc/​internal/​fourslash/​tests/​codeFixClassImplementInterfaceMappedType2_test.go Tests quoted mapped member generation.
tsc/​internal/​fourslash/​tests/​basicJSDocCompletions_test.go Tests comment terminators in parameter completions.
tsc/​internal/​fourslash/​tests/​autoImportQuotedModuleSpecifier_test.go Tests comment-safe JSDoc auto-import paths.
tsc/​internal/​fourslash/​tests/​autoCloseTag_test.go Tests escaped JSX closing-tag output.
tsc/​internal/​fourslash/​fourslash.go Uses an identifier placeholder for rename baselines.
tsc/​internal/​checker/​symbolaccessibility.go Filters non-identifier aliases for import-type qualifiers.

Review effort: Max

Comment thread tsc/internal/ls/autoimport/view.go Resolved
Comment thread tsc/internal/ls/completions.go Resolved
Comment thread tsc/internal/ls/file_rename.go Resolved
Comment thread tsc/internal/ls/file_rename.go Resolved
Comment thread tsc/internal/ls/rename.go Resolved
Comment thread tsc/internal/ls/rename.go Resolved
Comment thread tsc/internal/ls/rename.go Resolved
Comment thread tsc/internal/ls/rename.go Resolved
This test records the tsconfig edit for a directory renamed to a name
containing a vertical tab.
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.
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.
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.
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.
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.
A property name containing */ in a nested destructuring pattern is
still copied into the generated @PARAM tags, where it ends the comment.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A property name containing "*/" completed inside a JSDoc type closes
the comment early, leaving the rest of the name as source code.
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.
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.
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.
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.
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.
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.
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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +646 to +647
// A qualified name can only reference exports with identifier names
(!ignoreQualification || isIdentifierExportName(symbolFromSymbolTable.Name())) {
Description: "Implement interface 'I'",
NewFileContent: `import { I } from "dep";
class C implements I {
"c\\u0064": Hidden;
Comment on lines +493 to +494
if nameType != nil && nameType.Flags()&checker.TypeFlagsUniqueESSymbol != 0 {
return factory.NewComputedPropertyName(typeChecker.SymbolToExpression(nameType.Symbol(), ast.SymbolFlagsValue, enclosingDeclaration, nodebuilder.FlagsNone))
Comment thread tsc/internal/ls/rename.go
Comment on lines +177 to +191
// 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)
}

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

Status: Not started

Development

Successfully merging this pull request may close these issues.

2 participants