-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathstatement_parser.ml
2189 lines (2085 loc) · 80.1 KB
/
statement_parser.ml
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
(*
* 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.
*)
module Ast = Flow_ast
open Token
open Parser_env
open Flow_ast
open Parser_common
open Comment_attachment
module type STATEMENT = sig
val for_ : env -> (Loc.t, Loc.t) Statement.t
val if_ : env -> (Loc.t, Loc.t) Statement.t
val let_ : env -> (Loc.t, Loc.t) Statement.t
val try_ : env -> (Loc.t, Loc.t) Statement.t
val while_ : env -> (Loc.t, Loc.t) Statement.t
val with_ : env -> (Loc.t, Loc.t) Statement.t
val block : env -> (Loc.t, Loc.t) Statement.t
val break : env -> (Loc.t, Loc.t) Statement.t
val continue : env -> (Loc.t, Loc.t) Statement.t
val debugger : env -> (Loc.t, Loc.t) Statement.t
val declare : ?in_module:bool -> env -> (Loc.t, Loc.t) Statement.t
val declare_export_declaration : ?allow_export_type:bool -> env -> (Loc.t, Loc.t) Statement.t
val declare_opaque_type : env -> (Loc.t, Loc.t) Statement.t
val do_while : env -> (Loc.t, Loc.t) Statement.t
val empty : env -> (Loc.t, Loc.t) Statement.t
val export_declaration :
decorators:(Loc.t, Loc.t) Class.Decorator.t list -> env -> (Loc.t, Loc.t) Statement.t
val expression : env -> (Loc.t, Loc.t) Statement.t
val import_declaration : env -> (Loc.t, Loc.t) Statement.t
val interface : env -> (Loc.t, Loc.t) Statement.t
val maybe_labeled : env -> (Loc.t, Loc.t) Statement.t
val opaque_type : env -> (Loc.t, Loc.t) Statement.t
val return : env -> (Loc.t, Loc.t) Statement.t
val switch : env -> (Loc.t, Loc.t) Statement.t
val throw : env -> (Loc.t, Loc.t) Statement.t
val type_alias : env -> (Loc.t, Loc.t) Statement.t
val var : env -> (Loc.t, Loc.t) Statement.t
val const : env -> (Loc.t, Loc.t) Statement.t
end
module Statement
(Parse : PARSER)
(Type : Type_parser.TYPE)
(Declaration : Declaration_parser.DECLARATION)
(Object : Object_parser.OBJECT)
(Pattern_cover : Pattern_cover.COVER) : STATEMENT = struct
type for_lhs =
| For_expression of pattern_cover
| For_declaration of (Loc.t * (Loc.t, Loc.t) Ast.Statement.VariableDeclaration.t)
type semicolon_type =
| Explicit of Loc.t Comment.t list
| Implicit of Comment_attachment.trailing_and_remover_result
(* FunctionDeclaration is not a valid Statement, but Annex B sometimes allows it.
However, AsyncFunctionDeclaration and GeneratorFunctionDeclaration are never
allowed as statements. We still parse them as statements (and raise an error) to
recover gracefully. *)
let function_as_statement env =
let func = Declaration._function env in
( if in_strict_mode env then
function_as_statement_error_at env (fst func)
else
let open Ast.Statement in
match func with
| (loc, FunctionDeclaration { Ast.Function.async = true; _ }) ->
error_at env (loc, Parse_error.AsyncFunctionAsStatement)
| (loc, FunctionDeclaration { Ast.Function.generator = true; _ }) ->
error_at env (loc, Parse_error.GeneratorFunctionAsStatement)
| _ -> ()
);
func
(* https://tc39.es/ecma262/#sec-exports-static-semantics-early-errors *)
let assert_identifier_name_is_identifier
?restricted_error env (loc, { Ast.Identifier.name; comments = _ }) =
match name with
| "let" ->
(* "let" is disallowed as an identifier in a few situations. 11.6.2.1
lists them out. It is always disallowed in strict mode *)
if in_strict_mode env then
strict_error_at env (loc, Parse_error.StrictReservedWord)
else if no_let env then
error_at env (loc, Parse_error.Unexpected (Token.quote_token_value name))
| "await" ->
(* `allow_await` means that `await` is allowed to be a keyword,
which makes it illegal to use as an identifier.
https://tc39.github.io/ecma262/#sec-identifiers-static-semantics-early-errors *)
if allow_await env then error_at env (loc, Parse_error.UnexpectedReserved)
| "yield" ->
(* `allow_yield` means that `yield` is allowed to be a keyword,
which makes it illegal to use as an identifier.
https://tc39.github.io/ecma262/#sec-identifiers-static-semantics-early-errors *)
if allow_yield env then
error_at env (loc, Parse_error.UnexpectedReserved)
else
strict_error_at env (loc, Parse_error.StrictReservedWord)
| _ when is_strict_reserved name -> strict_error_at env (loc, Parse_error.StrictReservedWord)
| _ when is_reserved name ->
error_at env (loc, Parse_error.Unexpected (Token.quote_token_value name))
| _ ->
begin
match restricted_error with
| Some err when is_restricted name -> strict_error_at env (loc, err)
| _ -> ()
end
let string_literal env (loc, value, raw, octal) =
if octal then strict_error env Parse_error.StrictOctalLiteral;
let leading = Peek.comments env in
Expect.token env (T_STRING (loc, value, raw, octal));
let trailing = Eat.trailing_comments env in
( loc,
{ StringLiteral.value; raw; comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
)
(* Semicolon insertion is handled here :(. There seem to be 2 cases where
* semicolons are inserted. First, if we reach the EOF. Second, if the next
* token is } or is separated by a LineTerminator.
*)
let semicolon ?(expected = "the token `;`") ?(required = true) env =
match Peek.token env with
| T_EOF
| T_RCURLY ->
Implicit { trailing = Eat.trailing_comments env; remove_trailing = (fun x _ -> x) }
| T_SEMICOLON ->
Eat.token env;
(match Peek.token env with
| T_EOF
| T_RCURLY ->
Explicit (Eat.trailing_comments env)
| _ when Peek.is_line_terminator env -> Explicit (Eat.comments_until_next_line env)
| _ -> Explicit [])
| _ when Peek.is_line_terminator env ->
Implicit (Comment_attachment.trailing_and_remover_after_last_line env)
| _ ->
if required then error_unexpected ~expected env;
Explicit []
(* Consumes and returns the trailing comments after the end of a statement. Also returns
a remover that can remove all comments that are not trailing the previous token.
If a statement is the end of a block or file, all comments are trailing.
Otherwise, if a statement is followed by a new line, only comments on the current
line are trailing. If a statement is not followed by a new line, it does not have
trailing comments as they are instead leading comments for the next statement. *)
let statement_end_trailing_comments env =
match Peek.token env with
| T_EOF
| T_RCURLY ->
{ trailing = Eat.trailing_comments env; remove_trailing = (fun x _ -> x) }
| _ when Peek.is_line_terminator env ->
Comment_attachment.trailing_and_remover_after_last_line env
| _ -> Comment_attachment.trailing_and_remover_after_last_loc env
let variable_declaration_end ~kind env declarations =
match semicolon env with
| Explicit comments -> (comments, declarations)
| Implicit { remove_trailing; _ } ->
(* Remove trailing comments from the last declarator *)
let declarations =
match List.rev declarations with
| [] -> []
| decl :: decls ->
let decl' =
remove_trailing decl (fun remover decl -> remover#variable_declarator ~kind decl)
in
List.rev (decl' :: decls)
in
([], declarations)
let rec empty env =
let loc = Peek.loc env in
let leading = Peek.comments env in
Expect.token env T_SEMICOLON;
let { trailing; _ } = statement_end_trailing_comments env in
( loc,
Statement.Empty
{ Statement.Empty.comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
)
and break env =
let leading = Peek.comments env in
let (loc, (label, trailing)) =
with_loc
(fun env ->
Expect.token env T_BREAK;
let label =
if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
None
else
let ((_, { Identifier.name; comments = _ }) as label) = Parse.identifier env in
if not (SSet.mem name (labels env)) then error env (Parse_error.UnknownLabel name);
Some label
in
let (trailing, label) =
match (semicolon env, label) with
| (Explicit trailing, _)
| (Implicit { trailing; _ }, None) ->
(trailing, label)
| (Implicit { remove_trailing; _ }, Some label) ->
([], Some (remove_trailing label (fun remover label -> remover#identifier label)))
in
(label, trailing))
env
in
if label = None && not (in_loop env || in_switch env) then
error_at env (loc, Parse_error.IllegalBreak);
let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
(loc, Statement.Break { Statement.Break.label; comments })
and continue env =
let leading = Peek.comments env in
let (loc, (label, trailing)) =
with_loc
(fun env ->
Expect.token env T_CONTINUE;
let label =
if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
None
else
let ((_, { Identifier.name; comments = _ }) as label) = Parse.identifier env in
if not (SSet.mem name (labels env)) then error env (Parse_error.UnknownLabel name);
Some label
in
let (trailing, label) =
match (semicolon env, label) with
| (Explicit trailing, _)
| (Implicit { trailing; _ }, None) ->
(trailing, label)
| (Implicit { remove_trailing; _ }, Some label) ->
([], Some (remove_trailing label (fun remover label -> remover#identifier label)))
in
(label, trailing))
env
in
if not (in_loop env) then error_at env (loc, Parse_error.IllegalContinue);
( loc,
Statement.Continue
{
Statement.Continue.label;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and debugger =
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_DEBUGGER;
let pre_semicolon_trailing =
if Peek.token env = T_SEMICOLON then
Eat.trailing_comments env
else
[]
in
let trailing =
match semicolon env with
| Explicit trailing
| Implicit { trailing; _ } ->
pre_semicolon_trailing @ trailing
in
Statement.Debugger
{ Statement.Debugger.comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
)
and do_while =
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_DO;
let body = Parse.statement (env |> with_in_loop true) in
(* Annex B allows labelled FunctionDeclarations (see
sec-labelled-function-declarations), but not in IterationStatement
(see sec-semantics-static-semantics-early-errors). *)
if (not (in_strict_mode env)) && is_labelled_function body then
function_as_statement_error_at env (fst body);
let pre_keyword_trailing = Eat.trailing_comments env in
Expect.token env T_WHILE;
let pre_cond_trailing = Eat.trailing_comments env in
Expect.token env T_LPAREN;
let test = Parse.expression env in
Expect.token env T_RPAREN;
let past_cond_trailing =
if Peek.token env = T_SEMICOLON then
Eat.trailing_comments env
else
[]
in
(* The rules of automatic semicolon insertion in ES5 don't mention this,
* but the semicolon after a do-while loop is optional. This is properly
* specified in ES6 *)
let past_cond_trailing =
match semicolon ~required:false env with
| Explicit trailing -> past_cond_trailing @ trailing
| Implicit { trailing; _ } -> trailing
in
let trailing = pre_keyword_trailing @ pre_cond_trailing @ past_cond_trailing in
Statement.DoWhile
{
Statement.DoWhile.body;
test;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and for_ =
let assert_can_be_forin_or_forof env err = function
| (loc, { Statement.VariableDeclaration.declarations; _ }) ->
(* Only a single declarator is allowed, without an init. So
* something like
*
* for (var x in y) {}
*
* is allowed, but we disallow
*
* for (var x, y in z) {}
* for (var x = 42 in y) {}
*)
(match declarations with
| [(_, { Statement.VariableDeclaration.Declarator.init = None; _ })] -> ()
| _ -> error_at env (loc, err))
in
(* Annex B allows labelled FunctionDeclarations (see
sec-labelled-function-declarations), but not in IterationStatement
(see sec-semantics-static-semantics-early-errors). *)
let assert_not_labelled_function env body =
if (not (in_strict_mode env)) && is_labelled_function body then
function_as_statement_error_at env (fst body)
else
()
in
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_FOR;
let async = allow_await env && Eat.maybe env T_AWAIT in
let leading = leading @ Peek.comments env in
Expect.token env T_LPAREN;
let comments = Flow_ast_utils.mk_comments_opt ~leading () in
let (init, errs) =
let env = env |> with_no_in true in
match Peek.token env with
| T_SEMICOLON -> (None, [])
| T_LET ->
let (loc, (declarations, leading, errs)) = with_loc Declaration.let_ env in
( Some
(For_declaration
( loc,
{
Statement.VariableDeclaration.kind = Statement.VariableDeclaration.Let;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ();
}
)
),
errs
)
| T_CONST ->
let (loc, (declarations, leading, errs)) = with_loc Declaration.const env in
( Some
(For_declaration
( loc,
{
Statement.VariableDeclaration.kind = Statement.VariableDeclaration.Const;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ();
}
)
),
errs
)
| T_VAR ->
let (loc, (declarations, leading, errs)) = with_loc Declaration.var env in
( Some
(For_declaration
( loc,
{
Statement.VariableDeclaration.kind = Statement.VariableDeclaration.Var;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ();
}
)
),
errs
)
| _ ->
let expr = Parse.expression_or_pattern (env |> with_no_let true) in
(Some (For_expression expr), [])
in
match Peek.token env with
| T_OF ->
(* This is a for of loop *)
let left =
match init with
| Some (For_declaration decl) ->
assert_can_be_forin_or_forof env Parse_error.InvalidLHSInForOf decl;
Statement.ForOf.LeftDeclaration decl
| Some (For_expression expr) ->
(* #sec-for-in-and-for-of-statements-static-semantics-early-errors *)
let patt = Pattern_cover.as_pattern ~err:Parse_error.InvalidLHSInForOf env expr in
Statement.ForOf.LeftPattern patt
| None -> assert false
in
Expect.token env T_OF;
let right = Parse.assignment env in
Expect.token env T_RPAREN;
let body = Parse.statement (env |> with_in_loop true) in
assert_not_labelled_function env body;
Statement.ForOf { Statement.ForOf.left; right; body; await = async; comments }
| T_IN ->
(* This is a for in loop *)
let left =
match init with
| Some (For_declaration decl) ->
assert_can_be_forin_or_forof env Parse_error.InvalidLHSInForIn decl;
Statement.ForIn.LeftDeclaration decl
| Some (For_expression expr) ->
(* #sec-for-in-and-for-of-statements-static-semantics-early-errors *)
let patt = Pattern_cover.as_pattern ~err:Parse_error.InvalidLHSInForIn env expr in
Statement.ForIn.LeftPattern patt
| None -> assert false
in
if async then
(* If `async` is true, this should have been a for-await-of loop, but we
recover by trying to parse like a for-in loop. *)
Expect.token env T_OF
else
Expect.token env T_IN;
let right = Parse.expression env in
Expect.token env T_RPAREN;
let body = Parse.statement (env |> with_in_loop true) in
assert_not_labelled_function env body;
Statement.ForIn { Statement.ForIn.left; right; body; each = false; comments }
| _ ->
(* This is a for loop *)
errs |> List.iter (error_at env);
if async then
(* If `async` is true, this should have been a for-await-of loop, but we
recover by trying to parse like a normal loop. *)
Expect.token env T_OF
else
Expect.token env T_SEMICOLON;
let init =
match init with
| Some (For_declaration decl) -> Some (Statement.For.InitDeclaration decl)
| Some (For_expression expr) ->
Some (Statement.For.InitExpression (Pattern_cover.as_expression env expr))
| None -> None
in
let test =
match Peek.token env with
| T_SEMICOLON -> None
| _ -> Some (Parse.expression env)
in
Expect.token env T_SEMICOLON;
let update =
match Peek.token env with
| T_RPAREN -> None
| _ -> Some (Parse.expression env)
in
Expect.token env T_RPAREN;
let body = Parse.statement (env |> with_in_loop true) in
assert_not_labelled_function env body;
Statement.For { Statement.For.init; test; update; body; comments }
)
and if_ =
(*
* Either the consequent or alternate of an if statement
*)
let if_branch env =
(* Normally this would just be a Statement, but Annex B allows
FunctionDeclarations in non-strict mode. See
sec-functiondeclarations-in-ifstatement-statement-clauses *)
let stmt =
if Peek.is_function env then
function_as_statement env
else
Parse.statement env
in
(* Annex B allows labelled FunctionDeclarations in non-strict mode
(see sec-labelled-function-declarations), but not in IfStatement
(see sec-if-statement-static-semantics-early-errors). *)
if (not (in_strict_mode env)) && is_labelled_function stmt then
function_as_statement_error_at env (fst stmt);
stmt
in
let alternate env =
let leading = Peek.comments env in
Expect.token env T_ELSE;
let body = if_branch env in
{ Statement.If.Alternate.body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
in
with_loc (fun env ->
let pre_if_leading = Peek.comments env in
Expect.token env T_IF;
let pre_cond_leading = Peek.comments env in
let leading = pre_if_leading @ pre_cond_leading in
Expect.token env T_LPAREN;
let test = Parse.expression env in
Expect.token env T_RPAREN;
let consequent = if_branch env in
let alternate =
if Peek.token env = T_ELSE then
Some (with_loc alternate env)
else
None
in
Statement.If
{
Statement.If.test;
consequent;
alternate;
comments = Flow_ast_utils.mk_comments_opt ~leading ();
}
)
and return =
with_loc (fun env ->
if not (in_function env) then error env Parse_error.IllegalReturn;
let leading = Peek.comments env in
let start_loc = Peek.loc env in
Expect.token env T_RETURN;
let trailing =
if Peek.token env = T_SEMICOLON then
Eat.trailing_comments env
else
[]
in
let argument =
if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
None
else
Some (Parse.expression env)
in
let return_out = Loc.btwn start_loc (Peek.loc env) in
let (trailing, argument) =
match (semicolon env, argument) with
| (Explicit comments, _)
| (Implicit { trailing = comments; _ }, None) ->
(trailing @ comments, argument)
| (Implicit { remove_trailing; _ }, Some arg) ->
(trailing, Some (remove_trailing arg (fun remover arg -> remover#expression arg)))
in
Statement.Return
{
Statement.Return.argument;
return_out;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and switch =
let case ~seen_default env =
let leading = Peek.comments env in
let (test, trailing) =
match Peek.token env with
| T_DEFAULT ->
if seen_default then error env Parse_error.MultipleDefaultsInSwitch;
Expect.token env T_DEFAULT;
(None, Eat.trailing_comments env)
| _ ->
Expect.token env T_CASE;
(Some (Parse.expression env), [])
in
let seen_default = seen_default || test = None in
Expect.token env T_COLON;
let { trailing = line_end_trailing; _ } = statement_end_trailing_comments env in
let trailing = trailing @ line_end_trailing in
let term_fn = function
| T_RCURLY
| T_DEFAULT
| T_CASE ->
true
| _ -> false
in
let consequent = Parse.statement_list ~term_fn (env |> with_in_switch true) in
let comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () in
let case = { Statement.Switch.Case.test; consequent; comments } in
(case, seen_default)
in
let rec case_list env (seen_default, acc) =
match Peek.token env with
| T_EOF
| T_RCURLY ->
List.rev acc
| _ ->
let (case_, seen_default) = with_loc_extra (case ~seen_default) env in
let acc = case_ :: acc in
case_list env (seen_default, acc)
in
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_SWITCH;
Expect.token env T_LPAREN;
let discriminant = Parse.expression env in
Expect.token env T_RPAREN;
Expect.token env T_LCURLY;
let cases = case_list env (false, []) in
Expect.token env T_RCURLY;
let { trailing; _ } = statement_end_trailing_comments env in
Statement.Switch
{
Statement.Switch.discriminant;
cases;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
exhaustive_out = fst discriminant;
}
)
and throw =
with_loc (fun env ->
let leading = Peek.comments env in
let start_loc = Peek.loc env in
Expect.token env T_THROW;
if Peek.is_line_terminator env then error_at env (start_loc, Parse_error.NewlineAfterThrow);
let argument = Parse.expression env in
let (trailing, argument) =
match semicolon env with
| Explicit trailing -> (trailing, argument)
| Implicit { remove_trailing; _ } ->
([], remove_trailing argument (fun remover arg -> remover#expression arg))
in
let open Statement in
Throw { Throw.argument; comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing () }
)
and try_ =
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_TRY;
let block =
let block = Parse.block_body env in
if Peek.token env = T_CATCH then
block_remove_trailing env block
else
block
in
let handler =
match Peek.token env with
| T_CATCH ->
let catch =
with_loc
(fun env ->
let leading = Peek.comments env in
Expect.token env T_CATCH;
let trailing = Eat.trailing_comments env in
let param =
if Peek.token env = T_LPAREN then (
Expect.token env T_LPAREN;
let p = Some (Parse.pattern env Parse_error.StrictCatchVariable) in
Expect.token env T_RPAREN;
p
) else
None
in
let body = Parse.block_body env in
(* Fix trailing comment attachment if catch block is end of statement *)
let body =
if Peek.token env <> T_FINALLY then
let { remove_trailing; _ } = statement_end_trailing_comments env in
remove_trailing body (fun remover (loc, body) -> (loc, remover#block loc body))
else
body
in
{
Ast.Statement.Try.CatchClause.param;
body;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
})
env
in
Some catch
| _ -> None
in
let finalizer =
match Peek.token env with
| T_FINALLY ->
Expect.token env T_FINALLY;
let (loc, body) = Parse.block_body env in
let { remove_trailing; _ } = statement_end_trailing_comments env in
let body = remove_trailing body (fun remover body -> remover#block loc body) in
Some (loc, body)
| _ -> None
in
(* No catch or finally? That's an error! *)
if handler = None && finalizer = None then
error_at env (fst block, Parse_error.NoCatchOrFinally);
Statement.Try
{
Statement.Try.block;
handler;
finalizer;
comments = Flow_ast_utils.mk_comments_opt ~leading ();
}
)
and var =
with_loc (fun env ->
let kind = Statement.VariableDeclaration.Var in
let (declarations, leading, errs) = Declaration.var env in
let (trailing, declarations) = variable_declaration_end ~kind env declarations in
errs |> List.iter (error_at env);
Statement.VariableDeclaration
{
Statement.VariableDeclaration.kind;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and const =
with_loc (fun env ->
let kind = Statement.VariableDeclaration.Const in
let (declarations, leading, errs) = Declaration.const env in
let (trailing, declarations) = variable_declaration_end ~kind env declarations in
errs |> List.iter (error_at env);
Statement.VariableDeclaration
{
Statement.VariableDeclaration.kind;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and let_ =
with_loc (fun env ->
let kind = Statement.VariableDeclaration.Let in
let (declarations, leading, errs) = Declaration.let_ env in
let (trailing, declarations) = variable_declaration_end ~kind env declarations in
errs |> List.iter (error_at env);
Statement.VariableDeclaration
{
Statement.VariableDeclaration.kind;
declarations;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
)
and while_ =
with_loc (fun env ->
let leading = Peek.comments env in
Expect.token env T_WHILE;
let leading = leading @ Peek.comments env in
Expect.token env T_LPAREN;
let test = Parse.expression env in
Expect.token env T_RPAREN;
let body = Parse.statement (env |> with_in_loop true) in
(* Annex B allows labelled FunctionDeclarations in non-strict mode
(see sec-labelled-function-declarations), but not in IterationStatement
(see sec-semantics-static-semantics-early-errors). *)
if (not (in_strict_mode env)) && is_labelled_function body then
function_as_statement_error_at env (fst body);
Statement.While
{ Statement.While.test; body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
)
and with_ env =
let (loc, stmt) =
with_loc
(fun env ->
let leading = Peek.comments env in
Expect.token env T_WITH;
let leading = leading @ Peek.comments env in
Expect.token env T_LPAREN;
let _object = Parse.expression env in
Expect.token env T_RPAREN;
let body = Parse.statement env in
(* Annex B allows labelled FunctionDeclarations in non-strict mode
(see sec-labelled-function-declarations), but not in WithStatement
(see sec-with-statement-static-semantics-early-errors). *)
if (not (in_strict_mode env)) && is_labelled_function body then
function_as_statement_error_at env (fst body);
Statement.With
{ Statement.With._object; body; comments = Flow_ast_utils.mk_comments_opt ~leading () })
env
in
strict_error_at env (loc, Parse_error.StrictModeWith);
(loc, stmt)
and block env =
let (loc, block) = Parse.block_body env in
let { remove_trailing; _ } = statement_end_trailing_comments env in
let block = remove_trailing block (fun remover block -> remover#block loc block) in
(loc, Statement.Block block)
and maybe_labeled =
with_loc (fun env ->
let leading = Peek.comments env in
match (Parse.expression env, Peek.token env) with
| ((loc, Ast.Expression.Identifier label), T_COLON) ->
let (_, { Identifier.name; comments = _ }) = label in
Expect.token env T_COLON;
if SSet.mem name (labels env) then
error_at env (loc, Parse_error.Redeclaration ("Label", name));
let env = add_label env name in
let body =
(* labelled FunctionDeclarations are allowed in non-strict mode
(see #sec-labelled-function-declarations) *)
if Peek.is_function env then
function_as_statement env
else
Parse.statement env
in
Statement.Labeled
{ Statement.Labeled.label; body; comments = Flow_ast_utils.mk_comments_opt ~leading () }
| (expression, _) ->
let (trailing, expression) =
match semicolon ~expected:"the end of an expression statement (`;`)" env with
| Explicit comments -> (comments, expression)
| Implicit { remove_trailing; _ } ->
([], remove_trailing expression (fun remover expr -> remover#expression expr))
in
let open Statement in
Expression
{
Expression.expression;
directive = None;
comments = Flow_ast_utils.mk_comments_opt ~trailing ();
}
)
and expression =
with_loc (fun env ->
let expression = Parse.expression env in
let (trailing, expression) =
match semicolon ~expected:"the end of an expression statement (`;`)" env with
| Explicit comments -> (comments, expression)
| Implicit { remove_trailing; _ } ->
([], remove_trailing expression (fun remover expr -> remover#expression expr))
in
let directive =
if allow_directive env then
match expression with
| (_, Ast.Expression.Literal { Ast.Literal.value = Ast.Literal.String _; raw; _ }) ->
(* the parser may recover from errors and generate unclosed strings, where
the opening quote should be reliable but the closing one might not exist.
be defensive. *)
if String.length raw > 1 && raw.[0] = raw.[String.length raw - 1] then
Some (String.sub raw 1 (String.length raw - 2))
else
None
| _ -> None
else
None
in
Statement.Expression
{
Statement.Expression.expression;
directive;
comments = Flow_ast_utils.mk_comments_opt ~trailing ();
}
)
and type_alias_helper ~leading env =
if not (should_parse_types env) then error env Parse_error.UnexpectedTypeAlias;
let leading = leading @ Peek.comments env in
Expect.token env T_TYPE;
Eat.push_lex_mode env Lex_mode.TYPE;
let id =
let id = Type.type_identifier env in
if Peek.token env = T_LESS_THAN then
id_remove_trailing env id
else
id
in
let tparams = Type.type_params env in
Expect.token env T_ASSIGN;
let right = Type._type env in
Eat.pop_lex_mode env;
let (trailing, right) =
match semicolon env with
| Explicit comments -> (comments, right)
| Implicit { remove_trailing; _ } ->
([], remove_trailing right (fun remover right -> remover#type_ right))
in
{
Statement.TypeAlias.id;
tparams;
right;
comments = Flow_ast_utils.mk_comments_opt ~leading ~trailing ();
}
and declare_type_alias env =
with_loc
(fun env ->
let leading = Peek.comments env in
Expect.token env T_DECLARE;
let type_alias = type_alias_helper ~leading env in
Statement.DeclareTypeAlias type_alias)
env
(** Type aliases squeeze into an unambiguous unused portion of the grammar: `type` is not a
reserved word, so `type T` is otherwise two identifiers in a row and that's never valid JS.
However, if there's a line separator between the two, ASI makes it valid JS, so line
separators are disallowed. *)
and type_alias env =
if Peek.ith_is_identifier ~i:1 env && not (Peek.ith_is_implicit_semicolon ~i:1 env) then
let (loc, type_alias) = with_loc (type_alias_helper ~leading:[]) env in
(loc, Statement.TypeAlias type_alias)
else
Parse.statement env
and opaque_type_helper ?(declare = false) ~leading env =
if not (should_parse_types env) then error env Parse_error.UnexpectedOpaqueTypeAlias;
let leading_opaque = leading @ Peek.comments env in
Expect.token env T_OPAQUE;
let leading_type = Peek.comments env in
Expect.token env T_TYPE;
let leading = leading_opaque @ leading_type in
Eat.push_lex_mode env Lex_mode.TYPE;
let id =
let id = Type.type_identifier env in
if Peek.token env = T_LESS_THAN then
id_remove_trailing env id
else
id
in
let tparams = Type.type_params env in
let supertype =
match Peek.token env with
| T_COLON ->
Expect.token env T_COLON;
Some (Type._type env)
| _ -> None
in
let impltype =
if declare then
match Peek.token env with
| T_ASSIGN ->
error env Parse_error.DeclareOpaqueTypeInitializer;
Eat.token env;
if Peek.token env = T_SEMICOLON || Peek.is_implicit_semicolon env then
None
else
Some (Type._type env)
| _ -> None
else (
Expect.token env T_ASSIGN;
Some (Type._type env)
)
in
Eat.pop_lex_mode env;
let (trailing, id, tparams, supertype, impltype) =
match (semicolon env, tparams, supertype, impltype) with
(* opaque type Foo = Bar; *)
| (Explicit comments, _, _, _) -> (comments, id, tparams, supertype, impltype)
(* opaque type Foo = Bar *)
| (Implicit { remove_trailing; _ }, _, _, Some impl) ->
( [],
id,
tparams,
supertype,
Some (remove_trailing impl (fun remover impl -> remover#type_ impl))
)
(* opaque type Foo: Super *)
| (Implicit { remove_trailing; _ }, _, Some super, None) ->
( [],
id,
tparams,
Some (remove_trailing super (fun remover super -> remover#type_ super)),
None
)
(* opaque type Foo<T> *)
| (Implicit { remove_trailing; _ }, Some tparams, None, None) ->
( [],
id,
Some (remove_trailing tparams (fun remover tparams -> remover#type_params tparams)),