Skip to content

Commit

Permalink
fix: reporting within anonymous function
Browse files Browse the repository at this point in the history
  • Loading branch information
tomarrell committed Mar 31, 2023
1 parent 23b75d2 commit e43f1d2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions wrapcheck/testdata/issue_17_anon_function/main.go
@@ -0,0 +1,17 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
)

func main() {
var b bytes.Buffer

test := func() error {
return json.NewEncoder(&b).Encode("test")
}

fmt.Println(test())
}
24 changes: 24 additions & 0 deletions wrapcheck/wrapcheck.go
Expand Up @@ -121,7 +121,20 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) {
}

for _, file := range pass.Files {
// Keep track of parents so that can can traverse upwards to check for
// FuncDecls and FuncLits.
var parents []ast.Node

ast.Inspect(file, func(n ast.Node) bool {
if n == nil {
// Pop, since we're done with this node and its children.
parents = parents[:len(parents)-1]
} else {
// Push this node on the stack, since its children will be visited
// next.
parents = append(parents, n)
}

ret, ok := n.(*ast.ReturnStmt)
if !ok {
return true
Expand All @@ -137,6 +150,17 @@ func run(cfg WrapcheckConfig) func(*analysis.Pass) (interface{}, error) {
// to handle it by checking the return params of the function.
retFn, ok := expr.(*ast.CallExpr)
if ok {
// If you go up, and the parent is a FuncLit, then don't report an
// error as you are in an anonymous function. If you are inside a
// FuncDecl, then continue as normal.
for i := len(parents) - 1; i > 0; i-- {
if _, ok := parents[i].(*ast.FuncLit); ok {
return true
} else if _, ok := parents[i].(*ast.FuncDecl); ok {
break
}
}

// If the return type of the function is a single error. This will not
// match an error within multiple return values, for that, the below
// tuple check is required.
Expand Down

0 comments on commit e43f1d2

Please sign in to comment.