1use crate::ast::{Expr, LogicalOp};
15use crate::trivia::{Comment, GapPiece, scan_gap, take_block_comment};
16
17fn literal_level(value: &crate::Literal) -> Level {
19 let negative = match value {
20 crate::Literal::I8(value) => *value < 0,
21 crate::Literal::I16(value) => *value < 0,
22 crate::Literal::I32(value) => *value < 0,
23 crate::Literal::I64(value) => *value < 0,
24 crate::Literal::I128(value) => *value < 0,
25 crate::Literal::Isize(value) => *value < 0,
26 _ => false,
27 };
28 if negative {
29 Level::UNARY
30 } else {
31 Level::PRIMARY
32 }
33}
34
35struct Source<'a> {
39 text: &'a str,
40 lines: Vec<usize>,
41 bytes: Vec<usize>,
42}
43
44impl<'a> Source<'a> {
45 fn new(text: &'a str) -> Self {
47 let mut lines = vec![0];
48 let mut bytes = Vec::new();
49 for (character, (byte, ch)) in text.char_indices().enumerate() {
51 bytes.push(byte);
52 if ch == '\n' {
53 lines.push(character + 1);
54 }
55 }
56 bytes.push(text.len());
57 Self { text, lines, bytes }
58 }
59
60 fn byte(&self, position: proc_macro2::LineColumn) -> usize {
64 debug_assert!((1..=self.lines.len()).contains(&position.line));
65 let character = self.lines[position.line - 1] + position.column;
66 debug_assert!(
67 character
68 < self
69 .lines
70 .get(position.line)
71 .copied()
72 .unwrap_or(self.bytes.len())
73 );
74 self.bytes[character]
75 }
76
77 fn between(&self, from: proc_macro2::LineColumn, to: proc_macro2::LineColumn) -> &'a str {
81 if self.text.is_empty() {
82 return "";
83 }
84 self.text.get(self.byte(from)..self.byte(to)).unwrap_or("")
85 }
86}
87
88type Doc = pretty::RcDoc<'static, ()>;
90
91fn verbatim_doc(text: String) -> Doc {
95 let mut lines = text.split('\n');
96 let first = Doc::text(lines.next().unwrap_or_default().to_owned());
97 lines.fold(first, |doc, line| {
98 let line = Doc::text(line.to_owned());
99 doc.append(Doc::nesting(move |indent| {
100 let offset = isize::try_from(indent)
101 .expect("document indentation fits isize")
102 .checked_neg()
103 .expect("nonnegative indentation can be negated");
104 Doc::hardline().append(line.clone()).nest(offset)
105 }))
106 })
107}
108
109fn trivia_doc(text: String) -> Doc {
113 trivia_doc_at(text, 4)
114}
115
116fn trivia_doc_at(text: String, continuation: isize) -> Doc {
120 let mut lines = text.split('\n');
121 let first = Doc::text(lines.next().unwrap_or_default().to_owned());
122 lines.fold(first, |doc, line| {
123 doc.append(
124 Doc::hardline()
125 .append(Doc::text(
126 line.strip_prefix(" ").unwrap_or(line).to_owned(),
127 ))
128 .nest(continuation),
129 )
130 })
131}
132
133fn gap_doc(pieces: &[GapPiece], spacing: Spacing) -> Doc {
137 if pieces
138 .iter()
139 .any(|piece| matches!(piece, GapPiece::Comment(_)))
140 && let Some(index) = pieces
141 .iter()
142 .position(|piece| matches!(piece, GapPiece::Punct(_)))
143 && matches!(spacing, Spacing::Around | Spacing::CommaAfter)
144 {
145 let GapPiece::Punct(token) = pieces[index] else {
146 unreachable!()
147 };
148 let before = emit_gap(&pieces[..index], Spacing::None, 0);
149 let after = emit_gap(&pieces[index + 1..], Spacing::None, 0);
150 let after_empty = after.is_empty();
151 let before_line = matches!(
152 pieces.get(index.wrapping_sub(1)),
153 Some(GapPiece::Comment(Comment::Line(_)))
154 );
155 let after_line = matches!(pieces.last(), Some(GapPiece::Comment(Comment::Line(_))));
156 let prefix = if before_line {
157 trivia_doc_at(before, 0)
158 } else {
159 trivia_doc_at(before.trim_end().to_owned(), 0)
160 };
161 let suffix = if after_line {
162 trivia_doc_at(after, 0)
163 } else {
164 trivia_doc_at(after.trim_end().to_owned(), 0)
165 };
166 return match spacing {
167 Spacing::Around => prefix
168 .append(if before_line {
169 Doc::nil()
170 } else {
171 Doc::softline()
172 })
173 .append(token)
174 .append(if after_empty {
175 Doc::space()
176 } else {
177 suffix.append(if after_line { Doc::nil() } else { Doc::space() })
178 }),
179 Spacing::CommaAfter => prefix.append(token).append(if after_empty {
180 Doc::line()
181 } else {
182 suffix.append(if after_line { Doc::nil() } else { Doc::line() })
183 }),
184 Spacing::None => unreachable!(),
185 };
186 }
187 if pieces
188 .iter()
189 .all(|piece| matches!(piece, GapPiece::Punct(_)))
190 {
191 Doc::concat(pieces.iter().map(|piece| {
192 let GapPiece::Punct(token) = piece else {
193 unreachable!()
194 };
195 match spacing {
196 Spacing::Around => Doc::line().append(*token).append(" "),
197 Spacing::CommaAfter => Doc::text(*token).append(Doc::line()),
198 Spacing::None => Doc::text(*token),
199 }
200 }))
201 } else {
202 trivia_doc(emit_gap(pieces, spacing, 0))
203 }
204}
205
206fn binary_doc(lhs: Doc, gap: &[GapPiece], rhs: Doc) -> Doc {
210 lhs.append(gap_doc(gap, Spacing::Around).append(rhs).nest(4))
211 .group()
212}
213
214fn body_gap_doc(pieces: &[GapPiece], trim_start: bool) -> Doc {
220 let text = emit_gap(pieces, Spacing::Around, 0);
221 let text = if trim_start { text.trim_start() } else { &text };
222 if matches!(pieces.last(), Some(GapPiece::Comment(Comment::Line(_)))) {
223 trivia_doc_at(text.to_owned(), 0)
224 } else {
225 trivia_doc_at(text.trim_end().to_owned(), 0).append(Doc::line())
226 }
227}
228
229#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
232struct Level(u8);
233
234impl Level {
235 const RANGE: Level = Level(0);
236 const OR: Level = Level(1);
237 const AND: Level = Level(2);
238 const COMPARISON: Level = Level(3);
239 const BIT_OR: Level = Level(4);
240 const BIT_XOR: Level = Level(5);
241 const BIT_AND: Level = Level(6);
242 const SHIFT: Level = Level(7);
243 const ADDITIVE: Level = Level(8);
244 const MULTIPLICATIVE: Level = Level(9);
245 const CAST: Level = Level(10);
246 const UNARY: Level = Level(11);
247 const POSTFIX: Level = Level(12);
248 const PRIMARY: Level = Level(13);
249
250 fn tighter(self) -> Level {
252 Level(self.0 + 1)
253 }
254}
255
256fn indent(depth: usize) -> String {
260 " ".repeat(depth)
261}
262
263#[derive(Clone, Copy)]
265enum Spacing {
266 Around,
268 None,
270 CommaAfter,
272}
273
274fn emit_gap(pieces: &[GapPiece], spacing: Spacing, depth: usize) -> String {
285 let cont = indent(depth + 1);
286 let mut out = String::new();
287 for piece in pieces {
288 match piece {
289 GapPiece::Punct(tok) => {
290 match spacing {
291 Spacing::Around => {
292 if !out.ends_with(' ') {
296 out.push(' ');
297 }
298 out.push_str(tok);
299 out.push(' ');
300 }
301 Spacing::None => out.push_str(tok),
302 Spacing::CommaAfter => {
303 if out.ends_with(' ') && !out.ends_with(&cont) {
313 out.pop();
314 }
315 out.push_str(tok);
316 out.push(' ');
317 }
318 }
319 }
320 GapPiece::Comment(Comment::Block(text)) => {
321 if !out.ends_with(' ') {
325 out.push(' ');
326 }
327 out.push_str("/* ");
328 out.push_str(text);
329 out.push_str(" */ ");
330 }
331 GapPiece::Comment(Comment::Line(text)) => {
332 let continuation = out
335 .rsplit_once('\n')
336 .is_some_and(|(_, tail)| tail.trim().is_empty());
337 if continuation {
338 out.push_str("// ");
339 } else {
340 let trimmed_len = out.trim_end().len();
341 out.truncate(trimmed_len);
342 out.push_str(" // ");
343 }
344 out.push_str(text);
345 out.push('\n');
346 out.push_str(&cont);
347 }
348 }
349 }
350 out
351}
352
353fn binary_op_level(name: &str) -> Level {
362 match name {
363 "|" => Level::BIT_OR,
364 "^" => Level::BIT_XOR,
365 "&" => Level::BIT_AND,
366 "<<" | ">>" => Level::SHIFT,
367 "+" | "-" => Level::ADDITIVE,
368 "*" | "/" | "%" => Level::MULTIPLICATIVE,
369 "==" | "!=" | "<" | ">" | "<=" | ">=" => Level::COMPARISON,
370 other => unreachable!("binary_op_level called with unknown operator `{other}`"),
371 }
372}
373
374fn render_literal(span: crate::ExprSpan) -> String {
378 span.start.source_text().unwrap_or_default()
379}
380
381fn gap_between(
390 source: &Source<'_>,
391 prev_end: proc_macro2::Span,
392 next_start: proc_macro2::Span,
393 expected: &[&'static str],
394) -> Vec<GapPiece> {
395 scan_gap(source.between(prev_end.end(), next_start.start()), expected)
396}
397
398fn member_gap(
405 source: &Source<'_>,
406 receiver_end: proc_macro2::Span,
407 name_start: proc_macro2::Span,
408) -> Vec<GapPiece> {
409 grouping_gap(source, receiver_end.end(), name_start.start(), &["."])
410}
411
412fn format_postfix_base(
418 base: &Expr,
419 source: &Source<'_>,
420 depth: usize,
421 start: proc_macro2::LineColumn,
422) -> Doc {
423 let leading = grouping_gap(source, start, base.span().start.start(), &[]);
424 if leading.is_empty() {
425 format_at(base, source, depth, Level::POSTFIX)
426 } else {
427 let (text, _) = render(base, source, depth);
428 let prefix = emit_gap(&leading, Spacing::None, 0);
429 Doc::text("(")
430 .append(trivia_doc(prefix.trim_start().to_owned()))
431 .append(text)
432 .append(")")
433 }
434}
435
436fn emit_list(
457 source: &Source<'_>,
458 depth: usize,
459 delims: (&'static str, &'static str),
460 bounds: (proc_macro2::LineColumn, proc_macro2::LineColumn),
461 elements: &[Expr],
462 trailing_comma: bool,
463) -> Doc {
464 let (open, close) = delims;
465 let (open_pos, close_pos) = bounds;
466 let scan = |from: proc_macro2::LineColumn,
470 to: proc_macro2::LineColumn,
471 expected: &[&'static str]|
472 -> Vec<GapPiece> { scan_gap(source.between(from, to), expected) };
473
474 if elements.is_empty() {
475 let pieces = scan(open_pos, close_pos, &[open, close]);
477 let whole = emit_gap(&pieces, Spacing::None, 0);
478 return trivia_doc(glue_before_close(&glue_after_open(&whole, open), close));
479 }
480 let mut pre = grouping_gap(source, open_pos, elements[0].span().start.start(), &[open]);
485 if open == "(" {
486 pre.insert(0, GapPiece::Punct("("));
487 }
488 let mut out = trivia_doc(glue_after_open(&emit_gap(&pre, Spacing::None, 0), open));
489 let mut body = Doc::line_();
490 for (i, el) in elements.iter().enumerate() {
491 body = body.append(format_at(el, source, depth, Level::OR));
492 if i + 1 < elements.len() {
493 let pieces = grouping_gap(
494 source,
495 el.span().end.end(),
496 elements[i + 1].span().start.start(),
497 &[","],
498 );
499 body = body.append(gap_doc(&pieces, Spacing::CommaAfter));
500 }
501 }
502 if trailing_comma {
503 body = body.append(",");
504 }
505 let mut post = grouping_gap(
509 source,
510 elements[elements.len() - 1].span().end.end(),
511 close_pos,
512 &[close],
513 );
514 if close == ")" {
515 post.push(GapPiece::Punct(")"));
516 }
517 out = out.append(body.nest(4));
518 let tail = glue_before_close(&emit_gap(&post, Spacing::None, 0), close);
519 out.append(Doc::line_()).append(trivia_doc(tail)).group()
520}
521
522fn glue_after_open(gap: &str, open: &'static str) -> String {
526 match gap.strip_prefix(&format!("{open} ")) {
527 Some(rest) => format!("{open}{rest}"),
528 None => gap.to_string(),
529 }
530}
531
532fn glue_before_close(gap: &str, close: &'static str) -> String {
535 if let Some((_, last_line)) = gap.rsplit_once('\n') {
536 if let Some(rest) = last_line.strip_suffix(close)
542 && rest.chars().all(|c| c == ' ')
543 {
544 return gap.to_string();
545 }
546 }
547 match gap.strip_suffix(&format!(" {close}")) {
548 Some(rest) => format!("{rest}{close}"),
549 None => gap.to_string(),
550 }
551}
552
553fn binary_op_token(name: &str) -> &'static str {
557 match name {
558 "|" => "|",
559 "^" => "^",
560 "&" => "&",
561 "<<" => "<<",
562 ">>" => ">>",
563 "+" => "+",
564 "-" => "-",
565 "*" => "*",
566 "/" => "/",
567 "%" => "%",
568 "==" => "==",
569 "!=" => "!=",
570 "<" => "<",
571 ">" => ">",
572 "<=" => "<=",
573 ">=" => ">=",
574 other => unreachable!("binary_op_token called with unknown operator `{other}`"),
575 }
576}
577
578fn unary_op_token(name: &str) -> &'static str {
580 match name {
581 "-" => "-",
582 "!" => "!",
583 other => unreachable!("unary_op_token called with unknown operator `{other}`"),
584 }
585}
586
587fn render_type_expr(type_expr: &crate::TypeExpr, source: &Source<'_>) -> String {
596 let span = type_expr.span();
597 let original = source.between(span.start.start(), span.end.end());
598 if original.contains("/*") || original.contains("//") {
599 return original.to_owned();
600 }
601 let mut output = String::new();
602 write_type_expr(type_expr, &mut output);
603 output
604}
605
606fn write_type_expr(type_expr: &crate::TypeExpr, output: &mut String) {
610 match type_expr {
611 crate::TypeExpr::Named { name, args, .. } => {
612 output.push_str(name);
613 if !args.is_empty() {
614 write_type_list(args, output, false);
615 }
616 }
617 crate::TypeExpr::Array { element, .. } => {
618 output.push('[');
619 write_type_expr(element, output);
620 output.push(']');
621 }
622 crate::TypeExpr::Tuple { elements, .. } => {
623 write_type_list(elements, output, true);
624 }
625 }
626}
627
628fn write_type_list(elements: &[crate::TypeExpr], output: &mut String, tuple: bool) {
632 output.push('(');
633 for (index, element) in elements.iter().enumerate() {
635 if index != 0 {
636 output.push_str(", ");
637 }
638 write_type_expr(element, output);
639 }
640 if tuple && elements.len() == 1 {
641 output.push(',');
642 }
643 output.push(')');
644}
645
646fn render(expr: &Expr, source: &Source<'_>, depth: usize) -> (Doc, Level) {
655 match expr {
656 Expr::Struct {
657 name,
658 name_span,
659 fields,
660 span,
661 } => {
662 let mut out = Doc::text(name.clone());
663 let mut body = Doc::nil();
664 if let Some(first) = fields.first() {
665 let open = grouping_gap(
666 source,
667 name_span.end.end(),
668 first.name_span.start.start(),
669 &["{"],
670 );
671 body = body.append(body_gap_doc(&open, false));
672 for (index, field) in fields.iter().enumerate() {
673 body = body.append(Doc::text(field.name.clone()));
674 let colon = grouping_gap(
675 source,
676 field.name_span.end.end(),
677 field.value.span().start.start(),
678 &[":"],
679 );
680 body = body.append(trivia_doc(emit_gap(&colon, Spacing::CommaAfter, 0)));
681 body = body.append(format_at(&field.value, source, depth, Level::RANGE));
682 if let Some(next) = fields.get(index + 1) {
683 let comma = grouping_gap(
684 source,
685 field.value.span().end.end(),
686 next.name_span.start.start(),
687 &[","],
688 );
689 body = body.append(gap_doc(&comma, Spacing::CommaAfter));
690 }
691 }
692 let last = fields.last().expect("non-empty fields");
693 let mut tail = grouping_gap(
694 source,
695 last.value.span().end.end(),
696 span.end.end(),
697 &[",", "}"],
698 );
699 tail.retain(|piece| !matches!(piece, GapPiece::Punct(",")));
700 let closing = emit_gap(&tail, Spacing::Around, 0);
701 out = out
702 .append(body.nest(4))
703 .append(Doc::line())
704 .append(trivia_doc(closing.trim().to_owned()))
705 .group();
706 } else {
707 let tail = grouping_gap(source, name_span.end.end(), span.end.end(), &["{", "}"]);
708 out = out
709 .append(" ")
710 .append(trivia_doc(emit_gap(&tail, Spacing::None, 0)));
711 }
712 (out, Level::PRIMARY)
713 }
714 Expr::Literal { value, span } => {
715 (verbatim_doc(render_literal(*span)), literal_level(value))
716 }
717 Expr::Ident { name, .. } => (Doc::text(name.clone()), Level::PRIMARY),
718 Expr::Logical { op, lhs, rhs, .. } => {
719 let level = match op {
720 LogicalOp::Or => Level::OR,
721 LogicalOp::And => Level::AND,
722 };
723 let op_static: &'static str = match op {
724 LogicalOp::Or => "||",
725 LogicalOp::And => "&&",
726 };
727 let lhs_s = format_at(lhs, source, depth, level);
728 let rhs_s = format_at(rhs, source, depth, level.tighter());
729 let pieces = gap_between(source, lhs.span().end, rhs.span().start, &[op_static]);
730 (binary_doc(lhs_s, &pieces, rhs_s), level)
731 }
732 Expr::Op { operands, .. } if operands.is_empty() => (Doc::text(".."), Level::RANGE),
733 Expr::Op {
734 name,
735 operands,
736 span,
737 } if operands.len() == 1
738 && matches!(
739 name.as_str(),
740 "range_from" | "range_to" | "range_to_inclusive"
741 ) =>
742 {
743 let operand_s = format_at(&operands[0], source, depth, Level::RANGE.tighter());
748 let text = match name.as_str() {
749 "range_from" => {
750 let pieces = gap_between(source, operands[0].span().end, span.end, &[".."]);
751 operand_s.append(gap_doc(&pieces, Spacing::None))
752 }
753 "range_to" => {
754 let pieces = gap_between(source, span.start, operands[0].span().start, &[]);
760 Doc::text("..")
761 .append(gap_doc(&pieces, Spacing::None))
762 .append(operand_s)
763 }
764 "range_to_inclusive" => {
765 let pieces = gap_between(source, span.start, operands[0].span().start, &[]);
766 Doc::text("..=")
767 .append(gap_doc(&pieces, Spacing::None))
768 .append(operand_s)
769 }
770 _ => unreachable!("guarded by the outer match arm"),
771 };
772 (text, Level::RANGE)
773 }
774 Expr::Op {
775 name,
776 operands,
777 span,
778 } if operands.len() == 1 => {
779 let operand_s = format_at(&operands[0], source, depth, Level::UNARY);
780 let op_static = unary_op_token(name);
781 let pieces = gap_between(source, span.start, operands[0].span().start, &[]);
785 let default_sep = if matches!(&operands[0], Expr::Op { name, operands, .. }
787 if operands.len() == 1 && matches!(name.as_str(), "-" | "!"))
788 {
789 " "
790 } else {
791 ""
792 };
793 let gap = if pieces.iter().any(|p| matches!(p, GapPiece::Comment(_))) {
794 emit_gap(&pieces, Spacing::None, 0)
795 } else {
796 default_sep.to_string()
797 };
798 (
799 Doc::text(op_static)
800 .append(trivia_doc(gap))
801 .append(operand_s),
802 Level::UNARY,
803 )
804 }
805 Expr::Op { name, operands, .. } if name == "range" || name == "range_inclusive" => {
806 let lhs_s = format_at(&operands[0], source, depth, Level::RANGE.tighter());
809 let rhs_s = format_at(&operands[1], source, depth, Level::RANGE.tighter());
810 let op_static: &'static str = if name == "range_inclusive" {
811 "..="
812 } else {
813 ".."
814 };
815 let pieces = gap_between(
816 source,
817 operands[0].span().end,
818 operands[1].span().start,
819 &[op_static],
820 );
821 (
822 lhs_s
823 .append(
824 Doc::softline_()
825 .append(gap_doc(&pieces, Spacing::None))
826 .append(rhs_s)
827 .nest(4),
828 )
829 .group(),
830 Level::RANGE,
831 )
832 }
833 Expr::Op { name, operands, .. } => {
834 let level = binary_op_level(name);
835 let (lhs_min, rhs_min) = if level == Level::COMPARISON {
839 (level.tighter(), level.tighter())
840 } else {
841 (level, level.tighter())
842 };
843 let lhs_s = format_at(&operands[0], source, depth, lhs_min);
844 let rhs_s = format_at(&operands[1], source, depth, rhs_min);
845 let op_static = binary_op_token(name);
847 let pieces = gap_between(
848 source,
849 operands[0].span().end,
850 operands[1].span().start,
851 &[op_static],
852 );
853 (binary_doc(lhs_s, &pieces, rhs_s), level)
854 }
855 Expr::Cast {
856 expr,
857 type_name,
858 span,
859 } => {
860 let expr_s = format_at(expr, source, depth, Level::CAST);
864 let pieces = gap_between(source, expr.span().end, span.end, &["as"]);
868 let text = binary_doc(expr_s, &pieces, Doc::text(type_name.clone()));
869 (text, Level::CAST)
870 }
871 Expr::Apply { callee, args, span } => {
872 let mut callee_s = format_postfix_base(callee, source, depth, span.start.start());
873 if matches!(callee.as_ref(), Expr::Member { args: None, .. }) {
876 callee_s = Doc::text("(").append(callee_s).append(")");
877 }
878 let tail = grouping_gap(source, callee.span().end.end(), span.end.start(), &[]);
879 callee_s = callee_s.append(gap_doc(&tail, Spacing::None));
880 let list = emit_list(
883 source,
884 depth,
885 ("(", ")"),
886 (span.end.start(), span.end.end()),
887 args,
888 false,
889 );
890 (callee_s.append(list), Level::POSTFIX)
891 }
892 Expr::Member {
893 receiver,
894 name,
895 name_span,
896 args,
897 span,
898 } => {
899 let receiver_s = format_postfix_base(receiver, source, depth, span.start.start());
900 let gap = member_gap(source, receiver.span().end, name_span.start);
901 let member_gap = if gap.iter().all(|piece| matches!(piece, GapPiece::Punct(_))) {
902 Doc::line_().append(".")
903 } else if gap
904 .iter()
905 .any(|piece| matches!(piece, GapPiece::Comment(Comment::Line(_))))
906 {
907 trivia_doc_at(emit_gap(&gap, Spacing::None, 0), 0)
908 } else {
909 verbatim_doc(emit_gap(&gap, Spacing::None, 0))
910 };
911 let mut text = receiver_s
912 .append(member_gap.append(Doc::text(name.clone())).nest(4))
913 .group();
914 if let Some(args) = args {
915 text = text.append(emit_list(
916 source,
917 depth,
918 ("(", ")"),
919 (name_span.end.end(), span.end.end()),
920 args,
921 false,
922 ));
923 }
924 (text, Level::POSTFIX)
925 }
926 Expr::Tuple { elements, span } => {
927 let list = emit_list(
931 source,
932 depth,
933 ("(", ")"),
934 (span.start.start(), span.end.end()),
935 elements,
936 elements.len() == 1,
937 );
938 (list, Level::PRIMARY)
939 }
940 Expr::Array {
941 elements,
942 annotation_span,
943 type_annotation,
944 span,
945 } => {
946 let close_pos = annotation_span
951 .map(|annotation_span| annotation_span.start.start())
952 .unwrap_or_else(|| span.end.end());
953 let mut list = emit_list(
954 source,
955 depth,
956 ("[", "]"),
957 (span.start.start(), close_pos),
958 elements,
959 false,
960 );
961 if let Some(type_annotation) = type_annotation {
962 let comments = annotation_span
963 .map(|annotation| {
964 gap_between(source, annotation.start, type_annotation.span().start, &[])
965 })
966 .unwrap_or_default();
967 let gap = emit_gap(&comments, Spacing::None, 0);
968 list = list
969 .append(":")
970 .append(trivia_doc(if gap.is_empty() {
971 " ".to_owned()
972 } else {
973 gap
974 }))
975 .append(verbatim_doc(render_type_expr(type_annotation, source)));
976 }
977 (list, Level::PRIMARY)
978 }
979 Expr::TupleIndex { base, index, span } => (
980 format_postfix_base(base, source, depth, span.start.start())
981 .append(gap_doc(
982 &grouping_gap(source, base.span().end.end(), span.end.start(), &["."]),
983 Spacing::None,
984 ))
985 .append(Doc::text(index.to_string())),
986 Level::POSTFIX,
987 ),
988 Expr::If {
989 cond,
990 then_branch,
991 else_branch,
992 span,
993 } => {
994 let cond_s = restricted_doc(
1003 cond,
1004 source,
1005 depth,
1006 crate::ExpressionRestriction::NoStructLiteral,
1007 );
1008 let then_s = format_at(then_branch, source, depth, Level::OR);
1009 let if_gap = grouping_gap(source, span.start.start(), header_start(cond), &["if"]);
1010 let open_gap = grouping_gap(
1011 source,
1012 header_end(cond),
1013 then_branch.span().start.start(),
1014 &["{"],
1015 );
1016 let mut text = Doc::nil();
1017 text = text.append(trivia_doc(
1020 emit_gap(&if_gap, Spacing::Around, 0)
1021 .trim_start()
1022 .to_owned(),
1023 ));
1024 text = text.append(cond_s);
1025 text = text.append(body_gap_doc(&open_gap, false).append(then_s).nest(4));
1026 match else_branch {
1027 None => {
1028 let close_gap = gap_between(source, then_branch.span().end, span.end, &["}"]);
1031 text = text.append(Doc::line()).append(trivia_doc(
1035 emit_gap(&close_gap, Spacing::Around, 0).trim().to_owned(),
1036 ));
1037 }
1038 Some(else_branch) => {
1039 let is_chain = matches!(else_branch.as_ref(), Expr::If { .. });
1040 let expected: &[&'static str] = if is_chain {
1043 &["}", "else"]
1044 } else {
1045 &["}", "else", "{"]
1046 };
1047 let else_gap = gap_between(
1051 source,
1052 then_branch.span().end,
1053 else_branch.span().start,
1054 expected,
1055 );
1056 text = text.append(Doc::line());
1057 if is_chain {
1058 let (else_s, _) = render(else_branch, source, depth);
1062 text = text.append(body_gap_doc(&else_gap, true)).append(else_s);
1063 } else {
1064 let else_s = format_at(else_branch, source, depth, Level::OR);
1065 text = text.append(body_gap_doc(&else_gap, true).append(else_s).nest(4));
1066 let final_close_gap =
1067 gap_between(source, else_branch.span().end, span.end, &["}"]);
1068 text = text.append(Doc::line()).append(trivia_doc(
1069 emit_gap(&final_close_gap, Spacing::Around, 0)
1070 .trim()
1071 .to_owned(),
1072 ));
1073 }
1074 }
1075 }
1076 (text.group(), Level::PRIMARY)
1077 }
1078 Expr::Closure { params, body, span } => {
1079 let body_s = format_at(body, source, depth, Level::OR);
1080 let header = if params.is_empty() {
1081 Doc::text("||")
1082 } else {
1083 let leading = gap_between(source, span.start, params[0].name_span.start, &[]);
1084 let mut parameters =
1085 trivia_doc(emit_gap(&leading, Spacing::None, 0).trim_start().to_owned());
1086 for (index, param) in params.iter().enumerate() {
1087 if index > 0 {
1088 let comma = gap_between(
1089 source,
1090 params[index - 1].type_expr.span().end,
1091 param.name_span.start,
1092 &[","],
1093 );
1094 parameters = parameters.append(gap_doc(&comma, Spacing::CommaAfter));
1095 }
1096 let colon = gap_between(
1097 source,
1098 param.name_span.end,
1099 param.type_expr.span().start,
1100 &[":"],
1101 );
1102 parameters = parameters
1103 .append(Doc::text(param.name.clone()))
1104 .append(trivia_doc(emit_gap(&colon, Spacing::CommaAfter, 0)))
1105 .append(verbatim_doc(render_type_expr(¶m.type_expr, source)));
1106 }
1107 Doc::text("|")
1108 .append(Doc::line_().append(parameters).nest(4))
1109 .append(Doc::line_())
1110 .append("|")
1111 .group()
1112 };
1113 let (tail_start, expected): (proc_macro2::Span, &[&'static str]) = match params.last() {
1114 Some(last) => (last.type_expr.span().end, &["|"]),
1115 None => (span.start, &[]),
1116 };
1117 let pieces = gap_between(source, tail_start, body.span().start, expected);
1118 let comments: Vec<GapPiece> = pieces
1119 .into_iter()
1120 .filter(|p| matches!(p, GapPiece::Comment(_)))
1121 .collect();
1122 let gap = emit_gap(&comments, Spacing::None, 0);
1123 let has_line_comment = comments
1128 .iter()
1129 .any(|p| matches!(p, GapPiece::Comment(Comment::Line(_))));
1130 let sep = if has_line_comment {
1131 trivia_doc_at(gap, 0)
1132 } else if gap.trim().is_empty() {
1133 Doc::line()
1134 } else {
1135 trivia_doc(format!(" {} ", gap.trim()))
1136 };
1137 (
1139 header.append(sep.append(body_s).nest(4)).group(),
1140 Level::RANGE,
1141 )
1142 }
1143 }
1144}
1145
1146fn header_start(expr: &Expr) -> proc_macro2::LineColumn {
1153 match expr {
1154 Expr::Op { name, operands, .. }
1155 if operands.len() == 2 || (name == "range_from" && operands.len() == 1) =>
1156 {
1157 header_start(&operands[0])
1158 }
1159 Expr::Logical { lhs, .. } => header_start(lhs),
1160 Expr::Cast { expr, .. } => header_start(expr),
1161 _ => expr.span().start.start(),
1162 }
1163}
1164
1165fn header_end(expr: &Expr) -> proc_macro2::LineColumn {
1171 match expr {
1172 Expr::Op { name, operands, .. } if name != "range_from" && !operands.is_empty() => {
1173 header_end(operands.last().expect("non-empty operands"))
1174 }
1175 Expr::Logical { rhs, .. } => header_end(rhs),
1176 Expr::Closure { body, .. } => header_end(body),
1177 _ => expr.span().end.end(),
1178 }
1179}
1180
1181fn grouping_gap(
1187 source: &Source<'_>,
1188 from: proc_macro2::LineColumn,
1189 to: proc_macro2::LineColumn,
1190 expected: &[&'static str],
1191) -> Vec<GapPiece> {
1192 let gap = source.between(from, to);
1193 let mut rest = gap;
1194 let mut tokens = Vec::new();
1195 let mut next = 0;
1196 loop {
1197 rest = rest.trim_start();
1198 if let Some(after) = rest.strip_prefix("//") {
1199 rest = &after[after.find('\n').unwrap_or(after.len())..];
1200 } else if let Some((_, after)) = take_block_comment(rest) {
1201 rest = after;
1202 } else if let Some(after) = rest.strip_prefix('(') {
1203 tokens.push("(");
1204 rest = after;
1205 } else if let Some(after) = rest.strip_prefix(')') {
1206 tokens.push(")");
1207 rest = after;
1208 } else if next < expected.len() && rest.starts_with(expected[next]) {
1209 tokens.push(expected[next]);
1210 rest = &rest[expected[next].len()..];
1211 next += 1;
1212 } else {
1213 break;
1214 }
1215 }
1216 tokens.extend_from_slice(&expected[next..]);
1217 scan_gap(gap, &tokens)
1218 .into_iter()
1219 .filter(|piece| !matches!(piece, GapPiece::Punct("(" | ")")))
1220 .collect()
1221}
1222
1223fn header_contains_record(expr: &Expr) -> bool {
1227 match expr {
1228 Expr::Struct { .. } => true,
1229 Expr::Op { operands, .. } => operands.iter().any(header_contains_record),
1230 Expr::Logical { lhs, rhs, .. } => {
1231 header_contains_record(lhs) || header_contains_record(rhs)
1232 }
1233 Expr::Cast { expr, .. } | Expr::Closure { body: expr, .. } => header_contains_record(expr),
1234 Expr::Member { receiver, .. } => header_contains_record(receiver),
1235 Expr::TupleIndex { base, .. } => header_contains_record(base),
1236 Expr::Apply { callee, .. } => header_contains_record(callee),
1237 Expr::Literal { .. }
1238 | Expr::Ident { .. }
1239 | Expr::Tuple { .. }
1240 | Expr::Array { .. }
1241 | Expr::If { .. } => false,
1242 }
1243}
1244
1245pub fn format_expr_restricted(
1263 expr: &Expr,
1264 source: &str,
1265 depth: usize,
1266 restriction: crate::ExpressionRestriction,
1267) -> String {
1268 render_document(
1269 restricted_doc(expr, &Source::new(source), depth, restriction),
1270 depth,
1271 depth * 4,
1272 100,
1273 0,
1274 )
1275}
1276
1277fn restricted_doc(
1282 expr: &Expr,
1283 source: &Source<'_>,
1284 depth: usize,
1285 restriction: crate::ExpressionRestriction,
1286) -> Doc {
1287 let text = format_at(expr, source, depth, Level::RANGE);
1288 if restriction == crate::ExpressionRestriction::NoStructLiteral && header_contains_record(expr)
1289 {
1290 Doc::text("(").append(text).append(")")
1291 } else {
1292 text
1293 }
1294}
1295
1296pub fn format_expr_header(
1318 expr: &Expr,
1319 source: &str,
1320 depth: usize,
1321 bounds: (proc_macro2::LineColumn, proc_macro2::LineColumn),
1322) -> String {
1323 format_expr_header_with_layout(expr, source, depth, bounds, depth * 4, 100, 0)
1324}
1325
1326pub fn format_expr_header_with_layout(
1345 expr: &Expr,
1346 source: &str,
1347 depth: usize,
1348 bounds: (proc_macro2::LineColumn, proc_macro2::LineColumn),
1349 column: usize,
1350 width: usize,
1351 suffix_columns: usize,
1352) -> String {
1353 let source = &Source::new(source);
1354 let leading = grouping_gap(source, bounds.0, header_start(expr), &[]);
1355 let trailing = grouping_gap(source, header_end(expr), bounds.1, &[]);
1356 let mut text = trivia_doc(emit_gap(&leading, Spacing::None, 0).trim_start().to_owned());
1357 text = text.append(restricted_doc(
1358 expr,
1359 source,
1360 depth,
1361 crate::ExpressionRestriction::NoStructLiteral,
1362 ));
1363 let tail = emit_gap(&trailing, Spacing::None, 0);
1364 if matches!(trailing.last(), Some(GapPiece::Comment(Comment::Line(_)))) {
1365 text = text.append(trivia_doc(tail));
1366 } else {
1367 text = text.append(trivia_doc(tail.trim_end().to_owned()));
1368 }
1369 render_document(text, depth, column, width, suffix_columns)
1370}
1371
1372fn format_at(expr: &Expr, source: &Source<'_>, depth: usize, min_level: Level) -> Doc {
1379 let (text, level) = render(expr, source, depth);
1380 if level < min_level {
1381 Doc::text("(").append(text).append(")").group()
1382 } else {
1383 text
1384 }
1385}
1386
1387pub fn format_expr(expr: &Expr, source: &str, depth: usize) -> String {
1407 format_expr_with_layout(expr, source, depth, depth * 4, 100, 0)
1408}
1409
1410pub fn format_expr_with_layout(
1432 expr: &Expr,
1433 source: &str,
1434 depth: usize,
1435 column: usize,
1436 width: usize,
1437 suffix_columns: usize,
1438) -> String {
1439 render_document(
1440 format_at(expr, &Source::new(source), depth, Level::RANGE),
1441 depth,
1442 column,
1443 width,
1444 suffix_columns,
1445 )
1446}
1447
1448fn render_document(
1453 doc: Doc,
1454 depth: usize,
1455 column: usize,
1456 width: usize,
1457 suffix_columns: usize,
1458) -> String {
1459 let prefix = " ".repeat(column);
1460 let suffix = " ".repeat(suffix_columns);
1461 let doc = if column > depth * 4 + 4 {
1462 Doc::hardline()
1465 .append(" ")
1466 .flat_alt(Doc::nil())
1467 .group()
1468 .append(Doc::column(move |current| {
1469 if current == column {
1470 doc.clone()
1471 } else {
1472 doc.clone().nest(4)
1473 }
1474 }))
1475 } else {
1476 doc
1477 };
1478 let document = Doc::text(prefix)
1479 .append(doc.nest((depth * 4) as isize))
1480 .append(Doc::text(suffix));
1481 let mut out = String::new();
1482 document
1483 .render_fmt(width, &mut out)
1484 .expect("writing to String is infallible");
1485 out.truncate(out.len() - suffix_columns);
1486 out.drain(..column);
1487 out
1488}
1489
1490#[cfg(test)]
1491mod tests {
1492 use super::*;
1493 use crate::{AstContext, OpLookup, Parser};
1494
1495 #[test]
1497 fn wraps_long_expressions_with_leading_operators() {
1498 let source = std::iter::repeat_n("long_operand_name", 8)
1499 .collect::<Vec<_>>()
1500 .join(" + ");
1501 let text = fmt(&source);
1502 assert!(text.contains("\n + "), "{text}");
1503 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1504 assert_eq!(fmt(&text), text);
1505 }
1506
1507 #[test]
1509 fn wraps_binary_ranges_before_their_operators() {
1510 for operator in ["..", "..="] {
1511 let source = format!("{}{}{}", "a".repeat(45), operator, "b".repeat(45));
1512 let expr = parse(&source);
1513 let text = format_expr_with_layout(&expr, &source, 1, 13, 100, 1);
1514 assert_eq!(
1515 text,
1516 format!("{}\n {operator}{}", "a".repeat(45), "b".repeat(45))
1517 );
1518 assert_eq!(
1519 format_expr_with_layout(&parse(&text), &text, 1, 13, 100, 1),
1520 text
1521 );
1522 assert_eq!(
1523 fmt(&format!("left{operator}right")),
1524 format!("left{operator}right")
1525 );
1526 let call = format!("call({source})");
1527 let formatted = fmt(&call);
1528 assert!(
1529 formatted.lines().all(|line| line.len() <= 100),
1530 "{formatted}"
1531 );
1532 assert_eq!(fmt(&formatted), formatted);
1533 }
1534 }
1535
1536 #[test]
1538 fn empty_closure_can_break_before_its_header() {
1539 let source = "|| predicate";
1540 let expr = parse(source);
1541 let text = format_expr_with_layout(&expr, source, 1, 100, 100, 1);
1542 assert_eq!(text, "\n || predicate");
1543 assert_eq!(
1544 format_expr_with_layout(&parse(&text), &text, 1, 100, 100, 1),
1545 text
1546 );
1547 }
1548
1549 #[test]
1551 fn wraps_nested_calls_records_arrays_and_closures() {
1552 let name = "a_long_argument_name_that_occupies_thirty_columns";
1553 for source in [
1554 format!("outer(inner({name}, {name}), [{name}, {name}])"),
1555 format!("Record {{ first: ({name}, {name}), second: [{name}, {name}] }}"),
1556 format!("map([{name}, {name}], |value: i32| value + {name} + {name})"),
1557 ] {
1558 let text = fmt(&source);
1559 assert!(text.contains('\n'), "{text}");
1560 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1561 assert_eq!(fmt(&text), text);
1562 }
1563 }
1564
1565 #[test]
1567 fn wraps_closure_parameters_without_losing_comments() {
1568 let source = "|/* first */ a_long_parameter: i32 /* second */, another_long_parameter: i32, third_long_parameter: i32, fourth_long_parameter: i32| a_long_parameter";
1569 let text = fmt(source);
1570 for label in ["first", "second"] {
1571 assert_eq!(text.matches(label).count(), 1, "{text}");
1572 }
1573 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1574 assert_eq!(fmt(&text), text);
1575 }
1576
1577 #[test]
1579 fn wraps_commented_binary_gaps() {
1580 let operand = "a".repeat(45);
1581 let source = format!("{operand} /* keep */ + {operand} + {operand}");
1582 let text = fmt(&source);
1583 assert!(text.lines().all(|line| line.len() <= 100), "{text}");
1584 assert_eq!(text.matches("keep").count(), 1);
1585 assert_eq!(fmt(&text), text);
1586 }
1587
1588 #[test]
1590 fn consecutive_line_comments_remain_separate() {
1591 let text = fmt("1 + // first\n// second\n2");
1592 assert_eq!(text, "1 + // first\n // second\n 2");
1593 assert_eq!(fmt(&text), text);
1594 }
1595
1596 #[test]
1598 fn brace_opening_line_comments_keep_their_mandatory_breaks() {
1599 for source in [
1600 "Record { // first\n value: 1 }",
1601 "if condition { // first\n 1 } else { // second\n 2 }",
1602 ] {
1603 let text = fmt(source);
1604 assert!(text.contains("// first\n"), "{text}");
1605 assert_eq!(fmt(&text), text);
1606 }
1607 }
1608
1609 #[test]
1611 fn embedding_reserves_exact_prefix_and_suffix_columns() {
1612 let source = "first + second";
1613 let expr = parse(source);
1614 assert_eq!(format_expr_with_layout(&expr, source, 1, 12, 27, 1), source);
1615 assert_eq!(
1616 format_expr_with_layout(&expr, source, 1, 12, 26, 1),
1617 "first\n + second"
1618 );
1619 let bounds = (
1620 proc_macro2::LineColumn { line: 1, column: 0 },
1621 proc_macro2::LineColumn {
1622 line: 1,
1623 column: source.len(),
1624 },
1625 );
1626 assert_eq!(
1627 format_expr_header_with_layout(&expr, source, 1, bounds, 12, 28, 2),
1628 source
1629 );
1630 assert_eq!(
1631 format_expr_header_with_layout(&expr, source, 1, bounds, 12, 27, 2),
1632 "first\n + second"
1633 );
1634 }
1635
1636 #[test]
1638 fn multiline_literal_spelling_is_independent_of_layout_nesting() {
1639 let source = "call(r#\"first\n second\"#, 0xffi32)";
1640 let expr = parse(source);
1641 let text = format_expr_with_layout(&expr, source, 2, 20, 30, 1);
1642 assert!(text.contains("r#\"first\n second\"#"), "{text}");
1643 assert!(text.contains("0xffi32"));
1644 assert_eq!(
1645 format_expr_with_layout(&parse(&text), &text, 2, 20, 30, 1),
1646 text
1647 );
1648 }
1649
1650 #[test]
1652 fn narrow_layout_preserves_expression_semantics_and_reaches_a_fixed_point() {
1653 for source in [
1654 "-(first_long_name + second_long_name) as i32",
1655 "first_long_name - (second_long_name - third_long_name)",
1656 "(|value: i32| value + first_long_name)(second_long_name)",
1657 "(holder.long_member_name)(first_long_name, second_long_name)",
1658 "first_long_name..=second_long_name",
1659 "[first_long_name, second_long_name]: [i32]",
1660 "(first_long_name + second_long_name,)",
1661 "[(first_long_name, second_long_name), (third_long_name, fourth_long_name)]",
1662 "if (Record { value: first_long_name }).value { 0xffi32 } else { 1i32 }",
1663 "first_long_name /* keep\n block */ + second_long_name",
1664 "call(first_long_name, // keep line\n second_long_name)",
1665 "first_long_name + // first\n // second\n second_long_name",
1666 ] {
1667 let expr = parse(source);
1668 let text = format_expr_with_layout(&expr, source, 0, 0, 40, 0);
1669 let parsed = parse(&text);
1670 assert_eq!(
1671 format_expr_with_layout(&parsed, &text, 0, 0, 40, 0),
1672 text,
1673 "{source}"
1674 );
1675 assert_eq!(
1676 format_expr_with_layout(&parsed, &text, 0, 0, 10_000, 0),
1677 format_expr_with_layout(&expr, source, 0, 0, 10_000, 0),
1678 "{source} -> {text}"
1679 );
1680 }
1681 for (source, expected) in [
1682 ("-(10 + 3) as i32", -13),
1683 ("10 - (3 - 1)", 8),
1684 ("(|value: i32| value + 5)(7)", 12),
1685 ("(1 + 2,).0", 3),
1686 ("if true && false { 1 / 0 } else { 42 }", 42),
1687 ] {
1688 let text = format_expr_with_layout(&parse(source), source, 0, 0, 12, 0);
1689 let mut segment = crate::CELParser::new(OpLookup::new())
1690 .parse_str(&text)
1691 .unwrap();
1692 assert_eq!(
1693 segment.call0::<i32>().unwrap(),
1694 expected,
1695 "{source} -> {text}"
1696 );
1697 }
1698 }
1699
1700 #[test]
1702 fn source_index_preserves_character_boundaries() {
1703 let source = Source::new("é\nβ\n");
1704 assert_eq!(
1705 source.byte(proc_macro2::LineColumn { line: 1, column: 1 }),
1706 2
1707 );
1708 assert_eq!(
1709 source.byte(proc_macro2::LineColumn { line: 2, column: 1 }),
1710 5
1711 );
1712 assert_eq!(
1713 source.byte(proc_macro2::LineColumn { line: 3, column: 0 }),
1714 6
1715 );
1716 assert_eq!(
1717 Source::new("").byte(proc_macro2::LineColumn { line: 1, column: 0 }),
1718 0
1719 );
1720 }
1721
1722 fn parse(source: &str) -> Expr {
1724 Parser::<AstContext>::new(OpLookup::new())
1725 .parse_str_ast(source)
1726 .unwrap()
1727 }
1728
1729 fn fmt(source: &str) -> String {
1731 format_expr(&parse(source), source, 0)
1732 }
1733
1734 #[test]
1735 fn additive_and_multiplicative_reprint_without_extra_parens() {
1736 assert_eq!(fmt("1i32 + 2i32 * 3i32"), "1i32 + 2i32 * 3i32");
1737 }
1738
1739 #[test]
1740 fn explicit_grouping_that_changes_precedence_keeps_its_parens() {
1741 assert_eq!(fmt("(1i32 + 2i32) * 3i32"), "(1i32 + 2i32) * 3i32");
1742 }
1743
1744 #[test]
1745 fn left_associative_chain_at_the_same_precedence_has_no_parens() {
1746 assert_eq!(fmt("1i32 - 2i32 - 3i32"), "1i32 - 2i32 - 3i32");
1747 }
1748
1749 #[test]
1750 fn a_right_leaning_tree_at_the_same_precedence_needs_parens() {
1751 fn ident(name: &str) -> Expr {
1756 Expr::Ident {
1757 name: name.to_string(),
1758 span: point(),
1759 }
1760 }
1761 fn point() -> crate::ExprSpan {
1762 crate::ExprSpan {
1763 start: proc_macro2::Span::call_site(),
1764 end: proc_macro2::Span::call_site(),
1765 }
1766 }
1767 let expr = Expr::Op {
1768 name: "-".to_string(),
1769 operands: vec![
1770 ident("a"),
1771 Expr::Op {
1772 name: "-".to_string(),
1773 operands: vec![ident("b"), ident("c")],
1774 span: point(),
1775 },
1776 ],
1777 span: point(),
1778 };
1779 assert_eq!(format_expr(&expr, "", 0), "a - (b - c)");
1780 }
1781
1782 #[test]
1783 fn nested_comparison_needs_parens_on_both_sides() {
1784 fn ident(name: &str) -> Expr {
1788 Expr::Ident {
1789 name: name.to_string(),
1790 span: crate::ExprSpan {
1791 start: proc_macro2::Span::call_site(),
1792 end: proc_macro2::Span::call_site(),
1793 },
1794 }
1795 }
1796 let inner = Expr::Op {
1797 name: "==".to_string(),
1798 operands: vec![ident("a"), ident("b")],
1799 span: crate::ExprSpan {
1800 start: proc_macro2::Span::call_site(),
1801 end: proc_macro2::Span::call_site(),
1802 },
1803 };
1804 let expr = Expr::Op {
1805 name: "==".to_string(),
1806 operands: vec![inner, ident("c")],
1807 span: crate::ExprSpan {
1808 start: proc_macro2::Span::call_site(),
1809 end: proc_macro2::Span::call_site(),
1810 },
1811 };
1812 assert_eq!(format_expr(&expr, "", 0), "(a == b) == c");
1813 }
1814
1815 #[test]
1816 fn literal_notation_is_preserved_exactly() {
1817 assert_eq!(fmt("1920.0"), "1920.0");
1818 assert_eq!(fmt("1920.0f64"), "1920.0f64");
1819 assert_eq!(fmt("1i32"), "1i32");
1820 }
1821
1822 #[test]
1824 fn integer_form_float_retained_syntax_preserves_source() {
1825 for (source, is_f32, expected) in [
1826 ("1f64", false, 1.0),
1827 ("1_f64", false, 1.0),
1828 ("0f64", false, 0.0),
1829 ("1f32", true, 1.0),
1830 ] {
1831 let expr = parse(source);
1832 let Expr::Literal { value, span } = &expr else {
1833 panic!("expected literal for {source}");
1834 };
1835 match value {
1836 crate::Literal::F32(value) if is_f32 => assert_eq!(*value as f64, expected),
1837 crate::Literal::F64(value) if !is_f32 => assert_eq!(*value, expected),
1838 other => panic!("wrong literal type for {source}: {other:?}"),
1839 }
1840 assert_eq!(span.start.source_text().as_deref(), Some(source));
1841 assert_eq!(span.end.source_text().as_deref(), Some(source));
1842 assert_eq!(format_expr(&expr, source, 0), source);
1843 }
1844 }
1845
1846 #[test]
1847 fn unary_minus_of_a_binary_expression_needs_parens() {
1848 assert_eq!(fmt("-(1i32 + 2i32)"), "-(1i32 + 2i32)");
1849 }
1850
1851 #[test]
1852 fn double_unary_minus_keeps_a_separating_space() {
1853 assert_eq!(fmt("- -1i32"), "- -1i32");
1854 }
1855
1856 #[test]
1857 fn cast_chain_reprints_without_extra_parens() {
1858 assert_eq!(fmt("x as i32 as f64"), "x as i32 as f64");
1859 }
1860
1861 #[test]
1862 fn unary_minus_before_a_cast_needs_no_parens() {
1863 assert_eq!(fmt("-x as f64"), "-x as f64");
1866 }
1867
1868 #[test]
1869 fn explicit_grouping_before_a_cast_keeps_its_parens() {
1870 assert_eq!(fmt("(a + b) as i32"), "(a + b) as i32");
1873 }
1874
1875 #[test]
1876 fn cast_operand_of_an_additive_expression_needs_no_parens() {
1877 assert_eq!(fmt("a + b as i32"), "a + b as i32");
1880 }
1881
1882 #[test]
1883 fn explicit_grouping_around_a_cast_before_multiplicative_is_redundant_and_dropped() {
1884 assert_eq!(fmt("(x as i32) * y"), "x as i32 * y");
1888 }
1889
1890 #[test]
1891 fn one_tuple_keeps_its_trailing_comma() {
1892 assert_eq!(fmt("(1i32,)"), "(1i32,)");
1893 }
1894
1895 #[test]
1896 fn multi_element_tuple_has_no_trailing_comma() {
1897 assert_eq!(fmt("(1i32, 2i32)"), "(1i32, 2i32)");
1898 }
1899
1900 #[test]
1901 fn arrays_format_with_brackets_and_normalized_commas() {
1902 assert_eq!(fmt("[1i32,2i32]"), "[1i32, 2i32]");
1903 assert_eq!(fmt("[[1i32], [2i32]]"), "[[1i32], [2i32]]");
1904 }
1905
1906 #[test]
1907 fn typed_arrays_format_with_a_type_ascription() {
1908 assert_eq!(fmt("[1i32,2i32]:[i32]"), "[1i32, 2i32]: [i32]");
1909 assert_eq!(fmt("[]:[[i32]]"), "[]: [[i32]]");
1910 }
1911
1912 #[test]
1913 fn format_array_annotation_with_a_generic_builtin_element_type() {
1914 let source = "[]: [RangeInclusive(f64)]";
1915 let expr = parse(source);
1916 let formatted = format_expr(&expr, source, 0);
1917 assert_eq!(formatted, source);
1918 }
1919
1920 #[test]
1921 fn array_comments_remain_in_source_order() {
1922 assert_eq!(
1923 fmt("[1i32 /* first */, /* second */ 2i32]"),
1924 "[1i32 /* first */, /* second */ 2i32]"
1925 );
1926 }
1927
1928 #[test]
1929 fn comments_in_a_call_argument_list_are_preserved() {
1930 assert_eq!(
1931 fmt("f(/* a */ 1i32, /* b */ 2i32)"),
1932 "f(/* a */ 1i32, /* b */ 2i32)"
1933 );
1934 }
1935
1936 #[test]
1937 fn a_comment_before_a_closing_call_paren_is_preserved() {
1938 assert_eq!(fmt("f(1i32 /* end */)"), "f(1i32 /* end */)");
1939 }
1940
1941 #[test]
1942 fn comments_in_a_tuple_are_preserved() {
1943 assert_eq!(fmt("(1i32, /* mid */ 2i32)"), "(1i32, /* mid */ 2i32)");
1944 }
1945
1946 #[test]
1947 fn comment_free_calls_and_tuples_are_unchanged() {
1948 assert_eq!(fmt("f(1i32, 2i32)"), "f(1i32, 2i32)");
1949 assert_eq!(fmt("(1i32, 2i32)"), "(1i32, 2i32)");
1950 assert_eq!(fmt("(1i32,)"), "(1i32,)");
1951 assert_eq!(fmt("(1i32, 2i32).1"), "(1i32, 2i32).1");
1952 }
1953
1954 #[test]
1955 fn if_without_else_omits_the_else_clause() {
1956 assert_eq!(fmt("if true { 1i32 }"), "if true { 1i32 }");
1957 }
1958
1959 #[test]
1960 fn if_else_reprints_both_branches() {
1961 assert_eq!(
1962 fmt("if true { 1i32 } else { 2i32 }"),
1963 "if true { 1i32 } else { 2i32 }"
1964 );
1965 }
1966
1967 #[test]
1968 fn else_if_chain_has_no_braces_around_the_nested_if() {
1969 let source = "if true { 1i32 } else if false { 2i32 } else { 3i32 }";
1970 assert_eq!(fmt(source), source);
1971 }
1972
1973 #[test]
1974 fn a_comment_after_if_condition_is_preserved() {
1975 assert_eq!(fmt("if a /* c */ { 1i32 }"), "if a /* c */ { 1i32 }");
1976 }
1977
1978 #[test]
1979 fn a_comment_before_else_is_preserved() {
1980 assert_eq!(
1981 fmt("if a { 1i32 } /* e */ else { 2i32 }"),
1982 "if a { 1i32 } /* e */ else { 2i32 }"
1983 );
1984 }
1985
1986 #[test]
1987 fn logical_or_and_and_are_not_desugared_and_need_no_extra_parens() {
1988 assert_eq!(fmt("a || b && c"), "a || b && c");
1989 }
1990
1991 #[test]
1992 fn a_comment_around_a_logical_operator_is_preserved() {
1993 assert_eq!(fmt("a /* x */ || b"), "a /* x */ || b");
1994 assert_eq!(fmt("a && /* y */ b"), "a && /* y */ b");
1995 }
1996
1997 #[test]
1998 fn format_is_idempotent_through_a_reparse() {
1999 let source = "(1i32 + 2i32) * 3i32 - -4i32";
2000 let once = fmt(source);
2001 let twice = format_expr(&parse(&once), &once, 0);
2002 assert_eq!(once, twice);
2003 }
2004
2005 #[test]
2006 fn typed_array_annotation_round_trips_through_reparse() {
2007 let source = "[1.0, 42.5]: [f64]";
2008 let once = fmt(source);
2009 let twice = format_expr(&parse(&once), &once, 0);
2010 assert_eq!(once, twice);
2011 }
2012
2013 #[test]
2014 fn closure_with_one_param_reprints_with_its_type() {
2015 assert_eq!(fmt("|x: i32| x + 1i32"), "|x: i32| x + 1i32");
2016 }
2017
2018 #[test]
2019 fn closure_with_no_params_reprints_with_double_pipe() {
2020 assert_eq!(fmt("|| 1i32"), "|| 1i32");
2021 }
2022
2023 #[test]
2024 fn closure_with_multiple_params_joins_them_with_commas() {
2025 assert_eq!(fmt("|x: i32, y: i32| x + y"), "|x: i32, y: i32| x + y");
2026 }
2027
2028 #[test]
2029 fn closure_with_a_tuple_typed_param_reprints_the_tuple_type() {
2030 assert_eq!(fmt("|x: (i32, f64)| x.0"), "|x: (i32, f64)| x.0");
2031 }
2032
2033 #[test]
2034 fn a_comment_before_a_closure_body_is_preserved() {
2035 assert_eq!(
2036 fmt("|x: i32| /* b */ x + 1i32"),
2037 "|x: i32| /* b */ x + 1i32"
2038 );
2039 }
2040
2041 #[test]
2042 fn a_line_comment_before_a_closure_body_wraps_the_expression() {
2043 let source = "|x: i32| // c\n x + 1i32";
2047 let once = fmt(source);
2048 assert!(once.contains("// c"), "comment must survive: {once:?}");
2049 assert!(once.contains("x + 1i32"), "body must survive: {once:?}");
2050 let twice = format_expr(&parse(&once), &once, 0);
2051 assert_eq!(once, twice, "formatting must be idempotent");
2052 }
2053
2054 #[test]
2055 fn range_inclusive_reprints_without_spaces() {
2056 assert_eq!(fmt("1i32..=5i32"), "1i32..=5i32");
2057 }
2058
2059 #[test]
2060 fn range_reprints_without_spaces() {
2061 assert_eq!(fmt("1i32..5i32"), "1i32..5i32");
2062 }
2063
2064 #[test]
2065 fn range_from_reprints_without_spaces() {
2066 assert_eq!(fmt("1i32.."), "1i32..");
2067 }
2068
2069 #[test]
2070 fn range_to_reprints_without_spaces() {
2071 assert_eq!(fmt("..5i32"), "..5i32");
2072 }
2073
2074 #[test]
2075 fn range_to_inclusive_reprints_without_spaces() {
2076 assert_eq!(fmt("..=5i32"), "..=5i32");
2077 }
2078
2079 #[test]
2080 fn range_full_reprints_as_two_dots() {
2081 assert_eq!(fmt(".."), "..");
2082 }
2083
2084 #[test]
2085 fn range_endpoints_that_are_comparisons_need_no_parens() {
2086 assert_eq!(fmt("a == b..c == d"), "a == b..c == d");
2090 }
2091
2092 #[test]
2093 fn range_endpoints_that_are_arithmetic_need_no_parens() {
2094 assert_eq!(fmt("1i32 + 2i32..3i32 * 4i32"), "1i32 + 2i32..3i32 * 4i32");
2097 }
2098
2099 #[test]
2100 fn emit_gap_around_a_plain_operator_uses_single_spaces() {
2101 let pieces = vec![GapPiece::Punct("+")];
2102 assert_eq!(emit_gap(&pieces, Spacing::Around, 0), " + ");
2103 }
2104
2105 #[test]
2106 fn emit_gap_none_spacing_glues_a_range_operator() {
2107 let pieces = vec![GapPiece::Punct("..")];
2108 assert_eq!(emit_gap(&pieces, Spacing::None, 0), "..");
2109 }
2110
2111 #[test]
2112 fn emit_gap_comma_after_puts_one_trailing_space() {
2113 let pieces = vec![GapPiece::Punct(",")];
2114 assert_eq!(emit_gap(&pieces, Spacing::CommaAfter, 0), ", ");
2115 }
2116
2117 #[test]
2118 fn emit_gap_inlines_a_block_comment_before_an_operator() {
2119 let pieces = vec![
2120 GapPiece::Comment(Comment::Block("a".to_string())),
2121 GapPiece::Punct("+"),
2122 ];
2123 assert_eq!(emit_gap(&pieces, Spacing::Around, 0), " /* a */ + ");
2124 }
2125
2126 #[test]
2127 fn emit_gap_inlines_a_block_comment_after_an_operator() {
2128 let pieces = vec![
2129 GapPiece::Punct("+"),
2130 GapPiece::Comment(Comment::Block("b".to_string())),
2131 ];
2132 assert_eq!(emit_gap(&pieces, Spacing::Around, 0), " + /* b */ ");
2133 }
2134
2135 #[test]
2136 fn emit_gap_wraps_after_a_line_comment_to_the_continuation_indent() {
2137 let pieces = vec![
2138 GapPiece::Punct("+"),
2139 GapPiece::Comment(Comment::Line("why".to_string())),
2140 ];
2141 assert_eq!(emit_gap(&pieces, Spacing::Around, 0), " + // why\n ");
2144 }
2145
2146 #[test]
2147 fn emit_gap_comma_after_a_line_comment_keeps_the_full_continuation_indent() {
2148 let pieces = vec![
2152 GapPiece::Comment(Comment::Line("why".to_string())),
2153 GapPiece::Punct(","),
2154 ];
2155 assert_eq!(emit_gap(&pieces, Spacing::CommaAfter, 0), " // why\n , ");
2156 }
2157
2158 #[test]
2159 fn a_block_comment_before_a_binary_operator_is_preserved() {
2160 let source = "1i32 /* a */ + 2i32";
2161 assert_eq!(fmt(source), "1i32 /* a */ + 2i32");
2162 }
2163
2164 #[test]
2165 fn a_block_comment_after_a_binary_operator_is_preserved() {
2166 let source = "1i32 + /* b */ 2i32";
2167 assert_eq!(fmt(source), "1i32 + /* b */ 2i32");
2168 }
2169
2170 #[test]
2171 fn comments_on_both_sides_of_a_binary_operator_are_preserved() {
2172 let source = "1i32 /* a */ + /* b */ 2i32";
2173 assert_eq!(fmt(source), "1i32 /* a */ + /* b */ 2i32");
2174 }
2175
2176 #[test]
2177 fn a_comment_after_unary_minus_is_preserved() {
2178 assert_eq!(fmt("- /* neg */ 1i32"), "- /* neg */ 1i32");
2179 }
2180
2181 #[test]
2182 fn a_comment_around_a_cast_operator_is_preserved() {
2183 assert_eq!(fmt("x /* c */ as i32"), "x /* c */ as i32");
2184 }
2185
2186 #[test]
2187 fn a_comment_inside_a_range_is_preserved() {
2188 assert_eq!(fmt("1i32 /* r */ ..5i32"), "1i32 /* r */ ..5i32");
2189 }
2190
2191 #[test]
2192 fn comment_free_unary_cast_and_range_are_unchanged() {
2193 assert_eq!(fmt("-1i32"), "-1i32");
2194 assert_eq!(fmt("x as i32"), "x as i32");
2195 assert_eq!(fmt("1i32..5i32"), "1i32..5i32");
2196 }
2197
2198 #[test]
2199 fn a_line_comment_after_a_cast_operator_wraps_the_expression() {
2200 let source = "x as // c\n i32";
2204 let once = fmt(source);
2205 assert!(once.contains("// c"), "comment must survive: {once:?}");
2206 assert!(once.contains("i32"), "type name must survive: {once:?}");
2207 let twice = format_expr(&parse(&once), &once, 0);
2208 assert_eq!(once, twice, "formatting must be idempotent");
2209 }
2210
2211 #[test]
2212 fn issue_201_line_comment_inside_an_expression_round_trips() {
2213 let source = "1i32 +\n // why 2\n 2i32";
2215 let once = fmt(source);
2216 assert_eq!(once, "1i32 + // why 2\n 2i32");
2217 assert!(once.contains("// why 2"), "comment must survive: {once:?}");
2218 let twice = format_expr(&parse(&once), &once, 0);
2219 assert_eq!(once, twice, "formatting must be idempotent");
2220 }
2221
2222 #[test]
2223 fn the_full_inline_comment_example_round_trips() {
2224 let source = "/* p */ 1i32 /* q */ + // hello\n2i32 /* r */";
2232 let once = fmt(source);
2233 assert!(
2234 once.contains("/* q */") && once.contains("// hello"),
2235 "the in-scope operand/operator comments survive: {once:?}"
2236 );
2237 let twice = format_expr(&parse(&once), &once, 0);
2238 assert_eq!(once, twice);
2239 }
2240}