Debian Codegraph @

gopls/doc/features/diagnostics.md

raw symbols SCIP
1 ---
2 title: "Gopls: Diagnostics"
3 ---
4
5 Gopls continuously annotates all your open files of source code with a
6 variety of diagnostics. Every time you edit a file or make a
7 configuration change, gopls asynchronously recomputes these
8 diagnostics and sends them to the client using the LSP
9 [`publishDiagnostics`](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification#textDocument_publishDiagnostics)
10 notification, giving you real-time feedback that reduces the cost of
11 common mistakes.
12
13 Diagnostics come from two main sources: compilation errors and analysis findings.
14
15 - **Compilation errors** are those that you would obtain from running `go
16 build`. Gopls doesn't actually run the compiler; that would be too
17 slow. Instead it runs `go list` (when needed) to compute the
18 metadata of the compilation, then processes those packages in a similar
19 manner to the compiler front-end: reading, scanning, and parsing the
20 source files, then type-checking them. Each of these steps can
21 produce errors that gopls will surface as a diagnostic.
22
23 The `source` field of the LSP `Diagnostic` record indicates where
24 the diagnostic came from: those with source `"go list"` come from
25 the `go list` command, and those with source `"compiler"` come from
26 gopls' parsing or type checking phases, which are similar to those
27 used in the Go compiler.
28
29 ![A diagnostic due to a type error](../assets/diagnostic-typeerror.png)
30
31 The example above shows a `string + int` addition, causes the type
32 checker to report a `MismatchedTypes` error. The diagnostic contains
33 a link to the documentation about this class of type error.
34
35 - **Analysis findings** come from the [**Go analysis
36 framework**](https://golang.org/x/tools/go/analysis), the system
37 used by `go vet` to apply a variety of additional static checks to
38 your Go code. The best-known example is the [`printf`
39 analyzer](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/printf),
40 which reports calls to [`fmt.Printf`](https://pkg.go.dev/fmt#Printf)
41 where the format "verb" doesn't match the argument, such as
42 `fmt.Printf("%d", "three")`.
43
44 Gopls provides dozens of analyzers aggregated from a variety of
45 suites; see [Analyzers](../analyzers.md) for the complete list. The
46 `source` field of each diagnostic produced by an analyzer records
47 the name of the analyzer that produced it.
48
49 ![A diagnostic due to an analysis finding](../assets/diagnostic-analysis.png)
50
51 The example above shows a `printf` formatting mistake. The diagnostic contains
52 a link to the documentation for the `printf` analyzer.
53
54 There is an optional third source of diagnostics:
55
56 <a id='toggleCompilerOptDetails'></a>
57
58 - **Compiler optimization details** are diagnostics that report
59 details relevant to optimization decisions made by the Go
60 compiler, such as whether a variable escapes or a slice index
61 requires a bounds check.
62
63 Optimization decisions include:
64 whether a variable escapes, and how escape is inferred;
65 whether a nil-pointer check is implied or eliminated; and
66 whether a function can be inlined.
67
68 This source is disabled by default but can be enabled on a
69 package-by-package basis by invoking the
70 `source.toggleCompilerOptDetails` ("{Show,Hide} compiler optimization
71 details") code action.
72
73 Remember that the compiler's optimizer runs only on packages that
74 are transitively free from errors, so optimization diagnostics
75 will not be shown on packages that do not build.
76
77
78 ## Recomputation of diagnostics
79
80 By default, diagnostics are automatically recomputed each time the source files
81 are edited.
82
83 Compilation errors in open files are updated after a very short delay
84 (tens of milliseconds) after each file change, potentially after every keystroke.
85 This ensures rapid feedback of syntax and type errors while editing.
86
87 Compilation and analysis diagnostics for the whole workspace are much
88 more expensive to compute, so they are usually recomputed after a
89 short idle period (around 1s) following an edit.
90
91 The [`diagnosticsDelay`](../settings.md#diagnosticsDelay) setting determines
92 this period.
93 Alternatively, diagnostics may be triggered only after an edited file
94 is saved, using the
95 [`diagnosticsTrigger`](../settings.md#diagnosticsTrigger) setting.
96
97 When initialized with `"pullDiagnostics": true`, gopls also supports
98 ["pull diagnostics"](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_pullDiagnostics),
99 an alternative mechanism for recomputing diagnostics in which the client
100 requests diagnostics from gopls explicitly using the `textDocument/diagnostic`
101 request. This feature is off by default until the performance of pull
102 diagnostics is comparable to push diagnostics.
103
104 ## Quick fixes
105
106 Each analyzer diagnostic may suggest one or more alternative
107 ways to fix the problem by editing the code.
108 For example, when a `return` statement has too few operands,
109 the [`fillreturns`](../analyzers.md#fillreturns) analyzer
110 suggests a fix that heuristically fills in the missing ones
111 with suitable values. Applying the fix eliminates the compilation error.
112
113 ![An analyzer diagnostic with two alternative fixes](../assets/remove-unusedparam-before.png)
114
115 The screenshot above shows VS Code's Quick Fix menu for an "unused
116 parameter" analysis diagnostic with two alternative fixes.
117 (See [Remove unused parameter](transformation.md#remove-unused-parameter) for more detail.)
118
119 Suggested fixes that are indisputably safe are [code
120 actions](transformation.md#code-actions) whose kind is
121 `"source.fixAll"`.
122 Many client editors have a shortcut to apply all such fixes.
123
124 <!-- Note: each Code Action has exactly one kind, so a server
125 must offer each "safe" action twice, once with its usual kind
126 and once with kind "source.fixAll".
127 The only ones in gopls are simplify{compositelit,range,slice},
128 which are fixAll + quickfix.
129 -->
130
131 TODO(adonovan): audit all the analyzers to ensure that their
132 documentation is up-to-date w.r.t. any fixes they suggest.
133
134 Settings:
135
136 - The [`diagnosticsDelay`](../settings.md#diagnosticsDelay) setting determines
137 the idle period after an edit before diagnostics are recomputed.
138 - The [`diagnosticsTriggerr`](../settings.md#diagnosticsTrigger) setting determines
139 what events cause recomputation of diagnostics.
140 - The [`linkTarget`](../settings.md#linkTarget) setting specifies
141 the base URI for Go package links in the Diagnostic.CodeDescription field.
142
143 Client support:
144
145 - **VS Code**: Each diagnostic appears as a squiggly underline.
146 Hovering reveals the details, along with any suggested fixes.
147 - **Emacs + eglot**: Each diagnostic appears as a squiggly underline.
148 Hovering reveals the details. Use `M-x eglot-code-action-quickfix`
149 to apply available fixes; it will prompt if there are more than one.
150 - **Vim + coc.nvim**: ??
151 - **CLI**: `gopls check file.go`
152
153 <!-- Below we list any quick fixes (by their internal fix name)
154 that aren't analyzers. -->
155
156 ### `stubMissingInterfaceMethods`: Declare missing methods of I
157
158 When a value of a concrete type is assigned to a variable of an
159 interface type, but the concrete type does not possess all the
160 necessary methods, the type checker will report a "missing method"
161 error.
162
163 In this situation, gopls offers a quick fix to add stub declarations
164 of all the missing methods to the concrete type so that it implements
165 the interface.
166
167 For example, this function will not compile because the value
168 `NegativeErr{}` does not implement the "error" interface:
169
170 ```go
171 func sqrt(x float64) (float64, error) {
172 if x < 0 {
173 return 0, NegativeErr{} // error: missing method
174 }
175 ...
176 }
177
178 type NegativeErr struct{}
179 ```
180
181 Gopls will offer a quick fix to declare this method:
182
183 ```go
184
185 // Error implements [error.Error].
186 func (NegativeErr) Error() string {
187 panic("unimplemented")
188 }
189 ```
190
191 Beware that the new declarations appear alongside the concrete type,
192 which may be in a different file or even package from the cursor
193 position.
194 (Perhaps gopls should send a `showDocument` request to navigate the
195 client there, or a progress notification indicating that something
196 happened.)
197
198 ### `StubMissingCalledFunction`: Declare missing method T.f
199
200 When you attempt to call a method on a type that does not have that method,
201 the compiler will report an error such as "type X has no field or method Y".
202 In this scenario, gopls now offers a quick fix to generate a stub declaration of
203 the missing method, inferring its type from the call.
204
205 Consider the following code where `Foo` does not have a method `bar`:
206
207 ```go
208 type Foo struct{}
209
210 func main() {
211 var s string
212 f := Foo{}
213 s = f.bar("str", 42) // error: f.bar undefined (type Foo has no field or method bar)
214 }
215 ```
216
217 Gopls will offer a quick fix, "Declare missing method Foo.bar".
218 When invoked, it creates the following declaration:
219
220 ```go
221 func (f Foo) bar(s string, i int) string {
222 panic("unimplemented")
223 }
224 ```
225
226 ### `CreateUndeclared`: Create missing declaration for "undeclared name: X"
227
228 A Go compiler error "undeclared name: X" indicates that a variable or function is being used before
229 it has been declared in the current scope. In this scenario, gopls offers a quick fix to create the declaration.
230
231 #### Declare a new variable
232
233 When you reference a variable that hasn't been declared:
234
235 ```go
236 func main() {
237 x := 42
238 min(x, y) // error: undefined: y
239 }
240 ```
241
242 The quick fix would insert a declaration with a default
243 value inferring its type from the context:
244
245 ```go
246 func main() {
247 x := 42
248 y := 0
249 min(x, y)
250 }
251 ```
252
253 #### Declare a new function
254
255 Similarly, if you call a function that hasn't been declared:
256
257 ```go
258 func main() {
259 var s string
260 s = doSomething(42) // error: undefined: doSomething
261 }
262 ```
263
264 Gopls will insert a new function declaration below,
265 inferring its type from the call:
266
267 ```go
268 func main() {
269 var s string
270 s = doSomething(42)
271 }
272
273 func doSomething(i int) string {
274 panic("unimplemented")
275 }
276 ```
277 <!--
278
279 dorky details and deletia:
280
281 - The **vet suite**, of about thirty analyzers
282 designed to catch likely mistakes in your code.
283
284 - **Type-error fixers**. These are gopls-specific analyzers that
285 enrich diagnostics from the type checker by suggesting fixes for
286 simple problems.
287
288 For example, when a return statement has too few operands, the
289 [fillreturns](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns) analyzer can heuristically fill in the missing ones
290 with suitable values.
291
292 The actual diagnostics are produced by the type checker,
293 so these analyzers won't cause you to see any new diagnostics;
294 but they add fixes to existing ones.
295 (The user needs to know this because the settings expose it.)
296
297 currently: fillreturns nonewvars noresultvalues stubmethods undeclaredname unusedvariable
298
299 - **Simplifiers**. These are gopls-specific analyzers that
300 suggest ways to rewrite your code more simply.
301 They do not indicate a mistake in your code,
302 which is why they are not part of `go vet`.
303
304 For example, the `simplifyrange` analyzer will eliminate the
305 unnecessary blank variable in `for _ = range v {...}`.
306
307 currently: simplifycompositelit simplifyrange simplifyslice unusedparams infertypeargs
308
309 - **Bug detectors**. Gopls has a suite of bug-detecting analyzers that
310 can't be part of vet for some reason. That might be because they
311 have dependencies that vet cannot have (e.g. nilness and
312 unusedwrite, which construct SSA), or because they are tightly
313 integrated with gopls (e.g. embeddirective, which produces lazy
314 fixes through the code action mechanism
315 [But others do that too: undeclaredname embeddirective unusedparams stubmethods]
316
317 currently: atomicalign deepequalerrors nilness sortslice unusedwrite embeddirective
318
319 - **staticcheck**: four suites (S=simple, SA=static analysis, QF=quickfix, ST=stylecheck)
320 Only a hand-picked subset of them are enabled by default.
321
322 - **Experimental analyzers**. Gopls has some analyzers that are not
323 enabled by default, because they produce too high a rate of false
324 positives. For example, fieldalignment, shadow.
325
326 Note: fillstruct is not a real analyzer.
327
328 -->