This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 665
/
expr.rs
1337 lines (1214 loc) · 32.5 KB
/
expr.rs
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
//! Expressions, these include `this`, identifiers, arrays, objects,
//! binary expressions, unary expressions, and more.
//!
//! See the [ECMAScript spec](https://www.ecma-international.org/ecma-262/5.1/#sec-11).
use super::decl::{arrow_body, maybe_private_name, parameter_list};
use super::pat::pattern;
use super::typescript::*;
use super::util::*;
use crate::syntax::class::class_expression;
use crate::syntax::function::function_expression;
use crate::syntax::object::object_expr;
use crate::syntax::stmt::is_semi;
use crate::{SyntaxKind::*, *};
pub const EXPR_RECOVERY_SET: TokenSet = token_set![VAR_KW, R_PAREN, L_PAREN, L_BRACK, R_BRACK];
pub const ASSIGN_TOKENS: TokenSet = token_set![
T![=],
T![+=],
T![-=],
T![*=],
T![%=],
T![<<=],
T![>>=],
T![>>>=],
T![&=],
T![|=],
T![^=],
T![&&=],
T![||=],
T![??=],
T![/=],
T![>>=]
];
pub const STARTS_EXPR: TokenSet = token_set![
T![!],
T!['('],
T!['['],
T!['{'],
T![++],
T![--],
T![~],
T![+],
T![-],
T![throw],
T![new],
T![typeof],
T![void],
T![delete],
T![ident],
T![...],
T![this],
T![yield],
T![await],
T![function],
T![class],
T![import],
T![super],
BACKTICK,
TRUE_KW,
FALSE_KW,
JS_NUMBER_LITERAL_TOKEN,
JS_STRING_LITERAL_TOKEN,
NULL_KW,
JS_REGEX_LITERAL_TOKEN
];
/// A literal expression.
///
/// `TRUE | FALSE | NUMBER | STRING | NULL`
// test literals
// 5
// true
// false
// 5n
// "foo"
// 'bar'
// null
pub fn literal(p: &mut Parser) -> Option<CompletedMarker> {
let literal_kind = match p.cur_tok().kind {
SyntaxKind::JS_NUMBER_LITERAL_TOKEN => {
if p.cur_src().ends_with('n') {
let m = p.start();
p.bump_remap(SyntaxKind::JS_BIG_INT_LITERAL_TOKEN);
return Some(m.complete(p, JS_BIG_INT_LITERAL));
};
SyntaxKind::JS_NUMBER_LITERAL
}
SyntaxKind::JS_STRING_LITERAL_TOKEN => SyntaxKind::JS_STRING_LITERAL,
SyntaxKind::NULL_KW => SyntaxKind::JS_NULL_LITERAL,
SyntaxKind::TRUE_KW | SyntaxKind::FALSE_KW => SyntaxKind::JS_BOOLEAN_LITERAL,
SyntaxKind::JS_REGEX_LITERAL_TOKEN => SyntaxKind::JS_REGEX_LITERAL,
_ => return None,
};
let m = p.start();
p.bump_any();
Some(m.complete(p, literal_kind))
}
/// An assignment expression such as `foo += bar` or `foo = 5`.
pub fn assign_expr(p: &mut Parser) -> Option<CompletedMarker> {
if p.at(T![<])
&& (token_set![T![ident], T![await], T![yield]].contains(p.nth(1)) || p.nth(1).is_keyword())
{
let res = try_parse_ts(p, |p| {
let m = p.start();
ts_type_params(p)?;
let res = assign_expr_base(p);
if res.map(|x| x.kind()) != Some(JS_ARROW_FUNCTION_EXPRESSION) {
m.abandon(p);
None
} else {
res.unwrap().undo_completion(p).abandon(p);
Some(m.complete(p, JS_ARROW_FUNCTION_EXPRESSION))
}
});
if let Some(mut res) = res {
res.err_if_not_ts(p, "type parameters can only be used in TypeScript files");
return Some(res);
}
}
assign_expr_base(p)
}
fn assign_expr_base(p: &mut Parser) -> Option<CompletedMarker> {
if p.state.in_generator && p.at(T![yield]) {
return Some(yield_expr(p));
}
let potential_arrow_start = matches!(p.cur(), T![ident] | T!['('] | T![yield] | T![await]);
let mut guard = p.with_state(ParserState {
potential_arrow_start,
..p.state.clone()
});
let checkpoint = guard.checkpoint();
let target = conditional_expr(&mut *guard)?;
assign_expr_recursive(&mut *guard, target, checkpoint)
}
pub(crate) fn is_valid_target(p: &mut Parser, marker: &CompletedMarker) -> bool {
match marker.kind() {
DOT_EXPR
| BRACKET_EXPR
| JS_REFERENCE_IDENTIFIER_EXPRESSION
| PRIVATE_PROP_ACCESS
| TS_CONST_ASSERTION
| TS_ASSERTION
| TS_NON_NULL => true,
JS_PARENTHESIZED_EXPRESSION => {
// avoid parsing the marker because it is incredibly expensive and this is a hot path
for (idx, event) in p.events[marker.start_pos as usize..].iter().enumerate() {
match event {
Event::Finish { .. } if marker.finish_pos as usize == idx => return true,
Event::Start {
kind: SyntaxKind::JS_PARENTHESIZED_EXPRESSION,
..
} => {}
Event::Start {
kind: SyntaxKind::TOMBSTONE,
..
} => {}
Event::Start { kind, .. } => {
return matches!(
kind,
DOT_EXPR
| BRACKET_EXPR | JS_REFERENCE_IDENTIFIER_EXPRESSION
| PRIVATE_PROP_ACCESS | TS_CONST_ASSERTION
| TS_ASSERTION | TS_NON_NULL
);
}
_ => {}
}
}
true
}
_ => false,
}
}
fn check_assign_target_from_marker(p: &mut Parser, marker: &CompletedMarker) {
if !is_valid_target(p, marker) {
let err = p
.err_builder(&format!(
"Invalid assignment to `{}`",
p.source(marker.range(p))
))
.primary(marker.range(p), "This expression cannot be assigned to");
p.error(err);
}
}
// test assign_expr
// foo += bar = b ??= 3;
// foo -= bar;
// [foo, bar] = baz;
// ({ bar, baz } = {});
// ({ bar: [baz], foo } = {});
fn assign_expr_recursive(
p: &mut Parser,
mut target: CompletedMarker,
checkpoint: Checkpoint,
) -> Option<CompletedMarker> {
// TODO: dont always reparse as pattern since it will yield wonky errors for `(foo = true) = bar`
if p.at_ts(ASSIGN_TOKENS) {
if p.at(T![=]) {
if !is_valid_target(p, &target) && target.kind() != TEMPLATE {
p.rewind(checkpoint);
target = pattern(p, false, true)?;
}
} else {
if !is_valid_target(p, &target) {
let err = p
.err_builder(&format!(
"Invalid assignment to `{}`",
p.source(target.range(p)).trim()
))
.primary(target.range(p), "This expression cannot be assigned to");
p.error(err);
}
let text = p.source(target.range(p));
if (text == "eval" || text == "arguments") && p.state.strict.is_some() && p.typescript()
{
let err = p
.err_builder("`eval` and `arguments` cannot be assigned to")
.primary(target.range(p), "");
p.error(err);
}
}
let m = target.precede(p);
p.bump_any();
assign_expr(p);
Some(m.complete(p, ASSIGN_EXPR))
} else {
Some(target)
}
}
// test yield_expr
// function *foo() {
// yield foo;
// yield* foo;
// }
pub fn yield_expr(p: &mut Parser) -> CompletedMarker {
let m = p.start();
p.expect(T![yield]);
if !is_semi(p, 0) && (p.at(T![*]) || p.at_ts(STARTS_EXPR)) {
p.eat(T![*]);
assign_expr(p);
}
m.complete(p, JS_YIELD_EXPRESSION)
}
/// A conditional expression such as `foo ? bar : baz`
// test conditional_expr
// foo ? bar : baz
// foo ? bar : baz ? bar : baz
pub fn conditional_expr(p: &mut Parser) -> Option<CompletedMarker> {
// test_err conditional_expr_err
// foo ? bar baz
// foo ? bar baz ? foo : bar
let lhs = binary_or_logical_expression(p);
if p.at(T![?]) {
let m = lhs?.precede(p);
p.bump_any();
assign_expr(&mut *p.with_state(ParserState {
in_cond_expr: true,
..p.state.clone()
}));
p.expect(T![:]);
assign_expr(p);
return Some(m.complete(p, JS_CONDITIONAL_EXPRESSION));
}
lhs
}
/// A binary expression such as `2 + 2` or `foo * bar + 2` or a logical expression 'a || b'
pub fn binary_or_logical_expression(p: &mut Parser) -> Option<CompletedMarker> {
let left = unary_expr(p);
binary_or_logical_expression_recursive(p, left, 0)
}
// test binary_expressions
// 5 * 5
// 6 ** 6 ** 7
// 1 + 2 * 3
// (1 + 2) * 3
// 1 / 2
// 74 in foo
// foo instanceof Array
// foo ?? bar
// 1 + 1 + 1 + 1
// 5 + 6 - 1 * 2 / 1 ** 6
// test_err binary_expressions_err
// foo(foo +);
// foo + * 2;
// !foo * bar;
fn binary_or_logical_expression_recursive(
p: &mut Parser,
left: Option<CompletedMarker>,
min_prec: u8,
) -> Option<CompletedMarker> {
if 7 > min_prec && !p.has_linebreak_before_n(0) && p.cur_src() == "as" {
let m = left.map(|x| x.precede(p)).unwrap_or_else(|| p.start());
p.bump_any();
let mut res = if p.eat(T![const]) {
m.complete(p, TS_CONST_ASSERTION)
} else {
ts_type(p);
m.complete(p, TS_ASSERTION)
};
res.err_if_not_ts(p, "type assertions can only be used in TypeScript files");
return binary_or_logical_expression_recursive(p, Some(res), min_prec);
}
let kind = match p.cur() {
T![>] if p.nth_at(1, T![>]) && p.nth_at(2, T![>]) => T![>>>],
T![>] if p.nth_at(1, T![>]) => T![>>],
k => k,
};
let precedence = match kind {
T![in] if p.state.include_in => 7,
T![instanceof] => 7,
_ => {
if let Some(prec) = get_precedence(kind) {
prec
} else {
return left;
}
}
};
if precedence <= min_prec {
return left;
}
let op = kind;
let op_tok = p.cur_tok();
let m = left.map(|m| m.precede(p)).unwrap_or_else(|| p.start());
if op == T![>>] {
p.bump_multiple(2, T![>>]);
} else if op == T![>>>] {
p.bump_multiple(3, T![>>>]);
} else {
p.bump_any();
}
// This is a hack to allow us to effectively recover from `foo + / bar`
let right = if get_precedence(p.cur()).is_some() && !p.at_ts(token_set![T![-], T![+], T![<]]) {
let err = p.err_builder(&format!("Expected an expression for the right hand side of a `{}`, but found an operator instead", p.token_src(&op_tok)))
.secondary(op_tok.range, "This operator requires a right hand side value")
.primary(p.cur_tok().range, "But this operator was encountered instead");
p.error(err);
None
} else {
unary_expr(p)
};
binary_or_logical_expression_recursive(
p,
right,
// ** is right recursive
if op == T![**] {
precedence - 1
} else {
precedence
},
);
let expression_kind = match op {
T![??] | T![||] | T![&&] => JS_LOGICAL_EXPRESSION,
_ => JS_BINARY_EXPRESSION,
};
let complete = m.complete(p, expression_kind);
binary_or_logical_expression_recursive(p, Some(complete), min_prec)
// FIXME(RDambrosio016): We should check for nullish-coalescing and logical expr being used together,
// however, i can't figure out a way to do this efficiently without using parse_marker which is way too
// expensive to use since this is a hot path
}
/// A parenthesis expression, also called a grouping expression.
///
/// `"(" Expr ")"`
pub fn paren_expr(p: &mut Parser) -> CompletedMarker {
let m = p.start();
p.expect(T!['(']);
expr(p);
p.expect(T![')']);
m.complete(p, JS_PARENTHESIZED_EXPRESSION)
}
/// A member or new expression with subscripts. e.g. `new foo`, `new Foo()`, `foo`, or `foo().bar[5]`
// test new_exprs
// new Foo()
// new foo;
// new.target
// new new new new Foo();
// new Foo(bar, baz, 6 + 6, foo[bar] + (foo) => {} * foo?.bar)
pub fn member_or_new_expr(p: &mut Parser, new_expr: bool) -> Option<CompletedMarker> {
if p.at(T![new]) {
// We must start the marker here and not outside or else we make
// a needless node if the node ends up just being a primary expr
let m = p.start();
p.bump_any();
// new.target
if p.at(T![.]) && p.token_src(&p.nth_tok(1)) == "target" {
p.bump_any();
p.bump_any();
let complete = m.complete(p, NEW_TARGET);
return Some(subscripts(p, complete, true));
}
let complete = if let Some(expr) = member_or_new_expr(p, new_expr) {
expr
} else {
m.abandon(p);
return None;
};
if complete.kind() == JS_ARROW_FUNCTION_EXPRESSION {
m.abandon(p);
return Some(complete);
}
if p.at(T![<]) {
if let Some(mut complete) = try_parse_ts(p, |p| {
let compl = ts_type_args(p);
if !p.at(T!['(']) {
return None;
}
compl
}) {
complete.err_if_not_ts(
p,
"`new` expressions can only have type arguments in TypeScript files",
);
}
}
if !new_expr || p.at(T!['(']) {
args(p);
let complete = m.complete(p, NEW_EXPR);
return Some(subscripts(p, complete, true));
}
return Some(m.complete(p, NEW_EXPR));
}
// super.foo and super[bar]
// test super_property_access
// super.foo
// super[bar]
// super[foo][bar]
if p.at(T![super]) && token_set!(T![.], T!['[']).contains(p.nth(1)) {
let m = p.start();
p.bump_any();
let lhs = match p.cur() {
T![.] => {
p.bump_any();
identifier_name(p);
m.complete(p, DOT_EXPR)
}
T!['['] => {
p.bump_any();
expr(p);
p.expect(T![']']);
m.complete(p, BRACKET_EXPR)
}
_ => unreachable!(),
};
return Some(subscripts(p, lhs, true));
}
let lhs = primary_expr(p)?;
Some(subscripts(p, lhs, true))
}
/// Dot, Array, or Call expr subscripts. Including optional chaining.
// test subscripts
// foo`bar`
// foo(bar)(baz)(baz)[bar]
pub fn subscripts(p: &mut Parser, mut lhs: CompletedMarker, no_call: bool) -> CompletedMarker {
// test_err subscripts_err
// foo()?.baz[].
// BAR`b
let mut should_try_parsing_ts = true;
while !p.at(EOF) {
match p.cur() {
T![?.] if p.nth_at(1, T!['(']) => {
lhs = {
let m = lhs.precede(p);
p.bump_any();
args(p);
m.complete(p, CALL_EXPR)
}
}
T!['('] if !no_call => {
lhs = {
let m = lhs.precede(p);
args(p);
m.complete(p, CALL_EXPR)
}
}
T![?.] if p.nth_at(1, T!['[']) => lhs = bracket_expr(p, lhs, true),
T!['['] => lhs = bracket_expr(p, lhs, false),
T![?.] => lhs = dot_expr(p, lhs, true),
T![.] => lhs = dot_expr(p, lhs, false),
T![!] if !p.has_linebreak_before_n(0) => {
lhs = {
// FIXME(RDambrosio016): we need to tell the lexer that an expression is not
// allowed here, but we have no way of doing that currently because we get all of the
// tokens ahead of time, therefore we need to switch to using the lexer as an iterator
// which isn't as simple as it sounds :)
let m = lhs.precede(p);
p.bump_any();
let mut comp = m.complete(p, TS_NON_NULL);
comp.err_if_not_ts(
p,
"non-null assertions can only be used in TypeScript files",
);
comp
}
}
T![<] if p.typescript() && should_try_parsing_ts => {
let res = try_parse_ts(p, |p| {
let m = lhs.precede(p);
// TODO: handle generic async arrow function expressions
ts_type_args(p)?;
if !no_call && p.at(T!['(']) {
args(p);
Some(m.complete(p, CALL_EXPR))
} else if p.at(BACKTICK) {
m.abandon(p);
Some(template(p, Some(lhs)))
} else {
None
}
});
if res.is_none() {
should_try_parsing_ts = false;
}
}
BACKTICK => lhs = template(p, Some(lhs)),
_ => return lhs,
}
}
lhs
}
/// A dot expression for accessing a property
// test dot_expr
// foo.bar
// foo.await
// foo.yield
// foo.for
// foo?.for
// foo?.bar
pub fn dot_expr(p: &mut Parser, lhs: CompletedMarker, optional_chain: bool) -> CompletedMarker {
let m = lhs.precede(p);
let range = if optional_chain {
Some(p.cur_tok().range).filter(|_| p.expect(T![?.]))
} else {
p.expect(T![.]);
None
};
if let Some(priv_range) = maybe_private_name(p).filter(|x| x.kind() == PRIVATE_NAME) {
if !p.syntax.class_fields {
let err = p
.err_builder("private identifiers are unsupported")
.primary(priv_range.range(p), "");
p.error(err);
return m.complete(p, ERROR);
}
if let Some(range) = range {
let err = p
.err_builder("optional chaining cannot contain private identifiers")
.primary(range, "");
p.error(err);
m.complete(p, ERROR)
} else {
m.complete(p, PRIVATE_PROP_ACCESS)
}
} else {
m.complete(p, DOT_EXPR)
}
}
/// An array expression for property access or indexing, such as `foo[0]` or `foo?.["bar"]`
// test bracket_expr
// foo[bar]
// foo[5 + 5]
// foo["bar"]
// foo[bar][baz]
// foo?.[bar]
pub fn bracket_expr(p: &mut Parser, lhs: CompletedMarker, optional_chain: bool) -> CompletedMarker {
// test_err bracket_expr_err
// foo[]
// foo?.[]
// foo[
let m = lhs.precede(p);
if optional_chain {
p.expect(T![?.]);
}
p.expect(T!['[']);
expr(p);
p.expect(T![']']);
m.complete(p, BRACKET_EXPR)
}
/// An identifier name, either an ident or a keyword
pub fn identifier_name(p: &mut Parser) -> Option<CompletedMarker> {
let m = p.start();
match p.cur() {
t if t.is_keyword() || t == T![ident] => p.bump_remap(T![ident]),
_ => {
let err = p
.err_builder("Expected an identifier or keyword")
.primary(p.cur_tok().range, "Expected an identifier or keyword here");
p.error(err);
m.abandon(p);
return None;
}
}
Some(m.complete(p, NAME))
}
/// Arguments to a function.
///
/// `"(" (AssignExpr ",")* ")"`
// test_err invalid_arg_LIST
// foo(a,b;
// foo(a,b var
pub fn args(p: &mut Parser) -> CompletedMarker {
let m = p.start();
p.expect(T!['(']);
let args_list = p.start();
while !p.at(EOF) && !p.at(T![')']) {
if p.at(T![...]) {
spread_element(p);
} else {
assign_expr(p);
}
if p.at(T![,]) {
p.bump_any();
} else {
break;
}
}
args_list.complete(p, LIST);
p.expect(T![')']);
m.complete(p, ARG_LIST)
}
// test paren_or_arrow_expr
// (foo);
// (foo) => {};
// (5 + 5);
// ({foo, bar, b: [f, ...baz]}) => {};
// (foo, ...bar) => {}
// test_err paren_or_arrow_expr_invalid_params
// (5 + 5) => {}
pub fn paren_or_arrow_expr(p: &mut Parser, can_be_arrow: bool) -> CompletedMarker {
let m = p.start();
let checkpoint = p.checkpoint();
let start = p.cur_tok().range.start;
p.expect(T!['(']);
let mut spread_range = None;
let mut trailing_comma_marker = None;
let mut params_marker = None;
let mut temp = p.with_state(ParserState {
potential_arrow_start: true,
..p.state.clone()
});
let is_empty = temp.eat(T![')']);
if !is_empty {
// stores a potentially started sequence expression
let mut sequence: Option<Marker> = None;
loop {
if temp.at(T![...]) {
let m = temp.start();
temp.bump_any();
pattern(&mut *temp, false, false);
if temp.eat(T![:]) {
if let Some(mut ty) = ts_type(&mut *temp) {
ty.err_if_not_ts(
&mut *temp,
"spread elements can only have type annotations in TypeScript files",
);
}
}
let complete = m.complete(&mut *temp, REST_PATTERN);
spread_range = Some(complete.range(&*temp));
if !temp.eat(T![')']) {
if temp.eat(T![=]) {
// formal params will handle this error
assign_expr(&mut *temp);
temp.expect(T![')']);
} else {
let err = temp.err_builder(&format!("expect a closing parenthesis after a spread element, but instead found `{}`", temp.cur_src()))
.primary(temp.cur_tok().range, "");
temp.err_recover(err, EXPR_RECOVERY_SET, false);
}
}
break;
}
let expr = assign_expr(&mut *temp);
if expr.is_some() && temp.at(T![:]) {
temp.rewind(checkpoint);
params_marker = Some(parameter_list(&mut *temp));
break;
}
if temp.at(T![,]) {
if temp.at(T![')']) {
// case where we are at a `,)` so the `,` is a trailing comma
let trailing_marker = temp.start();
temp.bump_any(); // bump ,
trailing_comma_marker = Some(trailing_marker.complete(&mut *temp, ERROR));
temp.bump_any(); // bump )
break;
} else {
// start a sequence expression that precedes the before parsed expression statement
// and bump the ',' into it.
sequence = sequence
.or_else(|| expr.map(|expr| expr.precede(&mut *temp)))
.or_else(|| Some(temp.start()));
temp.bump_any(); // bump ; into sequence expression which may or may not miss a lhs
}
} else {
temp.expect(T![')']);
break;
}
}
if let Some(sequence) = sequence.take() {
sequence.complete(&mut *temp, JS_SEQUENCE_EXPRESSION);
}
}
drop(temp);
// if we are in a ternary expression, then we need to try and see if parsing as an arrow worked
// if it did then we just return it, otherwise it should be interpreted as a grouping expr
if p.state.in_cond_expr && p.at(T![:]) && params_marker.is_none() {
let func = |p: &mut Parser| {
let p = &mut *p.with_state(ParserState {
no_recovery: true,
..p.state.clone()
});
p.rewind(checkpoint);
parameter_list(p);
if p.at(T![:]) {
if let Some(mut ret) = ts_type_or_type_predicate_ann(p, T![:]) {
ret.err_if_not_ts(
p,
"arrow functions can only have return types in TypeScript files",
);
}
}
p.expect_no_recover(T![=>])?;
arrow_body(p)?;
Some(())
};
// we can't just rewind the parser, since the function rewinds, and cloning and replacing the
// events does not work apparently, therefore we need to clone the entire parser
let cloned = p.clone();
if func(p).is_some() {
return m.complete(p, JS_ARROW_FUNCTION_EXPRESSION);
} else {
*p = cloned;
}
}
let has_ret_type = !p.state.in_cond_expr && p.at(T![:]) && !p.state.in_case_cond;
// This is an arrow expr, so we rewind the parser and reparse as parameters
// This is kind of inefficient but in the grand scheme of things it does not matter
// FIXME: verify that this logic is correct
if (p.at(T![=>]) && !p.has_linebreak_before_n(0)) || has_ret_type || params_marker.is_some() {
if !can_be_arrow && !p.at(T![:]) {
let err = p
.err_builder("Unexpected token `=>`")
.primary(p.cur_tok().range, "an arrow expression is not allowed here");
p.error(err);
} else {
if params_marker.is_none() {
// Rewind the parser so we can reparse as formal parameters
p.rewind(checkpoint);
parameter_list(p);
}
if p.at(T![:]) {
let complete = ts_type_or_type_predicate_ann(p, T![:]);
if let Some(mut complete) = complete {
complete.err_if_not_ts(
p,
"arrow functions can only have return types in TypeScript files",
);
}
}
p.bump_any();
arrow_body(p);
return m.complete(p, JS_ARROW_FUNCTION_EXPRESSION);
}
}
if let Some(params) = params_marker {
let err = p
.err_builder("grouping expressions cannot contain parameters")
.primary(params.range(p), "");
p.error(err);
return m.complete(p, JS_UNKNOWN_EXPRESSION);
}
if is_empty {
let err = p
.err_builder("grouping expressions cannot be empty")
.primary(start..p.cur_tok().range.start, "");
p.error(err);
return m.complete(p, JS_PARENTHESIZED_EXPRESSION);
}
if let Some(range) = spread_range {
let err = p
.err_builder("Illegal spread element inside grouping expression")
.primary(range, "");
p.error(err);
}
if let Some(complete) = trailing_comma_marker {
let err = p
.err_builder("Illegal trailing comma in grouping expression")
.primary(complete.range(p), "");
p.error(err);
}
m.complete(p, JS_PARENTHESIZED_EXPRESSION)
}
pub fn expr_or_spread(p: &mut Parser) -> Option<CompletedMarker> {
if p.at(T![...]) {
let m = p.start();
p.bump_any();
assign_expr(p);
Some(m.complete(p, SPREAD_ELEMENT))
} else {
assign_expr(p)
}
}
/// A general expression.
// test sequence_expr
// 1, 2, 3, 4, 5
pub fn expr(p: &mut Parser) -> Option<CompletedMarker> {
let first = assign_expr(p)?;
if p.at(T![,]) {
let sequence_expr_marker = first.precede(p);
p.bump_any();
expr(p)?;
Some(sequence_expr_marker.complete(p, JS_SEQUENCE_EXPRESSION))
} else {
Some(first)
}
}
/// A primary expression such as a literal, an object, an array, or `this`.
pub fn primary_expr(p: &mut Parser) -> Option<CompletedMarker> {
if let Some(m) = literal(p) {
return Some(m);
}
let complete = match p.cur() {
T![this] => {
// test this_expr
// this
// this.foo
let m = p.start();
p.bump_any();
m.complete(p, JS_THIS_EXPRESSION)
}
T![class] => {
// test class_expr
// let a = class {};
// let a = class foo {
// constructor() {}
// }
// foo[class {}]
class_expression(p)
}
// test async_ident
// let a = async;
T![ident] if p.cur_src() == "async" => {
// test async_function_expr
// let a = async function() {};
// let b = async function foo() {};
if p.nth_at(1, T![function]) {
function_expression(p)
} else {
// `async a => {}` and `async (a) => {}`
if p.state.potential_arrow_start
&& token_set![T![ident], T![yield], T!['(']].contains(p.nth(1))
{
// test async_arrow_expr
// let a = async foo => {}
// let b = async (bar) => {}
// async (foo, bar, ...baz) => foo
let m = p.start();
p.bump_remap(T![async]);
if p.at(T!['(']) {
parameter_list(p);
} else {
let m = p.start();
// test_err async_arrow_expr_await_parameter
// let a = async await => {}
p.bump_remap(T![ident]);
m.complete(p, JS_IDENTIFIER_BINDING);
}
if p.at(T![:]) {
let complete = ts_type_or_type_predicate_ann(p, T![:]);
if let Some(mut complete) = complete {
complete.err_if_not_ts(
p,
"arrow functions can only have return types in TypeScript files",
);
}
}
p.expect(T![=>]);
arrow_body(&mut *p.with_state(ParserState {
in_async: true,
..p.state.clone()
}));
m.complete(p, JS_ARROW_FUNCTION_EXPRESSION)
} else {
identifier_reference(p)?
}
}
}
T![function] => {
// test function_expr
// let a = function() {}
// let b = function foo() {}
function_expression(p)
}
T![ident] | T![yield] | T![await] => {
// test identifier_reference
// foo;
// yield;
// await;
let mut ident = identifier_reference(p)?;
if p.state.potential_arrow_start && p.at(T![=>]) && !p.has_linebreak_before_n(0) {
// test arrow_expr_single_param
// foo => {}
// yield => {}
// await => {}
// foo =>
// {}
// parameters are binding so we need to change the kind from NAME_REF to JS_IDENTIFIER_BINDING
ident.change_kind(p, JS_IDENTIFIER_BINDING);
let m = ident.precede(p);
p.bump_any();
arrow_body(p);
m.complete(p, JS_ARROW_FUNCTION_EXPRESSION)
} else {
ident
}
}
// test grouping_expr
// ((foo))