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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
//! Expression and pattern parsing — the precedence ladder (`parse_expr`
//! down through `parse_unary`/`parse_postfix`/`parse_primary`), record
//! construction, `match`/pattern parsing, `if`, and the `Ok`/`Err`
//! expression forms. 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::*;
impl<'a> Parser<'a> {
// -- expressions --
/// Depth-guarded entry to the expression grammar. Parenthesised
/// expressions re-enter here from `parse_primary`, and every nested
/// subexpression (call arguments, record fields, `if`/`match` operands, …)
/// routes through it, so bounding depth here bounds expression recursion as
/// a whole (#713). It also resets the no-record-literal restriction (#636);
/// the unguarded ladder body lives in [`Parser::parse_expr_inner`].
pub(crate) fn parse_expr(&mut self) -> Result<Expr, CompileError> {
self.enter_recursion("this expression")?;
// A fresh `parse_expr` is always a new sub-expression — the operands of
// a delimited form (parentheses, call arguments, list, record field) or
// a statement expression. The no-record-literal restriction (#636)
// applies only to the *spine* of an `if`/`match` condition, so clear it
// here: a record literal is legal again the moment we descend through a
// delimiter, e.g. `if f(A { x: 1 }) { … }`. The condition spine reaches
// the precedence ladder via [`parse_cond_expr`], which bypasses this.
let prev = self.no_record_literal;
self.no_record_literal = false;
let result = self.parse_expr_inner();
self.no_record_literal = prev;
self.depth -= 1;
result
}
/// The precedence-ladder entry, shared by [`parse_expr`] (which resets the
/// no-record-literal restriction first) and [`parse_cond_expr`] (which sets
/// it). Keeping the ladder here — rather than in `parse_expr` — is what lets
/// a condition parse its spine under the restriction without also clearing
/// it on entry.
fn parse_expr_inner(&mut self) -> Result<Expr, CompileError> {
// v0.9.1: `assert e` is an expression of type `()`. Parsed at the
// topmost precedence so `assert x == 1` binds as `assert (x == 1)`.
// In statement position the block parser still consumes `assert` as
// a Statement::Expect (preserving the v0.7+ form), so this production
// only fires when `assert` appears in true expression position
// (e.g., a match-arm body).
if self.peek_kind() == Some(TokenKind::Expect) {
let kw = self.expect(TokenKind::Expect, "to start an expect expression")?;
let value = self.parse_expect_body()?;
let span = kw.span.merge(value.span);
return Ok(Expr {
kind: ExprKind::Expect(Box::new(value)),
span,
});
}
self.parse_implies()
}
/// Parse an expression in **condition position** — an `if` condition or a
/// `match` discriminant — where a trailing `{` opens the branch/arm block,
/// not a record literal (#636). `if ready { result } else { … }` must read
/// `ready` as the condition and `{ result }` as the then-branch, even
/// though `ready { result }` is also the shape of a shorthand-field record
/// construction.
///
/// The restriction is set for the condition's own spine only, then
/// restored. It reaches the precedence ladder through [`parse_expr_inner`],
/// bypassing [`parse_expr`]'s reset; any delimited sub-expression within the
/// condition still goes through `parse_expr` and so lifts the restriction
/// (`if (ready { x }) { … }` constructs a record). Mirrors Rust's
/// `NO_STRUCT_LITERAL` restriction; parenthesise to construct a record in
/// condition head position, e.g. `match (A { x: 1 }) { … }`.
fn parse_cond_expr(&mut self) -> Result<Expr, CompileError> {
let prev = self.no_record_literal;
self.no_record_literal = true;
let result = self.parse_expr_inner();
self.no_record_literal = prev;
result
}
/// The subject of an `expect` (v0.117): either an observation over a
/// consumed capability's recorded calls (`Cap.op called …`, `Cap.op never
/// called`, `A.op before B.op`) or an ordinary `Bool` predicate. The
/// observation shape is detected by a `Cap . op` prefix followed by one of
/// the contextual words `called` / `never` / `before` — which stay ordinary
/// identifiers everywhere else.
pub(crate) fn parse_expect_body(&mut self) -> Result<Expr, CompileError> {
if self.peek_kind() == Some(TokenKind::Ident)
&& self.nth_kind(1) == Some(TokenKind::Dot)
&& self.nth_kind(2) == Some(TokenKind::Ident)
&& self.nth_kind(3) == Some(TokenKind::Ident)
&& matches!(self.nth_text(3), "called" | "never" | "before")
{
return self.parse_observation();
}
self.parse_expr()
}
/// Parse an observation clause (v0.117): `Cap.op` followed by a matcher —
/// `called [once | <n> times] [with <pred>]`, `never called`, or
/// `before Cap.op`. The contextual words are matched by text, not token kind.
fn parse_observation(&mut self) -> Result<Expr, CompileError> {
let cap = self.expect_ident("as the observed capability name")?;
self.expect(
TokenKind::Dot,
"after the capability name in an observation",
)?;
let op = self.expect_ident("as the observed operation name")?;
let start = cap.span;
let word = self.nth_text(0);
let matcher = match word {
"never" => {
let never_tok = self.bump().unwrap(); // `never`
// `never called`
if self.peek_kind() == Some(TokenKind::Ident) && self.nth_text(0) == "called" {
self.bump();
} else {
return Err(CompileError::new(
"bynk.parse.expected_expression",
never_tok.span,
"expected `called` after `never` in an observation",
));
}
ObservationMatcher::NeverCalled
}
"called" => {
self.bump(); // `called`
// Optional count: `once` or `<int> times`.
let count = if self.peek_kind() == Some(TokenKind::Ident)
&& self.nth_text(0) == "once"
{
let once = self.bump().unwrap();
Some(Box::new(Expr {
kind: ExprKind::int_lit(1),
span: once.span,
}))
} else if self.peek_kind() == Some(TokenKind::IntLit) {
let n = self.parse_primary()?;
// `<int> times`
if self.peek_kind() == Some(TokenKind::Ident) && self.nth_text(0) == "times" {
self.bump();
} else {
return Err(CompileError::new(
"bynk.parse.expected_expression",
n.span,
"expected `times` after the call count in an observation",
));
}
Some(Box::new(n))
} else {
None
};
// Optional `with <pred>`.
let with_pred =
if self.peek_kind() == Some(TokenKind::Ident) && self.nth_text(0) == "with" {
self.bump(); // `with`
Some(Box::new(self.parse_expr()?))
} else {
None
};
ObservationMatcher::Called { count, with_pred }
}
"before" => {
self.bump(); // `before`
let cap2 = self.expect_ident("as the capability name after `before`")?;
self.expect(TokenKind::Dot, "after the capability name in `before`")?;
let op2 = self.expect_ident("as the operation name after `before`")?;
ObservationMatcher::Before { cap: cap2, op: op2 }
}
other => {
return Err(CompileError::new(
"bynk.parse.expected_expression",
op.span,
format!(
"expected an observation matcher (`called`/`never`/`before`), found `{other}`"
),
));
}
};
let end = self.prev_span();
Ok(Expr {
kind: ExprKind::Observation(ObservationExpr { cap, op, matcher }),
span: start.merge(end),
})
}
/// v0.80: `P implies Q` — logical implication, the lowest-precedence binary
/// operator (below `||`). Right-associative, so `A implies B implies C`
/// parses as `A implies (B implies C)` (matching `A → (B → C)`).
fn parse_implies(&mut self) -> Result<Expr, CompileError> {
let lhs = self.parse_or()?;
if self.peek_kind() == Some(TokenKind::Implies) {
self.bump();
// `implies` is right-associative, so a chain recurses here rather
// than looping — guard it as a self-recursive descent so
// `A implies B implies …` cannot overflow the parser (#714).
self.enter_recursion("this expression")?;
let rhs = self.parse_implies();
self.depth -= 1;
let rhs = rhs?;
let span = lhs.span.merge(rhs.span);
return Ok(Expr {
kind: ExprKind::BinOp(BinOp::Implies, Box::new(lhs), Box::new(rhs)),
span,
});
}
Ok(lhs)
}
fn parse_or(&mut self) -> Result<Expr, CompileError> {
let mut lhs = self.parse_and()?;
// Associative chains are built iteratively, so each fold is counted
// against the shared nesting budget rather than a recursive descent
// (#714); `folds` is unwound from `self.depth` before returning.
let mut folds = 0usize;
let result = loop {
if self.peek_kind() != Some(TokenKind::PipePipe) {
break Ok(lhs);
}
self.bump();
let rhs = match self.parse_and() {
Ok(rhs) => rhs,
Err(e) => break Err(e),
};
let span = lhs.span.merge(rhs.span);
lhs = Expr {
kind: ExprKind::BinOp(BinOp::Or, Box::new(lhs), Box::new(rhs)),
span,
};
if let Err(e) = self.enter_chain_fold(&mut folds, lhs.span) {
break Err(e);
}
};
self.depth -= folds;
result
}
fn parse_and(&mut self) -> Result<Expr, CompileError> {
let mut lhs = self.parse_eq()?;
let mut folds = 0usize;
let result = loop {
if self.peek_kind() != Some(TokenKind::AmpAmp) {
break Ok(lhs);
}
self.bump();
let rhs = match self.parse_eq() {
Ok(rhs) => rhs,
Err(e) => break Err(e),
};
let span = lhs.span.merge(rhs.span);
lhs = Expr {
kind: ExprKind::BinOp(BinOp::And, Box::new(lhs), Box::new(rhs)),
span,
};
if let Err(e) = self.enter_chain_fold(&mut folds, lhs.span) {
break Err(e);
}
};
self.depth -= folds;
result
}
fn parse_eq(&mut self) -> Result<Expr, CompileError> {
let lhs = self.parse_cmp()?;
// v0.2: the `is` operator sits at the same precedence level as
// equality but produces a Bool from a pattern test.
if self.peek_kind() == Some(TokenKind::Is) {
self.bump();
// #472: `is`'s pattern is a top-level position — [`Parser::parse_pattern_top`]
// admits a trailing `where` there the same as a match arm's
// pattern (a nested payload never does — `r is Ok(_ where P)` is
// a syntax error, caught below the recursive `parse_pattern`).
// But a *top-level* refined pattern is rejected here too, at
// parse time rather than deferred to `check_is`: the tree-sitter
// grammar cannot admit `refined_pattern` inside `is_expr` at all
// (D4 in the refined-patterns ADR) — `refinement`'s own
// `&&`-joined predicate list is ambiguous with the surrounding
// expression grammar there. A plain top-level `matches!` check
// suffices even with #474's or-patterns in the mix:
// `parse_pattern_top` folds `|` *before* checking for `where`
// (`Refined` always wraps the whole pattern, never appearing as
// one alternative inside an `Or`), so `Pattern::Refined` can only
// ever be this expression's outermost pattern shape, not buried
// inside one. Rejecting it here, not just in the checker, keeps
// the two parsers in agreement on every input (ADR 0213).
let pattern = self.parse_pattern_top()?;
if matches!(pattern, Pattern::Refined { .. }) {
return Err(CompileError::new(
"bynk.types.is_refined_pattern",
pattern.span(),
"the `is` operator does not accept a refined pattern here",
)
.with_note(
"declare a named refined type and use `x is TypeName`, or use a `match` arm",
));
}
let span = lhs.span.merge(pattern.span());
return Ok(Expr {
kind: ExprKind::Is {
value: Box::new(lhs),
pattern,
},
span,
});
}
let op = match self.peek_kind() {
Some(TokenKind::EqEq) => Some(BinOp::Eq),
Some(TokenKind::BangEq) => Some(BinOp::NotEq),
_ => None,
};
if let Some(op) = op {
self.bump();
let rhs = self.parse_cmp()?;
// Non-associative: reject a second `==` or `!=` at this level.
if matches!(
self.peek_kind(),
Some(TokenKind::EqEq) | Some(TokenKind::BangEq)
) {
let t = self.peek().unwrap();
return Err(CompileError::new(
"bynk.parse.non_associative",
t.span,
format!(
"`{}` is non-associative; chained equality is not allowed",
t.kind.describe().trim_matches('`')
),
)
.with_note("parenthesise to disambiguate, e.g. `(a == b) == c`"));
}
let span = lhs.span.merge(rhs.span);
Ok(Expr {
kind: ExprKind::BinOp(op, Box::new(lhs), Box::new(rhs)),
span,
})
} else {
Ok(lhs)
}
}
fn parse_cmp(&mut self) -> Result<Expr, CompileError> {
let lhs = self.parse_add()?;
let op = match self.peek_kind() {
Some(TokenKind::Lt) => Some(BinOp::Lt),
Some(TokenKind::LtEq) => Some(BinOp::LtEq),
Some(TokenKind::Gt) => Some(BinOp::Gt),
Some(TokenKind::GtEq) => Some(BinOp::GtEq),
_ => None,
};
if let Some(op) = op {
self.bump();
let rhs = self.parse_add()?;
if matches!(
self.peek_kind(),
Some(TokenKind::Lt)
| Some(TokenKind::LtEq)
| Some(TokenKind::Gt)
| Some(TokenKind::GtEq)
) {
let t = self.peek().unwrap();
return Err(CompileError::new(
"bynk.parse.non_associative",
t.span,
"comparison operators are non-associative; chained comparison is not allowed",
)
.with_note("split the comparison: `a < b && b < c` instead of `a < b < c`"));
}
let span = lhs.span.merge(rhs.span);
Ok(Expr {
kind: ExprKind::BinOp(op, Box::new(lhs), Box::new(rhs)),
span,
})
} else {
Ok(lhs)
}
}
fn parse_add(&mut self) -> Result<Expr, CompileError> {
let mut lhs = self.parse_mul()?;
let mut folds = 0usize;
let result = loop {
let op = match self.peek_kind() {
Some(TokenKind::Plus) => BinOp::Add,
Some(TokenKind::Minus) => BinOp::Sub,
_ => break Ok(lhs),
};
// v0.130: a `+`/`-` that begins a new line does not continue the
// expression — it starts a new construct. Without this, a negative
// literal pattern in the next match arm (`10` ⏎ `-2 => …`) would be
// mis-parsed as `10 - 2`. No existing program continues a binary
// expression with a leading operator on the next line.
if self.next_token_on_new_line(lhs.span) {
break Ok(lhs);
}
self.bump();
let rhs = match self.parse_mul() {
Ok(rhs) => rhs,
Err(e) => break Err(e),
};
let span = lhs.span.merge(rhs.span);
lhs = Expr {
kind: ExprKind::BinOp(op, Box::new(lhs), Box::new(rhs)),
span,
};
if let Err(e) = self.enter_chain_fold(&mut folds, lhs.span) {
break Err(e);
}
};
self.depth -= folds;
result
}
fn parse_mul(&mut self) -> Result<Expr, CompileError> {
let mut lhs = self.parse_unary()?;
let mut folds = 0usize;
let result = loop {
let op = match self.peek_kind() {
Some(TokenKind::Star) => BinOp::Mul,
Some(TokenKind::Slash) => BinOp::Div,
_ => break Ok(lhs),
};
self.bump();
let rhs = match self.parse_unary() {
Ok(rhs) => rhs,
Err(e) => break Err(e),
};
let span = lhs.span.merge(rhs.span);
lhs = Expr {
kind: ExprKind::BinOp(op, Box::new(lhs), Box::new(rhs)),
span,
};
if let Err(e) = self.enter_chain_fold(&mut folds, lhs.span) {
break Err(e);
}
};
self.depth -= folds;
result
}
fn parse_unary(&mut self) -> Result<Expr, CompileError> {
// `-`/`!` self-recurse here (`----1`, `!!!x`), and — like parentheses —
// that recursion bypasses `parse_expr`, so guard it directly on the
// shared budget or a long run overflows the parser's own stack (#714,
// sibling of #713). The pass-through to `parse_postfix` is not a nesting
// level and must not be counted.
let op = match self.peek_kind() {
Some(TokenKind::Minus) => UnaryOp::Neg,
Some(TokenKind::Bang) => UnaryOp::Not,
_ => return self.parse_postfix(),
};
let t = self.bump().unwrap();
self.enter_recursion("this expression")?;
let inner = self.parse_unary();
self.depth -= 1;
let inner = inner?;
let span = t.span.merge(inner.span);
Ok(Expr {
kind: ExprKind::UnaryOp(op, Box::new(inner)),
span,
})
}
/// Parse a primary expression and then apply postfix operators (`?`,
/// `.identifier` field access, `.identifier(args)` method call —
/// v0.2 §3.7).
///
/// A postfix chain is built iteratively into a left-nested receiver spine
/// (`a.b.c…`, `f()?.g()…`), so — like the associative operator chains — it
/// can grow an arbitrarily deep tree without recursing `parse_expr` and hit
/// the same downstream overflow (#714). The bounded-depth guard
/// ([`Parser::deepen_spine`]) runs in [`Parser::parse_postfix_inner`]; the
/// wrapper restores the shared `depth` budget wholesale, which — given the
/// several error-return paths inside — is cleaner than unwinding per fold.
fn parse_postfix(&mut self) -> Result<Expr, CompileError> {
let saved = self.depth;
let result = self.parse_postfix_inner();
self.depth = saved;
result
}
fn parse_postfix_inner(&mut self) -> Result<Expr, CompileError> {
let mut e = self.parse_primary()?;
loop {
match self.peek_kind() {
Some(TokenKind::Question) => {
let q = self.bump().unwrap();
let span = e.span.merge(q.span);
e = Expr {
kind: ExprKind::Question(Box::new(e)),
span,
};
self.deepen_spine(e.span)?;
}
Some(TokenKind::Dot) => {
let dot = self.bump().unwrap();
// `1.` — a numeric literal followed by `.` and no method
// name is a malformed float literal, not a member access
// (v0.21 §3). `1.toFloat()` stays a method call.
if matches!(e.kind, ExprKind::IntLit { .. } | ExprKind::FloatLit { .. })
&& self.peek_kind() != Some(TokenKind::Ident)
{
return Err(CompileError::new(
"bynk.parse.malformed_float_literal",
e.span.merge(dot.span),
"a float literal needs a digit on both sides of the `.`",
)
.with_note(format!(
"write `{lit}.0` (or call a method: `{lit}.round()`)",
lit = &self.source[e.span.range()]
)));
}
let member = self.expect_ident("after `.` in field access or method call")?;
// v0.22b: explicit type arguments on a method/static —
// `Json.decode[T](…)`. The v0.20b same-line-`[` rule
// applies: a `[` opening a new line is a list literal.
let type_args = if self.peek_kind() == Some(TokenKind::LBracket)
&& !self.next_token_on_new_line(member.span)
{
self.bump();
let mut type_args = Vec::new();
loop {
type_args.push(self.parse_type_ref("as a type argument")?);
if self.eat(TokenKind::Comma).is_none() {
break;
}
}
let close =
self.expect(TokenKind::RBracket, "to close the type-argument list")?;
if self.peek_kind() != Some(TokenKind::LParen) {
return Err(CompileError::new(
"bynk.parse.expected_token",
close.span,
"type arguments must be followed by an argument list — `name[T](…)`",
)
.with_note("a bare `name[T]` value form is reserved"));
}
type_args
} else {
Vec::new()
};
if self.peek_kind() == Some(TokenKind::LParen) {
// Method call: `receiver.method(args)`.
self.bump();
let mut args = Vec::new();
if self.peek_kind() != Some(TokenKind::RParen) {
args.push(self.parse_expr()?);
while self.eat(TokenKind::Comma).is_some() {
args.push(self.parse_expr()?);
}
}
let close = self
.expect(TokenKind::RParen, "to close the method-call argument list")?;
let span = e.span.merge(close.span);
e = Expr {
kind: ExprKind::MethodCall {
receiver: Box::new(e),
method: member,
type_args,
args,
},
span,
};
self.deepen_spine(e.span)?;
} else if let (ExprKind::IntLit { value: v, .. }, Some(unit)) =
(&e.kind, DurationUnit::from_name(&member.name))
{
// v0.86 (ADR 0112): `<int-literal>.<unit>` is a `Duration`
// literal, not a field access — an integer-literal
// receiver has no fields, so this is unambiguous.
let value = *v;
let span = e.span.merge(member.span);
let millis = value.checked_mul(unit.millis()).ok_or_else(|| {
CompileError::new(
"bynk.duration.literal_overflow",
span,
format!(
"the duration `{value}.{}` overflows the millisecond range",
unit.name()
),
)
})?;
e = Expr {
kind: ExprKind::DurationLit {
value,
unit,
millis,
},
span,
};
} else {
// Field access: `receiver.field`.
let span = e.span.merge(member.span);
e = Expr {
kind: ExprKind::FieldAccess {
receiver: Box::new(e),
field: member,
},
span,
};
self.deepen_spine(e.span)?;
}
}
_ => break,
}
}
Ok(e)
}
/// `Mock '[' type ']' ( '(' args? ')' )?` — v0.9.4 test-context value
/// construction. The leading `Val` identifier and the `[` lookahead have
/// already been confirmed by the caller; `kw_span` is the `Val` span.
fn parse_val_expr(&mut self, kw_span: Span) -> Result<Expr, CompileError> {
self.expect(TokenKind::LBracket, "after `Val`")?;
let type_ref = self.parse_type_ref("as the type argument of `Val[T]`")?;
let close_b = self.expect(TokenKind::RBracket, "to close `Val[T]`")?;
let mut args = Vec::new();
let mut end = close_b.span;
if self.peek_kind() == Some(TokenKind::LParen) {
self.bump();
if self.peek_kind() != Some(TokenKind::RParen) {
args.push(self.parse_expr()?);
while self.eat(TokenKind::Comma).is_some() {
args.push(self.parse_expr()?);
}
}
end = self
.expect(TokenKind::RParen, "to close the `Val` arguments")?
.span;
}
Ok(Expr {
kind: ExprKind::Val { type_ref, args },
span: kw_span.merge(end),
})
}
/// `Wire '(' expr ')'` — Slice C raw system-tier argument. The leading `Wire`
/// identifier and the `(` lookahead have already been confirmed by the caller;
/// `kw_span` is the `Wire` span. The inner expression's `String`-ness is a
/// checker concern, not the parser's.
fn parse_wire_expr(&mut self, kw_span: Span) -> Result<Expr, CompileError> {
self.expect(TokenKind::LParen, "after `Wire`")?;
let inner = self.parse_expr()?;
let close = self.expect(TokenKind::RParen, "to close `Wire(…)`")?;
Ok(Expr {
kind: ExprKind::Wire(Box::new(inner)),
span: kw_span.merge(close.span),
})
}
fn parse_primary(&mut self) -> Result<Expr, CompileError> {
let t = self.peek().ok_or_else(|| {
CompileError::new(
"bynk.parse.unexpected_eof",
self.eof_span(),
"expected an expression, found end of file",
)
})?;
match t.kind {
TokenKind::IntLit => {
self.bump();
let slice = self.slice(t.span);
// v0.142 (ADR 0166): parse the value from the separator-free form,
// but keep the as-written lexeme so `fmt` preserves the author's
// `_` grouping.
let n: i64 = crate::lexer::strip_digit_separators(slice)
.parse()
.map_err(|_| {
CompileError::new(
"bynk.lex.integer_overflow",
t.span,
format!("integer literal `{slice}` out of 64-bit range"),
)
})?;
Ok(Expr {
kind: ExprKind::IntLit {
value: n,
lexeme: slice.to_string(),
},
span: t.span,
})
}
TokenKind::FloatLit => {
self.bump();
let slice = self.slice(t.span);
// tokenize() already validated the separator-free form, so this
// parse cannot fail — but a silent NaN would corrupt the value
// if the two ever desync, so fail loudly instead (v0.142).
let value: f64 = crate::lexer::strip_digit_separators(slice)
.parse()
.map_err(|_| {
CompileError::new(
"bynk.lex.float_literal_overflow",
t.span,
format!("float literal `{slice}` does not parse"),
)
})?;
Ok(Expr {
kind: ExprKind::FloatLit {
value,
lexeme: slice.to_string(),
},
span: t.span,
})
}
// `.5` — a float literal missing its leading digit (v0.21 §3).
TokenKind::Dot
if matches!(
self.tokens.get(self.pos + 1).map(|t| t.kind),
Some(TokenKind::IntLit | TokenKind::FloatLit)
) =>
{
let lit = self.tokens[self.pos + 1];
Err(CompileError::new(
"bynk.parse.malformed_float_literal",
t.span.merge(lit.span),
"a float literal needs a digit on both sides of the `.`",
)
.with_note(format!("write `0.{}`", &self.source[lit.span.range()])))
}
TokenKind::StrLit => {
self.bump();
let s = parse_string_literal(self.slice(t.span), t.span)?;
Ok(Expr {
kind: ExprKind::StrLit(s),
span: t.span,
})
}
// An interpolated string `"… \(expr) …"` (v0.43). The lexer has
// already delimited the token and balanced its holes; here we
// split the chunks from the holes and parse each hole as a full
// expression (against the original source, so spans stay absolute).
TokenKind::InterpStr => {
self.bump();
let parts = self.parse_interp_parts(t.span)?;
Ok(Expr {
kind: ExprKind::InterpStr(parts),
span: t.span,
})
}
TokenKind::True => {
self.bump();
Ok(Expr {
kind: ExprKind::BoolLit(true),
span: t.span,
})
}
TokenKind::False => {
self.bump();
Ok(Expr {
kind: ExprKind::BoolLit(false),
span: t.span,
})
}
TokenKind::LParen => {
// v0.20a: `(params) => …` — a lambda. Token-level scan to the
// matching `)` then a one-token peek for `=>`; only paren
// depth matters (strings are single tokens).
if self.lambda_ahead() {
return self.parse_lambda();
}
self.bump();
// `()` — unit literal (v0.5).
if self.peek_kind() == Some(TokenKind::RParen) {
let close = self.bump().unwrap();
return Ok(Expr {
kind: ExprKind::UnitLit,
span: t.span.merge(close.span),
});
}
let inner = self.parse_expr()?;
let close =
self.expect(TokenKind::RParen, "to close the parenthesised expression")?;
Ok(Expr {
kind: ExprKind::Paren(Box::new(inner)),
span: t.span.merge(close.span),
})
}
// v0.22a: `Int.parse(…)` / `Float.parse(…)` — a numeric base-type
// keyword in static-receiver position. Only recognised when the
// next token is `.`, so a bare `Int` in expression position keeps
// the ordinary "expected an expression" error. Lowered to an
// Ident-shaped receiver; postfix builds the MethodCall and the
// resolver/checker own the static dispatch (like `List.empty()`).
// v0.86 (ADR 0112): `Duration.millis(…)` is the same static-receiver
// shape, so the `Duration` keyword joins `Int`/`Float` here. v0.90
// (ADR 0114): `Instant.fromEpochMillis(…)` joins them.
TokenKind::Int
| TokenKind::Float
| TokenKind::Duration
| TokenKind::Instant
| TokenKind::Bytes
if self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::Dot) =>
{
self.bump();
let name = self.slice(t.span).to_string();
Ok(Expr {
kind: ExprKind::Ident(Ident { name, span: t.span }),
span: t.span,
})
}
// `Effect.pure(value)` — wrap a synchronous value as `Effect[T]` (v0.5).
TokenKind::Effect => {
let kw = self.bump().unwrap();
self.expect(TokenKind::Dot, "after `Effect` in `Effect.pure(...)`")?;
let method = self.expect_ident("after `Effect.`")?;
if method.name != "pure" {
return Err(CompileError::new(
"bynk.parse.unknown_effect_method",
method.span,
format!(
"the only operation on `Effect` in expression position is `pure`, but got `{}`",
method.name
),
)
.with_note("use `Effect.pure(value)` to lift a synchronous value into `Effect[T]`"));
}
self.expect(TokenKind::LParen, "after `Effect.pure`")?;
let value = self.parse_expr()?;
let close =
self.expect(TokenKind::RParen, "to close the `Effect.pure` argument")?;
Ok(Expr {
kind: ExprKind::EffectPure(Box::new(value)),
span: kw.span.merge(close.span),
})
}
TokenKind::Ident => {
self.bump();
let ident = Ident {
name: self.slice(t.span).to_string(),
span: t.span,
};
// v0.9.4: `Val[T]` / `Val[T](args)` — test-context construction.
if ident.name == "Val" && self.peek_kind() == Some(TokenKind::LBracket) {
return self.parse_val_expr(ident.span);
}
// Slice C: `Wire(<String>)` — a raw, pre-validation argument to a
// `system`-tier service address. Recognised by the `Wire (` shape,
// like `Val[`, so an ordinary call to a user function named `Wire`
// is still possible only if it never sits in argument position at
// `system` (the checker restricts `Wire` to that use).
if ident.name == "Wire" && self.peek_kind() == Some(TokenKind::LParen) {
return self.parse_wire_expr(ident.span);
}
// v0.117: `trace(Cap.op)` — the observation escape hatch, a
// test-only builtin. Recognised by the `trace ( Ident . Ident )`
// shape so an ordinary `trace(value)` call is left untouched.
if ident.name == "trace"
&& self.peek_kind() == Some(TokenKind::LParen)
&& self.nth_kind(1) == Some(TokenKind::Ident)
&& self.nth_kind(2) == Some(TokenKind::Dot)
&& self.nth_kind(3) == Some(TokenKind::Ident)
&& self.nth_kind(4) == Some(TokenKind::RParen)
{
self.bump(); // `(`
let cap = self.expect_ident("as the capability name in `trace(Cap.op)`")?;
self.expect(TokenKind::Dot, "in `trace(Cap.op)`")?;
let op = self.expect_ident("as the operation name in `trace(Cap.op)`")?;
let close = self.expect(TokenKind::RParen, "to close `trace(Cap.op)`")?;
return Ok(Expr {
kind: ExprKind::Trace { cap, op },
span: ident.span.merge(close.span),
});
}
// v0.20a: explicit type arguments — `name[T, U](…)`.
// Bare `name[T]` without an argument list is reserved.
// v0.20b: the `[` must sit on the same line — a `[` opening
// a new line starts a list literal, not type application.
if self.peek_kind() == Some(TokenKind::LBracket)
&& !self.next_token_on_new_line(ident.span)
{
self.bump();
let mut type_args = Vec::new();
loop {
type_args.push(self.parse_type_ref("as a type argument")?);
if self.eat(TokenKind::Comma).is_none() {
break;
}
}
let close =
self.expect(TokenKind::RBracket, "to close the type-argument list")?;
if self.peek_kind() != Some(TokenKind::LParen) {
return Err(CompileError::new(
"bynk.parse.expected_token",
close.span,
"type arguments must be followed by an argument list — `name[T](…)`",
)
.with_note("a bare `name[T]` value form is reserved"));
}
self.bump();
let mut args = Vec::new();
if self.peek_kind() != Some(TokenKind::RParen) {
args.push(self.parse_expr()?);
while self.eat(TokenKind::Comma).is_some() {
args.push(self.parse_expr()?);
}
}
let close_paren =
self.expect(TokenKind::RParen, "to close the argument list")?;
return Ok(Expr {
kind: ExprKind::Call {
name: ident.clone(),
type_args,
args,
},
span: ident.span.merge(close_paren.span),
});
}
if self.peek_kind() == Some(TokenKind::LParen) {
self.bump();
let mut args = Vec::new();
if self.peek_kind() != Some(TokenKind::RParen) {
args.push(self.parse_expr()?);
while self.eat(TokenKind::Comma).is_some() {
args.push(self.parse_expr()?);
}
}
let close = self.expect(TokenKind::RParen, "to close the argument list")?;
Ok(Expr {
kind: ExprKind::Call {
name: ident.clone(),
type_args: Vec::new(),
args,
},
span: ident.span.merge(close.span),
})
} else if self.peek_kind() == Some(TokenKind::LBrace)
&& !self.no_record_literal
&& self.looks_like_record_construction()
{
// Record construction: `TypeName { field: value, ... }`.
// Suppressed on an `if`/`match` condition spine, where a
// trailing `ident {` opens the branch/arm block (#636).
self.parse_record_construction(ident)
} else {
Ok(Expr {
kind: ExprKind::Ident(ident.clone()),
span: ident.span,
})
}
}
// v0.1: `if cond { ... } else { ... }`.
TokenKind::If => self.parse_if_expr(),
// v0.1: `Ok(value)` and `Err(value)` result constructors.
TokenKind::Ok => self.parse_result_expr(true),
TokenKind::Err => self.parse_result_expr(false),
// v0.2: `Some(value)` / `None` / `match` / `self`.
TokenKind::Some => self.parse_some_expr(),
TokenKind::None => {
let tok = self.bump().unwrap();
Ok(Expr {
kind: ExprKind::None,
span: tok.span,
})
}
TokenKind::Match => self.parse_match_expr(),
TokenKind::Self_ => {
// `self` is parsed as a primary identifier with the literal
// name `self`; the resolver scopes it to method bodies.
let tok = self.bump().unwrap();
Ok(Expr {
kind: ExprKind::Ident(Ident {
name: "self".to_string(),
span: tok.span,
}),
span: tok.span,
})
}
// v0.5: bare record spread `{ ...base, field: value }`. Used by
// `commit { ... }` when the state type is implied.
TokenKind::LBrace => {
if self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::DotDotDot) {
self.parse_bare_record_spread()
} else {
Err(CompileError::new(
"bynk.parse.expected_expression",
t.span,
"expected an expression, found `{`",
)
.with_note(
"bare record-spread `{ ...base, ... }` is the only `{`-led expression in v0.5; for record construction, use `TypeName { ... }`",
))
}
}
// v0.20b: `[a, b, c]` — list literal. A leading `[` is
// unambiguous: type application (`name[T](…)`) is parsed as a
// postfix form on the callee identifier and never reaches here.
TokenKind::LBracket => {
let open = self.bump().unwrap();
let mut elems = Vec::new();
if self.peek_kind() != Some(TokenKind::RBracket) {
loop {
elems.push(self.parse_expr()?);
if self.eat(TokenKind::Comma).is_none() {
break;
}
// Trailing comma before the closing bracket.
if self.peek_kind() == Some(TokenKind::RBracket) {
break;
}
}
}
let close = self.expect(TokenKind::RBracket, "to close the list literal")?;
Ok(Expr {
kind: ExprKind::ListLit(elems),
span: open.span.merge(close.span),
})
}
_ => Err(CompileError::new(
"bynk.parse.expected_expression",
t.span,
format!("expected an expression, found {}", t.kind.describe()),
)),
}
}
/// Lookahead helper: distinguish record construction `T { ... }` from
/// a `T` ident followed by an unrelated block (which can happen inside
/// match-arm bodies or if-branches that take a block).
///
/// A record construction has either `Ident :` or `Ident ,` or `Ident }`
/// after the opening brace, or `}` immediately for the empty case.
/// A function body or match body never starts with `Ident :` or `Ident ,`
/// at this position because a `let` would come first as a statement.
///
/// The `Ident }` arm (a single shorthand field, `T { field }`) and the
/// empty `}` arm are genuinely ambiguous with a block whose whole tail is a
/// bare identifier and with an empty block — the shapes are identical to a
/// 2-token lookahead. That ambiguity is resolved by *context*, not here: an
/// `if`/`match` condition sets `no_record_literal` so the caller never
/// consults this helper on the condition spine (#636). This predicate is a
/// pure token-shape test and deliberately stays context-free.
fn looks_like_record_construction(&self) -> bool {
debug_assert_eq!(self.peek_kind(), Some(TokenKind::LBrace));
let a = self.tokens.get(self.pos + 1).map(|t| t.kind);
let b = self.tokens.get(self.pos + 2).map(|t| t.kind);
match (a, b) {
// `T {}` — empty record.
(Some(TokenKind::RBrace), _) => true,
// `T { ...base, ... }` — record spread (v0.5).
(Some(TokenKind::DotDotDot), _) => true,
// `T { field: ... }` or `T { field, ... }` — record construction.
(
Some(TokenKind::Ident),
Some(TokenKind::Colon) | Some(TokenKind::Comma) | Some(TokenKind::RBrace),
) => true,
_ => false,
}
}
/// Parse `TypeName { field: value, ... }` or `TypeName { ...base, field: value }`
/// once we've already consumed the type name and the next token is `{`.
fn parse_record_construction(&mut self, type_name: Ident) -> Result<Expr, CompileError> {
let open = self.expect(TokenKind::LBrace, "to open the record construction")?;
// v0.5: spread form `TypeName { ...base, field: value, ... }`.
if self.peek_kind() == Some(TokenKind::DotDotDot) {
self.bump();
let base = self.parse_expr()?;
let mut overrides = Vec::new();
while self.eat(TokenKind::Comma).is_some() {
if self.peek_kind() == Some(TokenKind::RBrace) {
break;
}
overrides.push(self.parse_field_init()?);
}
let close = self.expect(TokenKind::RBrace, "to close the record spread")?;
let span = type_name.span.merge(close.span);
return Ok(Expr {
kind: ExprKind::RecordSpread {
type_name: Some(type_name),
base: Box::new(base),
overrides,
},
span,
});
}
let mut fields = Vec::new();
while self.peek_kind() != Some(TokenKind::RBrace) {
fields.push(self.parse_field_init()?);
if self.eat(TokenKind::Comma).is_none() {
break;
}
}
let close = self.expect(TokenKind::RBrace, "to close the record construction")?;
let span = type_name.span.merge(close.span);
let _ = open;
Ok(Expr {
kind: ExprKind::RecordConstruction { type_name, fields },
span,
})
}
/// Parse `{ ...base, field: value, ... }` — the bare record-spread form.
fn parse_bare_record_spread(&mut self) -> Result<Expr, CompileError> {
let open = self.expect(TokenKind::LBrace, "to open the record spread")?;
self.expect(TokenKind::DotDotDot, "after `{` in a record spread")?;
let base = self.parse_expr()?;
let mut overrides = Vec::new();
while self.eat(TokenKind::Comma).is_some() {
if self.peek_kind() == Some(TokenKind::RBrace) {
break;
}
overrides.push(self.parse_field_init()?);
}
let close = self.expect(TokenKind::RBrace, "to close the record spread")?;
let span = open.span.merge(close.span);
Ok(Expr {
kind: ExprKind::RecordSpread {
type_name: None,
base: Box::new(base),
overrides,
},
span,
})
}
fn parse_field_init(&mut self) -> Result<FieldInit, CompileError> {
let name = self.expect_ident("as a record-field initialiser name")?;
// `name : expr` (full form) or `name ,` / `name }` (shorthand).
if self.eat(TokenKind::Colon).is_some() {
let value = self.parse_expr()?;
let span = name.span.merge(value.span);
Ok(FieldInit {
name,
value: Some(value),
span,
})
} else {
let span = name.span;
Ok(FieldInit {
name,
value: None,
span,
})
}
}
/// Parse a `Some(value)` expression.
fn parse_some_expr(&mut self) -> Result<Expr, CompileError> {
let kw = self.expect(TokenKind::Some, "to start a `Some` expression")?;
self.expect(TokenKind::LParen, "after `Some`")?;
let value = self.parse_expr()?;
let close = self.expect(TokenKind::RParen, "to close the `Some` argument")?;
Ok(Expr {
kind: ExprKind::Some(Box::new(value)),
span: kw.span.merge(close.span),
})
}
/// Parse a `match` expression: `match expr { pat => body, ... }`.
fn parse_match_expr(&mut self) -> Result<Expr, CompileError> {
let kw = self.expect(TokenKind::Match, "to start a match expression")?;
let discriminant = self.parse_cond_expr()?;
self.expect(TokenKind::LBrace, "to open the match-arm list")?;
let mut arms = Vec::new();
while self.peek_kind() != Some(TokenKind::RBrace) {
arms.push(self.parse_match_arm()?);
// No newline check here: the token stream carries no line info, and
// arms are terminated purely by each arm's own greedy parse plus the
// final `RBrace`. A trailing comma is optional and otherwise eaten.
let _ = self.eat(TokenKind::Comma);
}
let close = self.expect(TokenKind::RBrace, "to close the match-arm list")?;
if arms.is_empty() {
return Err(CompileError::new(
"bynk.parse.empty_match",
kw.span.merge(close.span),
"a `match` expression must have at least one arm",
));
}
Ok(Expr {
kind: ExprKind::Match {
discriminant: Box::new(discriminant),
arms,
},
span: kw.span.merge(close.span),
})
}
fn parse_match_arm(&mut self) -> Result<MatchArm, CompileError> {
// #472: a match arm's pattern is a top-level position — a trailing
// `where` is admitted here, but not on a nested payload pattern.
let pattern = self.parse_pattern_top()?;
// Optional `if <Bool-expr>` guard between the pattern and `=>` (ADR 0169).
// The guard sees the arm's bindings; it is unambiguous here because an
// arm-position `if` can only be a guard.
let guard = if self.peek_kind() == Some(TokenKind::If) {
self.bump();
Some(self.parse_expr()?)
} else {
None
};
self.expect(TokenKind::FatArrow, "after a match-arm pattern")?;
let body = if self.peek_kind() == Some(TokenKind::LBrace) {
MatchBody::Block(self.parse_block("to open the match-arm body")?)
} else {
MatchBody::Expr(self.parse_expr()?)
};
let span = pattern.span().merge(body.span());
Ok(MatchArm {
pattern,
guard,
body,
span,
})
}
/// Depth-guarded entry to the pattern grammar for a **nested** position —
/// a variant payload (`parse_pattern` -> `parse_pattern_binding` ->
/// `parse_pattern`), a third self-recursive descent independent of
/// `parse_expr`/`parse_type_ref`, so it needs its own guard or a nested
/// `Ok(Ok(…))` still overflows (#713). Folds `|` alternatives (#474), but
/// never checks for a trailing `where` (#472) — that suffix is admitted
/// only at a pattern's top level; see [`Parser::parse_pattern_top`].
fn parse_pattern(&mut self) -> Result<Pattern, CompileError> {
self.enter_recursion("this pattern")?;
let result = self.parse_pattern_or();
self.depth -= 1;
result
}
/// Depth-guarded entry to the pattern grammar for a **top-level**
/// position — a match arm's pattern, or `is`'s right-hand side. Folds `|`
/// alternatives first (#474, [`Parser::parse_pattern_or`]), then checks
/// the *whole* result for a trailing `where <refinement>` (#472) —
/// matching the tree-sitter grammar's `refined_pattern: seq(inner:
/// $._pattern, "where", refinement)`, where `$._pattern` already folds
/// `|` internally. So `(A | B) where P` is syntactically valid (and
/// semantically rejected by [`Parser::parse_pattern_where_suffix`]'s
/// `_`-only rule, the same as any other non-wildcard inner), but a
/// refined pattern can never be *one alternative* among others in an
/// outer `|`-chain — `match_arm`'s pattern field is a single
/// `choice($._pattern, $.refined_pattern)`, not a repetition, so
/// `(_ where P) | Some(x)` has no tree-sitter shape at all. Checking
/// `where` per-alternative (inside the fold) rather than once at the end
/// would admit exactly that unparseable shape — a real grammar/parser
/// conformance gap caught while resolving this merge (#827/#472 met
/// #474 for the first time here).
fn parse_pattern_top(&mut self) -> Result<Pattern, CompileError> {
self.enter_recursion("this pattern")?;
let result = self
.parse_pattern_or()
.and_then(|base| self.parse_pattern_where_suffix(base));
self.depth -= 1;
result
}
/// #474: `p₁ | p₂ | … | pₙ` — an or-pattern, left-associative over
/// [`Parser::parse_pattern_base`] (never a `where`-suffixed alternative —
/// see [`Parser::parse_pattern_top`]). Built as an iterative chain fold
/// (like `parse_or`'s fold over boolean `||`, lines 211-237) rather than a
/// recursive production, so a long chain costs one nesting level total
/// against the shared budget (#714) instead of one per alternative. `|`
/// is lexically distinct from `||` and not a valid expression operator,
/// so there is no ambiguity with the surrounding `is`/match-arm callers.
fn parse_pattern_or(&mut self) -> Result<Pattern, CompileError> {
let first = self.parse_pattern_base()?;
if self.peek_kind() != Some(TokenKind::Pipe) {
return Ok(first);
}
// Parenthesized grouping (`(A | B) | C`) is transparent — matching an
// or-pattern is associative regardless of how it's grouped — so an
// already-`Or` atom (from a parenthesized sub-pattern, see the
// `LParen` case in `parse_pattern_base`) splices its alternatives in
// rather than nesting, preserving the "an `Or`'s alternatives are
// always leaves" invariant every `Pattern::Or` consumer relies on.
let mut alts = flatten_or_alt(first);
let mut folds = 0usize;
let result = loop {
if self.peek_kind() != Some(TokenKind::Pipe) {
break Ok(());
}
self.bump();
match self.parse_pattern_base() {
Ok(p) => alts.extend(flatten_or_alt(p)),
Err(e) => break Err(e),
}
if let Err(e) = self.enter_chain_fold(&mut folds, alts.last().unwrap().span()) {
break Err(e);
}
};
self.depth -= folds;
result?;
let span = alts[0].span().merge(alts.last().unwrap().span());
Ok(Pattern::Or(alts, span))
}
/// After a (possibly `|`-chained) top-level pattern, an optional trailing
/// `where <refinement>` (#472) wraps the *whole* thing — a guard checked
/// at runtime. v1 admits only a wildcard `_` as the refined inner form;
/// any other inner shape (including an `Or`) is rejected
/// (`bynk.parse.refined_pattern_inner`) rather than silently accepted, so
/// the AST doesn't need reworking once binding/nested forms are designed.
fn parse_pattern_where_suffix(&mut self, base: Pattern) -> Result<Pattern, CompileError> {
if self.peek_kind() != Some(TokenKind::Where) {
return Ok(base);
}
self.bump();
let predicate = self.parse_refinement()?;
if !matches!(base, Pattern::Wildcard(_)) {
return Err(CompileError::new(
"bynk.parse.refined_pattern_inner",
base.span(),
"a refined pattern's inner form must be `_` in this version",
)
.with_note(
"write `_ where <predicate>`; binding a refined value is not yet supported",
));
}
let span = base.span().merge(predicate.span);
Ok(Pattern::Refined {
inner: Box::new(base),
predicate,
span,
})
}
fn parse_pattern_base(&mut self) -> Result<Pattern, CompileError> {
if let Some(t) = self.peek() {
// #474 §2.3.6: parens around a pattern are transparent grouping —
// `is (Held(...) | Confirmed(...))` — recommended for readability
// around an or-pattern but not otherwise meaningful (the spec calls
// them "syntactically optional": `is` already greedily parses one
// whole pattern, `|`-chain included, with or without them). Recurse
// through the full `parse_pattern` entry (which folds `|` via
// `parse_pattern_or`) so a nested `|` chain inside the parens is
// grouped as one alternative — but never `parse_pattern_top`, so
// a parenthesized pattern never admits a `where` suffix either
// (#472; matches tree-sitter's `paren_pattern: seq("(", $._pattern, ")")`,
// which likewise excludes `refined_pattern`).
if t.kind == TokenKind::LParen {
self.bump();
let inner = self.parse_pattern()?;
self.expect(TokenKind::RParen, "to close a parenthesized pattern")?;
return Ok(inner);
}
if t.kind == TokenKind::Underscore {
self.bump();
return Ok(Pattern::Wildcard(t.span));
}
// Literal patterns (v0.130 §2.3.4): `31`, `"english"`, `true`, and a
// leading unary minus on an integer literal (`-1`). A closed set
// (ADR 0001) — no `Float`, no `()`.
match t.kind {
TokenKind::IntLit | TokenKind::StrLit | TokenKind::True | TokenKind::False => {
return self.parse_literal_pattern();
}
TokenKind::Minus
if self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::IntLit) =>
{
return self.parse_literal_pattern();
}
_ => {}
}
// Built-in variant patterns: `Ok(...)`, `Err(...)`, `Some(...)`, `None`.
match t.kind {
TokenKind::Ok | TokenKind::Err | TokenKind::Some | TokenKind::None => {
return self.parse_variant_pattern_builtin();
}
_ => {}
}
}
// Otherwise: an ident-led pattern. Possibly qualified as `Type.Variant`.
let first = self.expect_ident("as a match-arm pattern")?;
let (type_name, variant) = if self.eat(TokenKind::Dot).is_some() {
let v = self.expect_ident("after `.` in a qualified pattern")?;
(Some(first), v)
} else {
(None, first)
};
// A bare lowercase identifier with no qualifier and no payload list is a
// binding (ADR 0169) — `Some(user)`, or a top-level `n if n > 0`. An
// uppercase-led identifier (or one carrying a payload list) is a variant
// constructor. Built-in variants are keyword tokens, handled above.
let has_payload = self.peek_kind() == Some(TokenKind::LParen);
if type_name.is_none()
&& !has_payload
&& variant
.name
.chars()
.next()
.is_some_and(|c| c.is_ascii_lowercase())
{
return Ok(Pattern::Binding(variant));
}
let mut bindings = Vec::new();
let mut end_span = variant.span;
if has_payload {
self.bump();
if self.peek_kind() != Some(TokenKind::RParen) {
bindings.push(self.parse_pattern_binding()?);
while self.eat(TokenKind::Comma).is_some() {
bindings.push(self.parse_pattern_binding()?);
}
}
let close = self.expect(TokenKind::RParen, "to close the pattern binding list")?;
end_span = close.span;
}
let start_span = type_name.as_ref().map(|t| t.span).unwrap_or(variant.span);
Ok(Pattern::Variant {
type_name,
variant,
bindings,
span: start_span.merge(end_span),
})
}
/// Parse a literal pattern (v0.130 §2.3.4): `31`, `-1`, `"english"`,
/// `true`/`false`. The caller has already confirmed the leading token is one
/// of these forms.
fn parse_literal_pattern(&mut self) -> Result<Pattern, CompileError> {
// Optional leading `-` on an integer literal (ADR 0001).
let neg = self.eat(TokenKind::Minus);
let t = self.bump().expect("literal-pattern lead token");
let (value, end_span) = match t.kind {
TokenKind::IntLit => {
let slice = self.slice(t.span);
// v0.142 (ADR 0166): parse from the separator-free form.
let mut n: i64 = crate::lexer::strip_digit_separators(slice)
.parse()
.map_err(|_| {
CompileError::new(
"bynk.lex.integer_overflow",
t.span,
format!("integer literal `{slice}` out of 64-bit range"),
)
})?;
if neg.is_some() {
n = -n;
}
(LiteralValue::Int(n), t.span)
}
TokenKind::StrLit => {
let s = parse_string_literal(self.slice(t.span), t.span)?;
(LiteralValue::Str(s), t.span)
}
TokenKind::True => (LiteralValue::Bool(true), t.span),
TokenKind::False => (LiteralValue::Bool(false), t.span),
_ => unreachable!("parse_literal_pattern called on a non-literal token"),
};
let span = neg.map(|m| m.span).unwrap_or(t.span).merge(end_span);
Ok(Pattern::Literal { value, span })
}
/// Parse a built-in variant pattern (Ok/Err/Some/None) — these are
/// keyword tokens rather than Idents so they need special handling.
fn parse_variant_pattern_builtin(&mut self) -> Result<Pattern, CompileError> {
let t = self.bump().unwrap();
let variant_name = match t.kind {
TokenKind::Ok => "Ok",
TokenKind::Err => "Err",
TokenKind::Some => "Some",
TokenKind::None => "None",
_ => unreachable!(),
};
let variant = Ident {
name: variant_name.to_string(),
span: t.span,
};
let mut bindings = Vec::new();
let mut end_span = variant.span;
if self.peek_kind() == Some(TokenKind::LParen) {
self.bump();
if self.peek_kind() != Some(TokenKind::RParen) {
bindings.push(self.parse_pattern_binding()?);
while self.eat(TokenKind::Comma).is_some() {
bindings.push(self.parse_pattern_binding()?);
}
}
let close = self.expect(TokenKind::RParen, "to close the pattern binding list")?;
end_span = close.span;
}
let variant_span = variant.span;
Ok(Pattern::Variant {
type_name: None,
variant,
bindings,
span: variant_span.merge(end_span),
})
}
fn parse_pattern_binding(&mut self) -> Result<PatternBinding, CompileError> {
// Allowed shapes (ADR 0169 — each field position is a full sub-pattern):
// `_` positional wildcard
// `name` positional binding
// `Ok(x)` / `Pending` positional nested pattern
// `field: <pattern>` named (where <pattern> is any of the above)
// A named field is a lowercase-style ident immediately followed by `:`;
// everything else is a positional sub-pattern.
if let Some(t) = self.peek()
&& t.kind == TokenKind::Ident
&& self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::Colon)
{
let field = self.expect_ident("as a named pattern field")?;
self.expect(TokenKind::Colon, "after a named pattern field")?;
let pattern = self.parse_pattern()?;
let span = field.span.merge(pattern.span());
return Ok(PatternBinding {
kind: PatternBindingKind::Named { field, pattern },
span,
});
}
let pattern = self.parse_pattern()?;
let span = pattern.span();
Ok(PatternBinding {
kind: PatternBindingKind::Positional { pattern },
span,
})
}
/// Parse `if expr block 'else' (if-expr | block)` (v0.1 §3.2).
/// Both branches are represented as Blocks; an `else if` chain becomes a
/// Block whose tail is another If expression.
fn parse_if_expr(&mut self) -> Result<Expr, CompileError> {
let kw = self.expect(TokenKind::If, "to start an if expression")?;
let cond = self.parse_cond_expr()?;
let then_block = self.parse_block("to open the `if` branch")?;
// v0.146 (ADR 0170): `else` is optional. A missing `else` defaults to a
// synthesised `{ () }` (unit) else-branch — legal only when the
// then-branch is itself unit (`()` / `Effect[()]`), which the checker
// enforces (`bynk.types.if_without_else_requires_unit`). The synthetic
// block is marked `implicit_tail` so the formatter round-trips the
// else-less form. A valued `if` still requires an explicit `else`.
let else_block = if self.eat(TokenKind::Else).is_some() {
if self.peek_kind() == Some(TokenKind::If) {
// `else if ...` desugars to `else { if ... }`.
let inner = self.parse_if_expr()?;
let span = inner.span;
Block {
statements: Vec::new(),
tail: Box::new(inner),
span,
tail_leading_comments: Vec::new(),
implicit_tail: false,
}
} else {
self.parse_block("to open the `else` branch")?
}
} else {
Block {
statements: Vec::new(),
tail: Box::new(Expr {
kind: ExprKind::UnitLit,
span: then_block.span,
}),
span: then_block.span,
tail_leading_comments: Vec::new(),
implicit_tail: true,
}
};
let span = kw.span.merge(else_block.span);
Ok(Expr {
kind: ExprKind::If {
cond: Box::new(cond),
then_block: Box::new(then_block),
else_block: Box::new(else_block),
},
span,
})
}
/// Parse `Ok(value)` (when `ok` is true) or `Err(error)` (when `ok` is false).
fn parse_result_expr(&mut self, ok: bool) -> Result<Expr, CompileError> {
let kw = if ok {
self.expect(TokenKind::Ok, "to start an `Ok` expression")?
} else {
self.expect(TokenKind::Err, "to start an `Err` expression")?
};
self.expect(
TokenKind::LParen,
if ok { "after `Ok`" } else { "after `Err`" },
)?;
let value = self.parse_expr()?;
let close = self.expect(
TokenKind::RParen,
if ok {
"to close the `Ok` argument"
} else {
"to close the `Err` argument"
},
)?;
let span = kw.span.merge(close.span);
let kind = if ok {
ExprKind::Ok(Box::new(value))
} else {
ExprKind::Err(Box::new(value))
};
Ok(Expr { kind, span })
}
/// Split an `InterpStr` token (covering the whole `"…"`) into its
/// alternating chunks and holes, parsing each hole as a full expression.
/// (v0.43.)
fn parse_interp_parts(&mut self, span: Span) -> Result<Vec<InterpPart>, CompileError> {
let segments = crate::lexer::split_interp(self.source, span)?;
let mut parts = Vec::with_capacity(segments.len());
for segment in segments {
match segment {
crate::lexer::InterpSegment::Chunk(text) => parts.push(InterpPart::Chunk(text)),
crate::lexer::InterpSegment::Hole(hole) => {
parts.push(InterpPart::Hole(Box::new(self.parse_hole_expr(hole)?)));
}
}
}
Ok(parts)
}
/// Parse the body of one interpolation hole (`\(expr)`) — the bytes spanned
/// by `hole` — as a single expression. The hole source is re-lexed and its
/// token spans are rebased to absolute positions in the full source, so
/// diagnostics and the (later) LSP point at the real location. (v0.43.)
fn parse_hole_expr(&mut self, hole: Span) -> Result<Expr, CompileError> {
let src = &self.source[hole.range()];
if src.trim().is_empty() {
return Err(CompileError::new(
"bynk.parse.empty_interpolation",
hole,
"empty interpolation hole",
)
.with_note("`\\(…)` must contain an expression"));
}
// A lex error here carries spans relative to `src` (the hole substring);
// rebase them into the full source before propagating, mirroring the
// success-path token rebasing below. Otherwise the diagnostic points at
// the file's opening bytes and can split a multibyte char. (#716.)
let mut tokens = crate::lexer::tokenize(src).map_err(|e| e.offset_spans(hole.start))?;
for token in &mut tokens {
token.span = token.span.offset(hole.start);
}
let (content, trivia) = split_trivia(&tokens, self.source);
let mut warnings = Vec::new();
let mut sub = Parser::new(&content, self.source, trivia, &mut warnings);
let expr = sub.parse_expr()?;
if let Some(extra) = sub.peek() {
return Err(CompileError::new(
"bynk.parse.extra_tokens",
extra.span,
format!(
"unexpected {} after the interpolation expression",
extra.kind.describe()
),
)
.with_note("an interpolation hole `\\(…)` holds a single expression"));
}
Ok(expr)
}
}
/// #474: the alternatives `p` contributes to an enclosing or-pattern — its own
/// alternatives if it is already `Pattern::Or` (a parenthesized sub-or-pattern
/// being spliced in), otherwise itself alone. Keeps every `Pattern::Or` flat.
fn flatten_or_alt(p: Pattern) -> Vec<Pattern> {
match p {
Pattern::Or(alts, _) => alts,
p => vec![p],
}
}