Skip to content
This repository
tree: f86e58cfa8
Fetching contributors…

Cannot retrieve contributors at this time

file 1444 lines (1113 sloc) 42.22 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
(*
Copyright © 2011 MLstate

This file is part of OPA.

OPA is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.

OPA is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details.

You should have received a copy of the GNU Affero General Public License
along with OPA. If not, see <http://www.gnu.org/licenses/>.
*)
(* CF mli *)

module File = File
module List = Base.List
module String = Base.String
module Format = Base.Format

exception SigInt

let set_signal_sigint () =
  Sys.set_signal Sys.sigint (Sys.Signal_handle (fun _ -> raise SigInt))

let unset_signal_sigint () =
  assert false (* TODO if needed *)

(* The bsl used is the dummy version, bslregister does not generated projection code *)
module BSL = BslLib.BSL

(* alias *)
module BPI = BslPluginInterface
module BI = BslInterface
module BMP = BslMarshalPlugin
module BRI = BSL.RegisterInterface

module BRParse = BslRegisterParser
module BRState = BslRegisterParserState
module BDir = BslDirectives


(*
Types alias and definition.
*)
type language = BslLanguage.t
type filename = string
type module_name = string
type contents = string
type uniq_id = string
type line_number = int
type skey = string
type implementation = string


(* debug *)

let debug fmt =
  OManager.printf ("@[<2>@{<cyan>[bslregister]@}@ "^^fmt^^"@]@.")


(*
Parsing files.
*)


(*
From a previous primitive library, Ordered topologicly
*)
type depends = {
  d_plugins : BPI.plugin list ;

  d_bymap : BSL.ByPassMap.t ;
  d_ml_runtimes : module_name list ;
  d_parents : BPI.plugin_basename list ;

  d_js_code : ( filename * contents ) list ;
  d_opa_code : ( filename * contents ) list ;

}


(*
Some of then are needed, because their name appears in some generated files
*)
type identification = {
  i_basename : BPI.plugin_basename ;

  i_ml_plugin : module_name ;
  i_ml_runtime : module_name ;

  i_uniq_id : uniq_id ;
}

(*
Calls to BRI register_primitive and register_type need to be grouped,
once all languages have been processed.
This type is used for collecting calls, and the effective calls to the
BRI is done only @finalize.

TODO: there is currently a hack about BslTags, the file BslLib expects
BslTags.parsed_t, where is should be BslTags.t.
Once BslLib is no more using a hack about this, we can change
the type of field c_rpi_tags for BslTags.t
*)

type rp_impl = {
  c_rpi_filename : filename ;
  c_rpi_tags : BslTags.parsed_t ;
  c_rpi_implementation : implementation ;
}

type collecting_rp_ips = rp_impl BslLanguageMap.t

type rp_call = {
  c_rp_ks : skey list ;
  c_rp_ty : BslTypes.t ;
  c_rp_ips : collecting_rp_ips ;
  c_rp_obj : implementation option ;
}

type collecting_rp_calls = rp_call BslKeyMap.t

type rt_call = {
  c_rt_ks : skey list ;
  c_rt_ty : BslTypes.t ;
}

type collecting_rt_calls = rt_call BslKeyMap.t

(*
The session
*)

type session = {

  (* 1) static part, built at creation time *)

  s_options : BI.options ;

  s_depends : depends ;
  s_identification : identification ;


  (* 2) evoluation as long as we process files *)

  s_conf : BslConf.t ;
  s_js_confs : BslJsConf.t ;

  s_marshal_plugin_s : BMP.session ;

  s_ml_dynloader_loader : FBuffer.t ;
  s_ml_dynloader_plugin : FBuffer.t ;

  s_rev_js_parsed_files : BslDirectives.bypasslang_decorated_file list ;
  s_rev_ml_parsed_files : BslDirectives.bypasslang_decorated_file list ;

  s_rev_opa_decorated_files : BslDirectives.opalang_decorated_file list ;

  (*
3) collecting calls to the Register Interface.
*)
  s_rp_calls : collecting_rp_calls ;
  s_rt_calls : collecting_rt_calls ;

  (* 4) A pre-finalization, which keep the type session for its representation *)
  (*
opa files may contains include directives which need to be solved at finalization
opa_code and opa_interface are optained at finalization time
*)
  s_js_code : (filename * contents * BslJsConf.conf) list ;

  s_ml_runtime : FBuffer.t ;
  s_ml_runtime_mli : FBuffer.t ;

  s_opa_code : (filename * contents) list ;
  s_opa_interface : (filename * contents) list ;
}


(*
Create
*)


let create_s_fbuffer () = FBuffer.create (8 * 1024)


(*
Load some plugins
*)
let load_plugin plugins =
  let dynlink plugin =
    OManager.verbose "loading primitives from file @{<bright>%S@}" (BslDynlink.file plugin) ;
    BslDynlink.load_bypass_plugin plugin
  in
  List.iter dynlink plugins


