-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
expr.rs
2082 lines (1835 loc) · 74.6 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
use either::Either;
use swc_atoms::js_word;
use swc_common::{ast_node, collections::AHashMap, util::take::Take, Spanned};
use super::{pat::PatType, util::ExprExt, *};
use crate::{
lexer::TokenContext, parser::class_and_fn::IsSimpleParameterList, token::AssignOpToken,
};
mod ops;
#[cfg(test)]
mod tests;
mod verifier;
impl<I: Tokens> Parser<I> {
pub fn parse_expr(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_expr);
let _tracing = debug_tracing!(self, "parse_expr");
let expr = self.parse_assignment_expr()?;
let start = expr.span_lo();
if is!(self, ',') {
let mut exprs = vec![expr];
while eat!(self, ',') {
exprs.push(self.parse_assignment_expr()?);
}
return Ok(Box::new(Expr::Seq(SeqExpr {
span: span!(self, start),
exprs,
})));
}
Ok(expr)
}
///`parseMaybeAssign` (overridden)
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub(super) fn parse_assignment_expr(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_assignment_expr);
if self.input.syntax().typescript() && self.input.syntax().jsx() {
// Note: When the JSX plugin is on, type assertions (`<T> x`) aren't valid
// syntax.
if is!(self, JSXTagStart) {
let cur_context = self.input.token_context().current();
debug_assert_eq!(cur_context, Some(TokenContext::JSXOpeningTag));
// Only time j_oTag is pushed is right after j_expr.
debug_assert_eq!(
self.input.token_context().0[self.input.token_context().len() - 2],
TokenContext::JSXExpr
);
let res = self.try_parse_ts(|p| p.parse_assignment_expr_base().map(Some));
if let Some(res) = res {
return Ok(res);
} else {
debug_assert_eq!(
self.input.token_context().current(),
Some(TokenContext::JSXOpeningTag)
);
self.input.token_context_mut().pop();
debug_assert_eq!(
self.input.token_context().current(),
Some(TokenContext::JSXExpr)
);
self.input.token_context_mut().pop();
}
}
}
self.parse_assignment_expr_base()
}
/// Parse an assignment expression. This includes applications of
/// operators like `+=`.
///
/// `parseMaybeAssign`
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn parse_assignment_expr_base(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_assignment_expr_base);
if self.input.syntax().typescript()
&& (is_one_of!(self, '<', JSXTagStart))
&& (peeked_is!(self, IdentName) || peeked_is!(self, JSXName))
{
let ctx = Context {
will_expect_colon_for_cond: false,
..self.ctx()
};
let res = self.with_ctx(ctx).try_parse_ts(|p| {
if is!(p, JSXTagStart) {
if let Some(TokenContext::JSXOpeningTag) = p.input.token_context().current() {
p.input.token_context_mut().pop();
debug_assert_eq!(
p.input.token_context().current(),
Some(TokenContext::JSXExpr)
);
p.input.token_context_mut().pop();
}
}
let type_parameters = p.parse_ts_type_params(false)?;
let mut arrow = p.parse_assignment_expr_base()?;
match *arrow {
Expr::Arrow(ArrowExpr {
ref mut span,
ref mut type_params,
..
}) => {
*span = Span::new(type_parameters.span.lo, span.hi, Default::default());
*type_params = Some(type_parameters);
}
_ => unexpected!(p, "("),
}
Ok(Some(arrow))
});
if let Some(res) = res {
return Ok(res);
}
}
if self.ctx().in_generator && is!(self, "yield") {
return self.parse_yield_expr();
}
self.state.potential_arrow_start = match *cur!(self, true)? {
Word(Word::Ident(..)) | tok!('(') | tok!("yield") => Some(cur_pos!(self)),
_ => None,
};
let start = cur_pos!(self);
// Try to parse conditional expression.
let cond = self.parse_cond_expr()?;
return_if_arrow!(self, cond);
match *cond {
// if cond is conditional expression but not left-hand-side expression,
// just return it.
Expr::Cond(..) | Expr::Bin(..) | Expr::Unary(..) | Expr::Update(..) => return Ok(cond),
_ => {}
}
self.finish_assignment_expr(start, cond)
}
fn finish_assignment_expr(&mut self, start: BytePos, cond: Box<Expr>) -> PResult<Box<Expr>> {
trace_cur!(self, finish_assignment_expr);
match cur!(self, false) {
Ok(&Token::AssignOp(op)) => {
let left = if op == AssignOpToken::Assign {
self.reparse_expr_as_pat(PatType::AssignPat, cond)
.map(Box::new)
.map(PatOrExpr::Pat)?
} else {
// It is an early Reference Error if IsValidSimpleAssignmentTarget of
// LeftHandSideExpression is false.
if !cond.is_valid_simple_assignment_target(self.ctx().strict) {
if self.input.syntax().typescript() {
self.emit_err(cond.span(), SyntaxError::TS2406);
} else {
self.emit_err(cond.span(), SyntaxError::NotSimpleAssign)
}
}
if self.input.syntax().typescript()
&& cond
.as_ident()
.map(|i| i.is_reserved_in_strict_bind())
.unwrap_or(false)
{
self.emit_strict_mode_err(cond.span(), SyntaxError::TS1100);
}
// TODO
PatOrExpr::Expr(cond)
};
bump!(self);
let right = self.parse_assignment_expr()?;
Ok(Box::new(Expr::Assign(AssignExpr {
span: span!(self, start),
op,
// TODO:
left,
right,
})))
}
_ => Ok(cond),
}
}
/// Spec: 'ConditionalExpression'
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn parse_cond_expr(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_cond_expr);
let start = cur_pos!(self);
let test = self.parse_bin_expr()?;
return_if_arrow!(self, test);
if eat!(self, '?') {
let ctx = Context {
in_cond_expr: true,
will_expect_colon_for_cond: true,
include_in_expr: true,
..self.ctx()
};
let cons = self.with_ctx(ctx).parse_assignment_expr()?;
expect!(self, ':');
let ctx = Context {
in_cond_expr: true,
will_expect_colon_for_cond: false,
..self.ctx()
};
let alt = self.with_ctx(ctx).parse_assignment_expr()?;
let span = Span::new(start, alt.span_hi(), Default::default());
Ok(Box::new(Expr::Cond(CondExpr {
span,
test,
cons,
alt,
})))
} else {
Ok(test)
}
}
/// Parse a primary expression or arrow function
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub(super) fn parse_primary_expr(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_primary_expr);
let _ = self.input.cur();
let start = cur_pos!(self);
let can_be_arrow = self
.state
.potential_arrow_start
.map(|s| s == start)
.unwrap_or(false);
if let Some(tok) = self.input.cur() {
match tok {
tok!("this") => {
self.input.bump();
return Ok(Box::new(Expr::This(ThisExpr {
span: span!(self, start),
})));
}
tok!("import") => {
let import = self.parse_ident_name()?;
if is!(self, '.') {
self.state.found_module_item = true;
if !self.ctx().can_be_module {
let span = span!(self, start);
self.emit_err(span, SyntaxError::ImportMetaInScript);
}
return self
.parse_import_meta_prop(Import { span: import.span })
.map(Expr::MetaProp)
.map(Box::new);
}
return self.parse_dynamic_import(start, import.span);
}
tok!("async") => {
if peeked_is!(self, "function")
&& !self.input.has_linebreak_between_cur_and_peeked()
{
// handle `async function` expression
return self.parse_async_fn_expr();
}
if can_be_arrow && self.input.syntax().typescript() && peeked_is!(self, '<') {
// try parsing `async<T>() => {}`
if let Some(res) = self.try_parse_ts(|p| {
let start = cur_pos!(p);
assert_and_bump!(p, "async");
p.try_parse_ts_generic_async_arrow_fn(start)
}) {
return Ok(Box::new(Expr::Arrow(res)));
}
}
if can_be_arrow
&& peeked_is!(self, '(')
&& !self.input.has_linebreak_between_cur_and_peeked()
{
expect!(self, "async");
let async_span = self.input.prev_span();
return self.parse_paren_expr_or_arrow_fn(can_be_arrow, Some(async_span));
}
}
tok!('[') => {
let ctx = Context {
will_expect_colon_for_cond: false,
..self.ctx()
};
return self.with_ctx(ctx).parse_array_lit();
}
tok!('{') => {
return self.parse_object();
}
// Handle FunctionExpression and GeneratorExpression
tok!("function") => {
return self.parse_fn_expr();
}
// Literals
tok!("null")
| tok!("true")
| tok!("false")
| Token::Num { .. }
| Token::BigInt { .. }
| Token::Str { .. } => {
return Ok(Box::new(Expr::Lit(self.parse_lit()?)));
}
// Regexp
tok!('/') | tok!("/=") => {
bump!(self);
self.input.set_next_regexp(Some(start));
if let Some(Token::Regex(..)) = self.input.cur() {
self.input.set_next_regexp(None);
match bump!(self) {
Token::Regex(exp, flags) => {
let span = span!(self, start);
let mut flags_count = flags.chars().fold(
AHashMap::<char, usize>::default(),
|mut map, flag| {
let key = match flag {
'g' | 'i' | 'm' | 's' | 'u' | 'y' | 'd' => flag,
_ => '\u{0000}', // special marker for unknown flags
};
map.entry(key).and_modify(|count| *count += 1).or_insert(1);
map
},
);
if flags_count.remove(&'\u{0000}').is_some() {
self.emit_err(span, SyntaxError::UnknownRegExpFlags);
}
if let Some((flag, _)) =
flags_count.iter().find(|(_, count)| **count > 1)
{
self.emit_err(span, SyntaxError::DuplicatedRegExpFlags(*flag));
}
return Ok(Box::new(Expr::Lit(Lit::Regex(Regex {
span,
exp,
flags,
}))));
}
_ => unreachable!(),
}
}
}
tok!('`') => {
let ctx = Context {
will_expect_colon_for_cond: false,
..self.ctx()
};
// parse template literal
return Ok(Box::new(Expr::Tpl(self.with_ctx(ctx).parse_tpl(false)?)));
}
tok!('(') => {
return self.parse_paren_expr_or_arrow_fn(can_be_arrow, None);
}
_ => {}
}
}
let decorators = self.parse_decorators(false)?;
if is!(self, "class") {
return self.parse_class_expr(start, decorators);
}
if is!(self, "let")
|| (self.input.syntax().typescript() && is_one_of!(self, IdentRef, "await"))
|| is!(self, IdentRef)
{
let ctx = self.ctx();
let id = self.parse_ident(!ctx.in_generator, !ctx.in_async)?;
if id.is_reserved_in_strict_mode(self.ctx().module && !self.ctx().in_declare) {
self.emit_strict_mode_err(
self.input.prev_span(),
SyntaxError::InvalidIdentInStrict(id.sym.clone()),
);
}
if can_be_arrow
&& id.sym == js_word!("async")
&& !self.input.had_line_break_before_cur()
&& is!(self, BindingIdent)
{
// see https://github.com/tc39/ecma262/issues/2034
// ```js
// for(async of
// for(async of x);
// for(async of =>{};;);
// ```
if ctx.expr_ctx.for_loop_init && is!(self, "of") && !peeked_is!(self, "=>") {
// ```spec https://tc39.es/ecma262/#prod-ForInOfStatement
// for ( [lookahead ∉ { let, async of }] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]
// [+Await] for await ( [lookahead ≠ let] LeftHandSideExpression[?Yield, ?Await] of AssignmentExpression[+In, ?Yield, ?Await] ) Statement[?Yield, ?Await, ?Return]
// ```
if !ctx.expr_ctx.for_await_loop_init {
self.emit_err(self.input.prev_span(), SyntaxError::TS1106);
}
return Ok(Box::new(Expr::Ident(id)));
}
let ident = self.parse_binding_ident()?;
if self.input.syntax().typescript()
&& ident.id.sym == js_word!("as")
&& !is!(self, "=>")
{
// async as type
let type_ann = self.in_type().parse_with(|p| p.parse_ts_type())?;
return Ok(Box::new(Expr::TsAs(TsAsExpr {
span: span!(self, start),
expr: Box::new(Expr::Ident(id)),
type_ann,
})));
}
// async a => body
let arg = Pat::from(ident);
let params = vec![arg];
expect!(self, "=>");
let body =
self.parse_fn_body(true, false, true, params.is_simple_parameter_list())?;
return Ok(Box::new(Expr::Arrow(ArrowExpr {
span: span!(self, start),
body,
params,
is_async: true,
is_generator: false,
return_type: None,
type_params: None,
})));
} else if can_be_arrow && !self.input.had_line_break_before_cur() && eat!(self, "=>") {
if self.ctx().strict && id.is_reserved_in_strict_bind() {
self.emit_strict_mode_err(id.span, SyntaxError::EvalAndArgumentsInStrict)
}
let params = vec![id.into()];
let body =
self.parse_fn_body(false, false, true, params.is_simple_parameter_list())?;
return Ok(Box::new(Expr::Arrow(ArrowExpr {
span: span!(self, start),
body,
params,
is_async: false,
is_generator: false,
// TODO
return_type: None,
// TODO
type_params: None,
})));
} else {
return Ok(Box::new(Expr::Ident(id)));
}
}
if eat!(self, '#') {
let id = self.parse_ident_name()?;
return Ok(Box::new(Expr::PrivateName(PrivateName {
span: span!(self, start),
id,
})));
}
syntax_error!(self, self.input.cur_span(), SyntaxError::TS1109)
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn parse_array_lit(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_array_lit);
let start = cur_pos!(self);
assert_and_bump!(self, '[');
let mut elems = vec![];
while !eof!(self) && !is!(self, ']') {
if is!(self, ',') {
expect!(self, ',');
elems.push(None);
continue;
}
elems.push(
self.include_in_expr(true)
.parse_expr_or_spread()
.map(Some)?,
);
if !is!(self, ']') {
expect!(self, ',');
if is!(self, ']') {
self.state
.trailing_commas
.insert(start, self.input.prev_span());
}
}
}
expect!(self, ']');
let span = span!(self, start);
Ok(Box::new(Expr::Array(ArrayLit { span, elems })))
}
#[allow(dead_code)]
fn parse_member_expr(&mut self) -> PResult<Box<Expr>> {
self.parse_member_expr_or_new_expr(false)
}
/// `parseImportMetaProperty`
pub(super) fn parse_import_meta_prop(&mut self, import: Import) -> PResult<MetaPropExpr> {
expect!(self, '.');
let _ = if is!(self, "meta") {
self.parse_ident_name()?
} else {
unexpected!(self, "meta");
};
Ok(MetaPropExpr {
span: span!(self, import.span.lo()),
kind: MetaPropKind::ImportMeta,
})
}
/// `is_new_expr`: true iff we are parsing production 'NewExpression'.
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn parse_member_expr_or_new_expr(&mut self, is_new_expr: bool) -> PResult<Box<Expr>> {
trace_cur!(self, parse_member_expr_or_new_expr);
let start = cur_pos!(self);
if eat!(self, "new") {
if eat!(self, '.') {
if eat!(self, "target") {
let span = span!(self, start);
let expr = Box::new(Expr::MetaProp(MetaPropExpr {
span,
kind: MetaPropKind::NewTarget,
}));
let ctx = self.ctx();
if (!ctx.inside_non_arrow_function_scope) && !ctx.in_parameters && !ctx.in_class
{
self.emit_err(span, SyntaxError::InvalidNewTarget);
}
return self.parse_subscripts(Callee::Expr(expr), true, false);
}
unexpected!(self, "target")
}
// 'NewExpression' allows new call without paren.
let callee = self.parse_member_expr_or_new_expr(is_new_expr)?;
return_if_arrow!(self, callee);
if is_new_expr {
match *callee {
Expr::OptChain(OptChainExpr {
question_dot_token, ..
}) => {
syntax_error!(
self,
question_dot_token,
SyntaxError::OptChainCannotFollowConstructorCall
)
}
Expr::Member(MemberExpr { ref obj, .. }) => {
if let Expr::OptChain(OptChainExpr {
question_dot_token, ..
}) = **obj
{
syntax_error!(
self,
question_dot_token,
SyntaxError::OptChainCannotFollowConstructorCall
)
}
}
_ => {}
}
}
let type_args = if self.input.syntax().typescript() && is!(self, '<') {
self.try_parse_ts(|p| {
let args = p.parse_ts_type_args()?;
if !is!(p, '(') {
// This will fail
expect!(p, '(');
}
Ok(Some(args))
})
} else {
None
};
if !is_new_expr || is!(self, '(') {
// Parsed with 'MemberExpression' production.
let args = self.parse_args(false).map(Some)?;
let new_expr = Callee::Expr(Box::new(Expr::New(NewExpr {
span: span!(self, start),
callee,
args,
type_args,
})));
// We should parse subscripts for MemberExpression.
// Because it's left recursive.
return self.parse_subscripts(new_expr, true, false);
}
// Parsed with 'NewExpression' production.
return Ok(Box::new(Expr::New(NewExpr {
span: span!(self, start),
callee,
args: None,
type_args,
})));
}
if eat!(self, "super") {
let base = Callee::Super(Super {
span: span!(self, start),
});
return self.parse_subscripts(base, true, false);
}
if eat!(self, "import") {
let base = Callee::Import(Import {
span: span!(self, start),
});
return self.parse_subscripts(base, true, false);
}
let obj = self.parse_primary_expr()?;
return_if_arrow!(self, obj);
let type_args = if self.syntax().typescript() && is!(self, '<') {
self.with_ctx(Context {
prefer_bin_op_over_type_arg_closing: true,
..self.ctx()
})
.try_parse_ts_type_args()
} else {
None
};
let obj = if let Some(type_args) = type_args {
Box::new(Expr::TsInstantiation(TsInstantiation {
expr: obj,
type_args,
span: span!(self, start),
}))
} else {
obj
};
self.parse_subscripts(Callee::Expr(obj), true, false)
}
/// Parse `NewExpression`.
/// This includes `MemberExpression`.
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub(super) fn parse_new_expr(&mut self) -> PResult<Box<Expr>> {
trace_cur!(self, parse_new_expr);
self.parse_member_expr_or_new_expr(true)
}
/// Parse `Arguments[Yield, Await]`
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub(super) fn parse_args(&mut self, is_dynamic_import: bool) -> PResult<Vec<ExprOrSpread>> {
trace_cur!(self, parse_args);
let ctx = Context {
will_expect_colon_for_cond: false,
..self.ctx()
};
self.with_ctx(ctx).parse_with(|p| {
let start = cur_pos!(p);
expect!(p, '(');
let mut first = true;
let mut expr_or_spreads = Vec::with_capacity(8);
while !eof!(p) && !is!(p, ')') {
if first {
first = false;
} else {
expect!(p, ',');
// Handle trailing comma.
if is!(p, ')') {
if is_dynamic_import && !p.input.syntax().import_assertions() {
syntax_error!(
p,
span!(p, start),
SyntaxError::TrailingCommaInsideImport
)
}
break;
}
}
expr_or_spreads.push(p.include_in_expr(true).parse_expr_or_spread()?);
}
expect!(p, ')');
Ok(expr_or_spreads)
})
}
/// AssignmentExpression[+In, ?Yield, ?Await]
/// ...AssignmentExpression[+In, ?Yield, ?Await]
pub(super) fn parse_expr_or_spread(&mut self) -> PResult<ExprOrSpread> {
trace_cur!(self, parse_expr_or_spread);
let start = cur_pos!(self);
if eat!(self, "...") {
let spread_span = span!(self, start);
let spread = Some(spread_span);
self.include_in_expr(true)
.parse_assignment_expr()
.map_err(|err| {
Error::new(
err.span(),
SyntaxError::WithLabel {
inner: Box::new(err),
span: spread_span,
note: "An expression should follow '...'",
},
)
})
.map(|expr| ExprOrSpread { spread, expr })
} else {
self.parse_assignment_expr()
.map(|expr| ExprOrSpread { spread: None, expr })
}
}
/// Parse paren expression or arrow function expression.
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn parse_paren_expr_or_arrow_fn(
&mut self,
can_be_arrow: bool,
async_span: Option<Span>,
) -> PResult<Box<Expr>> {
trace_cur!(self, parse_paren_expr_or_arrow_fn);
let expr_start = async_span.map(|x| x.lo()).unwrap_or_else(|| cur_pos!(self));
// At this point, we can't know if it's parenthesized
// expression or head of arrow function.
// But as all patterns of javascript is subset of
// expressions, we can parse both as expression.
let ctx = Context {
will_expect_colon_for_cond: false,
..self.ctx()
};
let (paren_items, trailing_comma) = self
.with_ctx(ctx)
.include_in_expr(true)
.parse_args_or_pats()?;
let has_pattern = paren_items
.iter()
.any(|item| matches!(item, PatOrExprOrSpread::Pat(..)));
let will_expect_colon_for_cond = self.ctx().will_expect_colon_for_cond;
// This is slow path. We handle arrow in conditional expression.
if self.syntax().typescript() && self.ctx().in_cond_expr && is!(self, ':') {
// TODO: Remove clone
let items_ref = &paren_items;
if let Some(expr) = self.try_parse_ts(|p| {
let return_type = p.parse_ts_type_or_type_predicate_ann(&tok!(':'))?;
expect!(p, "=>");
let params: Vec<Pat> = p
.parse_paren_items_as_params(items_ref.clone(), trailing_comma)?
.into_iter()
.collect();
let body: BlockStmtOrExpr = p.parse_fn_body(
async_span.is_some(),
false,
true,
params.is_simple_parameter_list(),
)?;
if will_expect_colon_for_cond && !is!(p, ':') {
trace_cur!(p, parse_arrow_in_cond__fail);
unexpected!(p, "fail")
}
Ok(Some(Box::new(Expr::Arrow(ArrowExpr {
span: span!(p, expr_start),
is_async: async_span.is_some(),
is_generator: false,
params,
body,
return_type: Some(return_type),
type_params: None,
}))))
}) {
return Ok(expr);
}
}
let return_type = if !self.ctx().will_expect_colon_for_cond
&& self.input.syntax().typescript()
&& is!(self, ':')
{
self.try_parse_ts(|p| {
let return_type = p.parse_ts_type_or_type_predicate_ann(&tok!(':'))?;
if !is!(p, "=>") {
unexpected!(p, "fail")
}
Ok(Some(return_type))
})
} else {
None
};
// we parse arrow function at here, to handle it efficiently.
if has_pattern || return_type.is_some() || is!(self, "=>") {
if self.input.had_line_break_before_cur() {
syntax_error!(
self,
span!(self, expr_start),
SyntaxError::LineBreakBeforeArrow
);
}
if !can_be_arrow {
syntax_error!(self, span!(self, expr_start), SyntaxError::ArrowNotAllowed);
}
expect!(self, "=>");
let params: Vec<Pat> = self
.parse_paren_items_as_params(paren_items, trailing_comma)?
.into_iter()
.collect();
let body: BlockStmtOrExpr = self.parse_fn_body(
async_span.is_some(),
false,
true,
params.is_simple_parameter_list(),
)?;
let arrow_expr = ArrowExpr {
span: span!(self, expr_start),
is_async: async_span.is_some(),
is_generator: false,
params,
body,
return_type,
type_params: None,
};
if let BlockStmtOrExpr::BlockStmt(..) = arrow_expr.body {
if let Ok(&Token::BinOp(..)) = cur!(self, false) {
// ) is required
self.emit_err(self.input.cur_span(), SyntaxError::TS1005);
let errorred_expr =
self.parse_bin_op_recursively(Box::new(arrow_expr.into()), 0)?;
if !is!(self, ';') {
// ; is required
self.emit_err(self.input.cur_span(), SyntaxError::TS1005);
}
return Ok(errorred_expr);
}
}
return Ok(Box::new(Expr::Arrow(arrow_expr)));
} else {
// If there's no arrow function, we have to check there's no
// AssignProp in lhs to check against assignment in object literals
// like (a, {b = 1});
for expr_or_spread in paren_items.iter() {
if let PatOrExprOrSpread::ExprOrSpread(e) = expr_or_spread {
if let Expr::Object(o) = &*e.expr {
for p in o.props.iter() {
if let PropOrSpread::Prop(prop) = p {
if let Prop::Assign(..) = **prop {
self.emit_err(prop.span(), SyntaxError::AssignProperty);
}
}
}
}
}
}
}
let expr_or_spreads = paren_items
.into_iter()
.map(|item| -> PResult<_> {
match item {
PatOrExprOrSpread::ExprOrSpread(e) => Ok(e),
_ => syntax_error!(self, item.span(), SyntaxError::InvalidExpr),
}
})
.collect::<Result<Vec<_>, _>>()?;
if let Some(async_span) = async_span {
// It's a call expression
return Ok(Box::new(Expr::Call(CallExpr {
span: span!(self, async_span.lo()),
callee: Callee::Expr(Box::new(Expr::Ident(Ident::new(
"async".into(),
async_span,
)))),
args: expr_or_spreads,
type_args: None,
})));
}
// It was not head of arrow function.
if expr_or_spreads.is_empty() {
syntax_error!(
self,
Span::new(expr_start, last_pos!(self), Default::default()),
SyntaxError::EmptyParenExpr
);
}
// TODO: Verify that invalid expression like {a = 1} does not exists.
// ParenthesizedExpression cannot contain spread.
if expr_or_spreads.len() == 1 {
let expr = match expr_or_spreads.into_iter().next().unwrap() {
ExprOrSpread {
spread: Some(..),
ref expr,
} => syntax_error!(self, expr.span(), SyntaxError::SpreadInParenExpr),
ExprOrSpread { expr, .. } => expr,
};
Ok(Box::new(Expr::Paren(ParenExpr {
span: span!(self, expr_start),
expr,
})))
} else {
debug_assert!(expr_or_spreads.len() >= 2);
let mut exprs = Vec::with_capacity(expr_or_spreads.len());
for expr in expr_or_spreads {
match expr {
ExprOrSpread {
spread: Some(..),
ref expr,
} => syntax_error!(self, expr.span(), SyntaxError::SpreadInParenExpr),
ExprOrSpread { expr, .. } => exprs.push(expr),
}
}
debug_assert!(exprs.len() >= 2);
// span of sequence expression should not include '(', ')'
let seq_expr = Box::new(Expr::Seq(SeqExpr {
span: Span::new(
exprs.first().unwrap().span_lo(),