bynk-syntax 0.508.4

The syntax foundation of the Bynk compiler: lexer, parser, AST, spans, the CompileError type, and the diagnostic-code registry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
//! Function-declaration, block, statement, parameter, and lambda parsing.
//! Split out of `parser.rs` (ADR 0060) as a further `impl Parser` block; the
//! scanning core and the other concerns stay in the parent module, reached
//! as ancestor privates via `self`.

use super::*;
use crate::error::Applicability;

impl<'a> Parser<'a> {
    // -- function declarations --

    pub(crate) fn parse_fn_decl(&mut self) -> Result<FnDecl, CompileError> {
        let kw = self.expect(TokenKind::Fn, "to start a function declaration")?;
        let first = self.expect_ident("after `fn`")?;
        // A method declaration uses `TypeName.methodName`; a free function
        // is just an identifier. Disambiguate on the next token.
        let name = if let Some(dot) = self.eat(TokenKind::Dot) {
            let method = self.expect_member_name("after `.` in a method declaration", dot.span)?;
            FnName::Method {
                type_name: first,
                method_name: method,
            }
        } else {
            FnName::Free(first)
        };
        // v0.20a: optional `[A, B]` type parameters, each optionally bounded
        // (`[A: Eq]`); the checker validates the constraint names.
        let type_params = self.parse_optional_type_params()?;
        self.expect(TokenKind::LParen, "after the function name")?;
        // For methods, the first parameter may be the special `self` keyword.
        let mut params = Vec::new();
        let mut has_self = false;
        if self.peek_kind() == Some(TokenKind::Self_) {
            let self_tok = self.bump().unwrap();
            if !matches!(name, FnName::Method { .. }) {
                return Err(CompileError::new(
                    "bynk.parse.self_outside_method",
                    self_tok.span,
                    "`self` can only appear as the first parameter of a method declaration",
                )
                .with_note(
                    "use `fn TypeName.method(self, ...)` to declare a method, \
                     or remove `self` for a free function",
                ));
            }
            has_self = true;
            // Allow a trailing comma after `self` for further params.
            if self.peek_kind() == Some(TokenKind::Comma) {
                self.bump();
                if self.peek_kind() != Some(TokenKind::RParen) {
                    params.push(self.parse_param()?);
                    while self.eat(TokenKind::Comma).is_some() {
                        params.push(self.parse_param()?);
                    }
                }
            }
        } else if self.peek_kind() != Some(TokenKind::RParen) {
            params.push(self.parse_param()?);
            while self.eat(TokenKind::Comma).is_some() {
                params.push(self.parse_param()?);
            }
        }
        self.expect(TokenKind::RParen, "to close the parameter list")?;
        self.expect(TokenKind::Arrow, "before the return type")?;
        let return_type = self.parse_type_ref("as the return type")?;
        // #2868: an optional `given C1, C2` follows the return type.
        let given = self.parse_given_clause()?;
        let where_bounds = self.parse_optional_where_bounds()?;
        // v0.115: contract clauses ride between the return type and the body —
        // any number of `requires <name>: <pred>` then `ensures <name>: <pred>`.
        // The two-list split is by keyword, not order; the checker enforces the
        // scoping difference (`result` bound only in `ensures`).
        let mut requires = Vec::new();
        let mut ensures = Vec::new();
        loop {
            match self.peek_kind() {
                Some(TokenKind::Requires) => requires.push(self.parse_contract_clause(true)?),
                Some(TokenKind::Ensures) => ensures.push(self.parse_contract_clause(false)?),
                _ => break,
            }
        }
        let body = self.parse_block("to open the function body")?;
        let span = kw.span.merge(body.span);
        Ok(FnDecl {
            type_params,
            name,
            params,
            return_type,
            given,
            where_bounds,
            requires,
            ensures,
            body,
            has_self,
            documentation: None,
            span,
            trivia: Trivia::default(),
            private: None,
        })
    }

    /// Parse a single contract clause (v0.115): `requires <name>: <pred>` or
    /// `ensures <name>: <pred>`. The predicate is an ordinary expression (with
    /// `implies`/`is`) over the parameters — and, for an `ensures`, the
    /// contextual `result` binding; well-formedness (purity, `Bool`, `result`
    /// scope) is the checker's job, mirroring [`parse_invariant`].
    fn parse_contract_clause(&mut self, is_requires: bool) -> Result<Contract, CompileError> {
        let kw = if is_requires {
            self.expect(TokenKind::Requires, "to start a precondition clause")?
        } else {
            self.expect(TokenKind::Ensures, "to start a postcondition clause")?
        };
        let word = if is_requires { "requires" } else { "ensures" };
        let name = self.expect_ident(&format!("as the clause name after `{word}`"))?;
        self.expect(TokenKind::Colon, "after the contract clause name")?;
        // #2703: a contract clause is always followed by the function body's
        // `{` (or another clause), so a bare name before it ends the predicate;
        // it is never the head of a record construction (`Limit { n }`). Parse
        // the predicate under the same no-record-literal rule as an `if`/`match`
        // condition; a record literal still works parenthesised.
        let predicate = self.parse_cond_expr()?;
        let span = kw.span.merge(predicate.span);
        Ok(Contract {
            name,
            predicate,
            span,
        })
    }

    /// Parse a brace-delimited block: `{ statement* expr }` (v0.1 §3.1, v0.5).
    pub(crate) fn parse_block(&mut self, ctx: &str) -> Result<Block, CompileError> {
        let open = self.expect(TokenKind::LBrace, ctx)?;
        self.parse_block_rest(open.span)
    }