(*
Fold depends plugin
*)
let d_fold_plugin
    (rev_ml_runtime_list, rev_parent_list, rev_js_code_list, rev_opa_code_list) plugin =

  BSL.RegisterInterface.dynload_no_obj plugin.BPI.dynloader ;

  let rev_ml_runtime_list = plugin.BPI.ml_runtime :: rev_ml_runtime_list in
  let rev_parent_list = plugin.BPI.basename :: rev_parent_list in
  let rev_js_code_list = List.fold_left (fun rev (f, c, _) -> (f, c)::rev) rev_js_code_list plugin.BPI.js_code in
  let rev_opa_code_list = List.rev_append plugin.BPI.opa_code rev_opa_code_list in

  rev_ml_runtime_list, rev_parent_list, rev_js_code_list, rev_opa_code_list


let create_s_depends options =

  (* This has a side effect on BslPluginTable *)
  load_plugin options.BI.bypass_plugins ;

  let d_plugins = BslPluginTable.finalize () in

  let (ml, prt, js, opa) = List.fold_left d_fold_plugin ([], [], [], []) d_plugins in

  let d_ml_runtimes = List.rev ml in
  let d_parents = List.rev prt in
  let d_js_code = List.rev js in
  let d_opa_code = List.rev opa in


  (* All dynload have been done in d_fold, we can build the depends bymap *)
  let d_bymap = BSL.RegisterTable.build_bypass_map () in

  let depends = {
    d_plugins ;
    d_bymap ;

    d_ml_runtimes ;
    d_parents ;

    d_js_code ;
    d_opa_code ;
  }

  in

  depends


let create_uniq_id name =
  (* FIXME: thing about where does go the function now () *)
  let now = DebugTracer.now in

  let buildinfos = BuildInfos.version_id in
  let now = now () in
  let uniq_id = Printf.sprintf "%s_%s_%s" name buildinfos now in
  uniq_id


let create_s_identification options =
  let i_basename = options.BI.basename in
  let i_ml_plugin = OcamlUtils.Module.of_filename options.BI.ml_plugin_filename in
  let i_ml_runtime = OcamlUtils.Module.of_filename options.BI.ml_runtime_filename in

  let i_uniq_id = create_uniq_id i_ml_plugin in

  let identification = {
    i_basename ;
    i_ml_plugin ;
    i_ml_runtime ;
    i_uniq_id ;
  }

  in

  identification


(* some checks *)
let check_session session =
  let depends = session.s_depends in
  let identification = session.s_identification in

  let error_unicity kind name =
      OManager.error "Generation of @{<bright>%s@} module-clash@\nThe asked target module name @{<bright>%S@} is already used by a previous loaded primitive library@\nPlease specify an other target ( try option --help )@\n" kind name

  in
  (* unicity of plugin names *)
  let _ =
    let ml_plugin = identification.i_basename in
    if List.mem ml_plugin depends.d_parents then
      error_unicity "MLplugin" ml_plugin
  in
  (* unicity of runtime names *)
  let _ =
    let ml_runtime = identification.i_ml_runtime in
    if List.mem ml_runtime depends.d_ml_runtimes then
      error_unicity "MLruntime" ml_runtime
  in

  session


let create ~options =
  let s_options = options in

  let s_depends = create_s_depends options in
  let s_identification = create_s_identification options in

  let s_conf = BslConf.default in
  let s_js_confs = BslJsConf.empty options.BI.js_files in

  let s_marshal_plugin_s = BMP.create () in

  let s_ml_dynloader_loader = create_s_fbuffer () in
  let s_ml_dynloader_plugin = create_s_fbuffer () in

  let s_rev_js_parsed_files = [] in
  let s_rev_ml_parsed_files = [] in

  let s_rev_opa_decorated_files = [] in

  let s_rp_calls = BslKeyMap.empty in
  let s_rt_calls = BslKeyMap.empty in

  let s_js_code = [] in

  let s_ml_runtime = create_s_fbuffer () in
  let s_ml_runtime_mli = create_s_fbuffer () in

  let s_opa_code = [] in
  let s_opa_interface = [] in

  let session = {
    s_options ;

    s_depends ;
    s_identification ;

    s_conf ;
    s_js_confs ;

    s_marshal_plugin_s ;

    s_ml_dynloader_plugin ;
    s_ml_dynloader_loader ;

    s_rev_js_parsed_files ;
    s_rev_ml_parsed_files ;

    s_rev_opa_decorated_files ;

    s_rp_calls ;
    s_rt_calls ;

    s_js_code ;

    s_ml_runtime ;
    s_ml_runtime_mli ;

    s_opa_code ;
    s_opa_interface ;
  }

  in

  check_session session


(*
Registering
*)

(*
Note

The goal there is that from the plugin, it should be possible to get exactly
to the same point as there, with the same calls to the RegisterInterface now,
later when somebody will dynload the plugin.

A way of doing that, is to have the strict same interface for the 3 register_*
The register of this module returns the session.

CF
+ BslPluginInterface.register_*
*)

(*
Collecting calls.
*)

let compute_skey ks = String.concat_map "_" BslKey.normalize_string ks

let warning_set = WarningClass.Set.create_from_list [
  WarningClass.bsl_register ;
]

let warning fmt = OManager.warning ~wclass:WarningClass.bsl_register fmt

let equal_ks ks ks' =
  let c = List.make_compare String.compare ks ks' in
  c = 0

let pp_ks fmt ks = Format.pp_list "." Format.pp_print_string fmt ks


