internal/lsp: don't diagnose/analyze intermediate test variants

As part of debugging CL 324394, I found that we were returning
intermediate test variant packages in packageHandlesForFile. This
happened because, even though these packages were not workspace
packages, they would still be picked up by the file URIs -> IDs map.

This is typically not a problem when we are picking out the widest or
narrowest package for a specific request, but for diagnostics on changed
files, we run them on all of the possible packages. This also led to us
analyzing these intermediate test variant packages. Filter them out, as
we will never want them for this purpose.

Change-Id: Ifa780cd104f9c4b3fe6c530402956e2337c8fcdc
Reviewed-on: https://go-review.googlesource.com/c/tools/+/324689
Trust: Rebecca Stambler <rstambler@golang.org>
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
diff --git a/internal/lsp/cache/load.go b/internal/lsp/cache/load.go
index 56a4e72..8387915 100644
--- a/internal/lsp/cache/load.go
+++ b/internal/lsp/cache/load.go
@@ -45,6 +45,11 @@
 
 	// config is the *packages.Config associated with the loaded package.
 	config *packages.Config
+
+	// isIntermediateTestVariant reports whether the given package is an
+	// intermediate test variant, e.g.
+	// "golang.org/x/tools/internal/lsp/cache [golang.org/x/tools/internal/lsp/source.test]".
+	isIntermediateTestVariant bool
 }
 
 // load calls packages.Load for the given scopes, updating package metadata,
@@ -463,6 +468,7 @@
 			s.workspacePackages[m.id] = m.forTest
 		default:
 			// A test variant of some intermediate package. We don't care about it.
+			m.isIntermediateTestVariant = true
 		}
 	}
 	return m, nil
diff --git a/internal/lsp/cache/snapshot.go b/internal/lsp/cache/snapshot.go
index a47cc21..111ff02 100644
--- a/internal/lsp/cache/snapshot.go
+++ b/internal/lsp/cache/snapshot.go
@@ -525,6 +525,11 @@
 	// Get the list of IDs from the snapshot again, in case it has changed.
 	var phs []*packageHandle
 	for _, id := range s.getIDsForURI(uri) {
+		// Filter out any intermediate test variants. We typically aren't
+		// interested in these packages for file= style queries.
+		if m := s.getMetadata(id); m != nil && m.isIntermediateTestVariant {
+			continue
+		}
 		var parseModes []source.ParseMode
 		switch mode {
 		case source.TypecheckAll: