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.
13 "golang.org/x/tools/go/analysis"
14 "golang.org/x/tools/go/analysis/passes/inspect"
15 "golang.org/x/tools/go/ast/inspector"
16 "golang.org/x/tools/go/types/typeutil"
19 const Doc = `check references to loop variables from within nested functions
21 This analyzer checks for references to loop variables from within a
22 function literal inside the loop body. It checks only instances where
23 the function literal is called in a defer or go statement that is the
24 last statement in the loop body, as otherwise we would need whole
31 println(i, v) // not what you might expect
35 See: https://golang.org/doc/go_faq.html#closures_and_goroutines`
37 var Analyzer = &analysis.Analyzer{
40 Requires: []*analysis.Analyzer{inspect.Analyzer},
44 func run(pass *analysis.Pass) (interface{}, error) {
45 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
47 nodeFilter := []ast.Node{
48 (*ast.RangeStmt)(nil),
51 inspect.Preorder(nodeFilter, func(n ast.Node) {
52 // Find the variables updated by the loop statement.
54 addVar := func(expr ast.Expr) {
55 if id, ok := expr.(*ast.Ident); ok {
56 vars = append(vars, id)
59 var body *ast.BlockStmt
60 switch n := n.(type) {
67 switch post := n.Post.(type) {
69 // e.g. for p = head; p != nil; p = p.next
70 for _, lhs := range post.Lhs {
74 // e.g. for i := 0; i < n; i++
82 // Inspect a go or defer statement
83 // if it's the last one in the loop body.
84 // (We give up if there are following statements,
85 // because it's hard to prove go isn't followed by wait,
86 // or defer by return.)
87 if len(body.List) == 0 {
90 // The function invoked in the last return statement.
92 switch s := body.List[len(body.List)-1].(type) {
97 case *ast.ExprStmt: // check for errgroup.Group.Go()
98 if call, ok := s.X.(*ast.CallExpr); ok {
99 fun = goInvokes(pass.TypesInfo, call)
102 lit, ok := fun.(*ast.FuncLit)
106 ast.Inspect(lit.Body, func(n ast.Node) bool {
107 id, ok := n.(*ast.Ident)
108 if !ok || id.Obj == nil {
111 if pass.TypesInfo.Types[id].Type == nil {
112 // Not referring to a variable (e.g. struct field name)
115 for _, v := range vars {
117 pass.ReportRangef(id, "loop variable %s captured by func literal",
127 // goInvokes returns a function expression that would be called asynchronously
128 // (but not awaited) in another goroutine as a consequence of the call.
129 // For example, given the g.Go call below, it returns the function literal expression.
131 // import "sync/errgroup"
132 // var g errgroup.Group
133 // g.Go(func() error { ... })
135 // Currently only "golang.org/x/sync/errgroup.Group()" is considered.
136 func goInvokes(info *types.Info, call *ast.CallExpr) ast.Expr {
137 f := typeutil.StaticCallee(info, call)
138 // Note: Currently only supports: golang.org/x/sync/errgroup.Go.
139 if f == nil || f.Name() != "Go" {
142 recv := f.Type().(*types.Signature).Recv()
146 rtype, ok := recv.Type().(*types.Pointer)
150 named, ok := rtype.Elem().(*types.Named)
154 if named.Obj().Name() != "Group" {
161 if pkg.Path() != "golang.org/x/sync/errgroup" {