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.
13 "golang.org/x/tools/internal/lsp/protocol"
14 "golang.org/x/tools/internal/span"
15 "golang.org/x/tools/internal/tool"
18 // references implements the references verb for gopls
19 type references struct {
20 IncludeDeclaration bool `flag:"d" help:"include the declaration of the specified identifier in the results"`
25 func (r *references) Name() string { return "references" }
26 func (r *references) Usage() string { return "<position>" }
27 func (r *references) ShortHelp() string { return "display selected identifier's references" }
28 func (r *references) DetailedHelp(f *flag.FlagSet) {
29 fmt.Fprint(f.Output(), `
32 $ # 1-indexed location (:line:column or :#offset) of the target identifier
33 $ gopls references helper/helper.go:8:6
34 $ gopls references helper/helper.go:#53
36 gopls references flags are:
41 func (r *references) Run(ctx context.Context, args ...string) error {
43 return tool.CommandLineErrorf("references expects 1 argument (position)")
46 conn, err := r.app.connect(ctx)
50 defer conn.terminate(ctx)
52 from := span.Parse(args[0])
53 file := conn.AddFile(ctx, from.URI())
57 loc, err := file.mapper.Location(from)
61 p := protocol.ReferenceParams{
62 Context: protocol.ReferenceContext{
63 IncludeDeclaration: r.IncludeDeclaration,
65 TextDocumentPositionParams: protocol.TextDocumentPositionParams{
66 TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI},
67 Position: loc.Range.Start,
70 locations, err := conn.References(ctx, &p)
75 for _, l := range locations {
76 f := conn.AddFile(ctx, fileURI(l.URI))
77 // convert location to span for user-friendly 1-indexed line
79 span, err := f.mapper.Span(l)
83 spans = append(spans, fmt.Sprint(span))
87 for _, s := range spans {