ocaml-core / base / sexplib / syntax / pa_sexp_conv.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
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
(* Pa_sexp_conv: Preprocessing Module for Automated S-expression Conversions *)

open StdLabels
open MoreLabels

open Printf

open Camlp4
open PreCast

open Syntax

module Gen = Pa_type_conv.Gen

(* Utility functions *)

let mk_rev_bindings loc fps =
  let coll (i, bindings, patts, vars) fp =
    let name = "v" ^ string_of_int i in
    let var_expr = <:expr@loc< $lid:name$ >> in
    let expr =
      match fp with
      | `Fun fun_expr -> <:expr@loc< $fun_expr$ $var_expr$ >>
      | `Match matchings -> <:expr@loc< match $var_expr$ with [ $matchings$ ] >>
    in
    let patt = <:patt@loc< $lid:name$ >> in
    let bindings = <:binding@loc< $patt$ = $expr$ and $bindings$ >> in
    i - 1, bindings, patt :: patts, var_expr :: vars
  in
  let n = List.length fps in
  let _, bindings, patts, expr =
    List.fold_left ~f:coll ~init:(n, Ast.BiNil loc, [], []) fps
  in
  bindings, patts, expr

let mk_bindings loc fps = mk_rev_bindings loc (List.rev fps)

let unroll_cnv_fp loc var = function
  | `Fun fun_expr -> <:expr@loc< $fun_expr$ $var$ >>
  | `Match matchings -> <:expr@loc< match $var$ with [ $matchings$ ] >>

let unroll_fun_matches loc fp1 fp2 =
  match fp1, fp2 with
  | `Fun fun_expr1, `Fun fun_expr2 ->
      <:expr@loc< $fun_expr1$ $fun_expr2$ >>
  | `Fun fun_expr, `Match matching ->
      <:expr@loc< $fun_expr$ (fun [ $matching$ ]) >>
  | _ -> assert false  (* impossible *)

let rec sig_of_tds cnv = function
  | Ast.TyDcl (loc, type_name, tps, rhs, cl) -> cnv loc type_name tps rhs cl
  | Ast.TyAnd (loc, tp1, tp2) ->
      <:sig_item@loc< $sig_of_tds cnv tp1$; $sig_of_tds cnv tp2$ >>
  | _ -> assert false  (* impossible *)


(* Generators for S-expressions *)

(* Generates the signature for type conversion to S-expressions *)
module Sig_generate_sexp_of = struct

  let rec sig_of_td__loop acc = function
    | [] ->
        let loc = Ast.loc_of_ctyp acc in
        <:ctyp@loc< $acc$ -> Sexplib.Sexp.t >>
    | tp :: tps ->
        let tp = Gen.drop_variance_annotations tp in
        let loc = Ast.loc_of_ctyp tp in
        let sexp_of = sig_of_td__loop <:ctyp@loc< $acc$ $tp$ >> tps in
        <:ctyp@loc< ( $tp$ -> Sexplib.Sexp.t ) -> $sexp_of$ >>

  let sig_of_td loc type_name tps _rhs _cl =
    let sexp_of = sig_of_td__loop <:ctyp@loc< $lid:type_name$ >> tps in
    <:sig_item@loc< value $lid: "sexp_of_" ^ type_name$ : $sexp_of$ >>

  let mk_sig tds = <:sig_item< $sig_of_tds sig_of_td tds$ >>

  let () = Pa_type_conv.add_sig_generator "sexp_of" mk_sig

  let mk_sig_exn = function
    | <:ctyp@loc< $uid:_$ >> | <:ctyp@loc< $uid:_$ of $_$ >> ->
        <:sig_item@loc< >>
    | tp -> Gen.error tp ~fn:"mk_sig_exn" ~msg:"unknown type"

  let () = Pa_type_conv.add_sig_generator ~is_exn:true "sexp" mk_sig_exn
end


