3 This document describes the analyzers that `gopls` uses inside the editor.
5 Details about how to enable/disable these analyses can be found
6 [here](settings.md#analyses).
8 <!-- BEGIN Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->
11 report mismatches between assembly files and Go declarations
13 **Enabled by default.**
17 check for useless assignments
19 This checker reports assignments of the form x = x or a[i] = a[i].
20 These are almost always useless, and even when they aren't they are
23 **Enabled by default.**
27 check for common mistakes using the sync/atomic package
29 The atomic checker looks for assignment statements of the form:
31 x = atomic.AddUint64(&x, 1)
35 **Enabled by default.**
39 check for non-64-bits-aligned arguments to sync/atomic functions
41 **Enabled by default.**
45 check for common mistakes involving boolean operators
47 **Enabled by default.**
51 check that +build tags are well-formed and correctly located
53 **Enabled by default.**
57 detect some violations of the cgo pointer passing rules
59 Check for invalid cgo pointer passing.
60 This looks for code that uses cgo to call C code passing values
61 whose types are almost always invalid according to the cgo pointer
63 Specifically, it warns about attempts to pass a Go chan, map, func,
64 or slice to C, either directly, or via a pointer, array, or struct.
66 **Enabled by default.**
70 check for unkeyed composite literals
72 This analyzer reports a diagnostic for composite literals of struct
73 types imported from another package that do not use the field-keyed
74 syntax. Such literals are fragile because the addition of a new field
75 (even if unexported) to the struct will cause compilation to fail.
79 err = &net.DNSConfigError{err}
81 should be replaced by:
83 err = &net.DNSConfigError{Err: err}
86 **Enabled by default.**
90 check for locks erroneously passed by value
92 Inadvertently copying a value containing a lock, such as sync.Mutex or
93 sync.WaitGroup, may cause both copies to malfunction. Generally such
94 values should be referred to through a pointer.
96 **Enabled by default.**
98 ## **deepequalerrors**
100 check for calls of reflect.DeepEqual on error values
102 The deepequalerrors checker looks for calls of the form:
104 reflect.DeepEqual(err1, err2)
106 where err1 and err2 are errors. Using reflect.DeepEqual to compare
107 errors is discouraged.
109 **Enabled by default.**
113 report passing non-pointer or non-error values to errors.As
115 The errorsas analysis reports calls to errors.As where the type
116 of the second argument is not a pointer to a type implementing error.
118 **Enabled by default.**
120 ## **fieldalignment**
122 find structs that would take less memory if their fields were sorted
124 This analyzer find structs that can be rearranged to take less memory, and provides
125 a suggested edit with the optimal order.
128 **Disabled by default. Enable it by setting `"analyses": {"fieldalignment": true}`.**
132 check for mistakes using HTTP responses
134 A common mistake when using the net/http package is to defer a function
135 call to close the http.Response Body before checking the error that
136 determines whether the response is valid:
138 resp, err := http.Head(url)
139 defer resp.Body.Close()
143 // (defer statement belongs here)
145 This checker helps uncover latent nil dereference bugs by reporting a
146 diagnostic for such mistakes.
148 **Enabled by default.**
152 detect impossible interface-to-interface type assertions
154 This checker flags type assertions v.(T) and corresponding type-switch cases
155 in which the static type V of v is an interface that cannot possibly implement
156 the target interface T. This occurs when V and T contain methods with the same
157 name but different signatures. Example:
164 The Read method in v has a different signature than the Read method in
165 io.Reader, so this assertion cannot succeed.
168 **Enabled by default.**
172 check references to loop variables from within nested functions
174 This analyzer checks for references to loop variables from within a
175 function literal inside the loop body. It checks only instances where
176 the function literal is called in a defer or go statement that is the
177 last statement in the loop body, as otherwise we would need whole
182 for i, v := range s {
184 println(i, v) // not what you might expect
188 See: https://golang.org/doc/go_faq.html#closures_and_goroutines
190 **Enabled by default.**
194 check cancel func returned by context.WithCancel is called
196 The cancellation function returned by context.WithCancel, WithTimeout,
197 and WithDeadline must be called or the new context will remain live
198 until its parent context is cancelled.
199 (The background context is never cancelled.)
201 **Enabled by default.**
205 check for useless comparisons between functions and nil
207 A useless comparison is one like f == nil as opposed to f() == nil.
209 **Enabled by default.**
213 check for redundant or impossible nil comparisons
215 The nilness checker inspects the control-flow graph of each function in
216 a package and reports nil pointer dereferences, degenerate nil
217 pointers, and panics with nil values. A degenerate comparison is of the form
218 x==nil or x!=nil where x is statically known to be nil or non-nil. These are
219 often a mistake, especially in control flow related to errors. Panics with nil
220 values are checked because they are not detectable by
222 if r := recover(); r != nil {
224 This check reports conditions such as:
226 if f == nil { // impossible condition (f is a function)
233 if p != nil { // tautological condition
239 print(*p) // nil dereference
249 **Disabled by default. Enable it by setting `"analyses": {"nilness": true}`.**
253 check consistency of Printf format strings and arguments
255 The check applies to known functions (for example, those in package fmt)
256 as well as any detected wrappers of known functions.
258 A function that wants to avail itself of printf checking but is not
259 found by this analyzer's heuristics (for example, due to use of
260 dynamic calls) can insert a bogus call:
263 _ = fmt.Sprintf(format, args...) // enable printf checking
266 The -funcs flag specifies a comma-separated list of names of additional
267 known formatting functions or methods. If the name contains a period,
268 it must denote a specific function using one of the following forms:
272 (*dir/pkg.Type).Method
274 Otherwise the name is interpreted as a case-insensitive unqualified
275 identifier such as "errorf". Either way, if a listed name ends in f, the
276 function is assumed to be Printf-like, taking a format string before the
277 argument list. Otherwise it is assumed to be Print-like, taking a list
278 of arguments with no format string.
281 **Enabled by default.**
285 check for possible unintended shadowing of variables
287 This analyzer check for shadowed variables.
288 A shadowed variable is a variable declared in an inner scope
289 with the same name and type as a variable in an outer scope,
290 and where the outer variable is mentioned after the inner one
293 (This definition can be refined; the module generates too many
294 false positives and is not yet enabled by default.)
298 func BadRead(f *os.File, buf []byte) error {
301 n, err := f.Read(buf) // shadows the function variable 'err'
303 break // causes return of wrong value
311 **Disabled by default. Enable it by setting `"analyses": {"shadow": true}`.**
315 check for shifts that equal or exceed the width of the integer
317 **Enabled by default.**
319 ## **simplifycompositelit**
321 check for composite literal simplifications
323 An array, slice, or map composite literal of the form:
325 will be simplified to:
328 This is one of the simplifications that "gofmt -s" applies.
330 **Enabled by default.**
334 check for range statement simplifications
337 for x, _ = range v {...}
338 will be simplified to:
339 for x = range v {...}
342 for _ = range v {...}
343 will be simplified to:
346 This is one of the simplifications that "gofmt -s" applies.
348 **Enabled by default.**
352 check for slice simplifications
354 A slice expression of the form:
356 will be simplified to:
359 This is one of the simplifications that "gofmt -s" applies.
361 **Enabled by default.**
365 check the argument type of sort.Slice
367 sort.Slice requires an argument of a slice type. Check that
368 the interface{} value passed to sort.Slice is actually a slice.
370 **Enabled by default.**
374 check signature of methods of well-known interfaces
376 Sometimes a type may be intended to satisfy an interface but may fail to
377 do so because of a mistake in its method signature.
378 For example, the result of this WriteTo method should be (int64, error),
379 not error, to satisfy io.WriterTo:
381 type myWriterTo struct{...}
382 func (myWriterTo) WriteTo(w io.Writer) error { ... }
384 This check ensures that each method whose name matches one of several
385 well-known interface methods from the standard library has the correct
386 signature for that interface.
388 Checked method names include:
389 Format GobEncode GobDecode MarshalJSON MarshalXML
390 Peek ReadByte ReadFrom ReadRune Scan Seek
391 UnmarshalJSON UnreadByte UnreadRune WriteByte
395 **Enabled by default.**
399 check for string(int) conversions
401 This checker flags conversions of the form string(x) where x is an integer
402 (but not byte or rune) type. Such conversions are discouraged because they
403 return the UTF-8 representation of the Unicode code point x, and not a decimal
404 string representation of x as one might expect. Furthermore, if x denotes an
405 invalid code point, the conversion cannot be statically rejected.
407 For conversions that intend on using the code point, consider replacing them
408 with string(rune(x)). Otherwise, strconv.Itoa and its equivalents return the
409 string representation of the value in the desired base.
412 **Enabled by default.**
416 check that struct field tags conform to reflect.StructTag.Get
418 Also report certain struct tags (json, xml) used with unexported fields.
420 **Enabled by default.**
422 ## **testinggoroutine**
424 report calls to (*testing.T).Fatal from goroutines started by a test.
426 Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and
427 Skip{,f,Now} methods of *testing.T, must be called from the test goroutine itself.
428 This checker detects calls to these functions that occur within a goroutine
429 started by the test. For example:
431 func TestFoo(t *testing.T) {
433 t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine
438 **Enabled by default.**
442 check for common mistaken usages of tests and examples
444 The tests checker walks Test, Benchmark and Example functions checking
445 malformed names, wrong signatures and examples documenting non-existent
448 Please see the documentation for package testing in golang.org/pkg/testing
449 for the conventions that are enforced for Tests, Benchmarks, and Examples.
451 **Enabled by default.**
455 report passing non-pointer or non-interface values to unmarshal
457 The unmarshal analysis reports calls to functions such as json.Unmarshal
458 in which the argument type is not a pointer or an interface.
460 **Enabled by default.**
464 check for unreachable code
466 The unreachable analyzer finds statements that execution can never reach
467 because they are preceded by an return statement, a call to panic, an
468 infinite loop, or similar constructs.
470 **Enabled by default.**
474 check for invalid conversions of uintptr to unsafe.Pointer
476 The unsafeptr analyzer reports likely incorrect uses of unsafe.Pointer
477 to convert integers to pointers. A conversion from uintptr to
478 unsafe.Pointer is invalid if it implies that there is a uintptr-typed
479 word in memory that holds a pointer value, because that word will be
480 invisible to stack copying and to the garbage collector.
482 **Enabled by default.**
486 check for unused parameters of functions
488 The unusedparams analyzer checks functions to see if there are
489 any parameters that are not being used.
491 To reduce false positives it ignores:
493 - parameters that do not have a name or are underscored
494 - functions in test files
495 - functions with empty bodies or those with just a return stmt
497 **Disabled by default. Enable it by setting `"analyses": {"unusedparams": true}`.**
501 check for unused results of calls to some functions
503 Some functions like fmt.Errorf return a result and have no side effects,
504 so it is always a mistake to discard the result. This analyzer reports
505 calls to certain functions in which the result of the call is ignored.
507 The set of functions may be controlled using flags.
509 **Enabled by default.**
513 checks for unused writes
515 The analyzer reports instances of writes to struct fields and
516 arrays that are never read. Specifically, when a struct object
517 or an array is copied, its elements are copied implicitly by
518 the compiler, and any element write to this copy does nothing
519 with the original object.
523 type T struct { x int }
525 for i, v := range input { // v is a copy
526 v.x = i // unused write to field x
530 Another example is about non-pointer receiver:
532 type T struct { x int }
533 func (t T) f() { // t is a copy
534 t.x = i // unused write to field x
538 **Disabled by default. Enable it by setting `"analyses": {"unusedwrite": true}`.**
542 suggested fixes for "wrong number of return values (want %d, got %d)"
544 This checker provides suggested fixes for type errors of the
545 type "wrong number of return values (want %d, got %d)". For example:
546 func m() (int, string, *bool, error) {
550 func m() (int, string, *bool, error) {
551 return 0, "", nil, nil
554 This functionality is similar to https://github.com/sqs/goreturns.
557 **Enabled by default.**
561 suggested fixes for "no new vars on left side of :="
563 This checker provides suggested fixes for type errors of the
564 type "no new vars on left side of :=". For example:
572 **Enabled by default.**
574 ## **noresultvalues**
576 suggested fixes for "no result values expected"
578 This checker provides suggested fixes for type errors of the
579 type "no result values expected". For example:
580 func z() { return nil }
585 **Enabled by default.**
587 ## **undeclaredname**
589 suggested fixes for "undeclared name: <>"
591 This checker provides suggested fixes for type errors of the
592 type "undeclared name: <>". It will insert a new statement:
595 **Enabled by default.**
599 note incomplete struct initializations
601 This analyzer provides diagnostics for any struct literals that do not have
602 any fields initialized. Because the suggested fix for this analysis is
603 expensive to compute, callers should compute it separately, using the
604 SuggestedFix function below.
607 **Enabled by default.**
609 <!-- END Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->