aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorAkshay <[email protected]>2022-02-20 04:07:32 +0000
committerAkshay <[email protected]>2022-02-20 04:07:32 +0000
commite8130a90dca048d195603281f72e1af0b4f7ccc6 (patch)
tree7b722cfc3dcf16417f73ba1577f824782903ad2e /lib
parenta80e252193096f22ae79fa03e66a0853ddae050e (diff)
new lint: bool_simplification
TODO: add more patterns to this
Diffstat (limited to 'lib')
-rw-r--r--lib/src/lints.rs1
-rw-r--r--lib/src/lints/bool_simplification.rs61
2 files changed, 62 insertions, 0 deletions
diff --git a/lib/src/lints.rs b/lib/src/lints.rs
index 439fd8f..582cabe 100644
--- a/lib/src/lints.rs
+++ b/lib/src/lints.rs
@@ -18,4 +18,5 @@ lints! {
18 faster_groupby, 18 faster_groupby,
19 faster_zipattrswith, 19 faster_zipattrswith,
20 deprecated_to_path, 20 deprecated_to_path,
21 bool_simplification,
21} 22}
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}