Skip to content

Commit

Permalink
ruleguard: fix empty gogrep node slice interpolation (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
quasilyte authored Jan 3, 2022
1 parent 4538cb2 commit 22be084
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
17 changes: 17 additions & 0 deletions analyzer/testdata/src/gocritic/deferUnlambda.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package gocritic

import "fmt"

func f(...interface{}) int { return 1 }

const ten = 10

func positiveTests() {
defer func() { f() }() // want `\Qdefer f()`

defer func() { f(1) }() // want `\Qdefer f(1)`

defer func() { f(ten, ten+1) }() // want `\Qdefer f(ten, ten+1)`

defer func() { fmt.Println("hello") }() // want `\Qdefer fmt.Println("hello")`
}
11 changes: 11 additions & 0 deletions analyzer/testdata/src/gocritic/rules.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build ignore
// +build ignore

package gorules
Expand Down Expand Up @@ -264,3 +265,13 @@ func equalFold(m dsl.Matcher) {
Suggest(`bytes.EqualFold($x, $y)]`).
Report(`consider replacing with bytes.EqualFold($x, $y)`)
}

func deferUnlambda(m dsl.Matcher) {
m.Match(`defer func() { $f($*args) }()`).
Where(m["f"].Node.Is(`Ident`) && m["f"].Text != "panic" && m["f"].Text != "recover" && m["args"].Const).
Report("can rewrite as `defer $f($args)`")

m.Match(`defer func() { $pkg.$f($*args) }()`).
Where(m["f"].Node.Is(`Ident`) && m["args"].Const && m["pkg"].Object.Is(`PkgName`)).
Report("can rewrite as `defer $pkg.$f($args)`")
}
2 changes: 1 addition & 1 deletion ruleguard/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ func (rr *rulesRunner) renderMessage(msg string, m matchData, truncate bool) str
// For example, pattern `func $_() $results { $*_ }` may
// match a nil *ast.FieldList for $results if executed
// against a function with no results.
if reflect.ValueOf(n).IsNil() {
if reflect.ValueOf(n).IsNil() && !gogrep.IsEmptyNodeSlice(n) {
continue
}
key := "$" + c.Name
Expand Down

0 comments on commit 22be084

Please sign in to comment.