Skip to content

Commit e43f1d2

Browse files
committed
fix: reporting within anonymous function
1 parent 23b75d2 commit e43f1d2

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"fmt"
7+
)
8+
9+
func main() {
10+
var b bytes.Buffer
11+
12+
test := func() error {
13+
return json.NewEncoder(&b).Encode("test")
14+
}
15+
16+
fmt.Println(test())
17+
}

wrapcheck/wrapcheck.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,20 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) {
121121
}
122122

123123
for _, file := range pass.Files {
124+
// Keep track of parents so that can can traverse upwards to check for
125+
// FuncDecls and FuncLits.
126+
var parents []ast.Node
127+
124128
ast.Inspect(file, func(n ast.Node) bool {
129+
if n == nil {
130+
// Pop, since we're done with this node and its children.
131+
parents = parents[:len(parents)-1]
132+
} else {
133+
// Push this node on the stack, since its children will be visited
134+
// next.
135+
parents = append(parents, n)
136+
}
137+
125138
ret, ok := n.(*ast.ReturnStmt)
126139
if !ok {
127140
return true
@@ -137,6 +150,17 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) {
137150
// to handle it by checking the return params of the function.
138151
retFn, ok := expr.(*ast.CallExpr)
139152
if ok {
153+
// If you go up, and the parent is a FuncLit, then don't report an
154+
// error as you are in an anonymous function. If you are inside a
155+
// FuncDecl, then continue as normal.
156+
for i := len(parents) - 1; i > 0; i-- {
157+
if _, ok := parents[i].(*ast.FuncLit); ok {
158+
return true
159+
} else if _, ok := parents[i].(*ast.FuncDecl); ok {
160+
break
161+
}
162+
}
163+
140164
// If the return type of the function is a single error. This will not
141165
// match an error within multiple return values, for that, the below
142166
// tuple check is required.

0 commit comments

Comments
 (0)