(*
Note for hackers:

This function is quite verbose, because there are a lot of error cases to detect.
if --check-style is set, warning of the class bsl.register will be set to --warn-error.

For citation, plugins file are no more available, so it makes not any sence to print
citation for types from plugins. For the types of the current session, the citation
is available.
*)
let register_type session ~ks ~ty =
  let _ =
    #<If:BSL_REGISTER $equals "2">
      debug "register-type: ks:[%a] ty:(%a)@\n" (Format.pp_list " ; " (fun f -> Format.fprintf f "%S") ) ks BslTypes.pp ty
    #<End>
  in
  let s_rt_calls = session.s_rt_calls in
  let depends_typesmap = BSL.ByPassMap.typesmap session.s_depends.d_bymap in
  let skey = compute_skey ks in
  let key = BslKey.normalize skey in
  let pos = BslTypes.pos ty in
  (* rt_call will be an option of rt_call, to know if there is something to collect or not *)
  let rt_call =
    (* check coherence with --use-plugin *)
    match BslKeyMap.find_opt key depends_typesmap with
    | Some (_, plugin_ks, plugin_ty) ->
        if equal_ks ks plugin_ks
        then (
          (* checking the type *)
          if (BslTypes.compare ~normalize:true ty plugin_ty) <> 0
          then (
            OManager.printf "%a" FilePos.pp_citation pos ;
            OManager.printf "%a@\nThis type is already defined in a used plugin: @{<bright>%a@}@\n"
              FilePos.pp_pos (BslTypes.pos plugin_ty) BslTypes.pp plugin_ty ;
            OManager.error "##extern-type: @{<bright>conflicting type definitions@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
          )
          else (
            warning "@\n%aA used plugin already defines this type.@ You should avoid this kind of practice.@\n##extern-type: @{<bright>type redefinition@} for key '@{<brigth>%a@}'@\n"
              FilePos.pp_citation pos BslKey.pp key ;
            None (* in this case, we do not redefine the type *)
          )
        )
        else (
          OManager.printf "%a" FilePos.pp_citation pos ;
          OManager.printf "One of the used plugin contains a declaration of@ an extern-type with the same key@ but with a different module-path.@\nThe module-path in your lib is @{<bright>%a@},@ in the plugin the module-path is @{<bright>%a@}.@\n"
            pp_ks ks pp_ks plugin_ks
          ;
          OManager.error "##extern-type: @{<bright>module-path mismatch@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
        )

    | None -> (
        (* Check if the type is already defined in an other file of the current session *)
        (* It is almost the same erros, but more restrictive *)
        match BslKeyMap.find_opt key s_rt_calls with
        | Some ( { c_rt_ks = c_rt_ks ; c_rt_ty = c_rt_ty } as rt_call ) ->
            let pos = FilePos.merge_pos pos (BslTypes.pos c_rt_ty) in
            if equal_ks ks c_rt_ks then (
              (* checking the type *)
              if (BslTypes.compare ~normalize:true ty c_rt_ty) <> 0
              then (
                OManager.printf "%a" FilePos.pp_citation pos ;
                OManager.error "##extern-type: @{<bright>conflicting type definitions@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
              );
              let c_rt_ty = BslTypes.reset_pos c_rt_ty pos in
              Some {
                rt_call with
                  c_rt_ty = c_rt_ty
              }
            )
            else (
              OManager.printf "%a" FilePos.pp_citation pos ;
              OManager.printf "There are 2 extern-type definitions with the same key@ but with a different module-path.@\nThe first module-path is @{<bright>%a@},@ and the second is @{<bright>%a@}.@\n"
                pp_ks ks pp_ks c_rt_ks
              ;
              OManager.error "##extern-type: @{<bright>module-path mismatch@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
            )

        | None ->
            (* This is the first time this type is defined, collect it *)
            Some { c_rt_ks = ks ; c_rt_ty = ty }
      )

  in

  let session =
    match rt_call with
    | None -> session
    | Some rt_call ->
        let s_rt_calls = BslKeyMap.add key rt_call s_rt_calls in
        {
          session with
            s_rt_calls = s_rt_calls
        }

  in

  session


