go/packages doc文档

Package packages loads Go packages for inspection and analysis.
Package包加载Go包进行检查和分析。

The Load function takes as input a list of patterns and return a list of Package
structs describing individual packages matched by those patterns.
Load函数将模式列表作为输入,并返回一个包结构列表,该列表描述与这些模式匹配的各个包。
The LoadMode controls the amount of detail in the loaded packages.
LoadMode控制加载包中的详细信息。

Load passes most patterns directly to the underlying build tool,
but all patterns with the prefix “query=”, where query is a
non-empty string of letters from [a-z], are reserved and may be
interpreted as query operators.
Load将大多数模式直接传递给底层构建工具,但所有前缀为“query=”(其中query是来自[a-z]的非空字母字符串)的模式都是保留的,并且可能被解释为查询运算符。

Two query operators are currently supported: “file” and “pattern”.
当前支持两个查询运算符:“file”和“pattern”。

The query “file=path/to/file.go” matches the package or packages enclosing
the Go source file path/to/file.go. For example “file=~/go/src/fmt/print.go”
might return the packages “fmt” and “fmt [fmt.test]”.
查询“file=path/to/file.go”会匹配与包含go源文件path/to/file.go的一个或多个包。例如,“file=~/go/src/fmt/print.go”可能会返回包“fmt”和“fmt[fmt.test]”。

The query “pattern=string” causes “string” to be passed directly to
the underlying build tool. In most cases this is unnecessary,
but an application can use Load(“pattern=” + x) as an escaping mechanism
to ensure that x is not interpreted as a query operator if it contains ‘=’.
查询“pattern=string”导致将“string”直接传递给底层构建工具。在大多数情况下,这是不必要的,但应用程序可以使用Load(“pattern=”+x)作为转义机制,以确保x在包含“=”时不会被解释为查询运算符。

All other query operators are reserved for future use and currently
cause Load to report an error.
所有其他查询运算符保留供将来使用,并且当前导致Load报告错误。

The Package struct provides basic information about the package, including
Package结构体提供有关包的基本信息,包括:

  • ID, a unique identifier for the package in the returned set; -ID,返回集中包的唯一标识符;
  • GoFiles, the names of the package’s Go source files; -GoFiles,包的Go源文件的名称;
  • Imports, a map from source import strings to the Packages they name; -导入,从源导入字符串到它们命名的包的映射;
  • Types, the type information for the package’s exported symbols; -类型,包导出符号的类型信息;
  • Syntax, the parsed syntax trees for the package’s source code; and -语法,包源代码的已解析语法树;和
  • TypeInfo, the result of a complete type-check of the package syntax trees. -TypeInfo,包语法树的完整类型检查的结果。

(See the documentation for type Package for the complete list of fields and more detailed descriptions.)
(有关字段的完整列表和更详细的说明,请参阅type Package文档。)

For example,例如

Load(nil, "bytes", "unicode...")

returns four Package structs describing the standard library packages
bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern
can match multiple packages and that a package might be matched by
multiple patterns: in general it is not possible to determine which
packages correspond to which patterns.
返回四个Package结构体,描述标准库包bytes、unicode、unicode/utf16和unicode/utf8。请注意,一个模式可以匹配多个包,并且一个包可能由多个模式匹配:通常无法确定哪些包对应于哪些模式。

Note that the list returned by Load contains only the packages matched
by the patterns. Their dependencies can be found by walking the import
graph using the Imports fields.
请注意,Load返回的列表仅包含与模式匹配的包。通过使用Imports字段遍历导入图,可以找到它们的依赖关系。

The Load function can be configured by passing a pointer to a Config as
the first argument. A nil Config is equivalent to the zero Config, which
causes Load to run in LoadFiles mode, collecting minimal information.
See the documentation for type Config for details.
可以通过将指向Config的指针作为第一个参数来配置Load函数。nil配置相当于zero配置,它使Load以LoadFiles模式运行,收集最少的信息。有关详细信息,请参阅Config类型的文档。

As noted earlier, the Config.Mode controls the amount of detail
reported about the loaded packages. See the documentation for type LoadMode
for details.
如前所述, Config.Mode控制有关加载包的详细报告。有关详细信息,请参阅LoadMode类型的文档。

