This repository was archived by the owner on Jun 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathres_core.ml
6373 lines (6120 loc) · 201 KB
/
res_core.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
module Doc = Res_doc
module Grammar = Res_grammar
module Token = Res_token
module Diagnostics = Res_diagnostics
module CommentTable = Res_comments_table
module ResPrinter = Res_printer
module Scanner = Res_scanner
module JsFfi = Res_js_ffi
module Parser = Res_parser
let mkLoc startLoc endLoc =
Location.{loc_start = startLoc; loc_end = endLoc; loc_ghost = false}
module Recover = struct
let defaultExpr () =
let id = Location.mknoloc "rescript.exprhole" in
Ast_helper.Exp.mk (Pexp_extension (id, PStr []))
let defaultType () =
let id = Location.mknoloc "rescript.typehole" in
Ast_helper.Typ.extension (id, PStr [])
let defaultPattern () =
let id = Location.mknoloc "rescript.patternhole" in
Ast_helper.Pat.extension (id, PStr [])
let defaultModuleExpr () = Ast_helper.Mod.structure []
let defaultModuleType () = Ast_helper.Mty.signature []
let defaultSignatureItem =
let id = Location.mknoloc "rescript.sigitemhole" in
Ast_helper.Sig.extension (id, PStr [])
let recoverEqualGreater p =
Parser.expect EqualGreater p;
match p.Parser.token with
| MinusGreater -> Parser.next p
| _ -> ()
let shouldAbortListParse p =
let rec check breadcrumbs =
match breadcrumbs with
| [] -> false
| (grammar, _) :: rest ->
if Grammar.isPartOfList grammar p.Parser.token then true else check rest
in
check p.breadcrumbs
end
module ErrorMessages = struct
let listPatternSpread =
"List pattern matches only supports one `...` spread, at the end.\n\
Explanation: a list spread at the tail is efficient, but a spread in the \
middle would create new list[s]; out of performance concern, our pattern \
matching currently guarantees to never create new intermediate data."
let recordPatternSpread =
"Record's `...` spread is not supported in pattern matches.\n\
Explanation: you can't collect a subset of a record's field into its own \
record, since a record needs an explicit declaration and that subset \
wouldn't have one.\n\
Solution: you need to pull out each field you want explicitly."
(* let recordPatternUnderscore = "Record patterns only support one `_`, at the end." *)
[@@live]
let arrayPatternSpread =
"Array's `...` spread is not supported in pattern matches.\n\
Explanation: such spread would create a subarray; out of performance \
concern, our pattern matching currently guarantees to never create new \
intermediate data.\n\
Solution: if it's to validate the first few elements, use a `when` clause \
+ Array size check + `get` checks on the current pattern. If it's to \
obtain a subarray, use `Array.sub` or `Belt.Array.slice`."
let arrayExprSpread =
"Arrays can't use the `...` spread currently. Please use `concat` or other \
Array helpers."
let recordExprSpread =
"Records can only have one `...` spread, at the beginning.\n\
Explanation: since records have a known, fixed shape, a spread like `{a, \
...b}` wouldn't make sense, as `b` would override every field of `a` \
anyway."
let listExprSpread =
"Lists can only have one `...` spread, and at the end.\n\
Explanation: lists are singly-linked list, where a node contains a value \
and points to the next node. `list[a, ...bc]` efficiently creates a new \
item and links `bc` as its next nodes. `[...bc, a]` would be expensive, \
as it'd need to traverse `bc` and prepend each item to `a` one by one. We \
therefore disallow such syntax sugar.\n\
Solution: directly use `concat`."
let variantIdent =
"A polymorphic variant (e.g. #id) must start with an alphabetical letter \
or be a number (e.g. #742)"
let experimentalIfLet expr =
let switchExpr = {expr with Parsetree.pexp_attributes = []} in
Doc.concat
[
Doc.text "If-let is currently highly experimental.";
Doc.line;
Doc.text "Use a regular `switch` with pattern matching instead:";
Doc.concat
[
Doc.hardLine;
Doc.hardLine;
ResPrinter.printExpression switchExpr CommentTable.empty;
];
]
|> Doc.toString ~width:80
let typeParam =
"A type param consists of a singlequote followed by a name like `'a` or \
`'A`"
let typeVar =
"A type variable consists of a singlequote followed by a name like `'a` or \
`'A`"
let attributeWithoutNode (attr : Parsetree.attribute) =
let {Asttypes.txt = attrName}, _ = attr in
"Did you forget to attach `" ^ attrName
^ "` to an item?\n Standalone attributes start with `@@` like: `@@"
^ attrName ^ "`"
let typeDeclarationNameLongident longident =
"A type declaration's name cannot contain a module access. Did you mean `"
^ Longident.last longident ^ "`?"
let tupleSingleElement = "A tuple needs at least two elements"
let missingTildeLabeledParameter name =
if name = "" then "A labeled parameter starts with a `~`."
else "A labeled parameter starts with a `~`. Did you mean: `~" ^ name ^ "`?"
let stringInterpolationInPattern =
"String interpolation is not supported in pattern matching."
let spreadInRecordDeclaration =
"A record type declaration doesn't support the ... spread. Only an object \
(with quoted field names) does."
let objectQuotedFieldName name =
"An object type declaration needs quoted field names. Did you mean \""
^ name ^ "\"?"
let forbiddenInlineRecordDeclaration =
"An inline record type declaration is only allowed in a variant \
constructor's declaration"
let sameTypeSpread =
"You're using a ... spread without extra fields. This is the same type."
let polyVarIntWithSuffix number =
"A numeric polymorphic variant cannot be followed by a letter. Did you \
mean `#" ^ number ^ "`?"
end
let jsxAttr = (Location.mknoloc "JSX", Parsetree.PStr [])
let uncurryAttr = (Location.mknoloc "bs", Parsetree.PStr [])
let ternaryAttr = (Location.mknoloc "ns.ternary", Parsetree.PStr [])
let ifLetAttr = (Location.mknoloc "ns.iflet", Parsetree.PStr [])
let optionalAttr = (Location.mknoloc "ns.optional", Parsetree.PStr [])
let makeExpressionOptional ~optional (e : Parsetree.expression) =
if optional then {e with pexp_attributes = optionalAttr :: e.pexp_attributes}
else e
let makePatternOptional ~optional (p : Parsetree.pattern) =
if optional then {p with ppat_attributes = optionalAttr :: p.ppat_attributes}
else p
let suppressFragileMatchWarningAttr =
( Location.mknoloc "warning",
Parsetree.PStr
[
Ast_helper.Str.eval
(Ast_helper.Exp.constant (Pconst_string ("-4", None)));
] )
let makeBracesAttr loc = (Location.mkloc "ns.braces" loc, Parsetree.PStr [])
let templateLiteralAttr = (Location.mknoloc "res.template", Parsetree.PStr [])
type typDefOrExt =
| TypeDef of {
recFlag: Asttypes.rec_flag;
types: Parsetree.type_declaration list;
}
| TypeExt of Parsetree.type_extension
type labelledParameter =
| TermParameter of {
uncurried: bool;
attrs: Parsetree.attributes;
label: Asttypes.arg_label;
expr: Parsetree.expression option;
pat: Parsetree.pattern;
pos: Lexing.position;
}
| TypeParameter of {
uncurried: bool;
attrs: Parsetree.attributes;
locs: string Location.loc list;
pos: Lexing.position;
}
type recordPatternItem =
| PatUnderscore
| PatField of (Ast_helper.lid * Parsetree.pattern)
type context = OrdinaryExpr | TernaryTrueBranchExpr | WhenExpr
let getClosingToken = function
| Token.Lparen -> Token.Rparen
| Lbrace -> Rbrace
| Lbracket -> Rbracket
| List -> Rbrace
| LessThan -> GreaterThan
| _ -> assert false
let rec goToClosing closingToken state =
match (state.Parser.token, closingToken) with
| Rparen, Token.Rparen
| Rbrace, Rbrace
| Rbracket, Rbracket
| GreaterThan, GreaterThan ->
Parser.next state;
()
| ((Token.Lbracket | Lparen | Lbrace | List | LessThan) as t), _ ->
Parser.next state;
goToClosing (getClosingToken t) state;
goToClosing closingToken state
| (Rparen | Token.Rbrace | Rbracket | Eof), _ ->
() (* TODO: how do report errors here? *)
| _ ->
Parser.next state;
goToClosing closingToken state
(* Madness *)
let isEs6ArrowExpression ~inTernary p =
Parser.lookahead p (fun state ->
match state.Parser.token with
| Lident _ | Underscore -> (
Parser.next state;
match state.Parser.token with
(* Don't think that this valid
* Imagine: let x = (a: int)
* This is a parenthesized expression with a type constraint, wait for
* the arrow *)
(* | Colon when not inTernary -> true *)
| EqualGreater -> true
| _ -> false)
| Lparen -> (
let prevEndPos = state.prevEndPos in
Parser.next state;
match state.token with
(* arrived at `()` here *)
| Rparen -> (
Parser.next state;
match state.Parser.token with
(* arrived at `() :` here *)
| Colon when not inTernary -> (
Parser.next state;
match state.Parser.token with
(* arrived at `() :typ` here *)
| Lident _ -> (
Parser.next state;
(match state.Parser.token with
(* arrived at `() :typ<` here *)
| LessThan ->
Parser.next state;
goToClosing GreaterThan state
| _ -> ());
match state.Parser.token with
(* arrived at `() :typ =>` or `() :typ<'a,'b> =>` here *)
| EqualGreater -> true
| _ -> false)
| _ -> true)
| EqualGreater -> true
| _ -> false)
| Dot (* uncurried *) -> true
| Tilde -> true
| Backtick ->
false
(* (` always indicates the start of an expr, can't be es6 parameter *)
| _ -> (
goToClosing Rparen state;
match state.Parser.token with
| EqualGreater -> true
(* | Lbrace TODO: detect missing =>, is this possible? *)
| Colon when not inTernary -> true
| Rparen ->
(* imagine having something as :
* switch colour {
* | Red
* when l == l'
* || (&Clflags.classic && (l == Nolabel && !is_optional(l'))) => (t1, t2)
* We'll arrive at the outer rparen just before the =>.
* This is not an es6 arrow.
* *)
false
| _ -> (
Parser.nextUnsafe state;
(* error recovery, peek at the next token,
* (elements, providerId] => {
* in the example above, we have an unbalanced ] here
*)
match state.Parser.token with
| EqualGreater when state.startPos.pos_lnum == prevEndPos.pos_lnum
->
true
| _ -> false)))
| _ -> false)
let isEs6ArrowFunctor p =
Parser.lookahead p (fun state ->
match state.Parser.token with
(* | Uident _ | Underscore -> *)
(* Parser.next state; *)
(* begin match state.Parser.token with *)
(* | EqualGreater -> true *)
(* | _ -> false *)
(* end *)
| Lparen -> (
Parser.next state;
match state.token with
| Rparen -> (
Parser.next state;
match state.token with
| Colon | EqualGreater -> true
| _ -> false)
| _ -> (
goToClosing Rparen state;
match state.Parser.token with
| EqualGreater | Lbrace -> true
| Colon -> true
| _ -> false))
| _ -> false)
let isEs6ArrowType p =
Parser.lookahead p (fun state ->
match state.Parser.token with
| Lparen -> (
Parser.next state;
match state.Parser.token with
| Rparen -> (
Parser.next state;
match state.Parser.token with
| EqualGreater -> true
| _ -> false)
| Tilde | Dot -> true
| _ -> (
goToClosing Rparen state;
match state.Parser.token with
| EqualGreater -> true
| _ -> false))
| Tilde -> true
| _ -> false)
let buildLongident words =
match List.rev words with
| [] -> assert false
| hd :: tl -> List.fold_left (fun p s -> Longident.Ldot (p, s)) (Lident hd) tl
let makeInfixOperator p token startPos endPos =
let stringifiedToken =
if token = Token.MinusGreater then "|."
else if token = Token.PlusPlus then "^"
else if token = Token.BangEqual then "<>"
else if token = Token.BangEqualEqual then "!="
else if token = Token.Equal then (
(* TODO: could have a totally different meaning like x->fooSet(y)*)
Parser.err ~startPos ~endPos p
(Diagnostics.message "Did you mean `==` here?");
"=")
else if token = Token.EqualEqual then "="
else if token = Token.EqualEqualEqual then "=="
else Token.toString token
in
let loc = mkLoc startPos endPos in
let operator = Location.mkloc (Longident.Lident stringifiedToken) loc in
Ast_helper.Exp.ident ~loc operator
let negateString s =
if String.length s > 0 && (s.[0] [@doesNotRaise]) = '-' then
(String.sub [@doesNotRaise]) s 1 (String.length s - 1)
else "-" ^ s
let makeUnaryExpr startPos tokenEnd token operand =
match (token, operand.Parsetree.pexp_desc) with
| (Token.Plus | PlusDot), Pexp_constant (Pconst_integer _ | Pconst_float _) ->
operand
| Minus, Pexp_constant (Pconst_integer (n, m)) ->
{
operand with
pexp_desc = Pexp_constant (Pconst_integer (negateString n, m));
}
| (Minus | MinusDot), Pexp_constant (Pconst_float (n, m)) ->
{operand with pexp_desc = Pexp_constant (Pconst_float (negateString n, m))}
| (Token.Plus | PlusDot | Minus | MinusDot), _ ->
let tokenLoc = mkLoc startPos tokenEnd in
let operator = "~" ^ Token.toString token in
Ast_helper.Exp.apply
~loc:(mkLoc startPos operand.Parsetree.pexp_loc.loc_end)
(Ast_helper.Exp.ident ~loc:tokenLoc
(Location.mkloc (Longident.Lident operator) tokenLoc))
[(Nolabel, operand)]
| Token.Bang, _ ->
let tokenLoc = mkLoc startPos tokenEnd in
Ast_helper.Exp.apply
~loc:(mkLoc startPos operand.Parsetree.pexp_loc.loc_end)
(Ast_helper.Exp.ident ~loc:tokenLoc
(Location.mkloc (Longident.Lident "not") tokenLoc))
[(Nolabel, operand)]
| _ -> operand
let makeListExpression loc seq extOpt =
let rec handleSeq = function
| [] -> (
match extOpt with
| Some ext -> ext
| None ->
let loc = {loc with Location.loc_ghost = true} in
let nil = Location.mkloc (Longident.Lident "[]") loc in
Ast_helper.Exp.construct ~loc nil None)
| e1 :: el ->
let exp_el = handleSeq el in
let loc =
mkLoc e1.Parsetree.pexp_loc.Location.loc_start exp_el.pexp_loc.loc_end
in
let arg = Ast_helper.Exp.tuple ~loc [e1; exp_el] in
Ast_helper.Exp.construct ~loc
(Location.mkloc (Longident.Lident "::") loc)
(Some arg)
in
let expr = handleSeq seq in
{expr with pexp_loc = loc}
let makeListPattern loc seq ext_opt =
let rec handle_seq = function
| [] ->
let base_case =
match ext_opt with
| Some ext -> ext
| None ->
let loc = {loc with Location.loc_ghost = true} in
let nil = {Location.txt = Longident.Lident "[]"; loc} in
Ast_helper.Pat.construct ~loc nil None
in
base_case
| p1 :: pl ->
let pat_pl = handle_seq pl in
let loc = mkLoc p1.Parsetree.ppat_loc.loc_start pat_pl.ppat_loc.loc_end in
let arg = Ast_helper.Pat.mk ~loc (Ppat_tuple [p1; pat_pl]) in
Ast_helper.Pat.mk ~loc
(Ppat_construct (Location.mkloc (Longident.Lident "::") loc, Some arg))
in
handle_seq seq
(* TODO: diagnostic reporting *)
let lidentOfPath longident =
match Longident.flatten longident |> List.rev with
| [] -> ""
| ident :: _ -> ident
let makeNewtypes ~attrs ~loc newtypes exp =
let expr =
List.fold_right
(fun newtype exp -> Ast_helper.Exp.mk ~loc (Pexp_newtype (newtype, exp)))
newtypes exp
in
{expr with pexp_attributes = attrs}
(* locally abstract types syntax sugar
* Transforms
* let f: type t u v. = (foo : list</t, u, v/>) => ...
* into
* let f = (type t u v. foo : list</t, u, v/>) => ...
*)
let wrapTypeAnnotation ~loc newtypes core_type body =
let exp =
makeNewtypes ~attrs:[] ~loc newtypes
(Ast_helper.Exp.constraint_ ~loc body core_type)
in
let typ =
Ast_helper.Typ.poly ~loc newtypes
(Ast_helper.Typ.varify_constructors newtypes core_type)
in
(exp, typ)
(**
* process the occurrence of _ in the arguments of a function application
* replace _ with a new variable, currently __x, in the arguments
* return a wrapping function that wraps ((__x) => ...) around an expression
* e.g. foo(_, 3) becomes (__x) => foo(__x, 3)
*)
let processUnderscoreApplication args =
let exp_question = ref None in
let hidden_var = "__x" in
let check_arg ((lab, exp) as arg) =
match exp.Parsetree.pexp_desc with
| Pexp_ident ({txt = Lident "_"} as id) ->
let new_id = Location.mkloc (Longident.Lident hidden_var) id.loc in
let new_exp = Ast_helper.Exp.mk (Pexp_ident new_id) ~loc:exp.pexp_loc in
exp_question := Some new_exp;
(lab, new_exp)
| _ -> arg
in
let args = List.map check_arg args in
let wrap exp_apply =
match !exp_question with
| Some {pexp_loc = loc} ->
let pattern =
Ast_helper.Pat.mk (Ppat_var (Location.mkloc hidden_var loc)) ~loc
in
Ast_helper.Exp.mk (Pexp_fun (Nolabel, None, pattern, exp_apply)) ~loc
| None -> exp_apply
in
(args, wrap)
(* Transform A.a into a. For use with punned record fields as in {A.a, b}. *)
let removeModuleNameFromPunnedFieldValue exp =
match exp.Parsetree.pexp_desc with
| Pexp_ident pathIdent ->
{
exp with
pexp_desc =
Pexp_ident {pathIdent with txt = Lident (Longident.last pathIdent.txt)};
}
| _ -> exp
let rec parseLident p =
let recoverLident p =
if
Token.isKeyword p.Parser.token
&& p.Parser.prevEndPos.pos_lnum == p.startPos.pos_lnum
then (
Parser.err p (Diagnostics.lident p.Parser.token);
Parser.next p;
None)
else
let rec loop p =
if (not (Recover.shouldAbortListParse p)) && p.token <> Eof then (
Parser.next p;
loop p)
in
Parser.err p (Diagnostics.lident p.Parser.token);
Parser.next p;
loop p;
match p.Parser.token with
| Lident _ -> Some ()
| _ -> None
in
let startPos = p.Parser.startPos in
match p.Parser.token with
| Lident ident ->
Parser.next p;
let loc = mkLoc startPos p.prevEndPos in
(ident, loc)
| _ -> (
match recoverLident p with
| Some () -> parseLident p
| None -> ("_", mkLoc startPos p.prevEndPos))
let parseIdent ~msg ~startPos p =
match p.Parser.token with
| Lident ident | Uident ident ->
Parser.next p;
let loc = mkLoc startPos p.prevEndPos in
(ident, loc)
| token
when Token.isKeyword token && p.prevEndPos.pos_lnum == p.startPos.pos_lnum
->
let tokenTxt = Token.toString token in
let msg =
"`" ^ tokenTxt
^ "` is a reserved keyword. Keywords need to be escaped: \\\"" ^ tokenTxt
^ "\""
in
Parser.err ~startPos p (Diagnostics.message msg);
Parser.next p;
(tokenTxt, mkLoc startPos p.prevEndPos)
| _token ->
Parser.err ~startPos p (Diagnostics.message msg);
Parser.next p;
("", mkLoc startPos p.prevEndPos)
let parseHashIdent ~startPos p =
Parser.expect Hash p;
match p.token with
| String text ->
Parser.next p;
(text, mkLoc startPos p.prevEndPos)
| Int {i; suffix} ->
let () =
match suffix with
| Some _ ->
Parser.err p
(Diagnostics.message (ErrorMessages.polyVarIntWithSuffix i))
| None -> ()
in
Parser.next p;
(i, mkLoc startPos p.prevEndPos)
| _ -> parseIdent ~startPos ~msg:ErrorMessages.variantIdent p
(* Ldot (Ldot (Lident "Foo", "Bar"), "baz") *)
let parseValuePath p =
let startPos = p.Parser.startPos in
let rec aux p path =
match p.Parser.token with
| Lident ident -> Longident.Ldot (path, ident)
| Uident uident ->
Parser.next p;
if p.Parser.token = Dot then (
Parser.expect Dot p;
aux p (Ldot (path, uident)))
else (
Parser.err p (Diagnostics.unexpected p.Parser.token p.breadcrumbs);
path)
| token ->
Parser.err p (Diagnostics.unexpected token p.breadcrumbs);
Longident.Ldot (path, "_")
in
let ident =
match p.Parser.token with
| Lident ident ->
Parser.next p;
Longident.Lident ident
| Uident ident ->
Parser.next p;
let res =
if p.Parser.token = Dot then (
Parser.expect Dot p;
aux p (Lident ident))
else (
Parser.err p (Diagnostics.unexpected p.Parser.token p.breadcrumbs);
Longident.Lident ident)
in
if p.token <> Eof then Parser.next p;
res
| token ->
Parser.err p (Diagnostics.unexpected token p.breadcrumbs);
Parser.next p;
Longident.Lident "_"
in
Location.mkloc ident (mkLoc startPos p.prevEndPos)
let parseValuePathAfterDot p =
let startPos = p.Parser.startPos in
match p.Parser.token with
| Lident _ | Uident _ -> parseValuePath p
| token ->
Parser.err p (Diagnostics.unexpected token p.breadcrumbs);
Location.mkloc (Longident.Lident "_") (mkLoc startPos p.prevEndPos)
let parseValuePathTail p startPos ident =
let rec loop p path =
match p.Parser.token with
| Lident ident ->
Parser.next p;
Location.mkloc
(Longident.Ldot (path, ident))
(mkLoc startPos p.prevEndPos)
| Uident ident ->
Parser.next p;
Parser.expect Dot p;
loop p (Longident.Ldot (path, ident))
| token ->
Parser.err p (Diagnostics.unexpected token p.breadcrumbs);
Location.mkloc (Longident.Ldot (path, "_")) (mkLoc startPos p.prevEndPos)
in
loop p ident
let parseModuleLongIdentTail ~lowercase p startPos ident =
let rec loop p acc =
match p.Parser.token with
| Lident ident when lowercase ->
Parser.next p;
let lident = Longident.Ldot (acc, ident) in
Location.mkloc lident (mkLoc startPos p.prevEndPos)
| Uident ident -> (
Parser.next p;
let endPos = p.prevEndPos in
let lident = Longident.Ldot (acc, ident) in
match p.Parser.token with
| Dot ->
Parser.next p;
loop p lident
| _ -> Location.mkloc lident (mkLoc startPos endPos))
| t ->
Parser.err p (Diagnostics.uident t);
Location.mkloc (Longident.Ldot (acc, "_")) (mkLoc startPos p.prevEndPos)
in
loop p ident
(* Parses module identifiers:
Foo
Foo.Bar *)
let parseModuleLongIdent ~lowercase p =
(* Parser.leaveBreadcrumb p Reporting.ModuleLongIdent; *)
let startPos = p.Parser.startPos in
let moduleIdent =
match p.Parser.token with
| Lident ident when lowercase ->
let loc = mkLoc startPos p.endPos in
let lident = Longident.Lident ident in
Parser.next p;
Location.mkloc lident loc
| Uident ident -> (
let lident = Longident.Lident ident in
let endPos = p.endPos in
Parser.next p;
match p.Parser.token with
| Dot ->
Parser.next p;
parseModuleLongIdentTail ~lowercase p startPos lident
| _ -> Location.mkloc lident (mkLoc startPos endPos))
| t ->
Parser.err p (Diagnostics.uident t);
Location.mkloc (Longident.Lident "_") (mkLoc startPos p.prevEndPos)
in
(* Parser.eatBreadcrumb p; *)
moduleIdent
(* `window.location` or `Math` or `Foo.Bar` *)
let parseIdentPath p =
let rec loop p acc =
match p.Parser.token with
| Uident ident | Lident ident -> (
Parser.next p;
let lident = Longident.Ldot (acc, ident) in
match p.Parser.token with
| Dot ->
Parser.next p;
loop p lident
| _ -> lident)
| _t -> acc
in
match p.Parser.token with
| Lident ident | Uident ident -> (
Parser.next p;
match p.Parser.token with
| Dot ->
Parser.next p;
loop p (Longident.Lident ident)
| _ -> Longident.Lident ident)
| _ -> Longident.Lident "_"
let verifyJsxOpeningClosingName p nameExpr =
let closing =
match p.Parser.token with
| Lident lident ->
Parser.next p;
Longident.Lident lident
| Uident _ -> (parseModuleLongIdent ~lowercase:true p).txt
| _ -> Longident.Lident ""
in
match nameExpr.Parsetree.pexp_desc with
| Pexp_ident openingIdent ->
let opening =
let withoutCreateElement =
Longident.flatten openingIdent.txt
|> List.filter (fun s -> s <> "createElement")
in
match Longident.unflatten withoutCreateElement with
| Some li -> li
| None -> Longident.Lident ""
in
opening = closing
| _ -> assert false
let string_of_pexp_ident nameExpr =
match nameExpr.Parsetree.pexp_desc with
| Pexp_ident openingIdent ->
Longident.flatten openingIdent.txt
|> List.filter (fun s -> s <> "createElement")
|> String.concat "."
| _ -> ""
(* open-def ::=
* | open module-path
* | open! module-path *)
let parseOpenDescription ~attrs p =
Parser.leaveBreadcrumb p Grammar.OpenDescription;
let startPos = p.Parser.startPos in
Parser.expect Open p;
let override =
if Parser.optional p Token.Bang then Asttypes.Override else Asttypes.Fresh
in
let modident = parseModuleLongIdent ~lowercase:false p in
let loc = mkLoc startPos p.prevEndPos in
Parser.eatBreadcrumb p;
Ast_helper.Opn.mk ~loc ~attrs ~override modident
(* constant ::= integer-literal *)
(* ∣ float-literal *)
(* ∣ string-literal *)
let parseConstant p =
let isNegative =
match p.Parser.token with
| Token.Minus ->
Parser.next p;
true
| Plus ->
Parser.next p;
false
| _ -> false
in
let constant =
match p.Parser.token with
| Int {i; suffix} ->
let intTxt = if isNegative then "-" ^ i else i in
Parsetree.Pconst_integer (intTxt, suffix)
| Float {f; suffix} ->
let floatTxt = if isNegative then "-" ^ f else f in
Parsetree.Pconst_float (floatTxt, suffix)
| String s ->
Pconst_string (s, if p.mode = ParseForTypeChecker then Some "js" else None)
| Codepoint {c; original} ->
if p.mode = ParseForTypeChecker then Pconst_char c
else
(* Pconst_char char does not have enough information for formatting.
* When parsing for the printer, we encode the char contents as a string
* with a special prefix. *)
Pconst_string (original, Some "INTERNAL_RES_CHAR_CONTENTS")
| token ->
Parser.err p (Diagnostics.unexpected token p.breadcrumbs);
Pconst_string ("", None)
in
Parser.next p;
constant
let parseTemplateConstant ~prefix (p : Parser.t) =
(* Arrived at the ` char *)
let startPos = p.startPos in
Parser.nextTemplateLiteralToken p;
match p.token with
| TemplateTail txt ->
Parser.next p;
Parsetree.Pconst_string (txt, prefix)
| _ ->
let rec skipTokens () =
if p.token <> Eof then (
Parser.next p;
match p.token with
| Backtick ->
Parser.next p;
()
| _ -> skipTokens ())
in
skipTokens ();
Parser.err ~startPos ~endPos:p.prevEndPos p
(Diagnostics.message ErrorMessages.stringInterpolationInPattern);
Pconst_string ("", None)
let parseCommaDelimitedRegion p ~grammar ~closing ~f =
Parser.leaveBreadcrumb p grammar;
let rec loop nodes =
match f p with
| Some node -> (
match p.Parser.token with
| Comma ->
Parser.next p;
loop (node :: nodes)
| token when token = closing || token = Eof -> List.rev (node :: nodes)
| _ when Grammar.isListElement grammar p.token ->
(* missing comma between nodes in the region and the current token
* looks like the start of something valid in the current region.
* Example:
* type student<'extraInfo> = {
* name: string,
* age: int
* otherInfo: 'extraInfo
* }
* There is a missing comma between `int` and `otherInfo`.
* `otherInfo` looks like a valid start of the record declaration.
* We report the error here and then continue parsing the region.
*)
Parser.expect Comma p;
loop (node :: nodes)
| _ ->
if
not
(p.token = Eof || p.token = closing
|| Recover.shouldAbortListParse p)
then Parser.expect Comma p;
if p.token = Semicolon then Parser.next p;
loop (node :: nodes))
| None ->
if p.token = Eof || p.token = closing || Recover.shouldAbortListParse p
then List.rev nodes
else (
Parser.err p (Diagnostics.unexpected p.token p.breadcrumbs);
Parser.next p;
loop nodes)
in
let nodes = loop [] in
Parser.eatBreadcrumb p;
nodes
let parseCommaDelimitedReversedList p ~grammar ~closing ~f =
Parser.leaveBreadcrumb p grammar;
let rec loop nodes =
match f p with
| Some node -> (
match p.Parser.token with
| Comma ->
Parser.next p;
loop (node :: nodes)
| token when token = closing || token = Eof -> node :: nodes
| _ when Grammar.isListElement grammar p.token ->
(* missing comma between nodes in the region and the current token
* looks like the start of something valid in the current region.
* Example:
* type student<'extraInfo> = {
* name: string,
* age: int
* otherInfo: 'extraInfo
* }
* There is a missing comma between `int` and `otherInfo`.
* `otherInfo` looks like a valid start of the record declaration.
* We report the error here and then continue parsing the region.
*)
Parser.expect Comma p;
loop (node :: nodes)
| _ ->
if
not
(p.token = Eof || p.token = closing
|| Recover.shouldAbortListParse p)
then Parser.expect Comma p;
if p.token = Semicolon then Parser.next p;
loop (node :: nodes))
| None ->
if p.token = Eof || p.token = closing || Recover.shouldAbortListParse p
then nodes
else (
Parser.err p (Diagnostics.unexpected p.token p.breadcrumbs);
Parser.next p;
loop nodes)
in
let nodes = loop [] in
Parser.eatBreadcrumb p;
nodes
let parseDelimitedRegion p ~grammar ~closing ~f =
Parser.leaveBreadcrumb p grammar;
let rec loop nodes =
match f p with
| Some node -> loop (node :: nodes)
| None ->
if
p.Parser.token = Token.Eof || p.token = closing
|| Recover.shouldAbortListParse p
then List.rev nodes
else (
Parser.err p (Diagnostics.unexpected p.token p.breadcrumbs);
Parser.next p;
loop nodes)
in
let nodes = loop [] in
Parser.eatBreadcrumb p;
nodes
let parseRegion p ~grammar ~f =
Parser.leaveBreadcrumb p grammar;
let rec loop nodes =
match f p with
| Some node -> loop (node :: nodes)
| None ->
if p.Parser.token = Token.Eof || Recover.shouldAbortListParse p then
List.rev nodes
else (
Parser.err p (Diagnostics.unexpected p.token p.breadcrumbs);
Parser.next p;
loop nodes)
in
let nodes = loop [] in
Parser.eatBreadcrumb p;
nodes
(* let-binding ::= pattern = expr *)
(* ∣ value-name { parameter } [: typexpr] [:> typexpr] = expr *)
(* ∣ value-name : poly-typexpr = expr *)
(* pattern ::= value-name *)
(* ∣ _ *)
(* ∣ constant *)
(* ∣ pattern as value-name *)
(* ∣ ( pattern ) *)
(* ∣ ( pattern : typexpr ) *)
(* ∣ pattern | pattern *)
(* ∣ constr pattern *)
(* ∣ #variant variant-pattern *)
(* ∣ #...type *)
(* ∣ / pattern { , pattern }+ / *)
(* ∣ { field [: typexpr] [= pattern] { ; field [: typexpr] [= pattern] } [; _ ] [ ; ] } *)
(* ∣ [ pattern { ; pattern } [ ; ] ] *)
(* ∣ pattern :: pattern *)
(* ∣ [| pattern { ; pattern } [ ; ] |] *)
(* ∣ char-literal .. char-literal *)