rulewright 0.1.2

Executable engineering standards for Rust workspaces
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
#[cfg(test)]
use googletest::prelude::*;
use ra_ap_syntax::{AstNode, SyntaxNode, SyntaxToken, ast, syntax_editor::SyntaxEditor};

use crate::{AstCtx, Example, Violation};

use super::support::{gap_before_attached_comment, has_blank_line};

const CONTROL_FLOW: &str = "control-flow";
const FUNCTIONS: &str = "functions";
const LET_RUNS: &str = "let-runs";
const RETURNS: &str = "returns";
const TAIL_EXPRESSIONS: &str = "tail-expressions";
pub(crate) const VALID_BOUNDARIES: &[&str] =
    &[FUNCTIONS, CONTROL_FLOW, LET_RUNS, RETURNS, TAIL_EXPRESSIONS];

#[rustfmt::skip]
const EXAMPLES: &[Example] = &[
    Example {
        label: "return has padding",
        code: "fn value(flag: bool) -> usize {\n    let value = 1;\n\n    return value;\n}",
        pass: true,
    },
    Example {
        label: "return needs padding",
        code: "fn value() -> usize {\n    let value = 1;\n    return value;\n}",
        pass: false,
    },
    Example {
        label: "first return is exempt",
        code: "fn value() -> usize {\n    return 1;\n}",
        pass: true,
    },
    Example {
        label: "tail expression has padding",
        code: "fn value() -> usize {\n    let value = 1;\n\n    value\n}",
        pass: true,
    },
    Example {
        label: "tail expression needs padding",
        code: "fn value() -> usize {\n    let value = 1;\n    value\n}",
        pass: false,
    },
    Example {
        label: "effect followed by tail expression stays compact",
        code: "fn value() -> Result<(), Error> {\n    verify_state()?;\n    finish()\n}",
        pass: true,
    },
    Example {
        label: "let run needs following padding",
        code: "fn run() {\n    let one = 1;\n    let two = 2;\n    consume(one, two);\n}",
        pass: false,
    },
    Example {
        label: "let run followed by padding",
        code: "fn run() {\n    let one = 1;\n    let two = 2;\n\n    consume(one, two);\n}",
        pass: true,
    },
    Example {
        label: "multiline control expression is padded",
        code: "fn run(flag: bool) {\n    prepare();\n\n    if flag {\n        work();\n    }\n\n    finish();\n}",
        pass: true,
    },
    Example {
        label: "multiline control expression needs padding before and after",
        code: "fn run(flag: bool) {\n    prepare();\n    if flag {\n        work();\n    }\n    finish();\n}",
        pass: false,
    },
    Example {
        label: "let after multiline guard needs padding",
        code: "fn inspect(path: &Path) {\n    if path.is_dir() {\n        return;\n    }\n    let manifest = path.join(\"Cargo.toml\");\n}",
        pass: false,
    },
    Example {
        label: "compact guard needs following padding",
        code: "fn inspect(path: &Path) {\n    if path.is_dir() { return; }\n    observe(path);\n}",
        pass: false,
    },
    Example {
        label: "compact consecutive guards need padding",
        code: "fn validate(one: bool, two: bool) {\n    if one { return; }\n    if two { return; }\n}",
        pass: false,
    },
    Example {
        label: "adjacent free functions need padding",
        code: "fn one() {}\nfn two() {}",
        pass: false,
    },
    Example {
        label: "separated free functions",
        code: "fn one() {}\n\nfn two() {}",
        pass: true,
    },
    Example {
        label: "adjacent methods need padding",
        code: "impl Value {\n    fn one() {}\n    fn two() {}\n}",
        pass: false,
    },
    Example {
        label: "adjacent trait methods need padding",
        code: "trait Value {\n    fn one();\n    fn two();\n}",
        pass: false,
    },
    Example {
        label: "else-if remains one control-flow chain",
        code: "fn choose(one: bool, two: bool) {\n    if one { work(); } else if two { work(); }\n}",
        pass: true,
    },
    Example {
        label: "first and last multiline controls need only interior padding",
        code: "fn run(flag: bool) {\n    if flag {\n        work();\n    }\n\n    loop {\n        break;\n    }\n}",
        pass: true,
    },
    Example {
        label: "block-like control expression separates let runs",
        code: "fn run(mut bits: u32) {\n    while bits != 0 {\n        let index = bits.trailing_zeros();\n\n        if index > 10 {\n            observe(index);\n        }\n\n        bits &= bits - 1;\n    }\n}",
        pass: true,
    },
    Example {
        label: "single-expression closure is exempt",
        code: "fn run() {\n    consume(|| { 1 });\n}",
        pass: true,
    },
    Example {
        label: "directive stays attached to multiline control",
        code: "fn run(flag: bool) {\n    let value = String::new();\n    // #rw(rust_panic) bounded control path\n    if flag {\n        consume(value.clone());\n    }\n}",
        pass: false,
    },
    Example {
        label: "directive stays attached to tail expression",
        code: "fn value() -> usize {\n    let value = 1;\n    // #rw(rust_panic) representative fixture\n    value\n}",
        pass: false,
    },
    Example {
        label: "block directive stays attached to loop",
        code: "fn run(values: &[String]) {\n    let mut copies = Vec::new();\n    // #rw(block: rust_panic) bounded fixture\n    for value in values {\n        copies.push(value.clone());\n    }\n}",
        pass: false,
    },
];

