Skip to main content

bynk_syntax/
parser.rs

1//! Hand-written recursive-descent parser for Bynk v0.
2//!
3//! Token grammar in spec §4. The expression parser uses one function per
4//! precedence level (§4.4). Errors carry spans and short fix-oriented
5//! messages. The parser recovers at declaration level, skipping a malformed
6//! declaration and carrying on, so several parse errors can be reported per file.
7
8use crate::ast::*;
9use crate::error::CompileError;
10use crate::lexer::{
11    Token, TokenKind, comment_body, comment_is_legacy, doc_block_content, doc_fence_len,
12    doc_line_is_legacy, doc_line_text, has_blank_line_between, legacy_comment_error,
13    legacy_doc_line_error,
14};
15use crate::span::Span;
16mod declarations;
17mod duration;
18mod expressions;
19mod staircase;
20mod statements;
21mod types;
22
23/// Side-channel store for line-comment trivia (v1.1 LSP spec §3.5).
24///
25/// Built once up-front by [`split_trivia`] from the raw lexer token stream.
26/// Comments are removed from the token stream the parser walks; their text
27/// is filed into `leading` (comments on lines preceding a content token)
28/// and `trailing` (a single comment on the same line as a content token).
29/// The parser consumes entries through [`TriviaTable::take_leading`] and
30/// [`TriviaTable::take_trailing`] as it recognises declarations.
31#[derive(Debug, Default)]
32struct TriviaTable {
33    /// `leading[i]` holds the comments that appear immediately before content
34    /// token `i` (zero or more `--` lines, in source order, not separated from
35    /// the token by another content token). A comment on its own line is
36    /// followed by a [`Comment::Blank`] when a blank line comes after it
37    /// (#1884).
38    leading: Vec<Vec<Comment>>,
39    /// `trailing[i]` holds an optional comment on the same source line as
40    /// content token `i`. Only one trailing comment is recorded per token
41    /// because a single `--` consumes the rest of the line. A doc block or an
42    /// opening `{` never has one: see [`split_trivia`].
43    trailing: Vec<Option<String>>,
44    /// `blank_before[i]` is whether a blank line separates content token `i`
45    /// from the previous token, with a comment on its own line between them
46    /// (#2893): the blank line that sets the comment apart from what is above.
47    blank_before: Vec<bool>,
48    /// Any pending leading comments at end-of-file (no content token
49    /// followed), shaped as a `leading` entry. Used to preserve file-trailing
50    /// comments.
51    epilogue: Vec<Comment>,
52    /// #2203: a `bynk.lex.legacy_comment` or `bynk.lex.legacy_doc_line` error
53    /// for each comment or doc line spelled the legacy way. The tokens still
54    /// stand as trivia and docs, so the parse goes on and reports them all;
55    /// [`Parser::new`] files them with the doc errors, and the formatter's
56    /// migrating parse ([`parse_units_migrating`]) drops them.
57    legacy: Vec<CompileError>,
58}
59
60impl TriviaTable {
61    fn take_leading(&mut self, index: usize) -> Vec<Comment> {
62        match self.leading.get_mut(index) {
63            Some(v) => std::mem::take(v),
64            None => Vec::new(),
65        }
66    }
67
68    fn blank_before(&self, index: usize) -> bool {
69        self.blank_before.get(index).copied().unwrap_or(false)
70    }
71
72    fn take_trailing(&mut self, index: usize) -> Option<String> {
73        self.trailing.get_mut(index).and_then(|s| s.take())
74    }
75
76    fn take_epilogue(&mut self) -> Vec<Comment> {
77        std::mem::take(&mut self.epilogue)
78    }
79
80    /// True when every entry has been drained via `take_leading`/
81    /// `take_trailing`/`take_epilogue` — i.e. no comment was silently
82    /// dropped. Each harvest is already a `mem::take`, so anything still
83    /// present here is exactly the set of comments that never reached an
84    /// AST `Trivia` field.
85    ///
86    /// Deliberately **not** wired into a `debug_assert!` in the general parse
87    /// path: expressions carry no per-node trivia (§ "Comment trivia" in the
88    /// 2026-07-27 pipeline review), so an ordinary, valid program with a
89    /// comment inside a `match`/list/record/binop — a common, accepted
90    /// pattern `bynk-fmt`'s own comment-loss guard already handles
91    /// gracefully — would leave `leading`/`trailing` non-empty and trip it on
92    /// every compile, not just on formatting. Instead surfaced through
93    /// [`parse_units_with_drain_check`] (finding #66), whose one caller
94    /// (`bynk-fmt`) *does* care about exactly this signal.
95    /// [`Self::epilogue_is_empty`] is the narrower, safe-to-assert check.
96    fn is_fully_drained(&self) -> bool {
97        self.leading.iter().all(Vec::is_empty)
98            && self.trailing.iter().all(Option::is_none)
99            && self.epilogue.is_empty()
100    }
101
102    /// True when no file-trailing comment was left stranded. Unlike
103    /// [`Self::is_fully_drained`], this is safe to assert unconditionally: a
104    /// clean file's epilogue is empty by construction (nothing pending at
105    /// EOF), and the one shape that legitimately populates it — a top-level
106    /// trailing comment — is drained by every parse path that calls
107    /// `take_epilogue`. A brace-form declaration that forgets to is exactly
108    /// the bug this catches.
109    fn epilogue_is_empty(&self) -> bool {
110        self.epilogue.is_empty()
111    }
112}
113
114/// Remove `Comment` trivia tokens from `tokens` and bin them into a
115/// [`TriviaTable`] keyed against the surviving content tokens. A comment
116/// on the same source line as the preceding content token is recorded as
117/// that token's *trailing* trivia, unless that token is a doc block or an
118/// opening `{`; everything else is *leading* for the next content token.
119///
120/// A blank line after a leading comment on its own line, before the next
121/// comment or content token, is recorded as a [`Comment::Blank`] (#1884). Only
122/// a declaration that canonical style sets apart with blank lines keeps it: see
123/// [`Parser::take_leading_trivia`].
124fn split_trivia(tokens: &[Token], source: &str) -> (Vec<Token>, TriviaTable) {
125    let mut filtered: Vec<Token> = Vec::with_capacity(tokens.len());
126    let mut table = TriviaTable::default();
127    let mut pending_leading: Vec<Comment> = Vec::new();
128    let mut last_content_end: Option<usize> = None;
129    // Where the last comment in `pending_leading` ends, if it has a line to
130    // itself: the gap from there to the next token says whether a blank line
131    // follows it. A comment's span stops before its newline, so a blank line
132    // is two newlines. A comment that leads only because it sits on a `{` line
133    // has no blank line of its own: the one below it was between the `{` and
134    // the first item.
135    let mut last_leading_end: Option<usize> = None;
136    // Whether the first own-line comment now pending follows a blank line.
137    let mut pending_blank_before = false;
138    for tok in tokens {
139        if !pending_leading.is_empty()
140            && let Some(end) = last_leading_end
141            && source[end..tok.span.start].matches('\n').count() >= 2
142        {
143            pending_leading.push(Comment::Blank);
144        }
145        if tok.kind == TokenKind::DocLine && doc_line_is_legacy(source, tok.span) {
146            table.legacy.push(legacy_doc_line_error(source, tok.span));
147        }
148        if tok.kind == TokenKind::Comment {
149            if comment_is_legacy(source, tok.span) {
150                table.legacy.push(legacy_comment_error(tok.span));
151            }
152            let body = comment_body(source, tok.span).into_owned();
153            // If nothing has been buffered as leading for the next token and
154            // there is no newline between the previous content token and
155            // this comment, it trails that token. A doc block never has a
156            // trailing comment: its token ends past the newline after the
157            // closing `---`, so a `--` line directly under it would otherwise
158            // look same-line and be binned where nothing collects it (#1756).
159            // A `--|` doc line (#1888) ends past its newline the same way.
160            // Nor does an opening `{`: no parser collects trivia right after
161            // one, so its comment leads whatever follows instead, the first
162            // item or the `}` of an empty body (#1788). The same goes for a
163            // `[`: a list literal's first element or its `]` (#3067).
164            if pending_leading.is_empty()
165                && filtered.last().is_some_and(|t| {
166                    !matches!(
167                        t.kind,
168                        TokenKind::DocBlock
169                            | TokenKind::DocLine
170                            | TokenKind::LBrace
171                            | TokenKind::LBracket
172                            | TokenKind::LParen
173                    )
174                })
175                && let Some(prev_end) = last_content_end
176                && !source[prev_end..tok.span.start].contains('\n')
177            {
178                let last_idx = filtered.len() - 1;
179                // Only attach if no trailing already recorded (shouldn't
180                // happen because `--` consumes through end-of-line).
181                if table.trailing[last_idx].is_none() {
182                    table.trailing[last_idx] = Some(body);
183                    continue;
184                }
185            }
186            // A doc block's token ends past its closing line's newline, so a
187            // comment under it is on its own line with no newline between. A
188            // `--|` doc line's token does too (#1888).
189            let own_line = !pending_leading.is_empty()
190                || filtered
191                    .last()
192                    .is_none_or(|t| matches!(t.kind, TokenKind::DocBlock | TokenKind::DocLine))
193                || last_content_end.is_some_and(|end| source[end..tok.span.start].contains('\n'));
194            if pending_leading.is_empty() {
195                pending_blank_before = own_line
196                    && last_content_end
197                        .is_some_and(|end| source[end..tok.span.start].matches('\n').count() >= 2);
198            }
199            pending_leading.push(Comment::Line(body));
200            last_leading_end = own_line.then_some(tok.span.end);
201            continue;
202        }
203        filtered.push(*tok);
204        table.leading.push(std::mem::take(&mut pending_leading));
205        table.trailing.push(None);
206        table
207            .blank_before
208            .push(std::mem::take(&mut pending_blank_before));
209        last_content_end = Some(tok.span.end);
210        last_leading_end = None;
211    }
212    table.epilogue = pending_leading;
213    (filtered, table)
214}
215
216/// Parse a token slice into a [`Commons`] AST.
217///
218/// Accepts either form of v0.3 commons file:
219/// - Brace form: `commons name { items... }` (v0–v0.2 compatible).
220/// - Fragment form: `commons name uses... items...` to EOF (v0.3).
221pub fn parse(tokens: &[Token], source: &str) -> Result<Commons, Vec<CompileError>> {
222    parse_with_warnings(tokens, source).map(|(c, _warnings)| c)
223}
224
225/// [`parse`] with the non-fatal diagnostics threaded out alongside the AST
226/// (ADR 0117) — see [`parse_units_with_warnings`].
227pub fn parse_with_warnings(
228    tokens: &[Token],
229    source: &str,
230) -> Result<(Commons, Vec<CompileError>), Vec<CompileError>> {
231    let (unit, warnings) = parse_unit_with_warnings(tokens, source)?;
232    match unit {
233        SourceUnit::Commons(c) => Ok((c, warnings)),
234        SourceUnit::Context(ctx) => Err(vec![
235            CompileError::new(
236                "bynk.parse.unexpected_context",
237                ctx.span,
238                "expected a `commons` declaration but found a `context` declaration",
239            )
240            .with_note(
241                "contexts must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
242            ),
243        ]),
244        SourceUnit::Suite(t) => Err(vec![
245            CompileError::new(
246                "bynk.parse.unexpected_suite",
247                t.span,
248                "expected a `commons` declaration but found a `suite` declaration",
249            )
250            .with_note(
251                "tests must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
252            ),
253        ]),
254        SourceUnit::Adapter(a) => Err(vec![
255            CompileError::new(
256                "bynk.parse.unexpected_adapter",
257                a.span,
258                "expected a `commons` declaration but found an `adapter` declaration",
259            )
260            .with_note(
261                "adapters must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
262            ),
263        ]),
264    }
265}
266
267/// Parse a token slice into a [`SourceUnit`] with error recovery, returning a
268/// best-effort partial AST plus the full list of parse errors and warnings.
269///
270/// Used by the LSP: item-level recovery skips past a malformed declaration to
271/// the next top-level item, so multiple errors are reported per compilation
272/// rather than just the first. Compared to [`parse_unit`], this never bails;
273/// if no SourceUnit could be parsed at all (e.g. the file is empty or the
274/// header itself fails) the returned `Option` is `None`.
275///
276/// Keeps only the *first* unit — v0.113 allows more than one top-level unit
277/// per file (an atomic `commons` + `suite`, DECISION S), and every existing
278/// caller here is keyed on the primary declaration. [`parse_units_with_recovery`]
279/// is the same recovery parse without that narrowing, for the one caller
280/// (finding #29/#30) that needs every unit a file declares.
281pub fn parse_unit_with_recovery(
282    tokens: &[Token],
283    source: &str,
284) -> (Option<SourceUnit>, Vec<CompileError>) {
285    let (units, errors) = parse_units_with_recovery(tokens, source);
286    (units.into_iter().next(), errors)
287}
288
289/// [`parse_unit_with_recovery`], keeping **every** top-level unit instead of
290/// discarding all but the first (finding #29/#30). Used by the IDE's own parse
291/// entry point, which needs to see a trailing `suite` in an atomic
292/// `commons`+`suite` file, not just the primary declaration.
293pub fn parse_units_with_recovery(
294    tokens: &[Token],
295    source: &str,
296) -> (Vec<SourceUnit>, Vec<CompileError>) {
297    let recovered = parse_units_recovering(tokens, source);
298    (recovered.units, recovered.errors)
299}
300
301/// #1663: everything a recovering parse learns — the units it built, every
302/// syntax error, and the names of the top-level declarations it had to skip.
303#[derive(Debug)]
304pub struct Recovered {
305    pub units: Vec<SourceUnit>,
306    pub errors: Vec<CompileError>,
307    /// Declarations recovery dropped, by name (see `Parser::broken_decl_names`).
308    /// A caller keeps references to them from echoing as unknown names.
309    pub broken_decl_names: Vec<String>,
310}
311
312/// #1663: a strict parse's error(s) together with a recovering parse's, each
313/// reported once. The strict errors come first and always survive: some rules
314/// hold only for the strict single-unit parse (`extra_tokens`, a `commons`
315/// expected but a `context` found), which the multi-unit recovering parse
316/// accepts. A recovered error at the same position as one already listed is
317/// the same fault (the two parsers may name it differently) and is dropped.
318pub fn merge_syntax_errors(
319    strict: Vec<CompileError>,
320    recovered: Vec<CompileError>,
321) -> Vec<CompileError> {
322    let mut out = strict;
323    for e in recovered {
324        if !out.iter().any(|o| o.span.start == e.span.start) {
325            out.push(e);
326        }
327    }
328    out
329}
330
331/// [`parse_units_with_recovery`], also returning the names of the declarations
332/// recovery skipped (#1663).
333pub fn parse_units_recovering(tokens: &[Token], source: &str) -> Recovered {
334    parse_units_recovering_from(tokens, source, &mut 0)
335}
336
337/// [`parse_units_recovering`], continuing [`ExprId`] allocation from `next_id`
338/// rather than starting at 0 — see [`parse_unit_with_warnings_from`]. #1710:
339/// the project path checks a recovered file's surviving declarations
340/// alongside every other file's, so its ids must come from the same durable
341/// counter (`bynk_project::parse_cache`), or they would collide.
342pub fn parse_units_recovering_from(tokens: &[Token], source: &str, next_id: &mut u32) -> Recovered {
343    let (filtered, trivia) = split_trivia(tokens, source);
344    let mut warnings = Vec::new();
345    let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
346    p.recover_mode = true;
347    p.next_expr_id = *next_id;
348    let mut units = Vec::new();
349    loop {
350        match p.parse_unit() {
351            Ok(u) => units.push(u),
352            Err(e) => {
353                p.recovered_errors.push(e);
354                break;
355            }
356        }
357        // A genuinely malformed trailing declaration is still surfaced via
358        // recovery — checked *after* each successful parse, matching
359        // `parse_unit`'s own "at least once" attempt on the first unit (an
360        // empty file must still produce its usual unexpected-EOF diagnostic,
361        // not silently yield an empty `units` with no error at all).
362        if p.peek().is_none() {
363            break;
364        }
365    }
366    let broken_decl_names = std::mem::take(&mut p.broken_decl_names);
367    *next_id = p.next_expr_id;
368    let mut all_errors = p.recovered_errors;
369    all_errors.append(&mut p.doc_errors);
370    all_errors.append(&mut warnings);
371    Recovered {
372        units,
373        errors: all_errors,
374        broken_decl_names,
375    }
376}
377
378/// Parse a token slice into a [`SourceUnit`] — either a commons or a context.
379///
380/// Each `.bynk` file is exactly one declaration of one kind.
381pub fn parse_unit(tokens: &[Token], source: &str) -> Result<SourceUnit, Vec<CompileError>> {
382    parse_unit_with_warnings(tokens, source).map(|(unit, _warnings)| unit)
383}
384
385/// [`parse_unit`] with the non-fatal diagnostics threaded out alongside the
386/// AST (ADR 0117) — see [`parse_units_with_warnings`].
387pub fn parse_unit_with_warnings(
388    tokens: &[Token],
389    source: &str,
390) -> Result<(SourceUnit, Vec<CompileError>), Vec<CompileError>> {
391    parse_unit_with_warnings_from(tokens, source, &mut 0)
392}
393
394/// [`parse_unit_with_warnings`], continuing [`ExprId`] allocation from
395/// `next_id` instead of starting at 0, and writing the id one past the last
396/// one this parse handed out back into it. T3.4 (R2.4): every top-level parse
397/// entry point in this file constructs its own `Parser` and therefore its own
398/// zero-based id space; a caller that will check two files' output together
399/// in one pass (a multi-file commons — `bynk-emit`'s `collect_unit_methods`
400/// merges a type's methods from sibling files into the file that declares the
401/// type, before one `check_record` call) must thread one counter across every
402/// file it parses, or two independently-numbered files collide on the same
403/// id in the same `expr_types` map. Every *other* caller (a single buffer, an
404/// LSP hover/completion query, a fixture test) never merges its output with
405/// another file's before checking, so starting at 0 every time is correct —
406/// [`parse_unit_with_warnings`] above is that default, unchanged.
407pub fn parse_unit_with_warnings_from(
408    tokens: &[Token],
409    source: &str,
410    next_id: &mut u32,
411) -> Result<(SourceUnit, Vec<CompileError>), Vec<CompileError>> {
412    let (filtered, trivia) = split_trivia(tokens, source);
413    let mut warnings = Vec::new();
414    let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
415    p.next_expr_id = *next_id;
416    let result = match p.parse_unit() {
417        Ok(u) => {
418            if let Some(extra) = p.peek() {
419                Err(vec![
420                    CompileError::new(
421                        "bynk.parse.extra_tokens",
422                        extra.span,
423                        "unexpected token after top-level declaration",
424                    )
425                    .with_note(
426                        "a `.bynk` file contains exactly one `commons` or `context` declaration",
427                    ),
428                ])
429            } else {
430                Ok(u)
431            }
432        }
433        Err(e) => Err(vec![e]),
434    };
435    // #1885: a doc block that holds code fails the parse, after any error the
436    // parse itself hit.
437    let result = match (result, std::mem::take(&mut p.doc_errors)) {
438        (r, docs) if docs.is_empty() => r,
439        (Ok(_), docs) => Err(docs),
440        (Err(mut errs), mut docs) => {
441            errs.append(&mut docs);
442            Err(errs)
443        }
444    };
445    *next_id = p.next_expr_id;
446    // ADR 0117: warnings (e.g. orphan doc blocks) ride alongside a successful
447    // parse — severity governs gating at the caller, not here.
448    match result {
449        Ok(u) => {
450            // See `parse_units_with_warnings`: a file-trailing comment must
451            // have been drained by `take_epilogue`.
452            debug_assert!(
453                p.trivia.epilogue_is_empty(),
454                "a file-trailing comment was left undrained after a successful parse"
455            );
456            Ok((u, warnings))
457        }
458        Err(mut errs) => {
459            errs.append(&mut warnings);
460            Err(errs)
461        }
462    }
463}
464
465/// Parse a token slice into **all** the top-level [`SourceUnit`]s in one file
466/// (v0.113, testing track slice 1b). A `.bynk` file may hold more than one
467/// top-level declaration — an *atomic* file with `commons`/`context` **and** a
468/// `suite` together (DECISION S) — so the compiler parses a `Vec`, not a single
469/// unit. Test-ness is a property of each declaration, not of the file.
470///
471/// Bails on the first malformed declaration (like [`parse_unit`], not the
472/// recovering LSP path). An empty file is an error.
473pub fn parse_units(tokens: &[Token], source: &str) -> Result<Vec<SourceUnit>, Vec<CompileError>> {
474    parse_units_with_warnings(tokens, source).map(|(units, _warnings)| units)
475}
476
477/// [`parse_units`] with the non-fatal diagnostics threaded out alongside the
478/// AST (ADR 0117): a successful parse returns `Ok((units, warnings))` instead
479/// of hard-failing on a warning-severity diagnostic (an orphan doc block used
480/// to abort file discovery and throw the good AST away). A failed parse still
481/// returns every diagnostic — errors then warnings — in the `Err`.
482pub fn parse_units_with_warnings(
483    tokens: &[Token],
484    source: &str,
485) -> Result<(Vec<SourceUnit>, Vec<CompileError>), Vec<CompileError>> {
486    parse_units_with_drain_check(tokens, source)
487        .map(|(units, warnings, _drained)| (units, warnings))
488}
489
490/// [`parse_units_with_warnings`], continuing [`ExprId`] allocation from
491/// `next_id` rather than starting at 0 — see [`parse_unit_with_warnings_from`]
492/// for why this exists. The one production caller is `bynk-emit`'s per-file
493/// parse loop (`phase_parse`), which owns one counter across every file in a
494/// single project parse so two files whose methods later get merged into one
495/// `check_record` call (a multi-file commons) never collide.
496pub fn parse_units_with_warnings_from(
497    tokens: &[Token],
498    source: &str,
499    next_id: &mut u32,
500) -> Result<(Vec<SourceUnit>, Vec<CompileError>), Vec<CompileError>> {
501    parse_units_with_drain_check_from(tokens, source, next_id)
502        .map(|(units, warnings, _drained)| (units, warnings))
503}
504
505/// [`parse_units_with_warnings`] plus whether every comment's trivia was
506/// drained into the AST (`TriviaTable::is_fully_drained`). Finding #66:
507/// `bynk-fmt`'s comment-preservation guard re-tokenized its own rendered
508/// output just to diff comment bodies against the input — wasted work in the
509/// overwhelming common case where nothing was left behind. That guard uses
510/// this drain signal, computed from the same parse it already needs for
511/// rendering, as a fast-path: `true` means every comment landed in the AST,
512/// so re-checking the output can be skipped outright. No other caller needs
513/// the signal, so it rides its own entry point rather than widening
514/// [`parse_units_with_warnings`].
515pub fn parse_units_with_drain_check(
516    tokens: &[Token],
517    source: &str,
518) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
519    parse_units_with_drain_check_from(tokens, source, &mut 0)
520}
521
522/// [`parse_units_with_drain_check`], continuing [`ExprId`] allocation from
523/// `next_id` — see [`parse_unit_with_warnings_from`].
524pub fn parse_units_with_drain_check_from(
525    tokens: &[Token],
526    source: &str,
527    next_id: &mut u32,
528) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
529    parse_units_drain(tokens, source, next_id, false)
530}
531
532/// #2203 (DECISION F): [`parse_units_with_drain_check`] for the formatter,
533/// which accepts the legacy `--` comment and `--|` doc line spellings instead
534/// of reporting them, since printing them as `//` and `--- ` is the
535/// migration. Every other error is reported as usual.
536pub fn parse_units_migrating(
537    tokens: &[Token],
538    source: &str,
539) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
540    parse_units_drain(tokens, source, &mut 0, true)
541}
542
543fn parse_units_drain(
544    tokens: &[Token],
545    source: &str,
546    next_id: &mut u32,
547    migrate: bool,
548) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
549    let (filtered, trivia) = split_trivia(tokens, source);
550    let mut warnings = Vec::new();
551    let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
552    if migrate {
553        p.doc_errors.clear();
554    }
555    p.next_expr_id = *next_id;
556    let mut units = Vec::new();
557    let mut errors: Vec<CompileError> = Vec::new();
558    while p.peek().is_some() {
559        match p.parse_unit() {
560            Ok(u) => units.push(u),
561            Err(e) => {
562                errors.push(e);
563                break;
564            }
565        }
566    }
567    // #1885: a doc block that holds code fails the parse.
568    errors.append(&mut p.doc_errors);
569    *next_id = p.next_expr_id;
570    let eof = p.eof_span();
571    let fully_drained = p.trivia.is_fully_drained();
572    // `p` (and thus its `&mut warnings` borrow) is no longer used past here, so
573    // the local `warnings` are readable again.
574    if !errors.is_empty() {
575        errors.append(&mut warnings);
576        return Err(errors);
577    }
578    if units.is_empty() {
579        return Err(vec![CompileError::new(
580            "bynk.parse.unexpected_eof",
581            eof,
582            "expected `commons`, `context`, or `suite` to start the file, found end of file",
583        )]);
584    }
585    // A file-trailing comment must have been drained by `take_epilogue` — the
586    // one brace-form declarations forgot to call (a live comment-loss bug,
587    // not the fundamentally-unfixed expression-interior case: expressions
588    // carry no trivia at all, so asserting full drainage here would fire on
589    // any ordinary program with a comment inside a `match`/list/record, which
590    // `bynk-fmt`'s own comment-loss guard already handles gracefully rather
591    // than as a hard failure).
592    debug_assert!(
593        p.trivia.epilogue_is_empty(),
594        "a file-trailing comment was left undrained after a successful parse"
595    );
596    Ok((units, warnings, fully_drained))
597}
598
599/// A signed numeric literal in refinement-bound position (v0.21): `InRange`
600/// bounds are either both `Int` or both `Float`.
601enum SignedNumLit {
602    Int(IntBound),
603    Float(FloatBound),
604    Decimal(DecimalBound),
605}
606
607struct Parser<'a> {
608    tokens: &'a [Token],
609    source: &'a str,
610    pos: usize,
611    /// Accumulated non-fatal diagnostics. v0.3 uses this for orphan-doc
612    /// warnings, which are emitted as errors with a distinguishable category.
613    warnings: &'a mut Vec<CompileError>,
614    /// When true, the item-level loops catch errors from individual item
615    /// parses, push them into `recovered_errors`, and skip forward to the
616    /// next top-level item boundary instead of bailing. Used by the LSP via
617    /// [`parse_unit_with_recovery`]; disabled in the normal `parse` path so
618    /// existing single-error behaviour is preserved.
619    recover_mode: bool,
620    /// Errors collected during recovery-mode parsing. Only populated when
621    /// `recover_mode` is true.
622    recovered_errors: Vec<CompileError>,
623    /// #1663: the token index where the current top-level item starts, set by
624    /// each top-level item loop. Read once by [`Self::handle_item_err`] to name
625    /// the declaration a recovery skips.
626    pub(crate) item_start: Option<usize>,
627    /// #1663: the names of top-level declarations recovery skipped (a `type`,
628    /// `fn`, method, `event`, `capability`, `service`, `agent` or `actor`).
629    /// They are known names whose declaration is broken, so a caller can keep
630    /// references to them from echoing as unknown. Recovery mode only.
631    broken_decl_names: Vec<String>,
632    /// Line-comment trivia separated from the token stream. See
633    /// [`TriviaTable`].
634    trivia: TriviaTable,
635    /// Live recursion depth of the three self-recursive parse entry points
636    /// (`parse_expr`, `parse_type_ref`, `parse_pattern`). Incremented on entry
637    /// and decremented on exit by [`Parser::enter_recursion`] so it tracks the
638    /// current stack depth; when it exceeds [`crate::MAX_NESTING_DEPTH`] the
639    /// parser reports a bounded-depth diagnostic instead of overflowing its
640    /// stack (#713).
641    depth: usize,
642    /// When true, a bare `ident {` on the *spine* of the current expression is
643    /// an identifier followed by an unrelated block, never a record
644    /// construction — so an `if`/`match` condition that ends in a bare
645    /// identifier does not swallow the branch/arm block as `Ident { field }`
646    /// (#636). Set only around the condition parse (see [`parse_cond_expr`]);
647    /// `parse_expr` clears it, so the restriction is lifted inside any
648    /// delimited sub-expression (parentheses, call arguments, list, record
649    /// field). Mirrors Rust's `NO_STRUCT_LITERAL` restriction.
650    no_record_literal: bool,
651    /// #2721: set while parsing a match-arm guard's spine, where a `(` is never a
652    /// lambda head: the `=>` after `)` is the arm's own arrow. Cleared by
653    /// `parse_expr` on entry to any delimited sub-expression.
654    in_guard: bool,
655    /// True while parsing the tail of an `is` pattern that sits outside every
656    /// delimiter — `x is P`, `x is A | B`. A record pattern there would be
657    /// ambiguous with the block that follows an `if` condition, so it must be
658    /// parenthesised (`x is (T { .. })`, #2641; the patterns track's Q2 in
659    /// `design/archive/retired-tracks.md`). Cleared by
660    /// [`Parser::parse_pattern`], the entry every delimited (nested) pattern
661    /// goes through.
662    is_pattern_tail: bool,
663    /// Running count of unclosed `{` seen so far — maintained solely by
664    /// [`Self::bump`] (the one primitive that advances `self.pos`), so it
665    /// always reflects the true nesting depth no matter which parse function
666    /// is on the call stack. Finding #27/#30: `recover_to_top_item` reads it
667    /// against [`Self::item_loop_baseline`] to tell "the enclosing item
668    /// loop's own closing brace" apart from a still-unclosed nested
669    /// construct's — without it, a sync scan that started partway through
670    /// such a construct (an error deep inside a function body) stopped at the
671    /// first `}` it saw, however deeply nested, and the enclosing item loop
672    /// mistook that for its own body's end.
673    brace_depth: usize,
674    /// Stack of `brace_depth` snapshots, one per active item-loop body
675    /// (commons/context/adapter/suite) — pushed right after that body's own
676    /// `{` is consumed (or at loop entry, for a brace-free fragment form),
677    /// popped at the loop's normal exit. `recover_to_top_item` treats its top
678    /// entry as the depth an `}` must return to before it counts as the
679    /// enclosing body's own closing brace rather than a nested construct's.
680    item_loop_baseline: Vec<usize>,
681    /// T3.4 (R2.4): next [`ExprId`] to hand out — monotonic, incremented by
682    /// [`Self::alloc_expr_id`], the sole allocation point every `Expr`
683    /// construction site in this parser calls.
684    next_expr_id: u32,
685    /// #1885: `bynk.parse.doc_block_contains_code` errors found by
686    /// [`Self::take_doc_block`], with its `bynk.parse.multiple_docs` (#2203)
687    /// and the legacy-spelling errors [`split_trivia`] found. Kept apart from the item `Result` path so a
688    /// doc block, which every item loop reads before its recovery point, never
689    /// aborts the body it sits in; each entry point turns them into errors.
690    doc_errors: Vec<CompileError>,
691    /// #1885: true for the parser [`doc_content_is_code`] runs over a doc
692    /// block's content. It skips the code check on doc blocks inside that
693    /// content, so the probe stays a plain parse.
694    doc_probe: bool,
695}
696
697impl<'a> Parser<'a> {
698    fn new(
699        tokens: &'a [Token],
700        source: &'a str,
701        mut trivia: TriviaTable,
702        warnings: &'a mut Vec<CompileError>,
703    ) -> Self {
704        let doc_errors = std::mem::take(&mut trivia.legacy);
705        Self {
706            tokens,
707            source,
708            pos: 0,
709            warnings,
710            recover_mode: false,
711            recovered_errors: Vec::new(),
712            item_start: None,
713            broken_decl_names: Vec::new(),
714            trivia,
715            depth: 0,
716            no_record_literal: false,
717            in_guard: false,
718            is_pattern_tail: false,
719            brace_depth: 0,
720            item_loop_baseline: Vec::new(),
721            next_expr_id: 0,
722            doc_errors,
723            doc_probe: false,
724        }
725    }
726
727    /// T3.4 (R2.4): allocate the next [`ExprId`]. The sole allocation point —
728    /// every `Expr { id: self.alloc_expr_id(), .. }` construction in this
729    /// parser calls it exactly once, so two nodes never share an id and every
730    /// id a caller holds was actually handed out here.
731    fn alloc_expr_id(&mut self) -> ExprId {
732        let id = ExprId(self.next_expr_id);
733        self.next_expr_id += 1;
734        id
735    }
736
737    /// Enter a self-recursive parse step, bumping the live recursion depth and
738    /// failing with a bounded-depth diagnostic if it would exceed
739    /// [`crate::MAX_NESTING_DEPTH`]. The caller pairs a successful entry with a
740    /// matching `self.depth -= 1` on the way out (see `parse_expr` /
741    /// `parse_type_ref`); on the error path the depth is restored here so a
742    /// recovering caller is not left mis-counted. `what` names the construct
743    /// for the message (e.g. "this expression", "this type"). See #713.
744    fn enter_recursion(&mut self, what: &str) -> Result<(), CompileError> {
745        self.depth += 1;
746        if self.depth > crate::MAX_NESTING_DEPTH {
747            self.depth -= 1;
748            let span = self
749                .peek()
750                .map(|t| t.span)
751                .unwrap_or_else(|| self.eof_span());
752            return Err(self.nesting_too_deep(span, what));
753        }
754        Ok(())
755    }
756
757    /// The bounded-depth diagnostic shared by [`enter_recursion`] and
758    /// [`enter_chain_fold`].
759    fn nesting_too_deep(&self, span: Span, what: &str) -> CompileError {
760        CompileError::new(
761            "bynk.parse.nesting_too_deep",
762            span,
763            format!(
764                "{what} nests more than {} levels deep",
765                crate::MAX_NESTING_DEPTH
766            ),
767        )
768        .with_note(
769            "deeply nested source is rejected to keep the parser from overflowing its \
770             stack and aborting; flatten or split the construct",
771        )
772    }
773
774    /// The bounded-depth diagnostic for the *iteratively*-built spines —
775    /// associative operator chains ([`enter_chain_fold`]) and postfix receiver
776    /// chains ([`deepen_spine`]). Same code as [`nesting_too_deep`] (one budget,
777    /// one diagnostic) but phrased for a flat chain, which is long rather than
778    /// *nested*, and points at the idiomatic fix.
779    fn expression_too_long(&self, span: Span) -> CompileError {
780        CompileError::new(
781            "bynk.parse.nesting_too_deep",
782            span,
783            format!(
784                "this expression is more than {} levels deep",
785                crate::MAX_NESTING_DEPTH
786            ),
787        )
788        .with_note(
789            "a long operator or member chain is rejected to keep the compiler from overflowing \
790             its stack; split it across `let` bindings, or reduce a sequence with \
791             `.sum()`/`.fold(...)`",
792        )
793    }
794
795    /// Count one more operand folded onto an associative operator chain against
796    /// the same recursion budget as [`enter_recursion`] (#714).
797    ///
798    /// Associative chains (`+`, `*`, `&&`, `||`) are built *iteratively* in the
799    /// precedence ladder, so — unlike parentheses, calls, or `implies` — they
800    /// never re-enter `parse_expr` and thus slip past the `enter_recursion`
801    /// guard. Yet each fold deepens the left-nested `Expr` tree by one level,
802    /// and a long flat chain (`1 + 1 + … + 1`) overflows every *recursive*
803    /// consumer of that tree downstream — the checker's `type_of`, the
804    /// formatter, the emitter, and the AST's own recursive `Drop` — exactly as
805    /// deeply nested source overflows the parser. Counting each fold on the
806    /// shared `depth` budget bounds the whole expression's height, and because
807    /// it is the *same* budget it composes with the ambient nesting depth, so a
808    /// chain buried inside deeply nested source cannot exceed the bound either.
809    ///
810    /// The caller accumulates `folds` and subtracts them from `depth` before it
811    /// returns, so the live count unwinds as a recursive descent would; on the
812    /// overflow path the whole chain's contribution is restored here so a
813    /// recovering caller is not left mis-counted.
814    fn enter_chain_fold(&mut self, folds: &mut usize, span: Span) -> Result<(), CompileError> {
815        self.depth += 1;
816        *folds += 1;
817        if self.depth > crate::MAX_NESTING_DEPTH {
818            self.depth -= *folds;
819            *folds = 0;
820            return Err(self.expression_too_long(span));
821        }
822        Ok(())
823    }
824
825    /// Count one more level of an iteratively-built postfix receiver spine
826    /// (`a.b.c…`, `f()?.g()…`) against the shared budget (#714). Like
827    /// [`enter_chain_fold`], postfix loops rather than recurses, so a long spine
828    /// escapes [`enter_recursion`] yet grows an arbitrarily deep receiver tree
829    /// that the downstream walks recurse through. `parse_postfix` restores
830    /// `depth` wholesale on the way out (its many error paths make a
831    /// save/restore wrapper cleaner than per-fold unwinding), so this only bumps
832    /// and checks.
833    fn deepen_spine(&mut self, span: Span) -> Result<(), CompileError> {
834        self.depth += 1;
835        if self.depth > crate::MAX_NESTING_DEPTH {
836            return Err(self.expression_too_long(span));
837        }
838        Ok(())
839    }
840
841    /// Comments immediately preceding the current peek position. Consumed
842    /// (the table entry is cleared) so the same comments are not attached
843    /// to two nodes.
844    ///
845    /// For a slot in a body: canonical style has no blank lines there, so a
846    /// [`Comment::Blank`] is dropped and the comments stay attached to what
847    /// follows. A declaration set apart by blank lines (one at unit level, or a
848    /// service's or agent's section or handler) keeps it, through
849    /// [`Self::take_unit_leading_trivia`].
850    fn take_leading_trivia(&mut self) -> Vec<Comment> {
851        let mut comments = self.take_unit_leading_trivia();
852        comments.retain(|c| *c != Comment::Blank);
853        comments
854    }
855
856    /// [`Self::take_leading_trivia`] for a slot set apart by blank lines, keeping each
857    /// [`Comment::Blank`] (#1884).
858    fn take_unit_leading_trivia(&mut self) -> Vec<Comment> {
859        self.trivia.take_leading(self.pos)
860    }
861
862    /// The comments after the last token, which close the file at unit level,
863    /// so a [`Comment::Blank`] between them is kept.
864    fn take_epilogue_trivia(&mut self) -> Vec<Comment> {
865        self.trivia.take_epilogue()
866    }
867
868    /// Trailing comment, if any, on the same source line as the most
869    /// recently consumed content token. Call AFTER finishing a declaration
870    /// or statement, while `self.pos` points one past its last token.
871    fn take_trailing_trivia(&mut self) -> Option<String> {
872        if self.pos == 0 {
873            return None;
874        }
875        self.trivia.take_trailing(self.pos - 1)
876    }
877
878    /// Handle a per-item parse error. In recovery mode, record the error and
879    /// advance to the next sync point so the item loop can continue; otherwise
880    /// propagate as a hard failure.
881    fn handle_item_err(&mut self, e: CompileError) -> Result<(), CompileError> {
882        if self.recover_mode {
883            self.recovered_errors.push(e);
884            if let Some(start) = self.item_start.take() {
885                self.broken_decl_names.extend(self.decl_names_at(start));
886            }
887            let before = self.pos;
888            self.recover_to_top_item();
889            // The sync target may be the very token that produced the error —
890            // a context-only keyword (`capability`, `service`, …) at item
891            // position in a commons errors *without consuming it*, and it is
892            // itself a sync point. Recovery must always make progress, or the
893            // item loop re-reports the same error until memory runs out
894            // (found by the `parse` fuzz target on a seed input).
895            // #1663: unless the cursor is on the `}` that closes this item
896            // loop's own body (an error raised at the end of the last item):
897            // consuming it would make the body look unclosed, a follow-on
898            // `unexpected_eof`. The loop ends on that `}` itself. A fragment-
899            // form loop has no closing brace (baseline 0), so a stray `}`
900            // there is still consumed.
901            let baseline = self.item_loop_baseline.last().copied().unwrap_or(0);
902            let closes_body = baseline > 0
903                && self.brace_depth == baseline
904                && self.peek_kind() == Some(TokenKind::RBrace);
905            if self.pos == before && !closes_body {
906                self.bump();
907                // #1663: and skip the rest of the rejected item too (`agent`
908                // in a commons: its name and `{ … }` body). Otherwise the next
909                // loop iteration misreads its name as a malformed item and
910                // reports a second, follow-on syntax error.
911                self.recover_to_top_item();
912            }
913            Ok(())
914        } else {
915            Err(e)
916        }
917    }
918
919    /// #1663: the name(s) a declaration starting at token `start` declares:
920    /// `type T`, `fn f`, `fn T.m` (recorded as `T.m`), `event E`,
921    /// `capability C`, `service S`, `agent A`, `actor A`. Empty when the item
922    /// is not one of those or its name never parsed (`fn ( -> Int`).
923    fn decl_names_at(&self, start: usize) -> Vec<String> {
924        let kind_at = |i: usize| self.tokens.get(i).map(|t| t.kind);
925        let ident_at = |i: usize| {
926            self.tokens
927                .get(i)
928                .filter(|t| t.kind == TokenKind::Ident)
929                .map(|t| self.slice(t.span).to_string())
930        };
931        match kind_at(start) {
932            Some(
933                TokenKind::Type
934                | TokenKind::Event
935                | TokenKind::Capability
936                | TokenKind::Service
937                | TokenKind::Agent
938                | TokenKind::Actor,
939            ) => ident_at(start + 1).into_iter().collect(),
940            Some(TokenKind::Fn) => match (ident_at(start + 1), kind_at(start + 2)) {
941                // A method is recorded qualified, `T.m`, so a broken method
942                // is never mistaken for a free `fn m` of the same name.
943                (Some(owner), Some(TokenKind::Dot)) => match ident_at(start + 3) {
944                    Some(method) => vec![format!("{owner}.{method}")],
945                    None => Vec::new(),
946                },
947                (Some(name), _) => vec![name],
948                (None, _) => Vec::new(),
949            },
950            _ => Vec::new(),
951        }
952    }
953
954    /// Skip forward to the next top-level item boundary: either an
955    /// [`is_item_start`] keyword at the enclosing item loop's own nesting
956    /// depth, a closing brace that returns to that depth, or end-of-input.
957    /// Used only in recovery mode.
958    ///
959    /// Finding #27/#30: brace-depth-gated against
960    /// [`Self::item_loop_baseline`], so a `}` deep inside a still-unclosed
961    /// nested construct (an error partway through a function body, itself
962    /// inside a `match` arm) is skipped over rather than mistaken for the
963    /// enclosing body's own closing brace — the old flat scan stopped at
964    /// literally the first `}` it saw, however deep, handing the item loop a
965    /// brace that did not belong to it and making it return with zero items.
966    fn recover_to_top_item(&mut self) {
967        let baseline = self.item_loop_baseline.last().copied().unwrap_or(0);
968        while let Some(t) = self.peek() {
969            match t.kind {
970                TokenKind::RBrace if self.brace_depth == baseline => return,
971                _ if self.brace_depth == baseline && is_item_start(t.kind) => return,
972                _ => {
973                    self.bump();
974                }
975            }
976        }
977    }
978
979    /// Mark the start of a top-level item loop (`declarations.rs`'s
980    /// `parse_commons_brace`/`_fragment`, `parse_context_brace`/`_fragment`,
981    /// `parse_test_brace`/`_fragment`, `parse_adapter_body`) — called right
982    /// after that body's own `{` is consumed (brace form) or at the loop's
983    /// own entry (fragment form, which has no enclosing brace of its own).
984    /// Paired with [`Self::exit_item_loop`] at the loop's normal exit.
985    fn enter_item_loop(&mut self) {
986        self.item_loop_baseline.push(self.brace_depth);
987    }
988
989    /// Pair of [`Self::enter_item_loop`].
990    fn exit_item_loop(&mut self) {
991        self.item_loop_baseline.pop();
992    }
993
994    fn peek(&self) -> Option<Token> {
995        self.tokens.get(self.pos).copied()
996    }
997
998    fn peek_kind(&self) -> Option<TokenKind> {
999        self.peek().map(|t| t.kind)
1000    }
1001
1002    /// #2618: consume a leading `private` modifier at item position and return
1003    /// its span. `private` is contextual, not reserved: it is a modifier only
1004    /// when it is an identifier spelled `private` immediately followed by a
1005    /// declaration keyword, so `@cache(scope: private)` and a binding named
1006    /// `private` keep their meaning.
1007    ///
1008    /// The modifier applies to `fn`, `type`, `messages`, `asset`, `embed` and
1009    /// `const` in a commons or context (`allowed`). On any other declaration, or in an
1010    /// adapter, it is `bynk.visibility.private_not_allowed`: an error in
1011    /// recovery mode that leaves the declaration to parse as if unmodified,
1012    /// and the parse's error otherwise.
1013    fn take_private_modifier(&mut self, allowed: bool) -> Result<Option<Span>, CompileError> {
1014        let Some(t) = self.peek() else {
1015            return Ok(None);
1016        };
1017        if t.kind != TokenKind::Ident || self.slice(t.span) != "private" {
1018            return Ok(None);
1019        }
1020        let Some(next) = self.nth(1) else {
1021            return Ok(None);
1022        };
1023        let modifiable = matches!(
1024            next.kind,
1025            TokenKind::Fn
1026                | TokenKind::Type
1027                | TokenKind::Messages
1028                | TokenKind::Asset
1029                | TokenKind::Embed
1030                | TokenKind::Const
1031        );
1032        let declaration = modifiable
1033            || matches!(
1034                next.kind,
1035                TokenKind::Service
1036                    | TokenKind::Agent
1037                    | TokenKind::Capability
1038                    | TokenKind::Provides
1039                    | TokenKind::Actor
1040                    | TokenKind::Event
1041            );
1042        if !declaration {
1043            return Ok(None);
1044        }
1045        self.bump();
1046        if modifiable && allowed {
1047            return Ok(Some(t.span));
1048        }
1049        let what = self.slice(next.span);
1050        let err = if allowed {
1051            CompileError::new(
1052                "bynk.visibility.private_not_allowed",
1053                t.span,
1054                format!("`private` does not apply to `{what}` declarations"),
1055            )
1056            .with_note(
1057                "`private` applies to `fn`, `type`, `messages`, `asset`, `embed` and `const`; a context's `exports` and `consumes` govern how far its services, agents, capabilities, providers, actors and events reach",
1058            )
1059        } else {
1060            CompileError::new(
1061                "bynk.visibility.private_not_allowed",
1062                t.span,
1063                "`private` applies only to declarations in a commons or context, not in an adapter",
1064            )
1065            .with_note("an adapter's `exports` governs what its consumers see")
1066        };
1067        if self.recover_mode {
1068            self.recovered_errors.push(err);
1069            Ok(None)
1070        } else {
1071            Err(err)
1072        }
1073    }
1074
1075    /// The token `n` positions ahead of the cursor (`nth(0)` == `peek()`).
1076    fn nth(&self, n: usize) -> Option<Token> {
1077        self.tokens.get(self.pos + n).copied()
1078    }
1079
1080    fn nth_kind(&self, n: usize) -> Option<TokenKind> {
1081        self.nth(n).map(|t| t.kind)
1082    }
1083
1084    /// The source text of the token `n` positions ahead, or `""` if none.
1085    fn nth_text(&self, n: usize) -> &'a str {
1086        self.nth(n).map(|t| self.slice(t.span)).unwrap_or("")
1087    }
1088
1089    /// The span of the most recently consumed token (`self.pos - 1`). Falls back
1090    /// to the current token's span when nothing has been consumed yet.
1091    fn prev_span(&self) -> Span {
1092        self.tokens
1093            .get(self.pos.wrapping_sub(1))
1094            .or_else(|| self.peek_ref())
1095            .map(|t| t.span)
1096            .unwrap_or_default()
1097    }
1098
1099    fn peek_ref(&self) -> Option<&Token> {
1100        self.tokens.get(self.pos)
1101    }
1102
1103    fn bump(&mut self) -> Option<Token> {
1104        let t = self.peek();
1105        if let Some(t) = t {
1106            match t.kind {
1107                TokenKind::LBrace => self.brace_depth += 1,
1108                TokenKind::RBrace => self.brace_depth = self.brace_depth.saturating_sub(1),
1109                _ => {}
1110            }
1111            self.pos += 1;
1112        }
1113        t
1114    }
1115
1116    fn eat(&mut self, kind: TokenKind) -> Option<Token> {
1117        if self.peek_kind() == Some(kind) {
1118            self.bump()
1119        } else {
1120            None
1121        }
1122    }
1123
1124    fn slice(&self, span: Span) -> &'a str {
1125        &self.source[span.range()]
1126    }
1127
1128    /// True when the next token sits on a later line than `prev`. Used to
1129    /// keep a `[` that opens a new line out of the postfix type-application
1130    /// form: `f` followed by `[1, 2]` on the next line is an identifier and
1131    /// a list literal, not `f[…]` (v0.20b).
1132    fn next_token_on_new_line(&self, prev: Span) -> bool {
1133        match self.peek() {
1134            Some(t) if prev.end <= t.span.start => {
1135                self.source[prev.end..t.span.start].contains('\n')
1136            }
1137            _ => false,
1138        }
1139    }
1140
1141    /// Span pointing at the end of input — used for "unexpected EOF" reports.
1142    /// The start backs up to the **start of the final char**, not `len - 1`, so
1143    /// the span never splits a multibyte codepoint (an unterminated construct
1144    /// whose last line ends in non-ASCII — e.g. a `--` comment ending in `→`).
1145    fn eof_span(&self) -> Span {
1146        let end = self.source.len();
1147        let start = (0..end)
1148            .rev()
1149            .find(|&i| self.source.is_char_boundary(i))
1150            .unwrap_or(0);
1151        Span::new(start, end)
1152    }
1153
1154    fn expect(&mut self, kind: TokenKind, ctx: &str) -> Result<Token, CompileError> {
1155        match self.peek() {
1156            Some(t) if t.kind == kind => {
1157                self.bump();
1158                Ok(t)
1159            }
1160            Some(t) => Err(CompileError::new(
1161                "bynk.parse.expected_token",
1162                t.span,
1163                format!(
1164                    "expected {} {ctx}, found {}",
1165                    kind.describe(),
1166                    t.kind.describe()
1167                ),
1168            )),
1169            None => Err(CompileError::new(
1170                "bynk.parse.unexpected_eof",
1171                self.eof_span(),
1172                format!("expected {} {ctx}, found end of file", kind.describe()),
1173            )),
1174        }
1175    }
1176
1177    fn expect_ident(&mut self, ctx: &str) -> Result<Ident, CompileError> {
1178        match self.peek() {
1179            Some(t) if t.kind == TokenKind::Ident => {
1180                self.bump();
1181                Ok(Ident {
1182                    name: self.slice(t.span).to_string(),
1183                    span: t.span,
1184                })
1185            }
1186            // v0.5 contextual keyword `on` doubles as an identifier in
1187            // expression / field-access positions so users can name fields and
1188            // parameters using it. It retains its keyword meaning only at
1189            // handler-decl-level (`on call(...)`).
1190            //
1191            // v0.7 / v0.112: `suite` and `case` are contextual too — they
1192            // introduce the suite declaration and its cases, but are perfectly
1193            // valid commons/context/field names otherwise.
1194            //
1195            // The tier is single-sourced in `keywords::RESERVED_CONTEXTUAL`:
1196            // this arm defers to it rather than hardcoding the token kinds, so
1197            // extending that list is enough to admit a new contextual keyword
1198            // here. Each of these words lexes only to its own token, so matching
1199            // the source text is equivalent to matching the kind.
1200            Some(t) if crate::keywords::is_reserved_contextual(self.slice(t.span)) => {
1201                self.bump();
1202                Ok(Ident {
1203                    name: self.slice(t.span).to_string(),
1204                    span: t.span,
1205                })
1206            }
1207            Some(t) if is_reserved_keyword(t.kind) => Err(CompileError::new(
1208                "bynk.parse.reserved_keyword",
1209                t.span,
1210                format!(
1211                    "expected identifier {ctx}, but `{}` is a reserved keyword",
1212                    self.slice(t.span)
1213                ),
1214            )
1215            .with_note("rename the identifier to something that is not a keyword")),
1216            Some(t) => Err(CompileError::new(
1217                "bynk.parse.expected_token",
1218                t.span,
1219                format!("expected identifier {ctx}, found {}", t.kind.describe()),
1220            )),
1221            None => Err(CompileError::new(
1222                "bynk.parse.unexpected_eof",
1223                self.eof_span(),
1224                format!("expected identifier {ctx}, found end of file"),
1225            )),
1226        }
1227    }
1228
1229    /// True when the cursor is on a reserved keyword followed by `:`: a
1230    /// keyword used as a label (#2837). The `:` is what separates a label from
1231    /// a binding, so `type: t` is a field name while `type` alone stays refused.
1232    fn at_keyword_label(&self) -> bool {
1233        matches!(self.peek(), Some(t) if is_reserved_keyword(t.kind))
1234            && self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::Colon)
1235    }
1236
1237    /// Like [`Parser::expect_ident`], but admits any reserved keyword that is
1238    /// followed by `:` (#2837): a field declaration, a construction
1239    /// initialiser, a record or named pattern field and a variant payload
1240    /// field are labels, never bindings. A keyword without the `:` keeps the
1241    /// `reserved_keyword` refusal, which is how shorthand stays an error.
1242    pub(crate) fn expect_label(&mut self, ctx: &str) -> Result<Ident, CompileError> {
1243        if self.at_keyword_label() {
1244            let t = self.bump().expect("peeked a keyword");
1245            return Ok(Ident {
1246                name: self.slice(t.span).to_string(),
1247                span: t.span,
1248            });
1249        }
1250        self.expect_ident(ctx)
1251    }
1252
1253    /// The targeted refusal for a keyword written as field shorthand (#2837):
1254    /// `Account { type, .. }` as a pattern would bind a variable named `type`,
1255    /// and `Account { type }` as a construction would read one. `None` when the
1256    /// cursor is not on such a shorthand, so the caller falls back to
1257    /// [`Parser::expect_ident`]'s plain `reserved_keyword`.
1258    ///
1259    /// A pattern gets the fix `type: type_`. The parser cannot see scope, so the
1260    /// fresh name is the first `type_`, `type_2`, … that no identifier in the
1261    /// file spells: over-cautious, never colliding, and `MaybeIncorrect` all the
1262    /// same. A construction gets a note and no fix: no variable called `type`
1263    /// can exist, so there is no value to suggest.
1264    pub(crate) fn keyword_shorthand_error(&self, pattern: bool) -> Option<CompileError> {
1265        let t = self.peek()?;
1266        if !is_reserved_keyword(t.kind) {
1267            return None;
1268        }
1269        let next = self.tokens.get(self.pos + 1).map(|t| t.kind);
1270        let shorthand = match next {
1271            Some(TokenKind::Comma | TokenKind::RBrace) => true,
1272            Some(TokenKind::DotDot) => pattern,
1273            _ => false,
1274        };
1275        if !shorthand {
1276            return None;
1277        }
1278        let word = self.slice(t.span);
1279        let mut err = CompileError::new(
1280            "bynk.parse.keyword_field_shorthand",
1281            t.span,
1282            format!("`{word}` is a reserved keyword, so it cannot be a field shorthand"),
1283        );
1284        if pattern {
1285            let taken = |name: &str| {
1286                self.tokens
1287                    .iter()
1288                    .any(|k| k.kind == TokenKind::Ident && self.slice(k.span) == name)
1289            };
1290            let mut binding = format!("{word}_");
1291            let mut n = 2;
1292            while taken(&binding) {
1293                binding = format!("{word}_{n}");
1294                n += 1;
1295            }
1296            err = err
1297                .with_note(format!(
1298                    "the shorthand binds a variable named `{word}`; name the binding instead"
1299                ))
1300                .with_suggestion(
1301                    format!("bind the `{word}` field as `{binding}`"),
1302                    vec![(t.span, format!("{word}: {binding}"))],
1303                    crate::error::Applicability::MaybeIncorrect,
1304                );
1305        } else {
1306            err = err.with_note(format!(
1307                "write `{word}: <value>`; a keyword names the field but cannot name a variable"
1308            ));
1309        }
1310        Some(err)
1311    }
1312
1313    /// Like [`Parser::expect_ident`], but admits any reserved keyword on the
1314    /// same line as the `.` before it (#2837, #2778): a field access, a method
1315    /// call or a method declaration. The same-line rule keeps a half-typed
1316    /// `foo.` above a line starting `let` from parsing as `foo.let`.
1317    pub(crate) fn expect_member_name(
1318        &mut self,
1319        ctx: &str,
1320        dot: Span,
1321    ) -> Result<Ident, CompileError> {
1322        if matches!(self.peek(), Some(t) if is_reserved_keyword(t.kind))
1323            && !self.next_token_on_new_line(dot)
1324        {
1325            let t = self.bump().expect("peeked a keyword");
1326            return Ok(Ident {
1327                name: self.slice(t.span).to_string(),
1328                span: t.span,
1329            });
1330        }
1331        self.expect_ident(ctx)
1332    }
1333
1334    // -- top level --
1335
1336    /// Consume an optional doc at the current position, in either form,
1337    /// returning the doc and its span (through the end of its last line).
1338    /// Returns None if the next token is not a doc.
1339    ///
1340    /// #1885: a doc block whose content is code (see [`doc_content_is_code`])
1341    /// records `bynk.parse.doc_block_contains_code` in [`Self::doc_errors`];
1342    /// the block is still returned, so parsing carries on around it. A run of
1343    /// `--|` lines is not probed: each line is marked as a doc on purpose, so
1344    /// it cannot swallow code by accident the way a pair of dividers can.
1345    ///
1346    /// #2203 (DECISION D): a target has one doc. A doc directly followed by
1347    /// another (no blank line between), of either form, records
1348    /// `bynk.parse.multiple_docs` the same way; all are consumed and the first
1349    /// is returned. This replaces #1888's joined `--|` lines and its
1350    /// mixed-forms error.
1351    fn take_doc_block(&mut self) -> Option<(Doc, Span)> {
1352        let first = self.take_one_doc()?;
1353        let mut docs = vec![first.clone()];
1354        while let Some(next) = self.peek()
1355            && matches!(next.kind, TokenKind::DocBlock | TokenKind::DocLine)
1356            && !has_blank_line_between(self.source, docs[docs.len() - 1].1.end, next.span.start)
1357        {
1358            docs.push(self.take_one_doc().expect("a doc token was peeked"));
1359        }
1360        if docs.len() > 1 && !self.doc_probe {
1361            self.doc_errors.push(multiple_docs(self.source, &docs));
1362        }
1363        Some(first)
1364    }
1365
1366    /// One doc: a `---` block or a one-line doc.
1367    fn take_one_doc(&mut self) -> Option<(Doc, Span)> {
1368        match self.peek_kind()? {
1369            TokenKind::DocBlock => {
1370                let t = self.bump().unwrap();
1371                let body = doc_block_content(self.source, t.span);
1372                if !self.doc_probe && doc_content_is_code(&body) {
1373                    self.doc_errors.push(doc_block_contains_code(t.span));
1374                }
1375                Some((Doc::new(body, DocForm::Block), t.span))
1376            }
1377            TokenKind::DocLine => {
1378                let t = self.bump().unwrap();
1379                let text = doc_line_text(self.source, t.span);
1380                Some((Doc::new(text, DocForm::Lines), t.span))
1381            }
1382            _ => None,
1383        }
1384    }
1385
1386    /// Collect all line-comment trivia leading the next declaration plus
1387    /// the optional doc block. Comments may appear both *before* and
1388    /// *between* the doc and the declaration; the spec canonicalises both
1389    /// groups above the doc, so we concatenate them.
1390    ///
1391    /// The doc comes back as a [`DocLead`], which records where it sat among
1392    /// the comments, so an orphan can be kept in place ([`keep_orphan`]).
1393    ///
1394    /// For a declaration set apart by blank lines (a unit-level one, or a
1395    /// service's or agent's section or handler), which keeps a blank line after
1396    /// a comment (#1884); [`Self::collect_body_item_lead`] is the form for a
1397    /// body whose items have no blank lines between them.
1398    fn collect_item_lead(&mut self) -> (Vec<Comment>, Option<DocLead>) {
1399        self.collect_lead(Self::take_unit_leading_trivia)
1400    }
1401
1402    /// [`Self::collect_item_lead`] for a declaration in a body, which drops a
1403    /// [`Comment::Blank`] as [`Self::take_leading_trivia`] does.
1404    fn collect_body_item_lead(&mut self) -> (Vec<Comment>, Option<DocLead>) {
1405        self.collect_lead(Self::take_leading_trivia)
1406    }
1407
1408    fn collect_lead(
1409        &mut self,
1410        take: fn(&mut Self) -> Vec<Comment>,
1411    ) -> (Vec<Comment>, Option<DocLead>) {
1412        let mut leading = take(self);
1413        let doc = self.take_doc_block().map(|(content, span)| DocLead {
1414            content,
1415            span,
1416            at: leading.len(),
1417        });
1418        if doc.is_some() {
1419            leading.extend(take(self));
1420        }
1421        (leading, doc)
1422    }
1423
1424    /// #1888: the comments and doc above a member: a record field, a variant,
1425    /// a variant's payload field or a message entry. As
1426    /// [`Self::collect_body_item_lead`] and [`Self::finalize_doc`] together, so
1427    /// a blank line orphans a member's doc as it does a declaration's, and a
1428    /// [`Comment::Blank`] is dropped, as in any body (#1884). A doc with
1429    /// `close` (the body's closing token) next documents nothing: it is warned
1430    /// about and kept among the comments, which the caller then takes as the
1431    /// body's closing comments.
1432    fn collect_member_lead(&mut self, close: TokenKind) -> (Vec<Comment>, Option<Doc>) {
1433        let (mut leading, doc) = self.collect_body_item_lead();
1434        let Some(doc) = doc else {
1435            return (leading, None);
1436        };
1437        match self.peek() {
1438            Some(t) if t.kind != close => {
1439                let doc = self.finalize_doc(Some(doc), t.span, &mut leading);
1440                (leading, doc)
1441            }
1442            _ => {
1443                self.warnings.push(CompileError::new(
1444                    "bynk.parse.orphan_doc_block",
1445                    doc.span,
1446                    "documentation has no following member to attach to",
1447                ));
1448                keep_orphan(&mut leading, doc);
1449                (leading, None)
1450            }
1451        }
1452    }
1453
1454    /// #1888: the kind of the first token after any doc tokens at the cursor,
1455    /// so a member loop can tell a doc on its next member from a doc on the
1456    /// declaration after the body (a pipe-form sum has no closing token).
1457    fn peek_past_docs(&self) -> Option<TokenKind> {
1458        self.tokens[self.pos.min(self.tokens.len())..]
1459            .iter()
1460            .map(|t| t.kind)
1461            .find(|k| !matches!(k, TokenKind::DocBlock | TokenKind::DocLine))
1462    }
1463
1464    /// Attach a parsed doc block to a following declaration unless a blank
1465    /// line separates them, in which case the doc is orphaned: a warning, and
1466    /// the block is kept in `leading` where it sat (#1756).
1467    fn finalize_doc(
1468        &mut self,
1469        doc: Option<DocLead>,
1470        next_span: Span,
1471        leading: &mut Vec<Comment>,
1472    ) -> Option<Doc> {
1473        let doc = doc?;
1474        let doc_span = doc.span;
1475        // A blank line between the doc and the next decl orphans the doc.
1476        if has_blank_line_between(self.source, doc_span.end, next_span.start) {
1477            self.warnings.push(
1478                CompileError::new(
1479                    "bynk.parse.orphan_doc_block",
1480                    doc_span,
1481                    "documentation block is separated from the following declaration by a blank line; it will not be attached",
1482                )
1483                .with_note(
1484                    "remove the blank line to attach the doc to the next declaration, \
1485                     or remove the doc block if it is not meant to document anything",
1486                ),
1487            );
1488            keep_orphan(leading, doc);
1489            return None;
1490        }
1491        Some(doc.content)
1492    }
1493}
1494
1495/// A doc block read ahead of a declaration, before it is known to attach: its
1496/// normalised content, its span, and its index among the leading comments
1497/// collected with it.
1498pub(crate) struct DocLead {
1499    pub(crate) content: Doc,
1500    pub(crate) span: Span,
1501    pub(crate) at: usize,
1502}
1503
1504/// #1756: keep an orphaned doc block in `leading`, at the place it was written
1505/// among those comments, so the formatter prints it where it was rather than
1506/// dropping it.
1507fn keep_orphan(leading: &mut Vec<Comment>, doc: DocLead) {
1508    let at = doc.at.min(leading.len());
1509    leading.insert(at, Comment::OrphanDoc(doc.content));
1510}
1511
1512/// #2203 (DECISION D): the `bynk.parse.multiple_docs` error for `docs`, two
1513/// or more docs directly above one target. When every one is a `--- text`
1514/// line, the fix joins them into one block, which is what a doc of more than
1515/// one line is.
1516fn multiple_docs(source: &str, docs: &[(Doc, Span)]) -> CompileError {
1517    let (_, first) = docs[0];
1518    let (_, last) = docs[docs.len() - 1];
1519    let mut err = CompileError::new(
1520        "bynk.parse.multiple_docs",
1521        docs[1].1,
1522        "this declaration or member already has a doc; a target has one doc",
1523    )
1524    .with_label(first, "the first doc is here")
1525    .with_note(
1526        "a doc of more than one line is a block: a `---` line, the text, and another `---` line",
1527    );
1528    let one_liners = docs
1529        .iter()
1530        .all(|(d, span)| d.form == DocForm::Lines && !doc_line_is_legacy(source, *span));
1531    if one_liners {
1532        let line_start = source[..first.start].rfind('\n').map_or(0, |i| i + 1);
1533        let indent = &source[line_start..first.start];
1534        let text = docs
1535            .iter()
1536            .map(|(d, _)| d.as_str())
1537            .collect::<Vec<_>>()
1538            .join("\n");
1539        let fence = "-".repeat(doc_fence_len(&text));
1540        let mut block = fence.clone();
1541        for line in text.lines() {
1542            block.push('\n');
1543            if !line.is_empty() {
1544                block.push_str(indent);
1545                block.push_str(line);
1546            }
1547        }
1548        block.push('\n');
1549        block.push_str(indent);
1550        block.push_str(&fence);
1551        let end = source[..last.end].trim_end_matches(['\n', '\r']).len();
1552        err = err.with_suggestion(
1553            "join the docs into one `---` block",
1554            vec![(Span::new_in(first.file, first.start, end), block)],
1555            crate::error::Applicability::MachineApplicable,
1556        );
1557    }
1558    err
1559}
1560
1561/// #1885: the `bynk.parse.doc_block_contains_code` error for the doc block at
1562/// `span`.
1563fn doc_block_contains_code(span: Span) -> CompileError {
1564    CompileError::new(
1565        "bynk.parse.doc_block_contains_code",
1566        span,
1567        "this documentation block contains declarations, so they are not compiled",
1568    )
1569    .with_note(
1570        "a line of three or more dashes opens or closes a doc block, so two dash \
1571         dividers turn the code between them into documentation; for a divider use a \
1572         line comment with text, such as `// Helpers`, and to show code in a doc \
1573         block put it in a Markdown code fence (```)",
1574    )
1575}
1576
1577/// The keywords that open a declaration in a unit body. A doc block's content
1578/// is probed as code only when it lexes and holds one of these, so prose (which
1579/// usually fails to lex, or has none) costs one tokenize at most.
1580const DECLARATION_KEYWORDS: &[TokenKind] = &[
1581    TokenKind::Type,
1582    TokenKind::Fn,
1583    TokenKind::Capability,
1584    TokenKind::Provides,
1585    TokenKind::Service,
1586    TokenKind::Agent,
1587    TokenKind::Actor,
1588    TokenKind::Messages,
1589    TokenKind::Event,
1590    TokenKind::Asset,
1591    TokenKind::Embed,
1592    TokenKind::Const,
1593    TokenKind::Uses,
1594    TokenKind::Consumes,
1595    TokenKind::Exports,
1596    TokenKind::Binding,
1597];
1598
1599/// #1885 (ADR: doc-fence-matched-length): true when a doc block's `content`,
1600/// with its Markdown code fences removed, parses as one or more declarations.
1601///
1602/// The probe is an `adapter` body in fragment form: an adapter accepts every
1603/// item a context or commons does, plus `binding`, and leaves placement to the
1604/// checker. Success means the whole content parsed and declared something; a
1605/// content that only holds another doc block (front matter, say) is prose.
1606///
1607/// Nesting is legal since #1885, so code can hide one level down: a doc block
1608/// inside the content lexes to one opaque token, and its content is probed in
1609/// turn (up to [`DOC_PROBE_MAX_DEPTH`] levels), the outer block reporting what
1610/// any level finds. The probe parser itself does not report on those blocks
1611/// (`doc_probe`). Content that does not lex because it holds a lone `---` (a
1612/// Markdown rule) is probed again with its marker lines blanked out.
1613fn doc_content_is_code(content: &str) -> bool {
1614    doc_content_is_code_at(content, 0)
1615}
1616
1617/// How many levels of nested doc blocks [`doc_content_is_code`] looks into.
1618/// Doc blocks nested this deep are written on purpose; the bound only keeps
1619/// adversarial input from costing a parse per level without end.
1620const DOC_PROBE_MAX_DEPTH: usize = 4;
1621
1622fn doc_content_is_code_at(content: &str, depth: usize) -> bool {
1623    let stripped = strip_code_fences(content);
1624    let tokens = match crate::lexer::tokenize(&stripped) {
1625        Ok(tokens) => tokens,
1626        Err(_) => {
1627            // A lone `---` rule leaves the content unlexable; without the
1628            // marker lines it may still be nothing but declarations.
1629            let unmarked = blank_marker_lines(&stripped);
1630            if unmarked == stripped {
1631                return false;
1632            }
1633            return doc_content_is_code_at(&unmarked, depth);
1634        }
1635    };
1636    if depth < DOC_PROBE_MAX_DEPTH
1637        && tokens.iter().any(|t| {
1638            t.kind == TokenKind::DocBlock
1639                && doc_content_is_code_at(&doc_block_content(&stripped, t.span), depth + 1)
1640        })
1641    {
1642        return true;
1643    }
1644    if !tokens
1645        .iter()
1646        .any(|t| DECLARATION_KEYWORDS.contains(&t.kind))
1647    {
1648        return false;
1649    }
1650    let (filtered, trivia) = split_trivia(&tokens, &stripped);
1651    let mut warnings = Vec::new();
1652    let mut p = Parser::new(&filtered, &stripped, trivia, &mut warnings);
1653    p.doc_probe = true;
1654    let at = Span::new(0, 0);
1655    let name = QualifiedName {
1656        parts: Vec::new(),
1657        span: at,
1658    };
1659    match p.parse_adapter_body(at, name, None, false) {
1660        Ok(a) => {
1661            p.peek().is_none()
1662                && (!a.items.is_empty()
1663                    || !a.uses.is_empty()
1664                    || !a.consumes.is_empty()
1665                    || !a.exports.is_empty()
1666                    || a.binding.is_some())
1667        }
1668        Err(_) => false,
1669    }
1670}
1671
1672/// `content` with every doc-block marker line (three or more dashes alone on
1673/// the line) blanked out, line for line.
1674fn blank_marker_lines(content: &str) -> String {
1675    let mut out = String::with_capacity(content.len());
1676    for line in content.lines() {
1677        let trimmed = line.trim();
1678        if !(trimmed.len() >= 3 && trimmed.bytes().all(|b| b == b'-')) {
1679            out.push_str(line);
1680        }
1681        out.push('\n');
1682    }
1683    out
1684}
1685
1686/// `content` with every Markdown fenced code block (```` ``` ```` or `~~~`,
1687/// three or more, closed by a fence of the same character at least as long)
1688/// blanked out, line for line. An unclosed fence runs to the end, as in
1689/// Markdown. Code shown in a fence is an example, not swallowed code.
1690fn strip_code_fences(content: &str) -> String {
1691    let mut out = String::with_capacity(content.len());
1692    let mut open: Option<(char, usize)> = None;
1693    for line in content.lines() {
1694        let trimmed = line.trim();
1695        let fence = ['`', '~'].into_iter().find_map(|c| {
1696            let n = trimmed.chars().take_while(|&x| x == c).count();
1697            (n >= 3).then_some((c, n))
1698        });
1699        match (open, fence) {
1700            (None, Some(f)) => open = Some(f),
1701            (Some((c, n)), Some((fc, fnum)))
1702                if fc == c && fnum >= n && trimmed.len() == fnum * c.len_utf8() =>
1703            {
1704                open = None;
1705            }
1706            (None, None) => out.push_str(line),
1707            (Some(_), _) => {}
1708        }
1709        out.push('\n');
1710    }
1711    out
1712}
1713
1714/// The value of a lexed, hole-free string literal (the lexeme, including its
1715/// delimiters), in any form: plain, raw, or multi-line (#2619).
1716fn parse_string_literal(lexeme: &str, span: Span) -> Result<String, CompileError> {
1717    crate::lexer::decode_string_literal(lexeme, span)
1718}
1719
1720pub fn is_reserved_keyword(kind: TokenKind) -> bool {
1721    use TokenKind::*;
1722    matches!(
1723        kind,
1724        Commons
1725            | Type
1726            | Fn
1727            | Where
1728            | True
1729            | False
1730            | Int
1731            | String
1732            | Bool
1733            | Let
1734            | If
1735            | Else
1736            | Ok
1737            | Err
1738            | Result
1739            | ValidationError
1740            | Enum
1741            | Match
1742            | Option
1743            | Record
1744            | Self_
1745            | Some
1746            | None
1747            | Is
1748            | Opaque
1749            | Uses
1750            | Context
1751            | Consumes
1752            | Exports
1753            | Transparent
1754            | Agent
1755            | As
1756            | Capability
1757            | Effect
1758            | Do
1759            | Given
1760            | On
1761            | Http
1762            | Provides
1763            | Stub
1764            | Service
1765            | Actor
1766            | Expect
1767            | Suite
1768            | Case
1769            | Float
1770            | Duration
1771            | Instant
1772            | Bytes
1773            | Decimal
1774            | DecodeError
1775            | JsonErrorDeprecated
1776            | Property
1777            | Adapter
1778            | Binding
1779            | Cron
1780            | Queue
1781            | From
1782            | Protocol
1783            | Invariant
1784            | Implies
1785            | Requires
1786            | Ensures
1787            | Transition
1788    )
1789}
1790
1791/// True when `kind` starts a top-level unit (`commons`/`context`/`adapter`/
1792/// `suite`) or an item within one of their bodies — every keyword any of
1793/// `parse_commons_brace`/`_fragment`, `parse_context_brace`/`_fragment`,
1794/// `parse_test_brace`/`_fragment`, or `parse_adapter_body` dispatches on
1795/// (`declarations.rs`). The single set [`Parser::recover_to_top_item`]'s sync
1796/// scan checks against — finding #27/#30: that scan had drifted from what the
1797/// item loops actually recognise (`Property`, `Actor`, `Event`, `Binding`,
1798/// and the `adapter` unit keyword itself were all missing), so an error
1799/// recovery sync could walk past a real item/unit boundary instead of
1800/// stopping there.
1801fn is_item_start(kind: TokenKind) -> bool {
1802    use TokenKind::*;
1803    matches!(
1804        kind,
1805        // Top-level unit keywords.
1806        Commons | Context | Adapter | Suite
1807        // Body items shared across commons/context/adapter.
1808        | Type | Fn | Messages | Event | Asset | Embed | Const | Uses
1809        // Context/adapter-only body items.
1810        | Consumes | Exports | Capability | Provides | Service | Agent | Actor
1811        // Adapter-only.
1812        | Binding
1813        // Suite/test-only body items.
1814        | Stub | Case | Property
1815    )
1816}
1817
1818#[cfg(test)]
1819mod tests {
1820    use super::*;
1821    use crate::lexer::tokenize;
1822
1823    fn parse_str(src: &str) -> Result<Commons, Vec<CompileError>> {
1824        let toks = tokenize(src).map_err(|e| vec![e])?;
1825        parse(&toks, src)
1826    }
1827
1828    fn parse_recover_str(src: &str) -> (Option<SourceUnit>, Vec<CompileError>) {
1829        let toks = match tokenize(src) {
1830            Ok(t) => t,
1831            Err(e) => return (None, vec![e]),
1832        };
1833        parse_unit_with_recovery(&toks, src)
1834    }
1835
1836    /// #2703: a bare name ending a contract clause is the end of the predicate,
1837    /// not the head of a record construction, even with the body's `{` on the
1838    /// next line (and a lone-name body `{ n }`, which looks like `Limit { n }`).
1839    #[test]
1840    fn contract_clause_name_before_next_line_brace_is_not_a_record() {
1841        for src in [
1842            "commons m\n\nconst Limit: Int = 10\n\nfn small(n: Int) -> Int\n  requires small: n <= Limit\n{\n  n\n}\n",
1843            "commons m\n\nfn f(n: Int) -> Int\n  ensures same: result == n\n{\n  n\n}\n",
1844            "commons m\n\nfn f(n: Int) -> Int\n  requires r: n <= Limit {\n  n\n}\n",
1845        ] {
1846            assert!(parse_str(src).is_ok(), "{src}\n{:?}", parse_str(src).err());
1847        }
1848        // A record literal in a clause still works once parenthesised.
1849        let src = "commons m\n\ntype P = { x: Int }\n\nfn f(p: P) -> Int\n  requires r: (p == P { x: 1 })\n{\n  1\n}\n";
1850        assert!(parse_str(src).is_ok(), "{:?}", parse_str(src).err());
1851    }
1852
1853    /// #2703: the flip side — an unparenthesised record literal on a clause's
1854    /// spine is rejected (the `{` opens the body), as in an `if` condition.
1855    #[test]
1856    fn contract_clause_unparenthesised_record_literal_is_rejected() {
1857        let src = "commons m\n\ntype P = { x: Int }\n\nfn f(p: P) -> Int\n  requires r: p == P { x: 1 }\n{\n  1\n}\n";
1858        assert!(parse_str(src).is_err());
1859    }
1860
1861    /// Finding #29/#30: `parse_units_with_recovery` keeps every top-level unit
1862    /// an atomic `commons`+`suite` file declares (v0.113, DECISION S), where
1863    /// `parse_unit_with_recovery` keeps only the first — the defect the IDE's
1864    /// old single-unit parse entry point had (it silently discarded the
1865    /// trailing `suite`).
1866    #[test]
1867    fn parse_units_with_recovery_keeps_every_top_level_unit() {
1868        let src =
1869            "commons m {\n  fn f() -> Int { 1 }\n}\n\nsuite m\n\ncase \"c\" {\n  expect true\n}\n";
1870        let toks = tokenize(src).unwrap();
1871        let (units, errors) = parse_units_with_recovery(&toks, src);
1872        assert!(errors.is_empty(), "{errors:?}");
1873        assert_eq!(units.len(), 2, "expected both units, got {units:?}");
1874        assert!(matches!(units[0], SourceUnit::Commons(_)));
1875        assert!(matches!(units[1], SourceUnit::Suite(_)));
1876
1877        // The singular wrapper still narrows to just the first, unchanged.
1878        let (unit, errors) = parse_unit_with_recovery(&toks, src);
1879        assert!(errors.is_empty(), "{errors:?}");
1880        assert!(matches!(unit, Some(SourceUnit::Commons(_))));
1881    }
1882
1883    /// `parse_unit_with_recovery` always attempts at least one parse, even on
1884    /// empty input — `parse_units_with_recovery`'s loop must preserve that
1885    /// (its `while`-style peek check alone would skip the body entirely and
1886    /// silently return no error), since 16+ existing callers rely on an empty
1887    /// file still producing its usual diagnostic rather than a silent `None`
1888    /// with no error at all.
1889    #[test]
1890    fn empty_input_still_reports_an_error_through_the_plural_entry_point() {
1891        let toks = tokenize("").unwrap();
1892        let (units, errors) = parse_units_with_recovery(&toks, "");
1893        assert!(units.is_empty());
1894        assert!(
1895            !errors.is_empty(),
1896            "an empty file must still produce a diagnostic, not silently no units and no error"
1897        );
1898
1899        let (unit, unit_errors) = parse_unit_with_recovery(&toks, "");
1900        assert!(unit.is_none());
1901        assert_eq!(
1902            errors.len(),
1903            unit_errors.len(),
1904            "the singular wrapper must see the same error(s) as the plural entry point"
1905        );
1906    }
1907
1908    /// Finding #66: `parse_units_with_drain_check`'s `fully_drained` flag is
1909    /// `bynk-fmt`'s signal for whether its comment-loss guard can skip a
1910    /// re-tokenize-and-diff of its own output. It must be `true` for an
1911    /// ordinary file (every comment sits before a declaration/statement or
1912    /// trails one) and `false` the moment a comment sits inside an expression
1913    /// subtree, where `TriviaTable` has no field to attach it to.
1914    #[test]
1915    fn drain_check_reports_expression_interior_comments_as_undrained() {
1916        let ordinary = "commons x {\n// note\ntype T = Int where Positive\n}\n";
1917        let toks = tokenize(ordinary).unwrap();
1918        let (_, _, drained) = parse_units_with_drain_check(&toks, ordinary).unwrap();
1919        assert!(
1920            drained,
1921            "a declaration-leading comment must be fully drained"
1922        );
1923
1924        let lossy = "commons x {\n  fn f() -> Int {\n    1 + // note\n    2\n  }\n}\n";
1925        let toks = tokenize(lossy).unwrap();
1926        let (_, _, drained) = parse_units_with_drain_check(&toks, lossy).unwrap();
1927        assert!(
1928            !drained,
1929            "a comment inside a binop expression must be reported as undrained"
1930        );
1931    }
1932
1933    #[test]
1934    fn eof_span_never_splits_a_multibyte_codepoint() {
1935        // An unterminated construct whose final line ends in a non-ASCII char
1936        // (here a `--` comment ending in `→`) once produced an `unexpected_eof`
1937        // span of `len - 1 .. len`, landing on the arrow's last continuation
1938        // byte. Every reported span must sit on char boundaries.
1939        for src in [
1940            "commons x {\n  // ends with an arrow →",
1941            "agent A {\n  key k: String\n  // note 🦀",
1942            "commons y {\n  type T = é",
1943        ] {
1944            let (_unit, errors) = parse_recover_str(src);
1945            for e in &errors {
1946                assert!(
1947                    src.is_char_boundary(e.span.start) && src.is_char_boundary(e.span.end),
1948                    "span {:?} splits a codepoint in {src:?}",
1949                    e.span,
1950                );
1951            }
1952        }
1953    }
1954
1955    #[test]
1956    fn reserved_contextual_keywords_readable_in_expression_position() {
1957        // Events track, slice 0 (#939): `expect_ident`'s `RESERVED_CONTEXTUAL`
1958        // exemption (`keywords::RESERVED_CONTEXTUAL`: case/event/messages/on/
1959        // suite) covers *declaring* a binding with one of these names — a
1960        // parameter, a `let` — but the primary-expression parser previously
1961        // only admitted plain `TokenKind::Ident` when *reading one back*.
1962        // Latent since messages/on/case/suite shipped (no fixture happened to
1963        // name a binding after one of them and read it back inside the body);
1964        // surfaced concretely when `event` joined the tier and collided with
1965        // `examples/event-log`'s pre-existing `add(event: Event)` handler.
1966        for kw in [
1967            "asset", "case", "const", "embed", "event", "messages", "on", "suite",
1968        ] {
1969            let src = format!("commons x\n\nfn f({kw}: Int) -> Int {{\n  {kw}\n}}\n");
1970            let result = parse_str(&src);
1971            assert!(
1972                result.is_ok(),
1973                "a parameter named `{kw}` must be readable in expression position: {:?}",
1974                result.err()
1975            );
1976        }
1977    }
1978
1979    /// #3486: a contextual keyword is a field label wherever a field is
1980    /// named, including as the *first* field of a record literal, which the
1981    /// construction lookahead (two tokens after the `{`) used to refuse.
1982    #[test]
1983    fn contextual_keywords_open_a_record_literal() {
1984        for kw in [
1985            "asset", "case", "const", "embed", "event", "messages", "on", "suite",
1986        ] {
1987            let src = format!(
1988                "commons x\n\ntype R = {{ {kw}: Int, other: Int }}\n\n\
1989                 fn first() -> R {{\n  R {{ {kw}: 1, other: 2 }}\n}}\n\n\
1990                 fn last() -> R {{\n  R {{ other: 2, {kw}: 1 }}\n}}\n"
1991            );
1992            let result = parse_str(&src);
1993            assert!(
1994                result.is_ok(),
1995                "a record literal with `{kw}` as a field label must parse: {:?}",
1996                result.err()
1997            );
1998        }
1999    }
2000
2001    #[test]
2002    fn recovery_skips_garbage_between_decls() {
2003        // Two `type` declarations separated by garbage. Recovery should
2004        // accept both and report one error for the garbage between them.
2005        let src = "commons x {\n\
2006                   type A = Int where NonNegative\n\
2007                   ??? !!!\n\
2008                   type B = String where NonEmpty\n\
2009                   }";
2010        let (unit, errors) = parse_recover_str(src);
2011        let unit = unit.expect("recovery should produce a partial AST");
2012        let SourceUnit::Commons(c) = unit else {
2013            panic!("expected commons")
2014        };
2015        // Both type decls should have been collected despite the garbage.
2016        let names: Vec<_> = c
2017            .items
2018            .iter()
2019            .map(|i| match i {
2020                CommonsItem::Type(t) => t.name.name.clone(),
2021                _ => panic!("expected only types"),
2022            })
2023            .collect();
2024        assert!(
2025            names.contains(&"A".to_string()) && names.contains(&"B".to_string()),
2026            "expected both A and B; got {names:?}",
2027        );
2028        assert!(!errors.is_empty(), "expected at least one parse error");
2029    }
2030
2031    #[test]
2032    fn recovery_handles_bad_first_decl_then_good_second() {
2033        // First decl is malformed (missing `=`); second is well-formed.
2034        let src = "commons x {\n\
2035                   type A Int where NonNegative\n\
2036                   type B = String where NonEmpty\n\
2037                   }";
2038        let (unit, errors) = parse_recover_str(src);
2039        let unit = unit.expect("recovery should produce a partial AST");
2040        let SourceUnit::Commons(c) = unit else {
2041            panic!("expected commons")
2042        };
2043        let names: Vec<_> = c
2044            .items
2045            .iter()
2046            .filter_map(|i| match i {
2047                CommonsItem::Type(t) => Some(t.name.name.clone()),
2048                _ => None,
2049            })
2050            .collect();
2051        assert!(
2052            names.contains(&"B".to_string()),
2053            "B should be parsed after A's failure; got {names:?}"
2054        );
2055        assert!(!errors.is_empty(), "expected at least one parse error");
2056    }
2057
2058    /// Finding #27/#30: an error two levels deep inside `f`'s body (a
2059    /// `match` arm's own block) used to make `recover_to_top_item`'s flat,
2060    /// depth-blind scan stop at the *first* `}` it saw — the arm block's own,
2061    /// not `f`'s. Two more `}` (the match's, then `f`'s) then got consumed one
2062    /// at a time across repeated recovery re-entries, and the outer item loop
2063    /// eventually mistook the commons's *own* closing `}` for having arrived
2064    /// early, returning zero items and a spurious second
2065    /// `bynk.parse.expected_unit_header` error. With brace-depth tracking, `g`
2066    /// is recovered as the sole item and only `f`'s own error is reported.
2067    /// #1663: an item that ends without its body (`fn f() -> Int` then the
2068    /// commons' own `}`) raises its error *on* that `}`, so recovery makes no
2069    /// progress. The no-progress step must not consume the brace that closes
2070    /// the body (brace form): doing so made the body look unclosed, a
2071    /// follow-on `unexpected_eof`.
2072    #[test]
2073    fn recovery_keeps_the_bodys_closing_brace_after_a_bodiless_item() {
2074        let src = "commons m {\n  fn f() -> Int\n}\n";
2075        let (unit, errors) = parse_recover_str(src);
2076        assert!(unit.is_some(), "recovery should produce a partial AST");
2077        let categories: Vec<_> = errors.iter().map(|e| e.category).collect();
2078        assert_eq!(
2079            categories.len(),
2080            1,
2081            "one syntax error, no follow-on: {categories:?}"
2082        );
2083        assert!(
2084            !categories.contains(&"bynk.parse.unexpected_eof"),
2085            "the commons' closing brace must survive: {categories:?}"
2086        );
2087    }
2088
2089    /// #1663: an item keyword illegal at this position (`agent` in a commons)
2090    /// is skipped *with* its name and `{ … }` body, not one token at a time —
2091    /// otherwise the item loop misreads the agent's name as a malformed item,
2092    /// a second, follow-on `expected_item`. The next item still parses.
2093    #[test]
2094    fn recovery_skips_a_rejected_item_whole() {
2095        let src = "commons m\n\nagent Counter {\n  key id: String\n}\n\nfn g() -> Int { 2 }\n";
2096        let recovered = parse_units_recovering(&crate::lexer::tokenize(src).unwrap(), src);
2097        assert_eq!(
2098            recovered.errors.len(),
2099            1,
2100            "one syntax error, no follow-on: {:?}",
2101            recovered
2102                .errors
2103                .iter()
2104                .map(|e| e.category)
2105                .collect::<Vec<_>>()
2106        );
2107        let Some(SourceUnit::Commons(c)) = recovered.units.first() else {
2108            panic!("expected commons")
2109        };
2110        assert!(
2111            c.items.iter().any(|i| matches!(i, CommonsItem::Fn(_))),
2112            "the `fn g` after the skipped agent must still parse"
2113        );
2114        assert_eq!(recovered.broken_decl_names, ["Counter"]);
2115    }
2116
2117    #[test]
2118    fn recovery_skips_a_nested_blocks_own_closing_brace() {
2119        let src = "commons m {\n  \
2120                   fn f() -> Int {\n    \
2121                   match 1 {\n      \
2122                   is 1 -> { let z = }\n      \
2123                   is _ -> 2\n    \
2124                   }\n  \
2125                   }\n  \
2126                   fn g() -> Int { 2 }\n\
2127                   }\n";
2128        let (unit, errors) = parse_recover_str(src);
2129        let unit = unit.expect("recovery should produce a partial AST");
2130        let SourceUnit::Commons(c) = unit else {
2131            panic!("expected commons")
2132        };
2133        let names: Vec<_> = c
2134            .items
2135            .iter()
2136            .filter_map(|i| match i {
2137                CommonsItem::Fn(f) => match &f.name {
2138                    FnName::Free(id) => Some(id.name.clone()),
2139                    _ => None,
2140                },
2141                _ => None,
2142            })
2143            .collect();
2144        assert_eq!(
2145            names,
2146            vec!["g".to_string()],
2147            "g must still be recovered as an item; got {names:?}"
2148        );
2149        assert!(
2150            !errors
2151                .iter()
2152                .any(|e| e.category == "bynk.parse.expected_unit_header"),
2153            "the outer body's own closing brace must not be mistaken for \
2154             end-of-file: {errors:?}"
2155        );
2156    }
2157
2158    #[test]
2159    fn doc_block_attaches_to_type() {
2160        let c =
2161            parse_str("commons x {\n---\nA descriptive doc.\n---\ntype T = Int where Positive\n}")
2162                .unwrap();
2163        let CommonsItem::Type(t) = &c.items[0] else {
2164            panic!()
2165        };
2166        assert!(t.documentation.is_some());
2167        assert!(
2168            t.documentation
2169                .as_ref()
2170                .unwrap()
2171                .contains("A descriptive doc.")
2172        );
2173    }
2174
2175    #[test]
2176    fn interpolated_string_parses_into_parts() {
2177        // v0.43: `"Hi, \(name)!"` splits into chunk / hole / chunk.
2178        let c = parse_str("commons x\n\nfn f(name: String) -> String {\n  \"Hi, \\(name)!\"\n}\n")
2179            .unwrap();
2180        let CommonsItem::Fn(f) = &c.items[0] else {
2181            panic!("expected fn")
2182        };
2183        let ExprKind::InterpStr(parts) = &f.body.tail.kind else {
2184            panic!("expected InterpStr, got {:?}", f.body.tail.kind)
2185        };
2186        assert_eq!(parts.len(), 3);
2187        assert!(matches!(&parts[0], InterpPart::Chunk(s) if s == "Hi, "));
2188        assert!(
2189            matches!(&parts[1], InterpPart::Hole(h) if matches!(&h.kind, ExprKind::Ident(id) if id.name == "name"))
2190        );
2191        assert!(matches!(&parts[2], InterpPart::Chunk(s) if s == "!"));
2192    }
2193
2194    #[test]
2195    fn interpolated_hole_parses_a_full_expression() {
2196        // A hole holds an arbitrary expression, not just an identifier.
2197        let c =
2198            parse_str("commons x\n\nfn f(a: Int, b: Int) -> String {\n  \"sum = \\(a + b)\"\n}\n")
2199                .unwrap();
2200        let CommonsItem::Fn(f) = &c.items[0] else {
2201            panic!("expected fn")
2202        };
2203        let ExprKind::InterpStr(parts) = &f.body.tail.kind else {
2204            panic!("expected InterpStr")
2205        };
2206        assert!(matches!(&parts[1], InterpPart::Hole(h) if matches!(&h.kind, ExprKind::BinOp(..))));
2207    }
2208
2209    #[test]
2210    fn empty_interpolation_hole_is_rejected() {
2211        let errs = parse_str("commons x\n\nfn f() -> String {\n  \"\\()\"\n}\n").unwrap_err();
2212        assert!(
2213            errs.iter()
2214                .any(|e| e.category == "bynk.parse.empty_interpolation"),
2215            "expected empty_interpolation; got {errs:?}"
2216        );
2217    }
2218
2219    #[test]
2220    fn interpolation_hole_lex_error_span_is_rebased() {
2221        // #716: a lex error inside a `\(…)` hole once carried a span relative to
2222        // the hole substring — never rebased by `hole.start` — so it pointed at
2223        // the file's opening bytes and could split a multibyte char, tripping
2224        // the char-boundary invariant. The error must land on the offending
2225        // bytes within the hole and stay on char boundaries.
2226        let cases = [
2227            // `$` is not a valid token; the error should point at it, not byte 0.
2228            "commons x\n\nfn f() -> String {\n  \"a \\($)\"\n}\n",
2229            // Integer overflow — the reported span must cover the literal itself.
2230            "commons x\n\nfn f() -> String {\n  \"n = \\(99999999999999999999)\"\n}\n",
2231            // A multibyte char before the hole means an un-rebased span could
2232            // land inside the `é`; the rebased span must not.
2233            "commons x\n\nfn f() -> String {\n  \"é \\($)\"\n}\n",
2234        ];
2235        for src in cases {
2236            let errs = parse_str(src).unwrap_err();
2237            assert!(!errs.is_empty(), "expected a lex error for {src:?}");
2238            for e in &errs {
2239                assert!(
2240                    src.is_char_boundary(e.span.start) && src.is_char_boundary(e.span.end),
2241                    "span {:?} splits a codepoint in {src:?}",
2242                    e.span,
2243                );
2244                // The error must point inside the interpolation hole, not at the
2245                // header text that precedes it.
2246                let hole_start = src.find("\\(").expect("case has a hole") + 2;
2247                assert!(
2248                    e.span.start >= hole_start,
2249                    "span {:?} precedes the hole (starts at {hole_start}) in {src:?}",
2250                    e.span,
2251                );
2252            }
2253        }
2254    }
2255
2256    #[test]
2257    fn fragment_form_parses() {
2258        let c = parse_str("commons x.y\n\ntype T = Int where NonNegative\n").unwrap();
2259        assert_eq!(c.form, CommonsForm::Fragment);
2260        assert_eq!(c.items.len(), 1);
2261    }
2262
2263    #[test]
2264    fn uses_parses() {
2265        let c = parse_str("commons x\n\nuses other.lib\n").unwrap();
2266        assert_eq!(c.uses.len(), 1);
2267        assert_eq!(c.uses[0].target.joined(), "other.lib");
2268    }
2269
2270    /// #2804: `%` is a targeted error, with a fix to `.rem` only for simple operands.
2271    #[test]
2272    fn percent_is_a_targeted_error_with_a_fix_for_simple_operands() {
2273        let err = |expr: &str| {
2274            let src = format!("commons m\n\nfn f(n: Int, k: Int) -> Int {{ {expr} }}\n");
2275            let errs = parse_str(&src).unwrap_err();
2276            assert_eq!(
2277                errs[0].category, "bynk.parse.no_remainder_operator",
2278                "{expr}"
2279            );
2280            errs.into_iter().next().unwrap()
2281        };
2282        let fix = err("n % 2");
2283        assert_eq!(fix.suggestions.len(), 1);
2284        assert_eq!(
2285            fix.notes,
2286            [
2287                "use `a.rem(b)` for the C-family remainder, which takes the dividend's sign, \
2288              or `a.mod(b)` for the modulo, which takes the divisor's sign"
2289            ]
2290        );
2291        assert_eq!(fix.suggestions[0].edits[0].1, "n.rem(2)");
2292        assert_eq!(
2293            fix.suggestions[0].applicability,
2294            crate::error::Applicability::MaybeIncorrect
2295        );
2296        assert_eq!(err("n % k").suggestions[0].edits[0].1, "n.rem(k)");
2297        for complex in [
2298            "(n + 1) % k",
2299            "n * 2 % k",
2300            "n % (k + 1)",
2301            "-n % k",
2302            "n % -k",
2303        ] {
2304            assert!(err(complex).suggestions.is_empty(), "{complex}");
2305        }
2306    }
2307
2308    fn parse_unit_str(src: &str) -> Result<SourceUnit, Vec<CompileError>> {
2309        let toks = tokenize(src).map_err(|e| vec![e])?;
2310        parse_unit(&toks, src)
2311    }
2312
2313    #[test]
2314    fn minimal_context_parses() {
2315        let u = parse_unit_str("context commerce.orders {}").unwrap();
2316        let SourceUnit::Context(c) = u else {
2317            panic!("expected context");
2318        };
2319        assert_eq!(c.name.joined(), "commerce.orders");
2320        assert!(c.items.is_empty());
2321    }
2322
2323    #[test]
2324    fn context_consumes_and_exports_parse() {
2325        let src = "context commerce.orders {\n  uses commerce.money\n  consumes commerce.payment\n  exports opaque { OrderId }\n  exports transparent { OrderError }\n  type OrderId = String where Matches(\"ORD-[0-9]+\")\n  type OrderError = enum { CartEmpty, BadInput }\n}";
2326        let u = parse_unit_str(src).unwrap();
2327        let SourceUnit::Context(c) = u else { panic!() };
2328        assert_eq!(c.uses.len(), 1);
2329        assert_eq!(c.consumes.len(), 1);
2330        assert_eq!(c.exports.len(), 2);
2331        assert_eq!(c.exports[0].kind, ExportKind::Type(Visibility::Opaque));
2332        assert_eq!(c.exports[1].kind, ExportKind::Type(Visibility::Transparent));
2333    }
2334
2335    #[test]
2336    fn context_fragment_form_parses() {
2337        let src = "context x.y\n\nuses other.lib\nconsumes other.ctx\nexports opaque { T }\n\ntype T = Int where NonNegative\n";
2338        let u = parse_unit_str(src).unwrap();
2339        let SourceUnit::Context(c) = u else { panic!() };
2340        assert_eq!(c.form, CommonsForm::Fragment);
2341        assert_eq!(c.uses.len(), 1);
2342        assert_eq!(c.consumes.len(), 1);
2343        assert_eq!(c.exports.len(), 1);
2344    }
2345
2346    #[test]
2347    fn opaque_type_parses() {
2348        let c = parse_str("commons x { type T = opaque Int where NonNegative }").unwrap();
2349        let CommonsItem::Type(t) = &c.items[0] else {
2350            panic!()
2351        };
2352        assert!(matches!(t.body, TypeBody::Opaque { .. }));
2353    }
2354
2355    #[test]
2356    fn empty_commons() {
2357        let c = parse_str("commons fitness.units {}").unwrap();
2358        assert_eq!(c.name.joined(), "fitness.units");
2359        assert!(c.items.is_empty());
2360    }
2361
2362    #[test]
2363    fn one_type_decl() {
2364        let c = parse_str("commons x { type Metres = Int where NonNegative }").unwrap();
2365        assert_eq!(c.items.len(), 1);
2366        let CommonsItem::Type(t) = &c.items[0] else {
2367            panic!()
2368        };
2369        assert_eq!(t.name.name, "Metres");
2370        match &t.body {
2371            TypeBody::Refined {
2372                base, refinement, ..
2373            } => {
2374                assert_eq!(*base, BaseType::Int);
2375                assert!(refinement.is_some());
2376            }
2377            _ => panic!("expected refined body"),
2378        }
2379    }
2380
2381    #[test]
2382    fn function_decl() {
2383        let c = parse_str("commons x { fn add(a: Int, b: Int) -> Int { a + b } }").unwrap();
2384        let CommonsItem::Fn(f) = &c.items[0] else {
2385            panic!()
2386        };
2387        assert_eq!(f.name.ident().name, "add");
2388        assert_eq!(f.params.len(), 2);
2389    }
2390
2391    #[test]
2392    fn chained_comparison_is_error() {
2393        let errs = parse_str("commons x { fn f(a: Int, b: Int, c: Int) -> Bool { a < b < c } }")
2394            .unwrap_err();
2395        assert_eq!(errs[0].category, "bynk.parse.non_associative");
2396    }
2397
2398    #[test]
2399    fn chained_equality_is_error() {
2400        let errs = parse_str("commons x { fn f(a: Int, b: Int, c: Int) -> Bool { a == b == c } }")
2401            .unwrap_err();
2402        assert_eq!(errs[0].category, "bynk.parse.non_associative");
2403    }
2404
2405    /// Run `f` on a thread with a generous stack. The depth-guard tests build
2406    /// source that, *without* the guard, overflows — so if the guard ever
2407    /// regressed we want a clean assertion failure, not a `SIGABRT` that takes
2408    /// the whole test binary down. A large stack also absorbs the fat frames a
2409    /// debug build spends per recursion level (production release frames are
2410    /// ~9 KB/level, so `MAX_NESTING_DEPTH = 64` sits well inside a 1 MB stack;
2411    /// a debug frame is several times larger and would overflow libtest's
2412    /// default 2 MB test thread near the limit even though the guard fires).
2413    fn on_big_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
2414        std::thread::Builder::new()
2415            .stack_size(64 * 1024 * 1024)
2416            .spawn(f)
2417            .unwrap()
2418            .join()
2419            .unwrap()
2420    }
2421
2422    #[test]
2423    fn deeply_nested_parens_are_bounded_not_overflowed() {
2424        // Without a depth guard the parenthesised-expression recursion
2425        // (`parse_primary` -> `parse_expr` -> …) overflows the stack and aborts
2426        // the process (#713). Well past the limit it must instead report a
2427        // bounded-depth diagnostic. The nesting is left open so the guard, not
2428        // a later `)`, is what stops the descent.
2429        let errs = on_big_stack(|| {
2430            let depth = crate::MAX_NESTING_DEPTH + 8;
2431            let src = format!(
2432                "commons x {{ fn f() -> Int {{ {}0{} }} }}",
2433                "(".repeat(depth),
2434                ")".repeat(depth),
2435            );
2436            parse_str(&src).unwrap_err()
2437        });
2438        assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2439    }
2440
2441    #[test]
2442    fn deeply_nested_types_are_bounded_not_overflowed() {
2443        // The type parser self-recurses through generic type arguments
2444        // (`parse_type_ref` -> `parse_type_atom` -> `parse_type_ref`); the same
2445        // guard bounds it (#713). A right-nested `Result[Int, …]` in parameter
2446        // position drives that recursion.
2447        let errs = on_big_stack(|| {
2448            let depth = crate::MAX_NESTING_DEPTH + 8;
2449            let src = format!(
2450                "commons x {{ fn f(x: {}Int{}) -> Int {{ 0 }} }}",
2451                "Result[Int, ".repeat(depth),
2452                "]".repeat(depth),
2453            );
2454            parse_str(&src).unwrap_err()
2455        });
2456        assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2457    }
2458
2459    #[test]
2460    fn deeply_nested_patterns_are_bounded_not_overflowed() {
2461        // Variant patterns are a third self-recursive descent (`parse_pattern`
2462        // -> `parse_pattern_binding` -> `parse_pattern`) that routes through
2463        // neither `parse_expr` nor `parse_type_ref`; without its own guard a
2464        // nested `Ok(Ok(…))` match arm reproduces the #713 crash.
2465        let errs = on_big_stack(|| {
2466            let depth = crate::MAX_NESTING_DEPTH + 8;
2467            let src = format!(
2468                "commons x {{ fn f(n: Int) -> Int {{ match n {{ {}n{} => 0 }} }} }}",
2469                "Ok(".repeat(depth),
2470                ")".repeat(depth),
2471            );
2472            parse_str(&src).unwrap_err()
2473        });
2474        assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2475    }
2476
2477    #[test]
2478    fn nesting_below_the_limit_still_parses() {
2479        // The guard must not reject ordinary well-nested source: a paren-nested
2480        // expression comfortably under the limit still parses cleanly.
2481        let ok = on_big_stack(|| {
2482            let depth = crate::MAX_NESTING_DEPTH - 8;
2483            let src = format!(
2484                "commons x {{ fn f() -> Int {{ {}0{} }} }}",
2485                "(".repeat(depth),
2486                ")".repeat(depth),
2487            );
2488            parse_str(&src).is_ok()
2489        });
2490        assert!(ok, "well-nested source under the limit should parse");
2491    }
2492
2493    #[test]
2494    fn let_statement_parses() {
2495        let c = parse_str("commons x { fn f(n: Int) -> Int { let y = n + 1\n y } }").unwrap();
2496        let CommonsItem::Fn(f) = &c.items[0] else {
2497            panic!()
2498        };
2499        assert_eq!(f.body.statements.len(), 1);
2500        match &f.body.statements[0] {
2501            Statement::Let(l) => {
2502                assert_eq!(l.name.name, "y");
2503                assert!(l.type_annot.is_none());
2504            }
2505            _ => panic!("expected a pure `let` statement"),
2506        }
2507    }
2508
2509    #[test]
2510    fn let_with_annotation() {
2511        let c = parse_str("commons x { fn f(n: Int) -> Int { let y: Int = n\n y } }").unwrap();
2512        let CommonsItem::Fn(f) = &c.items[0] else {
2513            panic!()
2514        };
2515        match &f.body.statements[0] {
2516            Statement::Let(l) => assert!(l.type_annot.is_some()),
2517            _ => panic!("expected a pure `let` statement"),
2518        }
2519    }
2520
2521    #[test]
2522    fn if_else_parses_as_expression() {
2523        let c = parse_str("commons x { fn f(b: Bool) -> Int { if b { 1 } else { 0 } } }").unwrap();
2524        let CommonsItem::Fn(f) = &c.items[0] else {
2525            panic!()
2526        };
2527        assert!(matches!(f.body.tail.kind, ExprKind::If { .. }));
2528    }
2529
2530    #[test]
2531    fn else_if_chain_parses() {
2532        let c = parse_str(
2533            "commons x { fn f(n: Int) -> Int { if n < 0 { -1 } else if n == 0 { 0 } else { 1 } } }",
2534        )
2535        .unwrap();
2536        let CommonsItem::Fn(f) = &c.items[0] else {
2537            panic!()
2538        };
2539        let ExprKind::If { else_block, .. } = &f.body.tail.kind else {
2540            panic!()
2541        };
2542        // The else-branch is a block whose tail is another `If`.
2543        assert!(else_block.statements.is_empty());
2544        assert!(matches!(else_block.tail.kind, ExprKind::If { .. }));
2545    }
2546
2547    #[test]
2548    fn ok_and_err_parse_as_expressions() {
2549        let c = parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Ok(n) } }").unwrap();
2550        let CommonsItem::Fn(f) = &c.items[0] else {
2551            panic!()
2552        };
2553        assert!(matches!(f.body.tail.kind, ExprKind::Ok(_)));
2554
2555        let c =
2556            parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Err(\"x\") } }").unwrap();
2557        let CommonsItem::Fn(f) = &c.items[0] else {
2558            panic!()
2559        };
2560        assert!(matches!(f.body.tail.kind, ExprKind::Err(_)));
2561    }
2562
2563    #[test]
2564    fn question_postfix_parses() {
2565        let c = parse_str(
2566            "commons x { type T = Int where Positive\n fn f(n: Int) -> Result[T, ValidationError] { let x = T.of(n)?\n Ok(x) } }",
2567        )
2568        .unwrap();
2569        let CommonsItem::Fn(f) = &c.items[1] else {
2570            panic!()
2571        };
2572        let Statement::Let(l) = &f.body.statements[0] else {
2573            panic!("expected a pure `let` statement");
2574        };
2575        assert!(matches!(l.value.kind, ExprKind::Question(_)));
2576    }
2577
2578    #[test]
2579    fn constructor_call_parses() {
2580        let c = parse_str(
2581            "commons x { type T = Int where Positive\n fn f(n: Int) -> Result[T, ValidationError] { T.of(n) } }",
2582        )
2583        .unwrap();
2584        let CommonsItem::Fn(f) = &c.items[1] else {
2585            panic!()
2586        };
2587        // v0.2: T.of(n) parses as a MethodCall with receiver Ident("T"); the
2588        // checker reinterprets it as a static call by noticing T is a type.
2589        let ExprKind::MethodCall {
2590            receiver, method, ..
2591        } = &f.body.tail.kind
2592        else {
2593            panic!("expected MethodCall, got {:?}", f.body.tail.kind)
2594        };
2595        let ExprKind::Ident(id) = &receiver.kind else {
2596            panic!("expected receiver Ident");
2597        };
2598        assert_eq!(id.name, "T");
2599        assert_eq!(method.name, "of");
2600    }
2601
2602    #[test]
2603    fn result_type_ref_parses() {
2604        let c = parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Ok(n) } }").unwrap();
2605        let CommonsItem::Fn(f) = &c.items[0] else {
2606            panic!()
2607        };
2608        assert!(matches!(f.return_type, TypeRef::Result(_, _, _)));
2609    }
2610
2611    #[test]
2612    fn result_missing_arg_count_errors() {
2613        let errs = parse_str("commons x { fn f(n: Int) -> Result[Int] { Ok(n) } }").unwrap_err();
2614        assert_eq!(errs[0].category, "bynk.parse.generic_arg_count");
2615    }
2616
2617    #[test]
2618    fn field_access_parses_in_v0_2() {
2619        // v0.2: field access is supported (the type checker validates the
2620        // field exists on the receiver's type). Parser-level acceptance:
2621        let c =
2622            parse_str("commons x { type R = { foo: Int }\n fn f(r: R) -> Int { r.foo } }").unwrap();
2623        let CommonsItem::Fn(f) = &c.items[1] else {
2624            panic!()
2625        };
2626        assert!(matches!(f.body.tail.kind, ExprKind::FieldAccess { .. }));
2627    }
2628
2629    // -- v1.1 trivia attachment --
2630
2631    #[test]
2632    fn leading_line_comment_attaches_to_next_decl() {
2633        let src = "commons x {\n// explain the type\ntype T = Int where NonNegative\n}";
2634        let c = parse_str(src).unwrap();
2635        let CommonsItem::Type(t) = &c.items[0] else {
2636            panic!()
2637        };
2638        assert_eq!(
2639            t.trivia.leading,
2640            vec![Comment::Line(" explain the type".to_string())]
2641        );
2642        assert!(t.trivia.trailing.is_none());
2643    }
2644
2645    #[test]
2646    fn trailing_line_comment_attaches_to_prev_decl() {
2647        let src = "commons x {\ntype T = Int where NonNegative  // trailing note\n}";
2648        let c = parse_str(src).unwrap();
2649        let CommonsItem::Type(t) = &c.items[0] else {
2650            panic!()
2651        };
2652        assert!(t.trivia.leading.is_empty());
2653        assert_eq!(t.trivia.trailing.as_deref(), Some(" trailing note"));
2654    }
2655
2656    #[test]
2657    fn grouped_leading_comments_attach_together() {
2658        let src = "commons x {\n// one\n// two\n// three\ntype T = Int where Positive\n}";
2659        let c = parse_str(src).unwrap();
2660        let CommonsItem::Type(t) = &c.items[0] else {
2661            panic!()
2662        };
2663        assert_eq!(
2664            t.trivia.leading,
2665            vec![
2666                Comment::Line(" one".to_string()),
2667                Comment::Line(" two".to_string()),
2668                Comment::Line(" three".to_string())
2669            ],
2670        );
2671    }
2672
2673    #[test]
2674    fn comment_with_doc_block_keeps_both() {
2675        // Both `-- intro` and the doc block should attach to the type decl.
2676        let src = "commons x {\n// intro\n---\ndocs\n---\ntype T = Int where Positive\n}";
2677        let c = parse_str(src).unwrap();
2678        let CommonsItem::Type(t) = &c.items[0] else {
2679            panic!()
2680        };
2681        assert_eq!(t.trivia.leading, vec![Comment::Line(" intro".to_string())]);
2682        assert_eq!(t.documentation.as_deref(), Some("docs"));
2683    }
2684
2685    #[test]
2686    fn messages_keyword_does_not_collide_with_a_commons_name_segment() {
2687        // `messages` is RESERVED_CONTEXTUAL (like `case`/`on`/`suite`), not a
2688        // hard keyword: `commons app.messages { ... }` — the design's own
2689        // natural naming choice for a bundle commons — must still parse.
2690        // (Caught during slice-1 implementation: a first pass made `messages`
2691        // a plain hard keyword and this exact name broke.)
2692        let src = "commons app.messages {\ntype T = Int where Positive\n}";
2693        let c = parse_str(src).unwrap();
2694        assert_eq!(c.name.joined(), "app.messages");
2695    }
2696
2697    #[test]
2698    fn messages_decl_parses_tag_annotation_and_entries() {
2699        // message-bundles slice 1 (#859): the construct + doc/trivia wiring.
2700        let src = "commons app.messages {\n\
2701                   // intro\n\
2702                   ---\n\
2703                   docs\n\
2704                   ---\n\
2705                   messages \"en\" @reference {\n\
2706                   \"greeting\" => \"Hello, {name}!\"\n\
2707                   \"farewell\" => \"Bye\"\n\
2708                   } // trailing\n\
2709                   }";
2710        let c = parse_str(src).unwrap();
2711        let CommonsItem::Messages(m) = &c.items[0] else {
2712            panic!("expected a messages item, got {:?}", c.items[0]);
2713        };
2714        assert_eq!(m.tag, "en");
2715        assert_eq!(m.annotations.len(), 1);
2716        assert_eq!(m.annotations[0].name.name, "reference");
2717        assert!(m.annotations[0].args.is_empty());
2718        assert_eq!(m.entries.len(), 2);
2719        assert_eq!(m.entries[0].code, "greeting");
2720        assert_eq!(m.entries[0].template, "Hello, {name}!");
2721        assert_eq!(m.entries[1].code, "farewell");
2722        assert_eq!(m.entries[1].template, "Bye");
2723        assert_eq!(m.trivia.leading, vec![Comment::Line(" intro".to_string())]);
2724        assert_eq!(m.documentation.as_deref(), Some("docs"));
2725        assert_eq!(m.trivia.trailing.as_deref(), Some(" trailing"));
2726    }
2727
2728    #[test]
2729    fn messages_decl_parses_with_no_annotation_and_no_entries() {
2730        // The parser stays permissive on annotation cardinality (zero-or-more)
2731        // — "exactly one `@reference`" is a checker concern (validate.rs), not
2732        // a parse error.
2733        let src = "commons app.messages {\nmessages \"en\" {\n}\n}";
2734        let c = parse_str(src).unwrap();
2735        let CommonsItem::Messages(m) = &c.items[0] else {
2736            panic!("expected a messages item, got {:?}", c.items[0]);
2737        };
2738        assert_eq!(m.tag, "en");
2739        assert!(m.annotations.is_empty());
2740        assert!(m.entries.is_empty());
2741    }
2742
2743    #[test]
2744    fn messages_decl_parses_syntactically_inside_a_context_too() {
2745        // Commons-only legality is a checker concern (bynk.messages.outside_commons
2746        // in bynk-emit's project validation), not a parser rejection — mirrors
2747        // how `service`/`agent` already parse syntactically inside `adapter`
2748        // bodies for the same reason.
2749        let src = "context app.svc {\nmessages \"en\" @reference {\n\"a\" => \"b\"\n}\n}";
2750        let toks = tokenize(src).unwrap();
2751        let (unit, errors) = parse_unit_with_recovery(&toks, src);
2752        assert!(errors.is_empty(), "unexpected parse errors: {errors:?}");
2753        let Some(SourceUnit::Context(ctx)) = unit else {
2754            panic!("expected a context")
2755        };
2756        let CommonsItem::Messages(m) = &ctx.items[0] else {
2757            panic!("expected a messages item, got {:?}", ctx.items[0]);
2758        };
2759        assert_eq!(m.tag, "en");
2760    }
2761
2762    #[test]
2763    fn comment_before_let_statement_attaches() {
2764        let src = "commons x {\nfn f(n: Int) -> Int {\n// pick a value\nlet y = n + 1\ny\n}\n}";
2765        let c = parse_str(src).unwrap();
2766        let CommonsItem::Fn(f) = &c.items[0] else {
2767            panic!()
2768        };
2769        let Statement::Let(l) = &f.body.statements[0] else {
2770            panic!()
2771        };
2772        assert_eq!(
2773            l.trivia.leading,
2774            vec![Comment::Line(" pick a value".to_string())]
2775        );
2776    }
2777
2778    #[test]
2779    fn comment_before_tail_attaches_to_block_tail() {
2780        let src = "commons x {\nfn f(n: Int) -> Int {\nlet y = n + 1\n// result\ny\n}\n}";
2781        let c = parse_str(src).unwrap();
2782        let CommonsItem::Fn(f) = &c.items[0] else {
2783            panic!()
2784        };
2785        assert_eq!(
2786            f.body.tail_leading_comments,
2787            vec![Comment::Line(" result".to_string())],
2788        );
2789    }
2790
2791    /// #637 Gap A: the contextual keywords `on` / `suite` / `case` are lexer
2792    /// tokens but `expect_ident` admits them as identifiers outside their one
2793    /// keyword position, so they are valid record-field and parameter names.
2794    /// The keyword reference now renders them as a distinct "contextual" tier
2795    /// rather than claiming (falsely) that they cannot be used as identifiers.
2796    #[test]
2797    fn contextual_keywords_are_valid_identifiers() {
2798        // Record field names.
2799        let c = parse_str("commons demo {\n  type R = { on: Int, suite: String, case: Bool }\n}")
2800            .expect("`on`/`suite`/`case` are valid field names");
2801        let CommonsItem::Type(_) = &c.items[0] else {
2802            panic!("expected a type decl")
2803        };
2804
2805        // Function parameter names (the other `expect_ident` position).
2806        parse_str("commons demo {\n  fn f(on: Int, case: Int) -> Int { 0 }\n}")
2807            .expect("`on`/`case` are valid parameter names");
2808
2809        // `suite` too, as a field name.
2810        parse_str("commons demo {\n  type R = { suite: Int }\n}")
2811            .expect("`suite` is a valid field name");
2812    }
2813
2814    /// #2837: a keyword is a name where the name is a label (followed by `:`)
2815    /// or a member on the `.`'s line, and nowhere it would bind a variable.
2816    #[test]
2817    fn keywords_are_labels_and_members_not_bindings() {
2818        for src in [
2819            "commons demo {\n  type A = { type: String, from: Int, self: Bool }\n}",
2820            "commons demo {\n  type S = | P(from: String, type: String)\n}",
2821            "commons demo {\n  type A = { type: String }\n  fn f(a: A) -> String { a.type }\n}",
2822            "commons demo {\n  type A = { type: String }\n  fn f() -> A { A { type: \"x\" } }\n}",
2823            "commons demo {\n  type A = { type: String }\n  fn f(a: A) -> String { match a { A { type: t, .. } => t } }\n}",
2824            "commons demo {\n  type S = | P(from: String)\n  fn f(s: S) -> String { match s { P(from: x) => x } }\n}",
2825            "commons demo {\n  type S = { n: Int }\n  fn S.from(n: Int) -> S { S { n: n } }\n  fn g() -> S { S.from(1) }\n}",
2826        ] {
2827            parse_str(src).unwrap_or_else(|e| panic!("should parse: {src}\n{e:?}"));
2828        }
2829        for src in [
2830            "commons demo {\n  fn f(type: Int) -> Int { 1 }\n}",
2831            "commons demo {\n  fn f() -> Int { let from = 1\n from }\n}",
2832            "commons demo {\n  type A = { type String }\n}",
2833            // The same-line rule: `a.` then a statement on the next line.
2834            "commons demo {\n  fn f(a: Int) -> Int {\n    a.\n    let x = 1\n    x\n  }\n}",
2835        ] {
2836            let errs = parse_str(src).expect_err(src);
2837            assert_eq!(errs[0].category, "bynk.parse.reserved_keyword", "{src}");
2838        }
2839    }
2840
2841    /// #2837: keyword shorthand is a targeted error. A pattern gets the fix
2842    /// `type: type_` (`MaybeIncorrect`), fresh when `type_` is already spelled;
2843    /// a construction gets a note and no fix.
2844    #[test]
2845    fn keyword_shorthand_is_a_targeted_error() {
2846        let pat = |extra: &str| {
2847            format!(
2848                "commons demo {{\n  type A = {{ type: String }}\n  fn f(a: A) -> String {{ {extra} match a {{ A {{ type, .. }} => \"x\" }} }}\n}}"
2849            )
2850        };
2851        let errs = parse_str(&pat("")).expect_err("pattern shorthand");
2852        assert_eq!(errs[0].category, "bynk.parse.keyword_field_shorthand");
2853        let fix = &errs[0].suggestions[0];
2854        assert_eq!(fix.edits[0].1, "type: type_");
2855        assert!(matches!(
2856            fix.applicability,
2857            crate::error::Applicability::MaybeIncorrect
2858        ));
2859
2860        let errs = parse_str(&pat("let type_ = 1")).expect_err("pattern shorthand");
2861        assert_eq!(errs[0].suggestions[0].edits[0].1, "type: type_2");
2862
2863        let errs = parse_str(
2864            "commons demo {\n  type A = { type: String }\n  fn f() -> A { A { type } }\n}",
2865        )
2866        .expect_err("construction shorthand");
2867        assert_eq!(errs[0].category, "bynk.parse.keyword_field_shorthand");
2868        assert!(errs[0].suggestions.is_empty());
2869    }
2870
2871    /// Drift guard: every alphabetic keyword the lexer declares must be
2872    /// classified by `is_reserved_keyword`, or be one of the *contextual*
2873    /// keywords `expect_ident` deliberately admits as identifiers
2874    /// (`on`/`suite`/`case`). Everything else in this codebase that can
2875    /// drift has a guard; this predicate had silently fallen 17 keywords
2876    /// behind, degrading the reserved-keyword diagnostic to the generic
2877    /// expected-token one.
2878    #[test]
2879    fn is_reserved_keyword_covers_every_lexer_keyword() {
2880        let lexer_src = include_str!("lexer.rs");
2881        let mut words = Vec::new();
2882        for line in lexer_src.lines() {
2883            let t = line.trim();
2884            if let Some(rest) = t.strip_prefix("#[token(\"")
2885                && let Some(word) = rest.split('"').next()
2886                && word.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
2887                && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
2888            {
2889                words.push(word.to_string());
2890            }
2891        }
2892        assert!(
2893            words.len() > 30,
2894            "keyword extraction looks broken: only {} words",
2895            words.len()
2896        );
2897        // Contextual keywords double as identifiers (see `expect_ident`); the
2898        // tier is single-sourced in `keywords::RESERVED_CONTEXTUAL`.
2899        use crate::keywords::RESERVED_CONTEXTUAL;
2900        let mut unclassified = Vec::new();
2901        for word in &words {
2902            let tokens = crate::lexer::tokenize(word).expect("keyword lexes");
2903            let kind = tokens.first().expect("keyword yields a token").kind;
2904            if !is_reserved_keyword(kind) && !RESERVED_CONTEXTUAL.contains(&word.as_str()) {
2905                unclassified.push(word.clone());
2906            }
2907        }
2908        assert!(
2909            unclassified.is_empty(),
2910            "keywords missing from is_reserved_keyword (add them, or document \
2911             them as contextual): {unclassified:?}"
2912        );
2913    }
2914
2915    /// Finding #27/#30: pins `is_item_start` to exactly the keyword set
2916    /// `declarations.rs`'s six item loops (`parse_commons_brace`/`_fragment`,
2917    /// `parse_context_brace`/`_fragment`, `parse_test_brace`/`_fragment`) plus
2918    /// `parse_adapter_body` dispatch on, as of this writing — the drift this
2919    /// finding fixed (`Property`, `Actor`, `Event`, `Binding`, and the
2920    /// `adapter` unit keyword itself were all missing from
2921    /// `recover_to_top_item`'s old hand-written sync list, even though every
2922    /// one of them is a real item/unit start). Adding a new item keyword to
2923    /// any of those loops should mean deliberately updating this list too,
2924    /// not silently leaving recovery unable to resync at it.
2925    #[test]
2926    fn is_item_start_matches_the_pinned_keyword_set() {
2927        use TokenKind::*;
2928        let expected_true = [
2929            Commons, Context, Adapter, Suite, Type, Fn, Messages, Event, Asset, Embed, Const, Uses,
2930            Consumes, Exports, Capability, Provides, Service, Agent, Actor, Binding, Stub, Case,
2931            Property,
2932        ];
2933        for kind in expected_true {
2934            assert!(is_item_start(kind), "{kind:?} must be an item start");
2935        }
2936        let expected_false = [
2937            Ident, Plus, Minus, Colon, Dot, Eq, LBrace, RBrace, LParen, RParen, If, Else, Let,
2938            Where, True, False, Match, Is, On, Given,
2939        ];
2940        for kind in expected_false {
2941            assert!(!is_item_start(kind), "{kind:?} must not be an item start");
2942        }
2943    }
2944
2945    /// Fuzz-found (#516): a context-only keyword at item position in a
2946    /// commons errors without consuming the token, and the recovery sync
2947    /// stops at exactly that keyword — without a progress guard the item
2948    /// loop re-reported the same error until memory ran out.
2949    #[test]
2950    fn recovery_makes_progress_on_context_only_keyword_in_commons() {
2951        let src = "commons demo\n\ncapability Logger {\n  fn log(m: String) -> Effect[()]\n}\n";
2952        let tokens = crate::lexer::tokenize(src).unwrap();
2953        let (unit, errors) = parse_unit_with_recovery(&tokens, src);
2954        assert!(unit.is_some(), "the commons header still parses");
2955        assert!(
2956            errors
2957                .iter()
2958                .any(|e| e.category == "bynk.capability.outside_context"),
2959            "the misplaced capability is reported: {errors:?}"
2960        );
2961        // Termination is the real assertion (this used to OOM); a bounded,
2962        // non-repeating error list is the observable proxy.
2963        assert!(errors.len() < 10, "recovery repeated itself: {errors:?}");
2964    }
2965
2966    #[test]
2967    fn trailing_file_comment_becomes_unit_trailing() {
2968        // A comment after the last item but before EOF (fragment form)
2969        // becomes the commons body's trailing comments so the formatter
2970        // can preserve it.
2971        let src = "commons x\n\ntype T = Int where Positive\n// afterword\n";
2972        let c = parse_str(src).unwrap();
2973        assert_eq!(
2974            c.trailing_comments,
2975            vec![Comment::Line(" afterword".to_string())]
2976        );
2977    }
2978
2979    #[test]
2980    fn trailing_file_comment_after_a_brace_form_commons_is_not_dropped() {
2981        // Regression: the brace form's item loop exits on `RBrace`, never
2982        // reaching the fragment form's end-of-input case that drains the
2983        // trivia table's epilogue — so a comment after the closing `}` was
2984        // silently discarded (and, per `epilogue_is_empty`'s debug_assert,
2985        // would panic a debug build instead of round-tripping through
2986        // `bynk-fmt`).
2987        let src = "commons x {\n  type T = Int where Positive\n}\n// afterword\n";
2988        let c = parse_str(src).unwrap();
2989        assert_eq!(
2990            c.trailing_comments,
2991            vec![Comment::Line(" afterword".to_string())]
2992        );
2993    }
2994
2995    #[test]
2996    fn trailing_file_comment_after_a_brace_form_context_is_not_dropped() {
2997        // Same regression as the commons case, for `parse_context_brace`.
2998        let src = "context x {\n  type T = Int where Positive\n}\n// afterword\n";
2999        let SourceUnit::Context(c) = parse_unit_str(src).unwrap() else {
3000            panic!("expected context");
3001        };
3002        assert_eq!(
3003            c.trailing_comments,
3004            vec![Comment::Line(" afterword".to_string())]
3005        );
3006    }
3007
3008    #[test]
3009    fn trailing_file_comment_after_a_brace_form_suite_is_not_dropped() {
3010        // Same regression as the commons case, for `parse_test_brace`.
3011        let src = "suite x {\n  case \"c\" {\n    expect 1 == 1\n  }\n}\n// afterword\n";
3012        let SourceUnit::Suite(s) = parse_unit_str(src).unwrap() else {
3013            panic!("expected suite");
3014        };
3015        assert_eq!(
3016            s.trailing_comments,
3017            vec![Comment::Line(" afterword".to_string())]
3018        );
3019    }
3020
3021    /// Finding #30: unlike the three regressions just above,
3022    /// `parse_adapter_body`'s brace-closing path never called
3023    /// `take_epilogue` at all (not a regression from a shared pattern — it
3024    /// simply never had the call), so a comment after a brace-form adapter's
3025    /// closing `}` was silently dropped. The fragment form (no braces) was
3026    /// already correct.
3027    #[test]
3028    fn trailing_file_comment_after_a_brace_form_adapter_is_not_dropped() {
3029        let src = "adapter x {\n  binding \"./x.ts\"\n}\n// afterword\n";
3030        let SourceUnit::Adapter(a) = parse_unit_str(src).unwrap() else {
3031            panic!("expected adapter");
3032        };
3033        assert_eq!(
3034            a.trailing_comments,
3035            vec![Comment::Line(" afterword".to_string())]
3036        );
3037    }
3038
3039    /// #2321: `includes [ … ]` follows the module, before `requires`; it is a
3040    /// contextual word, so a malformed or unclosed list is an error, not a panic.
3041    #[test]
3042    fn binding_includes_list_parses_before_requires() {
3043        let src = "adapter x {\n  binding \"./x.ts\" includes [\"./a.wasm\", \"b/c.wasm\"] requires { \"p\": \"^1\" }\n}\n";
3044        let SourceUnit::Adapter(a) = parse_unit_str(src).unwrap() else {
3045            panic!("expected adapter");
3046        };
3047        let b = a.binding.unwrap();
3048        let paths: Vec<_> = b.includes.iter().map(|i| i.path.as_str()).collect();
3049        assert_eq!(paths, ["./a.wasm", "b/c.wasm"]);
3050        assert_eq!(b.requires.len(), 1);
3051        assert!(parse_unit_str("adapter x {\n  binding \"./x.ts\" includes [\"a.wasm\"").is_err());
3052        assert!(parse_unit_str("adapter x {\n  binding \"./x.ts\" includes [a]\n}\n").is_err());
3053    }
3054
3055    // -- Six-fold unification (review Part 3): the fragment-only ordering
3056    // restrictions declarations.rs's brace/fragment pairs preserve, now that
3057    // they share one function each behind `brace: bool`. None of these had
3058    // any prior test coverage at all. --
3059
3060    /// Fragment-form commons: `uses` must precede every `type`/`fn`.
3061    #[test]
3062    fn commons_fragment_rejects_uses_after_a_decl() {
3063        let src = "commons x\n\ntype T = Int where Positive\nuses bynk.list\n";
3064        let errs = parse_str(src).unwrap_err();
3065        assert!(
3066            errs.iter()
3067                .any(|e| e.category == "bynk.parse.uses_after_decls"),
3068            "{errs:?}"
3069        );
3070    }
3071
3072    /// The same ordering is NOT enforced in brace form — `uses` may appear
3073    /// anywhere in the body.
3074    #[test]
3075    fn commons_brace_allows_uses_after_a_decl() {
3076        let src = "commons x {\n  type T = Int where Positive\n  uses bynk.list\n}\n";
3077        parse_str(src).expect("brace form must not enforce fragment's uses-ordering rule");
3078    }
3079
3080    /// Fragment-form context: `consumes` must precede every `type`/`fn`/etc.
3081    #[test]
3082    fn context_fragment_rejects_consumes_after_a_decl() {
3083        let src = "context x\n\ntype T = Int where Positive\nconsumes bynk\n";
3084        let errs = parse_unit_str(src).unwrap_err();
3085        assert!(
3086            errs.iter()
3087                .any(|e| e.category == "bynk.parse.consumes_after_decls"),
3088            "{errs:?}"
3089        );
3090    }
3091
3092    /// Fragment-form context: `exports` must precede every `type`/`fn`/etc.
3093    #[test]
3094    fn context_fragment_rejects_exports_after_a_decl() {
3095        let src = "context x\n\ntype T = Int where Positive\nexports opaque { T }\n";
3096        let errs = parse_unit_str(src).unwrap_err();
3097        assert!(
3098            errs.iter()
3099                .any(|e| e.category == "bynk.parse.exports_after_decls"),
3100            "{errs:?}"
3101        );
3102    }
3103
3104    /// Brace-form context enforces none of the three orderings.
3105    #[test]
3106    fn context_brace_allows_consumes_and_exports_after_a_decl() {
3107        let src = "context x {\n  type T = Int where Positive\n  consumes bynk\n  exports opaque { T }\n}\n";
3108        parse_unit_str(src)
3109            .expect("brace form must not enforce fragment's consumes/exports-ordering rules");
3110    }
3111
3112    /// Fragment-form suite/test: `uses` must precede every `stub`/`case`/`property`.
3113    #[test]
3114    fn test_fragment_rejects_uses_after_a_decl() {
3115        let src = "suite m\n\ncase \"c\" {\n  expect true\n}\nuses bynk.list\n";
3116        let errs = parse_unit_str(src).unwrap_err();
3117        assert!(
3118            errs.iter()
3119                .any(|e| e.category == "bynk.parse.uses_after_decls"),
3120            "{errs:?}"
3121        );
3122    }
3123
3124    /// Brace-form suite/test allows `uses` anywhere.
3125    #[test]
3126    fn test_brace_allows_uses_after_a_decl() {
3127        let src = "suite m {\n  case \"c\" {\n    expect true\n  }\n  uses bynk.list\n}\n";
3128        parse_unit_str(src).expect("brace form must not enforce fragment's uses-ordering rule");
3129    }
3130
3131    // ---- #636: `if`/`match` condition vs record construction ----
3132
3133    /// Parse `body` as the tail expression of a fn and return its kind.
3134    fn body_tail(body: &str) -> ExprKind {
3135        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3136        let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3137        let CommonsItem::Fn(f) = &c.items[0] else {
3138            panic!("expected fn, got {:?}", c.items[0]);
3139        };
3140        f.body.tail.kind.clone()
3141    }
3142
3143    fn body_err(body: &str) -> Vec<CompileError> {
3144        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3145        parse_str(&src).expect_err(&format!("expected a parse error for {body:?}"))
3146    }
3147
3148    // ---- #3191: `by` is a contextual keyword ----
3149
3150    /// The body of `fn f() -> Int { <body> }`, parsed.
3151    fn body_of(body: &str) -> Block {
3152        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3153        let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3154        let CommonsItem::Fn(f) = &c.items[0] else {
3155            panic!("expected fn, got {:?}", c.items[0]);
3156        };
3157        f.body.clone()
3158    }
3159
3160    fn effect_let_principal(stmt: &Statement) -> Option<&CallSiteActor> {
3161        match stmt {
3162            Statement::EffectLet(l) => l.principal.as_ref(),
3163            other => panic!("expected an effect-let, got {other:?}"),
3164        }
3165    }
3166
3167    #[test]
3168    fn by_is_an_ordinary_name_in_every_identifier_position() {
3169        // A parameter, a lambda parameter, a `let`, a bare reference, field
3170        // shorthand, a record pattern and an annotation label all take `by`.
3171        for src in [
3172            "commons x\n\nfn f(by: Int) -> Int { by }\n",
3173            "commons x\n\nfn f(xs: List[Int], by: Int) -> List[Int] { xs.map((x) => x + by) }\n",
3174            "commons x\n\nfn f() -> Int { let by = 1 by }\n",
3175            "commons x\n\ntype S = { by: Int }\n\nfn f() -> S { let by = 1 S { by } }\n",
3176            "commons x\n\ntype S = { by: Int }\n\nfn f(s: S) -> Int { let S { by, .. } = s by }\n",
3177            "commons x\n\nfn f() -> Int { let g = (by: Int) => by g(1) }\n",
3178        ] {
3179            parse_str(src).unwrap_or_else(|e| panic!("{src:?}: {e:?}"));
3180        }
3181        // An agent operation and a `store` field named `by` (ADR: decision E).
3182        let agent = "context x\n\nagent A {\n  key id: String\n  store by: Cell[Int]\n  on call by(n: Int) -> Effect[Int] {\n    Effect.pure(n)\n  }\n}\n";
3183        let (_, errors) = parse_recover_str(agent);
3184        assert!(errors.is_empty(), "{errors:?}");
3185    }
3186
3187    #[test]
3188    fn by_still_starts_a_call_site_actor_clause_on_the_values_line() {
3189        let block = body_of("let r <- g() by User(\"bob\")\n  1");
3190        let actor = effect_let_principal(&block.statements[0]).expect("a clause");
3191        assert_eq!(actor.actor.name, "User");
3192        // Without an identity too.
3193        let block = body_of("let r <- g() by Nobody\n  1");
3194        assert_eq!(
3195            effect_let_principal(&block.statements[0])
3196                .unwrap()
3197                .actor
3198                .name,
3199            "Nobody"
3200        );
3201    }
3202
3203    #[test]
3204    fn a_by_on_the_next_line_after_an_effect_let_is_a_statement_not_a_clause() {
3205        let block = body_of("let a <- g()\n  by");
3206        assert!(effect_let_principal(&block.statements[0]).is_none());
3207        assert!(matches!(&block.tail.kind, ExprKind::Ident(i) if i.name == "by"));
3208        // Even with an identifier after it: the line break ends the value.
3209        let src = "commons x\n\nfn f() -> Int {\n  let a <- g()\n  by\n  User\n}\n";
3210        let c = parse_str(src);
3211        // `by` then `User` is two expressions in a row — the generic report,
3212        // never a silently-read clause.
3213        assert!(c.is_err(), "{c:?}");
3214    }
3215
3216    #[test]
3217    fn a_by_not_followed_by_an_identifier_is_a_tail_even_on_the_values_line() {
3218        let src = "commons x\n\nfn f() -> Effect[Int] { let by = 1 let a <- g() by }\n";
3219        let c = parse_str(src).unwrap_or_else(|e| panic!("{e:?}"));
3220        let CommonsItem::Fn(f) = &c.items[0] else {
3221            panic!("expected fn")
3222        };
3223        assert!(effect_let_principal(&f.body.statements[1]).is_none());
3224        assert!(matches!(&f.body.tail.kind, ExprKind::Ident(i) if i.name == "by"));
3225    }
3226
3227    #[test]
3228    fn advance_still_reads_its_by_and_admits_a_variable_amount() {
3229        for stmt in ["advance Clock by 15.minutes", "advance Clock by by"] {
3230            let src = format!("suite x\n\ncase \"c\" {{\n  let by = 1.minute\n  {stmt}\n}}\n");
3231            let toks = tokenize(&src).unwrap();
3232            let unit = parse_unit_with_recovery(&toks, &src);
3233            assert!(unit.1.is_empty(), "{stmt}: {:?}", unit.1);
3234        }
3235    }
3236
3237    #[test]
3238    fn a_handler_actor_clause_still_follows_the_return_type() {
3239        let src = "context x\n\nservice api from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by v: Visitor {\n    Ok(\"x\")\n  }\n}\n";
3240        let (unit, errors) = parse_recover_str(src);
3241        assert!(errors.is_empty(), "{errors:?}");
3242        assert!(unit.is_some());
3243        // The clause word is also a legal name for the binder and the actor.
3244        let src = "context x\n\nservice api from http {\n  on GET(\"/\") (by: Int) -> Effect[HttpResult[String]] by by: Visitor {\n    Ok(\"x\")\n  }\n}\n";
3245        let (_, errors) = parse_recover_str(src);
3246        assert!(errors.is_empty(), "{errors:?}");
3247    }
3248
3249    #[test]
3250    fn another_keyword_is_still_refused_as_a_field_shorthand() {
3251        // `by` left the keyword shorthand diagnostic; the hard keywords did not.
3252        let errs = parse_str(
3253            "commons x\n\ntype S = { type: Int }\n\nfn f() -> S { let type = 1 S { type } }\n",
3254        )
3255        .expect_err("`type` is reserved");
3256        assert!(!errs.is_empty());
3257    }
3258
3259    // ---- #2641: record patterns ----
3260
3261    /// Apply a parse error's first suggestion to `src`.
3262    fn apply_fix(src: &str, err: &CompileError) -> String {
3263        assert_eq!(
3264            err.suggestions[0].applicability,
3265            crate::error::Applicability::MachineApplicable
3266        );
3267        apply_quick_fix(src, err)
3268    }
3269
3270    /// Apply the first suggestion whatever its applicability: a quick fix the
3271    /// editor offers, which `--fix` and fix-all would not take.
3272    fn apply_quick_fix(src: &str, err: &CompileError) -> String {
3273        let s = &err.suggestions[0];
3274        let mut edits = s.edits.clone();
3275        edits.sort_by_key(|(span, _)| std::cmp::Reverse(span.start));
3276        let mut out = src.to_string();
3277        for (span, text) in edits {
3278            out.replace_range(span.start..span.end, &text);
3279        }
3280        out
3281    }
3282
3283    // ---- #3161: a bare expression statement ----
3284
3285    const BARE: &str = "bynk.parse.bare_expression_statement";
3286
3287    #[test]
3288    fn a_bare_effectful_call_suggests_let_arrow() {
3289        let src = "commons x\n\nfn f() -> Int {\n  Logger.info(\"hi\")\n  1\n}\n";
3290        let errs = parse_str(src).expect_err("bare call");
3291        assert_eq!(errs[0].category, BARE, "{errs:?}");
3292        assert_eq!(
3293            apply_fix(src, &errs[0]),
3294            "commons x\n\nfn f() -> Int {\n  let _ <- Logger.info(\"hi\")\n  1\n}\n"
3295        );
3296    }
3297
3298    #[test]
3299    fn a_bare_cell_update_and_agent_call_suggest_let_arrow() {
3300        for call in ["n.update((v) => v + 1)", "Counter(\"a\").bump(1)"] {
3301            let src = format!("commons x\n\nfn f() -> Int {{\n  {call}\n  n\n}}\n");
3302            let errs = parse_str(&src).expect_err(call);
3303            assert_eq!(errs[0].category, BARE, "{call}: {errs:?}");
3304            assert!(apply_fix(&src, &errs[0]).contains(&format!("let _ <- {call}")));
3305        }
3306    }
3307
3308    #[test]
3309    fn a_bare_pure_static_call_suggests_let_equals() {
3310        // A capitalised root is not always a capability: these namespaces
3311        // are pure, so `<-` would be the wrong guess.
3312        for call in [
3313            "Json.encode(x)",
3314            "Set.of(xs)",
3315            "List.empty()",
3316            "Bytes.fromUtf8(s).toHex()",
3317            "Map.empty()",
3318        ] {
3319            let src = format!("commons x\n\nfn f() -> Int {{\n  {call}\n  1\n}}\n");
3320            let errs = parse_str(&src).expect_err(call);
3321            assert_eq!(errs[0].category, BARE, "{call}: {errs:?}");
3322            let fixed = apply_quick_fix(&src, &errs[0]);
3323            assert!(
3324                fixed.contains(&format!("let _ = {call}")),
3325                "{call}: {fixed}"
3326            );
3327        }
3328    }
3329
3330    #[test]
3331    fn a_bare_pure_expression_suggests_let_equals() {
3332        let src = "commons x\n\nfn f() -> Int {\n  g(1)\n  let y = 2\n  y\n}\n";
3333        let errs = parse_str(src).expect_err("bare call");
3334        assert_eq!(errs[0].category, BARE, "{errs:?}");
3335        // #3537: `let _ =` may drop an effect, so it is never taken mechanically.
3336        assert_eq!(
3337            errs[0].suggestions[0].applicability,
3338            crate::error::Applicability::MaybeIncorrect
3339        );
3340        assert_eq!(
3341            apply_quick_fix(src, &errs[0]),
3342            "commons x\n\nfn f() -> Int {\n  let _ = g(1)\n  let y = 2\n  y\n}\n"
3343        );
3344    }
3345
3346    #[test]
3347    fn parsing_continues_after_a_bare_expression() {
3348        // The second error, in the same block, is still reported; the bare
3349        // statement itself is kept (as `let _ = …`) in the recovered AST.
3350        let src =
3351            "commons x\n\nfn f() -> Int {\n  g(1)\n  let = 2\n  3\n}\n\nfn h() -> Int { 4 }\n";
3352        let (unit, errors) = parse_recover_str(src);
3353        let cats: Vec<_> = errors.iter().map(|e| e.category).collect();
3354        assert_eq!(cats[0], BARE, "{cats:?}");
3355        assert!(cats.len() >= 2, "a later error is still reported: {cats:?}");
3356        let Some(SourceUnit::Commons(c)) = unit else {
3357            panic!("expected commons")
3358        };
3359        assert!(
3360            c.items
3361                .iter()
3362                .any(|i| matches!(i, CommonsItem::Fn(f) if f.name.ident().name == "h")),
3363            "`fn h` after the broken block still parses"
3364        );
3365    }
3366
3367    #[test]
3368    fn a_bare_expression_alone_in_the_recovered_ast_keeps_the_function() {
3369        let src = "commons x\n\nfn f() -> Int {\n  g(1)\n  2\n}\n";
3370        let (unit, errors) = parse_recover_str(src);
3371        assert_eq!(errors.len(), 1, "{errors:?}");
3372        assert_eq!(errors[0].category, BARE);
3373        let Some(SourceUnit::Commons(c)) = unit else {
3374            panic!("expected commons")
3375        };
3376        assert!(c.items.iter().any(|i| matches!(i, CommonsItem::Fn(_))));
3377    }
3378
3379    #[test]
3380    fn a_stray_token_after_a_tail_keeps_the_generic_report() {
3381        // `)` cannot start a statement, so this is not a bare expression.
3382        let errs = body_err("1\n  )");
3383        assert_eq!(errs[0].category, "bynk.parse.expected_token", "{errs:?}");
3384        // Nor is a tail followed on the same line.
3385        let errs = body_err("1 2");
3386        assert_ne!(errs[0].category, BARE, "{errs:?}");
3387    }
3388
3389    #[test]
3390    fn a_second_match_keeps_its_own_report() {
3391        let errs = body_err("match 1 {\n    _ => 1\n  }\n  match 2 {\n    _ => 2\n  }");
3392        assert_eq!(errs[0].category, "bynk.parse.match_ends_block", "{errs:?}");
3393    }
3394
3395    // ---- #2680: list patterns ----
3396
3397    #[test]
3398    fn list_patterns_parse_in_every_shape() {
3399        let ExprKind::Match { arms, .. } = body_tail(
3400            "match xs { [] => 0\n [a] => 1\n [a, b, ..] => 2\n [a, ..rest] => 3\n [..all] => 4\n [..] => 5\n [a, ..,] => 6\n Some([x, ..]) => 7 }",
3401        ) else {
3402            panic!("expected Match");
3403        };
3404        let shape = |i: usize| match &arms[i].pattern {
3405            Pattern::List { elems, rest, .. } => (
3406                elems.len(),
3407                rest.as_ref()
3408                    .map(|r| r.binder.as_ref().map(|b| b.name.clone())),
3409            ),
3410            other => panic!("arm {i}: expected a list pattern, got {other:?}"),
3411        };
3412        assert_eq!(shape(0), (0, None));
3413        assert_eq!(shape(1), (1, None));
3414        assert_eq!(shape(2), (2, Some(None)));
3415        assert_eq!(shape(3), (1, Some(Some("rest".to_string()))));
3416        assert_eq!(shape(4), (0, Some(Some("all".to_string()))));
3417        assert_eq!(shape(5), (0, Some(None)));
3418        assert_eq!(shape(6), (1, Some(None)));
3419        assert!(matches!(&arms[7].pattern, Pattern::Variant { bindings, .. }
3420            if matches!(bindings[0].pattern(), Pattern::List { .. })));
3421        // Only `[..]` and `[..rest]` match every list.
3422        assert!(!arms[0].pattern.is_irrefutable());
3423        assert!(!arms[2].pattern.is_irrefutable());
3424        assert!(arms[4].pattern.is_irrefutable());
3425        assert!(arms[5].pattern.is_irrefutable());
3426    }
3427
3428    #[test]
3429    fn list_pattern_after_is_closes_at_the_bracket() {
3430        for body in [
3431            "if xs is [_, ..] { 1 } else { 2 }",
3432            "if xs is [] { 1 } else { 2 }",
3433            "if xs is [a, ..rest] { 1 } else { 2 }",
3434            "if xs is [S { n: 1, .. }, ..] { 1 } else { 2 }",
3435            "if xs is [] | [_] { 1 } else { 2 }",
3436        ] {
3437            let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3438            parse_str(&src).unwrap_or_else(|e| panic!("{body:?}: {e:?}"));
3439        }
3440    }
3441
3442    #[test]
3443    fn list_rest_must_be_last() {
3444        for body in [
3445            "match xs { [.., last] => 1 }",
3446            "match xs { [..r, last] => 1 }",
3447            "match xs { [.., ..] => 1 }",
3448            "match xs { [a, .., b, c] => 1 }",
3449        ] {
3450            let errs = body_err(body);
3451            assert_eq!(errs[0].category, "bynk.parse.list_rest_not_last", "{body}");
3452            assert!(
3453                errs[0].suggestions.is_empty(),
3454                "{body}: only trailing wildcards earn a fix"
3455            );
3456        }
3457    }
3458
3459    #[test]
3460    fn list_rest_followed_by_wildcards_has_a_fix() {
3461        for (body, fixed) in [
3462            ("match xs { [.., _] => 1 }", "match xs { [_, ..] => 1 }"),
3463            (
3464                "match xs { [a, .., _, _] => 1 }",
3465                "match xs { [a, _, _, ..] => 1 }",
3466            ),
3467        ] {
3468            let errs = body_err(body);
3469            assert_eq!(errs[0].category, "bynk.parse.list_rest_not_last");
3470            let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3471            let got = apply_fix(&src, &errs[0]);
3472            assert!(got.contains(fixed), "{body}: fixed to {got:?}");
3473            parse_str(&got).unwrap_or_else(|e| panic!("{body:?} fixed to {got:?}: {e:?}"));
3474        }
3475    }
3476
3477    #[test]
3478    fn list_rest_followed_by_an_integer_is_a_range_element() {
3479        // #2699 retired slice 4's reservation: `..` then an integer is a range.
3480        for body in [
3481            "match xs { [..9] => 1 _ => 0 }",
3482            "match xs { [a, ..-1] => 1 _ => 0 }",
3483            "match xs { [0..9, ..rest] => 1 _ => 0 }",
3484            "match xs { [18.., ..] => 1 _ => 0 }",
3485        ] {
3486            let ExprKind::Match { arms, .. } = body_tail(body) else {
3487                panic!("expected Match: {body}");
3488            };
3489            let Pattern::List { elems, .. } = &arms[0].pattern else {
3490                panic!("expected a list pattern: {body}");
3491            };
3492            assert!(
3493                elems.iter().any(|e| matches!(e, Pattern::Range(_))),
3494                "{body}"
3495            );
3496        }
3497        // A string or boolean after `..` is still no form.
3498        for body in ["match xs { [..\"a\"] => 1 }", "match xs { [..true] => 1 }"] {
3499            let errs = body_err(body);
3500            assert_eq!(errs[0].category, "bynk.parse.expected_token", "{body}");
3501        }
3502        // And `.._` is not a form.
3503        let errs = body_err("match xs { [a, .._] => 1 }");
3504        assert_eq!(errs[0].category, "bynk.parse.expected_token");
3505    }
3506
3507    #[test]
3508    fn int_range_patterns_parse_in_every_form() {
3509        let range = |body: &str| {
3510            let ExprKind::Match { arms, .. } = body_tail(body) else {
3511                panic!("expected Match: {body}");
3512            };
3513            match &arms[0].pattern {
3514                Pattern::Range(r) => (r.lo, r.hi),
3515                other => panic!("expected a range: {body}: {other:?}"),
3516            }
3517        };
3518        assert_eq!(range("match n { 0..12 => 1 _ => 0 }"), (Some(0), Some(12)));
3519        assert_eq!(range("match n { 18.. => 1 _ => 0 }"), (Some(18), None));
3520        assert_eq!(range("match n { ..-1 => 1 _ => 0 }"), (None, Some(-1)));
3521        assert_eq!(
3522            range("match n { -5..-1 => 1 _ => 0 }"),
3523            (Some(-5), Some(-1))
3524        );
3525        assert_eq!(
3526            range("match n { 1_000..2_000 => 1 _ => 0 }"),
3527            (Some(1000), Some(2000))
3528        );
3529        // An open range ends its arm: the next arm's literal is not its bound.
3530        let ExprKind::Match { arms, .. } = body_tail("match n { 18.. => 1 5 => 2 _ => 0 }") else {
3531            panic!("expected Match");
3532        };
3533        assert!(matches!(arms[0].pattern, Pattern::Range(_)));
3534        assert!(matches!(arms[1].pattern, Pattern::Literal { .. }));
3535    }
3536
3537    #[test]
3538    fn a_range_is_not_an_event_pattern_value() {
3539        // Only `via schema(...)` takes a range; a payload field's value does not.
3540        let src = "service S from Events(E { n: 1..5 }) { }";
3541        assert!(parse_str(src).is_err());
3542    }
3543
3544    #[test]
3545    fn record_pattern_parses_in_a_match_arm_and_nested() {
3546        let ExprKind::Match { arms, .. } = body_tail(
3547            "match o { Order { status: Paid, total, .. } => 1 Some(Order { .. }) => 2 _ => 3 }",
3548        ) else {
3549            panic!("expected Match");
3550        };
3551        let Pattern::Record {
3552            type_name, fields, ..
3553        } = &arms[0].pattern
3554        else {
3555            panic!("expected a record pattern, got {:?}", arms[0].pattern);
3556        };
3557        assert_eq!(type_name.name, "Order");
3558        assert_eq!(fields.len(), 2);
3559        assert!(fields[0].1.is_some(), "`status: Paid` has a sub-pattern");
3560        assert!(fields[1].1.is_none(), "`total` is shorthand");
3561        let Pattern::Variant { bindings, .. } = &arms[1].pattern else {
3562            panic!("expected Some(..)");
3563        };
3564        assert!(matches!(bindings[0].pattern(), Pattern::Record { .. }));
3565    }
3566
3567    #[test]
3568    fn record_pattern_without_rest_is_an_error_with_a_fix() {
3569        for body in [
3570            "match o { Order { total } => 1 }",
3571            "match o { Order { total, } => 1 }",
3572            "match o { Order { status: Paid, total } => 1 }",
3573            "match o { Order { } => 1 }",
3574        ] {
3575            let errs = body_err(body);
3576            assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
3577            let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3578            let fixed = apply_fix(&src, &errs[0]);
3579            parse_str(&fixed).unwrap_or_else(|e| panic!("{body:?} fixed to {fixed:?}: {e:?}"));
3580        }
3581    }
3582
3583    #[test]
3584    fn record_pattern_after_is_must_be_parenthesised() {
3585        for body in [
3586            "if o is Order { status: Paid, .. } { 1 } else { 2 }",
3587            "if o is None | Order { .. } { 1 } else { 2 }",
3588        ] {
3589            let errs = body_err(body);
3590            assert_eq!(
3591                errs[0].category,
3592                "bynk.parse.record_pattern_in_is_unparenthesised"
3593            );
3594            let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3595            if body.contains("None |") {
3596                continue; // the fix wraps only the record alternative
3597            }
3598            let fixed = apply_fix(&src, &errs[0]);
3599            parse_str(&fixed).unwrap_or_else(|e| panic!("{body:?} fixed to {fixed:?}: {e:?}"));
3600        }
3601        // Parenthesised, nested, and a unit variant before the block all parse.
3602        for body in [
3603            "if o is (Order { status: Paid, .. }) { 1 } else { 2 }",
3604            "if o is Some(Order { .. }) { 1 } else { 2 }",
3605            "if o is (None | Order { .. }) { 1 } else { 2 }",
3606            "if o is Paid { 1 } else { 2 }",
3607        ] {
3608            body_tail(body);
3609        }
3610    }
3611
3612    #[test]
3613    fn if_condition_ending_in_ident_does_not_swallow_a_single_ident_branch() {
3614        // #636: `ready { result }` shares its shape with a shorthand-field
3615        // record construction. In condition position the branch must win.
3616        for src in [
3617            "if ready { result } else { fallback }",
3618            "if ready { fallback } else { result }",
3619            "if !ready { result } else { fallback }",
3620            "if a == b { result } else { fallback }",
3621            "if a && b { result } else { fallback }",
3622        ] {
3623            let ExprKind::If {
3624                then_block,
3625                else_block,
3626                ..
3627            } = body_tail(src)
3628            else {
3629                panic!("expected If for {src:?}, got {:?}", body_tail(src));
3630            };
3631            // Both branches carry a bare-identifier tail — proof the `{ … }`
3632            // was read as a block, not consumed as a record by the condition.
3633            assert!(
3634                matches!(&then_block.tail.kind, ExprKind::Ident(_)),
3635                "then-branch tail not an ident for {src:?}: {:?}",
3636                then_block.tail.kind,
3637            );
3638            assert!(
3639                matches!(&else_block.tail.kind, ExprKind::Ident(_)),
3640                "else-branch tail not an ident for {src:?}: {:?}",
3641                else_block.tail.kind,
3642            );
3643        }
3644    }
3645
3646    #[test]
3647    fn else_less_if_with_single_ident_branch_parses() {
3648        // The no-`else` reproduction: previously errored `found `}``.
3649        let ExprKind::If { then_block, .. } = body_tail("if ready { result }") else {
3650            panic!("expected If");
3651        };
3652        assert!(matches!(&then_block.tail.kind, ExprKind::Ident(_)));
3653    }
3654
3655    #[test]
3656    fn record_construction_still_parses_in_value_position() {
3657        // The restriction is confined to condition spines — an ordinary value
3658        // position still constructs records, including the shorthand tail form.
3659        assert!(matches!(
3660            body_tail("Point { x }"),
3661            ExprKind::RecordConstruction { .. }
3662        ));
3663        assert!(matches!(
3664            body_tail("Point { x: 1, y: 2 }"),
3665            ExprKind::RecordConstruction { .. }
3666        ));
3667        assert!(matches!(
3668            body_tail("Empty {}"),
3669            ExprKind::RecordConstruction { .. }
3670        ));
3671    }
3672
3673    #[test]
3674    fn parenthesised_record_is_allowed_in_condition_head() {
3675        // A delimiter lifts the restriction: `(ready { result })` constructs a
3676        // record even in condition position (mirrors Rust's paren escape).
3677        let ExprKind::If { cond, .. } =
3678            body_tail("if (ready { result }) { branch } else { other }")
3679        else {
3680            panic!("expected If");
3681        };
3682        let ExprKind::Paren(inner) = &cond.kind else {
3683            panic!("expected a parenthesised condition, got {:?}", cond.kind);
3684        };
3685        assert!(
3686            matches!(&inner.kind, ExprKind::RecordConstruction { .. }),
3687            "parenthesised record in condition head should still construct: {:?}",
3688            inner.kind,
3689        );
3690    }
3691
3692    #[test]
3693    fn record_in_call_arg_within_condition_still_constructs() {
3694        // The restriction is lifted through a call-argument delimiter, so a
3695        // record literal passed to a predicate in the condition still parses.
3696        let ExprKind::If { cond, .. } = body_tail("if check(Point { x: 1 }) { a } else { b }")
3697        else {
3698            panic!("expected If");
3699        };
3700        let ExprKind::Call { args, .. } = &cond.kind else {
3701            panic!("expected Call in condition, got {:?}", cond.kind);
3702        };
3703        assert!(matches!(&args[0].kind, ExprKind::RecordConstruction { .. }));
3704    }
3705
3706    #[test]
3707    fn safe_condition_shapes_are_unaffected() {
3708        // Cases the issue lists as already-safe must stay safe.
3709        assert!(matches!(
3710            body_tail("if ready == true { result } else { fallback }"),
3711            ExprKind::If { .. }
3712        ));
3713        assert!(matches!(
3714            body_tail("if (ready) { result } else { fallback }"),
3715            ExprKind::If { .. }
3716        ));
3717        assert!(matches!(
3718            body_tail("if ready { \"a\" } else { \"b\" }"),
3719            ExprKind::If { .. }
3720        ));
3721    }
3722
3723    fn body_block(body: &str) -> Block {
3724        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3725        let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3726        let CommonsItem::Fn(f) = &c.items[0] else {
3727            panic!("expected fn, got {:?}", c.items[0]);
3728        };
3729        f.body.clone()
3730    }
3731
3732    fn has_error(errs: &[CompileError], code: &str) -> bool {
3733        errs.iter().any(|e| e.category == code)
3734    }
3735
3736    // ---- #2712: record patterns as lambda parameters ----
3737
3738    fn lambda_of(body: &str) -> LambdaExpr {
3739        let b = body_block(body);
3740        let ExprKind::Lambda(l) = &b.tail.kind else {
3741            panic!("expected a lambda tail, got {:?}", b.tail.kind);
3742        };
3743        l.clone()
3744    }
3745
3746    #[test]
3747    fn a_record_pattern_parameter_desugars_to_a_hidden_binder_and_a_let() {
3748        // `(P) => body` is `(__lambdaArg) => { let P = __lambdaArg; body }`.
3749        let l = lambda_of("(Item { qty, .. }) => qty");
3750        assert_eq!(l.params.len(), 1);
3751        let p = &l.params[0];
3752        assert!(p.name.name.starts_with(LAMBDA_ARG_BINDER_PREFIX));
3753        assert!(is_generated_binding(&p.name.name));
3754        assert_eq!(
3755            p.name.span.start, p.name.span.end,
3756            "the binder has no extent"
3757        );
3758        assert!(p.type_ref.is_none());
3759        assert!(matches!(p.pattern, Some(Pattern::Record { .. })));
3760        assert!(!l.block_body);
3761        let ExprKind::Block(b) = &l.body.kind else {
3762            panic!("expected a block body, got {:?}", l.body.kind);
3763        };
3764        let Statement::Let(hidden) = &b.statements[0] else {
3765            panic!("expected the hidden `let`, got {:?}", b.statements[0]);
3766        };
3767        assert_eq!(
3768            hidden.let_else.as_ref().map(|le| le.form),
3769            Some(LetElseForm::Plain)
3770        );
3771        assert!(b.tail.is_let_else_match());
3772        assert!(
3773            matches!(&hidden.value.kind, ExprKind::Ident(i) if i.name == p.name.name),
3774            "the `let` destructures the hidden parameter"
3775        );
3776    }
3777
3778    #[test]
3779    fn name_and_pattern_parameters_mix_and_each_binder_is_distinct() {
3780        let l = lambda_of("(a, Item { qty, .. }, b: Int, Box { v, .. }) => a");
3781        let names: Vec<_> = l.params.iter().map(|p| p.name.name.as_str()).collect();
3782        assert_eq!(names[0], "a");
3783        assert_eq!(names[2], "b");
3784        assert!(names[1].starts_with(LAMBDA_ARG_BINDER_PREFIX));
3785        assert!(names[3].starts_with(LAMBDA_ARG_BINDER_PREFIX));
3786        assert_ne!(names[1], names[3]);
3787        assert!(l.params[0].pattern.is_none() && l.params[2].type_ref.is_some());
3788        // The first pattern's `let` is outermost, the second's inside its arm.
3789        let ExprKind::Block(outer) = &l.body.kind else {
3790            panic!("expected a block body");
3791        };
3792        let ExprKind::Match { arms, .. } = &outer.tail.kind else {
3793            panic!("expected the first pattern's match");
3794        };
3795        let MatchBody::Block(inner) = &arms[0].body else {
3796            panic!("expected the arm's block");
3797        };
3798        assert!(inner.tail.is_let_else_match(), "the second pattern nests");
3799    }
3800
3801    #[test]
3802    fn a_block_body_is_kept_as_the_pattern_arms_block() {
3803        let l = lambda_of("(Item { qty, .. }) => { let x = qty\n  x }");
3804        assert!(l.block_body);
3805    }
3806
3807    #[test]
3808    fn a_lambda_without_pattern_parameters_is_unchanged() {
3809        let l = lambda_of("(a, b: Int) => a");
3810        assert!(l.params.iter().all(|p| p.pattern.is_none()));
3811        assert!(matches!(l.body.kind, ExprKind::Ident(_)));
3812    }
3813
3814    #[test]
3815    fn a_lambda_pattern_parameter_that_is_refutable_names_its_first_failing_field() {
3816        let errs = body_err("(Item { status: Paid, qty, .. }) => qty");
3817        assert_eq!(errs[0].category, "bynk.parse.lambda_pattern_refutable");
3818        assert!(
3819            errs[0].notes.iter().any(|n| n.contains("status: Paid")),
3820            "{:?}",
3821            errs[0].notes
3822        );
3823    }
3824
3825    #[test]
3826    fn a_lambda_pattern_parameter_must_be_a_record_pattern() {
3827        for body in [
3828            "(Some(x)) => x",
3829            "(a, [x, ..]) => x",
3830            "(0..9) => 1",
3831            "(1) => 1",
3832            "(None) => 1",
3833            "(Status.Paid) => 1",
3834        ] {
3835            let errs = body_err(body);
3836            assert_eq!(
3837                errs[0].category, "bynk.parse.lambda_pattern_not_record",
3838                "{body}"
3839            );
3840        }
3841    }
3842
3843    #[test]
3844    fn an_annotated_lambda_pattern_parameter_offers_to_remove_the_annotation() {
3845        let body = "(Item { qty, .. }: Item) => qty";
3846        let errs = body_err(body);
3847        assert_eq!(errs[0].category, "bynk.parse.lambda_pattern_annotation");
3848        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3849        let fixed = apply_fix(&src, &errs[0]);
3850        assert!(fixed.contains("(Item { qty, .. }) => qty"), "{fixed}");
3851        parse_str(&fixed).unwrap_or_else(|e| panic!("fixed to {fixed:?}: {e:?}"));
3852    }
3853
3854    #[test]
3855    fn a_missing_rest_in_a_lambda_pattern_parameter_has_slice_ones_fix() {
3856        let body = "(a, Item { qty }) => qty";
3857        let errs = body_err(body);
3858        assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
3859        let src = format!("commons x\n\nfn f() -> Int {{\n  {body}\n}}\n");
3860        let fixed = apply_fix(&src, &errs[0]);
3861        parse_str(&fixed).unwrap_or_else(|e| panic!("fixed to {fixed:?}: {e:?}"));
3862    }
3863
3864    #[test]
3865    fn let_else_desugars_to_a_hidden_binding_and_a_match() {
3866        // #2010: `let P = e else E; rest` is `let __v = e` then
3867        // `match __v { P => { rest }, _ => E }`.
3868        let b = body_block("let x = 1\n  let Some(n) = find(x) else { 0 }\n  n + x");
3869        assert_eq!(
3870            b.statements.len(),
3871            2,
3872            "the plain let and the hidden binding"
3873        );
3874        let Statement::Let(hidden) = &b.statements[1] else {
3875            panic!("expected a pure hidden binding, got {:?}", b.statements[1]);
3876        };
3877        assert!(
3878            is_generated_binding(&hidden.name.name),
3879            "{}",
3880            hidden.name.name
3881        );
3882        assert_eq!(
3883            hidden.name.span.start, hidden.name.span.end,
3884            "the binder has no extent"
3885        );
3886        let le = hidden
3887            .let_else
3888            .as_ref()
3889            .expect("the binding records the sugar");
3890        assert_eq!(le.form, LetElseForm::Block);
3891        let ExprKind::Match { discriminant, arms } = &b.tail.kind else {
3892            panic!("expected a match tail, got {:?}", b.tail.kind);
3893        };
3894        assert!(matches!(&discriminant.kind, ExprKind::Ident(i) if i.name == hidden.name.name));
3895        assert_eq!(arms.len(), 2);
3896        assert!(matches!(arms[0].pattern, Pattern::Variant { .. }));
3897        let MatchBody::Block(rest) = &arms[0].body else {
3898            panic!("the pattern's arm runs the rest of the block");
3899        };
3900        assert!(rest.statements.is_empty());
3901        assert!(
3902            !matches!(rest.tail.kind, ExprKind::UnitLit),
3903            "{:?}",
3904            rest.tail.kind
3905        );
3906        assert!(matches!(arms[1].pattern, Pattern::Wildcard(_)));
3907    }
3908
3909    /// #2640: `par { … }` parses to a `Par` holding its statements in order.
3910    #[test]
3911    fn par_block_holds_its_statements_in_source_order() {
3912        let b = body_block(
3913            "par {\n    let a <- one()\n    do two()\n    let b: Int <- three()\n  }\n  a",
3914        );
3915        let Statement::Par(p) = &b.statements[0] else {
3916            panic!("expected a par block, got {:?}", b.statements[0]);
3917        };
3918        assert_eq!(p.statements.len(), 3);
3919        assert!(matches!(&p.statements[0], Statement::EffectLet(l) if l.name.name == "a"));
3920        assert!(matches!(&p.statements[1], Statement::Do(_)));
3921        assert!(
3922            matches!(&p.statements[2], Statement::EffectLet(l) if l.name.name == "b" && l.type_annot.is_some())
3923        );
3924    }
3925
3926    /// #2640: `par` is contextual — an identifier everywhere but before `{`.
3927    #[test]
3928    fn par_is_an_identifier_outside_its_statement_shape() {
3929        let b = body_block("let par = 1\n  let x = par + 1\n  x");
3930        assert_eq!(b.statements.len(), 2);
3931        assert!(matches!(&b.statements[0], Statement::Let(l) if l.name.name == "par"));
3932    }
3933
3934    /// #2640: the parser admits any statement in a block (the checker names the
3935    /// forbidden ones), except those it cannot hold at all.
3936    #[test]
3937    fn par_block_admits_statements_for_the_checker_to_refuse() {
3938        let b = body_block(
3939            "par {\n    let a = 1\n    do notify().detach()\n    par {\n      do x()\n    }\n  }\n  1",
3940        );
3941        let Statement::Par(p) = &b.statements[0] else {
3942            panic!("expected a par block");
3943        };
3944        assert!(matches!(&p.statements[0], Statement::Let(_)));
3945        assert!(matches!(&p.statements[1], Statement::Do(_)));
3946        assert!(matches!(&p.statements[2], Statement::Par(_)));
3947    }
3948
3949    #[test]
3950    fn par_block_refuses_a_refutable_let_and_a_stray_expression() {
3951        assert!(has_error(
3952            &body_err("par {\n    let Ok(v) <- load() else { 0 }\n  }\n  1"),
3953            "bynk.par.invalid_statement"
3954        ));
3955        assert!(has_error(
3956            &body_err("par {\n    load()\n  }\n  1"),
3957            "bynk.par.invalid_statement"
3958        ));
3959    }
3960
3961    #[test]
3962    fn effectful_let_else_binds_with_an_arrow() {
3963        let b = body_block("let Ok(v) <- load() else { Effect.pure(0) }\n  v");
3964        assert!(matches!(&b.statements[0], Statement::EffectLet(l) if l.let_else.is_some()));
3965    }
3966
3967    #[test]
3968    fn let_else_chain_nests_each_step_in_the_previous_arm() {
3969        // Three steps in one flat block: each later step lives in the earlier
3970        // one's pattern arm, and the plain `let` between them stays in order.
3971        let b = body_block(
3972            "let Ok(a) = one() else { 1 }\n  let y = a\n  let Ok(b) = two(y) else { 2 }\n  let Ok(c) = three(b) else { 3 }\n  c",
3973        );
3974        let ExprKind::Match { arms, .. } = &b.tail.kind else {
3975            panic!("expected a match tail");
3976        };
3977        let MatchBody::Block(second) = &arms[0].body else {
3978            panic!("expected a block arm");
3979        };
3980        assert_eq!(
3981            second.statements.len(),
3982            2,
3983            "`let y` and the second hidden binding"
3984        );
3985        assert!(matches!(&second.statements[0], Statement::Let(l) if l.name.name == "y"));
3986        let ExprKind::Match { arms, .. } = &second.tail.kind else {
3987            panic!("expected the second step's match");
3988        };
3989        let MatchBody::Block(third) = &arms[0].body else {
3990            panic!("expected a block arm");
3991        };
3992        let ExprKind::Match { arms, .. } = &third.tail.kind else {
3993            panic!("expected the third step's match");
3994        };
3995        let MatchBody::Block(last) = &arms[0].body else {
3996            panic!("expected a block arm");
3997        };
3998        assert!(matches!(&last.tail.kind, ExprKind::Ident(i) if i.name == "c"));
3999    }
4000
4001    #[test]
4002    fn else_match_arms_follow_the_patterns_arm() {
4003        let b = body_block("let Ok(v) = r else match { Err(e) => 0 }\n  v");
4004        let Statement::Let(l) = &b.statements[0] else {
4005            panic!("expected the hidden binding");
4006        };
4007        assert_eq!(l.let_else.as_ref().unwrap().form, LetElseForm::Match);
4008        let ExprKind::Match { arms, .. } = &b.tail.kind else {
4009            panic!("expected a match tail");
4010        };
4011        assert_eq!(arms.len(), 2);
4012        assert!(
4013            matches!(&arms[1].pattern, Pattern::Variant { variant, .. } if variant.name == "Err")
4014        );
4015    }
4016
4017    #[test]
4018    fn an_irrefutable_record_let_needs_no_else() {
4019        // #2654: `let T { .. } = e` is the one-arm `match` of a `let … else`
4020        // with no `else` arm, marked `LetElseForm::Plain`.
4021        for body in [
4022            "let Item { sku, qty: n, .. } = item\n  n",
4023            "let (Item { sku, .. }) = item\n  sku",
4024            "let Item { sku: _, inner: Inner { x, .. }, .. } <- load(1)\n  x",
4025            "let Item { sku, .. } <- load(1) by Admin(\"a\")\n  sku",
4026        ] {
4027            let b = body_block(body);
4028            let (Statement::Let(l) | Statement::EffectLet(l)) = &b.statements[0] else {
4029                panic!("{body:?}: expected the hidden binding");
4030            };
4031            let le = l.let_else.as_ref().expect("the binding records the sugar");
4032            assert_eq!(le.form, LetElseForm::Plain, "{body:?}");
4033            assert_eq!(le.else_span.start, le.else_span.end, "no `else` extent");
4034            let ExprKind::Match { arms, .. } = &b.tail.kind else {
4035                panic!("{body:?}: expected a match tail");
4036            };
4037            assert_eq!(arms.len(), 1, "{body:?}: only the pattern's arm");
4038            assert!(matches!(arms[0].pattern, Pattern::Record { .. }));
4039        }
4040    }
4041
4042    #[test]
4043    fn a_refutable_record_let_without_else_names_the_refutable_field() {
4044        for (body, field) in [
4045            (
4046                "let Order { status: Paid, total, .. } = o\n  total",
4047                "status: Paid",
4048            ),
4049            (
4050                "let Order { total, c: Cust { kind: Gold, .. }, .. } = o\n  total",
4051                "kind: Gold",
4052            ),
4053            ("let Order { id: 1, .. } <- load()\n  1", "id: 1"),
4054        ] {
4055            let errs = body_err(body);
4056            assert_eq!(errs[0].category, "bynk.parse.let_pattern_without_else");
4057            assert!(
4058                errs[0]
4059                    .notes
4060                    .iter()
4061                    .any(|n| n.contains(&format!("`{field}` can fail to match"))),
4062                "{body:?}: {:?}",
4063                errs[0].notes
4064            );
4065        }
4066        // Any other pattern without an `else` is refused as before, with no field named.
4067        for body in [
4068            "let Ok(n) = r\n  n",
4069            "let (Ok(n)) = r\n  n",
4070            "let Item { sku, .. } | Other = r\n  1",
4071        ] {
4072            let errs = body_err(body);
4073            assert_eq!(
4074                errs[0].category, "bynk.parse.let_pattern_without_else",
4075                "{body:?}"
4076            );
4077        }
4078    }
4079
4080    #[test]
4081    fn a_record_let_keeps_an_else_when_one_is_written() {
4082        let b = body_block("let Item { sku, .. } = item else { 0 }\n  1");
4083        let Statement::Let(l) = &b.statements[0] else {
4084            panic!("expected the hidden binding");
4085        };
4086        assert_eq!(l.let_else.as_ref().unwrap().form, LetElseForm::Block);
4087    }
4088
4089    #[test]
4090    fn a_capitalised_binding_is_not_a_record_pattern() {
4091        // `let Name = e` and `let Name: T = e` read `Name` as a binding, as before.
4092        for body in ["let Total = 1\n  Total", "let Total: Int = 1\n  Total"] {
4093            let b = body_block(body);
4094            let Statement::Let(l) = &b.statements[0] else {
4095                panic!("{body:?}: expected a plain let");
4096            };
4097            assert!(l.let_else.is_none(), "{body:?}");
4098        }
4099        // And `let Name {` is no longer an error at the brace: it opens a pattern.
4100        let errs = body_err("let Item { sku } = item\n  1");
4101        assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
4102    }
4103
4104    #[test]
4105    fn let_else_as_the_last_statement_leaves_a_unit_rest() {
4106        let b = body_block("let Some(n) = find(1) else { () }");
4107        let ExprKind::Match { arms, .. } = &b.tail.kind else {
4108            panic!("expected a match tail");
4109        };
4110        let MatchBody::Block(rest) = &arms[0].body else {
4111            panic!("expected a block arm");
4112        };
4113        assert!(rest.implicit_tail && rest.statements.is_empty());
4114    }
4115
4116    #[test]
4117    fn let_pattern_forms_are_recognised() {
4118        for src in [
4119            "let None = o else { 0 }\n  1",
4120            "let Status.Done = s else { 0 }\n  1",
4121            "let Shipped(at) = s else { 0 }\n  at",
4122            "let 0 = n else { 1 }\n  0",
4123            "let -1 = n else { 1 }\n  0",
4124            "let \"a\" = s else { 1 }\n  0",
4125            "let (Ok(x) | Err(x)) = r else { 1 }\n  x",
4126        ] {
4127            let b = body_block(src);
4128            assert!(
4129                matches!(&b.statements[0], Statement::Let(l) if l.let_else.is_some()),
4130                "{src:?} should parse as a let-else"
4131            );
4132        }
4133        // A bare name, even capitalised, is still a binding.
4134        let b = body_block("let Total = 1\n  Total");
4135        assert!(
4136            matches!(&b.statements[0], Statement::Let(l) if l.let_else.is_none() && l.name.name == "Total")
4137        );
4138    }
4139
4140    #[test]
4141    fn let_pattern_without_else_is_refused() {
4142        assert!(has_error(
4143            &body_err("let Ok(v) = r\n  v"),
4144            "bynk.parse.let_pattern_without_else"
4145        ));
4146        assert!(has_error(
4147            &body_err("let Ok(v) <- r()\n  v"),
4148            "bynk.parse.let_pattern_without_else"
4149        ));
4150    }
4151
4152    #[test]
4153    fn else_on_a_plain_binding_is_refused() {
4154        assert!(has_error(
4155            &body_err("let v = r else { 0 }\n  v"),
4156            "bynk.parse.let_else_on_binding"
4157        ));
4158        assert!(has_error(
4159            &body_err("let v <- r() else { 0 }\n  v"),
4160            "bynk.parse.let_else_on_binding"
4161        ));
4162    }
4163
4164    #[test]
4165    fn annotated_let_pattern_is_refused() {
4166        assert!(has_error(
4167            &body_err("let Ok(v): Int = r else { 0 }\n  v"),
4168            "bynk.parse.let_pattern_annotation"
4169        ));
4170    }
4171
4172    #[test]
4173    fn empty_else_match_is_refused() {
4174        assert!(has_error(
4175            &body_err("let Ok(v) = r else match { }\n  v"),
4176            "bynk.parse.empty_match"
4177        ));
4178    }
4179
4180    #[test]
4181    fn let_else_steps_count_against_the_nesting_budget() {
4182        // Each step nests the rest of the block one level deeper, exactly as
4183        // the hand-written `match` it stands for, so a very long chain is
4184        // refused with the nesting diagnostic rather than overflowing later.
4185        let chain = |n: usize| -> String {
4186            let steps: String = (0..n)
4187                .map(|i| format!("let Ok(v{i}) = step() else {{ {i} }}\n  "))
4188                .collect();
4189            format!("{steps}0")
4190        };
4191        body_block(&chain(40));
4192        let errs = body_err(&chain(400));
4193        assert!(
4194            errs.iter()
4195                .any(|e| e.category == "bynk.parse.nesting_too_deep"),
4196            "{errs:?}"
4197        );
4198    }
4199
4200    #[test]
4201    fn empty_match_reports_its_own_diagnostic() {
4202        // #636: `match result {}` once parsed `result {}` as an empty record,
4203        // masking `bynk.parse.empty_match`. The intended diagnostic is now
4204        // reachable.
4205        let errs = body_err("match result {}");
4206        assert!(
4207            errs.iter().any(|e| e.category == "bynk.parse.empty_match"),
4208            "expected empty_match; got {errs:?}",
4209        );
4210    }
4211
4212    #[test]
4213    fn match_discriminant_ending_in_ident_parses() {
4214        // A `match` over a bare-identifier discriminant reaches its arm list.
4215        assert!(matches!(
4216            body_tail("match ready { x => x }"),
4217            ExprKind::Match { .. }
4218        ));
4219    }
4220
4221    /// #981: an identifier statement immediately followed, on its own line, by
4222    /// a standalone `()` must stay two separate constructs — not merge into a
4223    /// zero-arg call. `status := Paid` / `()` is an Assign statement whose
4224    /// value is the bare identifier `Paid`, then a unit tail; it must never
4225    /// parse as a single `status := Paid()` (a call). The call-parens rule
4226    /// mirrors the v0.20b same-line `[` rule already applied to type
4227    /// arguments: a postfix opener that begins a new line does not continue
4228    /// the previous token.
4229    #[test]
4230    fn identifier_statement_followed_by_unit_tail_does_not_merge_into_a_call() {
4231        let src = "commons c\n\nfn f() -> Int {\n  status := Paid\n  ()\n}\n";
4232        let c = parse_str(src).unwrap_or_else(|e| panic!("parse failed: {e:?}"));
4233        let CommonsItem::Fn(f) = &c.items[0] else {
4234            panic!("expected fn, got {:?}", c.items[0]);
4235        };
4236        assert_eq!(
4237            f.body.statements.len(),
4238            1,
4239            "expected exactly one Assign statement, got {:?}",
4240            f.body.statements
4241        );
4242        let Statement::Assign(a) = &f.body.statements[0] else {
4243            panic!(
4244                "expected an Assign statement, got {:?}",
4245                f.body.statements[0]
4246            );
4247        };
4248        assert!(
4249            matches!(a.value.kind, ExprKind::Ident(_)),
4250            "assign value must stay the bare identifier `Paid`, got {:?}",
4251            a.value.kind
4252        );
4253        assert!(
4254            matches!(f.body.tail.kind, ExprKind::UnitLit),
4255            "the `()` must remain the block's own tail, got {:?}",
4256            f.body.tail.kind
4257        );
4258    }
4259
4260    /// #1858: a variant pattern's `(` must sit on the variant's line too. An
4261    /// `is` test ending in a nullary variant, above a `()` tail on its own
4262    /// line, is a pattern and a unit, not `Paid()`/`None()`: `fmt` writes that
4263    /// tail after a comment, and its reparse must not absorb it.
4264    #[test]
4265    fn variant_pattern_followed_by_unit_tail_does_not_take_it_as_bindings() {
4266        for (name, pat) in [("user variant", "Paid"), ("built-in variant", "None")] {
4267            let src = format!("commons c\n\nfn f() -> () {{\n  let b = r is {pat}\n  ()\n}}\n");
4268            let c = parse_str(&src).unwrap_or_else(|e| panic!("{name}: parse failed: {e:?}"));
4269            let CommonsItem::Fn(f) = &c.items[0] else {
4270                panic!("expected fn, got {:?}", c.items[0]);
4271            };
4272            let Statement::Let(l) = &f.body.statements[0] else {
4273                panic!("{name}: expected a Let, got {:?}", f.body.statements[0]);
4274            };
4275            let ExprKind::Is { pattern, .. } = &l.value.kind else {
4276                panic!("{name}: expected an `is` test, got {:?}", l.value.kind);
4277            };
4278            let Pattern::Variant { variant, span, .. } = pattern.as_ref() else {
4279                panic!("{name}: expected a variant pattern, got {pattern:?}");
4280            };
4281            assert_eq!(
4282                span.end, variant.span.end,
4283                "{name}: the pattern must end at `{pat}`, not take the `()` below it"
4284            );
4285            assert!(
4286                matches!(f.body.tail.kind, ExprKind::UnitLit),
4287                "{name}: the `()` must remain the block's own tail, got {:?}",
4288                f.body.tail.kind
4289            );
4290        }
4291    }
4292
4293    /// #1858's boundary: a `(` on the variant's line still opens its payload
4294    /// list, and the list itself may span lines.
4295    #[test]
4296    fn variant_pattern_payload_on_the_same_line_still_binds() {
4297        for (name, pat) in [
4298            ("user variant", "Paid(\n    x\n  )"),
4299            ("built-in variant", "Some(x)"),
4300        ] {
4301            let src = format!("commons c\n\nfn f() -> Bool {{\n  r is {pat}\n}}\n");
4302            let c = parse_str(&src).unwrap_or_else(|e| panic!("{name}: parse failed: {e:?}"));
4303            let CommonsItem::Fn(f) = &c.items[0] else {
4304                panic!("expected fn, got {:?}", c.items[0]);
4305            };
4306            let ExprKind::Is { pattern, .. } = &f.body.tail.kind else {
4307                panic!("{name}: expected an `is` tail, got {:?}", f.body.tail.kind);
4308            };
4309            assert!(
4310                matches!(pattern.as_ref(), Pattern::Variant { bindings, .. } if bindings.len() == 1),
4311                "{name}: expected one binding, got {pattern:?}"
4312            );
4313        }
4314    }
4315
4316    /// #1858, chosen uniformly: a match arm's pattern is followed only by `if`
4317    /// or `=>`, so a next-line `(` there could not be the next statement, but
4318    /// the same-line rule holds in every pattern position anyway. One lexical
4319    /// rule, wherever a pattern appears, is the one a reader can apply without
4320    /// knowing the position. The arm is rejected, not misparsed.
4321    #[test]
4322    fn match_arm_pattern_payload_on_a_later_line_is_rejected() {
4323        let src = "commons c\n\nfn f() -> Int {\n  match m {\n    Settled\n      (amount) => 1,\n    _ => 0,\n  }\n}\n";
4324        assert!(
4325            parse_str(src).is_err(),
4326            "a next-line `(` after an arm's variant must not open its payload list"
4327        );
4328        let same_line = src.replace("Settled\n      (amount)", "Settled(amount)");
4329        parse_str(&same_line).unwrap_or_else(|e| panic!("same-line form must parse: {e:?}"));
4330    }
4331
4332    /// #981: the same same-line rule extends to a method call's parens — a
4333    /// `.method` immediately followed, on its own line, by a standalone `()`
4334    /// must not merge into `.method()`.
4335    #[test]
4336    fn method_reference_followed_by_unit_tail_does_not_merge_into_a_call() {
4337        let src = "commons c\n\nfn f() -> Int {\n  let y = x.field\n  ()\n}\n";
4338        let c = parse_str(src).unwrap_or_else(|e| panic!("parse failed: {e:?}"));
4339        let CommonsItem::Fn(f) = &c.items[0] else {
4340            panic!("expected fn, got {:?}", c.items[0]);
4341        };
4342        let Statement::Let(l) = &f.body.statements[0] else {
4343            panic!("expected a Let statement, got {:?}", f.body.statements[0]);
4344        };
4345        assert!(
4346            matches!(l.value.kind, ExprKind::FieldAccess { .. }),
4347            "let value must stay a field access, got {:?}",
4348            l.value.kind
4349        );
4350        assert!(
4351            matches!(f.body.tail.kind, ExprKind::UnitLit),
4352            "the `()` must remain the block's own tail, got {:?}",
4353            f.body.tail.kind
4354        );
4355    }
4356
4357    #[test]
4358    fn unparenthesised_record_in_condition_head_now_errors() {
4359        // #636 narrowing (matches Rust): a record literal in condition *head*
4360        // position must be parenthesised. Unparenthesised, `Point` reads as the
4361        // discriminant and `{ x: 1 }` as the arm list, whose first "arm" `x: 1`
4362        // is not an arm — so the parse fails. Pinned so the divergence from the
4363        // (still-accepting) tree-sitter grammar is deliberate, not a bug.
4364        assert!(
4365            !body_err("match Point { x: 1 } { p => p }").is_empty(),
4366            "unparenthesised record discriminant should not parse",
4367        );
4368        // Parenthesised, the record is the discriminant and the match parses.
4369        let ExprKind::Match { discriminant, .. } = body_tail("match (Point { x: 1 }) { p => p }")
4370        else {
4371            panic!("expected Match for the parenthesised form");
4372        };
4373        let ExprKind::Paren(inner) = &discriminant.kind else {
4374            panic!(
4375                "expected a parenthesised discriminant, got {:?}",
4376                discriminant.kind
4377            );
4378        };
4379        assert!(matches!(&inner.kind, ExprKind::RecordConstruction { .. }));
4380    }
4381
4382    /// The codes a strict multi-unit parse (the build's path) reports.
4383    fn strict_codes(src: &str) -> Vec<&'static str> {
4384        let toks = tokenize(src).unwrap();
4385        match parse_units_with_warnings(&toks, src) {
4386            Ok((_, warnings)) => warnings.iter().map(|e| e.category).collect(),
4387            Err(errs) => errs.iter().map(|e| e.category).collect(),
4388        }
4389    }
4390
4391    /// #1885 (DECISION B): a divider pair around a declaration, attached to
4392    /// the next one, swallowed `helper` silently. Every parse entry point now
4393    /// reports it.
4394    #[test]
4395    fn a_divider_pair_around_code_is_doc_block_contains_code() {
4396        let src =
4397            "commons m\n\n--------\nfn helper() -> Int { 1 }\n--------\nfn f() -> Int { 2 }\n";
4398        assert_eq!(strict_codes(src), ["bynk.parse.doc_block_contains_code"]);
4399        let errs = parse_str(src).unwrap_err();
4400        assert_eq!(errs[0].category, "bynk.parse.doc_block_contains_code");
4401        // The span is the whole doc block.
4402        assert_eq!(
4403            &src[errs[0].span.range()],
4404            "--------\nfn helper() -> Int { 1 }\n--------\n"
4405        );
4406        let (unit, errs) = parse_recover_str(src);
4407        assert!(unit.is_some(), "recovery keeps the unit");
4408        assert!(
4409            errs.iter()
4410                .any(|e| e.category == "bynk.parse.doc_block_contains_code"),
4411            "{errs:?}"
4412        );
4413    }
4414
4415    /// #3378: the divider the note recommends is itself valid source. It once
4416    /// suggested a `--` comment, which `bynk.lex.legacy_comment` refuses.
4417    #[test]
4418    fn the_divider_the_doc_block_note_suggests_parses() {
4419        let src =
4420            "commons m\n\n--------\nfn helper() -> Int { 1 }\n--------\nfn f() -> Int { 2 }\n";
4421        let errs = parse_str(src).unwrap_err();
4422        let note = &errs[0].notes[0];
4423        let divider = note
4424            .split('`')
4425            .nth(1)
4426            .expect("the note quotes a divider in backticks");
4427        let fixed = format!("commons m\n\n{divider}\nfn helper() -> Int {{ 1 }}\n");
4428        assert_eq!(strict_codes(&fixed), [] as [&str; 0], "{divider:?}");
4429    }
4430
4431    /// The orphan shape (a blank line before `fn f`) is the same error, beside
4432    /// the orphan warning; and so is a pair with nothing after it.
4433    #[test]
4434    fn an_orphaned_or_trailing_divider_pair_is_doc_block_contains_code() {
4435        let orphan = "commons m\n\n---\nfn helper() -> Int { 1 }\n---\n\nfn f() -> Int { 2 }\n";
4436        let codes = strict_codes(orphan);
4437        assert!(
4438            codes.contains(&"bynk.parse.doc_block_contains_code"),
4439            "{codes:?}"
4440        );
4441        let trailing = "commons m\n\nfn f() -> Int { 2 }\n\n---\ntype Id = Int\n---\n";
4442        let codes = strict_codes(trailing);
4443        assert!(
4444            codes.contains(&"bynk.parse.doc_block_contains_code"),
4445            "{codes:?}"
4446        );
4447    }
4448
4449    /// Prose that only starts like a declaration, a doc whose code sits in a
4450    /// Markdown fence, and a doc that holds only a nested doc example are all
4451    /// documentation.
4452    #[test]
4453    fn near_miss_prose_and_fenced_code_are_not_code() {
4454        for doc in [
4455            "type of the thing",
4456            "fn is used here",
4457            "The type Id is an Int.",
4458            "uses the clock",
4459            "Event handler.\nfn helper() -> Int { 1 }",
4460            "Example:\n```bynk\nfn helper() -> Int { 1 }\n```",
4461            "~~~~\ntype Id = Int\n~~~~",
4462            "---\nA nested doc.\n---",
4463            "",
4464        ] {
4465            assert!(!doc_content_is_code(doc), "{doc:?} read as code");
4466        }
4467        for doc in [
4468            "fn helper() -> Int { 1 }",
4469            "type Id = Int\nfn f() -> Int { 1 }",
4470            "```\nan example\n```\nfn helper() -> Int { 1 }",
4471            "---\nA nested doc.\n---\nfn helper() -> Int { 1 }",
4472        ] {
4473            assert!(doc_content_is_code(doc), "{doc:?} not read as code");
4474        }
4475    }
4476
4477    /// #1894 review: code one level down, inside a nested doc block, or
4478    /// beside a lone `---` rule that keeps the content from lexing, is still
4479    /// code; prose at either level is not.
4480    #[test]
4481    fn code_inside_a_nested_doc_or_beside_a_rule_is_code() {
4482        let nested =
4483            "commons m\n\n----\n---\nfn helper() -> Int { 1 }\n---\n----\nfn f() -> Int { 2 }\n";
4484        assert_eq!(strict_codes(nested), ["bynk.parse.doc_block_contains_code"]);
4485        let ruled = "commons m\n\n----\n---\nfn helper() -> Int { 1 }\n----\nfn f() -> Int { 2 }\n";
4486        assert_eq!(strict_codes(ruled), ["bynk.parse.doc_block_contains_code"]);
4487        // Two levels down.
4488        assert!(doc_content_is_code(
4489            "----\n---\nfn helper() -> Int { 1 }\n---\n----"
4490        ));
4491        for doc in [
4492            "---\nAn inner doc.\n---",
4493            "Intro.\n\n---\n\nfn is used here",
4494            "---\n```\nfn helper() -> Int { 1 }\n```\n---",
4495        ] {
4496            assert!(!doc_content_is_code(doc), "{doc:?} read as code");
4497        }
4498        // Deeper than the bound, the probe stops looking.
4499        let mut deep = "fn helper() -> Int { 1 }".to_string();
4500        for n in (3..3 + DOC_PROBE_MAX_DEPTH + 1).rev() {
4501            let fence = "-".repeat(n);
4502            deep = format!("{fence}\n{deep}\n{fence}");
4503        }
4504        assert!(!doc_content_is_code(&deep));
4505    }
4506
4507    /// A `----` doc holding a nested doc example in a code fence attaches to
4508    /// its declaration with no diagnostic.
4509    #[test]
4510    fn a_fenced_nested_doc_example_parses_clean() {
4511        let src = "commons m\n\n----\nShows a doc.\n\n```bynk\n---\nInner.\n---\nfn example() -> Int { 1 }\n```\n----\nfn f() -> Int { 2 }\n";
4512        assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4513        let c = parse_str(src).unwrap();
4514        let CommonsItem::Fn(f) = &c.items[0] else {
4515            panic!("expected fn")
4516        };
4517        assert!(
4518            f.documentation
4519                .as_deref()
4520                .is_some_and(|d| d.contains("---\nInner.\n---")),
4521            "{:?}",
4522            f.documentation
4523        );
4524    }
4525
4526    /// #2618: `private` before a declaration keyword is the modifier, its span
4527    /// recorded and folded into the declaration's; a doc above it still
4528    /// attaches. Elsewhere `private` is an ordinary identifier.
4529    #[test]
4530    fn private_modifier_is_contextual() {
4531        let src = "commons m\n\n--- Hidden.\nprivate type T = Int\n\nprivate fn T.get(self) -> Int { 1 }\n\nfn f(private: Int) -> Int { private }\n";
4532        let c = parse_str(src).unwrap();
4533        let t = type_at(&c, 0);
4534        let at = src.find("private type").unwrap();
4535        assert_eq!(t.private.map(|s| s.start), Some(at));
4536        assert_eq!(t.span.start, at);
4537        assert_eq!(doc_of(&t.documentation), Some(("Hidden.", DocForm::Lines)));
4538        assert!(c.items[1].is_private());
4539        assert!(!c.items[2].is_private());
4540    }
4541
4542    /// `private` before `const` is the modifier too, its span folded into the
4543    /// constant's.
4544    #[test]
4545    fn private_modifier_on_a_constant() {
4546        let src = "commons m\n\nprivate const Max: Int = 3\n\nconst Min: Int = 1\n";
4547        let c = parse_str(src).unwrap();
4548        let CommonsItem::Const(k) = &c.items[0] else {
4549            panic!("a constant");
4550        };
4551        assert_eq!(
4552            k.private.map(|s| s.start),
4553            Some(src.find("private").unwrap())
4554        );
4555        assert_eq!(k.span.start, src.find("private").unwrap());
4556        assert!(c.items[0].is_private());
4557        assert!(!c.items[1].is_private());
4558    }
4559
4560    /// #2618: `private` on a declaration it does not apply to is rejected.
4561    #[test]
4562    fn private_on_a_service_is_rejected() {
4563        let src =
4564            "context m\n\nprivate service s {\n  on call() -> Effect[Int] by Caller { 1 }\n}\n";
4565        let tokens = crate::lexer::tokenize(src).unwrap();
4566        let errs = parse_units(&tokens, src).unwrap_err();
4567        assert_eq!(errs[0].category, "bynk.visibility.private_not_allowed");
4568    }
4569
4570    /// The `TypeDecl` at `items[i]`.
4571    fn type_at(c: &Commons, i: usize) -> &TypeDecl {
4572        let CommonsItem::Type(t) = &c.items[i] else {
4573            panic!("expected a type at {i}")
4574        };
4575        t
4576    }
4577
4578    fn doc_of(d: &Option<Doc>) -> Option<(&str, DocForm)> {
4579        // An indented `---` block keeps a trailing newline (its closing
4580        // marker's indent survives the marker trim); it prints the same.
4581        d.as_ref().map(|d| (d.as_str().trim_end(), d.form))
4582    }
4583
4584    /// #2203 (DECISION C): a `--- text` line documents a declaration, with or
4585    /// without its closer.
4586    #[test]
4587    fn doc_lines_document_a_declaration() {
4588        let src = "commons m\n\n--- A commit SHA.\ntype Commit = String\n\n---- First. ----\nfn f() -> Int { 1 }\n";
4589        let c = parse_str(src).unwrap();
4590        assert_eq!(
4591            doc_of(&type_at(&c, 0).documentation),
4592            Some(("A commit SHA.", DocForm::Lines))
4593        );
4594        let CommonsItem::Fn(f) = &c.items[1] else {
4595            panic!("expected fn")
4596        };
4597        assert_eq!(doc_of(&f.documentation), Some(("First.", DocForm::Lines)));
4598        assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4599    }
4600
4601    /// #2203 (DECISION E): a legacy `--` comment and `--|` doc line still
4602    /// parse as a comment and a doc, and each is reported, all at once, with
4603    /// its fix; the formatter's migrating parse accepts them.
4604    #[test]
4605    fn legacy_spellings_parse_and_are_each_reported() {
4606        let src =
4607            "-- a header\ncommons m\n\n--| A run.\ntype Run = {\n  repo: String, -- trailing\n}\n";
4608        assert_eq!(
4609            strict_codes(src),
4610            [
4611                "bynk.lex.legacy_comment",
4612                "bynk.lex.legacy_doc_line",
4613                "bynk.lex.legacy_comment"
4614            ]
4615        );
4616        let tokens = tokenize(src).unwrap();
4617        let (units, _, _) = parse_units_migrating(&tokens, src).unwrap();
4618        let SourceUnit::Commons(c) = &units[0] else {
4619            panic!("commons")
4620        };
4621        assert_eq!(
4622            doc_of(&type_at(c, 0).documentation),
4623            Some(("A run.", DocForm::Lines))
4624        );
4625    }
4626
4627    /// #2203 (DECISION D): two one-line docs on one target is
4628    /// `bynk.parse.multiple_docs`, whose fix joins them into a block.
4629    #[test]
4630    fn consecutive_doc_lines_are_multiple_docs_with_a_block_fix() {
4631        let src = "commons m\n\ntype R = {\n  --- First.\n  --- Second.\n  a: Int,\n}\n";
4632        let tokens = tokenize(src).unwrap();
4633        let errs = parse_units(&tokens, src).unwrap_err();
4634        assert_eq!(errs.len(), 1, "{errs:?}");
4635        assert_eq!(errs[0].category, "bynk.parse.multiple_docs");
4636        let (span, block) = &errs[0].suggestions[0].edits[0];
4637        assert_eq!(&src[span.range()], "--- First.\n  --- Second.");
4638        assert_eq!(block, "---\n  First.\n  Second.\n  ---");
4639    }
4640
4641    /// #1888 (DECISION D): record fields, both sum forms' variants, payload
4642    /// fields and message entries take a doc in either form; a `//` comment
4643    /// above a field stays a comment.
4644    #[test]
4645    fn members_take_docs_in_either_form() {
4646        let src = "commons m\n\ntype Run = {\n  --- The repository.\n  repo: String,\n  ---\n  The version.\n  ---\n  version: String,\n  // a note\n  sha: String, // trailing\n}\n\ntype Outcome = enum {\n  --- Passed.\n  Pass,\n  Fail,\n}\n\ntype Shape =\n  --- Round.\n  | Circle(\n    --- The radius.\n    r: Int,\n  )\n  | Dot\n\n--- After the sum.\nfn f() -> Int { 1 }\n\nmessages \"en\" @reference {\n  --- Greets.\n  \"hi\" => \"Hello\"\n}\n";
4647        assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4648        let c = parse_str(src).unwrap();
4649        let TypeBody::Record(r) = &type_at(&c, 0).body else {
4650            panic!("record")
4651        };
4652        assert_eq!(
4653            doc_of(&r.fields[0].documentation),
4654            Some(("The repository.", DocForm::Lines))
4655        );
4656        assert_eq!(
4657            doc_of(&r.fields[1].documentation),
4658            Some(("The version.", DocForm::Block))
4659        );
4660        assert_eq!(r.fields[2].documentation, None);
4661        assert_eq!(
4662            r.fields[2].trivia.leading,
4663            vec![Comment::Line(" a note".into())]
4664        );
4665        assert_eq!(r.fields[2].trivia.trailing.as_deref(), Some(" trailing"));
4666        let TypeBody::Sum(e) = &type_at(&c, 1).body else {
4667            panic!("enum")
4668        };
4669        assert_eq!(
4670            doc_of(&e.variants[0].documentation),
4671            Some(("Passed.", DocForm::Lines))
4672        );
4673        assert_eq!(e.variants[1].documentation, None);
4674        let TypeBody::Sum(p) = &type_at(&c, 2).body else {
4675            panic!("sum")
4676        };
4677        assert_eq!(
4678            doc_of(&p.variants[0].documentation),
4679            Some(("Round.", DocForm::Lines))
4680        );
4681        assert_eq!(
4682            doc_of(&p.variants[0].payload[0].documentation),
4683            Some(("The radius.", DocForm::Lines))
4684        );
4685        assert_eq!(p.variants[1].documentation, None);
4686        // The doc after the last variant is the next declaration's.
4687        let CommonsItem::Fn(f) = &c.items[3] else {
4688            panic!("expected fn")
4689        };
4690        assert_eq!(
4691            doc_of(&f.documentation),
4692            Some(("After the sum.", DocForm::Lines))
4693        );
4694        let CommonsItem::Messages(m) = &c.items[4] else {
4695            panic!("expected messages")
4696        };
4697        assert_eq!(
4698            doc_of(&m.entries[0].documentation),
4699            Some(("Greets.", DocForm::Lines))
4700        );
4701    }
4702
4703    /// #2203 (DECISION D): two docs directly above one target, of either
4704    /// form or both, is `bynk.parse.multiple_docs`, on a declaration and on a
4705    /// member; the recovering parse keeps the unit.
4706    #[test]
4707    fn two_docs_on_one_target_is_multiple_docs() {
4708        for src in [
4709            "commons m\n\n---\nBlock.\n---\n--- Lines.\nfn f() -> Int { 1 }\n",
4710            "commons m\n\n--- Lines.\n---\nBlock.\n---\nfn f() -> Int { 1 }\n",
4711            "commons m\n\n---\nOne.\n---\n---\nTwo.\n---\nfn f() -> Int { 1 }\n",
4712            "commons m\n\n--- One.\n--- Two.\nfn f() -> Int { 1 }\n",
4713            "commons m\n\ntype R = {\n  --- Lines.\n  ---\n  Block.\n  ---\n  a: Int,\n}\n",
4714        ] {
4715            assert_eq!(strict_codes(src), ["bynk.parse.multiple_docs"], "{src}");
4716            let (unit, errs) = parse_recover_str(src);
4717            assert!(unit.is_some());
4718            assert!(
4719                errs.iter()
4720                    .any(|e| e.category == "bynk.parse.multiple_docs")
4721            );
4722        }
4723    }
4724
4725    /// #1888 review: a doc with only a payload's `)` after it is an orphan
4726    /// warning, and the variant still parses with its field.
4727    #[test]
4728    fn a_dangling_doc_before_a_payload_close_is_only_an_orphan() {
4729        let src =
4730            "commons m\n\ntype S =\n  | Circle(\n    r: Int,\n    --- dangling\n  )\n  | Dot\n";
4731        assert_eq!(strict_codes(src), ["bynk.parse.orphan_doc_block"]);
4732        let c = parse_str(src).unwrap();
4733        let TypeBody::Sum(s) = &type_at(&c, 0).body else {
4734            panic!("sum")
4735        };
4736        assert_eq!(s.variants[0].payload.len(), 1);
4737        assert_eq!(s.variants[0].payload[0].documentation, None);
4738    }
4739
4740    /// #1888: a member doc follows the declaration rules: a blank line
4741    /// orphans it (a warning, kept in place), as does the body's end.
4742    #[test]
4743    fn an_unattached_member_doc_is_an_orphan() {
4744        let src = "commons m\n\ntype R = {\n  --- Spaced.\n\n  a: Int,\n  --- Dangling.\n}\n";
4745        assert_eq!(
4746            strict_codes(src),
4747            ["bynk.parse.orphan_doc_block", "bynk.parse.orphan_doc_block"]
4748        );
4749        let c = parse_str(src).unwrap();
4750        let TypeBody::Record(r) = &type_at(&c, 0).body else {
4751            panic!("record")
4752        };
4753        assert_eq!(r.fields[0].documentation, None);
4754        assert!(matches!(
4755            &r.fields[0].trivia.leading[..],
4756            [Comment::OrphanDoc(d)] if d.as_str() == "Spaced." && d.form == DocForm::Lines
4757        ));
4758        assert!(matches!(
4759            &r.trailing_comments[..],
4760            [Comment::OrphanDoc(d)] if d.as_str() == "Dangling."
4761        ));
4762    }
4763}
4764
4765#[cfg(test)]
4766mod paren_guard_2721 {
4767    use super::*;
4768    use crate::lexer::tokenize;
4769
4770    fn ok(src: &str) {
4771        let toks = tokenize(src).unwrap();
4772        parse(&toks, src).unwrap_or_else(|e| panic!("{src}\n{e:?}"));
4773    }
4774
4775    fn wrap(guard: &str) -> String {
4776        format!(
4777            "commons t {{\n  fn f(n: Int, flag: Bool) -> Int {{\n    match n {{\n      n if {guard} => n,\n      _ => 0,\n    }}\n  }}\n}}\n"
4778        )
4779    }
4780
4781    #[test]
4782    fn parenthesised_guards_parse() {
4783        ok(&wrap("(flag)"));
4784        ok(&wrap("(n > 0 && flag)"));
4785        ok(&wrap("(n > 0) && flag"));
4786        ok(&wrap("!(flag)"));
4787        ok(&wrap("()"));
4788    }
4789
4790    #[test]
4791    fn lambda_still_parses_when_parenthesised_in_guard() {
4792        ok(&wrap("pred(((x: Int) => x > 0))"));
4793    }
4794}