diff --git a/go/analysis/passes/internal/analysisutil/util.go b/go/analysis/passes/internal/analysisutil/util.go index c0060753f..3f01b3b55 100644 --- a/go/analysis/passes/internal/analysisutil/util.go +++ b/go/analysis/passes/internal/analysisutil/util.go @@ -13,6 +13,8 @@ import ( "go/token" "go/types" "os" + + "golang.org/x/tools/internal/analysisinternal" ) // Format returns a string representation of the expression. @@ -150,3 +152,5 @@ func IsFunctionNamed(f *types.Func, pkgPath string, names ...string) bool { } return false } + +var MustExtractDoc = analysisinternal.MustExtractDoc diff --git a/gopls/doc/analyzers.md b/gopls/doc/analyzers.md index c0b7c4341..51eec8a90 100644 --- a/gopls/doc/analyzers.md +++ b/gopls/doc/analyzers.md @@ -8,7 +8,7 @@ Details about how to enable/disable these analyses can be found ## **appends** -check for missing values after append +appends: check for missing values after append This checker reports calls to append that pass no values to be appended to the slice. @@ -19,27 +19,33 @@ no values to be appended to the slice. Such calls are always no-ops and often indicate an underlying mistake. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/appends) + **Enabled by default.** ## **asmdecl** -report mismatches between assembly files and Go declarations +asmdecl: report mismatches between assembly files and Go declarations + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/asmdecl) **Enabled by default.** ## **assign** -check for useless assignments +assign: check for useless assignments This checker reports assignments of the form x = x or a[i] = a[i]. These are almost always useless, and even when they aren't they are usually a mistake. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/assign) + **Enabled by default.** ## **atomic** -check for common mistakes using the sync/atomic package +atomic: check for common mistakes using the sync/atomic package The atomic checker looks for assignment statements of the form: @@ -47,29 +53,37 @@ The atomic checker looks for assignment statements of the form: which are not atomic. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/atomic) + **Enabled by default.** ## **atomicalign** -check for non-64-bits-aligned arguments to sync/atomic functions +atomicalign: check for non-64-bits-aligned arguments to sync/atomic functions + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/atomicalign) **Enabled by default.** ## **bools** -check for common mistakes involving boolean operators +bools: check for common mistakes involving boolean operators + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/bools) **Enabled by default.** ## **buildtag** -check //go:build and // +build directives +buildtag: check //go:build and // +build directives + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/buildtag) **Enabled by default.** ## **cgocall** -detect some violations of the cgo pointer passing rules +cgocall: detect some violations of the cgo pointer passing rules Check for invalid cgo pointer passing. This looks for code that uses cgo to call C code passing values @@ -78,11 +92,13 @@ sharing rules. Specifically, it warns about attempts to pass a Go chan, map, func, or slice to C, either directly, or via a pointer, array, or struct. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/cgocall) + **Enabled by default.** ## **composites** -check for unkeyed composite literals +composites: check for unkeyed composite literals This analyzer reports a diagnostic for composite literals of struct types imported from another package that do not use the field-keyed @@ -98,21 +114,25 @@ should be replaced by: err = &net.DNSConfigError{Err: err} +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/composite) + **Enabled by default.** ## **copylocks** -check for locks erroneously passed by value +copylocks: check for locks erroneously passed by value Inadvertently copying a value containing a lock, such as sync.Mutex or sync.WaitGroup, may cause both copies to malfunction. Generally such values should be referred to through a pointer. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/copylocks) + **Enabled by default.** ## **deepequalerrors** -check for calls of reflect.DeepEqual on error values +deepequalerrors: check for calls of reflect.DeepEqual on error values The deepequalerrors checker looks for calls of the form: @@ -121,11 +141,13 @@ The deepequalerrors checker looks for calls of the form: where err1 and err2 are errors. Using reflect.DeepEqual to compare errors is discouraged. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/deepequalerrors) + **Enabled by default.** ## **defers** -report common mistakes in defer statements +defers: report common mistakes in defer statements The defers analyzer reports a diagnostic when a defer statement would result in a non-deferred call to time.Since, as experience has shown @@ -141,22 +163,27 @@ The correct code is: defer func() { recordLatency(time.Since(start)) }() +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/defers) + **Enabled by default.** ## **deprecated** -check for use of deprecated identifiers +deprecated: check for use of deprecated identifiers -The deprecated analyzer looks for deprecated symbols and package imports. +The deprecated analyzer looks for deprecated symbols and package +imports. See https://go.dev/wiki/Deprecated to learn about Go's convention for documenting and signaling deprecated identifiers. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/deprecated) + **Enabled by default.** ## **directive** -check Go toolchain directives such as //go:debug +directive: check Go toolchain directives such as //go:debug This analyzer checks for problems with known Go toolchain directives in all Go source files in a package directory, even those excluded by @@ -172,11 +199,13 @@ This analyzer does not check //go:build, which is handled by the buildtag analyzer. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/directive) + **Enabled by default.** ## **embed** -check //go:embed directive usage +embed: check //go:embed directive usage This analyzer checks that the embed package is imported if //go:embed directives are present, providing a suggested fix to add the import if @@ -185,20 +214,24 @@ it is missing. This analyzer also checks that //go:embed directives precede the declaration of a single variable. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/embeddirective) + **Enabled by default.** ## **errorsas** -report passing non-pointer or non-error values to errors.As +errorsas: report passing non-pointer or non-error values to errors.As The errorsas analysis reports calls to errors.As where the type of the second argument is not a pointer to a type implementing error. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/errorsas) + **Enabled by default.** ## **fieldalignment** -find structs that would use less memory if their fields were sorted +fieldalignment: find structs that would use less memory if their fields were sorted This analyzer find structs that can be rearranged to use less memory, and provides a suggested edit with the most compact order. @@ -226,11 +259,13 @@ to occupy the same CPU cache line, inducing a form of memory contention known as "false sharing" that slows down both goroutines. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/fieldalignment) + **Disabled by default. Enable it by setting `"analyses": {"fieldalignment": true}`.** ## **httpresponse** -check for mistakes using HTTP responses +httpresponse: check for mistakes using HTTP responses A common mistake when using the net/http package is to defer a function call to close the http.Response Body before checking the error that @@ -246,11 +281,13 @@ determines whether the response is valid: This checker helps uncover latent nil dereference bugs by reporting a diagnostic for such mistakes. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/httpresponse) + **Enabled by default.** ## **ifaceassert** -detect impossible interface-to-interface type assertions +ifaceassert: detect impossible interface-to-interface type assertions This checker flags type assertions v.(T) and corresponding type-switch cases in which the static type V of v is an interface that cannot possibly implement @@ -265,11 +302,13 @@ name but different signatures. Example: The Read method in v has a different signature than the Read method in io.Reader, so this assertion cannot succeed. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/ifaceassert) + **Enabled by default.** ## **loopclosure** -check references to loop variables from within nested functions +loopclosure: check references to loop variables from within nested functions This analyzer reports places where a function literal references the iteration variable of an enclosing loop, and the loop calls the function @@ -335,30 +374,36 @@ statements such as if, switch, and select.) See: https://golang.org/doc/go_faq.html#closures_and_goroutines +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/loopclosure) + **Enabled by default.** ## **lostcancel** -check cancel func returned by context.WithCancel is called +lostcancel: check cancel func returned by context.WithCancel is called The cancellation function returned by context.WithCancel, WithTimeout, and WithDeadline must be called or the new context will remain live until its parent context is cancelled. (The background context is never cancelled.) +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/lostcancel) + **Enabled by default.** ## **nilfunc** -check for useless comparisons between functions and nil +nilfunc: check for useless comparisons between functions and nil A useless comparison is one like f == nil as opposed to f() == nil. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilfunc) + **Enabled by default.** ## **nilness** -check for redundant or impossible nil comparisons +nilness: check for redundant or impossible nil comparisons The nilness checker inspects the control-flow graph of each function in a package and reports nil pointer dereferences, degenerate nil @@ -393,11 +438,13 @@ and: panic(p) } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/nilness) + **Enabled by default.** ## **printf** -check consistency of Printf format strings and arguments +printf: check consistency of Printf format strings and arguments The check applies to calls of the formatting functions such as [fmt.Printf] and [fmt.Sprintf], as well as any detected wrappers of @@ -435,11 +482,13 @@ function is assumed to be Printf-like, taking a format string before the argument list. Otherwise it is assumed to be Print-like, taking a list of arguments with no format string. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/printf) + **Enabled by default.** ## **shadow** -check for possible unintended shadowing of variables +shadow: check for possible unintended shadowing of variables This analyzer check for shadowed variables. A shadowed variable is a variable declared in an inner scope @@ -464,61 +513,83 @@ For example: return err } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow) + **Disabled by default. Enable it by setting `"analyses": {"shadow": true}`.** ## **shift** -check for shifts that equal or exceed the width of the integer +shift: check for shifts that equal or exceed the width of the integer + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shift) **Enabled by default.** ## **simplifycompositelit** -check for composite literal simplifications +simplifycompositelit: check for composite literal simplifications An array, slice, or map composite literal of the form: + []T{T{}, T{}} + will be simplified to: + []T{{}, {}} This is one of the simplifications that "gofmt -s" applies. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifycompositelit) + **Enabled by default.** ## **simplifyrange** -check for range statement simplifications +simplifyrange: check for range statement simplifications A range of the form: + for x, _ = range v {...} + will be simplified to: + for x = range v {...} A range of the form: + for _ = range v {...} + will be simplified to: + for range v {...} This is one of the simplifications that "gofmt -s" applies. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyrange) + **Enabled by default.** ## **simplifyslice** -check for slice simplifications +simplifyslice: check for slice simplifications A slice expression of the form: + s[a:len(s)] + will be simplified to: + s[a:] This is one of the simplifications that "gofmt -s" applies. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyslice) + **Enabled by default.** ## **slog** -check for invalid structured logging calls +slog: check for invalid structured logging calls The slog checker looks for calls to functions from the log/slog package that take alternating key-value pairs. It reports calls @@ -532,20 +603,24 @@ and slog.Info("message", "k1", v1, "k2") // call to slog.Info missing a final value +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/slog) + **Enabled by default.** ## **sortslice** -check the argument type of sort.Slice +sortslice: check the argument type of sort.Slice sort.Slice requires an argument of a slice type. Check that the interface{} value passed to sort.Slice is actually a slice. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/sortslice) + **Enabled by default.** ## **stdmethods** -check signature of methods of well-known interfaces +stdmethods: check signature of methods of well-known interfaces Sometimes a type may be intended to satisfy an interface but may fail to do so because of a mistake in its method signature. @@ -566,11 +641,13 @@ Checked method names include: UnmarshalJSON UnreadByte UnreadRune WriteByte WriteTo +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stdmethods) + **Enabled by default.** ## **stringintconv** -check for string(int) conversions +stringintconv: check for string(int) conversions This checker flags conversions of the form string(x) where x is an integer (but not byte or rune) type. Such conversions are discouraged because they @@ -582,19 +659,23 @@ For conversions that intend on using the code point, consider replacing them with string(rune(x)). Otherwise, strconv.Itoa and its equivalents return the string representation of the value in the desired base. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stringintconv) + **Enabled by default.** ## **structtag** -check that struct field tags conform to reflect.StructTag.Get +structtag: check that struct field tags conform to reflect.StructTag.Get Also report certain struct tags (json, xml) used with unexported fields. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/structtag) + **Enabled by default.** ## **testinggoroutine** -report calls to (*testing.T).Fatal from goroutines started by a test +testinggoroutine: report calls to (*testing.T).Fatal from goroutines started by a test Functions that abruptly terminate a test, such as the Fatal, Fatalf, FailNow, and Skip{,f,Now} methods of *testing.T, must be called from the test goroutine itself. @@ -607,11 +688,13 @@ started by the test. For example: }() } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/testinggoroutine) + **Enabled by default.** ## **tests** -check for common mistaken usages of tests and examples +tests: check for common mistaken usages of tests and examples The tests checker walks Test, Benchmark, Fuzzing and Example functions checking malformed names, wrong signatures and examples documenting non-existent @@ -620,40 +703,48 @@ identifiers. Please see the documentation for package testing in golang.org/pkg/testing for the conventions that are enforced for Tests, Benchmarks, and Examples. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/tests) + **Enabled by default.** ## **timeformat** -check for calls of (time.Time).Format or time.Parse with 2006-02-01 +timeformat: check for calls of (time.Time).Format or time.Parse with 2006-02-01 The timeformat checker looks for time formats with the 2006-02-01 (yyyy-dd-mm) format. Internationally, "yyyy-dd-mm" does not occur in common calendar date standards, and so it is more likely that 2006-01-02 (yyyy-mm-dd) was intended. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/timeformat) + **Enabled by default.** ## **unmarshal** -report passing non-pointer or non-interface values to unmarshal +unmarshal: report passing non-pointer or non-interface values to unmarshal The unmarshal analysis reports calls to functions such as json.Unmarshal in which the argument type is not a pointer or an interface. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unmarshal) + **Enabled by default.** ## **unreachable** -check for unreachable code +unreachable: check for unreachable code The unreachable analyzer finds statements that execution can never reach because they are preceded by an return statement, a call to panic, an infinite loop, or similar constructs. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unreachable) + **Enabled by default.** ## **unsafeptr** -check for invalid conversions of uintptr to unsafe.Pointer +unsafeptr: check for invalid conversions of uintptr to unsafe.Pointer The unsafeptr analyzer reports likely incorrect uses of unsafe.Pointer to convert integers to pointers. A conversion from uintptr to @@ -661,11 +752,13 @@ unsafe.Pointer is invalid if it implies that there is a uintptr-typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unsafeptr) + **Enabled by default.** ## **unusedparams** -check for unused parameters of functions +unusedparams: check for unused parameters of functions The unusedparams analyzer checks functions to see if there are any parameters that are not being used. @@ -676,11 +769,13 @@ To reduce false positives it ignores: - functions in test files - functions with empty bodies or those with just a return stmt +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedparams) + **Disabled by default. Enable it by setting `"analyses": {"unusedparams": true}`.** ## **unusedresult** -check for unused results of calls to some functions +unusedresult: check for unused results of calls to some functions Some functions like fmt.Errorf return a result and have no side effects, so it is always a mistake to discard the result. Other @@ -690,11 +785,13 @@ functions like these when the result of the call is ignored. The set of functions may be controlled using flags. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unusedresult) + **Enabled by default.** ## **unusedwrite** -checks for unused writes +unusedwrite: checks for unused writes The analyzer reports instances of writes to struct fields and arrays that are never read. Specifically, when a struct object @@ -720,93 +817,109 @@ Another example is about non-pointer receiver: t.x = i // unused write to field x } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unusedwrite) + **Disabled by default. Enable it by setting `"analyses": {"unusedwrite": true}`.** ## **useany** -check for constraints that could be simplified to "any" +useany: check for constraints that could be simplified to "any" + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/useany) **Disabled by default. Enable it by setting `"analyses": {"useany": true}`.** ## **fillreturns** -suggest fixes for errors due to an incorrect number of return values +fillreturns: suggest fixes for errors due to an incorrect number of return values This checker provides suggested fixes for type errors of the type "wrong number of return values (want %d, got %d)". For example: + func m() (int, string, *bool, error) { return } + will turn into + func m() (int, string, *bool, error) { return 0, "", nil, nil } This functionality is similar to https://github.com/sqs/goreturns. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns) **Enabled by default.** ## **nonewvars** -suggested fixes for "no new vars on left side of :=" +nonewvars: suggested fixes for "no new vars on left side of :=" This checker provides suggested fixes for type errors of the type "no new vars on left side of :=". For example: + z := 1 z := 2 + will turn into + z := 1 z = 2 +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/nonewvars) **Enabled by default.** ## **noresultvalues** -suggested fixes for unexpected return values +noresultvalues: suggested fixes for unexpected return values This checker provides suggested fixes for type errors of the type "no result values expected" or "too many return values". For example: + func z() { return nil } + will turn into + func z() { return } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/noresultvars) **Enabled by default.** ## **undeclaredname** -suggested fixes for "undeclared name: <>" +undeclaredname: suggested fixes for "undeclared name: <>" This checker provides suggested fixes for type errors of the type "undeclared name: <>". It will either insert a new statement, such as: -"<> := " + <> := or a new function declaration, such as: -func <>(inferred parameters) { - panic("implement me!") -} + func <>(inferred parameters) { + panic("implement me!") + } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/undeclaredname) **Enabled by default.** ## **unusedvariable** -check for unused variables - -The unusedvariable analyzer suggests fixes for unused variables errors. +unusedvariable: check for unused variables and suggest fixes +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedvariable) **Disabled by default. Enable it by setting `"analyses": {"unusedvariable": true}`.** ## **fillstruct** -note incomplete struct initializations +fillstruct: note incomplete struct initializations This analyzer provides diagnostics for any struct literals that do not have any fields initialized. Because the suggested fix for this analysis is @@ -814,11 +927,13 @@ expensive to compute, callers should compute it separately, using the SuggestedFix function below. +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillstruct) + **Enabled by default.** ## **infertypeargs** -check for unnecessary type arguments in call expressions +infertypeargs: check for unnecessary type arguments in call expressions Explicit type arguments may be omitted from call expressions if they can be inferred from function arguments, or from other type arguments: @@ -830,14 +945,43 @@ inferred from function arguments, or from other type arguments: } +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs) + **Enabled by default.** ## **stubmethods** -stub methods analyzer +stubmethods: detect missing methods and fix with stub implementations -This analyzer generates method stubs for concrete types -in order to implement a target interface +This analyzer detects type-checking errors due to missing methods +in assignments from concrete types to interface types, and offers +a suggested fix that will create a set of stub methods so that +the concrete type satisfies the interface. + +For example, this function will not compile because the value +NegativeErr{} does not implement the "error" interface: + + func sqrt(x float64) (float64, error) { + if x < 0 { + return 0, NegativeErr{} // error: missing method + } + ... + } + + type NegativeErr struct{} + +This analyzer will suggest a fix to declare this method: + + // Error implements error.Error. + func (NegativeErr) Error() string { + panic("unimplemented") + } + +(At least, it appears to behave that way, but technically it +doesn't use the SuggestedFix mechanism and the stub is created by +logic in gopls's source.stub function.) + +[Full documentation](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/stubmethods) **Enabled by default.** diff --git a/gopls/doc/generate.go b/gopls/doc/generate.go index 20fa51fdd..ee5c52b07 100644 --- a/gopls/doc/generate.go +++ b/gopls/doc/generate.go @@ -748,7 +748,10 @@ func rewriteAnalyzers(doc []byte, api *settings.APIJSON) ([]byte, error) { section := bytes.NewBuffer(nil) for _, analyzer := range api.Analyzers { fmt.Fprintf(section, "## **%v**\n\n", analyzer.Name) - fmt.Fprintf(section, "%s\n\n", analyzer.Doc) + fmt.Fprintf(section, "%s: %s\n\n", analyzer.Name, analyzer.Doc) + if analyzer.URL != "" { + fmt.Fprintf(section, "[Full documentation](%s)\n\n", analyzer.URL) + } switch analyzer.Default { case true: fmt.Fprintf(section, "**Enabled by default.**\n\n") diff --git a/gopls/internal/analysis/deprecated/deprecated.go b/gopls/internal/analysis/deprecated/deprecated.go index 5f7354e4f..a4c531fad 100644 --- a/gopls/internal/analysis/deprecated/deprecated.go +++ b/gopls/internal/analysis/deprecated/deprecated.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package deprecated defines an Analyzer that marks deprecated symbols and package imports. package deprecated import ( @@ -14,27 +13,26 @@ import ( "strconv" "strings" + _ "embed" + "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/analysisinternal" "golang.org/x/tools/internal/typeparams" ) -// TODO(hyangah): use analysisutil.MustExtractDoc. -var doc = `check for use of deprecated identifiers - -The deprecated analyzer looks for deprecated symbols and package imports. - -See https://go.dev/wiki/Deprecated to learn about Go's convention -for documenting and signaling deprecated identifiers.` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "deprecated", - Doc: doc, + Doc: analysisinternal.MustExtractDoc(doc, "deprecated"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: checkDeprecated, FactTypes: []analysis.Fact{(*deprecationFact)(nil)}, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/deprecated", } // checkDeprecated is a simplified copy of staticcheck.CheckDeprecated. diff --git a/gopls/internal/analysis/deprecated/doc.go b/gopls/internal/analysis/deprecated/doc.go new file mode 100644 index 000000000..0d96b86b3 --- /dev/null +++ b/gopls/internal/analysis/deprecated/doc.go @@ -0,0 +1,16 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package deprecated defines an Analyzer that marks deprecated symbols and package imports. +// +// # Analyzer deprecated +// +// deprecated: check for use of deprecated identifiers +// +// The deprecated analyzer looks for deprecated symbols and package +// imports. +// +// See https://go.dev/wiki/Deprecated to learn about Go's convention +// for documenting and signaling deprecated identifiers. +package deprecated diff --git a/gopls/internal/analysis/embeddirective/doc.go b/gopls/internal/analysis/embeddirective/doc.go new file mode 100644 index 000000000..f8cc69fda --- /dev/null +++ b/gopls/internal/analysis/embeddirective/doc.go @@ -0,0 +1,18 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package embeddirective defines an Analyzer that validates //go:embed directives. +// The analyzer defers fixes to its parent source.Analyzer. +// +// # Analyzer embed +// +// embed: check //go:embed directive usage +// +// This analyzer checks that the embed package is imported if //go:embed +// directives are present, providing a suggested fix to add the import if +// it is missing. +// +// This analyzer also checks that //go:embed directives precede the +// declaration of a single variable. +package embeddirective diff --git a/gopls/internal/analysis/embeddirective/embeddirective.go b/gopls/internal/analysis/embeddirective/embeddirective.go index 33af72b9f..20d3cbff5 100644 --- a/gopls/internal/analysis/embeddirective/embeddirective.go +++ b/gopls/internal/analysis/embeddirective/embeddirective.go @@ -2,34 +2,28 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package embeddirective defines an Analyzer that validates //go:embed directives. -// The analyzer defers fixes to its parent source.Analyzer. package embeddirective import ( + _ "embed" "go/ast" "go/token" "go/types" "strings" "golang.org/x/tools/go/analysis" + "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `check //go:embed directive usage - -This analyzer checks that the embed package is imported if //go:embed -directives are present, providing a suggested fix to add the import if -it is missing. - -This analyzer also checks that //go:embed directives precede the -declaration of a single variable.` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "embed", - Doc: Doc, - Requires: []*analysis.Analyzer{}, + Doc: analysisinternal.MustExtractDoc(doc, "embed"), Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/embeddirective", } // source.fixedByImportingEmbed relies on this message to filter diff --git a/gopls/internal/analysis/fillreturns/doc.go b/gopls/internal/analysis/fillreturns/doc.go new file mode 100644 index 000000000..584aec47d --- /dev/null +++ b/gopls/internal/analysis/fillreturns/doc.go @@ -0,0 +1,27 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package fillreturns defines an Analyzer that will attempt to +// automatically fill in a return statement that has missing +// values with zero value elements. +// +// # Analyzer fillreturns +// +// fillreturns: suggest fixes for errors due to an incorrect number of return values +// +// This checker provides suggested fixes for type errors of the +// type "wrong number of return values (want %d, got %d)". For example: +// +// func m() (int, string, *bool, error) { +// return +// } +// +// will turn into +// +// func m() (int, string, *bool, error) { +// return 0, "", nil, nil +// } +// +// This functionality is similar to https://github.com/sqs/goreturns. +package fillreturns diff --git a/gopls/internal/analysis/fillreturns/fillreturns.go b/gopls/internal/analysis/fillreturns/fillreturns.go index c8146df2d..fb70c541e 100644 --- a/gopls/internal/analysis/fillreturns/fillreturns.go +++ b/gopls/internal/analysis/fillreturns/fillreturns.go @@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package fillreturns defines an Analyzer that will attempt to -// automatically fill in a return statement that has missing -// values with zero value elements. package fillreturns import ( "bytes" + _ "embed" "fmt" "go/ast" "go/format" @@ -23,27 +21,15 @@ import ( "golang.org/x/tools/internal/typeparams" ) -const Doc = `suggest fixes for errors due to an incorrect number of return values - -This checker provides suggested fixes for type errors of the -type "wrong number of return values (want %d, got %d)". For example: - func m() (int, string, *bool, error) { - return - } -will turn into - func m() (int, string, *bool, error) { - return 0, "", nil, nil - } - -This functionality is similar to https://github.com/sqs/goreturns. -` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "fillreturns", - Doc: Doc, - Requires: []*analysis.Analyzer{}, + Doc: analysisinternal.MustExtractDoc(doc, "fillreturns"), Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns", } func run(pass *analysis.Pass) (interface{}, error) { diff --git a/gopls/internal/analysis/fillstruct/fillstruct.go b/gopls/internal/analysis/fillstruct/fillstruct.go index 8b9a41491..1230a87ff 100644 --- a/gopls/internal/analysis/fillstruct/fillstruct.go +++ b/gopls/internal/analysis/fillstruct/fillstruct.go @@ -45,6 +45,7 @@ var Analyzer = &analysis.Analyzer{ Doc: Doc, Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillstruct", RunDespiteErrors: true, } diff --git a/gopls/internal/analysis/infertypeargs/infertypeargs.go b/gopls/internal/analysis/infertypeargs/infertypeargs.go index 9cc9cb9f0..2c3fdd31a 100644 --- a/gopls/internal/analysis/infertypeargs/infertypeargs.go +++ b/gopls/internal/analysis/infertypeargs/infertypeargs.go @@ -31,6 +31,7 @@ var Analyzer = &analysis.Analyzer{ Doc: Doc, Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs", } // TODO(rfindley): remove this thin wrapper around the infertypeargs refactoring, diff --git a/gopls/internal/analysis/nonewvars/doc.go b/gopls/internal/analysis/nonewvars/doc.go new file mode 100644 index 000000000..b0bef847e --- /dev/null +++ b/gopls/internal/analysis/nonewvars/doc.go @@ -0,0 +1,22 @@ +// Copyright 2020 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package nonewvars defines an Analyzer that applies suggested fixes +// to errors of the type "no new variables on left side of :=". +// +// # Analyzer nonewvars +// +// nonewvars: suggested fixes for "no new vars on left side of :=" +// +// This checker provides suggested fixes for type errors of the +// type "no new vars on left side of :=". For example: +// +// z := 1 +// z := 2 +// +// will turn into +// +// z := 1 +// z = 2 +package nonewvars diff --git a/gopls/internal/analysis/nonewvars/nonewvars.go b/gopls/internal/analysis/nonewvars/nonewvars.go index 6937b36d1..b9c9b4d6f 100644 --- a/gopls/internal/analysis/nonewvars/nonewvars.go +++ b/gopls/internal/analysis/nonewvars/nonewvars.go @@ -8,6 +8,7 @@ package nonewvars import ( "bytes" + _ "embed" "go/ast" "go/format" "go/token" @@ -18,23 +19,16 @@ import ( "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `suggested fixes for "no new vars on left side of :=" - -This checker provides suggested fixes for type errors of the -type "no new vars on left side of :=". For example: - z := 1 - z := 2 -will turn into - z := 1 - z = 2 -` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "nonewvars", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "nonewvars"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/nonewvars", } func run(pass *analysis.Pass) (interface{}, error) { diff --git a/gopls/internal/analysis/noresultvalues/doc.go b/gopls/internal/analysis/noresultvalues/doc.go new file mode 100644 index 000000000..87df2093e --- /dev/null +++ b/gopls/internal/analysis/noresultvalues/doc.go @@ -0,0 +1,21 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package noresultvalues defines an Analyzer that applies suggested fixes +// to errors of the type "no result values expected". +// +// # Analyzer noresultvalues +// +// noresultvalues: suggested fixes for unexpected return values +// +// This checker provides suggested fixes for type errors of the +// type "no result values expected" or "too many return values". +// For example: +// +// func z() { return nil } +// +// will turn into +// +// func z() { return } +package noresultvalues diff --git a/gopls/internal/analysis/noresultvalues/noresultvalues.go b/gopls/internal/analysis/noresultvalues/noresultvalues.go index 41952a547..7e2e3d4f6 100644 --- a/gopls/internal/analysis/noresultvalues/noresultvalues.go +++ b/gopls/internal/analysis/noresultvalues/noresultvalues.go @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package noresultvalues defines an Analyzer that applies suggested fixes -// to errors of the type "no result values expected". package noresultvalues import ( @@ -12,28 +10,24 @@ import ( "go/format" "strings" + _ "embed" + "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `suggested fixes for unexpected return values - -This checker provides suggested fixes for type errors of the -type "no result values expected" or "too many return values". -For example: - func z() { return nil } -will turn into - func z() { return } -` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "noresultvalues", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "noresultvalues"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/noresultvars", } func run(pass *analysis.Pass) (interface{}, error) { diff --git a/gopls/internal/analysis/simplifycompositelit/doc.go b/gopls/internal/analysis/simplifycompositelit/doc.go new file mode 100644 index 000000000..fe4059674 --- /dev/null +++ b/gopls/internal/analysis/simplifycompositelit/doc.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package simplifycompositelit defines an Analyzer that simplifies composite literals. +// https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go +// https://golang.org/cmd/gofmt/#hdr-The_simplify_command +// +// # Analyzer simplifycompositelit +// +// simplifycompositelit: check for composite literal simplifications +// +// An array, slice, or map composite literal of the form: +// +// []T{T{}, T{}} +// +// will be simplified to: +// +// []T{{}, {}} +// +// This is one of the simplifications that "gofmt -s" applies. +package simplifycompositelit diff --git a/gopls/internal/analysis/simplifycompositelit/simplifycompositelit.go b/gopls/internal/analysis/simplifycompositelit/simplifycompositelit.go index c91fc7577..c651206b0 100644 --- a/gopls/internal/analysis/simplifycompositelit/simplifycompositelit.go +++ b/gopls/internal/analysis/simplifycompositelit/simplifycompositelit.go @@ -9,6 +9,7 @@ package simplifycompositelit import ( "bytes" + _ "embed" "fmt" "go/ast" "go/printer" @@ -18,22 +19,18 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `check for composite literal simplifications - -An array, slice, or map composite literal of the form: - []T{T{}, T{}} -will be simplified to: - []T{{}, {}} - -This is one of the simplifications that "gofmt -s" applies.` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "simplifycompositelit", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "simplifycompositelit"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifycompositelit", } func run(pass *analysis.Pass) (interface{}, error) { diff --git a/gopls/internal/analysis/simplifyrange/doc.go b/gopls/internal/analysis/simplifyrange/doc.go new file mode 100644 index 000000000..f55ed56b3 --- /dev/null +++ b/gopls/internal/analysis/simplifyrange/doc.go @@ -0,0 +1,30 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package simplifyrange defines an Analyzer that simplifies range statements. +// https://golang.org/cmd/gofmt/#hdr-The_simplify_command +// https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go +// +// # Analyzer simplifyrange +// +// simplifyrange: check for range statement simplifications +// +// A range of the form: +// +// for x, _ = range v {...} +// +// will be simplified to: +// +// for x = range v {...} +// +// A range of the form: +// +// for _ = range v {...} +// +// will be simplified to: +// +// for range v {...} +// +// This is one of the simplifications that "gofmt -s" applies. +package simplifyrange diff --git a/gopls/internal/analysis/simplifyrange/simplifyrange.go b/gopls/internal/analysis/simplifyrange/simplifyrange.go index c9cb38798..364728d4c 100644 --- a/gopls/internal/analysis/simplifyrange/simplifyrange.go +++ b/gopls/internal/analysis/simplifyrange/simplifyrange.go @@ -2,13 +2,11 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package simplifyrange defines an Analyzer that simplifies range statements. -// https://golang.org/cmd/gofmt/#hdr-The_simplify_command -// https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go package simplifyrange import ( "bytes" + _ "embed" "go/ast" "go/printer" "go/token" @@ -16,27 +14,18 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `check for range statement simplifications - -A range of the form: - for x, _ = range v {...} -will be simplified to: - for x = range v {...} - -A range of the form: - for _ = range v {...} -will be simplified to: - for range v {...} - -This is one of the simplifications that "gofmt -s" applies.` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "simplifyrange", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "simplifyrange"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyrange", } func run(pass *analysis.Pass) (interface{}, error) { diff --git a/gopls/internal/analysis/simplifyslice/doc.go b/gopls/internal/analysis/simplifyslice/doc.go new file mode 100644 index 000000000..2fb4c4610 --- /dev/null +++ b/gopls/internal/analysis/simplifyslice/doc.go @@ -0,0 +1,22 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package simplifyslice defines an Analyzer that simplifies slice statements. +// https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go +// https://golang.org/cmd/gofmt/#hdr-The_simplify_command +// +// # Analyzer simplifyslice +// +// simplifyslice: check for slice simplifications +// +// A slice expression of the form: +// +// s[a:len(s)] +// +// will be simplified to: +// +// s[a:] +// +// This is one of the simplifications that "gofmt -s" applies. +package simplifyslice diff --git a/gopls/internal/analysis/simplifyslice/simplifyslice.go b/gopls/internal/analysis/simplifyslice/simplifyslice.go index da1728e6f..0c7cc3ff2 100644 --- a/gopls/internal/analysis/simplifyslice/simplifyslice.go +++ b/gopls/internal/analysis/simplifyslice/simplifyslice.go @@ -1,14 +1,12 @@ -// Copyright 2020 The Go Authors. All rights reserved. +// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package simplifyslice defines an Analyzer that simplifies slice statements. -// https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go -// https://golang.org/cmd/gofmt/#hdr-The_simplify_command package simplifyslice import ( "bytes" + _ "embed" "fmt" "go/ast" "go/printer" @@ -16,22 +14,18 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `check for slice simplifications - -A slice expression of the form: - s[a:len(s)] -will be simplified to: - s[a:] - -This is one of the simplifications that "gofmt -s" applies.` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "simplifyslice", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "simplifyslice"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyslice", } // Note: We could also simplify slice expressions of the form s[0:b] to s[:b] diff --git a/gopls/internal/analysis/stubmethods/doc.go b/gopls/internal/analysis/stubmethods/doc.go new file mode 100644 index 000000000..5b5957d2c --- /dev/null +++ b/gopls/internal/analysis/stubmethods/doc.go @@ -0,0 +1,38 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package stubmethods defines an analyzer for missing interface methods. +// +// # Analyzer stubmethods +// +// stubmethods: detect missing methods and fix with stub implementations +// +// This analyzer detects type-checking errors due to missing methods +// in assignments from concrete types to interface types, and offers +// a suggested fix that will create a set of stub methods so that +// the concrete type satisfies the interface. +// +// For example, this function will not compile because the value +// NegativeErr{} does not implement the "error" interface: +// +// func sqrt(x float64) (float64, error) { +// if x < 0 { +// return 0, NegativeErr{} // error: missing method +// } +// ... +// } +// +// type NegativeErr struct{} +// +// This analyzer will suggest a fix to declare this method: +// +// // Error implements error.Error. +// func (NegativeErr) Error() string { +// panic("unimplemented") +// } +// +// (At least, it appears to behave that way, but technically it +// doesn't use the SuggestedFix mechanism and the stub is created by +// logic in gopls's source.stub function.) +package stubmethods diff --git a/gopls/internal/analysis/stubmethods/stubmethods.go b/gopls/internal/analysis/stubmethods/stubmethods.go index 409134471..690cea91b 100644 --- a/gopls/internal/analysis/stubmethods/stubmethods.go +++ b/gopls/internal/analysis/stubmethods/stubmethods.go @@ -6,6 +6,7 @@ package stubmethods import ( "bytes" + _ "embed" "fmt" "go/ast" "go/format" @@ -20,16 +21,15 @@ import ( "golang.org/x/tools/internal/typesinternal" ) -const Doc = `stub methods analyzer - -This analyzer generates method stubs for concrete types -in order to implement a target interface` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "stubmethods", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "stubmethods"), Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/stubmethods", } // TODO(rfindley): remove this thin wrapper around the stubmethods refactoring, diff --git a/gopls/internal/analysis/undeclaredname/doc.go b/gopls/internal/analysis/undeclaredname/doc.go new file mode 100644 index 000000000..02989c9d7 --- /dev/null +++ b/gopls/internal/analysis/undeclaredname/doc.go @@ -0,0 +1,23 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package undeclaredname defines an Analyzer that applies suggested fixes +// to errors of the type "undeclared name: %s". +// +// # Analyzer undeclaredname +// +// undeclaredname: suggested fixes for "undeclared name: <>" +// +// This checker provides suggested fixes for type errors of the +// type "undeclared name: <>". It will either insert a new statement, +// such as: +// +// <> := +// +// or a new function declaration, such as: +// +// func <>(inferred parameters) { +// panic("implement me!") +// } +package undeclaredname diff --git a/gopls/internal/analysis/undeclaredname/undeclared.go b/gopls/internal/analysis/undeclaredname/undeclared.go index fc00d4b2b..147831c07 100644 --- a/gopls/internal/analysis/undeclaredname/undeclared.go +++ b/gopls/internal/analysis/undeclaredname/undeclared.go @@ -2,12 +2,11 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package undeclaredname defines an Analyzer that applies suggested fixes -// to errors of the type "undeclared name: %s". package undeclaredname import ( "bytes" + _ "embed" "fmt" "go/ast" "go/format" @@ -22,27 +21,16 @@ import ( "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `suggested fixes for "undeclared name: <>" - -This checker provides suggested fixes for type errors of the -type "undeclared name: <>". It will either insert a new statement, -such as: - -"<> := " - -or a new function declaration, such as: - -func <>(inferred parameters) { - panic("implement me!") -} -` +//go:embed doc.go +var doc string var Analyzer = &analysis.Analyzer{ Name: "undeclaredname", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "undeclaredname"), Requires: []*analysis.Analyzer{}, Run: run, RunDespiteErrors: true, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/undeclaredname", } // The prefix for this error message changed in Go 1.20. diff --git a/gopls/internal/analysis/unusedparams/doc.go b/gopls/internal/analysis/unusedparams/doc.go new file mode 100644 index 000000000..2bf9fa96c --- /dev/null +++ b/gopls/internal/analysis/unusedparams/doc.go @@ -0,0 +1,20 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package unusedparams defines an analyzer that checks for unused +// parameters of functions. +// +// # Analyzer unusedparams +// +// unusedparams: check for unused parameters of functions +// +// The unusedparams analyzer checks functions to see if there are +// any parameters that are not being used. +// +// To reduce false positives it ignores: +// - methods +// - parameters that do not have a name or have the name '_' (the blank identifier) +// - functions in test files +// - functions with empty bodies or those with just a return stmt +package unusedparams diff --git a/gopls/internal/analysis/unusedparams/unusedparams.go b/gopls/internal/analysis/unusedparams/unusedparams.go index 64702b2f0..076acf79d 100644 --- a/gopls/internal/analysis/unusedparams/unusedparams.go +++ b/gopls/internal/analysis/unusedparams/unusedparams.go @@ -2,11 +2,10 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package unusedparams defines an analyzer that checks for unused -// parameters of functions. package unusedparams import ( + _ "embed" "fmt" "go/ast" "go/types" @@ -15,25 +14,19 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" + "golang.org/x/tools/internal/analysisinternal" ) -const Doc = `check for unused parameters of functions - -The unusedparams analyzer checks functions to see if there are -any parameters that are not being used. - -To reduce false positives it ignores: -- methods -- parameters that do not have a name or have the name '_' (the blank identifier) -- functions in test files -- functions with empty bodies or those with just a return stmt` +//go:embed doc.go +var doc string var ( Analyzer = &analysis.Analyzer{ Name: "unusedparams", - Doc: Doc, + Doc: analysisinternal.MustExtractDoc(doc, "unusedparams"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedparams", } inspectLits bool inspectWrappers bool diff --git a/gopls/internal/analysis/unusedvariable/unusedvariable.go b/gopls/internal/analysis/unusedvariable/unusedvariable.go index 904016be7..e85b9dc84 100644 --- a/gopls/internal/analysis/unusedvariable/unusedvariable.go +++ b/gopls/internal/analysis/unusedvariable/unusedvariable.go @@ -18,10 +18,7 @@ import ( "golang.org/x/tools/go/ast/astutil" ) -const Doc = `check for unused variables - -The unusedvariable analyzer suggests fixes for unused variables errors. -` +const Doc = `check for unused variables and suggest fixes` var Analyzer = &analysis.Analyzer{ Name: "unusedvariable", @@ -29,6 +26,7 @@ var Analyzer = &analysis.Analyzer{ Requires: []*analysis.Analyzer{}, Run: run, RunDespiteErrors: true, // an unusedvariable diagnostic is a compile error + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedvariable", } // The suffix for this error message changed in Go 1.20. diff --git a/gopls/internal/analysis/useany/useany.go b/gopls/internal/analysis/useany/useany.go index 73e2f7633..799b35fd5 100644 --- a/gopls/internal/analysis/useany/useany.go +++ b/gopls/internal/analysis/useany/useany.go @@ -25,16 +25,13 @@ var Analyzer = &analysis.Analyzer{ Doc: Doc, Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/useany", } func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) universeAny := types.Universe.Lookup("any") - if universeAny == nil { - // Go <= 1.17. Nothing to check. - return nil, nil - } nodeFilter := []ast.Node{ (*ast.TypeSpec)(nil), diff --git a/gopls/internal/settings/api_json.go b/gopls/internal/settings/api_json.go index 48006be55..1ecbe61ed 100644 --- a/gopls/internal/settings/api_json.go +++ b/gopls/internal/settings/api_json.go @@ -287,7 +287,7 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "\"deprecated\"", - Doc: "check for use of deprecated identifiers\n\nThe deprecated analyzer looks for deprecated symbols and package imports.\n\nSee https://go.dev/wiki/Deprecated to learn about Go's convention\nfor documenting and signaling deprecated identifiers.", + Doc: "check for use of deprecated identifiers\n\nThe deprecated analyzer looks for deprecated symbols and package\nimports.\n\nSee https://go.dev/wiki/Deprecated to learn about Go's convention\nfor documenting and signaling deprecated identifiers.", Default: "true", }, { @@ -357,17 +357,17 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "\"simplifycompositelit\"", - Doc: "check for composite literal simplifications\n\nAn array, slice, or map composite literal of the form:\n\t[]T{T{}, T{}}\nwill be simplified to:\n\t[]T{{}, {}}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for composite literal simplifications\n\nAn array, slice, or map composite literal of the form:\n\n\t[]T{T{}, T{}}\n\nwill be simplified to:\n\n\t[]T{{}, {}}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", Default: "true", }, { Name: "\"simplifyrange\"", - Doc: "check for range statement simplifications\n\nA range of the form:\n\tfor x, _ = range v {...}\nwill be simplified to:\n\tfor x = range v {...}\n\nA range of the form:\n\tfor _ = range v {...}\nwill be simplified to:\n\tfor range v {...}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for range statement simplifications\n\nA range of the form:\n\n\tfor x, _ = range v {...}\n\nwill be simplified to:\n\n\tfor x = range v {...}\n\nA range of the form:\n\n\tfor _ = range v {...}\n\nwill be simplified to:\n\n\tfor range v {...}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", Default: "true", }, { Name: "\"simplifyslice\"", - Doc: "check for slice simplifications\n\nA slice expression of the form:\n\ts[a:len(s)]\nwill be simplified to:\n\ts[a:]\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for slice simplifications\n\nA slice expression of the form:\n\n\ts[a:len(s)]\n\nwill be simplified to:\n\n\ts[a:]\n\nThis is one of the simplifications that \"gofmt -s\" applies.", Default: "true", }, { @@ -447,27 +447,27 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "\"fillreturns\"", - Doc: "suggest fixes for errors due to an incorrect number of return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"wrong number of return values (want %d, got %d)\". For example:\n\tfunc m() (int, string, *bool, error) {\n\t\treturn\n\t}\nwill turn into\n\tfunc m() (int, string, *bool, error) {\n\t\treturn 0, \"\", nil, nil\n\t}\n\nThis functionality is similar to https://github.com/sqs/goreturns.\n", + Doc: "suggest fixes for errors due to an incorrect number of return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"wrong number of return values (want %d, got %d)\". For example:\n\n\tfunc m() (int, string, *bool, error) {\n\t\treturn\n\t}\n\nwill turn into\n\n\tfunc m() (int, string, *bool, error) {\n\t\treturn 0, \"\", nil, nil\n\t}\n\nThis functionality is similar to https://github.com/sqs/goreturns.", Default: "true", }, { Name: "\"nonewvars\"", - Doc: "suggested fixes for \"no new vars on left side of :=\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"no new vars on left side of :=\". For example:\n\tz := 1\n\tz := 2\nwill turn into\n\tz := 1\n\tz = 2\n", + Doc: "suggested fixes for \"no new vars on left side of :=\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"no new vars on left side of :=\". For example:\n\n\tz := 1\n\tz := 2\n\nwill turn into\n\n\tz := 1\n\tz = 2", Default: "true", }, { Name: "\"noresultvalues\"", - Doc: "suggested fixes for unexpected return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"no result values expected\" or \"too many return values\".\nFor example:\n\tfunc z() { return nil }\nwill turn into\n\tfunc z() { return }\n", + Doc: "suggested fixes for unexpected return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"no result values expected\" or \"too many return values\".\nFor example:\n\n\tfunc z() { return nil }\n\nwill turn into\n\n\tfunc z() { return }", Default: "true", }, { Name: "\"undeclaredname\"", - Doc: "suggested fixes for \"undeclared name: <>\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"undeclared name: <>\". It will either insert a new statement,\nsuch as:\n\n\"<> := \"\n\nor a new function declaration, such as:\n\nfunc <>(inferred parameters) {\n\tpanic(\"implement me!\")\n}\n", + Doc: "suggested fixes for \"undeclared name: <>\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"undeclared name: <>\". It will either insert a new statement,\nsuch as:\n\n\t<> :=\n\nor a new function declaration, such as:\n\n\tfunc <>(inferred parameters) {\n\t\tpanic(\"implement me!\")\n\t}", Default: "true", }, { Name: "\"unusedvariable\"", - Doc: "check for unused variables\n\nThe unusedvariable analyzer suggests fixes for unused variables errors.\n", + Doc: "check for unused variables and suggest fixes", Default: "false", }, { @@ -482,7 +482,7 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "\"stubmethods\"", - Doc: "stub methods analyzer\n\nThis analyzer generates method stubs for concrete types\nin order to implement a target interface", + Doc: "detect missing methods and fix with stub implementations\n\nThis analyzer detects type-checking errors due to missing methods\nin assignments from concrete types to interface types, and offers\na suggested fix that will create a set of stub methods so that\nthe concrete type satisfies the interface.\n\nFor example, this function will not compile because the value\nNegativeErr{} does not implement the \"error\" interface:\n\n\tfunc sqrt(x float64) (float64, error) {\n\t\tif x < 0 {\n\t\t\treturn 0, NegativeErr{} // error: missing method\n\t\t}\n\t\t...\n\t}\n\n\ttype NegativeErr struct{}\n\nThis analyzer will suggest a fix to declare this method:\n\n\t// Error implements error.Error.\n\tfunc (NegativeErr) Error() string {\n\t\tpanic(\"unimplemented\")\n\t}\n\n(At least, it appears to behave that way, but technically it\ndoesn't use the SuggestedFix mechanism and the stub is created by\nlogic in gopls's source.stub function.)", Default: "true", }, }, @@ -1037,7 +1037,8 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "deprecated", - Doc: "check for use of deprecated identifiers\n\nThe deprecated analyzer looks for deprecated symbols and package imports.\n\nSee https://go.dev/wiki/Deprecated to learn about Go's convention\nfor documenting and signaling deprecated identifiers.", + Doc: "check for use of deprecated identifiers\n\nThe deprecated analyzer looks for deprecated symbols and package\nimports.\n\nSee https://go.dev/wiki/Deprecated to learn about Go's convention\nfor documenting and signaling deprecated identifiers.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/deprecated", Default: true, }, { @@ -1049,6 +1050,7 @@ var GeneratedAPIJSON = &APIJSON{ { Name: "embed", Doc: "check //go:embed directive usage\n\nThis analyzer checks that the embed package is imported if //go:embed\ndirectives are present, providing a suggested fix to add the import if\nit is missing.\n\nThis analyzer also checks that //go:embed directives precede the\ndeclaration of a single variable.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/embeddirective", Default: true, }, { @@ -1117,17 +1119,20 @@ var GeneratedAPIJSON = &APIJSON{ }, { Name: "simplifycompositelit", - Doc: "check for composite literal simplifications\n\nAn array, slice, or map composite literal of the form:\n\t[]T{T{}, T{}}\nwill be simplified to:\n\t[]T{{}, {}}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for composite literal simplifications\n\nAn array, slice, or map composite literal of the form:\n\n\t[]T{T{}, T{}}\n\nwill be simplified to:\n\n\t[]T{{}, {}}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifycompositelit", Default: true, }, { Name: "simplifyrange", - Doc: "check for range statement simplifications\n\nA range of the form:\n\tfor x, _ = range v {...}\nwill be simplified to:\n\tfor x = range v {...}\n\nA range of the form:\n\tfor _ = range v {...}\nwill be simplified to:\n\tfor range v {...}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for range statement simplifications\n\nA range of the form:\n\n\tfor x, _ = range v {...}\n\nwill be simplified to:\n\n\tfor x = range v {...}\n\nA range of the form:\n\n\tfor _ = range v {...}\n\nwill be simplified to:\n\n\tfor range v {...}\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyrange", Default: true, }, { Name: "simplifyslice", - Doc: "check for slice simplifications\n\nA slice expression of the form:\n\ts[a:len(s)]\nwill be simplified to:\n\ts[a:]\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + Doc: "check for slice simplifications\n\nA slice expression of the form:\n\n\ts[a:len(s)]\n\nwill be simplified to:\n\n\ts[a:]\n\nThis is one of the simplifications that \"gofmt -s\" applies.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyslice", Default: true, }, { @@ -1199,6 +1204,7 @@ var GeneratedAPIJSON = &APIJSON{ { Name: "unusedparams", Doc: "check for unused parameters of functions\n\nThe unusedparams analyzer checks functions to see if there are\nany parameters that are not being used.\n\nTo reduce false positives it ignores:\n- methods\n- parameters that do not have a name or have the name '_' (the blank identifier)\n- functions in test files\n- functions with empty bodies or those with just a return stmt", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedparams", }, { Name: "unusedresult", @@ -1214,44 +1220,53 @@ var GeneratedAPIJSON = &APIJSON{ { Name: "useany", Doc: "check for constraints that could be simplified to \"any\"", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/useany", }, { Name: "fillreturns", - Doc: "suggest fixes for errors due to an incorrect number of return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"wrong number of return values (want %d, got %d)\". For example:\n\tfunc m() (int, string, *bool, error) {\n\t\treturn\n\t}\nwill turn into\n\tfunc m() (int, string, *bool, error) {\n\t\treturn 0, \"\", nil, nil\n\t}\n\nThis functionality is similar to https://github.com/sqs/goreturns.\n", + Doc: "suggest fixes for errors due to an incorrect number of return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"wrong number of return values (want %d, got %d)\". For example:\n\n\tfunc m() (int, string, *bool, error) {\n\t\treturn\n\t}\n\nwill turn into\n\n\tfunc m() (int, string, *bool, error) {\n\t\treturn 0, \"\", nil, nil\n\t}\n\nThis functionality is similar to https://github.com/sqs/goreturns.", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns", Default: true, }, { Name: "nonewvars", - Doc: "suggested fixes for \"no new vars on left side of :=\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"no new vars on left side of :=\". For example:\n\tz := 1\n\tz := 2\nwill turn into\n\tz := 1\n\tz = 2\n", + Doc: "suggested fixes for \"no new vars on left side of :=\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"no new vars on left side of :=\". For example:\n\n\tz := 1\n\tz := 2\n\nwill turn into\n\n\tz := 1\n\tz = 2", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/nonewvars", Default: true, }, { Name: "noresultvalues", - Doc: "suggested fixes for unexpected return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"no result values expected\" or \"too many return values\".\nFor example:\n\tfunc z() { return nil }\nwill turn into\n\tfunc z() { return }\n", + Doc: "suggested fixes for unexpected return values\n\nThis checker provides suggested fixes for type errors of the\ntype \"no result values expected\" or \"too many return values\".\nFor example:\n\n\tfunc z() { return nil }\n\nwill turn into\n\n\tfunc z() { return }", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/noresultvars", Default: true, }, { Name: "undeclaredname", - Doc: "suggested fixes for \"undeclared name: <>\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"undeclared name: <>\". It will either insert a new statement,\nsuch as:\n\n\"<> := \"\n\nor a new function declaration, such as:\n\nfunc <>(inferred parameters) {\n\tpanic(\"implement me!\")\n}\n", + Doc: "suggested fixes for \"undeclared name: <>\"\n\nThis checker provides suggested fixes for type errors of the\ntype \"undeclared name: <>\". It will either insert a new statement,\nsuch as:\n\n\t<> :=\n\nor a new function declaration, such as:\n\n\tfunc <>(inferred parameters) {\n\t\tpanic(\"implement me!\")\n\t}", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/undeclaredname", Default: true, }, { Name: "unusedvariable", - Doc: "check for unused variables\n\nThe unusedvariable analyzer suggests fixes for unused variables errors.\n", + Doc: "check for unused variables and suggest fixes", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/unusedvariable", }, { Name: "fillstruct", Doc: "note incomplete struct initializations\n\nThis analyzer provides diagnostics for any struct literals that do not have\nany fields initialized. Because the suggested fix for this analysis is\nexpensive to compute, callers should compute it separately, using the\nSuggestedFix function below.\n", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillstruct", Default: true, }, { Name: "infertypeargs", Doc: "check for unnecessary type arguments in call expressions\n\nExplicit type arguments may be omitted from call expressions if they can be\ninferred from function arguments, or from other type arguments:\n\n\tfunc f[T any](T) {}\n\t\n\tfunc _() {\n\t\tf[string](\"foo\") // string could be inferred\n\t}\n", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs", Default: true, }, { Name: "stubmethods", - Doc: "stub methods analyzer\n\nThis analyzer generates method stubs for concrete types\nin order to implement a target interface", + Doc: "detect missing methods and fix with stub implementations\n\nThis analyzer detects type-checking errors due to missing methods\nin assignments from concrete types to interface types, and offers\na suggested fix that will create a set of stub methods so that\nthe concrete type satisfies the interface.\n\nFor example, this function will not compile because the value\nNegativeErr{} does not implement the \"error\" interface:\n\n\tfunc sqrt(x float64) (float64, error) {\n\t\tif x < 0 {\n\t\t\treturn 0, NegativeErr{} // error: missing method\n\t\t}\n\t\t...\n\t}\n\n\ttype NegativeErr struct{}\n\nThis analyzer will suggest a fix to declare this method:\n\n\t// Error implements error.Error.\n\tfunc (NegativeErr) Error() string {\n\t\tpanic(\"unimplemented\")\n\t}\n\n(At least, it appears to behave that way, but technically it\ndoesn't use the SuggestedFix mechanism and the stub is created by\nlogic in gopls's source.stub function.)", + URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/stubmethods", Default: true, }, }, diff --git a/go/analysis/passes/internal/analysisutil/extractdoc.go b/internal/analysisinternal/extractdoc.go similarity index 99% rename from go/analysis/passes/internal/analysisutil/extractdoc.go rename to internal/analysisinternal/extractdoc.go index 0e175ca06..39507723d 100644 --- a/go/analysis/passes/internal/analysisutil/extractdoc.go +++ b/internal/analysisinternal/extractdoc.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package analysisutil +package analysisinternal import ( "fmt" diff --git a/go/analysis/passes/internal/analysisutil/extractdoc_test.go b/internal/analysisinternal/extractdoc_test.go similarity index 92% rename from go/analysis/passes/internal/analysisutil/extractdoc_test.go rename to internal/analysisinternal/extractdoc_test.go index 8fbf80e26..8c99b11ed 100644 --- a/go/analysis/passes/internal/analysisutil/extractdoc_test.go +++ b/internal/analysisinternal/extractdoc_test.go @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -package analysisutil_test +package analysisinternal_test import ( "testing" - "golang.org/x/tools/go/analysis/passes/internal/analysisutil" + "golang.org/x/tools/internal/analysisinternal" ) func TestExtractDoc(t *testing.T) { @@ -68,7 +68,7 @@ var x = syntax error {multi, "nocolon", "error: 'Analyzer nocolon' heading not followed by 'nocolon: summary...' line"}, } { - got, err := analysisutil.ExtractDoc(test.content, test.name) + got, err := analysisinternal.ExtractDoc(test.content, test.name) if err != nil { got = "error: " + err.Error() }