1
0
mirror of https://github.com/golang/go synced 2024-11-11 20:01:37 -07:00

go/ast: add Range token.Pos to RangeStmt

For #50429

Change-Id: Idb027244f901d9f482c894b5b979a054d0f07de5
Reviewed-on: https://go-review.googlesource.com/c/go/+/426091
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Reviewed-by: Robert Griesemer <gri@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Robert Findley <rfindley@google.com>
This commit is contained in:
cuiweixie 2022-08-27 15:21:29 +08:00 committed by Daniel Martí
parent 40ced0c00b
commit 67e6542467
4 changed files with 33 additions and 0 deletions

1
api/next/50429.txt Normal file
View File

@ -0,0 +1 @@
pkg go/ast, type RangeStmt struct, Range token.Pos #50429

View File

@ -754,6 +754,7 @@ type (
Key, Value Expr // Key, Value may be nil
TokPos token.Pos // position of Tok; invalid if Key == nil
Tok token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE
Range token.Pos // position of "range" keyword
X Expr // value to range over
Body *BlockStmt
}

View File

@ -2338,6 +2338,7 @@ func (p *parser) parseForStmt() ast.Stmt {
Value: value,
TokPos: as.TokPos,
Tok: as.Tok,
Range: as.Rhs[0].Pos(),
X: x,
Body: body,
}

View File

@ -697,3 +697,33 @@ func TestScopeDepthLimit(t *testing.T) {
}
}
}
// proposal #50429
func TestRangePos(t *testing.T) {
testcases := []string{
"package p; func _() { for range x {} }",
"package p; func _() { for i = range x {} }",
"package p; func _() { for i := range x {} }",
"package p; func _() { for k, v = range x {} }",
"package p; func _() { for k, v := range x {} }",
}
for _, src := range testcases {
fset := token.NewFileSet()
f, err := ParseFile(fset, src, src, 0)
if err != nil {
t.Fatal(err)
}
ast.Inspect(f, func(x ast.Node) bool {
switch s := x.(type) {
case *ast.RangeStmt:
pos := fset.Position(s.Range)
if pos.Offset != strings.Index(src, "range") {
t.Errorf("%s: got offset %v, want %v", src, pos.Offset, strings.Index(src, "range"))
}
}
return true
})
}
}