x/tools/cmd/gopls: prevent nil pointer dereferences

The `files` slice is used twice. First it's used to get all results from `ph.Parse`, and then it's reused to filter all `nil` values (which may have been returned by the `ph.Parse` method).

After the loop to "filter" out all the `nil` values, we also need to strip the remaining values.

I also changed the ordering so that we first check the errors and
only then perform this loop. That way the code will return earlier
when the context was canceled.

Partially fixes #33531 by prevention the panic reported in that issue.

Change-Id: I09478e765adcd0384ec4745921eb5c5aea405ef2
Reviewed-on: https://go-review.googlesource.com/c/tools/+/189397
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/internal/lsp/cache/check.go b/internal/lsp/cache/check.go
index c571cf5..3bc6f05 100644
--- a/internal/lsp/cache/check.go
+++ b/internal/lsp/cache/check.go
@@ -146,13 +146,6 @@
 	}
 	wg.Wait()
 
-	var i int
-	for _, f := range files {
-		if f != nil {
-			files[i] = f
-			i++
-		}
-	}
 	for _, err := range parseErrors {
 		if err == context.Canceled {
 			return nil, err
@@ -162,6 +155,15 @@
 		}
 	}
 
+	var i int
+	for _, f := range files {
+		if f != nil {
+			files[i] = f
+			i++
+		}
+	}
+	files = files[:i]
+
 	// Use the default type information for the unsafe package.
 	if meta.pkgPath == "unsafe" {
 		pkg.types = types.Unsafe