github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/internal/lsp/cmd/implementation.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  	"flag"
    10  	"fmt"
    11  	"sort"
    12  
    13  	"github.com/jhump/golang-x-tools/internal/lsp/protocol"
    14  	"github.com/jhump/golang-x-tools/internal/span"
    15  	"github.com/jhump/golang-x-tools/internal/tool"
    16  )
    17  
    18  // implementation implements the implementation verb for gopls
    19  type implementation struct {
    20  	app *Application
    21  }
    22  
    23  func (i *implementation) Name() string      { return "implementation" }
    24  func (i *implementation) Parent() string    { return i.app.Name() }
    25  func (i *implementation) Usage() string     { return "<position>" }
    26  func (i *implementation) ShortHelp() string { return "display selected identifier's implementation" }
    27  func (i *implementation) DetailedHelp(f *flag.FlagSet) {
    28  	fmt.Fprint(f.Output(), `
    29  Example:
    30  
    31  	$ # 1-indexed location (:line:column or :#offset) of the target identifier
    32  	$ gopls implementation helper/helper.go:8:6
    33  	$ gopls implementation helper/helper.go:#53
    34  `)
    35  	printFlagDefaults(f)
    36  }
    37  
    38  func (i *implementation) Run(ctx context.Context, args ...string) error {
    39  	if len(args) != 1 {
    40  		return tool.CommandLineErrorf("implementation expects 1 argument (position)")
    41  	}
    42  
    43  	conn, err := i.app.connect(ctx)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	defer conn.terminate(ctx)
    48  
    49  	from := span.Parse(args[0])
    50  	file := conn.AddFile(ctx, from.URI())
    51  	if file.err != nil {
    52  		return file.err
    53  	}
    54  
    55  	loc, err := file.mapper.Location(from)
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	p := protocol.ImplementationParams{
    61  		TextDocumentPositionParams: protocol.TextDocumentPositionParams{
    62  			TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI},
    63  			Position:     loc.Range.Start,
    64  		},
    65  	}
    66  
    67  	implementations, err := conn.Implementation(ctx, &p)
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	var spans []string
    73  	for _, impl := range implementations {
    74  		f := conn.AddFile(ctx, fileURI(impl.URI))
    75  		span, err := f.mapper.Span(impl)
    76  		if err != nil {
    77  			return err
    78  		}
    79  		spans = append(spans, fmt.Sprint(span))
    80  	}
    81  	sort.Strings(spans)
    82  
    83  	for _, s := range spans {
    84  		fmt.Println(s)
    85  	}
    86  
    87  	return nil
    88  }