go/ast/astutil: fix DeleteImport SEGV when Rparen is invalid
Updates #36383
Change-Id: I04b33810c16f4fb7871f5a6a8207b1c159cbc65f
GitHub-Last-Rev: 791fb862709c9a210bedde524555c5a6a92d9c51
GitHub-Pull-Request: golang/tools#196
Reviewed-on: https://go-review.googlesource.com/c/tools/+/214340
Reviewed-by: Michael Matloob <matloob@golang.org>
diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go
index 3e4b195..2087cee 100644
--- a/go/ast/astutil/imports.go
+++ b/go/ast/astutil/imports.go
@@ -275,9 +275,10 @@
// We deleted an entry but now there may be
// a blank line-sized hole where the import was.
- if line-lastLine > 1 {
+ if line-lastLine > 1 || !gen.Rparen.IsValid() {
// There was a blank line immediately preceding the deleted import,
- // so there's no need to close the hole.
+ // so there's no need to close the hole. The right parenthesis is
+ // invalid after AddImport to an import statement without parenthesis.
// Do nothing.
} else if line != fset.File(gen.Rparen).LineCount() {
// There was no blank line. Close the hole.
diff --git a/go/ast/astutil/imports_test.go b/go/ast/astutil/imports_test.go
index 1d86e47..68f05ab 100644
--- a/go/ast/astutil/imports_test.go
+++ b/go/ast/astutil/imports_test.go
@@ -1684,6 +1684,19 @@
}
}
+func TestDeleteImportAfterAddImport(t *testing.T) {
+ file := parse(t, "test", `package main
+
+import "os"
+`)
+ if got, want := AddImport(fset, file, "fmt"), true; got != want {
+ t.Errorf("AddImport: got: %v, want: %v", got, want)
+ }
+ if got, want := DeleteImport(fset, file, "fmt"), true; got != want {
+ t.Errorf("DeleteImport: got: %v, want: %v", got, want)
+ }
+}
+
type rewriteTest struct {
name string
srcPkg string