Skip to main content

cel_parser/
fmt.rs

1//! Pretty-prints a [`crate::Expr`] tree back to CEL source text: precedence-aware
2//! parenthesization (added only where required, not exhaustively), single-space-around-operator
3//! normalization, and a 100-column layout target. Short expressions stay inline; longer lists,
4//! records and closure bodies nest by four spaces, with leading binary continuation operators.
5//! Unbreakable tokens and comments may exceed the target. Literal leaves are re-emitted via
6//! [`proc_macro2::Span::source_text`] rather than synthesized from [`crate::Literal`], so exact
7//! original notation (`1920.0` vs `1920.0f64`, a byte literal's spelling) round-trips.
8//!
9//! Typed arrays round-trip with their postfix `: Type` ascriptions, including recursive array
10//! types such as `[]: [[i32]]` and reusable tuple syntax such as `[]: [(i32, f64)]`. The
11//! formatter preserves complete tuple, array, and `Fn((A,), R)` callable annotations,
12//! including the comma that distinguishes a singleton tuple from grouping.
13
14use crate::ast::{Expr, LogicalOp};
15use crate::trivia::{Comment, GapPiece, scan_gap, take_block_comment};
16
17/// Returns unary precedence for negative integer literals and primary precedence otherwise.
18fn 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
35/// Owns one character-position index for a borrowed source.
36///
37/// Line starts index a shared character-to-byte boundary table.
38struct Source<'a> {
39    text: &'a str,
40    lines: Vec<usize>,
41    bytes: Vec<usize>,
42}
43
44impl<'a> Source<'a> {
45    /// Indexes every source position once in O(n) time and space for n source bytes.
46    fn new(text: &'a str) -> Self {
47        let mut lines = vec![0];
48        let mut bytes = Vec::new();
49        // Record each character boundary in its owning line.
50        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    /// Returns the byte boundary for a position in this source.
61    ///
62    /// - Precondition: `position` belongs to this source.
63    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    /// Borrows the source between two positions, or an empty slice for synthetic source.
78    ///
79    /// - Precondition: nonempty source owns both positions.
80    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
88/// An immutable Wadler document; construction never lays out a child expression.
89type Doc = pretty::RcDoc<'static, ()>;
90
91/// Preserves a lexical token's internal newlines and indentation independently of layout nesting.
92///
93/// - Complexity: O(n) in the token's text length.
94fn 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
109/// Lifts recovered trivia into a document with mandatory line-comment boundaries.
110///
111/// - Complexity: O(n) in the recovered text length.
112fn trivia_doc(text: String) -> Doc {
113    trivia_doc_at(text, 4)
114}
115
116/// Lifts recovered trivia with continuation nesting supplied by its grammar owner.
117///
118/// - Complexity: O(n) in the recovered text length.
119fn 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
133/// Builds a gap document, with a soft boundary before binary operators or after commas.
134///
135/// - Complexity: O(n) in the gap's text length.
136fn 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
206/// Builds an indented leading-operator continuation without nesting the left operand.
207///
208/// - Complexity: O(n) in the gap's text length.
209fn 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
214/// Ends an opening-brace gap with a soft boundary, preserving mandatory comment boundaries.
215///
216/// `trim_start` removes spacing already supplied by the preceding closing-brace boundary.
217///
218/// - Complexity: O(n) in the recovered gap's text length.
219fn 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/// Binding-strength level, loosest first, mirroring `lib.rs`'s grammar chain from
230/// `range_expression` (via `expression = range_expression`) through `primary_expression`.
231#[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    /// The next level up (strictly tighter-binding than `self`).
251    fn tighter(self) -> Level {
252        Level(self.0 + 1)
253    }
254}
255
256/// 4 spaces per nesting level (mirrors `adam-lang::fmt::indent`).
257///
258/// - Complexity: O(depth).
259fn indent(depth: usize) -> String {
260    "    ".repeat(depth)
261}
262
263/// How a gap's expected `Punct` tokens are spaced against their operands.
264#[derive(Clone, Copy)]
265enum Spacing {
266    /// A single space on each side of the token: `a + b`.
267    Around,
268    /// No surrounding spaces: `a..b`, or a bare delimiter.
269    None,
270    /// The token then one space: `a, b`.
271    CommaAfter,
272}
273
274/// Renders the pieces of one scanned gap into the text that goes *between* two already-rendered
275/// operands. A `Comment::Block` is inlined space-separated; a `Comment::Line` ends its line and
276/// resumes at `indent(depth + 1)` (the wrap continuation), since a `//` comment runs to
277/// end-of-line. A `Punct` is spaced per `spacing`.
278///
279/// - Postcondition: the returned string starts and ends exactly as `spacing` dictates for the
280///   comment-free case (e.g. `Spacing::Around` with a lone `Punct` returns `" + "`), so a
281///   comment-free gap reprints identically to the pre-`scan_gap` formatter.
282///
283/// - Complexity: O(n) in `pieces.len()` plus their text lengths.
284fn 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                        // Skip the leading space only when the previous piece already left one
293                        // (a block comment's trailing `" */ "`, or a line comment's continuation
294                        // indent) — otherwise this token opens the gap and needs its own.
295                        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                        // Unlike `Around`, a comma never gets a leading space of its own -- it
304                        // glues directly to whatever precedes it, whether that's the element text
305                        // itself (the comment-free case) or a comment's trailing `" */ "` (a block
306                        // comment written between the element and its `,`, e.g.
307                        // `1i32 /* c */, 2i32`). A line comment's trailing continuation *indent*
308                        // is different: that space is meaningful (it's `indent(depth + 1)`, not
309                        // filler), so it must be left alone -- only the incidental single-space
310                        // filler a block comment or a prior `Around` punct leaves behind is
311                        // trimmed.
312                        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                // Separate from whatever came before (or, when this is the first piece, from the
322                // already-rendered operand this gap is appended to) with exactly one space,
323                // unless the previous piece already left a trailing space.
324                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                // A `//` comment runs to end of line, so anything after it must start on the next
333                // line; drop any trailing space this gap had accumulated before appending it.
334                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
353/// Returns the binding-strength level of a binary (two-operand) operator.
354///
355/// - Precondition: `name` is one of the binary operator tokens `lib.rs`'s grammar recognizes,
356///   excluding `"range"`/`"range_inclusive"` — those, and every other range-family operator
357///   (`"range_from"`/`"range_to"`/`"range_to_inclusive"`/`"range_full"`), are rendered by their
358///   own dedicated [`render`] match arms before any operator ever reaches this function, since
359///   their printed form (`x..y`, no surrounding spaces) doesn't fit this function's shared
360///   `"{lhs} {name} {rhs}"` shape the way every other binary operator here does.
361fn 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
374/// Re-emits a literal's exact original text via its span, falling back to an empty string when
375/// none is recoverable (spans built without a live source file — never a real parse; see the
376/// module doc).
377fn render_literal(span: crate::ExprSpan) -> String {
378    span.start.source_text().unwrap_or_default()
379}
380
381/// Scans the source gap between two adjacent AST positions for comments interleaved with
382/// `expected` tokens. Returns just the expected tokens (no comments) when `source` is empty (a
383/// hand-built `Expr`), so a source-less format still works.
384///
385/// - Precondition: when `source` is non-empty, it is the exact text `expr` was parsed from —
386///   `prev_end`/`next_start` must resolve within it.
387///
388/// - Complexity: O(g + e) time and space for g gap bytes and e expected-token bytes.
389fn 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
398/// Recovers member-dot comments across closing receiver groups omitted from the AST.
399///
400/// - Precondition: non-empty `source` is the receiver's original parsed text, and both spans
401///   resolve within it.
402/// - Postcondition: grouping delimiters are omitted; comments and the dot retain source order.
403/// - Complexity: O(g) time and space for g gap bytes.
404fn 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
412/// Renders a postfix base, retaining leading group comments inside one owning group.
413///
414/// - Precondition: `start` is the postfix node's original start in `source`, or source is empty.
415/// - Postcondition: the base's leading comments appear once, before its first rendered token.
416/// - Complexity: O(n + g) document space for n base nodes and g recovered gap bytes.
417fn 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
436/// Renders a comma-separated element list with per-gap comment recovery: the gap before the first
437/// element (after `bounds.0`, the opening delimiter's position, e.g. a `(` or `[`), each
438/// inter-element `,` gap, and the gap after the last element (before `bounds.1`, the position
439/// right past the closing delimiter, e.g. a `)` or `]`). `delims` is `(open, close)`, the
440/// delimiter tokens. When `trailing_comma` is set (a 1-tuple), a `,` is emitted after the sole
441/// element.
442///
443/// `bounds` holds raw [`proc_macro2::LineColumn`] positions (not `Span`s, unlike [`gap_between`]'s
444/// `prev_end`/`next_start`) because `Expr::Apply`'s, `Expr::Tuple`'s, and `Expr::Array`'s own
445/// recorded delimiter span covers the *whole* `(...)`/`[...]` group rather than a single
446/// delimiter character: `AstContext::apply_op`'s `"()"` arm, `is_tuple_or_group`, and
447/// `is_array_expression` all capture `self.last_span` from a `Token::CloseDelim`, and
448/// `lex_lexer`'s flattening gives every `OpenDelim`/`CloseDelim` the *enclosing `Group`'s* span
449/// (see `LexLexer::next`), so a group span's `.start()` lands on the opening delimiter and its
450/// `.end()` lands just past the closing delimiter regardless of which delimiter "produced" it.
451/// Resolving which of `.start()`/`.end()` is the right boundary is the caller's job (it knows
452/// whether it's holding a whole-group span or an ordinary leaf span, e.g. a callee's own end);
453/// this helper just consumes the two positions it's given.
454///
455/// - Complexity: O(n) in the number of elements plus their gap lengths.
456fn 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    // Scans the raw gap between two already-resolved positions, mirroring `gap_between` but
467    // taking `LineColumn`s directly instead of deriving them from a fixed `prev_end.end()` /
468    // `next_start.start()` pairing (which doesn't fit `open_pos`/`close_pos`; see above).
469    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        // Whole gap between the delimiters: `open`, comments, `close`.
476        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    // Opening delimiter + any comment before the first element. `emit_gap`'s comment rendering
481    // always pads a leading space before a comment that opens a gap, which is right when the gap
482    // follows an already-rendered operand (`x /* c */ as i32`) but wrong right after a delimiter
483    // -- `glue_after_open` corrects it back to `f(/* a */ 1i32)`.
484    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    // Any comment before the closing delimiter, then the delimiter; symmetric to the opening gap
506    // above (`glue_before_close` drops the trailing space before `)` a comment would otherwise
507    // leave: `f(1i32 /* end */)`, not `f(1i32 /* end */ )`).
508    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
522/// Strips the one space [`emit_gap`] pads before a comment that immediately opens a gap, when
523/// that gap begins right after `open` — appropriate between an operand and an operator, but not
524/// right after an opening delimiter, which glues directly to a following comment.
525fn 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
532/// Symmetric to [`glue_after_open`]: strips the one space [`emit_gap`] pads after a comment that
533/// immediately precedes `close`, so a trailing comment glues directly to the closing delimiter.
534fn glue_before_close(gap: &str, close: &'static str) -> String {
535    if let Some((_, last_line)) = gap.rsplit_once('\n') {
536        // `gap` wrapped after a `//` comment; `last_line` is the continuation line `emit_gap`
537        // started with its own indent. When that line holds nothing but indentation before
538        // `close` (no block comment glued onto the same line), those spaces are the
539        // continuation's own indent, not `emit_gap`'s one-space comment padding — leave them
540        // alone instead of stripping one as if it were the padding space.
541        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
553/// Returns the `'static` source spelling of a binary operator name, for `scan_gap`'s expected-token
554/// list (which needs `&'static str`). The spelling equals `name` for every binary operator this
555/// formatter's `binary_op_level` accepts.
556fn 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
578/// Returns the `'static` source spelling of a unary operator name (`"-"` or `"!"`).
579fn 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
587/// Renders one unresolved array-annotation type expression.
588///
589/// Named leaves are emitted verbatim, so built-in names and host-registered custom names format
590/// identically. Recursive arrays keep their bracket nesting, and tuple type expressions keep the
591/// same reusable syntax the parser accepts for future typed CEL surfaces.
592///
593/// - Complexity: O(t + n + b) time for t inspected type-source bytes, n type nodes and
594///   b emitted bytes; O(b) output and O(d) auxiliary stack space for type depth d.
595fn 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
606/// Appends canonical type syntax without materializing intermediate child strings.
607///
608/// - Complexity: O(n + b) time and O(d) stack space for n nodes, b emitted bytes and depth d.
609fn 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
628/// Appends parenthesized type arguments or tuple elements with committed separators.
629///
630/// - Complexity: O(n + b) time and O(d) stack space for n descendant nodes, b bytes and depth d.
631fn write_type_list(elements: &[crate::TypeExpr], output: &mut String, tuple: bool) {
632    output.push('(');
633    // Emit each child directly into the shared output.
634    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
646/// Builds `expr`'s document alongside its binding-strength level, so the
647/// caller ([`format_at`]) can decide whether the context it's being placed in requires parens.
648///
649/// `source` is the text `expr` was parsed from (or `""` for a hand-built `Expr`).
650/// Children contribute documents, never independently formatted strings.
651///
652/// - Complexity: O(v + g + b) time and space for v node visits, g inspected source-slice bytes
653///   and b document-text bytes.
654fn 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            // Range's own endpoints are always `or_expression`s (never chained further range
744            // expressions — see `is_range_expression`'s doc comment), so an operand only needs
745            // rendering strictly tighter than Range itself, the same non-chaining treatment
746            // `Level::COMPARISON` gets below.
747            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                    // `span.start` is the `".."` token's own span; a `gap_between` call always
755                    // scans strictly *after* its `prev_end` argument's end, so `".."` itself can
756                    // never appear inside the scanned gap here (unlike the operand-then-operator
757                    // arms below, where the operator genuinely sits inside the scanned range) —
758                    // it's rendered directly instead, and only a comment is scanned for.
759                    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            // Same reasoning as the `range_to`/`range_to_inclusive` arm above: the operator
782            // precedes the operand, so it can never appear inside the scanned gap; only a
783            // comment is scanned for, and the operator is rendered directly.
784            let pieces = gap_between(source, span.start, operands[0].span().start, &[]);
785            // Preserve the existing "- -1" disambiguating space when there are no comments.
786            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            // Same non-chaining reasoning as the arity-1 range arm above: both endpoints render
807            // strictly tighter than Range.
808            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            // Comparison can't chain — the grammar parses at most one per comparison_expression —
836            // so both operands must be strictly tighter than Comparison itself, unlike the other,
837            // left-associative (chaining) binary levels below, where only the right operand does.
838            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            // The operator token itself has no span; it lives in the gap between the two operands.
846            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            // Left-associative, like multiplicative/additive: the operand only needs to be at
861            // least as tight as Cast itself, so a chain like `x as i32 as f64` reprints without
862            // extra parens.
863            let expr_s = format_at(expr, source, depth, Level::CAST);
864            // The type name has no span of its own, so the gap scanned here runs from the operand's
865            // end through the whole cast node's end (which includes both `as` and the type name);
866            // only `"as"` is expected inside it, and the type name is appended afterward.
867            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            // Without parentheses a bare member followed by `()` becomes direct dispatch,
874            // rather than an ordinary call of the member's result.
875            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            // The call's end span covers the complete argument group, so neither boundary
881            // includes closing callee groups omitted from the AST.
882            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            // `span.start` and `span.end` are both the same whole-group span here (see
928            // `emit_list`'s doc comment): `.start()` is the position of `(`, `.end()` the
929            // position right after `)`.
930            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            // `span.start` is the `[` token. The closing `]` sits either at `span.end` for an
947            // unannotated array or immediately before `annotation_span` when a `: Type`
948            // ascription follows. Array literals never take a trailing comma (the grammar is
949            // LL(1) and rejects one outright), unlike the one-tuple special case above.
950            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            // `if` <cond> `{` <then_branch> `}` [ `else` ( `{` <else_branch> `}` | <else-if> ) ].
995            // None of `if`/`{`/`}`/`else` carry their own span (each is a fixed keyword/delimiter
996            // consumed structurally by the parser, never recorded as its own node), so every gap
997            // between two real spans is scanned for its expected fixed token(s) alongside any
998            // interleaved comment. `Spacing::Around` is used throughout (rather than `None`) so
999            // that a gap holding more than one fixed token (`"}"`, `"else"`, and — for a braced
1000            // else — `"{"`) still gets a single space between each token and the next, matching
1001            // the pre-`scan_gap` literal `" } else { "` spacing exactly in the comment-free case.
1002            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            // Only the very first gap is `trim_start`'d: it opens the whole node's text, so any
1018            // leading space `Spacing::Around` would otherwise add before `"if"` must be dropped.
1019            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                    // No `else`: the gap between the then-branch and the node's own end holds
1029                    // just the closing `}` (plus any comment before it).
1030                    let close_gap = gap_between(source, then_branch.span().end, span.end, &["}"]);
1031                    // `trim_end`'d because this is the node's last piece of text: a trailing
1032                    // space here would otherwise survive into the caller's output (or, wrapped in
1033                    // parens by `format_at`, land right before the close-paren).
1034                    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                    // An `else if` chain has no braces of its own around the nested `if`; a plain
1041                    // `else` block does.
1042                    let expected: &[&'static str] = if is_chain {
1043                        &["}", "else"]
1044                    } else {
1045                        &["}", "else", "{"]
1046                    };
1047                    // One scan across the whole then-branch-to-else-branch gap (rather than one
1048                    // scan per token) so a comment sitting anywhere in it -- before `}`, between
1049                    // `}` and `else`, or between `else` and `{` -- is recovered in source order.
1050                    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                        // The nested `if` recurses through `render`, which lays out its own
1059                        // `if`/`{`/`}`/`else` gaps (including its own trailing `trim_end`), so
1060                        // nothing further is appended here.
1061                        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(&param.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            // A `//` comment among `comments` made `emit_gap` end `gap` with a line wrap (`\n` +
1124            // continuation indent); the body must continue right there, so `gap` is used verbatim
1125            // (already correctly spaced/wrapped) rather than trimmed — trimming would collapse the
1126            // wrap and glue the body onto the comment's own line, commenting it out.
1127            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            // Closures are complete expressions; operator and postfix operands require grouping.
1138            (
1139                header.append(sep.append(body_s).nest(4)).group(),
1140                Level::RANGE,
1141            )
1142        }
1143    }
1144}
1145
1146/// Returns the first rendered header token's position, excluding omitted operand groups.
1147///
1148/// Prefix/postfix operators and explicit expression delimiters retain their starting positions;
1149/// postfix rendering owns any leading receiver-group trivia.
1150///
1151/// - Complexity: O(h) in the visited leftmost AST path, with O(h) stack space.
1152fn 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
1165/// Returns the last rendered header token's position, excluding omitted operand/body groups.
1166///
1167/// Postfix operators and explicit expression delimiters retain their own ending positions.
1168///
1169/// - Complexity: O(h) in the visited rightmost AST path, with O(h) stack space.
1170fn 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
1181/// Recovers a field or header gap across grouping parentheses omitted from the AST.
1182///
1183/// - Precondition: positions refer to `source`, or `source` is empty.
1184/// - Postcondition: comments and expected tokens retain source order without grouping tokens.
1185/// - Complexity: O(g + e) time and space for g gap bytes and e expected-token bytes.
1186fn 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
1223/// Detects record syntax reached without an explicit expression boundary in a header.
1224///
1225/// - Complexity: O(n) in the number of visited AST nodes.
1226fn 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
1245/// Formats an embedded expression while preserving a header's brace reservation.
1246///
1247/// Groups the complete header when an otherwise unparenthesized record would be ambiguous.
1248/// Ordinary delimiters and nested branch bodies retain their normal formatting.
1249///
1250/// - Precondition: `source` is the parsed source, or empty for a hand-built AST.
1251/// - Complexity: O(s + v + g + b) construction time and space for s source bytes,
1252///   v node visits, g inspected source-slice bytes and b document-text bytes, plus pretty layout.
1253///
1254/// # Examples
1255/// ```
1256/// use cel_parser::{AstContext, ExpressionRestriction, OpLookup, Parser, format_expr_restricted};
1257/// let source = "(Point { x: 1.0 }).x";
1258/// let ast = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast(source).unwrap();
1259/// let text = format_expr_restricted(&ast, source, 0, ExpressionRestriction::NoStructLiteral);
1260/// assert_eq!(text, "(Point { x: 1.0 }.x)");
1261/// ```
1262pub 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
1277/// Builds a brace-reserving expression without independently laying out its children.
1278///
1279/// - Complexity: O(v + g + b) time and space for v node visits, g inspected source-slice bytes
1280///   and b document-text bytes.
1281fn 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
1296/// Formats a brace-reserving header and its surrounding comments within explicit boundaries.
1297///
1298/// `bounds` runs from just after the introducing keyword to just before the body brace.
1299/// Grouping parentheses omitted from the AST do not interrupt comment recovery.
1300///
1301/// - Precondition: `source` is the parsed source and `bounds` encloses `expr`, or source is empty.
1302/// - Postcondition: boundary comments appear exactly once in source order.
1303/// - Complexity: O(s + v + g + b) construction time and space for s source bytes,
1304///   v node visits, g inspected source-slice bytes and b document-text bytes, plus pretty layout.
1305///
1306/// # Examples
1307/// ```
1308/// use cel_parser::{AstContext, OpLookup, Parser, format_expr_header};
1309/// let source = "(Point { x: 1.0 }) /* keep */";
1310/// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast(source).unwrap();
1311/// let text = format_expr_header(&expr, source, 0, (
1312///     proc_macro2::LineColumn { line: 1, column: 0 },
1313///     proc_macro2::LineColumn { line: 1, column: source.len() },
1314/// ));
1315/// assert_eq!(text, "(Point { x: 1.0 }) /* keep */");
1316/// ```
1317pub 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
1326/// Formats a brace-reserving header at `column`, reserving `suffix_columns` on its last line.
1327///
1328/// The target width includes the already-written prefix and following punctuation. Continuations
1329/// nest four spaces from `depth`; unbreakable tokens and comments may exceed `width`.
1330///
1331/// - Precondition: `source` is the parsed source and `bounds` encloses `expr`, or source is empty.
1332/// - Complexity: O(s + v + g + b) construction time and space for s source bytes,
1333///   v node visits, g inspected source-slice bytes and b document-text bytes, plus pretty layout.
1334///
1335/// # Examples
1336/// ```
1337/// use cel_parser::{AstContext, OpLookup, Parser, format_expr_header_with_layout, LineColumn};
1338/// let source = "value";
1339/// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast(source).unwrap();
1340/// assert_eq!(format_expr_header_with_layout(&expr, source, 1,
1341///     (LineColumn { line: 1, column: 0 }, LineColumn { line: 1, column: 5 }),
1342///     16, 100, 2), "value");
1343/// ```
1344pub 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
1372/// Renders `expr`, wrapping it in parens if its own level is looser than `min_level` requires.
1373///
1374/// `source` and `depth` are forwarded to [`render`] unchanged; see its doc comment.
1375///
1376/// - Complexity: O(v + g + b) time and space for v node visits, g inspected source-slice bytes
1377///   and b document-text bytes.
1378fn 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
1387/// Pretty-prints `expr` back to CEL source text — see the module doc for the printing rules.
1388///
1389/// `source` is the text `expr` was parsed from (or `""` for a hand-built `Expr`); `depth` supplies
1390/// the base indentation for wrapped continuations and the assumed initial output column.
1391/// Postfix bases retain leading group comments, and member-dot comments survive omitted groups.
1392/// Closure bases stay grouped so following postfixes cannot move into their bodies.
1393///
1394/// - Complexity: O(s + v + g + b) construction time and space for s source bytes,
1395///   v node visits, g inspected source-slice bytes and b document-text bytes, plus pretty layout.
1396///
1397/// # Examples
1398///
1399/// ```
1400/// use cel_parser::{AstContext, OpLookup, Parser, format_expr};
1401///
1402/// let mut parser = Parser::<AstContext>::new(OpLookup::new());
1403/// let expr = parser.parse_str_ast("(1i32 + 2i32) * 3i32").unwrap();
1404/// assert_eq!(format_expr(&expr, "(1i32 + 2i32) * 3i32", 0), "(1i32 + 2i32) * 3i32");
1405/// ```
1406pub fn format_expr(expr: &Expr, source: &str, depth: usize) -> String {
1407    format_expr_with_layout(expr, source, depth, depth * 4, 100, 0)
1408}
1409
1410/// Formats an expression at the actual output `column` with a target `width`.
1411///
1412/// Reserves `suffix_columns` for following punctuation on the final line. Short expressions remain
1413/// inline. Lists, records and closure bodies nest four spaces; binary continuations lead with their
1414/// operator. Unbreakable tokens and comments may exceed the target. The result excludes the prefix,
1415/// suffix and initial indentation; continuation indentation starts at `depth * 4`.
1416/// When an indented continuation has more room and the first fragment cannot fit after the prefix,
1417/// the expression starts on a new line indented four spaces beyond `depth`.
1418///
1419/// - Precondition: `source` is the expression's parsed source, or empty for a hand-built AST.
1420/// - Complexity: O(s + v + g + b) construction time and space for s source bytes,
1421///   v node visits, g inspected source-slice bytes and b document-text bytes, plus pretty layout.
1422///
1423/// # Examples
1424/// ```
1425/// use cel_parser::{AstContext, OpLookup, Parser, format_expr_with_layout};
1426/// let source = "first + second";
1427/// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast(source).unwrap();
1428/// assert_eq!(format_expr_with_layout(&expr, source, 1, 12, 26, 1),
1429///     "first\n        + second");
1430/// ```
1431pub 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
1448/// Lays out one complete expression document, accounting for both embedding boundaries.
1449///
1450/// - Complexity: O(n + column + suffix_columns) space; layout uses the document library's group
1451///   fit traversal and never renders subtrees to measure them.
1452fn 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        // Group only the boundary: fitting inspects the following document in broken mode,
1463        // stopping at its first existing break instead of demanding a flat whole expression.
1464        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    /// Long binary expressions wrap before their operators and reparse unchanged.
1496    #[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    /// Binary ranges retain compact spelling and expose a zero-width leading-operator boundary.
1508    #[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    /// An empty closure's header can move with its body when the embedding prefix fills the line.
1537    #[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    /// Nested grammar-owned lists break without introducing unsupported trailing commas.
1550    #[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    /// Parameter lists wrap and retain comments on both sides of their separators.
1566    #[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    /// Block comments do not disable leading-operator break opportunities.
1578    #[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    /// Consecutive line comments keep separate mandatory line boundaries.
1589    #[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    /// A comment after an opening brace cannot consume the first field or branch expression.
1597    #[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    /// Width includes the actual prefix and suffix, not an independently reduced child budget.
1610    #[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    /// Literal-internal newlines retain their spelling rather than inheriting expression nesting.
1637    #[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    /// Layout retains grammar, literal spelling, and precedence across every compound surface.
1651    #[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    /// Maps empty, Unicode, newline, and final-line positions through one reusable index.
1701    #[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    /// Parses one complete expression for formatter contracts.
1723    fn parse(source: &str) -> Expr {
1724        Parser::<AstContext>::new(OpLookup::new())
1725            .parse_str_ast(source)
1726            .unwrap()
1727    }
1728
1729    /// Formats one parsed expression with the default layout.
1730    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        // Not producible by real parsing (the grammar's additive_expression loop is always
1752        // left-associative) — built by hand to prove the printer round-trips a tree shape it
1753        // didn't itself produce. Uses Ident operands (rendered from `name`, not a span) so the
1754        // assertion reads as real text rather than the no-source-text fallback.
1755        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        // Also not producible by real parsing (comparison_expression allows at most one
1785        // comparison, never a nested one) — proves format_expr stays reparseable even for a
1786        // hand-built tree shape the grammar itself can't emit.
1787        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    /// Retains float widths, spans, and notation through the syntax formatter.
1823    #[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        // Matches Rust: `-x as f64` parses as `(-x) as f64` - unary already binds tighter than
1864        // Cast, so the printer doesn't need to add parens to preserve that grouping.
1865        assert_eq!(fmt("-x as f64"), "-x as f64");
1866    }
1867
1868    #[test]
1869    fn explicit_grouping_before_a_cast_keeps_its_parens() {
1870        // `as` binds tighter than `+`, so without parens `(a + b) as i32` would reprint as
1871        // `a + b as i32` - a different expression (`a + (b as i32)`). The parens must survive.
1872        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        // `a + b as i32` already parses as `a + (b as i32)` (`as` binds tighter than `+`), so no
1878        // parens are needed around the cast when reprinting.
1879        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        // `(x as i32) * y` parses to the exact same tree as `x as i32 * y` (cast already binds
1885        // tighter than `*`), so the now-redundant parens are dropped on reprint - matching the
1886        // module doc's "parens added only where required, not exhaustively".
1887        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        // A `//` comment forces a line wrap; the body must land on the continuation line, not get
2044        // glued onto the comment's own line (which would comment it out and make the output
2045        // non-reparseable).
2046        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        // From `is_range_expression`'s own doc comment: `a == b..c == d` parses as
2087        // `(a == b)..(c == d)` -- comparison already binds tighter than range, so the printer
2088        // doesn't need parens to preserve that grouping.
2089        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        // From the same doc comment: `1 + 2..3 * 4` parses as `(1 + 2)..(3 * 4)` -- arithmetic
2095        // binds well inside range's own endpoints, so no parens are needed on reprint either.
2096        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        // depth 0 => continuation at depth 1 (4 spaces). The operator keeps its leading space; the
2142        // line comment ends the line, and the next operand resumes at the continuation indent.
2143        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        // A comma following a line comment must NOT lose one space of the continuation indent --
2149        // that indent is meaningful (it's `indent(depth + 1)`), unlike the single incidental
2150        // space a block comment or an `Around` punct leaves before a comma.
2151        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        // A `//` comment forces a line wrap; `i32` must land on the continuation line, not get
2201        // glued onto the comment's own line (which would comment it out and make the output
2202        // non-reparseable).
2203        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        // The exact repro from stlab/cel-rs#201.
2214        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        // From the design discussion: block comments on both operands and around the operator,
2225        // plus a trailing line comment. The leading `/* p */` and trailing `/* r */` sit outside
2226        // the expression's own span (before its first token, after its last), which the design
2227        // doc explicitly carves out of `format_expr`'s scope: "`Expr`'s own outer boundary ... is
2228        // not `format_expr`'s to own ... that boundary belongs to whatever embeds the expression"
2229        // (adam-lang's Part A2, not yet implemented) -- so only the two in-scope, inter-operand
2230        // comments are expected to survive here.
2231        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}