gopls/internal/lsp/cache: don't record edges to invalid packages

The importer assumes that packages have non-empty package path and name.
Enforce this invariant when loading metadata.

Fixes golang/go#60952

Change-Id: I2f4f18e475ba306d93c8b649d19897a584e5ba19
Reviewed-on: https://go-review.googlesource.com/c/tools/+/505219
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Alan Donovan <adonovan@google.com>
Run-TryBot: Robert Findley <rfindley@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
(cherry picked from commit c8278fe909aba46f3cad6253a0d3b1303a16ad72)
Reviewed-on: https://go-review.googlesource.com/c/tools/+/505222
diff --git a/go/packages/golist.go b/go/packages/golist.go
index e84f19d..5823003 100644
--- a/go/packages/golist.go
+++ b/go/packages/golist.go
@@ -671,6 +671,9 @@
 		// Temporary work-around for golang/go#39986. Parse filenames out of
 		// error messages. This happens if there are unrecoverable syntax
 		// errors in the source, so we can't match on a specific error message.
+		//
+		// TODO(rfindley): remove this heuristic, in favor of considering
+		// InvalidGoFiles from the list driver.
 		if err := p.Error; err != nil && state.shouldAddFilenameFromError(p) {
 			addFilenameFromPos := func(pos string) bool {
 				split := strings.Split(pos, ":")
diff --git a/gopls/internal/lsp/cache/load.go b/gopls/internal/lsp/cache/load.go
index da985a8..eb302b7 100644
--- a/gopls/internal/lsp/cache/load.go
+++ b/gopls/internal/lsp/cache/load.go
@@ -528,9 +528,21 @@
 			continue
 		}
 
+		buildMetadata(updates, imported, loadDir, false) // only top level packages can be standalone
+
+		// Don't record edges to packages with no name, as they cause trouble for
+		// the importer (golang/go#60952).
+		//
+		// However, we do want to insert these packages into the update map
+		// (buildMetadata above), so that we get type-checking diagnostics for the
+		// invalid packages.
+		if imported.Name == "" {
+			depsByImpPath[importPath] = "" // missing
+			continue
+		}
+
 		depsByImpPath[importPath] = PackageID(imported.ID)
 		depsByPkgPath[PackagePath(imported.PkgPath)] = PackageID(imported.ID)
-		buildMetadata(updates, imported, loadDir, false) // only top level packages can be standalone
 	}
 	m.DepsByImpPath = depsByImpPath
 	m.DepsByPkgPath = depsByPkgPath