    /// v0.118: the body of a block after the opening `{` has been consumed. A
    /// `case` body opens the brace itself, peels its leading `provides` clauses,
    /// then calls this to parse the statements and tail.
    pub(crate) fn parse_block_rest(&mut self, open: Span) -> Result<Block, CompileError> {
        self.parse_block_rest_in(open, false)
    }

    /// `in_case_body` is true only for a test case's own top-level body, where
    /// a late `stub`/`env` clause gets its targeted diagnostic (#2913).
    pub(crate) fn parse_block_rest_in(
        &mut self,
        open: Span,
        in_case_body: bool,
    ) -> Result<Block, CompileError> {
        // #2010: each `let … else` in the block counts one level against the
        // nesting budget, as the `match` it stands for would. They are counted
        // here and given back however the block ends, error included.
        let mut let_else_depth = 0usize;
        let result = self.parse_block_rest_counted(open, &mut let_else_depth, in_case_body);
        self.depth -= let_else_depth;
        result
    }

    fn parse_block_rest_counted(
        &mut self,
        open: Span,
        let_else_depth: &mut usize,
        in_case_body: bool,
    ) -> Result<Block, CompileError> {
        let mut statements = Vec::new();
        // #2010: the `let <pattern> … else …` statements in this block, each
        // with the number of ordinary statements that precede it. Each one
        // takes the rest of the block as its first `match` arm, so they are
        // folded in from the back once the tail is known. The fold is
        // iterative; the nesting budget is charged as each step is parsed.
        let mut let_elses: Vec<(usize, LetElseParts)> = Vec::new();
        // Loop: parse statements until we hit something that's not a statement.
        // v0.1: `let`. v0.5: `let ... <-` is also a statement.
        // v0.7: `assert` is a statement form inside test bodies.
        let tail_leading: Vec<Comment>;
        loop {
            let leading = self.take_leading_trivia();
            // v0.81: `name := expr` is a statement led by an identifier, so it is
            // detected by lookahead rather than a leading keyword.
            let is_statement = matches!(
                self.peek_kind(),
                Some(TokenKind::Let)
                    | Some(TokenKind::Expect)
                    | Some(TokenKind::TildeArrow)
                    | Some(TokenKind::Do)
            ) || self.assign_ahead()
                || self.advance_ahead()
                || self.par_ahead();
            if self.peek_kind() == Some(TokenKind::Let) && self.let_pattern_ahead() {
                self.enter_recursion("this chain of `let … else` steps")?;
                *let_else_depth += 1;
                let mut parts = self.parse_let_else()?;
                parts.leading = leading;
                parts.trailing = self.take_trailing_trivia();
                let_elses.push((statements.len(), parts));
                continue;
            }
            if is_statement {
                let mut stmt = self.parse_statement()?;
                let trailing = self.take_trailing_trivia();
                attach_trivia(&mut stmt, leading, trailing);
                statements.push(stmt);
            } else {
                // #2913: `stub`/`env` clauses lead a case body; one after a
                // statement would otherwise fall to "expected an expression".
                let first = match (statements.first(), let_elses.first()) {
                    (Some(s), Some((_, l))) if l.span.start < s.span().start => Some(l.span),
                    (Some(s), _) => Some(s.span()),
                    (None, Some((_, l))) => Some(l.span),
                    (None, None) => None,
                };
                if let Some(first) = first.filter(|_| in_case_body) {
                    let word = if self.peek_kind() == Some(TokenKind::Stub) {
                        Some("stub")
                    } else if self.at_env_clause() {
                        Some("env")
                    } else {
                        None
                    };
                    if let Some(word) = word {
                        let at = self.peek().unwrap().span;
                        return Err(CompileError::new(
                            "bynk.parse.clause_after_statement",
                            at,
                            format!("`{word}` clauses must come before a case's statements"),
                        )
                        .with_label(first, "the first statement")
                        .with_note(format!(
                            "move the `{word}` clause above the first statement of the case body"
                        )));
                    }
                }
                tail_leading = leading;
                break;
            }
        }
        // v0.7: a block whose last statement is an `assert` may close without an
        // explicit tail expression. v0.146 (ADR 0170): *any* block may — a block
        // that closes right after its statements (or an empty `{}`) carries a
        // synthesised `()` (unit) tail. Against an `Effect[()]` context the
        // tail-position auto-lift wraps it; against a valued context it is an
        // ordinary type mismatch. `implicit_tail` records the synthesis so the
        // formatter omits the `()` (Bynk has no statement terminator, so a
        // printed `()` would re-attach to the last statement on re-parse).
        let (tail, close, implicit_tail) = if self.peek_kind() == Some(TokenKind::RBrace) {
            let close = self.expect(TokenKind::RBrace, "to close the block")?;
            let tail = Expr {
                id: self.alloc_expr_id(),
                kind: ExprKind::UnitLit,
                span: close.span,
            };
            (tail, close.span, true)
        } else {
            let tail = self.parse_expr()?;
            self.check_staircase(&tail);
            // #2838: a block has no expression statements, so a `match` ends
            // it. A second `match` straight after is the common slip; say why
            // it cannot follow rather than only that a `}` was expected.
            if matches!(tail.kind, ExprKind::Match { .. })
                && self.peek_kind() == Some(TokenKind::Match)
            {
                let next = self.peek().unwrap().span;
                return Err(CompileError::new(
                    "bynk.parse.match_ends_block",
                    next,
                    "a `match` ends the block it is in, so another `match` cannot follow it",
                )
                .with_label(tail.span, "this `match` is the block's final value")
                .with_note(
                    "bind the first with `let _ = match …`, or flatten a chain of fallible \
                     steps with `let … else`",
                ));
            }
            let close = self.expect(TokenKind::RBrace, "to close the block")?;
            (tail, close.span, false)
        };
        let mut block = Block {
            statements,
            tail: Box::new(tail),
            span: open.merge(close),
            tail_leading_comments: tail_leading,
            implicit_tail,
        };
        // #2010: fold each `let … else`, innermost (last) first. The statements
        // after it, with the tail, become the block its pattern's arm runs.
        while let Some((at, parts)) = let_elses.pop() {
            let rest_statements = block.statements.split_off(at);
            let rest = Block {
                statements: rest_statements,
                tail: block.tail,
                // From the end of the `let … else` to the block's `}` (not
                // including it): the rest has no braces of its own.
                span: Span {
                    file: parts.span.file,
                    start: parts.span.end,
                    end: close.start,
                },
                tail_leading_comments: std::mem::take(&mut block.tail_leading_comments),
                implicit_tail: block.implicit_tail,
            };
            let (binding, tail) = self.desugar_let_else(parts, rest);
            block.statements.push(binding);
            block.tail = Box::new(tail);
            block.implicit_tail = false;
        }
        Ok(block)
    }

