1# Analyzers 2 3This document describes the analyzers that `gopls` uses inside the editor. 4 5Details 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 11report mismatches between assembly files and Go declarations 12 13**Enabled by default.** 14 15## **assign** 16 17check for useless assignments 18 19This checker reports assignments of the form x = x or a[i] = a[i]. 20These are almost always useless, and even when they aren't they are 21usually a mistake. 22 23**Enabled by default.** 24 25## **atomic** 26 27check for common mistakes using the sync/atomic package 28 29The atomic checker looks for assignment statements of the form: 30 31 x = atomic.AddUint64(&x, 1) 32 33which are not atomic. 34 35**Enabled by default.** 36 37## **atomicalign** 38 39check for non-64-bits-aligned arguments to sync/atomic functions 40 41**Enabled by default.** 42 43## **bools** 44 45check for common mistakes involving boolean operators 46 47**Enabled by default.** 48 49## **buildtag** 50 51check that +build tags are well-formed and correctly located 52 53**Enabled by default.** 54 55## **cgocall** 56 57detect some violations of the cgo pointer passing rules 58 59Check for invalid cgo pointer passing. 60This looks for code that uses cgo to call C code passing values 61whose types are almost always invalid according to the cgo pointer 62sharing rules. 63Specifically, it warns about attempts to pass a Go chan, map, func, 64or slice to C, either directly, or via a pointer, array, or struct. 65 66**Enabled by default.** 67 68## **composites** 69 70check for unkeyed composite literals 71 72This analyzer reports a diagnostic for composite literals of struct 73types imported from another package that do not use the field-keyed 74syntax. Such literals are fragile because the addition of a new field 75(even if unexported) to the struct will cause compilation to fail. 76 77As an example, 78 79 err = &net.DNSConfigError{err} 80 81should be replaced by: 82 83 err = &net.DNSConfigError{Err: err} 84 85 86**Enabled by default.** 87 88## **copylocks** 89 90check for locks erroneously passed by value 91 92Inadvertently copying a value containing a lock, such as sync.Mutex or 93sync.WaitGroup, may cause both copies to malfunction. Generally such 94values should be referred to through a pointer. 95 96**Enabled by default.** 97 98## **deepequalerrors** 99 100check for calls of reflect.DeepEqual on error values 101 102The deepequalerrors checker looks for calls of the form: 103 104 reflect.DeepEqual(err1, err2) 105 106where err1 and err2 are errors. Using reflect.DeepEqual to compare 107errors is discouraged. 108 109**Enabled by default.** 110 111## **errorsas** 112 113report passing non-pointer or non-error values to errors.As 114 115The errorsas analysis reports calls to errors.As where the type 116of the second argument is not a pointer to a type implementing error. 117 118**Enabled by default.** 119 120## **fieldalignment** 121 122find structs that would use less memory if their fields were sorted 123 124This analyzer find structs that can be rearranged to use less memory, and provides 125a suggested edit with the optimal order. 126 127Note that there are two different diagnostics reported. One checks struct size, 128and the other reports "pointer bytes" used. Pointer bytes is how many bytes of the 129object that the garbage collector has to potentially scan for pointers, for example: 130 131 struct { uint32; string } 132 133have 16 pointer bytes because the garbage collector has to scan up through the string's 134inner pointer. 135 136 struct { string; *uint32 } 137 138has 24 pointer bytes because it has to scan further through the *uint32. 139 140 struct { string; uint32 } 141 142has 8 because it can stop immediately after the string pointer. 143 144 145**Disabled by default. Enable it by setting `"analyses": {"fieldalignment": true}`.** 146 147## **httpresponse** 148 149check for mistakes using HTTP responses 150 151A common mistake when using the net/http package is to defer a function 152call to close the http.Response Body before checking the error that 153determines whether the response is valid: 154 155 resp, err := http.Head(url) 156 defer resp.Body.Close() 157 if err != nil { 158 log.Fatal(err) 159 } 160 // (defer statement belongs here) 161 162This checker helps uncover latent nil dereference bugs by reporting a 163diagnostic for such mistakes. 164 165**Enabled by default.** 166 167## **ifaceassert** 168 169detect impossible interface-to-interface type assertions 170 171This checker flags type assertions v.(T) and corresponding type-switch cases 172in which the static type V of v is an interface that cannot possibly implement 173the target interface T. This occurs when V and T contain methods with the same 174name but different signatures. Example: 175 176 var v interface { 177 Read() 178 } 179 _ = v.(io.Reader) 180 181The Read method in v has a different signature than the Read method in 182io.Reader, so this assertion cannot succeed. 183 184 185**Enabled by default.** 186 187## **loopclosure** 188 189check references to loop variables from within nested functions 190 191This analyzer checks for references to loop variables from within a 192function literal inside the loop body. It checks only instances where 193the function literal is called in a defer or go statement that is the 194last statement in the loop body, as otherwise we would need whole 195program analysis. 196 197For example: 198 199 for i, v := range s { 200 go func() { 201 println(i, v) // not what you might expect 202 }() 203 } 204 205See: https://golang.org/doc/go_faq.html#closures_and_goroutines 206 207**Enabled by default.** 208 209## **lostcancel** 210 211check cancel func returned by context.WithCancel is called 212 213The cancellation function returned by context.WithCancel, WithTimeout, 214and WithDeadline must be called or the new context will remain live 215until its parent context is cancelled. 216(The background context is never cancelled.) 217 218**Enabled by default.** 219 220## **nilfunc** 221 222check for useless comparisons between functions and nil 223 224A useless comparison is one like f == nil as opposed to f() == nil. 225 226**Enabled by default.** 227 228## **nilness** 229 230check for redundant or impossible nil comparisons 231 232The nilness checker inspects the control-flow graph of each function in 233a package and reports nil pointer dereferences, degenerate nil 234pointers, and panics with nil values. A degenerate comparison is of the form 235x==nil or x!=nil where x is statically known to be nil or non-nil. These are 236often a mistake, especially in control flow related to errors. Panics with nil 237values are checked because they are not detectable by 238 239 if r := recover(); r != nil { 240 241This check reports conditions such as: 242 243 if f == nil { // impossible condition (f is a function) 244 } 245 246and: 247 248 p := &v 249 ... 250 if p != nil { // tautological condition 251 } 252 253and: 254 255 if p == nil { 256 print(*p) // nil dereference 257 } 258 259and: 260 261 if p == nil { 262 panic(p) 263 } 264 265 266**Disabled by default. Enable it by setting `"analyses": {"nilness": true}`.** 267 268## **printf** 269 270check consistency of Printf format strings and arguments 271 272The check applies to known functions (for example, those in package fmt) 273as well as any detected wrappers of known functions. 274 275A function that wants to avail itself of printf checking but is not 276found by this analyzer's heuristics (for example, due to use of 277dynamic calls) can insert a bogus call: 278 279 if false { 280 _ = fmt.Sprintf(format, args...) // enable printf checking 281 } 282 283The -funcs flag specifies a comma-separated list of names of additional 284known formatting functions or methods. If the name contains a period, 285it must denote a specific function using one of the following forms: 286 287 dir/pkg.Function 288 dir/pkg.Type.Method 289 (*dir/pkg.Type).Method 290 291Otherwise the name is interpreted as a case-insensitive unqualified 292identifier such as "errorf". Either way, if a listed name ends in f, the 293function is assumed to be Printf-like, taking a format string before the 294argument list. Otherwise it is assumed to be Print-like, taking a list 295of arguments with no format string. 296 297 298**Enabled by default.** 299 300## **shadow** 301 302check for possible unintended shadowing of variables 303 304This analyzer check for shadowed variables. 305A shadowed variable is a variable declared in an inner scope 306with the same name and type as a variable in an outer scope, 307and where the outer variable is mentioned after the inner one 308is declared. 309 310(This definition can be refined; the module generates too many 311false positives and is not yet enabled by default.) 312 313For example: 314 315 func BadRead(f *os.File, buf []byte) error { 316 var err error 317 for { 318 n, err := f.Read(buf) // shadows the function variable 'err' 319 if err != nil { 320 break // causes return of wrong value 321 } 322 foo(buf) 323 } 324 return err 325 } 326 327 328**Disabled by default. Enable it by setting `"analyses": {"shadow": true}`.** 329 330## **shift** 331 332check for shifts that equal or exceed the width of the integer 333 334**Enabled by default.** 335 336## **simplifycompositelit** 337 338check for composite literal simplifications 339 340An array, slice, or map composite literal of the form: 341 []T{T{}, T{}} 342will be simplified to: 343 []T{{}, {}} 344 345This is one of the simplifications that "gofmt -s" applies. 346 347**Enabled by default.** 348 349## **simplifyrange** 350 351check for range statement simplifications 352 353A range of the form: 354 for x, _ = range v {...} 355will be simplified to: 356 for x = range v {...} 357 358A range of the form: 359 for _ = range v {...} 360will be simplified to: 361 for range v {...} 362 363This is one of the simplifications that "gofmt -s" applies. 364 365**Enabled by default.** 366 367## **simplifyslice** 368 369check for slice simplifications 370 371A slice expression of the form: 372 s[a:len(s)] 373will be simplified to: 374 s[a:] 375 376This is one of the simplifications that "gofmt -s" applies. 377 378**Enabled by default.** 379 380## **sortslice** 381 382check the argument type of sort.Slice 383 384sort.Slice requires an argument of a slice type. Check that 385the interface{} value passed to sort.Slice is actually a slice. 386 387**Enabled by default.** 388 389## **stdmethods** 390 391check signature of methods of well-known interfaces 392 393Sometimes a type may be intended to satisfy an interface but may fail to 394do so because of a mistake in its method signature. 395For example, the result of this WriteTo method should be (int64, error), 396not error, to satisfy io.WriterTo: 397 398 type myWriterTo struct{...} 399 func (myWriterTo) WriteTo(w io.Writer) error { ... } 400 401This check ensures that each method whose name matches one of several 402well-known interface methods from the standard library has the correct 403signature for that interface. 404 405Checked method names include: 406 Format GobEncode GobDecode MarshalJSON MarshalXML 407 Peek ReadByte ReadFrom ReadRune Scan Seek 408 UnmarshalJSON UnreadByte UnreadRune WriteByte 409 WriteTo 410 411 412**Enabled by default.** 413 414## **stringintconv** 415 416check for string(int) conversions 417 418This checker flags conversions of the form string(x) where x is an integer 419(but not byte or rune) type. Such conversions are discouraged because they 420return the UTF-8 representation of the Unicode code point x, and not a decimal 421string representation of x as one might expect. Furthermore, if x denotes an 422invalid code point, the conversion cannot be statically rejected. 423 424For conversions that intend on using the code point, consider replacing them 425with string(rune(x)). Otherwise, strconv.Itoa and its equivalents return the 426string representation of the value in the desired base. 427 428 429**Enabled by default.** 430 431## **structtag** 432 433check that struct field tags conform to reflect.StructTag.Get 434 435Also report certain struct tags (json, xml) used with unexported fields. 436 437**Enabled by default.** 438 439## **testinggoroutine** 440 441report calls to (*testing.T).Fatal from goroutines started by a test. 442 443Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and 444Skip{,f,Now} methods of *testing.T, must be called from the test goroutine itself. 445This checker detects calls to these functions that occur within a goroutine 446started by the test. For example: 447 448func TestFoo(t *testing.T) { 449 go func() { 450 t.Fatal("oops") // error: (*T).Fatal called from non-test goroutine 451 }() 452} 453 454 455**Enabled by default.** 456 457## **tests** 458 459check for common mistaken usages of tests and examples 460 461The tests checker walks Test, Benchmark and Example functions checking 462malformed names, wrong signatures and examples documenting non-existent 463identifiers. 464 465Please see the documentation for package testing in golang.org/pkg/testing 466for the conventions that are enforced for Tests, Benchmarks, and Examples. 467 468**Enabled by default.** 469 470## **unmarshal** 471 472report passing non-pointer or non-interface values to unmarshal 473 474The unmarshal analysis reports calls to functions such as json.Unmarshal 475in which the argument type is not a pointer or an interface. 476 477**Enabled by default.** 478 479## **unreachable** 480 481check for unreachable code 482 483The unreachable analyzer finds statements that execution can never reach 484because they are preceded by an return statement, a call to panic, an 485infinite loop, or similar constructs. 486 487**Enabled by default.** 488 489## **unsafeptr** 490 491check for invalid conversions of uintptr to unsafe.Pointer 492 493The unsafeptr analyzer reports likely incorrect uses of unsafe.Pointer 494to convert integers to pointers. A conversion from uintptr to 495unsafe.Pointer is invalid if it implies that there is a uintptr-typed 496word in memory that holds a pointer value, because that word will be 497invisible to stack copying and to the garbage collector. 498 499**Enabled by default.** 500 501## **unusedparams** 502 503check for unused parameters of functions 504 505The unusedparams analyzer checks functions to see if there are 506any parameters that are not being used. 507 508To reduce false positives it ignores: 509- methods 510- parameters that do not have a name or are underscored 511- functions in test files 512- functions with empty bodies or those with just a return stmt 513 514**Disabled by default. Enable it by setting `"analyses": {"unusedparams": true}`.** 515 516## **unusedresult** 517 518check for unused results of calls to some functions 519 520Some functions like fmt.Errorf return a result and have no side effects, 521so it is always a mistake to discard the result. This analyzer reports 522calls to certain functions in which the result of the call is ignored. 523 524The set of functions may be controlled using flags. 525 526**Enabled by default.** 527 528## **unusedwrite** 529 530checks for unused writes 531 532The analyzer reports instances of writes to struct fields and 533arrays that are never read. Specifically, when a struct object 534or an array is copied, its elements are copied implicitly by 535the compiler, and any element write to this copy does nothing 536with the original object. 537 538For example: 539 540 type T struct { x int } 541 func f(input []T) { 542 for i, v := range input { // v is a copy 543 v.x = i // unused write to field x 544 } 545 } 546 547Another example is about non-pointer receiver: 548 549 type T struct { x int } 550 func (t T) f() { // t is a copy 551 t.x = i // unused write to field x 552 } 553 554 555**Disabled by default. Enable it by setting `"analyses": {"unusedwrite": true}`.** 556 557## **fillreturns** 558 559suggested fixes for "wrong number of return values (want %d, got %d)" 560 561This checker provides suggested fixes for type errors of the 562type "wrong number of return values (want %d, got %d)". For example: 563 func m() (int, string, *bool, error) { 564 return 565 } 566will turn into 567 func m() (int, string, *bool, error) { 568 return 0, "", nil, nil 569 } 570 571This functionality is similar to https://github.com/sqs/goreturns. 572 573 574**Enabled by default.** 575 576## **nonewvars** 577 578suggested fixes for "no new vars on left side of :=" 579 580This checker provides suggested fixes for type errors of the 581type "no new vars on left side of :=". For example: 582 z := 1 583 z := 2 584will turn into 585 z := 1 586 z = 2 587 588 589**Enabled by default.** 590 591## **noresultvalues** 592 593suggested fixes for "no result values expected" 594 595This checker provides suggested fixes for type errors of the 596type "no result values expected". For example: 597 func z() { return nil } 598will turn into 599 func z() { return } 600 601 602**Enabled by default.** 603 604## **undeclaredname** 605 606suggested fixes for "undeclared name: <>" 607 608This checker provides suggested fixes for type errors of the 609type "undeclared name: <>". It will insert a new statement: 610"<> := ". 611 612**Enabled by default.** 613 614## **fillstruct** 615 616note incomplete struct initializations 617 618This analyzer provides diagnostics for any struct literals that do not have 619any fields initialized. Because the suggested fix for this analysis is 620expensive to compute, callers should compute it separately, using the 621SuggestedFix function below. 622 623 624**Enabled by default.** 625 626<!-- END Analyzers: DO NOT MANUALLY EDIT THIS SECTION --> 627