github.com/Johnny2210/revive@v1.0.8-0.20210625134200-febf37ccd0f5/rule/bool-literal-in-expr.go (about)

     1  package rule
     2  
     3  import (
     4  	"go/ast"
     5  	"go/token"
     6  
     7  	"github.com/mgechev/revive/lint"
     8  )
     9  
    10  // BoolLiteralRule warns when logic expressions contains Boolean literals.
    11  type BoolLiteralRule struct{}
    12  
    13  // Apply applies the rule to given file.
    14  func (r *BoolLiteralRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
    15  	var failures []lint.Failure
    16  
    17  	onFailure := func(failure lint.Failure) {
    18  		failures = append(failures, failure)
    19  	}
    20  
    21  	astFile := file.AST
    22  	w := &lintBoolLiteral{astFile, onFailure}
    23  	ast.Walk(w, astFile)
    24  
    25  	return failures
    26  }
    27  
    28  // Name returns the rule name.
    29  func (r *BoolLiteralRule) Name() string {
    30  	return "bool-literal-in-expr"
    31  }
    32  
    33  type lintBoolLiteral struct {
    34  	file      *ast.File
    35  	onFailure func(lint.Failure)
    36  }
    37  
    38  func (w *lintBoolLiteral) Visit(node ast.Node) ast.Visitor {
    39  	switch n := node.(type) {
    40  	case *ast.BinaryExpr:
    41  		if !isBoolOp(n.Op) {
    42  			return w
    43  		}
    44  
    45  		lexeme, ok := isExprABooleanLit(n.X)
    46  		if !ok {
    47  			lexeme, ok = isExprABooleanLit(n.Y)
    48  
    49  			if !ok {
    50  				return w
    51  			}
    52  		}
    53  
    54  		isConstant := (n.Op == token.LAND && lexeme == "false") || (n.Op == token.LOR && lexeme == "true")
    55  
    56  		if isConstant {
    57  			w.addFailure(n, "Boolean expression seems to always evaluate to "+lexeme, "logic")
    58  		} else {
    59  			w.addFailure(n, "omit Boolean literal in expression", "style")
    60  		}
    61  	}
    62  
    63  	return w
    64  }
    65  
    66  func (w lintBoolLiteral) addFailure(node ast.Node, msg string, cat string) {
    67  	w.onFailure(lint.Failure{
    68  		Confidence: 1,
    69  		Node:       node,
    70  		Category:   cat,
    71  		Failure:    msg,
    72  	})
    73  }