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
use crate::rule_prelude::*;
use crate::util::StyleExt;
use crate::Inferable;
use ast::{BlockStmt, SwitchStmt};
use SyntaxKind::{BLOCK_STMT, L_CURLY, R_CURLY, SWITCH_STMT};

declare_lint! {
    /**
    Enforce or disallow spaces inside of blocks after the opening and closing brackets.

    This rule enforces consistent spacing inside blocks by enforcing the opening token and the next token
    being on the same line. It also enforces consistent spacing with a closing token and the previous token being
    on the same line.

    ## Always

    ### Incorrect code examples

    ```js
    function foo() {return true;}
    if (foo) { bar = 0;}
    function baz() {let i = 0;
        return i;
    }
    ```

    ### Correct code examples

    ```js
    function foo() { return true; }
    if (foo) { bar = 0; }
    ```

    ## Never

    ### Incorrect code examples

    ```js
    function foo() { return true; }
    if (foo) { bar = 0;}
    ```

    ### Correct code examples

    ```js
    function foo() {return true;}
    if (foo) {bar = 0;}
    ```
    */
    #[serde(default)]
    #[derive(rslint_macros::Mergeable)]
    BlockSpacing,
    style,
    "block-spacing",
    /// The style of spacing, either "always" (default) to require one or more spaces, or
    /// "never" to disallow spaces
    pub style: String
}

impl Default for BlockSpacing {
    fn default() -> Self {
        Self {
            style: "always".to_string(),
        }
    }
}

#[typetag::serde]
impl CstRule for BlockSpacing {
    fn check_node(&self, node: &SyntaxNode, ctx: &mut RuleCtx) -> Option<()> {
        if !matches!(node.kind(), SWITCH_STMT | BLOCK_STMT) {
            return None;
        }

        let open_token = node.token_with_kind(L_CURLY)?;
        let close_token = node.token_with_kind(R_CURLY)?;
        if is_empty(node) {
            return None;
        }

        let msg = |loc: &str, tok: &str| {
            if self.style == "always" {
                format!("Expected a space {} `{}`", loc, tok)
            } else {
                format!("Unexpected space(s) {} `{}`", loc, tok)
            }
        };

        if !(open_token.trailing_trivia_has_linebreak(true)
            || (open_token.has_trailing_whitespace(false, true) == (self.style == "always")))
        {
            let err = ctx.err(self.name(), msg("after", "{")).primary(node, "");

            ctx.add_err(err);
            let fix = ctx
                .fix()
                .delete_multiple(open_token.trailing_whitespace(false));
            if self.style == "always" {
                fix.insert_after(open_token, " ");
            }
        }

        if !(close_token.leading_trivia_has_linebreak(true)
            || (close_token.has_leading_whitespace(false, false) == (self.style == "always")))
        {
            let err = ctx.err(self.name(), msg("before", "}")).primary(node, "");

            ctx.add_err(err);
            let fix = ctx
                .fix()
                .delete_multiple(close_token.leading_whitespace(false));
            if self.style == "always" {
                fix.insert_before(close_token, " ");
            }
        }
        None
    }
}

fn is_empty(node: &SyntaxNode) -> bool {
    node.try_to::<SwitchStmt>()
        .map(|x| x.cases().next().is_none())
        .unwrap_or_default()
        || node
            .try_to::<BlockStmt>()
            .map(|x| x.stmts().next().is_none())
            .unwrap_or_default()
}

#[typetag::serde]
impl Inferable for BlockSpacing {
    fn infer(&mut self, nodes: &[SyntaxNode]) {
        let mut inferred_structs = vec![];
        for node in nodes {
            if matches!(node.kind(), SWITCH_STMT | BLOCK_STMT) {
                let mut ctx = RuleCtx::dummy_ctx();
                Self::default().check_node(node, &mut ctx);
                if ctx.diagnostics.is_empty() {
                    inferred_structs.push(Self::default());
                } else {
                    inferred_structs.push(Self {
                        style: "never".to_string(),
                    });
                }
            }
        }
        if let Some(new) = Self::merge(inferred_structs) {
            *self = new;
        }
    }
}

rule_tests! {
    BlockSpacing::default(),
    err: {
        "{foo();}",
        "{foo();}",
        "{ foo();}",
        "{foo(); }",
        "{foo();\n}",
        "if (a) {foo();}",
        "if (a) {} else {foo();}",
        "switch (a) {case 0: foo();}",
        "while (a) {foo();}",
        "do {foo();} while (a);",
        "for (;;) {foo();}",
        "for (var a in b) {foo();}",
        "for (var a of b) {foo();}",
        "try {foo();} catch (e) {foo();} finally {foo();}",
        "function foo() {bar();}",
        "(function() {bar();});",
        "(() => {bar();});",
        "if (a) {//comment\n foo(); }"
    },
    ok: {
        "{ foo(); }",
        "{ foo();\n}",
        "{\nfoo(); }",
        "{\r\nfoo();\r\n}",
        "if (a) { foo(); }",
        "if (a) {} else { foo(); }",
        "switch (a) {}",
        "switch (a) { case 0: foo(); }",
        "while (a) { foo(); }",
        "do { foo(); } while (a);",
        "for (;;) { foo(); }",
        "for (var a in b) { foo(); }",
        "for (var a of b) { foo(); }",
        "try { foo(); } catch (e) { foo(); }",
        "function foo() { bar(); }",
        "(function() { bar(); });",
        "(() => { bar(); });",
        "if (a) { /* comment */ foo(); /* comment */ }",
        "if (a) { //comment\n foo(); }",
    }
}

rule_tests! {
    block_spacing_never_valid,
    block_spacing_never_invalid,
    BlockSpacing { style: "never".to_string() },
    err: {
        "{ foo(); }",
        "{ foo();}",
        "{foo(); }",
        "{\nfoo(); }",
        "{ foo();\n}",
        "if (a) { foo(); }",
        "if (a) {} else { foo(); }",
        "switch (a) { case 0: foo(); }",
        "while (a) { foo(); }",
        "do { foo(); } while (a);",
        "for (;;) { foo(); }",
        "for (var a in b) { foo(); }",
        "for (var a of b) { foo(); }",
        "try { foo(); } catch (e) { foo(); } finally { foo(); }",
        "function foo() { bar(); }",
        "(function() { bar(); });",
        "(() => { bar(); });",
        "if (a) { /* comment */ foo(); /* comment */ }",
        "(() => {   bar();});",
        "(() => {bar();   });",
        "(() => {   bar();   });"
    },
    ok: {
        "{foo();}",
        "{foo();\n}",
        "{\nfoo();}",
        "{\r\nfoo();\r\n}",
        "if (a) {foo();}",
        "if (a) {} else {foo();}",
        "switch (a) {}",
        "switch (a) {case 0: foo();}",
        "while (a) {foo();}",
        "do {foo();} while (a);",
        "for (;;) {foo();}",
        "for (var a in b) {foo();}",
        "for (var a of b) {foo();}",
        "try {foo();} catch (e) {foo();}",
        "function foo() {bar();}",
        "(function() {bar();});",
        "(() => {bar();});",
    }
}