    /// #2010: whether the `let` at the cursor starts a pattern rather than a
    /// binding name. A pattern starts with `Ok`/`Err`/`Some`/`None`, a literal,
    /// `(`, a name followed by `(` or `.` (`Shipped(at)`, `Status.Pending`), or a
    /// capitalised name followed by `{` (`Item { sku, .. }`, #2654).
    /// A bare name stays a binding (`let None = …` is not a binding today
    /// either, since `None` is a keyword), so no existing program changes.
    fn let_pattern_ahead(&self) -> bool {
        let at = |k: usize| self.tokens.get(self.pos + k).map(|t| t.kind);
        match at(1) {
            Some(
                TokenKind::Ok
                | TokenKind::Err
                | TokenKind::Some
                | TokenKind::None
                | TokenKind::IntLit
                | TokenKind::StrLit
                | TokenKind::True
                | TokenKind::False
                | TokenKind::LParen
                // #2680: a list pattern.
                | TokenKind::LBracket,
            ) => true,
            Some(TokenKind::Minus) => at(2) == Some(TokenKind::IntLit),
            // #2699: a range opening on `..` (`let ..9 = …`); one opening on a
            // literal is already covered above.
            Some(TokenKind::DotDot) => matches!(at(2), Some(TokenKind::IntLit))
                || (at(2) == Some(TokenKind::Minus) && at(3) == Some(TokenKind::IntLit)),
            Some(TokenKind::Ident) => match at(2) {
                Some(TokenKind::LParen | TokenKind::Dot) => true,
                // #2654: a capitalised name directly followed by `{` opens a
                // record pattern. A binding name is never followed by `{`, so
                // no `let` that parses today changes.
                Some(TokenKind::LBrace) => self.tokens.get(self.pos + 1).is_some_and(|t| {
                    self.slice(t.span)
                        .starts_with(|c: char| c.is_ascii_uppercase())
                }),
                _ => false,
            },
            _ => false,
        }
    }

    /// #2010: `let <pattern> (= | <-) <expr> else (<block> | match { <arms> })`.
    fn parse_let_else(&mut self) -> Result<LetElseParts, CompileError> {
        let kw = self.expect(TokenKind::Let, "to start a let statement")?;
        let pattern_first = self.pos;
        let pattern = self.parse_pattern_top()?;
        let pattern_after = self.pos;
        if self.peek_kind() == Some(TokenKind::Colon) {
            let colon = self.peek().unwrap().span;
            return Err(CompileError::new(
                "bynk.parse.let_pattern_annotation",
                colon,
                "a `let` with a pattern cannot carry a type annotation",
            )
            .with_note(
                "the pattern's names take their types from the value; to pin the value's type, annotate an ordinary `let` first and match on that",
            ));
        }
        let effectful = match self.peek_kind() {
            Some(TokenKind::LArrow) => {
                self.bump();
                true
            }
            _ => {
                self.expect(TokenKind::Eq, "or `<-` after the `let` pattern")?;
                false
            }
        };
        let value = self.parse_expr()?;
        let principal = if effectful {
            self.parse_call_site_actor()?
        } else {
            None
        };
        if self.peek_kind() != Some(TokenKind::Else) {
            // #2654: an irrefutable record pattern has no values to fall back
            // on, so its `let` may omit the `else`. Parentheses around the
            // pattern are transparent, so they are already gone here.
            if matches!(pattern, Pattern::Record { .. }) && pattern.is_irrefutable() {
                let end = principal.as_ref().map_or(value.span, |p| p.span);
                return Ok(LetElseParts {
                    kw: kw.span,
                    pattern,
                    value,
                    effectful,
                    principal,
                    else_span: Span {
                        file: end.file,
                        start: end.end,
                        end: end.end,
                    },
                    remove_else: Vec::new(),
                    otherwise: None,
                    span: kw.span.merge(end),
                    leading: Vec::new(),
                    trailing: None,
                });
            }
            let mut err = CompileError::new(
                "bynk.parse.let_pattern_without_else",
                kw.span.merge(value.span),
                "a `let` with a pattern needs an `else` for the values the pattern does not match",
            );
            if let Some(field) = first_refutable_field(&pattern) {
                err = err.with_note(format!(
                    "`{}` can fail to match, so the pattern does not cover every value",
                    self.slice(field)
                ));
            }
            return Err(err.with_note(
                "add `else { … }` after the value to say what this block produces when it does not match, or write a `match`",
            ));
        }
        let after_value = principal.as_ref().map_or(value.span, |p| p.span);
        let else_span = self.bump().unwrap().span;
        let (otherwise, end) = if self.peek_kind() == Some(TokenKind::Match) {
            let match_kw = self.bump().unwrap().span;
            self.expect(TokenKind::LBrace, "to open the `else match` arm list")?;
            let mut arms = Vec::new();
            while self.peek_kind() != Some(TokenKind::RBrace) {
                arms.push(self.parse_match_arm()?);
                let _ = self.eat(TokenKind::Comma);
            }
            let close = self.expect(TokenKind::RBrace, "to close the `else match` arm list")?;
            if arms.is_empty() {
                return Err(CompileError::new(
                    "bynk.parse.empty_match",
                    match_kw.merge(close.span),
                    "an `else match` must have at least one arm",
                ));
            }
            (LetElseOtherwise::Arms(arms), close.span)
        } else {
            let block = self.parse_block("to open the `else` block")?;
            let end = block.span;
            (LetElseOtherwise::Block(block), end)
        };
        let remove_else =
            self.else_removal(&pattern, pattern_first..pattern_after, after_value, end);
        Ok(LetElseParts {
            kw: kw.span,
            pattern,
            value,
            effectful,
            principal,
            else_span,
            remove_else,
            otherwise: Some(otherwise),
            span: kw.span.merge(end),
            leading: Vec::new(),
            trailing: None,
        })
    }

