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
use crate::rule_prelude::*;
use ast::*;
use SyntaxKind::*;

declare_lint! {
    /**
    Disallow constructing `Symbol` using `new`.

    `Symbol` shouldn't be constructed using `new` keyword since it results in a `TypeError`, instead
    it should be called as a function.

    ## Incorrect code examples

    ```js
    // This call results in TypeError
    const fooSymbol = new Symbol("foo");
    ```

    ## Correct code examples

    ```js
    const fooSymbol = Symbol("foo");
    ```
    */
    #[derive(Default)]
    NoNewSymbol,
    errors,
    "no-new-symbol",
}

#[typetag::serde]
impl CstRule for NoNewSymbol {
    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        if node.kind() == NEW_EXPR {
            let new_expr = node.to::<NewExpr>();

            if new_expr.object()?.syntax().text() == "Symbol" {
                let err = ctx
                    .err(self.name(), "`Symbol` cannot be called as a constructor.")
                    .primary(node, "")
                    .suggestion(
                        node,
                        "help: call it as a function instead",
                        "Symbol()",
                        Applicability::MaybeIncorrect,
                    );

                ctx.add_err(err);
                ctx.fix()
                    .delete(new_expr.new_token()?)
                    .eat_trailing_whitespace(new_expr.new_token()?);
            }
        }
        None
    }
}

rule_tests! {
    NoNewSymbol::default(),
    err: {
        "
        new Symbol()
        ",
    },
    ok: {
        "
        Symbol()
        ",
        "
        new SomeClass()
        "
    }
}