Skip to content

Handle LSP textDocument/documentSymbol requests #1363

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

Merged
merged 2 commits into from
Jul 6, 2025
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
28 changes: 0 additions & 28 deletions internal/checker/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,34 +297,6 @@ const (
AccessFlagsPersistent = AccessFlagsIncludeUndefined
)

type AssignmentDeclarationKind = int32

const (
AssignmentDeclarationKindNone = AssignmentDeclarationKind(iota)
/// exports.name = expr
/// module.exports.name = expr
AssignmentDeclarationKindExportsProperty
/// module.exports = expr
AssignmentDeclarationKindModuleExports
/// className.prototype.name = expr
AssignmentDeclarationKindPrototypeProperty
/// this.name = expr
AssignmentDeclarationKindThisProperty
// F.name = expr
AssignmentDeclarationKindProperty
// F.prototype = { ... }
AssignmentDeclarationKindPrototype
// Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
// Object.defineProperty(x, 'name', { get: Function, set: Function });
// Object.defineProperty(x, 'name', { get: Function });
// Object.defineProperty(x, 'name', { set: Function });
AssignmentDeclarationKindObjectDefinePropertyValue
// Object.defineProperty(exports || module.exports, 'name', ...);
AssignmentDeclarationKindObjectDefinePropertyExports
// Object.defineProperty(Foo.prototype, 'name', ...);
AssignmentDeclarationKindObjectDefinePrototypeProperty
)

type NodeCheckFlags uint32