let register_primitive session ~ks ~ty ~ips ?obj:_ () =
  let _ =
    #<If:BSL_REGISTER $equals "3">
      debug "register-primitive: ks:[%a] ty:(%a)@\n" (Format.pp_list "." Format.pp_print_string) ks BslTypes.pp ty
    #<End>
  in
  let s_rp_calls = session.s_rp_calls in
  let depends_bymap = session.s_depends.d_bymap in
  let skey = compute_skey ks in
  let key = BslKey.normalize skey in
  let pos = BslTypes.pos ty in
  (* rt_call will be an option of rt_call, to know if there is something to collect or not *)
  let rp_call =
    (* check coherence with --use-plugin *)
    match BSL.ByPassMap.find_opt depends_bymap key with
    | Some bypass ->
        OManager.printf "%a" FilePos.pp_citation pos ;
        OManager.printf "@[<2>A primitive with the same key is already defined@ in a used plugin@\n%a@]@\n"
          (Format.pp_list "@, " BSL.Implementation.pp) (BSL.ByPass.all_implementations bypass) ;
        OManager.error "##register: @{<bright>primitive re-definition@} for key '@{<brigth>%a@}'@\n" BslKey.pp key

    | None -> (
        match BslKeyMap.find_opt key s_rp_calls with
        | Some rp_call -> (
            let c_rp_ks = rp_call.c_rp_ks in
            let c_rp_ty = rp_call.c_rp_ty in
            let c_rp_ips = rp_call.c_rp_ips in
            let c_rp_obj = rp_call.c_rp_obj in
            let pos = FilePos.merge_pos pos (BslTypes.pos c_rp_ty) in

            if equal_ks ks c_rp_ks then (
              (* checking the type *)
              if (BslTypes.compare ~normalize:true ty c_rp_ty) <> 0
              then (
                OManager.printf "%a" FilePos.pp_citation pos ;
                OManager.error "##register: @{<bright>conflicting primitive definitions@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
              );
              (* merge pos in ty. BslTypes.reset_pos, pos is already the merged pos *)
              (* TODO: merge type variables names, or keep the one from Ocaml *)
              let c_rp_ty = BslTypes.reset_pos c_rp_ty pos in

              let c_rp_ips = List.fold_left
                (fun c_rp_ips (lang, filename, parsed_t, implementation) ->
                   (* redefinition in the same language is not allowed *)
                   match BslLanguageMap.find_opt lang c_rp_ips with
                   | Some _ -> (
                       (* When this primitive was registred the first time, its position was merged *)
                       OManager.printf "%a" FilePos.pp_citation pos ;
                       OManager.printf "This primitive is already defined in %a@\n" BslLanguage.pp lang;
                       OManager.error "##register: @{<bright>multiple primitive definitions@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
                     )
                   | None ->
                       let rp_impl = {
                         c_rpi_filename = filename ;
                         c_rpi_tags = parsed_t ;
                         c_rpi_implementation = implementation ;
                       }
                       in
                       BslLanguageMap.add lang rp_impl c_rp_ips
                ) c_rp_ips ips
              in

              let c_rp_obj =
                match c_rp_obj with
                | Some _ -> c_rp_obj
                | None ->
                    List.find_map
                      (fun (ml, _, _, imp) -> if BslLanguage.is_ml ml then Some imp else None) ips
              in

              let rp_call = {
                rp_call with
                  c_rp_ty = c_rp_ty ;
                  c_rp_ips = c_rp_ips ;
                  c_rp_obj = c_rp_obj ;
              }
              in
              Some rp_call
            )
            else (
              OManager.printf "%a" FilePos.pp_citation pos ;
              OManager.printf "There are 2 primitive definitions with the same key@ but with a different module-path.@\nThe first module-path is @{<bright>%a@},@ and the second is @{<bright>%a@}.@\n"
                pp_ks ks pp_ks c_rp_ks
              ;
              OManager.error "##register: @{<bright>module-path mismatch@} for key '@{<brigth>%a@}'@\n" BslKey.pp key
            )
          )

        | None ->
            (* This is the first time this primitive is defined, collect it *)
            let c_rp_obj = List.find_map
              (fun (ml, _, _, imp) -> if BslLanguage.is_ml ml then Some imp else None) ips
            in
            let c_rp_ips = List.fold_left
              (fun c_rp_ips (lang, filename, parsed_t, implementation) ->
                 let rp_impl = {
                   c_rpi_filename = filename ;
                   c_rpi_tags = parsed_t ;
                   c_rpi_implementation = implementation ;
                 }
                 in
                 BslLanguageMap.add lang rp_impl c_rp_ips
              ) BslLanguageMap.empty ips
            in
            let rp_call = {
              c_rp_ks = ks ;
              c_rp_ty = ty ;
              c_rp_ips = c_rp_ips ;
              c_rp_obj = c_rp_obj ;
            }
            in
            Some rp_call
      )

  in

  let session =
    match rp_call with
    | None -> session
    | Some rp_call ->
        let s_rp_calls = BslKeyMap.add key rp_call s_rp_calls in
        {
          session with
            s_rp_calls = s_rp_calls
        }

  in

  session



(*
The finalized_t
*)

type finalized_t = {
  f_options : BI.options ;

  f_marshal_plugin_t : BMP.t ;
                                             (* loader | plugin *)
  f_plugin_up : FBuffer.t ; (* X | X *)
  f_ml_dynloader_loader : FBuffer.t ; (* X | *)
  f_ml_dynloader_plugin : FBuffer.t ; (* | X *)

  f_js_keys : FBuffer.t ;

  f_ml_runtime : FBuffer.t ;
  f_ml_runtime_mli : FBuffer.t ;

  f_js_code : (filename * contents * BslJsConf.conf) list ;
  f_opa_code : (filename * contents) list ;
  f_opa_interface : (filename * contents) list ;

}


(* Finalize *)

