-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlexer_flow.mll
1823 lines (1742 loc) · 71.1 KB
/
lexer_flow.mll
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) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the "flow" directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*)
{
module Ast = Spider_monkey_ast
module Token = struct
type t =
| T_NUMBER of number_type
| T_STRING of (Loc.t * string * string * bool) (* loc, value, raw, octal *)
| T_TEMPLATE_PART of (Loc.t * template_part * bool) (* loc, value, is_tail *)
| T_IDENTIFIER
| T_REGEXP of (Loc.t * string * string) (* /pattern/flags *)
(* Syntax *)
| T_LCURLY
| T_RCURLY
| T_LCURLYBAR
| T_RCURLYBAR
| T_LPAREN
| T_RPAREN
| T_LBRACKET
| T_RBRACKET
| T_SEMICOLON
| T_COMMA
| T_PERIOD
| T_ARROW
| T_ELLIPSIS
| T_AT
(* Keywords *)
| T_FUNCTION
| T_IF
| T_IN
| T_INSTANCEOF
| T_RETURN
| T_SWITCH
| T_THIS
| T_THROW
| T_TRY
| T_VAR
| T_WHILE
| T_WITH
| T_CONST
| T_LET
| T_NULL
| T_FALSE
| T_TRUE
| T_BREAK
| T_CASE
| T_CATCH
| T_CONTINUE
| T_DEFAULT
| T_DO
| T_FINALLY
| T_FOR
| T_CLASS
| T_EXTENDS
| T_STATIC
| T_ELSE
| T_NEW
| T_DELETE
| T_TYPEOF
| T_VOID
| T_ENUM
| T_EXPORT
| T_IMPORT
| T_SUPER
| T_IMPLEMENTS
| T_INTERFACE
| T_PACKAGE
| T_PRIVATE
| T_PROTECTED
| T_PUBLIC
| T_YIELD
| T_DEBUGGER
| T_DECLARE
| T_TYPE
| T_OF
| T_ASYNC
| T_AWAIT
| T_CHECKS
(* Operators *)
| T_RSHIFT3_ASSIGN
| T_RSHIFT_ASSIGN
| T_LSHIFT_ASSIGN
| T_BIT_XOR_ASSIGN
| T_BIT_OR_ASSIGN
| T_BIT_AND_ASSIGN
| T_MOD_ASSIGN
| T_DIV_ASSIGN
| T_MULT_ASSIGN
| T_EXP_ASSIGN
| T_MINUS_ASSIGN
| T_PLUS_ASSIGN
| T_ASSIGN
| T_PLING
| T_COLON
| T_OR
| T_AND
| T_BIT_OR
| T_BIT_XOR
| T_BIT_AND
| T_EQUAL
| T_NOT_EQUAL
| T_STRICT_EQUAL
| T_STRICT_NOT_EQUAL
| T_LESS_THAN_EQUAL
| T_GREATER_THAN_EQUAL
| T_LESS_THAN
| T_GREATER_THAN
| T_LSHIFT
| T_RSHIFT
| T_RSHIFT3
| T_PLUS
| T_MINUS
| T_DIV
| T_MULT
| T_EXP
| T_MOD
| T_NOT
| T_BIT_NOT
| T_INCR
| T_DECR
(* Extra tokens *)
| T_ERROR
| T_EOF
(* JSX *)
| T_JSX_IDENTIFIER
| T_JSX_TEXT of (Loc.t * string * string) (* loc, value, raw *)
(* Type primitives *)
| T_ANY_TYPE
| T_MIXED_TYPE
| T_EMPTY_TYPE
| T_BOOLEAN_TYPE
| T_NUMBER_TYPE
| T_NUMBER_SINGLETON_TYPE of number_type * float
| T_STRING_TYPE
| T_VOID_TYPE
and number_type =
| BINARY
| LEGACY_OCTAL
| OCTAL
| NORMAL
and template_part = {
cooked: string; (* string after processing special chars *)
raw: string; (* string as specified in source *)
literal: string; (* same as raw, plus characters like ` and ${ *)
}
(*****************************************************************************)
(* Pretty printer (pretty?) *)
(*****************************************************************************)
let token_to_string = function
| T_NUMBER _ -> "T_NUMBER"
| T_STRING _ -> "T_STRING"
| T_TEMPLATE_PART _ -> "T_TEMPLATE_PART"
| T_IDENTIFIER -> "T_IDENTIFIER"
| T_REGEXP _ -> "T_REGEXP"
| T_FUNCTION -> "T_FUNCTION"
| T_IF -> "T_IF"
| T_IN -> "T_IN"
| T_INSTANCEOF -> "T_INSTANCEOF"
| T_RETURN -> "T_RETURN"
| T_SWITCH -> "T_SWITCH"
| T_THIS -> "T_THIS"
| T_THROW -> "T_THROW"
| T_TRY -> "T_TRY"
| T_VAR -> "T_VAR"
| T_WHILE -> "T_WHILE"
| T_WITH -> "T_WITH"
| T_CONST -> "T_CONST"
| T_LET -> "T_LET"
| T_NULL -> "T_NULL"
| T_FALSE -> "T_FALSE"
| T_TRUE -> "T_TRUE"
| T_BREAK -> "T_BREAK"
| T_CASE -> "T_CASE"
| T_CATCH -> "T_CATCH"
| T_CONTINUE -> "T_CONTINUE"
| T_DEFAULT -> "T_DEFAULT"
| T_DO -> "T_DO"
| T_FINALLY -> "T_FINALLY"
| T_FOR -> "T_FOR"
| T_CLASS -> "T_CLASS"
| T_EXTENDS -> "T_EXTENDS"
| T_STATIC -> "T_STATIC"
| T_ELSE -> "T_ELSE"
| T_NEW -> "T_NEW"
| T_DELETE -> "T_DELETE"
| T_TYPEOF -> "T_TYPEOF"
| T_VOID -> "T_VOID"
| T_ENUM -> "T_ENUM"
| T_EXPORT -> "T_EXPORT"
| T_IMPORT -> "T_IMPORT"
| T_SUPER -> "T_SUPER"
| T_IMPLEMENTS -> "T_IMPLEMENTS"
| T_INTERFACE -> "T_INTERFACE"
| T_PACKAGE -> "T_PACKAGE"
| T_PRIVATE -> "T_PRIVATE"
| T_PROTECTED -> "T_PROTECTED"
| T_PUBLIC -> "T_PUBLIC"
| T_YIELD -> "T_YIELD"
| T_DEBUGGER -> "T_DEBUGGER"
| T_DECLARE -> "T_DECLARE"
| T_TYPE -> "T_TYPE"
| T_OF -> "T_OF"
| T_ASYNC -> "T_ASYNC"
| T_AWAIT -> "T_AWAIT"
| T_CHECKS -> "T_CHECKS"
| T_LCURLY -> "T_LCURLY"
| T_RCURLY -> "T_RCURLY"
| T_LCURLYBAR -> "T_LCURLYBAR"
| T_RCURLYBAR -> "T_RCURLYBAR"
| T_LPAREN -> "T_LPAREN"
| T_RPAREN -> "T_RPAREN"
| T_LBRACKET -> "T_LBRACKET"
| T_RBRACKET -> "T_RBRACKET"
| T_SEMICOLON -> "T_SEMICOLON"
| T_COMMA -> "T_COMMA"
| T_PERIOD -> "T_PERIOD"
| T_ARROW -> "T_ARROW"
| T_ELLIPSIS -> "T_ELLIPSIS"
| T_AT -> "T_AT"
| T_RSHIFT3_ASSIGN -> "T_RSHIFT3_ASSIGN"
| T_RSHIFT_ASSIGN -> "T_RSHIFT_ASSIGN"
| T_LSHIFT_ASSIGN -> "T_LSHIFT_ASSIGN"
| T_BIT_XOR_ASSIGN -> "T_BIT_XOR_ASSIGN"
| T_BIT_OR_ASSIGN -> "T_BIT_OR_ASSIGN"
| T_BIT_AND_ASSIGN -> "T_BIT_AND_ASSIGN"
| T_MOD_ASSIGN -> "T_MOD_ASSIGN"
| T_DIV_ASSIGN -> "T_DIV_ASSIGN"
| T_MULT_ASSIGN -> "T_MULT_ASSIGN"
| T_EXP_ASSIGN -> "T_EXP_ASSIGN"
| T_MINUS_ASSIGN -> "T_MINUS_ASSIGN"
| T_PLUS_ASSIGN -> "T_PLUS_ASSIGN"
| T_ASSIGN -> "T_ASSIGN"
| T_PLING -> "T_PLING"
| T_COLON -> "T_COLON"
| T_OR -> "T_OR"
| T_AND -> "T_AND"
| T_BIT_OR -> "T_BIT_OR"
| T_BIT_XOR -> "T_BIT_XOR"
| T_BIT_AND -> "T_BIT_AND"
| T_EQUAL -> "T_EQUAL"
| T_NOT_EQUAL -> "T_NOT_EQUAL"
| T_STRICT_EQUAL -> "T_STRICT_EQUAL"
| T_STRICT_NOT_EQUAL -> "T_STRICT_NOT_EQUAL"
| T_LESS_THAN_EQUAL -> "T_LESS_THAN_EQUAL"
| T_GREATER_THAN_EQUAL -> "T_GREATER_THAN_EQUAL"
| T_LESS_THAN -> "T_LESS_THAN"
| T_GREATER_THAN -> "T_GREATER_THAN"
| T_LSHIFT -> "T_LSHIFT"
| T_RSHIFT -> "T_RSHIFT"
| T_RSHIFT3 -> "T_RSHIFT3"
| T_PLUS -> "T_PLUS"
| T_MINUS -> "T_MINUS"
| T_DIV -> "T_DIV"
| T_MULT -> "T_MULT"
| T_EXP -> "T_EXP"
| T_MOD -> "T_MOD"
| T_NOT -> "T_NOT"
| T_BIT_NOT -> "T_BIT_NOT"
| T_INCR -> "T_INCR"
| T_DECR -> "T_DECR"
(* Extra tokens *)
| T_ERROR -> "T_ERROR"
| T_EOF -> "T_EOF"
| T_JSX_IDENTIFIER -> "T_JSX_IDENTIFIER"
| T_JSX_TEXT _ -> "T_JSX_TEXT"
(* Type primitives *)
| T_ANY_TYPE -> "T_ANY_TYPE"
| T_MIXED_TYPE -> "T_MIXED_TYPE"
| T_EMPTY_TYPE -> "T_EMPTY_TYPE"
| T_BOOLEAN_TYPE -> "T_BOOLEAN_TYPE"
| T_NUMBER_TYPE -> "T_NUMBER_TYPE"
| T_NUMBER_SINGLETON_TYPE _ -> "T_NUMBER_SINGLETON_TYPE"
| T_STRING_TYPE -> "T_STRING_TYPE"
| T_VOID_TYPE -> "T_VOID_TYPE"
end
open Token
(*****************************************************************************)
(* Backtracking. *)
(*****************************************************************************)
let yyback n lexbuf =
Lexing.(
lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - n;
let currp = lexbuf.lex_curr_p in
lexbuf.lex_curr_p <-
{ currp with pos_cnum = currp.pos_cnum - n }
)
let back lb =
let n = Lexing.lexeme_end lb - Lexing.lexeme_start lb in
yyback n lb
(*****************************************************************************)
(* Environment *)
(*****************************************************************************)
let debug_string_of_lexing_position position =
Printf.sprintf
"{pos_fname=%S; pos_lnum=%d; pos_bol=%d; pos_cnum=%d}"
position.Lexing.pos_fname
position.Lexing.pos_lnum
position.Lexing.pos_bol
position.Lexing.pos_cnum
let debug_string_of_lexbuf (lb: Lexing.lexbuf) =
Printf.sprintf
"{ \
lex_buffer = %S; \
lex_buffer_len = %d; \
lex_abs_pos = %d; \
lex_start_pos = %d; \
lex_curr_pos = %d; \
lex_last_pos = %d; \
lex_last_action = %d; \
lex_eof_reached = %b; \
lex_mem = TODO; \
lex_start_p = %s; \
lex_curr_p = %s; \
}"
lb.Lexing.lex_buffer
lb.Lexing.lex_buffer_len
lb.Lexing.lex_abs_pos
lb.Lexing.lex_start_pos
lb.Lexing.lex_curr_pos
lb.Lexing.lex_last_pos
lb.Lexing.lex_last_action
lb.Lexing.lex_eof_reached
(debug_string_of_lexing_position lb.Lexing.lex_start_p)
(debug_string_of_lexing_position lb.Lexing.lex_curr_p)
module Lex_env = struct
type t = {
lex_source : Loc.filename option;
lex_lb : Lexing.lexbuf;
lex_in_comment_syntax : bool;
lex_enable_comment_syntax: bool;
lex_state : lex_state;
}
and lex_state = {
lex_errors_acc: (Loc.t * Parse_error.t) list;
lex_comments_acc: Ast.Comment.t list;
}
let empty_lex_state = {
lex_errors_acc = [];
lex_comments_acc = [];
}
let new_lex_env lex_source lex_lb ~enable_types_in_comments = {
lex_source;
lex_lb;
lex_in_comment_syntax = false;
lex_enable_comment_syntax = enable_types_in_comments;
lex_state = empty_lex_state;
}
let get_and_clear_state env =
let state = env.lex_state in
let env = if state != empty_lex_state
then { env with lex_state = empty_lex_state }
else env
in
env, state
let lexbuf env = env.lex_lb
let with_lexbuf ~lexbuf env = { env with lex_lb = lexbuf }
let source env = env.lex_source
let state env = env.lex_state
let is_in_comment_syntax env = env.lex_in_comment_syntax
let is_comment_syntax_enabled env = env.lex_enable_comment_syntax
let in_comment_syntax is_in env =
if is_in <> env.lex_in_comment_syntax
then { env with lex_in_comment_syntax = is_in }
else env
let debug_string_of_lex_env (env: t) =
let source = match (source env) with
| None -> "None"
| Some x -> Printf.sprintf "Some %S" (Loc.string_of_filename x)
in
Printf.sprintf
"{\n \
lex_source = %s\n \
lex_lb = %s\n \
lex_in_comment_syntax = %b\n \
lex_enable_comment_syntax = %b\n \
lex_state = {errors = (count = %d); comments = (count = %d)}\n\
}"
source
(debug_string_of_lexbuf env.lex_lb)
(is_in_comment_syntax env)
(is_comment_syntax_enabled env)
(List.length (state env).lex_errors_acc)
(List.length (state env).lex_comments_acc)
end
open Lex_env
module Lex_result = struct
type t = {
lex_token: Token.t;
lex_loc: Loc.t;
lex_value: string;
lex_errors: (Loc.t * Parse_error.t) list;
lex_comments: Ast.Comment.t list;
}
let token result = result.lex_token
let loc result = result.lex_loc
let value result = result.lex_value
let comments result = result.lex_comments
let errors result = result.lex_errors
let debug_string_of_lex_result lex_result =
Printf.sprintf
"{\n \
lex_token = %s\n \
lex_value = %S\n \
lex_errors = (length = %d)\n \
lex_comments = (length = %d)\n\
}"
(token_to_string lex_result.lex_token)
lex_result.lex_value
(List.length lex_result.lex_errors)
(List.length lex_result.lex_comments)
end
let loc_of_lexbuf env lexbuf = Loc.from_lb (source env) lexbuf
let get_result_and_clear_state (env, lex_token) =
let env, state = get_and_clear_state env in
let (lex_loc, lex_value) = match lex_token with
| T_STRING (loc, _, raw, _) ->
loc, raw
| T_JSX_TEXT (loc, _, raw) -> loc, raw
| T_TEMPLATE_PART (loc, {literal; _}, _) ->
loc, literal
| T_REGEXP (loc, pattern, flags) -> loc, "/" ^ pattern ^ "/" ^ flags
| _ -> loc_of_lexbuf env env.lex_lb, Lexing.lexeme env.lex_lb in
env, {
Lex_result.lex_token;
lex_loc;
lex_value;
lex_errors = List.rev state.lex_errors_acc;
lex_comments = List.rev state.lex_comments_acc;
}
let lex_error (env: Lex_env.t) loc err: Lex_env.t =
let lex_errors_acc = (loc, err)::env.lex_state.lex_errors_acc in
{ env with lex_state = { env.lex_state with lex_errors_acc; } }
let unexpected_error env loc value =
lex_error env loc (Parse_error.UnexpectedToken value)
let unexpected_error_w_suggest (env: Lex_env.t) (loc: Loc.t) value suggest =
lex_error env loc (Parse_error.UnexpectedTokenWithSuggestion (value, suggest))
let illegal (env: Lex_env.t) (loc: Loc.t) =
lex_error env loc (Parse_error.UnexpectedToken "ILLEGAL")
let illegal_number (env: Lex_env.t) lexbuf word token =
let loc = loc_of_lexbuf env lexbuf in
yyback (String.length word) lexbuf;
let env = illegal env loc in
env, token
module FloatOfString : sig
val float_of_string: string -> float
end = struct
type t = {
negative: bool;
mantissa: int;
exponent: int;
decimal_exponent: int option;
todo: char list;
}
exception No_good
let eat f =
match f.todo with
| _::todo -> { f with todo; }
| _ -> raise No_good
let start str =
let todo = ref [] in
String.iter (fun c -> todo := c::(!todo)) str;
{
negative = false;
mantissa = 0;
exponent = 0;
decimal_exponent = None;
todo = List.rev (!todo);
}
let parse_sign f =
match f.todo with
| '+'::_ -> eat f
| '-'::_ -> { (eat f) with negative = true; }
| _ -> f
let parse_hex_symbol f =
match f.todo with
| '0'::('x' | 'X')::_ -> f |> eat |> eat
| _ -> raise No_good
let parse_exponent f =
let todo_str = f.todo
|> List.map Char.escaped
|> String.concat "" in
let exponent =
try int_of_string todo_str
with Failure _ -> raise No_good in
{ f with exponent; todo = [] }
let rec parse_body f =
match f.todo with
| [] -> f
(* _ is just ignored *)
| '_'::_ -> parse_body (eat f)
| '.'::_ ->
if f.decimal_exponent = None
then parse_body { (eat f) with decimal_exponent = Some 0 }
else raise No_good
| ('p' | 'P')::_ ->
parse_exponent (eat f)
| c::_ ->
let ref_char_code =
if c >= '0' && c <= '9'
then Char.code '0'
else if c >= 'A' && c <= 'F'
then Char.code 'A' - 10
else if c >= 'a' && c <= 'f'
then Char.code 'a' - 10
else raise No_good in
let value = (Char.code c) - ref_char_code in
let decimal_exponent = match f.decimal_exponent with
| None -> None
| Some e -> Some (e - 4) in
let mantissa = (f.mantissa lsl 4) + value in
parse_body { (eat f) with decimal_exponent; mantissa; }
let float_of_t f =
assert (f.todo = []);
let ret = float_of_int f.mantissa in
let exponent = match f.decimal_exponent with
| None -> f.exponent
| Some decimal_exponent -> f.exponent + decimal_exponent in
let ret =
if exponent = 0
then ret
else ret ** (float_of_int exponent) in
if f.negative
then -.ret
else ret
let float_of_string str =
try Pervasives.float_of_string str
with e when Sys.win32 ->
try
start str
|> parse_sign
|> parse_hex_symbol
|> parse_body
|> float_of_t
with No_good -> raise e
end
let save_comment
(env: Lex_env.t)
(start: Loc.t) (_end: Loc.t)
(buf: Buffer.t)
(multiline: bool)
: Lex_env.t = Ast.Comment.(
let loc = Loc.btwn start _end in
let s = Buffer.contents buf in
let c = if multiline then Block s else Line s in
let lex_comments_acc = (loc, c) :: env.lex_state.lex_comments_acc in
{ env with lex_state = { env.lex_state with lex_comments_acc; } }
)
let unicode_fix_cols lb =
let rec count start stop acc =
if start = stop then acc
else
let c = Char.code (lb.Lexing.lex_buffer.[start]) in
let acc = if (c land 0xC0) = 0x80
then acc + 1
else acc in
count (start+1) stop acc
in
Lexing.(
let bytes = count lb.lex_start_pos lb.lex_curr_pos 0 in
let new_bol = lb.lex_curr_p.pos_bol + bytes in
lb.lex_curr_p <- {
lb.lex_curr_p with pos_bol = new_bol;
}
)
let oct_to_int = function
| '0'..'7' as x -> Char.code x - Char.code '0'
| _ -> assert false
let hexa_to_int = function
| '0'..'9' as x -> Char.code x - Char.code '0'
| 'a'..'f' as x -> Char.code x - Char.code 'a' + 10
| 'A'..'F' as x -> Char.code x - Char.code 'A' + 10
| _ -> assert false
let utf16to8 code =
if code >= 0x10000
then
(* 4 bytes *)
[
Char.chr (0xf0 lor (code lsr 18));
Char.chr (0x80 lor ((code lsr 12) land 0x3f));
Char.chr (0x80 lor ((code lsr 6) land 0x3f));
Char.chr (0x80 lor (code land 0x3f));
]
else if code >= 0x800
then
(* 3 bytes *)
[
Char.chr (0xe0 lor (code lsr 12));
Char.chr (0x80 lor ((code lsr 6) land 0x3f));
Char.chr (0x80 lor (code land 0x3f));
]
else if code >= 0x80
then
(* 2 bytes *)
[
Char.chr (0xc0 lor (code lsr 6));
Char.chr (0x80 lor (code land 0x3f));
]
else
(* 1 byte *)
[
Char.chr code;
]
let mk_num_singleton number_type num neg =
(* convert singleton number type into a float *)
let value = match number_type with
| LEGACY_OCTAL ->
float (int_of_string ("0o"^num))
| BINARY
| OCTAL ->
float (int_of_string num)
| NORMAL ->
FloatOfString.float_of_string num
in
let value = if neg = "" then value else ~-.value in
T_NUMBER_SINGLETON_TYPE (number_type, value)
type jsx_text_mode =
| JSX_SINGLE_QUOTED_TEXT
| JSX_DOUBLE_QUOTED_TEXT
| JSX_CHILD_TEXT
let keywords = Hashtbl.create 53
let type_keywords = Hashtbl.create 53
let _ = List.iter (fun (key, token) -> Hashtbl.add keywords key token)
[
"function", T_FUNCTION;
"if", T_IF;
"in", T_IN;
"instanceof", T_INSTANCEOF;
"return", T_RETURN;
"switch", T_SWITCH;
"this", T_THIS;
"throw", T_THROW;
"try", T_TRY;
"var", T_VAR;
"while", T_WHILE;
"with", T_WITH;
"const", T_CONST;
"let", T_LET ;
"null", T_NULL;
"false", T_FALSE;
"true", T_TRUE;
"break", T_BREAK;
"case", T_CASE;
"catch", T_CATCH;
"continue", T_CONTINUE;
"default", T_DEFAULT;
"do", T_DO;
"finally", T_FINALLY;
"for", T_FOR;
"class", T_CLASS;
"extends", T_EXTENDS;
"static", T_STATIC;
"else", T_ELSE;
"new", T_NEW;
"delete", T_DELETE;
"typeof", T_TYPEOF;
"void", T_VOID;
"enum", T_ENUM;
"export", T_EXPORT ;
"import", T_IMPORT;
"super", T_SUPER ;
"implements", T_IMPLEMENTS;
"interface", T_INTERFACE;
"package", T_PACKAGE;
"private", T_PRIVATE;
"protected", T_PROTECTED;
"public", T_PUBLIC;
"yield", T_YIELD;
"debugger", T_DEBUGGER;
"declare", T_DECLARE;
"type", T_TYPE;
"of", T_OF;
"async", T_ASYNC;
"await", T_AWAIT;
]
let _ = List.iter (fun (key, token) -> Hashtbl.add type_keywords key token)
[
"static", T_STATIC;
"typeof", T_TYPEOF;
"any", T_ANY_TYPE;
"mixed", T_MIXED_TYPE;
"empty", T_EMPTY_TYPE;
"bool", T_BOOLEAN_TYPE;
"boolean", T_BOOLEAN_TYPE;
"true", T_TRUE;
"false", T_FALSE;
"number", T_NUMBER_TYPE;
"string", T_STRING_TYPE;
"void", T_VOID_TYPE;
"null", T_NULL;
]
}
let hex = ['0'-'9''a'-'f''A'-'F']
let unicode_whitespace =
('\xE1''\x9A''\x80')|('\xE1''\xA0''\x8E')|('\xE2''\x80''\x80')|
('\xE2''\x80''\x81')|('\xE2''\x80''\x82')|('\xE2''\x80''\x83')|
('\xE2''\x80''\x84')|('\xE2''\x80''\x85')|('\xE2''\x80''\x86')|
('\xE2''\x80''\x87')|('\xE2''\x80''\x88')|('\xE2''\x80''\x89')|
('\xE2''\x80''\x8A')|('\xE2''\x80''\xAF')|('\xE2''\x81''\x9F')|
('\xE3''\x80''\x80')|('\xEF''\xBB''\xBF')
let whitespace = [' ' '\t' '\r' '\x0c'] | unicode_whitespace
(* Different ways you can write a number *)
let binnumber = '0' ['B''b'] ['0''1']+
let hexnumber = '0' ['X''x'] hex+
let octnumber = '0' ['O''o'] ['0'-'7']+
let legacyoctnumber = '0' ['0'-'7']+
let scinumber = ['0'-'9']*'.'?['0'-'9']+['e''E']['-''+']?['0'-'9']+
let wholenumber = ['0'-'9']+'.'?
let floatnumber = ['0'-'9']*'.'['0'-'9']+
let digit = ['0'-'9']
let non_ascii_unicode =
['\xC2'-'\xDF']['\x80'-'\xBF']|('\xE0'['\xA0'-'\xBF']|['\xE1'-'\xEF']['\x80'-'\xBF'])['\x80'-'\xBF']
let explicit_unicode =
'\\'('u'['0'-'9']['0'-'9']['0'-'9']['0'-'9']|'x'['0'-'9']['0'-'9'])
(* these definitions include unicode in legal id and hex literal chars. *)
(* let letter = ['a'-'z''A'-'Z''_''$'] | non_ascii_unicode | explicit_unicode *)
(* let non_hex_letter = ['g'-'z''G'-'Z''_''$'] | non_ascii_unicode | explicit_unicode *)
(* we only allow unicode in string literals *)
let letter = ['a'-'z''A'-'Z''_''$']
let non_hex_letter = ['g'-'z''G'-'Z''_''$']
let alphanumeric = digit | letter
let word = letter alphanumeric*
let line_terminator = '\n'|'\r'
let line_terminator_sequence = line_terminator | "\r\n"
let single_escape_character = ['\'''"''\\''b''f''n''r''t''v']
(* 2-8 alphanumeric characters. I could match them directly, but this leads to
* ~5k more lines of generated lexer
let htmlentity = "quot" | "amp" | "apos" | "lt" | "gt" | "nbsp" | "iexcl" | "cent" | "pound" | "curren" | "yen" | "brvbar" | "sect" | "uml" | "copy" | "ordf" | "laquo" | "not" | "shy" | "reg" | "macr" | "deg" | "plusmn" | "sup2" | "sup3" | "acute" | "micro" | "para" | "middot" | "cedil" | "sup1" | "ordm" | "raquo" | "frac14" | "frac12" | "frac34" | "iquest" | "Agrave" | "Aacute" | "Acirc" | "Atilde" | "Auml" | "Aring" | "AElig" | "Ccedil" | "Egrave" | "Eacute" | "Ecirc" | "Euml" | "Igrave" | "Iacute" | "Icirc" | "Iuml" | "ETH" | "Ntilde" | "Ograve" | "Oacute" | "Ocirc" | "Otilde" | "Ouml" | "times" | "Oslash" | "Ugrave" | "Uacute" | "Ucirc" | "Uuml" | "Yacute" | "THORN" | "szlig" | "agrave" | "aacute" | "acirc" | "atilde" | "auml" | "aring" | "aelig" | "ccedil" | "egrave" | "eacute" | "ecirc" | "euml" | "igrave" | "iacute" | "icirc" | "iuml" | "eth" | "ntilde" | "ograve" | "oacute" | "ocirc" | "otilde" | "ouml" | "divide" | "oslash" | "ugrave" | "uacute" | "ucirc" | "uuml" | "yacute" | "thorn" | "yuml" | "OElig" | "oelig" | "Scaron" | "scaron" | "Yuml" | "fnof" | "circ" | "tilde" | "Alpha" | "Beta" | "Gamma" | "Delta" | "Epsilon" | "Zeta" | "Eta" | "Theta" | "Iota" | "Kappa" | "Lambda" | "Mu" | "Nu" | "Xi" | "Omicron" | "Pi" | "Rho" | "Sigma" | "Tau" | "Upsilon" | "Phi" | "Chi" | "Psi" | "Omega" | "alpha" | "beta" | "gamma" | "delta" | "epsilon" | "zeta" | "eta" | "theta" | "iota" | "kappa" | "lambda" | "mu" | "nu" | "xi" | "omicron" | "pi" | "rho" | "sigmaf" | "sigma" | "tau" | "upsilon" | "phi" | "chi" | "psi" | "omega" | "thetasym" | "upsih" | "piv" | "ensp" | "emsp" | "thinsp" | "zwnj" | "zwj" | "lrm" | "rlm" | "ndash" | "mdash" | "lsquo" | "rsquo" | "sbquo" | "ldquo" | "rdquo" | "bdquo" | "dagger" | "Dagger" | "bull" | "hellip" | "permil" | "prime" | "Prime" | "lsaquo" | "rsaquo" | "oline" | "frasl" | "euro" | "image" | "weierp" | "real" | "trade" | "alefsym" | "larr" | "uarr" | "rarr" | "darr" | "harr" | "crarr" | "lArr" | "uArr" | "rArr" | "dArr" | "hArr" | "forall" | "part" | "exist" | "empty" | "nabla" | "isin" | "notin" | "ni" | "prod" | "sum" | "minus" | "lowast" | "radic" | "prop" | "infin" | "ang" | "and" | "or" | "cap" | "cup" | "'int'" | "there4" | "sim" | "cong" | "asymp" | "ne" | "equiv" | "le" | "ge" | "sub" | "sup" | "nsub" | "sube" | "supe" | "oplus" | "otimes" | "perp" | "sdot" | "lceil" | "rceil" | "lfloor" | "rfloor" | "lang" | "rang" | "loz" | "spades" | "clubs" | "hearts" | "diams"
*)
let htmlentity = alphanumeric alphanumeric alphanumeric? alphanumeric? alphanumeric? alphanumeric? alphanumeric? alphanumeric?
(* minus sign in front of negative numbers
(only for types! regular numbers use T_MINUS!) *)
let neg = '-' whitespace*
rule token env = parse
(* Ignored *)
| '\n' {
Lexing.new_line lexbuf;
token env lexbuf
}
| '\\' { let env = illegal env (loc_of_lexbuf env lexbuf) in
token env lexbuf }
| whitespace+ {
unicode_fix_cols lexbuf;
token env lexbuf }
| "/*" {
let start = loc_of_lexbuf env lexbuf in
let buf = Buffer.create 127 in
let env, _end = comment env buf lexbuf in
let env = save_comment env start _end buf true in
token env lexbuf
}
| "/*" (whitespace* as sp) (":" | "::" | "flow-include" as escape_type) as pattern
{
if not (is_comment_syntax_enabled env) then
let start = loc_of_lexbuf env lexbuf in
let buf = Buffer.create 127 in
Buffer.add_string buf sp;
Buffer.add_string buf escape_type;
let env, _end = comment env buf lexbuf in
let env = save_comment env start _end buf true in
token env lexbuf
else
let env =
if is_in_comment_syntax env then
let loc = loc_of_lexbuf env lexbuf in
unexpected_error env loc pattern
else env
in
let env = in_comment_syntax true env in
match escape_type with
| ":" -> env, T_COLON
| _ -> token env lexbuf
}
| "*/" {
if is_in_comment_syntax env then
let env = in_comment_syntax false env in
token env lexbuf
else
let () = yyback 1 lexbuf in
env, T_MULT
}
| "//" {
let start = loc_of_lexbuf env lexbuf in
let buf = Buffer.create 127 in
let env, _end = line_comment env buf lexbuf in
let env = save_comment env start _end buf false in
token env lexbuf
}
(* Support for the shebang at the beginning of a file. It is treated like a
* comment at the beginning or an error elsewhere *)
| "#!" { if lexbuf.Lexing.lex_start_pos = 0
then begin
let env, _ =
line_comment env (Buffer.create 127) lexbuf in
token env lexbuf
end else env, T_ERROR
}
(* Values *)
| ("'"|'"') as quote {
let start = loc_of_lexbuf env lexbuf in
let buf = Buffer.create 127 in
let raw = Buffer.create 127 in
Buffer.add_char raw quote;
let octal = false in
let env, _end, octal =
string_quote env quote buf raw octal lexbuf in
env, T_STRING (Loc.btwn start _end, Buffer.contents buf, Buffer.contents raw, octal)
}
| '`' { let cooked = Buffer.create 127 in
let raw = Buffer.create 127 in
let literal = Buffer.create 127 in
Buffer.add_string literal (Lexing.lexeme lexbuf);
let start = loc_of_lexbuf env lexbuf in
let env, loc, is_tail =
template_part env start cooked raw literal lexbuf in
env, T_TEMPLATE_PART (
loc,
{
cooked = Buffer.contents cooked;
raw = Buffer.contents raw;
literal = Buffer.contents literal;
},
is_tail
)
}
(* Numbers cannot be immediately followed by words *)
| binnumber ((letter | ['2'-'9']) alphanumeric* as w)
{ illegal_number env lexbuf w (T_NUMBER BINARY) }
| binnumber { env, T_NUMBER BINARY }
| octnumber ((letter | ['8'-'9']) alphanumeric* as w)
{ illegal_number env lexbuf w (T_NUMBER OCTAL) }
| octnumber { env, T_NUMBER OCTAL }
| legacyoctnumber ((letter | ['8'-'9']) alphanumeric* as w)
{ illegal_number env lexbuf w (T_NUMBER LEGACY_OCTAL) }
| legacyoctnumber { env, T_NUMBER LEGACY_OCTAL }
| hexnumber (non_hex_letter alphanumeric* as w)
{ illegal_number env lexbuf w (T_NUMBER NORMAL) }
| hexnumber { env, T_NUMBER NORMAL }
| scinumber (word as w)
{ illegal_number env lexbuf w (T_NUMBER NORMAL) }
| scinumber { env, T_NUMBER NORMAL }
| (wholenumber | floatnumber) (word as w)
{ illegal_number env lexbuf w (T_NUMBER NORMAL) }
| wholenumber
| floatnumber { env, T_NUMBER NORMAL }
(* Keyword or Identifier *)
(* TODO: Use [Symbol.iterator] instead of @@iterator. *)
| ("@@"? word) as word
{
unicode_fix_cols lexbuf;
try env, Hashtbl.find keywords word
with Not_found -> env, T_IDENTIFIER
}
(* Syntax *)
| "{" { env, T_LCURLY }
| "}" { env, T_RCURLY }
| "(" { env, T_LPAREN }
| ")" { env, T_RPAREN }
| "[" { env, T_LBRACKET }
| "]" { env, T_RBRACKET }
| "..." { env, T_ELLIPSIS }
| "." { env, T_PERIOD }
| ";" { env, T_SEMICOLON }
| "," { env, T_COMMA }
| ":" { env, T_COLON }
| "?" { env, T_PLING }
| "&&" { env, T_AND }
| "||" { env, T_OR }
| "===" { env, T_STRICT_EQUAL }
| "!==" { env, T_STRICT_NOT_EQUAL }
| "<=" { env, T_LESS_THAN_EQUAL }
| ">=" { env, T_GREATER_THAN_EQUAL }
| "==" { env, T_EQUAL }
| "!=" { env, T_NOT_EQUAL }
| "++" { env, T_INCR }
| "--" { env, T_DECR }
| "<<=" { env, T_LSHIFT_ASSIGN }
| "<<" { env, T_LSHIFT }
| ">>=" { env, T_RSHIFT_ASSIGN }
| ">>>=" { env, T_RSHIFT3_ASSIGN }
| ">>>" { env, T_RSHIFT3 }
| ">>" { env, T_RSHIFT }
| "+=" { env, T_PLUS_ASSIGN }
| "-=" { env, T_MINUS_ASSIGN }
| "*=" { env, T_MULT_ASSIGN }
| "**=" { env, T_EXP_ASSIGN }
| "%=" { env, T_MOD_ASSIGN }
| "&=" { env, T_BIT_AND_ASSIGN }
| "|=" { env, T_BIT_OR_ASSIGN }
| "^=" { env, T_BIT_XOR_ASSIGN }
| "<" { env, T_LESS_THAN }
| ">" { env, T_GREATER_THAN }
| "+" { env, T_PLUS }
| "-" { env, T_MINUS }
| "*" { env, T_MULT }
| "**" { env, T_EXP }
| "%" { env, T_MOD }
| "|" { env, T_BIT_OR }
| "&" { env, T_BIT_AND }
| "^" { env, T_BIT_XOR }
| "!" { env, T_NOT }
| "~" { env, T_BIT_NOT }
| "=" { env, T_ASSIGN }
| "=>" { env, T_ARROW }
| "/=" { env, T_DIV_ASSIGN }
| "/" { env, T_DIV }
| "@" { env, T_AT }
(* Others *)
| eof { let env =
if is_in_comment_syntax env then
let loc = loc_of_lexbuf env lexbuf in
lex_error env loc Parse_error.UnexpectedEOS
else env
in
env, T_EOF }
| _ { let env = illegal env (loc_of_lexbuf env lexbuf) in
env, T_ERROR }
(* There are some tokens that never show up in a type and which can cause
* ambiguity. For example, Foo<Bar<number>> ends with two angle brackets, not
* with a right shift.
*)
and type_token env = parse
(* Ignored *)
| '\n' {
Lexing.new_line lexbuf;
type_token env lexbuf
}
| whitespace+ {
unicode_fix_cols lexbuf;
type_token env lexbuf }
| "/*" { let start = loc_of_lexbuf env lexbuf in
let buf = Buffer.create 127 in
let env, _end = comment env buf lexbuf in
let env = save_comment env start _end buf true in
type_token env lexbuf