proa_source_tools 0.1.0

Source formatting, linting, and inspection engines for Proa
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use super::*;
use std::path::Path;

fn roots(source: &str) -> HtmlRoot {
    let inv = find_macros(source).into_iter().next().expect("macro");
    parse_invocation(source, &inv).expect("parse")
}

#[test]
fn layout_changes_are_render_preserving() {
    let a = roots("fn f() { html_sync! { <div class=\"x\">\n<span>\"hi\"</span></div> } }");
    let b = roots("fn f() { html_sync! {\n    <div class=\"x\">\n        <span>\"hi\"</span>\n    </div>\n} }");
    assert!(nodes_equal(&a.nodes, &b.nodes, false).is_ok());
}

#[test]
fn text_changes_fail_verification() {
    let a = roots("fn f() { html_sync! { <span>\"hi\"</span> } }");
    let b = roots("fn f() { html_sync! { <span>\"hi \"</span> } }");
    assert!(nodes_equal(&a.nodes, &b.nodes, false).is_err());
}

#[test]
fn verify_passes_on_formatter_output() {
    let source =
        "fn f() { html_sync! { <div class=\"x\" data-n={n}><span>\"hi\"</span>{body}</div> } }";
    let formatted = format_file(Path::new("sample.rs"), source).expect("format");
    let diags = verify_render_preserving(Path::new("sample.rs"), source, &formatted.output);
    assert!(diags.is_empty(), "verify failed: {diags:?}");
}

#[test]
fn verify_allows_nested_macro_name_canonicalization() {
    let source = "fn f() { html_sync! { <div>{if show { html_sync! { <button data_item on_click={handler}></button> }; }}</div> } }";
    let formatted = format_file(Path::new("sample.rs"), source).expect("format");
    let diags = verify_render_preserving(Path::new("sample.rs"), source, &formatted.output);
    assert!(diags.is_empty(), "verify failed: {diags:?}");
}

#[test]
fn verify_allows_rsjs_legacy_name_formatting() {
    let source = "#[rsjs::rsjs(component, client)]\nfn f() { html_sync! { <button data - item on - click={handler}></button> } }";
    let formatted = format_file(Path::new("sample.rs"), source).expect("format");
    let diags = verify_render_preserving(Path::new("sample.rs"), source, &formatted.output);
    assert!(diags.is_empty(), "verify failed: {diags:?}");
}

// ── Markdown templates ───────────────────────────────────────────────

#[test]
fn verification_preserves_literal_mode_but_ignores_raw_hash_count() {
    let path = Path::new("mode.rs");
    let inline = r#"fn f() { md_sync! { "One\nTwo" }; }"#;
    let block = "fn f() { md_sync! { r\"One\nTwo\" }; }";
    let hashed_block = "fn f() { md_sync! { r###\"One\nTwo\"### }; }";
    assert!(!verify_render_preserving(path, inline, block).is_empty());
    assert!(verify_render_preserving(path, block, hashed_block).is_empty());
    let formatted = format_file(path, block).unwrap();
    assert!(verify_render_preserving(path, block, &formatted.output).is_empty());
}

/// The text a Markdown template lowers to, for asserting that formatting
/// moved the template without changing what it renders.
fn md_lowered(source: &str) -> Vec<Vec<MdRenderNode>> {
    find_macros(source)
        .iter()
        .filter(|inv| inv.dialect == MacroDialect::Md)
        .filter_map(|inv| md_render_text(source, inv))
        .collect()
}

#[test]
fn anchors_md_template_to_the_macro_indentation() {
    let source = r#"impl A {
    fn render_md(self, cx: &mut WebContext<::proa_core::NoLoader, B>) -> Result<(), WriteError> {
        md_sync! {"
## {self.title}

{self.description}
"}
        .render_md(cx)
    }
}"#;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;

    assert!(
        formatted.contains("            ## {self.title}\n"),
        "template not re-anchored:\n{formatted}"
    );
    assert!(
        formatted.contains("\n            \"\n        }\n"),
        "closing quote or macro brace not canonically aligned:\n{formatted}"
    );
    assert_eq!(md_lowered(source), md_lowered(&formatted));
}

