func Validate(analyzers []*Analyzer) error
Validate reports an error if any of the analyzers are misconfigured. Checks include: that the name is a valid identifier; that the Doc is not empty; that the Run is non-nil; that the Requires graph is acyclic; that analyzer fact types are unique; that each fact type is a pointer.
An Analyzer describes an analysis function and its options.
type Analyzer struct { // The Name of the analyzer must be a valid Go identifier // as it may appear in command-line flags, URLs, and so on. Name string // Doc is the documentation for the analyzer. // The part before the first "\n\n" is the title // (no capital or period, max ~60 letters). Doc string // Flags defines any flags accepted by the analyzer. // The manner in which these flags are exposed to the user // depends on the driver which runs the analyzer. Flags flag.FlagSet // Run applies the analyzer to a package. // It returns an error if the analyzer failed. // // On success, the Run function may return a result // computed by the Analyzer; its type must match ResultType. // The driver makes this result available as an input to // another Analyzer that depends directly on this one (see // Requires) when it analyzes the same package. // // To pass analysis results between packages (and thus // potentially between address spaces), use Facts, which are // serializable. Run func(*Pass) (interface{}, error) // RunDespiteErrors allows the driver to invoke // the Run method of this analyzer even on a // package that contains parse or type errors. // The Pass.TypeErrors field may consequently be non-empty. RunDespiteErrors bool // Requires is a set of analyzers that must run successfully // before this one on a given package. This analyzer may inspect // the outputs produced by each analyzer in Requires. // The graph over analyzers implied by Requires edges must be acyclic. // // Requires establishes a "horizontal" dependency between // analysis passes (different analyzers, same package). Requires []*Analyzer // ResultType is the type of the optional result of the Run function. ResultType reflect.Type // FactTypes indicates that this analyzer imports and exports // Facts of the specified concrete types. // An analyzer that uses facts may assume that its import // dependencies have been similarly analyzed before it runs. // Facts must be pointers. // // FactTypes establishes a "vertical" dependency between // analysis passes (same analyzer, different packages). FactTypes []Fact }
func (a *Analyzer) String() string
type CycleInRequiresGraphError struct { AnalyzerNames map[string]bool }
func (e *CycleInRequiresGraphError) Error() string
A Diagnostic is a message associated with a source location or range.
An Analyzer may return a variety of diagnostics; the optional Category, which should be a constant, may be used to classify them. It is primarily intended to make it easy to look up documentation.
If End is provided, the diagnostic is specified to apply to the range between Pos and End.
type Diagnostic struct { Pos token.Pos End token.Pos // optional Category string // optional Message string // SuggestedFixes contains suggested fixes for a diagnostic which can be used to perform // edits to a file that address the diagnostic. // TODO(matloob): Should multiple SuggestedFixes be allowed for a diagnostic? // Diagnostics should not contain SuggestedFixes that overlap. // Experimental: This API is experimental and may change in the future. SuggestedFixes []SuggestedFix // optional // Experimental: This API is experimental and may change in the future. Related []RelatedInformation // optional }
A Fact is an intermediate fact produced during analysis.
Each fact is associated with a named declaration (a types.Object) or with a package as a whole. A single object or package may have multiple associated facts, but only one of any particular fact type.
A Fact represents a predicate such as "never returns", but does not represent the subject of the predicate such as "function F" or "package P".
Facts may be produced in one analysis pass and consumed by another analysis pass even if these are in different address spaces. If package P imports Q, all facts about Q produced during analysis of that package will be available during later analysis of P. Facts are analogous to type export data in a build system: just as export data enables separate compilation of several passes, facts enable "separate analysis".
Each pass (a, p) starts with the set of facts produced by the same analyzer a applied to the packages directly imported by p. The analysis may add facts to the set, and they may be exported in turn. An analysis's Run function may retrieve facts by calling Pass.Import{Object,Package}Fact and update them using Pass.Export{Object,Package}Fact.
A fact is logically private to its Analysis. To pass values between different analyzers, use the results mechanism; see Analyzer.Requires, Analyzer.ResultType, and Pass.ResultOf.
A Fact type must be a pointer. Facts are encoded and decoded using encoding/gob. A Fact may implement the GobEncoder/GobDecoder interfaces to customize its encoding. Fact encoding should not fail.
A Fact should not be modified once exported.
type Fact interface {
AFact() // dummy method to avoid type errors
}
ObjectFact is an object together with an associated fact. WARNING: This is an experimental API and may change in the future.
type ObjectFact struct { Object types.Object Fact Fact }
PackageFact is a package together with an associated fact. WARNING: This is an experimental API and may change in the future.
type PackageFact struct { Package *types.Package Fact Fact }
A Pass provides information to the Run function that applies a specific analyzer to a single Go package.
It forms the interface between the analysis logic and the driver program, and has both input and an output components.
As in a compiler, one pass may depend on the result computed by another.
The Run function should not call any of the Pass functions concurrently.
type Pass struct { Analyzer *Analyzer // the identity of the current analyzer // syntax and type information Fset *token.FileSet // file position information Files []*ast.File // the abstract syntax tree of each file OtherFiles []string // names of non-Go files of this package IgnoredFiles []string // names of ignored source files in this package Pkg *types.Package // type information about the package TypesInfo *types.Info // type information about the syntax trees TypesSizes types.Sizes // function for computing sizes of types TypeErrors []types.Error // type errors (only if Analyzer.RunDespiteErrors) // Report reports a Diagnostic, a finding about a specific location // in the analyzed source code such as a potential mistake. // It may be called by the Run function. Report func(Diagnostic) // ResultOf provides the inputs to this analysis pass, which are // the corresponding results of its prerequisite analyzers. // The map keys are the elements of Analysis.Required, // and the type of each corresponding value is the required // analysis's ResultType. ResultOf map[*Analyzer]interface{} // ImportObjectFact retrieves a fact associated with obj. // Given a value ptr of type *T, where *T satisfies Fact, // ImportObjectFact copies the value to *ptr. // // ImportObjectFact panics if called after the pass is complete. // ImportObjectFact is not concurrency-safe. ImportObjectFact func(obj types.Object, fact Fact) bool // ImportPackageFact retrieves a fact associated with package pkg, // which must be this package or one of its dependencies. // See comments for ImportObjectFact. ImportPackageFact func(pkg *types.Package, fact Fact) bool // ExportObjectFact associates a fact of type *T with the obj, // replacing any previous fact of that type. // // ExportObjectFact panics if it is called after the pass is // complete, or if obj does not belong to the package being analyzed. // ExportObjectFact is not concurrency-safe. ExportObjectFact func(obj types.Object, fact Fact) // ExportPackageFact associates a fact with the current package. // See comments for ExportObjectFact. ExportPackageFact func(fact Fact) // AllPackageFacts returns a new slice containing all package facts of the analysis's FactTypes // in unspecified order. // WARNING: This is an experimental API and may change in the future. AllPackageFacts func() []PackageFact // AllObjectFacts returns a new slice containing all object facts of the analysis's FactTypes // in unspecified order. // WARNING: This is an experimental API and may change in the future. AllObjectFacts func() []ObjectFact // contains filtered or unexported fields }
func (pass *Pass) ReportRangef(rng Range, format string, args ...interface{})
ReportRangef is a helper function that reports a Diagnostic using the range provided. ast.Node values can be passed in as the range because they satisfy the Range interface.
func (pass *Pass) Reportf(pos token.Pos, format string, args ...interface{})
Reportf is a helper function that reports a Diagnostic using the specified position and formatted error message.
func (pass *Pass) String() string
The Range interface provides a range. It's equivalent to and satisfied by ast.Node.
type Range interface { Pos() token.Pos // position of first character belonging to the node End() token.Pos // position of first character immediately after the node }
RelatedInformation contains information related to a diagnostic. For example, a diagnostic that flags duplicated declarations of a variable may include one RelatedInformation per existing declaration.
type RelatedInformation struct { Pos token.Pos End token.Pos // optional Message string }
A SuggestedFix is a code change associated with a Diagnostic that a user can choose to apply to their code. Usually the SuggestedFix is meant to fix the issue flagged by the diagnostic. TextEdits for a SuggestedFix should not overlap. TextEdits for a SuggestedFix should not contain edits for other packages. Experimental: This API is experimental and may change in the future.
type SuggestedFix struct { // A description for this suggested fix to be shown to a user deciding // whether to accept it. Message string TextEdits []TextEdit }
A TextEdit represents the replacement of the code between Pos and End with the new text. Each TextEdit should apply to a single file. End should not be earlier in the file than Pos. Experimental: This API is experimental and may change in the future.
type TextEdit struct { // For a pure insertion, End can either be set to Pos or token.NoPos. Pos token.Pos End token.Pos NewText []byte }
Name | Synopsis |
---|---|
.. | |
analysistest | Package analysistest provides utilities for testing analyzers. |
multichecker | Package multichecker defines the main function for an analysis driver with several analyzers. |
passes | |
asmdecl | Package asmdecl defines an Analyzer that reports mismatches between assembly files and Go declarations. |
assign | Package assign defines an Analyzer that detects useless assignments. |
atomic | Package atomic defines an Analyzer that checks for common mistakes using the sync/atomic package. |
atomicalign | Package atomicalign defines an Analyzer that checks for non-64-bit-aligned arguments to sync/atomic functions. |
bools | Package bools defines an Analyzer that detects common mistakes involving boolean operators. |
buildssa | Package buildssa defines an Analyzer that constructs the SSA representation of an error-free package and returns the set of all functions within it. |
buildtag | Package buildtag defines an Analyzer that checks build tags. |
cgocall | Package cgocall defines an Analyzer that detects some violations of the cgo pointer passing rules. |
composite | Package composite defines an Analyzer that checks for unkeyed composite literals. |
copylock | Package copylock defines an Analyzer that checks for locks erroneously passed by value. |
ctrlflow | Package ctrlflow is an analysis that provides a syntactic control-flow graph (CFG) for the body of a function. |
deepequalerrors | Package deepequalerrors defines an Analyzer that checks for the use of reflect.DeepEqual with error values. |
errorsas | The errorsas package defines an Analyzer that checks that the second argument to errors.As is a pointer to a type implementing error. |
fieldalignment | Package fieldalignment defines an Analyzer that detects structs that would use less memory if their fields were sorted. |
cmd | |
fieldalignment | |
findcall | Package findcall defines an Analyzer that serves as a trivial example and test of the Analysis API. |
cmd | |
findcall | The findcall command runs the findcall analyzer. |
framepointer | Package framepointer defines an Analyzer that reports assembly code that clobbers the frame pointer before saving it. |
httpresponse | Package httpresponse defines an Analyzer that checks for mistakes using HTTP responses. |
ifaceassert | Package ifaceassert defines an Analyzer that flags impossible interface-interface type assertions. |
cmd | |
ifaceassert | The ifaceassert command runs the ifaceassert analyzer. |
inspect | Package inspect defines an Analyzer that provides an AST inspector (golang.org/x/tools/go/ast/inspector.Inspector) for the syntax trees of a package. |
loopclosure | Package loopclosure defines an Analyzer that checks for references to enclosing loop variables from within nested functions. |
lostcancel | Package lostcancel defines an Analyzer that checks for failure to call a context cancellation function. |
cmd | |
lostcancel | The lostcancel command applies the golang.org/x/tools/go/analysis/passes/lostcancel analysis to the specified packages of Go source code. |
nilfunc | Package nilfunc defines an Analyzer that checks for useless comparisons against nil. |
nilness | Package nilness inspects the control-flow graph of an SSA function and reports errors such as nil pointer dereferences and degenerate nil pointer comparisons. |
cmd | |
nilness | The nilness command applies the golang.org/x/tools/go/analysis/passes/nilness analysis to the specified packages of Go source code. |
pkgfact | The pkgfact package is a demonstration and test of the package fact mechanism. |
printf | Package printf defines an Analyzer that checks consistency of Printf format strings and arguments. |
reflectvaluecompare | Package reflectvaluecompare defines an Analyzer that checks for accidentally using == or reflect.DeepEqual to compare reflect.Value values. |
shadow | Package shadow defines an Analyzer that checks for shadowed variables. |
cmd | |
shadow | The shadow command runs the shadow analyzer. |
shift | Package shift defines an Analyzer that checks for shifts that exceed the width of an integer. |
sigchanyzer | Package sigchanyzer defines an Analyzer that detects misuse of unbuffered signal as argument to signal.Notify. |
sortslice | Package sortslice defines an Analyzer that checks for calls to sort.Slice that do not use a slice type as first argument. |
stdmethods | Package stdmethods defines an Analyzer that checks for misspellings in the signatures of methods similar to well-known interfaces. |
stringintconv | Package stringintconv defines an Analyzer that flags type conversions from integers to strings. |
cmd | |
stringintconv | The stringintconv command runs the stringintconv analyzer. |
structtag | Package structtag defines an Analyzer that checks struct field tags are well formed. |
testinggoroutine | |
tests | Package tests defines an Analyzer that checks for common mistaken usages of tests and examples. |
timeformat | Package timeformat defines an Analyzer that checks for the use of time.Format or time.Parse calls with a bad format. |
unmarshal | The unmarshal package defines an Analyzer that checks for passing non-pointer or non-interface types to unmarshal and decode functions. |
cmd | |
unmarshal | The unmarshal command runs the unmarshal analyzer. |
unreachable | Package unreachable defines an Analyzer that checks for unreachable code. |
unsafeptr | Package unsafeptr defines an Analyzer that checks for invalid conversions of uintptr to unsafe.Pointer. |
unusedresult | Package unusedresult defines an analyzer that checks for unused results of calls to certain pure functions. |
unusedwrite | Package unusedwrite checks for unused writes to the elements of a struct or array object. |
usesgenerics | Package usesgenerics defines an Analyzer that checks for usage of generic features added in Go 1.18. |
singlechecker | Package singlechecker defines the main function for an analysis driver with only a single analysis. |
unitchecker | The unitchecker package defines the main function for an analysis driver that analyzes a single compilation unit during a build. |