github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/cmd/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 cmd
     6  
     7  import (
     8  	"context"
     9  	"encoding/json"
    10  	"flag"
    11  	"fmt"
    12  	"os"
    13  	"strings"
    14  
    15  	"github.com/powerman/golang-tools/internal/lsp/protocol"
    16  	"github.com/powerman/golang-tools/internal/lsp/source"
    17  	"github.com/powerman/golang-tools/internal/span"
    18  	"github.com/powerman/golang-tools/internal/tool"
    19  	errors "golang.org/x/xerrors"
    20  )
    21  
    22  // A Definition is the result of a 'definition' query.
    23  type Definition struct {
    24  	Span        span.Span `json:"span"`        // span of the definition
    25  	Description string    `json:"description"` // description of the denoted object
    26  }
    27  
    28  // These constant is printed in the help, and then used in a test to verify the
    29  // help is still valid.
    30  // They refer to "Set" in "flag.FlagSet" from the DetailedHelp method below.
    31  const (
    32  	exampleLine   = 44
    33  	exampleColumn = 47
    34  	exampleOffset = 1270
    35  )
    36  
    37  // definition implements the definition verb for gopls.
    38  type definition struct {
    39  	app *Application
    40  
    41  	JSON              bool `flag:"json" help:"emit output in JSON format"`
    42  	MarkdownSupported bool `flag:"markdown" help:"support markdown in responses"`
    43  }
    44  
    45  func (d *definition) Name() string      { return "definition" }
    46  func (d *definition) Parent() string    { return d.app.Name() }
    47  func (d *definition) Usage() string     { return "[definition-flags] <position>" }
    48  func (d *definition) ShortHelp() string { return "show declaration of selected identifier" }
    49  func (d *definition) DetailedHelp(f *flag.FlagSet) {
    50  	fmt.Fprintf(f.Output(), `
    51  Example: show the definition of the identifier at syntax at offset %[1]v in this file (flag.FlagSet):
    52  
    53  	$ gopls definition internal/lsp/cmd/definition.go:%[1]v:%[2]v
    54  	$ gopls definition internal/lsp/cmd/definition.go:#%[3]v
    55  
    56  definition-flags:
    57  `, exampleLine, exampleColumn, exampleOffset)
    58  	printFlagDefaults(f)
    59  }
    60  
    61  // Run performs the definition query as specified by args and prints the
    62  // results to stdout.
    63  func (d *definition) Run(ctx context.Context, args ...string) error {
    64  	if len(args) != 1 {
    65  		return tool.CommandLineErrorf("definition expects 1 argument")
    66  	}
    67  	// Plaintext makes more sense for the command line.
    68  	opts := d.app.options
    69  	d.app.options = func(o *source.Options) {
    70  		if opts != nil {
    71  			opts(o)
    72  		}
    73  		o.PreferredContentFormat = protocol.PlainText
    74  		if d.MarkdownSupported {
    75  			o.PreferredContentFormat = protocol.Markdown
    76  		}
    77  	}
    78  	conn, err := d.app.connect(ctx)
    79  	if err != nil {
    80  		return err
    81  	}
    82  	defer conn.terminate(ctx)
    83  	from := span.Parse(args[0])
    84  	file := conn.AddFile(ctx, from.URI())
    85  	if file.err != nil {
    86  		return file.err
    87  	}
    88  	loc, err := file.mapper.Location(from)
    89  	if err != nil {
    90  		return err
    91  	}
    92  	tdpp := protocol.TextDocumentPositionParams{
    93  		TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI},
    94  		Position:     loc.Range.Start,
    95  	}
    96  	p := protocol.DefinitionParams{
    97  		TextDocumentPositionParams: tdpp,
    98  	}
    99  	locs, err := conn.Definition(ctx, &p)
   100  	if err != nil {
   101  		return errors.Errorf("%v: %v", from, err)
   102  	}
   103  
   104  	if len(locs) == 0 {
   105  		return errors.Errorf("%v: not an identifier", from)
   106  	}
   107  	q := protocol.HoverParams{
   108  		TextDocumentPositionParams: tdpp,
   109  	}
   110  	hover, err := conn.Hover(ctx, &q)
   111  	if err != nil {
   112  		return errors.Errorf("%v: %v", from, err)
   113  	}
   114  	if hover == nil {
   115  		return errors.Errorf("%v: not an identifier", from)
   116  	}
   117  	file = conn.AddFile(ctx, fileURI(locs[0].URI))
   118  	if file.err != nil {
   119  		return errors.Errorf("%v: %v", from, file.err)
   120  	}
   121  	definition, err := file.mapper.Span(locs[0])
   122  	if err != nil {
   123  		return errors.Errorf("%v: %v", from, err)
   124  	}
   125  	description := strings.TrimSpace(hover.Contents.Value)
   126  	result := &Definition{
   127  		Span:        definition,
   128  		Description: description,
   129  	}
   130  	if d.JSON {
   131  		enc := json.NewEncoder(os.Stdout)
   132  		enc.SetIndent("", "\t")
   133  		return enc.Encode(result)
   134  	}
   135  	fmt.Printf("%v: defined here as %s", result.Span, result.Description)
   136  	return nil
   137  }