(* Generates the signature for type conversion from S-expressions *)
module Sig_generate_of_sexp = struct

  let rec is_polymorphic_variant = function
    | <:ctyp< private $tp$ >> -> is_polymorphic_variant tp
    | <:ctyp< ( $tup:_$ ) >>
    | <:ctyp< $_$ -> $_$ >>
    | <:ctyp< { $_$ } >>
    | <:ctyp< [ $_$ ] >> -> `Surely_not
    | <:ctyp< [< $_$ ] >> | <:ctyp< [> $_$ ] >>
    | <:ctyp< [= $_$ ] >> -> `Definitely
    | <:ctyp< '$_$ >>
    | <:ctyp< $_$ $_$ >>
    | <:ctyp< $id:_$ >>
    | <:ctyp< >> -> `Maybe
    | <:ctyp< $tp1$ == $tp2$ >> ->
        begin match is_polymorphic_variant tp1 with
        | (`Surely_not | `Definitely) as res -> res
        | `Maybe -> is_polymorphic_variant tp2 end
    | tp -> Gen.unknown_type tp "Sig_generate_of_sexp.is_polymorphic_variant"

  let rec sig_of_td__loop acc = function
    | [] ->
        let loc = Ast.loc_of_ctyp acc in
        <:ctyp@loc< Sexplib.Sexp.t -> $acc$ >>
    | tp :: tps ->
        let tp = Gen.drop_variance_annotations tp in
        let loc = Ast.loc_of_ctyp tp in
        let of_sexp = sig_of_td__loop <:ctyp@loc< $acc$ $tp$ >> tps in
        <:ctyp@loc< ( Sexplib.Sexp.t -> $tp$ ) -> $of_sexp$ >>

  let sig_of_td with_poly loc type_name tps rhs _cl =
    let of_sexp = sig_of_td__loop <:ctyp@loc< $lid:type_name$ >> tps in
    let of_sexp_item =
      <:sig_item@loc< value $lid: type_name ^ "_of_sexp"$ : $of_sexp$; >>
    in
    match with_poly, is_polymorphic_variant rhs with
    | true, `Surely_not ->
        Gen.error rhs ~fn:"Sig_generate_of_sexp.sig_of_td"
          ~msg:"sexp_poly annotation \
            but type is surely not a polymorphic variant"
    | false, (`Surely_not | `Maybe) -> of_sexp_item
    | (true | false), `Definitely | true, `Maybe ->
        <:sig_item@loc<
          $of_sexp_item$;
          value $lid: type_name ^ "_of_sexp__"$ : $of_sexp$;
        >>

  let mk_sig with_poly tds =
    <:sig_item< $sig_of_tds (sig_of_td with_poly) tds$ >>

  let () = Pa_type_conv.add_sig_generator "of_sexp" (mk_sig false)
  let () = Pa_type_conv.add_sig_generator "of_sexp_poly" (mk_sig true)
end


(* Generates the signature for type conversion to S-expressions *)
module Sig_generate = struct
  let () =
    Pa_type_conv.add_sig_generator "sexp" (fun tds ->
      let loc = Ast.loc_of_ctyp tds in
      <:sig_item@loc<
        $Sig_generate_sexp_of.mk_sig tds$;
        $Sig_generate_of_sexp.mk_sig false tds$
      >>)

  let () =
    Pa_type_conv.add_sig_generator "sexp_poly" (fun tds ->
      let loc = Ast.loc_of_ctyp tds in
      <:sig_item@loc<
        $Sig_generate_sexp_of.mk_sig tds$;
        $Sig_generate_of_sexp.mk_sig true tds$
      >>)
end


(* Generator for converters of OCaml-values to S-expressions *)
module Generate_sexp_of = struct
  (* Handling of record defaults *)

  type record_field_handler = [ `keep | `drop_default | `drop_if of Ast.expr ]

  let record_field_handlers = Hashtbl.create 0

  let get_record_field_handler loc =
    try Hashtbl.find record_field_handlers loc
    with Not_found -> `keep

  let check_record_field_handler loc =
    if Hashtbl.mem record_field_handlers loc then
      Loc.raise loc (Failure "sexp record field handler defined twice")

  let () =
    Pa_type_conv.add_record_generator "sexp_drop_default" (fun loc ->
      check_record_field_handler loc;
      Hashtbl.replace record_field_handlers loc `drop_default)

  let () =
    Pa_type_conv.add_record_generator_with_arg "sexp_drop_if"
      Syntax.expr (fun expr_opt loc ->
        check_record_field_handler loc;
        let test =
          match expr_opt with
          | Some expr -> expr
          | None -> Loc.raise loc (Failure "could not parse expression")
        in
        Hashtbl.replace record_field_handlers loc (`drop_if test))

  (* Make abstract calls *)
  let mk_abst_call loc tn rev_path =
    <:expr@loc<
      $id:Gen.ident_of_rev_path loc (("sexp_of_" ^ tn) :: rev_path)$
    >>

  (* Conversion of type paths *)
  let sexp_of_path_fun loc id =
    match Gen.get_rev_id_path id [] with
    | tn :: rev_path -> mk_abst_call loc tn rev_path
    | [] -> assert false  (* impossible *)

  (* Conversion of types *)
  let rec sexp_of_type = function
    | <:ctyp@loc< sexp_opaque $_$ >> ->
        `Fun <:expr@loc< Sexplib.Conv.sexp_of_opaque >>
    | <:ctyp@loc< $tp1$ $tp2$ >> -> `Fun (sexp_of_appl_fun loc tp1 tp2)
    | <:ctyp< ( $tup:tp$ ) >> -> sexp_of_tuple tp
    | <:ctyp@loc< '$parm$ >> -> `Fun <:expr@loc< $lid:"_of_" ^ parm$ >>
    | <:ctyp@loc< $id:id$ >> -> `Fun (sexp_of_path_fun loc id)
    | <:ctyp@loc< $_$ -> $_$ >> as arrow ->
        `Fun <:expr@loc< fun (_f : $arrow$) ->
          Sexplib.Conv.sexp_of_fun Pervasives.ignore >>
    | <:ctyp< [< $row_fields$ ] >> | <:ctyp< [> $row_fields$ ] >>
    | <:ctyp< [= $row_fields$ ] >> -> sexp_of_variant row_fields
    | <:ctyp< ! $parms$ . $poly_tp$ >> -> sexp_of_poly parms poly_tp
    | tp -> Gen.unknown_type tp "sexp_of_type"

  (* Conversion of polymorphic types *)
  and sexp_of_appl_fun loc tp1 tp2 =
    match sexp_of_type tp1, sexp_of_type tp2 with
    | `Fun fun_expr1, `Fun fun_expr2 -> <:expr@loc< $fun_expr1$ $fun_expr2$ >>
    | `Fun fun_expr, `Match matching ->
        <:expr@loc< $fun_expr$ (fun [ $matching$ ]) >>
    | _ -> assert false  (* impossible *)


  (* Conversion of tuples *)
  and sexp_of_tuple tp =
    let loc = Ast.loc_of_ctyp tp in
    let fps = List.map ~f:sexp_of_type (Ast.list_of_ctyp tp []) in
    let bindings, patts, vars = mk_bindings loc fps in
    let in_expr = <:expr@loc< Sexplib.Sexp.List $Gen.mk_expr_lst loc vars$ >> in
    let expr = <:expr@loc< let $bindings$ in $in_expr$ >> in
    `Match <:match_case@loc< ( $tup:Ast.paCom_of_list patts$ ) -> $expr$ >>


  (* Conversion of variant types *)

  and mk_cnv_expr tp =
    let loc = Ast.loc_of_ctyp tp in
    match sexp_of_type tp with
    | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
    | `Match matchings -> <:expr@loc< fun [ $matchings$ ] >>

  and sexp_of_variant row_fields =
    let rec loop = function
      | <:ctyp@loc< $tp1$ | $tp2$ >> ->
          <:match_case@loc< $loop tp1$ | $loop tp2$ >>
      | <:ctyp@loc< `$cnstr$ >> ->
          <:match_case@loc< `$cnstr$ -> Sexplib.Sexp.Atom $str:cnstr$ >>
      | <:ctyp@loc< `$cnstr$ of sexp_list $tp$>> ->
        let cnv_expr =
          match sexp_of_type tp with
          | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
          | `Match matchings ->
              <:expr@loc< fun el -> match el with [ $matchings$ ] >>
        in
        <:match_case@loc<
          `$cnstr$ l ->
             Sexplib.Sexp.List
               [ Sexplib.Sexp.Atom $str:cnstr$ ::
                   Sexplib.Conv.list_map $cnv_expr$ l]
        >>
      | <:ctyp@loc< `$cnstr$ of $tps$ >> ->
          let fps = List.map ~f:sexp_of_type (Ast.list_of_ctyp tps []) in
          let bindings, patts, vars = mk_bindings loc fps in
          let cnstr_expr = <:expr@loc< Sexplib.Sexp.Atom $str:cnstr$ >> in
          let expr =
            <:expr@loc<
              let $bindings$ in
              Sexplib.Sexp.List $Gen.mk_expr_lst loc (cnstr_expr :: vars)$
            >>
          in
          <:match_case@loc< `$cnstr$ $Ast.paSem_of_list patts$ -> $expr$ >>
      | <:ctyp< [< $row_fields$ ] >> | <:ctyp< [> $row_fields$ ] >>
      | <:ctyp< [= $row_fields$ ] >> -> loop row_fields
      | <:ctyp@loc< $tp1$ $tp2$ >> ->
          let id_path = Gen.get_appl_path loc tp1 in
          let call = sexp_of_appl_fun loc tp1 tp2 in
          <:match_case@loc< #$id_path$ as v -> $call$ v >>
      | <:ctyp@loc< $id:id$ >> | <:ctyp@loc< #$id:id$ >> ->
          let call =
            match Gen.get_rev_id_path id [] with
            | tn :: rev_path -> mk_abst_call loc tn rev_path
            | [] -> assert false  (* impossible *)
          in
          <:match_case@loc< #$id$ as v -> $call$ v >>
      | tp -> Gen.unknown_type tp "sexp_of_variant"
    in
    `Match (loop row_fields)


  (* Polymorphic record fields *)

  and sexp_of_poly parms tp =
    let loc = Ast.loc_of_ctyp tp in
    let bindings =
      let mk_binding parm =
        <:binding@loc< $lid:"_of_" ^ parm$ = Sexplib.Conv.sexp_of_opaque >>
      in
      List.map ~f:mk_binding (Gen.ty_var_list_of_ctyp parms [])
    in
    match sexp_of_type tp with
    | `Fun fun_expr -> `Fun <:expr@loc< let $list:bindings$ in $fun_expr$ >>
    | `Match matchings ->
        `Match
          <:match_case@loc<
            arg ->
              let $list:bindings$ in
              match arg with
              [ $matchings$ ]
          >>


  (* Conversion of sum types *)

  let rec branch_sum = function
    | <:ctyp@loc< $tp1$ | $tp2$ >> ->
        <:match_case@loc< $branch_sum tp1$ | $branch_sum tp2$ >>
    | <:ctyp@loc< $uid:cnstr$ >> ->
        <:match_case@loc< $uid:cnstr$ -> Sexplib.Sexp.Atom $str:cnstr$ >>
    | <:ctyp@loc< $uid:cnstr$ of sexp_list $tp$>> ->
        let cnv_expr =
          match sexp_of_type tp with
          | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
          | `Match matchings ->
              <:expr@loc< fun el -> match el with [ $matchings$ ] >>
        in
        <:match_case@loc<
          $uid:cnstr$ l ->
             Sexplib.Sexp.List
               [Sexplib.Sexp.Atom $str:cnstr$ ::
                   Sexplib.Conv.list_map $cnv_expr$ l]
        >>
    | <:ctyp@loc< $uid:cnstr$ of $tps$ >> ->
        let fps = List.map ~f:sexp_of_type (Ast.list_of_ctyp tps []) in
        let cnstr_expr = <:expr@loc< Sexplib.Sexp.Atom $str:cnstr$ >> in
        let bindings, patts, vars = mk_bindings loc fps in
        let patt =
          match patts with
          | [patt] -> patt
          | _ -> <:patt@loc< ( $tup:Ast.paCom_of_list patts$ ) >>
        in
        <:match_case@loc<
          $uid:cnstr$ $patt$ ->
            let $bindings$ in
            Sexplib.Sexp.List $Gen.mk_expr_lst loc (cnstr_expr :: vars)$
        >>
    | tp -> Gen.unknown_type tp "branch_sum"

  let sexp_of_sum alts = `Match (branch_sum alts)


  (* Conversion of record types *)

  let mk_rec_patt loc patt name =
    let p = <:patt@loc< $lid:name$ = $lid:"v_" ^ name$ >> in
    <:patt@loc< $patt$; $p$ >>

  let sexp_of_record_field patt expr name tp ?sexp_of test =
    let loc = Ast.loc_of_ctyp tp in
    let patt = mk_rec_patt loc patt name in
    let cnv_expr =
      match sexp_of_type tp with
      | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
      | `Match matchings ->
          <:expr@loc< fun el -> match el with [ $matchings$ ] >>
    in
    let cnv_expr =
      match sexp_of with
      | None -> cnv_expr
      | Some sexp_of -> <:expr@loc< $sexp_of$ $cnv_expr$ >>
    in
    let expr =
      let v_name = <:expr@loc< $lid: "v_" ^ name$ >> in
      <:expr@loc<
        let bnds =
          if $test$ $v_name$ then bnds
          else
            let arg = $cnv_expr$ $v_name$ in
            let bnd =
              Sexplib.Sexp.List [Sexplib.Sexp.Atom $str:name$; arg]
            in
            [ bnd :: bnds ]
        in
        $expr$
      >>
    in
    patt, expr

  let sexp_of_default_field patt expr name tp ?sexp_of default =
    let loc = Ast.loc_of_expr default in
    sexp_of_record_field patt expr name tp ?sexp_of
      <:expr@loc< (=) $default$ >>

  let sexp_of_record flds_ctyp =
    let flds = Ast.list_of_ctyp flds_ctyp [] in
    let rec coll (patt, expr) = function
      | <:ctyp@loc< $lid:name$ : mutable sexp_option $tp$ >>
      | <:ctyp@loc< $lid:name$ : sexp_option $tp$ >> ->
          let patt = mk_rec_patt loc patt name in
          let vname = <:expr@loc< v >> in
          let cnv_expr = unroll_cnv_fp loc vname (sexp_of_type tp) in
          let expr =
            <:expr@loc<
              let bnds =
                match $lid:"v_" ^ name$ with
                [ None -> bnds
                | Some v ->
                    let arg = $cnv_expr$ in
                    let bnd =
                      Sexplib.Sexp.List [Sexplib.Sexp.Atom $str:name$; arg]
                    in
                    [ bnd :: bnds ] ]
              in
              $expr$
            >>
          in
          patt, expr
      | <:ctyp@loc< $lid:name$ : mutable sexp_bool >>
      | <:ctyp@loc< $lid:name$ : sexp_bool >> ->
          let patt = mk_rec_patt loc patt name in
          let expr =
            <:expr@loc<
              let bnds =
                if $lid:"v_" ^ name$ then
                  let bnd = Sexplib.Sexp.List [Sexplib.Sexp.Atom $str:name$] in
                  [ bnd :: bnds ]
                else bnds
              in
              $expr$
            >>
          in
          patt, expr
      | <:ctyp@loc< $lid:name$ : mutable sexp_list $tp$ >>
      | <:ctyp@loc< $lid:name$ : sexp_list $tp$ >> ->
          sexp_of_default_field patt expr name tp
            ~sexp_of:<:expr@loc< sexp_of_list >> <:expr@loc< [] >>
      | <:ctyp@loc< $lid:name$ : mutable sexp_array $tp$ >>
      | <:ctyp@loc< $lid:name$ : sexp_array $tp$ >> ->
          sexp_of_default_field patt expr name tp
            ~sexp_of:<:expr@loc< sexp_of_array >> <:expr@loc< [||] >>
      | <:ctyp@loc< $lid:name$ : mutable $tp$ >>
      | <:ctyp@loc< $lid:name$ : $tp$ >> ->
          let opt_default = Pa_type_conv.Gen.find_record_default loc in
          let field_handler = get_record_field_handler loc in
          begin match opt_default, field_handler with
          | None, `drop_default -> Loc.raise loc (Failure "no default to drop")
          | _, `drop_if test -> sexp_of_record_field patt expr name tp test
          | Some default, `drop_default ->
              sexp_of_default_field patt expr name tp default
          | _, `keep ->
              let patt = mk_rec_patt loc patt name in
              let vname = <:expr@loc< $lid:"v_" ^ name$ >> in
              let cnv_expr = unroll_cnv_fp loc vname (sexp_of_type tp) in
              let expr =
                <:expr@loc<
                  let arg = $cnv_expr$ in
                  let bnd =
                    Sexplib.Sexp.List [Sexplib.Sexp.Atom $str:name$; arg]
                  in
                  let bnds = [ bnd :: bnds ] in
                  $expr$
                >>
              in
              patt, expr
          end
      | _ -> assert false  (* impossible *)
    in
    let loc = Ast.loc_of_ctyp flds_ctyp in
    let init_expr = <:expr@loc< Sexplib.Sexp.List bnds >> in
    let patt, expr =
      List.fold_left ~f:coll ~init:(<:patt@loc<>>, init_expr) flds
    in
    `Match
      <:match_case@loc<
        { $patt$ } ->
          let bnds = [] in
          $expr$
      >>


  (* Empty type *)
  let sexp_of_nil loc = `Fun <:expr@loc< fun _v -> assert False >>


  (* Generate code from type definitions *)

  let sexp_of_td loc type_name tps rhs =
    let body =
      let rec loop tp =
        Gen.switch_tp_def tp
          ~alias:(fun (_ : Loc.t) tp -> sexp_of_type tp)
          ~sum:(fun (_ : Loc.t) tp -> sexp_of_sum tp)
          ~record:(fun (_ : Loc.t) tp -> sexp_of_record tp)
          ~variants:(fun (_ : Loc.t) tp -> sexp_of_variant tp)
          ~mani:(fun (_ : Loc.t) _tp1 tp2 -> loop tp2)
          ~nil:sexp_of_nil
      in
      match loop rhs with
      | `Fun fun_expr ->
          (* Prevent violation of value restriction and problems with
             recursive types by eta-expanding function definitions *)
          <:expr@loc< fun [ v -> $fun_expr$ v ] >>
      | `Match matchings -> <:expr@loc< fun [ $matchings$ ] >>
    in
    let mk_pat id = <:patt@loc< $lid:id$ >> in
    let patts =
      List.map tps
        ~f:(fun ty -> <:patt@loc< $lid:"_of_" ^ Gen.get_tparam_id ty$>>)
    in
    let bnd = mk_pat ("sexp_of_" ^ type_name) in
    <:binding@loc< $bnd$ = $Gen.abstract loc patts body$ >>

  let rec sexp_of_tds = function
    | Ast.TyDcl (loc, type_name, tps, rhs, _cl) ->
        sexp_of_td loc type_name tps rhs
    | Ast.TyAnd (loc, tp1, tp2) ->
        <:binding@loc< $sexp_of_tds tp1$ and $sexp_of_tds tp2$ >>
    | _ -> assert false  (* impossible *)

  let sexp_of tds =
    let binding, recursive, loc =
      match tds with
      | Ast.TyDcl (loc, type_name, tps, rhs, _cl) ->
          sexp_of_td loc type_name tps rhs,
          Gen.type_is_recursive type_name rhs, loc
      | Ast.TyAnd (loc, _, _) as tds -> sexp_of_tds tds, true, loc
      | _ -> assert false  (* impossible *)
    in
    if recursive then <:str_item@loc< value rec $binding$ >>
    else <:str_item@loc< value $binding$ >>

  (* Add code generator to the set of known generators *)
  let () = Pa_type_conv.add_generator "sexp_of" sexp_of

  let string_of_ident id =
    let str_lst = Gen.get_rev_id_path id [] in
    String.concat ~sep:"." str_lst

  let sexp_of_exn tp =
    let get_full_cnstr cnstr = Pa_type_conv.get_conv_path () ^ "." ^ cnstr in
    let expr =
      match tp with
      | <:ctyp@loc< $uid:cnstr$ >> ->
          <:expr@loc<
            Sexplib.Exn_magic.register $uid:cnstr$ $str:get_full_cnstr cnstr$
          >>
      | <:ctyp@loc< $uid:cnstr$ of $tps$ >> ->
          let ctyps = Ast.list_of_ctyp tps [] in
          let fps = List.map ~f:sexp_of_type ctyps in
          let sexp_converters =
            List.map fps ~f:(function
            | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
            | `Match matchings -> <:expr@loc< fun [ $matchings$ ] >>)
          in
          let _, patts, vars = mk_bindings loc fps in
          let register_name = sprintf "register%d" (List.length fps) in
          let make_exc =
            let var_args =
              match vars with
              | [var] -> var
              | _ -> <:expr@loc< $tup:Ast.exCom_of_list vars$ >>
            in
            Gen.abstract loc patts <:expr@loc< $uid:cnstr$ $var_args$ >>
          in
          let call =
            let partial =
              <:expr@loc<
                Sexplib.Exn_magic.$lid:register_name$
                  $make_exc$ $str:get_full_cnstr cnstr$
              >>
            in
            Gen.apply loc partial sexp_converters
          in
          <:expr@loc< $call$ >>
      | tp -> Gen.unknown_type tp "sexp_of_exn"
    in
    let loc = Ast.loc_of_ctyp tp in
    <:str_item@loc< value () = $expr$ >>

  let () = Pa_type_conv.add_generator ~is_exn:true "sexp" sexp_of_exn
end


(* Generator for converters of S-expressions to OCaml-values *)
module Generate_of_sexp = struct
  let mk_abst_call loc tn ?(internal = false) rev_path =
    let tns = tn ^ "_of_sexp" in
    let tns_suff = if internal then tns ^ "__" else tns in
    <:expr@loc< $id:Gen.ident_of_rev_path loc (tns_suff :: rev_path)$ >>

  (* Utility functions for polymorphic variants *)

  (* Handle backtracking when variants do not match *)
  let handle_no_variant_match loc expr =
    <:match_case@loc< Sexplib.Conv_error.No_variant_match _ -> $expr$ >>

  let is_wildcard = function [_] -> true | _ -> false

  (* Generate code depending on whether to generate a match for the last
     case of matching a variant *)
  let handle_variant_match_last loc match_last matches =
    if match_last || is_wildcard matches then
      match matches with
      | <:match_case< $_$ -> $expr$ >> :: _ -> expr
      | _ -> assert false  (* impossible *)
    else <:expr@loc< match atom with [ $list:matches$ ] >>

  (* Generate code for matching malformed S-expressions *)
  let mk_variant_other_matches loc rev_els call =
    let coll_structs acc (loc, cnstr) =
      <:match_case@loc<
        $str:cnstr$ -> Sexplib.Conv_error.$lid:call$ _tp_loc _sexp
      >> :: acc
    in
    let exc_no_variant_match =
      <:match_case@loc<
        _ -> Sexplib.Conv_error.no_variant_match _tp_loc _sexp
      >>
    in
    List.fold_left ~f:coll_structs ~init:[exc_no_variant_match] rev_els

  (* Split the row fields of a variant type into lists of atomic variants,
     structured variants, atomic variants + included variant types,
     and structured variants + included variant types. *)
  let rec split_row_field (atoms, structs, ainhs, sinhs as acc) = function
    | <:ctyp@loc< `$cnstr$ >> ->
        let tpl = loc, cnstr in
        (
          tpl :: atoms,
          structs,
          `A tpl :: ainhs,
          sinhs
        )
    | <:ctyp@loc< `$cnstr$ of $tps$ >> ->
        (
          atoms,
          (loc, cnstr) :: structs,
          ainhs,
          `S (loc, cnstr, tps) :: sinhs
        )
    | <:ctyp< [< $row_fields$ ] >> | <:ctyp< [> $row_fields$ ] >>
    | <:ctyp< [= $row_fields$ ] >> ->
        List.fold_left ~f:split_row_field
          ~init:acc (Ast.list_of_ctyp row_fields [])
    | <:ctyp< $_$ $_$ >>
    | (<:ctyp< $id:_$ >> | <:ctyp< #$id:_$ >>) as inh ->
        let iinh = `I inh in
        (
          atoms,
          structs,
          iinh :: ainhs,
          iinh :: sinhs
        )
    | tp -> Gen.unknown_type tp "split_row_field"

  (* Conversion of type paths *)
  let path_of_sexp_fun loc id =
    match Gen.get_rev_id_path id [] with
    | tn :: rev_path -> mk_abst_call loc tn rev_path
    | [] -> assert false  (* no empty paths *)

  (* Conversion of types *)
  let rec type_of_sexp = function
    | <:ctyp@loc< sexp_opaque $_$ >> ->
        `Fun <:expr@loc< Sexplib.Conv.opaque_of_sexp >>
    | <:ctyp@loc< sexp_option >> ->
        `Fun <:expr@loc< fun a_of_sexp v -> Some (a_of_sexp v) >>
    | <:ctyp@loc< sexp_list >> ->
        `Fun <:expr@loc< fun a_of_sexp v ->
          Sexplib.Conv.list_of_sexp a_of_sexp v >>
    | <:ctyp@loc< sexp_array >> ->
        `Fun <:expr@loc< fun a_of_sexp v ->
          Sexplib.Conv.array_of_sexp a_of_sexp v >>
    | <:ctyp@loc< $tp1$ $tp2$ >> ->
        let fp1 = type_of_sexp tp1 in
        let fp2 = type_of_sexp tp2 in
        `Fun (unroll_fun_matches loc fp1 fp2)
    | <:ctyp< ( $tup:tp$ ) >> -> tuple_of_sexp tp
    | <:ctyp@loc< '$parm$ >> -> `Fun <:expr@loc< $lid:"_of_" ^ parm$ >>
    | <:ctyp@loc< $id:id$ >> -> `Fun (path_of_sexp_fun loc id)
    | <:ctyp@loc< $_$ -> $_$ >> as arrow ->
        `Fun <:expr@loc< fun sexp ->
          (Sexplib.Conv.fun_of_sexp sexp : $arrow$) >>
    | <:ctyp< [< $row_fields$ ] >> | <:ctyp< [> $row_fields$ ] >>
    | <:ctyp< [= $row_fields$ ] >> ->
        variant_of_sexp ?full_type:None row_fields
    | <:ctyp< ! $parms$ . $poly_tp$ >> -> poly_of_sexp parms poly_tp
    | tp -> Gen.unknown_type tp "type_of_sexp"

  (* Conversion of tuples *)
  and tuple_of_sexp tps =
    let fps = List.map ~f:type_of_sexp (Ast.list_of_ctyp tps []) in
    let loc = Ast.loc_of_ctyp tps in
    let bindings, patts, vars = mk_bindings loc fps in
    let n = string_of_int (List.length fps) in
    `Match
      <:match_case@loc<
          Sexplib.Sexp.List $Gen.mk_patt_lst loc patts$ ->
            let $bindings$ in
            ( $tup:Ast.exCom_of_list vars$ )
        | sexp ->
            Sexplib.Conv_error.tuple_of_size_n_expected _tp_loc $int:n$ sexp
      >>

  (* Generate internal call *)
  and mk_internal_call = function
    | <:ctyp@loc< $id:id$ >> | <:ctyp@loc< #$id:id$ >> ->
        let call =
          match Gen.get_rev_id_path id [] with
          | tn :: rev_path -> mk_abst_call loc tn ~internal:true rev_path
          | [] -> assert false  (* impossible *)
        in
        call
    | <:ctyp@loc< $tp1$ $tp2$ >> ->
        let fp1 = `Fun (mk_internal_call tp1) in
        let fp2 = type_of_sexp tp2 in
        unroll_fun_matches loc fp1 fp2
    | _ -> assert false  (* impossible *)

  (* Generate code for matching included variant types *)
  and handle_variant_inh full_type match_last other_matches inh =
    let loc = Ast.loc_of_ctyp inh in
    let fun_expr = mk_internal_call inh in
    let match_exc =
      handle_no_variant_match loc (
        handle_variant_match_last loc match_last other_matches) in
    let new_other_matches =
      [
        <:match_case@loc<
          _ -> try ($fun_expr$ _sexp :> $full_type$) with [ $match_exc$ ]
        >>
      ]
    in
    new_other_matches, true

  (* Generate code for matching atomic variants *)
  and mk_variant_match_atom loc full_type rev_atoms_inhs rev_structs =
    let coll (other_matches, match_last) = function
      | `A (loc, cnstr) ->
          let new_match = <:match_case@loc< $str:cnstr$ -> `$cnstr$ >> in
          new_match :: other_matches, false
      | `I inh ->
          handle_variant_inh full_type match_last other_matches inh
    in
    let other_matches =
      mk_variant_other_matches loc rev_structs "ptag_no_args"
    in
    let match_atoms_inhs, match_last =
      List.fold_left ~f:coll ~init:(other_matches, false) rev_atoms_inhs in
    handle_variant_match_last loc match_last match_atoms_inhs


  (* Variant conversions *)

  (* Match arguments of constructors (variants or sum types) *)
  and mk_cnstr_args_match ~is_variant cnstr tps =
    let loc = Ast.loc_of_ctyp tps in
    let cnstr vars_expr =
      if is_variant then <:expr@loc< `$cnstr$ $vars_expr$ >>
      else <:expr@loc< $uid:cnstr$ $vars_expr$ >>
    in
    match tps with
    | <:ctyp@loc< sexp_list $tp$ >> ->
      let cnv =
        match type_of_sexp tp with
        | `Fun fun_expr -> <:expr@loc< $fun_expr$ >>
        | `Match matchings ->
            <:expr@loc< fun el -> match el with [ $matchings$ ] >>
      in
      cnstr <:expr@loc< Sexplib.Conv.list_map ($cnv$) sexp_args >>
    | _ ->
        let fps = List.map ~f:type_of_sexp (Ast.list_of_ctyp tps []) in
        let bindings, patts, vars = mk_bindings loc fps in
        let good_arg_match =
          let vars_expr =
            match vars with
            | [var_expr] -> var_expr
            | _ -> <:expr@loc< ( $tup:Ast.exCom_of_list vars$ ) >>
          in
          cnstr vars_expr
        in
        let handle_exc =
          if is_variant then "ptag_incorrect_n_args"
          else "stag_incorrect_n_args"
        in
        <:expr@loc<
          match sexp_args with
            [ $Gen.mk_patt_lst loc patts$ -> let $bindings$ in $good_arg_match$
            | _ -> Sexplib.Conv_error.$lid:handle_exc$ _tp_loc _tag _sexp ]
        >>

  (* Generate code for matching structured variants *)
  and mk_variant_match_struct loc full_type rev_structs_inhs rev_atoms =
    let has_structs_ref = ref false in
    let coll (other_matches, match_last) = function
      | `S (loc, cnstr, tps) ->
          has_structs_ref := true;
          let expr = mk_cnstr_args_match ~is_variant:true cnstr tps in
          let new_match =
            <:match_case@loc< ($str:cnstr$ as _tag) -> $expr$ >>
          in
          new_match :: other_matches, false
      | `I inh ->
          handle_variant_inh full_type match_last other_matches inh
    in
    let other_matches =
      mk_variant_other_matches loc rev_atoms "ptag_no_args"
    in
    let match_structs_inhs, match_last =
      List.fold_left ~f:coll ~init:(other_matches, false) rev_structs_inhs
    in
    (
      handle_variant_match_last loc match_last match_structs_inhs,
      !has_structs_ref
    )

  (* Generate code for handling atomic and structured variants (i.e. not
     included variant types) *)
  and handle_variant_tag loc full_type row_fields =
    let rev_atoms, rev_structs, rev_atoms_inhs, rev_structs_inhs =
      List.fold_left ~f:split_row_field ~init:([], [], [], []) row_fields
    in
    let match_struct, has_structs =
      mk_variant_match_struct loc full_type rev_structs_inhs rev_atoms in
    let maybe_sexp_args_patt =
      if has_structs then <:patt@loc< sexp_args >>
      else <:patt@loc< _ >>
    in
    <:match_case@loc<
        Sexplib.Sexp.Atom atom as _sexp ->
          $mk_variant_match_atom loc full_type rev_atoms_inhs rev_structs$
      | Sexplib.Sexp.List
          [Sexplib.Sexp.Atom atom :: $maybe_sexp_args_patt$] as _sexp ->
            $match_struct$
      | Sexplib.Sexp.List [Sexplib.Sexp.List _ :: _] as sexp ->
          Sexplib.Conv_error.nested_list_invalid_poly_var _tp_loc sexp
      | Sexplib.Sexp.List [] as sexp ->
          Sexplib.Conv_error.empty_list_invalid_poly_var _tp_loc sexp
    >>

  (* Generate matching code for variants *)
  and variant_of_sexp ?full_type row_tp =
    let loc = Ast.loc_of_ctyp row_tp in
    let row_fields = Ast.list_of_ctyp row_tp [] in
    let is_contained, full_type =
      match full_type with
      | None -> true, <:ctyp@loc< [= $row_tp$ ] >>
      | Some full_type -> false, full_type
    in
    let top_match =
      match row_fields with
      | (<:ctyp< $id:_$ >> | <:ctyp< $_$ $_$ >>) as inh :: rest ->
          let rec loop inh row_fields =
            let call =
              <:expr@loc< ( $mk_internal_call inh$ sexp :> $full_type$ ) >>
            in
            match row_fields with
            | [] -> call
            | h :: t ->
                let expr =
                  match h with
                  | <:ctyp< $id:_$ >> | <:ctyp< $_$ $_$ >> -> loop h t
                  | _ ->
                     let rftag_matches =
                       handle_variant_tag loc full_type row_fields
                     in
                     <:expr@loc< match sexp with [ $rftag_matches$ ] >>
                in
                <:expr@loc<
                  try $call$ with
                  [ $handle_no_variant_match loc expr$ ]
                >>
          in
          <:match_case@loc< sexp -> $loop inh rest$ >>
      | _ :: _ -> handle_variant_tag loc full_type row_fields
      | [] -> assert false  (* impossible *)
    in
    if is_contained then
      `Fun
        <:expr@loc<
          fun sexp ->
            try match sexp with [ $top_match$ ]
            with
            [ Sexplib.Conv_error.No_variant_match (_tp_loc, sexp) ->
                Sexplib.Conv_error.no_matching_variant_found _tp_loc sexp
            ]
        >>
    else `Match top_match

  and poly_of_sexp parms tp =
    let loc = Ast.loc_of_ctyp tp in
    let bindings =
      let mk_binding parm =
        <:binding@loc<
          $lid:"_of_" ^ parm$ =
            fun sexp -> Sexplib.Conv_error.record_poly_field_value _tp_loc sexp
        >>
      in
      List.map ~f:mk_binding (Gen.ty_var_list_of_ctyp parms [])
    in
    match type_of_sexp tp with
    | `Fun fun_expr -> `Fun <:expr@loc< let $list:bindings$ in $fun_expr$ >>
    | `Match matchings ->
        `Match
          <:match_case@loc<
            arg ->
              let $list:bindings$ in
              match arg with
              [ $matchings$ ]
          >>


  (* Sum type conversions *)

  (* Generate matching code for well-formed S-expressions wrt. sum types *)
  let rec mk_good_sum_matches = function
    | <:ctyp@loc< $uid:cnstr$ >> ->
        let lccnstr = String.uncapitalize cnstr in
        <:match_case@loc<
          Sexplib.Sexp.Atom ($str:lccnstr$ | $str:cnstr$) -> $uid:cnstr$
        >>
    | <:ctyp@loc< $uid:cnstr$ of $tps$ >> ->
        let lccnstr = String.uncapitalize cnstr in
        <:match_case@loc<
          (Sexplib.Sexp.List
            [Sexplib.Sexp.Atom ($str:lccnstr$ | $str:cnstr$ as _tag) ::
              sexp_args] as _sexp) ->
                $mk_cnstr_args_match ~is_variant:false cnstr tps$
        >>
    | <:ctyp@loc< $tp1$ | $tp2$ >> ->
        <:match_case@loc<
            $mk_good_sum_matches tp1$
          | $mk_good_sum_matches tp2$
        >>
    | _ -> assert false  (* impossible *)

  (* Generate matching code for malformed S-expressions with good tags
     wrt. sum types *)
  let rec mk_bad_sum_matches = function
    | <:ctyp@loc< $uid:cnstr$ >> ->
        let lccnstr = String.uncapitalize cnstr in
        <:match_case@loc<
          Sexplib.Sexp.List
            [Sexplib.Sexp.Atom ($str:lccnstr$ | $str:cnstr$) :: _] as sexp ->
              Sexplib.Conv_error.stag_no_args _tp_loc sexp
        >>
    | <:ctyp@loc< $uid:cnstr$ of $_$ >> ->
        let lccnstr = String.uncapitalize cnstr in
        <:match_case@loc<
          Sexplib.Sexp.Atom ($str:lccnstr$ | $str:cnstr$) as sexp ->
            Sexplib.Conv_error.stag_takes_args _tp_loc sexp
        >>
    | <:ctyp@loc< $tp1$ | $tp2$ >> ->
        <:match_case@loc<
            $mk_bad_sum_matches tp1$
          | $mk_bad_sum_matches tp2$
        >>
    | _ -> assert false  (* impossible *)

  (* Generate matching code for sum types *)
  let sum_of_sexp alts =
    let loc = Ast.loc_of_ctyp alts in
    `Match
      <:match_case@loc<
          $mk_good_sum_matches alts$
        | $mk_bad_sum_matches alts$
        | Sexplib.Sexp.List [Sexplib.Sexp.List _ :: _] as sexp ->
            Sexplib.Conv_error.nested_list_invalid_sum _tp_loc sexp
        | Sexplib.Sexp.List [] as sexp ->
            Sexplib.Conv_error.empty_list_invalid_sum _tp_loc sexp
        | sexp -> Sexplib.Conv_error.unexpected_stag _tp_loc sexp
      >>


  (* Record conversions *)

  (* Generate code for extracting record fields *)
  let mk_extract_fields tp =
    let rec loop no_args args = function
      | <:ctyp< $tp1$; $tp2$ >> ->
          let no_args, args = loop no_args args tp2 in
          loop no_args args tp1
      | <:ctyp@loc< $lid:nm$ : mutable sexp_bool >>
      | <:ctyp@loc< $lid:nm$ : sexp_bool>> ->
          let no_args =
            <:match_case@loc<
                $str:nm$ ->
                  if $lid:nm ^ "_field"$.val then
                    duplicates.val := [ field_name :: duplicates.val ]
                  else $lid:nm ^ "_field"$.val := True
              | $no_args$
            >>
          in
          no_args, args
      | <:ctyp@loc< $lid:nm$ : mutable sexp_option $tp$ >>
      | <:ctyp@loc< $lid:nm$ : sexp_option $tp$ >>
      | <:ctyp@loc< $lid:nm$ : mutable $tp$ >>
      | <:ctyp@loc< $lid:nm$ : $tp$ >> ->
          let unrolled =
            unroll_cnv_fp loc <:expr@loc< _field_sexp >> (type_of_sexp tp)
          in
          let args =
            <:match_case@loc<
                $str:nm$ ->
                  match $lid:nm ^ "_field"$.val with
                  [ None ->
                      let fvalue = $unrolled$ in
                      $lid:nm ^ "_field"$.val := Some fvalue
                  | Some _ ->
                      duplicates.val := [ field_name :: duplicates.val ] ]
              | $args$
            >>
          in
          no_args, args
        | _ -> assert false  (* impossible *)
    in
    let handle_extra =
      let loc = Ast.loc_of_ctyp tp in
      <:match_case@loc<
        _ ->
          if Sexplib.Conv.record_check_extra_fields.val then
            extra.val := [ field_name :: extra.val ]
          else ()
      >>
    in
    loop handle_extra handle_extra tp

  (* Generate code for handling the result of matching record fields *)
  let mk_handle_record_match_result has_poly flds =
    let has_nonopt_fields = ref false in
    let res_tpls, bi_lst, good_patts =
      let rec loop (res_tpls, bi_lst, good_patts as acc) = function
        | <:ctyp@loc< $lid:nm$ : $tp$ >> ->
            let fld = <:expr@loc< $lid:nm ^ "_field"$.val >> in
            let mk_default loc =
              bi_lst, <:patt@loc< $lid:nm ^ "_value"$ >> :: good_patts
            in
            let new_bi_lst, new_good_patts =
              match tp with
              | <:ctyp@loc< sexp_bool >> | <:ctyp@loc< mutable sexp_bool >>
              | <:ctyp@loc< sexp_option $_$ >>
              | <:ctyp@loc< mutable sexp_option $_$ >>
              | <:ctyp@loc< sexp_list $_$ >>
              | <:ctyp@loc< mutable sexp_list $_$ >>
              | <:ctyp@loc< sexp_array $_$ >>
              | <:ctyp@loc< mutable sexp_array $_$ >> -> mk_default loc
              | <:ctyp@loc< $_$ >> ->
                  match Pa_type_conv.Gen.find_record_default loc with
                  | Some _ -> mk_default loc
                  | None ->
                      has_nonopt_fields := true;
                      (
                        <:expr@loc<
                          (Pervasives.(=) $fld$ None, $str:nm$) >> :: bi_lst,
                        <:patt@loc< Some $lid:nm ^ "_value"$ >> :: good_patts
                      )
            in
            (
              <:expr@loc< $fld$ >> :: res_tpls,
              new_bi_lst,
              new_good_patts
            )
        | <:ctyp< $tp1$; $tp2$ >> -> loop (loop acc tp2) tp1
        | _ -> assert false  (* impossible *)
      in
      loop ([], [], []) flds
    in
    let loc = Ast.loc_of_ctyp flds in
    let match_good_expr =
      if has_poly then
        let rec loop acc = function
          | <:ctyp< $tp1$; $tp2$ >> -> loop (loop acc tp2) tp1
          | <:ctyp@loc< $lid:nm$ : $_$ >> ->
              <:expr@loc< $lid:nm ^ "_value"$ >> :: acc
          | _ -> assert false  (* impossible *)
        in
        match loop [] flds with
        | [match_good_expr] -> match_good_expr
        | match_good_exprs ->
            <:expr@loc< $tup:Ast.exCom_of_list match_good_exprs$ >>
      else
        let rec loop = function
          | <:ctyp@loc< $tp1$; $tp2$ >> ->
              <:rec_binding@loc< $loop tp1$; $loop tp2$ >>
          | <:ctyp@loc< $lid:nm$ : mutable sexp_list $_$ >>
          | <:ctyp@loc< $lid:nm$ : sexp_list $_$ >> ->
              <:rec_binding@loc<
                $lid:nm$ =
                  match $lid:nm ^ "_value"$ with
                  [ None -> [] | Some v -> v ]
              >>
          | <:ctyp@loc< $lid:nm$ : mutable sexp_array $_$ >>
          | <:ctyp@loc< $lid:nm$ : sexp_array $_$ >> ->
              <:rec_binding@loc<
                $lid:nm$ =
                  match $lid:nm ^ "_value"$ with
                  [ None -> [||] | Some v -> v ]
              >>
          | <:ctyp@loc< $lid:nm$ : mutable $_$ >>
          | <:ctyp@loc< $lid:nm$ : $_$ >> ->
              begin match Pa_type_conv.Gen.find_record_default loc with
              | None -> <:rec_binding@loc< $lid:nm$ = $lid:nm ^ "_value"$ >>
              | Some default ->
                  <:rec_binding@loc<
                    $lid:nm$ =
                      match $lid:nm ^ "_value"$ with
                      [ None -> $default$ | Some v -> v ]
                  >>
              end
          | _ -> assert false  (* impossible *)
        in
        <:expr@loc< { $loop flds$ } >>
    in
    let expr, patt =
      match res_tpls, good_patts with
      | [res_expr], [res_patt] -> res_expr, res_patt
      | _ ->
          <:expr@loc< $tup:Ast.exCom_of_list res_tpls$ >>,
          <:patt@loc< $tup:Ast.paCom_of_list good_patts$ >>
    in
    if !has_nonopt_fields then
      <:expr@loc<
        match $expr$ with
        [ $patt$ -> $match_good_expr$
        | _ ->
            Sexplib.Conv_error.record_undefined_elements _tp_loc sexp
              $Gen.mk_expr_lst loc bi_lst$
        ]
      >>
    else <:expr@loc< match $expr$ with [ $patt$ -> $match_good_expr$ ] >>

  (* Generate code for converting record fields *)
  let mk_cnv_fields has_poly flds =
    let field_refs =
      let rec loop = function
        | <:ctyp@loc< $tp1$; $tp2$ >> ->
            <:binding@loc< $loop tp1$ and $loop tp2$ >>
        | <:ctyp@loc< $lid:nm$ : sexp_bool >> ->
            <:binding@loc< $lid:nm ^ "_field"$ = ref False >>
        | <:ctyp@loc< $lid:nm$ : $_$ >> ->
            <:binding@loc< $lid:nm ^ "_field"$ = ref None >>
        | _ -> assert false  (* impossible *)
      in
      loop flds
    in
    let mc_no_args_fields, mc_fields_with_args = mk_extract_fields flds in
    let loc = Ast.loc_of_ctyp flds in
    <:expr@loc<
      let $field_refs$ and duplicates = ref [] and extra = ref [] in
      let rec iter = fun
        [ [
            Sexplib.Sexp.List
              [(Sexplib.Sexp.Atom field_name); _field_sexp] ::
            tail
          ] ->
            do {
              match field_name with
              [ $mc_fields_with_args$ ];
              iter tail }
        | [Sexplib.Sexp.List [(Sexplib.Sexp.Atom field_name)] :: tail] ->
            do {
              match field_name with
              [ $mc_no_args_fields$ ];
              iter tail }
        | [((Sexplib.Sexp.Atom _ | Sexplib.Sexp.List _) as sexp) :: _] ->
            Sexplib.Conv_error.record_only_pairs_expected _tp_loc sexp
        | [] -> () ]
      in
      do {
        iter field_sexps;
        if Pervasives.(<>) duplicates.val [] then
          Sexplib.Conv_error.record_duplicate_fields
            _tp_loc duplicates.val sexp
        else if Pervasives.(<>) extra.val [] then
          Sexplib.Conv_error.record_extra_fields _tp_loc extra.val sexp
        else $mk_handle_record_match_result has_poly flds$
      }
    >>

  let rec is_poly = function
    | <:ctyp< $_$ : ! $_$ . $_$ >> -> true
    | <:ctyp< $flds1$; $flds2$ >> -> is_poly flds1 || is_poly flds2
    | _ -> false

  (* Generate matching code for records *)
  let record_of_sexp flds =
    let loc = Ast.loc_of_ctyp flds in
    let handle_fields =
      let has_poly = is_poly flds in
      let cnv_fields = mk_cnv_fields has_poly flds in
      if has_poly then
        let is_singleton_ref = ref true in
        let patt =
          let rec loop = function
            | <:ctyp@loc< $tp1$; $tp2$ >> ->
                is_singleton_ref := false;
                <:patt@loc< $loop tp1$, $loop tp2$ >>
            | <:ctyp@loc< $lid:nm$ : $_$ >> -> <:patt@loc< $lid:nm$ >>
            | _ -> assert false  (* impossible *)
          in
          let patt = loop flds in
          if !is_singleton_ref then patt
          else <:patt@loc< $tup:patt$ >>
        in
        let record_def =
          let rec loop = function
            | <:ctyp@loc< $tp1$; $tp2$ >> ->
                <:rec_binding@loc< $loop tp1$; $loop tp2$ >>
            | <:ctyp@loc< $lid:nm$ : $_$ >> ->
                <:rec_binding@loc< $lid:nm$ = $lid:nm$ >>
            | _ -> assert false  (* impossible *)
          in
          loop flds
        in
        <:expr@loc<
          let $patt$ = $cnv_fields$ in
          { $record_def$ }
        >>
      else cnv_fields
    in
    `Match
      <:match_case@loc<
          Sexplib.Sexp.List field_sexps as sexp -> $handle_fields$
        | Sexplib.Sexp.Atom _ as sexp ->
            Sexplib.Conv_error.record_list_instead_atom _tp_loc sexp
      >>


  (* Empty type *)
  let nil_of_sexp loc =
    `Fun <:expr@loc< fun sexp -> Sexplib.Conv_error.empty_type _tp_loc sexp >>


  (* Generate code from type definitions *)

  let rec is_poly_call = function
    | <:expr< $f$ $_$ >> -> is_poly_call f
    | <:expr< $lid:name$ >> -> name.[0] = '_' && name.[1] = 'o'
    | _ -> false

  let td_of_sexp loc type_name tps rhs =
    let is_alias_ref = ref false in
    let handle_alias tp =
      is_alias_ref := true;
      type_of_sexp tp
    in
    let coll_args tp param =
      <:ctyp@loc< $tp$ $Gen.drop_variance_annotations param$ >>
    in
    let full_type =
      List.fold_left ~f:coll_args ~init:<:ctyp@loc< $lid:type_name$ >> tps
    in
    let is_variant_ref = ref false in
    let handle_variant row_fields =
      is_variant_ref := true;
      variant_of_sexp ~full_type row_fields
    in
    let body =
      let rec loop tp =
        Gen.switch_tp_def tp
          ~alias:(fun (_ : Loc.t) tp -> handle_alias tp)
          ~sum:(fun (_ : Loc.t) tp -> sum_of_sexp tp)
          ~record:(fun (_ : Loc.t) tp -> record_of_sexp tp)
          ~variants:(fun (_ : Loc.t) tp -> handle_variant tp)
          ~mani:(fun (_ : Loc.t) _tp1 tp2 -> loop tp2)
          ~nil:nil_of_sexp
      in
      match loop rhs with
      | `Fun fun_expr ->
          (* Prevent violation of value restriction and problems with
             recursive types by eta-expanding function definitions *)
          <:expr@loc< fun [ t -> $fun_expr$ t ] >>
      | `Match matchings -> <:expr@loc< fun [ $matchings$ ] >>
    in
    let internal_name = type_name ^ "_of_sexp__" in
    let arg_patts, arg_exprs =
      List.split (
        List.map ~f:(function tp ->
            let name = "_of_" ^ Gen.get_tparam_id tp in
            <:patt@loc< $lid:name$ >>, <:expr@loc< $lid:name$ >>
          )
          tps)
    in
    let with_poly_call = !is_alias_ref && is_poly_call body in
    let internal_fun_body =
      let full_type_name =
        sprintf "%s.%s" (Pa_type_conv.get_conv_path ()) type_name
      in
      if with_poly_call then
        Gen.abstract loc arg_patts
          <:expr@loc<
            fun sexp ->
              Sexplib.Conv_error.silly_type $str:full_type_name$ sexp
          >>
      else
        <:expr@loc<
          let _tp_loc = $str:full_type_name$ in
          $Gen.abstract loc arg_patts body$
        >>
    in
    let pre_external_fun_body =
      let internal_call =
        let internal_expr = <:expr@loc< $lid:internal_name$ >> in
        <:expr@loc< $Gen.apply loc internal_expr arg_exprs$ sexp >>
      in
      let no_variant_match_mc =
        <:match_case@loc<
          Sexplib.Conv_error.No_variant_match (_tp_loc, sexp) ->
            Sexplib.Conv_error.no_matching_variant_found _tp_loc sexp
        >>
      in
      if with_poly_call then
        <:expr@loc< try $body$ sexp with [ $no_variant_match_mc$ ] >>
      (* Type alias may refer to variant, therefore same handling here! *)
      else if !is_variant_ref || !is_alias_ref then
        <:expr@loc< try $internal_call$ with [ $no_variant_match_mc$ ] >>
      else internal_call
    in
    let internal_binding =
      <:binding@loc< $lid:internal_name$ = $internal_fun_body$ >>
    in
    let external_fun_patt = <:patt@loc< $lid:type_name ^ "_of_sexp"$ >> in
    let external_fun_body =
      Gen.abstract loc arg_patts
        <:expr@loc< fun sexp -> $pre_external_fun_body$ >>
    in
    let external_binding =
      <:binding@loc< $external_fun_patt$ = $external_fun_body$ >>
    in
    internal_binding, external_binding

  let rec tds_of_sexp acc = function
    | Ast.TyDcl (loc, type_name, tps, rhs, _cl) ->
        td_of_sexp loc type_name tps rhs :: acc
    | Ast.TyAnd (_, tp1, tp2) -> tds_of_sexp (tds_of_sexp acc tp2) tp1
    | _ -> assert false  (* impossible *)

  (* Generate code from type definitions *)
  let of_sexp = function
    | Ast.TyDcl (loc, type_name, tps, rhs, _cl) ->
        let internal_binding, external_binding =
          td_of_sexp loc type_name tps rhs
        in
        let recursive = Gen.type_is_recursive type_name rhs in
        if recursive then
          <:str_item@loc<
            value rec $internal_binding$
            and $external_binding$
          >>
        else
          <:str_item@loc<
            value $internal_binding$;
            value $external_binding$
          >>
    | Ast.TyAnd (loc, _, _) as tds ->
        let two_bindings = tds_of_sexp [] tds in
        let bindings =
          List.map ~f:(fun (b1, b2) -> <:binding@loc< $b1$ and $b2$ >>)
            two_bindings
        in
        <:str_item@loc< value rec $list:bindings$ >>
    | _ -> assert false  (* impossible *)

  (* Add code generator to the set of known generators *)
  let () = Pa_type_conv.add_generator "of_sexp" of_sexp
end

module Quotations = struct
  let of_sexp_quote loc _loc_name_opt cnt_str =
    Pa_type_conv.set_conv_path_if_not_set loc;
    let ctyp = Gram.parse_string ctyp_quot loc cnt_str in
    let fp = Generate_of_sexp.type_of_sexp ctyp in
    let body =
      match fp with
      | `Fun fun_expr -> <:expr@loc< $fun_expr$ sexp >>
      | `Match matchings -> <:expr@loc< match sexp with [$matchings$] >>
    in
    let full_type_name =
      sprintf "%s line %i: %s"
        (Pa_type_conv.get_conv_path ()) (Loc.start_line loc) cnt_str
    in
    <:expr@loc<
      fun [ sexp ->
        let _tp_loc = $str:full_type_name$ in
        $body$ ]
      >>

  let () =
    Quotation.add "of_sexp" Quotation.DynAst.expr_tag of_sexp_quote

  let sexp_of_quote loc _loc_name_opt cnt_str =
    Pa_type_conv.set_conv_path_if_not_set loc;
    let ctyp = Gram.parse_string ctyp_quot loc cnt_str in
    Generate_sexp_of.mk_cnv_expr ctyp

  let () = Quotation.add "sexp_of" Quotation.DynAst.expr_tag sexp_of_quote
end

(* Add "of_sexp" and "sexp_of" as "sexp" to the set of generators *)
let () =
  Pa_type_conv.add_generator
    "sexp"
    (fun tds ->
      let loc = Ast.loc_of_ctyp tds in
      <:str_item@loc<
        $Generate_of_sexp.of_sexp tds$; $Generate_sexp_of.sexp_of tds$
      >>
    )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.