gopls/internal/lsp/source: filter intermediate test variants

This change ensures that intermediate test variant (ITV) packages
are filtered out before type checking in all calls to PackageForFile
or TypeCheck. There should never be any need to type check ITVs
in practice: they contain identical syntax to the regular package,
but differ in their import metadata. Technically this may affect
types of selectors (fields/methods) but we choose to ignore that
as it is bad programming and expensive to accommodate.

Details:
- MetadataForFile now sorts primarily by narrowest and
  secondarily by ITVs.
- source.NarrowestMetadataForFile is a convenience wrapper
  that selects the first non-ITV element.
- PackageForFile now always chooses the narrowest,
  and is renamed NarrowestPackageForFile.
  The sole use of widest, from renameOrdinary, was inlined.
  (One other was replaced by narrowest.)
- The PackageSelector enum (narrowes/widest) is gone.
- TODOs added to think about ITVs in the implicitly
  type checking methods.

Fixes golang/go#57795

Change-Id: Id1e95990bcbc830594d2d5acec7b4f93bc01a501
Reviewed-on: https://go-review.googlesource.com/c/tools/+/487095
Reviewed-by: Robert Findley <rfindley@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Alan Donovan <adonovan@google.com>
diff --git a/gopls/internal/lsp/cache/snapshot.go b/gopls/internal/lsp/cache/snapshot.go
index 510431a..294995a 100644
--- a/gopls/internal/lsp/cache/snapshot.go
+++ b/gopls/internal/lsp/cache/snapshot.go
@@ -811,14 +811,24 @@
 		s.unloadableFiles[uri] = struct{}{}
 	}
 
-	// Sort packages "narrowest" to "widest" (in practice: non-tests before tests).
+	// Sort packages "narrowest" to "widest" (in practice:
+	// non-tests before tests), and regular packages before
+	// their intermediate test variants (which have the same
+	// files but different imports).
 	sort.Slice(metas, func(i, j int) bool {
-		return len(metas[i].CompiledGoFiles) < len(metas[j].CompiledGoFiles)
+		x, y := metas[i], metas[j]
+		xfiles, yfiles := len(x.CompiledGoFiles), len(y.CompiledGoFiles)
+		if xfiles != yfiles {
+			return xfiles < yfiles
+		}
+		return boolLess(x.IsIntermediateTestVariant(), y.IsIntermediateTestVariant())
 	})
 
 	return metas, nil
 }
 
+func boolLess(x, y bool) bool { return !x && y } // false < true
+
 func (s *snapshot) ReverseDependencies(ctx context.Context, id PackageID, transitive bool) (map[PackageID]*source.Metadata, error) {
 	if err := s.awaitLoaded(ctx); err != nil {
 		return nil, err