Skip to main content

bynk_fmt/
fmt.rs

1//! Bynk source formatter.
2//!
3//! Re-parses the source into an AST and re-prints it in canonical form per
4//! the style rules in `design/bynk-lsp-spec.md` §3.5:
5//!
6//! - Tabs by default (one tab per nesting level).
7//! - K&R brace style: opening brace on the same line as the construct header.
8//! - Trailing commas in multi-line record / sum / parameter / argument lists.
9//! - One blank line between top-level declarations.
10//! - No blank lines between fields within a record or arms within a match.
11//! - Doc blocks immediately above their declaration, no blank line between.
12//! - One space around binary operators, after commas, no space inside parens.
13//! - Soft 100-column line width — see below.
14//!
15//! Line width (#963). Every fit test measures the *whole* line: the column the
16//! construct starts at, its own width, and the width of whatever the caller
17//! will still emit after it (a `-> Ret {` signature tail, a closing `)`, a
18//! match arm's `,`). A construct that does not fit is re-emitted vertically,
19//! breaking only where the grammar tolerates a newline:
20//!
21//! - Record constructions, list literals, `exports`/`enum` bodies, and agent
22//!   scheme configuration take one entry per line, with a trailing comma.
23//! - Parameter and argument lists take one entry per line **without** a
24//!   trailing comma — the grammar rejects one there.
25//! - A `&&` / `||` / `implies` run breaks before each operator. Arithmetic and
26//!   comparison operators never break: a continuation line opening with `+`
27//!   does not re-attach to the line above on re-parse.
28//! - A `.`-chain of two or more calls breaks before each call, unless the
29//!   overflow belongs to a trailing argument that can open its body on the
30//!   chain's own line (`xs.fold(init, (acc, x) => match acc {`).
31//! - An `if` sends both branches vertical; a block sends its statements
32//!   vertical.
33//!
34//! The target is soft: a construct with no break point inside it — a long
35//! string literal, a `Matches("…")` regex — is left over-long rather than
36//! mangled. Every layout choice is a function of the AST and the current
37//! column, so the result is stable under re-formatting.
38//!
39//! The formatter is idempotent: format → format yields the same text.
40//!
41//! Comments (v1.1): line comments are preserved through the lexer-to-parser
42//! trivia pipeline (lexer emits `Comment` tokens, parser attaches them to
43//! AST declarations and statements). The formatter re-emits leading
44//! comments above each node and a trailing comment, if any, on the same
45//! line as the node's last token. Comments inside expression sub-trees
46//! are not yet attached to individual operands; they are folded into the
47//! enclosing statement's leading trivia. When even that would lose a
48//! comment, [`format_source`] refuses with a `bynk.fmt.comment_loss`
49//! diagnostic instead of dropping user text (#523) — the file is left
50//! unchanged. See `design/bynk-lsp-spec.md` §3.5 for the canonical
51//! comment-placement rules.
52
53use bynk_syntax::ast::*;
54use bynk_syntax::error::CompileError;
55use bynk_syntax::lexer::{
56    Token, TokenKind, comment_is_legacy, doc_fence_len, doc_line_is_legacy, one_line_doc, tokenize,
57    tokenize_legacy,
58};
59use bynk_syntax::parser::parse_units_migrating;
60use bynk_syntax::print::{
61    LambdaBodySrc, WrittenForms, binop_prec, call_site_actor_src, else_if_tail, escape_string,
62    expr_to_string, expr_with_prec, is_pattern_src, lambda_body_src, lambda_param_src,
63    let_else_binding, let_pattern_src, literal_text, matches_argument_span, omit_unit_tail,
64    pattern_to_string, type_ref_to_string,
65};
66use bynk_syntax::span::Span;
67
68/// Indentation style: tabs or spaces. Mirrors the LSP spec's `[fmt].indent`
69/// setting.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum IndentStyle {
72    #[default]
73    Tab,
74    Spaces(u8),
75}
76
77/// Formatter options. All fields have spec-defined defaults.
78///
79/// `Copy` (#972): three scalar fields, and the config layering passes them by
80/// value through per-file resolution — a `clone()` at each hop would be noise.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct FormatOptions {
83    pub indent: IndentStyle,
84    pub max_line_width: u32,
85    pub trailing_comma: bool,
86}
87
88impl Default for FormatOptions {
89    fn default() -> Self {
90        Self {
91            indent: IndentStyle::Tab,
92            max_line_width: 100,
93            trailing_comma: true,
94        }
95    }
96}
97
98/// Error returned when formatting fails. The formatter cannot format code
99/// that does not parse, so all failure modes here surface as parse errors.
100#[derive(Debug, Clone)]
101pub struct FormatError {
102    pub errors: Vec<CompileError>,
103}
104
105/// Format a Bynk source string. On parse failure, returns the original
106/// source unchanged is *not* this function's responsibility — callers (LSP,
107/// CLI) decide how to handle parse failure. Here we surface the errors so
108/// the caller can do so.
109pub fn format_source(source: &str, opts: &FormatOptions) -> Result<String, FormatError> {
110    // #1763: line endings are not a formatting difference. A CRLF file formats
111    // to the LF canonical form, CRs inside `---` blocks included (their text
112    // was kept verbatim, so a CR survived into the output). A caller rendering
113    // this function's errors should render them against the normalised text.
114    let source = &*normalize_line_endings(source);
115    let tokens = migration_tokens(source).map_err(|e| FormatError { errors: vec![e] })?;
116    // v0.113: a file may hold more than one top-level unit (an atomic
117    // `commons` + `suite` file, DECISION S). Format each and join with a blank
118    // line. Each unit's output already ends in exactly one newline, so joining
119    // with `"\n"` inserts one blank line between units and leaves a single-unit
120    // file byte-identical.
121    let (units, _warnings, _) =
122        parse_units_migrating(&tokens, source).map_err(|errors| FormatError { errors })?;
123    let output = render_units(&units, source, opts);
124    // #523/#66 guard: trivia is only attached at declaration/statement
125    // granularity, so a comment inside an expression subtree can be silently
126    // dropped. Losing user text is worse than leaving a file unformatted — when
127    // the output holds fewer comments than the input, refuse with a diagnostic
128    // pointing at the first comment that would vanish. It runs on every format:
129    // the parse's own `fully_drained` flag only says each comment was harvested
130    // from the trivia table, not that it reached the AST, and #1756 found
131    // comments harvested then dropped (at the end of a service, agent or
132    // capability body, and inside a `cors`/`security`/`limits` policy) that the
133    // formatter deleted with no refusal. Both places keep their comments now
134    // (#1756, #1786); the guard stays for whatever the next gap is.
135    if let Some(error) = comment_loss(source, &tokens, &output) {
136        return Err(FormatError {
137            errors: vec![error],
138        });
139    }
140    // #1664: doc blocks never enter the trivia table, so `fully_drained` says
141    // nothing about them, and the guard above counts `--` comments only. Check
142    // them separately, on every run. Since #1756 an orphan (a block separated
143    // from the next declaration by a blank line, or with none to follow) is
144    // kept as a `Comment::OrphanDoc` and printed in place; this is the backstop
145    // for a block some printer path still loses.
146    if let Some(error) = doc_block_loss(source, &tokens, &output) {
147        return Err(FormatError {
148            errors: vec![error],
149        });
150    }
151    // #735 guard: the printer is hand-written and dodges several parse traps by
152    // convention (a tail `()` re-attaching as a call, a trailing comma making a
153    // param list unparseable). A shape the corpus misses that the printer
154    // mis-renders would otherwise be written straight over the user's file with
155    // exit 0. Before returning, re-parse the output and compare its *code*
156    // structure — every comment stripped from both sides, so trivia re-flow is
157    // ignored — against the input. When the output fails to re-parse, or a
158    // shape round-trips to a different AST, refuse rather than corrupt.
159    if let Some(error) = roundtrip_divergence(&tokens, source, &output, opts) {
160        return Err(FormatError {
161            errors: vec![error],
162        });
163    }
164    Ok(output)
165}
166
167/// #2203 (DECISION F): the tokens `bynk fmt` formats `source` from. A file
168/// that uses a legacy spelling, a `--` comment or a `--|` doc line, was
169/// written before `//` comments, so it is read as it was then ([`tokenize_legacy`]),
170/// and printing its comments as `//` and its docs as `--- ` is its migration.
171/// Any other file is read as it is now.
172///
173/// A file can be half migrated, though: a stray `-- note` in a file whose
174/// `--- text` docs and `a --b` subtractions are new. The old and new rules read
175/// those lines differently, and only the author knows which was meant, so a
176/// legacy file is formatted only when both reads agree on everything but the
177/// legacy tokens themselves; otherwise it is refused
178/// (`bynk.fmt.mixed_comment_syntax`), naming the first line they disagree on.
179fn migration_tokens(source: &str) -> Result<Vec<Token>, CompileError> {
180    let is_legacy = |t: &Token| match t.kind {
181        TokenKind::Comment => comment_is_legacy(source, t.span),
182        TokenKind::DocLine => doc_line_is_legacy(source, t.span),
183        _ => false,
184    };
185    let current = tokenize(source);
186    if current.as_ref().is_ok_and(|t| !t.iter().any(is_legacy)) {
187        return current;
188    }
189    let old = match tokenize_legacy(source) {
190        Ok(old) if old.iter().any(is_legacy) => old,
191        _ => return current,
192    };
193    let Ok(new) = &current else {
194        return Ok(old);
195    };
196    let key = |t: &Token| (t.span.start, t.span.end);
197    let shared: std::collections::HashSet<_> =
198        new.iter().filter(|t| is_legacy(t)).map(key).collect();
199    let rest = |tokens: &[Token]| -> Vec<Token> {
200        tokens
201            .iter()
202            .filter(|t| !(is_legacy(t) && shared.contains(&key(t))))
203            .copied()
204            .collect()
205    };
206    let (old_rest, new_rest) = (rest(&old), rest(new));
207    let differ = old_rest
208        .iter()
209        .zip(&new_rest)
210        .find(|(a, b)| a.kind != b.kind || key(a) != key(b))
211        .map(|(a, b)| {
212            if a.span.start <= b.span.start {
213                a.span
214            } else {
215                b.span
216            }
217        })
218        .or_else(|| {
219            (old_rest.len() != new_rest.len()).then(|| {
220                let n = old_rest.len().min(new_rest.len());
221                old_rest
222                    .get(n)
223                    .or(new_rest.get(n))
224                    .expect("one is longer")
225                    .span
226            })
227        });
228    match differ {
229        None => Ok(old),
230        Some(span) => Err(mixed_comment_syntax(source, span)),
231    }
232}
233
234/// #2203: the `bynk.fmt.mixed_comment_syntax` refusal for a legacy file whose
235/// line at `span` reads differently under the old and new comment rules.
236fn mixed_comment_syntax(source: &str, span: Span) -> CompileError {
237    let line_start = source[..span.start].rfind('\n').map_or(0, |i| i + 1);
238    let line_end = source[span.start..]
239        .find('\n')
240        .map_or(source.len(), |i| span.start + i);
241    let line = Span::new_in(span.file, line_start, line_end);
242    CompileError::new(
243        "bynk.fmt.mixed_comment_syntax",
244        line,
245        "this file uses the retired `--` comment or `--|` doc spelling, and this line \
246         reads differently under the old and new comment rules — the file was left unchanged",
247    )
248    .with_label(
249        line,
250        "under the old rules a `--` here is a comment, and `--- text` is a comment, not a doc",
251    )
252    .with_note(
253        "change the retired `--` comments and `--|` docs to `//` and `--- ` (VS Code's Fix All \
254         does this), or rewrite this line, then format again",
255    )
256}
257
258/// #1763: `source` with every line ending made LF, borrowed when there is
259/// nothing to change. The canonical form uses LF, and comparing a file against
260/// it modulo line endings is what keeps a Windows checkout
261/// (`core.autocrlf=true`) of a canonical file canonical.
262///
263/// A run of CRs before an LF (`\r\n`, `\r\r\n`, …) is one line ending, so
264/// this is a fixed point: normalising its own output changes nothing (#1775
265/// review; a single `replace` turned `\r\r\n` into a `\r\n` a second pass
266/// would change again). A CR not before an LF is left alone; the lexer treats
267/// it as whitespace. Normalising can't change a program value, since a string
268/// literal can't span a line (`bynk.lex.unterminated_string`).
269pub fn normalize_line_endings(source: &str) -> std::borrow::Cow<'_, str> {
270    if !source.contains("\r\n") {
271        return std::borrow::Cow::Borrowed(source);
272    }
273    let mut out = String::with_capacity(source.len());
274    let mut pending_crs = 0usize;
275    for c in source.chars() {
276        match c {
277            '\r' => pending_crs += 1,
278            '\n' => {
279                pending_crs = 0;
280                out.push('\n');
281            }
282            _ => {
283                out.extend(std::iter::repeat_n('\r', pending_crs));
284                pending_crs = 0;
285                out.push(c);
286            }
287        }
288    }
289    out.extend(std::iter::repeat_n('\r', pending_crs));
290    std::borrow::Cow::Owned(out)
291}
292
293/// Format every top-level unit and join with a blank line. A file may hold more
294/// than one top-level unit (v0.113, an atomic `commons` + `suite` file,
295/// DECISION S). Each unit's output already ends in exactly one newline, so
296/// joining with `"\n"` inserts one blank line between units and leaves a
297/// single-unit file byte-identical.
298fn render_units(units: &[SourceUnit], source: &str, opts: &FormatOptions) -> String {
299    let _written_forms = WrittenForms::enter(source);
300    let parts: Vec<String> = units
301        .iter()
302        .map(|unit| {
303            let mut f = Formatter::new(opts);
304            f.format_unit(unit);
305            f.finish()
306        })
307        .collect();
308    parts.join("\n")
309}
310
311/// #735: the comment-free canonical rendering of `source` — every `Comment`
312/// token dropped before parsing, so the result carries no trivia and reflects
313/// only the code structure. Because the parser strips comments the same way
314/// ([`split_trivia`]), pre-filtering them changes nothing structural; it just
315/// leaves the trivia fields empty so the formatter emits pure code. Returns the
316/// parse errors when `source` does not tokenize or parse.
317fn code_only_canonical(source: &str, opts: &FormatOptions) -> Result<String, Vec<CompileError>> {
318    let tokens = tokenize(source).map_err(|e| vec![e])?;
319    code_only_canonical_from_tokens(&tokens, source, opts)
320}
321
322/// [`code_only_canonical`], given an already-tokenized `source` — finding #66:
323/// `format_source` tokenizes `source` once up front for the real render;
324/// `roundtrip_divergence` reuses that token list here instead of tokenizing
325/// `source` from scratch a second time.
326fn code_only_canonical_from_tokens(
327    tokens: &[Token],
328    source: &str,
329    opts: &FormatOptions,
330) -> Result<String, Vec<CompileError>> {
331    let code: Vec<Token> = tokens
332        .iter()
333        .filter(|t| t.kind != TokenKind::Comment)
334        .cloned()
335        .collect();
336    let (units, _, _) = parse_units_migrating(&code, source)?;
337    Ok(render_units(&units, source, opts))
338}
339
340/// #735: refuse when the formatter's `output` does not round-trip to the same
341/// code as `source`. Both sides are reduced to their comment-free canonical
342/// form ([`code_only_canonical`]) and compared: the formatter only re-flows
343/// whitespace and trivia, so for a faithful render the two canonical strings
344/// are byte-identical. A mismatch means either the output no longer parses (the
345/// data-loss vector) or the printer altered the AST. `None` when the output is
346/// safe to write.
347///
348/// Note: this guard assumes the formatter is idempotent on comment-free code —
349/// i.e. `render(parse(strip(x)))` is a stable canonical form. That invariant is
350/// held by the corpus/property idempotency tests. Were a future formatter
351/// change to break it on some shape, this guard would *refuse* an otherwise
352/// valid file rather than corrupt it — it fails safe (file unchanged + a
353/// diagnostic), but the surprise would be a formatter bug to fix upstream.
354fn roundtrip_divergence(
355    tokens: &[Token],
356    source: &str,
357    output: &str,
358    opts: &FormatOptions,
359) -> Option<CompileError> {
360    // The output MUST re-parse to the same structure; a failure here is the
361    // core corruption vector this guard exists to stop.
362    let canon_out = match code_only_canonical(output, opts) {
363        Ok(canon) => canon,
364        Err(_) => {
365            return Some(roundtrip_error(
366                "the formatter produced output that no longer parses",
367            ));
368        }
369    };
370    // The input already tokenized (and parsed) in `format_source` — `tokens` is
371    // that same token list, reused rather than tokenizing `source` a second
372    // time (finding #66). If its canonical form unexpectedly fails to compute,
373    // do not block a valid format on our own guard failing — leave the file
374    // writable.
375    let canon_in = code_only_canonical_from_tokens(tokens, source, opts).ok()?;
376    (canon_in != canon_out)
377        .then(|| roundtrip_error("the formatter's output does not round-trip to the same code"))
378}
379
380/// Build the `bynk.fmt.roundtrip` diagnostic shared by both failure modes of
381/// [`roundtrip_divergence`]. The span is deliberately `Span::default()` (the
382/// start of the file): the message points at neither the source nor the
383/// output — it is a generic "this is a formatter bug" — and the failing branch
384/// carries an *output*-relative span, which the caller renders against the
385/// *source* string. When the mis-rendered output is longer than the source,
386/// that span is out of range for the buffer ariadne is given (a misplaced
387/// caret, or a byte-index panic in the very formatter-bug path this guard
388/// exists to handle gracefully). A zero span is always in range and buys the
389/// message nothing to lose.
390fn roundtrip_error(what: &str) -> CompileError {
391    CompileError {
392        category: "bynk.fmt.roundtrip",
393        span: Span::default(),
394        message: format!("{what} — the file was left unchanged"),
395        labels: Vec::new(),
396        notes: vec![
397            "this is a formatter bug, not a problem with your source; please report it \
398             with the file that triggered it"
399                .to_string(),
400        ],
401        suggestions: Vec::new(),
402    }
403}
404
405/// #523: compare the comment population of `source` (already tokenized as
406/// `tokens`) against `output`. Returns a `bynk.fmt.comment_loss` error naming
407/// the first lost comment when the output would hold fewer comments, `None`
408/// when every comment survives. Comments may legitimately *move* (expression
409/// trivia folds into the enclosing statement's leading block), so the
410/// comparison is by body multiset, not position.
411fn comment_loss(source: &str, tokens: &[Token], output: &str) -> Option<CompileError> {
412    use bynk_syntax::lexer::comment_body;
413    let in_comments: Vec<Span> = tokens
414        .iter()
415        .filter(|t| t.kind == TokenKind::Comment)
416        .map(|t| t.span)
417        .collect();
418    if in_comments.is_empty() {
419        return None;
420    }
421    // The formatter's own output must tokenize; treat a failure as "all
422    // comments lost" rather than silently accepting the write.
423    let mut out_bodies: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
424    if let Ok(out_tokens) = tokenize(output) {
425        for t in &out_tokens {
426            if t.kind == TokenKind::Comment {
427                *out_bodies
428                    .entry(comment_body(output, t.span).trim().to_string())
429                    .or_insert(0) += 1;
430            }
431        }
432    }
433    let mut lost = 0usize;
434    let mut first_lost: Option<Span> = None;
435    for span in &in_comments {
436        let body = comment_body(source, *span).trim().to_string();
437        match out_bodies.get_mut(&body) {
438            Some(n) if *n > 0 => *n -= 1,
439            _ => {
440                lost += 1;
441                first_lost.get_or_insert(*span);
442            }
443        }
444    }
445    let span = first_lost?;
446    Some(CompileError {
447        category: "bynk.fmt.comment_loss",
448        span,
449        message: format!(
450            "formatting would lose {lost} comment{} — the file was left unchanged",
451            if lost == 1 { "" } else { "s" }
452        ),
453        labels: vec![(
454            span,
455            "this comment sits where the formatter cannot yet re-attach it".to_string(),
456        )],
457        notes: vec![
458            "comments inside expression subtrees are not yet preserved; move the comment onto \
459             its own line before the enclosing statement to format this file"
460                .to_string(),
461        ],
462        suggestions: Vec::new(),
463    })
464}
465
466/// #1888: every doc in `source` (already tokenized as `tokens`), in order: its
467/// span, its form, and its text with each line's surrounding whitespace
468/// removed, so the formatter's re-indentation of an attached doc is not
469/// mistaken for loss.
470fn source_docs(source: &str, tokens: &[Token]) -> Vec<(Span, DocForm, String)> {
471    use bynk_syntax::lexer::{doc_block_content, doc_line_text};
472    let normalise = |content: &str| {
473        content
474            .lines()
475            .map(str::trim)
476            .collect::<Vec<_>>()
477            .join("\n")
478    };
479    tokens
480        .iter()
481        .filter_map(|t| match t.kind {
482            TokenKind::DocLine => Some((
483                t.span,
484                DocForm::Lines,
485                normalise(doc_line_text(source, t.span)),
486            )),
487            TokenKind::DocBlock => Some((
488                t.span,
489                DocForm::Block,
490                normalise(&doc_block_content(source, t.span)),
491            )),
492            _ => None,
493        })
494        .collect()
495}
496
497/// #1664: the `---` counterpart of [`comment_loss`]. Returns a
498/// `bynk.fmt.comment_loss` error naming the first doc of `source` (already
499/// tokenized as `tokens`) that has no counterpart in `output`, compared by
500/// content multiset. Attached and orphaned (#1756) docs are both re-rendered
501/// with their content intact, so this fires only on a printer gap.
502///
503/// #1888: both doc forms are compared, each keyed by its form as well as its
504/// content, so a printer path that converted a doc from one form to the other
505/// (DECISION F says it never does) is refused as well as one that lost it.
506///
507/// An `output` that does not tokenize returns `None`: that is a formatter bug
508/// the round-trip guard reports accurately ("no longer parses"), and counting
509/// every block as lost would point the user at an innocent one instead.
510fn doc_block_loss(source: &str, tokens: &[Token], output: &str) -> Option<CompileError> {
511    let in_docs = source_docs(source, tokens);
512    if in_docs.is_empty() {
513        return None;
514    }
515    let out_tokens = tokenize(output).ok()?;
516    let mut out_docs: std::collections::HashMap<(DocForm, String), usize> =
517        std::collections::HashMap::new();
518    for (_, form, content) in source_docs(output, &out_tokens) {
519        *out_docs.entry((form, content)).or_insert(0) += 1;
520    }
521    let mut lost = 0usize;
522    let mut first_lost: Option<Span> = None;
523    for (span, form, content) in in_docs {
524        match out_docs.get_mut(&(form, content)) {
525            Some(n) if *n > 0 => *n -= 1,
526            _ => {
527                lost += 1;
528                first_lost.get_or_insert(span);
529            }
530        }
531    }
532    let span = first_lost?;
533    Some(CompileError {
534        category: "bynk.fmt.comment_loss",
535        span,
536        message: format!(
537            "formatting would lose {lost} doc{} — the file was left unchanged",
538            if lost == 1 { "" } else { "s" }
539        ),
540        labels: vec![(
541            span,
542            "this doc has no counterpart in the formatted output".to_string(),
543        )],
544        notes: vec![
545            "a doc (a `---` block or `--|` lines) attaches to the declaration or member \
546             directly below it; one separated from it by a blank line, or with nothing after \
547             it, attaches to nothing. Remove the blank line to attach it, or make it a `--` \
548             comment if it documents nothing"
549                .to_string(),
550            "if the block is already directly above a declaration, this is a formatter bug; \
551             please report it with the file that triggered it"
552                .to_string(),
553        ],
554        suggestions: Vec::new(),
555    })
556}
557
558// -- Internal formatter state --
559
560struct Formatter<'a> {
561    opts: &'a FormatOptions,
562    out: String,
563    indent_level: u32,
564    /// True when the formatter has just emitted a newline and is at the
565    /// start of a fresh line. Used to gate indent emission.
566    at_line_start: bool,
567}
568
569impl<'a> Formatter<'a> {
570    fn new(opts: &'a FormatOptions) -> Self {
571        Self {
572            opts,
573            out: String::new(),
574            indent_level: 0,
575            at_line_start: true,
576        }
577    }
578
579    fn finish(mut self) -> String {
580        // Single trailing newline.
581        while self.out.ends_with("\n\n") {
582            self.out.pop();
583        }
584        if !self.out.ends_with('\n') {
585            self.out.push('\n');
586        }
587        self.out
588    }
589
590    fn indent_unit(&self) -> String {
591        match self.opts.indent {
592            IndentStyle::Tab => "\t".to_string(),
593            IndentStyle::Spaces(n) => " ".repeat(n as usize),
594        }
595    }
596
597    fn emit_indent(&mut self) {
598        let unit = self.indent_unit();
599        for _ in 0..self.indent_level {
600            self.out.push_str(&unit);
601        }
602    }
603
604    fn push(&mut self, s: &str) {
605        if self.at_line_start && !s.starts_with('\n') {
606            self.emit_indent();
607            self.at_line_start = false;
608        }
609        if s.contains('\n') {
610            self.push_reindented(s);
611        } else {
612            self.out.push_str(s);
613        }
614    }
615
616    /// Append a multi-line string, re-applying the current indent to every
617    /// continuation line. Multi-line strings come from the single-line
618    /// expression renderers (`expr_to_string` and friends), which build their
619    /// internal structure assuming column zero — they embed `\n` plus relative
620    /// tabs but know nothing about the current nesting depth. Without this an
621    /// argument-position `match` (or any embedded multi-line expression) would
622    /// print its arms and trailing brace at column one regardless of how deeply
623    /// it is nested. The first line is emitted as-is (its indent, if any, was
624    /// handled by `push`); blank lines are left empty rather than padded.
625    fn push_reindented(&mut self, s: &str) {
626        let prefix = self.indent_unit().repeat(self.indent_level as usize);
627        for (i, line) in s.split('\n').enumerate() {
628            if i > 0 {
629                self.out.push('\n');
630                if !line.is_empty() {
631                    self.out.push_str(&prefix);
632                }
633            }
634            self.out.push_str(line);
635        }
636    }
637
638    fn newline(&mut self) {
639        self.out.push('\n');
640        self.at_line_start = true;
641    }
642
643    /// End the current line if it is open, then leave a blank line unless the
644    /// output already ends with one.
645    /// #2893: a comment on a header line (`uses`, `consumes`, `exports`) that
646    /// follows another header line keeps the blank line that set it apart in
647    /// the source, so it still reads as belonging to the line below. Plain
648    /// header lines, and comments written flush against the line above, stay
649    /// tight.
650    fn header_comment_gap(&mut self, any_before: bool, blank_before: bool, leading: &[Comment]) {
651        if any_before && blank_before && !leading.is_empty() {
652            self.blank_line();
653        }
654    }
655
656    fn blank_line(&mut self) {
657        if !self.out.ends_with('\n') {
658            self.out.push('\n');
659        }
660        if !self.out.ends_with("\n\n") {
661            self.out.push('\n');
662        }
663        self.at_line_start = true;
664    }
665
666    fn indented<F: FnOnce(&mut Self)>(&mut self, f: F) {
667        self.indent_level += 1;
668        f(self);
669        self.indent_level -= 1;
670    }
671
672    /// Render `body` into a detached formatter positioned at this one's exact
673    /// column and indent, and commit it only if every line it produces stays
674    /// inside the budget (the last line counting `reserve` further columns for
675    /// whatever the caller will append). Returns whether it was committed.
676    ///
677    /// A candidate layout is often only judgeable once rendered: whether a
678    /// `.`-chain needs breaking at its dots depends on how its arguments wrap,
679    /// which depends on the column they start at. Measuring a real rendering
680    /// beats predicting one (#963).
681    fn try_layout<F: FnOnce(&mut Self)>(&mut self, reserve: usize, body: F) -> bool {
682        self.try_layout_if(reserve, body, || true)
683    }
684
685    /// [`Self::try_layout`] with a second condition, evaluated after the
686    /// rendering, for a caller that judges the candidate on more than its
687    /// width — a chain that fits but only by exploding an argument list.
688    fn try_layout_if<F: FnOnce(&mut Self), A: FnOnce() -> bool>(
689        &mut self,
690        reserve: usize,
691        body: F,
692        accept: A,
693    ) -> bool {
694        let line_start = self.out.rfind('\n').map_or(0, |i| i + 1);
695        let mut sub = Formatter {
696            opts: self.opts,
697            out: self.out[line_start..].to_string(),
698            indent_level: self.indent_level,
699            at_line_start: self.at_line_start,
700        };
701        let produced_from = sub.out.len();
702        body(&mut sub);
703        if !sub.every_line_within_budget(reserve) || !accept() {
704            return false;
705        }
706        // Splice the raw text: `sub` already emitted its own indentation, so
707        // going through `push` would double it.
708        self.out.push_str(&sub.out[produced_from..]);
709        self.at_line_start = sub.at_line_start;
710        true
711    }
712
713    /// Does every line of this (detached) formatter's buffer fit, with
714    /// `reserve` columns still free on the last one?
715    fn every_line_within_budget(&self, reserve: usize) -> bool {
716        let tab = self.indent_width();
717        let mut lines = self.out.split('\n').peekable();
718        let mut last = "";
719        while let Some(line) = lines.next() {
720            if lines.peek().is_none() {
721                last = line;
722                break;
723            }
724            if display_width(line, tab) > self.opts.max_line_width as usize {
725                return false;
726            }
727        }
728        let last_width = if self.at_line_start {
729            // The trailing indent is not in the buffer yet; `push` adds it.
730            self.indent_level as usize * tab
731        } else {
732            display_width(last, tab)
733        };
734        last_width + reserve <= self.opts.max_line_width as usize
735    }
736
737    // -- Doc block --
738
739    /// Emit a doc block immediately above a declaration. The content is
740    /// already normalised (common leading indent stripped) when stored in
741    /// the AST; we re-emit with the current indent applied per line.
742    ///
743    /// #1885: a doc block closes only on a marker of its opener's length, so
744    /// the fence is the shortest (three or more dashes) that is longer than
745    /// every marker-shaped line in the content; the output re-lexes to the
746    /// same block. A doc with no such line keeps the canonical `---`.
747    ///
748    /// #1888 (DECISION F): a doc prints in the form it was written in, never
749    /// converted. A one-line doc prints as `--- text` (#2203), without the
750    /// optional closer, and a legacy `--|` line prints the same way.
751    fn emit_doc(&mut self, doc: &Doc) {
752        if doc.form == DocForm::Lines {
753            self.push(&one_line_doc(doc));
754            self.newline();
755            return;
756        }
757        let fence = "-".repeat(doc_fence_len(doc));
758        self.push(&fence);
759        self.newline();
760        for line in doc.lines() {
761            if line.is_empty() {
762                self.newline();
763            } else {
764                self.push(line);
765                self.newline();
766            }
767        }
768        self.push(&fence);
769        self.newline();
770    }
771
772    // -- Line-comment trivia (v1.1) --
773
774    /// Emit a sequence of leading comments, each on its own line at the
775    /// current indent. `--` lines have no blank lines between them, except
776    /// where a unit-level declaration's comments keep one (#1884,
777    /// [`Comment::Blank`]); an orphaned doc block (#1756) prints as a doc block
778    /// and is followed by a blank line, which is what keeps it from attaching
779    /// to the declaration below.
780    fn emit_leading_comments(&mut self, comments: &[Comment]) {
781        self.emit_comments(comments, true);
782    }
783
784    /// Emit the comments that close a body or file. As
785    /// [`Self::emit_leading_comments`], except that a blank line after the
786    /// last entry is not printed: nothing follows it to keep apart, and the
787    /// body's `}` comes straight after its last line.
788    fn emit_trailing_comments(&mut self, comments: &[Comment]) {
789        self.emit_comments(comments, false);
790    }
791
792    fn emit_comments(&mut self, comments: &[Comment], blank_after_last: bool) {
793        for (i, comment) in comments.iter().enumerate() {
794            let blank_after = i + 1 < comments.len() || blank_after_last;
795            match comment {
796                Comment::Line(body) => {
797                    self.push("//");
798                    self.push(body);
799                    self.newline();
800                }
801                Comment::OrphanDoc(doc) => {
802                    self.emit_doc(doc);
803                    if blank_after {
804                        self.newline();
805                    }
806                }
807                Comment::Blank if blank_after => self.blank_line(),
808                Comment::Blank => {}
809            }
810        }
811    }
812
813    /// Emit a trailing comment on the same line as the just-emitted token.
814    /// The spec uses two spaces between code and comment for readability.
815    fn emit_trailing_comment(&mut self, body: Option<&str>) {
816        if let Some(body) = body {
817            // Ensure we're on the same line as the preceding tokens —
818            // strip any newline we just emitted.
819            while self.out.ends_with('\n') {
820                self.out.pop();
821            }
822            self.out.push_str("  //");
823            self.out.push_str(body);
824            self.newline();
825        }
826    }
827
828    /// End the current line: with the trailing comment when there is one
829    /// (which [`Self::emit_trailing_comment`] closes with its own newline),
830    /// otherwise with a bare newline. A site that splices the comment onto a
831    /// line something else already ended calls `emit_trailing_comment` alone.
832    fn emit_trailing_comment_or_newline(&mut self, trailing: Option<&str>) {
833        if trailing.is_some() {
834            self.emit_trailing_comment(trailing);
835        } else {
836            self.newline();
837        }
838    }
839
840    // -- Top level --
841
842    fn format_unit(&mut self, unit: &SourceUnit) {
843        match unit {
844            SourceUnit::Commons(c) => self.format_commons(c),
845            SourceUnit::Context(c) => self.format_context(c),
846            SourceUnit::Suite(t) => self.format_test(t),
847            SourceUnit::Adapter(a) => self.format_adapter(a),
848        }
849    }
850
851    fn format_adapter(&mut self, a: &AdapterDecl) {
852        self.emit_leading_comments(&a.trivia.leading);
853        if let Some(doc) = &a.documentation {
854            self.emit_doc(doc);
855        }
856        let header = format!("adapter {}", a.name.joined());
857        match a.form {
858            CommonsForm::Brace => {
859                self.push(&header);
860                self.push(" {");
861                self.newline();
862                self.indented(|f| {
863                    f.format_adapter_body(a);
864                });
865                self.push("}");
866                self.newline();
867            }
868            CommonsForm::Fragment => {
869                self.push(&header);
870                self.newline();
871                self.newline();
872                self.format_adapter_body(a);
873            }
874        }
875    }
876
877    fn format_adapter_body(&mut self, a: &AdapterDecl) {
878        let mut any_header = false;
879        if let Some(b) = &a.binding {
880            self.emit_leading_comments(&b.trivia.leading);
881            self.push(&format!("binding {:?}", b.module));
882            if !b.includes.is_empty() {
883                let entries: Vec<String> =
884                    b.includes.iter().map(|i| format!("{:?}", i.path)).collect();
885                self.push(&format!(" includes [{}]", entries.join(", ")));
886            }
887            if !b.requires.is_empty() {
888                let entries: Vec<String> = b
889                    .requires
890                    .iter()
891                    .map(|r| format!("{:?}: {:?}", r.package, r.range))
892                    .collect();
893                self.push(&format!(" requires {{ {} }}", entries.join(", ")));
894            }
895            self.emit_trailing_comment_or_newline(b.trivia.trailing.as_deref());
896            any_header = true;
897        }
898        for u in &a.uses {
899            self.header_comment_gap(any_header, u.blank_before, &u.trivia.leading);
900            self.emit_leading_comments(&u.trivia.leading);
901            self.push(&format!("uses {}", u.target.joined()));
902            self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
903            any_header = true;
904        }
905        for c in &a.consumes {
906            self.format_consumes(c, any_header);
907            any_header = true;
908        }
909        for e in &a.exports {
910            self.header_comment_gap(any_header, e.blank_before, &e.trivia.leading);
911            self.emit_leading_comments(&e.trivia.leading);
912            self.format_exports(e);
913            if e.trivia.trailing.is_some() {
914                self.emit_trailing_comment(e.trivia.trailing.as_deref());
915            }
916            any_header = true;
917        }
918        if any_header && !a.items.is_empty() {
919            self.newline();
920        }
921        let mut first = true;
922        for item in &a.items {
923            if !first {
924                self.newline();
925            }
926            self.format_item(item);
927            first = false;
928        }
929        if !a.trailing_comments.is_empty() {
930            if !a.items.is_empty() || any_header {
931                self.newline();
932            }
933            self.emit_trailing_comments(&a.trailing_comments);
934        }
935    }
936
937    fn format_test(&mut self, t: &SuiteDecl) {
938        self.emit_leading_comments(&t.trivia.leading);
939        if let Some(doc) = &t.documentation {
940            self.emit_doc(doc);
941        }
942        let mut header = format!("suite {}", t.target.joined());
943        if let Some(tier) = t.tier {
944            header.push_str(&format!(" as {}", tier.as_str()));
945        }
946        match t.form {
947            CommonsForm::Brace => {
948                self.push(&header);
949                self.push(" {");
950                self.newline();
951                self.indented(|f| {
952                    f.format_test_body(
953                        &t.uses,
954                        &t.consumes,
955                        &t.envs,
956                        &t.stubs,
957                        &t.fixtures,
958                        &t.types,
959                        &t.consts,
960                        &t.fns,
961                        &t.cases,
962                        &t.properties,
963                        &t.trailing_comments,
964                    );
965                });
966                self.push("}");
967                self.newline();
968            }
969            CommonsForm::Fragment => {
970                self.push(&header);
971                self.newline();
972                self.newline();
973                self.format_test_body(
974                    &t.uses,
975                    &t.consumes,
976                    &t.envs,
977                    &t.stubs,
978                    &t.fixtures,
979                    &t.types,
980                    &t.consts,
981                    &t.fns,
982                    &t.cases,
983                    &t.properties,
984                    &t.trailing_comments,
985                );
986            }
987        }
988    }
989
990    #[allow(clippy::too_many_arguments)]
991    fn format_test_body(
992        &mut self,
993        uses: &[UsesDecl],
994        consumes: &[ConsumesDecl],
995        envs: &[EnvClause],
996        stubs: &[StubClause],
997        fixtures: &[FixtureDecl],
998        types: &[TypeDecl],
999        consts: &[ConstDecl],
1000        fns: &[FnDecl],
1001        cases: &[Case],
1002        properties: &[PropertyDecl],
1003        trailing_comments: &[Comment],
1004    ) {
1005        let mut first = true;
1006        for u in uses {
1007            if !first {
1008                self.newline();
1009            }
1010            self.emit_leading_comments(&u.trivia.leading);
1011            self.push(&format!("uses {}", u.target.joined()));
1012            self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1013            first = false;
1014        }
1015        // #3536: consecutive `consumes` lines stay together, as in a unit's header.
1016        for (i, c) in consumes.iter().enumerate() {
1017            if !first && i == 0 {
1018                self.newline();
1019            }
1020            self.format_consumes(c, i > 0);
1021            first = false;
1022        }
1023        for e in envs {
1024            if !first {
1025                self.newline();
1026            }
1027            self.format_env_clause(e);
1028            first = false;
1029        }
1030        for pv in stubs {
1031            if !first {
1032                self.newline();
1033            }
1034            self.format_stub_clause(pv);
1035            first = false;
1036        }
1037        // `fns`, `cases` and `properties` are separate lists, so merge them
1038        // back into source order rather than printing them by kind.
1039        enum Member<'a> {
1040            Fixture(&'a FixtureDecl),
1041            Type(&'a TypeDecl),
1042            Const(&'a ConstDecl),
1043            Fn(&'a FnDecl),
1044            Case(&'a Case),
1045            Property(&'a PropertyDecl),
1046        }
1047        let mut members: Vec<(usize, Member)> = fixtures
1048            .iter()
1049            .map(|f| (f.span.start, Member::Fixture(f)))
1050            .chain(types.iter().map(|t| (t.span.start, Member::Type(t))))
1051            .chain(consts.iter().map(|c| (c.span.start, Member::Const(c))))
1052            .chain(fns.iter().map(|f| (f.span.start, Member::Fn(f))))
1053            .chain(cases.iter().map(|c| (c.name_span.start, Member::Case(c))))
1054            .chain(
1055                properties
1056                    .iter()
1057                    .map(|p| (p.name_span.start, Member::Property(p))),
1058            )
1059            .collect();
1060        members.sort_by_key(|(start, _)| *start);
1061        for (_, member) in members {
1062            if !first {
1063                self.newline();
1064            }
1065            match member {
1066                Member::Fixture(f) => self.format_fixture_decl(f),
1067                Member::Type(t) => self.format_type_decl(t),
1068                Member::Const(c) => self.format_const_decl(c),
1069                Member::Fn(f) => self.format_fn_decl(f),
1070                Member::Case(c) => self.format_case(c),
1071                Member::Property(p) => self.format_property(p),
1072            }
1073            first = false;
1074        }
1075        self.emit_trailing_comments(trailing_comments);
1076    }
1077
1078    /// #2841: `fixture name = "path"` on its own line.
1079    fn format_fixture_decl(&mut self, f: &FixtureDecl) {
1080        self.emit_leading_comments(&f.trivia.leading);
1081        if let Some(doc) = &f.documentation {
1082            self.emit_doc(doc);
1083        }
1084        self.push(&format!(
1085            "fixture {} = \"{}\"",
1086            f.name.name,
1087            escape_string(&f.path)
1088        ));
1089        self.emit_trailing_comment_or_newline(f.trivia.trailing.as_deref());
1090    }
1091
1092    fn format_case(&mut self, c: &Case) {
1093        self.emit_leading_comments(&c.trivia.leading);
1094        if let Some(doc) = &c.documentation {
1095            self.emit_doc(doc);
1096        }
1097        let mut ch = format!("case \"{}\"", escape_string(&c.name));
1098        if let Some(tier) = c.tier {
1099            ch.push_str(&format!(" as {}", tier.as_str()));
1100        }
1101        ch.push(' ');
1102        self.push(&ch);
1103        self.format_case_block(&c.body, &c.envs, &c.stubs);
1104        self.newline();
1105    }
1106
1107    fn format_property(&mut self, p: &PropertyDecl) {
1108        self.emit_leading_comments(&p.trivia.leading);
1109        if let Some(doc) = &p.documentation {
1110            self.emit_doc(doc);
1111        }
1112        self.push(&format!("property \"{}\" {{", escape_string(&p.name)));
1113        self.newline();
1114        self.indented(|f| f.format_for_all(&p.forall));
1115        self.push("}");
1116        self.newline();
1117    }
1118
1119    /// v0.118: format a `stub` clause as a suite- or case-body line, with
1120    /// its leading comments / doc and a terminating newline (testing track
1121    /// slice 6).
1122    fn format_stub_clause(&mut self, pv: &StubClause) {
1123        self.emit_leading_comments(&pv.trivia.leading);
1124        if let Some(doc) = &pv.documentation {
1125            self.emit_doc(doc);
1126        }
1127        self.push(&stub_clause_to_string(pv));
1128        self.emit_trailing_comment_or_newline(pv.trivia.trailing.as_deref());
1129    }
1130
1131    /// #2134: format an `env { … }` clause as a suite- or case-body member,
1132    /// one `NAME = value` entry per line.
1133    fn format_env_clause(&mut self, e: &EnvClause) {
1134        self.emit_leading_comments(&e.trivia.leading);
1135        if let Some(doc) = &e.documentation {
1136            self.emit_doc(doc);
1137        }
1138        self.push("env {");
1139        self.newline();
1140        self.indented(|f| {
1141            for entry in &e.entries {
1142                f.push(&format!(
1143                    "{} = {}",
1144                    entry.name.name,
1145                    expr_to_string(&entry.value)
1146                ));
1147                f.newline();
1148            }
1149        });
1150        self.push("}");
1151        self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1152    }
1153
1154    /// v0.118: format a `case` body, emitting its case-scoped `env` (#2134)
1155    /// and `stub` clauses as the leading lines inside the block, before the
1156    /// statements and tail. With neither this is exactly [`Self::format_block`].
1157    fn format_case_block(&mut self, b: &Block, envs: &[EnvClause], stubs: &[StubClause]) {
1158        if stubs.is_empty() && envs.is_empty() {
1159            self.format_block(b);
1160            return;
1161        }
1162        self.push("{");
1163        self.newline();
1164        self.indented(|f| {
1165            for e in envs {
1166                f.format_env_clause(e);
1167            }
1168            for pv in stubs {
1169                f.format_stub_clause(pv);
1170            }
1171            // Through `format_block_body`, so a `let … else` prints back as
1172            // written (#2010).
1173            f.format_block_body(b);
1174        });
1175        self.push("}");
1176    }
1177
1178    /// v0.114: format a `for all <bindings> [where <pred>] { … }` binder — the
1179    /// sole body of a `property`.
1180    fn format_for_all(&mut self, fa: &ForAll) {
1181        let bindings = fa
1182            .bindings
1183            .iter()
1184            .map(|b| format!("{}: {}", b.name.name, type_ref_to_string(&b.type_ref)))
1185            .collect::<Vec<_>>()
1186            .join(", ");
1187        let mut header = format!("for all {bindings}");
1188        if let Some(w) = &fa.where_pred {
1189            header.push_str(&format!(" where {}", expr_to_string(w)));
1190        }
1191        self.push(&format!("{header} "));
1192        self.format_block(&fa.body);
1193        self.newline();
1194    }
1195
1196    fn format_commons(&mut self, c: &Commons) {
1197        self.emit_leading_comments(&c.trivia.leading);
1198        if let Some(doc) = &c.documentation {
1199            self.emit_doc(doc);
1200        }
1201        let header = format!("commons {}", c.name.joined());
1202        match c.form {
1203            CommonsForm::Brace => {
1204                self.push(&header);
1205                self.push(" {");
1206                self.newline();
1207                self.indented(|f| {
1208                    f.format_commons_body(&c.uses, &c.items, &c.trailing_comments);
1209                });
1210                self.push("}");
1211                self.newline();
1212            }
1213            CommonsForm::Fragment => {
1214                self.push(&header);
1215                self.newline();
1216                self.newline();
1217                self.format_commons_body(&c.uses, &c.items, &c.trailing_comments);
1218            }
1219        }
1220    }
1221
1222    fn format_commons_body(
1223        &mut self,
1224        uses: &[UsesDecl],
1225        items: &[CommonsItem],
1226        trailing_comments: &[Comment],
1227    ) {
1228        let mut any_uses = false;
1229        for u in uses {
1230            self.header_comment_gap(any_uses, u.blank_before, &u.trivia.leading);
1231            self.emit_leading_comments(&u.trivia.leading);
1232            self.push(&format!("uses {}", u.target.joined()));
1233            self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1234            any_uses = true;
1235        }
1236        if any_uses && !items.is_empty() {
1237            self.newline();
1238        }
1239        let mut first = true;
1240        for item in items {
1241            if !first {
1242                self.newline();
1243            }
1244            self.format_item(item);
1245            first = false;
1246        }
1247        if !trailing_comments.is_empty() {
1248            // One blank line before trailing-file comments if anything
1249            // came before them.
1250            if !items.is_empty() || any_uses {
1251                self.newline();
1252            }
1253            self.emit_trailing_comments(trailing_comments);
1254        }
1255    }
1256
1257    fn format_context(&mut self, c: &Context) {
1258        self.emit_leading_comments(&c.trivia.leading);
1259        if let Some(doc) = &c.documentation {
1260            self.emit_doc(doc);
1261        }
1262        let header = format!("context {}", c.name.joined());
1263        match c.form {
1264            CommonsForm::Brace => {
1265                self.push(&header);
1266                self.push(" {");
1267                self.newline();
1268                self.indented(|f| {
1269                    f.format_context_body(
1270                        &c.uses,
1271                        &c.consumes,
1272                        &c.exports,
1273                        &c.items,
1274                        &c.removed_agents,
1275                        &c.trailing_comments,
1276                    );
1277                });
1278                self.push("}");
1279                self.newline();
1280            }
1281            CommonsForm::Fragment => {
1282                self.push(&header);
1283                self.newline();
1284                self.newline();
1285                self.format_context_body(
1286                    &c.uses,
1287                    &c.consumes,
1288                    &c.exports,
1289                    &c.items,
1290                    &c.removed_agents,
1291                    &c.trailing_comments,
1292                );
1293            }
1294        }
1295    }
1296
1297    /// Print one `consumes` clause in any of its three forms: whole-unit,
1298    /// aliased, or braced capability selection (v0.17 §3.3 — previously the
1299    /// braced form was silently dropped, a semantic-changing format).
1300    fn format_consumes(&mut self, c: &ConsumesDecl, any_before: bool) {
1301        self.header_comment_gap(any_before, c.blank_before, &c.trivia.leading);
1302        self.emit_leading_comments(&c.trivia.leading);
1303        match (&c.alias, &c.selected) {
1304            (Some(alias), _) => {
1305                self.push(&format!("consumes {} as {}", c.target.joined(), alias.name))
1306            }
1307            (None, Some(selected)) if selected.is_empty() => {
1308                self.push(&format!("consumes {} {{ }}", c.target.joined()));
1309            }
1310            (None, Some(selected)) => {
1311                let names: Vec<String> = selected
1312                    .iter()
1313                    .map(|i| match &i.alias {
1314                        Some(a) => format!("{} as {}", i.name.name, a.name),
1315                        None => i.name.name.clone(),
1316                    })
1317                    .collect();
1318                self.push(&format!(
1319                    "consumes {} {{ {} }}",
1320                    c.target.joined(),
1321                    names.join(", ")
1322                ));
1323            }
1324            (None, None) => self.push(&format!("consumes {}", c.target.joined())),
1325        }
1326        self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
1327    }
1328
1329    fn format_context_body(
1330        &mut self,
1331        uses: &[UsesDecl],
1332        consumes: &[ConsumesDecl],
1333        exports: &[ExportsDecl],
1334        items: &[CommonsItem],
1335        removed_agents: &[RemovedAgentDecl],
1336        trailing_comments: &[Comment],
1337    ) {
1338        let mut any_header = false;
1339        for u in uses {
1340            self.header_comment_gap(any_header, u.blank_before, &u.trivia.leading);
1341            self.emit_leading_comments(&u.trivia.leading);
1342            self.push(&format!("uses {}", u.target.joined()));
1343            self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1344            any_header = true;
1345        }
1346        for c in consumes {
1347            self.format_consumes(c, any_header);
1348            any_header = true;
1349        }
1350        for e in exports {
1351            self.header_comment_gap(any_header, e.blank_before, &e.trivia.leading);
1352            self.emit_leading_comments(&e.trivia.leading);
1353            self.format_exports(e);
1354            // exports may emit multi-line — the trailing comment goes on
1355            // its last line. Since format_exports already terminates with
1356            // a newline, splice the comment before it if present.
1357            if e.trivia.trailing.is_some() {
1358                self.emit_trailing_comment(e.trivia.trailing.as_deref());
1359            }
1360            any_header = true;
1361        }
1362        if any_header && (!items.is_empty() || !removed_agents.is_empty()) {
1363            self.newline();
1364        }
1365        let mut first = true;
1366        for item in items {
1367            if !first {
1368                self.newline();
1369            }
1370            self.format_item(item);
1371            first = false;
1372        }
1373        // State-migrations S3 (#2248): `removed agent` declarations, after the
1374        // live items (a canonical place; they carry no order among items).
1375        for r in removed_agents {
1376            if !first {
1377                self.newline();
1378            }
1379            self.emit_leading_comments(&r.trivia.leading);
1380            if let Some(doc) = &r.documentation {
1381                self.emit_doc(doc);
1382            }
1383            self.push(&format!("removed agent {}", r.name.name));
1384            self.emit_trailing_comment_or_newline(r.trivia.trailing.as_deref());
1385            first = false;
1386        }
1387        if !trailing_comments.is_empty() {
1388            if !items.is_empty() || !removed_agents.is_empty() || any_header {
1389                self.newline();
1390            }
1391            self.emit_trailing_comments(trailing_comments);
1392        }
1393    }
1394
1395    fn format_exports(&mut self, e: &ExportsDecl) {
1396        let vis = match e.kind {
1397            ExportKind::Type(Visibility::Opaque) => "opaque",
1398            ExportKind::Type(Visibility::Transparent) => "transparent",
1399            ExportKind::Capability => "capability",
1400        };
1401        // #1797: a comment anywhere in the list forces the multi-line form.
1402        let has_comments = !e.trailing_comments.is_empty()
1403            || e.names
1404                .iter()
1405                .any(|n| !n.trivia.leading.is_empty() || n.trivia.trailing.is_some());
1406        if e.names.is_empty() && !has_comments {
1407            self.push(&format!("exports {} {{}}", vis));
1408            self.newline();
1409            return;
1410        }
1411        // Single-line form if it fits.
1412        if !has_comments {
1413            let oneline = format!(
1414                "exports {} {{ {} }}",
1415                vis,
1416                e.names
1417                    .iter()
1418                    .map(|n| n.name.name.as_str())
1419                    .collect::<Vec<_>>()
1420                    .join(", ")
1421            );
1422            if self.fits(&oneline, 0) {
1423                self.push(&oneline);
1424                self.newline();
1425                return;
1426            }
1427        }
1428        // Multi-line form.
1429        self.push(&format!("exports {} {{", vis));
1430        self.newline();
1431        self.indented(|f| {
1432            for (i, n) in e.names.iter().enumerate() {
1433                f.emit_leading_comments(&n.trivia.leading);
1434                f.push(&n.name.name);
1435                if i + 1 < e.names.len() || f.opts.trailing_comma {
1436                    f.push(",");
1437                }
1438                f.emit_trailing_comment_or_newline(n.trivia.trailing.as_deref());
1439            }
1440            f.emit_trailing_comments(&e.trailing_comments);
1441        });
1442        self.push("}");
1443        self.newline();
1444    }
1445
1446    /// The rendered width of one indent level. A tab is counted as four
1447    /// columns for width estimation (the file stores one byte; editors render
1448    /// it at the reader's chosen width, so any fixed number is an estimate).
1449    fn indent_width(&self) -> usize {
1450        match self.opts.indent {
1451            IndentStyle::Tab => 4,
1452            IndentStyle::Spaces(n) => n as usize,
1453        }
1454    }
1455
1456    /// The column the next character pushed would land on. Everything already
1457    /// emitted on the current line counts — #963: measuring only
1458    /// `indent_level` (as this did before) made every fit test blind to the
1459    /// prefix its caller had already printed, so a body measured as "fits"
1460    /// while sitting behind `fn name(params) -> Ret ` routinely overflowed.
1461    fn current_column(&self) -> usize {
1462        if self.at_line_start {
1463            // `push` has yet to emit this line's indent; account for it here.
1464            return self.indent_level as usize * self.indent_width();
1465        }
1466        let line = match self.out.rfind('\n') {
1467            Some(i) => &self.out[i + 1..],
1468            None => self.out.as_str(),
1469        };
1470        display_width(line, self.indent_width())
1471    }
1472
1473    /// Does `candidate`, emitted at the current column, leave `reserve`
1474    /// further columns inside the line budget? `reserve` is the width of text
1475    /// the caller knows will follow on the same line — a closing `)`, a
1476    /// `-> Ret {` suffix, an arm's `,`. A multi-line candidate never "fits":
1477    /// its own line breaks are the decision the caller is trying to make.
1478    fn fits(&self, candidate: &str, reserve: usize) -> bool {
1479        if candidate.contains('\n') {
1480            return false;
1481        }
1482        let column =
1483            self.current_column() + display_width(candidate, self.indent_width()) + reserve;
1484        column <= self.opts.max_line_width as usize
1485    }
1486
1487    fn format_item(&mut self, item: &CommonsItem) {
1488        match item {
1489            CommonsItem::Type(t) => self.format_type_decl(t),
1490            CommonsItem::Fn(f) => self.format_fn_decl(f),
1491            CommonsItem::Capability(c) => self.format_capability(c),
1492            CommonsItem::Provider(p) => self.format_provider(p),
1493            CommonsItem::Service(s) => self.format_service(s),
1494            CommonsItem::Agent(a) => self.format_agent(a),
1495            CommonsItem::Actor(a) => self.format_actor(a),
1496            CommonsItem::Messages(m) => self.format_messages(m),
1497            CommonsItem::Event(e) => self.format_event_decl(e),
1498            CommonsItem::Asset(a) => self.format_asset_decl(a),
1499            CommonsItem::Embed(e) => self.format_embed_decl(e),
1500            CommonsItem::Const(c) => self.format_const_decl(c),
1501        }
1502    }
1503
1504    /// #1883, slice 1a: `asset name = "path"` on one line.
1505    fn format_asset_decl(&mut self, a: &AssetDecl) {
1506        self.emit_leading_comments(&a.trivia.leading);
1507        if let Some(doc) = &a.documentation {
1508            self.emit_doc(doc);
1509        }
1510        // #2618: the unit-private modifier.
1511        if a.private.is_some() {
1512            self.push("private ");
1513        }
1514        self.push(&format!(
1515            "asset {} = \"{}\"",
1516            a.name.name,
1517            escape_string(&a.path)
1518        ));
1519        if let Some((at, _)) = &a.at {
1520            self.push(&format!(" at \"{}\"", escape_string(at)));
1521        }
1522        self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
1523    }
1524
1525    /// #2387, slice 1: `embed name = "path"` on one line.
1526    fn format_embed_decl(&mut self, e: &EmbedDecl) {
1527        self.emit_leading_comments(&e.trivia.leading);
1528        if let Some(doc) = &e.documentation {
1529            self.emit_doc(doc);
1530        }
1531        // #2618: the unit-private modifier.
1532        if e.private.is_some() {
1533            self.push("private ");
1534        }
1535        self.push(&format!(
1536            "embed {} = \"{}\"",
1537            e.name.name,
1538            escape_string(&e.path)
1539        ));
1540        self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1541    }
1542
1543    /// #2617: `const Name: Type = <expr>`, the initialiser laid out like a
1544    /// `let` value (a long record construction breaks across lines).
1545    fn format_const_decl(&mut self, c: &ConstDecl) {
1546        self.emit_leading_comments(&c.trivia.leading);
1547        if let Some(doc) = &c.documentation {
1548            self.emit_doc(doc);
1549        }
1550        // The unit-private modifier.
1551        if c.private.is_some() {
1552            self.push("private ");
1553        }
1554        self.push("const ");
1555        self.push(&c.name.name);
1556        self.push(": ");
1557        self.format_type_ref(&c.ty);
1558        self.push(" = ");
1559        self.format_expr(&c.init);
1560        self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
1561    }
1562
1563    fn format_event_decl(&mut self, e: &EventDecl) {
1564        self.emit_leading_comments(&e.trivia.leading);
1565        if let Some(doc) = &e.documentation {
1566            self.emit_doc(doc);
1567        }
1568        self.push(&format!("event {}", e.name.name));
1569        // Events slice 3b (#978): an optional `@schema(N)` (and any other
1570        // future event annotation) — same loop as `format_messages`'s.
1571        for ann in &e.annotations {
1572            self.push(" ");
1573            self.push(&annotation_to_string(ann));
1574        }
1575        self.push(" = ");
1576        self.format_record_body(&e.body);
1577        self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1578    }
1579
1580    fn format_messages(&mut self, m: &MessagesDecl) {
1581        self.emit_leading_comments(&m.trivia.leading);
1582        if let Some(doc) = &m.documentation {
1583            self.emit_doc(doc);
1584        }
1585        // #2618: the unit-private modifier.
1586        if m.private.is_some() {
1587            self.push("private ");
1588        }
1589        self.push(&format!("messages \"{}\"", escape_string(&m.tag)));
1590        for ann in &m.annotations {
1591            self.push(" ");
1592            self.push(&annotation_to_string(ann));
1593        }
1594        self.push(" {");
1595        self.newline();
1596        self.indented(|f| {
1597            for entry in &m.entries {
1598                if let Some(doc) = &entry.documentation {
1599                    f.emit_doc(doc);
1600                }
1601                f.push(&format!(
1602                    "{} => {}",
1603                    literal_text(entry.code_span, &entry.code),
1604                    literal_text(entry.template_span, &entry.template)
1605                ));
1606                f.newline();
1607            }
1608        });
1609        self.push("}");
1610        self.emit_trailing_comment_or_newline(m.trivia.trailing.as_deref());
1611    }
1612
1613    // -- Type declarations --
1614
1615    fn format_type_decl(&mut self, t: &TypeDecl) {
1616        self.emit_leading_comments(&t.trivia.leading);
1617        if let Some(doc) = &t.documentation {
1618            self.emit_doc(doc);
1619        }
1620        // #2618: the unit-private modifier.
1621        if t.private.is_some() {
1622            self.push("private ");
1623        }
1624        // v0.157 (ADR 0183): `[A, B]` type parameters, spelled as on a function.
1625        let params = if t.type_params.is_empty() {
1626            String::new()
1627        } else {
1628            let names: Vec<String> = t.type_params.iter().map(type_param_text).collect();
1629            format!("[{}]", names.join(", "))
1630        };
1631        self.push(&format!("type {}{} = ", t.name.name, params));
1632        self.format_type_body(&t.body);
1633        if !t.derives.is_empty() {
1634            let names: Vec<&str> = t.derives.iter().map(|d| d.name.as_str()).collect();
1635            let clause = format!("derives {}", names.join(" + "));
1636            // A pipe-form sum ends on its last variant's line, which may carry
1637            // a comment, so the clause takes its own line under the variants.
1638            if matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| !v.payload.is_empty()))
1639            {
1640                self.indented(|f| {
1641                    f.newline();
1642                    f.push(&clause);
1643                });
1644            } else {
1645                self.push(&format!(" {clause}"));
1646            }
1647        }
1648        self.emit_trailing_comment_or_newline(t.trivia.trailing.as_deref());
1649    }
1650
1651    fn format_type_body(&mut self, body: &TypeBody) {
1652        match body {
1653            TypeBody::Refined {
1654                base, refinement, ..
1655            } => {
1656                self.push(base.name());
1657                if let Some(r) = refinement {
1658                    self.push(" where ");
1659                    self.format_refinement(r);
1660                }
1661            }
1662            TypeBody::Opaque {
1663                base, refinement, ..
1664            } => {
1665                self.push("opaque ");
1666                self.push(base.name());
1667                if let Some(r) = refinement {
1668                    self.push(" where ");
1669                    self.format_refinement(r);
1670                }
1671            }
1672            TypeBody::Record(r) => self.format_record_body(r),
1673            TypeBody::Sum(s) => self.format_sum_body(s),
1674        }
1675    }
1676
1677    fn format_refinement(&mut self, r: &Refinement) {
1678        for (i, p) in r.predicates.iter().enumerate() {
1679            if i > 0 {
1680                self.push(" && ");
1681            }
1682            self.format_pred(p);
1683        }
1684        // #2686: `@example(…)` after a type's or field's refinement.
1685        for ann in &r.annotations {
1686            self.push(" ");
1687            self.push(&annotation_to_string(ann));
1688        }
1689    }
1690
1691    fn format_pred(&mut self, p: &RefinementPred) {
1692        let arg = |n: i64| p.arg_text.clone().unwrap_or_else(|| n.to_string());
1693        match &p.kind {
1694            PredKind::Matches(re) => self.push(&format!(
1695                "Matches({})",
1696                literal_text(matches_argument_span(p), re)
1697            )),
1698            PredKind::InRange(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1699            PredKind::InRangeF(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1700            PredKind::InRangeD(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1701            PredKind::MinLength(n) => self.push(&format!("MinLength({})", arg(*n))),
1702            PredKind::MaxLength(n) => self.push(&format!("MaxLength({})", arg(*n))),
1703            PredKind::Length(n) => self.push(&format!("Length({})", arg(*n))),
1704            PredKind::NonNegative => self.push("NonNegative"),
1705            PredKind::Positive => self.push("Positive"),
1706            PredKind::NonEmpty => self.push("NonEmpty"),
1707            PredKind::IsoDate => self.push("IsoDate"),
1708            PredKind::Cron => self.push("Cron"),
1709        }
1710    }
1711
1712    fn format_record_body(&mut self, r: &RecordBody) {
1713        // A comment, or a field's doc (#1888), forces the multi-line form.
1714        let has_comments = !r.trailing_comments.is_empty()
1715            || r.fields.iter().any(|f| {
1716                !f.trivia.leading.is_empty()
1717                    || f.trivia.trailing.is_some()
1718                    || f.documentation.is_some()
1719            });
1720        if r.fields.is_empty() && !has_comments {
1721            self.push("{}");
1722            return;
1723        }
1724        // A braced declaration body always breaks, one field per line.
1725        self.push("{");
1726        self.newline();
1727        self.indented(|f| {
1728            for (i, field) in r.fields.iter().enumerate() {
1729                f.emit_leading_comments(&field.trivia.leading);
1730                if let Some(doc) = &field.documentation {
1731                    f.emit_doc(doc);
1732                }
1733                f.format_record_field(field);
1734                if i + 1 < r.fields.len() || f.opts.trailing_comma {
1735                    f.push(",");
1736                }
1737                f.emit_trailing_comment_or_newline(field.trivia.trailing.as_deref());
1738            }
1739            f.emit_trailing_comments(&r.trailing_comments);
1740        });
1741        self.push("}");
1742    }
1743
1744    fn format_record_field(&mut self, field: &RecordField) {
1745        // #3343: annotations stay on the field's line, before its name.
1746        for ann in &field.annotations {
1747            self.push(&format!("{} ", annotation_to_string(ann)));
1748        }
1749        self.push(&format!("{}: ", field.name.name));
1750        self.format_type_ref(&field.type_ref);
1751        if let Some(r) = &field.refinement {
1752            self.push(" where ");
1753            self.format_refinement(r);
1754        }
1755        if let Some(init) = &field.init {
1756            self.push(" = ");
1757            self.format_expr(init);
1758        }
1759    }
1760
1761    fn format_sum_body(&mut self, s: &SumBody) {
1762        // Two surface forms exist; we render the pipe form (clearest for both
1763        // variants with and without payload). enum form is only meaningful for
1764        // payloadless variants — round-trip preserves semantics either way.
1765        let any_payload = s.variants.iter().any(|v| !v.payload.is_empty());
1766        if !any_payload {
1767            // Enum-style. #1794: a comment forces the multi-line form, as in
1768            // a record body.
1769            let has_comments = !s.trailing_comments.is_empty()
1770                || s.variants.iter().any(|v| {
1771                    !v.trivia.leading.is_empty()
1772                        || v.trivia.trailing.is_some()
1773                        || v.documentation.is_some()
1774                });
1775            if !has_comments {
1776                let names: Vec<&str> = s.variants.iter().map(|v| v.name.name.as_str()).collect();
1777                let oneline = format!("enum {{ {} }}", names.join(", "));
1778                if self.fits(&oneline, 0) {
1779                    self.push(&oneline);
1780                    return;
1781                }
1782            }
1783            self.push("enum {");
1784            self.newline();
1785            self.indented(|f| {
1786                for (i, v) in s.variants.iter().enumerate() {
1787                    f.emit_leading_comments(&v.trivia.leading);
1788                    if let Some(doc) = &v.documentation {
1789                        f.emit_doc(doc);
1790                    }
1791                    f.push(&v.name.name);
1792                    if i + 1 < s.variants.len() || f.opts.trailing_comma {
1793                        f.push(",");
1794                    }
1795                    f.emit_trailing_comment_or_newline(v.trivia.trailing.as_deref());
1796                }
1797                f.emit_trailing_comments(&s.trailing_comments);
1798            });
1799            self.push("}");
1800            return;
1801        }
1802        // Pipe form: break after `=`, one indented `| Variant` per line.
1803        // #1794: a variant's end-of-line comment ends its line, so the next
1804        // variant needs no newline of its own.
1805        while self.out.ends_with(' ') {
1806            self.out.pop();
1807        }
1808        self.indented(|f| {
1809            for (i, v) in s.variants.iter().enumerate() {
1810                if i == 0 || s.variants[i - 1].trivia.trailing.is_none() {
1811                    f.newline();
1812                }
1813                f.emit_leading_comments(&v.trivia.leading);
1814                if let Some(doc) = &v.documentation {
1815                    f.emit_doc(doc);
1816                }
1817                f.push("| ");
1818                f.push(&v.name.name);
1819                if v.payload.iter().any(|p| p.documentation.is_some()) {
1820                    // #1888: a documented payload field puts each field on its
1821                    // own line, under its doc, as in a record body.
1822                    f.push("(");
1823                    f.newline();
1824                    let last = v.payload.len() - 1;
1825                    f.indented(|f| {
1826                        for (j, p) in v.payload.iter().enumerate() {
1827                            if let Some(doc) = &p.documentation {
1828                                f.emit_doc(doc);
1829                            }
1830                            f.push(&format!(
1831                                "{}: {}",
1832                                p.name.name,
1833                                type_ref_to_string(&p.type_ref)
1834                            ));
1835                            if j < last || f.opts.trailing_comma {
1836                                f.push(",");
1837                            }
1838                            f.newline();
1839                        }
1840                    });
1841                    f.push(")");
1842                } else if !v.payload.is_empty() {
1843                    f.push("(");
1844                    let parts: Vec<String> = v
1845                        .payload
1846                        .iter()
1847                        .map(|p| format!("{}: {}", p.name.name, type_ref_to_string(&p.type_ref)))
1848                        .collect();
1849                    f.push(&parts.join(", "));
1850                    f.push(")");
1851                }
1852                f.emit_trailing_comment(v.trivia.trailing.as_deref());
1853            }
1854            // v0.154 (ADR 0178): the trailing `embeds E as V, …` clause, on its
1855            // own line under the variants and the comments above it (#1794).
1856            // Only a variant followed by `embeds` can be last with a comment on
1857            // its line.
1858            if !s.embeds.is_empty() {
1859                if s.variants
1860                    .last()
1861                    .is_none_or(|v| v.trivia.trailing.is_none())
1862                {
1863                    f.newline();
1864                }
1865                f.emit_trailing_comments(&s.trailing_comments);
1866                let parts: Vec<String> = s
1867                    .embeds
1868                    .iter()
1869                    .map(|e| {
1870                        format!(
1871                            "{} as {}",
1872                            type_ref_to_string(&e.source_type),
1873                            e.variant.name
1874                        )
1875                    })
1876                    .collect();
1877                f.push(&format!("embeds {}", parts.join(", ")));
1878            }
1879        });
1880    }
1881
1882    fn format_type_ref(&mut self, t: &TypeRef) {
1883        self.push(&type_ref_to_string(t));
1884    }
1885
1886    // -- Function declarations --
1887
1888    fn format_fn_decl(&mut self, f: &FnDecl) {
1889        self.emit_leading_comments(&f.trivia.leading);
1890        if let Some(doc) = &f.documentation {
1891            self.emit_doc(doc);
1892        }
1893        // #2618: the unit-private modifier.
1894        if f.private.is_some() {
1895            self.push("private ");
1896        }
1897        self.push("fn ");
1898        self.push(&f.name.display());
1899        // v0.20a: `[A, B]` type parameters.
1900        if !f.type_params.is_empty() {
1901            let names: Vec<String> = f.type_params.iter().map(type_param_text).collect();
1902            self.push(&format!("[{}]", names.join(", ")));
1903        }
1904        // #2868: a context function's `given` clause follows the return type,
1905        // before any `where`, as a handler's does.
1906        let given_text = if f.given.is_empty() {
1907            String::new()
1908        } else {
1909            let names: Vec<String> = f.given.iter().map(cap_ref_src).collect();
1910            format!(" given {}", names.join(", "))
1911        };
1912        // A method's `where A: Eq` clause rides after the return type.
1913        let where_text = if f.where_bounds.is_empty() {
1914            String::new()
1915        } else {
1916            let entries: Vec<String> = f
1917                .where_bounds
1918                .iter()
1919                .map(|wb| format!("{}: {}", wb.param.name, bounds_text(&wb.bounds)))
1920                .collect();
1921            format!(" where {}", entries.join(", "))
1922        };
1923        // The signature tail that shares the parameter list's line: ` -> Ret`
1924        // plus the body's ` {` (a contract clause moves the body to its own
1925        // line, so only the return type counts then).
1926        let tail = format!(
1927            " -> {}{given_text}{where_text}",
1928            type_ref_to_string(&f.return_type)
1929        );
1930        let reserve = if f.requires.is_empty() && f.ensures.is_empty() {
1931            tail.chars().count() + " {".len()
1932        } else {
1933            tail.chars().count()
1934        };
1935        self.format_params(&f.params, f.has_self, reserve);
1936        self.push(" -> ");
1937        self.format_type_ref(&f.return_type);
1938        self.push(&given_text);
1939        self.push(&where_text);
1940        // v0.115: contract clauses on their own indented lines between the
1941        // return type and the body (`requires`/`ensures <name>: <pred>`).
1942        if f.requires.is_empty() && f.ensures.is_empty() {
1943            self.push(" ");
1944        } else {
1945            self.newline();
1946            self.indented(|f2| {
1947                for c in &f.requires {
1948                    f2.push(&format!(
1949                        "requires {}: {}",
1950                        c.name.name,
1951                        expr_to_string(&c.predicate)
1952                    ));
1953                    f2.newline();
1954                }
1955                for c in &f.ensures {
1956                    f2.push(&format!(
1957                        "ensures {}: {}",
1958                        c.name.name,
1959                        expr_to_string(&c.predicate)
1960                    ));
1961                    f2.newline();
1962                }
1963            });
1964        }
1965        self.format_block_multiline(&f.body);
1966        self.emit_trailing_comment_or_newline(f.trivia.trailing.as_deref());
1967    }
1968
1969    /// Emit a parameter list. `reserve` is the width of the signature tail that
1970    /// will follow it on the same line — `-> Ret`, any `by`/`given` clauses,
1971    /// and the body's opening brace — so a list that only "fits" by ignoring
1972    /// what comes after it wraps instead (#963).
1973    fn format_params(&mut self, params: &[Param], has_self: bool, reserve: usize) {
1974        let mut rendered: Vec<String> = Vec::new();
1975        if has_self {
1976            rendered.push("self".to_string());
1977        }
1978        // `params` never includes `self` — it is tracked separately via the
1979        // `has_self` flag (see parser.rs parse_fn_decl).
1980        for p in params {
1981            rendered.push(format!(
1982                "{}: {}",
1983                p.name.name,
1984                type_ref_to_string(&p.type_ref)
1985            ));
1986        }
1987        let oneline = format!("({})", rendered.join(", "));
1988        // An empty list has nothing to wrap onto; `()` always stays put.
1989        if rendered.is_empty() || self.fits(&oneline, reserve) {
1990            self.push(&oneline);
1991            return;
1992        }
1993        // Wrapping moves the reserved tail onto the `)` line. When that line
1994        // would overflow anyway — a `given` list long enough on its own — the
1995        // wrap costs lines and buys nothing, so keep the single-line form.
1996        let closing_line = self.indent_level as usize * self.indent_width() + 1 + reserve;
1997        if closing_line > self.opts.max_line_width as usize {
1998            self.push(&oneline);
1999            return;
2000        }
2001        // Multi-line params.
2002        self.push("(");
2003        self.newline();
2004        self.indented(|f| {
2005            for (i, r) in rendered.iter().enumerate() {
2006                f.push(r);
2007                // Parameter lists — unlike records, enum/sum variants, agent
2008                // state fields and exports — do NOT accept a trailing comma in
2009                // the grammar, so never emit one here regardless of the
2010                // `trailing_comma` option, or the wrapped output fails to
2011                // re-parse.
2012                if i + 1 < rendered.len() {
2013                    f.push(",");
2014                }
2015                f.newline();
2016            }
2017        });
2018        self.push(")");
2019    }
2020
2021    // -- Capability / provider / service / agent (v0.5) --
2022
2023    fn format_capability(&mut self, c: &CapabilityDecl) {
2024        self.emit_leading_comments(&c.trivia.leading);
2025        if let Some(doc) = &c.documentation {
2026            self.emit_doc(doc);
2027        }
2028        // S4a (#1966): a derived capability is one line, its options after the
2029        // base, space-separated as on a `store` field.
2030        if let Some(d) = &c.derived {
2031            self.push(&format!("capability {} = {}", c.name.name, d.base.name));
2032            for ann in &d.annotations {
2033                self.push(&format!(" {}", annotation_to_string(ann)));
2034            }
2035            self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
2036            return;
2037        }
2038        self.push(&format!("capability {} {{", c.name.name));
2039        self.newline();
2040        self.indented(|f| {
2041            for op in &c.ops {
2042                f.emit_leading_comments(&op.trivia.leading);
2043                if let Some(doc) = &op.documentation {
2044                    f.emit_doc(doc);
2045                }
2046                f.push("fn ");
2047                f.push(&op.name.name);
2048                // #926: `[T, …]` type parameters on the op itself.
2049                if !op.type_params.is_empty() {
2050                    let names: Vec<String> = op.type_params.iter().map(type_param_text).collect();
2051                    f.push(&format!("[{}]", names.join(", ")));
2052                }
2053                let reserve = 4 + type_ref_to_string(&op.return_type).chars().count();
2054                f.format_params(&op.params, false, reserve);
2055                f.push(" -> ");
2056                f.format_type_ref(&op.return_type);
2057                // #3458: internal annotations stay on the operation's line.
2058                for ann in &op.annotations {
2059                    f.push(&format!(" {}", annotation_to_string(ann)));
2060                }
2061                f.emit_trailing_comment_or_newline(op.trivia.trailing.as_deref());
2062            }
2063            // #1756: the comments before the closing `}`, after a blank line.
2064            if !c.trailing_comments.is_empty() {
2065                if !c.ops.is_empty() {
2066                    f.newline();
2067                }
2068                f.emit_trailing_comments(&c.trailing_comments);
2069            }
2070        });
2071        self.push("}");
2072        self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
2073    }
2074
2075    fn format_provider(&mut self, p: &ProviderDecl) {
2076        self.emit_leading_comments(&p.trivia.leading);
2077        if let Some(doc) = &p.documentation {
2078            self.emit_doc(doc);
2079        }
2080        self.push(&format!(
2081            "provides {} = {}",
2082            p.capability.name, p.provider_name.name
2083        ));
2084        if !p.given.is_empty() {
2085            self.push(" given ");
2086            let names: Vec<String> = p.given.iter().map(cap_ref_src).collect();
2087            self.push(&names.join(", "));
2088        }
2089        // v0.17: an external provider (inside an adapter) has no body.
2090        if p.external {
2091            self.emit_trailing_comment_or_newline(p.trivia.trailing.as_deref());
2092            return;
2093        }
2094        self.push(" {");
2095        self.newline();
2096        self.indented(|f| {
2097            for (i, op) in p.ops.iter().enumerate() {
2098                if i > 0 {
2099                    f.newline();
2100                }
2101                f.emit_leading_comments(&op.trivia.leading);
2102                f.push("fn ");
2103                f.push(&op.name.name);
2104                let reserve = 4 + type_ref_to_string(&op.return_type).chars().count() + 2;
2105                f.format_params(&op.params, false, reserve);
2106                f.push(" -> ");
2107                f.format_type_ref(&op.return_type);
2108                f.push(" ");
2109                f.format_block_multiline(&op.body);
2110                f.emit_trailing_comment_or_newline(op.trivia.trailing.as_deref());
2111            }
2112        });
2113        self.push("}");
2114        self.emit_trailing_comment_or_newline(p.trivia.trailing.as_deref());
2115    }
2116
2117    fn format_service(&mut self, s: &ServiceDecl) {
2118        self.emit_leading_comments(&s.trivia.leading);
2119        if let Some(doc) = &s.documentation {
2120            self.emit_doc(doc);
2121        }
2122        let from = match &s.protocol {
2123            ServiceProtocol::Call => String::new(),
2124            ServiceProtocol::Http => " from http".to_string(),
2125            ServiceProtocol::Cron => " from cron".to_string(),
2126            ServiceProtocol::Queue { name } => {
2127                format!(" from queue(\"{}\")", escape_string(name))
2128            }
2129            ServiceProtocol::Email { address } => {
2130                format!(" from email(\"{}\")", escape_string(address))
2131            }
2132            ServiceProtocol::WebSocket { in_type, out_type } => {
2133                format!(
2134                    " from websocket(in: {}, out: {})",
2135                    type_ref_to_string(in_type),
2136                    type_ref_to_string(out_type)
2137                )
2138            }
2139            ServiceProtocol::Events {
2140                event_type,
2141                pattern,
2142                schema_dispatch,
2143            } => {
2144                let header = match pattern {
2145                    Some(p) => format!(
2146                        " from Events({} {})",
2147                        type_ref_to_string(event_type),
2148                        event_pattern_src(p)
2149                    ),
2150                    None => format!(" from Events({})", type_ref_to_string(event_type)),
2151                };
2152                match schema_dispatch {
2153                    Some(d) => format!("{header} {}", schema_dispatch_src(d)),
2154                    None => header,
2155                }
2156            }
2157        };
2158        // v0.155: the optional service-level `by`/`given` defaults follow the
2159        // protocol on the header, `by` first — the ambient contract every handler
2160        // inherits unless it declares its own.
2161        let mut header = format!("service {}{}", s.name.name, from);
2162        if let Some(by) = &s.default_by {
2163            header.push_str(&format!(" {}", by_clause_src(by)));
2164        }
2165        if !s.default_given.is_empty() {
2166            let names: Vec<String> = s.default_given.iter().map(cap_ref_src).collect();
2167            header.push_str(&format!(" given {}", names.join(", ")));
2168        }
2169        self.push(&format!("{header} {{"));
2170        self.newline();
2171        self.indented(|f| {
2172            // v0.131/v0.141/v0.142: the CORS, security, and limits policies are
2173            // header-position sections, before the handlers (mirroring the agent
2174            // phase order). A canonical order — `cors`, then `security`, then
2175            // `limits` — with a blank line between each section.
2176            if let Some(cors) = &s.cors {
2177                f.format_cors_policy(cors);
2178                if s.security.is_some()
2179                    || s.limits.is_some()
2180                    || s.json.is_some()
2181                    || !s.handlers.is_empty()
2182                {
2183                    f.newline();
2184                }
2185            }
2186            if let Some(security) = &s.security {
2187                f.format_security_policy(security);
2188                if s.limits.is_some() || s.json.is_some() || !s.handlers.is_empty() {
2189                    f.newline();
2190                }
2191            }
2192            if let Some(limits) = &s.limits {
2193                f.format_limits_policy(limits);
2194                if s.json.is_some() || !s.handlers.is_empty() {
2195                    f.newline();
2196                }
2197            }
2198            if let Some(json) = &s.json {
2199                f.format_json_policy(json);
2200                if !s.handlers.is_empty() {
2201                    f.newline();
2202                }
2203            }
2204            for (i, h) in s.handlers.iter().enumerate() {
2205                if i > 0 {
2206                    f.newline();
2207                }
2208                f.format_handler(h);
2209            }
2210            // #1756: the comments before the closing `}`, after a blank line.
2211            if !s.trailing_comments.is_empty() {
2212                if !s.handlers.is_empty()
2213                    || s.cors.is_some()
2214                    || s.security.is_some()
2215                    || s.limits.is_some()
2216                    || s.json.is_some()
2217                {
2218                    f.newline();
2219                }
2220                f.emit_trailing_comments(&s.trailing_comments);
2221            }
2222        });
2223        self.push("}");
2224        self.emit_trailing_comment_or_newline(s.trivia.trailing.as_deref());
2225    }
2226
2227    /// Format a `cors { }` policy section (v0.131). One `name: value` field per
2228    /// line, with a trailing comma, mirroring a record construction.
2229    fn format_cors_policy(&mut self, cors: &CorsPolicy) {
2230        let fields: Vec<_> = cors
2231            .fields
2232            .iter()
2233            .map(|f| (&f.name, &f.value, &f.trivia))
2234            .collect();
2235        self.format_policy("cors", &cors.trivia, &fields, &cors.trailing_comments);
2236    }
2237
2238    /// Format a `security { }` policy section (v0.141), as `format_cors_policy`.
2239    fn format_security_policy(&mut self, security: &SecurityPolicy) {
2240        let fields: Vec<_> = security
2241            .fields
2242            .iter()
2243            .map(|f| (&f.name, &f.value, &f.trivia))
2244            .collect();
2245        self.format_policy(
2246            "security",
2247            &security.trivia,
2248            &fields,
2249            &security.trailing_comments,
2250        );
2251    }
2252
2253    /// Format a `limits { }` policy section (v0.142), as `format_cors_policy`. A
2254    /// `maxBody` value keeps its as-written `_` digit separators (the `IntLit`
2255    /// lexeme).
2256    fn format_limits_policy(&mut self, limits: &LimitsPolicy) {
2257        let fields: Vec<_> = limits
2258            .fields
2259            .iter()
2260            .map(|f| (&f.name, &f.value, &f.trivia))
2261            .collect();
2262        self.format_policy("limits", &limits.trivia, &fields, &limits.trailing_comments);
2263    }
2264
2265    /// Format a `json { }` policy section (#2858), as `format_cors_policy`.
2266    fn format_json_policy(&mut self, json: &JsonPolicy) {
2267        let fields: Vec<_> = json
2268            .fields
2269            .iter()
2270            .map(|f| (&f.name, &f.value, &f.trivia))
2271            .collect();
2272        self.format_policy("json", &json.trivia, &fields, &json.trailing_comments);
2273    }
2274
2275    /// A `cors`/`security`/`limits` policy: `keyword {`, one `name: value,` field
2276    /// per line, `}`. #1786: each field's comments, the comments before `}`, and
2277    /// the comment after it are printed in place.
2278    fn format_policy(
2279        &mut self,
2280        keyword: &str,
2281        trivia: &Trivia,
2282        fields: &[(&Ident, &Expr, &Trivia)],
2283        trailing_comments: &[Comment],
2284    ) {
2285        self.emit_leading_comments(&trivia.leading);
2286        self.push(&format!("{keyword} {{"));
2287        self.newline();
2288        self.indented(|f| {
2289            for (name, value, field_trivia) in fields {
2290                f.emit_leading_comments(&field_trivia.leading);
2291                f.push(&format!("{}: ", name.name));
2292                f.format_expr_at(value, 0, 1);
2293                f.push(",");
2294                f.emit_trailing_comment_or_newline(field_trivia.trailing.as_deref());
2295            }
2296            f.emit_trailing_comments(trailing_comments);
2297        });
2298        self.push("}");
2299        self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2300    }
2301
2302    fn format_agent(&mut self, a: &AgentDecl) {
2303        self.emit_leading_comments(&a.trivia.leading);
2304        if let Some(doc) = &a.documentation {
2305            self.emit_doc(doc);
2306        }
2307        match &a.replaces {
2308            Some(old) => self.push(&format!("agent {} replaces {} {{", a.name.name, old.name)),
2309            None => self.push(&format!("agent {} {{", a.name.name)),
2310        }
2311        self.newline();
2312        self.indented(|f| {
2313            // key
2314            f.emit_leading_comments(&a.key_trivia.leading);
2315            f.push(&format!(
2316                "key {}: {}",
2317                a.key_name.name,
2318                type_ref_to_string(&a.key_type)
2319            ));
2320            f.emit_trailing_comment_or_newline(a.key_trivia.trailing.as_deref());
2321            f.newline();
2322            // storage (v0.81, storage track): the agent's `store` fields.
2323            for sf in &a.store_fields {
2324                f.format_store_field(sf);
2325            }
2326            // v0.80: invariants form a phase between the storage fields and the
2327            // handlers.
2328            for inv in &a.invariants {
2329                f.newline();
2330                f.format_invariant(inv);
2331            }
2332            // v0.116: step invariants form part of the same phase, beside the
2333            // snapshot invariants.
2334            for tr in &a.transitions {
2335                f.newline();
2336                f.format_transition(tr);
2337            }
2338            // State-migrations S2 (#2224): `migrate` steps, in the same phase.
2339            for m in &a.migrations {
2340                f.newline();
2341                f.format_migrate(m);
2342            }
2343            // handlers
2344            for h in &a.handlers {
2345                f.newline();
2346                f.format_handler(h);
2347            }
2348            // #1756: the comments before the closing `}`, after a blank line.
2349            if !a.trailing_comments.is_empty() {
2350                f.newline();
2351                f.emit_trailing_comments(&a.trailing_comments);
2352            }
2353        });
2354        self.push("}");
2355        self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
2356    }
2357
2358    /// Format a `store` field (v0.81): `store <name>: <Kind> [= <init>]`, with
2359    /// its leading comments / doc, ending its line with the trailing comment
2360    /// or a bare newline, never both (#1859).
2361    fn format_store_field(&mut self, sf: &StoreField) {
2362        self.emit_leading_comments(&sf.trivia.leading);
2363        if let Some(doc) = &sf.documentation {
2364            self.emit_doc(doc);
2365        }
2366        self.push(&format!(
2367            "store {}: {}",
2368            sf.name.name,
2369            store_kind_to_string(&sf.kind)
2370        ));
2371        // v0.85 (ADR 0111): annotations follow the kind, one space-separated each.
2372        for ann in &sf.annotations {
2373            self.push(&format!(" {}", annotation_to_string(ann)));
2374        }
2375        if let Some(init) = &sf.init {
2376            self.push(" = ");
2377            self.format_expr(init);
2378        }
2379        self.emit_trailing_comment_or_newline(sf.trivia.trailing.as_deref());
2380    }
2381
2382    /// Format an agent invariant (v0.80): the name on one line, the predicate
2383    /// indented beneath, matching the §14 worked examples.
2384    fn format_invariant(&mut self, inv: &Invariant) {
2385        self.emit_leading_comments(&inv.trivia.leading);
2386        if let Some(doc) = &inv.documentation {
2387            self.emit_doc(doc);
2388        }
2389        self.push(&format!("invariant {}:", inv.name.name));
2390        self.newline();
2391        self.indented(|f| {
2392            f.format_expr(&inv.predicate);
2393        });
2394        self.emit_trailing_comment_or_newline(inv.trivia.trailing.as_deref());
2395    }
2396
2397    /// Format an agent step invariant (v0.116): `transition <name>:` with the
2398    /// `old`/`new` predicate indented beneath, mirroring [`format_invariant`].
2399    fn format_transition(&mut self, tr: &Transition) {
2400        self.emit_leading_comments(&tr.trivia.leading);
2401        if let Some(doc) = &tr.documentation {
2402            self.emit_doc(doc);
2403        }
2404        self.push(&format!("transition {}:", tr.name.name));
2405        self.newline();
2406        self.indented(|f| {
2407            f.format_expr(&tr.predicate);
2408        });
2409        self.emit_trailing_comment_or_newline(tr.trivia.trailing.as_deref());
2410    }
2411
2412    /// Format a migration step (state-migrations S2, #2224):
2413    /// `migrate from N (old: T) { … }`, one item per line.
2414    fn format_migrate(&mut self, m: &MigrateDecl) {
2415        self.emit_leading_comments(&m.trivia.leading);
2416        if let Some(doc) = &m.documentation {
2417            self.emit_doc(doc);
2418        }
2419        self.push(&format!("migrate from {}", m.from));
2420        if let Some(old) = &m.old {
2421            self.push(&format!(
2422                " ({}: {})",
2423                old.name.name,
2424                type_ref_to_string(&old.type_ref)
2425            ));
2426        }
2427        self.push(" {");
2428        self.newline();
2429        self.indented(|f| {
2430            for item in &m.items {
2431                let trivia = match item {
2432                    MigrateItem::Let(l) => &l.trivia,
2433                    MigrateItem::Assign(a) => &a.trivia,
2434                    MigrateItem::Drop(d) => &d.trivia,
2435                };
2436                f.emit_leading_comments(&trivia.leading);
2437                match item {
2438                    MigrateItem::Let(l) => {
2439                        f.push("let ");
2440                        f.push(&l.name.name);
2441                        if let Some(t) = &l.type_annot {
2442                            f.push(": ");
2443                            f.format_type_ref(t);
2444                        }
2445                        f.push(" = ");
2446                        f.format_expr(&l.value);
2447                    }
2448                    MigrateItem::Assign(a) => {
2449                        f.push(&a.target.name);
2450                        f.push(" := ");
2451                        f.format_expr(&a.value);
2452                    }
2453                    MigrateItem::Drop(d) => f.push(&format!("drop {}", d.field.name)),
2454                }
2455                f.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2456            }
2457            if !m.trailing_comments.is_empty() {
2458                f.emit_trailing_comments(&m.trailing_comments);
2459            }
2460        });
2461        self.push("}");
2462        self.emit_trailing_comment_or_newline(m.trivia.trailing.as_deref());
2463    }
2464
2465    fn format_actor(&mut self, a: &ActorDecl) {
2466        self.emit_leading_comments(&a.trivia.leading);
2467        if let Some(doc) = &a.documentation {
2468            self.emit_doc(doc);
2469        }
2470        if let Some(r) = &a.refinement {
2471            // Reserved refinement form: `actor Name = Base where <predicate>`.
2472            self.push(&format!(
2473                "actor {} = {} where {}",
2474                a.name.name,
2475                r.base.name,
2476                expr_to_string(&r.predicate)
2477            ));
2478        } else {
2479            // Normal form: `actor Name { auth = Scheme(, identity = Type)? }`.
2480            let auth = a.auth.as_ref().map(|i| i.name.as_str()).unwrap_or("None");
2481            let args: Vec<String> = a
2482                .auth_config
2483                .iter()
2484                .map(|arg| match &arg.value {
2485                    bynk_syntax::ast::SchemeArgValue::Str(s) => {
2486                        format!("{} = \"{}\"", arg.key.name, escape_string(s))
2487                    }
2488                    bynk_syntax::ast::SchemeArgValue::Int(n) => {
2489                        format!("{} = {n}", arg.key.name)
2490                    }
2491                    bynk_syntax::ast::SchemeArgValue::Duration { value, unit, .. } => {
2492                        format!("{} = {value}.{}", arg.key.name, unit.name_for(*value))
2493                    }
2494                    bynk_syntax::ast::SchemeArgValue::Ident(id) => {
2495                        format!("{} = {id}", arg.key.name)
2496                    }
2497                })
2498                .collect();
2499            let config = if args.is_empty() {
2500                String::new()
2501            } else {
2502                format!("({})", args.join(", "))
2503            };
2504            let identity = a.identity.as_ref().map(type_ref_to_string);
2505            let oneline = format!(
2506                "actor {} {{ auth = {auth}{config}{} }}",
2507                a.name.name,
2508                identity
2509                    .as_ref()
2510                    .map(|id| format!(", identity = {id}"))
2511                    .unwrap_or_default()
2512            );
2513            // An OIDC-style scheme carries issuer / audience / JWKS URLs that
2514            // blow past any line budget on one line (#963): open the braces and
2515            // give each scheme argument its own line. The test ignores comments,
2516            // so commenting an actor never changes how its arguments break.
2517            let break_args = !args.is_empty() && !self.fits(&oneline, 0);
2518            // #1797: a comment anywhere in the body forces the multi-line form.
2519            let has_comments = !a.trailing_comments.is_empty()
2520                || [&a.auth_trivia, &a.identity_trivia]
2521                    .iter()
2522                    .any(|t| !t.leading.is_empty() || t.trailing.is_some());
2523            if !break_args && !has_comments {
2524                self.push(&oneline);
2525            } else {
2526                self.push(&format!("actor {} {{", a.name.name));
2527                self.newline();
2528                self.indented(|f| {
2529                    f.emit_leading_comments(&a.auth_trivia.leading);
2530                    if break_args {
2531                        f.push(&format!("auth = {auth}("));
2532                        f.newline();
2533                        f.indented(|f2| {
2534                            for (i, arg) in args.iter().enumerate() {
2535                                f2.push(arg);
2536                                if i + 1 < args.len() {
2537                                    f2.push(",");
2538                                }
2539                                f2.newline();
2540                            }
2541                        });
2542                        f.push(")");
2543                    } else {
2544                        f.push(&format!("auth = {auth}{config}"));
2545                    }
2546                    if let Some(id) = &identity {
2547                        // `identity` is a sibling of `auth`, so its comma stays
2548                        // with `auth`'s line and it starts a new line.
2549                        f.push(",");
2550                        f.emit_trailing_comment_or_newline(a.auth_trivia.trailing.as_deref());
2551                        f.emit_leading_comments(&a.identity_trivia.leading);
2552                        f.push(&format!("identity = {id}"));
2553                        f.emit_trailing_comment_or_newline(a.identity_trivia.trailing.as_deref());
2554                    } else {
2555                        f.emit_trailing_comment_or_newline(a.auth_trivia.trailing.as_deref());
2556                    }
2557                    f.emit_trailing_comments(&a.trailing_comments);
2558                });
2559                self.push("}");
2560            }
2561        }
2562        self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
2563    }
2564
2565    fn format_handler(&mut self, h: &Handler) {
2566        self.emit_leading_comments(&h.trivia.leading);
2567        if let Some(doc) = &h.documentation {
2568            self.emit_doc(doc);
2569        }
2570        // v0.140 (ADR 0163): handler-position annotations (`@cache(…)`) print one
2571        // per line above the `on`, mirroring how decorators read in source. Each is
2572        // rendered by the shared `annotation_to_string` used for `store` fields.
2573        for ann in &h.annotations {
2574            self.push(&annotation_to_string(ann));
2575            self.newline();
2576        }
2577        // The handler kind prefix: `on call`, `on http METHOD "path"`, or
2578        // `on cron("expr")`. Agent `on call` handlers carry a method name.
2579        match &h.kind {
2580            HandlerKind::Call => {
2581                self.push("on call");
2582                if let Some(m) = &h.method_name {
2583                    self.push(&format!(" {}", m.name));
2584                }
2585            }
2586            HandlerKind::Http { method, path } => {
2587                // Trailing space: the path string is followed by the param list,
2588                // which reads better separated (`… "/path" (params)`).
2589                self.push(&format!(
2590                    "on {}(\"{}\") ",
2591                    method.as_str(),
2592                    escape_string(path)
2593                ));
2594            }
2595            HandlerKind::Cron { expr } => {
2596                self.push(&format!("on schedule(\"{}\") ", escape_string(expr)));
2597            }
2598            HandlerKind::Message => {
2599                self.push("on message");
2600            }
2601            HandlerKind::Open => {
2602                self.push("on open");
2603            }
2604            HandlerKind::Close => {
2605                self.push("on close");
2606            }
2607            HandlerKind::Event => {
2608                self.push("on event");
2609            }
2610            HandlerKind::Rejected => {
2611                self.push("on rejected");
2612            }
2613        }
2614        // The param list follows the kind prefix directly — `on call(params)`,
2615        // `on open(params)` — while the Http/Cron prefixes already emit a trailing
2616        // space (`on GET("/x") (params)`). (v0.155: the `by` clause no longer sits
2617        // here, so no separating space is needed.)
2618        // Everything from `-> Ret` to the body's `{` shares the parameter
2619        // list's line and none of it can wrap (the `given` list in particular
2620        // is newline-sensitive), so the whole tail is reserved up front and the
2621        // parameters are what gives (#963).
2622        let mut tail = format!(" -> {}", type_ref_to_string(&h.return_type));
2623        if let Some(by) = &h.by_clause {
2624            tail.push_str(&format!(" {}", by_clause_src(by)));
2625        }
2626        if !h.given.is_empty() {
2627            let names: Vec<String> = h.given.iter().map(cap_ref_src).collect();
2628            tail.push_str(&format!(" given {}", names.join(", ")));
2629        }
2630        self.format_params(&h.params, false, tail.chars().count() + " {".len());
2631        self.push(&tail);
2632        self.push(" ");
2633        self.format_block_multiline(&h.body);
2634        self.emit_trailing_comment_or_newline(h.trivia.trailing.as_deref());
2635    }
2636
2637    // -- Blocks, statements, expressions --
2638
2639    fn format_block(&mut self, b: &Block) {
2640        self.format_block_with_reserve(b, 0);
2641    }
2642
2643    /// Format a block, knowing that `reserve` columns of text will follow its
2644    /// closing brace on the same line (` else {` on an `if`'s then-branch, an
2645    /// arm's `,`). Only a block that fits *including* that tail stays inline.
2646    fn format_block_with_reserve(&mut self, b: &Block, reserve: usize) {
2647        // A block with no statements, no trivia, and a simple tail
2648        // expression can be emitted inline if it fits; otherwise multi-line.
2649        let tail_oneline = expr_to_string(&b.tail);
2650        let any_stmt_trivia = b.statements.iter().any(|s| !statement_trivia(s).is_empty());
2651        if b.statements.is_empty()
2652            && b.tail_leading_comments.is_empty()
2653            && !any_stmt_trivia
2654            && !holds_comments(&b.tail)
2655            && self.fits(&format!("{{ {tail_oneline} }}"), reserve)
2656        {
2657            self.push("{ ");
2658            self.push(&tail_oneline);
2659            self.push(" }");
2660            return;
2661        }
2662        self.format_block_multiline(b);
2663    }
2664
2665    /// The multi-line block form: brace, one statement per indented line, the
2666    /// tail expression, closing brace. Split out of [`Self::format_block`] so
2667    /// the wrapped-expression printer can force it (#963) for an `if`/lambda
2668    /// body whose single-line form would overflow.
2669    fn format_block_multiline(&mut self, b: &Block) {
2670        // A body that is only the implicit unit prints as `{}`, not as an
2671        // open and close brace on separate lines around nothing.
2672        if b.statements.is_empty() && b.tail_leading_comments.is_empty() && omit_unit_tail(b) {
2673            self.push("{}");
2674            return;
2675        }
2676        self.push("{");
2677        self.newline();
2678        self.indented(|f| f.format_block_body(b));
2679        self.push("}");
2680    }
2681
2682    /// A block's statements and tail, one per line at the current indent.
2683    /// #2010: a `let … else` reaches the formatter desugared — a hidden
2684    /// binding, then a `match` tail whose first arm holds the rest of the
2685    /// block — so it is printed back as the author wrote it, and the rest of
2686    /// the block continues at this same indent.
2687    fn format_block_body(&mut self, b: &Block) {
2688        for stmt in &b.statements {
2689            let trivia = statement_trivia(stmt);
2690            self.emit_leading_comments(&trivia.leading);
2691            if let Some((l, effectful, le)) = let_else_binding(stmt)
2692                && let ExprKind::Match { arms, .. } = &b.tail.kind
2693                && let Some(MatchBody::Block(rest)) = arms.first().map(|a| &a.body)
2694            {
2695                self.format_let_else(l, effectful, le, arms);
2696                self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2697                self.format_block_body(rest);
2698                return;
2699            }
2700            self.format_statement(stmt);
2701            self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2702        }
2703        self.emit_leading_comments(&b.tail_leading_comments);
2704        if !omit_unit_tail(b) {
2705            self.format_expr(&b.tail);
2706            self.newline();
2707        }
2708    }
2709
2710    /// #2010: `let <pattern> (= | <-) <value> else <block>` or
2711    /// `… else match { <arms> }`, from the hidden binding `l` and the arms of
2712    /// the `match` it was desugared into (arm 0 is the pattern's).
2713    fn format_let_else(&mut self, l: &LetStmt, effectful: bool, le: &LetElse, arms: &[MatchArm]) {
2714        self.push("let ");
2715        self.push(&let_pattern_src(&arms[0].pattern));
2716        self.push(if effectful { " <- " } else { " = " });
2717        let principal = l
2718            .principal
2719            .as_ref()
2720            .map(|p| format!(" {}", call_site_actor_src(p)));
2721        let else_width = if le.form == LetElseForm::Plain {
2722            0
2723        } else {
2724            " else {".len()
2725        };
2726        let reserve = principal.as_deref().map_or(0, |p| p.chars().count()) + else_width;
2727        self.format_expr_at(&l.value, 0, reserve);
2728        if let Some(principal) = principal {
2729            self.push(&principal);
2730        }
2731        // #2654: the `else`-less form of an irrefutable record pattern.
2732        if le.form == LetElseForm::Plain {
2733            return;
2734        }
2735        self.push(" else ");
2736        match (le.form, arms.get(1).map(|a| &a.body)) {
2737            (LetElseForm::Block, Some(MatchBody::Block(otherwise))) => self.format_block(otherwise),
2738            _ => {
2739                self.push("match {");
2740                self.newline();
2741                self.indented(|f| f.format_arms(&arms[1..]));
2742                self.push("}");
2743            }
2744        }
2745    }
2746
2747    fn format_statement(&mut self, s: &Statement) {
2748        match s {
2749            Statement::Let(l) => {
2750                self.push("let ");
2751                self.push(&l.name.name);
2752                if let Some(t) = &l.type_annot {
2753                    self.push(": ");
2754                    self.format_type_ref(t);
2755                }
2756                self.push(" = ");
2757                self.format_expr(&l.value);
2758            }
2759            Statement::EffectLet(l) => {
2760                self.push("let ");
2761                self.push(&l.name.name);
2762                if let Some(t) = &l.type_annot {
2763                    self.push(": ");
2764                    self.format_type_ref(t);
2765                }
2766                self.push(" <- ");
2767                // The `by <Actor>` clause trails the value on the same line.
2768                let principal = l
2769                    .principal
2770                    .as_ref()
2771                    .map(|p| format!(" {}", call_site_actor_src(p)));
2772                let reserve = principal.as_deref().map_or(0, |p| p.chars().count());
2773                self.format_expr_at(&l.value, 0, reserve);
2774                if let Some(principal) = principal {
2775                    self.push(&principal);
2776                }
2777            }
2778            Statement::Expect(a) => {
2779                self.push("expect ");
2780                self.format_expr(&a.value);
2781                if let Some(snapshot) = &a.snapshot {
2782                    self.push(&format!(
2783                        " matches snapshot \"{}\"",
2784                        escape_string(&snapshot.name)
2785                    ));
2786                }
2787            }
2788            Statement::Do(d) => {
2789                self.push("do ");
2790                self.format_expr(&d.value);
2791            }
2792            Statement::Assign(a) => {
2793                self.push(&a.target.name);
2794                self.push(" := ");
2795                self.format_expr(&a.value);
2796            }
2797            Statement::Advance(a) => {
2798                self.push(&format!("advance {} by ", a.cap.name));
2799                self.format_expr(&a.amount);
2800            }
2801            Statement::Par(p) => {
2802                self.push("par {");
2803                self.newline();
2804                self.indented(|f| {
2805                    for stmt in &p.statements {
2806                        let trivia = statement_trivia(stmt);
2807                        f.emit_leading_comments(&trivia.leading);
2808                        f.format_statement(stmt);
2809                        f.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2810                    }
2811                    f.emit_leading_comments(&p.closing_comments);
2812                });
2813                self.push("}");
2814            }
2815        }
2816    }
2817
2818    fn format_expr(&mut self, e: &Expr) {
2819        self.format_expr_at(e, 0, 0);
2820    }
2821
2822    /// Emit `e` at the current column, breaking it across lines when its
2823    /// single-line form would overrun the line budget (#963).
2824    ///
2825    /// `parent_prec` is the enclosing operator's precedence, exactly as in
2826    /// [`expr_with_prec`] — it decides parenthesisation. `reserve` is the width
2827    /// of text the caller will emit after this expression on the same line (a
2828    /// closing `)`, an arm's `,`, ` else {`), so a sub-expression is not judged
2829    /// to fit on the strength of a line it does not in fact end.
2830    ///
2831    /// The flat form always wins when it fits: this only ever *adds* line
2832    /// breaks, and only at points the grammar accepts (verified by the
2833    /// round-trip guard in [`format_source`]).
2834    fn format_expr_at(&mut self, e: &Expr, parent_prec: u8, reserve: usize) {
2835        // `match` renders multi-line unconditionally, so it must go through the
2836        // indent-aware emitter rather than `expr_to_string` — the latter builds
2837        // a flat string with hardcoded single-tab arms that ignores the current
2838        // nesting depth (the closing brace and every arm would land at column
2839        // one regardless of how deeply the `match` is nested).
2840        if let ExprKind::Match { discriminant, arms } = &e.kind {
2841            self.format_match(discriminant, arms);
2842            return;
2843        }
2844        let flat = expr_with_prec(e, parent_prec);
2845        // A braced record literal with more than one item (several fields,
2846        // or a spread with overrides) always breaks, one per line, however
2847        // short.
2848        let braced_record = match &e.kind {
2849            ExprKind::RecordConstruction { fields, .. } => fields.len() > 1,
2850            ExprKind::RecordSpread { overrides, .. } => !overrides.is_empty(),
2851            _ => false,
2852        };
2853        // #3067: a list with a comment in it cannot be flattened.
2854        if !braced_record && !holds_comments(e) && self.fits(&flat, reserve) {
2855            self.push(&flat);
2856            return;
2857        }
2858        // Too wide. Re-emit broken across lines — inside the parentheses the
2859        // flat form would have added, if precedence calls for them.
2860        if needs_parens(e, parent_prec) {
2861            self.push("(");
2862            self.format_expr_broken(e, reserve + 1);
2863            self.push(")");
2864        } else {
2865            self.format_expr_broken(e, reserve);
2866        }
2867    }
2868
2869    /// The multi-line rendering of an expression that does not fit. Each arm
2870    /// breaks at a point the grammar tolerates a newline; anything with no such
2871    /// point (a long string literal, an identifier) falls through to the flat
2872    /// form, which simply overruns — the 100-column target is soft.
2873    fn format_expr_broken(&mut self, e: &Expr, reserve: usize) {
2874        match &e.kind {
2875            // `T { field: value, … }` — one field per line.
2876            ExprKind::RecordConstruction {
2877                type_name,
2878                fields,
2879                trivia,
2880            } if !fields.is_empty() || trivia.is_some() => {
2881                self.push(&format!("{} {{", type_name.name));
2882                self.format_field_inits(fields.iter(), None, trivia.as_deref());
2883            }
2884            // `T { ...base, field: value, … }` — the spread first, then the
2885            // overrides, one per line.
2886            ExprKind::RecordSpread {
2887                type_name,
2888                base,
2889                overrides,
2890                trivia,
2891            } => {
2892                match type_name {
2893                    Some(tn) => self.push(&format!("{} {{", tn.name)),
2894                    None => self.push("{"),
2895                }
2896                let spread = format!("...{}", expr_with_prec(base, 0));
2897                self.format_field_inits(overrides.iter(), Some(&spread), trivia.as_deref());
2898            }
2899            // A call's arguments, one per line. Unlike a record body an
2900            // argument list does NOT accept a trailing comma (the grammar
2901            // rejects it), so the wrapped form never emits one.
2902            ExprKind::Call {
2903                name,
2904                type_args,
2905                args,
2906                trivia,
2907            } if !args.is_empty() || trivia.is_some() => {
2908                self.push(&format!("{}{}(", name.name, type_args_src(type_args)));
2909                self.format_arg_list(args, trivia.as_deref(), reserve);
2910            }
2911            ExprKind::Val {
2912                type_ref,
2913                args,
2914                trivia,
2915            } if !args.is_empty() || trivia.is_some() => {
2916                self.push(&format!("Val[{}](", type_ref_to_string(type_ref)));
2917                self.format_arg_list(args, trivia.as_deref(), reserve);
2918            }
2919            // A `.`-chain: `receiver.a().b()` — kept on one line where the
2920            // overflow is an argument's, broken before each call where it is
2921            // the chain's own (see `format_chain`).
2922            ExprKind::MethodCall { .. } | ExprKind::FieldAccess { .. } => {
2923                self.format_chain(e, reserve);
2924            }
2925            // `[a, b, c]` — one element per line.
2926            // #3067: comments above an element, at the end of its line, and
2927            // before the `]` stay where they were.
2928            ExprKind::ListLit(elems, trivia) if !elems.is_empty() || trivia.is_some() => {
2929                self.push("[");
2930                self.newline();
2931                self.indented(|f| {
2932                    for (i, elem) in elems.iter().enumerate() {
2933                        let last = i + 1 == elems.len();
2934                        let item = trivia.as_ref().and_then(|t| t.items.get(i));
2935                        if let Some(item) = item {
2936                            f.emit_leading_comments(&item.leading);
2937                        }
2938                        // A trailing comment rides the line after the `,`, so
2939                        // the element only reserves room for the comma.
2940                        f.format_expr_at(elem, 0, if last { 0 } else { 1 });
2941                        if !last || f.opts.trailing_comma {
2942                            f.push(",");
2943                        }
2944                        let eol = item.and_then(|t| t.trailing.as_deref());
2945                        f.emit_trailing_comment_or_newline(eol);
2946                    }
2947                    if let Some(t) = trivia {
2948                        f.emit_trailing_comments(&t.closing);
2949                    }
2950                });
2951                self.push("]");
2952            }
2953            // A run of `&&` / `||` / `implies` breaks before each operator, per
2954            // the spec's "wraps at `&&`/`||` boundaries". Only these: a
2955            // continuation line starting with an arithmetic or comparison
2956            // operator does not re-attach to the line above on re-parse.
2957            ExprKind::BinOp(op, ..) if is_logical(*op) => {
2958                let prec = binop_prec(*op);
2959                let mut operands = Vec::new();
2960                flatten_binop(e, *op, &mut operands);
2961                self.format_expr_at(operands[0], prec, 0);
2962                self.indented(|f| {
2963                    for (i, operand) in operands.iter().enumerate().skip(1) {
2964                        f.newline();
2965                        f.push(&format!("{} ", op.name()));
2966                        let last = i + 1 == operands.len();
2967                        f.format_expr_at(operand, prec + 1, if last { reserve } else { 0 });
2968                    }
2969                });
2970            }
2971            // Any other binary operator stays on one line, but its operands may
2972            // still break internally (a record or call on either side).
2973            ExprKind::BinOp(op, lhs, rhs) => {
2974                let prec = binop_prec(*op);
2975                let tail = format!(" {} {}", op.name(), expr_with_prec(rhs, prec + 1));
2976                // The right-hand side shares the operator's line whenever it is
2977                // itself unbroken, so charge it to the left-hand side's budget.
2978                let lhs_reserve = if tail.contains('\n') || holds_comments(rhs) {
2979                    0
2980                } else {
2981                    tail.chars().count() + reserve
2982                };
2983                self.format_expr_at(lhs, prec, lhs_reserve);
2984                self.push(&format!(" {} ", op.name()));
2985                self.format_expr_at(rhs, prec + 1, reserve);
2986            }
2987            ExprKind::Is { value, pattern } => {
2988                let pat = format!(" is {}", is_pattern_src(pattern));
2989                self.format_expr_at(value, 4, pat.chars().count() + reserve);
2990                self.push(&pat);
2991            }
2992            // `if cond { … } else { … }` — both branches go vertical. Once the
2993            // one-line form is over budget, splitting only one branch leaves a
2994            // lopsided line that is no easier to read.
2995            ExprKind::If {
2996                cond,
2997                then_block,
2998                else_block,
2999            } => {
3000                self.push("if ");
3001                self.format_expr_at(cond, 0, 2);
3002                self.push(" ");
3003                self.format_block_multiline(then_block);
3004                // v0.146 (ADR 0170): an `if` with no `else` carries a
3005                // synthesised unit else-branch — omit it, as the flat form does.
3006                if let Some(chained) = else_if_tail(else_block) {
3007                    // #2891: an `else if` chain stays flat.
3008                    self.push(" else ");
3009                    self.format_expr_at(chained, 0, 0);
3010                } else if !else_block.is_synth_unit() {
3011                    self.push(" else ");
3012                    self.format_block_multiline(else_block);
3013                }
3014            }
3015            ExprKind::Block(b) => self.format_block_multiline(b),
3016            ExprKind::Lambda(lambda) => {
3017                let params: Vec<String> = lambda.params.iter().map(lambda_param_src).collect();
3018                self.push(&format!("({}) => ", params.join(", ")));
3019                match lambda_body_src(lambda) {
3020                    LambdaBodySrc::Expr(body) => self.format_expr_at(body, 0, reserve),
3021                    LambdaBodySrc::Block(block) => self.format_block_multiline(block),
3022                }
3023            }
3024            // Single-argument wrappers: nothing to break at the wrapper itself,
3025            // so recurse and let the payload wrap inside the parentheses.
3026            ExprKind::Ok(v) => self.wrap_call("Ok(", v, reserve),
3027            ExprKind::Err(v) => self.wrap_call("Err(", v, reserve),
3028            ExprKind::Some(v) => self.wrap_call("Some(", v, reserve),
3029            ExprKind::EffectPure(v) => self.wrap_call("Effect.pure(", v, reserve),
3030            ExprKind::Wire(v) => self.wrap_call("Wire(", v, reserve),
3031            ExprKind::Paren(v) => self.wrap_call("(", v, reserve),
3032            ExprKind::Question(v) => {
3033                self.format_expr_at(v, 8, reserve + 1);
3034                self.push("?");
3035            }
3036            ExprKind::Expect(v) => {
3037                self.push("expect ");
3038                self.format_expr_at(v, 0, reserve);
3039            }
3040            // Nothing breakable — a literal, an identifier, an interpolated
3041            // string. Emit it as-is and overrun.
3042            _ => self.push(&expr_with_prec(e, 0)),
3043        }
3044    }
3045
3046    /// `<head><inner>)` where `inner` wraps inside the parentheses.
3047    fn wrap_call(&mut self, head: &str, inner: &Expr, reserve: usize) {
3048        self.push(head);
3049        self.format_expr_at(inner, 0, reserve + 1);
3050        self.push(")");
3051    }
3052
3053    /// The body of a wrapped record construction or spread: one `name: value`
3054    /// per indented line, then the closing brace. `spread` is the leading
3055    /// `...base` entry, when there is one. The brace and any type name are the
3056    /// caller's to emit.
3057    fn format_field_inits<'f, I>(
3058        &mut self,
3059        fields: I,
3060        spread: Option<&str>,
3061        trivia: Option<&ListTrivia>,
3062    ) where
3063        I: ExactSizeIterator<Item = &'f FieldInit>,
3064    {
3065        let total = fields.len() + usize::from(spread.is_some());
3066        self.newline();
3067        self.indented(|f| {
3068            let mut emitted = 0usize;
3069            // #3110: the trivia runs parallel to the spread, then the fields.
3070            let slot = |f: &mut Self, emitted: usize| {
3071                let item = trivia.and_then(|t| t.items.get(emitted));
3072                if let Some(item) = item {
3073                    f.emit_leading_comments(&item.leading);
3074                }
3075                item.and_then(|t| t.trailing.clone())
3076            };
3077            if let Some(spread) = spread {
3078                let eol = slot(f, emitted);
3079                f.push(spread);
3080                emitted += 1;
3081                if emitted < total || f.opts.trailing_comma {
3082                    f.push(",");
3083                }
3084                f.emit_trailing_comment_or_newline(eol.as_deref());
3085            }
3086            for field in fields {
3087                let eol = slot(f, emitted);
3088                f.push(&field.name.name);
3089                if let Some(v) = &field.value {
3090                    f.push(": ");
3091                    f.format_expr_at(v, 0, 1);
3092                }
3093                emitted += 1;
3094                if emitted < total || f.opts.trailing_comma {
3095                    f.push(",");
3096                }
3097                f.emit_trailing_comment_or_newline(eol.as_deref());
3098            }
3099            if let Some(t) = trivia {
3100                f.emit_trailing_comments(&t.closing);
3101            }
3102        });
3103        self.push("}");
3104    }
3105
3106    /// The arguments of a wrapped call plus its closing `)` — the caller has
3107    /// already emitted the `name(` head.
3108    ///
3109    /// A trailing argument hugs the call — the earlier arguments stay on the
3110    /// call's line and it opens its own body there, so
3111    /// `xs.fold(init, (acc, x) => match acc {` reads as one construct instead
3112    /// of being pushed down a level. Hugging is attempted for a sole argument
3113    /// (there is no sibling for it to misalign against) and, past that, only
3114    /// for a trailing lambda / record / block / `match` / `if`, whose opening
3115    /// line is short. It is taken only if every line it produces fits;
3116    /// otherwise each argument goes on its own indented line.
3117    ///
3118    /// Never a trailing comma — the grammar rejects one in an argument list,
3119    /// and the wrapped output has to re-parse.
3120    fn format_arg_list(
3121        &mut self,
3122        args: &[Expr],
3123        trivia: Option<&ListTrivia>,
3124        reserve: usize,
3125    ) -> bool {
3126        // #3110: an argument list with a comment in it goes one per line.
3127        if trivia.is_none()
3128            && let Some((last, leading)) = args.split_last()
3129            && (leading.is_empty() || is_block_like(last))
3130            && !leading.iter().any(holds_comments)
3131            && self.try_layout(reserve, |f| {
3132                for arg in leading {
3133                    f.push(&expr_with_prec(arg, 0));
3134                    f.push(", ");
3135                }
3136                f.format_expr_at(last, 0, 1);
3137                f.push(")");
3138            })
3139        {
3140            return false;
3141        }
3142        self.newline();
3143        self.indented(|f| {
3144            for (i, arg) in args.iter().enumerate() {
3145                let last = i + 1 == args.len();
3146                let item = trivia.and_then(|t| t.items.get(i));
3147                if let Some(item) = item {
3148                    f.emit_leading_comments(&item.leading);
3149                }
3150                // A trailing comment rides the line after the `,`, so the
3151                // argument only reserves room for the comma.
3152                f.format_expr_at(arg, 0, if last { 0 } else { 1 });
3153                if !last {
3154                    f.push(",");
3155                }
3156                f.emit_trailing_comment_or_newline(item.and_then(|t| t.trailing.as_deref()));
3157            }
3158            if let Some(t) = trivia {
3159                f.emit_trailing_comments(&t.closing);
3160            }
3161        });
3162        self.push(")");
3163        true
3164    }
3165
3166    /// Emit a `.`-chain (`receiver.a(…).b(…).c`) broken across lines.
3167    ///
3168    /// A single-call chain never breaks at its `.` — there is no pipeline to
3169    /// read and the overflow belongs to the argument list. A multi-call chain
3170    /// prefers to stay on one line too, and breaks before each call only when
3171    /// staying inline would strand an exploded argument list mid-chain.
3172    fn format_chain(&mut self, e: &Expr, reserve: usize) {
3173        let (base, links) = flatten_chain(e);
3174        let calls = links
3175            .iter()
3176            .filter(|l| matches!(l, ChainLink::Method { .. }))
3177            .count();
3178        if calls < 2 {
3179            self.format_chain_inline(base, &links, reserve);
3180            return;
3181        }
3182        // Keeping a multi-call chain intact is preferable when the overflow
3183        // belongs to an argument rather than to the chain — the
3184        // `xs.fold(init, (acc, x) => match acc {` shape, where a body opens on
3185        // the chain's own line. That reading survives only while every step
3186        // either fits or *hugs*. A step forced to put its arguments one per
3187        // line strands a bare `)` mid-chain, at which point the chain itself is
3188        // what is too long, and breaking at its dots reads better.
3189        let exploded = std::cell::Cell::new(false);
3190        if self.try_layout_if(
3191            reserve,
3192            |f| exploded.set(f.format_chain_inline(base, &links, reserve)),
3193            || !exploded.get(),
3194        ) {
3195            return;
3196        }
3197        // Break before each *call*, not before each `.`. A field access is part
3198        // of whatever it qualifies: a leading `msg.params` belongs to the
3199        // receiver, and a `.rows.count()` reads as one step, so a line never
3200        // opens with a bare `.field`.
3201        let first_call = links
3202            .iter()
3203            .position(|l| matches!(l, ChainLink::Method { .. }))
3204            .expect("a chain with two calls has one");
3205        self.format_expr_at(base, 8, 0);
3206        for link in &links[..first_call] {
3207            self.format_chain_link(link, 0);
3208        }
3209        self.indented(|f| {
3210            let mut i = first_call;
3211            while i < links.len() {
3212                let mut end = i;
3213                while end < links.len() && matches!(links[end], ChainLink::Field(_)) {
3214                    end += 1;
3215                }
3216                // …and the call those field accesses qualify, if any.
3217                if end < links.len() {
3218                    end += 1;
3219                }
3220                f.newline();
3221                for (offset, link) in links[i..end].iter().enumerate() {
3222                    let is_last = end == links.len() && i + offset + 1 == links.len();
3223                    f.format_chain_link(link, if is_last { reserve } else { 0 });
3224                }
3225                i = end;
3226            }
3227        });
3228    }
3229
3230    /// The chain on one line: the receiver, then every `.`-step in place. Any
3231    /// step whose arguments do not fit wraps them, but no break is introduced
3232    /// at a `.`. Reports whether any step had to put its arguments one per
3233    /// line, which is what tells [`Self::format_chain`] this layout is a poor
3234    /// fit for the chain.
3235    fn format_chain_inline(
3236        &mut self,
3237        base: &Expr,
3238        links: &[ChainLink<'_>],
3239        reserve: usize,
3240    ) -> bool {
3241        self.format_expr_at(base, 8, 0);
3242        let mut exploded = false;
3243        for (i, link) in links.iter().enumerate() {
3244            exploded |=
3245                self.format_chain_link(link, if i + 1 == links.len() { reserve } else { 0 });
3246        }
3247        exploded
3248    }
3249
3250    /// One `.field` or `.method(args)` step of a chain, wrapping the argument
3251    /// list when the step does not fit on the current line. Reports whether
3252    /// that wrapping was the one-argument-per-line form.
3253    fn format_chain_link(&mut self, link: &ChainLink<'_>, reserve: usize) -> bool {
3254        match link {
3255            ChainLink::Field(name) => {
3256                self.push(&format!(".{name}"));
3257                false
3258            }
3259            ChainLink::Method {
3260                method,
3261                type_args,
3262                args,
3263                trivia,
3264            } => {
3265                let head = format!(".{}{}", method, type_args_src(type_args));
3266                let flat = format!(
3267                    "{head}({})",
3268                    args.iter()
3269                        .map(|a| expr_with_prec(a, 0))
3270                        .collect::<Vec<_>>()
3271                        .join(", ")
3272                );
3273                if (args.is_empty() && trivia.is_none())
3274                    || (trivia.is_none()
3275                        && !args.iter().any(holds_comments)
3276                        && self.fits(&flat, reserve))
3277                {
3278                    self.push(&flat);
3279                    return false;
3280                }
3281                self.push(&head);
3282                self.push("(");
3283                self.format_arg_list(args, *trivia, reserve)
3284            }
3285        }
3286    }
3287
3288    /// Emit a `match` expression at the current indent level. Arms sit one
3289    /// level deeper than the `match`/`}`; block-bodied arms recurse through
3290    /// `format_block` so their statements indent correctly in turn.
3291    fn format_match(&mut self, discriminant: &Expr, arms: &[MatchArm]) {
3292        self.push("match ");
3293        self.format_expr_at(discriminant, 0, " {".len());
3294        self.push(" {");
3295        self.newline();
3296        self.indented(|f| f.format_arms(arms));
3297        self.push("}");
3298    }
3299
3300    /// The arms of a `match` (or of a `let … else match`), one per line.
3301    fn format_arms(&mut self, arms: &[MatchArm]) {
3302        for arm in arms {
3303            self.push(&pattern_to_string(&arm.pattern));
3304            // ADR 0169: render an optional `if <guard>` before `=>`.
3305            if let Some(guard) = &arm.guard {
3306                self.push(" if ");
3307                self.format_expr_at(guard, 0, " => ".len());
3308            }
3309            self.push(" => ");
3310            // Every arm ends in a `,`, which counts against its budget.
3311            match &arm.body {
3312                MatchBody::Expr(e) => self.format_expr_at(e, 0, 1),
3313                MatchBody::Block(b) => self.format_block_with_reserve(b, 1),
3314            }
3315            self.push(",");
3316            self.newline();
3317        }
3318    }
3319}
3320
3321/// One step of a `.`-chain, as collected by [`flatten_chain`].
3322enum ChainLink<'e> {
3323    Field(&'e str),
3324    Method {
3325        method: &'e str,
3326        type_args: &'e [TypeRef],
3327        args: &'e [Expr],
3328        trivia: Option<&'e ListTrivia>,
3329    },
3330}
3331
3332/// Split `receiver.a(…).b.c(…)` into its innermost receiver and the `.`-steps
3333/// applied to it, outermost last. A non-chain expression yields itself and an
3334/// empty list.
3335fn flatten_chain(e: &Expr) -> (&Expr, Vec<ChainLink<'_>>) {
3336    let mut links = Vec::new();
3337    let mut cur = e;
3338    loop {
3339        match &cur.kind {
3340            ExprKind::FieldAccess { receiver, field } => {
3341                links.push(ChainLink::Field(field.name.as_str()));
3342                cur = receiver;
3343            }
3344            ExprKind::MethodCall {
3345                receiver,
3346                method,
3347                type_args,
3348                args,
3349                trivia,
3350            } => {
3351                links.push(ChainLink::Method {
3352                    method: method.name.as_str(),
3353                    type_args,
3354                    args,
3355                    trivia: trivia.as_deref(),
3356                });
3357                cur = receiver;
3358            }
3359            _ => break,
3360        }
3361    }
3362    links.reverse();
3363    (cur, links)
3364}
3365
3366/// The `[T, U]` type-argument suffix on a call, or the empty string.
3367fn type_args_src(type_args: &[TypeRef]) -> String {
3368    if type_args.is_empty() {
3369        return String::new();
3370    }
3371    format!(
3372        "[{}]",
3373        type_args
3374            .iter()
3375            .map(type_ref_to_string)
3376            .collect::<Vec<_>>()
3377            .join(", ")
3378    )
3379}
3380
3381/// The operators a wrapped expression may break *before*. A continuation line
3382/// opening with `&&`, `||`, or `implies` re-attaches to the line above on
3383/// re-parse; one opening with `+` or `==` does not.
3384fn is_logical(op: BinOp) -> bool {
3385    matches!(op, BinOp::And | BinOp::Or | BinOp::Implies)
3386}
3387
3388/// Collect the operands of a left-nested run of the same operator, so
3389/// `a && b && c` breaks into three lines rather than nesting two levels deep.
3390fn flatten_binop<'e>(e: &'e Expr, op: BinOp, out: &mut Vec<&'e Expr>) {
3391    if let ExprKind::BinOp(inner_op, lhs, rhs) = &e.kind
3392        && *inner_op == op
3393    {
3394        flatten_binop(lhs, op, out);
3395        out.push(rhs);
3396        return;
3397    }
3398    out.push(e);
3399}
3400
3401/// An expression whose wrapped form opens with a short header and a brace, so
3402/// it reads correctly as the sole argument of a call it shares a line with —
3403/// `xs.forEach((x) => {`, `Fetch.send(Request {`. Excludes anything whose first
3404/// wrapped line is as long as the construct itself (a call, a `.`-chain), which
3405/// would just move the overflow rather than remove it.
3406fn is_block_like(e: &Expr) -> bool {
3407    matches!(
3408        e.kind,
3409        ExprKind::Lambda(_)
3410            | ExprKind::Block(_)
3411            | ExprKind::RecordConstruction { .. }
3412            | ExprKind::RecordSpread { .. }
3413            | ExprKind::Match { .. }
3414            | ExprKind::If { .. }
3415    )
3416}
3417
3418/// Whether [`expr_with_prec`] would parenthesise `e` in a `parent_prec`
3419/// context. The wrapped printer emits those parentheses itself, since it
3420/// bypasses the flat renderer that would otherwise add them.
3421fn needs_parens(e: &Expr, parent_prec: u8) -> bool {
3422    match &e.kind {
3423        ExprKind::BinOp(op, ..) => binop_prec(*op) < parent_prec,
3424        ExprKind::UnaryOp(..) => parent_prec > 7,
3425        _ => false,
3426    }
3427}
3428
3429/// Borrow the trivia attached to a statement variant.
3430/// Render a `given`-clause capability reference back to source: a bare name
3431/// for a local capability, or `prefix.Name` for a cross-context one (v0.15).
3432fn cap_ref_src(c: &CapRef) -> String {
3433    match &c.context {
3434        Some(prefix) => format!("{}.{}", prefix.joined(), c.name.name),
3435        None => c.name.name.clone(),
3436    }
3437}
3438
3439/// Render a `by` clause back to source: `by <Actor>` (binder-less), `by <b>: <Actor>`
3440/// (captured identity), or an ordered sum `by <b>: A | B` (v0.52). Shared by handler
3441/// and service-header (v0.155) formatting.
3442fn by_clause_src(by: &ByClause) -> String {
3443    let actors = by
3444        .actors
3445        .iter()
3446        .map(|a| a.name.as_str())
3447        .collect::<Vec<_>>()
3448        .join(" | ");
3449    match &by.binder {
3450        Some(b) => format!("by {}: {actors}", b.name),
3451        None => format!("by {actors}"),
3452    }
3453}
3454
3455/// Render an events subscription pattern (Events track slice 1, spine
3456/// #936): `{ field: value, .. }`. The trailing `..` is mandatory whenever any
3457/// field is listed, so it always renders — there is no pattern-less `Some`
3458/// case to omit it for (a pattern-less subscription is `pattern: None` on
3459/// `ServiceProtocol::Events`, handled by the caller before this is reached).
3460fn event_pattern_src(p: &EventPattern) -> String {
3461    let fields: Vec<String> = p
3462        .fields
3463        .iter()
3464        .map(|f| format!("{}: {}", f.name.name, event_pattern_value_src(&f.value)))
3465        .collect();
3466    format!("{{ {}, .. }}", fields.join(", "))
3467}
3468
3469fn event_pattern_value_src(v: &EventPatternValue) -> String {
3470    match v {
3471        EventPatternValue::Literal { value, text, .. } => match value {
3472            LiteralValue::Int(n) => text.clone().unwrap_or_else(|| n.to_string()),
3473            LiteralValue::Str(s) => format!("\"{}\"", escape_string(s)),
3474            LiteralValue::Bool(b) => b.to_string(),
3475        },
3476        EventPatternValue::Variant {
3477            type_name, variant, ..
3478        } => match type_name {
3479            Some(t) => format!("{}.{}", t.name, variant.name),
3480            None => variant.name.clone(),
3481        },
3482    }
3483}
3484
3485/// Render a `via schema(N)` dispatch clause (Events track slice 4, spine
3486/// #936), written after the `from Events(...)` header's closing `)`.
3487fn schema_dispatch_src(d: &SchemaDispatch) -> String {
3488    match &d.pattern {
3489        SchemaVersionPattern::Literal(n) => format!("via schema({n})"),
3490        SchemaVersionPattern::Range(r) => format!("via schema({})", r.describe_source()),
3491        SchemaVersionPattern::Wildcard => "via schema(_)".to_string(),
3492    }
3493}
3494
3495/// Render a storage kind: `Cell[Int]`, `Map[K, V]`, or a bare head (v0.81).
3496fn store_kind_to_string(k: &StoreKind) -> String {
3497    if k.args.is_empty() {
3498        k.head.name.clone()
3499    } else {
3500        format!(
3501            "{}[{}]",
3502            k.head.name,
3503            k.args
3504                .iter()
3505                .map(type_ref_to_string)
3506                .collect::<Vec<_>>()
3507                .join(", ")
3508        )
3509    }
3510}
3511
3512/// Render a storage annotation (v0.85; ADR 0111): `@name`, or `@name(arg, …)`
3513/// where each argument is an optional `label: ` then the value expression.
3514/// Render a storage annotation as a single source-syntax token: `@indexed(by:
3515/// id)`, `@bounded(10000)`, `@ttl(5.minutes)`, or a bare `@retain`. Public so
3516/// the LSP's agent-state hover (ADR 0161) can render a `store` field's
3517/// annotations without re-deriving them.
3518pub fn annotation_to_string(ann: &Annotation) -> String {
3519    if ann.args.is_empty() {
3520        return format!("@{}", ann.name.name);
3521    }
3522    let args = ann
3523        .args
3524        .iter()
3525        .map(|a| match &a.label {
3526            Some(l) => format!("{}: {}", l.name, expr_with_prec(&a.value, 0)),
3527            None => expr_with_prec(&a.value, 0),
3528        })
3529        .collect::<Vec<_>>()
3530        .join(", ");
3531    format!("@{}({})", ann.name.name, args)
3532}
3533
3534/// v0.118: render a `stub` clause head-to-tail as a single source line:
3535/// `stub <capability>.<method>(<args>) <rhs>` (testing track slice 6).
3536fn stub_clause_to_string(pv: &StubClause) -> String {
3537    let args = pv
3538        .args
3539        .iter()
3540        .map(|a| match a {
3541            ArgPattern::Any(_) => "_".to_string(),
3542            ArgPattern::Value(e) => expr_to_string(e),
3543        })
3544        .collect::<Vec<_>>()
3545        .join(", ");
3546    let rhs = match &pv.rhs {
3547        StubRhs::Returns(e) => match &pv.after {
3548            Some(d) => format!("returns {} after {}", expr_to_string(e), expr_to_string(d)),
3549            None => format!("returns {}", expr_to_string(e)),
3550        },
3551        StubRhs::Fails(_) => "fails".to_string(),
3552        StubRhs::Never(_) => "never".to_string(),
3553        StubRhs::ReturnsEach(outcomes, _) => {
3554            let items = outcomes
3555                .iter()
3556                .map(|o| match o {
3557                    SeqOutcome::Value(e) => expr_to_string(e),
3558                    SeqOutcome::Fails(_) => "fails".to_string(),
3559                })
3560                .collect::<Vec<_>>()
3561                .join(", ");
3562            format!("returns each [{items}]")
3563        }
3564    };
3565    format!(
3566        "stub {}.{}({}) {}",
3567        pv.capability.name, pv.method.name, args, rhs
3568    )
3569}
3570
3571fn statement_trivia(s: &Statement) -> &Trivia {
3572    match s {
3573        Statement::Let(l) | Statement::EffectLet(l) => &l.trivia,
3574        Statement::Expect(a) => &a.trivia,
3575        Statement::Do(d) => &d.trivia,
3576        Statement::Assign(a) => &a.trivia,
3577        Statement::Advance(a) => &a.trivia,
3578        Statement::Par(p) => &p.trivia,
3579    }
3580}
3581
3582// -- String-rendering helpers (used by inline single-line emission) --
3583
3584/// The rendered width of a single line: one column per character, except a
3585/// tab, which advances to the next multiple of `tab`. Counting `char`s rather
3586/// than bytes keeps a non-ASCII identifier or string literal from being
3587/// over-measured and wrapped for no reason.
3588fn display_width(line: &str, tab: usize) -> usize {
3589    let mut col = 0usize;
3590    for ch in line.chars() {
3591        if ch == '\t' {
3592            col += tab - (col % tab);
3593        } else {
3594            col += 1;
3595        }
3596    }
3597    col
3598}
3599
3600/// `T` or `T: Eq + C`: a type parameter as written, bounds included.
3601fn type_param_text(tp: &TypeParam) -> String {
3602    if tp.bounds.is_empty() {
3603        tp.name.name.clone()
3604    } else {
3605        format!("{}: {}", tp.name.name, bounds_text(&tp.bounds))
3606    }
3607}
3608
3609fn bounds_text(bounds: &[Ident]) -> String {
3610    bounds
3611        .iter()
3612        .map(|b| b.name.as_str())
3613        .collect::<Vec<_>>()
3614        .join(" + ")
3615}
3616
3617/// #3067, #3110: whether `e` is, or holds, a list literal, call or record
3618/// literal with a comment in it, which forces every enclosing expression off
3619/// its flat form.
3620fn holds_comments(e: &Expr) -> bool {
3621    matches!(
3622        &e.kind,
3623        ExprKind::ListLit(_, Some(_))
3624            | ExprKind::Call {
3625                trivia: Some(_),
3626                ..
3627            }
3628            | ExprKind::MethodCall {
3629                trivia: Some(_),
3630                ..
3631            }
3632            | ExprKind::Val {
3633                trivia: Some(_),
3634                ..
3635            }
3636            | ExprKind::RecordConstruction {
3637                trivia: Some(_),
3638                ..
3639            }
3640            | ExprKind::RecordSpread {
3641                trivia: Some(_),
3642                ..
3643            }
3644    ) || bynk_syntax::ast::expr_children(e)
3645        .into_iter()
3646        .any(holds_comments)
3647}
3648
3649#[cfg(test)]
3650mod tests {
3651    use super::*;
3652
3653    /// Constrained generics slice 0: bounds and a method's `where` clause print as
3654    /// written, and the output is a fixed point.
3655    #[test]
3656    fn bounds_and_where_clauses_round_trip() {
3657        let src = "commons m\n\ntype Pair[T: Eq] = {\n\tleft: T,\n}\n\nfn same[T: Eq + Ord, U](a: T, b: T, u: U) -> Bool {\n\ta == b\n}\n\nfn Pair.has(self, x: T) -> Bool where T: Eq, T: Ord {\n\tself.left == x\n}\n\nfn Pair.has2(self, x: T) -> Bool where T: Eq\n\trequires p: true\n{\n\tself.left == x\n}\n";
3658        let out = format_source(src, &FormatOptions::default()).unwrap();
3659        assert_eq!(out, src);
3660    }
3661
3662    /// #2640: a `par` block prints one binding per line, indented, and the
3663    /// output is a fixed point; comments around and inside it stay put.
3664    #[test]
3665    fn par_block_round_trips() {
3666        let src = "commons x\n\nfn f(id: Int) -> Effect[Int] {\n\t// load both\n\tpar {\n\t\t// the user\n\t\tlet user <- Users.get(id)  // trailing\n\t\tlet orders: Int <- Orders.forUser(id)\n\t\tdo Audit.touch(id)\n\t\t// last word\n\t}\n\tEffect.pure(user + orders)\n}\n";
3667        let out = format_source(src, &FormatOptions::default()).unwrap();
3668        assert_eq!(out, src);
3669        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3670    }
3671
3672    #[test]
3673    fn par_block_is_reindented_and_split_onto_lines() {
3674        let messy = "commons x\n\nfn f(id: Int) -> Effect[Int] {\n  if id > 0 {   par { let a <- A.get(id)   let b <- B.get(id) }\n  Effect.pure(a + b) } else { Effect.pure(0) }\n}\n";
3675        let out = format_source(messy, &FormatOptions::default()).unwrap();
3676        assert!(
3677            out.contains("\t\tpar {\n\t\t\tlet a <- A.get(id)\n\t\t\tlet b <- B.get(id)\n\t\t}\n"),
3678            "{out}"
3679        );
3680        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3681    }
3682
3683    /// #2321: a binding's `includes` list prints between the module and
3684    /// `requires`, and the output is a fixed point.
3685    #[test]
3686    fn binding_includes_round_trips() {
3687        let src = "adapter x {\n\tbinding \"./x.ts\" includes [\"./a.wasm\", \"b.wasm\"] requires { \"p\": \"^1\" }\n}\n";
3688        let out = format_source(src, &FormatOptions::default()).unwrap();
3689        assert_eq!(out, src);
3690    }
3691
3692    /// #1885: a doc holding a `---` line prints with a `----` fence, so the
3693    /// output re-lexes as one block and is a fixed point; a doc with none
3694    /// prints the canonical `---`, whatever fence it was written with.
3695    #[test]
3696    fn doc_fence_outgrows_the_marker_lines_it_holds() {
3697        let held = "commons m\n\n-------\nAbove.\n---\nInner.\n-----\nBelow.\n-------\nfn f() -> Int { 1 }\n";
3698        let out = format_source(held, &FormatOptions::default()).unwrap();
3699        assert_eq!(
3700            out,
3701            "commons m\n\n------\nAbove.\n---\nInner.\n-----\nBelow.\n------\nfn f() -> Int {\n\t1\n}\n"
3702        );
3703        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3704        let plain = "commons m\n\n-----\nJust prose.\n-----\nfn f() -> Int { 1 }\n";
3705        assert_eq!(
3706            format_source(plain, &FormatOptions::default()).unwrap(),
3707            "commons m\n\n---\nJust prose.\n---\nfn f() -> Int {\n\t1\n}\n"
3708        );
3709        assert_eq!(doc_fence_len("a\n  ---  \nb"), 4);
3710        assert_eq!(doc_fence_len("a\n--\n- - -"), 3);
3711    }
3712
3713    /// #1888 (DECISION F): each doc form prints as written, on declarations
3714    /// and on every member kind: a `--- text` line stays a line, a one-line
3715    /// fence stays a fence. Canonical input is a fixed point.
3716    #[test]
3717    fn each_doc_form_round_trips_unchanged() {
3718        let src = "commons m\n\n--- A commit SHA.\ntype Commit = String\n\n---\nOne line, fenced.\n---\ntype Id = Int\n\ntype Point = {\n\t--- Across.\n\tx: Int,\n}\n\n--- One line.\ntype Run = {\n\t--- The repository.\n\trepo: String,\n\t---\n\tThe version.\n\t---\n\tversion: String,\n\t// a note\n\tsha: String,  // trailing\n}\n\ntype Outcome = enum {\n\t--- Passed.\n\tPass,\n\t---\n\tFailed.\n\t---\n\tFail,\n}\n\ntype Shape =\n\t--- Round.\n\t| Circle(\n\t\t--- The radius.\n\t\tr: Int,\n\t\td: Int,\n\t)\n\t--- A dot.\n\t| Dot\n\nmessages \"en\" @reference {\n\t--- Greets.\n\t\"hi\" => \"Hello\"\n}\n";
3719        let out = format_source(src, &FormatOptions::default()).unwrap();
3720        assert_eq!(out, src);
3721        // #2203: the marker is `---` and its separating space is one; the
3722        // optional closer is not printed, and a text ending in a `---` run
3723        // takes a longer marker so the run is not read as a closer.
3724        for (written, printed) in [
3725            ("--- bare", "--- bare"),
3726            ("-----\tspaced", "--- spaced"),
3727            ("--- Closed. ---", "--- Closed."),
3728            ("---- Ends in a rule ---", "---- Ends in a rule ---"),
3729        ] {
3730            let src = format!("commons m\n\n{written}\nfn f() -> Int {{ 1 }}\n");
3731            assert_eq!(
3732                format_source(&src, &FormatOptions::default()).unwrap(),
3733                format!("commons m\n\n{printed}\nfn f() -> Int {{\n\t1\n}}\n"),
3734                "{written:?}"
3735            );
3736        }
3737    }
3738
3739    /// #2203 (DECISION F): `bynk fmt` is the migration. A file with a legacy
3740    /// `--` comment or `--|` doc line is read by the old rules and printed
3741    /// with `//` comments and `--- ` docs, and `a--b` stays subtraction.
3742    #[test]
3743    fn legacy_spellings_format_to_the_new_ones() {
3744        let src = "-- A header.\ncommons m\n\n--| A run.\ntype Run = {\n\t--| The repo.\n\trepo: String,\n\tn: Int,  -- trailing\n}\n\nfn d(a: Int, b: Int) -> Int { a--b }\n";
3745        let out = format_source(src, &FormatOptions::default()).unwrap();
3746        assert_eq!(
3747            out,
3748            "// A header.\ncommons m\n\n--- A run.\ntype Run = {\n\t--- The repo.\n\trepo: String,\n\tn: Int,  // trailing\n}\n\nfn d(a: Int, b: Int) -> Int {\n\ta - -b\n}\n"
3749        );
3750        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3751        // A `--|` text ending in a `---` run takes a longer marker.
3752        let ruled = "commons m\n\n--| Ends in a rule ---\nfn f() -> Int { 1 }\n";
3753        assert_eq!(
3754            format_source(ruled, &FormatOptions::default()).unwrap(),
3755            "commons m\n\n---- Ends in a rule ---\nfn f() -> Int {\n\t1\n}\n"
3756        );
3757    }
3758
3759    /// #2203 review: a half-migrated file, a stray legacy `--` comment among
3760    /// lines that the old and new rules read differently (a `--- text` doc,
3761    /// an `a --b` subtraction), is refused, never silently reread; one whose
3762    /// other lines read the same either way migrates.
3763    #[test]
3764    fn a_half_migrated_file_is_refused_where_the_reads_differ() {
3765        let opts = FormatOptions::default();
3766        for (src, line) in [
3767            (
3768                "commons m\n\n-- note\n--- Adds two ints.\nfn add(a: Int, b: Int) -> Int { a + b }\n",
3769                "--- Adds two ints.",
3770            ),
3771            (
3772                "commons m\n\n-- note\nfn f(a: Int, b: Int) -> Int { a --b }\n",
3773                "fn f(a: Int, b: Int) -> Int { a --b }",
3774            ),
3775        ] {
3776            let err = format_source(src, &opts).unwrap_err();
3777            assert_eq!(
3778                err.errors[0].category, "bynk.fmt.mixed_comment_syntax",
3779                "{src}"
3780            );
3781            assert_eq!(&src[err.errors[0].span.range()], line, "{src}");
3782        }
3783        // An old `--- Helpers ---` divider was a comment but now reads as a
3784        // doc, so it is refused too, not guessed at.
3785        let divider = "-- A header.\ncommons m\n\n--- Helpers ---\n\nfn f() -> Int { 1 }\n";
3786        let err = format_source(divider, &opts).unwrap_err();
3787        assert_eq!(err.errors[0].category, "bynk.fmt.mixed_comment_syntax");
3788        let agreeing =
3789            "commons m\n\n-- note\n// new\nfn f(a: Int, b: Int) -> Int { a--b }  --| old\n";
3790        assert_eq!(
3791            format_source(agreeing, &opts).unwrap(),
3792            "commons m\n\n// note\n// new\nfn f(a: Int, b: Int) -> Int {\n\ta - -b\n}  // old\n"
3793        );
3794    }
3795
3796    /// #1888 review: a `//` comment under a one-line doc is on its own line,
3797    /// as one under a `---` block is, so the blank line after it (#1884) is
3798    /// kept in both forms.
3799    #[test]
3800    fn a_blank_after_a_comment_under_a_doc_line_is_kept() {
3801        for (doc, printed) in [
3802            ("--- Doc.\n", "--- Doc.\n"),
3803            ("---\nDoc.\n---\n", "---\nDoc.\n---\n"),
3804        ] {
3805            let src = format!("commons m\n\n{doc}// note\n\ntype X = Int\n");
3806            assert_eq!(
3807                format_source(&src, &FormatOptions::default()).unwrap(),
3808                format!("commons m\n\n// note\n\n{printed}type X = Int\n"),
3809                "{doc:?}"
3810            );
3811        }
3812    }
3813
3814    /// #1888: an orphaned one-line doc (a blank line before the declaration)
3815    /// stays a line too, where it was.
3816    #[test]
3817    fn an_orphaned_doc_line_run_keeps_its_form() {
3818        let src = "commons m\n\n--- Orphaned.\n\nfn f() -> Int { 1 }\n";
3819        assert_eq!(
3820            format_source(src, &FormatOptions::default()).unwrap(),
3821            "commons m\n\n--- Orphaned.\n\nfn f() -> Int {\n\t1\n}\n"
3822        );
3823    }
3824
3825    /// #1888: the doc-loss guard keys a doc by its form as well as its text,
3826    /// so a doc printed in the other form counts as lost.
3827    #[test]
3828    fn the_doc_loss_guard_sees_a_converted_form() {
3829        let src = "commons m\n\n--- Text.\nfn f() -> Int { 1 }\n";
3830        let tokens = tokenize(src).unwrap();
3831        let converted = "commons m\n\n---\nText.\n---\nfn f() -> Int { 1 }\n";
3832        assert!(doc_block_loss(src, &tokens, converted).is_some());
3833        assert!(doc_block_loss(src, &tokens, src).is_none());
3834    }
3835
3836    /// #1763: a CRLF copy of a canonical file formats to the LF canonical form,
3837    /// and a doc block's lines lose their CR too (its text was kept verbatim).
3838    #[test]
3839    fn crlf_formats_to_the_lf_canonical_form() {
3840        let lf = "context greeting\n\n---\nA greeting for a name.\n---\nfn greet(name: String) -> String {\n\tname\n}\n";
3841        assert_eq!(format_source(lf, &FormatOptions::default()).unwrap(), lf);
3842        let crlf = lf.replace('\n', "\r\n");
3843        let formatted = format_source(&crlf, &FormatOptions::default()).unwrap();
3844        assert_eq!(formatted, lf);
3845        assert!(!formatted.contains('\r'));
3846    }
3847
3848    /// A braced declaration always breaks, however short: a record type one
3849    /// field per line, an `fn` body on its own lines, an empty body as `{}`.
3850    #[test]
3851    fn braced_declarations_always_break() {
3852        let src = "commons m\n\ntype P = { x: Int, y: Int }\n\nfn id(n: Int) -> Int { n }\n\nfn nop() -> () {}\n";
3853        let out = format_source(src, &FormatOptions::default()).unwrap();
3854        assert_eq!(
3855            out,
3856            "commons m\n\ntype P = {\n\tx: Int,\n\ty: Int,\n}\n\nfn id(n: Int) -> Int {\n\tn\n}\n\nfn nop() -> () {}\n"
3857        );
3858        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3859    }
3860
3861    /// A record literal with several fields breaks; a single field stays
3862    /// inline. `match` arms and `if` branches stay compact when they fit.
3863    #[test]
3864    fn record_literals_break_but_match_arms_stay_compact() {
3865        let src = "commons m\n\nfn a(v: Int) -> P { P { x: v, y: v } }\n\nfn b(v: Int) -> P { P { x: v } }\n\nfn c(v: Int) -> Int { match v { 0 => 1, _ => 2 } }\n\nfn d(v: Int) -> Int { if v > 0 { 1 } else { 0 } }\n";
3866        let out = format_source(src, &FormatOptions::default()).unwrap();
3867        assert_eq!(
3868            out,
3869            "commons m\n\nfn a(v: Int) -> P {\n\tP {\n\t\tx: v,\n\t\ty: v,\n\t}\n}\n\nfn b(v: Int) -> P {\n\tP { x: v }\n}\n\nfn c(v: Int) -> Int {\n\tmatch v {\n\t\t0 => 1,\n\t\t_ => 2,\n\t}\n}\n\nfn d(v: Int) -> Int {\n\tif v > 0 { 1 } else { 0 }\n}\n"
3870        );
3871        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3872    }
3873
3874    /// A fragment-form `suite` header is followed by a blank line, and
3875    /// `case` and `property` blocks keep the order they were written in.
3876    #[test]
3877    fn suite_header_is_spaced_and_members_keep_source_order() {
3878        let src = "suite shop\nuses money\nproperty \"p1\" {\n  for all a: Int { expect a == a }\n}\ncase \"c1\" { expect true }\nproperty \"p2\" {\n  for all a: Int { expect a == a }\n}\n";
3879        let out = format_source(src, &FormatOptions::default()).unwrap();
3880        assert_eq!(
3881            out,
3882            "suite shop\n\nuses money\n\nproperty \"p1\" {\n\tfor all a: Int {\n\t\texpect a == a\n\t}\n}\n\ncase \"c1\" {\n\texpect true\n}\n\nproperty \"p2\" {\n\tfor all a: Int {\n\t\texpect a == a\n\t}\n}\n"
3883        );
3884        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3885    }
3886
3887    /// #3536: a suite file's `consumes` clauses follow its `uses`, stay together
3888    /// as a unit's header lines do, and survive a second format.
3889    #[test]
3890    fn a_suite_keeps_its_consumes_clauses_together() {
3891        let src = "suite shop as unit\nconsumes bynk { Claim }\nconsumes bynk.cloudflare { D1 }\ncase \"c\" { expect true }\n";
3892        let out = format_source(src, &FormatOptions::default()).unwrap();
3893        assert_eq!(
3894            out,
3895            "suite shop as unit\n\nconsumes bynk { Claim }\nconsumes bynk.cloudflare { D1 }\n\ncase \"c\" {\n\texpect true\n}\n"
3896        );
3897        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3898    }
3899
3900    /// A spread with overrides breaks like a multi-field literal; a bare
3901    /// spread (one item) stays inline.
3902    #[test]
3903    fn spread_literals_break_only_with_overrides() {
3904        let src =
3905            "commons m\n\nfn a(b: P) -> P { P { ...b, x: 1 } }\n\nfn c(b: P) -> P { P { ...b } }\n";
3906        let out = format_source(src, &FormatOptions::default()).unwrap();
3907        assert_eq!(
3908            out,
3909            "commons m\n\nfn a(b: P) -> P {\n\tP {\n\t\t...b,\n\t\tx: 1,\n\t}\n}\n\nfn c(b: P) -> P {\n\tP { ...b }\n}\n"
3910        );
3911        assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3912    }
3913
3914    #[test]
3915    fn normalize_line_endings_borrows_when_there_is_nothing_to_do() {
3916        assert!(matches!(
3917            normalize_line_endings("a\nb"),
3918            std::borrow::Cow::Borrowed(_)
3919        ));
3920        assert_eq!(normalize_line_endings("a\r\nb\r\n"), "a\nb\n");
3921    }
3922
3923    /// #1775 review: a run of CRs before an LF is one line ending, so the
3924    /// normaliser is a fixed point; a CR not before an LF is kept.
3925    #[test]
3926    fn normalize_line_endings_is_a_fixed_point() {
3927        for input in ["a\r\r\nb", "a\r\nb\rc\r\n", "\r\r\r\n", "x\r", "a\r\n\rb"] {
3928            let once = normalize_line_endings(input).into_owned();
3929            assert_eq!(normalize_line_endings(&once), once, "{input:?}");
3930            assert!(!once.contains("\r\n"), "{input:?} -> {once:?}");
3931        }
3932        assert_eq!(normalize_line_endings("a\r\r\nb"), "a\nb");
3933        assert_eq!(normalize_line_endings("a\r\nb\rc"), "a\nb\rc");
3934    }
3935
3936    /// #1755 review: output that does not even tokenize is the round-trip
3937    /// guard's to report ("no longer parses"). The doc-block guard runs first,
3938    /// so it must stay silent rather than blame every doc block as lost.
3939    #[test]
3940    fn doc_block_loss_leaves_an_untokenizable_output_to_the_roundtrip_guard() {
3941        let source = "commons d\n\n---\nattached\n---\nfn f() -> Int { 1 }\n";
3942        let tokens = tokenize(source).unwrap();
3943        assert!(tokenize("commons d\n\"unterminated").is_err());
3944        assert!(
3945            doc_block_loss(source, &tokens, "commons d\n\"unterminated").is_none(),
3946            "an untokenizable output was reported as doc-block loss"
3947        );
3948    }
3949
3950    /// #2807: the lexer recovers past a bad character, but the formatter must
3951    /// not: a recovered token list has a gap where the character stood, and
3952    /// printing from it would delete the user's text. A file with any lexical
3953    /// error is refused, and the error is the lexer's.
3954    #[test]
3955    fn a_file_with_a_lex_error_is_refused_not_formatted() {
3956        for src in [
3957            "commons d\n\n$\n\nfn f() -> Int { 1 }\n",
3958            "commons d\n\nfn f() -> Int { 1 }\n\nfn g() -> String { \"open }\n",
3959            "commons d\n\nfn f() -> Int { 99999999999999999999 }\n",
3960        ] {
3961            let errs = format_source(src, &FormatOptions::default())
3962                .expect_err("a file with a lex error must not format");
3963            assert!(
3964                errs.errors[0].category.starts_with("bynk.lex."),
3965                "{:?}",
3966                errs.errors
3967            );
3968        }
3969    }
3970
3971    fn fmt(src: &str) -> String {
3972        format_source(src, &FormatOptions::default()).expect("format failed")
3973    }
3974
3975    #[test]
3976    fn wildcard_lambda_params_round_trip() {
3977        let src = "commons x {\n\tfn f(r: Result[Int, String]) -> Result[Int, Int] {\n\t\tr.mapErr((_) => 0)\n\t}\n\n\tfn g(xs: List[Int]) -> Int {\n\t\txs.fold(0, (a, _) => a)\n\t}\n\n\tfn h(r: Result[Int, String]) -> Result[Int, Int] {\n\t\tr.mapErr((_: String) => 1)\n\t}\n\n\tfn k(f: (Int, Int) -> Int) -> Int {\n\t\tf(1, 2)\n\t}\n\n\tfn m() -> Int {\n\t\tk((_, _) => 1)\n\t}\n}\n";
3978        let out = fmt(src);
3979        assert_eq!(out, src);
3980        assert_eq!(fmt(&out), out);
3981    }
3982
3983    #[test]
3984    fn formats_minimal_commons() {
3985        let src = "commons fitness.units {}";
3986        let out = fmt(src);
3987        assert!(out.starts_with("commons fitness.units"));
3988        // Idempotency.
3989        let out2 = fmt(&out);
3990        assert_eq!(out, out2);
3991    }
3992
3993    #[test]
3994    fn formats_refined_type() {
3995        let src = "commons x { type Metres = Int where NonNegative }";
3996        let out = fmt(src);
3997        assert!(out.contains("type Metres = Int where NonNegative"));
3998        let out2 = fmt(&out);
3999        assert_eq!(out, out2);
4000    }
4001
4002    #[test]
4003    fn formats_function_decl() {
4004        let src = "commons x { fn add(a: Int, b: Int) -> Int { a + b } }";
4005        let out = fmt(src);
4006        assert!(out.contains("fn add(a: Int, b: Int) -> Int"));
4007        let out2 = fmt(&out);
4008        assert_eq!(out, out2);
4009    }
4010
4011    #[test]
4012    fn formats_record() {
4013        let src = "commons x { type Pt = { x: Int, y: Int } }";
4014        let out = fmt(src);
4015        let out2 = fmt(&out);
4016        assert_eq!(out, out2, "formatter not idempotent: {out}");
4017    }
4018
4019    #[test]
4020    fn formats_a_fault_claim_with_a_call_site_principal() {
4021        // #1812: the principal sits between the call and `faults`, and the
4022        // claim round-trips with it — and without it.
4023        let src = "suite s {\n  case \"c\" {\n    expect api.POST(\"/o\", x)   by  User( \"bob\" ) faults\n    expect api.GET(\"/a\") by Visitor faults\n    expect box.call() faults\n  }\n}\n";
4024        let out = fmt(src);
4025        assert!(
4026            out.contains("expect api.POST(\"/o\", x) by User(\"bob\") faults"),
4027            "{out}"
4028        );
4029        assert!(
4030            out.contains("expect api.GET(\"/a\") by Visitor faults"),
4031            "{out}"
4032        );
4033        assert!(out.contains("expect box.call() faults"), "{out}");
4034        assert_eq!(out, fmt(&out), "formatter not idempotent: {out}");
4035    }
4036
4037    #[test]
4038    fn formats_doc_block() {
4039        let src = "commons x {\n---\nA descriptive doc.\n---\ntype T = Int where Positive\n}";
4040        let out = fmt(src);
4041        assert!(out.contains("A descriptive doc."));
4042        let out2 = fmt(&out);
4043        assert_eq!(out, out2);
4044    }
4045
4046    // -- v1.1 comment preservation --
4047
4048    #[test]
4049    fn preserves_leading_line_comment_on_decl() {
4050        let src = "commons x {\n// explain T\ntype T = Int where NonNegative\n}";
4051        let out = fmt(src);
4052        assert!(out.contains("// explain T"), "comment dropped: {out}");
4053        // Idempotent.
4054        assert_eq!(out, fmt(&out));
4055    }
4056
4057    #[test]
4058    fn preserves_trailing_line_comment_on_decl() {
4059        let src = "commons x {\ntype T = Int where NonNegative  // short\n}";
4060        let out = fmt(src);
4061        assert!(out.contains("// short"));
4062        // The trailing comment must remain on the same line as the decl.
4063        assert!(
4064            out.lines()
4065                .any(|l| l.contains("type T") && l.contains("// short")),
4066            "trailing comment not on same line: {out}"
4067        );
4068        assert_eq!(out, fmt(&out));
4069    }
4070
4071    #[test]
4072    fn preserves_grouped_leading_comments() {
4073        let src = "commons x {\n// one\n// two\ntype T = Int where Positive\n}";
4074        let out = fmt(src);
4075        assert!(out.contains("// one"));
4076        assert!(out.contains("// two"));
4077        // Adjacent — no blank line between the comments.
4078        let i1 = out.find("// one").unwrap();
4079        let i2 = out.find("// two").unwrap();
4080        let between = &out[i1..i2];
4081        assert_eq!(
4082            between.matches('\n').count(),
4083            1,
4084            "blank line inserted: {out}"
4085        );
4086        assert_eq!(out, fmt(&out));
4087    }
4088
4089    #[test]
4090    fn preserves_comment_before_block_tail() {
4091        let src = "commons x {\nfn f(n: Int) -> Int {\nlet y = n + 1\n// result\ny\n}\n}";
4092        let out = fmt(src);
4093        assert!(out.contains("// result"), "tail comment dropped: {out}");
4094        assert_eq!(out, fmt(&out));
4095    }
4096
4097    #[test]
4098    fn preserves_comment_with_doc_block_above_decl() {
4099        let src = "commons x {\n// TODO: rename\n---\nThe canonical T.\n---\ntype T = Int where Positive\n}";
4100        let out = fmt(src);
4101        assert!(out.contains("// TODO: rename"));
4102        assert!(out.contains("The canonical T."));
4103        // Spec layout: comment, then doc block, then declaration.
4104        let ic = out.find("// TODO: rename").unwrap();
4105        let id = out.find("The canonical T.").unwrap();
4106        let it = out.find("type T").unwrap();
4107        assert!(ic < id && id < it, "ordering wrong: {out}");
4108        assert_eq!(out, fmt(&out));
4109    }
4110
4111    #[test]
4112    fn preserves_trailing_file_comment() {
4113        let src = "commons x.y\n\ntype T = Int where Positive\n// TODO\n";
4114        let out = fmt(src);
4115        assert!(out.contains("// TODO"));
4116        assert_eq!(out, fmt(&out));
4117    }
4118
4119    // -- Finding #66: the drain-check fast path must not weaken the
4120    // comment-loss guard --
4121
4122    /// A comment strictly inside an expression subtree (here, a binop chain)
4123    /// is the one shape `TriviaTable` genuinely cannot drain — `fully_drained`
4124    /// must be `false` for it, so `format_source`'s fast path does not skip
4125    /// `comment_loss` and the file is still refused rather than silently
4126    /// losing the comment.
4127    #[test]
4128    fn expression_interior_comment_is_not_fully_drained_and_still_refused() {
4129        let src = "commons x {\n  fn f() -> Int {\n    1 + // note\n    2\n  }\n}\n";
4130        let tokens = tokenize(src).unwrap();
4131        let (_, _, fully_drained) = bynk_syntax::parser::parse_units_with_drain_check(&tokens, src)
4132            .expect("a comment inside an expression is still a valid parse");
4133        assert!(
4134            !fully_drained,
4135            "an expression-interior comment must leave the trivia table undrained"
4136        );
4137        let err = format_source(src, &FormatOptions::default())
4138            .expect_err("formatting must still refuse rather than lose the comment");
4139        assert_eq!(err.errors[0].category, "bynk.fmt.comment_loss");
4140    }
4141
4142    /// The mirror image: an ordinary file with no expression-interior comment
4143    /// (every comment sits before a declaration/statement, or trailing one) is
4144    /// `fully_drained`, so `format_source`'s fast path is what actually runs —
4145    /// and formatting must still succeed and preserve the comment.
4146    #[test]
4147    fn ordinary_comment_is_fully_drained_and_formats_normally() {
4148        let src = "commons x {\n// note\ntype T = Int where Positive\n}\n";
4149        let tokens = tokenize(src).unwrap();
4150        let (_, _, fully_drained) =
4151            bynk_syntax::parser::parse_units_with_drain_check(&tokens, src).expect("should parse");
4152        assert!(
4153            fully_drained,
4154            "a declaration-leading comment must be fully drained"
4155        );
4156        let out = fmt(src);
4157        assert!(out.contains("// note"));
4158    }
4159
4160    // -- #981: a bare-identifier statement + trailing `()` must not merge
4161    // into a call expression.
4162
4163    #[test]
4164    fn match_arm_block_tail_unit_after_assign_does_not_reattach_as_a_call() {
4165        // The exact shape from #981: an Assign statement whose value is a
4166        // bare (capitalised, enum-variant-shaped) identifier, immediately
4167        // followed by the block's own explicit `()` tail. The formatter must
4168        // not print these adjacently — that reparses as `status := Paid()`,
4169        // a call, rather than the original two constructs.
4170        let src = "commons x { fn f(status: T) -> T {\n  match status {\n    Draft => {\n      status := Paid\n      ()\n    }\n    Paid => (),\n  }\n} }";
4171        let out = fmt(src);
4172        assert!(
4173            !out.contains("Paid()"),
4174            "the `()` tail must not re-attach to `Paid` as a call:\n{out}"
4175        );
4176        assert!(
4177            out.contains("status := Paid"),
4178            "the assignment must survive unmangled:\n{out}"
4179        );
4180        assert_eq!(out, fmt(&out), "must be idempotent");
4181    }
4182
4183    #[test]
4184    fn explicit_unit_tail_after_a_statement_is_omitted_like_an_implicit_one() {
4185        // Not just the implicit-tail shape #735 special-cased — an
4186        // *explicit* `()` written by the user right after a statement is
4187        // exactly as dangerous to print, so it is omitted the same way.
4188        let src = "commons x { fn f() -> Effect[()] {\n  let a = 1\n  ()\n} }";
4189        let out = fmt(src);
4190        let expected = "commons x {\n\tfn f() -> Effect[()] {\n\t\tlet a = 1\n\t}\n}\n";
4191        assert_eq!(
4192            out, expected,
4193            "an explicit unit tail after a statement must be omitted"
4194        );
4195        assert_eq!(out, fmt(&out), "must be idempotent");
4196    }
4197
4198    // -- #735 round-trip guard --
4199
4200    #[test]
4201    fn code_only_canonical_ignores_comments() {
4202        // Two sources whose only difference is comments must reduce to the same
4203        // comment-free canonical form — this is what lets the round-trip guard
4204        // compare structure while the formatter re-flows trivia freely.
4205        let opts = FormatOptions::default();
4206        let bare = "commons x { type T = Int where Positive }";
4207        let commented = "commons x {\n// a note\ntype T = Int where Positive  // trailing\n}";
4208        assert_eq!(
4209            code_only_canonical(bare, &opts).unwrap(),
4210            code_only_canonical(commented, &opts).unwrap(),
4211        );
4212    }
4213
4214    #[test]
4215    fn roundtrip_guard_accepts_faithful_output() {
4216        // The formatter's own output over a real source must round-trip.
4217        let opts = FormatOptions::default();
4218        let src = "commons x { fn add(a: Int, b: Int) -> Int { a + b } }";
4219        let out = format_source(src, &opts).unwrap();
4220        let tokens = tokenize(src).unwrap();
4221        assert!(roundtrip_divergence(&tokens, src, &out, &opts).is_none());
4222    }
4223
4224    #[test]
4225    fn roundtrip_guard_rejects_non_parsing_output() {
4226        // Simulate a printer that emitted garbage: the output no longer parses,
4227        // so the guard must fire rather than let it be written. The output here
4228        // is *longer* than the source and its parse error lands near its end —
4229        // the error's span must nonetheless stay within the source, because the
4230        // caller renders it against `source`, not the output (an out-of-range
4231        // primary span misplaces the caret or panics ariadne). See
4232        // `roundtrip_error`.
4233        let opts = FormatOptions::default();
4234        let src = "commons x { type T = Int where Positive }";
4235        let corrupt = "commons x { type T = Int where Positive } fn f(a: Int) -> Int { a +";
4236        assert!(
4237            corrupt.len() > src.len(),
4238            "output must be the longer buffer"
4239        );
4240        let tokens = tokenize(src).unwrap();
4241        let err = roundtrip_divergence(&tokens, src, corrupt, &opts)
4242            .expect("must reject non-parsing output");
4243        assert_eq!(err.category, "bynk.fmt.roundtrip");
4244        assert!(
4245            err.span.end <= src.len(),
4246            "roundtrip error span {:?} escapes the source it is rendered against (len {})",
4247            err.span,
4248            src.len(),
4249        );
4250    }
4251
4252    #[test]
4253    fn roundtrip_guard_rejects_structural_divergence() {
4254        // Simulate a printer that emitted parseable-but-wrong code: the output
4255        // parses, but to a different AST than the input. The guard must catch it.
4256        let opts = FormatOptions::default();
4257        let src = "commons x { type T = Int where Positive }";
4258        let wrong = "commons x { type T = Bool }";
4259        let tokens = tokenize(src).unwrap();
4260        let err = roundtrip_divergence(&tokens, src, wrong, &opts)
4261            .expect("must reject structural divergence");
4262        assert_eq!(err.category, "bynk.fmt.roundtrip");
4263        assert!(err.span.end <= src.len(), "span escapes the source buffer");
4264    }
4265
4266    #[test]
4267    fn unchanged_files_without_comments_format_identically() {
4268        let src = "commons x { type T = Int where NonNegative }";
4269        let out = fmt(src);
4270        // Sanity: the formatter still produces the canonical output for
4271        // existing fixtures (no spurious comment rendering).
4272        assert!(!out.contains("//"), "unexpected comment in output: {out}");
4273    }
4274
4275    // -- v0.81 storage track: `store` fields and the `:=` write --
4276
4277    #[test]
4278    fn formats_store_field_and_cell_write() {
4279        let src = "context shop {\nagent Counter {\nkey id: String\nstore count: Cell[Int] = 0\non call bump() -> Effect[()] {\ncount := count + 1\n()\n}\n}\n}";
4280        let out = fmt(src);
4281        assert!(
4282            out.contains("store count: Cell[Int] = 0"),
4283            "store field not formatted: {out}"
4284        );
4285        assert!(
4286            out.contains("count := count + 1"),
4287            "cell write not formatted: {out}"
4288        );
4289        assert_eq!(out, fmt(&out), "formatter not idempotent: {out}");
4290    }
4291
4292    #[test]
4293    fn formats_store_only_agent_without_state_block() {
4294        let src = "context shop {\nagent Counter {\nkey id: String\nstore count: Cell[Int] = 0\non call get() -> Effect[Int] {\ncount\n}\n}\n}";
4295        let out = fmt(src);
4296        // A `store`-only agent emits no empty `state { }` block.
4297        assert!(!out.contains("state {"), "spurious state block: {out}");
4298        assert!(out.contains("store count: Cell[Int] = 0"), "{out}");
4299        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4300    }
4301
4302    // -- #963: line-width-driven wrapping --
4303
4304    /// Every line of `out`, measured the way the formatter measures them.
4305    fn widths(out: &str) -> Vec<usize> {
4306        out.lines().map(|l| display_width(l, 4)).collect()
4307    }
4308
4309    fn assert_within_budget(out: &str) {
4310        let over: Vec<&str> = out.lines().filter(|l| display_width(l, 4) > 100).collect();
4311        assert!(over.is_empty(), "lines over 100 columns: {over:?}\n{out}");
4312    }
4313
4314    #[test]
4315    fn fit_test_counts_the_prefix_already_on_the_line() {
4316        // The body fits on its own but not behind the signature, which is what
4317        // the pre-#963 fit test measured.
4318        let src = "commons x {\nfn authorise(amount: Int, ceiling: Int, floor: Int) -> Result[Int, Error] { if amount > ceiling { Err(Declined) } else { Ok(amount) } }\n}";
4319        let out = fmt(src);
4320        assert_within_budget(&out);
4321        assert!(
4322            out.contains("-> Result[Int, Error] {\n"),
4323            "body not broken out: {out}"
4324        );
4325        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4326    }
4327
4328    #[test]
4329    fn wraps_a_long_record_construction_one_field_per_line() {
4330        let src = "commons x {\nfn make() -> R { R { alpha: \"first value here\", beta: \"second value here\", gamma: \"third value here\", delta: \"fourth value\" } }\n}";
4331        let out = fmt(src);
4332        assert_within_budget(&out);
4333        assert!(
4334            out.contains("\t\talpha: \"first value here\",\n"),
4335            "fields not one per line: {out}"
4336        );
4337        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4338    }
4339
4340    #[test]
4341    fn wraps_a_long_argument_list_without_a_trailing_comma() {
4342        // A parameter/argument list rejects a trailing comma in the grammar, so
4343        // the wrapped form must not emit one — `format_source` would refuse the
4344        // output on the round-trip guard if it did.
4345        let src = "commons x {\nfn go() -> Int { combine(firstOperandValue, secondOperandValue, thirdOperandValue, fourthOperandValue) }\n}";
4346        let out = fmt(src);
4347        assert_within_budget(&out);
4348        assert!(
4349            !out.contains(",\n\t\t)"),
4350            "trailing comma in an argument list: {out}"
4351        );
4352        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4353    }
4354
4355    #[test]
4356    fn wraps_long_parameter_lists_behind_the_return_type() {
4357        let src = "context x {\nservice api from http {\non POST(\"/reservations/confirm\") (identifier: String, body: Reservation) -> Effect[HttpResult[Reservation]] by Visitor { Ok(body) }\n}\n}";
4358        let out = fmt(src);
4359        assert_within_budget(&out);
4360        assert!(
4361            out.contains("\t\t\tidentifier: String,\n"),
4362            "params not wrapped: {out}"
4363        );
4364        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4365    }
4366
4367    #[test]
4368    fn breaks_a_long_chain_at_its_dots() {
4369        let src = "commons x {\nfn go(rows: List[Row]) -> List[Int] { rows.filterOnlyTheInteresting((r) => r.nights > 0).mapEachOntoItsValue((r) => r.nights * r.rate).collect() }\n}";
4370        let out = fmt(src);
4371        assert_within_budget(&out);
4372        assert!(
4373            out.contains("\n\t\t\t.collect()"),
4374            "chain not broken at the dots: {out}"
4375        );
4376        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4377    }
4378
4379    #[test]
4380    fn keeps_a_chain_intact_when_only_an_argument_needs_wrapping() {
4381        // The chain itself is short; the `match` inside is what spans lines.
4382        // Breaking at the dots here would be noise, so the chain stays put.
4383        let src = "commons x {\nfn join(parts: List[String]) -> String {\nlet init: Option[String] = None\nparts.fold(init, (acc, p) => match acc {\nSome(s) => Some(s.concat(p)),\nNone => Some(p),\n}).getOrElse(\"\")\n}\n}";
4384        let out = fmt(src);
4385        assert_within_budget(&out);
4386        assert!(
4387            out.contains("parts.fold(init, (acc, p) => match acc {"),
4388            "chain broken needlessly: {out}"
4389        );
4390        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4391    }
4392
4393    #[test]
4394    fn breaks_a_long_conjunction_before_each_operator() {
4395        let src = "commons x {\nfn ok(a: Int, b: Int, c: Int, d: Int) -> Bool { aSufficientlyLongPredicateName(a) && anotherRatherLongPredicate(b) && yetAnotherLongishPredicate(c) && theFinalPredicateHere(d) }\n}";
4396        let out = fmt(src);
4397        assert_within_budget(&out);
4398        assert!(
4399            out.lines().any(|l| l.trim_start().starts_with("&& ")),
4400            "conjunction not broken at the operators: {out}"
4401        );
4402        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4403    }
4404
4405    #[test]
4406    fn never_breaks_before_an_arithmetic_operator() {
4407        // A continuation line opening with `+` does not re-attach on re-parse,
4408        // so an arithmetic run stays on one line however long it gets.
4409        let src = "commons x {\nfn total(a: Int, b: Int, c: Int, d: Int) -> Int { someLongFunctionName(a) + anotherLongFunction(b) + aThirdLongFunction(c) + lastOne(d) }\n}";
4410        let out = fmt(src);
4411        assert!(
4412            !out.lines().any(|l| l.trim_start().starts_with("+ ")),
4413            "broke before `+`, which does not re-parse: {out}"
4414        );
4415        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4416    }
4417
4418    #[test]
4419    fn wraps_an_over_long_actor_auth_config() {
4420        let src = "context x {\nactor Partner { auth = Oidc(issuer = \"https://issuer.example.test\", audience = \"reservations-api\", jwks = \"https://issuer.example.test/jwks.json\"), identity = PartnerId }\n}";
4421        let out = fmt(src);
4422        assert_within_budget(&out);
4423        assert!(
4424            out.contains("\t\tissuer = "),
4425            "scheme args not wrapped: {out}"
4426        );
4427        assert!(out.contains("identity = PartnerId"), "identity lost: {out}");
4428        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4429    }
4430
4431    #[test]
4432    fn a_lone_block_like_argument_hugs_its_call() {
4433        let src = "commons x {\nfn go(items: List[Item]) -> Effect[()] { items.forEachInTurnAndOrder((item: Item) => { let _ <- store.put(item.identifier, item) }) }\n}";
4434        let out = fmt(src);
4435        assert_within_budget(&out);
4436        assert!(
4437            out.contains("((item: Item) => {"),
4438            "sole lambda argument did not hug its call: {out}"
4439        );
4440        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4441    }
4442
4443    #[test]
4444    fn an_unbreakable_line_is_left_long_rather_than_mangled() {
4445        // No break point exists inside a string literal; the 100-column target
4446        // is soft, so the line simply overruns.
4447        let long = "x".repeat(140);
4448        let src = format!("commons x {{\nfn go() -> String {{ \"{long}\" }}\n}}");
4449        let out = fmt(&src);
4450        assert!(
4451            widths(&out).iter().any(|w| *w > 100),
4452            "expected an over-long line: {out}"
4453        );
4454        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4455    }
4456
4457    #[test]
4458    fn wrapping_is_idempotent_and_structure_preserving_across_widths() {
4459        // The round-trip guard inside `format_source` already refuses output
4460        // that re-parses differently, so a successful format at each width is
4461        // itself the structural assertion.
4462        let src = "context x {\ntype R = { id: String, name: String, size: Int }\nfn build(id: String, name: String, size: Int) -> R { R { id: id, name: name, size: size } }\nfn pick(rows: List[R]) -> List[String] { rows.filter((r) => r.size > 0).map((r) => r.name).collect() }\n}";
4463        for width in [40u32, 60, 80, 100, 120] {
4464            let opts = FormatOptions {
4465                max_line_width: width,
4466                ..FormatOptions::default()
4467            };
4468            let out = format_source(src, &opts).unwrap_or_else(|e| {
4469                panic!("width {width}: format refused ({} errors)", e.errors.len())
4470            });
4471            let again = format_source(&out, &opts).unwrap_or_else(|e| {
4472                panic!(
4473                    "width {width}: reformat refused ({} errors)",
4474                    e.errors.len()
4475                )
4476            });
4477            assert_eq!(out, again, "width {width}: not idempotent:\n{out}");
4478        }
4479    }
4480
4481    // Events slice 3b (#978): `@schema(N)` on an event round-trips the same
4482    // way `messages "en" @reference { ... }`'s annotation already does.
4483    #[test]
4484    fn event_schema_annotation_formats_and_is_idempotent() {
4485        let src = "context commerce.order {\nevent PaymentConfirmed @schema(2) = {\norderId: String,\n}\n}";
4486        let out = fmt(src);
4487        assert!(
4488            out.contains("event PaymentConfirmed @schema(2) = {"),
4489            "{out}"
4490        );
4491        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4492    }
4493
4494    // An event with no annotation formats exactly as it did before this
4495    // slice — no stray space before `=`.
4496    #[test]
4497    fn event_with_no_annotation_formats_unchanged() {
4498        let src = "context commerce.order {\nevent PaymentConfirmed = {\norderId: String,\n}\n}";
4499        let out = fmt(src);
4500        assert!(out.contains("event PaymentConfirmed = {"), "{out}");
4501        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4502    }
4503
4504    // Events slice 4 (#985): `via schema(N)` on a subscription header
4505    // round-trips after the `from Events(...)` header's closing `)`.
4506    #[test]
4507    fn via_schema_dispatch_formats_and_is_idempotent() {
4508        let src = "context commerce.order {\nservice OnPayment from Events(PaymentConfirmed) via schema(2) {\non event(e: PaymentConfirmed) -> Effect[()] {\nEffect.pure(())\n}\n}\n}";
4509        let out = fmt(src);
4510        assert!(
4511            out.contains("from Events(PaymentConfirmed) via schema(2)"),
4512            "{out}"
4513        );
4514        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4515    }
4516
4517    // A payload pattern and a `via schema(...)` clause are independent and
4518    // combine on one header — neither one's presence should perturb the
4519    // other's rendering.
4520    #[test]
4521    fn via_schema_dispatch_combines_with_a_payload_pattern() {
4522        let src = "context commerce.order {\nservice OnPayment from Events(PaymentConfirmed { region: Domestic, .. }) via schema(2) {\non event(e: PaymentConfirmed) -> Effect[()] {\nEffect.pure(())\n}\n}\n}";
4523        let out = fmt(src);
4524        assert!(
4525            out.contains("from Events(PaymentConfirmed { region: Domestic, .. }) via schema(2)"),
4526            "{out}"
4527        );
4528        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4529    }
4530
4531    // #990: a `via schema(...)` range and `_` print without spaces, and a
4532    // spaced input normalises.
4533    #[test]
4534    fn via_schema_ranges_and_wildcard_format_and_are_idempotent() {
4535        for (written, printed) in [
4536            ("2 .. 4", "2..4"),
4537            ("2 ..", "2.."),
4538            (".. 4", "..4"),
4539            ("_", "_"),
4540        ] {
4541            let src = format!(
4542                "context commerce.order {{\nservice OnPayment from Events(PaymentConfirmed) via schema({written}) {{\non event(e: PaymentConfirmed) -> Effect[()] {{\nEffect.pure(())\n}}\n}}\n}}"
4543            );
4544            let out = fmt(&src);
4545            assert!(out.contains(&format!("via schema({printed})")), "{out}");
4546            assert_eq!(out, fmt(&out), "not idempotent: {out}");
4547        }
4548    }
4549
4550    // #2699: range patterns print as `lo..hi` with no spaces, in a match arm,
4551    // an or-pattern, a nested payload and a list.
4552    #[test]
4553    fn range_patterns_format_without_spaces_and_are_idempotent() {
4554        let src = "commons c {\nfn f(n: Int, o: Option[Int], xs: List[Int]) -> Int {\nlet 0 .. 9 = n else { 0 }\nlet _ = match o {\nSome(0 .. 9 | 90 .. 99) => 1\nSome(.. -1) => 2\nSome(18 ..) => 3\nSome(_) => 4\nNone => 5\n}\nmatch xs {\n[0 .. 9, ..rest] => 1\n[.. -1] => 2\n_ => 3\n}\n}\n}";
4555        let out = fmt(src);
4556        for want in [
4557            "let 0..9 = n else",
4558            "Some(0..9 | 90..99) =>",
4559            "Some(..-1) =>",
4560            "Some(18..) =>",
4561            "[0..9, ..rest] =>",
4562            "[..-1] =>",
4563        ] {
4564            assert!(out.contains(want), "{want}: {out}");
4565        }
4566        assert_eq!(out, fmt(&out), "not idempotent: {out}");
4567    }
4568}
4569
4570#[cfg(test)]
4571mod snapshot_clause_tests {
4572    use super::*;
4573
4574    /// #2842: the `matches snapshot "<name>"` clause survives formatting — it is
4575    /// part of the statement, not a trailing remark — with its name re-escaped.
4576    #[test]
4577    fn a_snapshot_clause_is_kept() {
4578        let src = "suite demo\n\ncase \"c\" {\n\texpect   read(1)   matches   snapshot   \"a \\\"q\\\" name\"\n\tlet matches = 1\n\texpect matches == 1\n}\n";
4579        let once = format_source(src, &FormatOptions::default()).expect("formats");
4580        assert!(
4581            once.contains("\texpect read(1) matches snapshot \"a \\\"q\\\" name\"\n"),
4582            "{once}"
4583        );
4584        assert!(once.contains("let matches = 1"), "{once}");
4585        let twice = format_source(&once, &FormatOptions::default()).expect("formats again");
4586        assert_eq!(once, twice);
4587    }
4588
4589    /// A statement that starts with a variable named `matches` still parses.
4590    #[test]
4591    fn a_bare_matches_after_an_expect_is_the_next_statement() {
4592        let src = "suite demo\n\ncase \"c\" {\n\tlet matches = 1\n\texpect true\n\texpect matches == 1\n}\n";
4593        format_source(src, &FormatOptions::default()).expect("formats");
4594    }
4595}