-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathstmt.rs
2573 lines (2222 loc) · 75.6 KB
/
stmt.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 swc_atoms::js_word;
use swc_common::Spanned;
use typed_arena::Arena;
use super::{pat::PatType, *};
use crate::error::SyntaxError;
mod module_item;
impl<'a, I: Tokens> Parser<I> {
pub fn parse_module_item(&mut self) -> PResult<ModuleItem> {
self.parse_stmt_like(true, true)
}
pub(super) fn parse_block_body<Type>(
&mut self,
mut allow_directives: bool,
top_level: bool,
end: Option<&'static Token>,
) -> PResult<Vec<Type>>
where
Self: StmtLikeParser<'a, Type>,
Type: IsDirective + From<Stmt>,
{
trace_cur!(self, parse_block_body);
let old_ctx = self.ctx();
let stmts = Arena::new();
while {
if self.input.cur().is_none() && end.is_some() {
let eof_text = self.input.dump_cur();
self.emit_err(
self.input.cur_span(),
SyntaxError::Expected(end.unwrap(), eof_text),
);
false
} else {
let c = cur!(self, false).ok();
c != end
}
} {
let stmt = self.parse_stmt_like(true, top_level)?;
if allow_directives {
allow_directives = false;
if stmt.is_use_strict() {
let ctx = Context {
strict: true,
..old_ctx
};
self.set_ctx(ctx);
if self.input.knows_cur() && !is!(self, ';') {
unreachable!(
"'use strict'; directive requires parser.input.cur to be empty or \
'}}', but current token was: {:?}",
self.input.cur()
)
}
}
}
stmts.alloc(stmt);
}
if self.input.cur().is_some() && end.is_some() {
bump!(self);
}
self.set_ctx(old_ctx);
Ok(stmts.into_vec())
}
/// Parse a statement but not a declaration.
pub fn parse_stmt(&mut self, top_level: bool) -> PResult<Stmt> {
trace_cur!(self, parse_stmt);
self.parse_stmt_like(false, top_level)
}
/// Parse a statement and maybe a declaration.
pub fn parse_stmt_list_item(&mut self, top_level: bool) -> PResult<Stmt> {
trace_cur!(self, parse_stmt_list_item);
self.parse_stmt_like(true, top_level)
}
/// Parse a statement, declaration or module item.
fn parse_stmt_like<Type>(&mut self, include_decl: bool, top_level: bool) -> PResult<Type>
where
Self: StmtLikeParser<'a, Type>,
Type: IsDirective + From<Stmt>,
{
trace_cur!(self, parse_stmt_like);
let _tracing = debug_tracing!(self, "parse_stmt_like");
let start = cur_pos!(self);
let decorators = self.parse_decorators(true)?;
if is_one_of!(self, "import", "export") {
return self.handle_import_export(top_level, decorators);
}
let ctx = Context {
will_expect_colon_for_cond: false,
allow_using_decl: true,
..self.ctx()
};
self.with_ctx(ctx)
.parse_stmt_internal(start, include_decl, top_level, decorators)
.map(From::from)
}
/// `parseStatementContent`
fn parse_stmt_internal(
&mut self,
start: BytePos,
include_decl: bool,
top_level: bool,
decorators: Vec<Decorator>,
) -> PResult<Stmt> {
trace_cur!(self, parse_stmt_internal);
if top_level && is!(self, "await") {
let valid = self.target() >= EsVersion::Es2017;
if !valid {
self.emit_err(self.input.cur_span(), SyntaxError::TopLevelAwait);
}
self.state.found_module_item = true;
if !self.ctx().can_be_module {
self.emit_err(self.input.cur_span(), SyntaxError::TopLevelAwaitInScript);
}
if peeked_is!(self, "using") {
assert_and_bump!(self, "await");
let v = self.parse_using_decl(start, true)?;
if let Some(v) = v {
return Ok(Stmt::Decl(Decl::Using(v)));
}
}
let expr = self.parse_await_expr()?;
let expr = self
.include_in_expr(true)
.parse_bin_op_recursively(expr, 0)?;
eat!(self, ';');
let span = span!(self, start);
return Ok(Stmt::Expr(ExprStmt { span, expr }));
}
let is_typescript = self.input.syntax().typescript();
if is_typescript && is!(self, "const") && peeked_is!(self, "enum") {
assert_and_bump!(self, "const");
assert_and_bump!(self, "enum");
return self
.parse_ts_enum_decl(start, true)
.map(Decl::from)
.map(Stmt::from);
}
match cur!(self, true)? {
tok!("await") if include_decl => {
if peeked_is!(self, "using") {
assert_and_bump!(self, "await");
let v = self.parse_using_decl(start, true)?;
if let Some(v) = v {
return Ok(Stmt::Decl(Decl::Using(v)));
}
}
}
tok!("break") | tok!("continue") => {
let is_break = is!(self, "break");
bump!(self);
let label = if eat!(self, ';') {
None
} else {
let i = self.parse_label_ident().map(Some)?;
expect!(self, ';');
i
};
let span = span!(self, start);
if is_break {
if label.is_some() && !self.state.labels.contains(&label.as_ref().unwrap().sym)
{
self.emit_err(span, SyntaxError::TS1116);
} else if !self.ctx().is_break_allowed {
self.emit_err(span, SyntaxError::TS1105);
}
} else if !self.ctx().is_continue_allowed {
self.emit_err(span, SyntaxError::TS1115);
} else if label.is_some()
&& !self.state.labels.contains(&label.as_ref().unwrap().sym)
{
self.emit_err(span, SyntaxError::TS1107);
}
return Ok(if is_break {
Stmt::Break(BreakStmt { span, label })
} else {
Stmt::Continue(ContinueStmt { span, label })
});
}
tok!("debugger") => {
bump!(self);
expect!(self, ';');
return Ok(Stmt::Debugger(DebuggerStmt {
span: span!(self, start),
}));
}
tok!("do") => {
return self.parse_do_stmt();
}
tok!("for") => {
return self.parse_for_stmt();
}
tok!("function") => {
if !include_decl {
self.emit_err(self.input.cur_span(), SyntaxError::DeclNotAllowed);
}
return self.parse_fn_decl(decorators).map(Stmt::from);
}
tok!("class") => {
if !include_decl {
self.emit_err(self.input.cur_span(), SyntaxError::DeclNotAllowed);
}
return self
.parse_class_decl(start, start, decorators, false)
.map(Stmt::from);
}
tok!("if") => {
return self.parse_if_stmt().map(Stmt::If);
}
tok!("return") => {
return self.parse_return_stmt();
}
tok!("switch") => {
return self.parse_switch_stmt();
}
tok!("throw") => {
return self.parse_throw_stmt();
}
// Error recovery
tok!("catch") => {
let span = self.input.cur_span();
self.emit_err(span, SyntaxError::TS1005);
let _ = self.parse_catch_clause();
let _ = self.parse_finally_block();
return Ok(Stmt::Expr(ExprStmt {
span,
expr: Box::new(Expr::Invalid(Invalid { span })),
}));
}
// Error recovery
tok!("finally") => {
let span = self.input.cur_span();
self.emit_err(span, SyntaxError::TS1005);
let _ = self.parse_finally_block();
return Ok(Stmt::Expr(ExprStmt {
span,
expr: Box::new(Expr::Invalid(Invalid { span })),
}));
}
tok!("try") => {
return self.parse_try_stmt();
}
tok!("with") => {
return self.parse_with_stmt();
}
tok!("while") => {
return self.parse_while_stmt();
}
tok!("var") => {
let v = self.parse_var_stmt(false)?;
return Ok(Stmt::Decl(Decl::Var(v)));
}
tok!("const") if include_decl => {
let v = self.parse_var_stmt(false)?;
return Ok(Stmt::Decl(Decl::Var(v)));
}
// 'let' can start an identifier reference.
tok!("let") if include_decl => {
let strict = self.ctx().strict;
let is_keyword = match peek!(self) {
Ok(t) => t.follows_keyword_let(strict),
_ => false,
};
if is_keyword {
let v = self.parse_var_stmt(false)?;
return Ok(Stmt::Decl(Decl::Var(v)));
}
}
tok!("using") if include_decl => {
let v = self.parse_using_decl(start, false)?;
if let Some(v) = v {
return Ok(Stmt::Decl(Decl::Using(v)));
}
}
tok!("interface") => {
if is_typescript
&& peeked_is!(self, IdentName)
&& !self.input.has_linebreak_between_cur_and_peeked()
{
let start = self.input.cur_pos();
bump!(self);
return Ok(Stmt::Decl(Decl::TsInterface(
self.parse_ts_interface_decl(start)?,
)));
}
}
tok!("enum") => {
if is_typescript
&& peeked_is!(self, IdentName)
&& !self.input.has_linebreak_between_cur_and_peeked()
{
let start = self.input.cur_pos();
bump!(self);
return Ok(Stmt::Decl(Decl::TsEnum(
self.parse_ts_enum_decl(start, false)?,
)));
}
}
tok!('{') => {
let ctx = Context {
allow_using_decl: true,
..self.ctx()
};
return self.with_ctx(ctx).parse_block(false).map(Stmt::Block);
}
_ => {}
}
if eat_exact!(self, ';') {
return Ok(Stmt::Empty(EmptyStmt {
span: span!(self, start),
}));
}
// Handle async function foo() {}
if is!(self, "async")
&& peeked_is!(self, "function")
&& !self.input.has_linebreak_between_cur_and_peeked()
{
return self.parse_async_fn_decl(decorators).map(From::from);
}
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
let expr = self.include_in_expr(true).parse_expr()?;
let expr = match *expr {
Expr::Ident(ident) => {
if eat!(self, ':') {
return self.parse_labelled_stmt(ident);
}
Box::new(Expr::Ident(ident))
}
_ => self.verify_expr(expr)?,
};
if let Expr::Ident(ref ident) = *expr {
if *ident.sym == js_word!("interface") && self.input.had_line_break_before_cur() {
self.emit_strict_mode_err(
ident.span,
SyntaxError::InvalidIdentInStrict(ident.sym.clone()),
);
eat!(self, ';');
return Ok(Stmt::Expr(ExprStmt {
span: span!(self, start),
expr,
}));
}
if self.input.syntax().typescript() {
if let Some(decl) = self.parse_ts_expr_stmt(decorators, ident.clone())? {
return Ok(Stmt::Decl(decl));
}
}
}
if let Expr::Ident(Ident { ref sym, span, .. }) = *expr {
match *sym {
js_word!("enum") | js_word!("interface") => {
self.emit_strict_mode_err(span, SyntaxError::InvalidIdentInStrict(sym.clone()));
}
_ => {}
}
}
if self.syntax().typescript() {
if let Expr::Ident(ref i) = *expr {
match i.sym {
js_word!("public") | js_word!("static") | js_word!("abstract") => {
if eat!(self, "interface") {
self.emit_err(i.span, SyntaxError::TS2427);
return self
.parse_ts_interface_decl(start)
.map(Decl::from)
.map(Stmt::from);
}
}
_ => {}
}
}
}
if eat!(self, ';') {
Ok(Stmt::Expr(ExprStmt {
span: span!(self, start),
expr,
}))
} else {
if let Token::BinOp(..) = *cur!(self, false)? {
self.emit_err(self.input.cur_span(), SyntaxError::TS1005);
let expr = self.parse_bin_op_recursively(expr, 0)?;
return Ok(ExprStmt {
span: span!(self, start),
expr,
}
.into());
}
syntax_error!(
self,
SyntaxError::ExpectedSemiForExprStmt { expr: expr.span() }
);
}
}
/// Utility function used to parse large if else statements iteratively.
///
/// THis function is recursive, but it is very cheap so stack overflow will
/// not occur.
fn adjust_if_else_clause(&mut self, cur: &mut IfStmt, alt: Box<Stmt>) {
cur.span = span!(self, cur.span.lo);
if let Some(Stmt::If(prev_alt)) = cur.alt.as_deref_mut() {
self.adjust_if_else_clause(prev_alt, alt)
} else {
debug_assert_eq!(cur.alt, None);
cur.alt = Some(alt);
}
}
fn parse_if_stmt(&mut self) -> PResult<IfStmt> {
let start = cur_pos!(self);
assert_and_bump!(self, "if");
let if_token = self.input.prev_span();
expect!(self, '(');
let ctx = Context {
ignore_else_clause: false,
..self.ctx()
};
let test = self
.with_ctx(ctx)
.include_in_expr(true)
.parse_expr()
.map_err(|err| {
Error::new(
err.span(),
SyntaxError::WithLabel {
inner: Box::new(err),
span: if_token,
note: "Tried to parse the condition for an if statement",
},
)
})?;
expect!(self, ')');
let cons = {
// Prevent stack overflow
crate::maybe_grow(512 * 1024, 2 * 1024 * 1024, || {
// Annex B
if !self.ctx().strict && is!(self, "function") {
// TODO: report error?
}
let ctx = Context {
ignore_else_clause: false,
..self.ctx()
};
self.with_ctx(ctx).parse_stmt(false).map(Box::new)
})?
};
// We parse `else` branch iteratively, to avoid stack overflow
// See https://github.com/swc-project/swc/pull/3961
let alt = if self.ctx().ignore_else_clause {
None
} else {
let mut cur = None;
let ctx = Context {
ignore_else_clause: true,
..self.ctx()
};
let last = loop {
if !eat!(self, "else") {
break None;
}
if !is!(self, "if") {
// As we eat `else` above, we need to parse statement once.
let last = crate::maybe_grow(512 * 1024, 2 * 1024 * 1024, || {
let ctx = Context {
ignore_else_clause: false,
..self.ctx()
};
self.with_ctx(ctx).parse_stmt(false)
})?;
break Some(last);
}
// We encountered `else if`
let alt = self.with_ctx(ctx).parse_if_stmt()?;
match &mut cur {
Some(cur) => {
self.adjust_if_else_clause(cur, Box::new(Stmt::If(alt)));
}
_ => {
cur = Some(alt);
}
}
};
match cur {
Some(mut cur) => {
if let Some(last) = last {
self.adjust_if_else_clause(&mut cur, Box::new(last));
}
Some(Stmt::If(cur))
}
_ => last,
}
}
.map(Box::new);
let span = span!(self, start);
Ok(IfStmt {
span,
test,
cons,
alt,
})
}
fn parse_return_stmt(&mut self) -> PResult<Stmt> {
let start = cur_pos!(self);
let stmt = self.parse_with(|p| {
assert_and_bump!(p, "return");
let arg = if is!(p, ';') {
None
} else {
p.include_in_expr(true).parse_expr().map(Some)?
};
expect!(p, ';');
Ok(Stmt::Return(ReturnStmt {
span: span!(p, start),
arg,
}))
});
if !self.ctx().in_function && !self.input.syntax().allow_return_outside_function() {
self.emit_err(span!(self, start), SyntaxError::ReturnNotAllowed);
}
stmt
}
fn parse_switch_stmt(&mut self) -> PResult<Stmt> {
let switch_start = cur_pos!(self);
assert_and_bump!(self, "switch");
expect!(self, '(');
let discriminant = self.include_in_expr(true).parse_expr()?;
expect!(self, ')');
let mut cases = vec![];
let mut span_of_previous_default = None;
expect!(self, '{');
let ctx = Context {
is_break_allowed: true,
..self.ctx()
};
self.with_ctx(ctx).parse_with(|p| {
while is_one_of!(p, "case", "default") {
let mut cons = vec![];
let is_case = is!(p, "case");
let case_start = cur_pos!(p);
bump!(p);
let test = if is_case {
p.include_in_expr(true).parse_expr().map(Some)?
} else {
if let Some(previous) = span_of_previous_default {
syntax_error!(p, SyntaxError::MultipleDefault { previous });
}
span_of_previous_default = Some(span!(p, case_start));
None
};
expect!(p, ':');
while !eof!(p) && !is_one_of!(p, "case", "default", '}') {
cons.push(p.parse_stmt_list_item(false)?);
}
cases.push(SwitchCase {
span: Span::new(case_start, p.input.prev_span().hi, Default::default()),
test,
cons,
});
}
Ok(())
})?;
// eof or rbrace
expect!(self, '}');
Ok(Stmt::Switch(SwitchStmt {
span: span!(self, switch_start),
discriminant,
cases,
}))
}
fn parse_throw_stmt(&mut self) -> PResult<Stmt> {
let start = cur_pos!(self);
assert_and_bump!(self, "throw");
if self.input.had_line_break_before_cur() {
// TODO: Suggest throw arg;
syntax_error!(self, SyntaxError::LineBreakInThrow);
}
let arg = self.include_in_expr(true).parse_expr()?;
expect!(self, ';');
let span = span!(self, start);
Ok(Stmt::Throw(ThrowStmt { span, arg }))
}
fn parse_try_stmt(&mut self) -> PResult<Stmt> {
let start = cur_pos!(self);
assert_and_bump!(self, "try");
let block = self.parse_block(false)?;
let catch_start = cur_pos!(self);
let handler = self.parse_catch_clause()?;
let finalizer = self.parse_finally_block()?;
if handler.is_none() && finalizer.is_none() {
self.emit_err(
Span::new(catch_start, catch_start, Default::default()),
SyntaxError::TS1005,
);
}
let span = span!(self, start);
Ok(Stmt::Try(Box::new(TryStmt {
span,
block,
handler,
finalizer,
})))
}
fn parse_catch_clause(&mut self) -> PResult<Option<CatchClause>> {
let start = cur_pos!(self);
Ok(if eat!(self, "catch") {
let param = self.parse_catch_param()?;
self.parse_block(false)
.map(|body| CatchClause {
span: span!(self, start),
param,
body,
})
.map(Some)?
} else {
None
})
}
fn parse_finally_block(&mut self) -> PResult<Option<BlockStmt>> {
Ok(if eat!(self, "finally") {
self.parse_block(false).map(Some)?
} else {
None
})
}
/// It's optional since es2019
fn parse_catch_param(&mut self) -> PResult<Option<Pat>> {
if eat!(self, '(') {
let mut pat = self.parse_binding_pat_or_ident()?;
let type_ann_start = cur_pos!(self);
if self.syntax().typescript() && eat!(self, ':') {
let ctx = Context {
in_type: true,
..self.ctx()
};
let ty = self.with_ctx(ctx).parse_with(|p| p.parse_ts_type())?;
// self.emit_err(ty.span(), SyntaxError::TS1196);
match &mut pat {
Pat::Ident(BindingIdent { type_ann, .. })
| Pat::Array(ArrayPat { type_ann, .. })
| Pat::Rest(RestPat { type_ann, .. })
| Pat::Object(ObjectPat { type_ann, .. }) => {
*type_ann = Some(Box::new(TsTypeAnn {
span: span!(self, type_ann_start),
type_ann: ty,
}));
}
Pat::Assign(..) => {}
Pat::Invalid(_) => {}
Pat::Expr(_) => {}
}
}
expect!(self, ')');
Ok(Some(pat))
} else {
Ok(None)
}
}
pub(super) fn parse_using_decl(
&mut self,
start: BytePos,
is_await: bool,
) -> PResult<Option<Box<UsingDecl>>> {
// using
// reader = init()
// is two statements
let _ = cur!(self, false);
if self.input.has_linebreak_between_cur_and_peeked() {
return Ok(None);
}
if !peeked_is!(self, BindingIdent) {
return Ok(None);
}
assert_and_bump!(self, "using");
let mut decls = vec![];
let mut first = true;
while first || eat!(self, ',') {
if first {
first = false;
}
// Handle
// var a,;
//
// NewLine is ok
if is_exact!(self, ';') || eof!(self) {
let span = self.input.prev_span();
self.emit_err(span, SyntaxError::TS1009);
break;
}
decls.push(self.parse_var_declarator(false, VarDeclKind::Var)?);
}
if !self.syntax().using_decl() {
self.emit_err(span!(self, start), SyntaxError::UsingDeclNotEnabled);
}
if !self.ctx().allow_using_decl {
self.emit_err(span!(self, start), SyntaxError::UsingDeclNotAllowed);
}
for decl in &decls {
match decl.name {
Pat::Ident(..) => {}
_ => {
self.emit_err(span!(self, start), SyntaxError::InvalidNameInUsingDecl);
}
}
if decl.init.is_none() {
self.emit_err(span!(self, start), SyntaxError::InitRequiredForUsingDecl);
}
}
Ok(Some(Box::new(UsingDecl {
span: span!(self, start),
is_await,
decls,
})))
}
pub(super) fn parse_var_stmt(&mut self, for_loop: bool) -> PResult<Box<VarDecl>> {
let start = cur_pos!(self);
let kind = match bump!(self) {
tok!("const") => VarDeclKind::Const,
tok!("let") => VarDeclKind::Let,
tok!("var") => VarDeclKind::Var,
_ => unreachable!(),
};
let var_span = span!(self, start);
let should_include_in = kind != VarDeclKind::Var || !for_loop;
if self.syntax().typescript() && for_loop {
let res = if is_one_of!(self, "in", "of") {
self.ts_look_ahead(|p| {
//
if !eat!(p, "of") && !eat!(p, "in") {
return Ok(false);
}
p.parse_assignment_expr()?;
expect!(p, ')');
Ok(true)
})
} else {
Ok(false)
};
match res {
Ok(true) => {
let pos = var_span.hi();
let span = Span::new(pos, pos, Default::default());
self.emit_err(span, SyntaxError::TS1123);
return Ok(Box::new(VarDecl {
span: span!(self, start),
kind,
declare: false,
decls: vec![],
}));
}
Err(..) => {}
_ => {}
}
}
let mut decls = vec![];
let mut first = true;
while first || eat!(self, ',') {
if first {
first = false;
}
let ctx = if should_include_in {
Context {
include_in_expr: true,
..self.ctx()
}
} else {
self.ctx()
};
// Handle
// var a,;
//
// NewLine is ok
if is_exact!(self, ';') || eof!(self) {
let prev_span = self.input.prev_span();
let span = if prev_span == var_span {
Span::new(prev_span.hi, prev_span.hi, Default::default())
} else {
prev_span
};
self.emit_err(span, SyntaxError::TS1009);
break;
}
decls.push(self.with_ctx(ctx).parse_var_declarator(for_loop, kind)?);
}
if !for_loop && !eat!(self, ';') {
self.emit_err(self.input.cur_span(), SyntaxError::TS1005);
let _ = self.parse_expr();
while !eat!(self, ';') {
bump!(self);
if let Some(Token::Error(_)) = self.input.cur() {
break;
}
}
}
Ok(Box::new(VarDecl {
span: span!(self, start),
declare: false,
kind,
decls,
}))
}
fn parse_var_declarator(
&mut self,
for_loop: bool,
kind: VarDeclKind,
) -> PResult<VarDeclarator> {
let start = cur_pos!(self);
let mut name = self.parse_binding_pat_or_ident()?;
let definite = if self.input.syntax().typescript() {
match name {
Pat::Ident(..) => eat!(self, '!'),
_ => false,
}
} else {
false
};
// Typescript extension
if self.input.syntax().typescript() && is!(self, ':') {
let type_annotation = self.try_parse_ts_type_ann()?;
match name {
Pat::Array(ArrayPat {
ref mut type_ann, ..
})
| Pat::Ident(BindingIdent {
ref mut type_ann, ..
})
| Pat::Object(ObjectPat {
ref mut type_ann, ..
})
| Pat::Rest(RestPat {
ref mut type_ann, ..
}) => {
*type_ann = type_annotation;
}
_ => unreachable!("invalid syntax: Pat: {:?}", name),
}
}
//FIXME: This is wrong. Should check in/of only on first loop.
let init = if !for_loop || !is_one_of!(self, "in", "of") {
if eat!(self, '=') {
let expr = self.parse_assignment_expr()?;
let expr = self.verify_expr(expr)?;