1 // Copyright 2019 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.
18 "golang.org/x/mod/module"
19 "golang.org/x/tools/go/packages"
20 "golang.org/x/tools/internal/event"
21 "golang.org/x/tools/internal/lsp/debug/tag"
22 "golang.org/x/tools/internal/lsp/source"
23 "golang.org/x/tools/internal/memoize"
24 "golang.org/x/tools/internal/span"
25 "golang.org/x/tools/internal/typesinternal"
26 errors "golang.org/x/xerrors"
29 type packageHandleKey string
31 type packageHandle struct {
32 handle *memoize.Handle
34 goFiles, compiledGoFiles []*parseGoHandle
36 // mode is the mode the files were parsed in.
39 // m is the metadata associated with the package.
42 // key is the hashed key for the package.
46 func (ph *packageHandle) packageKey() packageKey {
53 // packageData contains the data produced by type-checking a package.
54 type packageData struct {
59 // buildPackageHandle returns a packageHandle for a given package and mode.
60 func (s *snapshot) buildPackageHandle(ctx context.Context, id packageID, mode source.ParseMode) (*packageHandle, error) {
61 if ph := s.getPackage(id, mode); ph != nil {
65 // Build the packageHandle for this ID and its dependencies.
66 ph, deps, err := s.buildKey(ctx, id, mode)
71 // Do not close over the packageHandle or the snapshot in the Bind function.
72 // This creates a cycle, which causes the finalizers to never run on the handles.
73 // The possible cycles are:
75 // packageHandle.h.function -> packageHandle
76 // packageHandle.h.function -> snapshot -> packageHandle
82 h := s.generation.Bind(key, func(ctx context.Context, arg memoize.Arg) interface{} {
83 snapshot := arg.(*snapshot)
85 // Begin loading the direct dependencies, in parallel.
87 for _, dep := range deps {
89 go func(dep *packageHandle) {
90 dep.check(ctx, snapshot)
95 data := &packageData{}
96 data.pkg, data.err = typeCheck(ctx, snapshot, m, mode, deps)
97 // Make sure that the workers above have finished before we return,
98 // especially in case of cancellation.
105 // Cache the handle in the snapshot. If a package handle has already
106 // been cached, addPackage will return the cached value. This is fine,
107 // since the original package handle above will have no references and be
108 // garbage collected.
109 ph = s.addPackageHandle(ph)
114 // buildKey computes the key for a given packageHandle.
115 func (s *snapshot) buildKey(ctx context.Context, id packageID, mode source.ParseMode) (*packageHandle, map[packagePath]*packageHandle, error) {
116 m := s.getMetadata(id)
118 return nil, nil, errors.Errorf("no metadata for %s", id)
120 goFiles, err := s.parseGoHandles(ctx, m.goFiles, mode)
124 compiledGoFiles, err := s.parseGoHandles(ctx, m.compiledGoFiles, mode)
128 ph := &packageHandle{
131 compiledGoFiles: compiledGoFiles,
134 // Make sure all of the depList are sorted.
135 depList := append([]packageID{}, m.deps...)
136 sort.Slice(depList, func(i, j int) bool {
137 return depList[i] < depList[j]
140 deps := make(map[packagePath]*packageHandle)
142 // Begin computing the key by getting the depKeys for all dependencies.
143 var depKeys []packageHandleKey
144 for _, depID := range depList {
145 depHandle, err := s.buildPackageHandle(ctx, depID, s.workspaceParseMode(depID))
147 event.Error(ctx, fmt.Sprintf("%s: no dep handle for %s", id, depID), err, tag.Snapshot.Of(s.id))
148 if ctx.Err() != nil {
149 return nil, nil, ctx.Err()
151 // One bad dependency should not prevent us from checking the entire package.
152 // Add a special key to mark a bad dependency.
153 depKeys = append(depKeys, packageHandleKey(fmt.Sprintf("%s import not found", id)))
156 deps[depHandle.m.pkgPath] = depHandle
157 depKeys = append(depKeys, depHandle.key)
159 experimentalKey := s.View().Options().ExperimentalPackageCacheKey
160 ph.key = checkPackageKey(ctx, ph.m.id, compiledGoFiles, m.config, depKeys, mode, experimentalKey)
164 func (s *snapshot) workspaceParseMode(id packageID) source.ParseMode {
165 if _, ws := s.isWorkspacePackage(id); ws {
166 return source.ParseFull
168 return source.ParseExported
172 func checkPackageKey(ctx context.Context, id packageID, pghs []*parseGoHandle, cfg *packages.Config, deps []packageHandleKey, mode source.ParseMode, experimentalKey bool) packageHandleKey {
173 b := bytes.NewBuffer(nil)
174 b.WriteString(string(id))
175 if !experimentalKey {
176 // cfg was used to produce the other hashed inputs (package ID, parsed Go
177 // files, and deps). It should not otherwise affect the inputs to the type
178 // checker, so this experiment omits it. This should increase cache hits on
179 // the daemon as cfg contains the environment and working directory.
180 b.WriteString(hashConfig(cfg))
182 b.WriteByte(byte(mode))
183 for _, dep := range deps {
184 b.WriteString(string(dep))
186 for _, cgf := range pghs {
187 b.WriteString(cgf.file.FileIdentity().String())
189 return packageHandleKey(hashContents(b.Bytes()))
192 // hashConfig returns the hash for the *packages.Config.
193 func hashConfig(config *packages.Config) string {
194 b := bytes.NewBuffer(nil)
196 // Dir, Mode, Env, BuildFlags are the parts of the config that can change.
197 b.WriteString(config.Dir)
198 b.WriteString(string(rune(config.Mode)))
200 for _, e := range config.Env {
203 for _, f := range config.BuildFlags {
206 return hashContents(b.Bytes())
209 func (ph *packageHandle) Check(ctx context.Context, s source.Snapshot) (source.Package, error) {
210 return ph.check(ctx, s.(*snapshot))
213 func (ph *packageHandle) check(ctx context.Context, s *snapshot) (*pkg, error) {
214 v, err := ph.handle.Get(ctx, s.generation, s)
218 data := v.(*packageData)
219 return data.pkg, data.err
222 func (ph *packageHandle) CompiledGoFiles() []span.URI {
223 return ph.m.compiledGoFiles
226 func (ph *packageHandle) ID() string {
227 return string(ph.m.id)
230 func (ph *packageHandle) cached(g *memoize.Generation) (*pkg, error) {
231 v := ph.handle.Cached(g)
233 return nil, errors.Errorf("no cached type information for %s", ph.m.pkgPath)
235 data := v.(*packageData)
236 return data.pkg, data.err
239 func (s *snapshot) parseGoHandles(ctx context.Context, files []span.URI, mode source.ParseMode) ([]*parseGoHandle, error) {
240 pghs := make([]*parseGoHandle, 0, len(files))
241 for _, uri := range files {
242 fh, err := s.GetFile(ctx, uri)
246 pghs = append(pghs, s.parseGoHandle(ctx, fh, mode))
251 func typeCheck(ctx context.Context, snapshot *snapshot, m *metadata, mode source.ParseMode, deps map[packagePath]*packageHandle) (*pkg, error) {
252 ctx, done := event.Start(ctx, "cache.importer.typeCheck", tag.Package.Of(string(m.id)))
255 var rawErrors []error
256 for _, err := range m.errors {
257 rawErrors = append(rawErrors, err)
260 fset := snapshot.view.session.cache.fset
264 goFiles: make([]*source.ParsedGoFile, len(m.goFiles)),
265 compiledGoFiles: make([]*source.ParsedGoFile, len(m.compiledGoFiles)),
266 imports: make(map[packagePath]*pkg),
267 typesSizes: m.typesSizes,
268 typesInfo: &types.Info{
269 Types: make(map[ast.Expr]types.TypeAndValue),
270 Defs: make(map[*ast.Ident]types.Object),
271 Uses: make(map[*ast.Ident]types.Object),
272 Implicits: make(map[ast.Node]types.Object),
273 Selections: make(map[*ast.SelectorExpr]*types.Selection),
274 Scopes: make(map[ast.Node]*types.Scope),
277 // If this is a replaced module in the workspace, the version is
278 // meaningless, and we don't want clients to access it.
280 version := m.module.Version
281 if source.IsWorkspaceModuleVersion(version) {
284 pkg.version = &module.Version{
290 files = make([]*ast.File, len(m.compiledGoFiles))
291 parseErrors = make([]error, len(m.compiledGoFiles))
292 actualErrors = make([]error, len(m.compiledGoFiles))
298 for i, cgf := range m.compiledGoFiles {
300 go func(i int, cgf span.URI) {
302 fh, err := snapshot.GetFile(ctx, cgf)
304 actualErrors[i] = err
307 pgh := snapshot.parseGoHandle(ctx, fh, mode)
308 pgf, fixed, err := snapshot.parseGo(ctx, pgh)
310 actualErrors[i] = err
313 pkg.compiledGoFiles[i] = pgf
314 files[i], parseErrors[i], actualErrors[i] = pgf.File, pgf.ParseErr, err
317 skipTypeErrors = skipTypeErrors || fixed
321 for i, gf := range m.goFiles {
323 // We need to parse the non-compiled go files, but we don't care about their errors.
324 go func(i int, gf span.URI) {
326 fh, err := snapshot.GetFile(ctx, gf)
330 pgf, _ := snapshot.ParseGo(ctx, fh, mode)
335 for _, err := range actualErrors {
341 for _, e := range parseErrors {
343 rawErrors = append(rawErrors, e)
348 for _, f := range files {
356 // Use the default type information for the unsafe package.
357 if pkg.m.pkgPath == "unsafe" {
358 pkg.types = types.Unsafe
359 // Don't type check Unsafe: it's unnecessary, and doing so exposes a data
360 // race to Unsafe.completed.
362 } else if len(files) == 0 { // not the unsafe package, no parsed files
363 // Try to attach errors messages to the file as much as possible.
365 for _, e := range rawErrors {
366 srcErr, err := sourceError(ctx, snapshot, pkg, e)
371 pkg.errors = append(pkg.errors, srcErr)
376 return nil, errors.Errorf("no parsed files for package %s, expected: %v, list errors: %v", pkg.m.pkgPath, pkg.compiledGoFiles, rawErrors)
378 pkg.types = types.NewPackage(string(m.pkgPath), string(m.name))
381 cfg := &types.Config{
382 Error: func(e error) {
383 // If we have fixed parse errors in any of the files,
384 // we should hide type errors, as they may be completely nonsensical.
388 rawErrors = append(rawErrors, e)
390 Importer: importerFunc(func(pkgPath string) (*types.Package, error) {
391 // If the context was cancelled, we should abort.
392 if ctx.Err() != nil {
393 return nil, ctx.Err()
395 dep := resolveImportPath(pkgPath, pkg, deps)
397 return nil, errors.Errorf("no package for import %s", pkgPath)
399 if !isValidImport(m.pkgPath, dep.m.pkgPath) {
400 return nil, errors.Errorf("invalid use of internal package %s", pkgPath)
402 depPkg, err := dep.check(ctx, snapshot)
406 pkg.imports[depPkg.m.pkgPath] = depPkg
407 return depPkg.types, nil
410 // We want to type check cgo code if go/types supports it.
411 // We passed typecheckCgo to go/packages when we Loaded.
412 typesinternal.SetUsesCgo(cfg)
414 check := types.NewChecker(cfg, fset, pkg.types, pkg.typesInfo)
416 // Type checking errors are handled via the config, so ignore them here.
417 _ = check.Files(files)
418 // If the context was cancelled, we may have returned a ton of transient
419 // errors to the type checker. Swallow them.
420 if ctx.Err() != nil {
421 return nil, ctx.Err()
424 // We don't care about a package's errors unless we have parsed it in full.
425 if mode == source.ParseFull {
426 expandErrors(rawErrors)
427 for _, e := range rawErrors {
428 srcErr, err := sourceError(ctx, snapshot, pkg, e)
430 event.Error(ctx, "unable to compute error positions", err, tag.Package.Of(pkg.ID()))
433 pkg.errors = append(pkg.errors, srcErr)
434 if err, ok := e.(extendedError); ok {
435 pkg.typeErrors = append(pkg.typeErrors, err.primary)
443 type extendedError struct {
445 secondaries []types.Error
448 func (e extendedError) Error() string {
449 return e.primary.Error()
452 // expandErrors duplicates "secondary" errors by mapping them to their main
453 // error. Some errors returned by the type checker are followed by secondary
454 // errors which give more information about the error. These are errors in
455 // their own right, and they are marked by starting with \t. For instance, when
456 // there is a multiply-defined function, the secondary error points back to the
457 // definition first noticed.
459 // This code associates the secondary error with its primary error, which can
460 // then be used as RelatedInformation when the error becomes a diagnostic.
461 func expandErrors(errs []error) []error {
462 for i := 0; i < len(errs); {
463 e, ok := errs[i].(types.Error)
468 enew := extendedError{
472 for ; j < len(errs); j++ {
473 spl, ok := errs[j].(types.Error)
474 if !ok || len(spl.Msg) == 0 || spl.Msg[0] != '\t' {
477 enew.secondaries = append(enew.secondaries, spl)
485 // resolveImportPath resolves an import path in pkg to a package from deps.
486 // It should produce the same results as resolveImportPath:
487 // https://cs.opensource.google/go/go/+/master:src/cmd/go/internal/load/pkg.go;drc=641918ee09cb44d282a30ee8b66f99a0b63eaef9;l=990.
488 func resolveImportPath(importPath string, pkg *pkg, deps map[packagePath]*packageHandle) *packageHandle {
489 if dep := deps[packagePath(importPath)]; dep != nil {
492 // We may be in GOPATH mode, in which case we need to check vendor dirs.
493 searchDir := path.Dir(pkg.PkgPath())
495 vdir := packagePath(path.Join(searchDir, "vendor", importPath))
496 if vdep := deps[vdir]; vdep != nil {
500 // Search until Dir doesn't take us anywhere new, e.g. "." or "/".
501 next := path.Dir(searchDir)
502 if searchDir == next {
508 // Vendor didn't work. Let's try minimal module compatibility mode.
509 // In MMC, the packagePath is the canonical (.../vN/...) path, which
510 // is hard to calculate. But the go command has already resolved the ID
511 // to the non-versioned path, and we can take advantage of that.
512 for _, dep := range deps {
513 if dep.ID() == importPath {
520 func isValidImport(pkgPath, importPkgPath packagePath) bool {
521 i := strings.LastIndex(string(importPkgPath), "/internal/")
525 if pkgPath == "command-line-arguments" {
528 return strings.HasPrefix(string(pkgPath), string(importPkgPath[:i]))
531 // An importFunc is an implementation of the single-method
532 // types.Importer interface based on a function value.
533 type importerFunc func(path string) (*types.Package, error)
535 func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }