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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use crate::rule_prelude::*;
use ast::*;
use SyntaxKind::*;

declare_lint! {
    /**
    Disallow unnecessary boolean casts.

    In contexts where expression will be coerced to a `Boolean` (e.g. `if`),
    casting to a boolean (using `!!` or `Boolean(expr)`) is unnecessary.

    ## Invalid Code Examples

    ```js
    if (!!foo) {}
    while (!!foo) {}

    var foo = !!!bar;
    var foo = Boolean(!!bar);
    ```
    */
    #[derive(Default)]
    #[serde(default)]
    NoExtraBooleanCast,
    errors,
    "no-extra-boolean-cast",
    /// If this option is `true`, this rule will also check for unnecessary boolean
    /// cast inside logical expression, which is disabled by default.
    pub enforce_for_logical_operands: bool,
}

const BOOL_NODE_KINDS: [SyntaxKind; 5] = [IF_STMT, DO_WHILE_STMT, WHILE_STMT, COND_EXPR, FOR_STMT];

/// The reason the cast is not needed
#[derive(Debug)]
enum Reason {
    ExplicitBoolean(SyntaxNode),
    ImplicitCast(SyntaxNode),
    LogicalNotCast(SyntaxToken),
}

#[typetag::serde]
impl CstRule for NoExtraBooleanCast {
    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        match node.kind() {
            UNARY_EXPR => {
                let expr = node.to::<UnaryExpr>();
                let child = skip_grouping(expr.syntax().first_child(), SyntaxNode::first_child)
                    .next()?
                    .try_to::<Expr>()?;

                if expr.op()? != op![!]
                    || !matches!(child, Expr::UnaryExpr(expr) if expr.op()? == op![!])
                {
                    return None;
                }

                if let Some(reason) = in_bool_ctx(node, self.enforce_for_logical_operands) {
                    let err = ctx.err(self.name(), "redundant double negation").primary(
                        expr.op_token().unwrap().text_range(),
                        "this operator is redundant...",
                    );
                    ctx.add_err(reason_labels(err, reason));
                }
            }
            CALL_EXPR => {
                if !util::constructor_or_call_with_callee(node, "Boolean") {
                    return None;
                }

                if let Some(reason) = in_bool_ctx(node, self.enforce_for_logical_operands) {
                    let err = ctx.err(self.name(), "redundant `Boolean` call").primary(
                        node.trimmed_range(),
                        "this call to `Boolean` is redundant...",
                    );
                    ctx.add_err(reason_labels(err, reason));
                }
            }
            _ => {}
        }
        None
    }
}

fn reason_labels(builder: DiagnosticBuilder, reason: Reason) -> DiagnosticBuilder {
    match reason {
        Reason::ExplicitBoolean(node) => builder.secondary(
            node.trimmed_range(),
            "...because `Boolean` already creates a boolean value",
        ),
        Reason::ImplicitCast(node) => builder.secondary(
            node.trimmed_range(),
            "...because this condition already implicitly coerces to a boolean",
        ),
        Reason::LogicalNotCast(token) => builder.secondary(
            token.text_range(),
            "...because this operator already coerces to a boolean",
        ),
    }
}

fn in_bool_ctx(node: &SyntaxNode, enforce_logical: bool) -> Option<Reason> {
    let parent = skip_grouping(node.parent(), SyntaxNode::parent).nth(1);
    if let Some(parent) = parent {
        // TODO: Once we have scope analysis we can know if Boolean was shadowed
        // new Boolean(foo) or Boolean(foo)
        if util::constructor_or_call_with_callee(parent.clone(), "Boolean") {
            return parent
                .child_with_kind(ARG_LIST)
                .filter(|cond| {
                    skip_grouping(cond.first_child(), SyntaxNode::first_child)
                        .next()
                        .as_ref()
                        == Some(node)
                })
                .map(|_| Reason::ExplicitBoolean(parent));
        }
    }

    if let Some(casted_node) = implicitly_casted_node(node) {
        let cond_node = match casted_node.kind() {
            IF_STMT | DO_WHILE_STMT | WHILE_STMT => casted_node
                .child_with_kind(CONDITION)
                .and_then(|n| n.first_child()),
            FOR_STMT => casted_node.child_with_kind(FOR_STMT_TEST)?.first_child(),
            COND_EXPR => casted_node
                .to::<CondExpr>()
                .test()
                .map(|x| x.syntax().clone()),
            _ => None,
        };

        return cond_node
            .filter(|inner| {
                skip_grouping(inner.clone(), SyntaxNode::first_child)
                    .next()
                    .as_ref()
                    == Some(node)
            })
            .map(Reason::ImplicitCast);
    }

    // TODO: Improve error message, or even detection, of `!!!foo`,
    // without breaking `!Boolean(foo)`.
    let parent = skip_grouping(node.parent(), SyntaxNode::parent).next()?;
    if let Some(unexpr) = parent.try_to::<UnaryExpr>() {
        let (tok, op) = unexpr.op_details()?;
        if op == op![!] {
            return Some(Reason::LogicalNotCast(tok));
        }
    }

    if enforce_logical {
        let expr = parent.try_to::<BinExpr>()?;

        expr.op()
            .and_then(|op| match op {
                op if op == op![||] || op == op![&&] => Some(()),
                _ => None,
            })
            .and_then(|_| in_bool_ctx(expr.syntax(), true))
    } else {
        None
    }
}

fn skip_grouping<F>(
    child: impl Into<Option<SyntaxNode>>,
    successor: F,
) -> impl Iterator<Item = SyntaxNode>
where
    F: FnMut(&SyntaxNode) -> Option<SyntaxNode>,
{
    std::iter::successors(child.into(), successor).filter(|node| node.kind() != GROUPING_EXPR)
}

fn implicitly_casted_node(node: &SyntaxNode) -> Option<SyntaxNode> {
    let parent = skip_grouping(node.parent(), SyntaxNode::parent).next();
    if matches!(
        parent.map(|parent| parent.kind()),
        Some(CONDITION) | Some(FOR_STMT_TEST)
    ) {
        skip_grouping(node.parent(), SyntaxNode::parent)
            .nth(1)
            .filter(|node| BOOL_NODE_KINDS.contains(&node.kind()))
    } else {
        skip_grouping(node.parent(), SyntaxNode::parent)
            .next()
            .filter(|node| BOOL_NODE_KINDS.contains(&node.kind()))
    }
}

rule_tests! {
    NoExtraBooleanCast::default(),
    err: {
        "if (!!foo) {}",
        "do {} while (!!foo)",
        "while (!!foo) {}",
        "!!foo ? bar : baz",
        "for (; !!foo;) {}",
        "!!!foo",
        "Boolean(!!foo)",
        "new Boolean(!!foo)",
        "if (Boolean(foo)) {}",
        "do {} while (Boolean(foo))",
        "while (Boolean(foo)) {}",
        "Boolean(foo) ? bar : baz",
        "for (; Boolean(foo);) {}",
        "!Boolean(foo)",
        "!Boolean(foo && bar)",
        "!Boolean(foo + bar)",
        "!Boolean(+foo)",
        "!Boolean(foo())",
        "!Boolean(foo = bar)",
        "!Boolean(...foo);",
        "!Boolean(foo, bar());",
        "!Boolean((foo, bar()));",
        "!Boolean();",
        "!(Boolean());",
        "if (!Boolean()) { foo() }",
        "while (!Boolean()) { foo() }",
        "if (Boolean()) { foo() }",
        "while (Boolean()) { foo() }",
        "Boolean(Boolean(foo))",
        "Boolean(!!foo, bar)",
        "x=!!a ? b : c ",
        "void!Boolean()",
        "void! Boolean()",
        "typeof!Boolean()",
        "(!Boolean())",
        "+!Boolean()",
        "void !Boolean()",
        "void(!Boolean())",
        "void/**/!Boolean()",
        "!/**/!!foo",
        "!!/**/!foo",
        "!!!/**/foo",
        "!!!foo/**/",
        "if(!/**/!foo);",
        "(!!/**/foo ? 1 : 2)",
        "!/**/Boolean(foo)",
        "!Boolean/**/(foo)",
        "!Boolean(/**/foo)",
        "!Boolean(foo/**/)",
        "!Boolean(foo)/**/",
        "if(Boolean/**/(foo));",
        "(Boolean(foo/**/) ? 1 : 2)",
        "/**/!Boolean()",
        "!/**/Boolean()",
        "!Boolean/**/()",
        "!Boolean(/**/)",
        "!Boolean()/**/",
        "if(!/**/Boolean());",
        "(!Boolean(/**/) ? 1 : 2)",
        "if(/**/Boolean());",
        "if(Boolean/**/());",
        "if(Boolean(/**/));",
        "if(Boolean()/**/);",
        "(Boolean/**/() ? 1 : 2)",
        "Boolean(!!(a, b))",
        "Boolean(Boolean((a, b)))",
        "Boolean((!!(a, b)))",
        "Boolean((Boolean((a, b))))",
        "Boolean(!(!(a, b)))",
        "Boolean((!(!(a, b))))",
        "Boolean(!!(a = b))",
        "Boolean((!!(a = b)))",
        "Boolean(Boolean(a = b))",
        "Boolean(Boolean((a += b)))",
        "Boolean(!!(a === b))",
        "Boolean(!!((a !== b)))",
        "Boolean(!!a.b)",
        "Boolean(Boolean((a)))",
        "Boolean((!!(a)))",
        "new Boolean(!!(a, b))",
        "new Boolean(Boolean((a, b)))",
        "new Boolean((!!(a, b)))",
        "new Boolean((Boolean((a, b))))",
        "new Boolean(!(!(a, b)))",
        "new Boolean((!(!(a, b))))",
        "new Boolean(!!(a = b))",
        "new Boolean((!!(a = b)))",
        "new Boolean(Boolean(a = b))",
        "new Boolean(Boolean((a += b)))",
        "new Boolean(!!(a === b))",
        "new Boolean(!!((a !== b)))",
        "new Boolean(!!a.b)",
        "new Boolean(Boolean((a)))",
        "new Boolean((!!(a)))",
        "if (!!(a, b));",
        "if (Boolean((a, b)));",
        "if (!(!(a, b)));",
        "if (!!(a = b));",
        "if (Boolean(a = b));",
        "if (!!(a > b));",
        "if (Boolean(a === b));",
        "if (!!f(a));",
        "if (Boolean(f(a)));",
        "if (!!(f(a)));",
        "if ((!!f(a)));",
        "if ((Boolean(f(a))));",
        "if (!!a);",
        "if (Boolean(a));",
        "while (!!(a, b));",
        "while (Boolean((a, b)));",
        "while (!(!(a, b)));",
        "while (!!(a = b));",
        "while (Boolean(a = b));",
        "while (!!(a > b));",
        "while (Boolean(a === b));",
        "while (!!f(a));",
        "while (Boolean(f(a)));",
        "while (!!(f(a)));",
        "while ((!!f(a)));",
        "while ((Boolean(f(a))));",
        "while (!!a);",
        "while (Boolean(a));",
        "do {} while (!!(a, b));",
        "do {} while (Boolean((a, b)));",
        "do {} while (!(!(a, b)));",
        "do {} while (!!(a = b));",
        "do {} while (Boolean(a = b));",
        "do {} while (!!(a > b));",
        "do {} while (!!f(a));",
        "do {} while (Boolean(f(a)));",
        "do {} while (!!(f(a)));",
        "do {} while ((!!f(a)));",
        "do {} while ((Boolean(f(a))));",
        "do {} while (!!a);",
        "do {} while (Boolean(a));",
        "for (; !!(a, b););",
        "for (; Boolean((a, b)););",
        "for (; !(!(a, b)););",
        "for (; !!(a = b););",
        "for (; Boolean(a = b););",
        "for (; !!(a > b););",
        "for (; Boolean(a === b););",
        "for (; !!f(a););",
        "for (; Boolean(f(a)););",
        "for (; !!(f(a)););",
        "for (; (!!f(a)););",
        "for (; (Boolean(f(a))););",
        "for (; !!a;);",
        "for (; Boolean(a););",
        "!!(a, b) ? c : d",
        "(!!(a, b)) ? c : d",
        "Boolean((a, b)) ? c : d",
        "!!(a = b) ? c : d",
        "Boolean(a -= b) ? c : d",
        "(Boolean((a *= b))) ? c : d",
        "!!(a ? b : c) ? d : e",
        "Boolean(a ? b : c) ? d : e",
        "!!(a || b) ? c : d",
        "Boolean(a && b) ? c : d",
        "!!(a === b) ? c : d",
        "Boolean(a < b) ? c : d",
        "!!((a !== b)) ? c : d",
        "Boolean((a >= b)) ? c : d",
        "!!+a ? b : c",
        "!!+(a) ? b : c",
        "Boolean(!a) ? b : c",
        "!!f(a) ? b : c",
        "(!!f(a)) ? b : c",
        "Boolean(a.b) ? c : d",
        "!!a ? b : c",
        "Boolean(a) ? b : c",
        "!!!(a, b)",
        "!Boolean((a, b))",
        "!!!(a = b)",
        "!!(!(a += b))",
        "!(!!(a += b))",
        "!Boolean(a -= b)",
        "!Boolean((a -= b))",
        "!(Boolean(a -= b))",
        "!!!(a || b)",
        "!Boolean(a || b)",
        "!!!(a && b)",
        "!Boolean(a && b)",
        "!!!(a != b)",
        "!!!(a === b)",
        "var x = !Boolean(a > b)",
        "!!!(a - b)",
        "!!!(a ** b)",
        "!Boolean(a ** b)",
        "!Boolean(!a)",
        "!Boolean((!a))",
        "!Boolean(!(a))",
        "!(Boolean(!a))",
        "!!!+a",
        "!!!(+a)",
        "!!(!+a)",
        "!(!!+a)",
        "!Boolean((-a))",
        "!Boolean(-(a))",
        "!!!(--a)",
        "!Boolean(a++)",
        "!!!f(a)",
        "!!!(f(a))",
        "!!!a",
        "!Boolean(a)",
        "!Boolean(!!a)",
        "!Boolean(Boolean(a))",
        "!Boolean(Boolean(!!a))",
        "while (a) { if (!!b) {} }",
        "while (a) { if (Boolean(b)) {} }",
        "if (a) { const b = !!!c; }",
        "if (a) { const b = !Boolean(c); }",
        "for (let a = 0; a < n; a++) { if (!!b) {} }",
        "for (let a = 0; a < n; a++) { if (Boolean(b)) {} }",
        "do { const b = !!!c; } while(a)",
        "do { const b = !Boolean(c); } while(a)",
    },
    ok: {
        "Boolean(bar, !!baz);",
        "var foo = !!bar;",
        "function foo() { return !!bar; }",
        "var foo = bar() ? !!baz : !!bat",
        "for(!!foo;;) {}",
        "for(;; !!foo) {}",
        "var foo = Boolean(bar);",
        "function foo() { return Boolean(bar); }",
        "var foo = bar() ? Boolean(baz) : Boolean(bat)",
        "for(Boolean(foo);;) {}",
        "for(;; Boolean(foo)) {}",
        "if (new Boolean(foo)) {}"
    }
}

rule_tests! {
    logical_operands_valid,
    logical_operands_invalid,
    NoExtraBooleanCast { enforce_for_logical_operands: true },
    err: {
        "if (!!foo || bar) {}",
        "while (!!foo && bar) {}",
        "if ((!!foo || bar) && baz) {}",
        "foo && Boolean(bar) ? baz : bat",
        "var foo = new Boolean(!!bar || baz)"
    },
    ok: {
        "if (foo || bar) {}",
        "while (foo && bar) {}",
        "if ((foo || bar) && baz) {}",
        "foo && bar ? baz : bat",
        "var foo = new Boolean(bar || baz)",
        "var foo = !!bar || baz;"
    }
}