]> Cypherpunks repositories - gostls13.git/commitdiff
vet: fix rangeloop.
authorDavid Symonds <dsymonds@golang.org>
Wed, 19 Sep 2012 22:12:47 +0000 (08:12 +1000)
committerDavid Symonds <dsymonds@golang.org>
Wed, 19 Sep 2012 22:12:47 +0000 (08:12 +1000)
In a range loop, the presence of a value implies the presence of a key.
However, the presence of a value as an *ast.Ident does not imply that
the key is also an *ast.Ident, thus leading to a panic any time the
two argument form is used where the key is not an identifier.

R=golang-dev, adg, r
CC=golang-dev
https://golang.org/cl/6540045

src/cmd/vet/rangeloop.go

index 2fdb0b621600433e3ea93fc11ffb3da915564e95..71cbc115799beda1041a12a7b40fd70a932b175c 100644 (file)
@@ -53,8 +53,12 @@ func checkRangeLoop(f *File, n *ast.RangeStmt) {
                return
        }
        ast.Inspect(lit.Body, func(n ast.Node) bool {
-               if n, ok := n.(*ast.Ident); ok && n.Obj != nil && (n.Obj == key.Obj || n.Obj == val.Obj) {
-                       f.Warn(n.Pos(), "range variable", n.Name, "enclosed by function")
+               id, ok := n.(*ast.Ident)
+               if !ok || id.Obj == nil {
+                       return true
+               }
+               if key != nil && id.Obj == key.Obj || val != nil && id.Obj == val.Obj {
+                       f.Warn(id.Pos(), "range variable", id.Name, "enclosed by function")
                }
                return true
        })
@@ -101,4 +105,13 @@ func BadRangeLoopsUsedInTests() {
                        println(i, v)
                }()
        }
+       // If the key of the range statement is not an identifier
+       // the code should not panic (it used to).
+       var x [2]int
+       var f int
+       for x[0], f = range s {
+               go func() {
+                       _ = f // ERROR "range variable f enclosed by function"
+               }()
+       }
 }