doc.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 packages loads Go packages for inspection and analysis.
  6. The [Load] function takes as input a list of patterns and returns a
  7. list of [Package] values describing individual packages matched by those
  8. patterns.
  9. A [Config] specifies configuration options, the most important of which is
  10. the [LoadMode], which controls the amount of detail in the loaded packages.
  11. Load passes most patterns directly to the underlying build tool.
  12. The default build tool is the go command.
  13. Its supported patterns are described at
  14. https://pkg.go.dev/cmd/go#hdr-Package_lists_and_patterns.
  15. Other build systems may be supported by providing a "driver";
  16. see [The driver protocol].
  17. All patterns with the prefix "query=", where query is a
  18. non-empty string of letters from [a-z], are reserved and may be
  19. interpreted as query operators.
  20. Two query operators are currently supported: "file" and "pattern".
  21. The query "file=path/to/file.go" matches the package or packages enclosing
  22. the Go source file path/to/file.go. For example "file=~/go/src/fmt/print.go"
  23. might return the packages "fmt" and "fmt [fmt.test]".
  24. The query "pattern=string" causes "string" to be passed directly to
  25. the underlying build tool. In most cases this is unnecessary,
  26. but an application can use Load("pattern=" + x) as an escaping mechanism
  27. to ensure that x is not interpreted as a query operator if it contains '='.
  28. All other query operators are reserved for future use and currently
  29. cause Load to report an error.
  30. The Package struct provides basic information about the package, including
  31. - ID, a unique identifier for the package in the returned set;
  32. - GoFiles, the names of the package's Go source files;
  33. - Imports, a map from source import strings to the Packages they name;
  34. - Types, the type information for the package's exported symbols;
  35. - Syntax, the parsed syntax trees for the package's source code; and
  36. - TypesInfo, the result of a complete type-check of the package syntax trees.
  37. (See the documentation for type Package for the complete list of fields
  38. and more detailed descriptions.)
  39. For example,
  40. Load(nil, "bytes", "unicode...")
  41. returns four Package structs describing the standard library packages
  42. bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern
  43. can match multiple packages and that a package might be matched by
  44. multiple patterns: in general it is not possible to determine which
  45. packages correspond to which patterns.
  46. Note that the list returned by Load contains only the packages matched
  47. by the patterns. Their dependencies can be found by walking the import
  48. graph using the Imports fields.
  49. The Load function can be configured by passing a pointer to a Config as
  50. the first argument. A nil Config is equivalent to the zero Config, which
  51. causes Load to run in [LoadFiles] mode, collecting minimal information.
  52. See the documentation for type Config for details.
  53. As noted earlier, the Config.Mode controls the amount of detail
  54. reported about the loaded packages. See the documentation for type LoadMode
  55. for details.
  56. Most tools should pass their command-line arguments (after any flags)
  57. uninterpreted to Load, so that it can interpret them
  58. according to the conventions of the underlying build system.
  59. See the Example function for typical usage.
  60. # The driver protocol
  61. Load may be used to load Go packages even in Go projects that use
  62. alternative build systems, by installing an appropriate "driver"
  63. program for the build system and specifying its location in the
  64. GOPACKAGESDRIVER environment variable.
  65. For example,
  66. https://github.com/bazelbuild/rules_go/wiki/Editor-and-tool-integration
  67. explains how to use the driver for Bazel.
  68. The driver program is responsible for interpreting patterns in its
  69. preferred notation and reporting information about the packages that
  70. those patterns identify. Drivers must also support the special "file="
  71. and "pattern=" patterns described above.
  72. The patterns are provided as positional command-line arguments. A
  73. JSON-encoded [DriverRequest] message providing additional information
  74. is written to the driver's standard input. The driver must write a
  75. JSON-encoded [DriverResponse] message to its standard output. (This
  76. message differs from the JSON schema produced by 'go list'.)
  77. The value of the PWD environment variable seen by the driver process
  78. is the preferred name of its working directory. (The working directory
  79. may have other aliases due to symbolic links; see the comment on the
  80. Dir field of [exec.Cmd] for related information.)
  81. When the driver process emits in its response the name of a file
  82. that is a descendant of this directory, it must use an absolute path
  83. that has the value of PWD as a prefix, to ensure that the returned
  84. filenames satisfy the original query.
  85. */
  86. package packages // import "golang.org/x/tools/go/packages"
  87. /*
  88. Motivation and design considerations
  89. The new package's design solves problems addressed by two existing
  90. packages: go/build, which locates and describes packages, and
  91. golang.org/x/tools/go/loader, which loads, parses and type-checks them.
  92. The go/build.Package structure encodes too much of the 'go build' way
  93. of organizing projects, leaving us in need of a data type that describes a
  94. package of Go source code independent of the underlying build system.
  95. We wanted something that works equally well with go build and vgo, and
  96. also other build systems such as Bazel and Blaze, making it possible to
  97. construct analysis tools that work in all these environments.
  98. Tools such as errcheck and staticcheck were essentially unavailable to
  99. the Go community at Google, and some of Google's internal tools for Go
  100. are unavailable externally.
  101. This new package provides a uniform way to obtain package metadata by
  102. querying each of these build systems, optionally supporting their
  103. preferred command-line notations for packages, so that tools integrate
  104. neatly with users' build environments. The Metadata query function
  105. executes an external query tool appropriate to the current workspace.
  106. Loading packages always returns the complete import graph "all the way down",
  107. even if all you want is information about a single package, because the query
  108. mechanisms of all the build systems we currently support ({go,vgo} list, and
  109. blaze/bazel aspect-based query) cannot provide detailed information
  110. about one package without visiting all its dependencies too, so there is
  111. no additional asymptotic cost to providing transitive information.
  112. (This property might not be true of a hypothetical 5th build system.)
  113. In calls to TypeCheck, all initial packages, and any package that
  114. transitively depends on one of them, must be loaded from source.
  115. Consider A->B->C->D->E: if A,C are initial, A,B,C must be loaded from
  116. source; D may be loaded from export data, and E may not be loaded at all
  117. (though it's possible that D's export data mentions it, so a
  118. types.Package may be created for it and exposed.)
  119. The old loader had a feature to suppress type-checking of function
  120. bodies on a per-package basis, primarily intended to reduce the work of
  121. obtaining type information for imported packages. Now that imports are
  122. satisfied by export data, the optimization no longer seems necessary.
  123. Despite some early attempts, the old loader did not exploit export data,
  124. instead always using the equivalent of WholeProgram mode. This was due
  125. to the complexity of mixing source and export data packages (now
  126. resolved by the upward traversal mentioned above), and because export data
  127. files were nearly always missing or stale. Now that 'go build' supports
  128. caching, all the underlying build systems can guarantee to produce
  129. export data in a reasonable (amortized) time.
  130. Test "main" packages synthesized by the build system are now reported as
  131. first-class packages, avoiding the need for clients (such as go/ssa) to
  132. reinvent this generation logic.
  133. One way in which go/packages is simpler than the old loader is in its
  134. treatment of in-package tests. In-package tests are packages that
  135. consist of all the files of the library under test, plus the test files.
  136. The old loader constructed in-package tests by a two-phase process of
  137. mutation called "augmentation": first it would construct and type check
  138. all the ordinary library packages and type-check the packages that
  139. depend on them; then it would add more (test) files to the package and
  140. type-check again. This two-phase approach had four major problems:
  141. 1) in processing the tests, the loader modified the library package,
  142. leaving no way for a client application to see both the test
  143. package and the library package; one would mutate into the other.
  144. 2) because test files can declare additional methods on types defined in
  145. the library portion of the package, the dispatch of method calls in
  146. the library portion was affected by the presence of the test files.
  147. This should have been a clue that the packages were logically
  148. different.
  149. 3) this model of "augmentation" assumed at most one in-package test
  150. per library package, which is true of projects using 'go build',
  151. but not other build systems.
  152. 4) because of the two-phase nature of test processing, all packages that
  153. import the library package had to be processed before augmentation,
  154. forcing a "one-shot" API and preventing the client from calling Load
  155. in several times in sequence as is now possible in WholeProgram mode.
  156. (TypeCheck mode has a similar one-shot restriction for a different reason.)
  157. Early drafts of this package supported "multi-shot" operation.
  158. Although it allowed clients to make a sequence of calls (or concurrent
  159. calls) to Load, building up the graph of Packages incrementally,
  160. it was of marginal value: it complicated the API
  161. (since it allowed some options to vary across calls but not others),
  162. it complicated the implementation,
  163. it cannot be made to work in Types mode, as explained above,
  164. and it was less efficient than making one combined call (when this is possible).
  165. Among the clients we have inspected, none made multiple calls to load
  166. but could not be easily and satisfactorily modified to make only a single call.
  167. However, applications changes may be required.
  168. For example, the ssadump command loads the user-specified packages
  169. and in addition the runtime package. It is tempting to simply append
  170. "runtime" to the user-provided list, but that does not work if the user
  171. specified an ad-hoc package such as [a.go b.go].
  172. Instead, ssadump no longer requests the runtime package,
  173. but seeks it among the dependencies of the user-specified packages,
  174. and emits an error if it is not found.
  175. Questions & Tasks
  176. - Add GOARCH/GOOS?
  177. They are not portable concepts, but could be made portable.
  178. Our goal has been to allow users to express themselves using the conventions
  179. of the underlying build system: if the build system honors GOARCH
  180. during a build and during a metadata query, then so should
  181. applications built atop that query mechanism.
  182. Conversely, if the target architecture of the build is determined by
  183. command-line flags, the application can pass the relevant
  184. flags through to the build system using a command such as:
  185. myapp -query_flag="--cpu=amd64" -query_flag="--os=darwin"
  186. However, this approach is low-level, unwieldy, and non-portable.
  187. GOOS and GOARCH seem important enough to warrant a dedicated option.
  188. - How should we handle partial failures such as a mixture of good and
  189. malformed patterns, existing and non-existent packages, successful and
  190. failed builds, import failures, import cycles, and so on, in a call to
  191. Load?
  192. - Support bazel, blaze, and go1.10 list, not just go1.11 list.
  193. - Handle (and test) various partial success cases, e.g.
  194. a mixture of good packages and:
  195. invalid patterns
  196. nonexistent packages
  197. empty packages
  198. packages with malformed package or import declarations
  199. unreadable files
  200. import cycles
  201. other parse errors
  202. type errors
  203. Make sure we record errors at the correct place in the graph.
  204. - Missing packages among initial arguments are not reported.
  205. Return bogus packages for them, like golist does.
  206. - "undeclared name" errors (for example) are reported out of source file
  207. order. I suspect this is due to the breadth-first resolution now used
  208. by go/types. Is that a bug? Discuss with gri.
  209. */