Source file flow_ast_utils.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
open Flow_ast
module E = Expression
module I = Identifier
type 'loc binding = 'loc * string
type 'loc ident = 'loc * string [@@deriving show]
type 'loc source = 'loc * string [@@deriving show]
let rec fold_bindings_of_pattern =
Pattern.(
let property f acc =
Object.(
function
| Property (_, { Property.pattern = p; _ })
| RestElement (_, { RestElement.argument = p; comments = _ }) ->
fold_bindings_of_pattern f acc p
)
in
let element f acc =
Array.(
function
| Hole _ -> acc
| Element (_, { Element.argument = p; default = _ })
| RestElement (_, { RestElement.argument = p; comments = _ }) ->
fold_bindings_of_pattern f acc p
)
in
fun f acc -> function
| (_, Identifier { Identifier.name; _ }) -> f acc name
| (_, Object { Object.properties; _ }) -> List.fold_left (property f) acc properties
| (_, Array { Array.elements; _ }) -> List.fold_left (element f) acc elements
| (_, Expression _) -> acc
)
let fold_bindings_of_variable_declarations f acc declarations =
let open Statement.VariableDeclaration in
List.fold_left
(fun acc -> function
| (_, { Declarator.id = pattern; _ }) ->
let has_anno =
let open Pattern in
match pattern with
| (_, Array { Array.annot = Type.Available _; _ })
| (_, Object { Object.annot = Type.Available _; _ })
| (_, Identifier { Identifier.annot = Type.Available _; _ }) ->
true
| _ -> false
in
fold_bindings_of_pattern (f has_anno) acc pattern)
acc
declarations
let rec pattern_has_binding =
let open Pattern in
let property =
let open Object in
function
| Property (_, { Property.pattern = p; _ })
| RestElement (_, { RestElement.argument = p; comments = _ }) ->
pattern_has_binding p
in
let element =
let open Array in
function
| Hole _ -> false
| Element (_, { Element.argument = p; default = _ })
| RestElement (_, { RestElement.argument = p; comments = _ }) ->
pattern_has_binding p
in
function
| (_, Identifier _) -> true
| (_, Object { Object.properties; _ }) -> List.exists property properties
| (_, Array { Array.elements; _ }) -> List.exists element elements
| (_, Expression _) -> false
let rec match_pattern_has_binding =
let open MatchPattern in
let property = function
| (_, ObjectPattern.Property.Valid { ObjectPattern.Property.pattern = p; _ }) ->
match_pattern_has_binding p
| (_, ObjectPattern.Property.InvalidShorthand _) -> false
in
let rest_has_binding = function
| Some (_, { RestPattern.argument = Some _; comments = _ }) -> true
| _ -> false
in
function
| (_, WildcardPattern _)
| (_, NumberPattern _)
| (_, BigIntPattern _)
| (_, StringPattern _)
| (_, BooleanPattern _)
| (_, NullPattern _)
| (_, UnaryPattern _)
| (_, IdentifierPattern _)
| (_, MemberPattern _) ->
false
| (_, BindingPattern _) -> true
| (_, ObjectPattern { ObjectPattern.properties; rest; comments = _ }) ->
rest_has_binding rest || List.exists property properties
| (_, ArrayPattern { ArrayPattern.elements; rest; comments = _ }) ->
rest_has_binding rest
|| List.exists
(fun { ArrayPattern.Element.pattern; _ } -> match_pattern_has_binding pattern)
elements
| (_, OrPattern { OrPattern.patterns; _ }) -> List.exists match_pattern_has_binding patterns
| (_, AsPattern _) -> true
let string_of_variable_kind = function
| Variable.Var -> "var"
| Variable.Let -> "let"
| Variable.Const -> "const"
let partition_directives statements =
let open Statement in
let rec helper directives = function
| ((_, Expression { Expression.directive = Some _; _ }) as directive) :: rest ->
helper (directive :: directives) rest
| rest -> (List.rev directives, rest)
in
helper [] statements
let hoist_function_and_component_declarations stmts =
let open Statement in
let (func_and_component_decs, other_stmts) =
List.partition
(function
| (_, (FunctionDeclaration { Function.id = Some _; _ } | ComponentDeclaration _))
| ( _,
ExportNamedDeclaration
{
ExportNamedDeclaration.declaration =
Some
(_, (FunctionDeclaration { Function.id = Some _; _ } | ComponentDeclaration _));
_;
}
)
| ( _,
ExportDefaultDeclaration
{
ExportDefaultDeclaration.declaration =
ExportDefaultDeclaration.Declaration
(_, (FunctionDeclaration { Function.id = Some _; _ } | ComponentDeclaration _));
_;
}
)
| (_, DeclareFunction _)
| ( _,
DeclareExportDeclaration DeclareExportDeclaration.{ declaration = Some (Function _); _ }
) ->
true
| _ -> false)
stmts
in
func_and_component_decs @ other_stmts
let negate_raw_lit raw =
let raw_len = String.length raw in
if raw_len > 0 && raw.[0] = '-' then
String.sub raw 1 (raw_len - 1)
else
"-" ^ raw
let negate_number_literal (value, raw) = (~-.value, negate_raw_lit raw)
let negate_bigint_literal (value, raw) =
match value with
| None -> (None, raw)
| Some value -> (Some (Int64.neg value), negate_raw_lit raw)
let is_number_literal node =
match node with
| Expression.NumberLiteral _
| Expression.Unary
{
Expression.Unary.operator = Expression.Unary.Minus;
argument = (_, Expression.NumberLiteral _);
comments = _;
} ->
true
| _ -> false
let node =
match node with
| Expression.NumberLiteral { NumberLiteral.value; raw; comments = _ } -> Some (value, raw)
| Expression.Unary
{
Expression.Unary.operator = Expression.Unary.Minus;
argument = (_, Expression.NumberLiteral { NumberLiteral.value; raw; _ });
comments = _;
} ->
Some (negate_number_literal (value, raw))
| _ -> None
let is_bigint_literal node =
match node with
| Expression.BigIntLiteral _
| Expression.Unary
{
Expression.Unary.operator = Expression.Unary.Minus;
argument = (_, Expression.BigIntLiteral _);
comments = _;
} ->
true
| _ -> false
let node =
match node with
| Expression.BigIntLiteral { BigIntLiteral.value; raw; comments = _ } -> Some (value, raw)
| Expression.Unary
{
Expression.Unary.operator = Expression.Unary.Minus;
argument = (_, Expression.BigIntLiteral { BigIntLiteral.value; raw; comments = _ });
comments = _;
} ->
Some (negate_bigint_literal (value, raw))
| _ -> None
let is_call_to_invariant callee =
match callee with
| (_, Expression.Identifier (_, { Identifier.name = "invariant"; _ })) -> true
| _ -> false
let is_call_to_require callee =
match callee with
| (_, Expression.Identifier (_, { Identifier.name = "require"; _ })) -> true
| _ -> false
let is_call_to_is_array callee =
match callee with
| ( _,
E.Member
{
E.Member._object = (_, E.Identifier (_, { I.name = "Array"; comments = _ }));
property = E.Member.PropertyIdentifier (_, { I.name = "isArray"; comments = _ });
comments = _;
}
) ->
true
| _ -> false
let is_call_to_object_dot_freeze callee =
match callee with
| ( _,
E.Member
{
E.Member._object = (_, E.Identifier (_, { I.name = "Object"; comments = _ }));
property = E.Member.PropertyIdentifier (_, { I.name = "freeze"; comments = _ });
comments = _;
}
) ->
true
| _ -> false
let get_call_to_object_dot_freeze_arg callee targs args =
match (targs, args) with
| (None, (_args_loc, { E.ArgList.arguments = [E.Expression (obj_loc, E.Object o)]; comments = _ }))
when is_call_to_object_dot_freeze callee ->
Some (obj_loc, o)
| _ -> None
let is_call_to_object_static_method callee =
match callee with
| ( _,
E.Member
{
E.Member._object = (_, E.Identifier (_, { I.name = "Object"; comments = _ }));
property = E.Member.PropertyIdentifier _;
comments = _;
}
) ->
true
| _ -> false
let is_module_dot_exports callee =
match callee with
| ( _,
E.Member
{
E.Member._object = (_, E.Identifier (_, { I.name = "module"; comments = _ }));
property = E.Member.PropertyIdentifier (_, { I.name = "exports"; comments = _ });
comments = _;
}
) ->
true
| _ -> false
let get_call_to_jest_module_mocking_fn callee arguments =
match (callee, arguments) with
| ( ( _,
E.Member
{
E.Member._object = (_, E.Identifier (jest_loc, { I.name = "jest"; comments = _ }));
property =
E.Member.PropertyIdentifier
( _,
{
I.name =
( "createMockFromModule" | "mock" | "unmock" | "deepUnmock" | "doMock"
| "dontMock" | "setMock" | "requireActual" | "requireMock" );
comments = _;
}
);
_;
}
),
( _,
{
E.ArgList.arguments =
E.Expression
( source_loc,
( E.StringLiteral { StringLiteral.value = name; _ }
| E.TemplateLiteral
{
E.TemplateLiteral.quasis =
[
( _,
{
E.TemplateLiteral.Element.value =
{ E.TemplateLiteral.Element.cooked = name; _ };
_;
}
);
];
_;
} )
)
:: _;
comments = _;
}
)
) ->
Some (jest_loc, source_loc, name)
| _ -> None
let is_super_member_access = function
| { E.Member._object = (_, E.Super _); _ } -> true
| _ -> false
let acceptable_statement_in_declaration_context ~in_declare_namespace =
let open Statement in
function
| Block _ -> Error "block"
| Break _ -> Error "break"
| ClassDeclaration _ -> Error "class declaration"
| ComponentDeclaration _ -> Error "component declaration"
| Continue _ -> Error "continue"
| Debugger _ -> Error "debugger"
| DoWhile _ -> Error "do while"
| ExportDefaultDeclaration _ -> Error "export default"
| ExportNamedDeclaration { ExportNamedDeclaration.export_kind = ExportValue; _ } ->
Error "value export"
| Expression _ -> Error "expression"
| For _ -> Error "for"
| ForIn _ -> Error "for in"
| ForOf _ -> Error "for of"
| FunctionDeclaration _ -> Error "function declaration"
| If _ -> Error "if"
| Labeled _ -> Error "labeled"
| Match _ -> Error "match"
| Return _ -> Error "return"
| Switch _ -> Error "switch"
| Throw _ -> Error "throw"
| Try _ -> Error "try"
| VariableDeclaration _ -> Error "variable declaration"
| While _ -> Error "while"
| With _ -> Error "with"
| ImportDeclaration _ ->
if in_declare_namespace then
Error "import declaration"
else
Ok ()
| DeclareModuleExports _ ->
if in_declare_namespace then
Error "declare module.exports"
else
Ok ()
| DeclareClass _
| DeclareComponent _
| DeclareEnum _
| DeclareExportDeclaration _
| DeclareFunction _
| DeclareInterface _
| DeclareModule _
| DeclareNamespace _
| DeclareOpaqueType _
| DeclareTypeAlias _
| DeclareVariable _
| Empty _
| EnumDeclaration _
| ExportNamedDeclaration { ExportNamedDeclaration.export_kind = ExportType; _ }
| InterfaceDeclaration _
| OpaqueType _
| TypeAlias _ ->
Ok ()
let rec is_type_only_declaration_statement (_, stmt') =
let open Statement in
let is_type_only_declaration_statement' = function
| DeclareInterface _
| DeclareOpaqueType _
| DeclareTypeAlias _
| Empty _
| InterfaceDeclaration _
| OpaqueType _
| TypeAlias _ ->
true
| DeclareExportDeclaration
DeclareExportDeclaration.
{ declaration = Some (NamedType _ | NamedOpaqueType _ | Interface _); _ } ->
true
| DeclareNamespace { DeclareNamespace.body = (_, { Block.body; _ }); _ } ->
List.for_all is_type_only_declaration_statement body
| ExportNamedDeclaration { ExportNamedDeclaration.export_kind; _ } -> export_kind = ExportType
| Block _
| Break _
| ClassDeclaration _
| ComponentDeclaration _
| Continue _
| Debugger _
| DoWhile _
| EnumDeclaration _
| ExportDefaultDeclaration _
| Expression _
| For _
| ForIn _
| ForOf _
| FunctionDeclaration _
| If _
| Labeled _
| Match _
| Return _
| Switch _
| Throw _
| Try _
| VariableDeclaration _
| While _
| With _
| ImportDeclaration _
| DeclareClass _
| DeclareComponent _
| DeclareEnum _
| DeclareExportDeclaration _
| DeclareFunction _
| DeclareModule _
| DeclareModuleExports _
| DeclareVariable _ ->
false
in
is_type_only_declaration_statement' stmt'
let loc_of_statement = fst
let loc_of_expression = fst
let loc_of_pattern = fst
let loc_of_ident = fst
let name_of_ident (_, { Identifier.name; comments = _ }) = name
let source_of_ident (loc, { Identifier.name; comments = _ }) = (loc, name)
let ident_of_source ? (loc, name) = (loc, { Identifier.name; comments })
let ?(leading = []) ?(trailing = []) a = { Syntax.leading; trailing; internal = a }
let ?(leading = []) ?(trailing = []) () =
match (leading, trailing) with
| ([], []) -> None
| (_, _) -> Some (mk_comments ~leading ~trailing ())
let ?(leading = []) ?(trailing = []) ~internal () =
match (leading, trailing, internal) with
| ([], [], []) -> None
| _ -> Some (mk_comments ~leading ~trailing internal)
let ~inner ~outer =
let open Syntax in
match (inner, outer) with
| (None, c)
| (c, None) ->
c
| (Some inner, Some outer) ->
mk_comments_opt
~leading:(outer.leading @ inner.leading)
~trailing:(inner.trailing @ outer.trailing)
()
let ~inner ~outer =
match (inner, outer) with
| (inner, None) -> inner
| (None, Some { Syntax.leading; trailing; _ }) ->
mk_comments_with_internal_opt ~leading ~trailing ~internal:[] ()
| ( Some { Syntax.leading = inner_leading; trailing = inner_trailing; internal },
Some { Syntax.leading = outer_leading; trailing = outer_trailing; _ }
) ->
mk_comments_with_internal_opt
~leading:(outer_leading @ inner_leading)
~trailing:(inner_trailing @ outer_trailing)
~internal
()
let =
match comments with
| None -> (None, None)
| Some { Syntax.leading; trailing; _ } ->
(mk_comments_opt ~leading (), mk_comments_opt ~trailing ())
let string_of_assignment_operator op =
let open E.Assignment in
match op with
| PlusAssign -> "+="
| MinusAssign -> "-="
| MultAssign -> "*="
| ExpAssign -> "**="
| DivAssign -> "/="
| ModAssign -> "%="
| LShiftAssign -> "<<="
| RShiftAssign -> ">>="
| RShift3Assign -> ">>>="
| BitOrAssign -> "|="
| BitXorAssign -> "^="
| BitAndAssign -> "&="
| NullishAssign -> "??="
| AndAssign -> "&&="
| OrAssign -> "||="
let string_of_binary_operator op =
let open E.Binary in
match op 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"
module ExpressionSort = struct
type t =
| Array
| ArrowFunction
| Assignment
| Binary
| Call
| Class
| Conditional
| Function
| Identifier
| Import
| JSXElement
| JSXFragment
| Literal
| Logical
| Match
| Member
| MetaProperty
| New
| Object
| OptionalCall
| OptionalMember
| Satisfies
| Sequence
| Super
| TaggedTemplate
| TemplateLiteral
| This
| TypeCast
| Unary
| Update
| Yield
[@@deriving show]
let to_string = function
| Array -> "array"
| ArrowFunction -> "arrow function"
| Assignment -> "assignment expression"
| Binary -> "binary expression"
| Call -> "call expression"
| Class -> "class"
| Conditional -> "conditional expression"
| Function -> "function"
| Identifier -> "identifier"
| Import -> "import expression"
| JSXElement -> "JSX element"
| JSXFragment -> "JSX fragment"
| Literal -> "literal"
| Logical -> "logical expression"
| Match -> "match expression"
| Member -> "member expression"
| MetaProperty -> "metaproperty expression"
| New -> "new expression"
| Object -> "object"
| OptionalCall -> "optional call expression"
| OptionalMember -> "optional member expression"
| Satisfies -> "satisfies expression"
| Sequence -> "sequence"
| Super -> "`super` reference"
| TaggedTemplate -> "tagged template expression"
| TemplateLiteral -> "template literal"
| This -> "`this` reference"
| TypeCast -> "type cast"
| Unary -> "unary expression"
| Update -> "update expression"
| Yield -> "yield expression"
end
let loc_of_annotation_or_hint =
let open Type in
function
| Missing loc
| Available (_, (loc, _)) ->
loc
let loc_of_return_annot =
let open Function.ReturnAnnot in
function
| Missing loc
| Available (_, (loc, _))
| TypeGuard (loc, _) ->
loc
let push_toplevel_type t exp =
let open E in
let push_toplevel_identifier id =
let ((id_loc, _), id) = id in
((id_loc, t), id)
in
let push_to_member mem =
match mem with
| { Member.property = Member.PropertyIdentifier id; _ } ->
{ mem with Member.property = Member.PropertyIdentifier (push_toplevel_identifier id) }
| p -> p
in
let ((loc, _), e) = exp in
let e' =
match e with
| Identifier id -> Identifier (push_toplevel_identifier id)
| Member member -> Member (push_to_member member)
| OptionalMember ({ OptionalMember.member; _ } as omem) ->
OptionalMember { omem with OptionalMember.member = push_to_member member }
| _ -> e
in
((loc, t), e')
let hook_name s =
let is_cap c = c = Char.uppercase_ascii c in
String.starts_with ~prefix:"use" s && (String.length s = 3 || is_cap s.[3])
let hook_function { Function.id; _ } =
match id with
| Some (loc, { I.name; _ }) when hook_name name -> Some loc
| _ -> None
let hook_call { E.Call.callee; _ } =
let open E in
let rec hook_callee top exp =
match exp with
| (_, Identifier (_, { I.name; _ })) -> hook_name name || not top
| (_, Member { Member._object; property = Member.PropertyIdentifier (_, { I.name; _ }); _ }) ->
(hook_name name || not top) && hook_callee false _object
| _ -> false
in
hook_callee true callee
let match_root_name = "<match_root>"
let match_root_ident loc = (loc, { Identifier.name = match_root_name; comments = None })
let expression_of_match_member_pattern ~visit_expression pattern =
let open MatchPattern in
let rec f (loc, { MemberPattern.base; property; }) =
let (_object, root_name) =
match base with
| MemberPattern.BaseIdentifier ((loc, _) as id) -> ((loc, Expression.Identifier id), id)
| MemberPattern.BaseMember mem -> f mem
in
let property =
match property with
| MemberPattern.PropertyIdentifier id -> Expression.Member.PropertyIdentifier id
| MemberPattern.PropertyString (loc, lit) ->
Expression.Member.PropertyExpression (loc, Expression.StringLiteral lit)
| MemberPattern.PropertyNumber (loc, lit) ->
Expression.Member.PropertyExpression (loc, Expression.NumberLiteral lit)
| MemberPattern.PropertyBigInt (loc, lit) ->
Expression.Member.PropertyExpression (loc, Expression.BigIntLiteral lit)
in
let exp = (loc, Expression.Member { Expression.Member._object; property; comments }) in
visit_expression exp;
(exp, root_name)
in
f pattern
let get_inferred_type_guard_candidate params body return =
match (body, return) with
| (Function.BodyExpression _, Function.ReturnAnnot.Missing _) -> begin
match params with
| ( _,
{
Function.Params.params =
[
( _,
{
Function.Param.argument =
( _,
Pattern.Identifier
{ Pattern.Identifier.name = (loc, { Identifier.name; _ }); _ }
);
_;
}
);
];
rest = None;
_;
}
) ->
Some (loc, name)
| _ -> None
end
| _ -> None