You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bool-literal-in-expr.go 1.5KB

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