Debian Codegraph @

gopls/internal/settings/settings.go

raw symbols SCIP
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 settings
6
7 import (
8 "fmt"
9 "maps"
10 "math"
11 "path/filepath"
12 "reflect"
13 "strings"
14 "time"
15
16 "golang.org/x/tools/gopls/internal/file"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/protocol/semtok"
19 "golang.org/x/tools/gopls/internal/telemetry"
20 "golang.org/x/tools/gopls/internal/util/frob"
21 )
22
23 // An Annotation is a category of Go compiler optimization diagnostic.
24 type Annotation string
25
26 const (
27 // Nil controls nil checks.
28 Nil Annotation = "nil"
29
30 // Escape controls diagnostics about escape choices.
31 Escape Annotation = "escape"
32
33 // Inline controls diagnostics about inlining choices.
34 Inline Annotation = "inline"
35
36 // Bounds controls bounds checking diagnostics.
37 Bounds Annotation = "bounds"
38 )
39
40 // Options holds various configuration that affects Gopls execution, organized
41 // by the nature or origin of the settings.
42 //
43 // Options must be comparable with reflect.DeepEqual, and serializable with
44 // [frob.Codec].
45 //
46 // This type defines both the logic of LSP-supplied option parsing
47 // (see [SetOptions]), and the public documentation of options in
48 // ../../doc/settings.md (generated by gopls/doc/generate).
49 //
50 // Each exported field of each embedded type such as "ClientOptions"
51 // contributes a user-visible option setting. The option name is the
52 // field name rendered in camelCase. Unlike most Go doc comments,
53 // these fields should be documented using GitHub markdown.
54 type Options struct {
55 ClientOptions
56 ServerOptions
57 UserOptions
58 InternalOptions
59 }
60
61 // Debug returns a list of "name = value" strings for each Options field.
62 func (o *Options) Debug() []string {
63 var res []string
64
65 var visitStruct func(v reflect.Value, path []string)
66 visitStruct = func(v reflect.Value, path []string) {
67 for i := range v.NumField() {
68 f := v.Field(i)
69 ftyp := v.Type().Field(i)
70 path := append(path, ftyp.Name)
71 if ftyp.Type.Kind() == reflect.Struct {
72 visitStruct(f, path)
73 } else {
74 res = append(res, fmt.Sprintf("%s = %#v",
75 strings.Join(path, "."),
76 f.Interface()))
77 }
78 }
79 }
80 visitStruct(reflect.ValueOf(o).Elem(), nil)
81
82 return res
83 }
84
85 // ClientOptions holds LSP-specific configuration that is provided by the
86 // client.
87 //
88 // ClientOptions must be comparable with reflect.DeepEqual.
89 type ClientOptions struct {
90 ClientInfo protocol.ClientInfo
91 InsertTextFormat protocol.InsertTextFormat
92 InsertReplaceSupported bool
93 ConfigurationSupported bool
94 DynamicConfigurationSupported bool
95 DynamicRegistrationSemanticTokensSupported bool
96 DynamicWatchedFilesSupported bool
97 RelativePatternsSupported bool
98 PreferredContentFormat protocol.MarkupKind
99 LineFoldingOnly bool
100 HierarchicalDocumentSymbolSupport bool
101 ImportsSource ImportsSourceEnum `status:"experimental"`
102 SemanticTypes []string
103 SemanticMods []string
104 RelatedInformationSupported bool
105 CompletionTags bool
106 CompletionDeprecated bool
107 SupportedResourceOperations []protocol.ResourceOperationKind
108 CodeActionResolveOptions []string
109 ShowDocumentSupported bool
110 // SupportedWorkDoneProgressFormats specifies the formats supported by the
111 // client for handling workdone progress metadata.
112 SupportedWorkDoneProgressFormats map[WorkDoneProgressStyle]bool
113 // SupportedInteractiveInputTypes specifies the interactive types supported
114 // by the client.
115 SupportedInteractiveInputTypes map[InteractiveInputType]bool
116 }
117
118 // ServerOptions holds LSP-specific configuration that is provided by the
119 // server.
120 //
121 // ServerOptions must be comparable with reflect.DeepEqual.
122 type ServerOptions struct {
123 SupportedCodeActions map[file.Kind]map[protocol.CodeActionKind]bool
124 SupportedCommands []string
125 }
126
127 // Note: BuildOptions must be comparable with reflect.DeepEqual.
128 type BuildOptions struct {
129 // BuildFlags is the set of flags passed on to the build system when invoked.
130 // It is applied to queries like `go list`, which is used when discovering files.
131 // The most common use is to set `-tags`.
132 BuildFlags []string
133
134 // Env adds environment variables to external commands run by `gopls`, most notably `go list`.
135 Env map[string]string
136
137 // DirectoryFilters can be used to exclude unwanted directories from the
138 // workspace. By default, all directories are included. Filters are an
139 // operator, `+` to include and `-` to exclude, followed by a path prefix
140 // relative to the workspace folder. They are evaluated in order, and
141 // the last filter that applies to a path controls whether it is included.
142 // The path prefix can be empty, so an initial `-` excludes everything.
143 //
144 // DirectoryFilters also supports the `**` operator to match 0 or more directories.
145 //
146 // Examples:
147 //
148 // Exclude node_modules at current depth: `-node_modules`
149 //
150 // Exclude node_modules at any depth: `-**/node_modules`
151 //
152 // Include only project_a: `-` (exclude everything), `+project_a`
153 //
154 // Include only project_a, but not node_modules inside it: `-`, `+project_a`, `-project_a/node_modules`
155 DirectoryFilters []string
156
157 // TemplateExtensions gives the extensions of file names that are treated
158 // as template files. (The extension
159 // is the part of the file name after the final dot.)
160 TemplateExtensions []string
161
162 // obsolete, no effect
163 MemoryMode string `status:"experimental"`
164
165 // ExpandWorkspaceToModule determines which packages are considered
166 // "workspace packages" when the workspace is using modules.
167 //
168 // Workspace packages affect the scope of workspace-wide operations. Notably,
169 // gopls diagnoses all packages considered to be part of the workspace after
170 // every keystroke, so by setting "ExpandWorkspaceToModule" to false, and
171 // opening a nested workspace directory, you can reduce the amount of work
172 // gopls has to do to keep your workspace up to date.
173 ExpandWorkspaceToModule bool `status:"experimental"`
174
175 // StandaloneTags specifies a set of build constraints that identify
176 // individual Go source files that make up the entire main package of an
177 // executable.
178 //
179 // A common example of standalone main files is the convention of using the
180 // directive `//go:build ignore` to denote files that are not intended to be
181 // included in any package, for example because they are invoked directly by
182 // the developer using `go run`.
183 //
184 // Gopls considers a file to be a standalone main file if and only if it has
185 // package name "main" and has a build directive of the exact form
186 // "//go:build tag" or "// +build tag", where tag is among the list of tags
187 // configured by this setting. Notably, if the build constraint is more
188 // complicated than a simple tag (such as the composite constraint
189 // `//go:build tag && go1.18`), the file is not considered to be a standalone
190 // main file.
191 //
192 // This setting is only supported when gopls is built with Go 1.16 or later.
193 StandaloneTags []string
194
195 // WorkspaceFiles configures the set of globs that match files defining the
196 // logical build of the current workspace. Any on-disk changes to any files
197 // matching a glob specified here will trigger a reload of the workspace.
198 //
199 // This setting need only be customized in environments with a custom
200 // GOPACKAGESDRIVER.
201 WorkspaceFiles []string
202 }
203
204 // Note: UIOptions must be comparable with reflect.DeepEqual.
205 type UIOptions struct {
206 DocumentationOptions
207 CompletionOptions
208 NavigationOptions
209 DiagnosticOptions
210 InlayHintOptions
211
212 // Codelenses overrides the enabled/disabled state of each of gopls'
213 // sources of [Code Lenses](codelenses.md).
214 //
215 // Example Usage:
216 //
217 // ```json5
218 // "gopls": {
219 // ...
220 // "codelenses": {
221 // "generate": false, // Don't show the `go generate` lens.
222 // }
223 // ...
224 // }
225 // ```
226 Codelenses map[CodeLensSource]bool
227
228 // SemanticTokens determines whether gopls will return a
229 // SemanticTokensProvider at initialization, or respond
230 // to requests for semantic tokens.
231 //
232 // This setting being `false` won't necessary disable the client's calls
233 // for semantic tokens. If you want that, it would need to be configured in
234 // the client. For example, in VSCode, this would disable all Go semantic
235 // token calls to the LSP server:
236 //
237 // ```json5
238 // "[go]": {
239 // "editor.semanticHighlighting.enabled": false,
240 // }
241 // ```
242 SemanticTokens bool `status:"experimental"`
243
244 // NoSemanticString turns off the sending of the semantic token 'string'
245 //
246 // Deprecated: Use SemanticTokenTypes["string"] = false instead. See
247 // golang/vscode-go#3632
248 NoSemanticString bool `status:"experimental"`
249
250 // NoSemanticNumber turns off the sending of the semantic token 'number'
251 //
252 // Deprecated: Use SemanticTokenTypes["number"] = false instead. See
253 // golang/vscode-go#3632.
254 NoSemanticNumber bool `status:"experimental"`
255
256 // SemanticTokenTypes configures the semantic token types. It allows
257 // disabling types by setting each value to false.
258 // By default, all types are enabled.
259 SemanticTokenTypes map[string]bool `status:"experimental"`
260
261 // SemanticTokenModifiers configures the semantic token modifiers. It allows
262 // disabling modifiers by setting each value to false.
263 // By default, all modifiers are enabled.
264 SemanticTokenModifiers map[string]bool `status:"experimental"`
265
266 // NewGoFileHeader enables automatic insertion of the copyright comment
267 // and package declaration in a newly created Go file.
268 NewGoFileHeader bool
269
270 // RenameMovesSubpackages enables Rename operations on packages to
271 // move subdirectories of the target package.
272 RenameMovesSubpackages bool `status:"experimental"`
273 }
274
275 // A CodeLensSource identifies an (algorithmic) source of code lenses.
276 type CodeLensSource string
277
278 // CodeLens sources
279 //
280 // These identifiers appear in the "codelenses" configuration setting,
281 // and in the user documentation thereof, which is generated by
282 // gopls/doc/generate/generate.go parsing this file.
283 //
284 // Doc comments should use GitHub Markdown.
285 // The first line becomes the title.
286 //
287 // (For historical reasons, each code lens source identifier typically
288 // matches the name of one of the command.Commands returned by it,
289 // but that isn't essential.)
290 const (
291 // Run `go generate`
292 //
293 // This codelens source annotates any `//go:generate` comments
294 // with commands to run `go generate` in this directory, on
295 // all directories recursively beneath this one.
296 //
297 // See [Generating code](https://go.dev/blog/generate) for
298 // more details.
299 CodeLensGenerate CodeLensSource = "generate"
300
301 // Re-generate cgo declarations
302 //
303 // This codelens source annotates an `import "C"` declaration
304 // with a command to re-run the [cgo
305 // command](https://pkg.go.dev/cmd/cgo) to regenerate the
306 // corresponding Go declarations.
307 //
308 // Use this after editing the C code in comments attached to
309 // the import, or in C header files included by it.
310 CodeLensRegenerateCgo CodeLensSource = "regenerate_cgo"
311
312 // Run govulncheck
313 //
314 // This codelens source annotates the `module` directive in a go.mod file
315 // with a command to run govulncheck synchronously.
316 //
317 // [Govulncheck](https://go.dev/blog/vuln) is a static analysis tool that
318 // computes the set of functions reachable within your application, including
319 // dependencies; queries a database of known security vulnerabilities; and
320 // reports any potential problems it finds.
321 //
322 //gopls:status experimental
323 CodeLensVulncheck CodeLensSource = "vulncheck"
324
325 // Run govulncheck (legacy)
326 //
327 // This codelens source annotates the `module` directive in a go.mod file
328 // with a command to run Govulncheck asynchronously.
329 //
330 // [Govulncheck](https://go.dev/blog/vuln) is a static analysis tool that
331 // computes the set of functions reachable within your application, including
332 // dependencies; queries a database of known security vulnerabilities; and
333 // reports any potential problems it finds.
334 CodeLensRunGovulncheck CodeLensSource = "run_govulncheck"
335
336 // Run tests and benchmarks
337 //
338 // This codelens source annotates each `Test` and `Benchmark`
339 // function in a `*_test.go` file with a command to run it.
340 //
341 // This source is off by default because VS Code has
342 // a client-side custom UI for testing, and because progress
343 // notifications are not a great UX for streamed test output.
344 // See:
345 // - golang/go#67400 for a discussion of this feature.
346 // - https://github.com/joaotavora/eglot/discussions/1402
347 // for an alternative approach.
348 CodeLensTest CodeLensSource = "test"
349
350 // Tidy go.mod file
351 //
352 // This codelens source annotates the `module` directive in a
353 // go.mod file with a command to run [`go mod
354 // tidy`](https://go.dev/ref/mod#go-mod-tidy), which ensures
355 // that the go.mod file matches the source code in the module.
356 CodeLensTidy CodeLensSource = "tidy"
357
358 // Update dependencies
359 //
360 // This codelens source annotates the `module` directive in a
361 // go.mod file with commands to:
362 //
363 // - check for available upgrades,
364 // - upgrade direct dependencies, and
365 // - upgrade all dependencies transitively.
366 CodeLensUpgradeDependency CodeLensSource = "upgrade_dependency"
367
368 // Update vendor directory
369 //
370 // This codelens source annotates the `module` directive in a
371 // go.mod file with a command to run [`go mod
372 // vendor`](https://go.dev/ref/mod#go-mod-vendor), which
373 // creates or updates the directory named `vendor` in the
374 // module root so that it contains an up-to-date copy of all
375 // necessary package dependencies.
376 CodeLensVendor CodeLensSource = "vendor"
377 )
378
379 // Note: CompletionOptions must be comparable with reflect.DeepEqual.
380 type CompletionOptions struct {
381 // Placeholders enables placeholders for function parameters or struct
382 // fields in completion responses.
383 UsePlaceholders bool
384
385 // CompletionBudget is the soft latency goal for completion requests. Most
386 // requests finish in a couple milliseconds, but in some cases deep
387 // completions can take much longer. As we use up our budget we
388 // dynamically reduce the search scope to ensure we return timely
389 // results. Zero means unlimited.
390 CompletionBudget time.Duration `status:"debug"`
391
392 // Matcher sets the algorithm that is used when calculating completion
393 // candidates.
394 Matcher Matcher `status:"advanced"`
395
396 // ExperimentalPostfixCompletions enables artificial method snippets
397 // such as "someSlice.sort!".
398 ExperimentalPostfixCompletions bool `status:"experimental"`
399
400 // CompleteFunctionCalls enables function call completion.
401 //
402 // When completing a statement, or when a function return type matches the
403 // expected of the expression being completed, completion may suggest call
404 // expressions (i.e. may include parentheses).
405 CompleteFunctionCalls bool
406 }
407
408 // Note: DocumentationOptions must be comparable with reflect.DeepEqual.
409 type DocumentationOptions struct {
410 // HoverKind controls the information that appears in the hover text.
411 // SingleLine is intended for use only by authors of editor plugins.
412 HoverKind HoverKind
413
414 // LinkTarget is the base URL for links to Go package
415 // documentation returned by LSP operations such as Hover and
416 // DocumentLinks and in the CodeDescription field of each
417 // Diagnostic.
418 //
419 // It might be one of:
420 //
421 // * `"godoc.org"`
422 // * `"pkg.go.dev"`
423 //
424 // If company chooses to use its own `godoc.org`, its address can be used as well.
425 //
426 // Modules matching the GOPRIVATE environment variable will not have
427 // documentation links in hover.
428 LinkTarget string
429
430 // LinksInHover controls the presence of documentation links in hover markdown.
431 LinksInHover LinksInHoverEnum
432 }
433
434 // LinksInHoverEnum has legal values:
435 //
436 // - `false`, for no links;
437 // - `true`, for links to the `linkTarget` domain; or
438 // - `"gopls"`, for links to gopls' internal documentation viewer.
439 //
440 // Note: this type has special logic in loadEnums in generate.go.
441 // Be sure to reflect enum and doc changes there!
442 type LinksInHoverEnum int
443
444 const (
445 LinksInHover_None LinksInHoverEnum = iota
446 LinksInHover_LinkTarget
447 LinksInHover_Gopls
448 )
449
450 // MarshalJSON implements the json.Marshaler interface, so that the default
451 // values are formatted correctly in documentation. (See [Options.setOne] for
452 // the flexible custom unmarshaling behavior).
453 func (l LinksInHoverEnum) MarshalJSON() ([]byte, error) {
454 switch l {
455 case LinksInHover_None:
456 return []byte("false"), nil
457 case LinksInHover_LinkTarget:
458 return []byte("true"), nil
459 case LinksInHover_Gopls:
460 return []byte(`"gopls"`), nil
461 default:
462 return nil, fmt.Errorf("invalid LinksInHover value %d", l)
463 }
464 }
465
466 // Note: FormattingOptions must be comparable with reflect.DeepEqual.
467 type FormattingOptions struct {
468 // Local is the equivalent of the `goimports -local` flag, which puts
469 // imports beginning with this string after third-party packages. It should
470 // be the prefix of the import path whose imports should be grouped
471 // separately.
472 //
473 // It is used when tidying imports (during an LSP Organize
474 // Imports request) or when inserting new ones (for example,
475 // during completion); an LSP Formatting request merely sorts the
476 // existing imports.
477 Local string
478
479 // Gofumpt indicates if we should run gofumpt formatting.
480 Gofumpt bool
481 }
482
483 // Note: DiagnosticOptions must be comparable with reflect.DeepEqual,
484 // and frob-encodable (no interfaces).
485 type DiagnosticOptions struct {
486 // Analyses specify analyses that the user would like to enable or disable.
487 // A map of the names of analysis passes that should be enabled/disabled.
488 // A full list of analyzers that gopls uses can be found in
489 // [analyzers.md](https://github.com/golang/tools/blob/master/gopls/doc/analyzers.md).
490 //
491 // Example Usage:
492 //
493 // ```json5
494 // ...
495 // "analyses": {
496 // "unreachable": false, // Disable the unreachable analyzer.
497 // "unusedvariable": true // Enable the unusedvariable analyzer.
498 // }
499 // ...
500 // ```
501 Analyses map[string]bool
502
503 // Staticcheck configures the default set of analyses staticcheck.io.
504 // These analyses are documented on
505 // [Staticcheck's website](https://staticcheck.io/docs/checks/).
506 //
507 // The "staticcheck" option has three values:
508 // - false: disable all staticcheck analyzers
509 // - true: enable all staticcheck analyzers
510 // - unset: enable a subset of staticcheck analyzers
511 // selected by gopls maintainers for runtime efficiency
512 // and analytic precision.
513 //
514 // Regardless of this setting, individual analyzers can be
515 // selectively enabled or disabled using the `analyses` setting.
516 Staticcheck bool `status:"experimental"`
517 StaticcheckProvided bool `status:"experimental"` // = "staticcheck" was explicitly provided
518
519 // Annotations specifies the various kinds of compiler
520 // optimization details that should be reported as diagnostics
521 // when enabled for a package by the "Toggle compiler
522 // optimization details" (`gopls.gc_details`) command.
523 //
524 // (Some users care only about one kind of annotation in their
525 // profiling efforts. More importantly, in large packages, the
526 // number of annotations can sometimes overwhelm the user
527 // interface and exceed the per-file diagnostic limit.)
528 //
529 // TODO(adonovan): rename this field to CompilerOptDetail.
530 Annotations map[Annotation]bool
531
532 // Vulncheck enables vulnerability scanning.
533 Vulncheck VulncheckMode `status:"experimental"`
534
535 // DiagnosticsDelay controls the amount of time that gopls waits
536 // after the most recent file modification before computing deep diagnostics.
537 // Simple diagnostics (parsing and type-checking) are always run immediately
538 // on recently modified packages.
539 //
540 // This option must be set to a valid duration string, for example `"250ms"`.
541 DiagnosticsDelay time.Duration `status:"advanced"`
542
543 // DiagnosticsTrigger controls when to run diagnostics.
544 DiagnosticsTrigger DiagnosticsTrigger `status:"experimental"`
545
546 // AnalysisProgressReporting controls whether gopls sends progress
547 // notifications when construction of its index of analysis facts is taking a
548 // long time. Cancelling these notifications will cancel the indexing task,
549 // though it will restart after the next change in the workspace.
550 //
551 // When a package is opened for the first time and heavyweight analyses such as
552 // staticcheck are enabled, it can take a while to construct the index of
553 // analysis facts for all its dependencies. The index is cached in the
554 // filesystem, so subsequent analysis should be faster.
555 AnalysisProgressReporting bool
556 }
557
558 type InlayHintOptions struct {
559 // Hints specify inlay hints that users want to see. A full list of hints
560 // that gopls uses can be found in
561 // [inlayHints.md](https://github.com/golang/tools/blob/master/gopls/doc/inlayHints.md).
562 Hints map[InlayHint]bool `status:"experimental"`
563 }
564
565 // An InlayHint identifies a category of hint that may be
566 // independently requested through the "hints" setting.
567 type InlayHint string
568
569 // This is the source from which gopls/doc/inlayHints.md is generated.
570 const (
571 // ParameterNames controls inlay hints for parameter names:
572 // ```go
573 // parseInt(« str: » "123", « radix: » 8)
574 // ```
575 ParameterNames InlayHint = "parameterNames"
576
577 // AssignVariableTypes controls inlay hints for variable types in assign statements:
578 // ```go
579 // i« int», j« int» := 0, len(r)-1
580 // ```
581 AssignVariableTypes InlayHint = "assignVariableTypes"
582
583 // ConstantValues controls inlay hints for constant values:
584 // ```go
585 // const (
586 // KindNone Kind = iota« = 0»
587 // KindPrint« = 1»
588 // KindPrintf« = 2»
589 // KindErrorf« = 3»
590 // )
591 // ```
592 ConstantValues InlayHint = "constantValues"
593
594 // RangeVariableTypes controls inlay hints for variable types in range statements:
595 // ```go
596 // for k« int», v« string» := range []string{} {
597 // fmt.Println(k, v)
598 // }
599 // ```
600 RangeVariableTypes InlayHint = "rangeVariableTypes"
601
602 // CompositeLiteralTypes controls inlay hints for composite literal types:
603 // ```go
604 // for _, c := range []struct {
605 // in, want string
606 // }{
607 // «struct{ in string; want string }»{"Hello, world", "dlrow ,olleH"},
608 // }
609 // ```
610 CompositeLiteralTypes InlayHint = "compositeLiteralTypes"
611
612 // CompositeLiteralFieldNames inlay hints for composite literal field names:
613 // ```go
614 // Point2D{«X: »1, «Y: »2}
615 //
616 // Outer{«Embedded.»Field: 0}
617 // ```
618 CompositeLiteralFieldNames InlayHint = "compositeLiteralFields"
619
620 // FunctionTypeParameters inlay hints for implicit type parameters on generic functions:
621 // ```go
622 // myFoo«[int, string]»(1, "hello")
623 // ```
624 FunctionTypeParameters InlayHint = "functionTypeParameters"
625
626 // IgnoredError inlay hints for implicitly discarded errors:
627 // ```go
628 // f.Close()« // ignore error»
629 // ```
630 // This check inserts an `// ignore error` hint following any
631 // statement that is a function call whose error result is
632 // implicitly ignored.
633 //
634 // To suppress the hint, write an actual comment containing
635 // "ignore error" following the call statement, or explicitly
636 // assign the result to a blank variable. A handful of common
637 // functions such as `fmt.Println` are excluded from the
638 // check.
639 IgnoredError InlayHint = "ignoredError"
640 )
641
642 type NavigationOptions struct {
643 // ImportShortcut specifies whether import statements should link to
644 // documentation or go to definitions.
645 ImportShortcut ImportShortcut
646
647 // SymbolMatcher sets the algorithm that is used when finding workspace symbols.
648 SymbolMatcher SymbolMatcher `status:"advanced"`
649
650 // SymbolStyle controls how symbols are qualified in symbol responses.
651 //
652 // Example Usage:
653 //
654 // ```json5
655 // "gopls": {
656 // ...
657 // "symbolStyle": "Dynamic",
658 // ...
659 // }
660 // ```
661 SymbolStyle SymbolStyle `status:"advanced"`
662
663 // SymbolScope controls which packages are searched for workspace/symbol
664 // requests. When the scope is "workspace", gopls searches only workspace
665 // packages. When the scope is "all", gopls searches all loaded packages,
666 // including dependencies and the standard library.
667 SymbolScope SymbolScope
668 }
669
670 // UserOptions holds custom Gopls configuration (not part of the LSP) that is
671 // modified by the client.
672 //
673 // UserOptions must be comparable with reflect.DeepEqual.
674 type UserOptions struct {
675 BuildOptions
676 UIOptions
677 FormattingOptions
678
679 // FileWatcher specifies the server-side file watching strategy used by gopls.
680 //
681 // By default, this is set to "off", meaning gopls relies exclusively on the
682 // language client (e.g., the editor) to send file change notifications.
683 //
684 // Available options:
685 // - "off" : Client-driven watching (default)
686 // - "fsnotify" : OS-level event notifications
687 // - "poll" : Periodic directory scanning
688 FileWatcher FileWatcherMode `status:"experimental"`
689
690 // MaxFileCacheBytes sets a soft limit on the file cache size in bytes.
691 // If zero, the default budget is used.
692 //
693 // The cache may temporarily use more than this amount.
694 // Also, this parameter limits file contents; disk block usage
695 // as measured by du(1) may be significantly higher.
696 MaxFileCacheBytes int64 `status:"experimental"`
697
698 // VerboseOutput enables additional debug logging.
699 VerboseOutput bool `status:"debug"`
700 }
701
702 // EnvSlice returns Env as a slice of k=v strings.
703 func (u *UserOptions) EnvSlice() []string {
704 var result []string
705 for k, v := range u.Env {
706 result = append(result, fmt.Sprintf("%v=%v", k, v))
707 }
708 return result
709 }
710
711 // SetEnvSlice sets Env from a slice of k=v strings.
712 func (u *UserOptions) SetEnvSlice(env []string) {
713 u.Env = map[string]string{}
714 for _, kv := range env {
715 split := strings.SplitN(kv, "=", 2)
716 if len(split) != 2 {
717 continue
718 }
719 u.Env[split[0]] = split[1]
720 }
721 }
722
723 type WorkDoneProgressStyle string
724
725 const WorkDoneProgressStyleLog WorkDoneProgressStyle = "log"
726
727 type InteractiveInputType string
728
729 const (
730 InteractiveInputTypeString InteractiveInputType = "string"
731 InteractiveInputTypeFile InteractiveInputType = "file"
732 InteractiveInputTypeBool InteractiveInputType = "bool"
733 InteractiveInputTypeNumber InteractiveInputType = "number"
734 InteractiveInputTypeEnum InteractiveInputType = "enum"
735 InteractiveInputTypeLazyEnum InteractiveInputType = "lazyEnum"
736 InteractiveInputTypeList InteractiveInputType = "list"
737 )
738
739 // InternalOptions contains settings that are not intended for use by the
740 // average user. These may be settings used by tests or outdated settings that
741 // will soon be deprecated. Some of these settings may not even be configurable
742 // by the user.
743 //
744 // TODO(rfindley): even though these settings are not intended for
745 // modification, some of them should be surfaced in our documentation.
746 type InternalOptions struct {
747 // MCPTools configures enabled tools (by tool name), overriding the defaults.
748 MCPTools map[string]bool
749
750 // VerboseWorkDoneProgress controls whether the LSP server should send
751 // progress reports for all work done outside the scope of an RPC.
752 // Used by the regression tests.
753 VerboseWorkDoneProgress bool
754
755 // The following options were previously available to users, but they
756 // really shouldn't be configured by anyone other than "power users".
757
758 // CompletionDocumentation enables documentation with completion results.
759 CompletionDocumentation bool
760
761 // CompleteUnimported enables completion for packages that you do not
762 // currently import.
763 CompleteUnimported bool
764
765 // DeepCompletion enables the ability to return completions from deep
766 // inside relevant entities, rather than just the locally accessible ones.
767 //
768 // Consider this example:
769 //
770 // ```go
771 // package main
772 //
773 // import "fmt"
774 //
775 // type wrapString struct {
776 // str string
777 // }
778 //
779 // func main() {
780 // x := wrapString{"hello world"}
781 // fmt.Printf(<>)
782 // }
783 // ```
784 //
785 // At the location of the `<>` in this program, deep completion would suggest
786 // the result `x.str`.
787 DeepCompletion bool
788
789 // ShowBugReports causes a message to be shown when the first bug is reported
790 // on the server.
791 // This option applies only during initialization.
792 ShowBugReports bool
793
794 // SubdirWatchPatterns configures the file watching glob patterns registered
795 // by gopls.
796 //
797 // Some clients (namely VS Code) do not send workspace/didChangeWatchedFile
798 // notifications for files contained in a directory when that directory is
799 // deleted:
800 // https://github.com/microsoft/vscode/issues/109754
801 //
802 // In this case, gopls would miss important notifications about deleted
803 // packages. To work around this, gopls registers a watch pattern for each
804 // directory containing Go files.
805 //
806 // Unfortunately, other clients experience performance problems with this
807 // many watch patterns, so there is no single behavior that works well for
808 // all clients.
809 //
810 // The "subdirWatchPatterns" setting allows configuring this behavior. Its
811 // default value of "auto" attempts to guess the correct behavior based on
812 // the client name. We'd love to avoid this specialization, but as described
813 // above there is no single value that works for all clients.
814 //
815 // If any LSP client does not behave well with the default value (for
816 // example, if like VS Code it drops file notifications), please file an
817 // issue.
818 SubdirWatchPatterns SubdirWatchPatterns
819
820 // ReportAnalysisProgressAfter sets the duration for gopls to wait before starting
821 // progress reporting for ongoing go/analysis passes.
822 //
823 // It is intended to be used for testing only.
824 ReportAnalysisProgressAfter time.Duration
825
826 // TelemetryPrompt controls whether gopls prompts about enabling Go telemetry.
827 //
828 // Once the prompt is answered, gopls doesn't ask again, but TelemetryPrompt
829 // can prevent the question from ever being asked in the first place.
830 TelemetryPrompt bool
831
832 // LinkifyShowMessage controls whether the client wants gopls
833 // to linkify links in showMessage. e.g. [go.dev](https://go.dev).
834 LinkifyShowMessage bool
835
836 // IncludeReplaceInWorkspace controls whether locally replaced modules in a
837 // go.mod file are treated like workspace modules.
838 // Or in other words, if a go.mod file with local replaces behaves like a
839 // go.work file.
840 IncludeReplaceInWorkspace bool
841
842 // ZeroConfig enables the zero-config algorithm for workspace layout,
843 // dynamically creating build configurations for different modules,
844 // directories, and GOOS/GOARCH combinations to cover open files.
845 ZeroConfig bool
846
847 // PullDiagnostics enables support for pull diagnostics.
848 //
849 // TODO(rfindley): make pull diagnostics robust, and remove this option,
850 // allowing pull diagnostics by default.
851 PullDiagnostics bool
852 }
853
854 type FileWatcherMode string
855
856 const (
857 FileWatcherOff FileWatcherMode = "off"
858 FileWatcherFSNotify FileWatcherMode = "fsnotify"
859 FileWatcherPoll FileWatcherMode = "poll"
860 )
861
862 type SubdirWatchPatterns string
863
864 const (
865 SubdirWatchPatternsOn SubdirWatchPatterns = "on"
866 SubdirWatchPatternsOff SubdirWatchPatterns = "off"
867 SubdirWatchPatternsAuto SubdirWatchPatterns = "auto"
868 )
869
870 type ImportShortcut string
871
872 const (
873 BothShortcuts ImportShortcut = "Both"
874 LinkShortcut ImportShortcut = "Link"
875 DefinitionShortcut ImportShortcut = "Definition"
876 )
877
878 func (s ImportShortcut) ShowLinks() bool {
879 return s == BothShortcuts || s == LinkShortcut
880 }
881
882 func (s ImportShortcut) ShowDefinition() bool {
883 return s == BothShortcuts || s == DefinitionShortcut
884 }
885
886 // ImportsSourceEnum has legal values:
887 //
888 // - `off` to disable searching the file system for imports
889 // - `gopls` to use the metadata graph and module cache index
890 // - `goimports` for the old behavior, to be deprecated
891 type ImportsSourceEnum string
892
893 const (
894 ImportsSourceOff ImportsSourceEnum = "off"
895 ImportsSourceGopls ImportsSourceEnum = "gopls"
896 ImportsSourceGoimports ImportsSourceEnum = "goimports"
897 )
898
899 type Matcher string
900
901 const (
902 Fuzzy Matcher = "Fuzzy"
903 CaseInsensitive Matcher = "CaseInsensitive"
904 CaseSensitive Matcher = "CaseSensitive"
905 )
906
907 // A SymbolMatcher controls the matching of symbols for workspace/symbol
908 // requests.
909 type SymbolMatcher string
910
911 const (
912 SymbolFuzzy SymbolMatcher = "Fuzzy"
913 SymbolFastFuzzy SymbolMatcher = "FastFuzzy"
914 SymbolCaseInsensitive SymbolMatcher = "CaseInsensitive"
915 SymbolCaseSensitive SymbolMatcher = "CaseSensitive"
916 )
917
918 // A SymbolStyle controls the formatting of symbols in workspace/symbol results.
919 type SymbolStyle string
920
921 const (
922 // PackageQualifiedSymbols is package qualified symbols i.e.
923 // "pkg.Foo.Field".
924 PackageQualifiedSymbols SymbolStyle = "Package"
925 // FullyQualifiedSymbols is fully qualified symbols, i.e.
926 // "path/to/pkg.Foo.Field".
927 FullyQualifiedSymbols SymbolStyle = "Full"
928 // DynamicSymbols uses whichever qualifier results in the highest scoring
929 // match for the given symbol query. Here a "qualifier" is any "/" or "."
930 // delimited suffix of the fully qualified symbol. i.e. "to/pkg.Foo.Field" or
931 // just "Foo.Field".
932 DynamicSymbols SymbolStyle = "Dynamic"
933 )
934
935 // A SymbolScope controls the search scope for workspace/symbol requests.
936 type SymbolScope string
937
938 const (
939 // WorkspaceSymbolScope matches symbols in workspace packages only.
940 WorkspaceSymbolScope SymbolScope = "workspace"
941 // AllSymbolScope matches symbols in any loaded package, including
942 // dependencies.
943 AllSymbolScope SymbolScope = "all"
944 )
945
946 type HoverKind string
947
948 const (
949 SingleLine HoverKind = "SingleLine"
950 NoDocumentation HoverKind = "NoDocumentation"
951 SynopsisDocumentation HoverKind = "SynopsisDocumentation"
952 FullDocumentation HoverKind = "FullDocumentation"
953
954 // Structured is a misguided experimental setting that returns a JSON
955 // hover format. This setting should not be used, as it will be removed in a
956 // future release of gopls.
957 Structured HoverKind = "Structured"
958 )
959
960 type VulncheckMode string
961
962 const (
963 // Vulncheck can be triggered via prompt.
964 ModeVulncheckPrompt VulncheckMode = "Prompt"
965 // Disable vulnerability analysis.
966 ModeVulncheckOff VulncheckMode = "Off"
967 // In Imports mode, `gopls` will report vulnerabilities that affect packages
968 // directly and indirectly used by the analyzed main module.
969 ModeVulncheckImports VulncheckMode = "Imports"
970
971 // TODO: VulncheckRequire, VulncheckCallgraph
972 )
973
974 type DiagnosticsTrigger string
975
976 const (
977 // Trigger diagnostics on file edit and save. (default)
978 DiagnosticsOnEdit DiagnosticsTrigger = "Edit"
979 // Trigger diagnostics only on file save. Events like initial workspace load
980 // or configuration change will still trigger diagnostics.
981 DiagnosticsOnSave DiagnosticsTrigger = "Save"
982 // TODO: support "Manual"?
983 )
984
985 type CounterPath = telemetry.CounterPath
986
987 // Set updates *Options based on the provided JSON value:
988 // null, bool, string, number, array, or object.
989 //
990 // The applied result describes settings that were applied. Each CounterPath
991 // contains at least the name of the setting, but may also include sub-setting
992 // names for settings that are themselves maps, and/or a non-empty bucket name
993 // when bucketing is desirable.
994 //
995 // On failure, it returns one or more non-nil errors.
996 func (o *Options) Set(value any) (applied []CounterPath, errs []error) {
997 switch value := value.(type) {
998 case nil:
999 case map[string]any:
1000 seen := make(map[string]struct{})
1001 for name, value := range value {
1002 // Use only the last segment of a dotted name such as
1003 // ui.navigation.symbolMatcher. The other segments
1004 // are discarded, even without validation (!).
1005 // (They are supported to enable hierarchical names
1006 // in the VS Code graphical configuration UI.)
1007 split := strings.Split(name, ".")
1008 name = split[len(split)-1]
1009
1010 if _, ok := seen[name]; ok {
1011 errs = append(errs, fmt.Errorf("duplicate value for %s", name))
1012 }
1013 seen[name] = struct{}{}
1014
1015 paths, err := o.setOne(name, value)
1016 if err != nil {
1017 err := fmt.Errorf("setting option %q: %w", name, err)
1018 errs = append(errs, err)
1019 }
1020 _, soft := err.(*SoftError)
1021 if err == nil || soft {
1022 if len(paths) == 0 {
1023 path := CounterPath{name, ""}
1024 applied = append(applied, path)
1025 } else {
1026 for _, subpath := range paths {
1027 path := append(CounterPath{name}, subpath...)
1028 applied = append(applied, path)
1029 }
1030 }
1031 }
1032 }
1033 default:
1034 errs = append(errs, fmt.Errorf("invalid options type %T (want JSON null or object)", value))
1035 }
1036 return applied, errs
1037 }
1038
1039 func (o *Options) ForClientCapabilities(clientInfo *protocol.ClientInfo, caps protocol.ClientCapabilities) {
1040 if clientInfo != nil {
1041 o.ClientInfo = *clientInfo
1042 }
1043 if caps.Workspace.WorkspaceEdit != nil {
1044 o.SupportedResourceOperations = caps.Workspace.WorkspaceEdit.ResourceOperations
1045 }
1046 // Check if the client supports snippets in completion items.
1047 if c := caps.TextDocument.Completion; c.CompletionItem.SnippetSupport {
1048 o.InsertTextFormat = protocol.SnippetTextFormat
1049 }
1050 o.InsertReplaceSupported = caps.TextDocument.Completion.CompletionItem.InsertReplaceSupport
1051 if caps.Window.ShowDocument != nil {
1052 o.ShowDocumentSupported = caps.Window.ShowDocument.Support
1053 }
1054 // Check if the client supports configuration messages.
1055 o.ConfigurationSupported = caps.Workspace.Configuration
1056 o.DynamicConfigurationSupported = caps.Workspace.DidChangeConfiguration.DynamicRegistration
1057 o.DynamicRegistrationSemanticTokensSupported = caps.TextDocument.SemanticTokens.DynamicRegistration
1058 o.DynamicWatchedFilesSupported = caps.Workspace.DidChangeWatchedFiles.DynamicRegistration
1059 o.RelativePatternsSupported = caps.Workspace.DidChangeWatchedFiles.RelativePatternSupport
1060
1061 // Check which types of content format are supported by this client.
1062 if hover := caps.TextDocument.Hover; hover != nil && len(hover.ContentFormat) > 0 {
1063 o.PreferredContentFormat = hover.ContentFormat[0]
1064 }
1065 // Check if the client supports only line folding.
1066
1067 if fr := caps.TextDocument.FoldingRange; fr != nil {
1068 // TODO(pjw): add telemetry
1069 o.LineFoldingOnly = fr.LineFoldingOnly
1070 }
1071 // Check if the client supports hierarchical document symbols.
1072 o.HierarchicalDocumentSymbolSupport = caps.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport
1073
1074 // Client's semantic tokens
1075 o.SemanticTypes = caps.TextDocument.SemanticTokens.TokenTypes
1076 o.SemanticMods = caps.TextDocument.SemanticTokens.TokenModifiers
1077 // we don't need Requests, as we support full functionality
1078 // we don't need Formats, as there is only one, for now
1079
1080 // Check if the client supports diagnostic related information.
1081 o.RelatedInformationSupported = caps.TextDocument.PublishDiagnostics.RelatedInformation
1082 // Check if the client completion support includes tags (preferred) or deprecation
1083 if caps.TextDocument.Completion.CompletionItem.TagSupport != nil &&
1084 caps.TextDocument.Completion.CompletionItem.TagSupport.ValueSet != nil {
1085 o.CompletionTags = true
1086 } else if caps.TextDocument.Completion.CompletionItem.DeprecatedSupport {
1087 o.CompletionDeprecated = true
1088 }
1089
1090 // Check if the client supports code actions resolving.
1091 if caps.TextDocument.CodeAction.DataSupport && caps.TextDocument.CodeAction.ResolveSupport != nil {
1092 o.CodeActionResolveOptions = caps.TextDocument.CodeAction.ResolveSupport.Properties
1093 }
1094
1095 // Client experimental capabilities.
1096 if experimental, ok := caps.Experimental.(map[string]any); ok {
1097 if formats, ok := experimental["progressMessageStyles"].([]any); ok {
1098 o.SupportedWorkDoneProgressFormats = make(map[WorkDoneProgressStyle]bool, len(formats))
1099 for _, f := range formats {
1100 o.SupportedWorkDoneProgressFormats[WorkDoneProgressStyle(f.(string))] = true
1101 }
1102 }
1103
1104 if interactiveCap, ok := experimental["interactiveResolve"].(map[string]any); ok {
1105 if inputTypes, ok := interactiveCap["inputTypes"].([]any); ok {
1106 o.SupportedInteractiveInputTypes = make(map[InteractiveInputType]bool, len(inputTypes))
1107 for _, t := range inputTypes {
1108 if s, ok := t.(string); ok {
1109 o.SupportedInteractiveInputTypes[InteractiveInputType(s)] = true
1110 }
1111 }
1112 }
1113 }
1114 }
1115 }
1116
1117 var codec = frob.CodecFor[*Options]()
1118
1119 func (o *Options) Clone() *Options {
1120 return codec.Decode(codec.Encode(o))
1121 }
1122
1123 // validateDirectoryFilter validates if the filter string
1124 // - is not empty
1125 // - start with either + or -
1126 // - doesn't contain currently unsupported glob operators: *, ?
1127 func validateDirectoryFilter(ifilter string) (string, error) {
1128 filter := fmt.Sprint(ifilter)
1129 if filter == "" || (filter[0] != '+' && filter[0] != '-') {
1130 return "", fmt.Errorf("invalid filter %v, must start with + or -", filter)
1131 }
1132 segs := strings.Split(filter[1:], "/")
1133 unsupportedOps := [...]string{"?", "*"}
1134 for _, seg := range segs {
1135 if seg != "**" {
1136 for _, op := range unsupportedOps {
1137 if strings.Contains(seg, op) {
1138 return "", fmt.Errorf("invalid filter %v, operator %v not supported. If you want to have this operator supported, consider filing an issue", filter, op)
1139 }
1140 }
1141 }
1142 }
1143
1144 return strings.TrimRight(filepath.FromSlash(filter), "/"), nil
1145 }
1146
1147 // setOne updates a field of o based on the name and value.
1148 //
1149 // The applied result describes the counter values to be updated as a result of
1150 // the applied setting. If the result is nil, the default counter for this
1151 // setting should be updated.
1152 //
1153 // For example, if the setting name is "foo",
1154 // - If applied is nil, update the count for "foo".
1155 // - If applied is []CounterPath{{"bucket"}}, update the count for
1156 // foo:bucket.
1157 // - If applied is []CounterPath{{"a","b"}, {"c","d"}}, update foo/a:b and
1158 // foo/c:d.
1159 //
1160 // It returns an error if the value was invalid or duplicate.
1161 // It is the caller's responsibility to augment the error with 'name'.
1162 func (o *Options) setOne(name string, value any) (applied []CounterPath, _ error) {
1163 switch name {
1164 case "env":
1165 env, ok := value.(map[string]any)
1166 if !ok {
1167 return nil, fmt.Errorf("invalid type %T (want JSON object)", value)
1168 }
1169 if o.Env == nil {
1170 o.Env = make(map[string]string)
1171 }
1172 for k, v := range env {
1173 // For historic compatibility, we accept int too (e.g. CGO_ENABLED=1).
1174 switch v.(type) {
1175 case string, int:
1176 o.Env[k] = fmt.Sprint(v)
1177 default:
1178 return nil, fmt.Errorf("invalid map value %T (want string)", v)
1179 }
1180 }
1181 return nil, nil
1182
1183 case "buildFlags":
1184 return nil, setStringSlice(&o.BuildFlags, value)
1185
1186 case "directoryFilters":
1187 filterStrings, err := asStringSlice(value)
1188 if err != nil {
1189 return nil, err
1190 }
1191 var filters []string
1192 for _, filterStr := range filterStrings {
1193 filter, err := validateDirectoryFilter(filterStr)
1194 if err != nil {
1195 return nil, err
1196 }
1197 filters = append(filters, strings.TrimRight(filepath.FromSlash(filter), "/"))
1198 }
1199 o.DirectoryFilters = filters
1200 return nil, nil
1201
1202 case "workspaceFiles":
1203 return nil, setStringSlice(&o.WorkspaceFiles, value)
1204 case "completionDocumentation":
1205 return setBool(&o.CompletionDocumentation, value)
1206 case "usePlaceholders":
1207 return setBool(&o.UsePlaceholders, value)
1208 case "deepCompletion":
1209 return setBool(&o.DeepCompletion, value)
1210 case "completeUnimported":
1211 return setBool(&o.CompleteUnimported, value)
1212 case "completionBudget":
1213 return nil, setDuration(&o.CompletionBudget, value)
1214 case "importsSource":
1215 res, err := setEnum(&o.ImportsSource, value,
1216 ImportsSourceOff,
1217 ImportsSourceGopls,
1218 ImportsSourceGoimports)
1219 if err != nil {
1220 return nil, err
1221 }
1222 return res, &SoftError{
1223 msg: "importsSource is deprecated as it is no longer needed",
1224 }
1225 case "matcher":
1226 return setEnum(&o.Matcher, value,
1227 Fuzzy,
1228 CaseSensitive,
1229 CaseInsensitive)
1230
1231 case "symbolMatcher":
1232 return setEnum(&o.SymbolMatcher, value,
1233 SymbolFuzzy,
1234 SymbolFastFuzzy,
1235 SymbolCaseInsensitive,
1236 SymbolCaseSensitive)
1237
1238 case "symbolStyle":
1239 return setEnum(&o.SymbolStyle, value,
1240 FullyQualifiedSymbols,
1241 PackageQualifiedSymbols,
1242 DynamicSymbols)
1243
1244 case "symbolScope":
1245 return setEnum(&o.SymbolScope, value,
1246 WorkspaceSymbolScope,
1247 AllSymbolScope)
1248
1249 case "hoverKind":
1250 // TODO(rfindley): reinstate the deprecation of Structured hover by making
1251 // it a warning in gopls v0.N+1, and removing it in gopls v0.N+2.
1252 return setEnum(&o.HoverKind, value,
1253 NoDocumentation,
1254 SingleLine,
1255 SynopsisDocumentation,
1256 FullDocumentation,
1257 Structured,
1258 )
1259
1260 case "linkTarget":
1261 return nil, setString(&o.LinkTarget, value)
1262
1263 case "linksInHover":
1264 switch value {
1265 case false:
1266 o.LinksInHover = LinksInHover_None
1267 case true:
1268 o.LinksInHover = LinksInHover_LinkTarget
1269 case "gopls":
1270 o.LinksInHover = LinksInHover_Gopls
1271 default:
1272 return nil, fmt.Errorf(`invalid value %s; expect false, true, or "gopls"`, value)
1273 }
1274 return nil, nil
1275
1276 case "importShortcut":
1277 return setEnum(&o.ImportShortcut, value,
1278 BothShortcuts,
1279 LinkShortcut,
1280 DefinitionShortcut)
1281
1282 case "analyses":
1283 return setBoolMap(&o.Analyses, value)
1284
1285 case "hints":
1286 return setBoolMap(&o.Hints, value)
1287
1288 case "annotations":
1289 return setAnnotationMap(&o.Annotations, value)
1290
1291 case "vulncheck":
1292 return setEnum(&o.Vulncheck, value,
1293 ModeVulncheckOff,
1294 ModeVulncheckImports,
1295 ModeVulncheckPrompt)
1296
1297 case "codelenses", "codelens":
1298 lensOverrides, err := asBoolMap[CodeLensSource](value)
1299 if err != nil {
1300 return nil, err
1301 }
1302 if o.Codelenses == nil {
1303 o.Codelenses = make(map[CodeLensSource]bool)
1304 }
1305 o.Codelenses = maps.Clone(o.Codelenses)
1306 maps.Copy(o.Codelenses, lensOverrides)
1307
1308 var counts []CounterPath
1309 for k, v := range lensOverrides {
1310 counts = append(counts, CounterPath{string(k), fmt.Sprint(v)})
1311 }
1312
1313 var errs []string
1314 if name == "codelens" {
1315 errs = append(errs, deprecatedError("codelenses").Error())
1316 }
1317 if lensOverrides[CodeLensRunGovulncheck] && lensOverrides[CodeLensVulncheck] {
1318 errs = append(errs, "The 'run_govulncheck' codelens is superseded by the 'vulncheck' codelens. Only 'vulncheck' should be set.")
1319 }
1320 if len(errs) > 0 {
1321 return counts, &SoftError{msg: strings.Join(errs, "\n")}
1322 }
1323 return counts, nil
1324
1325 case "staticcheck":
1326 o.StaticcheckProvided = true
1327 return setBool(&o.Staticcheck, value)
1328
1329 case "local":
1330 return nil, setString(&o.Local, value)
1331
1332 case "maxFileCacheBytes":
1333 return setInt64(&o.MaxFileCacheBytes, value)
1334
1335 case "verboseOutput":
1336 return setBool(&o.VerboseOutput, value)
1337
1338 case "verboseWorkDoneProgress":
1339 return setBool(&o.VerboseWorkDoneProgress, value)
1340
1341 case "showBugReports":
1342 return setBool(&o.ShowBugReports, value)
1343
1344 case "gofumpt":
1345 return setBool(&o.Gofumpt, value)
1346
1347 case "completeFunctionCalls":
1348 return setBool(&o.CompleteFunctionCalls, value)
1349
1350 case "semanticTokens":
1351 return setBool(&o.SemanticTokens, value)
1352
1353 // TODO(hxjiang): deprecate noSemanticString and noSemanticNumber.
1354 case "noSemanticString":
1355 counts, err := setBool(&o.NoSemanticString, value)
1356 if err != nil {
1357 return nil, err
1358 }
1359 return counts, &SoftError{"noSemanticString setting is deprecated, use semanticTokenTypes instead (though you can continue to apply them for the time being)."}
1360
1361 case "noSemanticNumber":
1362 counts, err := setBool(&o.NoSemanticNumber, value)
1363 if err != nil {
1364 return nil, err
1365 }
1366 return counts, &SoftError{"noSemanticNumber setting is deprecated, use semanticTokenTypes instead (though you can continue to apply them for the time being)."}
1367
1368 case "semanticTokenTypes":
1369 return setBoolMap(&o.SemanticTokenTypes, value)
1370
1371 case "semanticTokenModifiers":
1372 return setBoolMap(&o.SemanticTokenModifiers, value)
1373
1374 case "newGoFileHeader":
1375 return setBool(&o.NewGoFileHeader, value)
1376
1377 case "expandWorkspaceToModule":
1378 // See golang/go#63536: we can consider deprecating
1379 // expandWorkspaceToModule, but probably need to change the default
1380 // behavior in that case to *not* expand to the module.
1381 return setBool(&o.ExpandWorkspaceToModule, value)
1382
1383 case "experimentalPostfixCompletions":
1384 return setBool(&o.ExperimentalPostfixCompletions, value)
1385
1386 case "templateExtensions":
1387 switch value := value.(type) {
1388 case []any:
1389 return nil, setStringSlice(&o.TemplateExtensions, value)
1390 case nil:
1391 o.TemplateExtensions = nil
1392 default:
1393 return nil, fmt.Errorf("unexpected type %T (want JSON array of string)", value)
1394 }
1395 return nil, nil
1396
1397 case "diagnosticsDelay":
1398 return nil, setDuration(&o.DiagnosticsDelay, value)
1399
1400 case "diagnosticsTrigger":
1401 return setEnum(&o.DiagnosticsTrigger, value,
1402 DiagnosticsOnEdit,
1403 DiagnosticsOnSave)
1404
1405 case "analysisProgressReporting":
1406 return setBool(&o.AnalysisProgressReporting, value)
1407
1408 case "standaloneTags":
1409 return nil, setStringSlice(&o.StandaloneTags, value)
1410
1411 case "subdirWatchPatterns":
1412 return setEnum(&o.SubdirWatchPatterns, value,
1413 SubdirWatchPatternsOn,
1414 SubdirWatchPatternsOff,
1415 SubdirWatchPatternsAuto)
1416
1417 case "reportAnalysisProgressAfter":
1418 return nil, setDuration(&o.ReportAnalysisProgressAfter, value)
1419
1420 case "telemetryPrompt":
1421 return setBool(&o.TelemetryPrompt, value)
1422
1423 case "linkifyShowMessage":
1424 return setBool(&o.LinkifyShowMessage, value)
1425
1426 case "includeReplaceInWorkspace":
1427 return setBool(&o.IncludeReplaceInWorkspace, value)
1428
1429 case "zeroConfig":
1430 return setBool(&o.ZeroConfig, value)
1431
1432 case "pullDiagnostics":
1433 return setBool(&o.PullDiagnostics, value)
1434
1435 case "mcpTools":
1436 return setBoolMap(&o.MCPTools, value)
1437
1438 case "renameMovesSubpackages":
1439 return setBool(&o.RenameMovesSubpackages, value)
1440
1441 case "fileWatcher":
1442 return setEnum(&o.FileWatcher, value, FileWatcherOff, FileWatcherFSNotify, FileWatcherPoll)
1443
1444 // deprecated and renamed settings
1445 //
1446 // These should never be deleted: there is essentially no cost
1447 // to providing a better error message indefinitely; it's not
1448 // as if we would ever want to recycle the name of a setting.
1449
1450 // renamed
1451 case "experimentalDisabledAnalyses":
1452 return nil, deprecatedError("analyses")
1453
1454 case "disableDeepCompletion":
1455 return nil, deprecatedError("deepCompletion")
1456
1457 case "disableFuzzyMatching":
1458 return nil, deprecatedError("fuzzyMatching")
1459
1460 case "wantCompletionDocumentation":
1461 return nil, deprecatedError("completionDocumentation")
1462
1463 case "wantUnimportedCompletions":
1464 return nil, deprecatedError("completeUnimported")
1465
1466 case "fuzzyMatching":
1467 return nil, deprecatedError("matcher")
1468
1469 case "caseSensitiveCompletion":
1470 return nil, deprecatedError("matcher")
1471
1472 case "experimentalDiagnosticsDelay":
1473 return nil, deprecatedError("diagnosticsDelay")
1474
1475 // deprecated
1476
1477 case "allowImplicitNetworkAccess":
1478 return nil, deprecatedError("")
1479
1480 case "memoryMode":
1481 return nil, deprecatedError("")
1482
1483 case "tempModFile":
1484 return nil, deprecatedError("")
1485
1486 case "experimentalWorkspaceModule":
1487 return nil, deprecatedError("")
1488
1489 case "experimentalTemplateSupport":
1490 return nil, deprecatedError("")
1491
1492 case "experimentalWatchedFileDelay":
1493 return nil, deprecatedError("")
1494
1495 case "experimentalPackageCacheKey":
1496 return nil, deprecatedError("")
1497
1498 case "allowModfileModifications":
1499 return nil, deprecatedError("")
1500
1501 case "allExperiments":
1502 // golang/go#65548: this setting is a no-op, but we fail don't report it as
1503 // deprecated, since the nightly VS Code injects it.
1504 //
1505 // If, in the future, VS Code stops injecting this, we could theoretically
1506 // report an error here, but it also seems harmless to keep ignoring this
1507 // setting forever.
1508 return nil, nil
1509
1510 case "experimentalUseInvalidMetadata":
1511 return nil, deprecatedError("")
1512
1513 case "newDiff":
1514 return nil, deprecatedError("")
1515
1516 case "wantSuggestedFixes":
1517 return nil, deprecatedError("")
1518
1519 case "noIncrementalSync":
1520 return nil, deprecatedError("")
1521
1522 case "watchFileChanges":
1523 return nil, deprecatedError("")
1524
1525 case "go-diff":
1526 return nil, deprecatedError("")
1527
1528 default:
1529 return nil, fmt.Errorf("unexpected setting")
1530 }
1531 }
1532
1533 // EnabledSemanticTokenModifiers returns a map of modifiers to boolean.
1534 func (o *Options) EnabledSemanticTokenModifiers() map[semtok.Modifier]bool {
1535 copy := make(map[semtok.Modifier]bool, len(o.SemanticTokenModifiers))
1536 for k, v := range o.SemanticTokenModifiers {
1537 copy[semtok.Modifier(k)] = v
1538 }
1539 return copy
1540 }
1541
1542 // EnabledSemanticTokenTypes returns a map of types to boolean.
1543 func (o *Options) EnabledSemanticTokenTypes() map[semtok.Type]bool {
1544 copy := make(map[semtok.Type]bool, len(o.SemanticTokenTypes))
1545 for k, v := range o.SemanticTokenTypes {
1546 copy[semtok.Type(k)] = v
1547 }
1548 if o.NoSemanticString {
1549 copy[semtok.TokString] = false
1550 }
1551 if o.NoSemanticNumber {
1552 copy[semtok.TokNumber] = false
1553 }
1554 return copy
1555 }
1556
1557 // A SoftError is an error that does not affect the functionality of gopls.
1558 type SoftError struct {
1559 msg string
1560 }
1561
1562 func (e *SoftError) Error() string {
1563 return e.msg
1564 }
1565
1566 // deprecatedError reports the current setting as deprecated.
1567 // The optional replacement is suggested to the user.
1568 func deprecatedError(replacement string) error {
1569 msg := "this setting is deprecated"
1570 if replacement != "" {
1571 msg = fmt.Sprintf("%s, use %q instead", msg, replacement)
1572 }
1573 return &SoftError{msg}
1574 }
1575
1576 // setT() and asT() helpers: the setT forms write to the 'dest *T'
1577 // variable only on success, to reduce boilerplate in Option.set.
1578
1579 func setBool(dest *bool, value any) ([]CounterPath, error) {
1580 b, err := asBool(value)
1581 if err != nil {
1582 return nil, err
1583 }
1584 *dest = b
1585 return []CounterPath{{fmt.Sprint(b)}}, nil
1586 }
1587
1588 func asBool(value any) (bool, error) {
1589 b, ok := value.(bool)
1590 if !ok {
1591 return false, fmt.Errorf("invalid type %T (want bool)", value)
1592 }
1593 return b, nil
1594 }
1595
1596 func setDuration(dest *time.Duration, value any) error {
1597 str, err := asString(value)
1598 if err != nil {
1599 return err
1600 }
1601 parsed, err := time.ParseDuration(str)
1602 if err != nil {
1603 return err
1604 }
1605 *dest = parsed
1606 return nil
1607 }
1608
1609 func setAnnotationMap(dest *map[Annotation]bool, value any) ([]CounterPath, error) {
1610 all, err := asBoolMap[string](value)
1611 if err != nil {
1612 return nil, err
1613 }
1614 var counters []CounterPath
1615 // Default to everything enabled by default.
1616 m := make(map[Annotation]bool)
1617 for k, enabled := range all {
1618 var a Annotation
1619 cnts, err := setEnum(&a, k,
1620 Nil,
1621 Escape,
1622 Inline,
1623 Bounds)
1624 if err != nil {
1625 // In case of an error, process any legacy values.
1626 switch k {
1627 case "noEscape":
1628 m[Escape] = false
1629 return nil, fmt.Errorf(`"noEscape" is deprecated, set "Escape: false" instead`)
1630
1631 case "noNilcheck":
1632 m[Nil] = false
1633 return nil, fmt.Errorf(`"noNilcheck" is deprecated, set "Nil: false" instead`)
1634
1635 case "noInline":
1636 m[Inline] = false
1637 return nil, fmt.Errorf(`"noInline" is deprecated, set "Inline: false" instead`)
1638
1639 case "noBounds":
1640 m[Bounds] = false
1641 return nil, fmt.Errorf(`"noBounds" is deprecated, set "Bounds: false" instead`)
1642
1643 default:
1644 return nil, err
1645 }
1646 }
1647 counters = append(counters, cnts...)
1648 m[a] = enabled
1649 }
1650 *dest = m
1651 return counters, nil
1652 }
1653
1654 func setBoolMap[K ~string](dest *map[K]bool, value any) ([]CounterPath, error) {
1655 m, err := asBoolMap[K](value)
1656 if err != nil {
1657 return nil, err
1658 }
1659 *dest = m
1660 var counts []CounterPath
1661 for k, v := range m {
1662 counts = append(counts, CounterPath{string(k), fmt.Sprint(v)})
1663 }
1664 return counts, nil
1665 }
1666
1667 func asBoolMap[K ~string](value any) (map[K]bool, error) {
1668 all, ok := value.(map[string]any)
1669 if !ok {
1670 return nil, fmt.Errorf("invalid type %T (want JSON object)", value)
1671 }
1672 m := make(map[K]bool)
1673 for a, enabled := range all {
1674 b, ok := enabled.(bool)
1675 if !ok {
1676 return nil, fmt.Errorf("invalid type %T for object field %q", enabled, a)
1677 }
1678 m[K(a)] = b
1679 }
1680 return m, nil
1681 }
1682
1683 func setString(dest *string, value any) error {
1684 str, err := asString(value)
1685 if err != nil {
1686 return err
1687 }
1688 *dest = str
1689 return nil
1690 }
1691
1692 func asString(value any) (string, error) {
1693 str, ok := value.(string)
1694 if !ok {
1695 return "", fmt.Errorf("invalid type %T (want string)", value)
1696 }
1697 return str, nil
1698 }
1699
1700 func setStringSlice(dest *[]string, value any) error {
1701 slice, err := asStringSlice(value)
1702 if err != nil {
1703 return err
1704 }
1705 *dest = slice
1706 return nil
1707 }
1708
1709 func asStringSlice(value any) ([]string, error) {
1710 array, ok := value.([]any)
1711 if !ok {
1712 return nil, fmt.Errorf("invalid type %T (want JSON array of string)", value)
1713 }
1714 var slice []string
1715 for _, elem := range array {
1716 str, ok := elem.(string)
1717 if !ok {
1718 return nil, fmt.Errorf("invalid array element type %T (want string)", elem)
1719 }
1720 slice = append(slice, str)
1721 }
1722 return slice, nil
1723 }
1724
1725 func setEnum[S ~string](dest *S, value any, options ...S) ([]CounterPath, error) {
1726 enum, err := asEnum(value, options...)
1727 if err != nil {
1728 return nil, err
1729 }
1730 *dest = enum
1731 return []CounterPath{{string(enum)}}, nil
1732 }
1733
1734 func asEnum[S ~string](value any, options ...S) (S, error) {
1735 str, err := asString(value)
1736 if err != nil {
1737 return "", err
1738 }
1739 for _, opt := range options {
1740 if strings.EqualFold(str, string(opt)) {
1741 return opt, nil
1742 }
1743 }
1744 return "", fmt.Errorf("invalid option %q for enum", str)
1745 }
1746
1747 func setInt64(dest *int64, value any) ([]CounterPath, error) {
1748 i, err := asInt64(value)
1749 if err != nil {
1750 return nil, err
1751 }
1752 *dest = i
1753 return []CounterPath{{fmt.Sprint(i)}}, nil
1754 }
1755
1756 func asInt64(value any) (int64, error) {
1757 switch v := value.(type) {
1758
1759 case float64:
1760 // Note that this is what we expect since JSON unmarshalling
1761 // into any produces float64 for numbers.
1762 if !isFinite(v) {
1763 return 0, fmt.Errorf("invalid value %v (want finite number)", v)
1764 }
1765 if v != math.Trunc(v) {
1766 return 0, fmt.Errorf("invalid value %v (want integer)", v)
1767 }
1768 if v != float64(int64(v)) {
1769 return 0, fmt.Errorf("invalid value %v (not representable as int64)", v)
1770 }
1771 return int64(v), nil
1772 case int64:
1773 return v, nil
1774 case int:
1775 return int64(v), nil
1776 default:
1777 return 0, fmt.Errorf("invalid type %T (want int64)", value)
1778 }
1779 }
1780
1781 // isFinite reports whether f represents a finite rational value.
1782 // It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
1783 func isFinite(f float64) bool {
1784 return math.Abs(f) <= math.MaxFloat64
1785 }