From 50c04b47cc9978e8ce71aeae24f9f0e11d835f2f Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:57:00 -0800 Subject: [PATCH 1/2] Respect Unicode boundaries when scanning symbol references Reference prefilters must classify neighboring Unicode code points, not UTF-8 bytes, so editor recovery does not drop real symbol uses. Substring matches also need their container's source offset; otherwise the first reference can be skipped or a local search can escape its scope. Keep imports and reference spans for Unicode-adjacent uses without matching parts of longer identifiers. --- tsc/internal/checker/services.go | 16 +++-- ...referenceScanningUnicodeBoundaries_test.go | 60 ++++++++++++++++ tsc/internal/ls/findallreferences.go | 16 +++-- ...urrencesOfAnonymousFunction.baseline.jsonc | 4 +- ...ertyDeclaration_inheritance.baseline.jsonc | 4 +- ...WithLeadingUnderscoreNames8.baseline.jsonc | 6 +- ...WithLeadingUnderscoreNames9.baseline.jsonc | 6 +- ...ceScanningUnicodeBoundaries.baseline.jsonc | 72 +++++++++++++++++++ .../processInvalidSyntax1.baseline.jsonc | 5 +- ...ceScanningUnicodeBoundaries.baseline.jsonc | 12 ++++ 10 files changed, 179 insertions(+), 22 deletions(-) create mode 100644 tsc/internal/fourslash/tests/referenceScanningUnicodeBoundaries_test.go create mode 100644 tsc/testdata/baselines/reference/fourslash/findAllReferences/referenceScanningUnicodeBoundaries.baseline.jsonc create mode 100644 tsc/testdata/baselines/reference/fourslash/findRenameLocations/referenceScanningUnicodeBoundaries.baseline.jsonc diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index 24cd180cb3e84..c36e96ee0040a 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -3,6 +3,7 @@ package checker import ( "slices" "strings" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -669,15 +670,20 @@ func getPossibleSymbolReferencePositions(sourceFile *ast.SourceFile, symbolName container = sourceFile.AsNode() } - position := strings.Index(text[container.Pos():], symbolName) + foundIndex := strings.Index(text[container.Pos():], symbolName) + if foundIndex == -1 { + return positions + } + position := container.Pos() + foundIndex endPos := container.End() for position >= 0 && position < endPos { - // We found a match. Make sure it's not part of a larger word (i.e. the char - // before and after it have to be a non-identifier char). + // We found a match. Make sure the runes before and after it are not identifier parts. endPosition := position + symbolNameLength + before, _ := utf8.DecodeLastRuneInString(text[:position]) + after, _ := utf8.DecodeRuneInString(text[endPosition:]) - if (position == 0 || !scanner.IsIdentifierPart(rune(text[position-1]))) && - (endPosition == sourceLength || !scanner.IsIdentifierPart(rune(text[endPosition]))) { + if (position == 0 || !scanner.IsIdentifierPart(before)) && + (endPosition == sourceLength || !scanner.IsIdentifierPart(after)) { // Found a real match. Keep searching. positions = append(positions, position) } diff --git a/tsc/internal/fourslash/tests/referenceScanningUnicodeBoundaries_test.go b/tsc/internal/fourslash/tests/referenceScanningUnicodeBoundaries_test.go new file mode 100644 index 0000000000000..dc20e58ac1c19 --- /dev/null +++ b/tsc/internal/fourslash/tests/referenceScanningUnicodeBoundaries_test.go @@ -0,0 +1,60 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/TypeScript/tsc/internal/fourslash" + "github.com/microsoft/TypeScript/tsc/internal/lsp/lsproto" + "github.com/microsoft/TypeScript/tsc/internal/testutil" +) + +func TestReferenceScanningUnicodeBoundaries(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `const padding = 0; +function example() { + const /*declaration*/obj = {}; + /*before*/obj¬; + ☺/*after*/obj; +  /*whitespace*/obj ; + const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; + éobj; objé; 𐐀obj; obj𐐀; obj́; + /*last*/obj; +}` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyBaselineFindAllReferences(t, "declaration", "before", "after", "whitespace", "last") + f.VerifyBaselineRename(t, nil /*preferences*/, "declaration") +} + +func TestOrganizeImportsUnicodeReferenceBoundaries(t *testing.T) { + t.Parallel() + for _, tt := range []struct { + name string + use string + used bool + }{ + {name: "following nonidentifier", use: "obj¬;", used: true}, + {name: "preceding nonidentifier", use: "¬obj;", used: true}, + {name: "preceding three-byte nonidentifier", use: "☺obj;", used: true}, + {name: "supplementary nonidentifier", use: "obj😀;", used: true}, + {name: "unicode whitespace", use: "\u3000obj\u3000;", used: true}, + {name: "unicode identifiers", use: "const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {};"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const importText = "import { obj } from './obj';\n" + content := "// @Filename: /obj.ts\nexport const obj = {};\n" + + "// @Filename: /main.ts\n/*main*/" + importText + tt.use + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.GoToMarker(t, "main") + expected := tt.use + if tt.used { + expected = importText + expected + } + f.VerifyOrganizeImports(t, expected, lsproto.CodeActionKindSourceOrganizeImportsTs, nil) + }) + } +} diff --git a/tsc/internal/ls/findallreferences.go b/tsc/internal/ls/findallreferences.go index ec77cebfc46fb..a4e801a3e724c 100644 --- a/tsc/internal/ls/findallreferences.go +++ b/tsc/internal/ls/findallreferences.go @@ -7,6 +7,7 @@ import ( "slices" "strings" "sync" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -1662,15 +1663,20 @@ func getPossibleSymbolReferencePositions(sourceFile *ast.SourceFile, symbolName container = sourceFile.AsNode() } - position := strings.Index(text[container.Pos():], symbolName) + foundIndex := strings.Index(text[container.Pos():], symbolName) + if foundIndex == -1 { + return positions + } + position := container.Pos() + foundIndex endPos := container.End() for position >= 0 && position < endPos { - // We found a match. Make sure it's not part of a larger word (i.e. the char - // before and after it have to be a non-identifier char). + // We found a match. Make sure the runes before and after it are not identifier parts. endPosition := position + symbolNameLength + before, _ := utf8.DecodeLastRuneInString(text[:position]) + after, _ := utf8.DecodeRuneInString(text[endPosition:]) - if (position == 0 || !scanner.IsIdentifierPart(rune(text[position-1]))) && - (endPosition == sourceLength || !scanner.IsIdentifierPart(rune(text[endPosition]))) { + if (position == 0 || !scanner.IsIdentifierPart(before)) && + (endPosition == sourceLength || !scanner.IsIdentifierPart(after)) { // Found a real match. Keep searching. positions = append(positions, position) } diff --git a/tsc/testdata/baselines/reference/fourslash/documentHighlights/getOccurrencesOfAnonymousFunction.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/documentHighlights/getOccurrencesOfAnonymousFunction.baseline.jsonc index 3b02bd09b6ab9..8133d9fafae42 100644 --- a/tsc/testdata/baselines/reference/fourslash/documentHighlights/getOccurrencesOfAnonymousFunction.baseline.jsonc +++ b/tsc/testdata/baselines/reference/fourslash/documentHighlights/getOccurrencesOfAnonymousFunction.baseline.jsonc @@ -1,6 +1,6 @@ // === documentHighlights === // === /getOccurrencesOfAnonymousFunction.ts === -// (function /*HIGHLIGHTS*/foo(): number { +// (function /*HIGHLIGHTS*/[|foo|](): number { // var x = [|foo|]; // return 0; // }) @@ -9,7 +9,7 @@ // === documentHighlights === // === /getOccurrencesOfAnonymousFunction.ts === -// (function foo(): number { +// (function [|foo|](): number { // var x = /*HIGHLIGHTS*/[|foo|]; // return 0; // }) \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsParameterPropertyDeclaration_inheritance.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsParameterPropertyDeclaration_inheritance.baseline.jsonc index 598c9cedf2ed8..42c43ea25538d 100644 --- a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsParameterPropertyDeclaration_inheritance.baseline.jsonc +++ b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsParameterPropertyDeclaration_inheritance.baseline.jsonc @@ -42,9 +42,7 @@ // === findAllReferences === // === /findAllRefsParameterPropertyDeclaration_inheritance.ts === -// class C { -// constructor(public [|x|]: string) { -// [|x|]; +// --- (line: 3) skipped --- // } // } // class D extends C { diff --git a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames8.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames8.baseline.jsonc index 4e30c5fd6e4b1..fbca5c8a1f758 100644 --- a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames8.baseline.jsonc +++ b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames8.baseline.jsonc @@ -1,6 +1,6 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames8.ts === -// (/*FIND ALL REFS*/function __foo() { +// (/*FIND ALL REFS*/function [|__foo|]() { // [|__foo|](); // }) @@ -8,7 +8,7 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames8.ts === -// (function /*FIND ALL REFS*/__foo() { +// (function /*FIND ALL REFS*/[|__foo|]() { // [|__foo|](); // }) @@ -16,6 +16,6 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames8.ts === -// (function __foo() { +// (function [|__foo|]() { // /*FIND ALL REFS*/[|__foo|](); // }) \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames9.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames9.baseline.jsonc index c13998007052d..39a4bc63f7549 100644 --- a/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames9.baseline.jsonc +++ b/tsc/testdata/baselines/reference/fourslash/findAllReferences/findAllRefsWithLeadingUnderscoreNames9.baseline.jsonc @@ -1,6 +1,6 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames9.ts === -// (/*FIND ALL REFS*/function ___foo() { +// (/*FIND ALL REFS*/function [|___foo|]() { // [|___foo|](); // }) @@ -8,7 +8,7 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames9.ts === -// (function /*FIND ALL REFS*/___foo() { +// (function /*FIND ALL REFS*/[|___foo|]() { // [|___foo|](); // }) @@ -16,6 +16,6 @@ // === findAllReferences === // === /findAllRefsWithLeadingUnderscoreNames9.ts === -// (function ___foo() { +// (function [|___foo|]() { // /*FIND ALL REFS*/[|___foo|](); // }) \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/fourslash/findAllReferences/referenceScanningUnicodeBoundaries.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findAllReferences/referenceScanningUnicodeBoundaries.baseline.jsonc new file mode 100644 index 0000000000000..6f56c6387afee --- /dev/null +++ b/tsc/testdata/baselines/reference/fourslash/findAllReferences/referenceScanningUnicodeBoundaries.baseline.jsonc @@ -0,0 +1,72 @@ +// === findAllReferences === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const /*FIND ALL REFS*/[|obj|] = {}; +// [|obj|]¬; +// ☺[|obj|]; +//  [|obj|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// [|obj|]; +// } + + + +// === findAllReferences === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const [|obj|] = {}; +// /*FIND ALL REFS*/[|obj|]¬; +// ☺[|obj|]; +//  [|obj|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// [|obj|]; +// } + + + +// === findAllReferences === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const [|obj|] = {}; +// [|obj|]¬; +// ☺/*FIND ALL REFS*/[|obj|]; +//  [|obj|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// [|obj|]; +// } + + + +// === findAllReferences === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const [|obj|] = {}; +// [|obj|]¬; +// ☺[|obj|]; +//  /*FIND ALL REFS*/[|obj|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// [|obj|]; +// } + + + +// === findAllReferences === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const [|obj|] = {}; +// [|obj|]¬; +// ☺[|obj|]; +//  [|obj|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// /*FIND ALL REFS*/[|obj|]; +// } \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/fourslash/findRenameLocations/processInvalidSyntax1.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findRenameLocations/processInvalidSyntax1.baseline.jsonc index f08a819ee4f98..7acbf0e8b85bc 100644 --- a/tsc/testdata/baselines/reference/fourslash/findRenameLocations/processInvalidSyntax1.baseline.jsonc +++ b/tsc/testdata/baselines/reference/fourslash/findRenameLocations/processInvalidSyntax1.baseline.jsonc @@ -11,4 +11,7 @@ // [|objRENAME|].𝒜 ; // === /unicode2.js === -// [|objRENAME|].¬ ; \ No newline at end of file +// [|objRENAME|].¬ ; + +// === /unicode3.js === +// [|objRENAME|]¬ \ No newline at end of file diff --git a/tsc/testdata/baselines/reference/fourslash/findRenameLocations/referenceScanningUnicodeBoundaries.baseline.jsonc b/tsc/testdata/baselines/reference/fourslash/findRenameLocations/referenceScanningUnicodeBoundaries.baseline.jsonc new file mode 100644 index 0000000000000..1d321e746d1aa --- /dev/null +++ b/tsc/testdata/baselines/reference/fourslash/findRenameLocations/referenceScanningUnicodeBoundaries.baseline.jsonc @@ -0,0 +1,12 @@ +// === findRenameLocations === +// === /referenceScanningUnicodeBoundaries.ts === +// const padding = 0; +// function example() { +// const /*RENAME*/[|objRENAME|] = {}; +// [|objRENAME|]¬; +// ☺[|objRENAME|]; +//  [|objRENAME|] ; +// const éobj = {}, objé = {}, 𐐀obj = {}, obj𐐀 = {}, obj́ = {}; +// éobj; objé; 𐐀obj; obj𐐀; obj́; +// [|objRENAME|]; +// } \ No newline at end of file From e2bef5fbac4b496bfc5e88a6cb24d0e8590a5f51 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:58:12 -0800 Subject: [PATCH 2/2] Share reference scanning between checker and language server Separate copies of the reference scanners can drift and require the same boundary fixes in two places. Keep node and position lookup in astnav so compiler services and language-server searches use one implementation. --- tsc/internal/astnav/tokens.go | 61 ++++++++++++++++++++++ tsc/internal/checker/services.go | 66 +----------------------- tsc/internal/ls/findallreferences.go | 75 +++------------------------- 3 files changed, 70 insertions(+), 132 deletions(-) diff --git a/tsc/internal/astnav/tokens.go b/tsc/internal/astnav/tokens.go index 99b58eb11fc6d..84be12bc37787 100644 --- a/tsc/internal/astnav/tokens.go +++ b/tsc/internal/astnav/tokens.go @@ -3,6 +3,8 @@ package astnav import ( "fmt" "slices" + "strings" + "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/core" @@ -27,6 +29,65 @@ func GetTouchingPropertyName(sourceFile *ast.SourceFile, position int) *ast.Node }) } +func GetPossibleSymbolReferenceNodes(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []*ast.Node { + return core.MapNonNil(GetPossibleSymbolReferencePositions(sourceFile, symbolName, container), func(pos int) *ast.Node { + if referenceLocation := GetTouchingPropertyName(sourceFile, pos); referenceLocation != sourceFile.AsNode() { + return referenceLocation + } + return nil + }) +} + +func GetPossibleSymbolReferencePositions(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []int { + positions := []int{} + + // TODO: Cache symbol existence for files to save text search + // Also, need to make this work for unicode escapes. + + // Be resilient in the face of a symbol with no name or zero length name + if symbolName == "" { + return positions + } + + text := sourceFile.Text() + sourceLength := len(text) + symbolNameLength := len(symbolName) + + if container == nil { + container = sourceFile.AsNode() + } + + foundIndex := strings.Index(text[container.Pos():], symbolName) + if foundIndex == -1 { + return positions + } + position := container.Pos() + foundIndex + endPos := container.End() + for position >= 0 && position < endPos { + // We found a match. Make sure the runes before and after it are not identifier parts. + endPosition := position + symbolNameLength + before, _ := utf8.DecodeLastRuneInString(text[:position]) + after, _ := utf8.DecodeRuneInString(text[endPosition:]) + + if (position == 0 || !scanner.IsIdentifierPart(before)) && + (endPosition == sourceLength || !scanner.IsIdentifierPart(after)) { + // Found a real match. Keep searching. + positions = append(positions, position) + } + startIndex := position + symbolNameLength + 1 + if startIndex > len(text) { + break + } + if foundIndex := strings.Index(text[startIndex:], symbolName); foundIndex != -1 { + position = startIndex + foundIndex + } else { + break + } + } + + return positions +} + func GetTouchingToken(sourceFile *ast.SourceFile, position int) *ast.Node { return getTokenAtPosition(sourceFile, position, false /*allowPositionInLeadingTrivia*/, nil) } diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index c36e96ee0040a..ecc28ea2b2b44 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -2,15 +2,12 @@ package checker import ( "slices" - "strings" - "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" "github.com/microsoft/TypeScript/tsc/internal/collections" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/debug" - "github.com/microsoft/TypeScript/tsc/internal/scanner" ) func (c *Checker) GetSymbolsInScope(location *ast.Node, meaning ast.SymbolFlags) []*ast.Symbol { @@ -554,7 +551,7 @@ func (c *Checker) IsSymbolReferencedInFile( symbol *ast.Symbol, ) bool { identifierText := definition.Text - for _, token := range getPossibleSymbolReferenceNodes(sourceFile, identifierText, sourceFile.AsNode()) { + for _, token := range astnav.GetPossibleSymbolReferenceNodes(sourceFile, identifierText, sourceFile.AsNode()) { if !ast.IsIdentifier(token) { continue } @@ -589,7 +586,7 @@ func (c *Checker) GetReferencesToSymbolInFile( ) []*ast.Node { identifierText := symbol.Name() var result []*ast.Node - for _, token := range getPossibleSymbolReferenceNodes(sourceFile, identifierText, sourceFile.AsNode()) { + for _, token := range astnav.GetPossibleSymbolReferenceNodes(sourceFile, identifierText, sourceFile.AsNode()) { if !ast.IsIdentifier(token) { continue } @@ -642,65 +639,6 @@ func isExportSpecifierAlias(referenceLocation *ast.Identifier, exportSpecifier * } } -func getPossibleSymbolReferenceNodes(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []*ast.Node { - return core.MapNonNil(getPossibleSymbolReferencePositions(sourceFile, symbolName, container), func(pos int) *ast.Node { - if referenceLocation := astnav.GetTouchingPropertyName(sourceFile, pos); referenceLocation != sourceFile.AsNode() { - return referenceLocation - } - return nil - }) -} - -func getPossibleSymbolReferencePositions(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []int { - positions := []int{} - - // TODO: Cache symbol existence for files to save text search - // Also, need to make this work for unicode escapes. - - // Be resilient in the face of a symbol with no name or zero length name - if symbolName == "" { - return positions - } - - text := sourceFile.Text() - sourceLength := len(text) - symbolNameLength := len(symbolName) - - if container == nil { - container = sourceFile.AsNode() - } - - foundIndex := strings.Index(text[container.Pos():], symbolName) - if foundIndex == -1 { - return positions - } - position := container.Pos() + foundIndex - endPos := container.End() - for position >= 0 && position < endPos { - // We found a match. Make sure the runes before and after it are not identifier parts. - endPosition := position + symbolNameLength - before, _ := utf8.DecodeLastRuneInString(text[:position]) - after, _ := utf8.DecodeRuneInString(text[endPosition:]) - - if (position == 0 || !scanner.IsIdentifierPart(before)) && - (endPosition == sourceLength || !scanner.IsIdentifierPart(after)) { - // Found a real match. Keep searching. - positions = append(positions, position) - } - startIndex := position + symbolNameLength + 1 - if startIndex > len(text) { - break - } - if foundIndex := strings.Index(text[startIndex:], symbolName); foundIndex != -1 { - position = startIndex + foundIndex - } else { - break - } - } - - return positions -} - func (c *Checker) GetTypeArgumentConstraint(node *ast.Node) *Type { if !ast.IsTypeNode(node) { return nil diff --git a/tsc/internal/ls/findallreferences.go b/tsc/internal/ls/findallreferences.go index a4e801a3e724c..662abc7edecdf 100644 --- a/tsc/internal/ls/findallreferences.go +++ b/tsc/internal/ls/findallreferences.go @@ -5,9 +5,7 @@ import ( "context" "fmt" "slices" - "strings" "sync" - "unicode/utf8" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/astnav" @@ -1364,7 +1362,7 @@ func (l *LanguageService) getReferencesForStringLiteral( return nil } var entries []*ReferenceEntry - possibleReferences := getPossibleSymbolReferenceNodes(sourceFile, node.Text(), nil /*container*/) + possibleReferences := astnav.GetPossibleSymbolReferenceNodes(sourceFile, node.Text(), nil /*container*/) for _, ref := range possibleReferences { if ast.IsStringLiteralLike(ref) && ref.Text() == node.Text() { if t != nil { @@ -1478,7 +1476,7 @@ func getReferencedSymbolsSpecial(node *ast.Node, sourceFiles []*ast.SourceFile) func getLabelReferencesInNode(container *ast.Node, targetLabel *ast.Node) []*SymbolAndEntries { sourceFile := ast.GetSourceFileOfNode(container) labelName := targetLabel.Text() - references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), func(node *ast.Node) *ReferenceEntry { + references := core.MapNonNil(astnav.GetPossibleSymbolReferenceNodes(sourceFile, labelName, container), func(node *ast.Node) *ReferenceEntry { // Only pick labels that are either the target label, or have a target that is the target label if node == targetLabel.AsNode() || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) == targetLabel) { return newNodeEntry(node) @@ -1526,7 +1524,7 @@ func getReferencesForThisKeyword(thisOrSuperKeyword *ast.Node, sourceFiles []*as core.FlatMap(filesToSearch, func(sourceFile *ast.SourceFile) []*ast.Node { // cancellationToken.throwIfCancellationRequested(); return core.Filter( - getPossibleSymbolReferenceNodes(sourceFile, "this", core.IfElse(searchSpaceNode.Kind == ast.KindSourceFile, sourceFile.AsNode(), searchSpaceNode)), + astnav.GetPossibleSymbolReferenceNodes(sourceFile, "this", core.IfElse(searchSpaceNode.Kind == ast.KindSourceFile, sourceFile.AsNode(), searchSpaceNode)), func(node *ast.Node) bool { if !isThis(node) { return false @@ -1583,7 +1581,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { } sourceFile := ast.GetSourceFileOfNode(searchSpaceNode) - references := core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), func(node *ast.Node) *ReferenceEntry { + references := core.MapNonNil(astnav.GetPossibleSymbolReferenceNodes(sourceFile, "super", searchSpaceNode), func(node *ast.Node) *ReferenceEntry { if node.Kind != ast.KindSuperKeyword { return nil } @@ -1604,7 +1602,7 @@ func getReferencesForSuperKeyword(superKeyword *ast.Node) []*SymbolAndEntries { func getAllReferencesForImportMeta(sourceFiles []*ast.SourceFile) []*SymbolAndEntries { references := core.FlatMap(sourceFiles, func(sourceFile *ast.SourceFile) []*ReferenceEntry { - return core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile.AsNode()), func(node *ast.Node) *ReferenceEntry { + return core.MapNonNil(astnav.GetPossibleSymbolReferenceNodes(sourceFile, "meta", sourceFile.AsNode()), func(node *ast.Node) *ReferenceEntry { parent := node.Parent if ast.IsImportMeta(parent) { return newNodeEntry(parent) @@ -1622,7 +1620,7 @@ func getAllReferencesForKeyword(sourceFiles []*ast.SourceFile, keywordKind ast.K // references is a list of NodeEntry references := core.FlatMap(sourceFiles, func(sourceFile *ast.SourceFile) []*ReferenceEntry { // cancellationToken.throwIfCancellationRequested(); - return core.MapNonNil(getPossibleSymbolReferenceNodes(sourceFile, scanner.TokenToString(keywordKind), sourceFile.AsNode()), func(referenceLocation *ast.Node) *ReferenceEntry { + return core.MapNonNil(astnav.GetPossibleSymbolReferenceNodes(sourceFile, scanner.TokenToString(keywordKind), sourceFile.AsNode()), func(referenceLocation *ast.Node) *ReferenceEntry { if referenceLocation.Kind == keywordKind && (!filterReadOnlyTypeOperator || isReadonlyTypeOperator(referenceLocation)) { return newNodeEntry(referenceLocation) } @@ -1635,65 +1633,6 @@ func getAllReferencesForKeyword(sourceFiles []*ast.SourceFile, keywordKind ast.K return []*SymbolAndEntries{NewSymbolAndEntries(definitionKindKeyword, references[0].node, nil, references)} } -func getPossibleSymbolReferenceNodes(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []*ast.Node { - return core.MapNonNil(getPossibleSymbolReferencePositions(sourceFile, symbolName, container), func(pos int) *ast.Node { - if referenceLocation := astnav.GetTouchingPropertyName(sourceFile, pos); referenceLocation != sourceFile.AsNode() { - return referenceLocation - } - return nil - }) -} - -func getPossibleSymbolReferencePositions(sourceFile *ast.SourceFile, symbolName string, container *ast.Node) []int { - positions := []int{} - - /// TODO: Cache symbol existence for files to save text search - // Also, need to make this work for unicode escapes. - - // Be resilient in the face of a symbol with no name or zero length name - if symbolName == "" { - return positions - } - - text := sourceFile.Text() - sourceLength := len(text) - symbolNameLength := len(symbolName) - - if container == nil { - container = sourceFile.AsNode() - } - - foundIndex := strings.Index(text[container.Pos():], symbolName) - if foundIndex == -1 { - return positions - } - position := container.Pos() + foundIndex - endPos := container.End() - for position >= 0 && position < endPos { - // We found a match. Make sure the runes before and after it are not identifier parts. - endPosition := position + symbolNameLength - before, _ := utf8.DecodeLastRuneInString(text[:position]) - after, _ := utf8.DecodeRuneInString(text[endPosition:]) - - if (position == 0 || !scanner.IsIdentifierPart(before)) && - (endPosition == sourceLength || !scanner.IsIdentifierPart(after)) { - // Found a real match. Keep searching. - positions = append(positions, position) - } - startIndex := position + symbolNameLength + 1 - if startIndex > len(text) { - break - } - if foundIndex := strings.Index(text[startIndex:], symbolName); foundIndex != -1 { - position = startIndex + foundIndex - } else { - break - } - } - - return positions -} - // findFirstJsxNode recursively searches for the first JSX element, self-closing element, or fragment func findFirstJsxNode(root *ast.Node) *ast.Node { var visit func(*ast.Node) *ast.Node @@ -2201,7 +2140,7 @@ func (state *refState) getReferencesInContainer(container *ast.Node, sourceFile return } - for _, position := range getPossibleSymbolReferencePositions(sourceFile, search.text, container) { + for _, position := range astnav.GetPossibleSymbolReferencePositions(sourceFile, search.text, container) { state.getReferencesAtLocation(sourceFile, position, search, addReferencesHere) } }