forked from ManasJayanth/flow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathestree_translator.ml
1488 lines (1370 loc) · 47 KB
/
estree_translator.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) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module type Config = sig
val include_locs: bool
val include_comments: bool
end
module Translate (Impl : Translator_intf.S) (Config : Config) : (sig
type t
val program:
Loc.t * Loc.t Ast.Statement.t list * (Loc.t * Ast.Comment.t') list ->
t
val expression: Loc.t Ast.Expression.t -> t
val errors: (Loc.t * Parse_error.t) list -> t
end with type t = Impl.t) = struct
type t = Impl.t
open Ast
open Impl
let array_of_list fn list = array (List.map fn list)
let int x = number (float x)
let option f = function
| Some v -> f v
| None -> null
let position p =
obj [
"line", int p.Loc.line;
"column", int p.Loc.column;
]
let loc location =
let source = match Loc.source location with
| Some File_key.LibFile src
| Some File_key.SourceFile src
| Some File_key.JsonFile src
| Some File_key.ResourceFile src -> string src
| Some File_key.Builtins -> string "(global)"
| None -> null
in
obj [
"source", source;
"start", position location.Loc.start;
"end", position location.Loc._end;
]
let range location = Loc.(
array [
int location.start.offset;
int location._end.offset;
]
)
let node _type location props =
let prefix =
if Config.include_locs then
(* sorted backwards due to the rev_append below *)
[ "range", range location;
"loc", loc location;
"type", string _type; ]
else
[ "type", string _type; ]
in
obj (List.rev_append prefix props)
let errors l =
let error (location, e) =
obj [
"loc", loc location;
"message", string (Parse_error.PP.error e);
]
in array_of_list error l
let rec program (loc, statements, comments) =
let body = statement_list statements in
let props =
if Config.include_comments then [ "body", body; "comments", comment_list comments; ]
else [ "body", body; ]
in
node "Program" loc props
and statement_list statements = array_of_list statement statements
and statement = Statement.(function
| loc, Empty -> node "EmptyStatement" loc []
| loc, Block b -> block (loc, b)
| loc, Expression expr ->
node "ExpressionStatement" loc [
"expression", expression expr.Expression.expression;
"directive", option string expr.Expression.directive;
]
| loc, If _if -> If.(
node "IfStatement" loc [
"test", expression _if.test;
"consequent", statement _if.consequent;
"alternate", option statement _if.alternate;
]
)
| loc, Labeled labeled -> Labeled.(
node "LabeledStatement" loc [
"label", identifier labeled.label;
"body", statement labeled.body;
]
)
| loc, Break break ->
node "BreakStatement" loc [
"label", option identifier break.Break.label;
]
| loc, Continue continue ->
node "ContinueStatement" loc [
"label", option identifier continue.Continue.label;
]
| loc, With _with -> With.(
node "WithStatement" loc [
"object", expression _with._object;
"body", statement _with.body;
]
)
| loc, TypeAlias alias -> type_alias (loc, alias)
| loc, OpaqueType opaque_t -> opaque_type ~declare:false (loc, opaque_t)
| loc, Switch switch -> Switch.(
node "SwitchStatement" loc [
"discriminant", expression switch.discriminant;
"cases", array_of_list case switch.cases;
]
)
| loc, Return return ->
node "ReturnStatement" loc [
"argument", option expression return.Return.argument;
]
| loc, Throw throw ->
node "ThrowStatement" loc [
"argument", expression throw.Throw.argument;
]
| loc, Try _try -> Try.(
node "TryStatement" loc [
"block", block _try.block;
"handler", option catch _try.handler;
"finalizer", option block _try.finalizer;
]
)
| loc, While _while -> While.(
node "WhileStatement" loc [
"test", expression _while.test;
"body", statement _while.body;
]
)
| loc, DoWhile dowhile -> DoWhile.(
node "DoWhileStatement" loc [
"body", statement dowhile.body;
"test", expression dowhile.test;
]
)
| loc, For _for -> For.(
let init = function
| InitDeclaration init -> variable_declaration init
| InitExpression expr -> expression expr
in
node "ForStatement" loc [
"init", option init _for.init;
"test", option expression _for.test;
"update", option expression _for.update;
"body", statement _for.body;
]
)
| loc, ForIn forin -> ForIn.(
let left = match forin.left with
| LeftDeclaration left -> variable_declaration left
| LeftPattern left -> pattern left
in
node "ForInStatement" loc [
"left", left;
"right", expression forin.right;
"body", statement forin.body;
"each", bool forin.each;
]
)
| loc, ForOf forof -> ForOf.(
let type_ =
if forof.async
then "ForAwaitStatement"
else "ForOfStatement"
in
let left = match forof.left with
| LeftDeclaration left -> variable_declaration left
| LeftPattern left -> pattern left
in
node type_ loc [
"left", left;
"right", expression forof.right;
"body", statement forof.body;
]
)
| loc, Debugger -> node "DebuggerStatement" loc []
| loc, ClassDeclaration c -> class_declaration (loc, c)
| loc, InterfaceDeclaration i -> interface_declaration (loc, i)
| loc, VariableDeclaration var -> variable_declaration (loc, var)
| loc, FunctionDeclaration fn -> function_declaration (loc, fn)
| loc, DeclareVariable d -> declare_variable (loc, d)
| loc, DeclareFunction d -> declare_function (loc, d)
| loc, DeclareClass d -> declare_class (loc, d)
| loc, DeclareInterface i -> declare_interface (loc, i)
| loc, DeclareTypeAlias a -> declare_type_alias (loc, a)
| loc, DeclareOpaqueType t -> opaque_type ~declare:true (loc, t)
| loc, DeclareModule m -> DeclareModule.(
let id = match m.id with
| Literal lit -> string_literal lit
| Identifier id -> identifier id
in
node "DeclareModule" loc [
"id", id;
"body", block m.body;
"kind", (
match m.kind with
| DeclareModule.CommonJS _ -> string "CommonJS"
| DeclareModule.ES _ -> string "ES"
)
]
)
| loc, DeclareExportDeclaration export -> DeclareExportDeclaration.(
match export.specifiers with
| Some (ExportNamedDeclaration.ExportBatchSpecifier (_, None)) ->
node "DeclareExportAllDeclaration" loc [
"source", option string_literal export.source;
]
| _ ->
let declaration = match export.declaration with
| Some (Variable v) -> declare_variable v
| Some (Function f) -> declare_function f
| Some (Class c) -> declare_class c
| Some (DefaultType t) -> _type t
| Some (NamedType t) -> type_alias t
| Some (NamedOpaqueType t) -> opaque_type ~declare:true t
| Some (Interface i) -> interface_declaration i
| None -> null
in
node "DeclareExportDeclaration" loc [
"default", bool (
match export.default with
| Some _ -> true
| None -> false);
"declaration", declaration;
"specifiers", export_specifiers export.specifiers;
"source", option string_literal export.source;
]
)
| loc, DeclareModuleExports annot ->
node "DeclareModuleExports" loc [
"typeAnnotation", type_annotation annot
]
| loc, ExportNamedDeclaration export -> ExportNamedDeclaration.(
match export.specifiers with
| Some (ExportBatchSpecifier (_, None)) ->
node "ExportAllDeclaration" loc [
"source", option string_literal export.source;
"exportKind", string (export_kind export.exportKind);
]
| _ ->
node "ExportNamedDeclaration" loc [
"declaration", option statement export.declaration;
"specifiers", export_specifiers export.specifiers;
"source", option string_literal export.source;
"exportKind", string (export_kind export.exportKind);
]
)
| loc, ExportDefaultDeclaration export -> ExportDefaultDeclaration.(
let declaration = match export.declaration with
| Declaration stmt -> statement stmt
| ExportDefaultDeclaration.Expression expr -> expression expr
in
node "ExportDefaultDeclaration" loc [
"declaration", declaration;
"exportKind", string (export_kind Statement.ExportValue);
]
)
| loc, ImportDeclaration import -> ImportDeclaration.(
let specifiers = match import.specifiers with
| Some (ImportNamedSpecifiers specifiers) ->
List.map (fun {local; remote; kind;} ->
import_named_specifier local remote kind
) specifiers
| Some (ImportNamespaceSpecifier id) ->
[import_namespace_specifier id]
| None ->
[]
in
let specifiers = match import.default with
| Some default -> (import_default_specifier default)::specifiers
| None -> specifiers
in
let import_kind = match import.importKind with
| ImportType -> "type"
| ImportTypeof -> "typeof"
| ImportValue -> "value"
in
node "ImportDeclaration" loc [
"specifiers", array specifiers;
"source", string_literal import.source;
"importKind", string (import_kind);
]
)
)
and expression = Expression.(function
| loc, This -> node "ThisExpression" loc []
| loc, Super -> node "Super" loc []
| loc, Array arr ->
node "ArrayExpression" loc [
"elements", array_of_list (option expression_or_spread) arr.Array.elements;
]
| loc, Object _object ->
node "ObjectExpression" loc [
"properties", array_of_list object_property _object.Object.properties;
]
| loc, Function _function -> function_expression (loc, _function)
| loc, ArrowFunction arrow -> Function.(
let body = (match arrow.body with
| BodyBlock b -> block b
| BodyExpression expr -> expression expr)
in
node "ArrowFunctionExpression" loc [
"id", option identifier arrow.id;
"params", function_params arrow.params;
"body", body;
"async", bool arrow.async;
"generator", bool arrow.generator;
"predicate", option predicate arrow.predicate;
"expression", bool arrow.expression;
"returnType", option type_annotation arrow.return;
"typeParameters", option type_parameter_declaration arrow.tparams;
]
)
| loc, Sequence sequence ->
node "SequenceExpression" loc [
"expressions", array_of_list expression sequence.Sequence.expressions;
]
| loc, Unary unary -> Unary.(
match unary.operator with
| Await ->
(* await is defined as a separate expression in ast-types
*
* TODO
* 1) Send a PR to ast-types
* (https://github.com/benjamn/ast-types/issues/113)
* 2) Output a UnaryExpression
* 3) Modify the esprima test runner to compare AwaitExpression and
* our UnaryExpression
* *)
node "AwaitExpression" loc [
"argument", expression unary.argument;
]
| _ -> begin
let operator = match unary.operator with
| Minus -> "-"
| Plus -> "+"
| Not -> "!"
| BitNot -> "~"
| Typeof -> "typeof"
| Void -> "void"
| Delete -> "delete"
| Await -> failwith "matched above"
in
node "UnaryExpression" loc [
"operator", string operator;
"prefix", bool unary.prefix;
"argument", expression unary.argument;
]
end
)
| loc, Binary binary -> Binary.(
let operator = match binary.operator with
| Equal -> "=="
| NotEqual -> "!="
| StrictEqual -> "==="
| StrictNotEqual -> "!=="
| LessThan -> "<"
| LessThanEqual -> "<="
| GreaterThan -> ">"
| GreaterThanEqual -> ">="
| LShift -> "<<"
| RShift -> ">>"
| RShift3 -> ">>>"
| Plus -> "+"
| Minus -> "-"
| Mult -> "*"
| Exp -> "**"
| Div -> "/"
| Mod -> "%"
| BitOr -> "|"
| Xor -> "^"
| BitAnd -> "&"
| In -> "in"
| Instanceof -> "instanceof"
in
node "BinaryExpression" loc [
"operator", string operator;
"left", expression binary.left;
"right", expression binary.right;
]
)
| loc, TypeCast typecast -> TypeCast.(
node "TypeCastExpression" loc [
"expression", expression typecast.expression;
"typeAnnotation", type_annotation typecast.annot;
]
)
| loc, Assignment assignment -> Assignment.(
let operator = match assignment.operator with
| Assign -> "="
| PlusAssign -> "+="
| MinusAssign -> "-="
| MultAssign -> "*="
| ExpAssign -> "**="
| DivAssign -> "/="
| ModAssign -> "%="
| LShiftAssign -> "<<="
| RShiftAssign -> ">>="
| RShift3Assign -> ">>>="
| BitOrAssign -> "|="
| BitXorAssign -> "^="
| BitAndAssign -> "&="
in
node "AssignmentExpression" loc [
"operator", string operator;
"left", pattern assignment.left;
"right", expression assignment.right;
]
)
| loc, Update update -> Update.(
let operator = match update.operator with
| Increment -> "++"
| Decrement -> "--"
in
node "UpdateExpression" loc [
"operator", string operator;
"argument", expression update.argument;
"prefix", bool update.prefix;
]
)
| loc, Logical logical -> Logical.(
let operator = match logical.operator with
| Or -> "||"
| And -> "&&"
| NullishCoalesce -> "??"
in
node "LogicalExpression" loc [
"operator", string operator;
"left", expression logical.left;
"right", expression logical.right;
]
)
| loc, Conditional conditional -> Conditional.(
node "ConditionalExpression" loc [
"test", expression conditional.test;
"consequent", expression conditional.consequent;
"alternate", expression conditional.alternate;
]
)
| loc, New _new -> New.(
node "NewExpression" loc [
"callee", expression _new.callee;
"typeArguments", option type_parameter_instantiation _new.targs;
"arguments", array_of_list expression_or_spread _new.arguments;
]
)
| loc, Call call ->
node "CallExpression" loc (call_node_properties call)
| loc, OptionalCall opt_call -> OptionalCall.(
node "OptionalCallExpression" loc (call_node_properties opt_call.call @ [
"optional", bool opt_call.optional;
])
)
| loc, Member member ->
node "MemberExpression" loc (member_node_properties member)
| loc, OptionalMember opt_member -> OptionalMember.(
node "OptionalMemberExpression" loc (member_node_properties opt_member.member @ [
"optional", bool opt_member.optional;
])
)
| loc, Yield yield -> Yield.(
node "YieldExpression" loc [
"argument", option expression yield.argument;
"delegate", bool yield.delegate;
]
)
| loc, Comprehension comp -> Comprehension.(
node "ComprehensionExpression" loc [
"blocks", array_of_list comprehension_block comp.blocks;
"filter", option expression comp.filter;
]
)
| loc, Generator gen -> Generator.(
node "GeneratorExpression" loc [
"blocks", array_of_list comprehension_block gen.blocks;
"filter", option expression gen.filter;
]
)
| _loc, Identifier id -> identifier id
| loc, Literal lit -> literal (loc, lit)
| loc, TemplateLiteral lit -> template_literal (loc, lit)
| loc, TaggedTemplate tagged -> tagged_template (loc, tagged)
| loc, Class c -> class_expression (loc, c)
| loc, JSXElement element -> jsx_element (loc, element)
| loc, JSXFragment fragment -> jsx_fragment (loc, fragment)
| loc, MetaProperty meta_prop -> MetaProperty.(
node "MetaProperty" loc [
"meta", identifier meta_prop.meta;
"property", identifier meta_prop.property;
]
)
| loc, Import arg -> node "CallExpression" loc [
"callee", node "Import" (Loc.btwn loc (fst arg)) [];
"arguments", array_of_list expression [arg];
]
)
and function_declaration (loc, fn) = Function.(
let body = match fn.body with
| BodyBlock b -> block b
| BodyExpression b -> expression b in
node "FunctionDeclaration" loc [
(* estree hasn't come around to the idea that function decls can have
optional ids, but acorn, babel, espree and esprima all have, so let's
do it too. see https://github.com/estree/estree/issues/98 *)
"id", option identifier fn.id;
"params", function_params fn.params;
"body", body;
"async", bool fn.async;
"generator", bool fn.generator;
"predicate", option predicate fn.predicate;
"expression", bool fn.expression;
"returnType", option type_annotation fn.return;
"typeParameters", option type_parameter_declaration fn.tparams;
]
)
and function_expression (loc, _function) = Function.(
let body = match _function.body with
| BodyBlock b -> block b
| BodyExpression expr -> expression expr
in
node "FunctionExpression" loc [
"id", option identifier _function.id;
"params", function_params _function.params;
"body", body;
"async", bool _function.async;
"generator", bool _function.generator;
"predicate", option predicate _function.predicate;
"expression", bool _function.expression;
"returnType", option type_annotation _function.return;
"typeParameters", option type_parameter_declaration _function.tparams;
]
)
and identifier (loc, name) =
node "Identifier" loc [
"name", string name;
"typeAnnotation", null;
"optional", bool false;
]
and private_name (loc, name) =
node "PrivateName" loc [
"id", identifier name;
]
and pattern_identifier loc {
Pattern.Identifier.name; annot; optional;
} =
node "Identifier" loc [
"name", string (snd name);
"typeAnnotation", option type_annotation annot;
"optional", bool optional;
]
and case (loc, c) = Statement.Switch.Case.(
node "SwitchCase" loc [
"test", option expression c.test;
"consequent", array_of_list statement c.consequent;
]
)
and catch (loc, c) = Statement.Try.CatchClause.(
node "CatchClause" loc [
"param", pattern c.param;
"body", block c.body;
]
)
and block (loc, b) =
node "BlockStatement" loc [
"body", statement_list b.Statement.Block.body;
]
and declare_variable (loc, d) = Statement.DeclareVariable.(
let id_loc = Loc.btwn (fst d.id) (match d.annot with
| Some annot -> fst annot
| None -> fst d.id) in
node "DeclareVariable" loc [
"id", pattern_identifier id_loc {
Pattern.Identifier.name = d.id;
annot = d.annot;
optional = false;
};
]
)
and declare_function (loc, d) = Statement.DeclareFunction.(
let id_loc = Loc.btwn (fst d.id) (fst d.annot) in
node "DeclareFunction" loc [
"id", pattern_identifier id_loc {
Pattern.Identifier.name = d.id;
annot = Some d.annot;
optional = false;
};
"predicate", option predicate d.predicate
]
)
and declare_class (loc, { Statement.DeclareClass.
id;
tparams;
body;
extends;
implements;
mixins;
}) =
(* TODO: extends shouldn't return an array *)
let extends = match extends with
| Some extends -> array [interface_extends extends]
| None -> array []
in
node "DeclareClass" loc [
"id", identifier id;
"typeParameters", option type_parameter_declaration tparams;
"body", object_type body;
"extends", extends;
"implements", array_of_list class_implements implements;
"mixins", array_of_list interface_extends mixins;
]
and declare_interface (loc, { Statement.Interface.
id;
tparams;
body;
extends;
}) =
node "DeclareInterface" loc [
"id", identifier id;
"typeParameters", option type_parameter_declaration tparams;
"body", object_type body;
"extends", array_of_list interface_extends extends;
]
and export_kind = function
| Statement.ExportType -> "type"
| Statement.ExportValue -> "value"
and export_specifiers = Statement.ExportNamedDeclaration.(function
| Some (ExportSpecifiers specifiers) ->
array_of_list export_specifier specifiers
| Some (ExportBatchSpecifier (loc, Some name)) ->
array [
node "ExportNamespaceSpecifier" loc [
"exported", identifier name
]
]
| Some (ExportBatchSpecifier (_, None)) ->
(* this should've been handled by callers, since this represents an
ExportAllDeclaration, not a specifier. *)
array []
| None ->
array []
)
and declare_type_alias (loc, { Statement.TypeAlias.
id;
tparams;
right;
}) =
node "DeclareTypeAlias" loc [
"id", identifier id;
"typeParameters", option type_parameter_declaration tparams;
"right", _type right;
]
and type_alias (loc, alias) = Statement.TypeAlias.(
node "TypeAlias" loc [
"id", identifier alias.id;
"typeParameters", option type_parameter_declaration alias.tparams;
"right", _type alias.right;
]
)
and opaque_type ~declare (loc, opaque_t) = Statement.OpaqueType.(
let name = if declare then "DeclareOpaqueType" else "OpaqueType" in
node name loc [
"id", identifier opaque_t.id;
"typeParameters", option type_parameter_declaration opaque_t.tparams;
"impltype", option _type opaque_t.impltype;
"supertype", option _type opaque_t.supertype;
]
)
and class_declaration (loc, c) = Class.(
node "ClassDeclaration" loc [
(* estree hasn't come around to the idea that class decls can have
optional ids, but acorn, babel, espree and esprima all have, so let's
do it too. see https://github.com/estree/estree/issues/98 *)
"id", option identifier c.id;
"body", class_body c.body;
"typeParameters", option type_parameter_declaration c.tparams;
"superClass", option expression c.super;
"superTypeParameters", option type_parameter_instantiation c.super_targs;
"implements", array_of_list class_implements c.implements;
"decorators", array_of_list expression c.classDecorators;
]
)
and class_expression (loc, c) = Class.(
node "ClassExpression" loc [
"id", option identifier c.id;
"body", class_body c.body;
"typeParameters", option type_parameter_declaration c.tparams;
"superClass", option expression c.super;
"superTypeParameters", option type_parameter_instantiation c.super_targs;
"implements", array_of_list class_implements c.implements;
"decorators", array_of_list expression c.classDecorators;
]
)
and class_implements (loc, implements) = Class.Implements.(
node "ClassImplements" loc [
"id", identifier implements.id;
"typeParameters", option type_parameter_instantiation implements.targs;
]
)
and class_body (loc, body) = Class.Body.(
node "ClassBody" loc [
"body", array_of_list class_element body.body;
]
)
and class_element = Class.Body.(function
| Method m -> class_method m
| PrivateField p -> class_private_field p
| Property p -> class_property p)
and class_method (loc, method_) =
let { Class.Method.key; value; kind; static; decorators; } = method_ in
let key, computed = Expression.Object.Property.(match key with
| Literal lit -> literal lit, false
| Identifier id -> identifier id, false
| PrivateName name -> private_name name, false
| Computed expr -> expression expr, true) in
let kind = Class.Method.(match kind with
| Constructor -> "constructor"
| Method -> "method"
| Get -> "get"
| Set -> "set") in
node "MethodDefinition" loc [
"key", key;
"value", function_expression value;
"kind", string kind;
"static", bool static;
"computed", bool computed;
"decorators", array_of_list expression decorators;
]
and class_private_field (loc, prop) = Class.PrivateField.(
let (_, key) = prop.key in
node "ClassPrivateProperty" loc [
"key", identifier key;
"value", option expression prop.value;
"typeAnnotation", option type_annotation prop.annot;
"static", bool prop.static;
"variance", option variance prop.variance;
]
)
and class_property (loc, prop) = Class.Property.(
let key, computed = (match prop.key with
| Expression.Object.Property.Literal lit -> literal lit, false
| Expression.Object.Property.Identifier id -> identifier id, false
| Expression.Object.Property.PrivateName _ ->
failwith "Internal Error: Private name found in class prop"
| Expression.Object.Property.Computed expr -> expression expr, true) in
node "ClassProperty" loc [
"key", key;
"value", option expression prop.value;
"typeAnnotation", option type_annotation prop.annot;
"computed", bool computed;
"static", bool prop.static;
"variance", option variance prop.variance;
]
)
and interface_declaration (loc, i) = Statement.Interface.(
node "InterfaceDeclaration" loc [
"id", identifier i.id;
"typeParameters", option type_parameter_declaration i.tparams;
"body", object_type i.body;
"extends", array_of_list interface_extends i.extends;
]
)
and interface_extends (loc, g) = Type.Generic.(
let id = match g.id with
| Identifier.Unqualified id -> identifier id
| Identifier.Qualified q -> generic_type_qualified_identifier q
in
node "InterfaceExtends" loc [
"id", id;
"typeParameters", option type_parameter_instantiation g.targs;
]
)
and pattern = Pattern.(function
| loc, Object obj ->
node "ObjectPattern" loc [
"properties", array_of_list object_pattern_property obj.Object.properties;
"typeAnnotation", option type_annotation obj.Object.annot;
]
| loc, Array arr ->
node "ArrayPattern" loc [
"elements", array_of_list (option array_pattern_element) arr.Array.elements;
"typeAnnotation", option type_annotation arr.Array.annot;
]
| loc, Assignment { Assignment.left; right } ->
node "AssignmentPattern" loc [
"left", pattern left;
"right", expression right
]
| loc, Identifier pattern_id ->
pattern_identifier loc pattern_id
| _loc, Expression expr -> expression expr)
and function_params = Ast.Function.Params.(function
| _, { params; rest = Some (rest_loc, { Function.RestElement.argument }) } ->
let rest = node "RestElement" rest_loc [
"argument", pattern argument;
] in
let rev_params = params |> List.map pattern |> List.rev in
let params = List.rev (rest::rev_params) in
array params
| _, { params; rest = None } ->
array_of_list pattern params
)
and array_pattern_element = Pattern.Array.(function
| Element p -> pattern p
| RestElement (loc, { RestElement.argument; }) ->
node "RestElement" loc [
"argument", pattern argument;
]
)
and object_property = Expression.Object.(function
| Property (loc, prop) -> Property.(
let key, value, kind, method_, shorthand = match prop with
| Init { key; value; shorthand } ->
key, expression value, "init", false, shorthand
| Method { key; value = (loc, func) } ->
key, function_expression (loc, func), "init", true, false
| Get { key; value = (loc, func) } ->
key, function_expression (loc, func), "get", false, false
| Set { key; value = (loc, func) } ->
key, function_expression (loc, func), "set", false, false
in
let key, computed = match key with
| Literal lit -> literal lit, false
| Identifier id -> identifier id, false
| PrivateName _ -> failwith "Internal Error: Found private field in object props"
| Computed expr -> expression expr, true
in
node "Property" loc [
"key", key;
"value", value;
"kind", string kind;
"method", bool method_;
"shorthand", bool shorthand;
"computed", bool computed;
]
)
| SpreadProperty(loc, prop) -> SpreadProperty.(
node "SpreadProperty" loc [
"argument", expression prop.argument;
]
))
and object_pattern_property = Pattern.Object.(function
| Property (loc, prop) -> Property.(
let key, computed = (match prop.key with
| Literal lit -> literal lit, false
| Identifier id -> identifier id, false
| Computed expr -> expression expr, true) in
node "Property" loc [
"key", key;
"value", pattern prop.pattern;
"kind", string "init";
"method", bool false;
"shorthand", bool prop.shorthand;
"computed", bool computed;
]
)
| RestProperty (loc, prop) -> RestProperty.(
node "RestProperty" loc [
"argument", pattern prop.argument;
]
)
)
and expression_or_spread = Expression.(function
| Expression expr -> expression expr
| Spread (loc, { SpreadElement.argument; }) ->
node "SpreadElement" loc [
"argument", expression argument;
]
)
and comprehension_block (loc, b) = Expression.Comprehension.Block.(
node "ComprehensionBlock" loc [
"left", pattern b.left;
"right", expression b.right;
"each", bool b.each;
]
)
and literal (loc, lit) = Literal.(
let { value; raw; } = lit in
let value_ = match value with
| String str -> string str
| Boolean b -> bool b
| Null -> null
| Number f -> number f
| RegExp { RegExp.pattern; flags; } -> regexp loc pattern flags
in
let props = match value with
| RegExp { RegExp.pattern; flags; } ->
let regex = obj [
"pattern", string pattern;
"flags", string flags;
] in
[ "value", value_; "raw", string raw; "regex", regex ]
| _ ->
[ "value", value_; "raw", string raw; ]
in
node "Literal" loc props
)
and string_literal (loc, lit) = StringLiteral.(
node "Literal" loc [
"value", string lit.value;
"raw", string lit.raw;
]
)
and template_literal (loc, value) = Expression.TemplateLiteral.(
node "TemplateLiteral" loc [
"quasis", array_of_list template_element value.quasis;
"expressions", array_of_list expression value.expressions;
]
)
and template_element (loc, element) = Expression.TemplateLiteral.Element.(
let value = obj [
"raw", string element.value.raw;
"cooked", string element.value.cooked;
] in
node "TemplateElement" loc [
"value", value;
"tail", bool element.tail;
]
)
and tagged_template (loc, tagged) = Expression.TaggedTemplate.(
node "TaggedTemplateExpression" loc [
"tag", expression tagged.tag;
"quasi", template_literal tagged.quasi;
]
)
and variable_declaration (loc, var) = Statement.VariableDeclaration.(
let kind = match var.kind with
| Var -> "var"
| Let -> "let"
| Const -> "const"
in
node "VariableDeclaration" loc [
"declarations", array_of_list variable_declarator var.declarations;
"kind", string kind;