Source file ast_external_process.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
open Import
module External_arg_spec = Melange_ffi.External_arg_spec
module External_ffi_types = Melange_ffi.External_ffi_types
let variant_unwrap =
let rec variant_can_unwrap_aux (row_fields : row_field list) : bool =
match row_fields with
| [] -> true
| { prf_desc = Rtag (_, true, []); _ } :: rest ->
variant_can_unwrap_aux rest
| { prf_desc = Rtag (_, false, [ _ ]); _ } :: rest ->
variant_can_unwrap_aux rest
| _ :: _ -> false
in
fun (row_fields : row_field list) : bool ->
match row_fields with
| [] -> false
| xs -> variant_can_unwrap_aux xs
let infer_mel_as ~loc row_fields ~allow_no_payload =
let mel_as_type =
List.fold_left
~f:(fun mel_as_type { prf_attributes; prf_loc; _ } ->
match List.filter ~f:Ast_attributes.is_mel_as prf_attributes with
| [] -> mel_as_type
| [ { attr_payload; attr_loc = loc; _ } ] -> (
match
( mel_as_type,
Ast_payload.is_single_string attr_payload,
Ast_payload.is_single_int attr_payload )
with
| (`Nothing | `String), Some _, None -> `String
| (`Nothing | `Int), None, Some _ -> `Int
| (`Nothing | `String | `Int), None, None -> `Nothing
| `String, None, Some _ -> Error.err ~loc Expect_string_literal
| `Int, Some _, None -> Error.err ~loc Expect_int_literal
| _, Some _, Some _ -> assert false)
| _ :: _ -> Error.err ~loc:prf_loc Duplicated_mel_as)
~init:`Nothing row_fields
in
match mel_as_type with
| `Nothing -> External_arg_spec.Nothing
| `String ->
Ast_polyvar.map_row_fields_into_strings row_fields ~loc ~allow_no_payload
| `Int ->
Ast_polyvar.map_row_fields_into_ints row_fields ~loc ~allow_no_payload
let spec_of_ptyp ~(nolabel : bool) (ptyp : core_type) : External_arg_spec.attr =
let ptyp_desc = ptyp.ptyp_desc in
match
Ast_attributes.iter_process_mel_string_int_unwrap_uncurry
ptyp.ptyp_attributes
with
| `String -> (
match ptyp_desc with
| Ptyp_variant (row_fields, Closed, None) ->
Ast_polyvar.map_row_fields_into_strings row_fields ~loc:ptyp.ptyp_loc
~allow_no_payload:false
| _ -> Error.err ~loc:ptyp.ptyp_loc Invalid_mel_string_type)
| `Ignore -> Ignore
| `Int -> (
match ptyp_desc with
| Ptyp_variant (row_fields, Closed, None) ->
Ast_polyvar.map_row_fields_into_ints row_fields ~loc:ptyp.ptyp_loc
~allow_no_payload:false
| _ -> Error.err ~loc:ptyp.ptyp_loc Invalid_mel_int_type)
| `Unwrap -> (
match ptyp_desc with
| Ptyp_variant (row_fields, Closed, _) when variant_unwrap row_fields ->
Unwrap
(infer_mel_as ~loc:ptyp.ptyp_loc row_fields ~allow_no_payload:true)
| _ -> Error.err ~loc:ptyp.ptyp_loc Invalid_mel_unwrap_type)
| `Uncurry opt_arity -> (
let real_arity = Ast_core_type.get_uncurry_arity ptyp in
match (opt_arity, real_arity) with
| Some arity, None -> Fn_uncurry_arity arity
| None, None -> Error.err ~loc:ptyp.ptyp_loc Cannot_infer_arity_by_syntax
| None, Some arity -> Fn_uncurry_arity arity
| Some arity, Some n ->
if n <> arity then
Error.err ~loc:ptyp.ptyp_loc
(Inconsistent_arity { uncurry_attribute = arity; real = n })
else Fn_uncurry_arity arity)
| `Nothing -> (
match ptyp_desc with
| Ptyp_constr ({ txt = Lident "unit"; _ }, []) ->
if nolabel then Extern_unit else Nothing
| Ptyp_variant (row_fields, Closed, None) ->
infer_mel_as ~loc:ptyp.ptyp_loc row_fields ~allow_no_payload:false
| _ -> Nothing)
let const_payload_cst = function
| Ast_attributes.Int i ->
External_arg_spec.Arg_cst (External_arg_spec.cst_int i)
| Str i -> Arg_cst (External_arg_spec.cst_string i)
| Js_literal_str s -> Arg_cst (External_arg_spec.cst_obj_literal s)
let refine_arg_type ~(nolabel : bool) ~has_mel_send (ptyp : core_type) :
External_arg_spec.attr =
match ptyp.ptyp_desc with
| Ptyp_any -> (
match
Ast_attributes.iter_process_mel_string_or_int_as ptyp.ptyp_attributes
with
| None -> spec_of_ptyp ~nolabel ptyp
| Some cst ->
Mel_ast_invariant.warn_discarded_unused_attributes ~has_mel_send
ptyp.ptyp_attributes;
const_payload_cst cst)
| _ ->
spec_of_ptyp ~nolabel ptyp
let refine_obj_arg_type ~(nolabel : bool) (ptyp : core_type) :
External_arg_spec.attr =
match ptyp.ptyp_desc with
| Ptyp_any -> (
match
Ast_attributes.iter_process_mel_string_or_int_as ptyp.ptyp_attributes
with
| None -> Error.err ~loc:ptyp.ptyp_loc Invalid_underscore_type_in_external
| Some cst ->
Mel_ast_invariant.warn_discarded_unused_attributes
ptyp.ptyp_attributes;
const_payload_cst cst)
| _ ->
spec_of_ptyp ~nolabel ptyp
let get_opt_arg_type (ptyp : core_type) : External_arg_spec.attr =
match ptyp.ptyp_desc with
| Ptyp_any ->
Error.err ~loc:ptyp.ptyp_loc Invalid_underscore_type_in_external
| _ ->
spec_of_ptyp ~nolabel:false ptyp
type bundle_source =
[ `Nm_payload of string
| `Nm_external of string lazy_t ]
let string_of_bundle_source (x : bundle_source) =
match x with `Nm_payload x | `Nm_external (lazy x) -> x
type name_source = [ bundle_source | `Nm_na ]
type external_desc = {
external_module_name : External_ffi_types.external_module_name option;
module_as_val : External_ffi_types.external_module_name option;
val_send : name_source;
val_send_pipe : core_type option;
variadic : bool;
scopes : string list;
set_index : bool;
get_index : bool;
new_name : name_source;
call_name : name_source;
set_name : name_source;
get_name : name_source;
mk_obj : bool;
return_wrapper : External_ffi_types.return_wrapper;
}
let init_st =
{
external_module_name = None;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
variadic = false;
scopes = [];
set_index = false;
get_index = false;
new_name = `Nm_na;
call_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
mk_obj = false;
return_wrapper = Return_unset;
}
let return_wrapper loc (txt : string) : External_ffi_types.return_wrapper =
match txt with
| "undefined_to_opt" -> Return_undefined_to_opt
| "null_to_opt" -> Return_null_to_opt
| "nullable" | "null_undefined_to_opt" -> Return_null_undefined_to_opt
| "identity" -> Return_identity
| _ -> Error.err ~loc Not_supported_directive_in_mel_return
exception Not_handled_external_attribute
let parse_external_attributes (prim_name_check : string)
(prim_name_or_pval_prim : bundle_source) (prim_attributes : attribute list)
: attribute list * external_desc =
let name_from_payload_or_prim ~loc (payload : payload) : name_source =
match payload with
| PStr [] -> (prim_name_or_pval_prim :> name_source)
| _ -> (
match Ast_payload.is_single_string payload with
| Some (val_name, _) -> `Nm_payload val_name
| None -> Location.raise_errorf ~loc "Invalid payload")
in
List.fold_left
~f:(fun
(attrs, st)
({ attr_name = { txt; loc }; attr_payload = payload; _ } as attr)
->
let action () =
match txt with
| "mel.module" -> (
match Ast_payload.assert_strings loc payload with
| [ bundle ] ->
{
st with
external_module_name =
Some { bundle; module_bind_name = Phint_nothing };
}
| [ bundle; bind_name ] ->
{
st with
external_module_name =
Some { bundle; module_bind_name = Phint_name bind_name };
}
| [] ->
{
st with
module_as_val =
Some
{
bundle =
string_of_bundle_source
(prim_name_or_pval_prim :> bundle_source);
module_bind_name = Phint_nothing;
};
}
| _ ->
Location.raise_errorf ~loc
"`[%@mel.module ..]' expects, at most, a tuple of two \
strings (module name, variable name)")
| "mel.scope" -> (
match Ast_payload.assert_strings loc payload with
| [] ->
Location.raise_errorf ~loc
"`[%@mel.scope ..]' expects a tuple of strings in its payload"
| scopes -> { st with scopes })
| "mel.variadic" -> { st with variadic = true }
| "mel.send" ->
{ st with val_send = name_from_payload_or_prim ~loc payload }
| "mel.send.pipe" ->
Mel_ast_invariant.warn ~loc Deprecated_send_pipe;
{
st with
val_send_pipe =
(match payload with
| PTyp x -> Some x
| _ ->
Location.raise_errorf ~loc
"expected a type after `[%@mel.send.pipe]', e.g. \
`[%@mel.send.pipe: t]'");
}
| "mel.set" ->
{ st with set_name = name_from_payload_or_prim ~loc payload }
| "mel.get" ->
{ st with get_name = name_from_payload_or_prim ~loc payload }
| "mel.new" ->
{ st with new_name = name_from_payload_or_prim ~loc payload }
| "mel.set_index" ->
if String.length prim_name_check <> 0 then
Location.raise_errorf ~loc
"`%@mel.set_index' requires its `external' payload to be the \
empty string";
{ st with set_index = true }
| "mel.get_index" ->
if String.length prim_name_check <> 0 then
Location.raise_errorf ~loc
"`%@mel.get_index' requires its `external' payload to be the \
empty string";
{ st with get_index = true }
| "mel.obj" -> { st with mk_obj = true }
| "mel.return" -> (
match Ast_payload.ident_or_record_as_config payload with
| Ok [ ({ txt; _ }, None) ] ->
{ st with return_wrapper = return_wrapper loc txt }
| Ok _ -> Error.err ~loc Not_supported_directive_in_mel_return
| Error s -> Location.raise_errorf ~loc "%s" s)
| _ -> raise_notrace Not_handled_external_attribute
in
try (attrs, action ())
with Not_handled_external_attribute -> (attr :: attrs, st))
~init:([], init_st) prim_attributes
let has_mel_uncurry (attrs : attribute list) =
List.exists
~f:(fun { attr_name = { txt; loc = _ }; _ } ->
match txt with "mel.uncurry" -> true | _ -> false)
attrs
let is_user_option ty =
match ty.ptyp_desc with
| Ptyp_constr
({ txt = Lident "option" | Ldot (Lident "*predef*", "option"); _ }, [ _ ])
->
true
| _ -> false
let check_return_wrapper loc (wrapper : External_ffi_types.return_wrapper)
result_type =
match wrapper with
| Return_identity -> wrapper
| Return_unset ->
if Ast_core_type.is_unit result_type then Return_replaced_with_unit
else wrapper
| Return_undefined_to_opt | Return_null_to_opt | Return_null_undefined_to_opt
->
if is_user_option result_type then wrapper
else Error.err ~loc Expect_opt_in_mel_return_to_opt
| Return_replaced_with_unit ->
assert false
type response = {
pval_type : core_type;
pval_prim : string list;
pval_attributes : attributes;
dont_inline_cross_module : bool;
}
type param_type = {
label : Asttypes.arg_label;
ty : core_type;
attrs : attributes;
loc : location;
}
let mk_fn_type (new_arg_types_ty : param_type list) (result : core_type) :
core_type =
List.fold_right
~f:(fun { label; ty; attrs; loc } acc ->
{
ptyp_desc = Ptyp_arrow (label, ty, acc);
ptyp_loc = loc;
ptyp_loc_stack = [ loc ];
ptyp_attributes = attrs;
})
new_arg_types_ty ~init:result
let process_obj (loc : Location.t) (st : external_desc) (prim_name : string)
(arg_types_ty : param_type list) (result_type : core_type) :
core_type * External_ffi_types.t =
match st with
| {
external_module_name = None;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
variadic = false;
new_name = `Nm_na;
call_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
get_index = false;
return_wrapper = Return_unset;
set_index = false;
mk_obj = _;
scopes = [];
} ->
if String.length prim_name > 0 then
Location.raise_errorf ~loc
"`[%@mel.obj]' requires its `external' payload to be the empty string"
else
let arg_kinds, new_arg_types_ty, (result_types : object_field list) =
List.fold_right
~f:(fun
param_type
(arg_labels, (arg_types : param_type list), result_types)
->
let new_arg_label, new_arg_types, output_tys =
let arg_label =
match (param_type.label, param_type.ty.ptyp_desc) with
| Nolabel, _ | _, Ptyp_any -> param_type.label
| _, _ -> (
match
Ast_attributes.iter_process_mel_string_as
param_type.ty.ptyp_attributes
with
| Some name -> (
match param_type.label with
| Labelled _ -> Labelled name
| Optional _ -> Optional name
| Nolabel -> param_type.label)
| None -> param_type.label)
in
let loc = param_type.loc in
let ty = param_type.ty in
match arg_label with
| Nolabel -> (
match ty.ptyp_desc with
| Ptyp_constr ({ txt = Lident "unit"; _ }, []) ->
( External_arg_spec.empty_kind Extern_unit,
param_type :: arg_types,
result_types )
| _ ->
Location.raise_errorf ~loc:ty.ptyp_loc
"`[%@mel.obj]' external declaration arguments must \
be one of:\n\
- a labelled argument\n\
- an optionally labelled argument\n\
- `unit' as the final argument")
| Labelled name -> (
let obj_arg_type = refine_obj_arg_type ~nolabel:false ty in
match obj_arg_type with
| Ignore ->
( External_arg_spec.empty_kind obj_arg_type,
param_type :: arg_types,
result_types )
| Arg_cst _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label = External_arg_spec.Obj_label.obj s;
arg_type = obj_arg_type;
},
arg_types,
result_types )
| Nothing | Unwrap _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label = External_arg_spec.Obj_label.obj s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag { Asttypes.txt = name; loc } ty
:: result_types )
| Int _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label = External_arg_spec.Obj_label.obj s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag
{ Asttypes.txt = name; loc }
[%type: int]
:: result_types )
| Poly_var_string _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label = External_arg_spec.Obj_label.obj s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag
{ Asttypes.txt = name; loc }
[%type: string]
:: result_types )
| Fn_uncurry_arity _ ->
Location.raise_errorf ~loc:ty.ptyp_loc
"`[%@mel.uncurry]' can't be used within `[@mel.obj]'"
| Extern_unit -> assert false
| Poly_var _ ->
raise
(Location.raise_errorf ~loc
"`[%@mel.obj]' must not be used with labelled \
polymorphic variants carrying payloads"
name))
| Optional name -> (
let obj_arg_type = get_opt_arg_type ty in
match obj_arg_type with
| Ignore ->
( External_arg_spec.empty_kind obj_arg_type,
param_type :: arg_types,
result_types )
| Nothing | Unwrap _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label =
External_arg_spec.Obj_label.optional
~for_sure_no_nested_option:false s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag
{ Asttypes.txt = name; loc }
(Ast_helper.Typ.constr ~loc
{ txt = Ast_literal.js_undefined; loc }
[ ty ])
:: result_types )
| Int _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label =
External_arg_spec.Obj_label.optional
~for_sure_no_nested_option:true s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag
{ Asttypes.txt = name; loc }
(Ast_helper.Typ.constr ~loc
{ txt = Ast_literal.js_undefined; loc }
[ [%type: int] ])
:: result_types )
| Poly_var_string _ ->
let s = Melange_ffi.Lam_methname.translate name in
( {
arg_label =
External_arg_spec.Obj_label.optional
~for_sure_no_nested_option:true s;
arg_type = obj_arg_type;
},
param_type :: arg_types,
Ast_helper.Of.tag
{ Asttypes.txt = name; loc }
(Ast_helper.Typ.constr ~loc
{ txt = Ast_literal.js_undefined; loc }
[ [%type: string] ])
:: result_types )
| Arg_cst _ ->
Location.raise_errorf ~loc
"`[%@mel.as ..]' is not supported within optionally \
labelled arguments yet"
| Fn_uncurry_arity _ ->
Location.raise_errorf ~loc
"`[%@mel.uncurry]' can't be used within `[@mel.obj]'"
| Extern_unit -> assert false
| Poly_var _ ->
Location.raise_errorf ~loc
"`[%@mel.obj]' must not be used with optionally \
labelled polymorphic variants carrying payloads"
name)
in
(new_arg_label :: arg_labels, new_arg_types, output_tys))
arg_types_ty ~init:([], [], [])
in
let result =
let open Ast_helper in
match result_type.ptyp_desc with
| Ptyp_any ->
Ast_core_type.to_js_type ~loc
(Typ.object_ ~loc result_types Closed)
| _ -> result_type
in
( mk_fn_type new_arg_types_ty result,
External_ffi_types.ffi_obj_create arg_kinds )
| _ ->
Location.raise_errorf ~loc
"Found an attribute that conflicts with `[%@mel.obj]'"
let mel_send_this_index arg_type_specs arg_types =
let find_index ~f:p =
let rec aux i = function
| [] -> None
| a :: l -> if p a then Some i else aux (i + 1) l
in
aux 0
in
let mel_this_idx =
find_index
~f:(fun { attrs; _ } ->
List.exists
~f:(fun ({ attr_name = { txt; _ }; _ } as attr) ->
match txt with
| "mel.this" ->
Mel_ast_invariant.mark_used_mel_attribute attr;
true
| _ -> false)
attrs)
arg_types
in
match mel_this_idx with
| Some self_idx -> self_idx
| None ->
find_index
~f:(function
| { External_arg_spec.arg_type = Arg_cst _; _ } -> false | _ -> true)
arg_type_specs
|> Option.get
let external_desc_of_non_obj (loc : Location.t) (st : external_desc)
(prim_name_or_pval_prim : bundle_source) (arg_type_specs_length : int)
arg_types_ty
(arg_type_specs :
External_arg_spec.Arg_label.t External_arg_spec.param list) :
External_ffi_types.external_spec =
match st with
| {
set_index = true;
external_module_name = None;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
variadic = false;
scopes;
get_index = false;
new_name = `Nm_na;
call_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
return_wrapper = _;
mk_obj = _;
} ->
if arg_type_specs_length = 3 then Js_set_index { scopes }
else
Location.raise_errorf ~loc
"`[%@mel.set_index]' requires a function of 3 arguments: `'t -> 'key \
-> 'value -> unit'"
| { set_index = true; _ } ->
Error.err ~loc
(Conflict_ffi_attribute
"Found an attribute that conflicts with `[@mel.set_index]'")
| {
get_index = true;
external_module_name = None;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
variadic = false;
scopes;
new_name = `Nm_na;
call_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
set_index = false;
mk_obj = _;
return_wrapper = _;
} ->
if arg_type_specs_length = 2 then Js_get_index { scopes }
else
Location.raise_errorf ~loc
"`[%@mel.get_index]' requires a function of 2 arguments: `'t -> 'key \
-> 'value'"
| { get_index = true; _ } ->
Error.err ~loc
(Conflict_ffi_attribute
"Found an attribute that conflicts with `@mel.get_index'")
| {
module_as_val = Some external_module_name;
get_index = false;
new_name;
external_module_name = None;
val_send = `Nm_na;
val_send_pipe = None;
scopes = [];
variadic;
call_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
set_index = false;
return_wrapper = _;
mk_obj = _;
} -> (
match (arg_types_ty, new_name) with
| [], `Nm_na -> Js_module_as_var external_module_name
| _, `Nm_na -> Js_module_as_fn { variadic; external_module_name }
| _, `Nm_external _ -> Js_module_as_class external_module_name
| _, `Nm_payload _ ->
Location.raise_errorf ~loc
"`[%@mel.new]' doesn't expect an attribute payload")
| { module_as_val = Some _; get_index; val_send; _ } ->
let reason =
match (get_index, val_send) with
| true, _ ->
"`@mel.get_index' doesn't import from a module. `@mel.module' is \
not necessary here."
| _, #bundle_source ->
"`@mel.send' doesn't import from a module. `@mel.module` is not \
necessary here."
| _ -> "Found an attribute that conflicts with `@mel.module'."
in
Error.err ~loc (Conflict_ffi_attribute reason)
| {
get_name = `Nm_na;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
val_send = `Nm_na;
val_send_pipe = None;
new_name = `Nm_na;
set_name = `Nm_na;
external_module_name = None;
variadic;
scopes;
mk_obj = _;
return_wrapper = _;
} ->
let name = string_of_bundle_source prim_name_or_pval_prim in
if arg_type_specs_length = 0 then
Js_var { name; external_module_name = None; scopes }
else Js_call { variadic; name; external_module_name = None; scopes }
| {
call_name = `Nm_external (lazy name) | `Nm_payload name;
variadic;
scopes;
external_module_name;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
set_index = false;
get_index = false;
new_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
mk_obj = _;
return_wrapper = _;
} ->
if arg_type_specs_length = 0 then
Js_var { name; external_module_name; scopes }
else Js_call { variadic; name; external_module_name; scopes }
| {
variadic;
scopes;
external_module_name = Some _ as external_module_name;
call_name = `Nm_na;
module_as_val = None;
val_send = `Nm_na;
val_send_pipe = None;
set_index = false;
get_index = false;
new_name = `Nm_na;
set_name = `Nm_na;
get_name = `Nm_na;
mk_obj = _;
return_wrapper = _;
} ->
let name = string_of_bundle_source prim_name_or_pval_prim in
if arg_type_specs_length = 0 then
Js_var { name; external_module_name; scopes }
else Js_call { variadic; name; external_module_name; scopes }
| {
val_send = `Nm_external (lazy name) | `Nm_payload name;
variadic;
scopes;
val_send_pipe = None;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
new_name;
set_name = `Nm_na;
get_name = `Nm_na;
external_module_name = None;
mk_obj = _;
return_wrapper = _;
} -> (
match (arg_type_specs, new_name) with
| [], _ ->
Location.raise_errorf ~loc
"`[%@mel.send]` requires a function with at least one argument"
| [ { arg_type = Arg_cst _; arg_label = _ } ], _ ->
Location.raise_errorf ~loc
"`[%@mel.send]`'s must have at least a non-constant argument"
| _, `Nm_payload _ ->
Location.raise_errorf ~loc
"`[%@mel.send]' doesn't expect an attribute payload"
| _ :: _, (`Nm_na | `Nm_external _) ->
Js_send
{
variadic;
name;
scopes;
kind = Send (mel_send_this_index arg_type_specs arg_types_ty);
new_ = not (new_name = `Nm_na);
})
| { val_send = #bundle_source; _ } ->
Location.raise_errorf ~loc
"Found an attribute that can't be used with `[%@mel.send]'"
| {
val_send_pipe = Some _;
val_send = `Nm_na;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
new_name;
set_name = `Nm_na;
get_name = `Nm_na;
external_module_name = None;
mk_obj = _;
return_wrapper = _;
scopes;
variadic;
} -> (
match new_name with
| `Nm_payload _ ->
Location.raise_errorf ~loc
"`[%@mel.new]' doesn't expect an attribute payload"
| `Nm_na ->
Js_send
{
variadic;
name = string_of_bundle_source prim_name_or_pval_prim;
scopes;
kind = Pipe;
new_ = false;
}
| `Nm_external _ ->
Js_send
{
variadic;
name = string_of_bundle_source prim_name_or_pval_prim;
scopes;
kind = Pipe;
new_ = true;
})
| { val_send_pipe = Some _; _ } ->
Location.raise_errorf ~loc
"Found an attribute that can't be used with `[%@mel.send.pipe]'"
| {
new_name = `Nm_external (lazy name);
external_module_name;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
val_send = `Nm_na;
val_send_pipe = None;
set_name = `Nm_na;
get_name = `Nm_na;
variadic;
scopes;
mk_obj = _;
return_wrapper = _;
} ->
Js_new { name; external_module_name; variadic; scopes }
| { new_name = #bundle_source; _ } ->
Error.err ~loc
(Conflict_ffi_attribute
"Found an attribute that can't be used with `@mel.new'")
| {
set_name = `Nm_external (lazy name) | `Nm_payload name;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
val_send = `Nm_na;
val_send_pipe = None;
new_name = `Nm_na;
get_name = `Nm_na;
external_module_name = None;
variadic = false;
mk_obj = _;
return_wrapper = _;
scopes;
} ->
if arg_type_specs_length = 2 then Js_set { name; scopes }
else
Location.raise_errorf ~loc
"`[%@mel.set]' requires a function of two arguments"
| { set_name = #bundle_source; _ } ->
Location.raise_errorf ~loc
"Found an attribute that can't be used with `[%@mel.set]'"
| {
get_name = `Nm_external (lazy name) | `Nm_payload name;
call_name = `Nm_na;
module_as_val = None;
set_index = false;
get_index = false;
val_send = `Nm_na;
val_send_pipe = None;
new_name = `Nm_na;
set_name = `Nm_na;
external_module_name = None;
variadic = false;
mk_obj = _;
return_wrapper = _;
scopes;
} ->
if arg_type_specs_length = 1 then Js_get { name; scopes }
else
Location.raise_errorf ~loc
"`[%@mel.get]' requires a function of only one argument"
| { get_name = #bundle_source; _ } ->
Location.raise_errorf ~loc
"Found an attribute that conflicts with `[%@mel.get]'"
let list_of_arrow (ty : core_type) : core_type * param_type list =
let rec aux (ty : core_type) acc =
match ty.ptyp_desc with
| Ptyp_arrow (label, t1, t2) ->
aux t2
(({
label;
ty = t1;
attrs = ty.ptyp_attributes @ t1.ptyp_attributes;
loc = ty.ptyp_loc;
}
: param_type)
:: acc)
| Ptyp_poly (_, ty) ->
Error.err ~loc:ty.ptyp_loc Unhandled_poly_type
| _ -> (ty, List.rev acc)
in
aux ty []
module From_attributes = struct
type t = {
pval_type : core_type;
pval_attributes : attributes;
ffi : External_ffi_types.t;
dont_inline_cross_module : bool;
}
let check_ffi =
let valid_js_char =
let a =
Array.init 256 ~f:(fun i ->
let c = Char.chr i in
(c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c = '_' || c = '$')
in
fun c -> Array.unsafe_get a (Char.code c)
in
let valid_first_js_char =
let a =
Array.init 256 ~f:(fun i ->
let c = Char.chr i in
(c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| c = '_' || c = '$')
in
fun c -> Array.unsafe_get a (Char.code c)
in
let valid_ident (s : string) =
let len = String.length s in
len > 0
&& valid_js_char s.[0]
&& valid_first_js_char s.[0]
&&
let module E = struct
exception E
end in
try
for i = 1 to len - 1 do
if not (valid_js_char (String.unsafe_get s i)) then raise E.E
done;
true
with E.E -> false
in
let check_external_module_name ~loc x =
match x with
| { External_ffi_types.bundle = ""; _ }
| { module_bind_name = Phint_name ""; _ } ->
Location.raise_errorf ~loc "`@mel.module' name cannot be empty"
| _ -> ()
in
let is_package_relative_path (x : string) =
String.starts_with x ~prefix:"./" || String.starts_with x ~prefix:"../"
in
let valid_global_name ~loc txt =
if not (valid_ident txt) then
let v = String.split_by ~keep_empty:true (fun x -> x = '.') txt in
List.iter
~f:(fun s ->
if not (valid_ident s) then
Location.raise_errorf ~loc
"%S isn't a valid JavaScript identifier" txt)
v
in
fun ~loc ffi
(_arg_type_specs :
External_arg_spec.Arg_label.t External_arg_spec.param list) : bool ->
let xrelative = ref false in
let upgrade bool = if not !xrelative then xrelative := bool in
(match ffi with
| External_ffi_types.Js_var { name; external_module_name; _ } ->
upgrade (is_package_relative_path name);
Option.iter
(fun (name : External_ffi_types.external_module_name) ->
upgrade (is_package_relative_path name.bundle))
external_module_name;
valid_global_name ~loc name
| Js_send _ | Js_set _ | Js_get _ ->
()
| Js_get_index _ | Js_set_index _ -> ()
| Js_module_as_var external_module_name
| Js_module_as_fn { external_module_name; variadic = _ }
| Js_module_as_class external_module_name ->
upgrade (is_package_relative_path external_module_name.bundle);
check_external_module_name ~loc external_module_name
| Js_new { external_module_name; name; _ }
| Js_call { external_module_name; name; variadic = _; scopes = _ } ->
Option.iter
(fun (external_module_name :
External_ffi_types.external_module_name) ->
upgrade (is_package_relative_path external_module_name.bundle))
external_module_name;
Option.iter
(fun name -> check_external_module_name ~loc name)
external_module_name;
valid_global_name ~loc name);
!xrelative
let parse ~(loc : Location.t) (type_annotation : core_type)
(prim_attributes : attribute list) ~(pval_name : string)
~(prim_name : string) =
if has_mel_uncurry type_annotation.ptyp_attributes then
Location.raise_errorf ~loc
"`[%@mel.uncurry]' must not be applied to the entire annotation"
else
let prim_name_or_pval_name =
if String.length prim_name = 0 then
`Nm_external
(lazy
(Mel_ast_invariant.warn ~loc (Fragile_external pval_name);
pval_name))
else `Nm_external (lazy prim_name)
in
let result_type, arg_types_ty =
list_of_arrow type_annotation
in
if has_mel_uncurry result_type.ptyp_attributes then
Location.raise_errorf ~loc
"`[%@mel.uncurry]' cannot be applied to the return type"
else
let unused_attrs, external_desc =
parse_external_attributes prim_name prim_name_or_pval_name
prim_attributes
in
if external_desc.mk_obj then
let new_type, spec =
process_obj loc external_desc prim_name arg_types_ty result_type
in
{
pval_type = new_type;
ffi = spec;
pval_attributes = unused_attrs;
dont_inline_cross_module = false;
}
else
let arg_type_specs, new_arg_types_ty, (arg_type_specs_length, _) =
let (init
: External_arg_spec.Arg_label.t External_arg_spec.param list
* param_type list
* (int * bool)) =
match external_desc.val_send_pipe with
| Some obj -> (
match
refine_arg_type ~has_mel_send:false ~nolabel:true obj
with
| Arg_cst _ ->
Location.raise_errorf ~loc
"`[%@mel.as ..]' must not be used in the payload for \
`[%@mel.send.pipe]'"
| arg_type ->
( [ { External_arg_spec.arg_label = Arg_empty; arg_type } ],
[
{
label = Nolabel;
ty = obj;
attrs = [];
loc = obj.ptyp_loc;
};
],
(0, false) ))
| None -> ([], [], (0, false))
in
List.fold_right
~f:(fun
param_type
(arg_type_specs, arg_types, (i, last_was_mel_this))
->
let arg_label = param_type.label in
let ty = param_type.ty in
let is_variadic =
(i = 0 || (i = 1 && last_was_mel_this))
&& external_desc.variadic
in
let is_mel_this_and_send =
external_desc.val_send <> `Nm_na
&& List.exists
~f:(fun { attr_name = { txt; _ }; _ } ->
txt = "mel.this")
param_type.attrs
in
(if is_variadic && not is_mel_this_and_send then
match arg_label with
| Optional _ ->
Location.raise_errorf ~loc
"`[%@mel.variadic]' cannot be applied to an \
optionally labelled argument"
| Labelled _ | Nolabel -> (
match ty.ptyp_desc with
| Ptyp_any ->
Location.raise_errorf
"`[%@mel.variadic]' expects its last argument to \
be an array"
| _ -> (
match spec_of_ptyp ~nolabel:true ty with
| Nothing -> (
match ty.ptyp_desc with
| Ptyp_constr ({ txt = Lident "array"; _ }, [ _ ])
->
()
| _ ->
Location.raise_errorf ~loc
"`[%@mel.variadic]' expects its last \
argument to be an array")
| _ ->
Location.raise_errorf ~loc
"`[%@mel.variadic]' expects its last argument \
to be an array")));
let ( (arg_label : External_arg_spec.Arg_label.t),
arg_type,
new_arg_types ) =
match arg_label with
| Optional _ -> (
match get_opt_arg_type ty with
| Poly_var _ ->
Location.raise_errorf ~loc:param_type.ty.ptyp_loc
"`[%@mel.as ..]' must not be used with an \
optionally labelled polymorphic variant"
| arg_type ->
(Arg_optional, arg_type, param_type :: arg_types))
| Labelled _ -> (
let arg_type =
let has_mel_send = external_desc.val_send <> `Nm_na in
refine_arg_type ~nolabel:false ~has_mel_send ty
in
( Arg_label,
arg_type,
match arg_type with
| Arg_cst _ -> arg_types
| _ -> param_type :: arg_types ))
| Nolabel -> (
let arg_type =
let has_mel_send = external_desc.val_send <> `Nm_na in
refine_arg_type ~nolabel:true ~has_mel_send ty
in
( Arg_empty,
arg_type,
match arg_type with
| Arg_cst _ -> arg_types
| _ -> param_type :: arg_types ))
in
( { External_arg_spec.arg_label; arg_type } :: arg_type_specs,
new_arg_types,
if arg_type = Ignore then (i, last_was_mel_this)
else (i + 1, is_mel_this_and_send) ))
arg_types_ty ~init
in
let ffi =
external_desc_of_non_obj loc external_desc prim_name_or_pval_name
arg_type_specs_length arg_types_ty arg_type_specs
in
let relative = check_ffi ~loc ffi arg_type_specs in
let return_wrapper =
check_return_wrapper loc external_desc.return_wrapper result_type
in
{
pval_type = mk_fn_type new_arg_types_ty result_type;
ffi = External_ffi_types.ffi_mel arg_type_specs return_wrapper ffi;
pval_attributes = unused_attrs;
dont_inline_cross_module = relative;
}
end
let handle_attributes_as_string (pval_loc : Location.t) (typ : core_type)
(attrs : attribute list) (pval_name : string) (prim_name : string) =
match typ.ptyp_desc with
| Ptyp_constr
({ txt = Ldot (Ldot (Lident "Js", "Fn"), arity); loc }, [ fn_type ]) ->
let {
From_attributes.pval_type;
ffi;
pval_attributes;
dont_inline_cross_module;
} =
From_attributes.parse ~loc:pval_loc fn_type attrs ~pval_name ~prim_name
in
{
pval_type =
Ast_helper.Typ.constr
{ txt = Ldot (Ast_literal.js_fn, arity); loc }
[ pval_type ];
pval_prim = [ prim_name; prim_name ];
pval_attributes = Ast_attributes.mel_ffi ffi :: pval_attributes;
dont_inline_cross_module;
}
| _ ->
let {
From_attributes.pval_type;
ffi;
pval_attributes;
dont_inline_cross_module;
} =
From_attributes.parse ~loc:pval_loc typ attrs ~pval_name ~prim_name
in
{
pval_type;
pval_prim = [ prim_name; prim_name ];
pval_attributes = Ast_attributes.mel_ffi ffi :: pval_attributes;
dont_inline_cross_module;
}