Movatterモバイル変換


[0]ホーム

URL:


analysis

package
v0.37.0Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2025 License:BSD-3-ClauseImports:8Imported by:5,825

Details

Repository

cs.opensource.google/go/x/tools

Links

Documentation

Overview

Package analysis defines the interface between a modular staticanalysis and an analysis driver program.

Background

A static analysis is a function that inspects a package of Go code andreports a set of diagnostics (typically mistakes in the code), andperhaps produces other results as well, such as suggested refactoringsor other facts. An analysis that reports mistakes is informally called a"checker". For example, the printf checker reports mistakes infmt.Printf format strings.

A "modular" analysis is one that inspects one package at a time but cansave information from a lower-level package and use it when inspecting ahigher-level package, analogous to separate compilation in a toolchain.The printf checker is modular: when it discovers that a function such aslog.Fatalf delegates to fmt.Printf, it records this fact, and checkscalls to that function too, including calls made from another package.

By implementing a common interface, checkers from a variety of sourcescan be easily selected, incorporated, and reused in a wide range ofdriver programs including command-line tools (such as vet), text editors andIDEs, build and test systems (such as go build, Bazel, or Buck), testframeworks, code review tools, code-base indexers (such as SourceGraph),documentation viewers (such as godoc), batch pipelines for large codebases, and so on.

Analyzer

The primary type in the API isAnalyzer. An Analyzer staticallydescribes an analysis function: its name, documentation, flags,relationship to other analyzers, and of course, its logic.

To define an analysis, a user declares a (logically constant) variableof type Analyzer. Here is a typical example from one of the analyzers inthe go/analysis/passes/ subdirectory:

package unusedresultvar Analyzer = &analysis.Analyzer{Name: "unusedresult",Doc:  "check for unused results of calls to some functions",Run:  run,...}func run(pass *analysis.Pass) (interface{}, error) {...}

An analysis driver is a program such as vet that runs a set ofanalyses and prints the diagnostics that they report.The driver program must import the list of Analyzers it needs.Typically each Analyzer resides in a separate package.To add a new Analyzer to an existing driver, add another item to the list:

import ( "unusedresult"; "nilness"; "printf" )var analyses = []*analysis.Analyzer{unusedresult.Analyzer,nilness.Analyzer,printf.Analyzer,}

A driver may use the name, flags, and documentation to provide on-linehelp that describes the analyses it performs.The doc comment contains a brief one-line summary,optionally followed by paragraphs of explanation.

TheAnalyzer type has more fields besides those shown above:

type Analyzer struct {Name             stringDoc              stringFlags            flag.FlagSetRun              func(*Pass) (interface{}, error)RunDespiteErrors boolResultType       reflect.TypeRequires         []*AnalyzerFactTypes        []Fact}

The Flags field declares a set of named (global) flag variables thatcontrol analysis behavior. Unlike vet, analysis flags are not declareddirectly in the command line FlagSet; it is up to the driver to set theflag variables. A driver for a single analysis, a, might expose its flagf directly on the command line as -f, whereas a driver for multipleanalyses might prefix the flag name by the analysis name (-a.f) to avoidambiguity. An IDE might expose the flags through a graphical interface,and a batch pipeline might configure them from a config file.See the "findcall" analyzer for an example of flags in action.

The RunDespiteErrors flag indicates whether the analysis is equipped tohandle ill-typed code. If not, the driver will skip the analysis ifthere were parse or type errors.The optional ResultType field specifies the type of the result valuecomputed by this analysis and made available to other analyses.The Requires field specifies a list of analyses upon whichthis one depends and whose results it may access, and it constrains theorder in which a driver may run analyses.The FactTypes field is discussed in the section on Modularity.The analysis package provides a Validate function to perform basicsanity checks on an Analyzer, such as that its Requires graph isacyclic, its fact and result types are unique, and so on.

Finally, the Run field contains a function to be called by the driver toexecute the analysis on a single package. The driver passes it aninstance of the Pass type.

Pass

APass describes a single unit of work: the application of a particularAnalyzer to a particular package of Go code.The Pass provides information to the Analyzer's Run function about thepackage being analyzed, and provides operations to the Run function forreporting diagnostics and other information back to the driver.

type Pass struct {Fset         *token.FileSetFiles        []*ast.FileOtherFiles   []stringIgnoredFiles []stringPkg          *types.PackageTypesInfo    *types.InfoResultOf     map[*Analyzer]interface{}Report       func(Diagnostic)...}