(*
Effective calls, at the end (finalization)
*)
let f_register_types session =
  let fold_session _ rt_call session =
    let ks = rt_call.c_rt_ks in
    let ty = rt_call.c_rt_ty in

    let bmp_s = session.s_marshal_plugin_s in
    let _side_effect =
      try
        BMP.unsafe_register_type bmp_s ~ks ~ty ;
        BRI.unsafe_register_type ~ks ~ty ;
        ()
      with
      | BRI.RegisterError error -> (
          (* pos : the pos of ty has merged the pos in all languages *)
          let pos = BslTypes.pos ty in
          OManager.printf "%a" FilePos.pp_citation pos ;
          OManager.error "%a@\n" BRI.pp_error error
        )
    in

    (* complete the buffer of call to BP *)

    let s_ml_dynloader_loader = session.s_ml_dynloader_loader in
    let s_ml_dynloader_plugin = session.s_ml_dynloader_plugin in

    let s_ml_dynloader_loader =
      BPI.meta_register_type s_ml_dynloader_loader ~ks ~ty
    in

    let s_ml_dynloader_plugin =
      BPI.meta_register_type s_ml_dynloader_plugin ~ks ~ty
    in

    {
      session with
        s_ml_dynloader_loader = s_ml_dynloader_loader ;
        s_ml_dynloader_plugin = s_ml_dynloader_plugin ;
    }

  in

  let session = BslKeyMap.fold fold_session session.s_rt_calls session in

  session


let f_collecting_rp_ips c_rp_ips =
  let fold lang rp_impl acc =
    let filename = rp_impl.c_rpi_filename in
    let tags = rp_impl.c_rpi_tags in
    let implementation = rp_impl.c_rpi_implementation in
    let item =
      lang, filename, tags, implementation
    in
    item :: acc
  in

  let ips = BslLanguageMap.fold fold c_rp_ips [] in

  ips


let f_register_primitives session =
  let fold_session _ rp_call session =
    let ks = rp_call.c_rp_ks in
    let ty = rp_call.c_rp_ty in
    let c_rp_ips = rp_call.c_rp_ips in
    let obj = rp_call.c_rp_obj in
    (* ips should now be transformed into a list (cf BPI) *)
    let ips = f_collecting_rp_ips c_rp_ips in

    let bmp_s = session.s_marshal_plugin_s in
    let _side_effect =
      try
        BMP.unsafe_register_primitive bmp_s ~ks ~ty ~ips () ;
        BRI.unsafe_register_primitive ~ks ~ty ~ips () ;
        ()
      with
      | BRI.RegisterError error -> (
          (* pos : the pos of ty has merged the pos in all languages *)
          let pos = BslTypes.pos ty in
          OManager.printf "%a" FilePos.pp_citation pos ;
          OManager.error "%a@\n" BRI.pp_error error
        )
    in

    (* complete the buffer of call to BP *)

    let s_ml_dynloader_loader = session.s_ml_dynloader_loader in
    let s_ml_dynloader_plugin = session.s_ml_dynloader_plugin in

    let s_ml_dynloader_loader =
      BPI.meta_register_primitive s_ml_dynloader_loader ~ks ~ty ~ips ?obj () ;
    in

    let s_ml_dynloader_plugin =
      BPI.meta_register_primitive s_ml_dynloader_plugin ~ks ~ty ~ips () ;
    in

    {
      session with
        s_ml_dynloader_loader = s_ml_dynloader_loader ;
        s_ml_dynloader_plugin = s_ml_dynloader_plugin ;
    }

  in

  let session = BslKeyMap.fold fold_session session.s_rp_calls session in

  session


let finalizing_register_calls session =
  let session = f_register_types session in
  let session = f_register_primitives session in
  session


let f_plugin_up ~conf ~ocaml_env ~javascript_env s =

  let s_identification = s.s_identification in

  let basename = s_identification.i_basename in
  let self_module_name = s_identification.i_ml_plugin in
  let uniq_id = s_identification.i_uniq_id in

  let ml_runtime = s_identification.i_ml_runtime in
  let depends = s.s_depends.d_parents in
  let js_code = s.s_js_code in
  let opa_code = s.s_opa_code in

  let buf = FBuffer.create 1024 in
  let buf =
    BPI.meta_plugin__01
      buf
      ~basename
      ~self_module_name
      ~uniq_id
      ~conf
      ~ml_runtime
      ~depends
      ~js_code
      ~opa_code
      ~ocaml_env
      ~javascript_env
  in

  buf


let finalizing_opa ~final_bymap s =
  let s_opa_code =
    List.rev_map (BslOpa.preprocess ~final_bymap) s.s_rev_opa_decorated_files in

  let s_opa_code =
    List.map (fun (f, b) -> (f, FBuffer.contents b)) s_opa_code in

  (*
Syntax check, and Type checking.
*)

  let s_opa_interface =
    let true_means_error, s_opa_interface =
      BslOpa.checking_fail ~final_bymap s_opa_code in

    if true_means_error && not s.s_options.BI.unsafe_opa then
      OManager.error "Process stopped because of errors in the Opa code@\n"
    ;
    s_opa_interface
  in

  let s_opa_interface =
    List.map (fun (f, b) -> (f, FBuffer.contents b)) s_opa_interface in

  { s
    with
      s_opa_code = s_opa_code ;
      s_opa_interface = s_opa_interface ;
  }


let make_imperative_dynloader_interface session =
  let session = ref session in
  let register_type ~ks ~ty =
    let s = register_type !session ~ks ~ty in
    session := s
  in
  let register_primitive ~ks ~ty ~ips ?obj () =
    let s = register_primitive !session ~ks ~ty ~ips ?obj () in
    session := s
  in

  let dynloader_interface = {
    BPI.register_type = register_type ;
    BPI.register_primitive = register_primitive ;
  }

  in session, dynloader_interface


