-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
index.js
3694 lines (3234 loc) 路 113 KB
/
index.js
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
// @flow
/*:: declare var invariant; */
// Error messages are colocated with the plugin.
/* eslint-disable @babel/development-internal/dry-error-messages */
import type Parser from "../../parser";
import { types as tt, type TokenType } from "../../tokenizer/types";
import * as N from "../../types";
import type { Pos, Position } from "../../util/location";
import type State from "../../tokenizer/state";
import { types as tc } from "../../tokenizer/context";
import * as charCodes from "charcodes";
import { isIteratorStart, isKeyword } from "../../util/identifier";
import FlowScopeHandler from "./scope";
import {
type BindingTypes,
BIND_LEXICAL,
BIND_VAR,
BIND_FUNCTION,
BIND_FLOW_DECLARE_FN,
SCOPE_ARROW,
SCOPE_FUNCTION,
SCOPE_OTHER,
} from "../../util/scopeflags";
import type { ExpressionErrors } from "../../parser/util";
import { Errors } from "../../parser/error";
const reservedTypes = new Set([
"_",
"any",
"bool",
"boolean",
"empty",
"extends",
"false",
"interface",
"mixed",
"null",
"number",
"static",
"string",
"true",
"typeof",
"void",
]);
/* eslint sort-keys: "error" */
// The Errors key follows https://github.com/facebook/flow/blob/master/src/parser/parse_error.ml unless it does not exist
const FlowErrors = Object.freeze({
AmbiguousConditionalArrow:
"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
AmbiguousDeclareModuleKind:
"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
AssignReservedType: "Cannot overwrite reserved type %0",
DeclareClassElement:
"The `declare` modifier can only appear on class fields.",
DeclareClassFieldInitializer:
"Initializers are not allowed in fields with the `declare` modifier.",
DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
EnumBooleanMemberNotInitialized:
"Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
EnumDuplicateMemberName:
"Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
EnumInconsistentMemberValues:
"Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
EnumInvalidExplicitType:
"Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidExplicitTypeUnknownSupplied:
"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
EnumInvalidMemberInitializerPrimaryType:
"Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
EnumInvalidMemberInitializerSymbolType:
"Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
EnumInvalidMemberInitializerUnknownType:
"The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
EnumInvalidMemberName:
"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
EnumNumberMemberNotInitialized:
"Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
EnumStringMemberInconsistentlyInitailized:
"String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
ImportTypeShorthandOnlyInPureImport:
"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
InexactInsideExact:
"Explicit inexact syntax cannot appear inside an explicit exact object type",
InexactInsideNonObject:
"Explicit inexact syntax cannot appear in class or interface definitions",
InexactVariance: "Explicit inexact syntax cannot have variance",
InvalidNonTypeImportInDeclareModule:
"Imports within a `declare module` body must always be `import type` or `import typeof`",
MissingTypeParamDefault:
"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
NestedDeclareModule:
"`declare module` cannot be used inside another `declare module`",
NestedFlowComment: "Cannot have a flow comment inside another flow comment",
OptionalBindingPattern:
"A binding pattern parameter cannot be optional in an implementation signature.",
SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
SpreadVariance: "Spread properties cannot have variance",
ThisParamAnnotationRequired:
"A type annotation is required for the `this` parameter.",
ThisParamBannedInConstructor:
"Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
ThisParamMustBeFirst:
"The `this` parameter must be the first function parameter.",
ThisParamNoDefault: "The `this` parameter may not have a default value.",
TypeBeforeInitializer:
"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
TypeCastInPattern:
"The type cast expression is expected to be wrapped with parenthesis",
UnexpectedExplicitInexactInObject:
"Explicit inexact syntax must appear at the end of an inexact object",
UnexpectedReservedType: "Unexpected reserved type %0",
UnexpectedReservedUnderscore:
"`_` is only allowed as a type argument to call or new",
UnexpectedSpaceBetweenModuloChecks:
"Spaces between `%` and `checks` are not allowed here.",
UnexpectedSpreadType:
"Spread operator cannot appear in class or interface definitions",
UnexpectedSubtractionOperand:
'Unexpected token, expected "number" or "bigint"',
UnexpectedTokenAfterTypeParameter:
"Expected an arrow function after this type parameter declaration",
UnexpectedTypeParameterBeforeAsyncArrowFunction:
"Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
UnsupportedDeclareExportKind:
"`declare export %0` is not supported. Use `%1` instead",
UnsupportedStatementInDeclareModule:
"Only declares and type imports are allowed inside declare module",
UnterminatedFlowComment: "Unterminated flow-comment",
});
/* eslint-disable sort-keys */
function isEsModuleType(bodyElement: N.Node): boolean {
return (
bodyElement.type === "DeclareExportAllDeclaration" ||
(bodyElement.type === "DeclareExportDeclaration" &&
(!bodyElement.declaration ||
(bodyElement.declaration.type !== "TypeAlias" &&
bodyElement.declaration.type !== "InterfaceDeclaration")))
);
}
function hasTypeImportKind(node: N.Node): boolean {
return node.importKind === "type" || node.importKind === "typeof";
}
function isMaybeDefaultImport(state: State): boolean {
return (
(state.type === tt.name || !!state.type.keyword) && state.value !== "from"
);
}
const exportSuggestions = {
const: "declare export var",
let: "declare export var",
type: "export type",
interface: "export interface",
};
// Like Array#filter, but returns a tuple [ acceptedElements, discardedElements ]
function partition<T>(
list: T[],
test: (T, number, T[]) => ?boolean,
): [T[], T[]] {
const list1 = [];
const list2 = [];
for (let i = 0; i < list.length; i++) {
(test(list[i], i, list) ? list1 : list2).push(list[i]);
}
return [list1, list2];
}
const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
// Flow enums types
type EnumExplicitType = null | "boolean" | "number" | "string" | "symbol";
type EnumContext = {|
enumName: string,
explicitType: EnumExplicitType,
memberName: string,
|};
type EnumMemberInit =
| {| type: "number", pos: number, value: N.Node |}
| {| type: "string", pos: number, value: N.Node |}
| {| type: "boolean", pos: number, value: N.Node |}
| {| type: "invalid", pos: number |}
| {| type: "none", pos: number |};
export default (superClass: Class<Parser>): Class<Parser> =>
class extends superClass {
// The value of the @flow/@noflow pragma. Initially undefined, transitions
// to "@flow" or "@noflow" if we see a pragma. Transitions to null if we are
// past the initial comment.
flowPragma: void | null | "flow" | "noflow" = undefined;
getScopeHandler(): Class<FlowScopeHandler> {
return FlowScopeHandler;
}
shouldParseTypes(): boolean {
return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
}
shouldParseEnums(): boolean {
return !!this.getPluginOption("flow", "enums");
}
finishToken(type: TokenType, val: any): void {
if (
type !== tt.string &&
type !== tt.semi &&
type !== tt.interpreterDirective
) {
if (this.flowPragma === undefined) {
this.flowPragma = null;
}
}
return super.finishToken(type, val);
}
addComment(comment: N.Comment): void {
if (this.flowPragma === undefined) {
// Try to parse a flow pragma.
const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
if (!matches) {
// do nothing
} else if (matches[1] === "flow") {
this.flowPragma = "flow";
} else if (matches[1] === "noflow") {
this.flowPragma = "noflow";
} else {
throw new Error("Unexpected flow pragma");
}
}
return super.addComment(comment);
}
flowParseTypeInitialiser(tok?: TokenType): N.FlowType {
const oldInType = this.state.inType;
this.state.inType = true;
this.expect(tok || tt.colon);
const type = this.flowParseType();
this.state.inType = oldInType;
return type;
}
flowParsePredicate(): N.FlowType {
const node = this.startNode();
const moduloPos = this.state.start;
this.next(); // eat `%`
this.expectContextual("checks");
// Force '%' and 'checks' to be adjacent
if (this.state.lastTokStart > moduloPos + 1) {
this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
}
if (this.eat(tt.parenL)) {
node.value = this.parseExpression();
this.expect(tt.parenR);
return this.finishNode(node, "DeclaredPredicate");
} else {
return this.finishNode(node, "InferredPredicate");
}
}
flowParseTypeAndPredicateInitialiser(): [?N.FlowType, ?N.FlowPredicate] {
const oldInType = this.state.inType;
this.state.inType = true;
this.expect(tt.colon);
let type = null;
let predicate = null;
if (this.match(tt.modulo)) {
this.state.inType = oldInType;
predicate = this.flowParsePredicate();
} else {
type = this.flowParseType();
this.state.inType = oldInType;
if (this.match(tt.modulo)) {
predicate = this.flowParsePredicate();
}
}
return [type, predicate];
}
flowParseDeclareClass(node: N.FlowDeclareClass): N.FlowDeclareClass {
this.next();
this.flowParseInterfaceish(node, /*isClass*/ true);
return this.finishNode(node, "DeclareClass");
}
flowParseDeclareFunction(
node: N.FlowDeclareFunction,
): N.FlowDeclareFunction {
this.next();
const id = (node.id = this.parseIdentifier());
const typeNode = this.startNode();
const typeContainer = this.startNode();
if (this.isRelational("<")) {
typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
typeNode.typeParameters = null;
}
this.expect(tt.parenL);
const tmp = this.flowParseFunctionTypeParams();
typeNode.params = tmp.params;
typeNode.rest = tmp.rest;
typeNode.this = tmp._this;
this.expect(tt.parenR);
[
// $FlowFixMe (destructuring not supported yet)
typeNode.returnType,
// $FlowFixMe (destructuring not supported yet)
node.predicate,
] = this.flowParseTypeAndPredicateInitialiser();
typeContainer.typeAnnotation = this.finishNode(
typeNode,
"FunctionTypeAnnotation",
);
id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
this.resetEndLocation(id);
this.semicolon();
this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
return this.finishNode(node, "DeclareFunction");
}
flowParseDeclare(
node: N.FlowDeclare,
insideModule?: boolean,
): N.FlowDeclare {
if (this.match(tt._class)) {
return this.flowParseDeclareClass(node);
} else if (this.match(tt._function)) {
return this.flowParseDeclareFunction(node);
} else if (this.match(tt._var)) {
return this.flowParseDeclareVariable(node);
} else if (this.eatContextual("module")) {
if (this.match(tt.dot)) {
return this.flowParseDeclareModuleExports(node);
} else {
if (insideModule) {
this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
}
return this.flowParseDeclareModule(node);
}
} else if (this.isContextual("type")) {
return this.flowParseDeclareTypeAlias(node);
} else if (this.isContextual("opaque")) {
return this.flowParseDeclareOpaqueType(node);
} else if (this.isContextual("interface")) {
return this.flowParseDeclareInterface(node);
} else if (this.match(tt._export)) {
return this.flowParseDeclareExportDeclaration(node, insideModule);
} else {
throw this.unexpected();
}
}
flowParseDeclareVariable(
node: N.FlowDeclareVariable,
): N.FlowDeclareVariable {
this.next();
node.id = this.flowParseTypeAnnotatableIdentifier(
/*allowPrimitiveOverride*/ true,
);
this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
this.semicolon();
return this.finishNode(node, "DeclareVariable");
}
flowParseDeclareModule(node: N.FlowDeclareModule): N.FlowDeclareModule {
this.scope.enter(SCOPE_OTHER);
if (this.match(tt.string)) {
node.id = this.parseExprAtom();
} else {
node.id = this.parseIdentifier();
}
const bodyNode = (node.body = this.startNode());
const body = (bodyNode.body = []);
this.expect(tt.braceL);
while (!this.match(tt.braceR)) {
let bodyNode = this.startNode();
if (this.match(tt._import)) {
this.next();
if (!this.isContextual("type") && !this.match(tt._typeof)) {
this.raise(
this.state.lastTokStart,
FlowErrors.InvalidNonTypeImportInDeclareModule,
);
}
this.parseImport(bodyNode);
} else {
this.expectContextual(
"declare",
FlowErrors.UnsupportedStatementInDeclareModule,
);
bodyNode = this.flowParseDeclare(bodyNode, true);
}
body.push(bodyNode);
}
this.scope.exit();
this.expect(tt.braceR);
this.finishNode(bodyNode, "BlockStatement");
let kind = null;
let hasModuleExport = false;
body.forEach(bodyElement => {
if (isEsModuleType(bodyElement)) {
if (kind === "CommonJS") {
this.raise(
bodyElement.start,
FlowErrors.AmbiguousDeclareModuleKind,
);
}
kind = "ES";
} else if (bodyElement.type === "DeclareModuleExports") {
if (hasModuleExport) {
this.raise(
bodyElement.start,
FlowErrors.DuplicateDeclareModuleExports,
);
}
if (kind === "ES") {
this.raise(
bodyElement.start,
FlowErrors.AmbiguousDeclareModuleKind,
);
}
kind = "CommonJS";
hasModuleExport = true;
}
});
node.kind = kind || "CommonJS";
return this.finishNode(node, "DeclareModule");
}
flowParseDeclareExportDeclaration(
node: N.FlowDeclareExportDeclaration,
insideModule: ?boolean,
): N.FlowDeclareExportDeclaration {
this.expect(tt._export);
if (this.eat(tt._default)) {
if (this.match(tt._function) || this.match(tt._class)) {
// declare export default class ...
// declare export default function ...
node.declaration = this.flowParseDeclare(this.startNode());
} else {
// declare export default [type];
node.declaration = this.flowParseType();
this.semicolon();
}
node.default = true;
return this.finishNode(node, "DeclareExportDeclaration");
} else {
if (
this.match(tt._const) ||
this.isLet() ||
((this.isContextual("type") || this.isContextual("interface")) &&
!insideModule)
) {
const label = this.state.value;
const suggestion = exportSuggestions[label];
throw this.raise(
this.state.start,
FlowErrors.UnsupportedDeclareExportKind,
label,
suggestion,
);
}
if (
this.match(tt._var) || // declare export var ...
this.match(tt._function) || // declare export function ...
this.match(tt._class) || // declare export class ...
this.isContextual("opaque") // declare export opaque ..
) {
node.declaration = this.flowParseDeclare(this.startNode());
node.default = false;
return this.finishNode(node, "DeclareExportDeclaration");
} else if (
this.match(tt.star) || // declare export * from ''
this.match(tt.braceL) || // declare export {} ...
this.isContextual("interface") || // declare export interface ...
this.isContextual("type") || // declare export type ...
this.isContextual("opaque") // declare export opaque type ...
) {
node = this.parseExport(node);
if (node.type === "ExportNamedDeclaration") {
// flow does not support the ExportNamedDeclaration
// $FlowIgnore
node.type = "ExportDeclaration";
// $FlowFixMe
node.default = false;
delete node.exportKind;
}
// $FlowIgnore
node.type = "Declare" + node.type;
return node;
}
}
throw this.unexpected();
}
flowParseDeclareModuleExports(
node: N.FlowDeclareModuleExports,
): N.FlowDeclareModuleExports {
this.next();
this.expectContextual("exports");
node.typeAnnotation = this.flowParseTypeAnnotation();
this.semicolon();
return this.finishNode(node, "DeclareModuleExports");
}
flowParseDeclareTypeAlias(
node: N.FlowDeclareTypeAlias,
): N.FlowDeclareTypeAlias {
this.next();
this.flowParseTypeAlias(node);
// Don't do finishNode as we don't want to process comments twice
node.type = "DeclareTypeAlias";
return node;
}
flowParseDeclareOpaqueType(
node: N.FlowDeclareOpaqueType,
): N.FlowDeclareOpaqueType {
this.next();
this.flowParseOpaqueType(node, true);
// Don't do finishNode as we don't want to process comments twice
node.type = "DeclareOpaqueType";
return node;
}
flowParseDeclareInterface(
node: N.FlowDeclareInterface,
): N.FlowDeclareInterface {
this.next();
this.flowParseInterfaceish(node);
return this.finishNode(node, "DeclareInterface");
}
// Interfaces
flowParseInterfaceish(
node: N.FlowDeclare,
isClass?: boolean = false,
): void {
node.id = this.flowParseRestrictedIdentifier(
/* liberal */ !isClass,
/* declaration */ true,
);
this.scope.declareName(
node.id.name,
isClass ? BIND_FUNCTION : BIND_LEXICAL,
node.id.start,
);
if (this.isRelational("<")) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
node.typeParameters = null;
}
node.extends = [];
node.implements = [];
node.mixins = [];
if (this.eat(tt._extends)) {
do {
node.extends.push(this.flowParseInterfaceExtends());
} while (!isClass && this.eat(tt.comma));
}
if (this.isContextual("mixins")) {
this.next();
do {
node.mixins.push(this.flowParseInterfaceExtends());
} while (this.eat(tt.comma));
}
if (this.isContextual("implements")) {
this.next();
do {
node.implements.push(this.flowParseInterfaceExtends());
} while (this.eat(tt.comma));
}
node.body = this.flowParseObjectType({
allowStatic: isClass,
allowExact: false,
allowSpread: false,
allowProto: isClass,
allowInexact: false,
});
}
flowParseInterfaceExtends(): N.FlowInterfaceExtends {
const node = this.startNode();
node.id = this.flowParseQualifiedTypeIdentifier();
if (this.isRelational("<")) {
node.typeParameters = this.flowParseTypeParameterInstantiation();
} else {
node.typeParameters = null;
}
return this.finishNode(node, "InterfaceExtends");
}
flowParseInterface(node: N.FlowInterface): N.FlowInterface {
this.flowParseInterfaceish(node);
return this.finishNode(node, "InterfaceDeclaration");
}
checkNotUnderscore(word: string) {
if (word === "_") {
this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
}
}
checkReservedType(word: string, startLoc: number, declaration?: boolean) {
if (!reservedTypes.has(word)) return;
this.raise(
startLoc,
declaration
? FlowErrors.AssignReservedType
: FlowErrors.UnexpectedReservedType,
word,
);
}
flowParseRestrictedIdentifier(
liberal?: boolean,
declaration?: boolean,
): N.Identifier {
this.checkReservedType(this.state.value, this.state.start, declaration);
return this.parseIdentifier(liberal);
}
// Type aliases
flowParseTypeAlias(node: N.FlowTypeAlias): N.FlowTypeAlias {
node.id = this.flowParseRestrictedIdentifier(
/* liberal */ false,
/* declaration */ true,
);
this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
if (this.isRelational("<")) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
node.typeParameters = null;
}
node.right = this.flowParseTypeInitialiser(tt.eq);
this.semicolon();
return this.finishNode(node, "TypeAlias");
}
flowParseOpaqueType(
node: N.FlowOpaqueType,
declare: boolean,
): N.FlowOpaqueType {
this.expectContextual("type");
node.id = this.flowParseRestrictedIdentifier(
/* liberal */ true,
/* declaration */ true,
);
this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
if (this.isRelational("<")) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
} else {
node.typeParameters = null;
}
// Parse the supertype
node.supertype = null;
if (this.match(tt.colon)) {
node.supertype = this.flowParseTypeInitialiser(tt.colon);
}
node.impltype = null;
if (!declare) {
node.impltype = this.flowParseTypeInitialiser(tt.eq);
}
this.semicolon();
return this.finishNode(node, "OpaqueType");
}
// Type annotations
flowParseTypeParameter(requireDefault?: boolean = false): N.TypeParameter {
const nodeStart = this.state.start;
const node = this.startNode();
const variance = this.flowParseVariance();
const ident = this.flowParseTypeAnnotatableIdentifier();
node.name = ident.name;
node.variance = variance;
node.bound = ident.typeAnnotation;
if (this.match(tt.eq)) {
this.eat(tt.eq);
node.default = this.flowParseType();
} else {
if (requireDefault) {
this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
}
}
return this.finishNode(node, "TypeParameter");
}
flowParseTypeParameterDeclaration(): N.TypeParameterDeclaration {
const oldInType = this.state.inType;
const node = this.startNode();
node.params = [];
this.state.inType = true;
// istanbul ignore else: this condition is already checked at all call sites
if (this.isRelational("<") || this.match(tt.jsxTagStart)) {
this.next();
} else {
this.unexpected();
}
let defaultRequired = false;
do {
const typeParameter = this.flowParseTypeParameter(defaultRequired);
node.params.push(typeParameter);
if (typeParameter.default) {
defaultRequired = true;
}
if (!this.isRelational(">")) {
this.expect(tt.comma);
}
} while (!this.isRelational(">"));
this.expectRelational(">");
this.state.inType = oldInType;
return this.finishNode(node, "TypeParameterDeclaration");
}
flowParseTypeParameterInstantiation(): N.TypeParameterInstantiation {
const node = this.startNode();
const oldInType = this.state.inType;
node.params = [];
this.state.inType = true;
this.expectRelational("<");
const oldNoAnonFunctionType = this.state.noAnonFunctionType;
this.state.noAnonFunctionType = false;
while (!this.isRelational(">")) {
node.params.push(this.flowParseType());
if (!this.isRelational(">")) {
this.expect(tt.comma);
}
}
this.state.noAnonFunctionType = oldNoAnonFunctionType;
this.expectRelational(">");
this.state.inType = oldInType;
return this.finishNode(node, "TypeParameterInstantiation");
}
flowParseTypeParameterInstantiationCallOrNew(): N.TypeParameterInstantiation {
const node = this.startNode();
const oldInType = this.state.inType;
node.params = [];
this.state.inType = true;
this.expectRelational("<");
while (!this.isRelational(">")) {
node.params.push(this.flowParseTypeOrImplicitInstantiation());
if (!this.isRelational(">")) {
this.expect(tt.comma);
}
}
this.expectRelational(">");
this.state.inType = oldInType;
return this.finishNode(node, "TypeParameterInstantiation");
}
flowParseInterfaceType(): N.FlowInterfaceType {
const node = this.startNode();
this.expectContextual("interface");
node.extends = [];
if (this.eat(tt._extends)) {
do {
node.extends.push(this.flowParseInterfaceExtends());
} while (this.eat(tt.comma));
}
node.body = this.flowParseObjectType({
allowStatic: false,
allowExact: false,
allowSpread: false,
allowProto: false,
allowInexact: false,
});
return this.finishNode(node, "InterfaceTypeAnnotation");
}
flowParseObjectPropertyKey(): N.Expression {
return this.match(tt.num) || this.match(tt.string)
? this.parseExprAtom()
: this.parseIdentifier(true);
}
flowParseObjectTypeIndexer(
node: N.FlowObjectTypeIndexer,
isStatic: boolean,
variance: ?N.FlowVariance,
): N.FlowObjectTypeIndexer {
node.static = isStatic;
// Note: bracketL has already been consumed
if (this.lookahead().type === tt.colon) {
node.id = this.flowParseObjectPropertyKey();
node.key = this.flowParseTypeInitialiser();
} else {
node.id = null;
node.key = this.flowParseType();
}
this.expect(tt.bracketR);
node.value = this.flowParseTypeInitialiser();
node.variance = variance;
return this.finishNode(node, "ObjectTypeIndexer");
}
flowParseObjectTypeInternalSlot(
node: N.FlowObjectTypeInternalSlot,
isStatic: boolean,
): N.FlowObjectTypeInternalSlot {
node.static = isStatic;
// Note: both bracketL have already been consumed
node.id = this.flowParseObjectPropertyKey();
this.expect(tt.bracketR);
this.expect(tt.bracketR);
if (this.isRelational("<") || this.match(tt.parenL)) {
node.method = true;
node.optional = false;
node.value = this.flowParseObjectTypeMethodish(
this.startNodeAt(node.start, node.loc.start),
);
} else {
node.method = false;
if (this.eat(tt.question)) {
node.optional = true;
}
node.value = this.flowParseTypeInitialiser();
}
return this.finishNode(node, "ObjectTypeInternalSlot");
}
flowParseObjectTypeMethodish(
node: N.FlowFunctionTypeAnnotation,
): N.FlowFunctionTypeAnnotation {
node.params = [];
node.rest = null;
node.typeParameters = null;
node.this = null;
if (this.isRelational("<")) {
node.typeParameters = this.flowParseTypeParameterDeclaration();
}
this.expect(tt.parenL);
if (this.match(tt._this)) {
node.this = this.flowParseFunctionTypeParam(/* first */ true);
// match Flow parser behavior
node.this.name = null;
if (!this.match(tt.parenR)) {
this.expect(tt.comma);
}
}
while (!this.match(tt.parenR) && !this.match(tt.ellipsis)) {
node.params.push(this.flowParseFunctionTypeParam(false));
if (!this.match(tt.parenR)) {
this.expect(tt.comma);
}
}
if (this.eat(tt.ellipsis)) {
node.rest = this.flowParseFunctionTypeParam(false);
}
this.expect(tt.parenR);
node.returnType = this.flowParseTypeInitialiser();
return this.finishNode(node, "FunctionTypeAnnotation");
}
flowParseObjectTypeCallProperty(
node: N.FlowObjectTypeCallProperty,
isStatic: boolean,
): N.FlowObjectTypeCallProperty {
const valueNode = this.startNode();
node.static = isStatic;
node.value = this.flowParseObjectTypeMethodish(valueNode);
return this.finishNode(node, "ObjectTypeCallProperty");
}
flowParseObjectType({
allowStatic,
allowExact,
allowSpread,
allowProto,
allowInexact,
}: {
allowStatic: boolean,
allowExact: boolean,
allowSpread: boolean,
allowProto: boolean,
allowInexact: boolean,
}): N.FlowObjectTypeAnnotation {
const oldInType = this.state.inType;
this.state.inType = true;
const nodeStart = this.startNode();
nodeStart.callProperties = [];
nodeStart.properties = [];
nodeStart.indexers = [];
nodeStart.internalSlots = [];
let endDelim;
let exact;
let inexact = false;
if (allowExact && this.match(tt.braceBarL)) {
this.expect(tt.braceBarL);
endDelim = tt.braceBarR;
exact = true;
} else {
this.expect(tt.braceL);
endDelim = tt.braceR;
exact = false;
}
nodeStart.exact = exact;
while (!this.match(endDelim)) {
let isStatic = false;
let protoStart: ?number = null;
let inexactStart: ?number = null;
const node = this.startNode();
if (allowProto && this.isContextual("proto")) {
const lookahead = this.lookahead();