The Fset, Files, Pkg, and TypesInfo fields provide the syntax trees,type information, and source positions for a single package of Go code.

The OtherFiles field provides the names of non-Gofiles such as assembly that are part of this package.Similarly, the IgnoredFiles field provides the names of Go and non-Gosource files that are not part of this package with the current buildconfiguration but may be part of other build configurations.The contents of these files may be read using Pass.ReadFile;see the "asmdecl" or "buildtags" analyzers for examples of loadingnon-Go files and reporting diagnostics against them.

The ResultOf field provides the results computed by the analyzersrequired by this one, as expressed in its Analyzer.Requires field. Thedriver runs the required analyzers first and makes their resultsavailable in this map. Each Analyzer must return a value of the typedescribed in its Analyzer.ResultType field.For example, the "ctrlflow" analyzer returns a *ctrlflow.CFGs, whichprovides a control-flow graph for each function in the package (seegolang.org/x/tools/go/cfg); the "inspect" analyzer returns a value thatenables other Analyzers to traverse the syntax trees of the package moreefficiently; and the "buildssa" analyzer constructs an SSA-formintermediate representation.Each of these Analyzers extends the capabilities of later Analyzerswithout adding a dependency to the core API, so an analysis tool paysonly for the extensions it needs.

The Report function emits a diagnostic, a message associated with asource position. For most analyses, diagnostics are their primaryresult.For convenience, Pass provides a helper method, Reportf, to report a newdiagnostic by formatting a string.Diagnostic is defined as:

