-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
typescript.rs
2952 lines (2551 loc) · 90.5 KB
/
typescript.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 std::fmt::Write;
use either::Either;
use swc_atoms::js_word;
use swc_common::{Spanned, SyntaxContext};
use super::*;
use crate::{lexer::TokenContexts, parser::class_and_fn::IsSimpleParameterList, token::Keyword};
impl<I: Tokens> Parser<I> {
/// `tsNextTokenCanFollowModifier`
fn ts_next_token_can_follow_modifier(&mut self) -> PResult<bool> {
debug_assert!(self.input.syntax().typescript());
// Note: TypeScript's implementation is much more complicated because
// more things are considered modifiers there.
// This implementation only handles modifiers not handled by @babel/parser
// itself. And "static". TODO: Would be nice to avoid lookahead. Want a
// hasLineBreakUpNext() method...
bump!(self);
Ok(!self.input.had_line_break_before_cur()
&& is_one_of!(self, '[', '{', '*', "...", '#', IdentName, Str, Num, BigInt))
}
/// Parses a modifier matching one the given modifier names.
///
/// `tsParseModifier`
pub(super) fn parse_ts_modifier(
&mut self,
allowed_modifiers: &[&'static str],
stop_on_start_of_class_static_blocks: bool,
) -> PResult<Option<&'static str>> {
if !self.input.syntax().typescript() {
return Ok(None);
}
let pos = {
let modifier = match *cur!(self, true)? {
Token::Word(ref w @ Word::Ident(..))
| Token::Word(ref w @ Word::Keyword(Keyword::In)) => w.cow(),
_ => return Ok(None),
};
allowed_modifiers.iter().position(|s| **s == **modifier)
};
if let Some(pos) = pos {
if stop_on_start_of_class_static_blocks && is!(self, "static") && peeked_is!(self, '{')
{
return Ok(None);
}
if self.try_parse_ts_bool(|p| p.ts_next_token_can_follow_modifier().map(Some))? {
return Ok(Some(allowed_modifiers[pos]));
}
}
Ok(None)
}
/// `tsIsListTerminator`
fn is_ts_list_terminator(&mut self, kind: ParsingContext) -> PResult<bool> {
debug_assert!(self.input.syntax().typescript());
Ok(match kind {
ParsingContext::EnumMembers | ParsingContext::TypeMembers => is!(self, '}'),
ParsingContext::HeritageClauseElement { .. } => {
is!(self, '{') || is!(self, "implements") || is!(self, "extends")
}
ParsingContext::TupleElementTypes => is!(self, ']'),
ParsingContext::TypeParametersOrArguments => is!(self, '>'),
})
}
/// `tsParseList`
fn parse_ts_list<T, F>(&mut self, kind: ParsingContext, mut parse_element: F) -> PResult<Vec<T>>
where
F: FnMut(&mut Self) -> PResult<T>,
{
debug_assert!(self.input.syntax().typescript());
let mut buf = vec![];
while !self.is_ts_list_terminator(kind)? {
// Skipping "parseListElement" from the TS source since that's just for error
// handling.
buf.push(parse_element(self)?);
}
Ok(buf)
}
/// `tsParseDelimitedList`
fn parse_ts_delimited_list<T, F>(
&mut self,
kind: ParsingContext,
mut parse_element: F,
) -> PResult<Vec<T>>
where
F: FnMut(&mut Self) -> PResult<T>,
{
self.parse_ts_delimited_list_inner(kind, |p| {
let start = p.input.cur_pos();
Ok((start, parse_element(p)?))
})
}
/// `tsParseDelimitedList`
fn parse_ts_delimited_list_inner<T, F>(
&mut self,
kind: ParsingContext,
mut parse_element: F,
) -> PResult<Vec<T>>
where
F: FnMut(&mut Self) -> PResult<(BytePos, T)>,
{
debug_assert!(self.input.syntax().typescript());
let mut buf = vec![];
loop {
trace_cur!(self, parse_ts_delimited_list_inner__element);
if self.is_ts_list_terminator(kind)? {
break;
}
let (_, element) = parse_element(self)?;
buf.push(element);
if eat!(self, ',') {
continue;
}
if self.is_ts_list_terminator(kind)? {
break;
}
if kind == ParsingContext::EnumMembers {
const TOKEN: &Token = &Token::Comma;
let cur = match cur!(self, false).ok() {
Some(tok) => format!("{:?}", tok),
None => "EOF".to_string(),
};
self.emit_err(self.input.cur_span(), SyntaxError::Expected(TOKEN, cur));
continue;
}
// This will fail with an error about a missing comma
expect!(self, ',');
}
Ok(buf)
}
fn parse_ts_bracketed_list<T, F>(
&mut self,
kind: ParsingContext,
parse_element: F,
bracket: bool,
skip_first_token: bool,
) -> PResult<Vec<T>>
where
F: FnMut(&mut Self) -> PResult<T>,
{
debug_assert!(self.input.syntax().typescript());
if !skip_first_token {
if bracket {
expect!(self, '[');
} else {
expect!(self, '<');
}
}
let result = self.parse_ts_delimited_list(kind, parse_element)?;
if bracket {
expect!(self, ']');
} else {
expect!(self, '>');
}
Ok(result)
}
/// `tsParseEntityName`
fn parse_ts_entity_name(&mut self, allow_reserved_words: bool) -> PResult<TsEntityName> {
debug_assert!(self.input.syntax().typescript());
let init = self.parse_ident_name()?;
if let Ident {
sym: js_word!("void"),
..
} = init
{
let dot_start = cur_pos!(self);
let dot_span = span!(self, dot_start);
self.emit_err(dot_span, SyntaxError::TS1005)
}
let mut entity = TsEntityName::Ident(init);
while eat!(self, '.') {
let dot_start = cur_pos!(self);
if !is!(self, '#') && !is!(self, IdentName) {
self.emit_err(
Span::new(dot_start, dot_start, Default::default()),
SyntaxError::TS1003,
);
return Ok(entity);
}
let left = entity;
let right = if allow_reserved_words {
self.parse_ident_name()?
} else {
self.parse_ident(false, false)?
};
entity = TsEntityName::TsQualifiedName(Box::new(TsQualifiedName { left, right }));
}
Ok(entity)
}
/// `tsParseTypeReference`
fn parse_ts_type_ref(&mut self) -> PResult<TsTypeRef> {
trace_cur!(self, parse_ts_type_ref);
debug_assert!(self.input.syntax().typescript());
let start = cur_pos!(self);
let has_modifier = self.eat_any_ts_modifier()?;
let type_name = self.parse_ts_entity_name(/* allow_reserved_words */ true)?;
trace_cur!(self, parse_ts_type_ref__type_args);
let type_params = if !self.input.had_line_break_before_cur() && is!(self, '<') {
Some(self.parse_ts_type_args()?)
} else {
None
};
if has_modifier {
self.emit_err(span!(self, start), SyntaxError::TS2369);
}
Ok(TsTypeRef {
span: span!(self, start),
type_name,
type_params,
})
}
/// `tsParseThisTypePredicate`
fn parse_ts_this_type_predicate(
&mut self,
start: BytePos,
has_asserts_keyword: bool,
lhs: TsThisType,
) -> PResult<TsTypePredicate> {
debug_assert!(self.input.syntax().typescript());
let param_name = TsThisTypeOrIdent::TsThisType(lhs);
let type_ann = if eat!(self, "is") {
let cur_pos = cur_pos!(self);
Some(self.parse_ts_type_ann(
// eat_colon
false, cur_pos,
)?)
} else {
None
};
Ok(TsTypePredicate {
span: span!(self, start),
asserts: has_asserts_keyword,
param_name,
type_ann,
})
}
/// `tsParseThisTypeNode`
fn parse_ts_this_type_node(&mut self) -> PResult<TsThisType> {
debug_assert!(self.input.syntax().typescript());
expect!(self, "this");
Ok(TsThisType {
span: self.input.prev_span(),
})
}
/// `tsParseImportType`
fn parse_ts_import_type(&mut self) -> PResult<TsImportType> {
let start = cur_pos!(self);
assert_and_bump!(self, "import");
expect!(self, '(');
let _ = cur!(self, false);
let arg_span = self.input.cur_span();
let arg = match cur!(self, true)? {
Token::Str { .. } => match bump!(self) {
Token::Str { value, raw } => Str {
span: arg_span,
value,
raw: Some(raw),
},
_ => unreachable!(),
},
_ => {
bump!(self);
self.emit_err(arg_span, SyntaxError::TS1141);
Str {
span: arg_span,
value: "".into(),
raw: Some("\"\"".into()),
}
}
};
expect!(self, ')');
let qualifier = if eat!(self, '.') {
self.parse_ts_entity_name(false).map(Some)?
} else {
None
};
let type_args = if is!(self, '<') {
self.parse_ts_type_args().map(Some)?
} else {
None
};
Ok(TsImportType {
span: span!(self, start),
arg,
qualifier,
type_args,
})
}
/// `tsParseTypeQuery`
fn parse_ts_type_query(&mut self) -> PResult<TsTypeQuery> {
debug_assert!(self.input.syntax().typescript());
let start = cur_pos!(self);
expect!(self, "typeof");
let expr_name = if is!(self, "import") {
self.parse_ts_import_type().map(From::from)?
} else {
self.parse_ts_entity_name(
// allow_reserved_word
true,
)
.map(From::from)?
};
let type_args = if !self.input.had_line_break_before_cur() && is!(self, '<') {
Some(self.parse_ts_type_args()?)
} else {
None
};
Ok(TsTypeQuery {
span: span!(self, start),
expr_name,
type_args,
})
}
/// `tsParseTypeParameter`
fn parse_ts_type_param(&mut self, allow_modifier: bool) -> PResult<TsTypeParam> {
debug_assert!(self.input.syntax().typescript());
let mut is_in = false;
let mut is_out = false;
let start = cur_pos!(self);
while let Some(modifer) = self.parse_ts_modifier(
&[
"public",
"private",
"protected",
"readonly",
"abstract",
"const",
"override",
"in",
"out",
],
false,
)? {
match modifer {
"in" => {
if !allow_modifier {
self.emit_err(self.input.prev_span(), SyntaxError::TS1274(js_word!("in")));
} else if is_in {
self.emit_err(self.input.prev_span(), SyntaxError::TS1030(js_word!("in")));
} else if is_out {
self.emit_err(
self.input.prev_span(),
SyntaxError::TS1029(js_word!("in"), js_word!("out")),
);
} else {
is_in = true;
}
}
"out" => {
if !allow_modifier {
self.emit_err(self.input.prev_span(), SyntaxError::TS1274(js_word!("out")));
} else if is_out {
self.emit_err(self.input.prev_span(), SyntaxError::TS1030(js_word!("out")));
} else {
is_out = true;
}
}
other => self.emit_err(self.input.prev_span(), SyntaxError::TS1273(other.into())),
};
}
let name = self.in_type().parse_ident_name()?;
let constraint = self.eat_then_parse_ts_type(&tok!("extends"))?;
let default = self.eat_then_parse_ts_type(&tok!('='))?;
Ok(TsTypeParam {
span: span!(self, start),
name,
is_in,
is_out,
constraint,
default,
})
}
/// `tsParseTypeParameter`
pub(super) fn parse_ts_type_params(
&mut self,
allow_modifier: bool,
) -> PResult<Box<TsTypeParamDecl>> {
self.in_type().parse_with(|p| {
p.ts_in_no_context(|p| {
let start = cur_pos!(p);
if !is!(p, '<') && !is!(p, JSXTagStart) {
unexpected!(p, "< (jsx tag start)")
}
bump!(p); // '<'
let params = p.parse_ts_bracketed_list(
ParsingContext::TypeParametersOrArguments,
|p| p.parse_ts_type_param(allow_modifier), // bracket
false,
// skip_first_token
true,
)?;
Ok(Box::new(TsTypeParamDecl {
span: span!(p, start),
params,
}))
})
})
}
/// `tsParseTypeOrTypePredicateAnnotation`
pub(super) fn parse_ts_type_or_type_predicate_ann(
&mut self,
return_token: &'static Token,
) -> PResult<Box<TsTypeAnn>> {
debug_assert!(self.input.syntax().typescript());
self.in_type().parse_with(|p| {
let return_token_start = cur_pos!(p);
if !p.input.eat(return_token) {
let cur = format!("{:?}", cur!(p, false).ok());
let span = p.input.cur_span();
syntax_error!(p, span, SyntaxError::Expected(return_token, cur))
}
let type_pred_start = cur_pos!(p);
let has_type_pred_asserts = is!(p, "asserts") && peeked_is!(p, IdentRef);
if has_type_pred_asserts {
assert_and_bump!(p, "asserts");
cur!(p, false)?;
}
let has_type_pred_is = is!(p, IdentRef)
&& peeked_is!(p, "is")
&& !p.input.has_linebreak_between_cur_and_peeked();
let is_type_predicate = has_type_pred_asserts || has_type_pred_is;
if !is_type_predicate {
return p.parse_ts_type_ann(
// eat_colon
false,
return_token_start,
);
}
let type_pred_var = p.parse_ident_name()?;
let type_ann = if has_type_pred_is {
assert_and_bump!(p, "is");
let pos = cur_pos!(p);
Some(p.parse_ts_type_ann(
// eat_colon
false, pos,
)?)
} else {
None
};
let node = Box::new(TsType::TsTypePredicate(TsTypePredicate {
span: span!(p, type_pred_start),
asserts: has_type_pred_asserts,
param_name: TsThisTypeOrIdent::Ident(type_pred_var),
type_ann,
}));
Ok(Box::new(TsTypeAnn {
span: span!(p, return_token_start),
type_ann: node,
}))
})
}
/// `tsTryParse`
fn try_parse_ts_bool<F>(&mut self, op: F) -> PResult<bool>
where
F: FnOnce(&mut Self) -> PResult<Option<bool>>,
{
if !self.input.syntax().typescript() {
return Ok(false);
}
let prev_ignore_error = self.input.get_ctx().ignore_error;
let mut cloned = self.clone();
let ctx = Context {
ignore_error: true,
..self.input.get_ctx()
};
cloned.set_ctx(ctx);
let res = op(&mut cloned);
match res {
Ok(Some(res)) if res => {
*self = cloned;
let ctx = Context {
ignore_error: prev_ignore_error,
..self.input.get_ctx()
};
self.input.set_ctx(ctx);
Ok(res)
}
Err(..) => Ok(false),
_ => Ok(false),
}
}
pub(super) fn try_parse_ts_type_args(&mut self) -> Option<Box<TsTypeParamInstantiation>> {
debug_assert!(self.input.syntax().typescript());
self.with_ctx(Context {
prefer_bin_op_over_type_arg_closing: true,
..self.ctx()
})
.try_parse_ts(|p| {
let type_args = p.parse_ts_type_args()?;
if is_one_of!(
p, '<', // invalid syntax
'>', '+', '-', // becomes relational expression
/* these should be type arguments in function call or template,
* not instantiation expression */
'(', '`'
) {
Ok(None)
} else if p.input.had_line_break_before_cur()
|| matches!(cur!(p, false), Ok(Token::BinOp(..)))
|| !p.is_start_of_expr()?
{
Ok(Some(type_args))
} else {
Ok(None)
}
})
}
/// `tsTryParse`
pub(super) fn try_parse_ts<T, F>(&mut self, op: F) -> Option<T>
where
F: FnOnce(&mut Self) -> PResult<Option<T>>,
{
if !self.input.syntax().typescript() {
return None;
}
let _tracing = debug_tracing!(self, "try_parse_ts");
trace_cur!(self, try_parse_ts);
let prev_ignore_error = self.input.get_ctx().ignore_error;
let mut cloned = self.clone();
let ctx = Context {
ignore_error: true,
..self.input.get_ctx()
};
cloned.set_ctx(ctx);
let res = op(&mut cloned);
match res {
Ok(Some(res)) => {
*self = cloned;
trace_cur!(self, try_parse_ts__success_value);
let ctx = Context {
ignore_error: prev_ignore_error,
..self.input.get_ctx()
};
self.input.set_ctx(ctx);
Some(res)
}
Ok(None) => {
trace_cur!(self, try_parse_ts__success_no_value);
None
}
Err(..) => {
trace_cur!(self, try_parse_ts__fail);
None
}
}
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
pub(super) fn parse_ts_type_ann(
&mut self,
eat_colon: bool,
start: BytePos,
) -> PResult<Box<TsTypeAnn>> {
trace_cur!(self, parse_ts_type_ann);
debug_assert!(self.input.syntax().typescript());
self.in_type().parse_with(|p| {
if eat_colon {
assert_and_bump!(p, ':');
}
trace_cur!(p, parse_ts_type_ann__after_colon);
let type_ann = p.parse_ts_type()?;
Ok(Box::new(TsTypeAnn {
span: span!(p, start),
type_ann,
}))
})
}
/// `tsEatThenParseType`
fn eat_then_parse_ts_type(
&mut self,
token_to_eat: &'static Token,
) -> PResult<Option<Box<TsType>>> {
if !cfg!(feature = "typescript") {
return Ok(Default::default());
}
self.in_type().parse_with(|p| {
if !p.input.eat(token_to_eat) {
return Ok(None);
}
p.parse_ts_type().map(Some)
})
}
/// `tsExpectThenParseType`
fn expect_then_parse_ts_type(
&mut self,
token: &'static Token,
token_str: &'static str,
) -> PResult<Box<TsType>> {
debug_assert!(self.input.syntax().typescript());
self.in_type().parse_with(|p| {
if !p.input.eat(token) {
let got = format!("{:?}", cur!(p, false).ok());
syntax_error!(
p,
p.input.cur_span(),
SyntaxError::Unexpected {
got,
expected: token_str
}
);
}
p.parse_ts_type()
})
}
/// `tsNextThenParseType`
pub(super) fn next_then_parse_ts_type(&mut self) -> PResult<Box<TsType>> {
debug_assert!(self.input.syntax().typescript());
self.in_type().parse_with(|p| {
bump!(p);
p.parse_ts_type()
})
}
/// `tsParseEnumMember`
fn parse_ts_enum_member(&mut self) -> PResult<TsEnumMember> {
debug_assert!(self.input.syntax().typescript());
let start = cur_pos!(self);
// Computed property names are grammar errors in an enum, so accept just string
// literal or identifier.
let id = match *cur!(self, true)? {
Token::Str { .. } => self.parse_lit().map(|lit| match lit {
Lit::Str(s) => TsEnumMemberId::Str(s),
_ => unreachable!(),
})?,
Token::Num { value, ref raw } => {
let mut new_raw = String::new();
new_raw.push('"');
new_raw.push_str(raw);
new_raw.push('"');
bump!(self);
let span = span!(self, start);
// Recover from error
self.emit_err(span, SyntaxError::TS2452);
TsEnumMemberId::Str(Str {
span,
value: value.to_string().into(),
raw: Some(new_raw.into()),
})
}
Token::LBracket => {
assert_and_bump!(self, '[');
let _ = self.parse_expr()?;
self.emit_err(span!(self, start), SyntaxError::TS1164);
expect!(self, ']');
TsEnumMemberId::Ident(Ident::new(js_word!(""), span!(self, start)))
}
_ => self.parse_ident_name().map(TsEnumMemberId::from)?,
};
let init = if eat!(self, '=') {
Some(self.parse_assignment_expr()?)
} else if is!(self, ',') || is!(self, '}') {
None
} else {
let start = cur_pos!(self);
bump!(self);
store!(self, ',');
self.emit_err(
Span::new(start, start, SyntaxContext::empty()),
SyntaxError::TS1005,
);
None
};
Ok(TsEnumMember {
span: span!(self, start),
id,
init,
})
}
/// `tsParseEnumDeclaration`
pub(super) fn parse_ts_enum_decl(
&mut self,
start: BytePos,
is_const: bool,
) -> PResult<Box<TsEnumDecl>> {
debug_assert!(self.input.syntax().typescript());
let id = self.parse_ident_name()?;
expect!(self, '{');
let members = self
.parse_ts_delimited_list(ParsingContext::EnumMembers, |p| p.parse_ts_enum_member())?;
expect!(self, '}');
Ok(Box::new(TsEnumDecl {
span: span!(self, start),
declare: false,
is_const,
id,
members,
}))
}
/// `tsParseModuleBlock`
fn parse_ts_module_block(&mut self) -> PResult<TsModuleBlock> {
trace_cur!(self, parse_ts_module_block);
debug_assert!(self.input.syntax().typescript());
let start = cur_pos!(self);
expect!(self, '{');
// Inside of a module block is considered "top-level", meaning it can have
// imports and exports.
let body = self.parse_block_body(
/* directives */ false,
/* topLevel */ true,
/* end */ Some(&tok!('}')),
)?;
Ok(TsModuleBlock {
span: span!(self, start),
body,
})
}
/// `tsParseModuleOrNamespaceDeclaration`
fn parse_ts_module_or_ns_decl(&mut self, start: BytePos) -> PResult<Box<TsModuleDecl>> {
debug_assert!(self.input.syntax().typescript());
let id = self.parse_ident_name()?;
let body: TsNamespaceBody = if eat!(self, '.') {
let inner_start = cur_pos!(self);
let inner = self.parse_ts_module_or_ns_decl(inner_start)?;
let inner = TsNamespaceDecl {
span: inner.span,
id: match inner.id {
TsModuleName::Ident(i) => i,
_ => unreachable!(),
},
body: Box::new(inner.body.unwrap()),
declare: inner.declare,
global: inner.global,
};
inner.into()
} else {
self.parse_ts_module_block().map(From::from)?
};
Ok(Box::new(TsModuleDecl {
span: span!(self, start),
declare: false,
id: TsModuleName::Ident(id),
body: Some(body),
global: false,
}))
}
/// `tsParseAmbientExternalModuleDeclaration`
fn parse_ts_ambient_external_module_decl(
&mut self,
start: BytePos,
) -> PResult<Box<TsModuleDecl>> {
debug_assert!(self.input.syntax().typescript());
let (global, id) = if is!(self, "global") {
let id = self.parse_ident_name()?;
(true, TsModuleName::Ident(id))
} else if matches!(*cur!(self, true)?, Token::Str { .. }) {
let id = self.parse_lit().map(|lit| match lit {
Lit::Str(s) => TsModuleName::Str(s),
_ => unreachable!(),
})?;
(false, id)
} else {
unexpected!(self, "global or a string literal");
};
let body = if is!(self, '{') {
Some(self.parse_ts_module_block().map(TsNamespaceBody::from)?)
} else {
expect!(self, ';');
None
};
Ok(Box::new(TsModuleDecl {
span: span!(self, start),
declare: false,
id,
global,
body,
}))
}
pub fn parse_type(&mut self) -> PResult<Box<TsType>> {
debug_assert!(self.input.syntax().typescript());
self.in_type().parse_ts_type()
}
/// Be sure to be in a type context before calling self.
///
/// `tsParseType`
pub(super) fn parse_ts_type(&mut self) -> PResult<Box<TsType>> {
trace_cur!(self, parse_ts_type);
debug_assert!(self.input.syntax().typescript());
// Need to set `state.inType` so that we don't parse JSX in a type context.
debug_assert!(self.ctx().in_type);
let start = cur_pos!(self);
self.with_ctx(Context {
disallow_conditional_types: false,
..self.ctx()
})
.parse_with(|p| {
let ty = p.parse_ts_non_conditional_type()?;
if p.input.had_line_break_before_cur() || !eat!(p, "extends") {
return Ok(ty);
}
let check_type = ty;
let extends_type = {
p.with_ctx(Context {
disallow_conditional_types: true,
..p.ctx()
})
.parse_ts_non_conditional_type()?
};
expect!(p, '?');
let true_type = p.parse_ts_type()?;
expect!(p, ':');
let false_type = p.parse_ts_type()?;
Ok(Box::new(TsType::TsConditionalType(TsConditionalType {
span: span!(p, start),
check_type,
extends_type,
true_type,
false_type,
})))
})
}
/// `tsParseNonConditionalType`
fn parse_ts_non_conditional_type(&mut self) -> PResult<Box<TsType>> {
trace_cur!(self, parse_ts_non_conditional_type);
debug_assert!(self.input.syntax().typescript());
if self.is_ts_start_of_fn_type()? {
return self
.parse_ts_fn_or_constructor_type(true)
.map(TsType::from)
.map(Box::new);
}
if (is!(self, "abstract") && peeked_is!(self, "new")) || is!(self, "new") {
// As in `new () => Date`
return self
.parse_ts_fn_or_constructor_type(false)
.map(TsType::from)
.map(Box::new);
}
self.parse_ts_union_type_or_higher()
}
fn is_ts_start_of_fn_type(&mut self) -> PResult<bool> {
debug_assert!(self.input.syntax().typescript());
if is!(self, '<') {
return Ok(true);
}
Ok(is!(self, '(') && self.ts_look_ahead(|p| p.is_ts_unambiguously_start_of_fn_type())?)
}
/// `tsParseTypeAssertion`
pub(super) fn parse_ts_type_assertion(&mut self, start: BytePos) -> PResult<TsTypeAssertion> {
debug_assert!(self.input.syntax().typescript());
// Not actually necessary to set state.inType because we never reach here if JSX
// plugin is enabled, but need `tsInType` to satisfy the assertion in
// `tsParseType`.
let type_ann = self.in_type().parse_with(|p| p.parse_ts_type())?;
expect!(self, '>');
let expr = self.parse_unary_expr()?;
Ok(TsTypeAssertion {
span: span!(self, start),
type_ann,
expr,
})
}
/// `tsParseHeritageClause`
pub(super) fn parse_ts_heritage_clause(&mut self) -> PResult<Vec<TsExprWithTypeArgs>> {
debug_assert!(self.input.syntax().typescript());
self.parse_ts_delimited_list(ParsingContext::HeritageClauseElement, |p| {