Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions tsc/internal/astnav/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}
Expand Down
60 changes: 2 additions & 58 deletions tsc/internal/checker/services.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package checker

import (
"slices"
"strings"

"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 {
Expand Down Expand Up @@ -553,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
}
Expand Down Expand Up @@ -588,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
}
Expand Down Expand Up @@ -641,60 +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()
}

position := strings.Index(text[container.Pos():], symbolName)
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).
endPosition := position + symbolNameLength

if (position == 0 || !scanner.IsIdentifierPart(rune(text[position-1]))) &&
(endPosition == sourceLength || !scanner.IsIdentifierPart(rune(text[endPosition]))) {
// 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
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
69 changes: 7 additions & 62 deletions tsc/internal/ls/findallreferences.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"context"
"fmt"
"slices"
"strings"
"sync"

"github.com/microsoft/TypeScript/tsc/internal/ast"
Expand Down Expand Up @@ -1363,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 {
Expand Down Expand Up @@ -1477,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)
Expand Down Expand Up @@ -1525,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
Expand Down Expand Up @@ -1582,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
}
Expand All @@ -1603,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)
Expand All @@ -1621,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)
}
Expand All @@ -1634,60 +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()
}

position := strings.Index(text[container.Pos():], symbolName)
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).
endPosition := position + symbolNameLength

if (position == 0 || !scanner.IsIdentifierPart(rune(text[position-1]))) &&
(endPosition == sourceLength || !scanner.IsIdentifierPart(rune(text[endPosition]))) {
// 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
Expand Down Expand Up @@ -2195,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)
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// === documentHighlights ===
// === /getOccurrencesOfAnonymousFunction.ts ===
// (function /*HIGHLIGHTS*/foo(): number {
// (function /*HIGHLIGHTS*/[|foo|](): number {
// var x = [|foo|];
// return 0;
// })
Expand All @@ -9,7 +9,7 @@

// === documentHighlights ===
// === /getOccurrencesOfAnonymousFunction.ts ===
// (function foo(): number {
// (function [|foo|](): number {
// var x = /*HIGHLIGHTS*/[|foo|];
// return 0;
// })
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@

// === findAllReferences ===
// === /findAllRefsParameterPropertyDeclaration_inheritance.ts ===
// class C {
// constructor(public [|x|]: string) {
// [|x|];
// --- (line: 3) skipped ---
// }
// }
// class D extends C {
Expand Down
Loading
Loading