let finalizing_ocaml session =

  let options = session.s_options in

  let plugins = session.s_depends.d_plugins in
  let ml_decorated_files = List.rev session.s_rev_ml_parsed_files in

  let session_ref, dynloader_interface =
    make_imperative_dynloader_interface session
  in

  let ocaml_env, s_ml_runtime, s_ml_runtime_mli =
    BslOcaml.preprocess ~options ~plugins ~dynloader_interface ml_decorated_files
  in

  ocaml_env,
  { !session_ref
    with
      s_ml_runtime ;
      s_ml_runtime_mli ;
  }


let finalizing_js_code_conf s_js_confs s_js_code =
  let confs = BslJsConf.export s_js_confs in
  let map (filename, content) =
    let index = Filename.basename filename in
    match StringMap.find_opt index confs with
    | Some conf -> filename, content, conf
    | None ->
        (*
Internal error, the list of given js files was not correct
*)
        assert false
  in
  List.map map s_js_code


let finalizing_js session =

  let options = session.s_options in

  let depends = session.s_depends.d_js_code in
  let plugins = session.s_depends.d_plugins in

  let js_decorated_files = List.rev session.s_rev_js_parsed_files in

  let session_ref, dynloader_interface =
    make_imperative_dynloader_interface session
  in

  let javascript_env, s_js_code =
    BslJs.preprocess ~options ~plugins ~dynloader_interface ~depends js_decorated_files
  in

  let s_js_code = finalizing_js_code_conf session.s_js_confs s_js_code in

  javascript_env,
  { !session_ref
    with
      s_js_code ;
  }


let finalizing_js_keys ~final_bymap =
  let fold key bypass buf =
    match BSL.ByPass.compiled_implementation bypass ~lang:BslLanguage.js with
    | Some compiled ->
        let skey = BslKey.to_string key in
        let resolution = BSL.Implementation.CompiledFunction.compiler_repr compiled in
        FBuffer.printf buf "var _check_definition_of_%s = %s@\n" skey resolution
    | None -> buf
  in
  let buf = FBuffer.create 1024 in
  let buf = FBuffer.addln buf "// Checking keys resolution." in
  let buf = FBuffer.addln buf "// File used by the jschecker only" in
  BSL.ByPassMap.fold fold final_bymap buf


let finalize s =

  let _ = OManager.flush_errors () in

  (*
first, we should preprocess ml and js files,
performing some side effects on the session
+ loader and plugin via the session ref with imperative
dynloader interface
+ register table via call to dynloader_interface
*)

  let ocaml_env, s = finalizing_ocaml s in
  let javascript_env, s = finalizing_js s in

  (*
Now all the calls to the register interface are regrouped in
the session, we can do the effective calls
*)
  let s = finalizing_register_calls s in

  (*
Now, we can build the final bymap, every bypass have been registred.
*)
  let final_bymap = BSL.RegisterTable.build_bypass_map () in

  (*
Opa generation, and checking
*)
  let s = finalizing_opa ~final_bymap s in

  let conf = BslConf.export s.s_conf in

  let f_options = s.s_options in
  let f_plugin_up = f_plugin_up ~conf ~ocaml_env ~javascript_env s in

  let f_ml_dynloader_loader = s.s_ml_dynloader_loader in
  let f_ml_dynloader_plugin = s.s_ml_dynloader_plugin in

  let f_js_code = s.s_js_code in
  let f_js_keys = finalizing_js_keys ~final_bymap in

  let f_ml_runtime = s.s_ml_runtime in
  let f_ml_runtime_mli = s.s_ml_runtime_mli in

  let f_opa_code = s.s_opa_code in
  let f_opa_interface = s.s_opa_interface in

  let f_marshal_plugin_t =
    let identification = s.s_identification in
    let depends = s.s_depends.d_parents in
    let bmp_session = s.s_marshal_plugin_s in

    (* we register all rest fields but primitives and types which are done in-line *)
    BMP.register_basename bmp_session identification.i_basename ;
    BMP.register_module_name bmp_session identification.i_ml_plugin ;
    BMP.register_uniq_id bmp_session identification.i_uniq_id ;
    BMP.register_conf bmp_session conf ;
    BMP.register_ml_runtime bmp_session identification.i_ml_runtime ;
    BMP.register_depends bmp_session depends ;

    BMP.register_js_code bmp_session f_js_code ;
    BMP.register_opa_code bmp_session f_opa_code ;

    BMP.register_ocaml_env bmp_session ocaml_env ;
    BMP.register_javascript_env bmp_session javascript_env ;

    BMP.finalize bmp_session

  in

  let finalized_t = {
    f_options ;

    f_marshal_plugin_t ;

    f_plugin_up ;
    f_ml_dynloader_loader ;
    f_ml_dynloader_plugin ;

    f_js_code ;
    f_js_keys ;

    f_ml_runtime ;
    f_ml_runtime_mli ;

    f_opa_code ;
    f_opa_interface ;
  }

  in

  let _ = OManager.flush_errors () in

  finalized_t


(* Output *)

type 'a output = out_channel -> 'a -> unit

type iterator = {
  output : 'a. filename -> (out_channel -> 'a -> unit) -> 'a -> unit
}

type 'a output_iterator = iterator -> 'a -> unit


let out_code_factory fc_extract extract iterator finalized_t =
  let iter = iterator.output in
  let iter fc_box =
    let filename, contents = fc_extract fc_box in
    iter filename output_string contents
  in
  List.iter iter (extract finalized_t)

let out_code extract iterator finalized_t =
  let fc (filename, contents) = filename, contents in
  out_code_factory fc extract iterator finalized_t


let out_js_code i f =
  let fc (filename, contents, _) = filename, contents in
  let extract f = f.f_js_code in
  out_code_factory fc extract i f


let out_opa_code i f =
  let extract f = f.f_opa_code in
  out_code extract i f


let out_opa_interface i f =
  let extract f = f.f_opa_interface in
  out_code extract i f


let out_ml_marshal_plugin oc f =
  BMP.output oc f.f_marshal_plugin_t


let out_fbuffer extract oc f = FBuffer.output oc (extract f)


let out_js_keys oc =
  let extract f = f.f_js_keys in
  out_fbuffer extract oc


let out_ml_runtime oc =
  let extract f = f.f_ml_runtime in
  out_fbuffer extract oc


let out_ml_runtime_mli oc =
  let extract f = f.f_ml_runtime_mli in
  out_fbuffer extract oc


let out_ml_plugin_or_loader dynloader oc f =

  (*
module Self : .... =
struct
let self_module_name = "..."
...
let opa_code = "..."
let js_code = "..." *)
  FBuffer.output oc f.f_plugin_up ;

  (*
let dynloader ( get_register : ... ) =
match get_register ...
| None -> ...
| Some ... ->
begin
*)
  output_string oc BPI.meta_plugin__02 ;

  (* The specific part, depends if loader or plugin *)
  FBuffer.output oc dynloader ;

  (*
end
let self = {
...
}

let self_register () = ...
end

let _ = Self.self_register () *)
  output_string oc BPI.meta_plugin__03 ;

  ()


let out_ml_loader oc f =
  out_ml_plugin_or_loader f.f_ml_dynloader_loader oc f


let out_ml_plugin oc f =
  out_ml_plugin_or_loader f.f_ml_dynloader_plugin oc f


(*
Parsing files
*)

let directives = ["##extern"; "##register"; "##import"; "##module"; "##endmodule" ]

let mayforget t =
  String.is_contained "##" t &&
    List.exists (fun e -> String.is_contained e t) directives

let directive_prefix t =
  let t = String.ltrim t in
  List.exists (fun e -> String.is_prefix e t) directives

let unsecure t =
  let t = String.ltrim t in List.exists (fun e -> String.is_prefix e t) ["##"]

let check_style _options pos line =
  let (!!) fmt =
    OManager.printf "%a" FilePos.pp_citation pos ;
    OManager.serror fmt
  in
  let _ =
    if directive_prefix line then
      !! "Using directive prefix is a bad practice@\n"
  in
  let _ =
    if mayforget line then
      !! "This line contains a non parsed directive@\n"
  in
  let _ =
    if unsecure line then
      !! "This line contains @{<bright>'##'@} but not any known directive@\nIt will probably raise an error by compiling the file@\n"
  in
  ()


let cache_file filename =
  let contents =
    try
      File.content filename
    with
    | e ->
        OManager.error
          "@[<4>Cannot open file %S :@\n%s@]@\n" filename (Printexc.to_string e)
  in
  FilePos.add_file filename contents

let parse_line_factory process_directive set_last_directive options parser_rule do_check_style =
  (fun line -> (
     try
       let n, parsed_line = parser_rule line in
       if n < String.length line then
         BRState.error "Syntax error"
       else (
         (* Simplification of the maintenance, parsing of tags is independant *)
         match parsed_line with
         | ( BDir.Source (pos, line) ) as parsed_line -> (* as: parametric type *)
             (
               if do_check_style then
                 check_style options pos line
             );
             parsed_line

         | BDir.Directive (pos, tags, directive) -> (
             set_last_directive directive ;
             process_directive pos tags directive
           )
       )
     with
     | (Trx_runtime.SyntaxError _) as e ->
         BRState.error "@[<2>Syntax error@\n%s@]@\n" (Printexc.to_string e)

     (* support for ide mode, OManager will raise a special exception *)
     | e -> raise e
   )
  )

(*
A warning for too long lines with directives
*)
let warning_size = 160

