internal/lsp: check the file's parse mode before formatting

Change-Id: I9ac3c273f305c41aed065cfcfdf96e59a828d71f
Reviewed-on: https://go-review.googlesource.com/c/tools/+/196317
Reviewed-by: Ian Cottrell <iancottrell@google.com>
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/internal/lsp/source/format.go b/internal/lsp/source/format.go
index ba2ce3d..ad91f40 100644
--- a/internal/lsp/source/format.go
+++ b/internal/lsp/source/format.go
@@ -42,6 +42,11 @@
 	if err != nil {
 		return nil, err
 	}
+	// Be extra careful that the file's ParseMode is correct,
+	// otherwise we might replace the user's code with a trimmed AST.
+	if ph.Mode() != ParseFull {
+		return nil, errors.Errorf("%s was parsed in the incorrect mode", ph.File().Identity().URI)
+	}
 	file, m, _, err := ph.Parse(ctx)
 	if err != nil {
 		return nil, err
@@ -102,6 +107,11 @@
 	if err != nil {
 		return nil, err
 	}
+	// Be extra careful that the file's ParseMode is correct,
+	// otherwise we might replace the user's code with a trimmed AST.
+	if ph.Mode() != ParseFull {
+		return nil, errors.Errorf("%s was parsed in the incorrect mode", ph.File().Identity().URI)
+	}
 	options := &imports.Options{
 		// Defaults.
 		AllErrors:  true,