Skip to main content

bynk_syntax/
print.rs

1//! The expression/pattern/statement printer: renders a parsed AST fragment back to Bynk
2//! source text.
3//!
4//! Moved here from `bynk-fmt` (crate-hygiene A3, `design/archive/retired-tracks.md` §5) so the
5//! checker can quote an expression in a diagnostic without depending on the formatter. The
6//! formatter and the checker both call it from here; the text is unchanged byte for byte.
7
8use crate::ast::*;
9use crate::span::Span;
10
11thread_local! {
12    /// The source being formatted, so a string literal can be re-emitted as it
13    /// was written (#2619). Set by `render_units` (in `bynk-fmt`) for the duration of a render.
14    static WRITTEN_SOURCE: std::cell::RefCell<Option<std::rc::Rc<str>>> =
15        const { std::cell::RefCell::new(None) };
16}
17
18/// Scope guard installing `WRITTEN_SOURCE`.
19pub struct WrittenForms(Option<std::rc::Rc<str>>);
20
21impl WrittenForms {
22    pub fn enter(source: &str) -> Self {
23        let new = Some(std::rc::Rc::<str>::from(source));
24        Self(WRITTEN_SOURCE.with(|cell| cell.replace(new)))
25    }
26}
27
28impl Drop for WrittenForms {
29    fn drop(&mut self) {
30        let previous = self.0.take();
31        WRITTEN_SOURCE.with(|cell| *cell.borrow_mut() = previous);
32    }
33}
34
35/// #2619: a string literal's written form, when the source holds one that is
36/// worth preserving: a raw or multi-line literal, or one using a `\u{…}`
37/// escape. It is the source text at `e.span`, kept only if it decodes to
38/// `value`, so a synthesised or mis-spanned literal falls back to the canonical
39/// rendering. Formatting must not turn `r"\d+"` into `"\\d+"`.
40fn written_string_form(e: &Expr, value: Option<&str>) -> Option<String> {
41    written_literal(e.span, value)
42}
43
44/// [`written_string_form`] for a literal at `span` anywhere (an expression, a
45/// `Matches` argument, a message template).
46fn written_literal(span: Span, value: Option<&str>) -> Option<String> {
47    WRITTEN_SOURCE.with(|cell| {
48        let source = cell.borrow();
49        let text = source.as_deref()?.get(span.range())?;
50        let special = text.starts_with("r\"")
51            || text.starts_with("r#")
52            || text.starts_with("\"\"\"")
53            || text.contains("\\u{");
54        if !special {
55            return None;
56        }
57        // A multi-line literal is re-emitted at column zero, with the closing
58        // delimiter's indentation removed from every line: the value is
59        // unchanged (that indentation is stripped anyway), the formatter's
60        // re-indent pass then sets the current depth for all of it, and the
61        // result no longer depends on how the author happened to indent it.
62        let text = if text.starts_with("\"\"\"") || text.starts_with("r\"\"\"") {
63            dedent_multiline(text)
64        } else {
65            text.to_string()
66        };
67        match value {
68            Some(value) => {
69                let decoded = crate::lexer::decode_string_literal(&text, span).ok()?;
70                (decoded == value).then_some(text)
71            }
72            // An interpolated multi-line string is kept whole only when it is
73            // multi-line (its holes would otherwise be reformatted).
74            None => (text.starts_with("\"\"\"") || text.contains("\\u{")).then_some(text),
75        }
76    })
77}
78
79/// Strip the closing delimiter's indentation from every line of a multi-line
80/// literal's text, so it sits at column zero (see [`written_string_form`]).
81fn dedent_multiline(text: &str) -> String {
82    let last = text.rsplit('\n').next().unwrap_or("");
83    let indent = &last[..last.len() - last.trim_start_matches([' ', '\t']).len()];
84    let mut out = String::with_capacity(text.len());
85    for (i, line) in text.split('\n').enumerate() {
86        if i > 0 {
87            out.push('\n');
88        }
89        if i == 0 {
90            // The opening line keeps a language tag (`"""sql`, #2958) as
91            // written, minus any trailing spaces after it.
92            let (line, cr) = line.strip_suffix('\r').map_or((line, ""), |l| (l, "\r"));
93            out.push_str(line.trim_end_matches([' ', '\t']));
94            out.push_str(cr);
95        } else if let Some(rest) = line.strip_prefix(indent) {
96            out.push_str(rest);
97        } else if line.trim().is_empty() {
98            // a blank line shorter than the indentation is empty
99        } else {
100            out.push_str(line);
101        }
102    }
103    out
104}
105
106/// v0.182 (#664): render a call-site actor clause — `by User("bob")` or the
107/// unit-identity `by Visitor`.
108pub fn call_site_actor_src(p: &CallSiteActor) -> String {
109    match (&p.identity, &p.claims) {
110        // #2380 (L5): an `Oidc` principal may carry the token's claims too.
111        (Some(id), Some(claims)) => format!(
112            "by {}({}, {})",
113            p.actor.name,
114            expr_with_prec(id, 0),
115            expr_with_prec(claims, 0)
116        ),
117        (Some(id), None) => format!("by {}({})", p.actor.name, expr_with_prec(id, 0)),
118        (None, _) => format!("by {}", p.actor.name),
119    }
120}
121
122pub fn type_ref_to_string(t: &TypeRef) -> String {
123    match t {
124        TypeRef::Base(b, _) => b.name().to_string(),
125        TypeRef::Named(id) => id.name.clone(),
126        TypeRef::Result(a, b, _) => format!(
127            "Result[{}, {}]",
128            type_ref_to_string(a),
129            type_ref_to_string(b)
130        ),
131        TypeRef::Option(t, _) => format!("Option[{}]", type_ref_to_string(t)),
132        TypeRef::Effect(t, _) => format!("Effect[{}]", type_ref_to_string(t)),
133        TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", type_ref_to_string(t)),
134        TypeRef::QueueResult(_) => "QueueResult".to_string(),
135        TypeRef::Asset(_) => "Asset".to_string(),
136        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
137        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
138        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
139        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
140        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
141        TypeRef::List(t, _) => format!("List[{}]", type_ref_to_string(t)),
142        TypeRef::Set(t, _) => format!("Set[{}]", type_ref_to_string(t)),
143        TypeRef::Query(t, _) => format!("Query[{}]", type_ref_to_string(t)),
144        TypeRef::Stream(t, _) => format!("Stream[{}]", type_ref_to_string(t)),
145        TypeRef::Connection(t, _) => format!("Connection[{}]", type_ref_to_string(t)),
146        TypeRef::History(t, _) => format!("History[{}]", type_ref_to_string(t)),
147        TypeRef::Map(k, v, _) => {
148            format!("Map[{}, {}]", type_ref_to_string(k), type_ref_to_string(v))
149        }
150        TypeRef::ValidationError(_) => "ValidationError".to_string(),
151        TypeRef::DecodeError(_) => "DecodeError".to_string(),
152        TypeRef::Unit(_) => "()".to_string(),
153        // v0.157 (ADR 0183): a user generic-type application, as written.
154        TypeRef::App { name, args, .. } => format!(
155            "{}[{}]",
156            name.name,
157            args.iter()
158                .map(type_ref_to_string)
159                .collect::<Vec<_>>()
160                .join(", ")
161        ),
162        TypeRef::Fn(params, ret, _) => {
163            let lhs = match params.len() {
164                0 => "()".to_string(),
165                1 if !matches!(params[0], TypeRef::Fn(..)) => type_ref_to_string(&params[0]),
166                _ => format!(
167                    "({})",
168                    params
169                        .iter()
170                        .map(type_ref_to_string)
171                        .collect::<Vec<_>>()
172                        .join(", ")
173                ),
174            };
175            format!("{lhs} -> {}", type_ref_to_string(ret))
176        }
177    }
178}
179
180pub fn refinement_to_string(r: &Refinement) -> String {
181    let mut s = String::new();
182    for (i, p) in r.predicates.iter().enumerate() {
183        if i > 0 {
184            s.push_str(" && ");
185        }
186        s.push_str(&pred_to_string(p));
187    }
188    s
189}
190
191/// A literal as written if it has a special form, else canonically escaped.
192pub fn literal_text(span: Span, value: &str) -> String {
193    written_literal(span, Some(value)).unwrap_or_else(|| format!("\"{}\"", escape_string(value)))
194}
195
196/// The span of a `Matches(…)` predicate's string argument.
197pub fn matches_argument_span(p: &RefinementPred) -> Span {
198    WRITTEN_SOURCE.with(|cell| {
199        let source = cell.borrow();
200        let Some(text) = source.as_deref().and_then(|s| s.get(p.span.range())) else {
201            return p.span;
202        };
203        let (Some(open), Some(close)) = (text.find('('), text.rfind(')')) else {
204            return p.span;
205        };
206        let inner = &text[open + 1..close];
207        let lead = inner.len() - inner.trim_start().len();
208        let start = p.span.start + open + 1 + lead;
209        Span::new_in(p.span.file, start, start + inner.trim().len())
210    })
211}
212
213fn pred_to_string(p: &RefinementPred) -> String {
214    let arg = |n: i64| p.arg_text.clone().unwrap_or_else(|| n.to_string());
215    match &p.kind {
216        PredKind::Matches(re) => format!("Matches({})", literal_text(matches_argument_span(p), re)),
217        PredKind::InRange(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
218        PredKind::InRangeF(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
219        PredKind::InRangeD(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
220        PredKind::MinLength(n) => format!("MinLength({})", arg(*n)),
221        PredKind::MaxLength(n) => format!("MaxLength({})", arg(*n)),
222        PredKind::Length(n) => format!("Length({})", arg(*n)),
223        PredKind::NonNegative => "NonNegative".to_string(),
224        PredKind::Positive => "Positive".to_string(),
225        PredKind::NonEmpty => "NonEmpty".to_string(),
226        PredKind::IsoDate => "IsoDate".to_string(),
227        PredKind::Cron => "Cron".to_string(),
228    }
229}
230
231pub fn escape_string(s: &str) -> String {
232    let mut out = String::with_capacity(s.len());
233    for ch in s.chars() {
234        match ch {
235            '\\' => out.push_str("\\\\"),
236            '"' => out.push_str("\\\""),
237            '\n' => out.push_str("\\n"),
238            '\t' => out.push_str("\\t"),
239            // #2619: a CR or NUL cannot sit raw in a literal, nor can other control
240            // characters; they print as `\u{…}`. Anything else (a ZWJ, an
241            // RLM, a no-break space) is written as it was.
242            '\r' => out.push_str("\\r"),
243            '\0' => out.push_str("\\0"),
244            c if c.is_control() => {
245                out.push_str(&format!("\\u{{{:X}}}", c as u32));
246            }
247            c => out.push(c),
248        }
249    }
250    out
251}
252
253pub fn expr_to_string(e: &Expr) -> String {
254    expr_with_prec(e, 0)
255}
256
257// Operator precedences (smaller = binds looser):
258//   1: || 2: && 3: == != 4: < <= > >= 5: + - 6: * / 7: unary ! - 8: postfix . () ?
259pub fn binop_prec(op: BinOp) -> u8 {
260    match op {
261        // v0.80: `implies` is the lowest-precedence binary operator (below `||`).
262        BinOp::Implies => 0,
263        BinOp::Or => 1,
264        BinOp::And => 2,
265        BinOp::Eq | BinOp::NotEq => 3,
266        BinOp::Lt | BinOp::LtEq | BinOp::Gt | BinOp::GtEq => 4,
267        BinOp::Add | BinOp::Sub => 5,
268        BinOp::Mul | BinOp::Div => 6,
269    }
270}
271
272pub fn expr_with_prec(e: &Expr, parent_prec: u8) -> String {
273    match &e.kind {
274        // v0.142 (ADR 0166): the stored lexeme verbatim — formatting must not
275        // normalise away the author's `_` digit separators.
276        ExprKind::IntLit { lexeme, .. } => lexeme.clone(),
277        // v0.21: the stored lexeme verbatim — formatting must not normalise.
278        ExprKind::FloatLit { lexeme, .. } => lexeme.clone(),
279        ExprKind::DecimalLit { lexeme, .. } => lexeme.clone(),
280        // v0.86 (ADR 0112): a duration literal `<value>.<unit>`.
281        ExprKind::DurationLit { value, unit, .. } => format!("{value}.{}", unit.name_for(*value)),
282        ExprKind::StrLit(s) => {
283            written_string_form(e, Some(s)).unwrap_or_else(|| format!("\"{}\"", escape_string(s)))
284        }
285        // v0.43: re-emit the interpolated string — chunks re-escaped, each
286        // hole as `\(expr)`. Re-escaping a chunk's literal `\` to `\\` keeps a
287        // source `\\(` (an escaped `\(`) round-tripping as text, not a hole.
288        ExprKind::InterpStr(parts) => {
289            if let Some(written) = written_string_form(e, None) {
290                return written;
291            }
292            let mut out = String::from("\"");
293            for part in parts {
294                match part {
295                    InterpPart::Chunk(text) => out.push_str(&escape_string(text)),
296                    InterpPart::Hole(hole) => {
297                        out.push_str(&format!("\\({})", expr_with_prec(hole, 0)));
298                    }
299                }
300            }
301            out.push('"');
302            out
303        }
304        ExprKind::BoolLit(b) => b.to_string(),
305        ExprKind::UnitLit => "()".to_string(),
306        ExprKind::Ident(id) => id.name.clone(),
307        ExprKind::ListLit(elems, ..) => format!(
308            "[{}]",
309            elems
310                .iter()
311                .map(expr_to_string)
312                .collect::<Vec<_>>()
313                .join(", ")
314        ),
315        ExprKind::Call {
316            name,
317            type_args,
318            args,
319            ..
320        } => {
321            let targs = if type_args.is_empty() {
322                String::new()
323            } else {
324                format!(
325                    "[{}]",
326                    type_args
327                        .iter()
328                        .map(type_ref_to_string)
329                        .collect::<Vec<_>>()
330                        .join(", ")
331                )
332            };
333            let parts: Vec<String> = args.iter().map(|a| expr_with_prec(a, 0)).collect();
334            format!("{}{}({})", name.name, targs, parts.join(", "))
335        }
336        ExprKind::BinOp(op, l, r) => {
337            let prec = binop_prec(*op);
338            let inner = format!(
339                "{} {} {}",
340                expr_with_prec(l, prec),
341                op.name(),
342                expr_with_prec(r, prec + 1)
343            );
344            if prec < parent_prec {
345                format!("({inner})")
346            } else {
347                inner
348            }
349        }
350        ExprKind::UnaryOp(op, inner) => {
351            // Unary binds tightly (prec 7).
352            let s = format!("{}{}", op.name(), expr_with_prec(inner, 7));
353            if parent_prec > 7 { format!("({s})") } else { s }
354        }
355        ExprKind::Paren(inner) => format!("({})", expr_with_prec(inner, 0)),
356        // v0.20a: a lambda prints as `(params) => body`.
357        ExprKind::Lambda(lambda) => {
358            let params: Vec<String> = lambda.params.iter().map(lambda_param_src).collect();
359            let body = match lambda_body_src(lambda) {
360                LambdaBodySrc::Block(b) => format_block_oneline(b),
361                LambdaBodySrc::Expr(e) => match &e.kind {
362                    ExprKind::Block(b) => format_block_oneline(b),
363                    _ => expr_with_prec(e, 0),
364                },
365            };
366            format!("({}) => {}", params.join(", "), body)
367        }
368        ExprKind::Block(b) => format_block_oneline(b),
369        ExprKind::If {
370            cond,
371            then_block,
372            else_block,
373        } => {
374            // v0.146 (ADR 0170): an `if` with no `else` carries a synthesised
375            // unit else-branch — omit it so the else-less form round-trips.
376            if else_block.is_synth_unit() {
377                format!(
378                    "if {} {}",
379                    expr_with_prec(cond, 0),
380                    format_block_oneline(then_block),
381                )
382            } else if let Some(chained) = else_if_tail(else_block) {
383                format!(
384                    "if {} {} else {}",
385                    expr_with_prec(cond, 0),
386                    format_block_oneline(then_block),
387                    expr_with_prec(chained, 0),
388                )
389            } else {
390                format!(
391                    "if {} {} else {}",
392                    expr_with_prec(cond, 0),
393                    format_block_oneline(then_block),
394                    format_block_oneline(else_block),
395                )
396            }
397        }
398        ExprKind::Ok(v) => format!("Ok({})", expr_with_prec(v, 0)),
399        ExprKind::Err(v) => format!("Err({})", expr_with_prec(v, 0)),
400        ExprKind::Some(v) => format!("Some({})", expr_with_prec(v, 0)),
401        ExprKind::None => "None".to_string(),
402        ExprKind::Question(v) => format!("{}?", expr_with_prec(v, 8)),
403        ExprKind::RecordConstruction {
404            type_name, fields, ..
405        } => {
406            let parts: Vec<String> = fields
407                .iter()
408                .map(|f| match &f.value {
409                    Some(v) => format!("{}: {}", f.name.name, expr_with_prec(v, 0)),
410                    None => f.name.name.clone(),
411                })
412                .collect();
413            if parts.is_empty() {
414                format!("{} {{}}", type_name.name)
415            } else {
416                format!("{} {{ {} }}", type_name.name, parts.join(", "))
417            }
418        }
419        ExprKind::FieldAccess { receiver, field } => {
420            format!("{}.{}", expr_with_prec(receiver, 8), field.name)
421        }
422        ExprKind::MethodCall {
423            receiver,
424            method,
425            type_args,
426            args,
427            ..
428        } => {
429            let targs = if type_args.is_empty() {
430                String::new()
431            } else {
432                format!(
433                    "[{}]",
434                    type_args
435                        .iter()
436                        .map(type_ref_to_string)
437                        .collect::<Vec<_>>()
438                        .join(", ")
439                )
440            };
441            let parts: Vec<String> = args.iter().map(|a| expr_with_prec(a, 0)).collect();
442            format!(
443                "{}.{}{targs}({})",
444                expr_with_prec(receiver, 8),
445                method.name,
446                parts.join(", ")
447            )
448        }
449        ExprKind::Match { discriminant, arms } => {
450            let mut out = String::new();
451            out.push_str("match ");
452            out.push_str(&expr_with_prec(discriminant, 0));
453            out.push_str(" {\n");
454            for arm in arms {
455                out.push('\t');
456                out.push_str(&pattern_to_string(&arm.pattern));
457                if let Some(guard) = &arm.guard {
458                    out.push_str(" if ");
459                    out.push_str(&expr_with_prec(guard, 0));
460                }
461                out.push_str(" => ");
462                match &arm.body {
463                    MatchBody::Expr(e) => out.push_str(&expr_with_prec(e, 0)),
464                    MatchBody::Block(b) => out.push_str(&format_block_oneline(b)),
465                }
466                out.push_str(",\n");
467            }
468            out.push('}');
469            out
470        }
471        ExprKind::Is { value, pattern } => {
472            format!(
473                "{} is {}",
474                expr_with_prec(value, 4),
475                is_pattern_src(pattern)
476            )
477        }
478        ExprKind::RecordSpread {
479            type_name,
480            base,
481            overrides,
482            ..
483        } => {
484            let mut parts = vec![format!("...{}", expr_with_prec(base, 0))];
485            for f in overrides {
486                if let Some(v) = &f.value {
487                    parts.push(format!("{}: {}", f.name.name, expr_with_prec(v, 0)));
488                } else {
489                    parts.push(f.name.name.clone());
490                }
491            }
492            let body = parts.join(", ");
493            match type_name {
494                Some(tn) => format!("{} {{ {} }}", tn.name, body),
495                None => format!("{{ {} }}", body),
496            }
497        }
498        ExprKind::EffectPure(v) => format!("Effect.pure({})", expr_with_prec(v, 0)),
499        ExprKind::Expect(v) => format!("expect {}", expr_with_prec(v, 0)),
500        ExprKind::Val { type_ref, args, .. } => {
501            let t = type_ref_to_string(type_ref);
502            if args.is_empty() {
503                format!("Val[{t}]")
504            } else {
505                let a = args
506                    .iter()
507                    .map(|x| expr_with_prec(x, 0))
508                    .collect::<Vec<_>>()
509                    .join(", ");
510                format!("Val[{t}]({a})")
511            }
512        }
513        ExprKind::Wire(inner) => format!("Wire({})", expr_with_prec(inner, 0)),
514        ExprKind::Trace { cap, op } => format!("trace({}.{})", cap.name, op.name),
515        // #1706: the fault claim — the call, then the contextual `faults`.
516        // #1812: the call-site principal sits between the call and `faults`,
517        // in the same position as on an effect-let.
518        ExprKind::Faults(f) => match &f.principal {
519            Some(p) => format!(
520                "{} {} faults",
521                expr_with_prec(&f.call, 0),
522                call_site_actor_src(p)
523            ),
524            None => format!("{} faults", expr_with_prec(&f.call, 0)),
525        },
526        ExprKind::Observation(o) => {
527            let subject = format!("{}.{}", o.cap.name, o.op.name);
528            match &o.matcher {
529                ObservationMatcher::NeverCalled => format!("{subject} never called"),
530                ObservationMatcher::Before { cap, op } => {
531                    format!("{subject} before {}.{}", cap.name, op.name)
532                }
533                ObservationMatcher::Called { count, with_pred } => {
534                    let mut s = format!("{subject} called");
535                    if let Some(c) = count {
536                        if matches!(c.kind, ExprKind::IntLit { value: 1, .. }) {
537                            s.push_str(" once");
538                        } else {
539                            s.push_str(&format!(" {} times", expr_with_prec(c, 0)));
540                        }
541                    }
542                    if let Some(p) = with_pred {
543                        s.push_str(&format!(" with {}", expr_with_prec(p, 0)));
544                    }
545                    s
546                }
547            }
548        }
549    }
550}
551
552/// #2891: the `if` an `else if` desugars to. The parser wraps it in a
553/// brace-less block with the same span as the `if` itself, which tells it apart
554/// from an explicit `else { if … }` (whose block spans its braces).
555pub fn else_if_tail(b: &Block) -> Option<&Expr> {
556    (b.statements.is_empty()
557        && b.tail_leading_comments.is_empty()
558        && !b.implicit_tail
559        && matches!(b.tail.kind, ExprKind::If { .. })
560        && b.span == b.tail.span)
561        .then_some(&*b.tail)
562}
563
564pub fn pattern_to_string(p: &Pattern) -> String {
565    match p {
566        Pattern::Wildcard(_) => "_".to_string(),
567        // ADR 0169: a bare name binding renders as its identifier.
568        Pattern::Binding(id) => id.name.clone(),
569        // v0.130: literal patterns render as their source literal.
570        Pattern::Literal { value, text, .. } => match value {
571            LiteralValue::Int(n) => text.clone().unwrap_or_else(|| n.to_string()),
572            LiteralValue::Str(s) => format!("\"{}\"", escape_string(s)),
573            LiteralValue::Bool(b) => b.to_string(),
574        },
575        // #2699: `lo..hi`, `lo..`, `..hi`, with no spaces.
576        Pattern::Range(r) => r.describe_source(),
577        // #472: `p where predicate` — the inner pattern, then the predicate
578        // list rendered the same way a `type X = Base where P` refinement is.
579        Pattern::Refined {
580            inner, predicate, ..
581        } => format!(
582            "{} where {}",
583            pattern_to_string(inner),
584            refinement_to_string(predicate)
585        ),
586        Pattern::Variant {
587            type_name,
588            variant,
589            bindings,
590            ..
591        } => {
592            let name_part = match type_name {
593                Some(t) => format!("{}.{}", t.name, variant.name),
594                None => variant.name.clone(),
595            };
596            if bindings.is_empty() {
597                name_part
598            } else {
599                // ADR 0169: each payload binding is a full sub-pattern.
600                let parts: Vec<String> = bindings
601                    .iter()
602                    .map(|b| match &b.kind {
603                        PatternBindingKind::Positional { pattern } => pattern_to_string(pattern),
604                        PatternBindingKind::Named { field, pattern } => {
605                            format!("{}: {}", field.name, pattern_to_string(pattern))
606                        }
607                    })
608                    .collect();
609                format!("{}({})", name_part, parts.join(", "))
610            }
611        }
612        // #2641: a record pattern renders like a record literal; the trailing
613        // `..` is part of the syntax, not an optional marker.
614        Pattern::Record {
615            type_name, fields, ..
616        } => {
617            let mut parts: Vec<String> = fields
618                .iter()
619                .map(|(name, sub)| match sub {
620                    Some(p) => format!("{}: {}", name.name, pattern_to_string(p)),
621                    None => name.name.clone(),
622                })
623                .collect();
624            parts.push("..".to_string());
625            format!("{} {{ {} }}", type_name.name, parts.join(", "))
626        }
627        // #2680: a list pattern renders like a list literal, with the rest
628        // marker last.
629        Pattern::List { elems, rest, .. } => {
630            let mut parts: Vec<String> = elems.iter().map(pattern_to_string).collect();
631            if let Some(r) = rest {
632                parts.push(match &r.binder {
633                    Some(b) => format!("..{}", b.name),
634                    None => "..".to_string(),
635                });
636            }
637            format!("[{}]", parts.join(", "))
638        }
639        // #474: an or-pattern renders as its alternatives joined by `|`.
640        Pattern::Or(alts, _) => alts
641            .iter()
642            .map(pattern_to_string)
643            .collect::<Vec<_>>()
644            .join(" | "),
645    }
646}
647
648/// #2641: a pattern after `is`. A record pattern there must be parenthesised —
649/// its `{` would otherwise read as the block that follows the condition — so a
650/// record, or an or-pattern with a record alternative, keeps the parentheses
651/// the parser dropped as transparent grouping.
652pub fn is_pattern_src(p: &Pattern) -> String {
653    let src = pattern_to_string(p);
654    let has_record = match p {
655        Pattern::Record { .. } => true,
656        Pattern::Or(alts, _) => alts.iter().any(|a| matches!(a, Pattern::Record { .. })),
657        _ => false,
658    };
659    if has_record { format!("({src})") } else { src }
660}
661
662/// #981: whether a block's `()` tail should be omitted rather than printed.
663///
664/// A `()` tail — whether the parser synthesised it ([`Block::implicit_tail`])
665/// or the user wrote it out explicitly — is exactly the block's default
666/// value, so dropping it is loss-free: the parser re-derives the same
667/// implicit unit tail either way (v0.7 / v0.146, ADR 0170).
668///
669/// Omitting it is not just an idempotency nicety, it is required for
670/// correctness whenever anything precedes the tail (a statement, a `case`'s
671/// `stub` clause): Bynk has no statement terminator, so a printed `()`
672/// immediately after a preceding line's last token re-attaches to it as a
673/// zero-arg call on re-parse (`x` / `()` → `x()`) rather than staying two
674/// separate constructs. #735 only special-cased the *implicit*-tail shape;
675/// #981 found the identical corruption for an *explicit* `()` tail (e.g. the
676/// last statement of a `match` arm's block), which is exactly as dangerous
677/// once anything comes before it. So this covers both, structurally, rather
678/// than special-casing another syntactic position.
679pub fn omit_unit_tail(b: &Block) -> bool {
680    matches!(b.tail.kind, ExprKind::UnitLit) && b.tail_leading_comments.is_empty()
681}
682
683fn format_block_oneline(b: &Block) -> String {
684    if b.statements.is_empty() {
685        // v0.146 (ADR 0170): an empty block with a synthesised `()` tail prints
686        // as `{}` — printing `{ () }` would not round-trip against the parser's
687        // implicit-tail synthesis.
688        if b.implicit_tail {
689            "{}".to_string()
690        } else {
691            format!("{{ {} }}", expr_with_prec(&b.tail, 0))
692        }
693    } else {
694        // Multi-line block — render with newlines and tab indentation.
695        let mut out = String::from("{\n");
696        block_body_lines(b, &mut out);
697        out.push('}');
698        out
699    }
700}
701
702/// The string form of [`Formatter::format_block_body`]: each statement and
703/// the tail on its own tab-indented line, a `let … else` printed back as
704/// written (#2010).
705fn block_body_lines(b: &Block, out: &mut String) {
706    for stmt in &b.statements {
707        if let Some((l, effectful, le)) = let_else_binding(stmt)
708            && let ExprKind::Match { arms, .. } = &b.tail.kind
709            && let Some(MatchBody::Block(rest)) = arms.first().map(|a| &a.body)
710        {
711            out.push('\t');
712            out.push_str(&let_else_to_string(l, effectful, le, arms));
713            out.push('\n');
714            block_body_lines(rest, out);
715            return;
716        }
717        out.push('\t');
718        out.push_str(&stmt_to_string(stmt));
719        out.push('\n');
720    }
721    if !omit_unit_tail(b) {
722        out.push('\t');
723        out.push_str(&expr_with_prec(&b.tail, 0));
724        out.push('\n');
725    }
726}
727
728/// #2712: a lambda's body as the author wrote it.
729pub enum LambdaBodySrc<'a> {
730    Expr(&'a Expr),
731    Block(&'a Block),
732}
733
734/// #2712: the body a lambda with pattern parameters was written with. The
735/// parser wraps it, one level per pattern parameter (first outermost), in
736/// `{ let __letElse = __lambdaArg; match __letElse { P => { <rest> } } }`;
737/// this peels those back off. A lambda with no pattern parameter is untouched.
738pub fn lambda_body_src(lambda: &LambdaExpr) -> LambdaBodySrc<'_> {
739    let patterns = lambda.params.iter().filter(|p| p.pattern.is_some()).count();
740    if patterns == 0 {
741        return LambdaBodySrc::Expr(&lambda.body);
742    }
743    let ExprKind::Block(block) = &lambda.body.kind else {
744        return LambdaBodySrc::Expr(&lambda.body);
745    };
746    let mut block: &Block = block;
747    for _ in 0..patterns {
748        let ExprKind::Match { arms, .. } = &block.tail.kind else {
749            return LambdaBodySrc::Expr(&lambda.body);
750        };
751        let Some(MatchBody::Block(rest)) = arms.first().map(|a| &a.body) else {
752            return LambdaBodySrc::Expr(&lambda.body);
753        };
754        block = rest;
755    }
756    if lambda.block_body {
757        LambdaBodySrc::Block(block)
758    } else {
759        LambdaBodySrc::Expr(&block.tail)
760    }
761}
762
763/// #2010: the hidden binding a `let … else` desugars into, if `s` is one —
764/// with whether it was `<-` and the sugar's own marker.
765pub fn let_else_binding(s: &Statement) -> Option<(&LetStmt, bool, &LetElse)> {
766    match s {
767        Statement::Let(l) => l.let_else.as_ref().map(|le| (l, false, le)),
768        Statement::EffectLet(l) => l.let_else.as_ref().map(|le| (l, true, le)),
769        _ => None,
770    }
771}
772
773/// #2010: a `let … else` pattern as source. After `let`, a bare name is a
774/// binding, not a pattern (`let Missing | Late = p` would re-parse as a
775/// binding named `Missing`), so a pattern whose text opens with a name not
776/// followed by `(`, `.` or `{` keeps the parentheses its author had to write.
777/// `None`, `true` and `false` are keywords, not names, so they need none.
778pub fn let_pattern_src(p: &Pattern) -> String {
779    let src = pattern_to_string(p);
780    let name_len = src
781        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
782        .unwrap_or(src.len());
783    let opens_with_name = src.starts_with(|c: char| c.is_ascii_alphabetic())
784        && !matches!(&src[..name_len], "None" | "true" | "false");
785    let then = src[name_len..].chars().next();
786    // #2654: `Name {` opens a record pattern, so it needs no parentheses.
787    let opens_record = src[name_len..].trim_start().starts_with('{');
788    if opens_with_name && !opens_record && !matches!(then, Some('(' | '.')) {
789        format!("({src})")
790    } else {
791        src
792    }
793}
794
795/// #2010: the single-line string form of a `let … else` (see
796/// [`Formatter::format_let_else`]).
797fn let_else_to_string(l: &LetStmt, effectful: bool, le: &LetElse, arms: &[MatchArm]) -> String {
798    let mut out = format!(
799        "let {} {} {}",
800        let_pattern_src(&arms[0].pattern),
801        if effectful { "<-" } else { "=" },
802        expr_with_prec(&l.value, 0)
803    );
804    if let Some(p) = &l.principal {
805        out.push_str(&format!(" {}", call_site_actor_src(p)));
806    }
807    match (le.form, arms.get(1).map(|a| &a.body)) {
808        (LetElseForm::Plain, _) => {}
809        (LetElseForm::Block, Some(MatchBody::Block(otherwise))) => {
810            out.push_str(&format!(" else {}", format_block_oneline(otherwise)));
811        }
812        _ => {
813            let rendered: Vec<String> = arms[1..]
814                .iter()
815                .map(|a| {
816                    let body = match &a.body {
817                        MatchBody::Expr(e) => expr_with_prec(e, 0),
818                        MatchBody::Block(b) => format_block_oneline(b),
819                    };
820                    let guard = a
821                        .guard
822                        .as_ref()
823                        .map(|g| format!(" if {}", expr_with_prec(g, 0)))
824                        .unwrap_or_default();
825                    format!("{}{guard} => {body}", pattern_to_string(&a.pattern))
826                })
827                .collect();
828            out.push_str(&format!(" else match {{ {} }}", rendered.join(", ")));
829        }
830    }
831    out
832}
833
834fn stmt_to_string(s: &Statement) -> String {
835    match s {
836        Statement::Let(l) => {
837            let mut out = format!("let {}", l.name.name);
838            if let Some(t) = &l.type_annot {
839                out.push_str(&format!(": {}", type_ref_to_string(t)));
840            }
841            out.push_str(&format!(" = {}", expr_with_prec(&l.value, 0)));
842            out
843        }
844        Statement::EffectLet(l) => {
845            let mut out = format!("let {}", l.name.name);
846            if let Some(t) = &l.type_annot {
847                out.push_str(&format!(": {}", type_ref_to_string(t)));
848            }
849            out.push_str(&format!(" <- {}", expr_with_prec(&l.value, 0)));
850            if let Some(p) = &l.principal {
851                out.push_str(&format!(" {}", call_site_actor_src(p)));
852            }
853            out
854        }
855        Statement::Expect(a) => format!(
856            "expect {}{}",
857            expr_with_prec(&a.value, 0),
858            a.snapshot.as_ref().map_or(String::new(), |c| format!(
859                " matches snapshot \"{}\"",
860                escape_string(&c.name)
861            ))
862        ),
863        Statement::Do(d) => format!("do {}", expr_with_prec(&d.value, 0)),
864        Statement::Assign(a) => format!("{} := {}", a.target.name, expr_with_prec(&a.value, 0)),
865        Statement::Advance(a) => {
866            format!("advance {} by {}", a.cap.name, expr_with_prec(&a.amount, 0))
867        }
868        Statement::Par(p) => {
869            let body: Vec<String> = p.statements.iter().map(stmt_to_string).collect();
870            format!("par {{ {} }}", body.join(" "))
871        }
872    }
873}
874
875/// #2712: a lambda parameter as source — the author's record pattern when it
876/// has one (its hidden binder never prints), else the name and any annotation.
877pub fn lambda_param_src(p: &LambdaParam) -> String {
878    let name = if p.is_wildcard() { "_" } else { &p.name.name };
879    match (&p.pattern, &p.type_ref) {
880        (Some(pattern), _) => pattern_to_string(pattern),
881        (None, Some(tr)) => format!("{name}: {}", type_ref_to_string(tr)),
882        (None, None) => name.to_string(),
883    }
884}