github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/definition.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 lsp
     6  
     7  import (
     8  	"context"
     9  
    10  	"github.com/powerman/golang-tools/internal/lsp/protocol"
    11  	"github.com/powerman/golang-tools/internal/lsp/source"
    12  	"github.com/powerman/golang-tools/internal/lsp/template"
    13  )
    14  
    15  func (s *Server) definition(ctx context.Context, params *protocol.DefinitionParams) ([]protocol.Location, error) {
    16  	snapshot, fh, ok, release, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
    17  	defer release()
    18  	if !ok {
    19  		return nil, err
    20  	}
    21  	if snapshot.View().FileKind(fh) == source.Tmpl {
    22  		return template.Definition(snapshot, fh, params.Position)
    23  	}
    24  	ident, err := source.Identifier(ctx, snapshot, fh, params.Position)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	if ident.IsImport() && !snapshot.View().Options().ImportShortcut.ShowDefinition() {
    29  		return nil, nil
    30  	}
    31  	var locations []protocol.Location
    32  	for _, ref := range ident.Declaration.MappedRange {
    33  		decRange, err := ref.Range()
    34  		if err != nil {
    35  			return nil, err
    36  		}
    37  
    38  		locations = append(locations, protocol.Location{
    39  			URI:   protocol.URIFromSpanURI(ref.URI()),
    40  			Range: decRange,
    41  		})
    42  	}
    43  
    44  	return locations, nil
    45  }
    46  
    47  func (s *Server) typeDefinition(ctx context.Context, params *protocol.TypeDefinitionParams) ([]protocol.Location, error) {
    48  	snapshot, fh, ok, release, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.Go)
    49  	defer release()
    50  	if !ok {
    51  		return nil, err
    52  	}
    53  	ident, err := source.Identifier(ctx, snapshot, fh, params.Position)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	identRange, err := ident.Type.Range()
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	return []protocol.Location{
    62  		{
    63  			URI:   protocol.URIFromSpanURI(ident.Type.URI()),
    64  			Range: identRange,
    65  		},
    66  	}, nil
    67  }