1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package loopclosure defines an Analyzer that checks for references to
6 // enclosing loop variables from within nested functions.
12 "golang.org/x/tools/go/analysis"
13 "golang.org/x/tools/go/analysis/passes/inspect"
14 "golang.org/x/tools/go/ast/inspector"
17 // TODO(adonovan): also report an error for the following structure,
18 // which is often used to ensure that deferred calls do not accumulate
21 // for i, x := range c {
23 // ...reference to i or x...
27 const Doc = `check references to loop variables from within nested functions
29 This analyzer checks for references to loop variables from within a
30 function literal inside the loop body. It checks only instances where
31 the function literal is called in a defer or go statement that is the
32 last statement in the loop body, as otherwise we would need whole
39 println(i, v) // not what you might expect
43 See: https://golang.org/doc/go_faq.html#closures_and_goroutines`
45 var Analyzer = &analysis.Analyzer{
48 Requires: []*analysis.Analyzer{inspect.Analyzer},
52 func run(pass *analysis.Pass) (interface{}, error) {
53 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
55 nodeFilter := []ast.Node{
56 (*ast.RangeStmt)(nil),
59 inspect.Preorder(nodeFilter, func(n ast.Node) {
60 // Find the variables updated by the loop statement.
62 addVar := func(expr ast.Expr) {
63 if id, ok := expr.(*ast.Ident); ok {
64 vars = append(vars, id)
67 var body *ast.BlockStmt
68 switch n := n.(type) {
75 switch post := n.Post.(type) {
77 // e.g. for p = head; p != nil; p = p.next
78 for _, lhs := range post.Lhs {
82 // e.g. for i := 0; i < n; i++
90 // Inspect a go or defer statement
91 // if it's the last one in the loop body.
92 // (We give up if there are following statements,
93 // because it's hard to prove go isn't followed by wait,
94 // or defer by return.)
95 if len(body.List) == 0 {
98 var last *ast.CallExpr
99 switch s := body.List[len(body.List)-1].(type) {
107 lit, ok := last.Fun.(*ast.FuncLit)
111 ast.Inspect(lit.Body, func(n ast.Node) bool {
112 id, ok := n.(*ast.Ident)
113 if !ok || id.Obj == nil {
116 if pass.TypesInfo.Types[id].Type == nil {
117 // Not referring to a variable (e.g. struct field name)
120 for _, v := range vars {
122 pass.ReportRangef(id, "loop variable %s captured by func literal",