-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmithy.ml
3720 lines (3574 loc) · 133 KB
/
smithy.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
(*
TODO
- generate operations for all protocols
- sign and perform requests
- mli files
- timestampFormat
- validation: length, pattern, range, uniqueItems (put that in the documentation?)
4 aws.protocols#restXml <== S3
17 aws.protocols#awsQuery
23 aws.protocols#awsJson1_0
106 aws.protocols#awsJson1_1
186 aws.protocols#restJson1
./gradlew :smithy-aws-protocol-tests:build
Things to consider
- endpoint configuration
- streaming
- pagination ==> modification of the request / access to the response
- waiters
- retries ==> retryable errors / idempotency
- presigned URLs
Compiling an operation:
- builder function (straight for arguments to JSon)
==> json + host prefix + uri ?
To_XML ==> xmlNamespace / xmlAttribute
type 'a error = {code : int; name : string; body: string; value : 'a }
enum are open (can send or receive arbitrary values)
===> add an 'Other of string'
context :
==> Lwt/async
==> retry policy
==> endpoint configuration
==> pagination
*)
open Yojson.Safe
module StringMap = Map.Make (struct
type t = string
let compare = compare
end)
type shape_id = { namespace : string; identifier : string }
let parse_shape_id s =
let i = String.index s '#' in
{
namespace = String.sub s 0 i;
identifier = String.sub s (i + 1) (String.length s - i - 1);
}
module IdMap = Map.Make (struct
type t = shape_id
let compare = compare
end)
module IdSet = Set.Make (struct
type t = shape_id
let compare = compare
end)
type traits = (string * Yojson.Safe.t) list
type http_request_test = {
id : string;
documentation : string option;
method_ : string option;
uri : string;
query_params : string list option;
forbid_query_params : string list;
require_query_params : string list;
headers : (string * string) list option;
forbid_headers : string list;
require_headers : string list;
body : string option;
body_media_type : string option;
host : string option;
resolved_host : string option;
params : Yojson.Safe.t;
applies_to : [ `Client | `Server ] option;
}
type http_response_test = {
id : string;
documentation : string option;
code : int;
headers : (string * string) list option;
body : string option;
params : Yojson.Safe.t;
applies_to : [ `Client | `Server ] option;
}
type shape_type =
| Blob (* string *)
| Boolean
| String (* string *)
| Enum of (string * shape_id * traits) list
| Integer (* int32 *)
| Long (* int64 *)
| Float
| Double
| IntEnum
| Short
| Byte
| Timestamp
| Document
| List of (shape_id * traits)
| Map of (shape_id * traits) * (shape_id * traits)
| Structure of (string * shape_id * traits) list
| Union of (string * shape_id * traits) list
| Service of service
| Resource of resource
| Operation of operation
and service = {
version : string;
operations : shape_id list;
resources : shape_id list;
errors : shape_id list;
rename : string IdMap.t;
}
and resource = {
create : shape_id option;
put : shape_id option;
read : shape_id option;
update : shape_id option;
delete : shape_id option;
list : shape_id option;
operations : shape_id list;
collection_operations : shape_id list;
resources : shape_id list;
}
and operation = {
input : shape_id;
output : shape_id;
errors : shape_id list;
http_request_tests : http_request_test list;
http_response_tests : http_response_test list;
}
let unit_type = { namespace = "smithy.api"; identifier = "Unit" }
let parse_http_request_test test =
let open Util in
{
id = test |> member "id" |> to_string;
documentation = test |> member "documentation" |> to_option to_string;
method_ = test |> member "method" |> to_option to_string;
uri = test |> member "uri" |> to_string;
host = test |> member "host" |> to_option to_string;
resolved_host = test |> member "resolvedHost" |> to_option to_string;
params = test |> member "params";
query_params =
test |> member "queryParams"
|> to_option (fun h -> h |> to_list |> List.map to_string);
forbid_query_params =
test |> member "forbidQueryParams" |> to_option to_list
|> Option.value ~default:[] |> List.map to_string;
require_query_params =
test
|> member "requireQueryParams"
|> to_option to_list |> Option.value ~default:[] |> List.map to_string;
headers =
test |> member "headers"
|> to_option (fun h ->
h |> to_assoc |> List.map (fun (k, v) -> (k, to_string v)));
forbid_headers =
test |> member "forbidHeaders" |> to_option to_list
|> Option.value ~default:[] |> List.map to_string;
require_headers =
test |> member "requireHeaders" |> to_option to_list
|> Option.value ~default:[] |> List.map to_string;
body = test |> member "body" |> to_option to_string;
body_media_type = test |> member "bodyMediaType" |> to_option to_string;
applies_to =
( test |> member "appliesTo" |> fun s ->
match to_option to_string s with
| None -> None
| Some "client" -> Some `Client
| Some "server" -> Some `Server
| _ -> assert false );
}
let parse_http_response_test test =
let open Util in
{
id = test |> member "id" |> to_string;
documentation = test |> member "documentation" |> to_option to_string;
code = test |> member "code" |> to_int;
params = test |> member "params";
headers =
test |> member "headers"
|> to_option (fun h ->
h |> to_assoc |> List.map (fun (k, v) -> (k, to_string v)));
body = test |> member "body" |> to_option to_string;
applies_to =
( test |> member "appliesTo" |> fun s ->
match to_option to_string s with
| None -> None
| Some "client" -> Some `Client
| Some "server" -> Some `Server
| _ -> assert false );
}
type shape = {
typ : shape_type;
traits : (string * Yojson.Safe.t) list;
mixins : shape_id list;
}
let parse_shape (id, sh) =
let typ = Util.(sh |> member "type" |> to_string) in
let parse_traits m =
Util.(
m |> member "traits" |> to_option to_assoc |> Option.value ~default:[])
in
let parse_member name =
let m = Util.(sh |> member name) in
(Util.(m |> member "target" |> to_string |> parse_shape_id), parse_traits m)
in
let parse_members () =
Util.(
sh |> member "members" |> to_assoc
|> List.map (fun (nm, m) ->
let ty =
Util.(m |> member "target" |> to_string |> parse_shape_id)
in
(nm, ty, parse_traits m)))
in
let parse_list name =
Util.(
sh |> member name |> to_option to_list |> Option.value ~default:[]
|> List.map (fun m ->
Util.(m |> member "target" |> to_string |> parse_shape_id)))
in
let traits = parse_traits sh in
( parse_shape_id id,
{
typ =
(match typ with
| "blob" -> Blob
| "boolean" -> Boolean
| "string" -> (
try
Enum
(List.assoc "smithy.api#enum" traits
|> Util.to_list
|> List.map (fun e ->
let value =
Util.(
e |> member "name" |> to_option to_string
|> Option.value
~default:(e |> member "value" |> to_string))
in
if String.contains value ' ' || String.contains value ':'
then raise Not_found;
(value, unit_type, [])))
with Not_found -> String (* string *))
| "enum" -> Enum (parse_members ())
| "integer" -> Integer (* int32 *)
| "long" -> Long (* int64 *)
| "float" -> Float
| "double" -> Double
| "timestamp" -> Timestamp
| "document" -> Document (* ??? *)
| "list" -> List (parse_member "member")
| "map" -> Map (parse_member "key", parse_member "value")
| "structure" -> Structure (parse_members ())
| "union" -> Union (parse_members ())
| "service" ->
Service
{
version = Util.(sh |> member "version" |> to_string);
operations = parse_list "operations";
resources = parse_list "resources";
errors = parse_list "errors";
rename =
Util.(
sh |> member "rename" |> to_option to_assoc
|> Option.value ~default:[]
|> List.fold_left
(fun m (k, v) ->
IdMap.add (parse_shape_id k) (to_string v) m)
IdMap.empty);
}
| "resource" ->
let parse_member_opt name =
Util.(
sh |> member name
|> to_option (fun t ->
t |> member "target" |> to_string |> parse_shape_id))
in
Resource
{
create = parse_member_opt "create";
put = parse_member_opt "put";
read = parse_member_opt "read";
update = parse_member_opt "update";
delete = parse_member_opt "delete";
list = parse_member_opt "list";
operations = parse_list "operations";
collection_operations = parse_list "collectionOperations";
resources = parse_list "resources";
}
| "operation" ->
Operation
{
input = fst (parse_member "input");
output = fst (parse_member "output");
errors = parse_list "errors";
http_request_tests =
Util.(
traits
|> List.assoc_opt "smithy.test#httpRequestTests"
|> Option.value ~default:`Null
|> to_option to_list |> Option.value ~default:[]
|> List.map parse_http_request_test);
http_response_tests =
Util.(
traits
|> List.assoc_opt "smithy.test#httpResponseTests"
|> Option.value ~default:`Null
|> to_option to_list |> Option.value ~default:[]
|> List.map parse_http_response_test);
}
| "intEnum" -> IntEnum
| "short" -> Short
| "byte" -> Byte
| _ -> assert false);
mixins = parse_list "mixins";
traits;
} )
let parse f =
let d = from_file f in
let shapes = Util.(d |> member "shapes" |> to_assoc) in
List.fold_left
(fun map shape ->
let id, shape = parse_shape shape in
IdMap.add id shape map)
IdMap.empty shapes
let rec resolve_mixin shapes id =
let sh = IdMap.find id shapes in
if sh.mixins = [] then shapes
else
let shapes = List.fold_left resolve_mixin shapes sh.mixins in
let l =
let get_members sh =
match sh.typ with Structure l -> l | _ -> assert false
in
List.fold_right
(fun id rem -> get_members (IdMap.find id shapes) @ rem)
sh.mixins (get_members sh)
in
let traits =
sh.traits
@ List.fold_left
(fun traits id -> (IdMap.find id shapes).traits @ traits)
[] sh.mixins
in
IdMap.add id { typ = Structure l; mixins = []; traits } shapes
let resolve_mixins shapes =
let shapes =
IdMap.fold (fun id _ shapes -> resolve_mixin shapes id) shapes shapes
in
IdMap.map
(fun sh ->
match List.assoc_opt "smithy.api#mixin" sh.traits with
| None -> sh
| Some local_traits ->
{
sh with
traits =
Util.(
local_traits |> member "localTraits" |> to_option to_list
|> Option.value ~default:[]
|> List.map (fun nm -> (to_string nm, `Assoc [])))
@ sh.traits;
})
shapes
let to_snake_case =
let uppercase = Re.rg 'A' 'Z' in
let lowercase = Re.rg 'a' 'z' in
let first_pattern_re =
Re.(
compile
(seq [ group (rep1 uppercase); group (seq [ uppercase; lowercase ]) ]))
in
let second_pattern_re =
Re.(
compile (seq [ group (alt [ lowercase; rg '0' '9' ]); group uppercase ]))
in
let space_re = Re.(compile (set " -")) in
let replace re s =
Re.replace re ~f:(fun g -> Re.Group.get g 1 ^ "_" ^ Re.Group.get g 2) s
in
fun s ->
s |> replace first_pattern_re |> replace second_pattern_re
|> Re.replace space_re ~f:(fun _ -> "_")
|> String.lowercase_ascii
let reserved_words =
[
"and";
"begin";
"constraint";
"else";
"end";
"exception";
"external";
"function";
"include";
"match";
"method";
"module";
"mutable";
"object";
"or";
"then";
"to";
"type";
"bool";
"float";
"int";
"option";
"string";
"unit";
]
let uncapitalized_identifier s =
let s = to_snake_case s in
if List.mem s reserved_words then s ^ "_" else s
let all_upper_re =
Re.(compile (whole_string (rep (alt [ rg 'A' 'Z'; rg '0' '9'; char '_' ]))))
let capitalized_identifier s =
if Re.execp all_upper_re s then s
else String.capitalize_ascii (to_snake_case s)
let type_name ~rename id =
match id.namespace with
| "smithy.api" -> (
match id.identifier with
| "Boolean" | "PrimitiveBoolean" -> "bool"
| "Blob" | "String" -> "string"
| "Integer" -> "int"
| "Long" | "PrimitiveLong" -> "Int64.t"
| "Float" | "Double" -> "float"
| "Timestamp" -> "Ptime.t"
| "Document" -> "Yojson.Safe.t"
| "Unit" -> "unit"
| "Short" -> "int"
| "Byte" -> "char"
| _ -> assert false)
| _ ->
uncapitalized_identifier
(try IdMap.find id rename with Not_found -> id.identifier)
let field_name = uncapitalized_identifier
let constr_name = capitalized_identifier
let optional_member (_, _, traits) =
List.mem_assoc "smithy.api#clientOptional" traits
|| not
(List.mem_assoc "smithy.api#required" traits
|| List.mem_assoc "smithy.api#default" traits)
let flattened_member (_, _, traits) =
List.mem_assoc "smithy.api#xmlFlattened" traits
let type_of_shape shapes nm =
if nm.namespace = "smithy.api" then (
match nm.identifier with
| "PrimitiveLong" -> Long
| "Integer" -> Integer
| "Long" -> Long
| "String" -> String
| "Float" -> Float
| "Double" -> Double
| "Boolean" | "PrimitiveBoolean" -> Boolean
| "Short" -> Short
| "Byte" -> Byte
| "Blob" -> Blob
| "Timestamp" -> Timestamp
| "Document" -> Document
| _ ->
Format.eprintf "%s/%s@." nm.namespace nm.identifier;
assert false)
else
match IdMap.find_opt nm shapes with
| None -> assert false
| Some { typ; _ } -> typ
let loc = Location.none
type html =
| Text of string
| Element of string * (string * string) list * html list
let rec text doc =
match doc with
| Text txt -> txt
| Element (_, _, children) -> children_text children
and children_text ch = String.concat "" (List.map text ch)
let escape_code =
let space_re = Re.(compile (rep1 (set " \n\t"))) in
let escaped_re = Re.(compile (set "[]")) in
let trailing_backslash_re = Re.(compile (seq [ char '\\'; stop ])) in
fun txt ->
txt
|> Re.replace escaped_re ~f:(fun g -> "\\" ^ Re.Group.get g 0)
|> Re.replace space_re ~f:(fun _ -> " ")
|> Re.replace trailing_backslash_re ~f:(fun _ -> "\\ ")
let escape_text =
let space_re = Re.(compile (rep1 (set " \n\t"))) in
let escaped_re = Re.(compile (set "{[]}@")) in
fun txt ->
txt
|> Re.replace escaped_re ~f:(fun g -> "\\" ^ Re.Group.get g 0)
|> Re.replace space_re ~f:(fun _ -> " ")
let empty_text =
let space_re = Re.(compile (whole_string (rep (set " \n\t")))) in
fun txt -> Re.execp space_re txt
let rec fix_list l =
match l with
| Element ("li", attr, children) :: Text txt :: rem ->
fix_list (Element ("li", attr, children @ [ Text txt ]) :: rem)
| Element ("li", attr, children) :: (Element (nm, _, children') as elt) :: rem
when nm <> "li" ->
if nm = "b" then
fix_list (Element ("li", attr, children) :: (children' @ rem))
else fix_list (Element ("li", attr, children @ [ elt ]) :: rem)
| elt :: rem -> elt :: fix_list rem
| [] -> []
let rec format_dl ~format l dts (dds : _ list) =
let format_group () =
"{- "
^ String.concat " / "
(List.rev_map
(fun s -> "{b " ^ s ^ "}")
(List.filter (fun s -> not (empty_text s)) dts))
^ " "
^ (match dds with
| [ dd ] -> dd
| _ ->
"\n{ul "
^ String.concat " " (List.rev_map (fun s -> "{- " ^ s ^ "}") dds)
^ "}")
^ "}"
in
match l with
| Element ("dt", [], children) :: rem ->
if dds <> [] then
format_group () ^ format_dl ~format rem (format children :: dts) []
else format_dl ~format rem (format children :: dts) []
| Element ("dd", [], children) :: rem ->
format_dl ~format rem dts (format children :: dds)
| Element _ :: _ -> assert false
| Text txt :: rem ->
assert (empty_text txt);
format_dl ~format rem dts dds
| [] -> if dts <> [] then format_group () else ""
let rec allowed_in_b l =
List.for_all
(fun item ->
match item with
| Element ("ul", _, _) -> false
| Element (_, _, children) -> allowed_in_b children
| Text _ -> true)
l
let rec format ~shapes ~field_refs ~in_anchor ?(in_list = false) ~toplevel doc =
match doc with
| Text txt -> escape_text txt
| Element ("p", _, children) ->
let s =
format_children ~shapes ~field_refs ~in_anchor ~toplevel:false children
in
if toplevel then s ^ "\n\n" else s
| Element ("code", _, children) | Element ("a", [], children) -> (
let s = escape_code (children_text children) in
let reference =
match StringMap.find_opt s field_refs with
| Some typ ->
Some
(Printf.sprintf "{!type-%s.%s}"
(uncapitalized_identifier typ)
(uncapitalized_identifier s))
| None -> (
match
IdMap.choose_opt
(IdMap.filter
(fun { identifier; _ } _ -> identifier = s)
shapes)
with
| Some (_, { typ; _ }) -> (
match typ with
| Service _ | Resource _ -> Some ("[" ^ s ^ "]")
| Operation _ ->
Some ("[" ^ s ^ "]")
(*ZZZZ "{!val:" ^ uncapitalized_identifier s ^ "}" *)
| _ -> Some ("{!type:" ^ uncapitalized_identifier s ^ "}"))
| None -> None)
in
match reference with
| Some reference when not in_anchor -> reference
| _ -> "[" ^ s ^ "]")
| Element (("i" | "replaceable" | "title"), _, children) ->
let s =
format_children ~shapes ~field_refs ~in_anchor ~toplevel:false children
in
if empty_text s then s else "{i " ^ s ^ "}"
| Element ("b", _, children) ->
let s =
format_children ~shapes ~field_refs ~in_anchor ~toplevel:false children
in
if empty_text s || not (allowed_in_b children) then s else "{b " ^ s ^ "}"
| Element (("note" | "para"), _, children) ->
format_children ~shapes ~field_refs ~in_anchor ~toplevel children
| Element ("important", _, children) ->
format_children ~shapes ~field_refs ~in_anchor ~toplevel children
| Element ("a", attr, children) when List.mem_assoc "href" attr ->
let url = List.assoc "href" attr in
let s =
format_children ~shapes ~field_refs ~in_anchor:true ~toplevel children
in
if empty_text url then s else "{{: " ^ url ^ " }" ^ s ^ "}"
| Element ("ul", _, children) ->
"\n{ul "
^ format_children ~shapes ~field_refs ~in_anchor ~in_list:true
~toplevel:false (fix_list children)
^ "}\n"
| Element ("li", _, children) ->
let s =
format_children ~shapes ~field_refs ~in_anchor ~toplevel:false children
in
if in_list then "{- " ^ s ^ "}" else s
| Element ("dl", _, children) ->
"\n{ul "
^ format_dl
~format:
(format_children ~shapes ~field_refs ~in_anchor ~toplevel:false)
children [] []
^ "}\n"
| Element ("ol", _, children) ->
"\n{ol "
^ format_children ~shapes ~field_refs ~in_anchor ~in_list:true
~toplevel:false (fix_list children)
^ "}\n"
| Element ("br", _, []) -> "\n\n"
| Element ("fullname", _, _) -> ""
| Element (nm, _, children) ->
let s =
"<" ^ nm ^ ">"
^ format_children ~shapes ~field_refs ~in_anchor ~toplevel:false
children
in
(* Format.eprintf "AAA %s@." s;*)
s
and format_children ~shapes ~field_refs ~in_anchor ?(in_list = false) ~toplevel
lst =
String.concat ""
(List.map (format ~shapes ~field_refs ~in_anchor ~in_list ~toplevel) lst)
let documentation ~shapes ~field_refs doc =
let open Markup in
if doc = "" then None
else
"<body>" ^ doc |> string |> parse_html |> signals
|> tree
~text:(fun ss -> Text (String.concat "" ss))
~element:(fun (_, name) attr children ->
Element
( name,
List.map (fun ((_, name), value) -> (name, value)) attr,
children ))
|> fun doc' ->
match doc' with
| Some (Element ("body", _, children)) ->
Some
(format_children ~shapes ~field_refs ~in_anchor:false ~toplevel:true
children)
| _ -> assert false
module B = Ppxlib.Ast_builder.Make (struct
let loc = Location.none
end)
let const_string s = Ppxlib.Parsetree.Pconst_string (s, Location.none, None)
let doc_loc = Location.mknoloc "ocaml.doc"
let doc_attr doc =
let exp = B.pexp_constant (const_string doc) in
let item = B.pstr_eval exp [] in
{
Ppxlib.Parsetree.attr_name = doc_loc;
attr_payload = PStr [ item ];
attr_loc = loc;
}
let text_loc = Location.mknoloc "ocaml.text"
let text_attr doc =
let exp = B.pexp_constant (const_string doc) in
let item = B.pstr_eval exp [] in
{
Ppxlib.Parsetree.attr_name = text_loc;
attr_payload = PStr [ item ];
attr_loc = loc;
}
let documentation ~shapes ?(field_refs = StringMap.empty) traits =
match List.assoc_opt "smithy.api#documentation" traits with
| None -> []
| Some doc -> (
let doc = Yojson.Safe.Util.to_string doc in
match documentation ~shapes ~field_refs doc with
| None | Some "" -> []
| Some doc -> [ doc_attr doc ])
let toplevel_documentation ~shapes traits =
List.map
(fun d -> B.pstr_attribute { d with attr_name = text_loc })
(documentation ~shapes traits)
let type_ident ~rename id =
B.ptyp_constr (Location.mknoloc (Longident.Lident (type_name ~rename id))) []
let member_name ~fixed ?(name = "smithy.api#jsonName") (nm, _, traits) =
if fixed then nm
else
try Yojson.Safe.Util.to_string (List.assoc name traits)
with Not_found -> nm
let default_value ~shapes ~rename typ default =
match default with
| `String s -> (
match type_of_shape shapes typ with
| String | Blob -> B.pexp_constant (const_string s)
| Enum l ->
let nm, _, _ =
List.find
(fun enum ->
member_name ~fixed:false ~name:"smithy.api#enumValue" enum = s)
l
in
[%expr
([%e
B.pexp_construct
(Location.mknoloc (Longident.Lident (constr_name nm)))
None]
: [%t type_ident ~rename typ])]
| Document -> [%expr `String [%e B.pexp_constant (const_string s)]]
| _ ->
prerr_endline typ.identifier;
assert false)
| `Int n -> (
match type_of_shape shapes typ with
| Float | Double ->
B.pexp_constant (Pconst_float (Printf.sprintf "%d." n, None))
| Integer | Short | IntEnum ->
B.pexp_constant (Pconst_integer (Int.to_string n, None))
| Long -> B.pexp_constant (Pconst_integer (Int.to_string n, Some 'L'))
| Byte -> B.pexp_constant (Pconst_char (Char.chr (n land 255)))
| Timestamp ->
[%expr
Converters.Timestamp.from_epoch_seconds
[%e B.pexp_constant (Pconst_float (Printf.sprintf "%d." n, None))]]
| _ ->
Format.eprintf "%s/%s@." typ.namespace typ.identifier;
assert false)
| `Bool b -> (
let b = if b then [%expr true] else [%expr false] in
match type_of_shape shapes typ with
| Boolean -> b
| Document -> [%expr `Bool [%e b]]
| _ -> assert false)
| `List [] -> (
match type_of_shape shapes typ with
| List _ -> [%expr []]
| Document -> [%expr `List []]
| _ -> assert false)
| `Float f ->
B.pexp_constant
(match type_of_shape shapes typ with
| Float | Double -> Pconst_float (Printf.sprintf "%f" f, None)
| _ -> assert false)
| `Assoc [] -> (
match type_of_shape shapes typ with
| Map _ -> [%expr Converters.StringMap.empty]
| Document -> [%expr `Assoc []]
| _ ->
Format.eprintf "%s/%s@." typ.namespace typ.identifier;
assert false)
| _ ->
Format.eprintf "DEFAULT %s/%s / %s@." typ.namespace typ.identifier
(Yojson.Safe.to_string default);
assert false
let structure_has_optionals fields =
List.exists
(fun (_, _, traits) ->
List.mem_assoc "smithy.api#default" traits
|| List.mem_assoc "smithy.api#clientOptional" traits
|| not (List.mem_assoc "smithy.api#required" traits))
fields
let constructor_parameters ~shapes ~rename ~fields ~body =
let has_optionals = structure_has_optionals fields in
List.fold_right
(fun field expr ->
let nm, typ, traits' = field in
match List.assoc_opt "smithy.api#default" traits' with
| Some default when default <> `Null ->
let default = default_value ~shapes ~rename typ default in
let default =
if List.mem_assoc "smithy.api#clientOptional" traits' then
[%expr Some [%e default]]
else default
in
B.pexp_fun
(Optional (field_name nm))
(Some default)
(B.ppat_var (Location.mknoloc (field_name nm)))
expr
| _ ->
let optional = optional_member field in
B.pexp_fun
(if optional then Optional (field_name nm)
else Labelled (field_name nm))
None
(B.ppat_var (Location.mknoloc (field_name nm)))
expr)
fields
(if has_optionals || fields = [] then
B.pexp_fun Nolabel None [%pat? ()] body
else body)
let print_constructor ~shapes ~rename name fields =
let body =
B.pexp_constraint
(B.pexp_record
(List.map
(fun (nm, _, _) ->
let label = Location.mknoloc (Longident.Lident (field_name nm)) in
(label, B.pexp_ident label))
fields)
None)
(type_ident ~rename name)
in
let expr = constructor_parameters ~shapes ~rename ~fields ~body in
[%stri
let [%p B.ppat_var (Location.mknoloc (type_name ~rename name))] = [%e expr]]
let print_constructors ~shapes ~rename =
IdMap.fold
(fun name { typ; _ } rem ->
match typ with
| Structure l when l <> [] ->
print_constructor ~shapes ~rename name l :: rem
| _ -> rem)
shapes []
let type_constructor ~rename ~info ?arg_type nm =
{
(B.constructor_declaration
~args:
(Pcstr_tuple
(match arg_type with
| None -> []
| Some typ -> [ type_ident ~rename typ ]))
~name:(Location.mknoloc (constr_name nm))
~res:None)
with
pcd_attributes = info;
}
let print_type ?heading ~inputs ~shapes ~rename (nm, { typ; traits; _ }) =
let text = match heading with None -> [] | Some h -> [ text_attr h ] in
let docs =
documentation ~shapes traits
@
match typ with
| Structure l when l <> [] && IdSet.mem nm inputs ->
[
doc_attr
("See associated record builder function {!val:"
^ type_name ~rename nm ^ "}.");
]
| _ -> []
in
let manifest_type manifest =
B.type_declaration ~manifest:(Some manifest)
~name:(Location.mknoloc (type_name ~rename nm))
~params:[] ~cstrs:[] ~kind:Ptype_abstract ~private_:Public
in
{
(match typ with
| Blob -> manifest_type [%type: string]
| Boolean -> manifest_type [%type: bool]
| String -> manifest_type [%type: string]
| Enum l ->
let l =
List.map
(fun (nm, _, traits) ->
type_constructor ~rename ~info:(documentation ~shapes traits) nm)
l
in
B.type_declaration ~manifest:None ~kind:(Ptype_variant l)
~name:(Location.mknoloc (type_name ~rename nm))
~params:[] ~cstrs:[] ~private_:Public
| Integer | IntEnum | Short -> manifest_type [%type: int]
| Long -> manifest_type [%type: Int64.t]
| Float | Double -> manifest_type [%type: float]
| Byte -> manifest_type [%type: char]
| Timestamp -> manifest_type [%type: Ptime.t]
| Document -> manifest_type [%type: Yojson.Safe.t]
| List (id, _) ->
let sparse = List.mem_assoc "smithy.api#sparse" traits in
let id = type_ident ~rename id in
manifest_type
[%type: [%t if sparse then [%type: [%t id] option] else id] list]
| Map ((key, _), (value, _)) ->
let sparse = List.mem_assoc "smithy.api#sparse" traits in
let id = type_ident ~rename value in
manifest_type
[%type:
( [%t type_ident ~rename key],
[%t if sparse then [%type: [%t id] option] else id] )
Converters.map]
| Structure [] -> manifest_type [%type: unit]
| Structure l ->
let l =
List.map
(fun ((nm, typ, traits) as field) ->
let optional = optional_member field in
let id = type_ident ~rename typ in
{
(B.label_declaration ~mutable_:Immutable
~name:(Location.mknoloc (field_name nm))
~type_:(if optional then [%type: [%t id] option] else id))
with
pld_attributes = documentation ~shapes traits;
})
l
in
B.type_declaration ~manifest:None ~kind:(Ptype_record l)
~name:(Location.mknoloc (type_name ~rename nm))
~params:[] ~cstrs:[] ~private_:Public
| Union l ->
let l =
List.map
(fun (nm, typ, traits) ->
let arg_type = if typ = unit_type then None else Some typ in
type_constructor ~rename
~info:(documentation ~shapes traits)
?arg_type nm)
l
in
B.type_declaration ~manifest:None ~kind:(Ptype_variant l)
~name:(Location.mknoloc (type_name ~rename nm))
~params:[] ~cstrs:[] ~private_:Public
| Service _ | Resource _ | Operation _ -> assert false)
with
ptype_attributes = text @ docs;
}
let print_types ~rename ~inputs ~outputs ~operations shapes =
let types =
IdMap.bindings
(IdMap.filter
(fun id { typ; _ } ->