doc.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. /*
  5. Package analysis defines the interface between a modular static
  6. analysis and an analysis driver program.
  7. # Background
  8. A static analysis is a function that inspects a package of Go code and
  9. reports a set of diagnostics (typically mistakes in the code), and
  10. perhaps produces other results as well, such as suggested refactorings
  11. or other facts. An analysis that reports mistakes is informally called a
  12. "checker". For example, the printf checker reports mistakes in
  13. fmt.Printf format strings.
  14. A "modular" analysis is one that inspects one package at a time but can
  15. save information from a lower-level package and use it when inspecting a
  16. higher-level package, analogous to separate compilation in a toolchain.
  17. The printf checker is modular: when it discovers that a function such as
  18. log.Fatalf delegates to fmt.Printf, it records this fact, and checks
  19. calls to that function too, including calls made from another package.
  20. By implementing a common interface, checkers from a variety of sources
  21. can be easily selected, incorporated, and reused in a wide range of
  22. driver programs including command-line tools (such as vet), text editors and
  23. IDEs, build and test systems (such as go build, Bazel, or Buck), test
  24. frameworks, code review tools, code-base indexers (such as SourceGraph),
  25. documentation viewers (such as godoc), batch pipelines for large code
  26. bases, and so on.
  27. # Analyzer
  28. The primary type in the API is [Analyzer]. An Analyzer statically
  29. describes an analysis function: its name, documentation, flags,
  30. relationship to other analyzers, and of course, its logic.
  31. To define an analysis, a user declares a (logically constant) variable
  32. of type Analyzer. Here is a typical example from one of the analyzers in
  33. the go/analysis/passes/ subdirectory:
  34. package unusedresult
  35. var Analyzer = &analysis.Analyzer{
  36. Name: "unusedresult",
  37. Doc: "check for unused results of calls to some functions",
  38. Run: run,
  39. ...
  40. }
  41. func run(pass *analysis.Pass) (interface{}, error) {
  42. ...
  43. }
  44. An analysis driver is a program such as vet that runs a set of
  45. analyses and prints the diagnostics that they report.
  46. The driver program must import the list of Analyzers it needs.
  47. Typically each Analyzer resides in a separate package.
  48. To add a new Analyzer to an existing driver, add another item to the list:
  49. import ( "unusedresult"; "nilness"; "printf" )
  50. var analyses = []*analysis.Analyzer{
  51. unusedresult.Analyzer,
  52. nilness.Analyzer,
  53. printf.Analyzer,
  54. }
  55. A driver may use the name, flags, and documentation to provide on-line
  56. help that describes the analyses it performs.
  57. The doc comment contains a brief one-line summary,
  58. optionally followed by paragraphs of explanation.
  59. The [Analyzer] type has more fields besides those shown above:
  60. type Analyzer struct {
  61. Name string
  62. Doc string
  63. Flags flag.FlagSet
  64. Run func(*Pass) (interface{}, error)
  65. RunDespiteErrors bool
  66. ResultType reflect.Type
  67. Requires []*Analyzer
  68. FactTypes []Fact
  69. }
  70. The Flags field declares a set of named (global) flag variables that
  71. control analysis behavior. Unlike vet, analysis flags are not declared
  72. directly in the command line FlagSet; it is up to the driver to set the
  73. flag variables. A driver for a single analysis, a, might expose its flag
  74. f directly on the command line as -f, whereas a driver for multiple
  75. analyses might prefix the flag name by the analysis name (-a.f) to avoid
  76. ambiguity. An IDE might expose the flags through a graphical interface,
  77. and a batch pipeline might configure them from a config file.
  78. See the "findcall" analyzer for an example of flags in action.
  79. The RunDespiteErrors flag indicates whether the analysis is equipped to
  80. handle ill-typed code. If not, the driver will skip the analysis if
  81. there were parse or type errors.
  82. The optional ResultType field specifies the type of the result value
  83. computed by this analysis and made available to other analyses.
  84. The Requires field specifies a list of analyses upon which
  85. this one depends and whose results it may access, and it constrains the
  86. order in which a driver may run analyses.
  87. The FactTypes field is discussed in the section on Modularity.
  88. The analysis package provides a Validate function to perform basic
  89. sanity checks on an Analyzer, such as that its Requires graph is
  90. acyclic, its fact and result types are unique, and so on.
  91. Finally, the Run field contains a function to be called by the driver to
  92. execute the analysis on a single package. The driver passes it an
  93. instance of the Pass type.
  94. # Pass
  95. A [Pass] describes a single unit of work: the application of a particular
  96. Analyzer to a particular package of Go code.
  97. The Pass provides information to the Analyzer's Run function about the
  98. package being analyzed, and provides operations to the Run function for
  99. reporting diagnostics and other information back to the driver.
  100. type Pass struct {
  101. Fset *token.FileSet
  102. Files []*ast.File
  103. OtherFiles []string
  104. IgnoredFiles []string
  105. Pkg *types.Package
  106. TypesInfo *types.Info
  107. ResultOf map[*Analyzer]interface{}
  108. Report func(Diagnostic)
  109. ...
  110. }
  111. The Fset, Files, Pkg, and TypesInfo fields provide the syntax trees,
  112. type information, and source positions for a single package of Go code.
  113. The OtherFiles field provides the names of non-Go
  114. files such as assembly that are part of this package.
  115. Similarly, the IgnoredFiles field provides the names of Go and non-Go
  116. source files that are not part of this package with the current build
  117. configuration but may be part of other build configurations.
  118. The contents of these files may be read using Pass.ReadFile;
  119. see the "asmdecl" or "buildtags" analyzers for examples of loading
  120. non-Go files and reporting diagnostics against them.
  121. The ResultOf field provides the results computed by the analyzers
  122. required by this one, as expressed in its Analyzer.Requires field. The
  123. driver runs the required analyzers first and makes their results
  124. available in this map. Each Analyzer must return a value of the type
  125. described in its Analyzer.ResultType field.
  126. For example, the "ctrlflow" analyzer returns a *ctrlflow.CFGs, which
  127. provides a control-flow graph for each function in the package (see
  128. golang.org/x/tools/go/cfg); the "inspect" analyzer returns a value that
  129. enables other Analyzers to traverse the syntax trees of the package more
  130. efficiently; and the "buildssa" analyzer constructs an SSA-form
  131. intermediate representation.
  132. Each of these Analyzers extends the capabilities of later Analyzers
  133. without adding a dependency to the core API, so an analysis tool pays
  134. only for the extensions it needs.
  135. The Report function emits a diagnostic, a message associated with a
  136. source position. For most analyses, diagnostics are their primary
  137. result.
  138. For convenience, Pass provides a helper method, Reportf, to report a new
  139. diagnostic by formatting a string.
  140. Diagnostic is defined as:
  141. type Diagnostic struct {
  142. Pos token.Pos
  143. Category string // optional
  144. Message string
  145. }
  146. The optional Category field is a short identifier that classifies the
  147. kind of message when an analysis produces several kinds of diagnostic.
  148. The [Diagnostic] struct does not have a field to indicate its severity
  149. because opinions about the relative importance of Analyzers and their
  150. diagnostics vary widely among users. The design of this framework does
  151. not hold each Analyzer responsible for identifying the severity of its
  152. diagnostics. Instead, we expect that drivers will allow the user to
  153. customize the filtering and prioritization of diagnostics based on the
  154. producing Analyzer and optional Category, according to the user's
  155. preferences.
  156. Most Analyzers inspect typed Go syntax trees, but a few, such as asmdecl
  157. and buildtag, inspect the raw text of Go source files or even non-Go
  158. files such as assembly. To report a diagnostic against a line of a
  159. raw text file, use the following sequence:
  160. content, err := pass.ReadFile(filename)
  161. if err != nil { ... }
  162. tf := fset.AddFile(filename, -1, len(content))
  163. tf.SetLinesForContent(content)
  164. ...
  165. pass.Reportf(tf.LineStart(line), "oops")
  166. # Modular analysis with Facts
  167. To improve efficiency and scalability, large programs are routinely
  168. built using separate compilation: units of the program are compiled
  169. separately, and recompiled only when one of their dependencies changes;
  170. independent modules may be compiled in parallel. The same technique may
  171. be applied to static analyses, for the same benefits. Such analyses are
  172. described as "modular".
  173. A compiler’s type checker is an example of a modular static analysis.
  174. Many other checkers we would like to apply to Go programs can be
  175. understood as alternative or non-standard type systems. For example,
  176. vet's printf checker infers whether a function has the "printf wrapper"
  177. type, and it applies stricter checks to calls of such functions. In
  178. addition, it records which functions are printf wrappers for use by
  179. later analysis passes to identify other printf wrappers by induction.
  180. A result such as “f is a printf wrapper” that is not interesting by
  181. itself but serves as a stepping stone to an interesting result (such as
  182. a diagnostic) is called a [Fact].
  183. The analysis API allows an analysis to define new types of facts, to
  184. associate facts of these types with objects (named entities) declared
  185. within the current package, or with the package as a whole, and to query
  186. for an existing fact of a given type associated with an object or
  187. package.
  188. An Analyzer that uses facts must declare their types:
  189. var Analyzer = &analysis.Analyzer{
  190. Name: "printf",
  191. FactTypes: []analysis.Fact{new(isWrapper)},
  192. ...
  193. }
  194. type isWrapper struct{} // => *types.Func f “is a printf wrapper”
  195. The driver program ensures that facts for a pass’s dependencies are
  196. generated before analyzing the package and is responsible for propagating
  197. facts from one package to another, possibly across address spaces.
  198. Consequently, Facts must be serializable. The API requires that drivers
  199. use the gob encoding, an efficient, robust, self-describing binary
  200. protocol. A fact type may implement the GobEncoder/GobDecoder interfaces
  201. if the default encoding is unsuitable. Facts should be stateless.
  202. Because serialized facts may appear within build outputs, the gob encoding
  203. of a fact must be deterministic, to avoid spurious cache misses in
  204. build systems that use content-addressable caches.
  205. The driver makes a single call to the gob encoder for all facts
  206. exported by a given analysis pass, so that the topology of
  207. shared data structures referenced by multiple facts is preserved.
  208. The Pass type has functions to import and export facts,
  209. associated either with an object or with a package:
  210. type Pass struct {
  211. ...
  212. ExportObjectFact func(types.Object, Fact)
  213. ImportObjectFact func(types.Object, Fact) bool
  214. ExportPackageFact func(fact Fact)
  215. ImportPackageFact func(*types.Package, Fact) bool
  216. }
  217. An Analyzer may only export facts associated with the current package or
  218. its objects, though it may import facts from any package or object that
  219. is an import dependency of the current package.
  220. Conceptually, ExportObjectFact(obj, fact) inserts fact into a hidden map keyed by
  221. the pair (obj, TypeOf(fact)), and the ImportObjectFact function
  222. retrieves the entry from this map and copies its value into the variable
  223. pointed to by fact. This scheme assumes that the concrete type of fact
  224. is a pointer; this assumption is checked by the Validate function.
  225. See the "printf" analyzer for an example of object facts in action.
  226. Some driver implementations (such as those based on Bazel and Blaze) do
  227. not currently apply analyzers to packages of the standard library.
  228. Therefore, for best results, analyzer authors should not rely on
  229. analysis facts being available for standard packages.
  230. For example, although the printf checker is capable of deducing during
  231. analysis of the log package that log.Printf is a printf wrapper,
  232. this fact is built in to the analyzer so that it correctly checks
  233. calls to log.Printf even when run in a driver that does not apply
  234. it to standard packages. We would like to remove this limitation in future.
  235. # Testing an Analyzer
  236. The analysistest subpackage provides utilities for testing an Analyzer.
  237. In a few lines of code, it is possible to run an analyzer on a package
  238. of testdata files and check that it reported all the expected
  239. diagnostics and facts (and no more). Expectations are expressed using
  240. "// want ..." comments in the input code.
  241. # Standalone commands
  242. Analyzers are provided in the form of packages that a driver program is
  243. expected to import. The vet command imports a set of several analyzers,
  244. but users may wish to define their own analysis commands that perform
  245. additional checks. To simplify the task of creating an analysis command,
  246. either for a single analyzer or for a whole suite, we provide the
  247. singlechecker and multichecker subpackages.
  248. The singlechecker package provides the main function for a command that
  249. runs one analyzer. By convention, each analyzer such as
  250. go/analysis/passes/findcall should be accompanied by a singlechecker-based
  251. command such as go/analysis/passes/findcall/cmd/findcall, defined in its
  252. entirety as:
  253. package main
  254. import (
  255. "golang.org/x/tools/go/analysis/passes/findcall"
  256. "golang.org/x/tools/go/analysis/singlechecker"
  257. )
  258. func main() { singlechecker.Main(findcall.Analyzer) }
  259. A tool that provides multiple analyzers can use multichecker in a
  260. similar way, giving it the list of Analyzers.
  261. */
  262. package analysis