internal/lsp: format files that parse in packages with parse errors

Updates golang/go#31291

Change-Id: Ibbd0b6cef9b9ec588c8a2e0c5e7ee6e3512b8a22
Reviewed-on: https://go-review.googlesource.com/c/tools/+/188767
Reviewed-by: Ian Cottrell <iancottrell@google.com>
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
diff --git a/internal/lsp/source/format.go b/internal/lsp/source/format.go
index 1f100c5..1296c19 100644
--- a/internal/lsp/source/format.go
+++ b/internal/lsp/source/format.go
@@ -30,7 +30,7 @@
 		return nil, err
 	}
 	pkg := f.GetPackage(ctx)
-	if hasListErrors(pkg.GetErrors()) || hasParseErrors(pkg.GetErrors()) {
+	if hasListErrors(pkg.GetErrors()) || hasParseErrors(pkg, f.URI()) {
 		// Even if this package has list or parse errors, this file may not
 		// have any parse errors and can still be formatted. Using format.Node
 		// on an ast with errors may result in code being added or removed.
@@ -104,7 +104,6 @@
 	if err != nil {
 		return nil, err
 	}
-
 	return computeTextEdits(ctx, f, string(formatted)), nil
 }
 
@@ -174,9 +173,11 @@
 	return edits, editsPerFix, nil
 }
 
-func hasParseErrors(errors []packages.Error) bool {
-	for _, err := range errors {
-		if err.Kind == packages.ParseError {
+// hasParseErrors returns true if the given file has parse errors.
+func hasParseErrors(pkg Package, uri span.URI) bool {
+	for _, err := range pkg.GetErrors() {
+		spn := packagesErrorSpan(err)
+		if spn.URI() == uri && err.Kind == packages.ParseError {
 			return true
 		}
 	}