blob: 180d04dff1994e365045bbcf4ff29f421db89ce8 [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 cmd
6
7import (
8 "context"
9 "flag"
10 "fmt"
11 "sort"
12
13 "golang.org/x/tools/gopls/internal/lsp/protocol"
Robert Findleyb15dac22022-08-30 14:40:12 -040014 "golang.org/x/tools/internal/tool"
15)
16
17// implementation implements the implementation verb for gopls
18type implementation struct {
19 app *Application
20}
21
22func (i *implementation) Name() string { return "implementation" }
23func (i *implementation) Parent() string { return i.app.Name() }
24func (i *implementation) Usage() string { return "<position>" }
25func (i *implementation) ShortHelp() string { return "display selected identifier's implementation" }
26func (i *implementation) DetailedHelp(f *flag.FlagSet) {
27 fmt.Fprint(f.Output(), `
28Example:
29
30 $ # 1-indexed location (:line:column or :#offset) of the target identifier
31 $ gopls implementation helper/helper.go:8:6
32 $ gopls implementation helper/helper.go:#53
33`)
34 printFlagDefaults(f)
35}
36
37func (i *implementation) Run(ctx context.Context, args ...string) error {
38 if len(args) != 1 {
39 return tool.CommandLineErrorf("implementation expects 1 argument (position)")
40 }
41
Rob Findley1c5ccad2023-04-18 13:48:38 -040042 conn, err := i.app.connect(ctx, nil)
Robert Findleyb15dac22022-08-30 14:40:12 -040043 if err != nil {
44 return err
45 }
46 defer conn.terminate(ctx)
47
Alan Donovan3292b362023-11-14 01:08:40 -050048 from := parseSpan(args[0])
Alan Donovan54c806f2023-04-07 15:04:09 -040049 file, err := conn.openFile(ctx, from.URI())
50 if err != nil {
51 return err
Robert Findleyb15dac22022-08-30 14:40:12 -040052 }
53
Alan Donovan3292b362023-11-14 01:08:40 -050054 loc, err := file.spanLocation(from)
Robert Findleyb15dac22022-08-30 14:40:12 -040055 if err != nil {
56 return err
57 }
58
59 p := protocol.ImplementationParams{
Alan Donovand093a132023-01-26 16:14:35 -050060 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
Robert Findleyb15dac22022-08-30 14:40:12 -040061 }
Robert Findleyb15dac22022-08-30 14:40:12 -040062 implementations, err := conn.Implementation(ctx, &p)
63 if err != nil {
64 return err
65 }
66
67 var spans []string
68 for _, impl := range implementations {
Alan Donovan979df5b2023-11-15 13:16:52 -050069 f, err := conn.openFile(ctx, impl.URI)
Alan Donovan54c806f2023-04-07 15:04:09 -040070 if err != nil {
71 return err
72 }
Alan Donovan3292b362023-11-14 01:08:40 -050073 span, err := f.locationSpan(impl)
Robert Findleyb15dac22022-08-30 14:40:12 -040074 if err != nil {
75 return err
76 }
77 spans = append(spans, fmt.Sprint(span))
78 }
79 sort.Strings(spans)
80
81 for _, s := range spans {
82 fmt.Println(s)
83 }
84
85 return nil
86}