#[test]
fn md_formatting_is_idempotent() {
    let source = r#"fn f() {
    let s = md_sync! {"
        # Title

        Body.
    "};
}"#;
    let once = format_file(Path::new("sample.rs"), source).unwrap().output;
    let twice = format_file(Path::new("sample.rs"), &once).unwrap().output;
    assert_eq!(once, twice);
    assert_eq!(md_lowered(source), md_lowered(&once));
}

#[test]
fn md_formatting_preserves_relative_indentation() {
    let source = r#"fn f() {
    let s = md_sync! {"
# List

- top
  - nested

    code_line();
"};
}"#;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    // Macro indent 4 + one level = 8, and the relative offsets survive.
    assert!(
        formatted.contains("        - top\n          - nested\n"),
        "{formatted}"
    );
    assert!(
        formatted.contains("\n            code_line();\n"),
        "{formatted}"
    );
    assert_eq!(md_lowered(source), md_lowered(&formatted));
}

#[test]
fn md_formatting_handles_raw_strings() {
    let source = r####"fn f() {
    let s = md_sync! {r###"
# {title}

A "quoted" word.
"###};
}"####;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert!(
        formatted.contains("r###\"\n        # {title}\n"),
        "{formatted}"
    );
    assert!(formatted.contains("\n        \"###\n    }"), "{formatted}");
    assert_eq!(md_lowered(source), md_lowered(&formatted));
}

#[test]
fn md_formats_named_arguments_and_multiline_code_spans() {
    let source = r####"fn f() {
    md_sync! { r###"
            {if show {
            title
            }}
            `first
            second`
            "###, title = self.title
    };
}"####;
    let formatted = format_file(Path::new("named.rs"), source).unwrap();
    assert!(
        formatted.diagnostics.is_empty(),
        "{:?}",
        formatted.diagnostics
    );
    assert!(formatted.output.contains(
        "        {if show {\n        title\n        }}\n        `first\n        second`"
    ));
    assert!(formatted.output.contains("\"###, title = self.title"));
    assert!(verify_render_preserving(Path::new("named.rs"), source, &formatted.output).is_empty());
    assert_eq!(
        format_file(Path::new("named.rs"), &formatted.output)
            .unwrap()
            .output,
        formatted.output
    );
}

