Skip to content

LSP: Jump to the function name #792

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
68 changes: 57 additions & 11 deletions internal/ls/definition.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/astnav"
"github.com/microsoft/typescript-go/internal/checker"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/scanner"
Expand All @@ -20,24 +21,69 @@ func (l *LanguageService) ProvideDefinition(ctx context.Context, documentURI lsp
checker, done := program.GetTypeCheckerForFile(ctx, file)
defer done()

calledDeclaration := tryGetSignatureDeclaration(checker, node)
Copy link
Author

Choose a reason for hiding this comment

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

I tried to port the logic from src/services/goToDefinition.ts in the TypeScript repository.

if calledDeclaration != nil {
name := ast.GetNameOfDeclaration(calledDeclaration)
if name != nil {
return l.createLocationsFromDeclarations([]*ast.Node{name})
}
}

if symbol := checker.GetSymbolAtLocation(node); symbol != nil {
if symbol.Flags&ast.SymbolFlagsAlias != 0 {
if resolved, ok := checker.ResolveAlias(symbol); ok {
symbol = resolved
}
}

locations := make([]lsproto.Location, 0, len(symbol.Declarations))
for _, decl := range symbol.Declarations {
file := ast.GetSourceFileOfNode(decl)
loc := decl.Loc
pos := scanner.GetTokenPosOfNode(decl, file, false /*includeJSDoc*/)
locations = append(locations, lsproto.Location{
Uri: FileNameToDocumentURI(file.FileName()),
Range: l.converters.ToLSPRange(file, core.NewTextRange(pos, loc.End())),
})
}
return &lsproto.Definition{Locations: &locations}, nil
return l.createLocationsFromDeclarations(symbol.Declarations)
}
return nil, nil
}

func (l *LanguageService) createLocationsFromDeclarations(declarations []*ast.Node) (*lsproto.Definition, error) {
locations := make([]lsproto.Location, 0, len(declarations))
for _, decl := range declarations {
file := ast.GetSourceFileOfNode(decl)
loc := decl.Loc
pos := scanner.GetTokenPosOfNode(decl, file, false /*includeJSDoc*/)
locations = append(locations, lsproto.Location{
Uri: FileNameToDocumentURI(file.FileName()),
Range: l.converters.ToLSPRange(file, core.NewTextRange(pos, loc.End())),
})
}
return &lsproto.Definition{Locations: &locations}, nil
}

/** Returns a CallLikeExpression where `node` is the target being invoked. */
func getAncestorCallLikeExpression(node *ast.Node) *ast.Node {
target := ast.FindAncestor(node, func(n *ast.Node) bool {
return !isRightSideOfPropertyAccess(n)
})

callLike := target.Parent
if callLike != nil && ast.IsCallLikeExpression(callLike) && ast.GetInvokedExpression(callLike) == target {
return callLike
}

return nil
}

func tryGetSignatureDeclaration(typeChecker *checker.Checker, node *ast.Node) *ast.Node {
var signature *checker.Signature
callLike := getAncestorCallLikeExpression(node)
if callLike != nil {
signature = typeChecker.GetResolvedSignature(callLike)
}

// Don't go to a function type, go to the value having that type.
var declaration *ast.Node
if signature != nil && signature.Declaration() != nil {
declaration = signature.Declaration()
if ast.IsFunctionLike(declaration) && !ast.IsFunctionTypeNode(declaration) {
return declaration
}
}

return nil
}
74 changes: 74 additions & 0 deletions internal/ls/definition_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package ls_test

import (
"testing"

"github.com/microsoft/typescript-go/internal/bundled"
"github.com/microsoft/typescript-go/internal/fourslash"
"github.com/microsoft/typescript-go/internal/ls"
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/testutil/projecttestutil"
"gotest.tools/v3/assert"
)

func TestDefinition(t *testing.T) {
t.Parallel()
if !bundled.Embedded {
// Without embedding, we'd need to read all of the lib files out from disk into the MapFS.
// Just skip this for now.
t.Skip("bundled files are not embedded")
}

testCases := []struct {
title string
input string
expected map[string]lsproto.Definition
}{
{
title: "localFunction",
input: `
// @filename: index.ts
function localFunction() { }
/*localFunction*/localFunction();`,
expected: map[string]lsproto.Definition{
"localFunction": {
Locations: &[]lsproto.Location{{
Uri: ls.FileNameToDocumentURI("/index.ts"),
Range: lsproto.Range{Start: lsproto.Position{Character: 9}, End: lsproto.Position{Character: 22}},
}},
},
},
},
}

for _, testCase := range testCases {
t.Run(testCase.title, func(t *testing.T) {
t.Parallel()
runDefinitionTest(t, testCase.input, testCase.expected)
})
}
}

func runDefinitionTest(t *testing.T, input string, expected map[string]lsproto.Definition) {
testData := fourslash.ParseTestData(t, input, "/mainFile.ts")
file := testData.Files[0].FileName()
markerPositions := testData.MarkerPositions
ctx := projecttestutil.WithRequestID(t.Context())
languageService, done := createLanguageService(ctx, file, map[string]any{
file: testData.Files[0].Content,
})
defer done()

for markerName, expectedResult := range expected {
marker, ok := markerPositions[markerName]
if !ok {
t.Fatalf("No marker found for '%s'", markerName)
}
locations, err := languageService.ProvideDefinition(
ctx,
ls.FileNameToDocumentURI(file),
marker.LSPosition)
assert.NilError(t, err)
assert.DeepEqual(t, *locations, expectedResult)
}
}