let parse_file_factory process_directive set_last_directive options parser_rule filename =
  let do_check_style = options.BI.check_style in
  let parse_multiline = parse_line_factory process_directive set_last_directive options parser_rule do_check_style in
  let aux (parsed_lines, multiline) line line_number =
    BRState.init_line ~line_number ;
    let trim_line = String.trim line in
    match multiline with
    | None ->
        (* search if this is the beginning of a multiline directive *)
        if String.is_prefix "##" trim_line
        then
          if String.is_suffix "\\" trim_line
          then (
            (* replace the last char by a space for concatenation *)
            trim_line.[pred (String.length trim_line)] <- ' ' ;
            parsed_lines, Some trim_line
          )
          else (
            let length = String.length line in
            let () =
              if length > warning_size then
                BRState.warning (
                  "This line is too long.@\n"^^
                  "@[<2>@{<bright>Hint@}:@\n"^^
                  "You can use several lines, with a '\\' at the end of unfinished lines@]"
                )
              in
            let parsed_line = parse_multiline trim_line in
            parsed_line::parsed_lines, None
          )
        else (
          let parsed_line = parse_multiline line in
          parsed_line::parsed_lines, None
        )

    | Some accu ->
        (* this is maybe not the last multiline *)
        if String.is_suffix "\\" trim_line
        then (
          (* replace the last char by a space for concatenation *)
          trim_line.[pred (String.length trim_line)] <- ' ' ;
          let accu = accu ^ trim_line in
          parsed_lines, Some accu
        )
        else (
          (* this is the last multitline *)
          let line = accu ^ line in
          let parsed_line = parse_multiline line in
          parsed_line::parsed_lines, None
        )
   in
  cache_file filename ;
  BRState.init_file ~filename ;
  let parsed_lines, multiline = File.lines_foldi aux ([], None) filename in
  if Option.is_some multiline
  then BRState.error "@[<2>Syntax error@\nunfinished multiline directive@]@\n"
  ;
  let parsed_lines = List.rev parsed_lines in

  let parsed_file = {
    BDir.filename = filename ;
    BDir.decorated_source = parsed_lines ;
  }

  in

  parsed_file


(*
Feature: in some cases, you may want to add automatically some tags when
you see some properties in the types, or in the keys.
*)
let bypass_auto_tags directive tags =
  match directive with
  | BDir.Register (_, _, _, bslty) ->
      let tags =
        if tags.BslTags.cps_bypass then
          { tags with
              BslTags.no_projection =
              let set =
                Option.default StringSet.empty tags.BslTags.no_projection in
              Some (StringSet.add "cps" set)
          }
        else tags
      in
      let second_order = tags.BslTags.second_order in
      let second_order = second_order || BslTypes.is_second_order bslty in
      let tags =
        { tags with
            BslTags.second_order = second_order ;
        }
      in
      tags
  | _ ->
      tags

let bypass_process_directive pos tags directive =
  match directive with
  | BDir.Property _ ->
      let ptags = BslTags.parse ~pos [] in
      BDir.Directive (pos, ptags, BDir.Property tags)
  | _ ->
      let tags = BslTags.parse ~pos tags in
      let tags = bypass_auto_tags directive tags in
      BDir.Directive (pos, tags, directive)


let parse_opa_file options f =
  (* used only in bypass files *)
  let set_last_directive _ = () in
  let process_directive pos tags directive =
    let tags = BslTags.parse ~pos tags in
    BDir.Directive (pos, tags, directive)
  in
  let parsed = parse_file_factory process_directive set_last_directive options
    BRParse.parse_bslregisterparser_opalang f in
  ( parsed : BslDirectives.opalang_decorated_file )


let parse_bypass_file options f =
  let set_last_directive d = BRState.set_last_directive d in
  let process_directive = bypass_process_directive in
  let parsed = parse_file_factory process_directive set_last_directive options
    BRParse.parse_bslregisterparser_bypasslang f in
  ( parsed : BslDirectives.bypasslang_decorated_file )


(*
Main preprocessor
*)

let check_ml_filename filename =
  let basename = File.chop_extension filename in
  if not (Ident.is_universal_ident basename)
  then
    OManager.error (
      "Unsupported filename @{<bright>%S@}@\n"^^
      "@[<2>@{<bright>Hint@}:@\n"^^
      "This is not a valid ml module name.@]@\n"
    )
      filename

let preprocess_file session filename =
  let basename = Filename.basename filename in
  let ext = File.extension basename in
  match ext with
  | "opa" ->
      let decorated_file = parse_opa_file session.s_options filename in
      let s_rev_opa_decorated_files =
        decorated_file :: session.s_rev_opa_decorated_files in

      let session = {
        session with
          s_rev_opa_decorated_files ;
      } in
      session

  | "ml" ->
      check_ml_filename basename ;
      let parsed_file = parse_bypass_file session.s_options filename in
      let s_rev_ml_parsed_files =
        parsed_file :: session.s_rev_ml_parsed_files in

      let session = {
        session with
          s_rev_ml_parsed_files ;
      } in
      session


  | "js" ->
      let parsed_file = parse_bypass_file session.s_options filename in
      let s_rev_js_parsed_files =
        parsed_file :: session.s_rev_js_parsed_files in

      let session = {
        session with
          s_rev_js_parsed_files ;
      } in
      session

  | "jsconf" ->
      let s_js_confs = session.s_js_confs in
      let s_js_confs = BslJsConf.fold filename s_js_confs in

      let session = {
        session with
          s_js_confs ;
      } in
      session

  | "conf" ->
      let s_conf = session.s_conf in
      let s_conf = BslConf.fold ~filename s_conf in

      let session = {
        session with
          s_conf ;
      } in
      session

  | _ ->
      OManager.error
        "@[<2>File %S has extension @{<bright>%S@}@\nThis is not a file type handled by @{<bright>bslregister@}@]@\n"
        filename ext
Something went wrong with that request. Please try again.