1use std::fmt::Write;
5use std::ops::RangeInclusive;
6use std::path::{Path, PathBuf};
7
8use anyhow::{Context, Result};
9use proa_dsl::parse::{Attribute, Element, HtmlRoot, Node};
10use quote::ToTokens;
11use syn::spanned::Spanned;
12use syn::{Attribute as SynAttribute, Item, Path as SynPath};
13
14use crate::diagnostic::{Diagnostic, Severity};
15use crate::lint::parse_invocation;
16use crate::source::{
17 display_path, find_macros, find_rust_files, MacroDialect, MacroInvocation, SourceMap,
18};
19
20const INDENT_WIDTH: usize = 4;
21const INLINE_WIDTH: usize = 100;
22
23#[derive(Debug, Default)]
24pub struct FormatSummary {
25 pub changed: Vec<PathBuf>,
26 pub diagnostics: Vec<Diagnostic>,
27 pub diffs: Vec<(PathBuf, String)>,
29}
30
31pub fn format_paths_with_options(
32 paths: &[PathBuf],
33 check: bool,
34 verify: bool,
35) -> Result<FormatSummary> {
36 let mut summary = FormatSummary::default();
37 let mut pending_writes = Vec::new();
38 for path in find_rust_files(paths)? {
39 let source = std::fs::read_to_string(&path)
40 .with_context(|| format!("failed to read {}", path.display()))?;
41 let mut formatted = format_file(&path, &source)?;
42 if verify {
43 formatted.diagnostics.extend(verify_render_preserving(
44 &path,
45 &source,
46 &formatted.output,
47 ));
48 }
49 let has_errors = formatted
50 .diagnostics
51 .iter()
52 .any(|diag| diag.severity == Severity::Error);
53
54 if formatted.output != source && !has_errors {
55 summary.changed.push(display_path(&path));
56 if check {
57 summary.diagnostics.push(
58 Diagnostic::new(
59 display_path(&path),
60 1,
61 1,
62 Severity::Warning,
63 "format",
64 "Proa macro formatting differs",
65 )
66 .with_help("run `cargo proa fmt` to rewrite Proa macro bodies"),
67 );
68 summary.diffs.push((
69 display_path(&path),
70 unified_diff(&source, &formatted.output),
71 ));
72 } else {
73 pending_writes.push((path, formatted.output));
74 }
75 }
76
77 summary.diagnostics.extend(formatted.diagnostics);
78 }
79
80 let has_errors = summary
81 .diagnostics
82 .iter()
83 .any(|diagnostic| diagnostic.severity == Severity::Error);
84 if !check && !has_errors {
85 for (path, output) in pending_writes {
86 std::fs::write(&path, output)
87 .with_context(|| format!("failed to write {}", path.display()))?;
88 }
89 }
90
91 Ok(summary)
92}
93
94fn unified_diff(original: &str, formatted: &str) -> String {
95 similar::TextDiff::from_lines(original, formatted)
96 .unified_diff()
97 .context_radius(2)
98 .to_string()
99}
100
101pub fn format_file(path: &Path, source: &str) -> Result<FormattedFile> {
102 let display = display_path(path);
103 let invocations = find_macros(source);
104 let mut output = source.to_owned();
105 let mut diagnostics = Vec::new();
106 let rsjs_ranges = rsjs_line_ranges(source);
107
108 for inv in invocations.iter().rev() {
109 if inv.dialect == MacroDialect::Md {
110 let body = inv.body(source);
111 let formatted = format_md_body(inv, body);
112 output.replace_range(inv.body_start..inv.body_end, &formatted);
113 continue;
114 }
115 match parse_invocation(source, inv) {
116 Ok(root) => {
117 let body = inv.body(source);
118 let preserve_legacy_names = line_in_ranges(inv.name_line, &rsjs_ranges);
119 let formatted = format_macro_body(inv, body, &root, preserve_legacy_names);
120 output.replace_range(inv.body_start..inv.body_end, &formatted);
121 }
122 Err(err) => diagnostics.push(Diagnostic::new(
123 &display,
124 inv.name_line,
125 inv.name_column + 1,
126 Severity::Error,
127 "parse",
128 format!("failed to parse {}! macro body: {err}", inv.name),
129 )),
130 }
131 }
132
133 Ok(FormattedFile {
134 output,
135 diagnostics,
136 })
137}
138
139pub(crate) fn verify_render_preserving(
144 path: &Path,
145 original: &str,
146 formatted: &str,
147) -> Vec<Diagnostic> {
148 let display = display_path(path);
149 let mut diagnostics = Vec::new();
150 let before = find_macros(original);
151 let after = find_macros(formatted);
152 let before_rsjs_ranges = rsjs_line_ranges(original);
153 let after_rsjs_ranges = rsjs_line_ranges(formatted);
154 if before.len() != after.len() {
155 diagnostics.push(Diagnostic::new(
156 &display,
157 1,
158 1,
159 Severity::Error,
160 "format/verify",
161 format!(
162 "formatting changed the number of Proa macros ({} -> {})",
163 before.len(),
164 after.len()
165 ),
166 ));
167 return diagnostics;
168 }
169 for (inv_before, inv_after) in before.iter().zip(after.iter()) {
170 if inv_before.dialect == MacroDialect::Md || inv_after.dialect == MacroDialect::Md {
171 let text_before = md_render_text(original, inv_before);
174 let text_after = md_render_text(formatted, inv_after);
175 if text_before != text_after {
176 diagnostics.push(
177 Diagnostic::new(
178 &display,
179 inv_before.name_line,
180 inv_before.name_column + 1,
181 Severity::Error,
182 "format/verify",
183 "formatting would change rendered Markdown".to_owned(),
184 )
185 .with_help("this is a formatter bug; the file was not rewritten"),
186 );
187 }
188 continue;
189 }
190 let Ok(root_before) = parse_invocation(original, inv_before) else {
191 continue;
193 };
194 let root_after = match parse_invocation(formatted, inv_after) {
195 Ok(root) => root,
196 Err(err) => {
197 diagnostics.push(
201 Diagnostic::new(
202 &display,
203 inv_before.name_line,
204 inv_before.name_column + 1,
205 Severity::Error,
206 "format/verify",
207 format!("formatted output no longer parses: {err}"),
208 )
209 .with_help("this is a formatter bug; the file was not rewritten"),
210 );
211 continue;
212 }
213 };
214 let allow_legacy_names = line_in_ranges(inv_before.name_line, &before_rsjs_ranges)
215 || line_in_ranges(inv_after.name_line, &after_rsjs_ranges);
216 if let Err(why) = nodes_equal(&root_before.nodes, &root_after.nodes, allow_legacy_names) {
217 diagnostics.push(
218 Diagnostic::new(
219 &display,
220 inv_before.name_line,
221 inv_before.name_column + 1,
222 Severity::Error,
223 "format/verify",
224 format!("formatting would change rendered output: {why}"),
225 )
226 .with_help("this is a formatter bug; the file was not rewritten"),
227 );
228 }
229 }
230 diagnostics
231}
232
233pub(crate) fn rsjs_line_ranges(source: &str) -> Vec<RangeInclusive<usize>> {
234 let Ok(file) = syn::parse_file(source) else {
235 return Vec::new();
236 };
237
238 let mut ranges = Vec::new();
239 collect_rsjs_line_ranges(&file.items, false, &mut ranges);
240 ranges.sort_by_key(|range| *range.start());
241 ranges
242}
243
244fn collect_rsjs_line_ranges(
245 items: &[Item],
246 in_client_module: bool,
247 ranges: &mut Vec<RangeInclusive<usize>>,
248) {
249 for item in items {
250 match item {
251 Item::Impl(item_impl)
252 if in_client_module || attrs_have_any_last_ident(&item_impl.attrs, &["rsjs"]) =>
253 {
254 push_span_line_range(item_impl.span(), ranges);
255 }
256 Item::Fn(item_fn)
257 if in_client_module
258 || attrs_have_any_last_ident(&item_fn.attrs, &["rsjs", "client"]) =>
259 {
260 push_span_line_range(item_fn.span(), ranges);
261 }
262 Item::Mod(item_mod) => {
263 let is_client_module = in_client_module
264 || attrs_have_any_last_ident(
265 &item_mod.attrs,
266 &["rsjs", "client", "client_module"],
267 )
268 || attrs_have_path_suffix(&item_mod.attrs, &["rsjs", "client_module"]);
269 if is_client_module {
270 push_span_line_range(item_mod.span(), ranges);
271 }
272 if let Some((_, items)) = &item_mod.content {
273 collect_rsjs_line_ranges(items, is_client_module, ranges);
274 }
275 }
276 _ => {}
277 }
278 }
279}
280
281fn push_span_line_range(span: proc_macro2::Span, ranges: &mut Vec<RangeInclusive<usize>>) {
282 let start = span.start().line;
283 let end = span.end().line;
284 if start != 0 && end >= start {
285 ranges.push(start..=end);
286 }
287}
288
289fn attrs_have_any_last_ident(attrs: &[SynAttribute], names: &[&str]) -> bool {
290 attrs.iter().any(|attr| {
291 attr.path()
292 .segments
293 .last()
294 .is_some_and(|segment| names.iter().any(|name| segment.ident == *name))
295 })
296}
297
298fn attrs_have_path_suffix(attrs: &[SynAttribute], suffix: &[&str]) -> bool {
299 attrs.iter().any(|attr| path_ends(attr.path(), suffix))
300}
301
302fn path_ends(path: &SynPath, suffix: &[&str]) -> bool {
303 path.segments.len() >= suffix.len()
304 && path
305 .segments
306 .iter()
307 .skip(path.segments.len() - suffix.len())
308 .zip(suffix)
309 .all(|(seg, expected)| seg.ident == *expected)
310}
311
312fn line_in_ranges(line: usize, ranges: &[RangeInclusive<usize>]) -> bool {
313 ranges.iter().any(|range| range.contains(&line))
314}
315
316pub(crate) fn html_void_element(tag: &str) -> bool {
317 matches!(
318 tag,
319 "area"
320 | "base"
321 | "br"
322 | "col"
323 | "embed"
324 | "hr"
325 | "img"
326 | "input"
327 | "link"
328 | "meta"
329 | "source"
330 | "track"
331 | "wbr"
332 | "path"
333 | "circle"
334 | "ellipse"
335 | "line"
336 | "polygon"
337 | "polyline"
338 | "rect"
339 | "stop"
340 | "use"
341 | "image"
342 | "animate"
343 | "animateMotion"
344 | "animateTransform"
345 | "set"
346 )
347}
348
349fn nodes_equal(
350 a: &[Node],
351 b: &[Node],
352 allow_legacy_names: bool,
353) -> std::result::Result<(), String> {
354 if a.len() != b.len() {
355 return Err(format!("child count changed ({} -> {})", a.len(), b.len()));
356 }
357 for (left, right) in a.iter().zip(b.iter()) {
358 node_equal(left, right, allow_legacy_names)?;
359 }
360 Ok(())
361}
362
363fn node_equal(a: &Node, b: &Node, allow_legacy_names: bool) -> std::result::Result<(), String> {
364 match (a, b) {
365 (Node::Element(ea), Node::Element(eb)) => element_equal(ea, eb, allow_legacy_names),
366 (Node::Fragment(ca), Node::Fragment(cb)) => nodes_equal(ca, cb, allow_legacy_names),
367 (Node::Text(ta), Node::Text(tb)) => {
368 if ta.value() == tb.value() {
369 Ok(())
370 } else {
371 Err(format!(
372 "text changed ({:?} -> {:?})",
373 ta.value(),
374 tb.value()
375 ))
376 }
377 }
378 (Node::Block(xa), Node::Block(xb)) => {
379 let sa = normalize_expr_for_compare(&xa.to_token_stream().to_string());
380 let sb = normalize_expr_for_compare(&xb.to_token_stream().to_string());
381 if sa == sb {
382 Ok(())
383 } else {
384 Err(format!("expression changed ({sa} -> {sb})"))
385 }
386 }
387 (Node::Doctype(da), Node::Doctype(db)) => {
388 if da == db {
389 Ok(())
390 } else {
391 Err("doctype changed".to_string())
392 }
393 }
394 _ => Err("node kind changed".to_string()),
395 }
396}
397
398fn normalize_expr_for_compare(expr: &str) -> String {
399 let normalized = format_embedded_macro_bodies(expr, false);
400 let tokens = syn::parse_str::<syn::Expr>(&normalized)
401 .map(|expr| expr.to_token_stream().to_string())
402 .unwrap_or(normalized);
403 strip_trailing_separators(&tokens)
404}
405
406fn strip_trailing_separators(tokens: &str) -> String {
414 let mut out = String::with_capacity(tokens.len());
415 let mut pending_separator = false;
416
417 for token in tokens.split_inclusive(' ') {
418 let trimmed = token.trim_end();
419 if trimmed == "," {
420 pending_separator = true;
422 continue;
423 }
424 if pending_separator {
425 pending_separator = false;
426 if !trimmed.starts_with(['}', ')', ']']) {
427 out.push_str(", ");
428 }
429 }
430 out.push_str(token);
431 }
432 if pending_separator {
433 out.push_str(", ");
434 }
435 out
436}
437
438fn element_equal(
439 a: &Element,
440 b: &Element,
441 allow_legacy_names: bool,
442) -> std::result::Result<(), String> {
443 let tag_a = a.tag_str();
444 if !markup_names_equal(&a.name, &b.name, allow_legacy_names) {
445 return Err(format!("tag changed ({} -> {})", tag_a, b.tag_str()));
446 }
447 if !html_void_element(&tag_a)
450 && (a.self_closing != b.self_closing)
451 && (a.children.is_empty() || b.children.is_empty())
452 {
453 return Err(format!(
454 "<{tag_a}> self-closing form changed on a non-void element"
455 ));
456 }
457 if a.attrs.len() != b.attrs.len() {
458 return Err(format!(
459 "<{tag_a}> attribute count changed ({} -> {})",
460 a.attrs.len(),
461 b.attrs.len()
462 ));
463 }
464 for (attr_a, attr_b) in a.attrs.iter().zip(b.attrs.iter()) {
465 attr_equal(&tag_a, attr_a, attr_b, allow_legacy_names)?;
466 }
467 nodes_equal(&a.children, &b.children, allow_legacy_names)
468}
469
470fn attr_equal(
471 tag: &str,
472 a: &Attribute,
473 b: &Attribute,
474 allow_legacy_names: bool,
475) -> std::result::Result<(), String> {
476 match (a, b) {
477 (
478 Attribute::Static {
479 name: na,
480 value: va,
481 },
482 Attribute::Static {
483 name: nb,
484 value: vb,
485 },
486 ) => {
487 if !markup_names_equal(na, nb, allow_legacy_names) {
488 return Err(format!("<{tag}> attribute name changed"));
489 }
490 if va.value() != vb.value() {
491 return Err(format!(
492 "<{tag} {}> attribute value changed",
493 na.as_markup_str()
494 ));
495 }
496 Ok(())
497 }
498 (
499 Attribute::Dynamic {
500 name: na,
501 value: va,
502 },
503 Attribute::Dynamic {
504 name: nb,
505 value: vb,
506 },
507 ) => {
508 if !markup_names_equal(na, nb, allow_legacy_names) {
509 return Err(format!("<{tag}> dynamic attribute name changed"));
510 }
511 let sa = va.to_token_stream().to_string();
512 let sb = vb.to_token_stream().to_string();
513 if sa != sb {
514 return Err(format!(
515 "<{tag} {}> dynamic attribute expression changed",
516 na.as_markup_str()
517 ));
518 }
519 Ok(())
520 }
521 (Attribute::Bool { name: na }, Attribute::Bool { name: nb }) => {
522 if markup_names_equal(na, nb, allow_legacy_names) {
523 Ok(())
524 } else {
525 Err(format!("<{tag}> boolean attribute changed"))
526 }
527 }
528 _ => Err(format!("<{tag}> attribute kind changed")),
529 }
530}
531
532fn markup_names_equal(
533 a: &proa_dsl::parse::MarkupName,
534 b: &proa_dsl::parse::MarkupName,
535 allow_legacy_names: bool,
536) -> bool {
537 a.as_markup_str() == b.as_markup_str()
538 || ((allow_legacy_names
539 || a.as_markup_str().starts_with('-')
540 || b.as_markup_str().starts_with('-'))
541 && a.legacy_ident() == b.legacy_ident())
542}
543
544#[derive(Debug)]
545pub struct FormattedFile {
546 pub output: String,
547 pub diagnostics: Vec<Diagnostic>,
548}
549
550struct MdTemplate {
555 open: String,
557 inner: String,
559 close: String,
561}
562
563fn md_template(body: &str) -> Option<MdTemplate> {
571 use std::str::FromStr;
572
573 if contains_source_comment(body) {
576 return None;
577 }
578
579 let lit: syn::LitStr = syn::parse2(proc_macro2::TokenStream::from_str(body).ok()?).ok()?;
580 let value = lit.value();
581 if !proa_dsl::md_layout::is_multiline_template(&value) {
582 return None;
583 }
584
585 let text = lit.token().to_string();
586 let (open, close) = match text.strip_prefix('r') {
587 Some(rest) => {
588 let hashes = "#".repeat(rest.len() - rest.trim_start_matches('#').len());
589 (format!("r{hashes}\""), format!("\"{hashes}"))
590 }
591 None => ("\"".to_owned(), "\"".to_owned()),
592 };
593 let inner = text.strip_prefix(&open)?.strip_suffix(&close)?.to_owned();
594
595 if inner.split('\n').count() != value.split('\n').count() {
599 return None;
600 }
601
602 Some(MdTemplate { open, inner, close })
603}
604
605pub(crate) fn format_md_body(inv: &MacroInvocation, body: &str) -> String {
614 let Some(tpl) = md_template(body) else {
615 return body.to_owned();
616 };
617
618 let Some(template) = tpl.inner.strip_prefix('\n') else {
620 return body.to_owned();
621 };
622 let common = proa_dsl::md_layout::layout_indent(template);
623 let close_indent = inv.indentation_column;
624 let content_indent = close_indent + INDENT_WIDTH;
625
626 let mut out = String::with_capacity(body.len());
627 out.push(' ');
628 out.push_str(&tpl.open);
629
630 let lines: Vec<&str> = template.split('\n').collect();
631 let last = lines.len().saturating_sub(1);
632 for (idx, line) in lines.iter().enumerate() {
633 out.push('\n');
634 let content = &line[common_prefix_len(common, line)..];
635 if idx == last && content.trim().is_empty() {
636 push_spaces(&mut out, content_indent);
638 continue;
639 }
640 if content.is_empty() {
641 continue;
642 }
643 push_spaces(&mut out, content_indent);
644 out.push_str(content);
645 }
646
647 out.push_str(&tpl.close);
648 out.push('\n');
649 push_spaces(&mut out, close_indent);
650 out
651}
652
653fn common_prefix_len(common: &str, line: &str) -> usize {
655 common
656 .char_indices()
657 .zip(line.chars())
658 .take_while(|((_, a), b)| a == b)
659 .map(|((idx, a), _)| idx + a.len_utf8())
660 .last()
661 .unwrap_or(0)
662}
663
664fn md_render_text(source: &str, inv: &MacroInvocation) -> Option<String> {
666 use std::str::FromStr;
667
668 let body = inv.body(source);
669 let lit: syn::LitStr = syn::parse2(proc_macro2::TokenStream::from_str(body).ok()?).ok()?;
670 Some(proa_dsl::md_layout::dedent_template(&lit.value()))
671}
672
673pub(crate) fn format_macro_body(
674 inv: &MacroInvocation,
675 body: &str,
676 root: &HtmlRoot,
677 preserve_legacy_names: bool,
678) -> String {
679 if contains_source_comment(body) {
684 return body.to_owned();
685 }
686 if root.nodes.is_empty() {
687 return String::new();
688 }
689
690 let source = SourceMap::new(body);
691 if root_requires_source_fallback(&source, root) {
692 return body.to_owned();
693 }
694 let close_indent = inv.indentation_column;
695 let child_indent = close_indent + INDENT_WIDTH;
696 let mut out = String::new();
697 out.push('\n');
698
699 for (idx, node) in root.nodes.iter().enumerate() {
700 if idx > 0 {
701 out.push('\n');
702 }
703 format_node(&mut out, &source, node, child_indent, preserve_legacy_names);
704 }
705
706 out.push('\n');
707 push_spaces(&mut out, close_indent);
708 out
709}
710
711pub(crate) fn macro_body_has_noncanonical_expression_layout(
718 inv: &MacroInvocation,
719 body: &str,
720 root: &HtmlRoot,
721 preserve_legacy_names: bool,
722) -> bool {
723 if contains_source_comment(body) {
724 return false;
725 }
726
727 let source = SourceMap::new(body);
728 if root_requires_source_fallback(&source, root) {
729 return false;
730 }
731
732 let child_indent = inv.indentation_column + INDENT_WIDTH;
733 root.nodes.iter().any(|node| {
734 node_has_noncanonical_expression_layout(&source, node, child_indent, preserve_legacy_names)
735 })
736}
737
738fn node_has_noncanonical_expression_layout(
739 source: &SourceMap<'_>,
740 node: &Node,
741 indent: usize,
742 preserve_legacy_names: bool,
743) -> bool {
744 match node {
745 Node::Element(element) => element.children.iter().any(|child| {
746 node_has_noncanonical_expression_layout(
747 source,
748 child,
749 indent + INDENT_WIDTH,
750 preserve_legacy_names,
751 )
752 }),
753 Node::Fragment(children) => children.iter().any(|child| {
754 node_has_noncanonical_expression_layout(
755 source,
756 child,
757 indent + INDENT_WIDTH,
758 preserve_legacy_names,
759 )
760 }),
761 Node::Block(expr) => {
762 let Some(authored) = source.span_snippet(expr.span()).map(str::trim) else {
763 return false;
764 };
765 if !matches!(expr, syn::Expr::Struct(_)) && !authored.contains('\n') {
766 return false;
767 }
768
769 let mut canonical = String::new();
770 format_block_expr(&mut canonical, source, expr, indent, preserve_legacy_names);
771 canonical != authored
772 }
773 Node::Text(_) | Node::Doctype(_) => false,
774 }
775}
776
777fn format_node(
778 out: &mut String,
779 source: &SourceMap<'_>,
780 node: &Node,
781 indent: usize,
782 preserve_legacy_names: bool,
783) {
784 match node {
785 Node::Element(el) => format_element(out, source, el, indent, preserve_legacy_names),
786 Node::Fragment(children) => {
787 format_fragment(out, source, children, indent, preserve_legacy_names)
788 }
789 Node::Text(lit) => {
790 push_spaces(out, indent);
791 out.push_str(&text_literal_source(source, lit));
792 }
793 Node::Block(expr) => {
794 push_spaces(out, indent);
795 out.push('{');
796 format_block_expr(out, source, expr, indent, preserve_legacy_names);
797 out.push('}');
798 }
799 Node::Doctype(content) => {
800 push_spaces(out, indent);
801 if content.is_empty() {
802 out.push_str("<!DOCTYPE html>");
803 } else {
804 out.push_str(content);
805 }
806 }
807 }
808}
809
810fn format_fragment(
811 out: &mut String,
812 source: &SourceMap<'_>,
813 children: &[Node],
814 indent: usize,
815 preserve_legacy_names: bool,
816) {
817 if let Some(inline) = inline_children(source, children, preserve_legacy_names) {
818 push_spaces(out, indent);
819 let _ = write!(out, "<>{inline}</>");
820 return;
821 }
822
823 push_spaces(out, indent);
824 out.push_str("<>");
825 for child in children {
826 out.push('\n');
827 format_node(
828 out,
829 source,
830 child,
831 indent + INDENT_WIDTH,
832 preserve_legacy_names,
833 );
834 }
835 out.push('\n');
836 push_spaces(out, indent);
837 out.push_str("</>");
838}
839
840fn format_element(
841 out: &mut String,
842 source: &SourceMap<'_>,
843 el: &Element,
844 indent: usize,
845 preserve_legacy_names: bool,
846) {
847 let attrs = format_attrs(source, &el.attrs, preserve_legacy_names);
848 let tag_name = format_markup_name_source(source, &el.name, preserve_legacy_names);
849 let multiline_attrs = el.attrs.len() > 1
850 && (el.name.start_line_column().line < el.opening_end_line_column().line
851 || indent + tag_name.len() + attrs.len() + 2 > INLINE_WIDTH);
852
853 if multiline_attrs {
854 format_element_with_multiline_attrs(
855 out,
856 source,
857 el,
858 indent,
859 tag_name.as_ref(),
860 preserve_legacy_names,
861 );
862 return;
863 }
864
865 let open = format!("<{}{}>", tag_name, attrs);
866
867 if el.self_closing {
868 push_spaces(out, indent);
869 out.push('<');
870 let _ = write!(out, "{tag_name}{attrs} />");
871 return;
872 }
873
874 if el.children.is_empty() {
875 push_spaces(out, indent);
876 let _ = write!(out, "{open}</{tag_name}");
877 out.push('>');
878 return;
879 }
880
881 if let Some(inline) = inline_children(source, &el.children, preserve_legacy_names) {
882 let line_len = indent + open.len() + inline.len() + tag_name.len() + 3;
883 if line_len <= INLINE_WIDTH {
884 push_spaces(out, indent);
885 let _ = write!(out, "{open}{inline}</{tag_name}");
886 out.push('>');
887 return;
888 }
889 }
890
891 push_spaces(out, indent);
892 out.push_str(&open);
893 for child in &el.children {
894 out.push('\n');
895 format_node(
896 out,
897 source,
898 child,
899 indent + INDENT_WIDTH,
900 preserve_legacy_names,
901 );
902 }
903 out.push('\n');
904 push_spaces(out, indent);
905 let _ = write!(out, "</{tag_name}");
906 out.push('>');
907}
908
909fn format_element_with_multiline_attrs(
910 out: &mut String,
911 source: &SourceMap<'_>,
912 el: &Element,
913 indent: usize,
914 tag_name: &str,
915 preserve_legacy_names: bool,
916) {
917 push_spaces(out, indent);
918 out.push('<');
919 out.push_str(tag_name);
920 for attr in &el.attrs {
921 out.push('\n');
922 push_spaces(out, indent + INDENT_WIDTH);
923 out.push_str(&format_attr(source, attr, preserve_legacy_names));
924 }
925 out.push('\n');
926 push_spaces(out, indent);
927
928 if el.self_closing {
929 out.push_str("/>");
930 return;
931 }
932
933 out.push('>');
934 if el.children.is_empty() {
935 let _ = write!(out, "</{tag_name}");
936 out.push('>');
937 return;
938 }
939
940 for child in &el.children {
941 out.push('\n');
942 format_node(
943 out,
944 source,
945 child,
946 indent + INDENT_WIDTH,
947 preserve_legacy_names,
948 );
949 }
950 out.push('\n');
951 push_spaces(out, indent);
952 let _ = write!(out, "</{tag_name}");
953 out.push('>');
954}
955
956fn inline_children(
957 source: &SourceMap<'_>,
958 children: &[Node],
959 preserve_legacy_names: bool,
960) -> Option<String> {
961 let mut out = String::new();
962 for child in children {
963 match child {
964 Node::Text(lit) => out.push_str(&text_literal_source(source, lit)),
965 Node::Block(expr) => {
966 let expr = expr_source(source, expr, preserve_legacy_names);
967 if expr.contains('\n') {
968 return None;
969 }
970 out.push('{');
971 out.push_str(expr.trim());
972 out.push('}');
973 }
974 Node::Element(_) | Node::Fragment(_) | Node::Doctype(_) => return None,
975 }
976 }
977 Some(out)
978}
979
980fn format_attrs(
981 source: &SourceMap<'_>,
982 attrs: &[Attribute],
983 preserve_legacy_names: bool,
984) -> String {
985 let mut out = String::new();
986 for attr in attrs {
987 out.push(' ');
988 out.push_str(&format_attr(source, attr, preserve_legacy_names));
989 }
990 out
991}
992
993fn format_attr(source: &SourceMap<'_>, attr: &Attribute, preserve_legacy_names: bool) -> String {
994 let mut out = String::new();
995 match attr {
996 Attribute::Static { name, value } => {
997 out.push_str(format_markup_name_source(source, name, preserve_legacy_names).as_ref());
998 out.push('=');
999 out.push_str(&text_literal_source(source, value));
1000 }
1001 Attribute::Dynamic { name, value } => {
1002 let _ = write!(
1003 out,
1004 "{name}={{{value}",
1005 name = format_markup_name_source(source, name, preserve_legacy_names),
1006 value = expr_source(source, value, preserve_legacy_names).trim()
1007 );
1008 out.push('}');
1009 }
1010 Attribute::Bool { name } => {
1011 out.push_str(format_markup_name_source(source, name, preserve_legacy_names).as_ref());
1012 }
1013 }
1014 out
1015}
1016
1017fn format_markup_name_source<'a>(
1018 source: &'a SourceMap<'_>,
1019 name: &proa_dsl::parse::MarkupName,
1020 preserve_legacy_names: bool,
1021) -> std::borrow::Cow<'a, str> {
1022 if let Some(candidate) = source_markup_name(source, name) {
1023 return std::borrow::Cow::Borrowed(candidate);
1024 }
1025
1026 let raw = name.as_markup_str();
1027 if preserve_legacy_names || raw.starts_with('-') {
1028 std::borrow::Cow::Owned(name.legacy_ident().to_string())
1029 } else {
1030 std::borrow::Cow::Owned(raw.to_owned())
1031 }
1032}
1033
1034fn source_markup_name<'a>(
1035 source: &'a SourceMap<'_>,
1036 name: &proa_dsl::parse::MarkupName,
1037) -> Option<&'a str> {
1038 let tail = source.source_from_span_start(name.span())?;
1039 let end = tail
1040 .char_indices()
1041 .find_map(|(idx, ch)| (!markup_name_source_char(ch)).then_some(idx))
1042 .unwrap_or(tail.len());
1043 let candidate = tail.get(..end)?;
1044 let legacy = name.legacy_ident().to_string();
1045 (candidate == name.as_markup_str() || candidate == legacy).then_some(candidate)
1046}
1047
1048fn markup_name_source_char(ch: char) -> bool {
1049 ch == '_' || ch == '-' || ch == ':' || ch == '#' || ch.is_alphanumeric()
1050}
1051
1052fn text_literal_source(source: &SourceMap<'_>, lit: &syn::LitStr) -> String {
1053 source
1054 .span_snippet(lit.span())
1055 .map(str::trim)
1056 .map(str::to_owned)
1057 .unwrap_or_else(|| lit.to_token_stream().to_string())
1058}
1059
1060fn expr_source(source: &SourceMap<'_>, expr: &syn::Expr, preserve_legacy_names: bool) -> String {
1061 let Some(snippet) = source.span_snippet(expr.span()).map(str::to_owned) else {
1062 return format_embedded_macro_bodies(&compact_expr_source(expr), preserve_legacy_names);
1063 };
1064 if snippet.contains('\n') && contains_layout_sensitive_expr(expr) {
1065 return snippet;
1071 }
1072 let source = if snippet.contains('\n') && should_compact_multiline_expr(expr) {
1073 compact_expr_source(expr)
1074 } else {
1075 snippet
1076 };
1077 format_embedded_macro_bodies(&source, preserve_legacy_names)
1078}
1079
1080fn format_embedded_macro_bodies(source: &str, preserve_legacy_names: bool) -> String {
1081 let invocations = find_macros(source);
1082 if invocations.is_empty() {
1083 return source.to_owned();
1084 }
1085
1086 let mut output = source.to_owned();
1087 for inv in invocations.iter().rev() {
1088 let body = inv.body(source);
1089 let formatted = if inv.dialect == MacroDialect::Md {
1090 format_md_body(inv, body)
1091 } else {
1092 let Ok(root) = parse_invocation(source, inv) else {
1093 continue;
1094 };
1095 format_macro_body(inv, body, &root, preserve_legacy_names)
1096 };
1097 output.replace_range(inv.body_start..inv.body_end, &formatted);
1098 let name_end = inv.name_start + inv.name.len();
1104 output.replace_range(name_end..inv.body_start, "! {");
1105 }
1106 output
1107}
1108
1109fn format_embedded_macro_bodies_at_indent(
1119 source: &str,
1120 indent: usize,
1121 preserve_legacy_names: bool,
1122) -> String {
1123 if find_macros(source).is_empty() {
1124 return source.to_owned();
1125 }
1126
1127 let prefix = " ".repeat(indent);
1128 let mut anchored = String::with_capacity(prefix.len() + source.len());
1129 let _ = write!(anchored, "{prefix}{source}");
1130 let formatted = format_embedded_macro_bodies(&anchored, preserve_legacy_names);
1131 formatted
1132 .strip_prefix(&prefix)
1133 .unwrap_or(&formatted)
1134 .to_owned()
1135}
1136
1137fn compact_expr_source(expr: &syn::Expr) -> String {
1138 compact_token_spacing(&expr.to_token_stream().to_string())
1139}
1140
1141fn should_compact_multiline_expr(expr: &syn::Expr) -> bool {
1142 let simple_shape = matches!(
1143 expr,
1144 syn::Expr::Array(_)
1145 | syn::Expr::Await(_)
1146 | syn::Expr::Cast(_)
1147 | syn::Expr::Field(_)
1148 | syn::Expr::Index(_)
1149 | syn::Expr::Lit(_)
1150 | syn::Expr::MethodCall(_)
1151 | syn::Expr::Paren(_)
1152 | syn::Expr::Path(_)
1153 | syn::Expr::Reference(_)
1154 | syn::Expr::Try(_)
1155 | syn::Expr::Tuple(_)
1156 | syn::Expr::Unary(_)
1157 );
1158 simple_shape
1159 && !contains_layout_sensitive_expr(expr)
1160 && compact_expr_source(expr).len() <= INLINE_WIDTH
1161}
1162
1163fn contains_layout_sensitive_expr(expr: &syn::Expr) -> bool {
1164 use syn::visit::Visit;
1165
1166 #[derive(Default)]
1167 struct Detector {
1168 found: bool,
1169 }
1170
1171 impl<'ast> Visit<'ast> for Detector {
1172 fn visit_expr_closure(&mut self, _node: &'ast syn::ExprClosure) {
1173 self.found = true;
1174 }
1175
1176 fn visit_expr_for_loop(&mut self, _node: &'ast syn::ExprForLoop) {
1177 self.found = true;
1178 }
1179
1180 fn visit_expr_if(&mut self, _node: &'ast syn::ExprIf) {
1181 self.found = true;
1182 }
1183
1184 fn visit_expr_macro(&mut self, _node: &'ast syn::ExprMacro) {
1185 self.found = true;
1186 }
1187
1188 fn visit_expr_match(&mut self, _node: &'ast syn::ExprMatch) {
1189 self.found = true;
1190 }
1191
1192 fn visit_expr_struct(&mut self, _node: &'ast syn::ExprStruct) {
1193 self.found = true;
1194 }
1195
1196 fn visit_expr_while(&mut self, _node: &'ast syn::ExprWhile) {
1197 self.found = true;
1198 }
1199 }
1200
1201 let mut detector = Detector::default();
1202 detector.visit_expr(expr);
1203 detector.found
1204}
1205
1206fn root_requires_source_fallback(source: &SourceMap<'_>, root: &HtmlRoot) -> bool {
1207 root.nodes
1208 .iter()
1209 .any(|node| node_requires_source_fallback(source, node))
1210}
1211
1212fn node_requires_source_fallback(source: &SourceMap<'_>, node: &Node) -> bool {
1213 match node {
1214 Node::Element(element) => {
1215 element.attrs.iter().any(|attr| {
1216 matches!(
1217 attr,
1218 Attribute::Dynamic { value, .. }
1219 if expr_requires_source_fallback(source, value)
1220 )
1221 }) || element
1222 .children
1223 .iter()
1224 .any(|child| node_requires_source_fallback(source, child))
1225 }
1226 Node::Fragment(children) => children
1227 .iter()
1228 .any(|child| node_requires_source_fallback(source, child)),
1229 Node::Block(expr) => expr_requires_source_fallback(source, expr),
1230 Node::Text(_) | Node::Doctype(_) => false,
1231 }
1232}
1233
1234fn expr_requires_source_fallback(source: &SourceMap<'_>, expr: &syn::Expr) -> bool {
1248 source.span_snippet(expr.span()).is_some_and(|snippet| {
1249 snippet.contains('\n')
1250 && contains_layout_sensitive_expr(expr)
1251 && contains_multiline_string_literal(snippet)
1252 })
1253}
1254
1255fn contains_multiline_string_literal(snippet: &str) -> bool {
1257 let mut idx = 0;
1258 while idx < snippet.len() {
1259 if let Some(end) = rust_string_literal_end(snippet, idx) {
1260 if snippet[idx..end].contains('\n') {
1261 return true;
1262 }
1263 idx = end;
1264 continue;
1265 }
1266 idx += snippet[idx..]
1267 .chars()
1268 .next()
1269 .map(char::len_utf8)
1270 .unwrap_or(1);
1271 }
1272 false
1273}
1274
1275fn contains_source_comment(source: &str) -> bool {
1276 let bytes = source.as_bytes();
1277 let mut idx = 0;
1278 while idx < bytes.len() {
1279 if let Some(end) = rust_string_literal_end(source, idx) {
1280 idx = end;
1281 continue;
1282 }
1283 if bytes.get(idx) == Some(&b'/') && matches!(bytes.get(idx + 1), Some(b'/' | b'*')) {
1284 return true;
1285 }
1286 idx += source[idx..]
1287 .chars()
1288 .next()
1289 .map(char::len_utf8)
1290 .unwrap_or(1);
1291 }
1292 false
1293}
1294
1295fn compact_token_spacing(tokens: &str) -> String {
1296 let mut out = String::with_capacity(tokens.len());
1297 let mut segment_start = 0;
1298 let mut idx = 0;
1299 while idx < tokens.len() {
1300 if let Some(end) = rust_string_literal_end(tokens, idx) {
1301 let _ = write!(
1302 out,
1303 "{segment}{literal}",
1304 segment = compact_token_spacing_segment(&tokens[segment_start..idx]),
1305 literal = &tokens[idx..end]
1306 );
1307 idx = end;
1308 segment_start = idx;
1309 } else {
1310 idx += tokens[idx..]
1311 .chars()
1312 .next()
1313 .map(char::len_utf8)
1314 .unwrap_or(1);
1315 }
1316 }
1317 out.push_str(&compact_token_spacing_segment(&tokens[segment_start..]));
1318 out.trim().to_owned()
1319}
1320
1321fn rust_string_literal_end(tokens: &str, start: usize) -> Option<usize> {
1322 normal_string_literal_end(tokens, start).or_else(|| raw_string_literal_end(tokens, start))
1323}
1324
1325fn normal_string_literal_end(tokens: &str, start: usize) -> Option<usize> {
1326 let bytes = tokens.as_bytes();
1327 let quote = match bytes.get(start) {
1328 Some(b'"') => start,
1329 Some(b'b' | b'c') if bytes.get(start + 1) == Some(&b'"') => start + 1,
1330 _ => return None,
1331 };
1332
1333 let mut idx = quote + 1;
1334 let mut escaped = false;
1335 while idx < bytes.len() {
1336 match bytes[idx] {
1337 b'\\' if !escaped => escaped = true,
1338 b'"' if !escaped => return Some(idx + 1),
1339 _ => escaped = false,
1340 }
1341 idx += 1;
1342 }
1343 None
1344}
1345
1346fn raw_string_literal_end(tokens: &str, start: usize) -> Option<usize> {
1347 let bytes = tokens.as_bytes();
1348 let mut idx = match bytes.get(start) {
1349 Some(b'r') => start + 1,
1350 Some(b'b' | b'c') if bytes.get(start + 1) == Some(&b'r') => start + 2,
1351 _ => return None,
1352 };
1353
1354 let hashes_start = idx;
1355 while bytes.get(idx) == Some(&b'#') {
1356 idx += 1;
1357 }
1358 if bytes.get(idx) != Some(&b'"') {
1359 return None;
1360 }
1361 let hash_count = idx - hashes_start;
1362 idx += 1;
1363
1364 while idx < bytes.len() {
1365 if bytes[idx] == b'"' {
1366 let hashes_end = idx + 1 + hash_count;
1367 if hashes_end <= bytes.len()
1368 && bytes[idx + 1..hashes_end].iter().all(|byte| *byte == b'#')
1369 {
1370 return Some(hashes_end);
1371 }
1372 }
1373 idx += 1;
1374 }
1375 None
1376}
1377
1378fn compact_token_spacing_segment(tokens: &str) -> String {
1379 let mut out = String::with_capacity(tokens.len());
1380 let mut prev_was_space = false;
1381 for ch in tokens.chars() {
1382 if ch.is_whitespace() {
1383 if !prev_was_space {
1384 out.push(' ');
1385 prev_was_space = true;
1386 }
1387 } else {
1388 out.push(ch);
1389 prev_was_space = false;
1390 }
1391 }
1392
1393 for (from, to) in [
1394 (" . ", "."),
1395 (" .", "."),
1396 (". ", "."),
1397 (" :: ", "::"),
1398 (" ::", "::"),
1399 (":: ", "::"),
1400 (" (", "("),
1401 ("[ ", "["),
1402 (" ]", "]"),
1403 (" ,", ","),
1404 (" :", ":"),
1405 (".. ", ".."),
1406 (" !", "!"),
1407 ("| |", "||"),
1408 (" |", "|"),
1409 (",..", ", .."),
1410 ] {
1411 out = out.replace(from, to);
1412 }
1413 compact_unary_bang_spacing(&out)
1414}
1415
1416fn compact_unary_bang_spacing(tokens: &str) -> String {
1417 let mut out = String::with_capacity(tokens.len());
1418 let mut chars = tokens.chars().peekable();
1419 while let Some(ch) = chars.next() {
1420 out.push(ch);
1421 if ch != '!' || chars.peek() != Some(&' ') {
1422 continue;
1423 }
1424 let previous = out[..out.len() - ch.len_utf8()]
1425 .chars()
1426 .rev()
1427 .find(|candidate| !candidate.is_whitespace());
1428 if previous.is_none_or(|previous| {
1429 matches!(
1430 previous,
1431 '(' | '['
1432 | '{'
1433 | '='
1434 | ':'
1435 | ','
1436 | ';'
1437 | '|'
1438 | '&'
1439 | '+'
1440 | '-'
1441 | '*'
1442 | '/'
1443 | '%'
1444 | '<'
1445 | '>'
1446 | '?'
1447 )
1448 }) {
1449 chars.next();
1450 }
1451 }
1452 out
1453}
1454
1455fn format_block_expr(
1463 out: &mut String,
1464 source: &SourceMap<'_>,
1465 expr: &syn::Expr,
1466 indent: usize,
1467 preserve_legacy_names: bool,
1468) {
1469 let rendered = expr_source(source, expr, preserve_legacy_names);
1470 let inline = rendered.trim();
1471
1472 if contains_multiline_string_literal(inline) {
1476 out.push_str(inline);
1477 return;
1478 }
1479
1480 if let syn::Expr::Struct(structure) = expr {
1481 let fits = !inline.contains('\n') && indent + inline.len() + 2 <= INLINE_WIDTH;
1483 if !fits {
1484 if let Some(multiline) =
1485 format_struct_multiline(source, structure, indent, preserve_legacy_names)
1486 {
1487 out.push_str(&multiline);
1488 return;
1489 }
1490 }
1491 }
1492
1493 out.push_str(&reindent_block_expr(inline, indent));
1494}
1495
1496fn format_struct_multiline(
1501 source: &SourceMap<'_>,
1502 structure: &syn::ExprStruct,
1503 indent: usize,
1504 preserve_legacy_names: bool,
1505) -> Option<String> {
1506 let path = source
1507 .span_snippet(structure.path.span())?
1508 .trim()
1509 .to_owned();
1510 let field_indent = indent + INDENT_WIDTH;
1511
1512 let mut out = String::new();
1513 let _ = writeln!(out, "{path} {{");
1514
1515 for field in &structure.fields {
1516 let name = source.span_snippet(field.member.span())?.trim().to_owned();
1517 push_spaces(&mut out, field_indent);
1518 if field.colon_token.is_none() {
1519 out.push_str(&name);
1521 } else {
1522 let _ = write!(out, "{name}: ");
1523 let value_column = field_indent + name.len() + ": ".len();
1524 out.push_str(&format_expr_value(
1525 source,
1526 &field.expr,
1527 field_indent,
1528 value_column,
1529 preserve_legacy_names,
1530 ));
1531 }
1532 out.push_str(",\n");
1533 }
1534
1535 if let Some(rest) = &structure.rest {
1536 let rest_source = source.span_snippet(rest.span())?.trim().to_owned();
1537 push_spaces(&mut out, field_indent);
1538 let _ = write!(
1539 out,
1540 "..{rest}",
1541 rest = reindent_block_expr(&rest_source, field_indent)
1542 );
1543 out.push('\n');
1544 }
1545
1546 push_spaces(&mut out, indent);
1547 out.push('}');
1548 Some(out)
1549}
1550
1551fn format_expr_value(
1560 source: &SourceMap<'_>,
1561 expr: &syn::Expr,
1562 indent: usize,
1563 value_column: usize,
1564 preserve_legacy_names: bool,
1565) -> String {
1566 if let syn::Expr::Struct(structure) = expr {
1567 let authored = expr_source(source, expr, preserve_legacy_names);
1568 let inline = authored.trim();
1569 let fits = !inline.contains('\n') && value_column + inline.len() <= INLINE_WIDTH;
1570 if !fits {
1571 if let Some(multiline) =
1572 format_struct_multiline(source, structure, indent, preserve_legacy_names)
1573 {
1574 return multiline;
1575 }
1576 }
1577 }
1578
1579 if let syn::Expr::Call(call) = expr {
1580 if let Some(argument) = (call.args.len() == 1).then(|| call.args.first()).flatten() {
1581 if let (Some(function), Some(authored_argument)) = (
1582 source.span_snippet(call.func.span()).map(str::trim),
1583 source.span_snippet(argument.span()).map(str::trim),
1584 ) {
1585 let formatted_argument = format_expr_value(
1586 source,
1587 argument,
1588 indent,
1589 value_column + function.len() + 1,
1590 preserve_legacy_names,
1591 );
1592 if formatted_argument != authored_argument {
1593 return format!("{function}({formatted_argument})");
1594 }
1595 }
1596 }
1597 }
1598
1599 let value = expr_source(source, expr, preserve_legacy_names);
1600 let value = reindent_block_expr(value.trim(), indent);
1601 let value = format_embedded_macro_bodies_at_indent(&value, indent, preserve_legacy_names);
1602 reindent_block_expr(value.trim(), indent)
1603}
1604
1605fn reindent_block_expr(snippet: &str, indent: usize) -> String {
1634 if !snippet.contains('\n') {
1635 return snippet.to_owned();
1636 }
1637
1638 let mut lines = snippet.lines();
1639 let Some(first) = lines.next() else {
1640 return snippet.to_owned();
1641 };
1642 let rest: Vec<&str> = lines.collect();
1643
1644 let Some(base) = rest
1645 .iter()
1646 .filter(|line| !line.trim().is_empty())
1647 .map(|line| line.len() - line.trim_start().len())
1648 .min()
1649 else {
1650 return snippet.to_owned();
1651 };
1652
1653 if base >= indent && base <= indent + INDENT_WIDTH * 2 {
1658 return snippet.to_owned();
1659 }
1660
1661 let mut out = String::with_capacity(snippet.len());
1662 out.push_str(first);
1663 for line in rest {
1664 out.push('\n');
1665 if line.trim().is_empty() {
1666 continue;
1668 }
1669 let current = line.len() - line.trim_start().len();
1670 push_spaces(&mut out, indent + current.saturating_sub(base));
1671 out.push_str(line.trim_start());
1672 }
1673 out
1674}
1675
1676fn push_spaces(out: &mut String, count: usize) {
1677 out.extend(std::iter::repeat_n(' ', count));
1678}
1679
1680#[cfg(test)]
1681mod tests;
1682
1683#[cfg(test)]
1684mod verify_tests;