type Diagnostic struct {Pos      token.PosCategory string // optionalMessage  string}

The optional Category field is a short identifier that classifies thekind of message when an analysis produces several kinds of diagnostic.

TheDiagnostic struct does not have a field to indicate its severitybecause opinions about the relative importance of Analyzers and theirdiagnostics vary widely among users. The design of this framework doesnot hold each Analyzer responsible for identifying the severity of itsdiagnostics. Instead, we expect that drivers will allow the user tocustomize the filtering and prioritization of diagnostics based on theproducing Analyzer and optional Category, according to the user'spreferences.

Most Analyzers inspect typed Go syntax trees, but a few, such as asmdecland buildtag, inspect the raw text of Go source files or even non-Gofiles such as assembly. To report a diagnostic against a line of araw text file, use the following sequence:

content, err := pass.ReadFile(filename)if err != nil { ... }tf := fset.AddFile(filename, -1, len(content))tf.SetLinesForContent(content)...pass.Reportf(tf.LineStart(line), "oops")

Modular analysis with Facts

To improve efficiency and scalability, large programs are routinelybuilt using separate compilation: units of the program are compiledseparately, and recompiled only when one of their dependencies changes;independent modules may be compiled in parallel. The same technique maybe applied to static analyses, for the same benefits. Such analyses aredescribed as "modular".

A compiler’s type checker is an example of a modular static analysis.Many other checkers we would like to apply to Go programs can beunderstood as alternative or non-standard type systems. For example,vet's printf checker infers whether a function has the "printf wrapper"type, and it applies stricter checks to calls of such functions. Inaddition, it records which functions are printf wrappers for use bylater analysis passes to identify other printf wrappers by induction.A result such as “f is a printf wrapper” that is not interesting byitself but serves as a stepping stone to an interesting result (such asa diagnostic) is called aFact.

The analysis API allows an analysis to define new types of facts, toassociate facts of these types with objects (named entities) declaredwithin the current package, or with the package as a whole, and to queryfor an existing fact of a given type associated with an object orpackage.

An Analyzer that uses facts must declare their types:

var Analyzer = &analysis.Analyzer{Name:      "printf",FactTypes: []analysis.Fact{new(isWrapper)},...}type isWrapper struct{} // => *types.Func f “is a printf wrapper”

The driver program ensures that facts for a pass’s dependencies aregenerated before analyzing the package and is responsible for propagatingfacts from one package to another, possibly across address spaces.Consequently, Facts must be serializable. The API requires that driversuse the gob encoding, an efficient, robust, self-describing binaryprotocol. A fact type may implement the GobEncoder/GobDecoder interfacesif the default encoding is unsuitable. Facts should be stateless.Because serialized facts may appear within build outputs, the gob encodingof a fact must be deterministic, to avoid spurious cache misses inbuild systems that use content-addressable caches.The driver makes a single call to the gob encoder for all factsexported by a given analysis pass, so that the topology ofshared data structures referenced by multiple facts is preserved.

The Pass type has functions to import and export facts,associated either with an object or with a package:

type Pass struct {...ExportObjectFact func(types.Object, Fact)ImportObjectFact func(types.Object, Fact) boolExportPackageFact func(fact Fact)ImportPackageFact func(*types.Package, Fact) bool}

An Analyzer may only export facts associated with the current package orits objects, though it may import facts from any package or object thatis an import dependency of the current package.

Conceptually, ExportObjectFact(obj, fact) inserts fact into a hidden map keyed bythe pair (obj, TypeOf(fact)), and the ImportObjectFact functionretrieves the entry from this map and copies its value into the variablepointed to by fact. This scheme assumes that the concrete type of factis a pointer; this assumption is checked by the Validate function.See the "printf" analyzer for an example of object facts in action.

Some driver implementations (such as those based on Bazel and Blaze) donot currently apply analyzers to packages of the standard library.Therefore, for best results, analyzer authors should not rely onanalysis facts being available for standard packages.For example, although the printf checker is capable of deducing duringanalysis of the log package that log.Printf is a printf wrapper,this fact is built in to the analyzer so that it correctly checkscalls to log.Printf even when run in a driver that does not applyit to standard packages. We would like to remove this limitation in future.

Testing an Analyzer

The analysistest subpackage provides utilities for testing an Analyzer.In a few lines of code, it is possible to run an analyzer on a packageof testdata files and check that it reported all the expecteddiagnostics and facts (and no more). Expectations are expressed using"// want ..." comments in the input code.

Standalone commands

Analyzers are provided in the form of packages that a driver program isexpected to import. The vet command imports a set of several analyzers,but users may wish to define their own analysis commands that performadditional checks. To simplify the task of creating an analysis command,either for a single analyzer or for a whole suite, we provide thesinglechecker and multichecker subpackages.

The singlechecker package provides the main function for a command thatruns one analyzer. By convention, each analyzer such asgo/analysis/passes/findcall should be accompanied by a singlechecker-basedcommand such as go/analysis/passes/findcall/cmd/findcall, defined in itsentirety as:

package mainimport ("golang.org/x/tools/go/analysis/passes/findcall""golang.org/x/tools/go/analysis/singlechecker")func main() { singlechecker.Main(findcall.Analyzer) }

A tool that provides multiple analyzers can use multichecker in asimilar way, giving it the list of Analyzers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

funcValidate

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.

Analyzer names need not be unique, though this may be confusing.

Types

typeAnalyzer

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.Namestring// Doc is the documentation for the analyzer.// The part before the first "\n\n" is the title// (no capital or period, max ~60 letters).Docstring// URL holds an optional link to a web page with additional// documentation for this analyzer.URLstring// 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.Flagsflag.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) (any,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.RunDespiteErrorsbool// 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.ResultTypereflect.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}

An Analyzer describes an analysis function and its options.

func (*Analyzer)String

func (a *Analyzer) String()string

typeCycleInRequiresGraphError

type CycleInRequiresGraphError struct {AnalyzerNames map[string]bool}

func (*CycleInRequiresGraphError)Error

typeDiagnostic

type Diagnostic struct {Postoken.PosEndtoken.Pos// optionalCategorystring// optionalMessagestring// URL is the optional location of a web page that provides// additional documentation for this diagnostic.//// If URL is empty but a Category is specified, then the// Analysis driver should treat the URL as "#"+Category.//// The URL may be relative. If so, the base URL is that of the// Analyzer that produced the diagnostic;// seehttps://pkg.go.dev/net/url#URL.ResolveReference.URLstring// SuggestedFixes is an optional list of fixes to address the// problem described by the diagnostic. Each one represents// an alternative strategy; at most one may be applied.//// Fixes for different diagnostics should be treated as// independent changes to the same baseline file state,// analogous to a set of git commits all with the same parent.// Combining fixes requires resolving any conflicts that// arise, analogous to a git merge.// Any conflicts that remain may be dealt with, depending on// the tool, by discarding fixes, consulting the user, or// aborting the operation.SuggestedFixes []SuggestedFix// Related contains optional secondary positions and messages// related to the primary diagnostic.Related []RelatedInformation}

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.

All Pos values are interpreted relative to Pass.Fset. If End isprovided, the diagnostic is specified to apply to the range betweenPos and End.

typeFact

type Fact interface {AFact()// dummy method to avoid type errors}

A Fact is an intermediate fact produced during analysis.

Each fact is associated with a named declaration (a types.Object) orwith a package as a whole. A single object or package may havemultiple associated facts, but only one of any particular fact type.

A Fact represents a predicate such as "never returns", but does notrepresent the subject of the predicate such as "function F" or "package P".

Facts may be produced in one analysis pass and consumed by anotheranalysis pass even if these are in different address spaces.If package P imports Q, all facts about Q produced duringanalysis 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 thesame 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 callingPass.Import{Object,Package}Fact and update them usingPass.Export{Object,Package}Fact.

A fact is logically private to its Analysis. To pass valuesbetween 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 interfacesto customize its encoding. Fact encoding should not fail.

A Fact should not be modified once exported.

typeModuleadded inv0.24.0

type Module struct {Pathstring// module pathVersionstring// module version ("" if unknown, such as for workspace modules)GoVersionstring// go version used in module (e.g. "go1.22.0")}

A Module describes the module to which a package belongs.

typeObjectFact

type ObjectFact struct {Objecttypes.ObjectFactFact}

ObjectFact is an object together with an associated fact.

typePackageFact

type PackageFact struct {Package *types.PackageFactFact}

PackageFact is a package together with an associated fact.

typePass

type Pass struct {Analyzer *Analyzer// the identity of the current analyzer// syntax and type informationFset         *token.FileSet// file position information; Run may add new filesFiles        []*ast.File// the abstract syntax tree of each fileOtherFiles   []string// names of non-Go files of this packageIgnoredFiles []string// names of ignored source files in this packagePkg          *types.Package// type information about the packageTypesInfo    *types.Info// type information about the syntax treesTypesSizestypes.Sizes// function for computing sizes of typesTypeErrors   []types.Error// type errors (only if Analyzer.RunDespiteErrors)Module *Module// the package's enclosing module (possibly nil in some drivers)// 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]any// ReadFile returns the contents of the named file.//// The only valid file names are the elements of OtherFiles// and IgnoredFiles, and names returned by// Fset.File(f.FileStart).Name() for each f in Files.//// Analyzers must use this function (if provided) instead of// accessing the file system directly. This allows a driver to// provide a virtualized file tree (including, for example,// unsaved editor buffers) and to track dependencies precisely// to avoid unnecessary recomputation.ReadFile func(filenamestring) ([]byte,error)// 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(objtypes.Object, factFact)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, factFact)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(objtypes.Object, factFact)// ExportPackageFact associates a fact with the current package.// See comments for ExportObjectFact.ExportPackageFact func(factFact)// AllPackageFacts returns a new slice containing all package// facts of the analysis's FactTypes in unspecified order.// See comments for AllObjectFacts.AllPackageFacts func() []PackageFact// AllObjectFacts returns a new slice containing all object// facts of the analysis's FactTypes in unspecified order.//// The result includes all facts exported by packages// whose symbols are referenced by the current package// (by qualified identifiers or field/method selections).// And it includes all facts exported from the current// package by the current analysis pass.AllObjectFacts func() []ObjectFact}

A Pass provides information to the Run function thatapplies a specific analyzer to a single Go package.

It forms the interface between the analysis logic and the driverprogram, 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.

func (*Pass)ReportRangef

func (pass *Pass) ReportRangef(rngRange, formatstring, args ...any)

ReportRangef is a helper function that reports a Diagnostic using therange provided. ast.Node values can be passed in as the range becausethey satisfy the Range interface.

func (*Pass)Reportf

func (pass *Pass) Reportf(postoken.Pos, formatstring, args ...any)

Reportf is a helper function that reports a Diagnostic using thespecified position and formatted error message.

func (*Pass)String

func (pass *Pass) String()string

typeRange

type Range interface {Pos()token.Pos// position of first character belonging to the nodeEnd()token.Pos// position of first character immediately after the node}

The Range interface provides a range. It's equivalent to and satisfied byast.Node.

typeRelatedInformation

type RelatedInformation struct {Postoken.PosEndtoken.Pos// optionalMessagestring}

RelatedInformation contains information related to a diagnostic.For example, a diagnostic that flags duplicated declarations of avariable may include one RelatedInformation per existingdeclaration.

typeSuggestedFix

type SuggestedFix struct {// A verb phrase describing the fix, to be shown to// a user trying to decide whether to accept it.//// Example: "Remove the surplus argument"MessagestringTextEdits []TextEdit}

A SuggestedFix is a code change associated with a Diagnostic that auser can choose to apply to their code. Usually the SuggestedFix ismeant to fix the issue flagged by the diagnostic.

The TextEdits must not overlap, nor contain edits for otherpackages. Edits need not be totally ordered, but the orderdetermines how insertions at the same point will be applied.

typeTextEdit

type TextEdit struct {// For a pure insertion, End can either be set to Pos or token.NoPos.Postoken.PosEndtoken.PosNewText []byte}

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.

Source Files

View all Source files

Directories

PathSynopsis
Package analysistest provides utilities for testing analyzers.
Package analysistest provides utilities for testing analyzers.
Package checker provides an analysis driver based on the golang.org/x/tools/go/packages representation of a set of packages and all their dependencies, as produced by packages.Load.
Package checker provides an analysis driver based on the golang.org/x/tools/go/packages representation of a set of packages and all their dependencies, as produced by packages.Load.
analysisflags
Package analysisflags defines helpers for processing flags (-help, -json, -fix, -diff, etc) common to unitchecker and {single,multi}checker.
Package analysisflags defines helpers for processing flags (-help, -json, -fix, -diff, etc) common to unitchecker and {single,multi}checker.
checker
Package internal/checker defines various implementation helpers for the singlechecker and multichecker packages, which provide the complete main function for an analysis driver executable based on go/packages.
Package internal/checker defines various implementation helpers for the singlechecker and multichecker packages, which provide the complete main function for an analysis driver executable based on go/packages.
Package multichecker defines the main function for an analysis driver with several analyzers.
Package multichecker defines the main function for an analysis driver with several analyzers.
passes
appends
Package appends defines an Analyzer that detects if there is only one variable in append.
Package appends defines an Analyzer that detects if there is only one variable in append.
asmdecl
Package asmdecl defines an Analyzer that reports mismatches between assembly files and Go declarations.
Package asmdecl defines an Analyzer that reports mismatches between assembly files and Go declarations.
assign
Package assign defines an Analyzer that detects useless assignments.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Package deepequalerrors defines an Analyzer that checks for the use of reflect.DeepEqual with error values.
defers
Package defers defines an Analyzer that checks for common mistakes in defer statements.
Package defers defines an Analyzer that checks for common mistakes in defer statements.
defers/cmd/deferscommand
The defers command runs the defers analyzer.
The defers command runs the defers analyzer.
directive
Package directive defines an Analyzer that checks known Go toolchain directives.
Package directive defines an Analyzer that checks known Go toolchain directives.
errorsas
The errorsas package defines an Analyzer that checks that the second argument to errors.As is a pointer to a type implementing error.
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.
Package fieldalignment defines an Analyzer that detects structs that would use less memory if their fields were sorted.
findcall
Package findcall defines an Analyzer that serves as a trivial example and test of the Analysis API.
Package findcall defines an Analyzer that serves as a trivial example and test of the Analysis API.
findcall/cmd/findcallcommand
The findcall command runs the findcall analyzer.
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.
Package framepointer defines an Analyzer that reports assembly code that clobbers the frame pointer before saving it.
gofix
Package gofix defines an Analyzer that checks "//go:fix inline" directives.
Package gofix defines an Analyzer that checks "//go:fix inline" directives.
hostport
Package hostport defines an analyzer for calls to net.Dial with addresses of the form "%s:%d" or "%s:%s", which work only with IPv4.
Package hostport defines an analyzer for calls to net.Dial with addresses of the form "%s:%d" or "%s:%s", which work only with IPv4.
httpmux/cmd/httpmuxcommand
The httpmux command runs the httpmux analyzer.
The httpmux command runs the httpmux analyzer.
httpresponse
Package httpresponse defines an Analyzer that checks for mistakes using HTTP responses.
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.
Package ifaceassert defines an Analyzer that flags impossible interface-interface type assertions.
ifaceassert/cmd/ifaceassertcommand
The ifaceassert command runs the ifaceassert analyzer.
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.
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.
internal/analysisutil
Package analysisutil defines various helper functions used by two or more packages beneath go/analysis.
Package analysisutil defines various helper functions used by two or more packages beneath go/analysis.
loopclosure
Package loopclosure defines an Analyzer that checks for references to enclosing loop variables from within nested functions.
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.
Package lostcancel defines an Analyzer that checks for failure to call a context cancellation function.
lostcancel/cmd/lostcancelcommand
The lostcancel command applies the golang.org/x/tools/go/analysis/passes/lostcancel analysis to the specified packages of Go source code.
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.
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.
Package nilness inspects the control-flow graph of an SSA function and reports errors such as nil pointer dereferences and degenerate nil pointer comparisons.
nilness/cmd/nilnesscommand
The nilness command applies the golang.org/x/tools/go/analysis/passes/nilness analysis to the specified packages of Go source code.
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.
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.
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.
Package reflectvaluecompare defines an Analyzer that checks for accidentally using == or reflect.DeepEqual to compare reflect.Value values.
reflectvaluecompare/cmd/reflectvaluecomparecommand
The reflectvaluecompare command applies the reflectvaluecompare checker to the specified packages of Go source code.
The reflectvaluecompare command applies the reflectvaluecompare checker to the specified packages of Go source code.
shadow
Package shadow defines an Analyzer that checks for shadowed variables.
Package shadow defines an Analyzer that checks for shadowed variables.
shadow/cmd/shadowcommand
The shadow command runs the shadow analyzer.
The shadow command runs the shadow analyzer.
shift
Package shift defines an Analyzer that checks for shifts that exceed the width of an integer.
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.
Package sigchanyzer defines an Analyzer that detects misuse of unbuffered signal as argument to signal.Notify.
slog
Package slog defines an Analyzer that checks for mismatched key-value pairs in log/slog calls.
Package slog defines an Analyzer that checks for mismatched key-value pairs in log/slog calls.
sortslice
Package sortslice defines an Analyzer that checks for calls to sort.Slice that do not use a slice type as first argument.
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.
Package stdmethods defines an Analyzer that checks for misspellings in the signatures of methods similar to well-known interfaces.
stdversion
Package stdversion reports uses of standard library symbols that are "too new" for the Go version in force in the referring file.
Package stdversion reports uses of standard library symbols that are "too new" for the Go version in force in the referring file.
stringintconv
Package stringintconv defines an Analyzer that flags type conversions from integers to strings.
Package stringintconv defines an Analyzer that flags type conversions from integers to strings.
stringintconv/cmd/stringintconvcommand
The stringintconv command runs the stringintconv analyzer.
The stringintconv command runs the stringintconv analyzer.
structtag
Package structtag defines an Analyzer that checks struct field tags are well formed.
Package structtag defines an Analyzer that checks struct field tags are well formed.
testinggoroutine
Package testinggoroutine defines an Analyzerfor detecting calls to Fatal from a test goroutine.
Package testinggoroutine defines an Analyzerfor detecting calls to Fatal from a test goroutine.
tests
Package tests defines an Analyzer that checks for common mistaken usages of tests and examples.
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.
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.
The unmarshal package defines an Analyzer that checks for passing non-pointer or non-interface types to unmarshal and decode functions.
unmarshal/cmd/unmarshalcommand
The unmarshal command runs the unmarshal analyzer.
The unmarshal command runs the unmarshal analyzer.
unreachable
Package unreachable defines an Analyzer that checks for unreachable code.
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.
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.
Package unusedresult defines an analyzer that checks for unused results of calls to certain pure functions.
unusedresult/cmd/unusedresultcommand
The unusedresult command applies the golang.org/x/tools/go/analysis/passes/unusedresult analysis to the specified packages of Go source code.
The unusedresult command applies the golang.org/x/tools/go/analysis/passes/unusedresult analysis to the specified packages of Go source code.
unusedwrite
Package unusedwrite checks for unused writes to the elements of a struct or array object.
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.
Package usesgenerics defines an Analyzer that checks for usage of generic features added in Go 1.18.
waitgroup
Package waitgroup defines an Analyzer that detects simple misuses of sync.WaitGroup.
Package waitgroup defines an Analyzer that detects simple misuses of sync.WaitGroup.
Package singlechecker defines the main function for an analysis driver with only a single analysis.
Package singlechecker defines the main function for an analysis driver with only a single analysis.
The unitchecker package defines the main function for an analysis driver that analyzes a single compilation unit during a build.
The unitchecker package defines the main function for an analysis driver that analyzes a single compilation unit during a build.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp