-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathjsx_v4.ml
More file actions
1380 lines (1320 loc) · 50 KB
/
jsx_v4.ml
File metadata and controls
1380 lines (1320 loc) · 50 KB
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 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 {txt = str} | Labelled {txt = str} -> str
| Nolabel -> ""
let constant_string ~loc str =
Ast_helper.Exp.constant ~loc (Pconst_string (str, 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]
let jsx_element_type config ~loc =
Typ.constr ~loc {loc; txt = module_access_name config "element"} []
(* 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" | "react.componentWithProps"
| "jsx.componentWithProps" ->
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 = [];
}
| {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
(* 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 {txt = label; loc = Location.none})))
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 {txt = label; loc = Location.none})
else
Type.field ~loc ~attrs {txt = label; loc}
(Typ.var @@ safe_type_from_value
@@ Labelled {txt = label; loc = Location.none}))
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 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 {arg_label = Labelled {txt = "key"} | Optional {txt = "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 {arg_label = arg; default; lhs = pattern; rhs = 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
{
arg_label = Nolabel;
lhs = {ppat_desc = Ppat_construct ({txt = Lident "()"}, _) | Ppat_any};
} ->
(args, newtypes, core_type)
| Pexp_fun
{
arg_label = Nolabel;
lhs =
{
ppat_desc =
Ppat_var {txt} | Ppat_constraint ({ppat_desc = Ppat_var {txt}}, _);
} as pattern;
} ->
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 {txt = "ref"; loc = Location.none},
None,
pattern,
txt,
pattern.ppat_loc,
type_ )
:: args,
newtypes,
core_type )
else (args, newtypes, core_type)
| Pexp_fun {arg_label = Nolabel; lhs = pattern} ->
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 {args = [(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
({
arg_label = Labelled _ | Optional _;
rhs = {pexp_desc = Pexp_fun _} as internal_expression;
} as f);
} ->
let wrap, has_forward_ref, exp =
spelunk_for_fun_expression internal_expression
in
( wrap,
has_forward_ref,
{expression with pexp_desc = Pexp_fun {f with rhs = exp}} )
(* let make = (()) => ... *)
(* let make = (_) => ... *)
| {
pexp_desc =
Pexp_fun
{
arg_label = Nolabel;
lhs =
{ppat_desc = Ppat_construct ({txt = Lident "()"}, _) | Ppat_any};
};
} ->
((fun a -> a), false, expression)
(* let make = (~prop) => ... *)
| {pexp_desc = Pexp_fun {arg_label = Labelled _ | Optional _}} ->
((fun a -> a), false, expression)
(* let make = (prop) => ... *)
| {pexp_desc = Pexp_fun {lhs = pattern}} ->
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
{funct = wrapper_expression; args = [(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 map_binding ~config ~empty_loc ~pstr_loc ~file_name ~rec_flag binding =
(* Traverse the component body and force every reachable return expression to
be annotated as `Jsx.element`. This walks through the wrapper constructs the
PPX introduces (fun/newtype/let/sequence) so that the constraint ends up on
the real return position even after we rewrite the function. *)
let rec constrain_jsx_return expr =
let jsx_element_constraint expr =
Exp.constraint_ expr (jsx_element_type config ~loc:expr.pexp_loc)
in
match expr.pexp_desc with
| Pexp_fun ({rhs} as desc) ->
{
expr with
pexp_desc = Pexp_fun {desc with rhs = constrain_jsx_return rhs};
}
| Pexp_newtype (param, inner) ->
{expr with pexp_desc = Pexp_newtype (param, constrain_jsx_return inner)}
| Pexp_constraint (inner, _) ->
let constrained_inner = constrain_jsx_return inner in
jsx_element_constraint constrained_inner
| Pexp_let (rec_flag, bindings, body) ->
{
expr with
pexp_desc = Pexp_let (rec_flag, bindings, constrain_jsx_return body);
}
| Pexp_sequence (first, second) ->
{expr with pexp_desc = Pexp_sequence (first, constrain_jsx_return second)}
| _ -> jsx_element_constraint expr
in
if Jsx_common.has_attr_on_binding Jsx_common.has_attr binding then (
check_multiple_components ~config ~loc:pstr_loc;
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
let internal_fn_name = fn_name ^ "$Internal" in
let full_module_name =
make_module_name file_name config.nested_modules fn_name
in
let binding_wrapper, has_forward_ref, expression =
modified_binding ~binding_loc ~binding_pat_loc ~fn_name binding
in
let is_async = Ast_async.dig_async_payload_from_function binding.pvb_expr in
let named_arg_list, newtypes, _typeConstraints =
recursively_transform_named_args_for_make
(modified_binding_old binding)
[] [] None
in
let named_type_list = List.fold_left arg_to_type [] named_arg_list in
(* type props = { ... } *)
let props_record_type =
make_props_record_type ~core_type_of_attr ~external_:false
~typ_vars_of_core_type "props" pstr_loc named_type_list
in
let inner_expression =
Exp.apply
(Exp.ident
(Location.mknoloc
@@ Lident
(match rec_flag with
| Recursive -> internal_fn_name
| Nonrecursive -> fn_name)))
([(Nolabel, Exp.ident (Location.mknoloc @@ Lident "props"))]
@
match has_forward_ref with
| true -> [(Nolabel, Exp.ident (Location.mknoloc @@ Lident "ref"))]
| false -> [])
in
let make_props_pattern = function
| [] -> Pat.var @@ Location.mknoloc "props"
| _ ->
Pat.constraint_
(Pat.var @@ Location.mknoloc "props")
(Typ.constr (Location.mknoloc @@ Lident "props") [Typ.any ()])
in
let inner_expression =
Jsx_common.async_component ~async:is_async inner_expression
in
let full_expression =
(* React component name should start with uppercase letter *)
(* let make = { let \"App" = props => make(props); \"App" } *)
(* let make = React.forwardRef({
let \"App" = (props, ref) => make({...props, ref: @optional (Js.Nullabel.toOption(ref))})
})*)
let total_arity = if has_forward_ref then 2 else 1 in
Exp.fun_ ~arity:(Some total_arity) Nolabel None
(match core_type_of_attr with
| None -> make_props_pattern named_type_list
| Some _ -> make_props_pattern typ_vars_of_core_type)
(if has_forward_ref then
Exp.fun_ ~arity:None Nolabel None
(Pat.var @@ Location.mknoloc "ref")
inner_expression
else inner_expression)
~attrs:binding.pvb_expr.pexp_attributes
in
let full_expression =
match full_module_name with
| "" -> full_expression
| txt ->
Exp.let_ Nonrecursive
[
Vb.mk ~loc:empty_loc
(Pat.var ~loc:empty_loc {loc = empty_loc; txt})
full_expression;
]
(Exp.ident ~loc:pstr_loc {loc = empty_loc; txt = Lident txt})
in
let rec strip_constraint_unpack ~label pattern =
match pattern with
| {ppat_desc = Ppat_constraint (_, {ptyp_desc = Ptyp_package _})} ->
pattern
| {ppat_desc = Ppat_constraint (pattern, _)} ->
strip_constraint_unpack ~label pattern
| _ -> pattern
in
let safe_pattern_label pattern =
match pattern with
| {ppat_desc = Ppat_var {txt; loc}} ->
{pattern with ppat_desc = Ppat_var {txt = "__" ^ txt; loc}}
| {ppat_desc = Ppat_alias (p, {txt; loc})} ->
{pattern with ppat_desc = Ppat_alias (p, {txt = "__" ^ txt; loc})}
| _ -> pattern
in
let rec returned_expression patterns_with_label patterns_with_nolabel
({pexp_desc} as expr) =
match pexp_desc with
| Pexp_newtype (_, expr) ->
returned_expression patterns_with_label patterns_with_nolabel expr
| Pexp_constraint (expr, _) ->
returned_expression patterns_with_label patterns_with_nolabel expr
| Pexp_fun
{
lhs = {ppat_desc = Ppat_construct ({txt = Lident "()"}, _)};
rhs = expr;
} ->
(patterns_with_label, patterns_with_nolabel, expr)
| Pexp_fun
{
arg_label;
default;
lhs = {ppat_loc; ppat_desc} as pattern;
rhs = expr;
} -> (
let pattern_without_constraint =
strip_constraint_unpack ~label:(get_label arg_label) pattern
in
(*
If prop has the default value as Ident, it will get a build error
when the referenced Ident value and the prop have the same name.
So we add a "__" to label to resolve the build error.
*)
let pattern_with_safe_label =
match default with
| Some _ -> safe_pattern_label pattern_without_constraint
| _ -> pattern_without_constraint
in
if is_labelled arg_label || is_optional arg_label then
returned_expression
({
lid = {loc = ppat_loc; txt = Lident (get_label arg_label)};
x =
{
pattern_with_safe_label with
ppat_attributes = pattern.ppat_attributes;
};
opt = is_optional arg_label;
}
:: patterns_with_label)
patterns_with_nolabel expr
else
(* Special case of nolabel arg "ref" in forwardRef fn *)
(* let make = React.forwardRef(ref => body) *)
match ppat_desc with
| Ppat_var {txt} | Ppat_constraint ({ppat_desc = Ppat_var {txt}}, _)
->
returned_expression patterns_with_label
(( {loc = ppat_loc; txt = Lident txt},
{pattern with ppat_attributes = pattern.ppat_attributes},
true )
:: patterns_with_nolabel)
expr
| _ ->
returned_expression patterns_with_label patterns_with_nolabel expr)
| _ -> (patterns_with_label, patterns_with_nolabel, expr)
in
let patterns_with_label, patterns_with_nolabel, expression =
returned_expression [] [] expression
in
(* add pattern matching for optional prop value *)
let expression =
if has_default_value named_arg_list then
vb_match_expr named_arg_list expression
else expression
in
let expression = constrain_jsx_return expression in
(* (ref) => expr *)
let expression =
List.fold_left
(fun expr (_, pattern, _opt) ->
let pattern =
match pattern.ppat_desc with
| Ppat_var {txt} when txt = "ref" ->
Pat.constraint_ pattern (ref_type Location.none)
| _ -> pattern
in
Exp.fun_ ~arity:None Nolabel None pattern expr)
expression patterns_with_nolabel
in
(* ({a, b, _}: props<'a, 'b>) *)
let record_pattern =
match patterns_with_label with
| [] -> Pat.any ()
| _ -> Pat.record (List.rev patterns_with_label) Open
in
let expression =
(* Shape internal implementation to match wrapper: uncurried when using forwardRef. *)
let total_arity = if has_forward_ref then 2 else 1 in
Exp.fun_ ~arity:(Some total_arity) ~async:is_async Nolabel None
(Pat.constraint_ record_pattern
(Typ.constr ~loc:empty_loc
{txt = Lident "props"; loc = empty_loc}
(match core_type_of_attr with
| None ->
make_props_type_params ~strip_explicit_option:true
~strip_explicit_js_nullable_of_ref:has_forward_ref
named_type_list
| Some _ -> (
match typ_vars_of_core_type with
| [] -> []
| _ -> [Typ.any ()]))))
expression
in
let expression =
(* Add new tupes (type a,b,c) to make's definition *)
newtypes
|> List.fold_left (fun e newtype -> Exp.newtype newtype e) expression
in
(* let make = ({id, name, ...}: props<'id, 'name, ...>) => { ... } *)
let binding, new_binding =
match rec_flag with
| Recursive ->
( binding_wrapper
(Exp.let_ ~loc:empty_loc Nonrecursive
[make_new_binding binding expression internal_fn_name]
(Exp.let_ ~loc:empty_loc Nonrecursive
[
Vb.mk
(Pat.var {loc = empty_loc; txt = fn_name})
full_expression;
]
(Exp.ident {loc = empty_loc; txt = Lident fn_name}))),
None )
| Nonrecursive ->
( {
binding with
pvb_expr = expression;
pvb_pat = Pat.var {txt = fn_name; loc = Location.none};
},
Some (binding_wrapper full_expression) )
in
(Some props_record_type, binding, new_binding))
else if Jsx_common.has_attr_on_binding Jsx_common.has_attr_with_props binding
then
let modified_binding =
{
binding with
pvb_attributes = binding.pvb_attributes |> List.filter other_attrs_pure;
}
in
let fn_name = get_fn_name modified_binding.pvb_pat in
let internal_fn_name = fn_name ^ "$Internal" in
let full_module_name =
make_module_name file_name config.nested_modules fn_name
in
let is_async =
Ast_async.dig_async_payload_from_function modified_binding.pvb_expr
in
let make_new_binding ~loc ~full_module_name binding =
let props_pattern =
match binding.pvb_expr with
| {
pexp_desc =
Pexp_apply {funct = wrapper_expr; args = [(Nolabel, func_expr)]};
}
when is_forward_ref wrapper_expr ->
(* Case when using React.forwardRef *)
let rec check_invalid_forward_ref expr =
match expr.pexp_desc with
| Pexp_fun {arg_label = Labelled _ | Optional _} ->
Location.raise_errorf ~loc:expr.pexp_loc
"Components using React.forwardRef cannot use \
@react.componentWithProps. Use @react.component instead."
| Pexp_fun {arg_label = Nolabel; rhs = body} ->
check_invalid_forward_ref body
| _ -> ()
in
check_invalid_forward_ref func_expr;
Pat.var {txt = "props"; loc}
| {pexp_desc = Pexp_fun {lhs = {ppat_desc = Ppat_constraint (_, typ)}}}
-> (
match typ with
| {ptyp_desc = Ptyp_constr ({txt = Lident "props"}, args)} ->
(* props<_> *)
if List.length args > 0 then
Pat.constraint_
(Pat.var {txt = "props"; loc})
(Typ.constr {txt = Lident "props"; loc} [Typ.any ()])
(* props *)
else
Pat.constraint_
(Pat.var {txt = "props"; loc})
(Typ.constr {txt = Lident "props"; loc} [])
| _ -> Pat.var {txt = "props"; loc})
| _ -> Pat.var {txt = "props"; loc}
in
let applied_expression =
Exp.apply
(Exp.ident
{
txt =
Lident
(match rec_flag with
| Recursive -> internal_fn_name
| Nonrecursive -> fn_name);
loc;
})
[(Nolabel, Exp.ident {txt = Lident "props"; loc})]
in
let applied_expression =
Jsx_common.async_component ~async:is_async applied_expression
in
let applied_expression = constrain_jsx_return applied_expression in
let wrapper_expr =
Exp.fun_ ~arity:(Some 1) Nolabel None props_pattern
~attrs:binding.pvb_expr.pexp_attributes applied_expression
in
let internal_expression =
Exp.let_ Nonrecursive
[Vb.mk (Pat.var {txt = full_module_name; loc}) wrapper_expr]
(Exp.ident {txt = Lident full_module_name; loc})
in
Vb.mk ~attrs:modified_binding.pvb_attributes
(Pat.var {txt = fn_name; loc})
internal_expression
in
let new_binding =
match rec_flag with
| Recursive -> None
| Nonrecursive ->
Some
(make_new_binding ~loc:empty_loc ~full_module_name modified_binding)
in
let binding_expr =
{
binding.pvb_expr with
(* moved to wrapper_expr *)
pexp_attributes = [];
}
in
( None,
{
binding with
pvb_attributes = binding.pvb_attributes |> List.filter other_attrs_pure;
pvb_expr = binding_expr |> constrain_jsx_return;
},
new_binding )
else (None, binding, None)
let rec collect_prop_types types {ptyp_loc; ptyp_desc} =
match ptyp_desc with
| Ptyp_arrow {arg; ret = {ptyp_desc = Ptyp_arrow _} as rest}
when is_labelled arg.lbl || is_optional arg.lbl ->
collect_prop_types ((arg.lbl, arg.attrs, ptyp_loc, arg.typ) :: types) rest
| Ptyp_arrow {arg = {lbl = Nolabel}; ret} -> collect_prop_types types ret
| Ptyp_arrow {arg; ret = return_value}
when is_labelled arg.lbl || is_optional arg.lbl ->
(arg.lbl, arg.attrs, return_value.ptyp_loc, arg.typ) :: types
| _ -> types
let transform_structure_item ~config item =
match item with
(* external *)
| {
pstr_loc;
pstr_desc =
Pstr_primitive ({pval_attributes; pval_type} as value_description);
} as pstr -> (
match
( List.filter Jsx_common.has_attr pval_attributes,
List.filter Jsx_common.has_attr_with_props pval_attributes )
with
| [], [] -> [item]
| _, [_] ->
Jsx_common.raise_error ~loc:pstr_loc
"Components cannot be defined as externals when using \
@react.componentWithProps.\n\n\
If you intended to define an external for a React component using a \
props type,\n\
use the type React.component<props> instead.\n\
Alternatively, use @react.component for an external definition with \
labeled arguments."
| [_], [] ->
check_multiple_components ~config ~loc:pstr_loc;
check_string_int_attribute_iter.structure_item
check_string_int_attribute_iter item;
let core_type_of_attr = Jsx_common.core_type_of_attrs pval_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 prop_types = collect_prop_types [] pval_type in
let named_type_list = List.fold_left arg_to_concrete_type [] prop_types in
let ret_props_type =
Typ.constr ~loc:pstr_loc
(Location.mkloc (Lident "props") pstr_loc)
(match core_type_of_attr with
| None -> make_props_type_params named_type_list
| Some _ -> (
match typ_vars_of_core_type with
| [] -> []
| _ -> [Typ.any ()]))
in
(* type props<'x, 'y> = { x: 'x, y?: 'y, ... } *)
let props_record_type =
make_props_record_type ~core_type_of_attr ~external_:true
~typ_vars_of_core_type "props" pstr_loc named_type_list
in
(* can't be an arrow because it will defensively uncurry *)
let new_external_type =
Ptyp_constr
( {loc = pstr_loc; txt = module_access_name config "component"},
[ret_props_type] )
in
let new_structure =
{
pstr with
pstr_desc =
Pstr_primitive
{
value_description with
pval_type = {pval_type with ptyp_desc = new_external_type};
pval_attributes = List.filter other_attrs_pure pval_attributes;
};
}
in
[props_record_type; new_structure]
| _ ->