Most tools should pass their command-line arguments (after any flags)
uninterpreted to the loader, so that the loader can interpret them
according to the conventions of the underlying build system.
See the Example function for typical usage.
大多数工具都应该将其未解释的命令行参数(在任何标志之后)传递给loader,以便loader可以根据底层构建系统的约定对其进行解释。有关类型的用法,请参见示例函数。

Motivation and design considerations
动机和设计考虑

The new package’s design solves problems addressed by two existing
packages: go/build, which locates and describes packages, and
golang.org/x/tools/go/loader, which loads, parses and type-checks them.
The go/build.Package structure encodes too much of the ‘go build’ way
of organizing projects, leaving us in need of a data type that describes a
package of Go source code independent of the underlying build system.
We wanted something that works equally well with go build and vgo, and
also other build systems such as Bazel and Blaze, making it possible to
construct analysis tools that work in all these environments.
新包的设计通过两个现有包解决问题:go/build定位和描述包, golang.org/x/tools/go/loader,用于加载、解析和类型检查它们。go/build.Package 结构体对组织项目的“go-build”方式进行了太多的编码,这使得我们需要一种数据类型来描述独立于底层构建系统的go源代码包。我们希望能够与go build和vgo以及其他构建系统(如Bazel和Blaze)一起工作,从而能够构建在所有这些环境中都能工作的分析工具。
Tools such as errcheck and staticcheck were essentially unavailable to
the Go community at Google, and some of Google’s internal tools for Go
are unavailable externally.
诸如errcheck和staticcheck之类的工具在Google的Go社区基本上是不可用的,而Google的一些Go内部工具在外部是不可用的。
This new package provides a uniform way to obtain package metadata by
querying each of these build systems, optionally supporting their
preferred command-line notations for packages, so that tools integrate
neatly with users’ build environments. The Metadata query function
executes an external query tool appropriate to the current workspace.
这个新的包提供了一种统一的方法,通过查询每个构建系统来获取包元数据,可以选择支持其首选的包命令行符号,以便工具能够与用户的构建环境巧妙地集成。元数据查询功能执行适用于当前工作区的外部查询工具。

Loading packages always returns the complete import graph “all the way down”,
even if all you want is information about a single package, because the query
mechanisms of all the build systems we currently support ({go,vgo} list, and
blaze/bazel aspect-based query) cannot provide detailed information
about one package without visiting all its dependencies too, so there is
no additional asymptotic cost to providing transitive information.
(This property might not be true of a hypothetical 5th build system.)
加载包总是“一路向下”返回完整的导入图,即使您只需要关于单个包的信息,因为我们当前支持的所有构建系统的查询机制({go,vgo}list,和blaze/bazel基于方面的查询)也无法在不访问其所有依赖项的情况下提供关于一个包的详细信息,因此,提供传递信息不需要额外的渐近代价。(对于假设的第5个构建系统,此属性可能不正确。)

In calls to TypeCheck, all initial packages, and any package that
transitively depends on one of them, must be loaded from source.
Consider A->B->C->D->E: if A,C are initial, A,B,C must be loaded from
source; D may be loaded from export data, and E may not be loaded at all
(though it’s possible that D’s export data mentions it, so a
types.Package may be created for it and exposed.)
在对TypeCheck的调用中,所有初始包以及任何可传递地依赖于其中一个包的包都必须从源代码加载。考虑A->B->C->D->E:如果A、C是初始值,则A、B、C必须从源加载;D可能从导出数据加载,而E可能根本不会加载(虽然D的导出数据可能会提到它,因此可能会为其创建一个types.Package并将其公开)

The old loader had a feature to suppress type-checking of function
bodies on a per-package basis, primarily intended to reduce the work of
obtaining type information for imported packages. Now that imports are
satisfied by export data, the optimization no longer seems necessary.
旧的loader有一个功能,可以在每个包的基础上抑制功能体的类型检查,主要目的是减少获取导入包的类型信息的工作。既然导出数据满足了导入的要求,那么优化似乎就没有必要了。

