internal/lsp: fix concurrent map read/write for missingmodules

This change fixes an issue with concurrent map reads and writes that occurred when determining if an import is missing the corresponding dependency in the go.mod file.

Change-Id: Ic5cf3a620b4fd84eb4a377d0e4c22edbc8f37540
Reviewed-on: https://go-review.googlesource.com/c/tools/+/221897
Run-TryBot: Rohan Challa <rohan@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
(cherry picked from commit 115860e962071630067eb55fd778cc7c37b56296)
Reviewed-on: https://go-review.googlesource.com/c/tools/+/222980
Reviewed-by: Heschi Kreinick <heschi@google.com>
diff --git a/internal/lsp/source/diagnostics.go b/internal/lsp/source/diagnostics.go
index ee81f53..8e06974 100644
--- a/internal/lsp/source/diagnostics.go
+++ b/internal/lsp/source/diagnostics.go
@@ -61,10 +61,10 @@
 		warn = true
 	}
 
-	isMissingModule := false
+	missing := make(map[string]*modfile.Require)
 	for _, imp := range pkg.Imports() {
-		if _, ok := missingModules[imp.PkgPath()]; ok {
-			isMissingModule = true
+		if req, ok := missingModules[imp.PkgPath()]; ok {
+			missing[imp.PkgPath()] = req
 			continue
 		}
 		for dep, req := range missingModules {
@@ -77,8 +77,7 @@
 			// )
 			// They both are related to the same module: "golang.org/x/tools"
 			if req != nil && strings.HasPrefix(imp.PkgPath(), dep) {
-				missingModules[imp.PkgPath()] = req
-				isMissingModule = true
+				missing[imp.PkgPath()] = req
 				break
 			}
 		}
@@ -90,8 +89,8 @@
 		if err := clearReports(snapshot, reports, fh.File().Identity().URI); err != nil {
 			return nil, warn, err
 		}
-		if isMissingModule {
-			if err := missingModulesDiagnostics(ctx, snapshot, reports, missingModules, fh.File().Identity().URI); err != nil {
+		if len(missing) > 0 {
+			if err := missingModulesDiagnostics(ctx, snapshot, reports, missing, fh.File().Identity().URI); err != nil {
 				return nil, warn, err
 			}
 		}