From 1be05957823982196cda7da755ac7d2f72ec56dd Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:13:59 -0800
Subject: [PATCH 01/24] Share numeric literal name check through jsnum
The language service needs the same check the checker uses to decide
whether a property name can be written as a numeric literal. It only
depends on number conversion, so it belongs with jsnum.
---
tsc/internal/checker/checker.go | 14 ++++++-------
tsc/internal/checker/nodebuilderimpl.go | 12 ++++++------
tsc/internal/checker/relater.go | 2 +-
tsc/internal/checker/utilities.go | 25 ------------------------
tsc/internal/jsnum/string.go | 26 +++++++++++++++++++++++++
5 files changed, 40 insertions(+), 39 deletions(-)
diff --git a/tsc/internal/checker/checker.go b/tsc/internal/checker/checker.go
index 694fc155b8e16..f0ddce515b8ae 100644
--- a/tsc/internal/checker/checker.go
+++ b/tsc/internal/checker/checker.go
@@ -19672,7 +19672,7 @@ func (c *Checker) isApplicableIndexType(source *Type, target *Type) bool {
// signature applies to types assignable to 'number', `${number}` and numeric string literal types.
return c.isTypeAssignableTo(source, target) ||
target == c.stringType && c.isTypeAssignableTo(source, c.numberType) ||
- target == c.numberType && (source == c.numericStringType || source.flags&TypeFlagsStringLiteral != 0 && isNumericLiteralName(getStringLiteralValue(source)))
+ target == c.numberType && (source == c.numericStringType || source.flags&TypeFlagsStringLiteral != 0 && jsnum.IsNumericLiteralName(getStringLiteralValue(source)))
}
func (c *Checker) resolveStructuredTypeMembers(t *Type) *StructuredType {
@@ -20467,7 +20467,7 @@ func (c *Checker) isSymbolWithSymbolName(symbol *ast.Symbol) bool {
}
func (c *Checker) isSymbolWithNumericName(symbol *ast.Symbol) bool {
- if isNumericLiteralName(symbol.Name()) {
+ if jsnum.IsNumericLiteralName(symbol.Name()) {
return true
}
if len(symbol.Declarations()) != 0 {
@@ -20490,7 +20490,7 @@ func (c *Checker) isNumericName(name *ast.Node) bool {
case ast.KindComputedPropertyName:
return c.isNumericComputedName(name)
case ast.KindIdentifier, ast.KindNumericLiteral, ast.KindStringLiteral:
- return isNumericLiteralName(name.Text())
+ return jsnum.IsNumericLiteralName(name.Text())
}
return false
}
@@ -24806,7 +24806,7 @@ func (c *Checker) computeEnumMemberValue(member *ast.Node, autoValue *jsnum.Numb
c.error(member.Name(), diagnostics.An_enum_member_cannot_have_a_numeric_name)
} else {
text := ast.GetTextOfPropertyName(member.Name())
- if isNumericLiteralName(text) && !ast.IsInfinityOrNaNString(text) {
+ if jsnum.IsNumericLiteralName(text) && !ast.IsInfinityOrNaNString(text) {
c.error(member.Name(), diagnostics.An_enum_member_cannot_have_a_numeric_name)
}
}
@@ -27965,7 +27965,7 @@ func (c *Checker) getPropertyTypeForIndexType(originalObjectType *Type, objectTy
return propType
}
}
- if everyType(objectType, isTupleType) && isNumericLiteralName(propName) {
+ if everyType(objectType, isTupleType) && jsnum.IsNumericLiteralName(propName) {
index := jsnum.FromString(propName)
if accessNode != nil && everyType(objectType, func(t *Type) bool {
return t.TargetTupleType().combinedFlags&ElementFlagsVariable == 0
@@ -28289,7 +28289,7 @@ func indexTypeLessThan(indexType *Type, limit int) bool {
return everyType(indexType, func(t *Type) bool {
if t.flags&TypeFlagsStringOrNumberLiteral != 0 {
propName := getPropertyNameFromType(t)
- if isNumericLiteralName(propName) {
+ if jsnum.IsNumericLiteralName(propName) {
index := jsnum.FromString(propName)
return index >= 0 && index < jsnum.Number(limit)
}
@@ -31590,7 +31590,7 @@ func (c *Checker) getTypeOfConcretePropertyOfContextualType(t *Type, name string
}
func (c *Checker) getTypeFromIndexInfosOfContextualType(t *Type, name string, nameType *Type) *Type {
- if isTupleType(t) && isNumericLiteralName(name) && jsnum.FromString(name) >= 0 {
+ if isTupleType(t) && jsnum.IsNumericLiteralName(name) && jsnum.FromString(name) >= 0 {
restType := c.getElementTypeOfSliceOfTupleType(t, t.TargetTupleType().fixedLength, 0 /*endSkipCount*/, false /*writing*/, true /*noReductions*/)
if restType != nil {
return restType
diff --git a/tsc/internal/checker/nodebuilderimpl.go b/tsc/internal/checker/nodebuilderimpl.go
index 5e8d3205ca031..a127c1762f75f 100644
--- a/tsc/internal/checker/nodebuilderimpl.go
+++ b/tsc/internal/checker/nodebuilderimpl.go
@@ -926,7 +926,7 @@ func (b *NodeBuilderImpl) createExpressionFromSymbolChain(chain []*ast.Symbol, i
literalText := stringutil.UnquoteString(symbolName)
b.ctx.approximateLength += len(literalText) + 2
expression = b.newStringLiteralEx(literalText, symbolName[0] == '\'')
- } else if jsnum.FromString(symbolName).String() == symbolName {
+ } else if jsnum.IsNumericLiteralName(symbolName) {
// TODO: the follwing in strada would assert if the number is negative, but no such assertion exists here
// Moreover, what's even guaranteeing the name *isn't* -1 here anyway? Needs double-checking.
b.ctx.approximateLength += len(symbolName)
@@ -979,10 +979,10 @@ func (b *NodeBuilderImpl) getNameOfSymbolFromNameType(symbol *ast.Symbol) string
case jsnum.Number:
name = v.String()
}
- if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) && !isNumericLiteralName(name) {
+ if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) && !jsnum.IsNumericLiteralName(name) {
return b.ch.valueToString(nameType.AsLiteralType().value)
}
- if isNumericLiteralName(name) && strings.HasPrefix(name, "-") {
+ if jsnum.IsNumericLiteralName(name) && strings.HasPrefix(name, "-") {
return fmt.Sprintf("[%s]", name)
}
return name
@@ -2510,7 +2510,7 @@ func classifyPropertyName(name string, stringNamed bool, isMethod bool) property
if scanner.IsIdentifierText(name, core.LanguageVariantStandard) {
return propertyNameNodeKindIdentifier
}
- return core.IfElse(!stringNamed && isNumericLiteralName(name) && jsnum.FromString(name) >= 0, propertyNameNodeKindNumericLiteral, propertyNameNodeKindStringLiteral)
+ return core.IfElse(!stringNamed && jsnum.IsNumericLiteralName(name) && jsnum.FromString(name) >= 0, propertyNameNodeKindNumericLiteral, propertyNameNodeKindStringLiteral)
}
func (b *NodeBuilderImpl) createPropertyNameNodeForIdentifierOrLiteral(name string, singleQuote bool, stringNamed bool, isMethod bool, symbol *ast.Symbol) *ast.Node {
@@ -2608,11 +2608,11 @@ func (b *NodeBuilderImpl) getPropertyNameNodeForSymbolFromNameType(symbol *ast.S
case string:
name = nameType.AsLiteralType().value.(string)
}
- if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) && (stringNamed || !isNumericLiteralName(name)) {
+ if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) && (stringNamed || !jsnum.IsNumericLiteralName(name)) {
node := b.f.NewStringLiteral(name, core.IfElse(singleQuote, ast.TokenFlagsSingleQuote, ast.TokenFlagsNone))
return node
}
- if isNumericLiteralName(name) && name[0] == '-' {
+ if jsnum.IsNumericLiteralName(name) && name[0] == '-' {
return b.f.NewComputedPropertyName(b.f.NewPrefixUnaryExpression(ast.KindMinusToken, b.f.NewNumericLiteral(name[1:], ast.TokenFlagsNone)))
}
return b.createPropertyNameNodeForIdentifierOrLiteral(name, singleQuote, stringNamed, isMethod, symbol)
diff --git a/tsc/internal/checker/relater.go b/tsc/internal/checker/relater.go
index bbaca3eba478e..ccd1e92e8140d 100644
--- a/tsc/internal/checker/relater.go
+++ b/tsc/internal/checker/relater.go
@@ -4314,7 +4314,7 @@ func (r *Relater) propertiesRelatedTo(source *Type, target *Type, reportErrors b
numericNamesOnly := isTupleType(source) && isTupleType(target)
for _, targetProp := range excludeProperties(properties, excludedProperties) {
name := targetProp.Name()
- if targetProp.Flags()&ast.SymbolFlagsPrototype == 0 && (!numericNamesOnly || isNumericLiteralName(name) || name == "length") && (!optionalsOnly || targetProp.Flags()&ast.SymbolFlagsOptional != 0) {
+ if targetProp.Flags()&ast.SymbolFlagsPrototype == 0 && (!numericNamesOnly || jsnum.IsNumericLiteralName(name) || name == "length") && (!optionalsOnly || targetProp.Flags()&ast.SymbolFlagsOptional != 0) {
sourceProp := r.c.getPropertyOfType(source, name)
if sourceProp != nil && sourceProp != targetProp {
related := r.propertyRelatedTo(source, target, sourceProp, targetProp, r.c.getNonMissingTypeOfSymbol, reportErrors, intersectionState, r.relation == r.c.comparableRelation)
diff --git a/tsc/internal/checker/utilities.go b/tsc/internal/checker/utilities.go
index c4cc97fa29a1b..01abc2278b039 100644
--- a/tsc/internal/checker/utilities.go
+++ b/tsc/internal/checker/utilities.go
@@ -1057,31 +1057,6 @@ func getPropertyNameFromType(t *Type) string {
panic("Unhandled case in getPropertyNameFromType")
}
-func isNumericLiteralName(name string) bool {
- // The intent of numeric names is that
- // - they are names with text in a numeric form, and that
- // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
- // acquired by applying the abstract 'ToNumber' operation on the name's text.
- //
- // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
- // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
- //
- // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
- // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
- // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
- // because their 'ToString' representation is not equal to their original text.
- // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
- //
- // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
- // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
- // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
- //
- // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
- // This is desired behavior, because when indexing with them as numeric entities, you are indexing
- // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
- return jsnum.FromString(name).String() == name
-}
-
func isThisProperty(node *ast.Node) bool {
return (ast.IsPropertyAccessExpression(node) || ast.IsElementAccessExpression(node)) && node.Expression().Kind == ast.KindThisKeyword
}
diff --git a/tsc/internal/jsnum/string.go b/tsc/internal/jsnum/string.go
index 639dd7f59380a..919af42e4a7f4 100644
--- a/tsc/internal/jsnum/string.go
+++ b/tsc/internal/jsnum/string.go
@@ -96,6 +96,32 @@ func FromString(s string) Number {
return Number(math.Copysign(f, sign))
}
+// IsNumericLiteralName reports whether name is the canonical string form of a number.
+func IsNumericLiteralName(name string) bool {
+ // The intent of numeric names is that
+ // - they are names with text in a numeric form, and that
+ // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
+ // acquired by applying the abstract 'ToNumber' operation on the name's text.
+ //
+ // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
+ // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
+ //
+ // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
+ // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
+ // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
+ // because their 'ToString' representation is not equal to their original text.
+ // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
+ //
+ // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
+ // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
+ // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
+ //
+ // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
+ // This is desired behavior, because when indexing with them as numeric entities, you are indexing
+ // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
+ return FromString(name).String() == name
+}
+
func isStrWhiteSpace(r rune) bool {
// This is different than stringutil.IsWhiteSpaceLike.
From edc7fd2200cff4ec2d9dca6402168e2085cd0c26 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:15:21 -0800
Subject: [PATCH 02/24] Add tests for escaping in string completions
Property names completed inside a string are inserted without escaping
for the surrounding quote, so a name containing that quote or ${ ends
the string or starts a substitution. String literal type completions in
single-quoted strings are escaped for double quotes.
---
...ListInvalidMemberNames_escapeQuote_test.go | 74 +++++++++++++++++++
1 file changed, 74 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 63510a2b85ed2..0cc4d3785131f 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -61,3 +61,77 @@ x[|./**/|];`
UserPreferences: &lsutil.UserPreferences{QuotePreference: lsutil.QuotePreference("single")},
})
}
+
+func TestStringCompletionEscaping(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `interface Properties {
+ "a'b\"c${x}\\z": number;
+}
+declare const value: Properties;
+value["[|/*double*/|]"];
+value['[|/*single*/|]'];
+value[` + "`[|/*template*/|]`" + `];
+type Indexed = Properties['[|/*indexed*/|]'];
+"[|/*in*/|]" in value;
+const object: Properties = { '[|/*object*/|]': 1 };
+declare function f(value: "a'b\"c${x}\\z"): void;
+f('[|/*typeSingle*/|]');
+f(` + "`[|/*typeTemplate*/|]`" + `);
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ for i, test := range []struct {
+ marker string
+ label string
+ insertText string
+ newText string
+ }{
+ {"double", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"single", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"template", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"indexed", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"in", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"object", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
+ {"typeSingle", `a'b\"c${x}\\z`, "", `a'b\"c${x}\\z`},
+ {"typeTemplate", `a'b"c\${x}\\z`, "", `a'b"c\${x}\\z`},
+ } {
+ item := &lsproto.CompletionItem{
+ Label: test.label,
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: test.newText, Range: f.Ranges()[i].LSRange},
+ },
+ }
+ if test.insertText != "" {
+ item.InsertText = &test.insertText
+ }
+ f.VerifyCompletions(t, test.marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{Includes: []fourslash.CompletionsExpectedItem{item}},
+ })
+ }
+}
+
+func TestStringCompletionEscapingUnterminated(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `declare const value: { "a'b": number };
+value['/*completion*/`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ f.VerifyCompletions(t, "completion", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{Label: "a'b"},
+ },
+ },
+ })
+}
From d1d66f98620ff6b2ea127351b485a0463ba08866 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:16:39 -0800
Subject: [PATCH 03/24] Escape string completions for the surrounding quote
A property name inserted into a string literal unescaped can end the
string early or start a template substitution, turning type metadata
from a dependency into code in the user's file. Escape names for the
quote of the string being completed, and read the quote style from the
token flags so single-quoted strings are no longer escaped as if they
were double-quoted.
---
...ListInvalidMemberNames_escapeQuote_test.go | 16 ++++++++--------
tsc/internal/ls/completions.go | 6 ++++++
tsc/internal/ls/string_completions.go | 19 +++++++++++--------
3 files changed, 25 insertions(+), 16 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 0cc4d3785131f..75e4a2f012b37 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -87,13 +87,13 @@ f(` + "`[|/*typeTemplate*/|]`" + `);
insertText string
newText string
}{
- {"double", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"single", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"template", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"indexed", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"in", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"object", `a'b"c${x}\z`, "", `a'b"c${x}\z`},
- {"typeSingle", `a'b\"c${x}\\z`, "", `a'b\"c${x}\\z`},
+ {"double", `a'b"c${x}\z`, `a'b\"c${x}\\z`, `a'b\"c${x}\\z`},
+ {"single", `a'b"c${x}\z`, `a\'b"c${x}\\z`, `a\'b"c${x}\\z`},
+ {"template", `a'b"c${x}\z`, `a'b"c\${x}\\z`, `a'b"c\${x}\\z`},
+ {"indexed", `a'b"c${x}\z`, `a\'b"c${x}\\z`, `a\'b"c${x}\\z`},
+ {"in", `a'b"c${x}\z`, `a'b\"c${x}\\z`, `a'b\"c${x}\\z`},
+ {"object", `a'b"c${x}\z`, `a\'b"c${x}\\z`, `a\'b"c${x}\\z`},
+ {"typeSingle", `a\'b"c${x}\\z`, "", `a\'b"c${x}\\z`},
{"typeTemplate", `a'b"c\${x}\\z`, "", `a'b"c\${x}\\z`},
} {
item := &lsproto.CompletionItem{
@@ -130,7 +130,7 @@ value['/*completion*/`
},
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
- &lsproto.CompletionItem{Label: "a'b"},
+ &lsproto.CompletionItem{Label: "a'b", InsertText: new(`a\'b`)},
},
},
})
diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go
index eea053c35a173..d783f957aded6 100644
--- a/tsc/internal/ls/completions.go
+++ b/tsc/internal/ls/completions.go
@@ -2201,6 +2201,12 @@ func (l *LanguageService) createCompletionItem(
source := getSourceFromOrigin(origin)
var labelDetails *lsproto.CompletionItemLabelDetails
preferences := l.UserPreferences()
+ if data.completionKind == CompletionKindString {
+ escaped := printer.EscapeString(name, stringCompletionQuoteChar(contextToken))
+ if escaped != name {
+ insertText = escaped
+ }
+ }
insertQuestionDot := originIsNullableMember(origin)
useBraces := originIsSymbolMember(origin) || needsConvertPropertyAccess
if originIsThisTypeNode(origin) {
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index b3f0f4c01ed46..cf8d729b03558 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -148,14 +148,7 @@ func (l *LanguageService) convertStringLiteralCompletions(
}
case completion.fromTypes != nil:
completion := completion.fromTypes
- var quoteChar printer.QuoteChar
- if contextToken.Kind == ast.KindNoSubstitutionTemplateLiteral {
- quoteChar = printer.QuoteCharBacktick
- } else if strings.HasPrefix(contextToken.Text(), "'") {
- quoteChar = printer.QuoteCharSingleQuote
- } else {
- quoteChar = printer.QuoteCharDoubleQuote
- }
+ quoteChar := stringCompletionQuoteChar(contextToken)
items := core.Map(completion.types, func(t *checker.StringLiteralType) *CompletionItem {
name := printer.EscapeString(t.AsLiteralType().Value().(string), quoteChar)
lspItem := l.createLSPCompletionItem(
@@ -203,6 +196,16 @@ func (l *LanguageService) convertStringLiteralCompletions(
}
}
+func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.QuoteChar {
+ if contextToken.Kind == ast.KindNoSubstitutionTemplateLiteral {
+ return printer.QuoteCharBacktick
+ }
+ if contextToken.AsStringLiteral().TokenFlags&ast.TokenFlagsSingleQuote != 0 {
+ return printer.QuoteCharSingleQuote
+ }
+ return printer.QuoteCharDoubleQuote
+}
+
func (l *LanguageService) convertPathCompletions(
ctx context.Context,
completion *pathCompletions,
From d2a06bc80541c4480cdacc029c0b90be805ab1a3 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:16:59 -0800
Subject: [PATCH 04/24] Add tests for escaping in module path completions
File and directory names completed in a module specifier are inserted
without escaping, so a name containing the specifier's quote character
ends the string early.
---
...ionForStringLiteralRelativeImport4_test.go | 44 +++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index 183514f45f275..3c0e81f7b8758 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_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/lsp/lsproto"
"github.com/microsoft/TypeScript/tsc/internal/testutil"
)
@@ -73,3 +74,46 @@ export const x = 0;
},
})
}
+
+func TestPathCompletionEscaping(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @Filename: /src/main.ts
+import "./[|a/*double*/|]";
+import './[|a/*single*/|]';
+// @Filename: /src/a"b.ts
+export {};
+// @Filename: /src/a'b.ts
+export {};
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ for i, test := range []struct {
+ marker string
+ label string
+ insertText string
+ newText string
+ }{
+ {"double", `a"b`, "", `a"b`},
+ {"single", `a'b`, "", `a'b`},
+ } {
+ item := &lsproto.CompletionItem{
+ Label: test.label,
+ Detail: new(test.label + ".ts"),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: test.newText, Range: f.Ranges()[i].LSRange},
+ },
+ }
+ if test.insertText != "" {
+ item.InsertText = &test.insertText
+ }
+ f.VerifyCompletions(t, test.marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &[]string{},
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{Includes: []fourslash.CompletionsExpectedItem{item}},
+ })
+ }
+}
From bac6db79f9c85ede788175aca210c63c8749ffd9 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:17:47 -0800
Subject: [PATCH 05/24] Escape module path completions for the surrounding
quote
A file or directory name containing the specifier's quote character
otherwise ends the string early instead of naming the selected file.
---
...mpletionForStringLiteralRelativeImport4_test.go | 4 ++--
tsc/internal/ls/string_completions.go | 14 +++++++++++---
2 files changed, 13 insertions(+), 5 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index 3c0e81f7b8758..76e8a85a59185 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -94,8 +94,8 @@ export {};
insertText string
newText string
}{
- {"double", `a"b`, "", `a"b`},
- {"single", `a'b`, "", `a'b`},
+ {"double", `a"b`, `a\"b`, `a\"b`},
+ {"single", `a'b`, `a\'b`, `a\'b`},
} {
item := &lsproto.CompletionItem{
Label: test.label,
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index cf8d729b03558..421b5e70038ae 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -65,7 +65,7 @@ func (l *LanguageService) getStringLiteralCompletions(
) *CompletionList {
if isInReferenceComment(file, position) {
completion := l.getTripleSlashReferenceCompletions(file, position, l.GetProgram(), checker)
- return l.convertPathCompletions(ctx, completion, file, position)
+ return l.convertPathCompletions(ctx, completion, nil, file, position)
}
if IsInString(file, position, contextToken) {
if contextToken == nil || !ast.IsStringLiteralLike(contextToken) {
@@ -109,7 +109,7 @@ func (l *LanguageService) convertStringLiteralCompletions(
optionalReplacementRange := l.createRangeFromStringLiteralLikeContent(file, contextToken, position)
switch {
case completion.fromPaths != nil:
- return l.convertPathCompletions(ctx, completion.fromPaths, file, position)
+ return l.convertPathCompletions(ctx, completion.fromPaths, contextToken, file, position)
case completion.fromProperties != nil:
completion := completion.fromProperties
data := &completionDataData{
@@ -209,6 +209,7 @@ func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.Quot
func (l *LanguageService) convertPathCompletions(
ctx context.Context,
completion *pathCompletions,
+ contextToken *ast.StringLiteralLike,
file *ast.SourceFile,
position int,
) *CompletionList {
@@ -222,10 +223,17 @@ func (l *LanguageService) convertPathCompletions(
if !strings.HasSuffix(pathCompletion.name, pathCompletion.extension) {
detail += pathCompletion.extension
}
+ insertText := ""
+ if contextToken != nil {
+ escaped := printer.EscapeString(pathCompletion.name, stringCompletionQuoteChar(contextToken))
+ if escaped != pathCompletion.name {
+ insertText = escaped
+ }
+ }
lspItem := l.createLSPCompletionItem(
ctx,
pathCompletion.name,
- "", /*insertText*/
+ insertText,
"", /*filterText*/
SortTextLocationPriority,
pathCompletion.kind,
From 2b5d4aa682bdd460e13d771a49cad2a2f4a4845b Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:18:06 -0800
Subject: [PATCH 06/24] Add tests for digit-prefixed member name completions
Any property name starting with a digit is inserted unquoted in an
element access, so "1+sideEffect()" becomes an expression and "01"
accesses property 1.
---
...ListInvalidMemberNames_escapeQuote_test.go | 34 +++++++++++++++++++
1 file changed, 34 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 75e4a2f012b37..978e105985293 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -135,3 +135,37 @@ value['/*completion*/`
},
})
}
+
+func TestCompletionListDigitPrefixedMemberNames(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `declare const x: { "1+sideEffect()": 0; "01": 0; 1: 0 };
+x[|./*member*/|];`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ var items []fourslash.CompletionsExpectedItem
+ for _, test := range []struct {
+ label string
+ newText string
+ }{
+ {"1+sideEffect()", "[1+sideEffect()]"},
+ {"01", "[01]"},
+ {"1", "[1]"},
+ } {
+ items = append(items, &lsproto.CompletionItem{
+ Label: test.label,
+ InsertText: new(test.newText),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: test.newText, Range: f.Ranges()[0].LSRange},
+ },
+ })
+ }
+ f.VerifyCompletions(t, "member", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{Includes: items},
+ })
+}
From 73ac3a18670191b80c498d9fe10850d48203da85 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:18:49 -0800
Subject: [PATCH 07/24] Quote digit-prefixed member names unless they are
numbers
Only names that are the canonical text of a number can be written as a
numeric literal in an element access. Inserting other names that start
with a digit produced an arbitrary expression, or accessed a different
property, as with "01" accessing property 1.
---
.../completionListInvalidMemberNames_escapeQuote_test.go | 4 ++--
tsc/internal/ls/completions.go | 3 +--
2 files changed, 3 insertions(+), 4 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 978e105985293..bc10727c5d4cc 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -148,8 +148,8 @@ x[|./*member*/|];`
label string
newText string
}{
- {"1+sideEffect()", "[1+sideEffect()]"},
- {"01", "[01]"},
+ {"1+sideEffect()", `["1+sideEffect()"]`},
+ {"01", `["01"]`},
{"1", "[1]"},
} {
items = append(items, &lsproto.CompletionItem{
diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go
index d783f957aded6..fefe75fc81373 100644
--- a/tsc/internal/ls/completions.go
+++ b/tsc/internal/ls/completions.go
@@ -3715,8 +3715,7 @@ func (l *LanguageService) createRangeFromStringLiteralLikeContent(file *ast.Sour
}
func quotePropertyName(file *ast.SourceFile, preferences lsutil.UserPreferences, name string) string {
- r, _ := utf8.DecodeRuneInString(name)
- if unicode.IsDigit(r) {
+ if len(name) > 0 && name[0] >= '0' && name[0] <= '9' && jsnum.IsNumericLiteralName(name) {
return name
}
return quote(file, preferences, name)
From 244ba96343e46b65ea545be9886976f06e145447 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:19:10 -0800
Subject: [PATCH 08/24] Add tests for quoted import and export name completions
Completions inside a quoted name in an import or export specifier list
look up the declaration instead of its module specifier, so they find
nothing. Outside quotes, a non-identifier export name starting with a
digit is inserted unquoted.
---
...ListInvalidMemberNames_escapeQuote_test.go | 30 +++++++++++++++++++
1 file changed, 30 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index bc10727c5d4cc..4721000f3009a 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -169,3 +169,33 @@ x[|./*member*/|];`
Items: &fourslash.CompletionsExpectedItems{Includes: items},
})
}
+
+func TestCompletionForQuotedImportExportNames(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @Filename: /lib.ts
+const value = 0;
+export { value as "a'b", value as "1" };
+// @Filename: /main.ts
+import { '[|/*import*/|]' as a } from "./lib";
+export { '[|/*export*/|]' } from "./lib";
+export { /*plain*/ } from "./lib";
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ f.VerifyCompletions(t, "plain", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{Label: "1", InsertText: new("1")},
+ },
+ },
+ })
+ for _, marker := range []string{"import", "export"} {
+ f.VerifyCompletions(t, marker, nil)
+ }
+}
From 851f10b9e11cd62aa6010e4df81605241c7d27c4 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:19:53 -0800
Subject: [PATCH 09/24] Fix completions in quoted import and export names
Completions inside a quoted specifier name resolved the declaration
node as if it were the module specifier and so found no exports. Names
inserted outside quotes must be quoted whenever they are not
identifiers, since a specifier name can never be a numeric literal.
---
...ListInvalidMemberNames_escapeQuote_test.go | 23 ++++++++++++++++---
tsc/internal/ls/completions.go | 2 +-
tsc/internal/ls/string_completions.go | 4 ++--
3 files changed, 23 insertions(+), 6 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 4721000f3009a..a06d149d13bf3 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -191,11 +191,28 @@ export { /*plain*/ } from "./lib";
},
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
- &lsproto.CompletionItem{Label: "1", InsertText: new("1")},
+ &lsproto.CompletionItem{Label: "1", InsertText: new(`"1"`)},
},
},
})
- for _, marker := range []string{"import", "export"} {
- f.VerifyCompletions(t, marker, nil)
+ for i, marker := range []string{"import", "export"} {
+ f.VerifyCompletions(t, marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{
+ Label: "a'b",
+ InsertText: new(`a\'b`),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: `a\'b`, Range: f.Ranges()[i].LSRange},
+ },
+ },
+ },
+ },
+ })
}
}
diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go
index fefe75fc81373..0dff9dc189b5e 100644
--- a/tsc/internal/ls/completions.go
+++ b/tsc/internal/ls/completions.go
@@ -2411,7 +2411,7 @@ func (l *LanguageService) createCompletionItem(
parentNamedImportOrExport := ast.FindAncestor(data.location, isNamedImportsOrExports)
if parentNamedImportOrExport != nil {
if !scanner.IsIdentifierText(name, core.LanguageVariantStandard) {
- insertText = quotePropertyName(file, preferences, name)
+ insertText = quote(file, preferences, name)
if parentNamedImportOrExport.Kind == ast.KindNamedImports {
// Check if it is `import { ^here as name } from '...'``.
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index 421b5e70038ae..f5913b3250a15 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -395,9 +395,9 @@ func (l *LanguageService) getStringLiteralCompletionEntries(
namedImportsOrExports := specifier.Parent
var moduleSpecifier *ast.Node
if namedImportsOrExports.Kind == ast.KindNamedImports {
- moduleSpecifier = namedImportsOrExports.Parent.Parent
+ moduleSpecifier = namedImportsOrExports.Parent.Parent.ModuleSpecifier()
} else {
- moduleSpecifier = namedImportsOrExports.Parent
+ moduleSpecifier = namedImportsOrExports.Parent.ModuleSpecifier()
}
if moduleSpecifier == nil {
return nil
From a070103315df407092b561a4c8fdbb41b54f95f5 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:20:24 -0800
Subject: [PATCH 10/24] Add tests for JSX attribute string completions
JSX attribute strings have no escape sequences, so completions escaped
as JavaScript strings insert stray backslashes into the value, and a
value containing the attribute's quote cannot be written at all.
---
...mpletionsInJsxAttributeInitializer_test.go | 44 +++++++++++++++++++
1 file changed, 44 insertions(+)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 3255d475ba49d..0258f7bd796cc 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_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/lsp/lsproto"
"github.com/microsoft/TypeScript/tsc/internal/testutil"
)
@@ -61,3 +62,46 @@ const a5 = `
},
})
}
+
+func TestStringLiteralCompletionsInJsxAttributeEscaping(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @jsx: preserve
+// @filename: /a.tsx
+declare function Foo(args: { value: "a'b&c\\z" | "a\"b" | "&" }): any;
+const a = ;
+const b = ;
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ textEdit := func(lsRange lsproto.Range, text string) *lsproto.TextEditOrInsertReplaceEdit {
+ return &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: text, Range: lsRange},
+ }
+ }
+ verify := func(marker string, items ...fourslash.CompletionsExpectedItem) {
+ f.VerifyCompletions(t, marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{Includes: items},
+ })
+ }
+ cursor := f.MarkerByName(t, "container").LSPos()
+ verify("raw", &lsproto.CompletionItem{
+ Label: `a'b&c\\z`,
+ TextEdit: textEdit(f.Ranges()[0].LSRange, `a'b&c\\z`),
+ })
+ verify("container",
+ &lsproto.CompletionItem{
+ Label: `a\"b`,
+ TextEdit: textEdit(lsproto.Range{Start: cursor, End: cursor}, `a\"b`),
+ },
+ &lsproto.CompletionItem{
+ Label: `&`,
+ TextEdit: textEdit(lsproto.Range{Start: cursor, End: cursor}, `&`),
+ },
+ )
+}
From 4969dab11c9c38830ad27a3724c07fc239183376 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:21:23 -0800
Subject: [PATCH 11/24] Insert JSX attribute string completions as they are
written
JSX attribute strings have no escape sequences, and character
references in them are decoded only during emit, so the checker and the
emitted code would see different values. Insert values literally when
the attribute string can hold them, and otherwise replace the string
with an expression container.
---
...mpletionsInJsxAttributeInitializer_test.go | 17 ++++----
tsc/internal/ls/string_completions.go | 42 ++++++++++++++++---
2 files changed, 47 insertions(+), 12 deletions(-)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 0258f7bd796cc..0f9da55dd65e0 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -89,19 +89,22 @@ const b = ;
Items: &fourslash.CompletionsExpectedItems{Includes: items},
})
}
- cursor := f.MarkerByName(t, "container").LSPos()
verify("raw", &lsproto.CompletionItem{
- Label: `a'b&c\\z`,
- TextEdit: textEdit(f.Ranges()[0].LSRange, `a'b&c\\z`),
+ Label: `a'b&c\z`,
+ TextEdit: textEdit(f.Ranges()[0].LSRange, `a'b&c\z`),
})
verify("container",
&lsproto.CompletionItem{
- Label: `a\"b`,
- TextEdit: textEdit(lsproto.Range{Start: cursor, End: cursor}, `a\"b`),
+ Label: `a"b`,
+ InsertText: new(`{"a\"b"}`),
+ FilterText: new(`"a"b`),
+ TextEdit: textEdit(f.Ranges()[1].LSRange, `{"a\"b"}`),
},
&lsproto.CompletionItem{
- Label: `&`,
- TextEdit: textEdit(lsproto.Range{Start: cursor, End: cursor}, `&`),
+ Label: `&`,
+ InsertText: new(`{"&"}`),
+ FilterText: new(`"&`),
+ TextEdit: textEdit(f.Ranges()[1].LSRange, `{"&"}`),
},
)
}
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index f5913b3250a15..29c51d3ecdcde 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -149,17 +149,38 @@ func (l *LanguageService) convertStringLiteralCompletions(
case completion.fromTypes != nil:
completion := completion.fromTypes
quoteChar := stringCompletionQuoteChar(contextToken)
- items := core.Map(completion.types, func(t *checker.StringLiteralType) *CompletionItem {
- name := printer.EscapeString(t.AsLiteralType().Value().(string), quoteChar)
+ isJsxAttribute := ast.IsJsxAttribute(contextToken.Parent)
+ items := core.MapNonNil(completion.types, func(t *checker.StringLiteralType) *CompletionItem {
+ value := t.AsLiteralType().Value().(string)
+ name := value
+ insertText := ""
+ filterText := ""
+ replacementSpan := l.getReplacementRangeForContextToken(file, contextToken, position)
+ if !isJsxAttribute {
+ name = printer.EscapeString(value, quoteChar)
+ } else if !jsxAttributeStringCanContain(value, byte(quoteChar)) {
+ // JSX attribute strings have no escape sequences, so replace the
+ // string with an expression container holding the value.
+ if ast.IsUnterminatedLiteral(contextToken) {
+ return nil
+ }
+ lspRange, fidelity := l.createLspRangeFromNode(contextToken, file)
+ if !fidelity.IsExact() {
+ return nil
+ }
+ replacementSpan = &lspRange
+ insertText = "{" + quote(file, l.UserPreferences(), value) + "}"
+ filterText = string(quoteChar) + value
+ }
lspItem := l.createLSPCompletionItem(
ctx,
name,
- "", /*insertText*/
- "", /*filterText*/
+ insertText,
+ filterText,
SortTextLocationPriority,
lsutil.ScriptElementKindString,
lsutil.ScriptElementKindModifierNone,
- l.getReplacementRangeForContextToken(file, contextToken, position),
+ replacementSpan,
nil, /*commitCharacters*/
nil, /*labelDetails*/
file,
@@ -196,6 +217,17 @@ func (l *LanguageService) convertStringLiteralCompletions(
}
}
+// JSX attribute strings have no escape sequences and their character references
+// are decoded only during emit, so values containing the quote character or a
+// possible character reference must be written as an expression instead.
+func jsxAttributeStringCanContain(value string, quoteChar byte) bool {
+ if strings.IndexByte(value, quoteChar) >= 0 {
+ return false
+ }
+ amp := strings.IndexByte(value, '&')
+ return amp < 0 || strings.IndexByte(value[amp:], ';') < 0
+}
+
func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.QuoteChar {
if contextToken.Kind == ast.KindNoSubstitutionTemplateLiteral {
return printer.QuoteCharBacktick
From d356ea8514f7f3c3a20332fd38ba33a394855148 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:21:45 -0800
Subject: [PATCH 12/24] Add tests for literal completions in JSX attribute
initializers
Literal completions directly after the equals sign of a JSX attribute
are inserted as JavaScript literals, which are not valid JSX attribute
values when they are numbers or contain escape sequences.
---
...mpletionsInJsxAttributeInitializer_test.go | 36 +++++++++++++++++++
1 file changed, 36 insertions(+)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 0f9da55dd65e0..9d76ac56d6503 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -108,3 +108,39 @@ const b = ;
},
)
}
+
+func TestJsxAttributeInitializerLiteralCompletions(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @jsx: preserve
+// @filename: /a.tsx
+declare function Foo(args: { value: "a'b&c\\z" | "a\"b" | "&"; count: 1 }): any;
+const a = ;
+const b = ;
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ for _, test := range []struct {
+ marker string
+ label string
+ insertText string
+ }{
+ {"value", `"a'b&c\\z"`, ""},
+ {"value", `"a\"b"`, ""},
+ {"value", `"&"`, ""},
+ {"count", "1", ""},
+ } {
+ item := &lsproto.CompletionItem{Label: test.label, CommitCharacters: &[]string{}}
+ if test.insertText != "" {
+ item.InsertText = &test.insertText
+ }
+ f.VerifyCompletions(t, test.marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{Includes: []fourslash.CompletionsExpectedItem{item}},
+ })
+ }
+}
From 9b6ad34f375d51d8535fcb3d63b70beabb4e4818 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:23:01 -0800
Subject: [PATCH 13/24] Insert JSX-valid literals in JSX attribute initializers
Literals completed directly after the equals sign of a JSX attribute
must be valid attribute values. Write strings with whichever quote can
hold them literally, falling back to an expression container, and wrap
other literals in an expression container.
---
...alCompletionsInJsxAttributeInitializer_test.go | 8 ++++----
tsc/internal/ls/completions.go | 15 +++++++++++++--
tsc/internal/ls/string_completions.go | 13 +++++++++++++
3 files changed, 30 insertions(+), 6 deletions(-)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 9d76ac56d6503..62e673ddb0ec4 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -125,10 +125,10 @@ const b = ;
label string
insertText string
}{
- {"value", `"a'b&c\\z"`, ""},
- {"value", `"a\"b"`, ""},
- {"value", `"&"`, ""},
- {"count", "1", ""},
+ {"value", `"a'b&c\\z"`, `"a'b&c\z"`},
+ {"value", `"a\"b"`, `'a"b'`},
+ {"value", `"&"`, `{"&"}`},
+ {"count", "1", "{1}"},
} {
item := &lsproto.CompletionItem{Label: test.label, CommitCharacters: &[]string{}}
if test.insertText != "" {
diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go
index 0dff9dc189b5e..a39b25f4e3fff 100644
--- a/tsc/internal/ls/completions.go
+++ b/tsc/internal/ls/completions.go
@@ -1901,7 +1901,7 @@ func (l *LanguageService) completionInfoFromData(
}
for _, literal := range literals {
- literalEntry := createCompletionItemForLiteral(file, preferences, literal)
+ literalEntry := createCompletionItemForLiteral(file, preferences, literal, data.jsxInitializer.isInitializer)
uniqueNames.Add(literalEntry.Label)
sortedEntries = append(sortedEntries, &CompletionItem{CompletionItem: literalEntry})
}
@@ -2168,13 +2168,24 @@ func createCompletionItemForLiteral(
file *ast.SourceFile,
preferences lsutil.UserPreferences,
literal literalValue,
+ isJsxInitializer bool,
) *lsproto.CompletionItem {
- return &lsproto.CompletionItem{
+ item := &lsproto.CompletionItem{
Label: completionNameForLiteral(file, preferences, literal),
Kind: new(lsproto.CompletionItemKindConstant),
SortText: new(string(SortTextLocationPriority)),
CommitCharacters: new([]string{}),
}
+ if isJsxInitializer {
+ insertText := "{" + item.Label + "}"
+ if value, ok := literal.(string); ok {
+ insertText = jsxAttributeInitializerText(file, preferences, value)
+ }
+ if insertText != item.Label {
+ item.InsertText = &insertText
+ }
+ }
+ return item
}
func (l *LanguageService) createCompletionItem(
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index 29c51d3ecdcde..800f72646ddf7 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -228,6 +228,19 @@ func jsxAttributeStringCanContain(value string, quoteChar byte) bool {
return amp < 0 || strings.IndexByte(value[amp:], ';') < 0
}
+func jsxAttributeInitializerText(file *ast.SourceFile, preferences lsutil.UserPreferences, value string) string {
+ quoteChar, otherQuoteChar := byte('"'), byte('\'')
+ if lsutil.GetQuotePreference(file, preferences) == lsutil.QuotePreferenceSingle {
+ quoteChar, otherQuoteChar = otherQuoteChar, quoteChar
+ }
+ for _, q := range []byte{quoteChar, otherQuoteChar} {
+ if jsxAttributeStringCanContain(value, q) {
+ return string(q) + value + string(q)
+ }
+ }
+ return "{" + quote(file, preferences, value) + "}"
+}
+
func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.QuoteChar {
if contextToken.Kind == ast.KindNoSubstitutionTemplateLiteral {
return printer.QuoteCharBacktick
From 4eb2493a72f7ed201abd7a53659d914b6451a608 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:23:35 -0800
Subject: [PATCH 14/24] Enable test for partially typed JSX attribute values
After an identifier following the equals sign of a JSX attribute,
completions do not know they are completing the attribute's value, so
they insert bare names that are not valid JSX and leave the identifier
in place.
---
.../completionsJsxAttributeInitializer2_test.go | 14 +++-----------
1 file changed, 3 insertions(+), 11 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go b/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
index 159e49f6521fc..aea448abc56f9 100644
--- a/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
+++ b/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
@@ -10,7 +10,6 @@ import (
)
func TestCompletionsJsxAttributeInitializer2(t *testing.T) {
- t.Skip("Known failing fourslash test")
t.Parallel()
defer testutil.RecoverAndFail(t, "Panic on fourslash test")
const content = `// @Filename: /a.tsx
@@ -35,16 +34,9 @@ const foo = 0;
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
- Label: "foo",
- InsertText: new("{foo}"),
- Detail: new("const foo: 0"),
- Kind: new(lsproto.CompletionItemKindVariable),
- TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
- TextEdit: &lsproto.TextEdit{
- NewText: "{foo}",
- Range: f.Ranges()[0].LSRange,
- },
- },
+ Label: "foo",
+ Detail: new("const foo: 0"),
+ Kind: new(lsproto.CompletionItemKindVariable),
},
},
},
From 795d6e2d35d8410fe31a8884d9c491269db3a1cf Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:24:21 -0800
Subject: [PATCH 15/24] Treat partially typed JSX attribute values as
initializers
After an identifier following the equals sign, completions did not know
they were completing an attribute value, so they inserted bare names and
literals that are not valid JSX, and did not replace the identifier.
---
.../completionsJsxAttributeInitializer2_test.go | 13 ++++++++++---
tsc/internal/ls/completions.go | 1 +
2 files changed, 11 insertions(+), 3 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go b/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
index aea448abc56f9..1f231a25d2884 100644
--- a/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
+++ b/tsc/internal/fourslash/tests/completionsJsxAttributeInitializer2_test.go
@@ -34,9 +34,16 @@ const foo = 0;
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
- Label: "foo",
- Detail: new("const foo: 0"),
- Kind: new(lsproto.CompletionItemKindVariable),
+ Label: "foo",
+ InsertText: new("{foo}"),
+ Detail: new("const foo: 0"),
+ Kind: new(lsproto.CompletionItemKindVariable),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{
+ NewText: "{foo}",
+ Range: f.Ranges()[0].LSRange,
+ },
+ },
},
},
},
diff --git a/tsc/internal/ls/completions.go b/tsc/internal/ls/completions.go
index a39b25f4e3fff..9affd8602168a 100644
--- a/tsc/internal/ls/completions.go
+++ b/tsc/internal/ls/completions.go
@@ -769,6 +769,7 @@ func (l *LanguageService) getCompletionData(
if parent != previousToken.Parent &&
parent.Initializer() == nil &&
astnav.FindChildOfKind(parent, ast.KindEqualsToken, file) != nil {
+ jsxInitializer.isInitializer = true
jsxInitializer.initializer = previousToken
}
}
From 3815cbe028a96d11af1379599595ad8cda296f03 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:25:05 -0800
Subject: [PATCH 16/24] Add tests for path completions after escaped directory
names
The replacement range for a module path completion is measured in the
string's value, which is shorter than its source text when an earlier
segment contains an escape sequence, so the edit lands on the wrong
characters.
---
...ionForStringLiteralRelativeImport4_test.go | 49 +++++++++++++++++++
1 file changed, 49 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index 76e8a85a59185..d74578fd302c5 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -117,3 +117,52 @@ export {};
})
}
}
+
+func TestPathCompletionEscapedDirectory(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @Filename: /src/main.ts
+import "./a\"b/c/*escaped*/";
+import "./\u0061\x2fc/*escapedSeparator*/";
+// @Filename: /src/a"b/cd.ts
+export {};
+// @Filename: /src/a/cd.ts
+export {};
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ for _, test := range []struct {
+ marker string
+ // Character offset of the replaced text; the "c" is at 15 and 20 respectively.
+ character uint32
+ }{
+ {"escaped", 14},
+ {"escapedSeparator", 12},
+ } {
+ line := f.MarkerByName(t, test.marker).LSPos().Line
+ f.VerifyCompletions(t, test.marker, &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &[]string{},
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{
+ Label: "cd",
+ Detail: new("cd.ts"),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{
+ NewText: "cd",
+ Range: lsproto.Range{
+ Start: lsproto.Position{Line: line, Character: test.character},
+ End: lsproto.Position{Line: line, Character: test.character + 1},
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+ }
+}
From f3336b8dab78fbe35ac920be01f76cde6e290c76 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:25:56 -0800
Subject: [PATCH 17/24] Measure path completion ranges in source text
When an earlier segment of a module specifier contains an escape
sequence, its value is shorter than its source text, so a range measured
in the value lands on the wrong characters.
---
...ionForStringLiteralRelativeImport4_test.go | 4 +-
tsc/internal/ls/string_completions.go | 41 ++++++++++++++++++-
2 files changed, 41 insertions(+), 4 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index d74578fd302c5..eec7f5df4432f 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -136,8 +136,8 @@ export {};
// Character offset of the replaced text; the "c" is at 15 and 20 respectively.
character uint32
}{
- {"escaped", 14},
- {"escapedSeparator", 12},
+ {"escaped", 15},
+ {"escapedSeparator", 20},
} {
line := f.MarkerByName(t, test.marker).LSPos().Line
f.VerifyCompletions(t, test.marker, &fourslash.CompletionsExpectedList{
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index 800f72646ddf7..b25c552401b99 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -646,8 +646,7 @@ func (l *LanguageService) getStringLiteralCompletionsFromModuleNames(
program *compiler.Program,
checker *checker.Checker,
) *stringLiteralCompletions {
- textStart := astnav.GetStartOfNode(node, file, false /*includeJSDoc*/) + 1
- replacementSpan, ok := l.pathCompletionReplacementSpan(file, getDirectoryFragmentRange(node.Text(), textStart))
+ replacementSpan, ok := l.pathCompletionReplacementSpan(file, getDirectoryFragmentRangeOfLiteral(file, node))
if !ok {
return nil
}
@@ -716,6 +715,44 @@ func getDirectoryFragmentRange(text string, textStart int) *core.TextRange {
return new(core.NewTextRange(textStart+offset, textStart+offset+length))
}
+// Like getDirectoryFragmentRange, but measures the fragment in the source text
+// of a string literal, whose escape sequences may differ in length from their values.
+func getDirectoryFragmentRangeOfLiteral(file *ast.SourceFile, node *ast.LiteralExpression) *core.TextRange {
+ start := astnav.GetStartOfNode(node, file, false /*includeJSDoc*/)
+ end := node.End()
+ if !ast.IsUnterminatedLiteral(node) {
+ end--
+ }
+ rawText := file.Text()[start+1 : max(start+1, end)]
+ text := node.Text()
+ if rawText == text {
+ return getDirectoryFragmentRange(text, start+1)
+ }
+ index := strings.LastIndexFunc(text, isAnyDirectorySeparator)
+ offset := 0
+ if index != -1 {
+ // Find the shortest source prefix whose value ends at the last separator.
+ quote := file.Text()[start : start+1]
+ s := scanner.NewScanner()
+ offset = -1
+ for i := index + 1; i <= len(rawText); i++ {
+ s.SetText(quote + rawText[:i] + quote)
+ s.Scan()
+ if s.TokenValue() == text[:index+1] {
+ offset = i
+ break
+ }
+ }
+ if offset == -1 {
+ return nil
+ }
+ }
+ if offset == len(rawText) {
+ return nil
+ }
+ return new(core.NewTextRange(start+1+offset, start+1+len(rawText)))
+}
+
func (l *LanguageService) getStringLiteralCompletionsFromModuleNamesWorker(
file *ast.SourceFile,
node *ast.LiteralExpression,
From 9ddba5a3a5a5650355e0253ee210d7cda23ad98c Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:26:21 -0800
Subject: [PATCH 18/24] Add tests for quotes in triple-slash reference
completions
Triple-slash directives cannot escape their quote character, so
offering a file name containing it inserts a reference to a different
path.
---
...ionForStringLiteralRelativeImport4_test.go | 24 +++++++++++++++++++
1 file changed, 24 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index eec7f5df4432f..c8426ed7abd71 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -166,3 +166,27 @@ export {};
})
}
}
+
+func TestTripleSlashReferenceCompletionQuotes(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @Filename: /src/main.ts
+///
+// @Filename: /src/a"b.ts
+export {};
+// @Filename: /src/a'b.ts
+export {};
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ f.VerifyCompletions(t, "reference", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &[]string{},
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{"a'b.ts", `a"b.ts`},
+ },
+ })
+}
From 4d3019385a80764fcaa679695de9a86b3e127ad8 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 09:26:43 -0800
Subject: [PATCH 19/24] Omit unrepresentable triple-slash reference completions
Triple-slash directives cannot escape their quote character, so file
names containing it cannot be referenced and must not be offered.
---
.../tests/completionForStringLiteralRelativeImport4_test.go | 3 ++-
tsc/internal/ls/string_completions.go | 5 +++++
2 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index c8426ed7abd71..6afc9ff8f91f4 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -186,7 +186,8 @@ export {};
EditRange: Ignored,
},
Items: &fourslash.CompletionsExpectedItems{
- Includes: []fourslash.CompletionsExpectedItem{"a'b.ts", `a"b.ts`},
+ Includes: []fourslash.CompletionsExpectedItem{"a'b.ts"},
+ Excludes: []string{`a"b.ts`},
},
})
}
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index b25c552401b99..156448ebd4770 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -2354,6 +2354,11 @@ func (l *LanguageService) getTripleSlashReferenceCompletions(
l.getCompletionEntriesFromTypings(program, scriptDirectory, getFragmentDirectory(toComplete), extensionOptions, result)
names = slices.Collect(maps.Values(result.names))
}
+ // Triple-slash directive values cannot contain their own quote character.
+ quoteChar := prefix[len(prefix)-1]
+ names = slices.DeleteFunc(names, func(name moduleCompletionNameAndKind) bool {
+ return strings.IndexByte(name.name, quoteChar) >= 0
+ })
return &pathCompletions{
entries: toPathCompletions(names),
From 1734c6aaeabb28fe198b84cb4f25200e7cb2bb35 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:00:53 -0800
Subject: [PATCH 20/24] Add tests for lone surrogates in JSX attribute
completions
JSX attribute strings cannot escape a lone surrogate, and one inserted
as raw text cannot survive LSP serialization, so the completion inserts
replacement characters instead of the selected value.
---
...mpletionsInJsxAttributeInitializer_test.go | 50 +++++++++++++++++++
1 file changed, 50 insertions(+)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 62e673ddb0ec4..bea41c0025a3d 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -144,3 +144,53 @@ const b = ;
})
}
}
+
+func TestJsxAttributeCompletionLoneSurrogate(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `// @jsx: preserve
+// @filename: /a.tsx
+declare function Foo(args: { value: "\uD800" }): any;
+const a = ;
+const b = ;
+`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ // A lone surrogate cannot be sent over LSP, so raw text containing one
+ // arrives as replacement characters.
+ const replaced = "\uFFFD\uFFFD\uFFFD"
+ cursor := f.MarkerByName(t, "quoted").LSPos()
+ f.VerifyCompletions(t, "quoted", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Exact: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{
+ Label: replaced,
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{NewText: replaced, Range: lsproto.Range{Start: cursor, End: cursor}},
+ },
+ },
+ },
+ },
+ })
+ f.VerifyCompletions(t, "initializer", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{
+ Label: `"` + replaced + `"`,
+ InsertText: new(`"` + replaced + `"`),
+ CommitCharacters: &[]string{},
+ },
+ },
+ },
+ })
+}
From bb07fa3a3db213dbb20be9dfd4af31037492912a Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:01:50 -0800
Subject: [PATCH 21/24] Escape lone surrogates in JSX attribute completions
A lone surrogate cannot be written in a JSX attribute string and cannot
survive LSP serialization as raw text, so use an expression container
with an escaped string literal for such values.
---
...mpletionsInJsxAttributeInitializer_test.go | 9 +++---
tsc/internal/ls/string_completions.go | 31 +++++++++++++++----
2 files changed, 30 insertions(+), 10 deletions(-)
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index bea41c0025a3d..966bb17c29d3d 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -159,7 +159,6 @@ const b = ;
// A lone surrogate cannot be sent over LSP, so raw text containing one
// arrives as replacement characters.
const replaced = "\uFFFD\uFFFD\uFFFD"
- cursor := f.MarkerByName(t, "quoted").LSPos()
f.VerifyCompletions(t, "quoted", &fourslash.CompletionsExpectedList{
IsIncomplete: false,
ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
@@ -169,9 +168,11 @@ const b = ;
Items: &fourslash.CompletionsExpectedItems{
Exact: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
- Label: replaced,
+ Label: replaced,
+ InsertText: new(`{"\uD800"}`),
+ FilterText: new(`"` + replaced),
TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
- TextEdit: &lsproto.TextEdit{NewText: replaced, Range: lsproto.Range{Start: cursor, End: cursor}},
+ TextEdit: &lsproto.TextEdit{NewText: `{"\uD800"}`, Range: f.Ranges()[0].LSRange},
},
},
},
@@ -187,7 +188,7 @@ const b = ;
Includes: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
Label: `"` + replaced + `"`,
- InsertText: new(`"` + replaced + `"`),
+ InsertText: new(`{"\uD800"}`),
CommitCharacters: &[]string{},
},
},
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index 156448ebd4770..76c44ba01cb26 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -8,6 +8,7 @@ import (
"maps"
"slices"
"strings"
+ "unicode/utf8"
"github.com/microsoft/TypeScript/tsc/internal/ast"
"github.com/microsoft/TypeScript/tsc/internal/astnav"
@@ -169,7 +170,7 @@ func (l *LanguageService) convertStringLiteralCompletions(
return nil
}
replacementSpan = &lspRange
- insertText = "{" + quote(file, l.UserPreferences(), value) + "}"
+ insertText = jsxExpressionContainerText(file, l.UserPreferences(), value)
filterText = string(quoteChar) + value
}
lspItem := l.createLSPCompletionItem(
@@ -218,14 +219,32 @@ func (l *LanguageService) convertStringLiteralCompletions(
}
// JSX attribute strings have no escape sequences and their character references
-// are decoded only during emit, so values containing the quote character or a
-// possible character reference must be written as an expression instead.
+// are decoded only during emit, so values containing the quote character, a
+// possible character reference, or a lone surrogate must be written as an
+// expression instead.
func jsxAttributeStringCanContain(value string, quoteChar byte) bool {
if strings.IndexByte(value, quoteChar) >= 0 {
return false
}
- amp := strings.IndexByte(value, '&')
- return amp < 0 || strings.IndexByte(value[amp:], ';') < 0
+ if amp := strings.IndexByte(value, '&'); amp >= 0 && strings.IndexByte(value[amp:], ';') >= 0 {
+ return false
+ }
+ for i := 0; i < len(value); {
+ ch, size := stringutil.DecodeJSStringRune(value[i:])
+ if stringutil.IsSurrogate(ch) || ch == utf8.RuneError && size == 1 {
+ return false
+ }
+ i += size
+ }
+ return true
+}
+
+func jsxExpressionContainerText(file *ast.SourceFile, preferences lsutil.UserPreferences, value string) string {
+ quoteChar := printer.QuoteCharDoubleQuote
+ if lsutil.GetQuotePreference(file, preferences) == lsutil.QuotePreferenceSingle {
+ quoteChar = printer.QuoteCharSingleQuote
+ }
+ return "{" + string(quoteChar) + printer.EscapeString(value, quoteChar) + string(quoteChar) + "}"
}
func jsxAttributeInitializerText(file *ast.SourceFile, preferences lsutil.UserPreferences, value string) string {
@@ -238,7 +257,7 @@ func jsxAttributeInitializerText(file *ast.SourceFile, preferences lsutil.UserPr
return string(q) + value + string(q)
}
}
- return "{" + quote(file, preferences, value) + "}"
+ return jsxExpressionContainerText(file, preferences, value)
}
func stringCompletionQuoteChar(contextToken *ast.StringLiteralLike) printer.QuoteChar {
From 66e945bfd3ba3ff820bdeea2a2ec38b4f2beb8f9 Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:01:50 -0800
Subject: [PATCH 22/24] Find path completion source offsets in a single pass
Rescanning every source prefix of a module specifier made computing
the replacement range quadratic in the specifier's length. Walk its
escape sequences once with the scanner's own decoding instead,
including the CR and CRLF to LF normalization of template literals.
---
...ionForStringLiteralRelativeImport4_test.go | 35 +++++++++++++++++++
tsc/internal/ls/string_completions.go | 13 +------
tsc/internal/scanner/scanner.go | 29 +++++++++++++++
3 files changed, 65 insertions(+), 12 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
index 6afc9ff8f91f4..057e060a72567 100644
--- a/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
+++ b/tsc/internal/fourslash/tests/completionForStringLiteralRelativeImport4_test.go
@@ -191,3 +191,38 @@ export {};
},
})
}
+
+func TestPathCompletionEscapedTemplate(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = "// @Filename: /src/main.ts\n" +
+ "import(`./\\x61/c/*template*/`);\n" +
+ "// @Filename: /src/a/cd.ts\n" +
+ "export {};\n"
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ f.VerifyCompletions(t, "template", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &[]string{},
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{
+ Label: "cd",
+ Detail: new("cd.ts"),
+ TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
+ TextEdit: &lsproto.TextEdit{
+ NewText: "cd",
+ Range: lsproto.Range{
+ Start: lsproto.Position{Line: 0, Character: 15},
+ End: lsproto.Position{Line: 0, Character: 16},
+ },
+ },
+ },
+ },
+ },
+ },
+ })
+}
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index 76c44ba01cb26..ec2a6d94f4eb1 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -750,18 +750,7 @@ func getDirectoryFragmentRangeOfLiteral(file *ast.SourceFile, node *ast.LiteralE
index := strings.LastIndexFunc(text, isAnyDirectorySeparator)
offset := 0
if index != -1 {
- // Find the shortest source prefix whose value ends at the last separator.
- quote := file.Text()[start : start+1]
- s := scanner.NewScanner()
- offset = -1
- for i := index + 1; i <= len(rawText); i++ {
- s.SetText(quote + rawText[:i] + quote)
- s.Scan()
- if s.TokenValue() == text[:index+1] {
- offset = i
- break
- }
- }
+ offset = scanner.GetStringLiteralSourceOffset(rawText, index+1, node.Kind == ast.KindNoSubstitutionTemplateLiteral)
if offset == -1 {
return nil
}
diff --git a/tsc/internal/scanner/scanner.go b/tsc/internal/scanner/scanner.go
index a59637584e2c5..273cbae5b02a3 100644
--- a/tsc/internal/scanner/scanner.go
+++ b/tsc/internal/scanner/scanner.go
@@ -2555,6 +2555,35 @@ func GetShebang(text string) string {
return text[:end]
}
+// GetStringLiteralSourceOffset returns the offset in contents, the source text
+// between the delimiters of a string or no-substitution template literal, at
+// which the first valueOffset bytes of the literal's value end. It returns -1
+// if that point is inside an escape sequence or past the end of the value.
+func GetStringLiteralSourceOffset(contents string, valueOffset int, isTemplate bool) int {
+ s := NewScanner()
+ s.SetText(contents)
+ value := 0
+ for value < valueOffset && s.pos < len(contents) {
+ if contents[s.pos] == '\\' {
+ value += len(s.scanEscapeSequence(EscapeSequenceScanningFlagsString | EscapeSequenceScanningFlagsReportErrors))
+ } else if isTemplate && contents[s.pos] == '\r' {
+ // Template values normalize CR and CRLF to LF.
+ s.pos++
+ if s.char() == '\n' {
+ s.pos++
+ }
+ value++
+ } else {
+ s.pos++
+ value++
+ }
+ }
+ if value != valueOffset {
+ return -1
+ }
+ return s.pos
+}
+
func GetScannerForSourceFile(sourceFile *ast.SourceFile, pos int) *Scanner {
s := NewScanner()
s.text = sourceFile.Text()
From df8ac04f840bfbd465783c091239e27c4dc4ef4a Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:18:34 -0800
Subject: [PATCH 23/24] Add tests for lone surrogates in literal completion
labels
Completions quote string values with a JSON encoder that replaces a
lone surrogate with replacement characters, where JSON.stringify would
write an escape sequence, so both the label and the inserted literal
lose the value.
---
...ListInvalidMemberNames_escapeQuote_test.go | 21 +++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index a06d149d13bf3..5736e7fb6f29c 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -216,3 +216,24 @@ export { /*plain*/ } from "./lib";
})
}
}
+
+func TestLiteralCompletionLoneSurrogate(t *testing.T) {
+ t.Parallel()
+ defer testutil.RecoverAndFail(t, "Panic on fourslash test")
+ const content = `declare function f(x: "\uD800"): void;
+f(/*argument*/);`
+ f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
+ defer done()
+ f.VerifyCompletions(t, "argument", &fourslash.CompletionsExpectedList{
+ IsIncomplete: false,
+ ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
+ CommitCharacters: &DefaultCommitCharacters,
+ EditRange: Ignored,
+ },
+ Items: &fourslash.CompletionsExpectedItems{
+ Includes: []fourslash.CompletionsExpectedItem{
+ &lsproto.CompletionItem{Label: "\"\uFFFD\uFFFD\uFFFD\"", CommitCharacters: &[]string{}},
+ },
+ },
+ })
+}
From c1a4505dbbc443437f08b02977e08d83a32407fd Mon Sep 17 00:00:00 2001
From: Jake Bailey <5341706+jakebailey@users.noreply.github.com>
Date: Fri, 20 Nov 2026 10:20:19 -0800
Subject: [PATCH 24/24] Escape lone surrogates when quoting completion text
JSON and LSP cannot carry a lone surrogate as raw text, so write one as
an escape sequence the way JSON.stringify does, both in quoted completion
text and in the labels of JSX attribute string completions.
---
...ListInvalidMemberNames_escapeQuote_test.go | 2 +-
...mpletionsInJsxAttributeInitializer_test.go | 9 +++----
tsc/internal/ls/string_completions.go | 4 ++--
tsc/internal/ls/utilities.go | 24 ++++++++++++++++++-
4 files changed, 29 insertions(+), 10 deletions(-)
diff --git a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
index 5736e7fb6f29c..db38662ac299d 100644
--- a/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
+++ b/tsc/internal/fourslash/tests/completionListInvalidMemberNames_escapeQuote_test.go
@@ -232,7 +232,7 @@ f(/*argument*/);`
},
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
- &lsproto.CompletionItem{Label: "\"\uFFFD\uFFFD\uFFFD\"", CommitCharacters: &[]string{}},
+ &lsproto.CompletionItem{Label: `"\ud800"`, CommitCharacters: &[]string{}},
},
},
})
diff --git a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
index 966bb17c29d3d..60121e38d1f0e 100644
--- a/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
+++ b/tsc/internal/fourslash/tests/stringLiteralCompletionsInJsxAttributeInitializer_test.go
@@ -156,9 +156,6 @@ const b = ;
`
f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content)
defer done()
- // A lone surrogate cannot be sent over LSP, so raw text containing one
- // arrives as replacement characters.
- const replaced = "\uFFFD\uFFFD\uFFFD"
f.VerifyCompletions(t, "quoted", &fourslash.CompletionsExpectedList{
IsIncomplete: false,
ItemDefaults: &fourslash.CompletionsExpectedItemDefaults{
@@ -168,9 +165,9 @@ const b = ;
Items: &fourslash.CompletionsExpectedItems{
Exact: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
- Label: replaced,
+ Label: `\ud800`,
InsertText: new(`{"\uD800"}`),
- FilterText: new(`"` + replaced),
+ FilterText: new(`"\ud800`),
TextEdit: &lsproto.TextEditOrInsertReplaceEdit{
TextEdit: &lsproto.TextEdit{NewText: `{"\uD800"}`, Range: f.Ranges()[0].LSRange},
},
@@ -187,7 +184,7 @@ const b = ;
Items: &fourslash.CompletionsExpectedItems{
Includes: []fourslash.CompletionsExpectedItem{
&lsproto.CompletionItem{
- Label: `"` + replaced + `"`,
+ Label: `"\ud800"`,
InsertText: new(`{"\uD800"}`),
CommitCharacters: &[]string{},
},
diff --git a/tsc/internal/ls/string_completions.go b/tsc/internal/ls/string_completions.go
index ec2a6d94f4eb1..aa9b9a8b193c7 100644
--- a/tsc/internal/ls/string_completions.go
+++ b/tsc/internal/ls/string_completions.go
@@ -153,7 +153,7 @@ func (l *LanguageService) convertStringLiteralCompletions(
isJsxAttribute := ast.IsJsxAttribute(contextToken.Parent)
items := core.MapNonNil(completion.types, func(t *checker.StringLiteralType) *CompletionItem {
value := t.AsLiteralType().Value().(string)
- name := value
+ name := mapLoneSurrogates(value, func(s string) string { return s })
insertText := ""
filterText := ""
replacementSpan := l.getReplacementRangeForContextToken(file, contextToken, position)
@@ -171,7 +171,7 @@ func (l *LanguageService) convertStringLiteralCompletions(
}
replacementSpan = &lspRange
insertText = jsxExpressionContainerText(file, l.UserPreferences(), value)
- filterText = string(quoteChar) + value
+ filterText = string(quoteChar) + name
}
lspItem := l.createLSPCompletionItem(
ctx,
diff --git a/tsc/internal/ls/utilities.go b/tsc/internal/ls/utilities.go
index f8a73f0f1eabb..c05dc839784d3 100644
--- a/tsc/internal/ls/utilities.go
+++ b/tsc/internal/ls/utilities.go
@@ -312,13 +312,35 @@ 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, _ := core.StringifyJson(text, "" /*prefix*/, "" /*indent*/)
+ quoted := `"` + mapLoneSurrogates(text, func(s string) string {
+ quoted, _ := core.StringifyJson(s, "" /*prefix*/, "" /*indent*/)
+ return stringutil.StripQuotes(quoted)
+ }) + `"`
if quotePreference == lsutil.QuotePreferenceSingle {
quoted = "'" + quoteReplacer.Replace(stringutil.StripQuotes(quoted)) + "'"
}
return quoted
}
+// mapLoneSurrogates applies f to the text between the lone surrogates in s and
+// writes each lone surrogate as a \uXXXX escape, as JSON.stringify does, since
+// neither JSON nor LSP can carry one as raw text.
+func mapLoneSurrogates(s string, f func(string) string) string {
+ var b strings.Builder
+ start := 0
+ for i := 0; i < len(s); {
+ ch, size := stringutil.DecodeJSStringRune(s[i:])
+ if stringutil.IsSurrogate(ch) {
+ b.WriteString(f(s[start:i]))
+ fmt.Fprintf(&b, `\u%04x`, ch)
+ start = i + size
+ }
+ i += size
+ }
+ b.WriteString(f(s[start:]))
+ return b.String()
+}
+
var typeKeywords *collections.Set[ast.Kind] = collections.NewSetFromItems(
ast.KindAnyKeyword,
ast.KindAssertsKeyword,