1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use crate::rule_prelude::*;
use ast::{ArrowExpr, Expr};
declare_lint! {
#[serde(default)]
NoConfusingArrow,
errors,
"no-confusing-arrow",
pub allow_parens: bool
}
impl Default for NoConfusingArrow {
fn default() -> Self {
Self { allow_parens: true }
}
}
#[typetag::serde]
impl CstRule for NoConfusingArrow {
fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
let function_stmt = node.try_to::<ArrowExpr>()?;
let expr = function_stmt.body()?.syntax().try_to::<Expr>()?;
if is_conditional(&expr) && !(self.allow_parens && is_parenthesised(&expr)) {
let diagnostic = ctx
.err(
self.name(),
"arrow function in ternary expression could be mistaken for a comparison",
)
.primary(
function_stmt.syntax(),
"it could be confused with a comparison operator",
);
ctx.add_err(diagnostic);
}
None
}
}
fn is_conditional(expr: &Expr) -> bool {
match expr {
Expr::CondExpr(_) => true,
Expr::GroupingExpr(group) => group.inner().map_or(false, |e| is_conditional(&e)),
_ => false,
}
}
fn is_parenthesised(expr: &Expr) -> bool {
matches!(expr, Expr::GroupingExpr(_))
}
rule_tests! {
NoConfusingArrow::default(),
err: {
"a => 1 ? 2 : 3",
"var x = a => 1 ? 2 : 3",
"var x = (a) => 1 ? 2 : 3",
},
ok: {
"a => { return 1 ? 2 : 3; }",
"var x = a => { return 1 ? 2 : 3; }",
"var x = (a) => { return 1 ? 2 : 3; }",
"var x = a => (1 ? 2 : 3)",
}
}
rule_tests! {
allow_parens_false_valid,
allow_parens_false_invalid,
NoConfusingArrow {
allow_parens: false,
},
err: {
"a => 1 ? 2 : 3",
"var x = a => 1 ? 2 : 3",
"var x = (a) => 1 ? 2 : 3",
"var x = a => (1 ? 2 : 3)",
},
ok: {
"a => { return 1 ? 2 : 3; }",
"var x = a => { return 1 ? 2 : 3; }",
"var x = (a) => { return 1 ? 2 : 3; }",
}
}