You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

doc.go 12KB

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