internal/lsp/mod: handle nil pointer exception for empty go.mod files

Fixes golang/go#41005

Change-Id: I1745c5233977d1b5603cfbb334ff087649feaa80
Reviewed-on: https://go-review.googlesource.com/c/tools/+/250657
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/internal/lsp/mod/diagnostics.go b/internal/lsp/mod/diagnostics.go
index 57eb934..af01cae 100644
--- a/internal/lsp/mod/diagnostics.go
+++ b/internal/lsp/mod/diagnostics.go
@@ -8,6 +8,7 @@
 
 import (
 	"context"
+	"fmt"
 	"regexp"
 	"strings"
 	"unicode"
@@ -130,7 +131,10 @@
 		return toDiagnostic(rep.Syntax)
 	}
 	// No match for the module path was found in the go.mod file.
-	// Show the error on the module declaration.
+	// Show the error on the module declaration, if one exists.
+	if pm.File.Module == nil {
+		return nil, fmt.Errorf("no module declaration in %s", fh.URI())
+	}
 	return toDiagnostic(pm.File.Module.Syntax)
 }