crate::ast_tree_rule!(
    padding,
    "Require configurable blank-line boundaries between functions and distinct statement groups.",
    "Consistent vertical separation makes functions, control flow, logical setup stages, and tail values easier to scan. Keep attributes, suppression directives, safety comments, and invariant explanations attached to the code they justify instead of inserting whitespace through those relationships.",
    Low,
    fix_padding,
    params {
        boundaries: [String] = [
            "functions",
            "control-flow",
            "let-runs",
            "returns",
            "tail-expressions",
        ] in [
            FUNCTIONS,
            CONTROL_FLOW,
            LET_RUNS,
            RETURNS,
            TAIL_EXPRESSIONS,
        ],
    },
);

#[derive(Clone)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "padding decisions combine four independent syntax classifications"
)]
struct Entry {
    syntax: SyntaxNode,
    is_let: bool,
    is_return: bool,
    is_control: bool,
    is_tail: bool,
}

fn check_padding(ctx: &AstCtx<'_>) -> Vec<Violation> {
    let mut violations = Vec::new();
    let boundaries = ctx
        .file
        .config
        .get_str_array("rust_padding", &PADDING_PARAMS[0]);

    for list in ctx.nodes::<ast::StmtList>() {
        for entry in missing_gaps(&list, &boundaries) {
            violations.push(ctx.violation(
                entry.syntax.clone(),
                format!("blank line required before {}", entry_label(&entry)),
            ));
        }
    }

    if boundary_enabled(&boundaries, FUNCTIONS) {
        violations.extend(missing_function_gaps(ctx).into_iter().map(|function| {
            ctx.violation(
                &function,
                "consecutive function definitions need a blank line between them",
            )
        }));
    }

    violations
}

fn entries(list: &ast::StmtList) -> Vec<Entry> {
    let tail = list.tail_expr();

    list.syntax()
        .children()
        .filter_map(|child| {
            if let Some(statement) = ast::Stmt::cast(child.clone()) {
                return Some(entry_from_stmt(statement));
            }

            let expression = ast::Expr::cast(child)?;

            Some(Entry {
                is_control: is_control(&expression),
                is_return: matches!(expression, ast::Expr::ReturnExpr(_)),
                is_tail: tail
                    .as_ref()
                    .is_some_and(|tail| tail.syntax() == expression.syntax()),
                syntax: expression.syntax().clone(),
                is_let: false,
            })
        })
        .collect()
}

#[expect(
    clippy::needless_pass_by_value,
    reason = "statement iterators yield owned facade nodes and this helper is used directly by Iterator::map"
)]
fn entry_from_stmt(statement: ast::Stmt) -> Entry {
    let is_let = matches!(statement, ast::Stmt::LetStmt(_));
    let expression = match &statement {
        ast::Stmt::ExprStmt(statement) => statement.expr(),
        _ => None,
    };

    Entry {
        syntax: statement.syntax().clone(),
        is_let,
        is_return: expression
            .as_ref()
            .is_some_and(|expr| matches!(expr, ast::Expr::ReturnExpr(_))),
        is_control: expression.as_ref().is_some_and(is_control),
        is_tail: false,
    }
}