    /// #2654: the ranges to delete to turn `let (T { … }) = e else …` into
    /// `let T { … } = e` — the parentheses around the pattern (any number: they
    /// are transparent) and everything from the end of the value to the end of
    /// the `else`. Empty unless the pattern is a record pattern, the only one
    /// that has an `else`-less form. `tokens` is the pattern's token range.
    fn else_removal(
        &self,
        pattern: &Pattern,
        tokens: std::ops::Range<usize>,
        after_value: Span,
        end: Span,
    ) -> Vec<Span> {
        if !matches!(pattern, Pattern::Record { .. }) {
            return Vec::new();
        }
        let kind = |i: usize| self.tokens.get(i).map(|t| t.kind);
        let opens = tokens
            .clone()
            .take_while(|&i| kind(i) == Some(TokenKind::LParen))
            .count();
        let closes = tokens
            .clone()
            .rev()
            .take_while(|&i| kind(i) == Some(TokenKind::RParen))
            .count();
        let mut out = Vec::new();
        if opens > 0 && opens == closes {
            let open = self.tokens[tokens.start].span;
            let close = self.tokens[tokens.end - 1].span;
            out.push(Span::new_in(open.file, open.start, pattern.span().start));
            out.push(Span::new_in(close.file, pattern.span().end, close.end));
        }
        out.push(Span::new_in(end.file, after_value.end, end.end));
        out
    }

    /// #2010: the hidden binding and the `match` a `let … else` stands for —
    /// `let __letElse<offset> (<- | =) e` and
    /// `match __letElse<offset> { P => { rest }, _ => E }` (or the `else match`
    /// arms in place of `_ => E`). The binder's spans are empty, at the `let`,
    /// so no editor surface lands on a name the author never wrote.
    fn desugar_let_else(&mut self, parts: LetElseParts, rest: Block) -> (Statement, Expr) {
        let LetElseParts {
            kw,
            pattern,
            value,
            effectful,
            principal,
            else_span,
            remove_else,
            otherwise,
            span,
            leading,
            trailing,
        } = parts;
        let at = Span {
            file: kw.file,
            start: kw.start,
            end: kw.start,
        };
        let binder = Ident {
            name: format!("{LET_ELSE_BINDER_PREFIX}{}", kw.start),
            span: at,
        };
        let form = match &otherwise {
            Some(LetElseOtherwise::Block(_)) => LetElseForm::Block,
            Some(LetElseOtherwise::Arms(_)) => LetElseForm::Match,
            None => LetElseForm::Plain,
        };
        let let_stmt = LetStmt {
            name: binder.clone(),
            type_annot: None,
            value,
            principal,
            let_else: Some(LetElse {
                form,
                else_span,
                remove_else,
            }),
            span,
            trivia: Trivia { leading, trailing },
        };
        let binding = if effectful {
            Statement::EffectLet(let_stmt)
        } else {
            Statement::Let(let_stmt)
        };
        let match_span = kw.merge(rest.span);
        let mut arms = vec![MatchArm {
            span: pattern.span().merge(rest.span),
            pattern,
            guard: None,
            body: MatchBody::Block(rest),
        }];
        match otherwise {
            None => {}
            Some(LetElseOtherwise::Block(block)) => arms.push(MatchArm {
                span: else_span.merge(block.span),
                pattern: Pattern::Wildcard(else_span),
                guard: None,
                body: MatchBody::Block(block),
            }),
            Some(LetElseOtherwise::Arms(more)) => arms.extend(more),
        }
        let discriminant = Expr {
            id: self.alloc_expr_id(),
            kind: ExprKind::Ident(binder),
            span: at,
        };
        let tail = Expr {
            id: self.alloc_expr_id(),
            kind: ExprKind::Match {
                discriminant: Box::new(discriminant),
                arms,
            },
            span: match_span,
        };
        (binding, tail)
    }

    /// v0.81: true when the next two tokens are `<ident> :=` — a `Cell` write
    /// statement, which (unlike `let`/`commit`/`~>`) is led by an identifier.
    /// #2137: `advance <Ident> by …` opens an `advance` statement. `advance` is
    /// contextual, and `<Ident> <Ident> by` is no other statement or
    /// expression (`by` is reserved), so the lookahead is unambiguous.
    fn advance_ahead(&self) -> bool {
        let kind = |i: usize| self.tokens.get(self.pos + i).map(|t| t.kind);
        kind(0) == Some(TokenKind::Ident)
            && self
                .tokens
                .get(self.pos)
                .is_some_and(|t| self.slice(t.span) == "advance")
            && kind(1) == Some(TokenKind::Ident)
            && kind(2) == Some(TokenKind::By)
    }

