Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions rule/constant-logical-expr.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package rule

import (
"github.com/mgechev/revive/lint"
"go/ast"
"go/token"

"github.com/mgechev/revive/lint"
)

// ConstantLogicalExprRule warns on constant logical expressions.
Expand Down Expand Up @@ -44,11 +45,13 @@ func (w *lintConstantLogicalExpr) Visit(node ast.Node) ast.Visitor {
return w
}

if n.Op == token.EQL {
// Handles cases like: a <= a, a == a, a >= a
if w.isEqualityOperator(n.Op) {
w.newFailure(n, "expression always evaluates to true")
return w
}

// Handles cases like: a < a, a > a, a != a
if w.isInequalityOperator(n.Op) {
w.newFailure(n, "expression always evaluates to false")
return w
Expand All @@ -69,9 +72,18 @@ func (w *lintConstantLogicalExpr) isOperatorWithLogicalResult(t token.Token) boo
return false
}

func (w *lintConstantLogicalExpr) isEqualityOperator(t token.Token) bool {
switch t {
case token.EQL, token.LEQ, token.GEQ:
return true
}

return false
}

func (w *lintConstantLogicalExpr) isInequalityOperator(t token.Token) bool {
switch t {
case token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ:
case token.LSS, token.GTR, token.NEQ:
return true
}

Expand Down
6 changes: 4 additions & 2 deletions testdata/constant-logical-expr.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package fixtures

import "fmt"

// from github.com/ugorji/go/codec/helper.go
func isNaN(f float64) bool { return f != f } // MATCH /expression always evaluates to false/

Expand All @@ -9,9 +11,9 @@ func foo1(f float64) bool { return foo2(2.) > foo2(2.) } // MATCH /expression al

func foo2(f float64) bool { return f < f } // MATCH /expression always evaluates to false/

func foo3(f float64) bool { return f <= f } // MATCH /expression always evaluates to false/
func foo3(f float64) bool { return f <= f } // MATCH /expression always evaluates to true/

func foo4(f float64) bool { return f >= f } // MATCH /expression always evaluates to false/
func foo4(f float64) bool { return f >= f } // MATCH /expression always evaluates to true/

func foo5(f float64) bool { return f == f } // MATCH /expression always evaluates to true/

Expand Down