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
//! JavaScript parser: token stream → AST.
//!
//! Recursive descent with precedence climbing for binary operators. Automatic
//! Semicolon Insertion is applied at statement boundaries using the
//! `newline_before` flag the lexer records on every token. Arrow functions are
//! detected at assignment level by looking ahead for `=>` after a parameter
//! list. Template-literal `${...}` fields are re-parsed here from the raw source
//! the lexer captured.
use crate::ast::*;
use crate::lexer::{lex, Tok, Token};
const KEYWORDS: &[&str] = &[
"var",
"let",
"const",
"function",
"return",
"if",
"else",
"while",
"do",
"for",
"of",
"in",
"switch",
"case",
"default",
"break",
"continue",
"true",
"false",
"null",
"this",
"new",
"typeof",
"void",
"delete",
"instanceof",
"throw",
"try",
"catch",
"finally",
];
fn is_keyword(s: &str) -> bool {
KEYWORDS.contains(&s)
}
struct Parser {
toks: Vec<Token>,
pos: usize,
/// True while parsing a generator body — enables `yield` as an operator.
in_generator: bool,
/// True while parsing an async body — enables `await` as an operator.
in_async: bool,
/// True while parsing a `for` init in LHS position — suppresses `in` as a
/// relational operator so `for (x in obj)` (no declaration keyword) parses
/// the `in` as the loop separator, not a binary expression. Cleared inside
/// any parenthesised/bracketed sub-expression, where `in` is legal again.
no_in: bool,
}
/// Parse a complete JS program into a statement list. Inline `rust { ... }` FFI
/// blocks are desugared to `__rust_compile(...)` calls before lexing.
pub fn parse(src: &str) -> Result<Vec<Stmt>, String> {
let src = crate::rust_ffi::desugar(src);
let toks = lex(&src)?;
let mut p = Parser {
toks,
pos: 0,
in_generator: false,
in_async: false,
no_in: false,
};
let mut out = Vec::new();
while !p.at_eof() {
out.push(p.parse_stmt()?);
}
Ok(out)
}
impl Parser {
// ── token helpers ────────────────────────────────────────────────────
fn cur(&self) -> &Token {
&self.toks[self.pos]
}
fn tok(&self) -> &Tok {
&self.toks[self.pos].tok
}
fn line(&self) -> u32 {
self.toks[self.pos].line
}
fn at_eof(&self) -> bool {
matches!(self.tok(), Tok::Eof)
}
fn newline_before(&self) -> bool {
self.cur().newline_before
}
fn advance(&mut self) -> Tok {
let t = self.toks[self.pos].tok.clone();
if self.pos + 1 < self.toks.len() {
self.pos += 1;
}
t
}
/// True if the current token is the punctuation `s`.
fn is_punct(&self, s: &str) -> bool {
matches!(self.tok(), Tok::Punct(p) if p == s)
}
/// True if the current token is the identifier/keyword `s`.
fn is_kw(&self, s: &str) -> bool {
matches!(self.tok(), Tok::Ident(i) if i == s)
}
/// Consume the punctuation `s` if present.
fn eat_punct(&mut self, s: &str) -> bool {
if self.is_punct(s) {
self.advance();
true
} else {
false
}
}
fn eat_kw(&mut self, s: &str) -> bool {
if self.is_kw(s) {
self.advance();
true
} else {
false
}
}
fn expect_punct(&mut self, s: &str) -> Result<(), String> {
if self.eat_punct(s) {
Ok(())
} else {
Err(format!(
"SyntaxError: expected '{s}' but found {:?} (line {})",
self.tok(),
self.line()
))
}
}
/// Consume an identifier name (any non-punct ident, including keywords used
/// as property names when `allow_kw`).
fn ident_name(&mut self) -> Result<String, String> {
match self.tok().clone() {
Tok::Ident(s) => {
self.advance();
Ok(s)
}
other => Err(format!(
"SyntaxError: expected identifier but found {other:?} (line {})",
self.line()
)),
}
}
/// Apply ASI: consume an explicit `;`, or accept a newline / `}` / EOF.
fn semicolon(&mut self) -> Result<(), String> {
if self.eat_punct(";") {
return Ok(());
}
if self.newline_before() || self.is_punct("}") || self.at_eof() {
return Ok(());
}
Err(format!(
"SyntaxError: expected ';' but found {:?} (line {})",
self.tok(),
self.line()
))
}
// ── statements ───────────────────────────────────────────────────────
fn parse_stmt(&mut self) -> Result<Stmt, String> {
let line = self.line();
let kind = match self.tok().clone() {
Tok::Punct(p) if p == "{" => {
self.advance();
StmtKind::Block(self.parse_block_body()?)
}
Tok::Punct(p) if p == ";" => {
self.advance();
StmtKind::Empty
}
Tok::Ident(kw) if kw == "var" || kw == "let" || kw == "const" => {
let k = self.parse_decl_kind();
let decls = self.parse_declarators()?;
self.semicolon()?;
StmtKind::Decl { kind: k, decls }
}
Tok::Ident(kw) if kw == "function" => self.parse_func_decl(false)?,
// `async function …` (declaration). `async` stays a plain identifier
// anywhere else (contextual keyword).
Tok::Ident(kw)
if kw == "async" && self.peek_kw(1, "function") && !self.peek_newline(1) =>
{
self.advance(); // async
self.parse_func_decl(true)?
}
Tok::Ident(kw) if kw == "class" => {
let node = self.parse_class(true)?;
StmtKind::ClassDecl(node)
}
Tok::Ident(kw) if kw == "if" => self.parse_if()?,
Tok::Ident(kw) if kw == "while" => self.parse_while()?,
Tok::Ident(kw) if kw == "do" => self.parse_do_while()?,
Tok::Ident(kw) if kw == "for" => self.parse_for()?,
Tok::Ident(kw) if kw == "switch" => self.parse_switch()?,
Tok::Ident(kw) if kw == "return" => {
self.advance();
let arg = if self.is_punct(";")
|| self.is_punct("}")
|| self.newline_before()
|| self.at_eof()
{
None
} else {
Some(self.parse_expr()?)
};
self.semicolon()?;
StmtKind::Return(arg)
}
Tok::Ident(kw) if kw == "break" => {
self.advance();
let label = self.opt_label();
self.semicolon()?;
StmtKind::Break(label)
}
Tok::Ident(kw) if kw == "continue" => {
self.advance();
let label = self.opt_label();
self.semicolon()?;
StmtKind::Continue(label)
}
Tok::Ident(kw) if kw == "throw" => {
self.advance();
let e = self.parse_expr()?;
self.semicolon()?;
StmtKind::Throw(e)
}
Tok::Ident(kw) if kw == "try" => self.parse_try()?,
// `label: stmt` — a bare identifier immediately followed by `:` at
// statement position is a label (never an expression; the reserved
// control keywords are all matched above, and switch `case`/`default`
// labels are parsed inside `parse_switch`).
Tok::Ident(name) if matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":") =>
{
self.advance(); // the label identifier
self.advance(); // the ':'
let body = Box::new(self.parse_stmt()?);
StmtKind::Labeled { label: name, body }
}
_ => {
let e = self.parse_expr()?;
self.semicolon()?;
StmtKind::Expr(e)
}
};
Ok(Stmt::new(kind, line))
}
/// Whether the token `n` ahead is the identifier `kw`.
fn peek_kw(&self, n: usize, kw: &str) -> bool {
matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Ident(s)) if s == kw)
}
/// Whether the token `n` ahead has a newline before it.
fn peek_newline(&self, n: usize) -> bool {
self.toks
.get(self.pos + n)
.map(|t| t.newline_before)
.unwrap_or(false)
}
/// Parse a `function` declaration (the `function`/`async function` keyword is
/// current). `is_async` is true when a preceding `async` was consumed.
fn parse_func_decl(&mut self, is_async: bool) -> Result<StmtKind, String> {
self.advance(); // function
let is_generator = self.eat_punct("*");
let name = self.ident_name()?;
let params = self.parse_params()?;
self.expect_punct("{")?;
let body = self.parse_fn_body_block(is_generator, is_async)?;
Ok(StmtKind::FuncDecl {
name,
params,
body,
is_generator,
is_async,
})
}
/// Parse a brace-delimited function body under the given generator/async
/// context (so `yield`/`await` inside are operators, not identifiers).
fn parse_fn_body_block(
&mut self,
is_generator: bool,
is_async: bool,
) -> Result<Vec<Stmt>, String> {
let (pg, pa) = (self.in_generator, self.in_async);
self.in_generator = is_generator;
self.in_async = is_async;
let body = self.parse_block_body();
self.in_generator = pg;
self.in_async = pa;
body
}
/// Parse a function *expression* (`function`/`async function`, keyword
/// current). Supports `function*` generators.
fn parse_function_expr(&mut self, is_async: bool) -> Result<Expr, String> {
self.advance(); // function
let is_generator = self.eat_punct("*");
let name = if let Tok::Ident(n) = self.tok() {
if !is_keyword(n) {
let n = n.clone();
self.advance();
Some(n)
} else {
None
}
} else {
None
};
let params = self.parse_params()?;
self.expect_punct("{")?;
let body = self.parse_fn_body_block(is_generator, is_async)?;
Ok(Expr::Function {
params,
body: FnBody::Block(body),
is_arrow: false,
name,
is_generator,
is_async,
is_method: false,
})
}
/// Parse a `class` (the `class` keyword is current). `_decl` distinguishes a
/// declaration (name required in strict mode, but we accept optional) from an
/// expression.
fn parse_class(&mut self, _decl: bool) -> Result<ClassNode, String> {
self.advance(); // class
let name = if let Tok::Ident(n) = self.tok() {
if !is_keyword(n) && n != "extends" {
let n = n.clone();
self.advance();
Some(n)
} else {
None
}
} else {
None
};
let parent = if self.eat_kw("extends") {
// The superclass is a left-hand-side expression (`extends Base`,
// `extends foo.Bar`).
Some(Box::new(self.parse_call_member()?))
} else {
None
};
self.expect_punct("{")?;
let mut members = Vec::new();
while !self.is_punct("}") && !self.at_eof() {
if self.eat_punct(";") {
continue; // stray semicolons between members
}
members.push(self.parse_class_member()?);
}
self.expect_punct("}")?;
Ok(ClassNode {
name,
parent,
members,
})
}
/// Parse one class member: `[static] [get|set|async|*] name(params){…}` or a
/// `[static] name [= init];` field.
fn parse_class_member(&mut self) -> Result<ClassMember, String> {
let is_static = self.is_kw("static") && !self.peek_is_member_punct(1) && {
self.advance();
true
};
// `static { … }` — a class static initialization block (ES2022). A brace
// where a member key would be is unambiguous: no member name can start
// with `{`, so this is checked before the key parse (which otherwise
// rejects it as `bad member key Punct("{")`).
if is_static && self.is_punct("{") {
self.advance();
// Its own function context: `yield`/`await` are plain identifiers
// inside a static block, whatever encloses the class.
let body = self.parse_fn_body_block(false, false)?;
return Ok(ClassMember {
key: Expr::Str(String::new()),
computed: false,
kind: MemberKind::StaticBlock,
is_static: true,
is_generator: false,
is_async: false,
params: Vec::new(),
body,
field_init: None,
});
}
// Accessor / async / generator prefixes (each contextual: only a prefix
// when followed by another member name, not itself the member name).
let mut kind = MemberKind::Method;
let mut is_async = false;
let mut is_generator = false;
if self.is_kw("get") && !self.peek_is_member_punct(1) {
self.advance();
kind = MemberKind::Get;
} else if self.is_kw("set") && !self.peek_is_member_punct(1) {
self.advance();
kind = MemberKind::Set;
} else {
if self.is_kw("async") && !self.peek_is_member_punct(1) && !self.peek_newline(1) {
self.advance();
is_async = true;
}
if self.eat_punct("*") {
is_generator = true;
}
}
// The member key (computed `[expr]`, string, number, or identifier).
let (key, computed) = self.parse_property_key()?;
// A field (no parentheses) vs a method.
if kind == MemberKind::Method && !self.is_punct("(") {
let field_init = if self.eat_punct("=") {
Some(self.parse_assign()?)
} else {
None
};
self.semicolon()?;
return Ok(ClassMember {
key,
computed,
kind: MemberKind::Field,
is_static,
is_generator: false,
is_async: false,
params: Vec::new(),
body: Vec::new(),
field_init,
});
}
// A method / accessor / constructor.
let is_ctor = !is_static
&& !computed
&& matches!(&key, Expr::Str(s) if s == "constructor")
&& kind == MemberKind::Method;
let params = self.parse_params()?;
self.expect_punct("{")?;
let body = self.parse_fn_body_block(is_generator, is_async)?;
Ok(ClassMember {
key,
computed,
kind: if is_ctor {
MemberKind::Constructor
} else {
kind
},
is_static,
is_generator,
is_async,
params,
body,
field_init: None,
})
}
/// Whether the token `n` ahead is `(`, `=`, `;`, `}`, or a newline-boundary —
/// i.e. the current word is itself the member name, not a modifier prefix.
fn peek_is_member_punct(&self, n: usize) -> bool {
matches!(
self.toks.get(self.pos + n).map(|t| &t.tok),
Some(Tok::Punct(p)) if p == "(" || p == "=" || p == ";" || p == "}"
)
}
/// Parse a property key for a class member / object method: `[expr]` (computed),
/// a string, a number, or an identifier (returned as an `Expr::Str`).
fn parse_property_key(&mut self) -> Result<(Expr, bool), String> {
if self.is_punct("[") {
self.advance();
let k = self.parse_assign()?;
self.expect_punct("]")?;
Ok((k, true))
} else {
match self.tok().clone() {
Tok::Str(s) => {
self.advance();
Ok((Expr::Str(s), false))
}
Tok::Num(n) => {
self.advance();
Ok((Expr::Str(crate::host::fmt_number(n)), false))
}
Tok::Ident(s) => {
self.advance();
Ok((Expr::Str(s), false))
}
other => Err(format!(
"SyntaxError: bad member key {other:?} (line {})",
self.line()
)),
}
}
}
/// An optional non-newline label after break/continue.
fn opt_label(&mut self) -> Option<String> {
if self.newline_before() {
return None;
}
if let Tok::Ident(s) = self.tok() {
if !is_keyword(s) {
let s = s.clone();
self.advance();
return Some(s);
}
}
None
}
/// Parse statements up to (and consuming) the closing `}`.
fn parse_block_body(&mut self) -> Result<Vec<Stmt>, String> {
let mut out = Vec::new();
while !self.is_punct("}") && !self.at_eof() {
out.push(self.parse_stmt()?);
}
self.expect_punct("}")?;
Ok(out)
}
fn parse_decl_kind(&mut self) -> DeclKind {
let k = match self.tok() {
Tok::Ident(s) if s == "let" => DeclKind::Let,
Tok::Ident(s) if s == "const" => DeclKind::Const,
_ => DeclKind::Var,
};
self.advance();
k
}
fn parse_declarators(&mut self) -> Result<Vec<Declarator>, String> {
let mut decls = Vec::new();
loop {
let target = self.parse_binding_target()?;
let init = if self.eat_punct("=") {
Some(self.parse_assign()?)
} else {
None
};
decls.push(Declarator { target, init });
if !self.eat_punct(",") {
break;
}
}
Ok(decls)
}
/// A binding target: identifier or array/object destructuring pattern.
fn parse_binding_target(&mut self) -> Result<Expr, String> {
if self.is_punct("[") {
self.parse_array_literal()
} else if self.is_punct("{") {
self.parse_object_literal()
} else {
Ok(Expr::Ident(self.ident_name()?))
}
}
fn parse_if(&mut self) -> Result<StmtKind, String> {
self.advance(); // if
self.expect_punct("(")?;
let test = self.parse_expr()?;
self.expect_punct(")")?;
let cons = Box::new(self.parse_stmt()?);
let alt = if self.eat_kw("else") {
Some(Box::new(self.parse_stmt()?))
} else {
None
};
Ok(StmtKind::If { test, cons, alt })
}
fn parse_while(&mut self) -> Result<StmtKind, String> {
self.advance();
self.expect_punct("(")?;
let test = self.parse_expr()?;
self.expect_punct(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::While { test, body })
}
fn parse_do_while(&mut self) -> Result<StmtKind, String> {
self.advance();
let body = Box::new(self.parse_stmt()?);
if !self.eat_kw("while") {
return Err(format!(
"SyntaxError: expected 'while' (line {})",
self.line()
));
}
self.expect_punct("(")?;
let test = self.parse_expr()?;
self.expect_punct(")")?;
self.semicolon()?;
Ok(StmtKind::DoWhile { body, test })
}
fn parse_for(&mut self) -> Result<StmtKind, String> {
self.advance();
// `for await (… of …)` — the async-iteration form (valid in an async body).
let is_await = self.eat_kw("await");
self.expect_punct("(")?;
// Optional declaration or expression init.
let decl_kind = match self.tok() {
Tok::Ident(s) if s == "var" || s == "let" || s == "const" => {
Some(self.parse_decl_kind())
}
_ => None,
};
// Empty init: `for (;;)`.
if decl_kind.is_none() && self.is_punct(";") {
return self.parse_c_for(None);
}
// Parse the first binding/expression, then decide of/in vs C-style.
let first_target = if decl_kind.is_some() {
self.parse_binding_target()?
} else {
self.parse_expr_no_in()?
};
if self.eat_kw("of") {
let iter = self.parse_assign()?;
self.expect_punct(")")?;
let body = Box::new(self.parse_stmt()?);
return Ok(StmtKind::ForOf {
decl_kind,
target: first_target,
iter,
body,
is_await,
});
}
if self.eat_kw("in") {
let object = self.parse_assign()?;
self.expect_punct(")")?;
let body = Box::new(self.parse_stmt()?);
return Ok(StmtKind::ForIn {
decl_kind,
target: first_target,
object,
body,
});
}
// C-style: reconstruct the init statement.
let init_stmt = if let Some(k) = decl_kind {
let init = if self.eat_punct("=") {
Some(self.parse_assign()?)
} else {
None
};
let mut decls = vec![Declarator {
target: first_target,
init,
}];
while self.eat_punct(",") {
let target = self.parse_binding_target()?;
let init = if self.eat_punct("=") {
Some(self.parse_assign()?)
} else {
None
};
decls.push(Declarator { target, init });
}
StmtKind::Decl { kind: k, decls }
} else {
// A non-declaration C-style init may be a comma sequence
// (`for (i = 0, n = a.length; …)`) — extend past the first assignment.
let init = if self.is_punct(",") {
let mut items = vec![first_target];
while self.eat_punct(",") {
items.push(self.parse_expr_no_in()?);
}
Expr::Sequence(items)
} else {
first_target
};
StmtKind::Expr(init)
};
self.parse_c_for(Some(Stmt::from(init_stmt)))
}
fn parse_c_for(&mut self, init: Option<Stmt>) -> Result<StmtKind, String> {
self.expect_punct(";")?;
let test = if self.is_punct(";") {
None
} else {
Some(self.parse_expr()?)
};
self.expect_punct(";")?;
let update = if self.is_punct(")") {
None
} else {
Some(self.parse_expr()?)
};
self.expect_punct(")")?;
let body = Box::new(self.parse_stmt()?);
Ok(StmtKind::For {
init: init.map(Box::new),
test,
update,
body,
})
}
fn parse_switch(&mut self) -> Result<StmtKind, String> {
self.advance();
self.expect_punct("(")?;
let disc = self.parse_expr()?;
self.expect_punct(")")?;
self.expect_punct("{")?;
let mut cases = Vec::new();
while !self.is_punct("}") && !self.at_eof() {
let test = if self.eat_kw("case") {
let e = self.parse_expr()?;
Some(e)
} else if self.eat_kw("default") {
None
} else {
return Err(format!(
"SyntaxError: expected 'case' or 'default' (line {})",
self.line()
));
};
self.expect_punct(":")?;
let mut body = Vec::new();
while !self.is_punct("}")
&& !self.is_kw("case")
&& !self.is_kw("default")
&& !self.at_eof()
{
body.push(self.parse_stmt()?);
}
cases.push(SwitchCase { test, body });
}
self.expect_punct("}")?;
Ok(StmtKind::Switch { disc, cases })
}
fn parse_try(&mut self) -> Result<StmtKind, String> {
self.advance();
self.expect_punct("{")?;
let block = self.parse_block_body()?;
let handler = if self.eat_kw("catch") {
let param = if self.eat_punct("(") {
let p = self.parse_binding_target()?;
self.expect_punct(")")?;
Some(p)
} else {
None
};
self.expect_punct("{")?;
let body = self.parse_block_body()?;
Some((param, body))
} else {
None
};
let finalizer = if self.eat_kw("finally") {
self.expect_punct("{")?;
Some(self.parse_block_body()?)
} else {
None
};
Ok(StmtKind::Try {
block,
handler,
finalizer,
})
}
// ── expressions ──────────────────────────────────────────────────────
/// Full expression, including the comma sequence operator.
fn parse_expr(&mut self) -> Result<Expr, String> {
let first = self.parse_assign()?;
if self.is_punct(",") {
let mut items = vec![first];
while self.eat_punct(",") {
items.push(self.parse_assign()?);
}
Ok(Expr::Sequence(items))
} else {
Ok(first)
}
}
/// Like `parse_expr` but stops before `in` (used in `for` init position).
fn parse_expr_no_in(&mut self) -> Result<Expr, String> {
// For simplicity the no-in variant only parses an assignment/LHS chain,
// which is sufficient for `for (x in ...)` / `for (x of ...)` heads.
let saved = self.no_in;
self.no_in = true;
let r = self.parse_assign();
self.no_in = saved;
r
}
/// Run `f` with `in` re-enabled (inside a parenthesised/bracketed sub-
/// expression of a `for` LHS, where the no-in restriction does not apply).
fn allow_in<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
let saved = self.no_in;
self.no_in = false;
let r = f(self);
self.no_in = saved;
r
}
fn parse_assign(&mut self) -> Result<Expr, String> {
// Arrow function detection.
if let Some(arrow) = self.try_parse_arrow()? {
return Ok(arrow);
}
let left = self.parse_conditional()?;
// Assignment operators (right-associative).
let op = match self.tok() {
Tok::Punct(p) => p.clone(),
_ => return Ok(left),
};
let compound = match op.as_str() {
"=" => None,
"+=" => Some(BinOp::Add),
"-=" => Some(BinOp::Sub),
"*=" => Some(BinOp::Mul),
"/=" => Some(BinOp::Div),
"%=" => Some(BinOp::Mod),
"**=" => Some(BinOp::Pow),
"&=" => Some(BinOp::BitAnd),
"|=" => Some(BinOp::BitOr),
"^=" => Some(BinOp::BitXor),
"<<=" => Some(BinOp::Shl),
">>=" => Some(BinOp::Shr),
">>>=" => Some(BinOp::UShr),
"&&=" | "||=" | "??=" => {
// Logical assignment.
self.advance();
let value = self.parse_assign()?;
let lop = match op.as_str() {
"&&=" => LogicalOp::And,
"||=" => LogicalOp::Or,
_ => LogicalOp::Nullish,
};
return Ok(Expr::Assign {
target: Box::new(left.clone()),
value: Box::new(Expr::Logical(lop, Box::new(left), Box::new(value))),
});
}
_ => return Ok(left),
};
self.advance();
let value = self.parse_assign()?;
let value = match compound {
None => value,
Some(b) => Expr::Binary(b, Box::new(left.clone()), Box::new(value)),
};
Ok(Expr::Assign {
target: Box::new(left),
value: Box::new(value),
})
}
fn parse_conditional(&mut self) -> Result<Expr, String> {
let test = self.parse_binary(0)?;
if self.eat_punct("?") {
let cons = self.parse_assign()?;
self.expect_punct(":")?;
let alt = self.parse_assign()?;
Ok(Expr::Conditional {
test: Box::new(test),
cons: Box::new(cons),
alt: Box::new(alt),
})
} else {
Ok(test)
}
}
/// Precedence-climbing binary parser. Handles `&& || ??` as logical nodes.
fn parse_binary(&mut self, min_prec: u8) -> Result<Expr, String> {
let mut left = self.parse_unary()?;
while let Some((prec, right_assoc, logical, bin)) = self.bin_info() {
if prec < min_prec {
break;
}
self.advance();
let next_min = if right_assoc { prec } else { prec + 1 };
let right = self.parse_binary(next_min)?;
left = if let Some(lop) = logical {
Expr::Logical(lop, Box::new(left), Box::new(right))
} else {
Expr::Binary(bin.unwrap(), Box::new(left), Box::new(right))
};
}
Ok(left)
}
/// `(precedence, right_assoc, logical_op, bin_op)` for the current token.
fn bin_info(&self) -> Option<(u8, bool, Option<LogicalOp>, Option<BinOp>)> {
let p = match self.tok() {
Tok::Punct(p) => p.as_str(),
// In a `for` LHS (no-in) context, `in` is the loop separator, not a
// relational operator.
Tok::Ident(s) if s == "in" => {
if self.no_in {
return None;
}
"in"
}
Tok::Ident(s) if s == "instanceof" => "instanceof",
_ => return None,
};
let (prec, ra, log, bin) = match p {
"??" => (1, false, Some(LogicalOp::Nullish), None),
"||" => (2, false, Some(LogicalOp::Or), None),
"&&" => (3, false, Some(LogicalOp::And), None),
"|" => (4, false, None, Some(BinOp::BitOr)),
"^" => (5, false, None, Some(BinOp::BitXor)),
"&" => (6, false, None, Some(BinOp::BitAnd)),
"==" => (7, false, None, Some(BinOp::EqEq)),
"!=" => (7, false, None, Some(BinOp::NeEq)),
"===" => (7, false, None, Some(BinOp::EqEqEq)),
"!==" => (7, false, None, Some(BinOp::NeEqEq)),
"<" => (8, false, None, Some(BinOp::Lt)),
"<=" => (8, false, None, Some(BinOp::Le)),
">" => (8, false, None, Some(BinOp::Gt)),
">=" => (8, false, None, Some(BinOp::Ge)),
"in" => (8, false, None, Some(BinOp::In)),
"instanceof" => (8, false, None, Some(BinOp::InstanceOf)),
"<<" => (9, false, None, Some(BinOp::Shl)),
">>" => (9, false, None, Some(BinOp::Shr)),
">>>" => (9, false, None, Some(BinOp::UShr)),
"+" => (10, false, None, Some(BinOp::Add)),
"-" => (10, false, None, Some(BinOp::Sub)),
"*" => (11, false, None, Some(BinOp::Mul)),
"/" => (11, false, None, Some(BinOp::Div)),
"%" => (11, false, None, Some(BinOp::Mod)),
"**" => (12, true, None, Some(BinOp::Pow)),
_ => return None,
};
Some((prec, ra, log, bin))
}
/// Reject a `**` directly after a just-parsed UnaryExpression. JS only
/// allows an UpdateExpression there (`x++ ** y` and `++x ** y` are fine),
/// so an unparenthesized `-x ** y` / `typeof x ** y` / `await x ** y` is a
/// SyntaxError rather than a silently-reassociated `-(x ** y)`.
fn reject_unary_before_pow(&mut self) -> Result<(), String> {
if self.is_punct("**") {
return Err(format!(
"SyntaxError: Unary operator used immediately before exponentiation \
expression. Parenthesis must be used to disambiguate operator \
precedence (line {})",
self.line()
));
}
Ok(())
}
fn parse_unary(&mut self) -> Result<Expr, String> {
let op = match self.tok() {
Tok::Punct(p) if p == "!" => Some(UnOp::Not),
Tok::Punct(p) if p == "~" => Some(UnOp::BitNot),
Tok::Punct(p) if p == "+" => Some(UnOp::Pos),
Tok::Punct(p) if p == "-" => Some(UnOp::Neg),
Tok::Ident(s) if s == "typeof" => Some(UnOp::TypeOf),
Tok::Ident(s) if s == "void" => Some(UnOp::Void),
Tok::Ident(s) if s == "delete" => Some(UnOp::Delete),
_ => None,
};
if let Some(op) = op {
self.advance();
let e = self.parse_unary()?;
// `ExponentiationExpression : UpdateExpression ** …` — a
// UnaryExpression on the left of `**` is a SyntaxError, so
// `-x ** y` must be written `(-x) ** y` or `-(x ** y)`.
self.reject_unary_before_pow()?;
return Ok(Expr::Unary(op, Box::new(e)));
}
// Prefix ++/--.
if self.is_punct("++") || self.is_punct("--") {
let op = if self.is_punct("++") {
UpdateOp::Inc
} else {
UpdateOp::Dec
};
self.advance();
let e = self.parse_unary()?;
return Ok(Expr::Update {
op,
prefix: true,
target: Box::new(e),
});
}
self.parse_postfix()
}
fn parse_postfix(&mut self) -> Result<Expr, String> {
let mut e = self.parse_call_member()?;
// Postfix ++/-- (no line break before).
if (self.is_punct("++") || self.is_punct("--")) && !self.newline_before() {
let op = if self.is_punct("++") {
UpdateOp::Inc
} else {
UpdateOp::Dec
};
self.advance();
e = Expr::Update {
op,
prefix: false,
target: Box::new(e),
};
}
Ok(e)
}
fn parse_call_member(&mut self) -> Result<Expr, String> {
let mut e = if self.eat_kw("new") {
// `new.target` meta-property.
if self.is_punct(".") {
self.advance();
let prop = self.ident_name()?;
if prop != "target" {
return Err(format!(
"SyntaxError: expected 'target' (line {})",
self.line()
));
}
Expr::NewTarget
} else {
let callee = self.parse_call_member_no_call()?;
let args = if self.is_punct("(") {
self.parse_args()?
} else {
Vec::new()
};
Expr::New {
callee: Box::new(callee),
args,
}
}
} else {
self.parse_primary()?
};
loop {
if self.eat_punct(".") {
let property = self.ident_name()?;
e = Expr::Member {
object: Box::new(e),
property,
optional: false,
};
} else if self.eat_punct("?.") {
if self.is_punct("(") {
let args = self.parse_args()?;
e = Expr::Call {
func: Box::new(e),
args,
optional: true,
};
} else if self.is_punct("[") {
self.advance();
let index = self.allow_in(|p| p.parse_expr())?;
self.expect_punct("]")?;
e = Expr::Index {
object: Box::new(e),
index: Box::new(index),
optional: true,
};
} else {
let property = self.ident_name()?;
e = Expr::Member {
object: Box::new(e),
property,
optional: true,
};
}
} else if self.is_punct("[") {
self.advance();
let index = self.allow_in(|p| p.parse_expr())?;
self.expect_punct("]")?;
e = Expr::Index {
object: Box::new(e),
index: Box::new(index),
optional: false,
};
} else if self.is_punct("(") {
let args = self.parse_args()?;
e = Expr::Call {
func: Box::new(e),
args,
optional: false,
};
} else if matches!(self.tok(), Tok::Template { .. }) {
// A template literal immediately after a callee is a *tagged*
// template: `` tag`...` `` → `tag(strings, ...values)`.
e = self.parse_tagged_template(e)?;
} else {
break;
}
}
Ok(e)
}
/// Parse `` tag`a${x}b` `` into a `TaggedTemplate` node (the tag expression is
/// already parsed as `tag`, and the current token is the template).
fn parse_tagged_template(&mut self, tag: Expr) -> Result<Expr, String> {
let (quasis, raws, exprs_src) = match self.tok().clone() {
Tok::Template {
quasis,
raws,
exprs,
} => (quasis, raws, exprs),
_ => unreachable!(),
};
self.advance();
let mut exprs = Vec::new();
for src in &exprs_src {
exprs.push(parse_expr_source(src)?);
}
Ok(Expr::TaggedTemplate {
tag: Box::new(tag),
quasis,
raws,
exprs,
})
}
/// Member chain without a trailing call — the `new X.Y` callee grammar.
fn parse_call_member_no_call(&mut self) -> Result<Expr, String> {
let mut e = self.parse_primary()?;
loop {
if self.eat_punct(".") {
let property = self.ident_name()?;
e = Expr::Member {
object: Box::new(e),
property,
optional: false,
};
} else if self.is_punct("[") {
self.advance();
let index = self.allow_in(|p| p.parse_expr())?;
self.expect_punct("]")?;
e = Expr::Index {
object: Box::new(e),
index: Box::new(index),
optional: false,
};
} else {
break;
}
}
Ok(e)
}
fn parse_args(&mut self) -> Result<Vec<Expr>, String> {
self.expect_punct("(")?;
// Inside a call-argument list `in` is always a relational operator, even
// in a `for` LHS.
let args = self.allow_in(|p| {
let mut args = Vec::new();
while !p.is_punct(")") {
if p.eat_punct("...") {
let e = p.parse_assign()?;
args.push(Expr::Spread(Box::new(e)));
} else {
args.push(p.parse_assign()?);
}
if !p.eat_punct(",") {
break;
}
}
Ok(args)
})?;
self.expect_punct(")")?;
Ok(args)
}
fn parse_primary(&mut self) -> Result<Expr, String> {
match self.tok().clone() {
Tok::Num(n) => {
self.advance();
Ok(Expr::Number(n))
}
Tok::BigInt(s) => {
self.advance();
Ok(Expr::BigInt(s))
}
Tok::Regex(pat, flags) => {
self.advance();
Ok(Expr::Regex(pat, flags))
}
Tok::Str(s) => {
self.advance();
Ok(Expr::Str(s))
}
Tok::Template {
quasis,
raws: _,
exprs,
} => {
self.advance();
let mut parsed = Vec::new();
for src in &exprs {
parsed.push(parse_expr_source(src)?);
}
Ok(Expr::Template {
quasis,
exprs: parsed,
})
}
Tok::Punct(p) if p == "(" => {
self.advance();
let e = self.parse_expr()?;
self.expect_punct(")")?;
Ok(e)
}
Tok::Punct(p) if p == "[" => self.parse_array_literal(),
Tok::Punct(p) if p == "{" => self.parse_object_literal(),
Tok::Ident(s) => {
match s.as_str() {
"true" => {
self.advance();
Ok(Expr::True)
}
"false" => {
self.advance();
Ok(Expr::False)
}
"null" => {
self.advance();
Ok(Expr::Null)
}
"this" => {
self.advance();
Ok(Expr::This)
}
"super" => {
self.advance();
Ok(Expr::Super)
}
"class" => Ok(Expr::Class(Box::new(self.parse_class(false)?))),
"function" => self.parse_function_expr(false),
"async" if self.peek_kw(1, "function") && !self.peek_newline(1) => {
self.advance(); // async
self.parse_function_expr(true)
}
"yield" if self.in_generator => {
self.advance();
let delegate = self.eat_punct("*");
// `yield` with no argument (before `)`, `]`, `}`, `,`, `;`,
// newline, or EOF).
let arg = if delegate
|| !(self.is_punct(")")
|| self.is_punct("]")
|| self.is_punct("}")
|| self.is_punct(",")
|| self.is_punct(";")
|| self.is_punct(":")
|| self.newline_before()
|| self.at_eof())
{
Some(Box::new(self.parse_assign()?))
} else {
None
};
Ok(Expr::Yield { arg, delegate })
}
"await" if self.in_async => {
self.advance();
let e = self.parse_unary()?;
// An AwaitExpression is a UnaryExpression, so it too
// cannot sit directly left of `**`.
self.reject_unary_before_pow()?;
Ok(Expr::Await(Box::new(e)))
}
_ if is_keyword(&s) => Err(format!(
"SyntaxError: unexpected keyword '{s}' (line {})",
self.line()
)),
_ => {
self.advance();
Ok(Expr::Ident(s))
}
}
}
other => Err(format!(
"SyntaxError: unexpected token {other:?} (line {})",
self.line()
)),
}
}
fn parse_array_literal(&mut self) -> Result<Expr, String> {
self.expect_punct("[")?;
let mut items = Vec::new();
while !self.is_punct("]") {
if self.is_punct(",") {
// Elision: the element is a HOLE, not a stored `undefined`.
items.push(Expr::Hole);
self.advance();
continue;
}
if self.eat_punct("...") {
let e = self.parse_assign()?;
items.push(Expr::Spread(Box::new(e)));
} else {
items.push(self.parse_assign()?);
}
if !self.eat_punct(",") {
break;
}
}
self.expect_punct("]")?;
Ok(Expr::Array(items))
}
fn parse_object_literal(&mut self) -> Result<Expr, String> {
self.expect_punct("{")?;
let mut props = Vec::new();
while !self.is_punct("}") {
if self.eat_punct("...") {
let e = self.parse_assign()?;
props.push(Prop::Spread(e));
if !self.eat_punct(",") {
break;
}
continue;
}
// `get key() {}` / `set key(v) {}` accessor (contextual: `get`/`set`
// is a modifier only when followed by another key, not `:`/`(`/`,`).
if (self.is_kw("get") || self.is_kw("set"))
&& !self.peek_is_member_punct(1)
&& !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
{
let is_getter = self.is_kw("get");
self.advance();
let (key, computed) = self.parse_property_key()?;
let params = self.parse_params()?;
self.expect_punct("{")?;
let body = self.parse_block_body()?;
let func = Expr::Function {
params,
body: FnBody::Block(body),
is_arrow: false,
name: None,
is_generator: false,
is_async: false,
is_method: true,
};
props.push(Prop::Accessor {
key,
computed,
is_getter,
func,
});
if !self.eat_punct(",") {
break;
}
continue;
}
// Concise-method modifiers: `async` and/or `*` before the key.
let mut m_async = false;
let mut m_gen = false;
if self.is_kw("async")
&& !self.peek_is_member_punct(1)
&& !self.peek_newline(1)
&& !matches!(self.toks.get(self.pos + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == ":" || p == ",")
{
self.advance();
m_async = true;
}
if self.is_punct("*") {
self.advance();
m_gen = true;
}
let (key, computed) = self.parse_property_key()?;
// Method shorthand `key(params) { }` (incl. `*gen(){}`, `async m(){}`).
if self.is_punct("(") {
let params = self.parse_params()?;
self.expect_punct("{")?;
let body = self.parse_fn_body_block(m_gen, m_async)?;
let f = Expr::Function {
params,
body: FnBody::Block(body),
is_arrow: false,
name: None,
is_generator: m_gen,
is_async: m_async,
is_method: true,
};
props.push(Prop::KeyValue {
key,
value: f,
computed,
});
} else if self.eat_punct(":") {
let value = self.parse_assign()?;
props.push(Prop::KeyValue {
key,
value,
computed,
});
} else {
// Shorthand `{ x }` -> key "x", value ident x. Or with default
// in a destructuring pattern: `{ x = 1 }`.
let name = match &key {
Expr::Str(s) => s.clone(),
_ => return Err(format!("SyntaxError: bad shorthand (line {})", self.line())),
};
let value = if self.eat_punct("=") {
// Pattern default; represent as Assign so destructuring reads it.
let d = self.parse_assign()?;
Expr::Assign {
target: Box::new(Expr::Ident(name.clone())),
value: Box::new(d),
}
} else {
Expr::Ident(name)
};
props.push(Prop::KeyValue {
key,
value,
computed,
});
}
if !self.eat_punct(",") {
break;
}
}
self.expect_punct("}")?;
Ok(Expr::Object(props))
}
// ── functions / arrows ───────────────────────────────────────────────
fn parse_params(&mut self) -> Result<Vec<Param>, String> {
self.expect_punct("(")?;
let mut params = Vec::new();
while !self.is_punct(")") {
let rest = self.eat_punct("...");
let pattern = self.parse_binding_target()?;
let default = if !rest && self.eat_punct("=") {
Some(self.parse_assign()?)
} else {
None
};
params.push(Param {
pattern,
default,
rest,
});
if !self.eat_punct(",") {
break;
}
}
self.expect_punct(")")?;
Ok(params)
}
/// Try to parse an arrow function starting at the current position. Returns
/// `None` (without consuming) if the head is not an arrow.
fn try_parse_arrow(&mut self) -> Result<Option<Expr>, String> {
// `async` prefix on an arrow (`async x => …` / `async (…) => …`), only
// when `async` is not itself the parameter and no newline intervenes.
let mut is_async = false;
let mut base = self.pos;
if self.is_kw("async") && !self.peek_newline(1) {
let next = self.toks.get(self.pos + 1).map(|t| &t.tok);
let looks_async_arrow = matches!(next, Some(Tok::Punct(p)) if p == "(")
|| matches!(next, Some(Tok::Ident(n)) if !is_keyword(n) && self.peek_is_arrow_after(2));
if looks_async_arrow {
is_async = true;
base += 1;
}
}
// `ident => ...`
if let Some(Tok::Ident(name)) = self.toks.get(base).map(|t| &t.tok) {
if !is_keyword(name)
&& matches!(self.toks.get(base + 1).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
{
let name = name.clone();
if is_async {
self.advance(); // async
}
self.advance(); // ident
self.advance(); // =>
let body = self.parse_arrow_body(is_async)?;
return Ok(Some(Expr::Function {
params: vec![Param {
pattern: Expr::Ident(name),
default: None,
rest: false,
}],
body,
is_arrow: true,
name: None,
is_generator: false,
is_async,
is_method: false,
}));
}
}
// `( ... ) => ...`
if matches!(self.toks.get(base).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "(") {
if let Some(close) = self.matching_paren(base) {
let after = close + 1;
if matches!(self.toks.get(after).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
{
if is_async {
self.advance(); // async
}
let params = self.parse_params()?;
self.expect_punct("=>")?;
let body = self.parse_arrow_body(is_async)?;
return Ok(Some(Expr::Function {
params,
body,
is_arrow: true,
name: None,
is_generator: false,
is_async,
is_method: false,
}));
}
}
}
Ok(None)
}
fn parse_arrow_body(&mut self, is_async: bool) -> Result<FnBody, String> {
let (pg, pa) = (self.in_generator, self.in_async);
self.in_generator = false;
self.in_async = is_async;
let r = if self.is_punct("{") {
self.advance();
self.parse_block_body().map(FnBody::Block)
} else {
self.parse_assign().map(|e| FnBody::Expr(Box::new(e)))
};
self.in_generator = pg;
self.in_async = pa;
r
}
/// Whether the token `n` positions ahead is `=>`.
fn peek_is_arrow_after(&self, n: usize) -> bool {
matches!(self.toks.get(self.pos + n).map(|t| &t.tok), Some(Tok::Punct(p)) if p == "=>")
}
/// Index of the `)` matching the `(` at `open`, skipping nested brackets.
fn matching_paren(&self, open: usize) -> Option<usize> {
let mut depth = 0i32;
let mut i = open;
while i < self.toks.len() {
match &self.toks[i].tok {
Tok::Punct(p) if p == "(" || p == "[" || p == "{" => depth += 1,
Tok::Punct(p) if p == ")" || p == "]" || p == "}" => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
Tok::Eof => return None,
_ => {}
}
i += 1;
}
None
}
}
/// Parse a template-literal `${...}` field's raw source into an expression.
fn parse_expr_source(src: &str) -> Result<Expr, String> {
let toks = lex(src)?;
let mut p = Parser {
toks,
pos: 0,
in_generator: false,
in_async: false,
no_in: false,
};
let e = p.parse_expr()?;
Ok(e)
}