fn is_control(expression: &ast::Expr) -> bool {
    matches!(
        expression,
        ast::Expr::IfExpr(_)
            | ast::Expr::MatchExpr(_)
            | ast::Expr::ForExpr(_)
            | ast::Expr::WhileExpr(_)
            | ast::Expr::LoopExpr(_)
    )
}

fn padding_gap_token(current: &SyntaxNode) -> Option<SyntaxToken> {
    gap_before_attached_comment(current)
}

fn missing_gaps(list: &ast::StmtList, boundaries: &[String]) -> Vec<Entry> {
    let entries = entries(list);

    entries
        .iter()
        .enumerate()
        .skip(1)
        .filter(|(index, current)| {
            let previous = &entries[index - 1];
            let required = boundary_enabled(boundaries, RETURNS) && current.is_return
                || boundary_enabled(boundaries, TAIL_EXPRESSIONS)
                    && current.is_tail
                    && previous.is_let
                || boundary_enabled(boundaries, LET_RUNS) && previous.is_let && !current.is_let
                || boundary_enabled(boundaries, CONTROL_FLOW)
                    && (current.is_control || previous.is_control);

            required
                && padding_gap_token(&current.syntax)
                    .is_some_and(|padding_gap| !has_blank_line(&padding_gap))
        })
        .map(|(_, entry)| entry.clone())
        .collect()
}

fn missing_function_gaps(ctx: &AstCtx<'_>) -> Vec<ast::Fn> {
    ctx.nodes::<ast::Fn>()
        .filter_map(|current| {
            let next = current.syntax().next_sibling().and_then(ast::Fn::cast)?;

            function_gap_token(next.syntax())
                .is_some_and(|gap| !has_blank_line(&gap))
                .then_some(next)
        })
        .collect()
}

fn function_gap_token(current: &SyntaxNode) -> Option<SyntaxToken> {
    gap_before_attached_comment(current)
}

fn boundary_enabled(boundaries: &[String], boundary: &str) -> bool {
    debug_assert!(
        VALID_BOUNDARIES.contains(&boundary),
        "padding boundary must be declared in VALID_BOUNDARIES"
    );

    boundaries.iter().any(|configured| configured == boundary)
}

const fn entry_label(entry: &Entry) -> &'static str {
    if entry.is_return {
        "return statement"
    } else if entry.is_tail {
        "tail expression"
    } else if entry.is_control {
        "control-flow statement"
    } else {
        "statement following a let run"
    }
}

fn fix_padding(ctx: &AstCtx<'_>, _violations: &[Violation]) -> Option<String> {
    let (editor, root) = SyntaxEditor::with_ast_node(ctx.root);
    let boundaries = ctx
        .file
        .config
        .get_str_array("rust_padding", &PADDING_PARAMS[0]);
    let mut changed = false;

    for list in root.syntax().descendants().filter_map(ast::StmtList::cast) {
        for entry in missing_gaps(&list, &boundaries) {
            let token = padding_gap_token(&entry.syntax)?;

            editor.replace(
                token.clone(),
                editor.make().whitespace(&format!("\n{}", token.text())),
            );
            changed = true;
        }
    }

    if boundary_enabled(&boundaries, FUNCTIONS) {
        for function in root.syntax().descendants().filter_map(ast::Fn::cast) {
            let Some(next) = function.syntax().next_sibling().and_then(ast::Fn::cast) else {
                continue;
            };
            let Some(token) = function_gap_token(next.syntax()).filter(|gap| !has_blank_line(gap))
            else {
                continue;
            };

            editor.replace(
                token.clone(),
                editor.make().whitespace(&format!("\n{}", token.text())),
            );
            changed = true;
        }
    }

    changed.then(|| editor.finish().new_root().to_string())
}

