Debian Codegraph @

gopls/internal/protocol/command/interface.go

raw symbols SCIP
1 // Copyright 2021 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 //go:generate go run -tags=generate generate.go
6
7 // Package command defines the interface provided by gopls for the
8 // workspace/executeCommand LSP request.
9 //
10 // This interface is fully specified by the Interface type, provided it
11 // conforms to the restrictions outlined in its doc string.
12 //
13 // Bindings for server-side command dispatch and client-side serialization are
14 // also provided by this package, via code generation.
15 package command
16
17 import (
18 "context"
19 "encoding/json"
20 "fmt"
21
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/vulncheck"
24 )
25
26 // Interface defines the interface gopls exposes for the
27 // workspace/executeCommand request.
28 //
29 // This interface is used to generate logic for marshaling,
30 // unmarshaling, and dispatch, so it has some additional restrictions:
31 //
32 // 1. All method arguments must be JSON serializable and strictly typed
33 // (infallible) so they can be safely unmarshaled from the JSON
34 // Arguments array. The only exception is the final input parameter,
35 // which may be exactly [*protocol.InteractiveParams]. While this type
36 // contains an 'any' slice, it is explicitly exempted by the code
37 // generator because it is passed directly from the top-level
38 // ExecuteCommandParams rather than unmarshaled from the Arguments
39 // array. Its dynamic values are validated manually by the command
40 // handlers at runtime.
41 //
42 // 2. Methods must return either error or (T, error), where T is a
43 // JSON serializable type.
44 //
45 // 3. The first line of the doc string is special.
46 // Everything after the colon is considered the command 'Title'.
47 // For example:
48 //
49 // Command: Capitalized verb phrase with no period
50 //
51 // Longer description here...
52 type Interface interface {
53 // ApplyFix: Apply a fix
54 //
55 // Applies a fix to a region of source code.
56 ApplyFix(context.Context, ApplyFixArgs) (*protocol.WorkspaceEdit, error)
57
58 // RunTests: Run tests
59 //
60 // Runs `go test` for a specific set of test or benchmark functions.
61 //
62 // This command is asynchronous; clients must wait for the 'end' progress notification.
63 RunTests(context.Context, RunTestsArgs) error
64
65 // Generate: Run go generate
66 //
67 // Runs `go generate` for a given directory.
68 Generate(context.Context, GenerateArgs) error
69
70 // Doc: Browse package documentation.
71 //
72 // Opens the Go package documentation page for the current
73 // package in a browser.
74 Doc(context.Context, DocArgs) (protocol.URI, error)
75
76 // SplitPackage: organize a package into two or more components
77 //
78 // Opens the "split package" tool in a web browser.
79 SplitPackage(ctx context.Context, viewID, packageID string) error
80
81 // RegenerateCgo: Regenerate cgo
82 //
83 // Regenerates cgo definitions.
84 RegenerateCgo(context.Context, URIArg) error
85
86 // Tidy: Run go mod tidy
87 //
88 // Runs `go mod tidy` for a module.
89 Tidy(context.Context, URIArgs) error
90
91 // Vendor: Run go mod vendor
92 //
93 // Runs `go mod vendor` for a module.
94 Vendor(context.Context, URIArg) error
95
96 // EditGoDirective: Run go mod edit -go=version
97 //
98 // Runs `go mod edit -go=version` for a module.
99 EditGoDirective(context.Context, EditGoDirectiveArgs) error
100
101 // UpdateGoSum: Update go.sum
102 //
103 // Updates the go.sum file for a module.
104 UpdateGoSum(context.Context, URIArgs) error
105
106 // CheckUpgrades: Check for upgrades
107 //
108 // Checks for module upgrades.
109 CheckUpgrades(context.Context, CheckUpgradesArgs) error
110
111 // AddDependency: Add a dependency
112 //
113 // Adds a dependency to the go.mod file for a module.
114 AddDependency(context.Context, DependencyArgs) error
115
116 // UpgradeDependency: Upgrade a dependency
117 //
118 // Upgrades a dependency in the go.mod file for a module.
119 UpgradeDependency(context.Context, DependencyArgs) error
120
121 // RemoveDependency: Remove a dependency
122 //
123 // Removes a dependency from the go.mod file of a module.
124 RemoveDependency(context.Context, RemoveDependencyArgs) error
125
126 // ResetGoModDiagnostics: Reset go.mod diagnostics
127 //
128 // Reset diagnostics in the go.mod file of a module.
129 ResetGoModDiagnostics(context.Context, ResetGoModDiagnosticsArgs) error
130
131 // GoGetPackage: 'go get' a package
132 //
133 // Runs `go get` to fetch a package.
134 GoGetPackage(context.Context, GoGetPackageArgs) error
135
136 // GCDetails: Toggle display of compiler optimization details
137 //
138 // Toggle the per-package flag that causes Go compiler
139 // optimization decisions to be reported as diagnostics.
140 //
141 // (The name is a legacy of a time when the Go compiler was
142 // known as "gc". Renaming the command would break custom
143 // client-side logic in VS Code.)
144 GCDetails(context.Context, protocol.DocumentURI) error
145
146 // LSP is a command that functions as a generic dispatcher, allowing clients
147 // to execute any LSP RPC through the "workspace/executeCommand" request.
148 //
149 // This serves two primary purposes:
150 //
151 // 1. It provides a unified endpoint for clients that are restricted from
152 // making arbitrary LSP calls directly, giving them full access to the
153 // server's capabilities.
154 //
155 // 2. It allows the client and server to extend the standard protocol. A
156 // client can send custom parameters that are not part of the official
157 // LSP, enabling richer functionality.
158 //
159 // The command takes the target LSP method name and its parameters as a
160 // [json.RawMessage], routing the call to the appropriate internal handler.
161 LSP(context.Context, LSPArgs) (any, error)
162
163 // ListKnownPackages: List known packages
164 //
165 // Retrieve a list of packages that are importable from the given URI.
166 ListKnownPackages(context.Context, URIArg) (ListKnownPackagesResult, error)
167
168 // ListImports: List imports of a file and its package
169 //
170 // Retrieve a list of imports in the given Go file, and the package it
171 // belongs to.
172 ListImports(context.Context, URIArg) (ListImportsResult, error)
173
174 // AddImport: Add an import
175 //
176 // Ask the server to add an import path to a given Go file. The method will
177 // call applyEdit on the client so that clients don't have to apply the edit
178 // themselves.
179 AddImport(context.Context, AddImportArgs) error
180
181 // ExtractToNewFile: Move selected declarations to a new file
182 //
183 // Used by the code action of the same name.
184 ExtractToNewFile(context.Context, protocol.Location) error
185
186 // StartDebugging: Start the gopls debug server
187 //
188 // Start the gopls debug server if it isn't running, and return the debug
189 // address.
190 StartDebugging(context.Context, DebuggingArgs) (DebuggingResult, error)
191
192 // StartProfile: Start capturing a profile of gopls' execution
193 //
194 // Start a new pprof profile. Before using the resulting file, profiling must
195 // be stopped with a corresponding call to StopProfile.
196 //
197 // This command is intended for internal use only, by the gopls benchmark
198 // runner.
199 StartProfile(context.Context, StartProfileArgs) (StartProfileResult, error)
200
201 // StopProfile: Stop an ongoing profile
202 //
203 // This command is intended for internal use only, by the gopls benchmark
204 // runner.
205 StopProfile(context.Context, StopProfileArgs) (StopProfileResult, error)
206
207 // GoVulncheck: run vulncheck synchronously.
208 //
209 // Run vulnerability check (`govulncheck`).
210 //
211 // This command is synchronous, and returns the govulncheck result.
212 Vulncheck(context.Context, VulncheckArgs) (VulncheckResult, error)
213
214 // RunGovulncheck: Run vulncheck asynchronously.
215 //
216 // Run vulnerability check (`govulncheck`).
217 //
218 // This command is asynchronous; clients must wait for the 'end' progress
219 // notification and then retrieve results using gopls.fetch_vulncheck_result.
220 //
221 // Deprecated: clients should call gopls.vulncheck instead, which returns the
222 // actual vulncheck result.
223 RunGovulncheck(context.Context, VulncheckArgs) (RunVulncheckResult, error)
224
225 // FetchVulncheckResult: Get known vulncheck result
226 //
227 // Fetch the result of latest vulnerability check (`govulncheck`).
228 //
229 // Deprecated: clients should call gopls.vulncheck instead, which returns the
230 // actual vulncheck result.
231 FetchVulncheckResult(context.Context, URIArg) (map[protocol.DocumentURI]*vulncheck.Result, error)
232
233 // MemStats: Fetch memory statistics
234 //
235 // Call runtime.GC multiple times and return memory statistics as reported by
236 // runtime.MemStats.
237 //
238 // This command is used for benchmarking, and may change in the future.
239 MemStats(context.Context) (MemStatsResult, error)
240
241 // WorkspaceStats: Fetch workspace statistics
242 //
243 // Query statistics about workspace builds, modules, packages, and files.
244 //
245 // This command is intended for internal use only, by the gopls stats
246 // command.
247 WorkspaceStats(context.Context) (WorkspaceStatsResult, error)
248
249 // RunGoWorkCommand: Run `go work [args...]`, and apply the resulting go.work
250 // edits to the current go.work file
251 RunGoWorkCommand(context.Context, RunGoWorkArgs) error
252
253 // AddTelemetryCounters: Update the given telemetry counters
254 //
255 // Gopls will prepend "fwd/" to all the counters updated using this command
256 // to avoid conflicts with other counters gopls collects.
257 AddTelemetryCounters(context.Context, AddTelemetryCountersArgs) error
258
259 // AddTest: add test for the selected function
260 AddTest(context.Context, protocol.Location) (*protocol.WorkspaceEdit, error)
261
262 // MaybePromptForTelemetry: Prompt user to enable telemetry
263 //
264 // Checks for the right conditions, and then prompts the user
265 // to ask if they want to enable Go telemetry uploading. If
266 // the user responds 'Yes', the telemetry mode is set to "on".
267 MaybePromptForTelemetry(context.Context) error
268
269 // ChangeSignature: Perform a "change signature" refactoring
270 //
271 // This command is experimental, currently only supporting parameter removal.
272 // Its signature will certainly change in the future (pun intended).
273 ChangeSignature(context.Context, ChangeSignatureArgs) (*protocol.WorkspaceEdit, error)
274
275 // DiagnoseFiles: Cause server to publish diagnostics for the specified files.
276 //
277 // This command is needed by the 'gopls {check,fix}' CLI subcommands.
278 DiagnoseFiles(context.Context, DiagnoseFilesArgs) error
279
280 // Views: List current Views on the server.
281 //
282 // This command is intended for use by gopls tests only.
283 Views(context.Context) ([]View, error)
284
285 // FreeSymbols: Browse free symbols referenced by the selection in a browser.
286 //
287 // This command is a query over a selected range of Go source
288 // code. It reports the set of "free" symbols of the
289 // selection: the set of symbols that are referenced within
290 // the selection but are declared outside of it. This
291 // information is useful for understanding at a glance what a
292 // block of code depends on, perhaps as a precursor to
293 // extracting it into a separate function.
294 FreeSymbols(ctx context.Context, viewID string, loc protocol.Location) error
295
296 // Assembly: Browse assembly listing of current function in a browser.
297 //
298 // This command opens a web-based disassembly listing of the
299 // specified function symbol (plus any nested lambdas and defers).
300 // The machine architecture is determined by the view.
301 Assembly(_ context.Context, viewID, packageID, symbol string) error
302
303 // ClientOpenURL: Request that the client open a URL in a browser.
304 ClientOpenURL(_ context.Context, url string) error
305
306 // ScanImports: force a synchronous scan of the imports cache.
307 //
308 // This command is intended for use by gopls tests only.
309 ScanImports(context.Context) error
310
311 // Packages: Return information about packages
312 //
313 // This command returns an empty result if the specified files
314 // or directories are not associated with any Views on the
315 // server yet.
316 Packages(context.Context, PackagesArgs) (PackagesResult, error)
317
318 // Modules: Return information about modules within a directory
319 //
320 // This command returns an empty result if there is no module, or if module
321 // mode is disabled. Modules will not cause any new views to be loaded and
322 // will only return modules associated with views that have already been
323 // loaded, regardless of how it is called. Given current usage (by the
324 // language server client), there should never be a case where Modules is
325 // called on a path that has not already been loaded.
326 Modules(context.Context, ModulesArgs) (ModulesResult, error)
327
328 // PackageSymbols: Return information about symbols in the given file's package.
329 PackageSymbols(context.Context, PackageSymbolsArgs) (PackageSymbolsResult, error)
330
331 // ModifyTags: Add or remove struct tags on a given node.
332 ModifyTags(context.Context, ModifyTagsArgs, *protocol.InteractiveParams) error
333
334 // MoveType: Move a type declaration to a different package.
335 MoveType(context.Context, MoveTypeArgs) error
336
337 // ImplementInterface: Add methods to a type to implement an interface.
338 ImplementInterface(context.Context, ImplementInterfaceArgs, *protocol.InteractiveParams) error
339 }
340
341 type RunTestsArgs struct {
342 // The test file containing the tests to run.
343 URI protocol.DocumentURI
344
345 // Specific test names to run, e.g. TestFoo.
346 Tests []string
347
348 // Specific benchmarks to run, e.g. BenchmarkFoo.
349 Benchmarks []string
350 }
351
352 type GenerateArgs struct {
353 // URI for the directory to generate.
354 Dir protocol.DocumentURI
355
356 // Whether to generate recursively (go generate ./...)
357 Recursive bool
358 }
359
360 type DocArgs struct {
361 Location protocol.Location
362 ShowDocument bool // in addition to returning the URL, send showDocument
363 }
364
365 // TODO(rFindley): document the rest of these once the docgen is fleshed out.
366
367 type ApplyFixArgs struct {
368 // The name of the fix to apply.
369 //
370 // For fixes suggested by analyzers, this is a string constant
371 // advertised by the analyzer that matches the Category of
372 // the analysis.Diagnostic with a SuggestedFix containing no edits.
373 //
374 // For fixes suggested by code actions, this is a string agreed
375 // upon by the code action and golang.ApplyFix.
376 Fix string
377
378 // The portion of the document to fix.
379 Location protocol.Location
380
381 // Whether to resolve and return the edits.
382 ResolveEdits bool
383 }
384
385 type URIArg struct {
386 // The file URI.
387 URI protocol.DocumentURI
388 }
389
390 type URIArgs struct {
391 // The file URIs.
392 URIs []protocol.DocumentURI
393 }
394
395 type CheckUpgradesArgs struct {
396 // The go.mod file URI.
397 URI protocol.DocumentURI
398 // The modules to check.
399 Modules []string
400 }
401
402 type DependencyArgs struct {
403 // The go.mod file URI.
404 URI protocol.DocumentURI
405 // Additional args to pass to the go command.
406 GoCmdArgs []string
407 // Whether to add a require directive.
408 AddRequire bool
409 }
410
411 type RemoveDependencyArgs struct {
412 // The go.mod file URI.
413 URI protocol.DocumentURI
414 // The module path to remove.
415 ModulePath string
416 // If the module is tidied apart from the one unused diagnostic, we can
417 // run `go get module@none`, and then run `go mod tidy`. Otherwise, we
418 // must make textual edits.
419 OnlyDiagnostic bool
420 }
421
422 type EditGoDirectiveArgs struct {
423 // Any document URI within the relevant module.
424 URI protocol.DocumentURI
425 // The version to pass to `go mod edit -go`.
426 Version string
427 }
428
429 type GoGetPackageArgs struct {
430 // Any document URI within the relevant module.
431 URI protocol.DocumentURI
432 // The package to go get.
433 Pkg string
434 AddRequire bool
435 }
436
437 type AddImportArgs struct {
438 // ImportPath is the target import path that should
439 // be added to the URI file
440 ImportPath string
441 // URI is the file that the ImportPath should be
442 // added to
443 URI protocol.DocumentURI
444 }
445
446 type ListKnownPackagesResult struct {
447 // Packages is a list of packages relative
448 // to the URIArg passed by the command request.
449 // In other words, it omits paths that are already
450 // imported or cannot be imported due to compiler
451 // restrictions.
452 Packages []string
453 }
454
455 type ListImportsResult struct {
456 // Imports is a list of imports in the requested file.
457 Imports []FileImport
458
459 // PackageImports is a list of all imports in the requested file's package.
460 PackageImports []PackageImport
461 }
462
463 type FileImport struct {
464 // Path is the import path of the import.
465 Path string
466 // Name is the name of the import, e.g. `foo` in `import foo "strings"`.
467 Name string
468 }
469
470 type PackageImport struct {
471 // Path is the import path of the import.
472 Path string
473 }
474
475 type DebuggingArgs struct {
476 // Optional: the address (including port) for the debug server to listen on.
477 // If not provided, the debug server will bind to "localhost:0", and the
478 // full debug URL will be contained in the result.
479 //
480 // If there is more than one gopls instance along the serving path (i.e. you
481 // are using a daemon), each gopls instance will attempt to start debugging.
482 // If Addr specifies a port, only the daemon will be able to bind to that
483 // port, and each intermediate gopls instance will fail to start debugging.
484 // For this reason it is recommended not to specify a port (or equivalently,
485 // to specify ":0").
486 //
487 // If the server was already debugging this field has no effect, and the
488 // result will contain the previously configured debug URL(s).
489 Addr string
490 }
491
492 type DebuggingResult struct {
493 // The URLs to use to access the debug servers, for all gopls instances in
494 // the serving path. For the common case of a single gopls instance (i.e. no
495 // daemon), this will be exactly one address.
496 //
497 // In the case of one or more gopls instances forwarding the LSP to a daemon,
498 // URLs will contain debug addresses for each server in the serving path, in
499 // serving order. The daemon debug address will be the last entry in the
500 // slice. If any intermediate gopls instance fails to start debugging, no
501 // error will be returned but the debug URL for that server in the URLs slice
502 // will be empty.
503 URLs []string
504 }
505
506 // StartProfileArgs holds the arguments to the StartProfile command.
507 //
508 // It is a placeholder for future compatibility.
509 type StartProfileArgs struct {
510 }
511
512 // StartProfileResult holds the result of the StartProfile command.
513 //
514 // It is a placeholder for future compatibility.
515 type StartProfileResult struct {
516 }
517
518 // StopProfileArgs holds the arguments to the StopProfile command.
519 //
520 // It is a placeholder for future compatibility.
521 type StopProfileArgs struct {
522 }
523
524 // StopProfileResult holds the result to the StopProfile command.
525 type StopProfileResult struct {
526 // File is the profile file name.
527 File string
528 }
529
530 type ResetGoModDiagnosticsArgs struct {
531 URIArg
532
533 // Optional: source of the diagnostics to reset.
534 // If not set, all resettable go.mod diagnostics will be cleared.
535 DiagnosticSource string
536 }
537
538 type VulncheckArgs struct {
539 // Any document in the directory from which govulncheck will run.
540 URI protocol.DocumentURI
541
542 // Package pattern. E.g. "", ".", "./...".
543 Pattern string
544
545 // TODO: -tests
546 }
547
548 // RunVulncheckResult holds the result of asynchronously starting the vulncheck
549 // command.
550 type RunVulncheckResult struct {
551 // Token holds the progress token for LSP workDone reporting of the vulncheck
552 // invocation.
553 Token protocol.ProgressToken
554 }
555
556 // VulncheckResult holds the result of synchronously running the vulncheck
557 // command.
558 type VulncheckResult struct {
559 // Result holds the result of running vulncheck.
560 Result *vulncheck.Result
561 // Token holds the progress token used to report progress during back to the
562 // LSP client during vulncheck execution.
563 Token protocol.ProgressToken
564 }
565
566 // MemStatsResult holds selected fields from runtime.MemStats.
567 type MemStatsResult struct {
568 HeapAlloc uint64
569 HeapInUse uint64
570 TotalAlloc uint64
571 }
572
573 // WorkspaceStatsResult returns information about the size and shape of the
574 // workspace.
575 type WorkspaceStatsResult struct {
576 Files FileStats // file stats for the cache
577 Views []ViewStats // stats for each view in the session
578 }
579
580 // FileStats holds information about a set of files.
581 type FileStats struct {
582 Total int // total number of files
583 Largest int // number of bytes in the largest file
584 Errs int // number of files that could not be read
585 }
586
587 // ViewStats holds information about a single View in the session.
588 type ViewStats struct {
589 GoCommandVersion string // version of the Go command resolved for this view
590 AllPackages PackageStats // package info for all packages (incl. dependencies)
591 WorkspacePackages PackageStats // package info for workspace packages
592 Diagnostics int // total number of diagnostics in the workspace
593 }
594
595 // PackageStats holds information about a collection of packages.
596 type PackageStats struct {
597 Packages int // total number of packages
598 LargestPackage int // number of files in the largest package
599 CompiledGoFiles int // total number of compiled Go files across all packages
600 Modules int // total number of unique modules
601 }
602
603 type RunGoWorkArgs struct {
604 ViewID string // ID of the view to run the command from
605 InitFirst bool // Whether to run `go work init` first
606 Args []string // Args to pass to `go work`
607 }
608
609 // AddTelemetryCountersArgs holds the arguments to the AddCounters command
610 // that updates the telemetry counters.
611 type AddTelemetryCountersArgs struct {
612 // Names and Values must have the same length.
613 Names []string // Name of counters.
614 Values []int64 // Values added to the corresponding counters. Must be non-negative.
615 }
616
617 // ChangeSignatureArgs specifies a "change signature" refactoring to perform.
618 //
619 // The new signature is expressed via the NewParams and NewResults fields. The
620 // elements of these lists each describe a new field of the signature, by
621 // either referencing a field in the old signature or by defining a new field:
622 // - If the element is an integer, it references a positional parameter in the
623 // old signature.
624 // - If the element is a string, it is parsed as a new field to add.
625 //
626 // Suppose we have a function `F(a, b int) (string, error)`. Here are some
627 // examples of refactoring this signature in practice, eliding the 'Location'
628 // and 'ResolveEdits' fields.
629 // - `{ "NewParams": [0], "NewResults": [0, 1] }` removes the second parameter
630 // - `{ "NewParams": [1, 0], "NewResults": [0, 1] }` flips the parameter order
631 // - `{ "NewParams": [0, 1, "a int"], "NewResults": [0, 1] }` adds a new field
632 // - `{ "NewParams": [1, 2], "NewResults": [1] }` drops the `error` result
633 type ChangeSignatureArgs struct {
634 // Location is any range inside the function signature. By convention, this
635 // is the same location provided in the codeAction request.
636 Location protocol.Location // a range inside of the function signature, as passed to CodeAction
637
638 // NewParams describes parameters of the new signature.
639 // An int value references a parameter in the old signature by index.
640 // A string value describes a new parameter field (e.g. "x int").
641 NewParams []ChangeSignatureParam
642
643 // NewResults describes results of the new signature (see above).
644 // An int value references a result in the old signature by index.
645 // A string value describes a new result field (e.g. "err error").
646 NewResults []ChangeSignatureParam
647
648 // Whether to resolve and return the edits.
649 ResolveEdits bool
650 }
651
652 // ChangeSignatureParam implements the API described in the doc string of
653 // [ChangeSignatureArgs]: a union of JSON int | string.
654 type ChangeSignatureParam struct {
655 OldIndex int
656 NewField string
657 }
658
659 func (a *ChangeSignatureParam) UnmarshalJSON(b []byte) error {
660 var s string
661 if err := json.Unmarshal(b, &s); err == nil {
662 a.NewField = s
663 return nil
664 }
665 var i int
666 if err := json.Unmarshal(b, &i); err == nil {
667 a.OldIndex = i
668 return nil
669 }
670 return fmt.Errorf("must be int or string")
671 }
672
673 func (a ChangeSignatureParam) MarshalJSON() ([]byte, error) {
674 if a.NewField != "" {
675 return json.Marshal(a.NewField)
676 }
677 return json.Marshal(a.OldIndex)
678 }
679
680 // DiagnoseFilesArgs specifies a set of files for which diagnostics are wanted.
681 type DiagnoseFilesArgs struct {
682 Files []protocol.DocumentURI
683 }
684
685 // A View holds summary information about a cache.View.
686 type View struct {
687 ID string // view ID (the index of this view among all views created)
688 Type string // view type (via cache.ViewType.String)
689 Root protocol.DocumentURI // root dir of the view (e.g. containing go.mod or go.work)
690 Folder protocol.DocumentURI // workspace folder associated with the view
691 EnvOverlay []string // environment variable overrides
692 }
693
694 // PackagesArgs holds arguments for the Packages command.
695 type PackagesArgs struct {
696 // Files is a list of files and directories whose associated
697 // packages should be described by the result.
698 //
699 // In some cases, a file may belong to more than one package;
700 // the result may describe any of them.
701 Files []protocol.DocumentURI
702
703 // Enumerate all packages under the directory loadable with
704 // the ... pattern.
705 // The search does not cross the module boundaries and
706 // does not return packages that are not yet loaded.
707 // (e.g. those excluded by the gopls directory filter setting,
708 // or the go.work configuration)
709 Recursive bool `json:"Recursive,omitempty"`
710
711 // Mode controls the types of information returned for each package.
712 Mode PackagesMode
713 }
714
715 // PackagesMode controls the details to include in PackagesResult.
716 type PackagesMode uint64
717
718 const (
719 // Populate the [TestFile.Tests] field in [Package] returned by the
720 // Packages command.
721 NeedTests PackagesMode = 1 << iota
722 )
723
724 // PackagesResult is the result of the Packages command.
725 type PackagesResult struct {
726 // Packages is an unordered list of package metadata.
727 Packages []Package
728
729 // Module maps module path to module metadata for
730 // all the modules of the returned Packages.
731 Module map[string]Module
732 }
733
734 // Package describes a Go package (not an empty parent).
735 type Package struct {
736 // Package path.
737 Path string
738 // Module path. Empty if the package doesn't
739 // belong to any module.
740 ModulePath string
741 // q in a "p [q.test]" package.
742 ForTest string
743
744 // Note: the result does not include the directory name
745 // of the package because mapping between a package and
746 // a folder is not possible in certain build systems.
747 // If directory info is needed, one can guess it
748 // from the TestFile's file name.
749
750 // TestFiles contains the subset of the files of the package
751 // whose name ends with "_test.go".
752 // They are ordered deterministically as determined
753 // by the underlying build system.
754 TestFiles []TestFile
755 }
756
757 type Module struct {
758 Path string // module path
759 Version string // module version if any.
760 GoMod protocol.DocumentURI // path to the go.mod file.
761 }
762
763 type TestFile struct {
764 URI protocol.DocumentURI // a *_test.go file
765
766 // Tests is the list of tests in File, including subtests.
767 //
768 // The set of subtests is not exhaustive as in general they may be
769 // dynamically generated, so it is impossible for static heuristics
770 // to enumerate them.
771 //
772 // Tests are lexically ordered.
773 // Since subtest names are prefixed by their top-level test names
774 // each top-level test precedes its subtests.
775 Tests []TestCase
776 }
777
778 // TestCase represents a test case.
779 // A test case can be a top-level Test/Fuzz/Benchmark/Example function,
780 // as recognized by 'go list' or 'go test -list', or
781 // a subtest within a top-level function.
782 type TestCase struct {
783 // Name is the complete name of the test (Test, Benchmark, Example, or Fuzz)
784 // or the subtest as it appears in the output of go test -json.
785 // The server may attempt to infer names of subtests by static
786 // analysis; if so, it should aim to simulate the actual computed
787 // name of the test, including any disambiguating suffix such as "#01".
788 // To run only this test, clients need to compute the -run, -bench, -fuzz
789 // flag values by first splitting the Name with "/" and
790 // quoting each element with "^" + regexp.QuoteMeta(Name) + "$".
791 // e.g. TestToplevel/Inner.Subtest → -run=^TestToplevel$/^Inner\.Subtest$
792 Name string
793
794 // Loc is the filename and range enclosing this test function
795 // or the subtest. This is used to place the gutter marker
796 // and group tests based on location.
797 // For subtests whose test names can be determined statically,
798 // this can be either t.Run or the test data table
799 // for table-driven setup.
800 // Some testing frameworks allow to declare the actual test
801 // logic in a different file. For example, one can define
802 // a testify test suite in suite_test.go and use it from
803 // main_test.go.
804 /*
805 -- main_test.go --
806 ...
807 func TestFoo(t *testing.T) {
808 suite.Run(t, new(MyTestSuite))
809 }
810 -- suite_test.go --
811 type MyTestSuite struct {
812 suite.Suite
813 }
814 func (suite *MyTestSuite) TestBar() { ... }
815 */
816 // In this case, the testing framework creates "TestFoo/TestBar"
817 // and the corresponding test case belongs to "main_test.go"
818 // TestFile. However, the test case has "suite_test.go" as its
819 // file location.
820 Loc protocol.Location
821 }
822
823 type ModulesArgs struct {
824 // Dir is the directory in which to search for go.mod files.
825 Dir protocol.DocumentURI
826
827 // MaxDepth is the directory walk limit.
828 // A value of 0 means inspect only Dir.
829 // 1 means inspect its child directories too, and so on.
830 // A negative value removes the limit.
831 MaxDepth int
832 }
833
834 type ModulesResult struct {
835 Modules []Module
836 }
837
838 type PackageSymbolsArgs struct {
839 URI protocol.DocumentURI
840 }
841
842 type PackageSymbolsResult struct {
843 PackageName string
844 // Files is a list of files in the given URI's package.
845 Files []protocol.DocumentURI
846 Symbols []PackageSymbol
847 }
848
849 // PackageSymbol has the same fields as DocumentSymbol, with an additional int field "File"
850 // which stores the index of the symbol's file in the PackageSymbolsResult.Files array
851 type PackageSymbol struct {
852 Name string `json:"name"`
853
854 Detail string `json:"detail,omitempty"`
855
856 // protocol.SymbolKind maps an integer to an enum:
857 // https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#symbolKind
858 // i.e. File = 1
859 Kind protocol.SymbolKind `json:"kind"`
860
861 Tags []protocol.SymbolTag `json:"tags,omitempty"`
862
863 Range protocol.Range `json:"range"`
864
865 SelectionRange protocol.Range `json:"selectionRange"`
866
867 Children []PackageSymbol `json:"children,omitempty"`
868
869 // Index of this symbol's file in PackageSymbolsResult.Files
870 File int `json:"file,omitempty"`
871 }
872
873 type ImplementInterfaceArgs struct {
874 // Location is the location where the user invoked the code action.
875 // This location must be within a type declaration.
876 Location protocol.Location
877
878 // Interface is the fully qualified name of pacakge-level interface type to
879 // implement. It must follow the pattern "path/to/package.InterfaceName"
880 // (e.g., "io.Reader").
881 Interface string
882 }
883
884 // ModifyTagsArgs holds variables that determine how struct tags are modified.
885 type ModifyTagsArgs struct {
886 // NOTE(hxjiang): the mofidication field is important, when resolving a
887 // command, the title of the code action or code lenses is no longer available.
888 // The language server is not aware of the original user intention, whether
889 // the command is meant for tag addition or tag removal.
890 Modification string
891 URI protocol.DocumentURI // uri of the file to be modified
892 Range protocol.Range // range in the file for where to modify struct tags
893 Add string // comma-separated list of tags to add; i.e. "json,xml"
894 AddOptions string // comma-separated list of options to add, per tag; i.e. "json=omitempty"
895 Remove string // comma-separated list of tags to remove
896 RemoveOptions string // comma-separated list of options to remove
897 Clear bool // if set, clear all tags. tags are cleared before any new tags are added
898 ClearOptions bool // if set, clear all tag options; options are cleared before any new options are added
899 Overwrite bool // if set, replace existing tags when adding
900 SkipUnexportedFields bool // if set, do not modify tags on unexported struct fields
901 Transform string // transform rule for adding tags; i.e. "snakecase"
902 ValueFormat string // format for the tag's value, after transformation; for example "column:{field}"
903 }
904
905 type LSPArgs struct {
906 Method string `json:"method"`
907 Param json.RawMessage `json:"param"`
908 }
909
910 // MoveTypeArgs specifies a "move type" refactoring to perform.
911 type MoveTypeArgs struct {
912 // The location of the type to move.
913 Location protocol.Location
914 // TODO(mkalil): Determine format of the parameter that specifies where to
915 // move the type to.
916 }