diff --git a/pkg/analyzer/analyzer.go b/pkg/analyzer/analyzer.go index b45dbc3..c4488bc 100644 --- a/pkg/analyzer/analyzer.go +++ b/pkg/analyzer/analyzer.go @@ -30,6 +30,7 @@ func run(pass *analysis.Pass) (interface{}, error) { (*ast.ForStmt)(nil), (*ast.RangeStmt)(nil), (*ast.FuncLit)(nil), + (*ast.FuncDecl)(nil), } inspctr.Preorder(nodeFilter, func(node ast.Node) { @@ -81,25 +82,23 @@ func getReportMessage(node ast.Node) string { return "nested context in loop" case *ast.FuncLit: return "nested context in function literal" + case *ast.FuncDecl: + return "potential nested context in function declaration" default: return "unsupported nested context type" } } func getBody(node ast.Node) (*ast.BlockStmt, error) { - forStmt, ok := node.(*ast.ForStmt) - if ok { - return forStmt.Body, nil - } - - rangeStmt, ok := node.(*ast.RangeStmt) - if ok { - return rangeStmt.Body, nil - } - - funcLit, ok := node.(*ast.FuncLit) - if ok { - return funcLit.Body, nil + switch typedNode := node.(type) { + case *ast.ForStmt: + return typedNode.Body, nil + case *ast.RangeStmt: + return typedNode.Body, nil + case *ast.FuncLit: + return typedNode.Body, nil + case *ast.FuncDecl: + return typedNode.Body, nil } return nil, errUnknown diff --git a/testdata/src/example.go b/testdata/src/example.go index df76f89..2dc714b 100644 --- a/testdata/src/example.go +++ b/testdata/src/example.go @@ -249,3 +249,25 @@ func testCasesInit(t *testing.T) { }) } } + +type Container struct { + Ctx context.Context +} + +func something() func(*Container) { + return func(r *Container) { + ctx := r.Ctx + ctx = context.WithValue(ctx, "key", "val") + r.Ctx = ctx // want "nested context in function literal" + } +} + +func other() func(*Container) { + return blah +} + +func blah(r *Container) { + ctx := r.Ctx + ctx = context.WithValue(ctx, "key", "val") + r.Ctx = ctx // want "potential nested context in function declaration" +}