Despite some early attempts, the old loader did not exploit export data,
instead always using the equivalent of WholeProgram mode. This was due
to the complexity of mixing source and export data packages (now
resolved by the upward traversal mentioned above), and because export data
files were nearly always missing or stale. Now that ‘go build’ supports
caching, all the underlying build systems can guarantee to produce
export data in a reasonable (amortized) time.
尽管有一些早期的尝试,旧的loader 并没有利用导出数据,而是始终使用等效的WholeProgram模式。这是由于混合源数据包和导出数据包的复杂性(现在通过上面提到的向上遍历解决),以及导出数据文件几乎总是丢失或过时。既然“go build”支持缓存,所有底层构建系统都可以保证在合理的(摊销)时间内生成导出数据。

Test “main” packages synthesized by the build system are now reported as
first-class packages, avoiding the need for clients (such as go/ssa) to
reinvent this generation logic.
构建系统合成的测试“main”包现在报告为first-class包,避免了客户机(如go/ssa)重新创建此生成逻辑的需要。

One way in which go/packages is simpler than the old loader is in its
treatment of in-package tests. In-package tests are packages that
consist of all the files of the library under test, plus the test files.
The old loader constructed in-package tests by a two-phase process of
mutation called “augmentation”: first it would construct and type check
all the ordinary library packages and type-check the packages that
depend on them; then it would add more (test) files to the package and
type-check again. This two-phase approach had four major problems:
go/packages比旧loader 更简单的一种方法是处理包内测试。包内测试是由被测库的所有文件以及测试文件组成的包。旧loader通过称为“扩充”的两阶段变异过程在包测试中构建:首先,它将构建所有普通库包并进行类型检查,并对依赖于它们的包进行类型检查;然后它会向包中添加更多(测试)文件,并再次进行类型检查。这种两阶段方法有四个主要问题:

  1. in processing the tests, the loader modified the library package,
    leaving no way for a client application to see both the test
    package and the library package; one would mutate into the other.
    1) 在处理测试时,加载程序修改了库包,客户端应用程序无法同时看到测试包和库包;一个会变异成另一个。
  2. because test files can declare additional methods on types defined in
    the library portion of the package, the dispatch of method calls in
    the library portion was affected by the presence of the test files.
    This should have been a clue that the packages were logically
    different.
    2) 由于测试文件可以对包的库部分中定义的类型声明其他方法,因此库部分中方法调用的调度会受到测试文件存在的影响。这应该是两个包在逻辑上不同的线索。
  3. this model of “augmentation” assumed at most one in-package test
    per library package, which is true of projects using ‘go build’,
    but not other build systems.
    3) 这种“扩充”模型假设每个库包最多进行一次包内测试,这适用于使用“go build”的项目,但不适用于其他构建系统。
  4. because of the two-phase nature of test processing, all packages that
    import the library package had to be processed before augmentation,
    forcing a “one-shot” API and preventing the client from calling Load
    in several times in sequence as is now possible in WholeProgram mode.
    (TypeCheck mode has a similar one-shot restriction for a different reason.)
    4) 由于测试处理的两个阶段性质,所有导入库包的包都必须在扩充之前进行处理,从而强制使用“一次性”API,并防止客户端按顺序多次调用Load,这在整个程序模式下是可能的。(由于不同的原因,TypeCheck模式具有类似的一次性限制。)

Early drafts of this package supported “multi-shot” operation.
该软件包的早期草稿支持“多命中”操作。
Although it allowed clients to make a sequence of calls (or concurrent
calls) to Load, building up the graph of Packages incrementally,
it was of marginal value: it complicated the API
(since it allowed some options to vary across calls but not others),
it complicated the implementation,
it cannot be made to work in Types mode, as explained above,
and it was less efficient than making one combined call (when this is possible).
尽管它允许客户端进行一系列调用(或并发调用)来加载,以增量方式构建包图,但它的价值微乎其微:它使API变得复杂(因为它允许某些选项在调用之间变化,但不允许其他选项变化),它使实现变得复杂,无法使其在类型模式下工作,如上所述,而且它的效率低于一次组合调用(如果可能的话)。
Among the clients we have inspected, none made multiple calls to load
but could not be easily and satisfactorily modified to make only a single call.
However, applications changes may be required.
在我们检查过的客户中,没有一个进行了多次调用以加载,但无法轻松且令人满意地修改为仅进行一次调用。但是,可能需要更改应用程序。
For example, the ssadump command loads the user-specified packages
and in addition the runtime package. It is tempting to simply append
“runtime” to the user-provided list, but that does not work if the user
specified an ad-hoc package such as [a.go b.go].
例如,ssadump命令加载用户指定的包以及运行时包。很容易将“runtime”简单地附加到用户提供的列表中,但如果用户指定了一个特殊的包,例如[a.go b.go],则这不起作用。
Instead, ssadump no longer requests the runtime package,
but seeks it among the dependencies of the user-specified packages,
and emits an error if it is not found.
相反,ssadump不再请求运行时包,而是在用户指定包的依赖项中查找它,如果找不到,则发出错误。

