elm-review/tests/NoExtraBooleanComparison.elm

111 lines
2.3 KiB
Elm
Raw Normal View History

2020-04-03 16:53:44 +03:00
module NoExtraBooleanComparison exposing (rule)
2019-06-16 16:31:40 +03:00
2019-07-03 15:19:29 +03:00
{-| Forbid the use of boolean comparisons that can be simplified.
2019-06-16 16:31:40 +03:00
# Rule
@docs rule
-}
import Elm.Syntax.Expression as Expression exposing (Expression(..))
import Elm.Syntax.Node as Node exposing (Node)
import Review.Rule as Rule exposing (Error, Rule)
{-| Forbid the use of boolean comparisons that can be simplified.
config =
2019-07-25 15:35:58 +03:00
[ NoExtraBooleanComparison.rule
]
2019-07-03 15:19:29 +03:00
## Fail
2019-06-16 16:31:40 +03:00
2019-07-03 15:19:29 +03:00
if someBooleanValue == True then
2019-06-16 16:31:40 +03:00
a
else
b
2019-07-03 15:19:29 +03:00
if someBooleanValue == False then
a
2019-06-16 16:31:40 +03:00
else
2019-07-03 15:19:29 +03:00
b
2019-06-16 16:31:40 +03:00
2019-07-03 15:19:29 +03:00
## Success
2019-06-16 16:31:40 +03:00
2019-07-03 15:19:29 +03:00
if someBooleanValue then
2019-06-16 16:31:40 +03:00
a
else
b
2019-07-03 15:19:29 +03:00
if not someBooleanValue then
a
else
b
# When not to use this rule
You should not use this rule if you
- prefer the explicitness of expressions like `value == True`
- dislike the use of the `not` function
- do not see the value in simplifying boolean comparisons
2019-06-16 16:31:40 +03:00
-}
rule : Rule
rule =
2020-01-19 22:37:19 +03:00
Rule.newModuleRuleSchema "NoExtraBooleanComparison" ()
|> Rule.withSimpleExpressionVisitor expressionVisitor
2020-01-19 22:37:19 +03:00
|> Rule.fromModuleRuleSchema
2019-06-16 16:31:40 +03:00
error : Node a -> String -> String -> Error {}
error node operator comparedValue =
2019-06-26 14:47:00 +03:00
Rule.error
{ message = "Unnecessary comparison with `" ++ comparedValue ++ "`"
, details = [ "You can simplify this expression by removing the `" ++ operator ++ "` operator and the value `" ++ comparedValue ++ "`." ]
}
2019-06-16 16:31:40 +03:00
(Node.range node)
expressionVisitor : Node Expression -> List (Error {})
expressionVisitor node =
case Node.value node of
Expression.OperatorApplication operator _ left right ->
2019-06-16 16:31:40 +03:00
if isEqualityOperator operator then
List.filterMap isTrueOrFalse [ left, right ]
|> List.map (error node operator)
2019-06-16 16:31:40 +03:00
else
[]
2019-06-16 16:31:40 +03:00
_ ->
[]
2019-06-16 16:31:40 +03:00
isEqualityOperator : String -> Bool
isEqualityOperator operator =
operator == "==" || operator == "/="
isTrueOrFalse : Node Expression -> Maybe String
2019-06-16 16:31:40 +03:00
isTrueOrFalse node =
case Node.value node of
FunctionOrValue [] functionOrValue ->
if functionOrValue == "True" || functionOrValue == "False" then
Just functionOrValue
2019-06-16 16:31:40 +03:00
else
Nothing
_ ->
Nothing