#[test]
fn md_formatting_preserves_commonmark_containers_with_crlf() {
    let source = r####"fn f() {
    md_sync! { r###"
- Example

    ~~~text
    {{literal}} {not_rust
    ~~~
Before `

{value}

After `
"### };
}"####
        .replace('\n', "\r\n");
    let path = Path::new("containers.rs");
    let formatted = format_file(path, &source).unwrap();
    assert!(
        formatted.diagnostics.is_empty(),
        "{:?}",
        formatted.diagnostics
    );
    assert!(verify_render_preserving(path, &source, &formatted.output).is_empty());
    assert_eq!(
        format_file(path, &formatted.output).unwrap().output,
        formatted.output
    );
}

#[test]
fn md_formatting_preserves_escapes_and_quoted_code() {
    let source = r####"fn f() {
    md_sync! { r###"
{{name}} {{{name}}} \{name} \{{name}} `{{name}}`
{ { name } } {md_sync! { "{{{name}}}" }}
> ~~~text
> {{name}} {not_rust
> ~~~
{name}
> > ```text
> > {{name}} {not_rust
> {name}
"### };
}"####;
    let path = Path::new("escaped.rs");
    let formatted = format_file(path, source).unwrap();
    assert!(
        formatted.diagnostics.is_empty(),
        "{:?}",
        formatted.diagnostics
    );
    assert_ne!(formatted.output, source);
    assert_eq!(md_lowered(source), md_lowered(&formatted.output));
    assert!(verify_render_preserving(path, source, &formatted.output).is_empty());
    assert_eq!(
        format_file(path, &formatted.output).unwrap().output,
        formatted.output
    );
}

#[test]
fn md_invalid_control_syntax_is_not_formatted_or_verified() {
    for template in [
        "{if false {A} elsse {B}}",
        "{for x in xs {X} ignored}",
        "{if true {unclosed}",
    ] {
        let source = format!(r####"fn f() {{ md_sync! {{ r###"{template}"### }}; }}"####);
        let formatted = format_file(Path::new("invalid.rs"), &source).unwrap();
        assert_eq!(formatted.output, source);
        assert!(formatted
            .diagnostics
            .iter()
            .any(|d| d.code == "parse/template"));
        assert!(
            verify_render_preserving(Path::new("invalid.rs"), &source, &source)
                .iter()
                .any(|d| d.code == "format/verify")
        );
    }
}

#[test]
fn md_formats_control_slots_preserving_relative_indentation() {
    let source = r####"impl Product {
    fn markdown(self) {
        md_sync! { r###"
                ## {&self.name}
                {if self.stock > 0 {
                    md_sync! { "Only {self.stock} left\n" }
                } else {
                    md_sync! { "**Sold out**\n" }
                }}
                ### Reviews
                {for review in self.reviews.iter() {
                    md_sync! { "- {review}\n" }
                }}
                "###
        }
    }
}"####;
    let expected = r####"impl Product {
    fn markdown(self) {
        md_sync! { r###"
            ## {&self.name}
            {if self.stock > 0 {
                md_sync! { "Only {self.stock} left\n" }
            } else {
                md_sync! { "**Sold out**\n" }
            }}
            ### Reviews
            {for review in self.reviews.iter() {
                md_sync! { "- {review}\n" }
            }}
            "###
        }
    }
}"####;
    let formatted = format_file(Path::new("product.rs"), source).unwrap().output;
    assert_eq!(formatted, expected);
    assert_eq!(
        format_file(Path::new("product.rs"), &formatted)
            .unwrap()
            .output,
        formatted
    );
    assert!(verify_render_preserving(Path::new("product.rs"), source, &formatted).is_empty());
}

#[test]
fn md_nested_template_literals_keep_markdown_indentation_and_code() {
    let source = r####"fn f() {
    md! { r###"
        {if show {
            md! { r#"
                - outer
                  - {child}

                    code_line();

                ```rust
                for item in items {
                    println!("{item}");
                }
                ```
            "# }
        }}
        "###
    }
}"####;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert_eq!(formatted, source);
    assert!(verify_render_preserving(Path::new("sample.rs"), source, &formatted).is_empty());
    let corrupted = formatted.replace(
        "                  - {child}",
        "                    - {child}",
    );
    assert!(!verify_render_preserving(Path::new("sample.rs"), source, &corrupted).is_empty());
}

#[test]
fn md_multiline_rust_slots_keep_their_layout() {
    let source = r####"fn f() {
    md_sync! { r###"
        {for (index, group) in groups.iter().enumerate() {
            if index > 0 {
                md_sync! { "\n" }
            }
            for item in group {
                md_sync! { "{item}\n" }
            }
        }}
        "###
    }
}"####;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert_eq!(formatted, source);
    assert!(verify_render_preserving(Path::new("sample.rs"), source, &formatted).is_empty());
}

#[test]
fn md_single_line_template_is_left_alone() {
    // Leading whitespace in a single-line template is content.
    let source = r#"fn f() { let s = md_sync!("    indented"); }"#;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert_eq!(formatted, source);
}

#[test]
fn verify_preserves_markdown_argument_order_and_initializers() {
    let source = r#"fn f() { md_sync! { "{b} {a}", a = first(), b = second() }; }"#;
    for changed in [
        source.replace("a = first(), b = second()", "b = second(), a = first()"),
        source.replace("first()", "third()"),
    ] {
        assert!(!verify_render_preserving(Path::new("sample.rs"), source, &changed).is_empty());
    }
}

#[test]
fn md_token_composition_is_reported_and_left_alone() {
    // The compiler rejects token composition; the formatter reports the same
    // message and does not rewrite the body.
    let source = r##"fn f() { let s = md_sync! { "# " {title} "\n" }; }"##;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap();
    assert_eq!(formatted.output, source);
    assert!(formatted.diagnostics.iter().any(|diagnostic| diagnostic
        .message
        .contains("unexpected tokens after the template string")));
}

#[test]
fn md_body_with_a_comment_is_left_alone() {
    // Rebuilding the body from the literal token would drop the comment.
    let source = r#"fn f() {
    let s = md_sync! {
        // the product heading
        "
# Title
"
    };
}"#;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert_eq!(formatted, source);
}

#[test]
fn md_escaped_newlines_are_left_alone() {
    // `\n` escapes decouple source lines from rendered lines, so the
    // layout indentation is not safe to rewrite.
    let source = r#"fn f() {
    let s = md_sync! {"
# Title\n\nBody.
"};
}"#;
    let formatted = format_file(Path::new("sample.rs"), source).unwrap().output;
    assert_eq!(formatted, source);
}

#[test]
fn verify_accepts_md_reindentation() {
    let source = r#"impl A {
    fn f(&self) {
        md_sync! {"
# {self.title}

Body.
"}
        .render_md(cx)
    }
}"#;
    let formatted = format_file(Path::new("sample.rs"), source).expect("format");
    let diags = verify_render_preserving(Path::new("sample.rs"), source, &formatted.output);
    assert!(diags.is_empty(), "verify failed: {diags:?}");
}

#[test]
fn verify_rejects_md_bodies_that_render_differently() {
    let source = r#"fn f() {
    let s = md_sync! {"
# Title

Body.
"};
}"#;
    // Simulate a formatter bug: indent one line of a template whose other
    // lines stay flush left. The common prefix stays empty, so those four
    // spaces survive lowering and turn the paragraph into a code block.
    let corrupted = source.replace("Body.", "    Body.");
    let diags = verify_render_preserving(Path::new("sample.rs"), source, &corrupted);
    assert!(
        diags.iter().any(|d| d.code == "format/verify"),
        "expected a verify failure: {diags:?}"
    );
}

#[test]
fn markdown_named_argument_layout_moves_without_changing_literal_data() {
    let source = r####"fn f() {
    md_sync! { r###"
                {title} {copy}
                "###,
                mark = '"' as u32,
                title = {
                    make_title()
                },
                copy = r#"first
                    literal indentation
                last"#,
    };
}"####;
    let formatted = format_file(Path::new("arguments.rs"), source).unwrap();
    assert!(
        formatted.diagnostics.is_empty(),
        "{:?}",
        formatted.diagnostics
    );
    assert!(
        formatted
            .output
            .contains("\n        title = {\n            make_title()\n        },\n        copy ="),
        "{}",
        formatted.output
    );
    assert!(formatted
        .output
        .contains("first\n                    literal indentation\n                last"));
    assert!(
        verify_render_preserving(Path::new("arguments.rs"), source, &formatted.output).is_empty()
    );
    assert_eq!(
        format_file(Path::new("arguments.rs"), &formatted.output)
            .unwrap()
            .output,
        formatted.output
    );
}

#[test]
fn whitespace_only_markdown_retains_authored_closing_indentation() {
    let source = "fn f() {\n    md_sync! { r\"\n    \" };\n}";
    let formatted = format_file(Path::new("empty.rs"), source).unwrap();
    assert!(formatted.output.contains("r\"\n    \""));
    assert!(verify_render_preserving(Path::new("empty.rs"), source, &formatted.output).is_empty());
    assert_eq!(
        format_file(Path::new("empty.rs"), &formatted.output)
            .unwrap()
            .output,
        formatted.output
    );
}