Overlays: The Overlay field in the Config allows providing alternate contents
for Go source files, by providing a mapping from file path to contents.
go/packages will pull in new imports added in overlay files when go/packages
is run in LoadImports mode or greater.
Overlay support for the go list driver isn’t complete yet: if the file doesn’t
exist on disk, it will only be recognized in an overlay if it is a non-test file
and the package would be reported even without the overlay.
Overlays:通过提供从文件路径到内容的映射,Config中的Overlay 字段允许为Go源文件提供备用内容。在LoadImports模式或更高模式下运行go/packages时,go/packages将引入覆盖文件中添加的新导入。对go list驱动程序的覆盖支持尚未完成:如果文件在磁盘上不存在,则只有在覆盖中才能识别该文件(如果它是非测试文件),并且即使没有覆盖,也会报告包。

Questions & Tasks

  • Add GOARCH/GOOS?
    They are not portable concepts, but could be made portable.
    Our goal has been to allow users to express themselves using the conventions
    of the underlying build system: if the build system honors GOARCH
    during a build and during a metadata query, then so should
    applications built atop that query mechanism.
    Conversely, if the target architecture of the build is determined by
    command-line flags, the application can pass the relevant
    flags through to the build system using a command such as:
    myapp -query_flag=“–cpu=amd64” -query_flag=“–os=darwin”
    它们不是可移植的概念,但可以进行移植。我们的目标是允许用户使用底层构建系统的约定来表达自己:如果构建系统在构建和元数据查询期间遵守GOARCH,那么在该查询机制之上构建的应用程序也应该遵守GOARCH。相反,如果构建的目标体系结构由命令行标志确定,则应用程序可以使用以下命令将相关标志传递给构建系统:myapp-query\u flag=“–cpu=amd64”-query\u flag=“–os=darwin”
    However, this approach is low-level, unwieldy, and non-portable.
    GOOS and GOARCH seem important enough to warrant a dedicated option.
    然而,这种方法是低级的、笨拙的和不可移植的。GOOS和GOARCH似乎足够重要,可以保证有一个专门的选项。

  • How should we handle partial failures such as a mixture of good and
    malformed patterns, existing and non-existent packages, successful and
    failed builds, import failures, import cycles, and so on, in a call to
    Load?
    我们应该如何在一个Load调用中处理部分失败,例如良好模式和错误模式、现有包和不存在包、成功构建和失败构建、导入失败、导入周期等的混合?

  • Support bazel, blaze, and go1.10 list, not just go1.11 list.
    支持bazel、blaze和go1.10列表,而不仅仅是go1.11列表。

  • Handle (and test) various partial success cases, e.g.
    a mixture of good packages and:
    invalid patterns
    nonexistent packages
    empty packages
    packages with malformed package or import declarations
    unreadable files
    import cycles
    other parse errors
    type errors
    Make sure we record errors at the correct place in the graph.
    处理(并测试)各种部分成功案例,例如,好的软件包和:
    无效的模式
    不存在的包
    空软件包
    包或导入声明格式错误的包
    无法读取的文件
    导入周期
    其他分析错误
    类型错误
    确保在图表中的正确位置记录错误。

  • Missing packages among initial arguments are not reported.
    Return bogus packages for them, like golist does.
    未报告初始参数中缺少的包。
    像高尔夫球手一样,为他们归还假包裹。

  • “undeclared name” errors (for example) are reported out of source file
    order. I suspect this is due to the breadth-first resolution now used
    by go/types. Is that a bug? Discuss with gri.
    “未声明的名称”错误(例如)的报告顺序与源文件的顺序不同。我怀疑这是由于go/types现在使用的广度优先分辨率造成的。那是虫子吗?与gri讨论。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值