go/ast/astutil: set Pos for import name

Failing to set this when adding a named import
to an existing block at the 0th position
caused the Lparen position to be set to zero.
As a result, the specs were printed as if
they were a single spec, not a group.
This made it appear as if imports had
been swallowed.

See CL 8663 for more context
and the original bug report.

CL 2050 fixed most similar cases
but missed this one.

Change-Id: Ic578fbb8040fa3d3d41db5bde2b839e394801608
Reviewed-on: https://go-review.googlesource.com/10252
Reviewed-by: Robert Griesemer <gri@golang.org>
This commit is contained in:
Josh Bleecher Snyder 2015-05-19 15:51:30 -07:00
parent 45716cd4c6
commit 3f8aef80c8
2 changed files with 19 additions and 0 deletions

View File

@ -121,6 +121,9 @@ func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added
// so that the sorter sees it as being in the same block. // so that the sorter sees it as being in the same block.
pos = impDecl.Specs[insertAt-1].Pos() pos = impDecl.Specs[insertAt-1].Pos()
} }
if newImport.Name != nil {
newImport.Name.NamePos = pos
}
newImport.Path.ValuePos = pos newImport.Path.ValuePos = pos
newImport.EndPos = pos newImport.EndPos = pos

View File

@ -378,6 +378,22 @@ import (
} }
} }
func TestDoubleAddNamedImport(t *testing.T) {
file := parse(t, "doublenamedimport", "package main\n")
AddNamedImport(fset, file, "o", "os")
AddNamedImport(fset, file, "i", "io")
want := `package main
import (
i "io"
o "os"
)
`
if got := print(t, "doublenamedimport", file); got != want {
t.Errorf("got: %s\nwant: %s", got, want)
}
}
// Part of issue 8729. // Part of issue 8729.
func TestDoubleAddImportWithDeclComment(t *testing.T) { func TestDoubleAddImportWithDeclComment(t *testing.T) {
file := parse(t, "doubleimport", `package main file := parse(t, "doubleimport", `package main