crate::rulewright_ast_test!(check_padding, {
    crate::example_tests!(EXAMPLES, check_padding);
    crate::fix_tests!(EXAMPLES, ast_tree, check_padding, fix_padding);

    #[gtest]
    fn fix_places_padding_before_attached_comments() -> Result<()> {
        let cases = [
            (
                "fn run(flag: bool) {\n    let value = String::new();\n    // #rw(rust_panic) bounded control path\n    if flag {\n        consume(value.clone());\n    }\n}",
                "fn run(flag: bool) {\n    let value = String::new();\n\n    // #rw(rust_panic) bounded control path\n    if flag {\n        consume(value.clone());\n    }\n}",
            ),
            (
                "fn value() -> usize {\n    let value = 1;\n    // #rw(rust_panic) representative fixture\n    value\n}",
                "fn value() -> usize {\n    let value = 1;\n\n    // #rw(rust_panic) representative fixture\n    value\n}",
            ),
            (
                "fn run(values: &[String]) {\n    let mut copies = Vec::new();\n    // #rw(block: rust_panic) bounded fixture\n    for value in values {\n        copies.push(value.clone());\n    }\n}",
                "fn run(values: &[String]) {\n    let mut copies = Vec::new();\n\n    // #rw(block: rust_panic) bounded fixture\n    for value in values {\n        copies.push(value.clone());\n    }\n}",
            ),
            (
                "fn visit(points: &[Point]) {\n    let first = &points[0];\n    // BOUNDS: the empty case returned above, so index one starts the remaining points.\n    for point in &points[1..] {\n        consume(first, point);\n    }\n}",
                "fn visit(points: &[Point]) {\n    let first = &points[0];\n\n    // BOUNDS: the empty case returned above, so index one starts the remaining points.\n    for point in &points[1..] {\n        consume(first, point);\n    }\n}",
            ),
        ];

        for (source, expected) in cases {
            verify_eq!(
                crate::apply_ast_tree_fix(source, check_padding, fix_padding),
                expected
            )?;
        }

        Ok(())
    }

    #[gtest]
    fn every_multiline_control_kind_is_padded_from_ordinary_statements() -> Result<()> {
        let controls = [
            "if flag {\n        work();\n    }",
            "match flag {\n        true => work(),\n        false => work(),\n    }",
            "for value in values {\n        consume(value);\n    }",
            "while flag {\n        work();\n        break;\n    }",
            "loop {\n        work();\n        break;\n    }",
        ];

        for control in controls {
            let source = format!(
                "fn run(flag: bool, values: &[usize]) {{\n    prepare();\n    {control}\n    finish();\n}}"
            );
            let violations = run(&source);

            verify_eq!(violations.len(), 2)?;
        }

        Ok(())
    }

    #[gtest]
    fn configured_boundaries_can_disable_function_padding() -> Result<()> {
        let source = "fn one() {}\nfn two() {}";
        let mut config = crate::Config::generate_default(&[("rust_padding", PADDING_PARAMS)]);

        config
            .rules
            .get_mut("rust_padding")
            .or_fail()?
            .params
            .insert(
                "boundaries".to_owned(),
                toml::Value::Array(vec![toml::Value::String(CONTROL_FLOW.to_owned())]),
            );
        let lines: Vec<&str> = source.lines().collect();
        let file = crate::FileCtx {
            rel: "fixture.rs",
            path: crate::Path::new("fixture.rs"),
            package_name: None,
            package_publishable: None,
            lines: &lines,
            contents: source,
            config: &config,
        };
        let parse = ra_ap_syntax::SourceFile::parse(source, ra_ap_syntax::Edition::Edition2024);
        let root = parse.tree();
        let line_index = line_index::LineIndex::new(source);
        let ctx = AstCtx::new(&file, &root, &line_index, false);

        verify_true!(check_padding(&ctx).is_empty())
    }

    #[gtest]
    fn function_fix_keeps_an_attached_comment_with_the_following_function() -> Result<()> {
        let source = "fn one() {}\n// Explains two.\nfn two() {}";
        let expected = "fn one() {}\n\n// Explains two.\nfn two() {}";

        verify_eq!(
            crate::apply_ast_tree_fix(source, check_padding, fix_padding),
            expected
        )
    }

    #[gtest]
    fn function_fix_keeps_a_trailing_comment_with_the_previous_function() -> Result<()> {
        let source = "fn one() {} // Explains one.\nfn two() {}";
        let expected = "fn one() {} // Explains one.\n\nfn two() {}";
        let first = crate::apply_ast_tree_fix(source, check_padding, fix_padding);

        verify_eq!(first, expected)?;
        verify_eq!(
            crate::apply_ast_tree_fix(&first, check_padding, fix_padding),
            expected
        )
    }
});