From 43d50277825c291cf84444b652566c6f79131ff8 Mon Sep 17 00:00:00 2001 From: itchyny Date: Tue, 14 Jan 2020 23:15:50 +0000 Subject: [PATCH] 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 --- go/ast/astutil/imports.go | 5 +++-- go/ast/astutil/imports_test.go | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/go/ast/astutil/imports.go b/go/ast/astutil/imports.go index 3e4b195368..2087ceec9c 100644 --- a/go/ast/astutil/imports.go +++ b/go/ast/astutil/imports.go @@ -275,9 +275,10 @@ func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (del // 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 1d86e4773e..68f05ab6d9 100644 --- a/go/ast/astutil/imports_test.go +++ b/go/ast/astutil/imports_test.go @@ -1684,6 +1684,19 @@ func TestDeleteImport(t *testing.T) { } } +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