From c9bde6c5035419ff7af6668e3abb51a0dc3642da Mon Sep 17 00:00:00 2001 From: chavacava Date: Mon, 11 Jun 2018 21:08:59 +0200 Subject: [PATCH] empty-block: ignore checking blocks of funcs and func literals (#17) * Adds rule superfluous-else (an extension of indent-error-flow) * Fix superfluous-else rule struct namming. * Adds superfuous-else rule to the rules table * Modifies empty-block rule to ignore bodies of func literals and funcs * add test cases on functions with a receiver for completeness --- fixtures/empty-block.go | 9 +++++++-- rule/empty-block.go | 29 +++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/fixtures/empty-block.go b/fixtures/empty-block.go index 79b9dde..9f04d5b 100644 --- a/fixtures/empty-block.go +++ b/fixtures/empty-block.go @@ -2,14 +2,19 @@ package fixtures -func f(x int) bool { // MATCH /this block is empty, you can remove it/ +func f(x int) bool {} // Must not match -} +type foo struct {} + +func (f foo) f(x *int) string {} // Must not match +func (f *foo) g(y *int) string {} // Must not match func g(f func() bool) string { { // MATCH /this block is empty, you can remove it/ } + a := func(e error){} // Must not match + if ok := f(); ok { // MATCH /this block is empty, you can remove it/ // only a comment } else { diff --git a/rule/empty-block.go b/rule/empty-block.go index 11e4af3..eed573f 100644 --- a/rule/empty-block.go +++ b/rule/empty-block.go @@ -17,7 +17,7 @@ func (r *EmptyBlockRule) Apply(file *lint.File, arguments lint.Arguments) []lint failures = append(failures, failure) } - w := lintEmptyBlock{make(map[*ast.IfStmt]bool), onFailure} + w := lintEmptyBlock{make([]*ast.BlockStmt, 0), onFailure} ast.Walk(w, file.AST) return failures } @@ -28,16 +28,32 @@ func (r *EmptyBlockRule) Name() string { } type lintEmptyBlock struct { - ignore map[*ast.IfStmt]bool + ignore []*ast.BlockStmt onFailure func(lint.Failure) } func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor { + fd, ok := node.(*ast.FuncDecl) + if ok { + w.ignore = append(w.ignore, fd.Body) + return w + } + + fl, ok := node.(*ast.FuncLit) + if ok { + w.ignore = append(w.ignore, fl.Body) + return w + } + block, ok := node.(*ast.BlockStmt) if !ok { return w } + if mustIgnore(block, w.ignore) { + return w + } + if len(block.List) == 0 { w.onFailure(lint.Failure{ Confidence: 1, @@ -50,3 +66,12 @@ func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor { return w } + +func mustIgnore(block *ast.BlockStmt, blackList []*ast.BlockStmt) bool { + for _, b := range blackList { + if b == block { + return true + } + } + return false +}