-
Notifications
You must be signed in to change notification settings - Fork 465
/
Copy pathjsx_v4.ml
1568 lines (1504 loc) · 57.1 KB
/
jsx_v4.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
open! Ast_helper
open Ast_mapper
open Asttypes
open Parsetree
open Longident
let module_access_name config value =
String.capitalize_ascii config.Jsx_common.module_ ^ "." ^ value
|> Longident.parse
let nolabel = Nolabel
let labelled str = Labelled str
let is_optional str =
match str with
| Optional _ -> true
| _ -> false
let is_labelled str =
match str with
| Labelled _ -> true
| _ -> false
let is_forward_ref = function
| {pexp_desc = Pexp_ident {txt = Ldot (Lident "React", "forwardRef")}} -> true
| _ -> false
let get_label str =
match str with
| Optional str | Labelled str -> str
| Nolabel -> ""
let optional_attrs = [Jsx_common.optional_attr]
let constant_string ~loc str =
Ast_helper.Exp.constant ~loc (Pconst_string (str, None))
(* {} empty record *)
let empty_record ~loc = Exp.record ~loc [] None
let unit_expr ~loc = Exp.construct ~loc (Location.mkloc (Lident "()") loc) None
let safe_type_from_value value_str =
let value_str = get_label value_str in
if value_str = "" || (value_str.[0] [@doesNotRaise]) <> '_' then value_str
else "T" ^ value_str
let ref_type_var loc = Typ.var ~loc "ref"
let ref_type loc =
Typ.constr ~loc
{loc; txt = Ldot (Ldot (Lident "Js", "Nullable"), "t")}
[ref_type_var loc]
type 'a children = ListLiteral of 'a | Exact of 'a
(* if children is a list, convert it to an array while mapping each element. If not, just map over it, as usual *)
let transform_children_if_list_upper ~mapper the_list =
let rec transformChildren_ the_list accum =
(* not in the sense of converting a list to an array; convert the AST
reprensentation of a list to the AST reprensentation of an array *)
match the_list with
| {pexp_desc = Pexp_construct ({txt = Lident "[]"}, None)} -> (
match accum with
| [single_element] -> Exact single_element
| accum -> ListLiteral (Exp.array (List.rev accum)))
| {
pexp_desc =
Pexp_construct
({txt = Lident "::"}, Some {pexp_desc = Pexp_tuple [v; acc]});
} ->
transformChildren_ acc (mapper.expr mapper v :: accum)
| not_a_list -> Exact (mapper.expr mapper not_a_list)
in
transformChildren_ the_list []
let transform_children_if_list ~mapper the_list =
let rec transformChildren_ the_list accum =
(* not in the sense of converting a list to an array; convert the AST
reprensentation of a list to the AST reprensentation of an array *)
match the_list with
| {pexp_desc = Pexp_construct ({txt = Lident "[]"}, None)} ->
Exp.array (List.rev accum)
| {
pexp_desc =
Pexp_construct
({txt = Lident "::"}, Some {pexp_desc = Pexp_tuple [v; acc]});
} ->
transformChildren_ acc (mapper.expr mapper v :: accum)
| not_a_list -> mapper.expr mapper not_a_list
in
transformChildren_ the_list []
let extract_children ?(remove_last_position_unit = false) ~loc
props_and_children =
let rec allButLast_ lst acc =
match lst with
| [] -> []
| [(Nolabel, {pexp_desc = Pexp_construct ({txt = Lident "()"}, None)})] ->
acc
| (Nolabel, {pexp_loc}) :: _rest ->
Jsx_common.raise_error ~loc:pexp_loc
"JSX: found non-labelled argument before the last position"
| arg :: rest -> allButLast_ rest (arg :: acc)
in
let all_but_last lst = allButLast_ lst [] |> List.rev in
match
List.partition
(fun (label, _) -> label = labelled "children")
props_and_children
with
| [], props ->
(* no children provided? Place a placeholder list *)
( Exp.construct {loc = Location.none; txt = Lident "[]"} None,
if remove_last_position_unit then all_but_last props else props )
| [(_, children_expr)], props ->
( children_expr,
if remove_last_position_unit then all_but_last props else props )
| _ ->
Jsx_common.raise_error ~loc
"JSX: somehow there's more than one `children` label"
let merlin_focus = ({loc = Location.none; txt = "merlin.focus"}, PStr [])
(* Helper method to filter out any attribute that isn't [@react.component] *)
let other_attrs_pure (loc, _) =
match loc.txt with
| "react.component" | "jsx.component" -> false
| _ -> true
(* Finds the name of the variable the binding is assigned to, otherwise raises Invalid_argument *)
let rec get_fn_name binding =
match binding with
| {ppat_desc = Ppat_var {txt}} -> txt
| {ppat_desc = Ppat_constraint (pat, _)} -> get_fn_name pat
| {ppat_loc} ->
Jsx_common.raise_error ~loc:ppat_loc
"JSX component calls cannot be destructured."
let make_new_binding binding expression new_name =
match binding with
| {pvb_pat = {ppat_desc = Ppat_var ppat_var} as pvb_pat} ->
{
binding with
pvb_pat =
{pvb_pat with ppat_desc = Ppat_var {ppat_var with txt = new_name}};
pvb_expr = expression;
pvb_attributes = [merlin_focus];
}
| {pvb_loc} ->
Jsx_common.raise_error ~loc:pvb_loc
"JSX component calls cannot be destructured."
(* Lookup the filename from the location information on the AST node and turn it into a valid module identifier *)
let filename_from_loc (pstr_loc : Location.t) =
let file_name =
match pstr_loc.loc_start.pos_fname with
| "" -> !Location.input_name
| file_name -> file_name
in
let file_name =
try Filename.chop_extension (Filename.basename file_name)
with Invalid_argument _ -> file_name
in
let file_name = String.capitalize_ascii file_name in
file_name
(* Build a string representation of a module name with segments separated by $ *)
let make_module_name file_name nested_modules fn_name =
let full_module_name =
match (file_name, nested_modules, fn_name) with
(* TODO: is this even reachable? It seems like the fileName always exists *)
| "", nested_modules, "make" -> nested_modules
| "", nested_modules, fn_name -> List.rev (fn_name :: nested_modules)
| file_name, nested_modules, "make" -> file_name :: List.rev nested_modules
| file_name, nested_modules, fn_name ->
file_name :: List.rev (fn_name :: nested_modules)
in
let full_module_name = String.concat "$" full_module_name in
full_module_name
(*
AST node builders
These functions help us build AST nodes that are needed when transforming a [@react.component] into a
constructor and a props external
*)
(* make record from props and spread props if exists *)
let record_from_props ~loc ~remove_key call_arguments =
let spread_props_label = "_spreadProps" in
let rec remove_last_position_unit_aux props acc =
match props with
| [] -> acc
| [(Nolabel, {pexp_desc = Pexp_construct ({txt = Lident "()"}, None)})] ->
acc
| (Nolabel, {pexp_loc}) :: _rest ->
Jsx_common.raise_error ~loc:pexp_loc
"JSX: found non-labelled argument before the last position"
| ((Labelled txt, {pexp_loc}) as prop) :: rest
| ((Optional txt, {pexp_loc}) as prop) :: rest ->
if txt = spread_props_label then
match acc with
| [] -> remove_last_position_unit_aux rest (prop :: acc)
| _ ->
Jsx_common.raise_error ~loc:pexp_loc
"JSX: use {...p} {x: v} not {x: v} {...p} \n\
\ multiple spreads {...p} {...p} not allowed."
else remove_last_position_unit_aux rest (prop :: acc)
in
let props, props_to_spread =
remove_last_position_unit_aux call_arguments []
|> List.rev
|> List.partition (fun (label, _) -> label <> labelled "_spreadProps")
in
let props =
if remove_key then
props |> List.filter (fun (arg_label, _) -> "key" <> get_label arg_label)
else props
in
let process_prop (arg_label, ({pexp_loc} as pexpr)) =
(* In case filed label is "key" only then change expression to option *)
let id = get_label arg_label in
if is_optional arg_label then
( {txt = Lident id; loc = pexp_loc},
{pexpr with pexp_attributes = optional_attrs} )
else ({txt = Lident id; loc = pexp_loc}, pexpr)
in
let fields = props |> List.map process_prop in
let spread_fields =
props_to_spread |> List.map (fun (_, expression) -> expression)
in
match (fields, spread_fields) with
| [], [spread_props] | [], spread_props :: _ -> spread_props
| _, [] ->
{
pexp_desc = Pexp_record (fields, None);
pexp_loc = loc;
pexp_attributes = [];
}
| _, [spread_props]
(* take the first spreadProps only *)
| _, spread_props :: _ ->
{
pexp_desc = Pexp_record (fields, Some spread_props);
pexp_loc = loc;
pexp_attributes = [];
}
(* make type params for make fn arguments *)
(* let make = ({id, name, children}: props<'id, 'name, 'children>) *)
let make_props_type_params_tvar named_type_list =
named_type_list
|> List.filter_map (fun (_isOptional, label, _, loc, _interiorType) ->
if label = "key" then None
else Some (Typ.var ~loc @@ safe_type_from_value (Labelled label)))
let strip_option core_type =
match core_type with
| {ptyp_desc = Ptyp_constr ({txt = Lident "option"}, core_types)} ->
List.nth_opt core_types 0 [@doesNotRaise]
| _ -> Some core_type
let strip_js_nullable core_type =
match core_type with
| {
ptyp_desc =
Ptyp_constr ({txt = Ldot (Ldot (Lident "Js", "Nullable"), "t")}, core_types);
} ->
List.nth_opt core_types 0 [@doesNotRaise]
| _ -> Some core_type
(* Make type params of the props type *)
(* (Sig) let make: React.componentLike<props<string>, React.element> *)
(* (Str) let make = ({x, _}: props<'x>) => body *)
(* (Str) external make: React.componentLike<props< .. >, React.element> = "default" *)
let make_props_type_params ?(strip_explicit_option = false)
?(strip_explicit_js_nullable_of_ref = false) named_type_list =
named_type_list
|> List.filter_map (fun (is_optional, label, _, loc, interior_type) ->
if label = "key" then None
(* TODO: Worth thinking how about "ref_" or "_ref" usages *)
else if label = "ref" then
(*
If ref has a type annotation then use it, else 'ref.
For example, if JSX ppx is used for React Native, type would be different.
*)
match interior_type with
| {ptyp_desc = Ptyp_any} -> Some (ref_type_var loc)
| _ ->
(* Strip explicit Js.Nullable.t in case of forwardRef *)
if strip_explicit_js_nullable_of_ref then
strip_js_nullable interior_type
else Some interior_type
(* Strip the explicit option type in implementation *)
(* let make = (~x: option<string>=?) => ... *)
else if is_optional && strip_explicit_option then
strip_option interior_type
else Some interior_type)
let make_label_decls named_type_list =
let rec check_duplicated_label l =
let rec mem_label ((_, (la : string), _, _, _) as x) = function
| [] -> false
| (_, (lb : string), _, _, _) :: l -> lb = la || mem_label x l
in
match l with
| [] -> ()
| hd :: tl ->
if mem_label hd tl then
let _, label, _, loc, _ = hd in
Jsx_common.raise_error ~loc
"The prop `%s` is defined several times in this component." label
else check_duplicated_label tl
in
let () = named_type_list |> List.rev |> check_duplicated_label in
named_type_list
|> List.map (fun (is_optional, label, attrs, loc, interior_type) ->
if label = "key" then
Type.field ~loc ~attrs ~optional:true {txt = label; loc}
interior_type
else if is_optional then
Type.field ~loc ~attrs ~optional:true {txt = label; loc}
(Typ.var @@ safe_type_from_value @@ Labelled label)
else
Type.field ~loc ~attrs {txt = label; loc}
(Typ.var @@ safe_type_from_value @@ Labelled label))
let make_type_decls ~attrs props_name loc named_type_list =
let label_decl_list = make_label_decls named_type_list in
(* 'id, 'className, ... *)
let params =
make_props_type_params_tvar named_type_list
|> List.map (fun core_type -> (core_type, Invariant))
in
[
Type.mk ~attrs ~loc ~params {txt = props_name; loc}
~kind:(Ptype_record label_decl_list);
]
let make_type_decls_with_core_type props_name loc core_type typ_vars =
[
Type.mk ~loc {txt = props_name; loc} ~kind:Ptype_abstract
~params:(typ_vars |> List.map (fun v -> (v, Invariant)))
~manifest:core_type;
]
let live_attr = ({txt = "live"; loc = Location.none}, PStr [])
let jsx_component_props_attr =
({txt = "res.jsxComponentProps"; loc = Location.none}, PStr [])
(* type props<'x, 'y, ...> = { x: 'x, y?: 'y, ... } *)
let make_props_record_type ~core_type_of_attr ~external_ ~typ_vars_of_core_type
props_name loc named_type_list =
let attrs =
if external_ then [jsx_component_props_attr; live_attr]
else [jsx_component_props_attr]
in
Str.type_ Nonrecursive
(match core_type_of_attr with
| None -> make_type_decls ~attrs props_name loc named_type_list
| Some core_type ->
make_type_decls_with_core_type props_name loc core_type
typ_vars_of_core_type)
(* type props<'x, 'y, ...> = { x: 'x, y?: 'y, ... } *)
let make_props_record_type_sig ~core_type_of_attr ~external_
~typ_vars_of_core_type props_name loc named_type_list =
let attrs =
if external_ then [jsx_component_props_attr; live_attr]
else [jsx_component_props_attr]
in
Sig.type_ Nonrecursive
(match core_type_of_attr with
| None -> make_type_decls ~attrs props_name loc named_type_list
| Some core_type ->
make_type_decls_with_core_type props_name loc core_type
typ_vars_of_core_type)
let transform_uppercase_call3 ~config module_path mapper jsx_expr_loc
call_expr_loc attrs call_arguments =
let children, args_with_labels =
extract_children ~remove_last_position_unit:true ~loc:jsx_expr_loc
call_arguments
in
let args_for_make = args_with_labels in
let children_expr = transform_children_if_list_upper ~mapper children in
let recursively_transformed_args_for_make =
args_for_make
|> List.map (fun (label, expression) ->
(label, mapper.expr mapper expression))
in
let children_arg = ref None in
let args =
recursively_transformed_args_for_make
@
match children_expr with
| Exact children -> [(labelled "children", children)]
| ListLiteral {pexp_desc = Pexp_array list} when list = [] -> []
| ListLiteral expression -> (
(* this is a hack to support react components that introspect into their children *)
children_arg := Some expression;
match config.Jsx_common.mode with
| "automatic" ->
[
( labelled "children",
Exp.apply
(Exp.ident
{txt = module_access_name config "array"; loc = Location.none})
[(Nolabel, expression)] );
]
| _ ->
[
( labelled "children",
Exp.ident {loc = Location.none; txt = Ldot (Lident "React", "null")}
);
])
in
let is_cap str = String.capitalize_ascii str = str in
let ident ~suffix =
match module_path with
| Lident _ -> Ldot (module_path, suffix)
| Ldot (_modulePath, value) as full_path when is_cap value ->
Ldot (full_path, suffix)
| module_path -> module_path
in
let is_empty_record {pexp_desc} =
match pexp_desc with
| Pexp_record (label_decls, _) when List.length label_decls = 0 -> true
| _ -> false
in
(* handle key, ref, children *)
(* React.createElement(Component.make, props, ...children) *)
let record = record_from_props ~loc:jsx_expr_loc ~remove_key:true args in
let props =
if is_empty_record record then empty_record ~loc:jsx_expr_loc else record
in
let key_prop =
args |> List.filter (fun (arg_label, _) -> "key" = get_label arg_label)
in
let make_i_d =
Exp.ident ~loc:call_expr_loc
{txt = ident ~suffix:"make"; loc = call_expr_loc}
in
match config.mode with
(* The new jsx transform *)
| "automatic" ->
let jsx_expr, key_and_unit =
match (!children_arg, key_prop) with
| None, key :: _ ->
( Exp.ident
{loc = Location.none; txt = module_access_name config "jsxKeyed"},
[key; (nolabel, unit_expr ~loc:Location.none)] )
| None, [] ->
( Exp.ident {loc = Location.none; txt = module_access_name config "jsx"},
[] )
| Some _, key :: _ ->
( Exp.ident
{loc = Location.none; txt = module_access_name config "jsxsKeyed"},
[key; (nolabel, unit_expr ~loc:Location.none)] )
| Some _, [] ->
( Exp.ident {loc = Location.none; txt = module_access_name config "jsxs"},
[] )
in
Exp.apply ~loc:jsx_expr_loc ~attrs jsx_expr
([(nolabel, make_i_d); (nolabel, props)] @ key_and_unit)
| _ -> (
match (!children_arg, key_prop) with
| None, key :: _ ->
Exp.apply ~loc:jsx_expr_loc ~attrs
(Exp.ident
{
loc = Location.none;
txt = Ldot (Lident "JsxPPXReactSupport", "createElementWithKey");
})
[key; (nolabel, make_i_d); (nolabel, props)]
| None, [] ->
Exp.apply ~loc:jsx_expr_loc ~attrs
(Exp.ident
{loc = Location.none; txt = Ldot (Lident "React", "createElement")})
[(nolabel, make_i_d); (nolabel, props)]
| Some children, key :: _ ->
Exp.apply ~loc:jsx_expr_loc ~attrs
(Exp.ident
{
loc = Location.none;
txt =
Ldot (Lident "JsxPPXReactSupport", "createElementVariadicWithKey");
})
[key; (nolabel, make_i_d); (nolabel, props); (nolabel, children)]
| Some children, [] ->
Exp.apply ~loc:jsx_expr_loc ~attrs
(Exp.ident
{
loc = Location.none;
txt = Ldot (Lident "React", "createElementVariadic");
})
[(nolabel, make_i_d); (nolabel, props); (nolabel, children)])
let transform_lowercase_call3 ~config mapper jsx_expr_loc call_expr_loc attrs
call_arguments id =
let component_name_expr = constant_string ~loc:call_expr_loc id in
match config.Jsx_common.mode with
(* the new jsx transform *)
| "automatic" ->
let element_binding =
match config.module_ |> String.lowercase_ascii with
| "react" -> Lident "ReactDOM"
| _generic -> module_access_name config "Elements"
in
let children, non_children_props =
extract_children ~remove_last_position_unit:true ~loc:jsx_expr_loc
call_arguments
in
let args_for_make = non_children_props in
let children_expr = transform_children_if_list_upper ~mapper children in
let recursively_transformed_args_for_make =
args_for_make
|> List.map (fun (label, expression) ->
(label, mapper.expr mapper expression))
in
let children_arg = ref None in
let args =
recursively_transformed_args_for_make
@
match children_expr with
| Exact children ->
[
( labelled "children",
Exp.apply ~attrs:optional_attrs
(Exp.ident
{
txt = Ldot (element_binding, "someElement");
loc = Location.none;
})
[(Nolabel, children)] );
]
| ListLiteral {pexp_desc = Pexp_array list} when list = [] -> []
| ListLiteral expression ->
(* this is a hack to support react components that introspect into their children *)
children_arg := Some expression;
[
( labelled "children",
Exp.apply
(Exp.ident
{txt = module_access_name config "array"; loc = Location.none})
[(Nolabel, expression)] );
]
in
let is_empty_record {pexp_desc} =
match pexp_desc with
| Pexp_record (label_decls, _) when List.length label_decls = 0 -> true
| _ -> false
in
let record = record_from_props ~loc:jsx_expr_loc ~remove_key:true args in
let props =
if is_empty_record record then empty_record ~loc:jsx_expr_loc else record
in
let key_prop =
args |> List.filter (fun (arg_label, _) -> "key" = get_label arg_label)
in
let jsx_expr, key_and_unit =
match (!children_arg, key_prop) with
| None, key :: _ ->
( Exp.ident
{loc = Location.none; txt = Ldot (element_binding, "jsxKeyed")},
[key; (nolabel, unit_expr ~loc:Location.none)] )
| None, [] ->
( Exp.ident {loc = Location.none; txt = Ldot (element_binding, "jsx")},
[] )
| Some _, key :: _ ->
( Exp.ident
{loc = Location.none; txt = Ldot (element_binding, "jsxsKeyed")},
[key; (nolabel, unit_expr ~loc:Location.none)] )
| Some _, [] ->
( Exp.ident {loc = Location.none; txt = Ldot (element_binding, "jsxs")},
[] )
in
Exp.apply ~loc:jsx_expr_loc ~attrs jsx_expr
([(nolabel, component_name_expr); (nolabel, props)] @ key_and_unit)
| _ ->
let children, non_children_props =
extract_children ~loc:jsx_expr_loc call_arguments
in
let children_expr = transform_children_if_list ~mapper children in
let create_element_call =
match children with
(* [@JSX] div(~children=[a]), coming from <div> a </div> *)
| {
pexp_desc =
( Pexp_construct ({txt = Lident "::"}, Some {pexp_desc = Pexp_tuple _})
| Pexp_construct ({txt = Lident "[]"}, None) );
} ->
"createDOMElementVariadic"
(* [@JSX] div(~children= value), coming from <div> ...(value) </div> *)
| {pexp_loc} ->
Jsx_common.raise_error ~loc:pexp_loc
"A spread as a DOM element's children don't make sense written \
together. You can simply remove the spread."
in
let args =
match non_children_props with
| [_justTheUnitArgumentAtEnd] ->
[
(* "div" *)
(nolabel, component_name_expr);
(* [|moreCreateElementCallsHere|] *)
(nolabel, children_expr);
]
| non_empty_props ->
let props_record =
record_from_props ~loc:Location.none ~remove_key:false non_empty_props
in
[
(* "div" *)
(nolabel, component_name_expr);
(* ReactDOM.domProps(~className=blabla, ~foo=bar, ()) *)
(labelled "props", props_record);
(* [|moreCreateElementCallsHere|] *)
(nolabel, children_expr);
]
in
Exp.apply ~loc:jsx_expr_loc ~attrs
(* ReactDOM.createElement *)
(Exp.ident
{
loc = Location.none;
txt = Ldot (Lident "ReactDOM", create_element_call);
})
args
let rec recursively_transform_named_args_for_make expr args newtypes core_type =
match expr.pexp_desc with
(* TODO: make this show up with a loc. *)
| Pexp_fun (Labelled "key", _, _, _) | Pexp_fun (Optional "key", _, _, _) ->
Jsx_common.raise_error ~loc:expr.pexp_loc
"Key cannot be accessed inside of a component. Don't worry - you can \
always key a component from its parent!"
| Pexp_fun (Labelled "ref", _, _, _) | Pexp_fun (Optional "ref", _, _, _) ->
Jsx_common.raise_error ~loc:expr.pexp_loc
"Ref cannot be passed as a normal prop. Please use `forwardRef` API \
instead."
| Pexp_fun (arg, default, pattern, expression)
when is_optional arg || is_labelled arg ->
let () =
match (is_optional arg, pattern, default) with
| true, {ppat_desc = Ppat_constraint (_, {ptyp_desc})}, None -> (
match ptyp_desc with
| Ptyp_constr ({txt = Lident "option"}, [_]) -> ()
| _ ->
let current_type =
match ptyp_desc with
| Ptyp_constr ({txt}, []) ->
String.concat "." (Longident.flatten txt)
| Ptyp_constr ({txt}, _innerTypeArgs) ->
String.concat "." (Longident.flatten txt) ^ "(...)"
| _ -> "..."
in
Location.prerr_warning pattern.ppat_loc
(Preprocessor
(Printf.sprintf
"React: optional argument annotations must have explicit \
`option`. Did you mean `option<%s>=?`?"
current_type)))
| _ -> ()
in
let alias =
match pattern with
| {
ppat_desc =
( Ppat_alias (_, {txt})
| Ppat_var {txt}
| Ppat_constraint ({ppat_desc = Ppat_var {txt}}, _) );
} ->
txt
| {ppat_desc = Ppat_any} -> "_"
| _ -> get_label arg
in
let type_ =
match pattern with
| {ppat_desc = Ppat_constraint (_, {ptyp_desc = Ptyp_package _})} -> None
| {ppat_desc = Ppat_constraint (_, type_)} -> Some type_
| _ -> None
in
recursively_transform_named_args_for_make expression
((arg, default, pattern, alias, pattern.ppat_loc, type_) :: args)
newtypes core_type
| Pexp_fun
( Nolabel,
_,
{ppat_desc = Ppat_construct ({txt = Lident "()"}, _) | Ppat_any},
_expression ) ->
(args, newtypes, core_type)
| Pexp_fun
( Nolabel,
_,
({
ppat_desc =
Ppat_var {txt} | Ppat_constraint ({ppat_desc = Ppat_var {txt}}, _);
} as pattern),
_expression ) ->
if txt = "ref" then
let type_ =
match pattern with
| {ppat_desc = Ppat_constraint (_, type_)} -> Some type_
| _ -> None
in
(* The ref arguement of forwardRef should be optional *)
( (Optional "ref", None, pattern, txt, pattern.ppat_loc, type_) :: args,
newtypes,
core_type )
else (args, newtypes, core_type)
| Pexp_fun (Nolabel, _, pattern, _expression) ->
Location.raise_errorf ~loc:pattern.ppat_loc
"React: react.component refs only support plain arguments and type \
annotations."
| Pexp_newtype (label, expression) ->
recursively_transform_named_args_for_make expression args
(label :: newtypes) core_type
| Pexp_constraint (expression, core_type) ->
recursively_transform_named_args_for_make expression args newtypes
(Some core_type)
| _ -> (args, newtypes, core_type)
let arg_to_type types
((name, default, {ppat_attributes = attrs}, _alias, loc, type_) :
arg_label * expression option * pattern * label * 'loc * core_type option)
=
match (type_, name, default) with
| Some type_, name, _ when is_optional name ->
(true, get_label name, attrs, loc, type_) :: types
| Some type_, name, _ -> (false, get_label name, attrs, loc, type_) :: types
| None, name, _ when is_optional name ->
(true, get_label name, attrs, loc, Typ.any ~loc ()) :: types
| None, name, _ when is_labelled name ->
(false, get_label name, attrs, loc, Typ.any ~loc ()) :: types
| _ -> types
let has_default_value name_arg_list =
name_arg_list
|> List.exists (fun (name, default, _, _, _, _) ->
Option.is_some default && is_optional name)
let arg_to_concrete_type types (name, attrs, loc, type_) =
match name with
| name when is_labelled name ->
(false, get_label name, attrs, loc, type_) :: types
| name when is_optional name ->
(true, get_label name, attrs, loc, type_) :: types
| _ -> types
let check_string_int_attribute_iter =
let attribute _ ({txt; loc}, _) =
if txt = "string" || txt = "int" then
Jsx_common.raise_error ~loc
"@string and @int attributes not supported. See \
https://github.com/rescript-lang/rescript-compiler/issues/5724"
in
{Ast_iterator.default_iterator with attribute}
let check_multiple_components ~config ~loc =
(* If there is another component, throw error *)
if config.Jsx_common.has_component then
Jsx_common.raise_error_multiple_component ~loc
else config.has_component <- true
let modified_binding_old binding =
let expression = binding.pvb_expr in
(* TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse *)
let rec spelunk_for_fun_expression expression =
match expression with
(* let make = (~prop) => ... *)
| {pexp_desc = Pexp_fun _} | {pexp_desc = Pexp_newtype _} -> expression
(* let make = {let foo = bar in (~prop) => ...} *)
| {pexp_desc = Pexp_let (_recursive, _vbs, return_expression)} ->
(* here's where we spelunk! *)
spelunk_for_fun_expression return_expression
(* let make = React.forwardRef((~prop) => ...) *)
| {
pexp_desc =
Pexp_apply (_wrapperExpression, [(Nolabel, inner_function_expression)]);
} ->
spelunk_for_fun_expression inner_function_expression
| {
pexp_desc = Pexp_sequence (_wrapperExpression, inner_function_expression);
} ->
spelunk_for_fun_expression inner_function_expression
| {pexp_desc = Pexp_constraint (inner_function_expression, _typ)} ->
spelunk_for_fun_expression inner_function_expression
| {pexp_loc} ->
Jsx_common.raise_error ~loc:pexp_loc
"JSX component calls can only be on function definitions or component \
wrappers (forwardRef, memo)."
in
spelunk_for_fun_expression expression
let modified_binding ~binding_loc ~binding_pat_loc ~fn_name binding =
let has_application = ref false in
let wrap_expression_with_binding expression_fn expression =
Vb.mk ~loc:binding_loc ~attrs:binding.pvb_attributes
(Pat.var ~loc:binding_pat_loc {loc = binding_pat_loc; txt = fn_name})
(expression_fn expression)
in
let expression = binding.pvb_expr in
(* TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse *)
let rec spelunk_for_fun_expression expression =
match expression with
(* let make = (~prop) => ... with no final unit *)
| {
pexp_desc =
Pexp_fun
( ((Labelled _ | Optional _) as label),
default,
pattern,
({pexp_desc = Pexp_fun _} as internal_expression) );
} ->
let wrap, has_forward_ref, exp =
spelunk_for_fun_expression internal_expression
in
( wrap,
has_forward_ref,
{expression with pexp_desc = Pexp_fun (label, default, pattern, exp)} )
(* let make = (()) => ... *)
(* let make = (_) => ... *)
| {
pexp_desc =
Pexp_fun
( Nolabel,
_default,
{ppat_desc = Ppat_construct ({txt = Lident "()"}, _) | Ppat_any},
_internalExpression );
} ->
((fun a -> a), false, expression)
(* let make = (~prop) => ... *)
| {
pexp_desc =
Pexp_fun
((Labelled _ | Optional _), _default, _pattern, _internalExpression);
} ->
((fun a -> a), false, expression)
(* let make = (prop) => ... *)
| {pexp_desc = Pexp_fun (_nolabel, _default, pattern, _internalExpression)}
->
if !has_application then ((fun a -> a), false, expression)
else
Location.raise_errorf ~loc:pattern.ppat_loc
"React: props need to be labelled arguments.\n\
\ If you are working with refs be sure to wrap with React.forwardRef.\n\
\ If your component doesn't have any props use () or _ instead of a \
name."
(* let make = {let foo = bar in (~prop) => ...} *)
| {pexp_desc = Pexp_let (recursive, vbs, internal_expression)} ->
(* here's where we spelunk! *)
let wrap, has_forward_ref, exp =
spelunk_for_fun_expression internal_expression
in
( wrap,
has_forward_ref,
{expression with pexp_desc = Pexp_let (recursive, vbs, exp)} )
(* let make = React.forwardRef((~prop) => ...) *)
| {
pexp_desc =
Pexp_apply (wrapper_expression, [(Nolabel, internal_expression)]);
} ->
let () = has_application := true in
let _, _, exp = spelunk_for_fun_expression internal_expression in
let has_forward_ref = is_forward_ref wrapper_expression in
( (fun exp -> Exp.apply wrapper_expression [(nolabel, exp)]),
has_forward_ref,
exp )
| {pexp_desc = Pexp_sequence (wrapper_expression, internal_expression)} ->
let wrap, has_forward_ref, exp =
spelunk_for_fun_expression internal_expression
in
( wrap,
has_forward_ref,
{expression with pexp_desc = Pexp_sequence (wrapper_expression, exp)} )
| e -> ((fun a -> a), false, e)
in
let wrap_expression, has_forward_ref, expression =
spelunk_for_fun_expression expression
in
(wrap_expression_with_binding wrap_expression, has_forward_ref, expression)
let vb_match ~expr (name, default, _, alias, loc, _) =
let label = get_label name in
match default with
| Some default ->
let value_binding =
Vb.mk
(Pat.var (Location.mkloc alias loc))
(Exp.match_
(Exp.ident {txt = Lident ("__" ^ alias); loc = Location.none})
[
Exp.case
(Pat.construct
(Location.mknoloc @@ Lident "Some")
(Some (Pat.var (Location.mknoloc label))))
(Exp.ident (Location.mknoloc @@ Lident label));
Exp.case
(Pat.construct (Location.mknoloc @@ Lident "None") None)
default;
])
in
Exp.let_ Nonrecursive [value_binding] expr
| None -> expr
let vb_match_expr named_arg_list expr =
let rec aux named_arg_list =
match named_arg_list with
| [] -> expr
| named_arg :: rest -> vb_match named_arg ~expr:(aux rest)
in
aux (List.rev named_arg_list)
let vb_type_annotation ~expr (name, default, pattern, alias, loc, core_type) =
let label = get_label name in
let pattern_name =
match default with
| Some _ -> "__" ^ alias
| None -> alias
in
let value_binding =
Vb.mk ~loc
(match pattern with
| {
ppat_desc =
Ppat_constraint (pattern, ({ptyp_desc = Ptyp_package _} as type_));
} ->
(* Handle pattern: ~comp as module(Comp: Comp) *)
Pat.record
[
( {txt = Lident label; loc = Location.none},
Pat.constraint_ pattern type_ );
]
Closed
| _ -> (
(* For other cases, use regular variable pattern with type constraint *)
let type_ =
match pattern with
| {ppat_desc = Ppat_constraint (_, type_)} -> Some type_
| _ -> core_type
in
match type_ with
| Some type_ ->
Pat.constraint_ (Pat.var (Location.mkloc pattern_name loc)) type_
| None -> Pat.var (Location.mkloc pattern_name loc)))
(match pattern with
| {ppat_desc = Ppat_constraint (_, {ptyp_desc = Ptyp_package _})} ->
(* For module types, use props directly *)
Exp.ident {txt = Lident "props"; loc = Location.none}
| _ ->
(* For other cases, use props.x form *)
Exp.field
(Exp.ident {txt = Lident "props"; loc = Location.none})
{txt = Lident label; loc = Location.none})
in
Exp.let_ Nonrecursive [value_binding] expr
let vb_type_annotations_expr named_arg_list expr =
let rec aux named_arg_list =
match named_arg_list with
| [] -> expr
| ((name, _, _, _, _, _) as named_arg) :: rest ->
let label = get_label name in
if label = "ref" then aux rest
else vb_type_annotation named_arg ~expr:(aux rest)
in
aux (List.rev named_arg_list)
let map_binding ~config ~empty_loc ~pstr_loc ~file_name ~rec_flag binding =
if Jsx_common.has_attr_on_binding binding then (
check_multiple_components ~config ~loc:pstr_loc;
let binding = Jsx_common.remove_arity binding in
let core_type_of_attr =
Jsx_common.core_type_of_attrs binding.pvb_attributes
in
let typ_vars_of_core_type =
core_type_of_attr
|> Option.map Jsx_common.typ_vars_of_core_type
|> Option.value ~default:[]
in
let binding_loc = binding.pvb_loc in
let binding_pat_loc = binding.pvb_pat.ppat_loc in
let binding =
{
binding with
pvb_pat = {binding.pvb_pat with ppat_loc = empty_loc};
pvb_loc = empty_loc;
pvb_attributes = binding.pvb_attributes |> List.filter other_attrs_pure;
}
in
let fn_name = get_fn_name binding.pvb_pat in