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