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
//! The MiruScriptX parser: turns a token stream into an AST.
//!
//! Statements are parsed with straightforward recursive descent. Expressions
//! use a small Pratt (precedence-climbing) parser: [`Parser::parse_binary`]
//! drives infix operators by binding power, while prefix operators, calls, and
//! indexing are handled by [`Parser::unary`] and [`Parser::postfix`].
use crate::ast::{BinaryOp, Expr, ExprKind, LogicalOp, Stmt, StmtKind, UnaryOp};
use crate::token::{Token, TokenKind};
use crate::MiruError;
pub struct Parser {
tokens: Vec<Token>,
pos: usize,
loop_depth: usize,
depth: usize,
}
impl Parser {
/// How deeply one program may nest.
///
/// Without a limit, deep source overflows the Rust stack and aborts the
/// process: no message, no caret, and nothing `try` can catch.
///
/// This counts **how far the parser calls itself**. `[[[ .. ]]]` descends
/// one frame per bracket and overflows on the way down, before a tree
/// exists to measure. [`Parser::enter`] counts it.
///
/// A tall tree is the other half of the same defect and has its own limit,
/// [`Parser::MAX_HEIGHT`], because it costs a different amount of stack.
/// One does not imply the other: `1 + 1 + 1 ..` is one frame and one loop
/// however long it runs, and nesting builds no tall tree at all.
///
/// The figure comes from the tightest configuration measured, not the
/// roomiest, because the promise is that deep source reports rather than
/// aborts, and a promise that holds only on the main thread is not one.
///
/// It is measured against a stack this project chooses rather than one it
/// inherits. `miru` starts a thread with 64 MiB (`STACK_SIZE` in
/// `src/main.rs`) and the WebAssembly build links a 16 MiB shadow stack
/// (`.cargo/config.toml`), because a language whose grammar depends on
/// which thread it runs on does not have a grammar. Nested maps, the most
/// expensive construct, survived to:
///
/// | Build | Depth |
/// | ---------------------- | ------ |
/// | Debug, 64 MiB thread | 3000 |
/// | Release, 64 MiB thread | 12000+ |
///
/// 1000 leaves a margin of three on the tightest of those.
///
/// It also clears what 1.0 managed. 1.0 had no limit, so it simply aborted
/// wherever the stack ran out, and the release binary reached 917 levels of
/// bracket nesting on the 1 MiB shadow stack the playground had. 1000 is
/// above that, so no program that nested successfully anywhere in 1.0 is
/// refused here.
///
/// **An embedder calling the library directly gets its own thread's stack**,
/// which is 2 MiB by default and will not support this limit. The `miru`
/// binary and the playground both provide the stack; anything else has to
/// ask for it. `docs/stability.md` says so, and the deep tests in
/// `tests/golden.rs` spawn a thread rather than assume one.
///
/// For scale, the deepest nesting in this project's own example programs is
/// four. Before 1.1 there was no limit at all, and the process aborted
/// somewhere past 600. [`crate::value::Value`] limits nesting at 256 for
/// comparing and printing, which is a different figure for a different
/// thing: a loop can build a value far deeper than the source that made it.
pub const MAX_NESTING: usize = 1000;
/// How tall the tree for one expression may get.
///
/// `1 + 1 + 1 ..` is one parser frame and one loop however long it runs, so
/// [`Parser::MAX_NESTING`] never sees it, but it leaves a tree as tall as
/// the chain is long. Nothing overflows until something walks that tree:
/// the compiler, the formatter, or `miru disasm`. [`Expr::height`] carries
/// the figure and [`Parser::checked`] tests it as each level is added,
/// rather than on the finished expression, because a tree too tall to walk
/// was until 1.1 also too tall to release, and rejecting it after building
/// it aborted in the destructor instead.
///
/// **This is ten times [`Parser::MAX_NESTING`] because height is ten times
/// cheaper.** Both were one figure at first, and 1000 was right for nesting
/// and much too strict for a chain. Measured on this project's own release
/// binary, with the height check lifted, on a 16 MiB stack, which is the
/// smallest of any build that ships:
///
/// | Walk | Height reached |
/// | -------------- | -------------- |
/// | `miru run` | 80000 |
/// | `miru disasm` | 80000 |
/// | `miru fmt` | 61000 |
///
/// The formatter is the binding one, so 10000 keeps a margin of six there.
/// Releasing the tree used to be a fourth walk and the tightest of them;
/// it is iterative as of 1.1 and no longer constrains this.
///
/// The lower bound comes from 1.0 rather than from the stack. 1.0 had no
/// limit and its release binary summed 4959 terms on the 1 MiB stack the
/// playground had, and 40255 on an 8 MiB main thread. A program has to
/// clear the first of those to have worked everywhere 1.0 ran, and 10000
/// is twice it. Between 10000 and 40255 sits a band that 1.0 ran on a large
/// native stack and never in a browser; that is refused here, and a chain
/// of ten thousand terms is not something a person writes.
pub const MAX_HEIGHT: usize = 10_000;
/// Parse a full program (a list of statements) from a token stream.
pub fn parse(tokens: Vec<Token>) -> Result<Vec<Stmt>, MiruError> {
let mut parser = Parser {
tokens,
pos: 0,
loop_depth: 0,
depth: 0,
};
parser.program()
}
/// Count one level of nesting, and refuse past the limit.
///
/// Every `enter` has a matching `leave` on the path that succeeds. On the
/// path that fails the count is left as it is, because an error ends the
/// parse: `Parser::parse` returns it, and this parser is never asked for
/// anything else.
fn enter(&mut self, line: usize, column: usize) -> Result<(), MiruError> {
self.depth += 1;
if self.depth > Parser::MAX_NESTING {
return Err(MiruError::with_column(
line,
column,
"the program is nested too deeply".to_string(),
));
}
Ok(())
}
fn leave(&mut self) {
self.depth -= 1;
}
/// Refuse an expression that is too tall to walk.
///
/// Called on each level as it is added, never on the finished expression.
///
/// The message is not the one [`Parser::enter`] gives, because this is not
/// the same fault. What trips this is a chain: a sum of thousands of terms,
/// or `a[0][0][0] ..`, where nothing is nested inside anything and telling
/// the reader it is would send them looking for brackets that are not
/// there.
fn checked(&self, expr: Expr) -> Result<Expr, MiruError> {
if expr.height > Parser::MAX_HEIGHT {
return Err(MiruError::with_column(
expr.line,
expr.column,
"the expression is too long".to_string(),
));
}
Ok(expr)
}
fn program(&mut self) -> Result<Vec<Stmt>, MiruError> {
let mut statements = Vec::new();
self.skip_newlines();
while !self.is_at_end() {
let stmt = self.statement()?;
if !Parser::ends_with_block(&stmt.kind) {
self.consume_terminator()?;
}
self.skip_newlines();
statements.push(stmt);
}
Ok(statements)
}
// --- Statements -------------------------------------------------------
/// A block holds statements, and a statement can open a block, so `if`
/// inside `if` inside `if` descends here as far as the source says to.
fn statement(&mut self) -> Result<Stmt, MiruError> {
let (line, column) = (self.peek().line, self.peek().column);
self.enter(line, column)?;
let statement = self.statement_kind(line);
self.leave();
statement
}
fn statement_kind(&mut self, line: usize) -> Result<Stmt, MiruError> {
match self.peek_kind() {
TokenKind::Import => self.import_statement(line),
TokenKind::Let => self.let_statement(line),
TokenKind::Return => self.return_statement(line),
TokenKind::If => self.if_statement(line),
TokenKind::While => self.while_statement(line),
TokenKind::For => self.for_statement(line),
TokenKind::Break => self.break_statement(line),
TokenKind::Continue => self.continue_statement(line),
TokenKind::Fn if matches!(self.peek_at_kind(1), Some(TokenKind::Ident(_))) => {
self.function_statement(line)
}
_ => self.expr_or_assign_statement(line),
}
}
/// `import "./math.miru" as math`.
///
/// The path is a string literal rather than a bare word so it can hold any
/// filename, and the alias is required rather than inferred from it: a
/// reader should be able to tell where a name came from without working out
/// what a path would have been shortened to.
fn import_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance();
let literal = self.peek().clone();
let spec = match &literal.kind {
TokenKind::Str(spec) => spec.clone(),
other => {
return Err(MiruError::with_column(
literal.line,
literal.column,
format!(
"expected a quoted path after 'import' but found {}",
other.describe()
),
))
}
};
self.advance();
self.expect(TokenKind::As, "after an import path")?;
let name = self.peek().clone();
let alias = match &name.kind {
TokenKind::Ident(alias) => alias.clone(),
other => {
return Err(MiruError::with_column(
name.line,
name.column,
format!("expected a name after 'as' but found {}", other.describe()),
))
}
};
self.advance();
Ok(Stmt::new(
StmtKind::Import {
spec,
alias,
column: literal.column,
},
line,
))
}
fn let_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'let'
let name = self.expect_identifier("after 'let'")?;
self.expect(TokenKind::Assign, "after the variable name")?;
let value = self.expression()?;
Ok(Stmt::new(StmtKind::Let { name, value }, line))
}
fn return_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'return'
if self.is_statement_end() {
Ok(Stmt::new(StmtKind::Return(None), line))
} else {
let value = self.expression()?;
Ok(Stmt::new(StmtKind::Return(Some(value)), line))
}
}
fn if_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'if'
let condition = self.expression()?;
let then_branch = self.block()?;
// Allow `else` either on the same line as the closing brace or on a
// line of its own. We look past newlines and only commit to consuming
// them if an `else` actually follows.
let saved = self.pos;
self.skip_newlines();
let else_branch = if self.check(&TokenKind::Else) {
self.advance(); // 'else'
if self.check(&TokenKind::If) {
let nested_line = self.peek().line;
Some(vec![self.if_statement(nested_line)?])
} else {
Some(self.block()?)
}
} else {
self.pos = saved;
None
};
Ok(Stmt::new(
StmtKind::If {
condition,
then_branch,
else_branch,
},
line,
))
}
fn while_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'while'
let condition = self.expression()?;
let body = self.loop_body()?;
Ok(Stmt::new(StmtKind::While { condition, body }, line))
}
fn for_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'for'
let name = self.expect_identifier("after 'for'")?;
self.expect(TokenKind::In, "after the loop variable")?;
let iterable = self.expression()?;
let body = self.loop_body()?;
Ok(Stmt::new(
StmtKind::For {
name,
iterable,
body,
},
line,
))
}
fn function_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
self.advance(); // 'fn'
let name = self.expect_identifier("after 'fn'")?;
let params = self.parse_params()?;
let body = self.function_body()?;
Ok(Stmt::new(StmtKind::Function { name, params, body }, line))
}
fn expr_or_assign_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
let expr = self.expression()?;
if self.check(&TokenKind::Assign) {
self.advance(); // '='
match &expr.kind {
ExprKind::Identifier(_) | ExprKind::Index { .. } | ExprKind::Field { .. } => {}
_ => {
return Err(MiruError::with_column(
expr.line,
expr.column,
"invalid assignment target (only variables, elements, and fields can be assigned to)",
));
}
}
let value = self.expression()?;
Ok(Stmt::new(
StmtKind::Assign {
target: expr,
value,
},
line,
))
} else {
Ok(Stmt::new(StmtKind::Expr(expr), line))
}
}
fn block(&mut self) -> Result<Vec<Stmt>, MiruError> {
self.expect(TokenKind::LBrace, "to start a block")?;
let mut statements = Vec::new();
self.skip_newlines();
while !self.check(&TokenKind::RBrace) && !self.is_at_end() {
let stmt = self.statement()?;
// Only `block` can tell that a statement is nested, and an import is
// a file-level thing: one is resolved before the file compiles, so
// an import inside a branch or a loop could not mean what it looks
// like it means.
if let StmtKind::Import { column, .. } = stmt.kind {
return Err(MiruError::with_column(
stmt.line,
column,
"import must appear at the top level of a file",
));
}
if !Parser::ends_with_block(&stmt.kind) {
self.consume_terminator()?;
}
self.skip_newlines();
statements.push(stmt);
}
self.expect(TokenKind::RBrace, "to close a block")?;
Ok(statements)
}
fn parse_params(&mut self) -> Result<Vec<String>, MiruError> {
self.expect(TokenKind::LParen, "to start a parameter list")?;
let mut params = Vec::new();
if !self.check(&TokenKind::RParen) {
loop {
params.push(self.expect_identifier("as a parameter name")?);
if self.check(&TokenKind::Comma) {
self.advance();
if self.check(&TokenKind::RParen) {
break; // tolerate a trailing comma
}
} else {
break;
}
}
}
self.expect(TokenKind::RParen, "to close the parameter list")?;
Ok(params)
}
fn break_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
let column = self.peek().column;
self.advance(); // 'break'
if self.loop_depth == 0 {
return Err(MiruError::with_column(
line,
column,
"break outside of a loop",
));
}
Ok(Stmt::new(StmtKind::Break, line))
}
fn continue_statement(&mut self, line: usize) -> Result<Stmt, MiruError> {
let column = self.peek().column;
self.advance(); // 'continue'
if self.loop_depth == 0 {
return Err(MiruError::with_column(
line,
column,
"continue outside of a loop",
));
}
Ok(Stmt::new(StmtKind::Continue, line))
}
/// Parse a loop body, marking that `break` and `continue` are allowed inside.
fn loop_body(&mut self) -> Result<Vec<Stmt>, MiruError> {
self.loop_depth += 1;
let body = self.block();
self.loop_depth -= 1;
body
}
/// Parse a function body. A `break` or `continue` cannot target a loop
/// outside the function, so loop depth is reset while parsing the body.
fn function_body(&mut self) -> Result<Vec<Stmt>, MiruError> {
let saved = self.loop_depth;
self.loop_depth = 0;
let body = self.block();
self.loop_depth = saved;
body
}
// --- Expressions (Pratt) ---------------------------------------------
fn expression(&mut self) -> Result<Expr, MiruError> {
// `try` binds looser than every operator, so `try a / b` covers the
// division rather than just `a`. It lives here rather than in `unary`
// for exactly that reason: a unary operator binds tighter than
// multiplication, and this has to bind looser than all of them.
//
// It nests, so `try try f()` parses, though the inner one makes the
// outer one unreachable.
if self.check(&TokenKind::Try) {
let token = self.advance().clone();
// Charged here rather than left to `unary`: this arm calls itself,
// so `try try try` never reaches `unary` more than once.
self.enter(token.line, token.column)?;
let inner = self.expression();
self.leave();
return Ok(Expr::new(
ExprKind::Try(Box::new(inner?)),
token.line,
token.column,
));
}
self.parse_binary(1)
}
fn parse_binary(&mut self, min_bp: u8) -> Result<Expr, MiruError> {
let mut left = self.unary()?;
// Each pass wraps everything parsed so far, so the tree grows one level
// per operator while this loop stays at a single Rust frame however far
// it runs. Counting the recursion here would see nothing: `1 + 1 + 1
// ...` parses happily and overflows whoever walks the result instead.
while let Some(bp) = Parser::infix_binding_power(self.peek_kind()) {
if bp < min_bp {
break;
}
let op = self.advance();
let right = self.parse_binary(bp + 1)?;
left = self.checked(Parser::make_infix(&op, left, right))?;
}
Ok(left)
}
fn infix_binding_power(kind: &TokenKind) -> Option<u8> {
match kind {
TokenKind::Or => Some(1),
TokenKind::And => Some(2),
TokenKind::Eq | TokenKind::NotEq => Some(3),
TokenKind::Lt | TokenKind::Gt | TokenKind::LtEq | TokenKind::GtEq => Some(4),
TokenKind::Plus | TokenKind::Minus => Some(5),
TokenKind::Star | TokenKind::Slash | TokenKind::Percent => Some(6),
_ => None,
}
}
fn make_infix(op: &Token, left: Expr, right: Expr) -> Expr {
let left = Box::new(left);
let right = Box::new(right);
let kind = match &op.kind {
TokenKind::Or => ExprKind::Logical {
op: LogicalOp::Or,
left,
right,
},
TokenKind::And => ExprKind::Logical {
op: LogicalOp::And,
left,
right,
},
_ => {
let binary_op = match &op.kind {
TokenKind::Eq => BinaryOp::Equal,
TokenKind::NotEq => BinaryOp::NotEqual,
TokenKind::Lt => BinaryOp::Less,
TokenKind::Gt => BinaryOp::Greater,
TokenKind::LtEq => BinaryOp::LessEqual,
TokenKind::GtEq => BinaryOp::GreaterEqual,
TokenKind::Plus => BinaryOp::Add,
TokenKind::Minus => BinaryOp::Subtract,
TokenKind::Star => BinaryOp::Multiply,
TokenKind::Slash => BinaryOp::Divide,
TokenKind::Percent => BinaryOp::Modulo,
_ => unreachable!("make_infix called with a non-operator token"),
};
ExprKind::Binary {
op: binary_op,
left,
right,
}
}
};
Expr::new(kind, op.line, op.column)
}
/// Every expression passes through here on its way down to `primary`, so
/// one count covers a nested array, a nested map, a parenthesised group, a
/// call argument, and an index, as well as the `-` and `!` chains that call
/// this function directly.
fn unary(&mut self) -> Result<Expr, MiruError> {
let (line, column) = (self.peek().line, self.peek().column);
self.enter(line, column)?;
let expr = self.unary_operand();
self.leave();
expr
}
fn unary_operand(&mut self) -> Result<Expr, MiruError> {
match self.peek_kind() {
TokenKind::Minus => {
let op = self.advance();
let operand = self.unary()?;
Ok(Expr::new(
ExprKind::Unary {
op: UnaryOp::Negate,
operand: Box::new(operand),
},
op.line,
op.column,
))
}
TokenKind::Bang => {
let op = self.advance();
let operand = self.unary()?;
Ok(Expr::new(
ExprKind::Unary {
op: UnaryOp::Not,
operand: Box::new(operand),
},
op.line,
op.column,
))
}
_ => self.postfix(),
}
}
fn postfix(&mut self) -> Result<Expr, MiruError> {
let mut expr = self.primary()?;
// A call, a field, or an index wraps what came before it, so `a[0][0]`
// and `a.b.c` grow the tree without growing this loop. Tested the same
// way the operator spine in `parse_binary` is, and for the same reason.
loop {
match self.peek_kind() {
TokenKind::LParen => {
self.advance();
let arguments = self.parse_arguments()?;
let (line, column) = (expr.line, expr.column);
expr = self.checked(Expr::new(
ExprKind::Call {
callee: Box::new(expr),
arguments,
},
line,
column,
))?;
}
TokenKind::Dot => {
self.advance();
// The access carries the *field's* position rather than the
// target's, following what Call and Index do: an expression
// reports at the part most likely to be at fault, which for
// `config.tiemout` is the name. The target's position rides
// along in the opcode's operand byte.
let field = self.peek().clone();
let name = match &field.kind {
TokenKind::Ident(name) => name.clone(),
other => {
return Err(MiruError::with_column(
field.line,
field.column,
format!(
"expected a field name after '.' but found {}",
other.describe()
),
))
}
};
self.advance();
expr = self.checked(Expr::new(
ExprKind::Field {
target: Box::new(expr),
name,
},
field.line,
field.column,
))?;
}
TokenKind::LBracket => {
self.advance();
let index = self.expression()?;
self.expect(TokenKind::RBracket, "to close an index")?;
let (line, column) = (expr.line, expr.column);
expr = self.checked(Expr::new(
ExprKind::Index {
target: Box::new(expr),
index: Box::new(index),
},
line,
column,
))?;
}
_ => break,
}
}
Ok(expr)
}
fn parse_arguments(&mut self) -> Result<Vec<Expr>, MiruError> {
let mut arguments = Vec::new();
if !self.check(&TokenKind::RParen) {
loop {
arguments.push(self.expression()?);
if self.check(&TokenKind::Comma) {
self.advance();
if self.check(&TokenKind::RParen) {
break; // tolerate a trailing comma
}
} else {
break;
}
}
}
self.expect(TokenKind::RParen, "to close the call")?;
Ok(arguments)
}
fn primary(&mut self) -> Result<Expr, MiruError> {
let token = self.peek().clone();
let line = token.line;
let column = token.column;
match token.kind {
TokenKind::Int(n) => {
self.advance();
Ok(Expr::new(ExprKind::Int(n), line, column))
}
TokenKind::Float(f) => {
self.advance();
Ok(Expr::new(ExprKind::Float(f), line, column))
}
TokenKind::Str(s) => {
self.advance();
Ok(Expr::new(ExprKind::Str(s), line, column))
}
TokenKind::True => {
self.advance();
Ok(Expr::new(ExprKind::Bool(true), line, column))
}
TokenKind::False => {
self.advance();
Ok(Expr::new(ExprKind::Bool(false), line, column))
}
TokenKind::Nil => {
self.advance();
Ok(Expr::new(ExprKind::Nil, line, column))
}
TokenKind::Ident(name) => {
self.advance();
Ok(Expr::new(ExprKind::Identifier(name), line, column))
}
TokenKind::LParen => {
self.advance();
let expr = self.expression()?;
self.expect(TokenKind::RParen, "to close a grouped expression")?;
Ok(expr)
}
TokenKind::LBracket => {
self.advance();
let elements = self.parse_array_elements()?;
Ok(Expr::new(ExprKind::Array(elements), line, column))
}
TokenKind::LBrace => {
self.advance();
self.parse_map(line, column)
}
TokenKind::Fn => {
self.advance();
let params = self.parse_params()?;
let body = self.function_body()?;
Ok(Expr::new(ExprKind::Function { params, body }, line, column))
}
other => Err(MiruError::with_column(
line,
column,
format!("expected an expression but found {}", other.describe()),
)),
}
}
fn parse_array_elements(&mut self) -> Result<Vec<Expr>, MiruError> {
let mut elements = Vec::new();
if !self.check(&TokenKind::RBracket) {
loop {
elements.push(self.expression()?);
if self.check(&TokenKind::Comma) {
self.advance();
if self.check(&TokenKind::RBracket) {
break; // tolerate a trailing comma
}
} else {
break;
}
}
}
self.expect(TokenKind::RBracket, "to close an array literal")?;
Ok(elements)
}
fn parse_map(&mut self, line: usize, column: usize) -> Result<Expr, MiruError> {
// A brace restores newline significance, because blocks need it, so a
// map literal skips newlines between its entries itself. That was true
// before v0.8 made braces restore it inside a group too, which is why
// that change did not disturb map literals.
let mut entries = Vec::new();
self.skip_newlines();
if !self.check(&TokenKind::RBrace) {
loop {
let key = self.expression()?;
self.expect(TokenKind::Colon, "after a map key")?;
let value = self.expression()?;
entries.push((key, value));
self.skip_newlines();
if self.check(&TokenKind::Comma) {
self.advance();
self.skip_newlines();
if self.check(&TokenKind::RBrace) {
break; // tolerate a trailing comma
}
} else {
break;
}
}
}
self.expect(TokenKind::RBrace, "to close a map literal")?;
Ok(Expr::new(ExprKind::Map(entries), line, column))
}
// --- Token helpers ----------------------------------------------------
fn peek(&self) -> &Token {
&self.tokens[self.pos]
}
fn peek_kind(&self) -> &TokenKind {
&self.tokens[self.pos].kind
}
fn peek_at_kind(&self, offset: usize) -> Option<&TokenKind> {
self.tokens.get(self.pos + offset).map(|token| &token.kind)
}
fn advance(&mut self) -> Token {
let token = self.tokens[self.pos].clone();
if !self.is_at_end() {
self.pos += 1;
}
token
}
fn is_at_end(&self) -> bool {
matches!(self.peek_kind(), TokenKind::Eof)
}
fn check(&self, kind: &TokenKind) -> bool {
self.peek_kind() == kind
}
fn is_statement_end(&self) -> bool {
matches!(
self.peek_kind(),
TokenKind::Newline | TokenKind::RBrace | TokenKind::Eof
)
}
fn skip_newlines(&mut self) {
while matches!(self.peek_kind(), TokenKind::Newline) {
self.advance();
}
}
/// Statements that end in a `}` (a block) do not need a following newline or
/// `;` before the next statement, so one-liners like
/// `if c { return 1 } return 2` parse cleanly.
fn ends_with_block(kind: &StmtKind) -> bool {
matches!(
kind,
StmtKind::If { .. }
| StmtKind::While { .. }
| StmtKind::For { .. }
| StmtKind::Function { .. }
)
}
fn consume_terminator(&mut self) -> Result<(), MiruError> {
match self.peek_kind() {
TokenKind::Newline => {
self.advance();
Ok(())
}
TokenKind::RBrace | TokenKind::Eof => Ok(()),
other => {
let token = self.peek();
Err(MiruError::with_column(
token.line,
token.column,
format!("expected end of statement but found {}", other.describe()),
))
}
}
}
fn expect(&mut self, kind: TokenKind, context: &str) -> Result<Token, MiruError> {
if self.peek_kind() == &kind {
Ok(self.advance())
} else {
let token = self.peek();
Err(MiruError::with_column(
token.line,
token.column,
format!(
"expected {} {} but found {}",
kind.describe(),
context,
token.kind.describe()
),
))
}
}
fn expect_identifier(&mut self, context: &str) -> Result<String, MiruError> {
let token = self.peek().clone();
if let TokenKind::Ident(name) = token.kind {
self.advance();
Ok(name)
} else {
Err(MiruError::with_column(
token.line,
token.column,
format!(
"expected an identifier {} but found {}",
context,
token.kind.describe()
),
))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::{BinaryOp, Expr, ExprKind, LogicalOp, StmtKind, UnaryOp};
use crate::lexer::Lexer;
fn parse_program(source: &str) -> Vec<Stmt> {
let tokens = Lexer::tokenize(source).expect("source should tokenize");
Parser::parse(tokens).expect("source should parse")
}
fn parse_expr(source: &str) -> Expr {
let mut statements = parse_program(source);
assert_eq!(statements.len(), 1, "expected a single statement");
match statements.remove(0).kind {
StmtKind::Expr(expr) => expr,
other => panic!("expected an expression statement, found {other:?}"),
}
}
/// Wrap an expression kind with dummy position, for comparing tree shape.
/// `Expr`'s `PartialEq` ignores positions, so these match parsed output.
fn e(kind: ExprKind) -> Expr {
Expr::new(kind, 0, 0)
}
#[test]
fn syntax_error_carries_a_column() {
// 'let' must be followed by a name; the '=' sits at column 5.
let tokens = Lexer::tokenize("let = 1").expect("source should tokenize");
let err = Parser::parse(tokens).unwrap_err();
assert_eq!(err.line, 1);
assert_eq!(err.column, 5);
}
#[test]
fn parses_let_statement() {
let statements = parse_program("let x = 1 + 2");
match &statements[0].kind {
StmtKind::Let { name, value } => {
assert_eq!(name, "x");
assert_eq!(
*value,
e(ExprKind::Binary {
op: BinaryOp::Add,
left: Box::new(e(ExprKind::Int(1))),
right: Box::new(e(ExprKind::Int(2))),
})
);
}
other => panic!("expected a let statement, found {other:?}"),
}
}
#[test]
fn multiplication_binds_tighter_than_addition() {
assert_eq!(
parse_expr("1 + 2 * 3"),
e(ExprKind::Binary {
op: BinaryOp::Add,
left: Box::new(e(ExprKind::Int(1))),
right: Box::new(e(ExprKind::Binary {
op: BinaryOp::Multiply,
left: Box::new(e(ExprKind::Int(2))),
right: Box::new(e(ExprKind::Int(3))),
})),
})
);
}
#[test]
fn subtraction_is_left_associative() {
assert_eq!(
parse_expr("1 - 2 - 3"),
e(ExprKind::Binary {
op: BinaryOp::Subtract,
left: Box::new(e(ExprKind::Binary {
op: BinaryOp::Subtract,
left: Box::new(e(ExprKind::Int(1))),
right: Box::new(e(ExprKind::Int(2))),
})),
right: Box::new(e(ExprKind::Int(3))),
})
);
}
#[test]
fn unary_negation_binds_tighter_than_multiplication() {
assert_eq!(
parse_expr("-2 * 3"),
e(ExprKind::Binary {
op: BinaryOp::Multiply,
left: Box::new(e(ExprKind::Unary {
op: UnaryOp::Negate,
operand: Box::new(e(ExprKind::Int(2))),
})),
right: Box::new(e(ExprKind::Int(3))),
})
);
}
#[test]
fn logical_and_binds_tighter_than_or() {
assert_eq!(
parse_expr("a || b && c"),
e(ExprKind::Logical {
op: LogicalOp::Or,
left: Box::new(e(ExprKind::Identifier("a".to_string()))),
right: Box::new(e(ExprKind::Logical {
op: LogicalOp::And,
left: Box::new(e(ExprKind::Identifier("b".to_string()))),
right: Box::new(e(ExprKind::Identifier("c".to_string()))),
})),
})
);
}
#[test]
fn parses_call_then_index() {
assert_eq!(
parse_expr("f(1)[0]"),
e(ExprKind::Index {
target: Box::new(e(ExprKind::Call {
callee: Box::new(e(ExprKind::Identifier("f".to_string()))),
arguments: vec![e(ExprKind::Int(1))],
})),
index: Box::new(e(ExprKind::Int(0))),
})
);
}
#[test]
fn parses_array_literal() {
assert_eq!(
parse_expr("[1, 2, 3]"),
e(ExprKind::Array(vec![
e(ExprKind::Int(1)),
e(ExprKind::Int(2)),
e(ExprKind::Int(3)),
]))
);
}
#[test]
fn parses_function_declaration() {
let statements = parse_program("fn add(a, b) {\n return a + b\n}");
match &statements[0].kind {
StmtKind::Function { name, params, body } => {
assert_eq!(name, "add");
assert_eq!(params, &vec!["a".to_string(), "b".to_string()]);
assert_eq!(body.len(), 1);
assert!(matches!(body[0].kind, StmtKind::Return(Some(_))));
}
other => panic!("expected a function declaration, found {other:?}"),
}
}
#[test]
fn parses_if_else_if_chain() {
let statements = parse_program("if a { 1 } else if b { 2 } else { 3 }");
match &statements[0].kind {
StmtKind::If {
else_branch: Some(else_statements),
..
} => {
assert_eq!(else_statements.len(), 1);
assert!(matches!(else_statements[0].kind, StmtKind::If { .. }));
}
other => panic!("expected an if with an else branch, found {other:?}"),
}
}
#[test]
fn parses_for_in_loop() {
let statements = parse_program("for n in names {\n print(n)\n}");
match &statements[0].kind {
StmtKind::For {
name,
iterable,
body,
} => {
assert_eq!(name, "n");
assert_eq!(*iterable, e(ExprKind::Identifier("names".to_string())));
assert_eq!(body.len(), 1);
}
other => panic!("expected a for loop, found {other:?}"),
}
}
#[test]
fn parses_assignment() {
let statements = parse_program("x = 5");
match &statements[0].kind {
StmtKind::Assign { target, value } => {
assert_eq!(*target, e(ExprKind::Identifier("x".to_string())));
assert_eq!(*value, e(ExprKind::Int(5)));
}
other => panic!("expected an assignment, found {other:?}"),
}
}
#[test]
fn reports_missing_expression() {
let tokens = Lexer::tokenize("let x =").expect("lexes");
let err = Parser::parse(tokens).unwrap_err();
assert!(err.message.contains("expected an expression"));
}
#[test]
fn a_statement_may_follow_a_block_on_one_line() {
let statements = parse_program("fn f(n) { if n < 1 { return 0 } return 1 }");
match &statements[0].kind {
StmtKind::Function { body, .. } => assert_eq!(body.len(), 2),
other => panic!("expected a function, found {other:?}"),
}
}
#[test]
fn parses_break_and_continue_in_a_loop() {
let statements = parse_program("while true {\n continue\n break\n}");
match &statements[0].kind {
StmtKind::While { body, .. } => {
assert!(matches!(body[0].kind, StmtKind::Continue));
assert!(matches!(body[1].kind, StmtKind::Break));
}
other => panic!("expected a while loop, found {other:?}"),
}
}
#[test]
fn break_outside_a_loop_is_an_error() {
let tokens = Lexer::tokenize("break").expect("lexes");
let err = Parser::parse(tokens).unwrap_err();
assert!(err.message.contains("break outside of a loop"));
}
#[test]
fn break_cannot_target_a_loop_outside_a_function() {
let tokens =
Lexer::tokenize("for i in [1] {\n fn f() {\n break\n }\n}").expect("lexes");
let err = Parser::parse(tokens).unwrap_err();
assert!(err.message.contains("break outside of a loop"));
}
#[test]
fn parses_map_literal() {
assert_eq!(
parse_expr("{\"a\": 1, \"b\": 2}"),
e(ExprKind::Map(vec![
(e(ExprKind::Str("a".to_string())), e(ExprKind::Int(1))),
(e(ExprKind::Str("b".to_string())), e(ExprKind::Int(2))),
]))
);
}
#[test]
fn parses_empty_map() {
assert_eq!(parse_expr("{}"), e(ExprKind::Map(vec![])));
}
}