const (
Expand Down
171 changes: 171 additions & 0 deletions internal/ls/symbols.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,181 @@ import (
"github.com/microsoft/typescript-go/internal/compiler"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/lsp/lsproto"
"github.com/microsoft/typescript-go/internal/printer"
"github.com/microsoft/typescript-go/internal/scanner"
"github.com/microsoft/typescript-go/internal/stringutil"
)

func (l *LanguageService) ProvideDocumentSymbols(ctx context.Context, documentURI lsproto.DocumentUri) ([]*lsproto.DocumentSymbol, error) {
_, file := l.getProgramAndFile(documentURI)
symbols := l.getDocumentSymbolsForChildren(ctx, file.AsNode())
return symbols, nil
}

func (l *LanguageService) getDocumentSymbolsForChildren(ctx context.Context, node *ast.Node) []*lsproto.DocumentSymbol {
var symbols []*lsproto.DocumentSymbol
addSymbolForNode := func(node *ast.Node, children []*lsproto.DocumentSymbol) {
symbol := l.newDocumentSymbol(node, children)
if symbol != nil {
symbols = append(symbols, symbol)
}
}
var visit func(*ast.Node) bool
getSymbolsForChildren := func(node *ast.Node) []*lsproto.DocumentSymbol {
var result []*lsproto.DocumentSymbol
if node != nil {
saveSymbols := symbols
symbols = nil
node.ForEachChild(visit)
result = symbols
symbols = saveSymbols
}
return result
}
visit = func(node *ast.Node) bool {
if ctx != nil && ctx.Err() != nil {
return true
}
switch node.Kind {
case ast.KindClassDeclaration, ast.KindClassExpression, ast.KindInterfaceDeclaration, ast.KindEnumDeclaration:
addSymbolForNode(node, getSymbolsForChildren(node))
case ast.KindModuleDeclaration:
addSymbolForNode(node, getSymbolsForChildren(getInteriorModule(node)))
case ast.KindFunctionDeclaration, ast.KindFunctionExpression, ast.KindArrowFunction, ast.KindMethodDeclaration, ast.KindGetAccessor,
ast.KindSetAccessor, ast.KindConstructor:
addSymbolForNode(node, getSymbolsForChildren(node.Body()))
case ast.KindVariableDeclaration, ast.KindBindingElement, ast.KindPropertyAssignment, ast.KindPropertyDeclaration:
name := node.Name()
if name != nil {
if ast.IsBindingPattern(name) {
visit(name)
} else {
addSymbolForNode(node, getSymbolsForChildren(node.Initializer()))
}
}
case ast.KindMethodSignature, ast.KindPropertySignature, ast.KindCallSignature, ast.KindConstructSignature, ast.KindIndexSignature,
ast.KindEnumMember, ast.KindShorthandPropertyAssignment, ast.KindTypeAliasDeclaration:
addSymbolForNode(node, nil)
default:
node.ForEachChild(visit)
}
return false
}
node.ForEachChild(visit)
return symbols
}

func (l *LanguageService) newDocumentSymbol(node *ast.Node, children []*lsproto.DocumentSymbol) *lsproto.DocumentSymbol {
result := new(lsproto.DocumentSymbol)
file := ast.GetSourceFileOfNode(node)
nodeStartPos := scanner.SkipTrivia(file.Text(), node.Pos())
name := ast.GetNameOfDeclaration(node)
var text string
var nameStartPos, nameEndPos int
if ast.IsModuleDeclaration(node) && !ast.IsAmbientModule(node) {
text = getModuleName(node)
nameStartPos = scanner.SkipTrivia(file.Text(), name.Pos())
nameEndPos = getInteriorModule(node).Name().End()
} else if name != nil {
text = getTextOfName(name)
nameStartPos = max(scanner.SkipTrivia(file.Text(), name.Pos()), nodeStartPos)
nameEndPos = max(name.End(), nodeStartPos)
} else {
text = getUnnamedNodeLabel(node)
nameStartPos = nodeStartPos
nameEndPos = nodeStartPos
}
if text == "" {
return nil
}
result.Name = text
result.Kind = getSymbolKindFromNode(node)
result.Range = lsproto.Range{
Start: l.converters.PositionToLineAndCharacter(file, core.TextPos(nodeStartPos)),
End: l.converters.PositionToLineAndCharacter(file, core.TextPos(node.End())),
}
result.SelectionRange = lsproto.Range{
Start: l.converters.PositionToLineAndCharacter(file, core.TextPos(nameStartPos)),
End: l.converters.PositionToLineAndCharacter(file, core.TextPos(nameEndPos)),
}
if children == nil {
children = []*lsproto.DocumentSymbol{}
}
result.Children = &children
return result
}

func getTextOfName(node *ast.Node) string {
switch node.Kind {
case ast.KindIdentifier, ast.KindPrivateIdentifier, ast.KindNumericLiteral:
return node.Text()
case ast.KindStringLiteral:
return "\"" + printer.EscapeString(node.Text(), '"') + "\""
case ast.KindNoSubstitutionTemplateLiteral:
return "`" + printer.EscapeString(node.Text(), '`') + "`"
case ast.KindComputedPropertyName:
if ast.IsStringOrNumericLiteralLike(node.Expression()) {
return getTextOfName(node.Expression())
}
}
return scanner.GetTextOfNode(node)
}

func getUnnamedNodeLabel(node *ast.Node) string {
switch node.Kind {
case ast.KindFunctionExpression, ast.KindArrowFunction:
if ast.IsCallExpression(node.Parent) {
name := getCallExpressionName(node.Parent.Expression())
if name != "" {
return name + "() callback"
}
}
return "<function>"
case ast.KindClassExpression:
return "<class>"
case ast.KindConstructor:
return "constructor"
case ast.KindCallSignature:
return "()"
case ast.KindConstructSignature:
return "new()"
case ast.KindIndexSignature:
return "[]"
}
return ""
}

func getCallExpressionName(node *ast.Node) string {
switch node.Kind {
case ast.KindIdentifier, ast.KindPrivateIdentifier:
return node.Text()
case ast.KindPropertyAccessExpression:
left := getCallExpressionName(node.Expression())
right := getCallExpressionName(node.Name())
if left != "" {
return left + "." + right
}
return right
}
return ""
}

func getInteriorModule(node *ast.Node) *ast.Node {
for node.Body() != nil && ast.IsModuleDeclaration(node.Body()) {
node = node.Body()
}
return node
}

func getModuleName(node *ast.Node) string {
result := node.Name().Text()
for node.Body() != nil && ast.IsModuleDeclaration(node.Body()) {
node = node.Body()
result = result + "." + node.Name().Text()
}
return result
}

type DeclarationInfo struct {
name string
declaration *ast.Node
Expand Down
18 changes: 18 additions & 0 deletions internal/lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,8 @@ func (s *Server) handleRequestOrNotification(ctx context.Context, req *lsproto.R
return s.handleDocumentOnTypeFormat(ctx, req)
case *lsproto.WorkspaceSymbolParams:
return s.handleWorkspaceSymbol(ctx, req)
case *lsproto.DocumentSymbolParams:
return s.handleDocumentSymbol(ctx, req)
default:
switch req.Method {
case lsproto.MethodShutdown:
Expand Down Expand Up @@ -578,6 +580,9 @@ func (s *Server) handleInitialize(req *lsproto.RequestMessage) {
WorkspaceSymbolProvider: &lsproto.BooleanOrWorkspaceSymbolOptions{
Boolean: ptrTo(true),
},
DocumentSymbolProvider: &lsproto.BooleanOrDocumentSymbolOptions{
Boolean: ptrTo(true),
},
},
})
}
Expand Down Expand Up @@ -786,6 +791,19 @@ func (s *Server) handleWorkspaceSymbol(ctx context.Context, req *lsproto.Request
return nil
}

func (s *Server) handleDocumentSymbol(ctx context.Context, req *lsproto.RequestMessage) error {
params := req.Params.(*lsproto.DocumentSymbolParams)
project := s.projectService.EnsureDefaultProjectForURI(params.TextDocument.Uri)
languageService, done := project.GetLanguageServiceForRequest(ctx)
defer done()
hover, err := languageService.ProvideDocumentSymbols(ctx, params.TextDocument.Uri)
if err != nil {
return err
}
s.sendResult(req.ID, hover)
return nil
}

func (s *Server) Log(msg ...any) {
fmt.Fprintln(s.stderr, msg...)
}
Expand Down