analysis.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. package analysis
  5. import (
  6. "flag"
  7. "fmt"
  8. "go/ast"
  9. "go/token"
  10. "go/types"
  11. "reflect"
  12. "golang.org/x/tools/internal/analysisinternal"
  13. )
  14. // An Analyzer describes an analysis function and its options.
  15. type Analyzer struct {
  16. // The Name of the analyzer must be a valid Go identifier
  17. // as it may appear in command-line flags, URLs, and so on.
  18. Name string
  19. // Doc is the documentation for the analyzer.
  20. // The part before the first "\n\n" is the title
  21. // (no capital or period, max ~60 letters).
  22. Doc string
  23. // Flags defines any flags accepted by the analyzer.
  24. // The manner in which these flags are exposed to the user
  25. // depends on the driver which runs the analyzer.
  26. Flags flag.FlagSet
  27. // Run applies the analyzer to a package.
  28. // It returns an error if the analyzer failed.
  29. //
  30. // On success, the Run function may return a result
  31. // computed by the Analyzer; its type must match ResultType.
  32. // The driver makes this result available as an input to
  33. // another Analyzer that depends directly on this one (see
  34. // Requires) when it analyzes the same package.
  35. //
  36. // To pass analysis results between packages (and thus
  37. // potentially between address spaces), use Facts, which are
  38. // serializable.
  39. Run func(*Pass) (interface{}, error)
  40. // RunDespiteErrors allows the driver to invoke
  41. // the Run method of this analyzer even on a
  42. // package that contains parse or type errors.
  43. RunDespiteErrors bool
  44. // Requires is a set of analyzers that must run successfully
  45. // before this one on a given package. This analyzer may inspect
  46. // the outputs produced by each analyzer in Requires.
  47. // The graph over analyzers implied by Requires edges must be acyclic.
  48. //
  49. // Requires establishes a "horizontal" dependency between
  50. // analysis passes (different analyzers, same package).
  51. Requires []*Analyzer
  52. // ResultType is the type of the optional result of the Run function.
  53. ResultType reflect.Type
  54. // FactTypes indicates that this analyzer imports and exports
  55. // Facts of the specified concrete types.
  56. // An analyzer that uses facts may assume that its import
  57. // dependencies have been similarly analyzed before it runs.
  58. // Facts must be pointers.
  59. //
  60. // FactTypes establishes a "vertical" dependency between
  61. // analysis passes (same analyzer, different packages).
  62. FactTypes []Fact
  63. }
  64. func (a *Analyzer) String() string { return a.Name }
  65. func init() {
  66. // Set the analysisinternal functions to be able to pass type errors
  67. // to the Pass type without modifying the go/analysis API.
  68. analysisinternal.SetTypeErrors = func(p interface{}, errors []types.Error) {
  69. p.(*Pass).typeErrors = errors
  70. }
  71. analysisinternal.GetTypeErrors = func(p interface{}) []types.Error {
  72. return p.(*Pass).typeErrors
  73. }
  74. }
  75. // A Pass provides information to the Run function that
  76. // applies a specific analyzer to a single Go package.
  77. //
  78. // It forms the interface between the analysis logic and the driver
  79. // program, and has both input and an output components.
  80. //
  81. // As in a compiler, one pass may depend on the result computed by another.
  82. //
  83. // The Run function should not call any of the Pass functions concurrently.
  84. type Pass struct {
  85. Analyzer *Analyzer // the identity of the current analyzer
  86. // syntax and type information
  87. Fset *token.FileSet // file position information
  88. Files []*ast.File // the abstract syntax tree of each file
  89. OtherFiles []string // names of non-Go files of this package
  90. IgnoredFiles []string // names of ignored source files in this package
  91. Pkg *types.Package // type information about the package
  92. TypesInfo *types.Info // type information about the syntax trees
  93. TypesSizes types.Sizes // function for computing sizes of types
  94. // Report reports a Diagnostic, a finding about a specific location
  95. // in the analyzed source code such as a potential mistake.
  96. // It may be called by the Run function.
  97. Report func(Diagnostic)
  98. // ResultOf provides the inputs to this analysis pass, which are
  99. // the corresponding results of its prerequisite analyzers.
  100. // The map keys are the elements of Analysis.Required,
  101. // and the type of each corresponding value is the required
  102. // analysis's ResultType.
  103. ResultOf map[*Analyzer]interface{}
  104. // -- facts --
  105. // ImportObjectFact retrieves a fact associated with obj.
  106. // Given a value ptr of type *T, where *T satisfies Fact,
  107. // ImportObjectFact copies the value to *ptr.
  108. //
  109. // ImportObjectFact panics if called after the pass is complete.
  110. // ImportObjectFact is not concurrency-safe.
  111. ImportObjectFact func(obj types.Object, fact Fact) bool
  112. // ImportPackageFact retrieves a fact associated with package pkg,
  113. // which must be this package or one of its dependencies.
  114. // See comments for ImportObjectFact.
  115. ImportPackageFact func(pkg *types.Package, fact Fact) bool
  116. // ExportObjectFact associates a fact of type *T with the obj,
  117. // replacing any previous fact of that type.
  118. //
  119. // ExportObjectFact panics if it is called after the pass is
  120. // complete, or if obj does not belong to the package being analyzed.
  121. // ExportObjectFact is not concurrency-safe.
  122. ExportObjectFact func(obj types.Object, fact Fact)
  123. // ExportPackageFact associates a fact with the current package.
  124. // See comments for ExportObjectFact.
  125. ExportPackageFact func(fact Fact)
  126. // AllPackageFacts returns a new slice containing all package facts of the analysis's FactTypes
  127. // in unspecified order.
  128. // WARNING: This is an experimental API and may change in the future.
  129. AllPackageFacts func() []PackageFact
  130. // AllObjectFacts returns a new slice containing all object facts of the analysis's FactTypes
  131. // in unspecified order.
  132. // WARNING: This is an experimental API and may change in the future.
  133. AllObjectFacts func() []ObjectFact
  134. // typeErrors contains types.Errors that are associated with the pkg.
  135. typeErrors []types.Error
  136. /* Further fields may be added in future. */
  137. // For example, suggested or applied refactorings.
  138. }
  139. // PackageFact is a package together with an associated fact.
  140. // WARNING: This is an experimental API and may change in the future.
  141. type PackageFact struct {
  142. Package *types.Package
  143. Fact Fact
  144. }
  145. // ObjectFact is an object together with an associated fact.
  146. // WARNING: This is an experimental API and may change in the future.
  147. type ObjectFact struct {
  148. Object types.Object
  149. Fact Fact
  150. }
  151. // Reportf is a helper function that reports a Diagnostic using the
  152. // specified position and formatted error message.
  153. func (pass *Pass) Reportf(pos token.Pos, format string, args ...interface{}) {
  154. msg := fmt.Sprintf(format, args...)
  155. pass.Report(Diagnostic{Pos: pos, Message: msg})
  156. }
  157. // The Range interface provides a range. It's equivalent to and satisfied by
  158. // ast.Node.
  159. type Range interface {
  160. Pos() token.Pos // position of first character belonging to the node
  161. End() token.Pos // position of first character immediately after the node
  162. }
  163. // ReportRangef is a helper function that reports a Diagnostic using the
  164. // range provided. ast.Node values can be passed in as the range because
  165. // they satisfy the Range interface.
  166. func (pass *Pass) ReportRangef(rng Range, format string, args ...interface{}) {
  167. msg := fmt.Sprintf(format, args...)
  168. pass.Report(Diagnostic{Pos: rng.Pos(), End: rng.End(), Message: msg})
  169. }
  170. func (pass *Pass) String() string {
  171. return fmt.Sprintf("%s@%s", pass.Analyzer.Name, pass.Pkg.Path())
  172. }
  173. // A Fact is an intermediate fact produced during analysis.
  174. //
  175. // Each fact is associated with a named declaration (a types.Object) or
  176. // with a package as a whole. A single object or package may have
  177. // multiple associated facts, but only one of any particular fact type.
  178. //
  179. // A Fact represents a predicate such as "never returns", but does not
  180. // represent the subject of the predicate such as "function F" or "package P".
  181. //
  182. // Facts may be produced in one analysis pass and consumed by another
  183. // analysis pass even if these are in different address spaces.
  184. // If package P imports Q, all facts about Q produced during
  185. // analysis of that package will be available during later analysis of P.
  186. // Facts are analogous to type export data in a build system:
  187. // just as export data enables separate compilation of several passes,
  188. // facts enable "separate analysis".
  189. //
  190. // Each pass (a, p) starts with the set of facts produced by the
  191. // same analyzer a applied to the packages directly imported by p.
  192. // The analysis may add facts to the set, and they may be exported in turn.
  193. // An analysis's Run function may retrieve facts by calling
  194. // Pass.Import{Object,Package}Fact and update them using
  195. // Pass.Export{Object,Package}Fact.
  196. //
  197. // A fact is logically private to its Analysis. To pass values
  198. // between different analyzers, use the results mechanism;
  199. // see Analyzer.Requires, Analyzer.ResultType, and Pass.ResultOf.
  200. //
  201. // A Fact type must be a pointer.
  202. // Facts are encoded and decoded using encoding/gob.
  203. // A Fact may implement the GobEncoder/GobDecoder interfaces
  204. // to customize its encoding. Fact encoding should not fail.
  205. //
  206. // A Fact should not be modified once exported.
  207. type Fact interface {
  208. AFact() // dummy method to avoid type errors
  209. }