Debian Codegraph @

gopls/internal/cmd/cmd.go

raw symbols SCIP
1 // Copyright 2018 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 handles the gopls command line.
6 // It contains a handler for each of the modes, along with all the flag handling
7 // and the command line output format.
8 package cmd
9
10 import (
11 "context"
12 "flag"
13 "fmt"
14 "log"
15 "os"
16 "path/filepath"
17 "reflect"
18 "sort"
19 "strings"
20 "sync"
21 "text/tabwriter"
22 "time"
23
24 "golang.org/x/tools/gopls/internal/cache"
25 "golang.org/x/tools/gopls/internal/debug"
26 "golang.org/x/tools/gopls/internal/filecache"
27 "golang.org/x/tools/gopls/internal/lsprpc"
28 "golang.org/x/tools/gopls/internal/protocol"
29 "golang.org/x/tools/gopls/internal/protocol/command"
30 "golang.org/x/tools/gopls/internal/protocol/semtok"
31 "golang.org/x/tools/gopls/internal/server"
32 "golang.org/x/tools/gopls/internal/settings"
33 "golang.org/x/tools/gopls/internal/tool"
34 "golang.org/x/tools/gopls/internal/util/browser"
35 "golang.org/x/tools/gopls/internal/util/bug"
36 "golang.org/x/tools/gopls/internal/util/moreslices"
37 "golang.org/x/tools/internal/diff"
38 "golang.org/x/tools/internal/jsonrpc2"
39 )
40
41 // Application is the main application as passed to tool.Main
42 // It handles the main command line parsing and dispatch to the sub commands.
43 type Application struct {
44 // Core application flags
45
46 // Embed the basic profiling flags supported by the tool package
47 tool.Profile
48
49 // We include the server configuration directly for now, so the flags work
50 // even without the verb.
51 // TODO: Remove this when we stop allowing the serve verb by default.
52 Serve Serve
53
54 // the options configuring function to invoke when building a server
55 options func(*settings.Options)
56
57 // Support for remote LSP server.
58 Remote string `flag:"remote" help:"forward all commands to a remote lsp specified by this flag. With no special prefix, this is assumed to be a TCP address. If prefixed by 'unix;', the subsequent address is assumed to be a unix domain socket. If 'auto', or prefixed by 'auto;', the remote address is automatically resolved based on the executing environment."`
59
60 // Verbose enables verbose logging.
61 Verbose bool `flag:"v,verbose" help:"verbose output"`
62
63 // VeryVerbose enables a higher level of verbosity in logging output.
64 VeryVerbose bool `flag:"vv,veryverbose" help:"very verbose output"`
65
66 // OTel specifies the OpenTelemetry collector endpoint (e.g. http://localhost:4318).
67 OTel string `flag:"otel" help:"export telemetry to specified OpenTelemetry collector address (e.g. http://localhost:4318)"`
68
69 // PrepareOptions is called to update the options when a new view is built.
70 // It is primarily to allow the behavior of gopls to be modified by hooks.
71 PrepareOptions func(*settings.Options)
72
73 // editFlags holds flags that control how file edit operations
74 // are applied, in particular when the server makes an ApplyEdits
75 // downcall to the client. Present only for commands that apply edits.
76 editFlags *EditFlags
77 }
78
79 // EditFlags defines flags common to {code{action,lens},format,imports,rename}
80 // that control how edits are applied to the client's files.
81 //
82 // The type is exported for flag reflection.
83 //
84 // The -write, -diff, and -list flags are orthogonal but any
85 // of them suppresses the default behavior, which is to print
86 // the edited file contents.
87 type EditFlags struct {
88 Write bool `flag:"w,write" help:"write edited content to source files"`
89 Preserve bool `flag:"preserve" help:"with -write, make copies of original files"`
90 Diff bool `flag:"d,diff" help:"display diffs instead of edited file content"`
91 List bool `flag:"l,list" help:"display names of edited files"`
92 }
93
94 func (app *Application) verbose() bool {
95 return app.Verbose || app.VeryVerbose
96 }
97
98 // New returns a new Application ready to run.
99 func New() *Application {
100 app := &Application{
101 Serve: Serve{
102 RemoteListenTimeout: 1 * time.Minute,
103 },
104 }
105 app.Serve.app = app
106 return app
107 }
108
109 // Name implements tool.Application returning the binary name.
110 func (app *Application) Name() string { return "gopls" }
111
112 // Usage implements tool.Application returning empty extra argument usage.
113 func (app *Application) Usage() string { return "" }
114
115 // ShortHelp implements tool.Application returning the main binary help.
116 func (app *Application) ShortHelp() string {
117 return ""
118 }
119
120 // DetailedHelp implements tool.Application returning the main binary help.
121 // This includes the short help for all the sub commands.
122 func (app *Application) DetailedHelp(f *flag.FlagSet) {
123 w := tabwriter.NewWriter(f.Output(), 0, 0, 2, ' ', 0)
124 defer w.Flush()
125
126 fmt.Fprint(w, `
127 gopls is a Go language server.
128
129 It is typically used with an editor to provide language features. When no
130 command is specified, gopls will default to the 'serve' command. The language
131 features can also be accessed via the gopls command-line interface.
132
133 For documentation of all its features, see:
134
135 https://github.com/golang/tools/blob/master/gopls/doc/features
136
137 Usage:
138 gopls help [<subject>]
139
140 Command:
141 `)
142 fmt.Fprint(w, "\nMain\t\n")
143 for _, c := range app.mainCommands() {
144 fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp())
145 }
146 fmt.Fprint(w, "\t\nFeatures\t\n")
147 for _, c := range app.featureCommands() {
148 fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp())
149 }
150 if app.verbose() {
151 fmt.Fprint(w, "\t\nInternal Use Only\t\n")
152 for _, c := range app.internalCommands() {
153 fmt.Fprintf(w, " %s\t%s\n", c.Name(), c.ShortHelp())
154 }
155 }
156 fmt.Fprint(w, "\nflags:\n")
157 printFlagDefaults(f)
158 }
159
160 // this is a slightly modified version of flag.PrintDefaults to give us control
161 func printFlagDefaults(s *flag.FlagSet) {
162 var flags [][]*flag.Flag
163 seen := map[flag.Value]int{}
164 s.VisitAll(func(f *flag.Flag) {
165 if i, ok := seen[f.Value]; !ok {
166 seen[f.Value] = len(flags)
167 flags = append(flags, []*flag.Flag{f})
168 } else {
169 flags[i] = append(flags[i], f)
170 }
171 })
172 for _, entry := range flags {
173 sort.SliceStable(entry, func(i, j int) bool {
174 return len(entry[i].Name) < len(entry[j].Name)
175 })
176 var b strings.Builder
177 for i, f := range entry {
178 switch i {
179 case 0:
180 b.WriteString(" -")
181 default:
182 b.WriteString(",-")
183 }
184 b.WriteString(f.Name)
185 }
186
187 f := entry[0]
188 name, usage := flag.UnquoteUsage(f)
189 if len(name) > 0 {
190 b.WriteString("=")
191 b.WriteString(name)
192 }
193 // Boolean flags of one ASCII letter are so common we
194 // treat them specially, putting their usage on the same line.
195 if b.Len() <= 4 { // space, space, '-', 'x'.
196 b.WriteString("\t")
197 } else {
198 // Four spaces before the tab triggers good alignment
199 // for both 4- and 8-space tab stops.
200 b.WriteString("\n \t")
201 }
202 b.WriteString(strings.ReplaceAll(usage, "\n", "\n \t"))
203 if !isZeroValue(f, f.DefValue) {
204 if reflect.TypeOf(f.Value).Elem().Name() == "stringValue" {
205 fmt.Fprintf(&b, " (default %q)", f.DefValue)
206 } else {
207 fmt.Fprintf(&b, " (default %v)", f.DefValue)
208 }
209 }
210 fmt.Fprint(s.Output(), b.String(), "\n")
211 }
212 }
213
214 // isZeroValue is copied from the flags package
215 func isZeroValue(f *flag.Flag, value string) bool {
216 // Build a zero value of the flag's Value type, and see if the
217 // result of calling its String method equals the value passed in.
218 // This works unless the Value type is itself an interface type.
219 typ := reflect.TypeOf(f.Value)
220 var z reflect.Value
221 if typ.Kind() == reflect.Pointer {
222 z = reflect.New(typ.Elem())
223 } else {
224 z = reflect.Zero(typ)
225 }
226 return value == z.Interface().(flag.Value).String()
227 }
228
229 // Run takes the args after top level flag processing, and invokes the correct
230 // sub command as specified by the first argument.
231 // If no arguments are passed it will invoke the server sub command, as a
232 // temporary measure for compatibility.
233 func (app *Application) Run(ctx context.Context, args ...string) error {
234 // In the category of "things we can do while waiting for the Go command":
235 // Pre-initialize the filecache, which takes ~50ms to hash the gopls
236 // executable, and immediately runs a gc.
237 filecache.Start()
238
239 ctx = debug.WithInstance(ctx, app.OTel)
240 if len(args) == 0 {
241 s := flag.NewFlagSet(app.Name(), flag.ExitOnError)
242 return tool.Run(ctx, s, &app.Serve, args)
243 }
244 command, args := args[0], args[1:]
245 for _, c := range app.Commands() {
246 if c.Name() == command {
247 s := flag.NewFlagSet(app.Name(), flag.ExitOnError)
248 return tool.Run(ctx, s, c, args)
249 }
250 }
251 return tool.CommandLineErrorf("Unknown command %v", command)
252 }
253
254 // Commands returns the set of commands supported by the gopls tool on the
255 // command line.
256 // The command is specified by the first non flag argument.
257 func (app *Application) Commands() []tool.Application {
258 var commands []tool.Application
259 commands = append(commands, app.mainCommands()...)
260 commands = append(commands, app.featureCommands()...)
261 commands = append(commands, app.internalCommands()...)
262 return commands
263 }
264
265 func (app *Application) mainCommands() []tool.Application {
266 return []tool.Application{
267 &app.Serve,
268 &version{app: app},
269 &help{app: app},
270 &apiJSON{app: app},
271 &licenses{app: app},
272 }
273 }
274
275 func (app *Application) internalCommands() []tool.Application {
276 return []tool.Application{
277 &vulncheck{app: app},
278 }
279 }
280
281 func (app *Application) featureCommands() []tool.Application {
282 return []tool.Application{
283 &callHierarchy{app: app},
284 &check{app: app, Severity: "warning"},
285 &codeaction{app: app},
286 &codelens{app: app},
287 &definition{app: app},
288 &execute{app: app},
289 &fix{app: app}, // (non-functional)
290 &foldingRanges{app: app},
291 &format{app: app},
292 &headlessMCP{app: app},
293 &highlight{app: app},
294 &implementation{app: app},
295 &imports{app: app},
296 newRemote(app, ""),
297 newRemote(app, "inspect"),
298 &links{app: app},
299 &prepareRename{app: app},
300 &references{app: app},
301 &rename{app: app},
302 &semanticToken{app: app},
303 &signature{app: app},
304 &stats{app: app},
305 &symbols{app: app},
306
307 &workspaceSymbol{app: app},
308 }
309 }
310
311 // connect creates and initializes a new in-process gopls LSP session.
312 func (app *Application) connect(ctx context.Context) (*client, *cache.Session, error) {
313 root, err := os.Getwd()
314 if err != nil {
315 return nil, nil, fmt.Errorf("finding workdir: %v", err)
316 }
317 options := settings.DefaultOptions(app.options)
318 client := newClient(app)
319 var (
320 svr protocol.Server
321 sess *cache.Session
322 )
323 if app.Remote == "" {
324 // local
325 sess = cache.NewSession(ctx, cache.New(nil))
326 svr = server.New(sess, client, options)
327 ctx = protocol.WithClient(ctx, client)
328 } else {
329 // remote
330 netConn, err := lsprpc.ConnectToRemote(ctx, app.Remote)
331 if err != nil {
332 return nil, nil, err
333 }
334 stream := jsonrpc2.NewHeaderStream(netConn)
335 jsonConn := jsonrpc2.NewConn(stream)
336 svr = protocol.ServerDispatcher(jsonConn)
337 ctx = protocol.WithClient(ctx, client)
338 jsonConn.Go(ctx,
339 protocol.Handlers(
340 protocol.ClientHandler(client, jsonrpc2.MethodNotFound)))
341 }
342 if err := client.initialize(ctx, svr, initParams(root, options)); err != nil {
343 return nil, nil, err
344 }
345 return client, sess, nil
346 }
347
348 func initParams(rootDir string, opts *settings.Options) *protocol.ParamInitialize {
349 params := &protocol.ParamInitialize{}
350 params.RootURI = protocol.URIFromPath(rootDir)
351 params.Capabilities.Workspace.Configuration = true
352
353 // If you add an additional option here,
354 // you must update the map key of settings.DefaultOptions called in (*Application).connect.
355 params.Capabilities.TextDocument.Hover = &protocol.HoverClientCapabilities{
356 ContentFormat: []protocol.MarkupKind{opts.PreferredContentFormat},
357 }
358 params.Capabilities.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport = opts.HierarchicalDocumentSymbolSupport
359 params.Capabilities.TextDocument.SemanticTokens = protocol.SemanticTokensClientCapabilities{}
360 params.Capabilities.TextDocument.SemanticTokens.Formats = []protocol.TokenFormat{"relative"}
361 params.Capabilities.TextDocument.SemanticTokens.Requests.Range = &protocol.Or_ClientSemanticTokensRequestOptions_range{Value: true}
362 // params.Capabilities.TextDocument.SemanticTokens.Requests.Range.Value = true
363 params.Capabilities.TextDocument.SemanticTokens.Requests.Full = &protocol.Or_ClientSemanticTokensRequestOptions_full{Value: true}
364 params.Capabilities.TextDocument.SemanticTokens.TokenTypes = moreslices.ConvertStrings[string](semtok.Types)
365 params.Capabilities.TextDocument.SemanticTokens.TokenModifiers = moreslices.ConvertStrings[string](semtok.Modifiers)
366 params.Capabilities.TextDocument.CodeAction = protocol.CodeActionClientCapabilities{
367 CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{
368 CodeActionKind: protocol.ClientCodeActionKindOptions{
369 ValueSet: []protocol.CodeActionKind{protocol.Empty}, // => all
370 },
371 },
372 }
373 params.Capabilities.Window.WorkDoneProgress = true
374 params.Capabilities.Workspace.FileOperations = &protocol.FileOperationClientCapabilities{
375 DidCreate: true,
376 }
377 params.InitializationOptions = map[string]any{
378 "symbolMatcher": string(opts.SymbolMatcher),
379 }
380 return params
381 }
382
383 // initialize performs LSP's two-call client/server handshake.
384 func (cli *client) initialize(ctx context.Context, server protocol.Server, params *protocol.ParamInitialize) error {
385 result, err := server.Initialize(ctx, params)
386 if err != nil {
387 return err
388 }
389 if err := server.Initialized(ctx, &protocol.InitializedParams{}); err != nil {
390 return err
391 }
392 cli.server = server
393 cli.initializeResult = result
394 return nil
395 }
396
397 // client implements [protocol.Client] and defines the LSP client
398 // operations of the gopls command.
399 //
400 // It holds the client-side state of a single client/server
401 // connection; it conceptually corresponds to a single call to
402 // connect(2).
403 type client struct {
404 app *Application
405
406 server protocol.Server
407 initializeResult *protocol.InitializeResult // includes server capabilities
408
409 progressMu sync.Mutex
410 iwlToken protocol.ProgressToken
411 iwlDone chan struct{}
412
413 filesMu sync.Mutex // guards files map
414 files map[protocol.DocumentURI]*cmdFile
415 }
416
417 // cmdFile represents an open file in the gopls command LSP client.
418 type cmdFile struct {
419 uri protocol.DocumentURI
420 mapper *protocol.Mapper
421 err error
422 diagnosticsMu sync.Mutex
423 diagnostics []protocol.Diagnostic
424 }
425
426 func newClient(app *Application) *client {
427 return &client{
428 app: app,
429 files: make(map[protocol.DocumentURI]*cmdFile),
430 iwlDone: make(chan struct{}),
431 }
432 }
433
434 func (cli *client) TextDocumentContentRefresh(context.Context, *protocol.TextDocumentContentRefreshParams) error {
435 return nil
436 }
437
438 func (cli *client) CodeLensRefresh(context.Context) error { return nil }
439
440 func (cli *client) FoldingRangeRefresh(context.Context) error { return nil }
441
442 func (cli *client) LogTrace(context.Context, *protocol.LogTraceParams) error { return nil }
443
444 func (cli *client) ShowMessage(ctx context.Context, p *protocol.ShowMessageParams) error {
445 fmt.Fprintf(os.Stderr, "%s: %s\n", p.Type, p.Message)
446 return nil
447 }
448
449 func (cli *client) ShowMessageRequest(ctx context.Context, p *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) {
450 return nil, nil
451 }
452
453 func (cli *client) LogMessage(ctx context.Context, p *protocol.LogMessageParams) error {
454 // This logic causes server logging to be double-prefixed with a timestamp.
455 // 2023/11/08 10:50:21 Error:2023/11/08 10:50:21 <actual message>
456 // TODO(adonovan): print just p.Message, plus a newline if needed?
457 switch p.Type {
458 case protocol.Error:
459 log.Print("Error:", p.Message)
460 case protocol.Warning:
461 log.Print("Warning:", p.Message)
462 case protocol.Info:
463 if cli.app.verbose() {
464 log.Print("Info:", p.Message)
465 }
466 case protocol.Log:
467 if cli.app.verbose() {
468 log.Print("Log:", p.Message)
469 }
470 default:
471 if cli.app.verbose() {
472 log.Print(p.Message)
473 }
474 }
475 return nil
476 }
477
478 func (cli *client) Event(ctx context.Context, t *any) error { return nil }
479
480 func (cli *client) RegisterCapability(ctx context.Context, p *protocol.RegistrationParams) error {
481 return nil
482 }
483
484 func (cli *client) UnregisterCapability(ctx context.Context, p *protocol.UnregistrationParams) error {
485 return nil
486 }
487
488 func (cli *client) WorkspaceFolders(ctx context.Context) ([]protocol.WorkspaceFolder, error) {
489 return nil, nil
490 }
491
492 func (cli *client) Configuration(ctx context.Context, p *protocol.ParamConfiguration) ([]any, error) {
493 results := make([]any, len(p.Items))
494 for i, item := range p.Items {
495 if item.Section != "gopls" {
496 continue
497 }
498 m := map[string]any{
499 "analyses": map[string]any{
500 "fillreturns": true,
501 "nonewvars": true,
502 "noresultvalues": true,
503 "undeclaredname": true,
504 },
505 }
506 if cli.app.VeryVerbose {
507 m["verboseOutput"] = true
508 }
509 results[i] = m
510 }
511 return results, nil
512 }
513
514 func (cli *client) ApplyEdit(ctx context.Context, p *protocol.ApplyWorkspaceEditParams) (*protocol.ApplyWorkspaceEditResult, error) {
515 if err := cli.applyWorkspaceEdit(&p.Edit); err != nil {
516 return &protocol.ApplyWorkspaceEditResult{FailureReason: err.Error()}, nil
517 }
518 return &protocol.ApplyWorkspaceEditResult{Applied: true}, nil
519 }
520
521 // applyWorkspaceEdit applies a complete WorkspaceEdit to the client's
522 // files, honoring the preferred edit mode specified by cli.app.editMode.
523 // (Used by rename and by ApplyEdit downcalls.)
524 //
525 // See also:
526 // - changedFiles in ../test/marker/marker_test.go for the golden-file capturing variant
527 // - applyWorkspaceEdit in ../test/integration/fake/editor.go for the Editor variant
528 func (cli *client) applyWorkspaceEdit(wsedit *protocol.WorkspaceEdit) error {
529
530 create := func(uri protocol.DocumentURI, content []byte) error {
531 edits := []diff.Edit{{Start: 0, End: 0, New: string(content)}}
532 return updateFile(uri.Path(), nil, content, edits, cli.app.editFlags)
533 }
534
535 delete := func(uri protocol.DocumentURI, content []byte) error {
536 edits := []diff.Edit{{Start: 0, End: len(content), New: ""}}
537 return updateFile(uri.Path(), content, nil, edits, cli.app.editFlags)
538 }
539
540 for _, c := range wsedit.DocumentChanges {
541 switch {
542 case c.TextDocumentEdit != nil:
543 f := cli.getFile(c.TextDocumentEdit.TextDocument.URI)
544 if f.err != nil {
545 return f.err
546 }
547 // TODO(adonovan): sanity-check c.TextDocumentEdit.TextDocument.Version
548 edits := protocol.AsTextEdits(c.TextDocumentEdit.Edits)
549 if err := applyTextEdits(f.mapper, edits, cli.app.editFlags); err != nil {
550 return err
551 }
552
553 case c.CreateFile != nil:
554 if err := create(c.CreateFile.URI, []byte{}); err != nil {
555 return err
556 }
557
558 case c.RenameFile != nil:
559 // Analyze as creation + deletion. (NB: loses file mode.)
560 f := cli.getFile(c.RenameFile.OldURI)
561 if f.err != nil {
562 return f.err
563 }
564 if err := create(c.RenameFile.NewURI, f.mapper.Content); err != nil {
565 return err
566 }
567 if err := delete(f.mapper.URI, f.mapper.Content); err != nil {
568 return err
569 }
570
571 case c.DeleteFile != nil:
572 f := cli.getFile(c.DeleteFile.URI)
573 if f.err != nil {
574 return f.err
575 }
576 if err := delete(f.mapper.URI, f.mapper.Content); err != nil {
577 return err
578 }
579
580 default:
581 return fmt.Errorf("unknown DocumentChange: %#v", c)
582 }
583 }
584 return nil
585 }
586
587 // applyTextEdits applies a list of edits to the mapper file content,
588 // using the preferred edit mode. It is a no-op if there are no edits.
589 func applyTextEdits(mapper *protocol.Mapper, edits []protocol.TextEdit, flags *EditFlags) error {
590 if len(edits) == 0 {
591 return nil
592 }
593 newContent, diffEdits, err := protocol.ApplyEdits(mapper, edits)
594 if err != nil {
595 return err
596 }
597 return updateFile(mapper.URI.Path(), mapper.Content, newContent, diffEdits, flags)
598 }
599
600 // updateFile performs a content update operation on the specified file.
601 // If the old content is nil, the operation creates the file.
602 // If the new content is nil, the operation deletes the file.
603 // The flags control whether the operation is written, or merely listed, diffed, or printed.
604 func updateFile(filename string, old, new []byte, edits []diff.Edit, flags *EditFlags) error {
605 if flags.List {
606 fmt.Println(filename)
607 }
608
609 if flags.Write {
610 if flags.Preserve && old != nil { // edit or delete
611 if err := os.WriteFile(filename+".orig", old, 0666); err != nil {
612 return err
613 }
614 }
615
616 if new != nil {
617 // create or edit
618 if err := os.WriteFile(filename, new, 0666); err != nil {
619 return err
620 }
621 } else {
622 // delete
623 if err := os.Remove(filename); err != nil {
624 return err
625 }
626 }
627 }
628
629 if flags.Diff {
630 // For diffing, creations and deletions are equivalent
631 // updating an empty file and making an existing file empty.
632 unified, err := diff.ToUnified(filename+".orig", filename, string(old), edits, diff.DefaultContextLines)
633 if err != nil {
634 return err
635 }
636 fmt.Print(unified)
637 }
638
639 // No flags: just print edited file content.
640 //
641 // This makes no sense for multiple files.
642 // (We should probably change the default to -diff.)
643 if !(flags.List || flags.Write || flags.Diff) {
644 os.Stdout.Write(new)
645 }
646
647 return nil
648 }
649
650 func (cli *client) PublishDiagnostics(ctx context.Context, p *protocol.PublishDiagnosticsParams) error {
651 // Don't worry about diagnostics without versions.
652 //
653 // (Note: the representation of PublishDiagnosticsParams
654 // cannot distinguish a missing Version from v0, but the
655 // server never sends back an explicit zero.)
656 if p.Version == 0 {
657 return nil
658 }
659
660 file := cli.getFile(p.URI)
661
662 file.diagnosticsMu.Lock()
663 defer file.diagnosticsMu.Unlock()
664
665 file.diagnostics = append(file.diagnostics, p.Diagnostics...)
666
667 // Perform a crude in-place deduplication.
668 // TODO(golang/go#60122): replace the gopls.diagnose_files
669 // command with support for textDocument/diagnostic,
670 // so that we don't need to do this de-duplication.
671 type key [6]any
672 seen := make(map[key]bool)
673 out := file.diagnostics[:0]
674 for _, d := range file.diagnostics {
675 var codeHref string
676 if desc := d.CodeDescription; desc != nil {
677 codeHref = desc.Href
678 }
679 k := key{d.Range, d.Severity, d.Code, codeHref, d.Source, d.Message}
680 if !seen[k] {
681 seen[k] = true
682 out = append(out, d)
683 }
684 }
685 file.diagnostics = out
686
687 return nil
688 }
689
690 func (cli *client) Progress(_ context.Context, params *protocol.ProgressParams) error {
691 if _, ok := params.Token.(string); !ok {
692 return fmt.Errorf("unexpected progress token: %[1]T %[1]v", params.Token)
693 }
694
695 switch v := params.Value.(type) {
696 case *protocol.WorkDoneProgressBegin:
697 if v.Title == server.DiagnosticWorkTitle(server.FromInitialWorkspaceLoad) {
698 cli.progressMu.Lock()
699 cli.iwlToken = params.Token
700 cli.progressMu.Unlock()
701 }
702
703 case *protocol.WorkDoneProgressReport:
704 if cli.app.Verbose {
705 fmt.Fprintln(os.Stderr, v.Message)
706 }
707
708 case *protocol.WorkDoneProgressEnd:
709 cli.progressMu.Lock()
710 iwlToken := cli.iwlToken
711 cli.progressMu.Unlock()
712
713 if params.Token == iwlToken {
714 close(cli.iwlDone)
715 }
716 }
717 return nil
718 }
719
720 func (cli *client) ShowDocument(ctx context.Context, params *protocol.ShowDocumentParams) (*protocol.ShowDocumentResult, error) {
721 var success bool
722 if params.External {
723 // Open URI in external browser.
724 success = browser.Open(params.URI)
725 } else {
726 // Open file in editor, optionally taking focus and selecting a range.
727 // (client has no editor. Should it fork+exec $EDITOR?)
728 log.Printf("Server requested that client editor open %q (takeFocus=%t, selection=%+v)",
729 params.URI, params.TakeFocus, params.Selection)
730 success = true
731 }
732 return &protocol.ShowDocumentResult{Success: success}, nil
733 }
734
735 func (cli *client) WorkDoneProgressCreate(context.Context, *protocol.WorkDoneProgressCreateParams) error {
736 return nil
737 }
738
739 func (cli *client) DiagnosticRefresh(context.Context) error {
740 return nil
741 }
742
743 func (cli *client) InlayHintRefresh(context.Context) error {
744 return nil
745 }
746
747 func (cli *client) SemanticTokensRefresh(context.Context) error {
748 return nil
749 }
750
751 func (cli *client) InlineValueRefresh(context.Context) error {
752 return nil
753 }
754
755 // getFile returns the specified file, adding it to the client state if needed.
756 func (cli *client) getFile(uri protocol.DocumentURI) *cmdFile {
757 cli.filesMu.Lock()
758 defer cli.filesMu.Unlock()
759
760 file, found := cli.files[uri]
761 if !found || file.err != nil {
762 file = &cmdFile{
763 uri: uri,
764 }
765 cli.files[uri] = file
766 }
767 if file.mapper == nil {
768 content, err := os.ReadFile(uri.Path())
769 if err != nil {
770 file.err = fmt.Errorf("getFile: %v: %v", uri, err)
771 return file
772 }
773 file.mapper = protocol.NewMapper(uri, content)
774 }
775 return file
776 }
777
778 // openFile returns the specified file, adding it to the client state
779 // if needed, and notifying the server that it was opened.
780 func (cli *client) openFile(ctx context.Context, uri protocol.DocumentURI) (*cmdFile, error) {
781 file := cli.getFile(uri)
782 if file.err != nil {
783 return nil, file.err
784 }
785
786 // Choose language ID from file extension.
787 var langID protocol.LanguageKind // "" eventually maps to file.UnknownKind
788 switch filepath.Ext(uri.Path()) {
789 case ".go":
790 langID = "go"
791 case ".mod":
792 langID = "go.mod"
793 case ".sum":
794 langID = "go.sum"
795 case ".work":
796 langID = "go.work"
797 case ".s":
798 langID = "go.s"
799 }
800
801 p := &protocol.DidOpenTextDocumentParams{
802 TextDocument: protocol.TextDocumentItem{
803 URI: uri,
804 LanguageID: langID,
805 Version: 1,
806 Text: string(file.mapper.Content),
807 },
808 }
809 if err := cli.server.DidOpen(ctx, p); err != nil {
810 // TODO(adonovan): is this assignment concurrency safe?
811 file.err = fmt.Errorf("%v: %v", uri, err)
812 return nil, file.err
813 }
814 return file, nil
815 }
816
817 func diagnoseFiles(ctx context.Context, server protocol.Server, files []protocol.DocumentURI) error {
818 cmd := command.NewDiagnoseFilesCommand("Diagnose files", command.DiagnoseFilesArgs{
819 Files: files,
820 })
821 _, err := executeCommand(ctx, server, cmd)
822 return err
823 }
824
825 func (cli *client) terminate(ctx context.Context) {
826 if err := cli.server.Shutdown(ctx); err != nil {
827 log.Printf("server shutdown failed: %v", err)
828 }
829
830 // Don't call Exit as it terminates the server process,
831 // which is the same as this client process.
832 // c.server.Exit(ctx)
833 }
834
835 // Implement io.Closer.
836 func (cli *client) Close() error {
837 return nil
838 }
839
840 // -- conversions to span (UTF-8) domain --
841
842 // locationSpan converts a protocol (UTF-16) Location to a (UTF-8) span.
843 // Precondition: the URIs of Location and Mapper match.
844 func (f *cmdFile) locationSpan(loc protocol.Location) (span, error) {
845 // TODO(adonovan): check that l.URI matches m.URI.
846 return f.rangeSpan(loc.Range)
847 }
848
849 // rangeSpan converts a protocol (UTF-16) range to a (UTF-8) span.
850 // The resulting span has valid Positions and Offsets.
851 func (f *cmdFile) rangeSpan(r protocol.Range) (span, error) {
852 start, end, err := f.mapper.RangeOffsets(r)
853 if err != nil {
854 return span{}, err
855 }
856 return f.offsetSpan(start, end)
857 }
858
859 // offsetSpan converts a byte-offset interval to a (UTF-8) span.
860 // The resulting span contains line, column, and offset information.
861 func (f *cmdFile) offsetSpan(start, end int) (span, error) {
862 if start > end {
863 return span{}, fmt.Errorf("start offset (%d) > end (%d)", start, end)
864 }
865 startPoint, err := offsetPoint(f.mapper, start)
866 if err != nil {
867 return span{}, fmt.Errorf("start: %v", err)
868 }
869 endPoint, err := offsetPoint(f.mapper, end)
870 if err != nil {
871 return span{}, fmt.Errorf("end: %v", err)
872 }
873 return newSpan(f.mapper.URI, startPoint, endPoint), nil
874 }
875
876 // offsetPoint converts a byte offset to a span (UTF-8) point.
877 // The resulting point contains line, column, and offset information.
878 func offsetPoint(m *protocol.Mapper, offset int) (point, error) {
879 if !(0 <= offset && offset <= len(m.Content)) {
880 return point{}, fmt.Errorf("invalid offset %d (want 0-%d)", offset, len(m.Content))
881 }
882 line, col8 := m.OffsetLineCol8(offset)
883 return newPoint(line, col8, offset), nil
884 }
885
886 // -- conversions from span (UTF-8) domain --
887
888 // spanLocation converts a (UTF-8) span to a protocol (UTF-16) range.
889 // Precondition: the URIs of spanLocation and Mapper match.
890 func (f *cmdFile) spanLocation(s span) (protocol.Location, error) {
891 rng, err := f.spanRange(s)
892 if err != nil {
893 return protocol.Location{}, err
894 }
895 return f.mapper.URI.Location(rng), nil
896 }
897
898 // spanRange converts a (UTF-8) span to a protocol (UTF-16) range.
899 // Precondition: the URIs of span and Mapper match.
900 func (f *cmdFile) spanRange(s span) (protocol.Range, error) {
901 // Assert that we aren't using the wrong mapper.
902 // We check only the base name, and case insensitively,
903 // because we can't assume clean paths, no symbolic links,
904 // case-sensitive directories. The authoritative answer
905 // requires querying the file system, and we don't want
906 // to do that.
907 if !strings.EqualFold(f.mapper.URI.Base(), s.URI().Base()) {
908 return protocol.Range{}, bug.Errorf("mapper is for file %q instead of %q", f.mapper.URI, s.URI())
909 }
910 start, err := pointPosition(f.mapper, s.Start())
911 if err != nil {
912 return protocol.Range{}, fmt.Errorf("start: %w", err)
913 }
914 end, err := pointPosition(f.mapper, s.End())
915 if err != nil {
916 return protocol.Range{}, fmt.Errorf("end: %w", err)
917 }
918 return protocol.Range{Start: start, End: end}, nil
919 }
920
921 // pointPosition converts a valid span (UTF-8) point to a protocol (UTF-16) position.
922 func pointPosition(m *protocol.Mapper, p point) (protocol.Position, error) {
923 if p.HasPosition() {
924 return m.LineCol8Position(p.Line(), p.Column())
925 }
926 if p.HasOffset() {
927 return m.OffsetPosition(p.Offset())
928 }
929 return protocol.Position{}, fmt.Errorf("point has neither offset nor line/column")
930 }
931
932 // TODO(adonovan): delete in 2025.
933 type fix struct{ app *Application }
934
935 func (*fix) Name() string { return "fix" }
936 func (cmd *fix) Parent() string { return cmd.app.Name() }
937 func (*fix) Usage() string { return "" }
938 func (*fix) ShortHelp() string { return "apply suggested fixes (obsolete)" }
939 func (*fix) DetailedHelp(flags *flag.FlagSet) {
940 fmt.Fprintf(flags.Output(), `No longer supported; use "gopls codeaction" instead.`)
941 }
942 func (*fix) Run(ctx context.Context, args ...string) error {
943 return tool.CommandLineErrorf(`no longer supported; use "gopls codeaction" instead`)
944 }