    /// #2640: `par {` opens a concurrent binding block. `par` is contextual, and
    /// `<Ident> {` is no other statement or expression start, so the lookahead
    /// is unambiguous.
    fn par_ahead(&self) -> bool {
        self.peek_kind() == Some(TokenKind::Ident)
            && self
                .tokens
                .get(self.pos)
                .is_some_and(|t| self.slice(t.span) == "par")
            && self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::LBrace)
    }

    /// #2640: `par { <statement>* }`. Any statement parses here; the checker
    /// admits only `let x <- e` and `do e`. A `let` with a refutable pattern
    /// would desugar into a `match` over the rest of the block, which a `par`
    /// has no room for, so it is refused here rather than mis-parsed.
    fn parse_par_stmt(&mut self) -> Result<Statement, CompileError> {
        let keyword = self.expect_ident("to start a `par` block")?.span;
        self.expect(TokenKind::LBrace, "to open the `par` block")?;
        let mut statements = Vec::new();
        let closing_comments = loop {
            let leading = self.take_leading_trivia();
            if self.peek_kind() == Some(TokenKind::RBrace) {
                break leading;
            }
            let is_statement = matches!(
                self.peek_kind(),
                Some(TokenKind::Let)
                    | Some(TokenKind::Expect)
                    | Some(TokenKind::TildeArrow)
                    | Some(TokenKind::Do)
            ) || self.assign_ahead()
                || self.advance_ahead()
                || self.par_ahead();
            if !is_statement {
                let (span, found) = match self.peek() {
                    Some(t) => (t.span, t.kind.describe().to_string()),
                    None => (self.eof_span(), "end of file".to_string()),
                };
                return Err(CompileError::new(
                    "bynk.par.invalid_statement",
                    span,
                    format!("a `par` block holds only `let x <- e` and `do e`, found {found}"),
                )
                .with_note("a `par` block has no value; bind each result with `let x <- e`"));
            }
            if self.peek_kind() == Some(TokenKind::Let) && self.let_pattern_ahead() {
                return Err(CompileError::new(
                    "bynk.par.invalid_statement",
                    self.peek().unwrap().span,
                    "a `let` with a pattern and an `else` cannot appear in a `par` block",
                )
                .with_note(
                    "bind the effect with a plain `let x <- e` in the block, then match on `x` after it",
                ));
            }
            self.enter_recursion("this nesting of `par` blocks")?;
            let parsed = self.parse_statement();
            self.depth -= 1;
            let mut stmt = parsed?;
            let trailing = self.take_trailing_trivia();
            attach_trivia(&mut stmt, leading, trailing);
            statements.push(stmt);
        };
        let close = self.expect(TokenKind::RBrace, "to close the `par` block")?;
        Ok(Statement::Par(ParStmt {
            keyword,
            statements,
            closing_comments,
            span: keyword.merge(close.span),
            trivia: Trivia::default(),
        }))
    }

    /// #2842: the optional `matches snapshot "<name>"` tail of an `expect`. Both
    /// words are contextual — an expression is never followed by a bare
    /// identifier, so `matches` here is unambiguous (as `faults` is).
    fn parse_snapshot_clause(&mut self) -> Result<Option<SnapshotClause>, CompileError> {
        // Only `matches snapshot` commits: a bare `matches` begins the next
        // statement (a variable of that name) and is left alone.
        if self.peek_kind() != Some(TokenKind::Ident)
            || self.nth_text(0) != "matches"
            || self.nth_kind(1) != Some(TokenKind::Ident)
            || self.nth_text(1) != "snapshot"
        {
            return Ok(None);
        }
        let matches_tok = self.bump().unwrap();
        if self.peek_kind() != Some(TokenKind::Ident) || self.nth_text(0) != "snapshot" {
            return Err(CompileError::new(
                "bynk.parse.expected_token",
                self.peek().map_or(self.eof_span(), |t| t.span),
                "expected `snapshot` after `matches` in an `expect`",
            )
            .with_note("the form is `expect <value> matches snapshot \"<name>\"`"));
        }
        self.bump();
        let Some(lit) = self.peek().filter(|t| t.kind == TokenKind::StrLit) else {
            return Err(CompileError::new(
                "bynk.test.snapshot_name_not_literal",
                self.peek().map_or(self.eof_span(), |t| t.span),
                "a snapshot is named by a string literal",
            )
            .with_note("write `expect <value> matches snapshot \"<name>\"`"));
        };
        self.bump();
        let name = super::parse_string_literal(self.slice(lit.span), lit.span)?;
        Ok(Some(SnapshotClause {
            name,
            span: matches_tok.span.merge(lit.span),
            name_span: lit.span,
        }))
    }

    pub(crate) fn assign_ahead(&self) -> bool {
        self.peek_kind() == Some(TokenKind::Ident)
            && self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::ColonEq)
    }

    /// v0.182 (#664): parse an optional call-site actor clause after an
    /// effect-let value — `by <Actor>` (unit identity) or `by <Actor>(<expr>)`.
    /// Distinct from the handler `by` clause (`parse_by_clause`), which admits a
    /// binder and an actor *sum* but no identity argument. #1812: also read
    /// after a fault claim's subject (`expect <call> by User("bob") faults`).
    pub(crate) fn parse_call_site_actor(&mut self) -> Result<Option<CallSiteActor>, CompileError> {
        if self.peek_kind() != Some(TokenKind::By) {
            return Ok(None);
        }
        let by_kw = self.expect(TokenKind::By, "to start the call-site actor clause")?;
        let actor = self.expect_ident("as the actor after `by` at a call site")?;
        let (identity, claims, end) = if self.peek_kind() == Some(TokenKind::LParen) {
            self.expect(TokenKind::LParen, "after the actor name")?;
            let id = self.parse_expr()?;
            // #2380 (L5): an optional second argument, the token's claims.
            let claims = if self.peek_kind() == Some(TokenKind::Comma) {
                self.expect(TokenKind::Comma, "between the identity and the claims")?;
                Some(Box::new(self.parse_expr()?))
            } else {
                None
            };
            let rp = self.expect(TokenKind::RParen, "after the identity value")?;
            (Some(Box::new(id)), claims, rp.span)
        } else {
            (None, None, actor.span)
        };
        let span = by_kw.span.merge(end);
        Ok(Some(CallSiteActor {
            actor,
            identity,
            claims,
            span,
        }))
    }

    pub(crate) fn parse_statement(&mut self) -> Result<Statement, CompileError> {
        if self.assign_ahead() {
            let target = self.expect_ident("as the assignment target")?;
            self.expect(TokenKind::ColonEq, "after the assignment target")?;
            let value = self.parse_expr()?;
            let span = target.span.merge(value.span);
            return Ok(Statement::Assign(AssignStmt {
                target,
                value,
                span,
                trivia: Trivia::default(),
            }));
        }
        if self.par_ahead() {
            return self.parse_par_stmt();
        }
        if self.advance_ahead() {
            let keyword = self.expect_ident("to start an advance statement")?.span;
            let cap = self.expect_ident("as the capability after `advance`")?;
            self.expect(TokenKind::By, "after the capability in `advance`")?;
            let amount = self.parse_expr()?;
            let span = keyword.merge(amount.span);
            return Ok(Statement::Advance(AdvanceStmt {
                keyword,
                cap,
                amount,
                span,
                trivia: Trivia::default(),
            }));
        }
        if self.peek_kind() == Some(TokenKind::Expect) {
            let kw = self.expect(TokenKind::Expect, "to start an expect statement")?;
            let value = self.parse_expect_body()?;
            let snapshot = self.parse_snapshot_clause()?;
            let span = kw
                .span
                .merge(snapshot.as_ref().map_or(value.span, |c| c.span));
            return Ok(Statement::Expect(ExpectStmt {
                value,
                snapshot,
                span,
                trivia: Trivia::default(),
            }));
        }
        if self.peek_kind() == Some(TokenKind::TildeArrow) {
            let kw = self.expect(TokenKind::TildeArrow, "to start an async send statement")?;
            let value = self.parse_expr()?;
            let span = kw.span.merge(value.span);
            return Ok(Statement::Send(SendStmt {
                value,
                span,
                trivia: Trivia::default(),
            }));
        }
        if self.peek_kind() == Some(TokenKind::Do) {
            // v0.146 (ADR 0170): `do e` — perform a unit effect as a statement.
            let kw = self.expect(TokenKind::Do, "to start a `do` statement")?;
            let value = self.parse_expr()?;
            let span = kw.span.merge(value.span);
            return Ok(Statement::Do(DoStmt {
                value,
                span,
                trivia: Trivia::default(),
            }));
        }
        let kw = self.expect(TokenKind::Let, "to start a let statement")?;
        // Allow `_` as a discard name in `let _ = ...` and `let _ <- ...`.
        let name = if self.peek_kind() == Some(TokenKind::Underscore) {
            let t = self.bump().unwrap();
            Ident {
                name: "_".to_string(),
                span: t.span,
            }
        } else {
            self.expect_ident("after `let`")?
        };
        let type_annot = if self.eat(TokenKind::Colon).is_some() {
            Some(self.parse_type_ref("as the let-binding's type annotation")?)
        } else {
            None
        };
        match self.peek_kind() {
            Some(TokenKind::Eq) => {
                self.bump();
                let value = self.parse_expr()?;
                self.reject_else_on_binding(&name)?;
                let span = kw.span.merge(value.span);
                Ok(Statement::Let(LetStmt {
                    name,
                    type_annot,
                    value,
                    principal: None,
                    let_else: None,
                    span,
                    trivia: Trivia::default(),
                }))
            }
            Some(TokenKind::LArrow) => {
                self.bump();
                let value = self.parse_expr()?;
                // v0.182 (#664): an optional call-site `by <Actor>(<identity>)`
                // clause — the test-body form that names the actor a case acts as
                // when it drives a service handler. Distinct from the handler
                // `by` (no argument); parsed only here, in the effect-let arm.
                let principal = self.parse_call_site_actor()?;
                self.reject_else_on_binding(&name)?;
                let end = principal.as_ref().map(|p| p.span).unwrap_or(value.span);
                let span = kw.span.merge(end);
                Ok(Statement::EffectLet(LetStmt {
                    name,
                    type_annot,
                    value,
                    principal,
                    let_else: None,
                    span,
                    trivia: Trivia::default(),
                }))
            }
            Some(_) => {
                let t = self.peek().unwrap();
                Err(CompileError::new(
                    "bynk.parse.expected_token",
                    t.span,
                    format!(
                        "expected `=` or `<-` after the let-binding's name, found {}",
                        t.kind.describe()
                    ),
                ))
            }
            None => Err(CompileError::new(
                "bynk.parse.unexpected_eof",
                self.eof_span(),
                "expected `=` or `<-` after the let-binding's name, found end of file",
            )),
        }
    }

    /// #2010: an `else` after a plain `let name = e` is never reached — a name
    /// matches every value — so it is refused rather than silently ignored.
    fn reject_else_on_binding(&self, name: &Ident) -> Result<(), CompileError> {
        if self.peek_kind() != Some(TokenKind::Else) {
            return Ok(());
        }
        Err(CompileError::new(
            "bynk.parse.let_else_on_binding",
            self.peek().unwrap().span,
            format!(
                "`else` can never run here: `{}` is a plain binding, which matches every value",
                name.name
            ),
        )
        .with_label(name.span, "a name, not a pattern")
        .with_note(
            "to match one variant, write a pattern: `Ok(x)`, `Some(x)`, or a qualified variant such as `Status.Pending`",
        ))
    }

    pub(crate) fn parse_param(&mut self) -> Result<Param, CompileError> {
        let name = self.expect_ident("as a parameter name")?;
        self.expect(TokenKind::Colon, "after the parameter name")?;
        let type_ref = self.parse_type_ref("as the parameter type")?;
        let span = name.span.merge(type_ref.span());
        Ok(Param {
            name,
            type_ref,
            span,
        })
    }

    /// v0.20a: at an `LParen` in primary-expression position, decide whether
    /// a lambda follows: scan to the matching `)` counting paren depth, then
    /// peek one token for `=>`. Terminates at EOF; cost is the distance to
    /// the matching paren (the same class as the record-construction
    /// lookahead).
    pub(crate) fn lambda_ahead(&self) -> bool {
        let mut n = 1;
        let mut depth = 1u32;
        loop {
            match self.tokens.get(self.pos + n).map(|t| t.kind) {
                Some(TokenKind::LParen) => depth += 1,
                Some(TokenKind::RParen) => {
                    depth -= 1;
                    if depth == 0 {
                        return self.tokens.get(self.pos + n + 1).map(|t| t.kind)
                            == Some(TokenKind::FatArrow);
                    }
                }
                None => return false,
                _ => {}
            }
            n += 1;
        }
    }

    /// v0.20a: parse `(params) => expr | { block }`. Param annotations are
    /// optional (`(o: Order) => …` / `(o) => …`); the unannotated form relies
    /// on an expected function type at the use site (checked semantically).
    pub(crate) fn parse_lambda(&mut self) -> Result<Expr, CompileError> {
        let open = self.bump().unwrap(); // `(`
        let mut params = Vec::new();
        if self.peek_kind() != Some(TokenKind::RParen) {
            loop {
                params.push(self.parse_lambda_param()?);
                if self.eat(TokenKind::Comma).is_none() {
                    break;
                }
            }
        }
        self.expect(TokenKind::RParen, "to close the lambda parameter list")?;
        self.expect(TokenKind::FatArrow, "after the lambda parameter list")?;
        let block_body = self.peek_kind() == Some(TokenKind::LBrace);
        let body = if block_body {
            let block = self.parse_block("as the lambda body")?;
            let span = block.span;
            Expr {
                id: self.alloc_expr_id(),
                kind: ExprKind::Block(block),
                span,
            }
        } else {
            self.parse_expr()?
        };
        let span = open.span.merge(body.span);
        let body = self.desugar_lambda_patterns(&params, body);
        Ok(Expr {
            id: self.alloc_expr_id(),
            kind: ExprKind::Lambda(LambdaExpr {
                params,
                body: Box::new(body),
                span,
                block_body,
            }),
            span,
        })
    }

    /// One lambda parameter: a name with an optional annotation, or (#2712) an
    /// irrefutable record pattern, `Item { qty, .. }`, which takes no annotation.
    fn parse_lambda_param(&mut self) -> Result<LambdaParam, CompileError> {
        let at = |k: usize| self.tokens.get(self.pos + k).map(|t| t.kind);
        let capitalised = self.tokens.get(self.pos).is_some_and(|t| {
            self.slice(t.span)
                .starts_with(|c: char| c.is_ascii_uppercase())
        });
        let is_pattern = match at(0) {
            Some(
                TokenKind::Ok
                | TokenKind::Err
                | TokenKind::Some
                | TokenKind::None
                | TokenKind::IntLit
                | TokenKind::StrLit
                | TokenKind::True
                | TokenKind::False
                | TokenKind::LBracket
                | TokenKind::DotDot,
            ) => true,
            Some(TokenKind::Minus) => at(1) == Some(TokenKind::IntLit),
            Some(TokenKind::Ident) => {
                matches!(at(1), Some(TokenKind::LParen | TokenKind::Dot))
                    || (at(1) == Some(TokenKind::LBrace) && capitalised)
            }
            _ => false,
        };
        if !is_pattern {
            let (name, mut p_span) = if at(0) == Some(TokenKind::Underscore) {
                let span = self.bump().unwrap().span;
                let name = Ident {
                    name: format!("{LAMBDA_WILDCARD_PREFIX}{}", span.start),
                    span: Span::new_in(span.file, span.start, span.start),
                };
                (name, span)
            } else {
                let name = self.expect_ident("as a lambda parameter name")?;
                let span = name.span;
                (name, span)
            };
            let type_ref = if self.eat(TokenKind::Colon).is_some() {
                let t = self.parse_type_ref("as the lambda parameter type")?;
                p_span = p_span.merge(t.span());
                Some(t)
            } else {
                None
            };
            return Ok(LambdaParam {
                name,
                type_ref,
                span: p_span,
                pattern: None,
            });
        }
        let pattern = self.parse_pattern()?;
        if !matches!(pattern, Pattern::Record { .. }) {
            return Err(CompileError::new(
                "bynk.parse.lambda_pattern_not_record",
                pattern.span(),
                "a lambda parameter pattern must be a record pattern",
            )
            .with_note(
                "only `TypeName { field, .. }` can be a lambda parameter; take a name and `match` on it in the body for any other pattern",
            ));
        }
        if !pattern.is_irrefutable() {
            let mut err = CompileError::new(
                "bynk.parse.lambda_pattern_refutable",
                pattern.span(),
                "a lambda parameter pattern must match every value of its type",
            );
            if let Some(field) = first_refutable_field(&pattern) {
                err = err.with_note(format!(
                    "`{}` can fail to match, so the pattern does not cover every value",
                    self.slice(field)
                ));
            }
            return Err(err.with_note(
                "take a name for the parameter and `match` on it in the body to handle the other cases",
            ));
        }
        if self.peek_kind() == Some(TokenKind::Colon) {
            let colon = self.peek().unwrap().span;
            self.bump();
            let annotation = self.parse_type_ref("as the lambda parameter type");
            let mut err = CompileError::new(
                "bynk.parse.lambda_pattern_annotation",
                colon,
                "a lambda parameter with a pattern cannot carry a type annotation",
            )
            .with_note(
                "the pattern's type name already says the parameter's type; its names take their types from that record",
            );
            if let Ok(t) = annotation {
                err = err.with_suggestion(
                    "remove the annotation",
                    vec![(
                        Span::new_in(colon.file, pattern.span().end, t.span().end),
                        String::new(),
                    )],
                    Applicability::MachineApplicable,
                );
            }
            return Err(err);
        }
        let span = pattern.span();
        let at_pattern = Span::new_in(span.file, span.start, span.start);
        Ok(LambdaParam {
            name: Ident {
                name: format!("{LAMBDA_ARG_BINDER_PREFIX}{}", span.start),
                span: at_pattern,
            },
            type_ref: None,
            span,
            pattern: Some(pattern),
        })
    }

    /// #2712: `(P) => body` is `(__lambdaArg<offset>) => { let P = __lambdaArg<offset>; body }`,
    /// the `let` being #2654's `else`-less destructuring (so the same hidden
    /// `let … else` binder and one-arm `match`). Parameters desugar last to
    /// first so the first pattern's `let` is outermost. The binders' spans are
    /// empty, at the pattern, so no editor surface lands on a name the author
    /// never wrote.
    fn desugar_lambda_patterns(&mut self, params: &[LambdaParam], body: Expr) -> Expr {
        if params.iter().all(|p| p.pattern.is_none()) {
            return body;
        }
        let mut rest = match body.kind {
            ExprKind::Block(b) => b,
            _ => Block {
                span: body.span,
                statements: Vec::new(),
                tail: Box::new(body),
                tail_leading_comments: Vec::new(),
                implicit_tail: false,
            },
        };
        for p in params.iter().rev() {
            let Some(pattern) = &p.pattern else { continue };
            let at = p.name.span;
            let value = Expr {
                id: self.alloc_expr_id(),
                kind: ExprKind::Ident(p.name.clone()),
                span: at,
            };
            let parts = LetElseParts {
                kw: at,
                pattern: pattern.clone(),
                value,
                effectful: false,
                principal: None,
                else_span: Span::new_in(at.file, p.span.end, p.span.end),
                remove_else: Vec::new(),
                otherwise: None,
                span: p.span,
                leading: Vec::new(),
                trailing: None,
            };
            let span = rest.span;
            let (binding, tail) = self.desugar_let_else(parts, rest);
            rest = Block {
                statements: vec![binding],
                tail: Box::new(tail),
                span,
                tail_leading_comments: Vec::new(),
                implicit_tail: false,
            };
        }
        let span = rest.span;
        Expr {
            id: self.alloc_expr_id(),
            kind: ExprKind::Block(rest),
            span,
        }
    }
}

