1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! The Flow type-annotation precedence hierarchy (`parseTypeAnnotationFlow`
//! → `parsePrimaryTypeAnnotationFlow`), the `typeof`/tuple productions, and
//! the reparse helpers. Port of the corresponding sections of
//! `lib/Parser/JSParserImpl-flow.cpp`.
use hermes_ast::node::{
AnyTypeAnnotation, ArrayTypeAnnotation, BigIntLiteralTypeAnnotation,
BigIntTypeAnnotation, BooleanLiteralTypeAnnotation, BooleanTypeAnnotation,
ComponentTypeAnnotation, ComponentTypeParameter, ConditionalTypeAnnotation,
EmptyTypeAnnotation, ExistsTypeAnnotation,
FunctionTypeParam, GenericTypeAnnotation, Identifier, IndexedAccessType,
InferTypeAnnotation,
InterfaceTypeAnnotation, IntersectionTypeAnnotation, KeyofTypeAnnotation,
MixedTypeAnnotation,
NeverTypeAnnotation, Node, NullLiteralTypeAnnotation,
NullableTypeAnnotation, NumberLiteralTypeAnnotation, NumberTypeAnnotation,
OptionalIndexedAccessType, QualifiedTypeofIdentifier, StringLiteral,
StringLiteralTypeAnnotation, StringTypeAnnotation, SymbolTypeAnnotation,
TupleTypeAnnotation, TupleTypeLabeledElement, TupleTypeSpreadElement,
TypeAnnotation, TypeOperator, TypeParameter, TypeofTypeAnnotation,
UndefinedTypeAnnotation, UnionTypeAnnotation, UnknownTypeAnnotation,
Variance, VoidTypeAnnotation,
};
use hermes_ast::node_child::{NodeLabel, NodeList, NodeMetadata};
use hermes_support::location::SMLoc;
use crate::js::expressions::inc_parens;
use crate::js::{JSParserImpl, Param};
use crate::lexer::GrammarContext;
use crate::token_kinds::TokenKind;
use super::{
can_follow_variance_keyword_flow, AllowAnonFunctionType,
AllowProtoProperty, AllowSpreadProperty, AllowStaticProperty,
};
impl<'gc, 'ast, 'ctx, 'a> JSParserImpl<'gc, 'ast, 'ctx, 'a> {
// -----------------------------------------------------------------------
// parseTypeAnnotationFlow — 3093 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a type annotation.
/// Port of `JSParserImpl::parseTypeAnnotationFlow` (flow.cpp:3091-3107).
///
/// \param wrapped_start if `Some`, the result is wrapped in a
/// `TypeAnnotation` node spanning from it to the previous token's end
/// (the C++ `wrappedStart` parameter, used for `: T` annotations).
/// \param allow_anon_function_type value for `allow_anon_function_type`
/// while parsing this annotation (saved/restored around the parse).
pub(in crate::js) fn parse_type_annotation_flow(
&mut self,
wrapped_start: Option<SMLoc>,
allow_anon_function_type: AllowAnonFunctionType,
) -> Option<&'gc Node<'gc>> {
// C++ 3093-3095: llvh::SaveAndRestore<bool> on allowAnonFunctionType_.
// The guard restores the old value on every exit path, including the
// `?` early return below.
let _guard = self.save_allow_anon_function_type(
allow_anon_function_type == AllowAnonFunctionType::Yes,
);
let opt_type = self.parse_conditional_type_annotation_flow()?;
if let Some(start) = wrapped_start {
// C++ 3099-3104.
let node = Node::TypeAnnotation(TypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
opt_type,
));
return Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
));
}
Some(opt_type)
}
// -----------------------------------------------------------------------
// The type-annotation precedence hierarchy:
// conditional → union → intersection → anon-fn-without-parens → prefix →
// postfix → primary.
// -----------------------------------------------------------------------
/// Parse a type annotation that may be used where a colon could follow
/// (e.g. a possibly-labeled tuple element or function parameter). Port of
/// `parseTypeAnnotationBeforeColonFlow` (flow.cpp:3024-3089).
pub(super) fn parse_type_annotation_before_colon_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 3024-3085: if the identifier name is a known keyword we need to
// look ahead to see if it's a type or an identifier, otherwise it
// could fail to parse. Gated on getParseFlowComponentSyntax().
if self.check(TokenKind::identifier) && self.parse_flow_component_syntax()
{
let name = self
.gc
.ctx()
.atom_table
.bytes(self.lexer.token().get_res_word_or_identifier())
.to_owned();
let renders_q =
name == b"renders" && self.lexer.check_following_character(b'?');
if (name == b"component" || name == b"hook")
|| (name == b"renders" && !renders_q)
{
// C++ 3028-3047: `component`/`hook`/`renders` (no following
// `?`) followed by `:` or `?` is a label, parsed as a generic
// type whose id is the keyword.
let opt_next = self.lexer.lookahead1::<true>(None);
if opt_next == Some(TokenKind::colon)
|| opt_next == Some(TokenKind::question)
{
let id = self.make_keyword_generic_type();
self.advance(GrammarContext::Type);
return Some(id);
}
} else if renders_q {
// C++ 3048-3083: `renders?` — either a `renders?` label on a
// `:`-typed element, or the `renders?` type operator.
let start_loc = self.cur_start();
let id = self.make_keyword_generic_type();
self.advance(GrammarContext::Type);
let opt_next = self.lexer.lookahead1::<true>(None);
if opt_next == Some(TokenKind::colon) {
return Some(id);
}
// C++ 3067-3074.
if !self.eat_at(
TokenKind::question,
GrammarContext::Type,
" in render type annotation",
Some("start of render type"),
start_loc,
) {
return None;
}
let body = self.parse_prefix_type_annotation_flow()?;
let operator =
self.gc.ctx().atom_table.atom_bytes(b"renders?");
let node = Node::TypeOperator(TypeOperator::new(
NodeMetadata::new(self.dummy_range()),
operator,
body,
));
return Some(self.set_location(
start_loc,
self.lexer.prev_token_end(),
node,
));
}
}
// C++ 3087.
self.parse_type_annotation_flow(None, AllowAnonFunctionType::Yes)
}
/// Build a `GenericTypeAnnotation` whose id is the current token's keyword
/// identifier (a `component`/`hook`/`renders` contextual keyword used as a
/// labelled-element name). Helper for the label-disambiguation paths of
/// `parseTypeAnnotationBeforeColonFlow` (flow.cpp:3036-3045 / 3041-3050).
/// Does NOT advance — the caller advances after.
fn make_keyword_generic_type(&mut self) -> &'gc Node<'gc> {
let range = self.cur_range();
let id_node = Node::Identifier(Identifier::new(
NodeMetadata::new(self.dummy_range()),
self.lexer.token().get_res_word_or_identifier(),
None,
false,
));
let id = self.set_location(range.start, range.end, id_node);
let generic = Node::GenericTypeAnnotation(GenericTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
id,
None,
));
self.set_location(range.start, range.end, generic)
}
/// Port of `parseConditionalTypeAnnotationFlow` (flow.cpp:3109-3158).
fn parse_conditional_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 3109.
let start = self.cur_start();
// C++ 3110: conditional types are allowed while parsing the check
// type.
let _guard = self.save_allow_conditional_type(true);
let check_type = self.parse_union_type_annotation_flow()?;
// C++ 3114-3116.
if !self.check_and_eat(TokenKind::rw_extends, GrammarContext::Type) {
return Some(check_type);
}
let extends_type = {
// C++ 3118-3122: We need to enter the state of parsing the
// extends_type disallowing conditional types not wrapped by
// parantheses, so that the following sequence
// `A extends infer B extends C ? D : E` will be interpreted
// as `A extends (infer B extends C) ? D : E`.
let _guard = self.save_allow_conditional_type(false);
self.parse_union_type_annotation_flow()
}?;
// C++ 3129-3135.
if !self.eat_at(
TokenKind::question,
GrammarContext::Type,
" in conditional type",
Some("start of type"),
start,
) {
return None;
}
// C++ 3137-3138.
let true_type =
self.parse_type_annotation_flow(None, AllowAnonFunctionType::Yes)?;
// C++ 3140-3146.
if !self.eat_at(
TokenKind::colon,
GrammarContext::Type,
" in conditional type",
Some("start of type"),
start,
) {
return None;
}
// C++ 3148-3150.
let false_type =
self.parse_type_annotation_flow(None, AllowAnonFunctionType::Yes)?;
// C++ 3152-3156: located from the check type's start (NOT the start
// of this production — they only differ if error recovery moved us).
let node = Node::ConditionalTypeAnnotation(
ConditionalTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
check_type,
extends_type,
true_type,
false_type,
),
);
Some(self.set_location(
check_type.metadata().range.get().start,
self.lexer.prev_token_end(),
node,
))
}
/// Port of `parseUnionTypeAnnotationFlow` (flow.cpp:3160-3187).
pub(super) fn parse_union_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 3160-3161: `start` is captured BEFORE the optional leading `|`.
let start = self.cur_start();
self.check_and_eat(TokenKind::pipe, GrammarContext::Type);
let first = self.parse_intersection_type_annotation_flow()?;
if !self.check(TokenKind::pipe) {
// Done with the union, move on.
return Some(first);
}
let mut types: Vec<&'gc Node<'gc>> = vec![first];
while self.check_and_eat(TokenKind::pipe, GrammarContext::Type) {
types.push(self.parse_intersection_type_annotation_flow()?);
}
// C++ 3182-3185.
let node = Node::UnionTypeAnnotation(UnionTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, types),
));
Some(self.set_location(start, self.lexer.prev_token_end(), node))
}
/// Port of `parseIntersectionTypeAnnotationFlow` (flow.cpp:3189-3217).
fn parse_intersection_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 3189-3190: `start` is captured BEFORE the optional leading `&`.
let start = self.cur_start();
self.check_and_eat(TokenKind::amp, GrammarContext::Type);
let first =
self.parse_anon_function_without_parens_type_annotation_flow()?;
if !self.check(TokenKind::amp) {
// Done with the union, move on.
return Some(first);
}
let mut types: Vec<&'gc Node<'gc>> = vec![first];
while self.check_and_eat(TokenKind::amp, GrammarContext::Type) {
types.push(
self.parse_anon_function_without_parens_type_annotation_flow()?,
);
}
// C++ 3211-3214.
let node =
Node::IntersectionTypeAnnotation(IntersectionTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, types),
));
Some(self.set_location(start, self.lexer.prev_token_end(), node))
}
/// Port of `parseAnonFunctionWithoutParensTypeAnnotationFlow`
/// (flow.cpp:3219-3243).
fn parse_anon_function_without_parens_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
let start = self.cur_start();
let param = self.parse_prefix_type_annotation_flow()?;
// C++ 3224-3240.
if self.allow_anon_function_type.get()
&& self.check(TokenKind::equalgreater)
{
// ParamType => ReturnType
// ^
// "Reparse" the param into a FunctionTypeParam so it can be used
// for parseFunctionTypeAnnotationWithParamsFlow. C++ 3228-3233:
// it spans exactly the param's range.
let param_range = param.metadata().range.get();
let ftp_node = Node::FunctionTypeParam(FunctionTypeParam::new(
NodeMetadata::new(self.dummy_range()),
None, // name
param,
false, // optional
));
let ftp =
self.set_location(param_range.start, param_range.end, ftp_node);
return self.parse_function_type_annotation_with_params_flow(
start,
vec![ftp],
None, // this constraint
None, // rest
None, // type params
false, // hook
);
}
Some(param)
}
/// Port of `parsePrefixTypeAnnotationFlow` (flow.cpp:3245-3257).
pub(super) fn parse_prefix_type_annotation_flow(&mut self) -> Option<&'gc Node<'gc>> {
let start = self.cur_start();
// C++ 3246-3254: nullable `?T` (right-recursive, so `??T` nests).
if self.check_and_eat(TokenKind::question, GrammarContext::Type) {
let prefix = self.parse_prefix_type_annotation_flow()?;
let node =
Node::NullableTypeAnnotation(NullableTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
prefix,
));
return Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
));
}
self.parse_postfix_type_annotation_flow()
}
/// Port of `parsePostfixTypeAnnotationFlow` (flow.cpp:3259-3316).
fn parse_postfix_type_annotation_flow(&mut self) -> Option<&'gc Node<'gc>> {
let start = self.cur_start();
let mut result = self.parse_primary_type_annotation_flow()?;
let mut seen_optional_indexed_access = false;
// C++ 3267-3268.
while self.check2(TokenKind::l_square, TokenKind::questiondot)
&& !self.lexer.is_new_line_before_current_token()
{
// C++ 3269: `checkAndEat(questiondot)` uses the DEFAULT grammar
// context (AllowRegExp), NOT Type — deliberate; keep it.
let optional = self.check_and_eat(
TokenKind::questiondot,
GrammarContext::AllowRegExp,
);
seen_optional_indexed_access =
seen_optional_indexed_access || optional;
// C++ 3272-3278.
if !self.eat_at(
TokenKind::l_square,
GrammarContext::Type,
" in indexed access type or postfix array type syntax",
Some("start of a type"),
start,
) {
return None;
}
if !optional
&& self.check_and_eat(TokenKind::r_square, GrammarContext::Type)
{
// Legacy Array syntax `T[]` (C++ 3280-3286; spans from this
// production's start).
let node = Node::ArrayTypeAnnotation(ArrayTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
result,
));
result = self.set_location(
start,
self.lexer.prev_token_end(),
node,
);
} else {
// Indexed Access `T[K]` (`T?.[K]` if `optional`),
// C++ 3288-3310.
let index_type = self.parse_type_annotation_flow(
None,
AllowAnonFunctionType::Yes,
)?;
if !self.need_at(
TokenKind::r_square,
" in indexed access type",
Some("start of type"),
start,
) {
return None;
}
// Once a `?.[` has been seen, all the enclosing accesses
// become OptionalIndexedAccessType (with optional=false for
// the plain `[` ones).
if seen_optional_indexed_access {
let node = Node::OptionalIndexedAccessType(
OptionalIndexedAccessType::new(
NodeMetadata::new(self.dummy_range()),
result,
index_type,
optional,
),
);
let end = self.advance(GrammarContext::Type).end;
result = self.set_location(start, end, node);
} else {
let node = Node::IndexedAccessType(IndexedAccessType::new(
NodeMetadata::new(self.dummy_range()),
result,
index_type,
));
let end = self.advance(GrammarContext::Type).end;
result = self.set_location(start, end, node);
}
}
}
Some(result)
}
// -----------------------------------------------------------------------
// parsePrimaryTypeAnnotationFlow — 3320 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a primary type annotation. Port of
/// `JSParserImpl::parsePrimaryTypeAnnotationFlow` (flow.cpp:3318-3615).
fn parse_primary_type_annotation_flow(&mut self) -> Option<&'gc Node<'gc>> {
let start = self.cur_start();
match self.cur_kind() {
// C++ 3320-3324.
TokenKind::star => {
let node = Node::ExistsTypeAnnotation(ExistsTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
));
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3325-3326.
TokenKind::less => self.parse_function_type_annotation_flow(),
// C++ 3327-3328.
TokenKind::l_paren => {
self.parse_function_or_group_type_annotation_flow()
}
// C++ 3329-3334.
TokenKind::l_brace | TokenKind::l_bracepipe => self
.parse_object_type_annotation_flow(
AllowProtoProperty::No,
AllowStaticProperty::No,
AllowSpreadProperty::Yes,
),
// C++ 3335-3346. `interface` lexes as rw_interface only in
// strict mode (it is a future reserved word); in loose mode it is
// an identifier and reaches the NamedType::Interface arm below.
TokenKind::rw_interface => {
self.advance(GrammarContext::Type);
let mut extends: Vec<&'gc Node<'gc>> = Vec::new();
let body =
self.parse_interface_tail_flow(start, &mut extends)?;
// The end location is the body node's end.
let end = body.metadata().range.get().end;
let node = Node::InterfaceTypeAnnotation(
InterfaceTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, extends),
Some(body),
),
);
Some(self.set_location(start, end, node))
}
// C++ 3347-3348.
TokenKind::rw_typeof => self.parse_typeof_type_annotation_flow(),
// C++ 3350-3351.
TokenKind::l_square => self.parse_tuple_type_annotation_flow(),
// C++ 3352-3523. The C++ compares `tok_->getResWordOrIdentifier()`
// against the pre-interned `anyIdent_`/`mixedIdent_`/... atoms
// (escape-insensitive); we compare the token's interned name bytes
// directly. Each named-primitive arm is
// `setLocation(start, advance(GrammarContext::Type).End, new
// <Name>Node())` (C++ 3355-3420).
TokenKind::rw_static | TokenKind::rw_this | TokenKind::identifier => {
/// Dispatch outcome of the named-type match below: either a
/// finished primitive node (consume the token and return), or
/// one of the multi-token productions.
enum NamedType<'gc> {
Prim(Node<'gc>),
Keyof,
Renders,
Component,
Hook,
Interface,
Infer,
Generic,
}
// C++ 3432/3432/3439: the `renders`/`component`/`hook` arms
// are gated on getParseFlowComponentSyntax().
let component_syntax = self.parse_flow_component_syntax();
let arm = {
let name = self.lexer.get_string_table().bytes(
self.lexer.token().get_res_word_or_identifier(),
);
let md = NodeMetadata::new(self.dummy_range());
match name {
// C++ 3355-3359.
b"any" => NamedType::Prim(Node::AnyTypeAnnotation(
AnyTypeAnnotation::new(md),
)),
// C++ 3360-3365.
b"mixed" => NamedType::Prim(Node::MixedTypeAnnotation(
MixedTypeAnnotation::new(md),
)),
// C++ 3366-3371.
b"empty" => NamedType::Prim(Node::EmptyTypeAnnotation(
EmptyTypeAnnotation::new(md),
)),
// C++ 3372-3377.
b"unknown" => NamedType::Prim(
Node::UnknownTypeAnnotation(
UnknownTypeAnnotation::new(md),
),
),
// C++ 3378-3383.
b"never" => NamedType::Prim(Node::NeverTypeAnnotation(
NeverTypeAnnotation::new(md),
)),
// C++ 3384-3389.
b"undefined" => NamedType::Prim(
Node::UndefinedTypeAnnotation(
UndefinedTypeAnnotation::new(md),
),
),
// C++ 3390-3396.
b"boolean" | b"bool" => NamedType::Prim(
Node::BooleanTypeAnnotation(
BooleanTypeAnnotation::new(md),
),
),
// C++ 3397-3402.
b"number" => NamedType::Prim(
Node::NumberTypeAnnotation(
NumberTypeAnnotation::new(md),
),
),
// C++ 3403-3408.
b"symbol" => NamedType::Prim(
Node::SymbolTypeAnnotation(
SymbolTypeAnnotation::new(md),
),
),
// C++ 3409-3414.
b"string" => NamedType::Prim(
Node::StringTypeAnnotation(
StringTypeAnnotation::new(md),
),
),
// C++ 3415-3420.
b"bigint" => NamedType::Prim(
Node::BigIntTypeAnnotation(
BigIntTypeAnnotation::new(md),
),
),
// C++ 3422-3430.
b"keyof" => NamedType::Keyof,
// C++ 3432-3443.
b"renders" if component_syntax => NamedType::Renders,
// C++ 3444-3450.
b"component" if component_syntax => {
NamedType::Component
}
// C++ 3451-3457.
b"hook" if component_syntax => NamedType::Hook,
// C++ 3459-3469.
b"interface" => NamedType::Interface,
// C++ 3471-3516.
b"infer" => NamedType::Infer,
// C++ 3518-3523.
_ => NamedType::Generic,
}
};
match arm {
NamedType::Prim(node) => {
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
NamedType::Keyof => {
// C++ 3422-3430.
self.advance(GrammarContext::Type);
let body = self.parse_prefix_type_annotation_flow()?;
let node =
Node::KeyofTypeAnnotation(KeyofTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
body,
));
Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
))
}
NamedType::Renders => {
// C++ 3432-3443.
let operator = self.parse_render_type_operator();
let body = self.parse_prefix_type_annotation_flow();
let (Some(body), Some(operator)) = (body, operator)
else {
return None;
};
let node = Node::TypeOperator(TypeOperator::new(
NodeMetadata::new(self.dummy_range()),
operator,
body,
));
Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
))
}
NamedType::Component => {
// C++ 3444-3450.
self.parse_component_type_annotation_flow()
}
NamedType::Hook => {
// C++ 3451-3457.
self.parse_hook_type_annotation_flow()
}
NamedType::Interface => {
// C++ 3459-3469 (the loose-mode spelling, where
// `interface` is an identifier rather than
// rw_interface).
self.advance(GrammarContext::Type);
let mut extends: Vec<&'gc Node<'gc>> = Vec::new();
let body = self
.parse_interface_tail_flow(start, &mut extends)?;
// The end location is the body node's end.
let end = body.metadata().range.get().end;
let node = Node::InterfaceTypeAnnotation(
InterfaceTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, extends),
Some(body),
),
);
Some(self.set_location(start, end, node))
}
NamedType::Infer => {
// C++ 3471-3516.
self.advance(GrammarContext::Type);
// C++ 3473-3474.
if !self.need(
TokenKind::identifier,
" in type parameter",
) {
return None;
}
let name = self.lexer.token().get_identifier();
self.advance(GrammarContext::Type);
let mut bound: Option<&'gc Node<'gc>> = None;
if self.check(TokenKind::rw_extends) {
// When we see an extends keyword,
// we enter the parsing logic that might need
// backtracking.
//
// For `infer A extends B ...`, is the `extends B`
// part of an infer type, or part of a larger
// conditional type like
// `infer A extends B ? C : D`?
//
// We don't know, so we assume it's part of the
// infer type for now, and later backtrack if the
// assumption is wrong.
//
// NOTE: like the C++, diagnostics are NOT
// suppressed during the speculative bound parse —
// a failed bound emits its errors and then still
// restores.
let save_point = self.lexer.save_point();
self.advance(GrammarContext::Type);
let parsed_bound =
self.parse_union_type_annotation_flow();
if (self.allow_conditional_type.get()
&& self.check(TokenKind::question))
|| parsed_bound.is_none()
{
// If we look ahead and see `?`, it might be
// the case that we are parsing a conditional
// type like `infer A extends B ? C : D`. If
// the current context allow parsing
// conditional type, then we must backtrack so
// that only `infer A` is treated as part of
// the infer type.
//
// Of course, if we fail to parse the type
// after extends, we also need to backtrack.
save_point.restore(&mut self.lexer);
} else {
bound = parsed_bound;
}
}
// C++ 3508-3515: the TypeParameter spans the same
// range as the InferTypeAnnotation.
let end = self.lexer.prev_token_end();
let type_param_node =
Node::TypeParameter(TypeParameter::new(
NodeMetadata::new(self.dummy_range()),
name,
false, // const
bound,
None, // variance
None, // default
true, // usesExtendsBound
));
let type_param =
self.set_location(start, end, type_param_node);
let node =
Node::InferTypeAnnotation(InferTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
type_param,
));
Some(self.set_location(start, end, node))
}
NamedType::Generic => self.parse_generic_type_flow(),
}
}
// C++ 3525-3529.
TokenKind::rw_null => {
let node = Node::NullLiteralTypeAnnotation(
NullLiteralTypeAnnotation::new(NodeMetadata::new(
self.dummy_range(),
)),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3531-3535.
TokenKind::rw_void => {
let node = Node::VoidTypeAnnotation(VoidTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
));
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3537-3544.
TokenKind::string_literal => {
let value = self.lexer.token().get_string_literal();
// C++: `lexer_.getStringLiteral(tok_->inputStr())` — the raw
// SOURCE text of the token (including the quotes), interned.
let raw = self.cur_token_source_atom();
let node = Node::StringLiteralTypeAnnotation(
StringLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
value,
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3546-3553.
TokenKind::numeric_literal => {
let value = self.lexer.token().get_numeric_literal();
let raw = self.cur_token_source_atom();
let node = Node::NumberLiteralTypeAnnotation(
NumberLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
value,
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3555-3561.
TokenKind::bigint_literal => {
let raw = self.lexer.token().get_bigint_literal_raw_value();
let node = Node::BigIntLiteralTypeAnnotation(
BigIntLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3563-3593.
TokenKind::minus => {
self.advance(GrammarContext::Type);
if self.check(TokenKind::numeric_literal) {
// Negate the literal (C++ 3565-3575). The raw text spans
// from the `-` through the end of the literal token.
let value = -self.lexer.token().get_numeric_literal();
let raw =
self.source_bytes_atom(start, self.cur_range().end);
let node = Node::NumberLiteralTypeAnnotation(
NumberLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
value,
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
} else if self.check(TokenKind::bigint_literal) {
// C++ 3576-3584: the BigInt raw keeps the `-` prefix.
let raw =
self.source_bytes_atom(start, self.cur_range().end);
let node = Node::BigIntLiteralTypeAnnotation(
BigIntLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
} else {
// C++ 3585-3590: errorExpected(numeric_literal,
// "in type annotation", "start of annotation", start).
self.need_at(
TokenKind::numeric_literal,
" in type annotation",
Some("start of annotation"),
start,
);
None
}
}
// C++ 3595-3603.
TokenKind::rw_true | TokenKind::rw_false => {
let value = self.check(TokenKind::rw_true);
let raw = self.lexer.token().get_res_word_identifier();
let node = Node::BooleanLiteralTypeAnnotation(
BooleanLiteralTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
value,
raw,
),
);
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
// C++ 3604-3612.
_ => {
if self.lexer.token().is_res_word() {
// C++ 3605-3609.
return self.parse_generic_type_flow();
}
// Point location, NOT the current token's range: C++
// (flow.cpp:3612) calls `error(tok_->getStartLoc(), ...)` —
// the `error(SMLoc, Twine)` overload.
self.error_at_loc(
self.cur_start(),
"unexpected token in type annotation",
);
None
}
}
}
// -----------------------------------------------------------------------
// parseTypeofTypeAnnotationFlow — 3619 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a `typeof X.Y<Args>` type annotation, with the current token at
/// `typeof`. Port of `parseTypeofTypeAnnotationFlow`
/// (flow.cpp:3617-3679).
fn parse_typeof_type_annotation_flow(&mut self) -> Option<&'gc Node<'gc>> {
debug_assert!(self.check(TokenKind::rw_typeof));
// C++ 3618: a bare `advance()` — the default GrammarContext
// (AllowRegExp), NOT Type; deliberate.
let start = self.advance(GrammarContext::AllowRegExp).start;
let mut paren_count: u32 = 0;
// C++ 3621-3622: default grammar context again.
while self.check_and_eat(TokenKind::l_paren, GrammarContext::AllowRegExp)
{
paren_count += 1;
}
// C++ 3624-3625: whatLoc is `startLoc` (the 'typeof' keyword).
if !self.need_at(
TokenKind::identifier,
" in typeof type",
Some("start of type"),
start,
) {
return None;
}
// C++ 3627-3632.
let ident_range = self.cur_range();
let ident_node = Node::Identifier(Identifier::new(
NodeMetadata::new(self.dummy_range()),
self.lexer.token().get_identifier(),
None,
false,
));
let mut ident =
self.set_location(ident_range.start, ident_range.end, ident_node);
self.advance(GrammarContext::Type);
// C++ 3634: `checkAndEat(period)` with the default grammar context.
while self.check_and_eat(TokenKind::period, GrammarContext::AllowRegExp)
{
// C++ 3635-3642.
if !self.check(TokenKind::identifier)
&& !self.lexer.token().is_res_word()
{
// flow.cpp:3636-3643: errorExpected(identifier, "in
// qualified typeof type", "start of type", startLoc).
self.need_at(
TokenKind::identifier,
" in qualified typeof type",
Some("start of type"),
start,
);
return None;
}
// C++ 3643-3648.
let next_range = self.cur_range();
let next_node = Node::Identifier(Identifier::new(
NodeMetadata::new(self.dummy_range()),
self.lexer.token().get_res_word_or_identifier(),
None,
false,
));
let next = self.set_location(
next_range.start,
next_range.end,
next_node,
);
self.advance(GrammarContext::Type);
// C++ 3649-3652: spans from the qualification's start to the new
// id's end.
let q_node = Node::QualifiedTypeofIdentifier(
QualifiedTypeofIdentifier::new(
NodeMetadata::new(self.dummy_range()),
ident,
next,
),
);
ident = self.set_location(
ident.metadata().range.get().start,
next_range.end,
q_node,
);
}
// C++ 3655-3663: close the wrapping parens, recording them on the
// (possibly qualified) identifier node.
for _ in 0..paren_count {
if !self.eat_at(
TokenKind::r_paren,
GrammarContext::Type,
" in typeof type",
Some("start of type"),
start,
) {
return None;
}
inc_parens(ident);
}
// C++ 3665-3672: `parseTypeArgsFlow()` is called with its default
// trailing grammar context (Type, per JSParserImpl.h:1506).
let mut type_arguments: Option<&'gc Node<'gc>> = None;
if self.check(TokenKind::less)
&& !self.lexer.is_new_line_before_current_token()
{
type_arguments =
Some(self.parse_type_args_flow(GrammarContext::Type)?);
}
// C++ 3674-3677.
let node = Node::TypeofTypeAnnotation(TypeofTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
ident,
type_arguments,
));
Some(self.set_location(start, self.lexer.prev_token_end(), node))
}
// -----------------------------------------------------------------------
// parseTupleTypeAnnotationFlow — 3683 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a tuple type annotation, with the current token at `[`.
/// Port of `parseTupleTypeAnnotationFlow` (flow.cpp:3681-3725).
fn parse_tuple_type_annotation_flow(&mut self) -> Option<&'gc Node<'gc>> {
debug_assert!(self.check(TokenKind::l_square));
// C++ 3682.
let start = self.advance(GrammarContext::Type).start;
let mut element_types: Vec<&'gc Node<'gc>> = Vec::new();
let mut inexact = false;
// C++ 3687-3710.
while !self.check(TokenKind::r_square) {
let elem_start = self.cur_start();
let starts_with_dotdotdot =
self.check_and_eat(TokenKind::dotdotdot, GrammarContext::Type);
if starts_with_dotdotdot && self.check(TokenKind::r_square) {
// ...]
inexact = true;
} else if starts_with_dotdotdot && self.check(TokenKind::comma) {
// ...,
self.error_cur(
"trailing commas after inexact tuple types are not allowed",
);
self.advance(GrammarContext::Type);
} else {
let elem = self.parse_tuple_element_flow(
elem_start,
starts_with_dotdotdot,
)?;
element_types.push(elem);
if !self.check_and_eat(TokenKind::comma, GrammarContext::Type) {
break;
}
}
}
// C++ 3712-3717.
if !self.need_at(
TokenKind::r_square,
" at end of tuple type annotation",
Some("start of tuple"),
start,
) {
return None;
}
// C++ 3719-3723.
let node = Node::TupleTypeAnnotation(TupleTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, element_types),
inexact,
));
let end = self.advance(GrammarContext::Type).end;
Some(self.set_location(start, end, node))
}
/// Parse one tuple type element, with `start` at the element's start
/// (including a leading `...`, already consumed iff
/// `starts_with_dotdotdot`). Port of `parseTupleElementFlow`
/// (flow.cpp:3727-3827).
fn parse_tuple_element_flow(
&mut self,
start: SMLoc,
starts_with_dotdotdot: bool,
) -> Option<&'gc Node<'gc>> {
let mut variance: Option<&'gc Node<'gc>> = None;
// ...Identifier : Type
// ...Type
// ^
if starts_with_dotdotdot {
// C++ 3737-3760.
let ty = self.parse_type_annotation_before_colon_flow()?;
if self.check_and_eat(TokenKind::colon, GrammarContext::Type) {
let label =
self.reparse_type_annotation_as_identifier_flow(ty)?;
let element_type = self.parse_type_annotation_flow(
None,
AllowAnonFunctionType::Yes,
)?;
let node = Node::TupleTypeSpreadElement(
TupleTypeSpreadElement::new(
NodeMetadata::new(self.dummy_range()),
Some(label),
element_type,
),
);
return Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
));
}
let node = Node::TupleTypeSpreadElement(
TupleTypeSpreadElement::new(
NodeMetadata::new(self.dummy_range()),
None, // label
ty,
),
);
return Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
));
}
// +Identifier : Type
// -Identifier : Type
// readonly Identifier : Type
// writeonly Identifier : Type
// ^
if self.check2(TokenKind::plus, TokenKind::minus) {
// C++ 3768-3774: the Variance kind is the interned "plus" /
// "minus" atom (plusIdent_ / minusIdent_).
let kind: &[u8] = if self.check(TokenKind::plus) {
b"plus"
} else {
b"minus"
};
let v_range = self.cur_range();
let v_node = Node::Variance(Variance::new(
NodeMetadata::new(self.dummy_range()),
self.lexer.get_identifier(kind),
));
variance =
Some(self.set_location(v_range.start, v_range.end, v_node));
self.advance(GrammarContext::Type);
} else if (self.check_name(b"readonly")
|| self.check_name(b"writeonly"))
&& can_follow_variance_keyword_flow(
self.lexer.lookahead1::<true>(None),
)
{
// C++ 3775-3780.
let v_range = self.cur_range();
let v_node = Node::Variance(Variance::new(
NodeMetadata::new(self.dummy_range()),
self.lexer.token().get_identifier(),
));
variance =
Some(self.set_location(v_range.start, v_range.end, v_node));
self.advance(GrammarContext::Type);
}
// Identifier [?] : Type
// Type
// ^
let ty = self.parse_type_annotation_before_colon_flow()?;
// Identifier [?] : Type
// ^
if self.check2(TokenKind::colon, TokenKind::question) {
// C++ 3793-3795.
let optional =
self.check_and_eat(TokenKind::question, GrammarContext::Type);
// C++ 3797-3804.
if !self.eat_at(
TokenKind::colon,
GrammarContext::Type,
" in labeled tuple type element",
Some("location of tuple"),
start,
) {
return None;
}
let label = self.reparse_type_annotation_as_identifier_flow(ty)?;
let element_type = self
.parse_type_annotation_flow(None, AllowAnonFunctionType::Yes)?;
// C++ 3812-3816.
let node = Node::TupleTypeLabeledElement(
TupleTypeLabeledElement::new(
NodeMetadata::new(self.dummy_range()),
label,
element_type,
optional,
variance,
),
);
return Some(self.set_location(
start,
self.lexer.prev_token_end(),
node,
));
}
// C++ 3818-3823.
if let Some(variance) = variance {
let range = variance.metadata().range.get();
self.error_at(
range,
"Variance can only be used with labeled tuple elements",
);
}
Some(ty)
}
// -----------------------------------------------------------------------
// reparseTypeAnnotationAsIdFlow — 5115 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Map a type-annotation node back to the identifier atom it would have
/// parsed as, reporting "identifier expected" at the node if impossible.
/// Port of `reparseTypeAnnotationAsIdFlow` (flow.cpp:5113-5146).
///
/// NOTE: BooleanTypeAnnotation maps to "boolean" even when the source
/// spelled it `bool` — the C++ maps both spellings to booleanIdent_ the
/// same way (5105-5106).
pub(super) fn reparse_type_annotation_as_id_flow(
&mut self,
type_annotation: &'gc Node<'gc>,
) -> Option<NodeLabel> {
let id: Option<NodeLabel> = match type_annotation {
Node::AnyTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"any"))
}
Node::EmptyTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"empty"))
}
Node::BooleanTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"boolean"))
}
Node::NumberTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"number"))
}
Node::StringTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"string"))
}
Node::SymbolTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"symbol"))
}
Node::NullLiteralTypeAnnotation(_) => {
Some(self.lexer.get_identifier(b"null"))
}
// C++ 5129-5137: a generic without type arguments whose id is a
// plain Identifier reparses as that identifier.
Node::GenericTypeAnnotation(generic)
if generic.type_parameters.is_none() =>
{
if let Node::Identifier(generic_id) = generic.id {
Some(generic_id.name.get())
} else {
None
}
}
_ => None,
};
if id.is_none() {
// C++ 5139-5143.
let range = type_annotation.metadata().range.get();
self.error_at(range, "identifier expected");
}
id
}
/// Reparse a type-annotation node as an `Identifier` node spanning the
/// original node's source range. Port of
/// `reparseTypeAnnotationAsIdentifierFlow` (flow.cpp:5148-5159).
pub(super) fn reparse_type_annotation_as_identifier_flow(
&mut self,
type_annotation: &'gc Node<'gc>,
) -> Option<&'gc Node<'gc>> {
let id = self.reparse_type_annotation_as_id_flow(type_annotation)?;
// C++ 5153-5157.
let range = type_annotation.metadata().range.get();
let node = Node::Identifier(Identifier::new(
NodeMetadata::new(self.dummy_range()),
id,
None,
false,
));
Some(self.set_location(range.start, range.end, node))
}
// -----------------------------------------------------------------------
// parseComponentTypeAnnotationFlow — 555 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a `component(params) renders T` TYPE annotation, with the cursor
/// at `component`. Port of
/// `JSParserImpl::parseComponentTypeAnnotationFlow` (flow.cpp:555-604).
pub(super) fn parse_component_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 557-558.
debug_assert!(self.check_name(b"component"));
let start = self.advance(GrammarContext::Type).start;
// C++ 560-566: component type annotations should not contain a name.
if self.check(TokenKind::identifier) {
self.error_at(
self.cur_range(),
"component type annotations should not contain a name",
);
self.advance(GrammarContext::Type);
}
// C++ 568-575.
let mut type_params: Option<&'gc Node<'gc>> = None;
if self.check(TokenKind::less) {
type_params = Some(self.parse_type_params_flow()?);
}
// C++ 577-583.
if !self.need_at(
TokenKind::l_paren,
" at start of component parameter list",
Some("component type annotation starts here"),
start,
) {
return None;
}
// C++ 585-589.
let mut param_list: Vec<&'gc Node<'gc>> = Vec::new();
let rest = self.parse_component_type_parameters_flow(
Param::default(),
&mut param_list,
)?;
// C++ 591-597.
let mut renders_type: Option<&'gc Node<'gc>> = None;
if self.check_name(b"renders") {
renders_type = Some(self.parse_component_render_type_flow(true)?);
}
// C++ 599-603.
let node = Node::ComponentTypeAnnotation(ComponentTypeAnnotation::new(
NodeMetadata::new(self.dummy_range()),
NodeList::from_iter(self.gc, param_list),
rest,
type_params,
renders_type,
));
Some(self.set_location(start, self.lexer.prev_token_end(), node))
}
// -----------------------------------------------------------------------
// parseComponentTypeParametersFlow — 606 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse the `( ... )` parameter list of a component TYPE annotation into
/// `param_list`, returning the optional rest parameter (outer `None` =
/// error already reported, `Some(None)` = no rest parameter). Port of
/// `JSParserImpl::parseComponentTypeParametersFlow` (flow.cpp:606-648).
pub(super) fn parse_component_type_parameters_flow(
&mut self,
param: Param,
param_list: &mut Vec<&'gc Node<'gc>>,
) -> Option<Option<&'gc Node<'gc>>> {
// C++ 609-613.
debug_assert!(self.check(TokenKind::l_paren));
let lparen_loc = self.advance(GrammarContext::Type).start;
let mut rest: Option<&'gc Node<'gc>> = None;
// C++ 616-635.
while !self.check(TokenKind::r_paren) {
if self.check(TokenKind::dotdotdot) {
// C++ 617-624: a ComponentTypeRestParameter.
rest = Some(self.parse_component_type_rest_parameter_flow(param)?);
break;
}
// C++ 626-631.
let param_node = self.parse_component_type_parameter_flow(param)?;
param_list.push(param_node);
// C++ 633-634.
if !self.check_and_eat(TokenKind::comma, GrammarContext::Type) {
break;
}
}
// C++ 637-645.
if !self.eat_at(
TokenKind::r_paren,
GrammarContext::Type,
" at end of component type parameter list",
Some("start of component type parameter list"),
lparen_loc,
) {
return None;
}
Some(rest)
}
// -----------------------------------------------------------------------
// parseComponentTypeRestParameterFlow — 650 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a `...IdentifierName: T` / `...T` rest parameter of a component
/// TYPE annotation, with the cursor at `...`. Port of
/// `JSParserImpl::parseComponentTypeRestParameterFlow` (flow.cpp:650-698).
fn parse_component_type_rest_parameter_flow(
&mut self,
_param: Param,
) -> Option<&'gc Node<'gc>> {
// C++ 657-659.
debug_assert!(self.check(TokenKind::dotdotdot));
let start = self.advance(GrammarContext::Type).start;
// C++ 661-663.
let left = self.parse_type_annotation_before_colon_flow()?;
// C++ 665-689.
let mut name: Option<&'gc Node<'gc>> = None;
let type_annotation: &'gc Node<'gc>;
let mut optional = false;
if self.check2(TokenKind::colon, TokenKind::question) {
// C++ 670-686: the node is actually supposed to be an identifier,
// not a TypeAnnotation.
name = Some(self.reparse_type_annotation_as_identifier_flow(left)?);
optional =
self.check_and_eat(TokenKind::question, GrammarContext::Type);
if !self.eat_at(
TokenKind::colon,
GrammarContext::Type,
" in component parameter type annotation",
Some("start of parameter"),
start,
) {
return None;
}
type_annotation =
self.parse_type_annotation_flow(None, AllowAnonFunctionType::Yes)?;
} else {
type_annotation = left;
}
// C++ 691.
self.check_and_eat(TokenKind::comma, GrammarContext::Type);
// C++ 693-697.
let node = Node::ComponentTypeParameter(ComponentTypeParameter::new(
NodeMetadata::new(self.dummy_range()),
name,
type_annotation,
optional,
));
Some(self.set_location(start, self.lexer.prev_token_end(), node))
}
// -----------------------------------------------------------------------
// parseComponentTypeParameterFlow — 700 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse one `Name?: T` parameter of a component TYPE annotation (the name
/// is a string literal or identifier; `as` is rejected). Port of
/// `JSParserImpl::parseComponentTypeParameterFlow` (flow.cpp:700-766).
fn parse_component_type_parameter_flow(
&mut self,
_param: Param,
) -> Option<&'gc Node<'gc>> {
// C++ 706.
let param_start = self.cur_start();
let name_elem: &'gc Node<'gc>;
// C++ 708-730.
if self.check(TokenKind::string_literal) {
// C++ 708-715.
let str_range = self.cur_range();
let value = self.lexer.token().get_string_literal();
let node = Node::StringLiteral(StringLiteral::new(
NodeMetadata::new(self.dummy_range()),
value,
));
name_elem =
self.set_location(str_range.start, str_range.end, node);
self.advance(GrammarContext::Type);
} else if self.check(TokenKind::identifier)
|| self.lexer.token().is_res_word()
{
// C++ 716-724.
let ident_rng = self.cur_range();
let id = self.lexer.token().get_res_word_or_identifier();
let node = Node::Identifier(Identifier::new(
NodeMetadata::new(self.dummy_range()),
id,
None,
false,
));
name_elem =
self.set_location(ident_rng.start, ident_rng.end, node);
self.advance(GrammarContext::Type);
} else {
// C++ 725-729.
self.error_at_loc(
self.cur_start(),
"identifier or string literal expected in component type parameter name",
);
return None;
}
// C++ 732-735: `as` is not allowed in component type parameters.
if self.check_name(b"as") {
self.error_at_loc(
self.cur_start(),
"'as' not allowed in component type parameter",
);
return None;
}
// C++ 737-743.
let mut optional = false;
if self.check_and_eat(TokenKind::question, GrammarContext::Type) {
optional = true;
}
// C++ 745-753.
if !self.eat_at(
TokenKind::colon,
GrammarContext::Type,
" in component type parameter",
Some("start of parameter"),
param_start,
) {
return None;
}
// C++ 755-759: parseTypeAnnotation() with default args
// (wrappedStart=None, AllowAnonFunctionType::Yes).
let ty =
self.parse_type_annotation(None, AllowAnonFunctionType::Yes)?;
// C++ 761-765.
let node = Node::ComponentTypeParameter(ComponentTypeParameter::new(
NodeMetadata::new(self.dummy_range()),
Some(name_elem),
ty,
optional,
));
Some(self.set_location(param_start, self.lexer.prev_token_end(), node))
}
// -----------------------------------------------------------------------
// parseHookTypeAnnotationFlow — 3831 in JSParserImpl-flow.cpp
// -----------------------------------------------------------------------
/// Parse a `hook(params) => R` TYPE annotation, with the cursor at `hook`.
/// Port of `JSParserImpl::parseHookTypeAnnotationFlow` (flow.cpp:3829-3834).
pub(super) fn parse_hook_type_annotation_flow(
&mut self,
) -> Option<&'gc Node<'gc>> {
// C++ 3830-3831.
debug_assert!(self.check_name(b"hook"));
self.advance(GrammarContext::Type);
// C++ 3832.
self.parse_function_or_hook_type_annotation_flow(true)
}
/// Intern the raw source text of the current token. The Rust equivalent
/// of the C++ `lexer_.getStringLiteral(tok_->inputStr())` idiom used by
/// the literal type annotations.
fn cur_token_source_atom(&self) -> NodeLabel {
let range = self.lexer.token().source_range();
self.source_bytes_atom(range.start, range.end)
}
}