Skip to content

Commit

Permalink
go/ast/astutil: fix panic in DeleteNamedImport from line directive
Browse files Browse the repository at this point in the history
DeleteNamedImport used FileSet.Position() where it should have
used FileSet.PositionFor(, false) to ignore line directives.

There are likely many more of these panics lurking in x/tools.

Change-Id: I11fc0ea5301fe873cb679a82e231b1720dbdaef6
Reviewed-on: https://go-review.googlesource.com/c/tools/+/398596
Run-TryBot: Peter Weinberger <pjw@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
Trust: Peter Weinberger <pjw@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
  • Loading branch information
pjweinbgo committed Apr 7, 2022
1 parent 48e6d8d commit ee2bc8b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions go/ast/astutil/imports.go
Expand Up @@ -270,8 +270,8 @@ func DeleteNamedImport(fset *token.FileSet, f *ast.File, name, path string) (del
}
if j > 0 {
lastImpspec := gen.Specs[j-1].(*ast.ImportSpec)
lastLine := fset.Position(lastImpspec.Path.ValuePos).Line
line := fset.Position(impspec.Path.ValuePos).Line
lastLine := fset.PositionFor(lastImpspec.Path.ValuePos, false).Line
line := fset.PositionFor(impspec.Path.ValuePos, false).Line

// We deleted an entry but now there may be
// a blank line-sized hole where the import was.
Expand Down
28 changes: 28 additions & 0 deletions go/ast/astutil/imports_test.go
Expand Up @@ -1654,6 +1654,34 @@ import f "fmt"
`,
unchanged: true,
},
// this test panics without PositionFor in DeleteNamedImport
{
name: "import.44",
pkg: "foo.com/other/v3",
renamedPkg: "",
in: `package main
//line mah.go:600
import (
"foo.com/a.thing"
"foo.com/surprise"
"foo.com/v1"
"foo.com/other/v2"
"foo.com/other/v3"
)
`,
out: `package main
//line mah.go:600
import (
"foo.com/a.thing"
"foo.com/other/v2"
"foo.com/surprise"
"foo.com/v1"
)
`,
},
}

func TestDeleteImport(t *testing.T) {
Expand Down

0 comments on commit ee2bc8b

Please sign in to comment.