/// #2010: a parsed `let <pattern> … else …`, before [`Parser::desugar_let_else`]
/// joins it to the rest of its block.
struct LetElseParts {
    kw: Span,
    pattern: Pattern,
    value: Expr,
    effectful: bool,
    principal: Option<CallSiteActor>,
    else_span: Span,
    remove_else: Vec<Span>,
    /// `None` for the `else`-less form of an irrefutable record pattern (#2654).
    otherwise: Option<LetElseOtherwise>,
    span: Span,
    leading: Vec<Comment>,
    trailing: Option<String>,
}

/// #2654: the span of the first field of a record pattern that can fail to
/// match, descending into nested record patterns to the field that does.
fn first_refutable_field(p: &Pattern) -> Option<Span> {
    let Pattern::Record { fields, .. } = p else {
        return None;
    };
    for (name, sub) in fields {
        let Some(sub) = sub else { continue };
        if let Some(inner) = first_refutable_field(sub) {
            return Some(inner);
        }
        if !sub.is_irrefutable() {
            return Some(name.span.merge(sub.span()));
        }
    }
    None
}

enum LetElseOtherwise {
    Block(Block),
    Arms(Vec<MatchArm>),
}

/// Set a statement's own leading and trailing comments.
fn attach_trivia(stmt: &mut Statement, leading: Vec<Comment>, trailing: Option<String>) {
    let trivia = match stmt {
        Statement::Let(l) | Statement::EffectLet(l) => &mut l.trivia,
        Statement::Expect(a) => &mut a.trivia,
        Statement::Send(s) => &mut s.trivia,
        Statement::Do(d) => &mut d.trivia,
        Statement::Assign(a) => &mut a.trivia,
        Statement::Advance(a) => &mut a.trivia,
        Statement::Par(p) => &mut p.trivia,
    };
    trivia.leading = leading;
    trivia.trailing = trailing;
}