Skip to content

Commit

Permalink
go/packages: fix load with NeedTypes but not NeedImports
Browse files Browse the repository at this point in the history
Fixes golang/go#45584.

Change-Id: I65238cc3bdc640bb044c615a5699e8d3cfa39db0
Reviewed-on: https://go-review.googlesource.com/c/tools/+/310512
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
Reviewed-by: Austin Clements <austin@google.com>
Auto-Submit: Russ Cox <rsc@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
  • Loading branch information
rsc authored and gopherbot committed Mar 25, 2022
1 parent 11930bd commit f4515dd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
15 changes: 3 additions & 12 deletions go/packages/packages.go
Expand Up @@ -1237,7 +1237,7 @@ func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error
return nil, fmt.Errorf("reading %s: %v", lpkg.ExportFile, err)
}
if viewLen != len(view) {
log.Fatalf("Unexpected package creation during export data loading")
log.Panicf("golang.org/x/tools/go/packages: unexpected new packages during load of %s", lpkg.PkgPath)
}

lpkg.Types = tpkg
Expand All @@ -1248,17 +1248,8 @@ func (ld *loader) loadFromExportData(lpkg *loaderPackage) (*types.Package, error

// impliedLoadMode returns loadMode with its dependencies.
func impliedLoadMode(loadMode LoadMode) LoadMode {
if loadMode&NeedTypesInfo != 0 && loadMode&NeedImports == 0 {
// If NeedTypesInfo, go/packages needs to do typechecking itself so it can
// associate type info with the AST. To do so, we need the export data
// for dependencies, which means we need to ask for the direct dependencies.
// NeedImports is used to ask for the direct dependencies.
loadMode |= NeedImports
}

if loadMode&NeedDeps != 0 && loadMode&NeedImports == 0 {
// With NeedDeps we need to load at least direct dependencies.
// NeedImports is used to ask for the direct dependencies.
if loadMode&(NeedDeps|NeedTypes|NeedTypesInfo) != 0 {
// All these things require knowing the import graph.
loadMode |= NeedImports
}

Expand Down
8 changes: 8 additions & 0 deletions go/packages/packages_test.go
Expand Up @@ -2843,3 +2843,11 @@ func copyAll(srcPath, dstPath string) error {
return nil
})
}

func TestExportFile(t *testing.T) {
// This used to trigger the log.Fatal in loadFromExportData.
// See go.dev/issue/45584.
cfg := new(packages.Config)
cfg.Mode = packages.NeedTypes
packages.Load(cfg, "fmt")
}

0 comments on commit f4515dd

Please sign in to comment.