aboutsummaryrefslogtreecommitdiff
path: root/lib/src/lints
diff options
context:
space:
mode:
Diffstat (limited to 'lib/src/lints')
-rw-r--r--lib/src/lints/bool_simplification.rs61
1 files changed, 61 insertions, 0 deletions
diff --git a/lib/src/lints/bool_simplification.rs b/lib/src/lints/bool_simplification.rs
new file mode 100644
index 0000000..9ccb1f6
--- /dev/null
+++ b/lib/src/lints/bool_simplification.rs
@@ -0,0 +1,61 @@
1use crate::{make, session::SessionInfo, Metadata, Report, Rule, Suggestion};
2
3use if_chain::if_chain;
4use macros::lint;
5use rnix::{
6 types::{BinOp, BinOpKind, Paren, TypedNode, UnaryOp, UnaryOpKind, Wrapper},
7 NodeOrToken, SyntaxElement, SyntaxKind,
8};
9
10/// ## What it does
11/// Checks for boolean expressions that can be simplified.
12///
13/// ## Why is this bad?
14/// Complex booleans affect readibility.
15///
16/// ## Example
17/// ```nix
18/// if !(x == y) then 0 else 1
19/// ```
20///
21/// Use `!=` instead:
22///
23/// ```nix
24/// if x != y then 0 else 1
25/// ```
26#[lint(
27 name = "bool_simplification",
28 note = "This boolean expression can be simplified",
29 code = 18,
30 match_with = SyntaxKind::NODE_UNARY_OP
31)]
32struct BoolSimplification;
33
34impl Rule for BoolSimplification {
35 fn validate(&self, node: &SyntaxElement, _sess: &SessionInfo) -> Option<Report> {
36 if_chain! {
37 if let NodeOrToken::Node(node) = node;
38 if let Some(unary_expr) = UnaryOp::cast(node.clone());
39 if unary_expr.operator() == UnaryOpKind::Invert;
40 if let Some(value_expr) = unary_expr.value();
41 if let Some(paren_expr) = Paren::cast(value_expr.clone());
42 if let Some(inner_expr) = paren_expr.inner();
43 if let Some(bin_expr) = BinOp::cast(inner_expr);
44 if let Some(BinOpKind::Equal) = bin_expr.operator();
45 then {
46 let at = node.text_range();
47 let message = "Try `!=` instead of `!(... == ...)`";
48
49 let lhs = bin_expr.lhs()?;
50 let rhs = bin_expr.rhs()?;
51 let replacement = make::binary(&lhs, "!=", &rhs).node().clone();
52 Some(
53 self.report()
54 .suggest(at, message, Suggestion::new(at, replacement)),
55 )
56 } else {
57 None
58 }
59 }
60 }
61}