rslint_core/groups/errors/
no_sparse_arrays.rs

1use crate::rule_prelude::*;
2
3declare_lint! {
4    /**
5    Disallow sparse arrays.
6
7    Sparse arrays are arrays with empty slots, they are denoted by extra commas, such as:
8
9    ```js
10    let foo = [,,];
11    let foo = [bar,, baz];
12    ```
13
14    Sparse elements will be filled in as undefined elements and count towards array length.
15    This is often a typo or is hard to comprehend and an explicit method should be used.
16
17    ## Invalid Code Examples
18
19    ```js
20    let foo = [,];
21    let bar = [foo,, bar];
22    ```
23    */
24    #[derive(Default)]
25    NoSparseArrays,
26    errors,
27    tags(Recommended),
28    "no-sparse-arrays"
29}
30
31#[typetag::serde]
32impl CstRule for NoSparseArrays {
33    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
34        let elems = node.try_to::<ast::ArrayExpr>()?.sparse_elements();
35        if !elems.is_empty() {
36            let mut err = ctx.err(self.name(), "sparse arrays are not allowed");
37            for elem in elems {
38                err = err.primary(elem, "");
39            }
40            err = err.footer_note(
41                "the sparse elements will become elements with a value of `undefined`",
42            );
43            ctx.add_err(err);
44        }
45        None
46    }
47}
48
49rule_tests! {
50    NoSparseArrays::default(),
51    err: {
52        "[,]",
53        "[...2,, 3]",
54        "[4,,]"
55    },
56    ok: {
57        "[1, 2]",
58        "[3,]"
59    }
60}