Skip to content

Commit 22be084

Browse files
authored
ruleguard: fix empty gogrep node slice interpolation (#345)
1 parent 4538cb2 commit 22be084

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package gocritic
2+
3+
import "fmt"
4+
5+
func f(...interface{}) int { return 1 }
6+
7+
const ten = 10
8+
9+
func positiveTests() {
10+
defer func() { f() }() // want `\Qdefer f()`
11+
12+
defer func() { f(1) }() // want `\Qdefer f(1)`
13+
14+
defer func() { f(ten, ten+1) }() // want `\Qdefer f(ten, ten+1)`
15+
16+
defer func() { fmt.Println("hello") }() // want `\Qdefer fmt.Println("hello")`
17+
}

analyzer/testdata/src/gocritic/rules.go

+11
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//go:build ignore
12
// +build ignore
23

34
package gorules
@@ -264,3 +265,13 @@ func equalFold(m dsl.Matcher) {
264265
Suggest(`bytes.EqualFold($x, $y)]`).
265266
Report(`consider replacing with bytes.EqualFold($x, $y)`)
266267
}
268+
269+
func deferUnlambda(m dsl.Matcher) {
270+
m.Match(`defer func() { $f($*args) }()`).
271+
Where(m["f"].Node.Is(`Ident`) && m["f"].Text != "panic" && m["f"].Text != "recover" && m["args"].Const).
272+
Report("can rewrite as `defer $f($args)`")
273+
274+
m.Match(`defer func() { $pkg.$f($*args) }()`).
275+
Where(m["f"].Node.Is(`Ident`) && m["args"].Const && m["pkg"].Object.Is(`PkgName`)).
276+
Report("can rewrite as `defer $pkg.$f($args)`")
277+
}

ruleguard/runner.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ func (rr *rulesRunner) renderMessage(msg string, m matchData, truncate bool) str
392392
// For example, pattern `func $_() $results { $*_ }` may
393393
// match a nil *ast.FieldList for $results if executed
394394
// against a function with no results.
395-
if reflect.ValueOf(n).IsNil() {
395+
if reflect.ValueOf(n).IsNil() && !gogrep.IsEmptyNodeSlice(n) {
396396
continue
397397
}
398398
key := "$" + c.Name

0 commit comments

Comments
 (0)