golang.org/x/tools/gopls@v0.15.3/internal/server/symbols.go (about)

     1  // Copyright 2019 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package server
     6  
     7  import (
     8  	"context"
     9  
    10  	"golang.org/x/tools/gopls/internal/file"
    11  	"golang.org/x/tools/gopls/internal/golang"
    12  	"golang.org/x/tools/gopls/internal/protocol"
    13  	"golang.org/x/tools/gopls/internal/template"
    14  	"golang.org/x/tools/internal/event"
    15  	"golang.org/x/tools/internal/event/tag"
    16  )
    17  
    18  func (s *server) DocumentSymbol(ctx context.Context, params *protocol.DocumentSymbolParams) ([]any, error) {
    19  	ctx, done := event.Start(ctx, "lsp.Server.documentSymbol", tag.URI.Of(params.TextDocument.URI))
    20  	defer done()
    21  
    22  	fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	defer release()
    27  
    28  	var docSymbols []protocol.DocumentSymbol
    29  	switch snapshot.FileKind(fh) {
    30  	case file.Tmpl:
    31  		docSymbols, err = template.DocumentSymbols(snapshot, fh)
    32  	case file.Go:
    33  		docSymbols, err = golang.DocumentSymbols(ctx, snapshot, fh)
    34  	default:
    35  		return nil, nil // empty result
    36  	}
    37  	if err != nil {
    38  		event.Error(ctx, "DocumentSymbols failed", err)
    39  		return nil, nil // empty result
    40  	}
    41  	// Convert the symbols to an interface array.
    42  	// TODO: Remove this once the lsp deprecates SymbolInformation.
    43  	symbols := make([]any, len(docSymbols))
    44  	for i, s := range docSymbols {
    45  		if snapshot.Options().HierarchicalDocumentSymbolSupport {
    46  			symbols[i] = s
    47  			continue
    48  		}
    49  		// If the client does not support hierarchical document symbols, then
    50  		// we need to be backwards compatible for now and return SymbolInformation.
    51  		symbols[i] = protocol.SymbolInformation{
    52  			Name:       s.Name,
    53  			Kind:       s.Kind,
    54  			Deprecated: s.Deprecated,
    55  			Location: protocol.Location{
    56  				URI:   params.TextDocument.URI,
    57  				Range: s.Range,
    58  			},
    59  		}
    60  	}
    61  	return symbols, nil
    62  }