.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools / gopls@v0.6.9 / doc / analyzers.md
1 # Analyzers
2
3 This document describes the analyzers that `gopls` uses inside the editor.
4
5 Details about how to enable/disable these analyses can be found
6 [here](settings.md#analyses).
7
8 <!-- BEGIN Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->
9 ## **asmdecl**
10
11 report mismatches between assembly files and Go declarations
12
13 **Enabled by default.**
14
15 ## **assign**
16
17 check for useless assignments
18
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
21 usually a mistake.
22
23 **Enabled by default.**
24
25 ## **atomic**
26
27 check for common mistakes using the sync/atomic package
28
29 The atomic checker looks for assignment statements of the form:
30
31         x = atomic.AddUint64(&x, 1)
32
33 which are not atomic.
34
35 **Enabled by default.**
36
37 ## **atomicalign**
38
39 check for non-64-bits-aligned arguments to sync/atomic functions
40
41 **Enabled by default.**
42
43 ## **bools**
44
45 check for common mistakes involving boolean operators
46
47 **Enabled by default.**
48
49 ## **buildtag**
50
51 check that +build tags are well-formed and correctly located
52
53 **Enabled by default.**
54
55 ## **cgocall**
56
57 detect some violations of the cgo pointer passing rules
58
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
62 sharing rules.
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.
65
66 **Enabled by default.**
67
68 ## **composites**
69
70 check for unkeyed composite literals
71
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.
76
77 As an example,
78
79         err = &net.DNSConfigError{err}
80
81 should be replaced by:
82
83         err = &net.DNSConfigError{Err: err}
84
85
86 **Enabled by default.**
87
88 ## **copylocks**
89
90 check for locks erroneously passed by value
91
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.
95
96 **Enabled by default.**
97
98 ## **deepequalerrors**
99
100 check for calls of reflect.DeepEqual on error values
101
102 The deepequalerrors checker looks for calls of the form:
103
104     reflect.DeepEqual(err1, err2)
105
106 where err1 and err2 are errors. Using reflect.DeepEqual to compare
107 errors is discouraged.
108
109 **Enabled by default.**
110
111 ## **errorsas**
112
113 report passing non-pointer or non-error values to errors.As
114
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.
117
118 **Enabled by default.**
119
120 ## **fieldalignment**
121
122 find structs that would take less memory if their fields were sorted
123
124 This analyzer find structs that can be rearranged to take less memory, and provides
125 a suggested edit with the optimal order.
126
127
128 **Disabled by default. Enable it by setting `"analyses": {"fieldalignment": true}`.**
129
130 ## **httpresponse**
131
132 check for mistakes using HTTP responses
133
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:
137
138         resp, err := http.Head(url)
139         defer resp.Body.Close()
140         if err != nil {
141                 log.Fatal(err)
142         }
143         // (defer statement belongs here)
144
145 This checker helps uncover latent nil dereference bugs by reporting a
146 diagnostic for such mistakes.
147
148 **Enabled by default.**
149
150 ## **ifaceassert**
151
152 detect impossible interface-to-interface type assertions
153
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:
158
159         var v interface {
160                 Read()
161         }
162         _ = v.(io.Reader)
163
164 The Read method in v has a different signature than the Read method in
165 io.Reader, so this assertion cannot succeed.
166
167
168 **Enabled by default.**
169
170 ## **loopclosure**
171
172 check references to loop variables from within nested functions
173
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
178 program analysis.
179
180 For example:
181
182         for i, v := range s {
183                 go func() {
184                         println(i, v) // not what you might expect
185                 }()
186         }
187
188 See: https://golang.org/doc/go_faq.html#closures_and_goroutines
189
190 **Enabled by default.**
191
192 ## **lostcancel**
193
194 check cancel func returned by context.WithCancel is called
195
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.)
200
201 **Enabled by default.**
202
203 ## **nilfunc**
204
205 check for useless comparisons between functions and nil
206
207 A useless comparison is one like f == nil as opposed to f() == nil.
208
209 **Enabled by default.**
210
211 ## **nilness**
212
213 check for redundant or impossible nil comparisons
214
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
221
222         if r := recover(); r != nil {
223
224 This check reports conditions such as:
225
226         if f == nil { // impossible condition (f is a function)
227         }
228
229 and:
230
231         p := &v
232         ...
233         if p != nil { // tautological condition
234         }
235
236 and:
237
238         if p == nil {
239                 print(*p) // nil dereference
240         }
241
242 and:
243
244         if p == nil {
245                 panic(p)
246         }
247
248
249 **Disabled by default. Enable it by setting `"analyses": {"nilness": true}`.**
250
251 ## **printf**
252
253 check consistency of Printf format strings and arguments
254
255 The check applies to known functions (for example, those in package fmt)
256 as well as any detected wrappers of known functions.
257
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:
261
262         if false {
263                 _ = fmt.Sprintf(format, args...) // enable printf checking
264         }
265
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:
269
270         dir/pkg.Function
271         dir/pkg.Type.Method
272         (*dir/pkg.Type).Method
273
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.
279
280
281 **Enabled by default.**
282
283 ## **shadow**
284
285 check for possible unintended shadowing of variables
286
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
291 is declared.
292
293 (This definition can be refined; the module generates too many
294 false positives and is not yet enabled by default.)
295
296 For example:
297
298         func BadRead(f *os.File, buf []byte) error {
299                 var err error
300                 for {
301                         n, err := f.Read(buf) // shadows the function variable 'err'
302                         if err != nil {
303                                 break // causes return of wrong value
304                         }
305                         foo(buf)
306                 }
307                 return err
308         }
309
310
311 **Disabled by default. Enable it by setting `"analyses": {"shadow": true}`.**
312
313 ## **shift**
314
315 check for shifts that equal or exceed the width of the integer
316
317 **Enabled by default.**
318
319 ## **simplifycompositelit**
320
321 check for composite literal simplifications
322
323 An array, slice, or map composite literal of the form:
324         []T{T{}, T{}}
325 will be simplified to:
326         []T{{}, {}}
327
328 This is one of the simplifications that "gofmt -s" applies.
329
330 **Enabled by default.**
331
332 ## **simplifyrange**
333
334 check for range statement simplifications
335
336 A range of the form:
337         for x, _ = range v {...}
338 will be simplified to:
339         for x = range v {...}
340
341 A range of the form:
342         for _ = range v {...}
343 will be simplified to:
344         for range v {...}
345
346 This is one of the simplifications that "gofmt -s" applies.
347
348 **Enabled by default.**
349
350 ## **simplifyslice**
351
352 check for slice simplifications
353
354 A slice expression of the form:
355         s[a:len(s)]
356 will be simplified to:
357         s[a:]
358
359 This is one of the simplifications that "gofmt -s" applies.
360
361 **Enabled by default.**
362
363 ## **sortslice**
364
365 check the argument type of sort.Slice
366
367 sort.Slice requires an argument of a slice type. Check that
368 the interface{} value passed to sort.Slice is actually a slice.
369
370 **Enabled by default.**
371
372 ## **stdmethods**
373
374 check signature of methods of well-known interfaces
375
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:
380
381         type myWriterTo struct{...}
382         func (myWriterTo) WriteTo(w io.Writer) error { ... }
383
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.
387
388 Checked method names include:
389         Format GobEncode GobDecode MarshalJSON MarshalXML
390         Peek ReadByte ReadFrom ReadRune Scan Seek
391         UnmarshalJSON UnreadByte UnreadRune WriteByte
392         WriteTo
393
394
395 **Enabled by default.**
396
397 ## **stringintconv**
398
399 check for string(int) conversions
400
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.
406
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.
410
411
412 **Enabled by default.**
413
414 ## **structtag**
415
416 check that struct field tags conform to reflect.StructTag.Get
417
418 Also report certain struct tags (json, xml) used with unexported fields.
419
420 **Enabled by default.**
421
422 ## **testinggoroutine**
423
424 report calls to (*testing.T).Fatal from goroutines started by a test.
425
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:
430
431 func TestFoo(t *testing.T) {
432     go func() {
433         t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine
434     }()
435 }
436
437
438 **Enabled by default.**
439
440 ## **tests**
441
442 check for common mistaken usages of tests and examples
443
444 The tests checker walks Test, Benchmark and Example functions checking
445 malformed names, wrong signatures and examples documenting non-existent
446 identifiers.
447
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.
450
451 **Enabled by default.**
452
453 ## **unmarshal**
454
455 report passing non-pointer or non-interface values to unmarshal
456
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.
459
460 **Enabled by default.**
461
462 ## **unreachable**
463
464 check for unreachable code
465
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.
469
470 **Enabled by default.**
471
472 ## **unsafeptr**
473
474 check for invalid conversions of uintptr to unsafe.Pointer
475
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.
481
482 **Enabled by default.**
483
484 ## **unusedparams**
485
486 check for unused parameters of functions
487
488 The unusedparams analyzer checks functions to see if there are
489 any parameters that are not being used.
490
491 To reduce false positives it ignores:
492 - methods
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
496
497 **Disabled by default. Enable it by setting `"analyses": {"unusedparams": true}`.**
498
499 ## **unusedresult**
500
501 check for unused results of calls to some functions
502
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.
506
507 The set of functions may be controlled using flags.
508
509 **Enabled by default.**
510
511 ## **unusedwrite**
512
513 checks for unused writes
514
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.
520
521 For example:
522
523         type T struct { x int }
524         func f(input []T) {
525                 for i, v := range input {  // v is a copy
526                         v.x = i  // unused write to field x
527                 }
528         }
529
530 Another example is about non-pointer receiver:
531
532         type T struct { x int }
533         func (t T) f() {  // t is a copy
534                 t.x = i  // unused write to field x
535         }
536
537
538 **Disabled by default. Enable it by setting `"analyses": {"unusedwrite": true}`.**
539
540 ## **fillreturns**
541
542 suggested fixes for "wrong number of return values (want %d, got %d)"
543
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) {
547                 return
548         }
549 will turn into
550         func m() (int, string, *bool, error) {
551                 return 0, "", nil, nil
552         }
553
554 This functionality is similar to https://github.com/sqs/goreturns.
555
556
557 **Enabled by default.**
558
559 ## **nonewvars**
560
561 suggested fixes for "no new vars on left side of :="
562
563 This checker provides suggested fixes for type errors of the
564 type "no new vars on left side of :=". For example:
565         z := 1
566         z := 2
567 will turn into
568         z := 1
569         z = 2
570
571
572 **Enabled by default.**
573
574 ## **noresultvalues**
575
576 suggested fixes for "no result values expected"
577
578 This checker provides suggested fixes for type errors of the
579 type "no result values expected". For example:
580         func z() { return nil }
581 will turn into
582         func z() { return }
583
584
585 **Enabled by default.**
586
587 ## **undeclaredname**
588
589 suggested fixes for "undeclared name: <>"
590
591 This checker provides suggested fixes for type errors of the
592 type "undeclared name: <>". It will insert a new statement:
593 "<> := ".
594
595 **Enabled by default.**
596
597 ## **fillstruct**
598
599 note incomplete struct initializations
600
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.
605
606
607 **Enabled by default.**
608
609 <!-- END Analyzers: DO NOT MANUALLY EDIT THIS SECTION -->