Skip to content
This repository
tree: 8e30b1e52f
Fetching contributors…

Cannot retrieve contributors at this time

file 2278 lines (2083 sloc) 77.767 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 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
(*
Copyright © 2011, 2012 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/>.
*)
(* shorthands *)
module O = OpaEnv
module P = Passes
module PH = PassHandler
module Q = QmlAst

module List = BaseList

(* Define some alias for OPA pass system *)
type opa_options = OpaEnv.opa_options

type 'env opa_env = (opa_options, 'env) PassHandler.one_env

type ('env, 'env2) opa_pass =
    (opa_options, opa_options, 'env, 'env2) PassHandler.pass

type ('env, 'env2) opa_old_pass =
    (opa_options, 'env, 'env2) PassHandler.old_pass

type env_bothFinalCompile = (Passes.env_NewFinalCompile * Passes.env_NewFinalCompile)

type env_QmlCompilation = {
  qmlCompilation_options : Qml2ocamlOptions.argv_options ;
  qmlCompilation_env_ocaml_input : Qml2ocaml.env_ocaml_input ;
}

type env_OcamlSplitCode = {
  ocamlSplitCode_options : Qml2ocamlOptions.argv_options ;
  ocamlSplitCode_env_ocaml_split : Qml2ocaml.env_ocaml_split ;
}

type env_OcamlGeneration = {
  ocamlGeneration_options : Qml2ocamlOptions.argv_options ;
  ocamlGeneration_env_ocaml_output : Qml2ocaml.env_ocaml_output ;
}

type env_OcamlCompilation = {
  ocamlCompilation_returned_code : int ;
}

(* when propagating to all environment is overkill
ensures that their is no package mismatch, and no mutability of extra env *)
let pass_extra_output_env (default:'extra_env option) =
  let r = ref None in
  (fun () -> match !r with
  | Some((pack,extra_env)) when ObjectFiles.get_current_package_name() = pack ->
    extra_env
  | _ -> match default with
    | None -> failwith "pass_extra_output_env:not initalized"
    | Some d -> d
  ),
  (fun (extra_env:'extra_env) ->
    let cur_pack = ObjectFiles.get_current_package_name() in
    match !r with
    | Some((pack,_)) when cur_pack = pack && cur_pack<>"" -> (* something wrong here *)
      failwith ("pass_extra_output_env:no mutability in <<"^pack^">>")
    | _ -> r:= Some(cur_pack,extra_env)
   )

(**********************************************************)
(* Private module : Provides some utils for make **********)
(* environnments ******************************************)
(**********************************************************)


(**********************************************************)
(* Extracter **********************************************)
(**********************************************************)
module Extract = struct
  module SAEnvGen = struct
    let code env = env.P.sa_lcode
  end
  module EnvGen = struct
    let code env = env.P.qmlAst
    let annotmap env = env.P.typerEnv.QmlTypes.annotmap
    let gamma env = env.P.typerEnv.QmlTypes.gamma
    let stdlib_gamma env = env.P.stdlib_gamma

    (** Return (annotmap, code).*)
    let ac env = (annotmap env, code env)
    let agc env = (annotmap env, (gamma env, stdlib_gamma env), code env)
    let bymap env = env.P.bsl.BslLib.bymap
    let bypass_typer env s = BslLib.BSL.ByPassMap.bypass_typer (bymap env) s

    (** Return (bypass_typer, (code, gamma, annotmap)). Used by
[QmlCheck.Typing.retype] condition *)
    let bcga env =
      (bypass_typer env), ((code env), (gamma env), (annotmap env))
  end
  module EnvGenSliced = struct
    let get_env_gen env = env.P.env_gen
    let code_client env = env.P.sliced_env.P.client.P.code
    let code_server env = env.P.sliced_env.P.server.P.code
    let annotmap env = EnvGen.annotmap (get_env_gen env)
    let gamma env = EnvGen.gamma (get_env_gen env)
    let stdlib_gamma env = EnvGen.stdlib_gamma (get_env_gen env)

    (** Return (annotmap, code) for client *)
    let a_client env = (annotmap env, code_client env)
    let ag_client env = (annotmap env, (gamma env, stdlib_gamma env), code_client env)

    (** Return (annotmap, server) for server *)
    let a_server env = (annotmap env, code_server env)
    let ag_server env = (annotmap env, (gamma env, stdlib_gamma env), code_server env)
    let bymap env = EnvGen.bymap (get_env_gen env)
    let bypass_typer env = EnvGen.bypass_typer (get_env_gen env)
    let gamma env = EnvGen.gamma (get_env_gen env)

    (** Return (bypass_typer, (code, gamma, annotmap)) client*)
    let bcga_client env =
      (bypass_typer env), ((code_client env), (gamma env), (annotmap env))

    (** Return (bypass_typer, (code, gamma, annotmap)) server*)
    let bcga_server env =
      (bypass_typer env), ((code_server env), (gamma env), (annotmap env))
  end
end

(* TODO: Some of this should be in OpaTracker *)
(* There should not be code there ! *)
(* please update consistently with QmlTracker and passdesign *)

module EnvUtils = struct
  let make_code_printer printer _opt =
    ["code",
     fun fmt env ->
       Format.fprintf fmt "%a\n%!" printer env]

  let create_sa_both_env_gen printers e env = { PH.
    options = e.PH.options;
    env = env;
    printers =
      (fun opt ->
         let user_printers =
           printers (fun e -> e.SurfaceAstPassesTypes.lcodeUser) opt in
         let nuser_printers =
           printers (fun e -> e.SurfaceAstPassesTypes.lcodeNotUser) opt in
         List.fold_right2
           (fun (id, u) (_, nu) acc -> (
              (* The printer size should not be modified, opa track is expecting a specific format *)
              if Base.String.is_prefix "size" (PassHandler.printer_id id)
              then
                (id,
                 (fun fmt e ->
                    let code = e.SurfaceAstPassesTypes.lcodeNotUser @ e.SurfaceAstPassesTypes.lcodeUser in
                    OpaTracker.Printer.size fmt code))
              else
                (id,
                 (fun fmt e ->
                    Format.fprintf fmt "/* Not user code */@\n%a" nu e;
                    Format.fprintf fmt "/* User code */@\n%a" u e))
            )::acc)
           user_printers nuser_printers []);

    trackers = fun _ -> [] (* TODO: use OpaTracker.trackers *);
  }

  let create_sa_both_env e env = create_sa_both_env_gen OpaTracker.printers_nonuid e env
  let create_sa_both_env_uids e env = create_sa_both_env_gen OpaTracker.printers_uids e env

  let create_sa_env e env = { PH.
    options = e.PH.options;
    env = env;
    printers = OpaTracker.printers_uids Extract.SAEnvGen.code;
    trackers = OpaTracker.trackers Extract.SAEnvGen.code;
  }

  let create_env_gen e env = { PH.
    options = e.PH.options;
    env = env;
    printers = QmlTracker.printers Extract.EnvGen.agc;
    trackers = QmlTracker.trackers Extract.EnvGen.code;
  }

  let qmlTracker_sliced define getid qmlTracker extract_client extract_server _ =
    let make_printer make_filename extract =
      let list = qmlTracker extract () in
      match make_filename with
      | None ->
          list
      | Some new_name ->
          List.map (
            fun (id, prt) ->
              let id = getid id in
              let id = new_name id in
              let id = define id in
              id, prt
          )
            list
  in
    (make_printer (Some (fun name -> name ^ "_client")) extract_client)
    @ (make_printer None extract_server)
      (* using (fun name -> name) allows to can compare a non sliced code with
* the server part of a sliced code *)

  (* keep generalized (x) *)
  let sliced_printers x = qmlTracker_sliced PassHandler.define_printer PassHandler.printer_id QmlTracker.printers x
  let sliced_trackers x = qmlTracker_sliced PassHandler.define_tracker PassHandler.tracker_id QmlTracker.trackers x

end



(**********************************************************)
(* Private module : Provides some adaptater for make an ***)
(* opa_pass with an opa_old_pass **************************)
(**********************************************************)
(** This module allows to make an [opa_pass] with a
[opa_old_pass]. The created [opa_pass] returns an environment with
a good behavior (printers, ...). *)
module Adapter : sig

  (* Keep sig here just for doc..*)

  val adapt_sa_both :
    ('a, (SurfaceAst.nonuid, [< SurfaceAst.all_directives ] as 'b) SurfaceAstPassesTypes.env_both_lcodes) opa_old_pass ->
    ('a, (SurfaceAst.nonuid, 'b) SurfaceAstPassesTypes.env_both_lcodes) opa_pass

  val adapt_sa :
    ('a, (SurfaceAst.uids, [< SurfaceAst.all_directives ] as 'd) P.sa_env_Gen) opa_old_pass ->
    ('a, (SurfaceAst.uids, 'd) P.sa_env_Gen) opa_pass

  val adapt_sliced :
    ?invariant:(('tmp_env P.env_Gen_sliced, 'tmp_env P.env_Gen_sliced) PassHandler.invariant list) ->
    ?precond:('tmp_env P.env_Gen_sliced PassHandler.cond list) ->
    ?postcond:('tmp_env P.env_Gen_sliced PassHandler.cond list) ->
    ('tmp_env P.env_Gen, 'tmp_env P.env_Gen) opa_old_pass ->
    ('tmp_env P.env_Gen_sliced, 'tmp_env P.env_Gen_sliced) opa_pass

  val adapt_sliced_on_client :
    ('b, 'b) opa_old_pass ->
    ('c * 'b, 'c * 'b) opa_pass

  val adapt_new_sliced_on_client :
    ('c, 'c) opa_pass ->
    ('s * 'c, 's * 'c) opa_pass

end = struct

  let adapt_sa pass =
    PassHandler.make_pass
      (fun e -> EnvUtils.create_sa_env e (pass ~options:e.PH.options e.PH.env))

  let adapt_sa_both pass =
    PassHandler.make_pass
      (fun e -> EnvUtils.create_sa_both_env e (pass ~options:e.PH.options e.PH.env))

  let adapt_sliced ?(invariant = []) ?(precond=[]) ?(postcond=[]) pass =
    PassHandler.make_pass ~invariant ~precond ~postcond
    (fun e ->
       let env_server =
         { e.PH.env.P.env_gen with P.qmlAst = e.PH.env.P.sliced_env.P.server.P.code } in
       let env_s = pass ~options:e.PH.options env_server in
       let env_client = {env_s with P.qmlAst = e.PH.env.P.sliced_env.P.client.P.code} in
       let env_c = pass ~options:e.PH.options env_client in
       { e with PH.env = {P.
           env_gen = { env_c with P.qmlAst = [] };
           sliced_env = {P.
             server = { e.PH.env.P.sliced_env.P.server with P.code = env_s.P.qmlAst };
             client = { e.PH.env.P.sliced_env.P.client with P.code = env_c.P.qmlAst };
           };
         }
       })

  let adapt_sliced_on_client pass =
    PassHandler.make_pass
      (fun e ->
        let senv, cenv = e.PH.env in
        let cenv = pass ~options:e.PH.options cenv in
        { e with PH.env = (senv, cenv) })


  let compose_pass
      (uncons : 'env -> 'env2 * ('env2 -> 'env))
      (pass : ('env2, 'env2) opa_pass)
      : ('env, 'env) opa_pass
      =
    let just_uncons x = fst ( uncons x ) in
    let map_cond cond = PH.compose_fun_condition just_uncons cond in
    let map_invariant i = PH.compose_fun_invariant just_uncons just_uncons i in

    let invariant = List.map map_invariant pass.PH.invariant in
    let precond = List.map map_cond pass.PH.precond in
    let postcond = List.map map_cond pass.PH.postcond in
    PassHandler.make_pass
      ~invariant
      ~precond
      ~postcond
      (fun e ->
        let new_env, cons = uncons e.PH.env in
        let options = e.PH.options in
        let printers = e.PH.printers in
        let trackers = e.PH.trackers in
        let map_track_print track_or_print opt =
          List.map
            (fun (id, p) -> (id, (fun f env -> p f (cons env) )))
            (track_or_print opt)
        in
        let one_env =
          { PH.
            env = new_env;
            options = options;
            printers = map_track_print printers;
            trackers = map_track_print trackers;
          } in
        let one_env = pass.PH.f one_env in
        let new_env = one_env.PH.env in
        { e with PH.env = (cons new_env) }
      )


  let adapt_new_sliced_on_client pass =
    compose_pass
      (fun (serv, cli) -> (cli, (fun cli -> (serv, cli))))
      pass

end

(** Select the good register function according to back-end *)
let register_fields options =
  match options.O.back_end with
  | `qmlflat -> Flat_Compiler.register_field_name


(**********************************************************)
(* Public : MAKE YOUR PASSES HERE *************************)
(* NO IMPLEMENTATIONS, JUST COATING (deconstruct and ******)
(* construct environnment) ********************************)
(* AND COMPLETE MLI ***************************************)
(**********************************************************)

let pass_Welcome =
  PassHandler.make_pass
    (fun {PH.env=()} ->
       OpaEnv.Options.parse_options ();
       let options = OpaEnv.Options.get_options () in
       OManager.verbose "OPA version %s" BuildInfos.opa_version_name ;
       OManager.verbose "(c) 2007-%s MLstate, All Rights Reserved." BuildInfos.year;
       OManager.verbose "Build: %s" BuildInfos.version_id;
       PassHandler.make_env options ())

let pass_CheckOptions =
  PassHandler.make_pass
    (fun e ->
       if List.is_empty e.PH.options.O.filenames
         && ObjectFiles.Arg.no_packages ()
       then (
         OManager.printf "opa.exe: @{<bright>no opa files@}@.";
         OpaEnv.Options.echo_help ();
         OManager.printf "@[<2>@{<bright>Hint@}:@\nprecise some opa files@]@.";
         exit 1;
       ) else (
         let filenames = e.PH.options.O.filenames in
         PassHandler.make_env e.PH.options filenames
       )
    )

let pass_AddStdlibFiles =
  PassHandler.make_pass
    (fun e ->
       let options = e.PH.options in
       let filenames = e.PH.env in
       let env_AddStdlibFiles =
         let special_files =
           (*
- In separated mode, we do not want to add the stdlib as loaded sources.
*)
           if ObjectFiles.Arg.is_separated ()
           then []
           else
             if options.O.embedded_opa
             then Pass_AddStdlibFiles.of_static_include options
             else
               (* keep in sync with build_rules *)
               Pass_AddStdlibFiles.of_basedir [ "stdlib/core" ; "stdlib/tests" ] options
         in
         if ObjectFiles.Arg.is_separated ()
         then
           ([], special_files@filenames)
         else
           (special_files, filenames)
       in
       PassHandler.make_env options env_AddStdlibFiles
    )

let pass_PreProcess =
  PassHandler.make_pass
    (fun e ->
       let (files, ufiles) = e.PH.env in
       let ppenv =
         Pprocess.fill_with_sysenv Pprocess.empty_env in
       let ppenv =
         OpaEnv.Options.to_ppenv e.PH.options ppenv in
       let ppopt = Pprocess.default_options ppenv in
       let process = (Pprocess.process Pplang.opa_description ppopt) in
       let process =
         List.map
           (fun f ->
              {f with P.inputFile_content = process f.P.inputFile_content})
       in
       { e with PH.env = (process files, process ufiles) })

let pass_Parse =
  PassHandler.make_pass
    (fun e ->
       let options = e.PH.options in
       let env = e.PH.env in
       let (special_files, user_files) = env in
       let parsed_of_input_file input_file =
         let lcode =
           OpaParser.code
             ~cache:(not options.O.no_cache_parse)
             ~filename:input_file.P.inputFile_basename
             input_file.P.inputFile_content
         in
         { SurfaceAstPassesTypes.
             parsedFile_filename = input_file.P.inputFile_filename;
             parsedFile_lcode = lcode;
             parsedFile_content = input_file.P.inputFile_content;
         }
       in
       let special_parsed_files = List.map parsed_of_input_file special_files in
       let user_parsed_files = List.map parsed_of_input_file user_files in
       PassHandler.make_env options ((special_parsed_files, user_parsed_files), env)
    )

let parsed_files_printers extract =
  function opt ->
    List.map
      (function (pid, printer) ->
         (pid, (fun fmt env ->
                  List.iter
                    (function pfile ->
                       Format.fprintf fmt "/** Code from %s**/@\n%a"
                         pfile.SurfaceAstPassesTypes.parsedFile_filename
                         printer pfile.SurfaceAstPassesTypes.parsedFile_lcode)
                    (extract env)
               )
         )
      )
      (OpaTracker.printers_nonuid (fun a -> a) opt)

let pass_RegisterAppSrcCode =
  PassHandler.make_pass
    (fun e ->
      let options = e.PH.options in
      let make_env =
        let printers = parsed_files_printers (fun (_, files) -> files) in
        PassHandler.make_env ~printers options in
      let ((special_files, user_files), (special_sources, user_sources)) = e.PH.env in
       (* FIXME for now we only not register the source code if option publish_src_code
is not set, ideally we should not generate the _internal_/src_code page at
all (now it will be empty if publish_src_code=false) *)
      if options.O.publish_src_code then
        let special_files' = Pass_RegisterAppSrcCode.register_code ~special:true
          special_files special_sources in
        let user_files' = Pass_RegisterAppSrcCode.register_code ~special:false
          user_files user_sources in
         make_env (special_files', user_files')
      else
        make_env (special_files, user_files)
    )

let pass_Print =
  PassHandler.make_pass
    (fun e ->
       let options = e.PH.options in
       let module Printer = (val OpaPrint.getDefaultFamilly () : OpaPrint.Familly) in
       if not (File.exists options.O.build_dir) then Unix.mkdir options.O.build_dir 0o740;
       List.iter
         (function pfile ->
            if not (File.exists options.O.build_dir) then Unix.mkdir options.O.build_dir 0o740;
            let fn = Filename.concat options.O.build_dir
              (Filename.basename pfile.SurfaceAstPassesTypes.parsedFile_filename) in
            OManager.verbose "Convert %s to %s"
              pfile.SurfaceAstPassesTypes.parsedFile_filename fn;
            let oc = open_out fn in
            let fmt = Format.formatter_of_out_channel oc in
            Printer.string#code fmt pfile.SurfaceAstPassesTypes.parsedFile_lcode;
            Format.pp_print_flush fmt ();
            ignore (close_out oc);
            ignore (try (* verification that we can reparse *)
              OpaParser.code
                ~parser_:(!OpaSyntax.Args.r.OpaSyntax.Args.printer)
                ~cache:false
                ~filename:fn
                (File.content fn)
            with _ -> assert false)
         ) (snd (fst e.PH.env));
       e
    )

let pass_DbEngineImportation =
  PassHandler.make_pass
    (fun e ->
       let (a, user_files) = e.PH.env in
       let stdlib = e.PH.options.O.stdlib in
       let user_files = List.map
         (fun pfile ->
            {pfile with SurfaceAstPassesTypes.parsedFile_lcode =
                Pass_DbEngineImportation.process_code ~stdlib
                  pfile.SurfaceAstPassesTypes.parsedFile_lcode}
         ) user_files in
       { e with PH.env = (a, user_files) }
    )


let pass_LoadObjects k =
  PH.make_pass
    (fun env ->
       let options = env.PH.options in
       let env =
         SurfaceAstPasses.pass_load_objects
           ~options
           env.PH.env
           (fun files -> k (PH.make_env options files)) in
       PH.make_env () env
    )

let pass_ConvertStructure =
  PassHandler.make_pass
    (fun env ->
       let options = env.PH.options in
       let files, env_bsl = env.PH.env in
       let both_env = { SurfaceAstPassesTypes.
         lcodeNotUser = [];
         lcodeUser = List.concat_map (fun (_, _, code) -> code) files;
         lcodeTypeRenaming = StringMap.empty;
         exported_values_idents = IdentSet.empty ;
         env_bsl;
       } in
       PassHandler.make_env options both_env
    )


let pass_CheckDuplication =
  PH.make_pass
    (fun env ->
       let options = env.PH.options in
       let both_env = SurfaceAstPasses.pass_check_duplication [] [] ~options env.PH.env in
       EnvUtils.create_sa_both_env_uids env both_env
    )

let pass_BslLoading =
  PassHandler.make_pass
    (fun e ->
       let options = e.PH.options in
       let env = e.PH.env in
       let options, env, env_bsl =
         Pass_BslLoading.process ~options ~code:env
       in
       PassHandler.make_env options (env, env_bsl)
    )

let pass_TreatNoClientCalls() =
  PassHandler.make_pass
    (fun e ->
      let options = e.PH.options in
      let env = e.PH.env in
      PassHandler.make_env options (Pass_TreatNoClientCalls.translate env)
    )

let pass_CheckServerEntryPoint =
  PassHandler.make_pass
    (fun e ->
       let (opt, env) =
         Pass_ServerDeclaration.pass_check_server_entry_point
           ~options:e.PH.options e.PH.env in
       let options = { e with PH.options = opt } in
       EnvUtils.create_sa_both_env options env)

let pass_I18nAndComputedString =
  PassHandler.make_pass
    (fun e -> EnvUtils.create_sa_both_env_uids e (I18nAndComputedString.process_directives__i18n__string ~options:e.PH.options e.PH.env))

let pass_ParserGeneration =
  Adapter.adapt_sa_both SurfaceAstPasses.pass_parser_generation

let pass_ConvertStructure2 () =
  PassHandler.make_pass
    (fun e ->
       let options = e.PH.options in
       let env = e.PH.env in
       let env2 =
         let sa_lcode = env.SurfaceAstPassesTypes.lcodeNotUser @ env.SurfaceAstPassesTypes.lcodeUser in
         let sa_doc_types = [] in
         let sa_bsl = env.SurfaceAstPassesTypes.env_bsl in
         let sa_type_renaming = env.SurfaceAstPassesTypes.lcodeTypeRenaming in
         let sa_exported_values_idents =
           env.SurfaceAstPassesTypes.exported_values_idents in
         {P.
           sa_lcode ;
           sa_doc_types ;
           sa_bsl ;
           sa_type_renaming ;
           sa_exported_values_idents ;
         }
       in
       PassHandler.make_env
         ~printers:(OpaTracker.printers_uids Extract.SAEnvGen.code)
         options
         env2)

let pass_CodingDirectives =
  let transform pass_env =
    let env = pass_env.PassHandler.env in
    let typerEnv = env.P.typerEnv in
    let gamma = typerEnv.QmlTypes.gamma in
    let annotmap = typerEnv.QmlTypes.annotmap in
    let code = env.P.qmlAst in
    let annotmap, code =
      Pass_CodingDirectives.process_code gamma annotmap code
    in
    let typerEnv = {
      typerEnv with QmlTypes.
        annotmap ;
    } in
    let env = {
      env with Passes.
        qmlAst = code ;
        typerEnv ;
    } in
    { pass_env with PassHandler.
        env ;
    }
  in
  (* invariants, and pre/post conds *)
  let invariant =
    [
    ] in
  let precond =
    [
    ] in
  let postcond =
    [
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform


let pass_AddDocApiDirectives () =
  Adapter.adapt_sa Pass_OpaDocApi.process_opa

let pass_ReorderToplevel () =
  Adapter.adapt_sa Passes.pass_reorder_toplevel

let pass_RewriteModules () =
  Adapter.adapt_sa Passes.pass_rewrite_modules



(**********************************************)
(* QML AST PASSES *****************************)
let pass_SaToQml =
  PassHandler.make_pass
    ~postcond:[
      QmlCheck.Annot.unicity Extract.EnvGen.code;
    ]
    (fun e ->
       let options = e.PH.options in
       let env = e.PH.env in

       (* new_toplevel_names are thoses that come from toplevel patterns *)
       let _new_toplevel_names, (qmlAst:QmlAst.code_elt list) =
         let options = OpaToQml.options in
         OpaToQml.UidsOpaToQml.code ~options env.P.sa_lcode
       in
       let duplicated = Hashtbl.create 16 in
       let type_renaming =
         SurfaceAstRenaming.ObjectType.fold
           (StringMap.merge_i
              (fun i x y -> Hashtbl.add duplicated i y; x)
           )
           env.P.sa_type_renaming in
       let type_renaming = StringMap.map
         (fun (i,_) -> OpaToQml.UidsOpaToQml.typeident_aux ~check:false i)
         type_renaming in
       let type_renamer ?(check=true) str =
         try let x = StringMap.find str type_renaming in
         match Hashtbl.find_all duplicated str with
         | [] -> x
         | _ -> OManager.error "Duplicated type ident is found %s\n" str
         with Not_found ->
           (* need to do that because the db uses bypasses with type [embed_info]
* but this type is not defined in the code because the bypasses can only
* be inserted by the compiler *)
           QmlAst.TypeIdent.of_string ~check str in
       (*
1) Initializing the typer env
With the mess S2/S3, passes, S3Passes,
there are a lot of different initilization of typerEnv.
The annotmap and the options for the typer are the only
relevant information from the typerEnv.

Here seems the right place for initializing the typerEnv.
In particular, we do not use the blender in S3 anymore, so
the 'prepare', the 'empty_env', and the 'blend_initial__Typing'
functions from [opa_Typers] will not be used.

Essentially, building the typerEnv there is just about passing
the correct options depending on the command line, and keeping
the annotations.
*)

       let typerEnv =
         let bypass_typer =
           BslLib.BSL.ByPassMap.bypass_typer
             ~typeident:type_renamer env.P.sa_bsl.BslLib.bymap in
         QmlTyper.OfficialTyper.initial
           ~bypass_typer
           ~exception_handler:
             QmlTyperErrHandling.typechecking_exception_handler
           ~explicit_instantiation: options.O.explicit_instantiation
           ~value_restriction: options.O.value_restriction
           ~display: options.O.show_types
           ~exported_values_idents: env.P.sa_exported_values_idents () in

       let env_Gen =
         { P.
           bsl = env.P.sa_bsl;
           qmlAst = qmlAst;
           typerEnv = typerEnv;
           doc_types = env.P.sa_doc_types;
           temporary_env = ();
           local_typedefs = QmlAst.TypeIdentSet.empty;
           stdlib_gamma = QmlTypes.Env.empty;
         } in
       EnvUtils.create_env_gen e env_Gen
    )

let make_pass_raw_env pass ?(invariant=[]) ?(precond=[]) ?(postcond=[]) ()=
   let fpass e = { e with PH.
     env = pass ~options:e.PH.options e.PH.env;
   } in
   PassHandler.make_pass ~invariant ~precond ~postcond fpass

(* same as [make_pass_raw_env] but refresh printers and trackers
hence, the start and end envs don't have to be of the same type. *)
let make_pass_raw_env_refresh pass ?(invariant=[]) ?(precond=[]) ?(postcond=[]) ()=
   let fpass e = EnvUtils.create_env_gen e (pass ~options:e.PH.options e.PH.env) in
   PassHandler.make_pass ~invariant ~precond ~postcond fpass


let make_process_code_pass process_code extract rebuild ?(invariant=[]) ?(precond=[]) ?(postcond=[]) () =
  let fpass = fun e ->
    let typerEnv, code = extract e.PH.env
    in
    let gamma = typerEnv.QmlTypes.gamma
    and annotmap = typerEnv.QmlTypes.annotmap
    and bypass_typer = typerEnv.QmlTypes.bypass_typer
    in
    let (gamma,annotmap),code = process_code bypass_typer gamma annotmap code
    in
    let typerEnv =
      { typerEnv with
        QmlTypes.gamma = gamma;
        QmlTypes.annotmap = annotmap }
    in
    { e with PH.env = rebuild e.PH.env typerEnv code
    }
  in
  PassHandler.make_pass ~invariant ~precond ~postcond fpass


(*** INVARIANT *)
let invariant = [
  PassHandler.make_cons_invariant (QmlCheck.Annot.unicity Extract.EnvGen.code);
  PassHandler.make_cons_invariant (QmlCheck.Annot.find Extract.EnvGen.ac)
]

(* Check the contents of code: filtering code_elts *)
module CodeContents =
struct
  let no_NewType =
    let contents = { QmlCheck.Code.contents_all with QmlCheck.Code.c_NewType = false } in
    QmlCheck.Code.contents contents

  (* NewVal & NewValRec *)
  let only_NewVal =
    let contents = { QmlCheck.Code.contents_all with QmlCheck.Code.
                       c_Database = false ;
                       c_NewDbValue = false ;
                       c_NewType = false ;
                   } in
    QmlCheck.Code.contents contents
end

let pass_AddCSS =
  PassHandler.make_pass
    ~invariant
    ~precond:[]
    ~postcond:[]
    (fun e ->
       let code = e.PH.env.P.qmlAst in
       let code = Pass_AddCSS.perform code in
       { e with PH.env = { e.PH.env with P.qmlAst = code } }
    )

let pass_CheckPatternMatching =
  PassHandler.make_pass
    ~invariant
    ~precond:[]
    ~postcond:[]
    (fun e ->
       let env = e.PH.env in
       let gamma = env.P.typerEnv.QmlTypes.gamma in
       let annotmap = env.P.typerEnv.QmlTypes.annotmap in
       let code = env.P.qmlAst in
       let annotmap, code = Pass_CheckPatternMatching.process_code gamma annotmap code in
       let typerEnv = {
         env.P.typerEnv with QmlTypes.
           annotmap ;
       } in
       let env = {
         env with P.
           typerEnv ;
           qmlAst = code
       } in
       { e with PH.env }
    )

let pass_EndOfSeparateCompilation k =
  PH.make_pass
    (fun env ->
       let env =
         Pass_EndOfSeparateCompilation.process_code
           env.PH.env
           (fun env_gen -> k (EnvUtils.create_env_gen env env_gen)) in
       PH.make_env () env
    )

(*** INVARIANT *)
(* The following invariants are global
hence, they should be polymorphic wrt. the environment.
The argument of [make_invariant] is duplicated in order to keep polymorphism. *)

let global_invariant () = [
      PassHandler.make_invariant (QmlCheck.Annot.unicity Extract.EnvGen.code)
                                 (QmlCheck.Annot.unicity Extract.EnvGen.code);
      PassHandler.make_invariant (QmlCheck.Code.valrec Extract.EnvGen.ac)
                                 (QmlCheck.Code.valrec Extract.EnvGen.ac);
      PassHandler.make_invariant (QmlCheck.Annot.find Extract.EnvGen.ac)
                                 (QmlCheck.Annot.find Extract.EnvGen.ac);
    ]
let invariant = global_invariant ()

let pass_FunActionLifting =
  PassHandler.make_pass
    ~invariant
    ~precond:[]
    ~postcond:[]
    (fun e ->
       let code = e.PH.env.P.qmlAst in
       let {QmlTypes.annotmap=annotmap} = e.PH.env.P.typerEnv in
       let annotmap, code =
         Pass_LambdaLifting.process_code_fun_action annotmap code in
       { e with PH.env = {e.PH.env with P.
                         qmlAst = code;
                         typerEnv = {e.PH.env.P.typerEnv with QmlTypes.annotmap = annotmap};
                         } })


let pass_TypesDefinitions =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      CodeContents.no_NewType Extract.EnvGen.ac ;
      (* TODO: add more postcondition *)
    ] in
  let invariant =
    [
      (* TODO: add postcondition *)
    ]
    @invariant
  in
  PassHandler.make_pass ~precond ~postcond ~invariant
    (fun e ->
       let env = ( e.PH.env : 'tmp_env Passes.env_Gen ) in
       let typerEnv = env.Passes.typerEnv in
       let code = env.Passes.qmlAst in
       let local_typedefs, typerEnv, code, stdlib_gamma = Pass_TypeDefinition.process_code
         (register_fields e.PH.options) typerEnv code in
       let env = { env with Passes.typerEnv; local_typedefs; stdlib_gamma; qmlAst = code; } in
       { e with PH.env = env }
    )

let pass_DbSchemaGeneration =
  let precond =
    [
      CodeContents.no_NewType Extract.EnvGen.ac ;
    ] in
  let postcond =
    [
    ] in
  let invariant =
    [
      (* TODO: add invariant *)
    ]
    @invariant
  in
  PassHandler.make_pass ~precond ~postcond ~invariant
    (fun e ->
        QmlDbGen.settyp OpaMapToIdent.typ;
       let env = ( e.PH.env : 'tmp_env Passes.env_Gen ) in
       let typerEnv = env.Passes.typerEnv in
       let code = env.Passes.qmlAst in
       let gamma = typerEnv.QmlTypes.gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let schema = typerEnv.QmlTypes.schema in
       let (gamma, schema, code) =
         Pass_DbSchemaGeneration.process_code gamma annotmap schema code
       in
       let typerEnv =
         { typerEnv with QmlTypes.schema = schema; QmlTypes.gamma = gamma }
       in
       let env = { env with Passes.typerEnv = typerEnv ; qmlAst = code } in
       { e with PH.env = env }
    )

let pass_DbPathCoercion =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      (* TODO: add postcondition *)
    ] in
  let invariant =
    [
      (* TODO: add postcondition *)
    ]
    @invariant
  in
  PassHandler.make_pass ~precond ~postcond ~invariant
    (fun e ->
       let env = ( e.PH.env : 'tmp_env Passes.env_Gen ) in
       let typerEnv = env.Passes.typerEnv in
       let schema = typerEnv.QmlTypes.schema in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let gamma = typerEnv.QmlTypes.gamma in
       let code = env.Passes.qmlAst in
       let val_ = OpaMapToIdent.val_ in
       let annotmap, code = Pass_DbPathCoercion.process_code ~val_ schema gamma annotmap code in
       let typerEnv = { typerEnv with QmlTypes.annotmap = annotmap } in
       let env = { env with Passes.typerEnv = typerEnv ; qmlAst = code } in
       { e with PH.env = env }
    )



(** {b Descr}: The typechecking passe. *)
let pass_Typing =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      QmlCheck.Annot.find Extract.EnvGen.ac ;
    ] in
  let invariant =
    [
      (* TODO: add postcondition *)
    ]
    @invariant
  in
  PassHandler.make_pass ~precond ~postcond ~invariant
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let env = Pass_Typing.process_code env in
       { e with PH.env = env }
    )

let pass_Retyping =
  PassHandler.make_pass
    (fun e -> {e with PH.env = Pass_Retyping.process_code e.PH.env})

(**
Checking the directive @@warncoerce in the code, after typing.
*)
let pass_WarnCoerce =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      (* TODO: add postcondition *)
    ] in
  let invariant =
    [
      (* TODO: add postcondition *)
    ]
    @invariant
  in
  PassHandler.make_pass ~precond ~postcond ~invariant
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let typerEnv = env.Passes.typerEnv in
       let gamma = typerEnv.QmlTypes.gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let code = env.Passes.qmlAst in
       let _ = Pass_WarnCoerce.process_code gamma annotmap code in
       e
    )

let pass_CompileRecursiveValues =
  PassHandler.make_pass ~invariant
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let typerEnv = env.Passes.typerEnv in
       let gamma = typerEnv.QmlTypes.gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let code = env.Passes.qmlAst in
       let val_ = OpaMapToIdent.val_ in
       if !(OpaSyntax.Args.r).OpaSyntax.Args.parser == OpaSyntax.Js then
         WarningClass.set_warn Pass_CompileRecursiveValues.Warning.recval_lambda false;
       let gamma, annotmap, code = Pass_CompileRecursiveValues.process_code ~val_ gamma annotmap code in
       let typerEnv = {typerEnv with QmlTypes.gamma; annotmap} in
       let env = {env with P.typerEnv; qmlAst = code} in
       {e with PH.env = env}
    )

let pass_RewriteAsyncLambda =
  PassHandler.make_pass ~invariant
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let typerEnv = env.Passes.typerEnv in
       let gamma = typerEnv.QmlTypes.gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let code = env.Passes.qmlAst in
       let val_ = OpaMapToIdent.val_ in
       let annotmap, code = Pass_RewriteAsyncLambda.process_code ~val_ gamma annotmap code in
       let typerEnv = {typerEnv with QmlTypes.annotmap} in
       let env = {env with P.typerEnv; qmlAst = code} in
       {e with PH.env = env}
    )

let pass_BadopCodeGeneration =
  let precond = [
  ] in
  let postcond = [
    CodeContents.only_NewVal Extract.EnvGen.ac ;
    QmlCheck.Annot.find Extract.EnvGen.ac ;
  ] in
  let pass ~options e =
    Passes.pass_DbCodeGeneration ~options (Passes.pass_DbAccessorsGeneration ~options e) in
  make_pass_raw_env_refresh pass
    ~invariant
    ~precond
    ~postcond
    ()

let pass_MongoCodeGeneration =
  PassHandler.make_pass ~invariant
    (fun e ->
       let env = e.PH.env in
       let typerEnv = env.Passes.typerEnv in
       let gamma = typerEnv.QmlTypes.gamma in
       let stdlib_gamma = env.Passes.stdlib_gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let schema = typerEnv.QmlTypes.schema in
       let code = env.Passes.qmlAst in
       let (nannotmap, code) =
         Pass_MongoAccessGeneration.process_code ~stdlib_gamma gamma annotmap schema code in
       let typerEnv = { typerEnv with QmlTypes.
                          gamma = gamma;
                          annotmap = nannotmap} in
       { e with PH.env = {env with Passes.qmlAst = code; typerEnv = typerEnv;} }
    )

let pass_DocApiGeneration =
  make_pass_raw_env Pass_OpaDocApi.process_qml
    ~invariant ()

let pass_MacroExpansion =
  make_pass_raw_env Pass_MacroExpansion.process
    ~invariant ()

(*
The first pass of bypass hoisting, before the slicer
TODO(slicer):see if we can set to true the property just_expand,
the sharing between bypass is maybe not necessary.
*)
let pass_BypassHoisting =
  make_pass_raw_env (
    Passes.pass_QmlProcessCode_env_Gen (
      (fun _bypass_typer gamma annotmap code ->
         let annotmap, code = Pass_BypassApply.process_code gamma annotmap code in
         (gamma, annotmap), code
      )
    )
  )
    ~invariant ()

let pass_RegisterFields =
  PassHandler.make_pass
    (fun e ->
       Pass_RegisterFields.perform (register_fields e.PH.options) e.PH.env.P.qmlAst;
       e
    )
    ~invariant

let pass_EnrichMagic =
  PassHandler.make_pass
    (fun e ->
       let env = e.PH.env in
       let {P.typerEnv = typerEnv; qmlAst = code; stdlib_gamma = stdlib} = env in
       let {QmlTypes.annotmap = annotmap; gamma = gamma} = typerEnv in
       let specialized_env, annotmap, code =
         Pass_EnrichMagic.process_code ~annotmap ~stdlib ~gamma code in
       let typerEnv = {typerEnv with QmlTypes.annotmap = annotmap} in
       let env = {env with Passes.typerEnv = typerEnv; qmlAst = code} in
       let env = Passes.change_temporary specialized_env env in
       EnvUtils.create_env_gen e env
    )
    ~invariant:(global_invariant ())

let pass_EnrichMagicPurge =
  PassHandler.make_pass
    (fun e ->
       let env = e.PH.env in
       let code = Pass_EnrichMagic.just_purge env.P.qmlAst in
       let env = {env with P.qmlAst = code} in
       let env = Passes.change_temporary IdentMap.empty env in
       EnvUtils.create_env_gen e env
    )
    ~invariant:(global_invariant ())

let pass_SimplifyEquality =
  PassHandler.make_pass
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let {Passes.typerEnv = typerEnv; qmlAst = code} = env in
       let {QmlTypes.annotmap = annotmap; gamma = gamma} = typerEnv in
       let annotmap, code = Pass_SimplifyEquality.process_code OpaMapToIdent.val_noerr gamma annotmap code in
       let typerEnv = {typerEnv with QmlTypes.annotmap = annotmap} in
       let env = {env with Passes.typerEnv = typerEnv; qmlAst = code} in
       {e with PH.env = env}
    )
    ~invariant:(global_invariant ())

let pass_SimplifyMagic =
  PassHandler.make_pass
    (fun e ->
       let env = e.PH.env in
       let {Passes.typerEnv = typerEnv; qmlAst = code;
            temporary_env = specialized_env} = env in
       let {QmlTypes.annotmap = annotmap; gamma = gamma} = typerEnv in
       let annotmap, code = Pass_SimplifyMagic.process_code
         ~specialized_env gamma annotmap code in
       let typerEnv = {typerEnv with QmlTypes.annotmap = annotmap} in
       let env = {env with Passes.typerEnv = typerEnv; qmlAst = code} in
       let env = Passes.change_temporary () env in
       EnvUtils.create_env_gen e env
    )
    ~invariant:(global_invariant ())

let pass_InstrumentForClosureSerialization_instrumented,
    pass_InstrumentForClosureSerialization_define_instrumented
  = pass_extra_output_env (None:IdentSet.t option)

let pass_InstrumentForClosureSerialization =
  PassHandler.make_pass
    (fun e ->
       let env = (e.PH.env : 'tmp_env Passes.env_Gen) in
       let {Passes.typerEnv = typerEnv; qmlAst = code} = env in
       let {QmlTypes.annotmap = annotmap; gamma = gamma} = typerEnv in
       let gamma, annotmap, code, instrumented =
         Pass_InstrumentForClosureSerialization.process_code gamma annotmap code
       in pass_InstrumentForClosureSerialization_define_instrumented instrumented;
       let typerEnv = {typerEnv with QmlTypes.annotmap = annotmap; gamma} in
       let env = {env with Passes.typerEnv = typerEnv; qmlAst = code} in
       {e with PH.env = env}
    )
    ~invariant:(global_invariant ())

let pass_ReorderEnvGen =
  PassHandler.make_pass
    (fun e ->
       let code = e.PH.env.Passes.qmlAst in
       let code = QmlDependencies.reorder OpaMapToIdent.val_noerr [] IdentMap.empty
         Reordering.create_group_list code in
       {e with PH.env = { e.PH.env with Passes.qmlAst = code } }
    )
    ~invariant

let pass_QmlUndot =
  make_pass_raw_env Passes.pass_QmlUndot
    ~invariant ()

(**********************************************)
(* SLICED PASSES ******************************)
module SlicedCheck = struct
  module Annot = struct
    let unicity =
      PassHandler.compose_condition
        [QmlCheck.Annot.unicity Extract.EnvGenSliced.code_client;
         QmlCheck.Annot.unicity Extract.EnvGenSliced.code_server]
    let find =
      PassHandler.compose_condition
        [QmlCheck.Annot.find Extract.EnvGenSliced.a_client;
         QmlCheck.Annot.find Extract.EnvGenSliced.a_server]
  end
  module Ident = struct
    let unbound =
      let weak = Qmljs_Serializer.JsIdent.is_toplevel_declaration in
      PassHandler.compose_condition
        [QmlAlphaConv.Check.unbound (OpaMapToIdent.val_noerr ~side:`client)
           Extract.EnvGenSliced.a_client;
         QmlAlphaConv.Check.unbound ~weak (OpaMapToIdent.val_noerr ~side:`server)
           Extract.EnvGenSliced.a_server]
  end
  module Code = struct
    let valrec =
      PassHandler.compose_condition
        [QmlCheck.Code.valrec Extract.EnvGenSliced.a_client;
         QmlCheck.Code.valrec Extract.EnvGenSliced.a_server]
  end
end
let sliced_printers =
  EnvUtils.sliced_printers
    Extract.EnvGenSliced.ag_client
    Extract.EnvGenSliced.ag_server
let pass_GenericSlicer slicer =
  PassHandler.make_pass
    ~invariant:[
      PassHandler.make_invariant
        (QmlCheck.Code.valrec Extract.EnvGen.ac)
        (SlicedCheck.Code.valrec);
      PassHandler.make_invariant
        (QmlCheck.Annot.unicity Extract.EnvGen.code)
        SlicedCheck.Annot.unicity
    ]
    ~precond:[
      QmlCheck.Annot.find Extract.EnvGen.ac ;
    ]
    ~postcond:[

    ]
    (fun e ->
       let env = slicer ~options:e.PH.options e.PH.env in
       { PH.
         env = env;
         options = e.PH.options;
         printers = sliced_printers;
         trackers =
           EnvUtils.sliced_trackers
             Extract.EnvGenSliced.code_client
             Extract.EnvGenSliced.code_server
       } )

let pass_NoSlicer = pass_GenericSlicer Passes.pass_no_slicer
let pass_SimpleSlicer = pass_GenericSlicer Passes.pass_simple_slicer

let pass_CleanLambdaLiftingDirectives =
  PassHandler.make_pass
    (fun one_env ->
       let env = one_env.PH.env in
       let milk = env.P.newFinalCompile_qml_milkshake in
       let code = milk.QmlBlender.code in
       let code = Pass_CleanLambdaLiftingDirectives.process_code code in
       let milk = {milk with QmlBlender.code} in
       let env = {env with P.newFinalCompile_qml_milkshake = milk} in
       {one_env with PH.env}
    )

let pass_Assertion =
  Adapter.adapt_sliced
    ~invariant:[
    ]
    ~precond:[
    ]
    ~postcond:[
    ]
    (fun ~options e ->
       let no_assert = options.OpaEnv.no_assert in
       let typerEnv = e.P.typerEnv in
       let gamma = typerEnv.QmlTypes.gamma in
       let annotmap = typerEnv.QmlTypes.annotmap in
       let code = e.P.qmlAst in
       let annotmap, code = Pass_Assertion.process_code ~no_assert gamma annotmap code in
       let typerEnv = { typerEnv with QmlTypes.annotmap } in
       { e with P.
           typerEnv ;
           qmlAst = code ;
       })

let pass_PurgeTypeDirectiveAfterTyping =
  PassHandler.make_pass
    ~invariant:[]
    ~precond:[]
    ~postcond:[]
    (fun one_env ->
       let env = one_env.PH.env in
       let typerEnv = env.P.typerEnv in
       let annotmap, qmlAst = Pass_Purge.process_code_after_typer typerEnv.QmlTypes.annotmap env.P.qmlAst in
       let env = {env with P.typerEnv = {typerEnv with QmlTypes.annotmap}; qmlAst} in
       {one_env with PH.env})

let pass_PurgeTypeDirectiveAfterEi =
  Adapter.adapt_sliced
    ~invariant:[
      PassHandler.make_cons_invariant SlicedCheck.Code.valrec;
      PassHandler.make_cons_invariant SlicedCheck.Annot.unicity
    ]
    ~precond:[
      SlicedCheck.Annot.unicity
    ]
    ~postcond:[
    ]
    (fun ~options:_ e ->
       let typerEnv = e.P.typerEnv in
       let annotmap, qmlAst = Pass_Purge.process_code_after_ei typerEnv.QmlTypes.annotmap e.P.qmlAst in
       {e with P.typerEnv = {typerEnv with QmlTypes.annotmap}; qmlAst})

let pass_ResolveRemoteCalls =
  let fpass =
    fun e ->
      { e with PH.
          env =
          Passes.pass_resolve_remote_calls ~options:e.PH.options e.PH.env;
      } in
  PassHandler.make_pass
    ~invariant:[
      PassHandler.make_cons_invariant SlicedCheck.Code.valrec;
      PassHandler.make_cons_invariant SlicedCheck.Annot.unicity;
    ]
    fpass

let pass_InsertMemoizedTypes =
  let fpass =
    fun e ->
      let gamma = e.PH.env.P.env_gen.P.typerEnv.QmlTypes.gamma in
      let local_typedefs = e.PH.env.P.env_gen.P.local_typedefs in
      let annotmap = e.PH.env.P.env_gen.P.typerEnv.QmlTypes.annotmap in
      (* tsc_map can be put here, because the tsc_map code is monomorphic,
so not changed by Explicit Instantiation *)
      let (annotmap, server_updater) =
        Pass_ExplicitInstantiation.generate_tsc_map_updates ~val_:OpaMapToIdent.val_ ~side:`server ~local_typedefs gamma annotmap
      in
      let (annotmap, client_updater) =
        Pass_ExplicitInstantiation.generate_tsc_map_updates ~val_:OpaMapToIdent.val_ ~side:`client ~local_typedefs gamma annotmap
      in
      let server_code = e.PH.env.P.sliced_env.P.server.P.code in
      let client_code = e.PH.env.P.sliced_env.P.client.P.code in
      let server_code = server_updater :: server_code in
      let client_code = client_updater :: client_code in
      let gamma, new_server_code = Pass_ExplicitInstantiation.get_memoized_definitions gamma `server in
      let gamma, new_client_code = Pass_ExplicitInstantiation.get_memoized_definitions gamma `client in
      let server_code = List.tail_append new_server_code server_code in
      let client_code = List.tail_append new_client_code client_code in
      let env_gen = {e.PH.env.P.env_gen with P.typerEnv = {e.PH.env.P.env_gen.P.typerEnv with QmlTypes.gamma = gamma ; annotmap = annotmap }} in
      let client = {e.PH.env.P.sliced_env.P.client with P.code = client_code} in
      let server = {e.PH.env.P.sliced_env.P.server with P.code = server_code} in
      let sliced_env = {(*e.PH.env.sliced_env with*) P.client = client; server = server} in
      let env = {(*e.PH.env with*) P.env_gen = env_gen; sliced_env = sliced_env} in
      { e with PH.env = env } in
  PassHandler.make_pass fpass

let pass_SlicedReorder =
  let fpass e =
    let client = Extract.EnvGenSliced.code_client e.PH.env in
    let server = Extract.EnvGenSliced.code_server e.PH.env in
    let client, server = Opa_SlicedReorder.perform ~client ~server in
    { e with PH.
        env =
        { e.PH.env with P.
            sliced_env = { P.
              client = { e.PH.env.P.sliced_env.P.client with P.
                           code = client };
              server = { e.PH.env.P.sliced_env.P.server with P.
                           code = server };
            };
        }
    }
  in
  PassHandler.make_pass
    ~postcond:[
      SlicedCheck.Code.valrec;
      SlicedCheck.Ident.unbound;
    ]
    fpass

(*
Factorizing construction and deconstruction of env for passes :
+ FunActionEnvSerialize
+ FunActionJsCallGeneration
*)
let decons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced =
  let env_gen = env_Gen_sliced.P.env_gen in
  let typerEnv = env_gen.P.typerEnv in
  let gamma = typerEnv.QmlTypes.gamma in
  let annotmap = typerEnv.QmlTypes.annotmap in
  let sliced_env = env_Gen_sliced.P.sliced_env in
  let server = sliced_env.P.server in
  let code = server.P.code in
  gamma, annotmap, code

let recons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced (gamma, annotmap) code =
  let env_gen = env_Gen_sliced.P.env_gen in
  let typerEnv = env_gen.P.typerEnv in
  let sliced_env = env_Gen_sliced.P.sliced_env in
  let server = sliced_env.P.server in
  let typerEnv =
    { typerEnv with QmlTypes.
        gamma = gamma ;
        annotmap = annotmap ;
    } in
  let env_gen =
    { env_gen with P.
        typerEnv = typerEnv
    } in
  let server =
    { server with P.
        code = code
    } in
  let sliced_env =
    { sliced_env with P.
        server = server
    } in
  let env =
    { P.
        env_gen = env_gen ;
        sliced_env = sliced_env ;
    } in
  env

let pass_SlicedCleaning =
  PassHandler.make_pass
    (fun e ->
       let env_gen_sliced = e.PH.env.P.sliced_env in
       let server_code = env_gen_sliced.P.server.P.code in
       let server_published = env_gen_sliced.P.server.P.published in
       let server_renaming = env_gen_sliced.P.server.P.renaming in
       let client_code = env_gen_sliced.P.client.P.code in
       let client_published = env_gen_sliced.P.client.P.published in
       let client_renaming = env_gen_sliced.P.client.P.renaming in
       let roots =
         let no_server = Option.get e.PH.options.O.no_server in
         List.filter_map (OpaMapToIdent.val_opt ~side:`server) (Opa_Roots.roots_for_s3 ~no_server) @
         List.filter_map (OpaMapToIdent.val_opt ~side:`client) (Opa_Roots.roots_for_s3 ~no_server) in
       let unreachable_idents, server_code, client_code =
         QmlDependencies.get_unreachable_idents_of_code
           OpaMapToIdent.val_noerr
           roots
           server_code
           client_code in
       let filter_fun = (fun i -> not (IdentSet.mem i unreachable_idents)) in
       let server_published =
         IdentMap.filter_keys
           filter_fun
           server_published in
       let client_published =
         IdentMap.filter_keys
           filter_fun
           client_published in
       let filter_fun_renaming = (fun _ id -> filter_fun id) in
       let server_renaming =
         QmlRenamingMap.filter server_renaming filter_fun_renaming in
       let client_renaming =
         QmlRenamingMap.filter client_renaming filter_fun_renaming in
       OpaMapToIdent.filter filter_fun;
       let server = {(* env_gen_sliced.P.server with *)
                       P.code = server_code;
                       P.published = server_published;
                       P.renaming = server_renaming;
                    } in
       let client = {(* env_gen_sliced.P.client with *)
                       P.code = client_code;
                       P.published = client_published;
                       P.renaming = client_renaming;
                    } in
       let env_gen_sliced = {(*env_gen_sliced with*) P.server = server; P.client = client} in
       let e = {e with PH.env = {e.PH.env with P.sliced_env = env_gen_sliced}} in
       e)

let pass_FunActionEnvSerialize =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      (* TODO: add postcondition *)
    ] in
  PassHandler.make_pass ~precond ~postcond
    (fun e ->
       let env_Gen_sliced = e.PH.env in

       (* Deconstruction of the env *)
       let gamma, annotmap, code =
         decons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced
       in
       let stdlib_gamma = env_Gen_sliced.P.env_gen.P.stdlib_gamma in

       (* FunActionEnvSerialize *)
       let (gamma, annotmap), code =
         Pass_FunActionEnvSerialize.process_server_code ~stdlib_gamma gamma annotmap code
       in

       (* Reconstruction of the env *)
       let env_Gen_sliced =
         recons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced (gamma, annotmap) code
       in
       let e = { e with PH.env = env_Gen_sliced } in
       e
    )

(* insert directives wherever values are instantiated or quantified
with a nonempty set of variables *)
let pass_ExplicitInstantiation =
  let precond =
    [
      SlicedCheck.Code.valrec;
      SlicedCheck.Annot.unicity
    ] in
  let postcond =
    [

    ] in
  PassHandler.make_pass ~precond ~postcond
    (fun e ->
      let env = e.PH.env in
      let gamma = env.P.env_gen.P.typerEnv.QmlTypes.gamma in
      let annotmap = env.P.env_gen.P.typerEnv.QmlTypes.annotmap in
      let {P.code=server_code;
           published=server_published;
           renaming=server_renaming} = env.P.sliced_env.P.server in
      let {P.code=client_code;
           published=client_published;
           renaming=client_renaming} = env.P.sliced_env.P.client in
      (* TODO: optimize by adding only dummy arguments for published functions,
if there is no explicit instantiation to be done there;
then return *_published pointing to the versions with dummy arguments,
but inside the server and client code use the original,
unchanged version*)

      Pass_ExplicitInstantiation.published_ref := server_published;
      Pass_ExplicitInstantiation.renaming_map := server_renaming;

      (* to compute the have_typeof set of a piece of code, ei needs
* the have_typeof set of its dependencies
* so it can't look at the server code first nor the client code first *)
      let have_typeof =
        Pass_ExplicitInstantiation.have_typeof gamma annotmap
          (Opa_SlicedReorder.reorder_in_new_qml
             (server_code @ client_code)) in

      let (annotmap, gamma, qmlAst_server) =
        Pass_ExplicitInstantiation.process_code
          have_typeof gamma annotmap
          (IdentSet.from_list (IdentMap.keys server_published))
          env.P.sliced_env.P.server.P.code
      in

      let server_published = !Pass_ExplicitInstantiation.published_ref in
      let server_renaming = !Pass_ExplicitInstantiation.renaming_map in

      Pass_ExplicitInstantiation.published_ref := client_published;
      Pass_ExplicitInstantiation.renaming_map := client_renaming;

      let (annotmap, gamma, qmlAst_client) =
        Pass_ExplicitInstantiation.process_code
          have_typeof gamma annotmap
          (IdentSet.from_list (IdentMap.keys client_published))
          env.P.sliced_env.P.client.P.code
      in

      let client_published = !Pass_ExplicitInstantiation.published_ref in
      let client_renaming = !Pass_ExplicitInstantiation.renaming_map in

      let stdlib_gamma = Pass_ExplicitInstantiation.get_stdlib_gamma gamma in

      let env_gen =
        { env.P.env_gen with P.
          stdlib_gamma = stdlib_gamma;
          typerEnv = { env.P.env_gen.P.typerEnv with
                       QmlTypes.annotmap = annotmap;
                       QmlTypes.gamma = gamma;
          };
        }
      in
      { e with PH.env = { P.
          env_gen = env_gen;
          sliced_env =
          { P.server = { P.code = qmlAst_server;
                         published = server_published;
                         renaming = server_renaming;
                       };
            P.client = { P.code = qmlAst_client;
                         published = client_published;
                         renaming = client_renaming;
                       }
          };
        }
      })

(* rewrite the directives to normal QML code; insert code generating
gamma accessible from OPA code *)
let pass_OptimizeExplicitInstantiation =
  let precond =
    [
      (* TODO: add pre condition *)
    ] in
  let postcond =
    [
      SlicedCheck.Code.valrec;
      SlicedCheck.Annot.unicity;
    ] in
  PassHandler.make_pass ~precond ~postcond
    (fun e ->
      let env = e.PH.env in
      let gamma = env.P.env_gen.P.typerEnv.QmlTypes.gamma in
      let annotmap = env.P.env_gen.P.typerEnv.QmlTypes.annotmap in
      let (annotmap, qmlAst_server) =
        Pass_ExplicitInstantiation.unprocess_code
          ~val_:OpaMapToIdent.val_
          ~side:`server gamma annotmap env.P.sliced_env.P.server.P.code
      in
      let (annotmap, qmlAst_client) =
        Pass_ExplicitInstantiation.unprocess_code
          ~val_:OpaMapToIdent.val_
          ~side:`client gamma annotmap env.P.sliced_env.P.client.P.code
      in
      let env_gen =
        { env.P.env_gen with P.
          typerEnv = { env.P.env_gen.P.typerEnv with
                       QmlTypes.annotmap = annotmap;
                     };
        }
      in
      { e with PH.env =
        { P.env_gen = env_gen;
          sliced_env =
          { P.server = { env.P.sliced_env.P.server with P.
                         code = qmlAst_server
                       };
            P.client = { env.P.sliced_env.P.client with P.
                         code = qmlAst_client
                       }
          };
        }
      })

let pass_FunActionJsCallGeneration =
  let precond =
    [
      (* TODO: add precondition *)
    ] in
  let postcond =
    [
      (* TODO: add postcondition *)
    ] in
  PassHandler.make_pass ~precond ~postcond
    (fun e ->
       let env_Gen_sliced = e.PH.env in

       (* Deconstruction of the env *)
       let gamma, annotmap, code =
         decons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced
       in
       let stdlib_gamma = env_Gen_sliced.P.env_gen.P.stdlib_gamma in

       (* FunActionEnvSerialize *)
       let (gamma, annotmap), code =
         Pass_FunActionJsCallGeneration.process_server_code stdlib_gamma gamma annotmap code
       in

       (* Reconstruction of the env *)
       let env_Gen_sliced =
         recons_env_Gen_sliced_for_funaction_Passes env_Gen_sliced (gamma, annotmap) code
       in
       let e = { e with PH.env = env_Gen_sliced } in
       e
    )

(* ***********************************************)
(* FINAL COMPILATION *****************************)

let extract_client_agc (_, cenv) =
  (cenv.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.annotmap,
   (cenv.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.gamma,
   QmlTypes.Env.empty),
   cenv.P.newFinalCompile_qml_milkshake.QmlBlender.code)
let extract_server_agc (senv, _) =
  (senv.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.annotmap,
   (senv.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.gamma,
   QmlTypes.Env.empty),
   senv.P.newFinalCompile_qml_milkshake.QmlBlender.code)
let extract_client (_, cenv) = cenv.P.newFinalCompile_qml_milkshake.QmlBlender.code
let extract_server (senv, _) = senv.P.newFinalCompile_qml_milkshake.QmlBlender.code
let final_printers = EnvUtils.sliced_printers extract_client_agc extract_server_agc
let pass_SlicedToFinal =
  PassHandler.make_pass
    (fun e ->
       let env =
         let eenv = e.PH.env in
         let mk_blender typerEnv sliced_aux =
           let blender_milkshake : QmlBlender.qml_milkshake =
             { QmlBlender.env = typerEnv;
               QmlBlender.code = sliced_aux.P.code;
             } in
           { P.
             newFinalCompile_bsl = e.PH.env.P.env_gen.P.bsl ;
             newFinalCompile_qml_milkshake = blender_milkshake;
             newFinalCompile_renaming_server = eenv.P.sliced_env.P.server.P.renaming;
             newFinalCompile_renaming_client = eenv.P.sliced_env.P.client.P.renaming;
             newFinalCompile_closure_map = IdentMap.empty;
             newFinalCompile_stdlib_gamma = e.PH.env.P.env_gen.P.stdlib_gamma;
           } in
         ((mk_blender eenv.P.env_gen.P.typerEnv eenv.P.sliced_env.P.server),
          (mk_blender eenv.P.env_gen.P.typerEnv eenv.P.sliced_env.P.client)) in
       {
         PH.
         env = env;
         options = e.PH.options;
         printers = final_printers;
         trackers = EnvUtils.sliced_trackers extract_client extract_server;
       }
    )

(* ***********************************************)
(* FINAL CLIENT COMPILATION **********************)

let pass_ClientCpsRewriter =
  Adapter.adapt_sliced_on_client (P.pass_QmlCpsRewriter true)

let pass_ClientLambdaLifting =
  Adapter.adapt_sliced_on_client (P.pass_LambdaLifting2 ~typed:true ~side:`client)

let pass_ClientQmlUncurry =
  Adapter.adapt_sliced_on_client (P.pass_QmlUncurry2 ~typed:true ~side:`client)

let pass_ClientQmlClosure =
  Adapter.adapt_sliced_on_client (P.pass_QmlClosure2 ~typed:true ~side:`client)

let pass_JavascriptCompilation =
  let make_extract make env =
    let env = make env in
    env.P.newFinalCompile_qml_milkshake.QmlBlender.code in
  let make_extract_ac make env =
    let env = make env in
    (env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.annotmap,
     env.P.newFinalCompile_qml_milkshake.QmlBlender.code) in
  let make_extract_agc make env =
    let env = make env in
    let gamma = (
      env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.gamma,
      QmlTypes.Env.empty
    )
    in
    let annotmap, code = make_extract_ac make env in
    annotmap, gamma, code in
  let pass pass_env =
    let options = pass_env.PassHandler.options in
    let mk_final_server_env env = { PH.
      env = env;
      options = options;
      printers = QmlTracker.printers (make_extract_agc (fun senv -> senv)) ;
      trackers = QmlTracker.trackers (make_extract (fun senv -> senv)) ;
    } in
    let (server_finalenv, client_finalenv) = pass_env.PassHandler.env in
    match Option.get options.O.no_server, ObjectFiles.compilation_mode () with
    | true, (`linking | `prelude | `init) -> mk_final_server_env server_finalenv
    | false, (`linking | `prelude | `init)
    | _, `compilation ->
      (* FIXME: i don't think we still need those roots
* and if it breaks without, it should be solved properly *)
      let client_roots = List.fold_left (
        fun set root ->
          match OpaMapToIdent.val_opt ~side:`client root with
          | Some id -> IdentSet.add id set
          | None -> set
      ) IdentSet.empty (Opa_Roots.roots_for_s3 ~no_server:false) in
      (* instrumented closure should not be cleaned *)
      let client_roots = IdentSet.fold (fun id set ->
        let id = QmlRenamingMap.new_from_original client_finalenv.P.newFinalCompile_renaming_client id in
        IdentSet.add id set
      ) (pass_InstrumentForClosureSerialization_instrumented()) client_roots
      in
      let typing = server_finalenv.P.newFinalCompile_qml_milkshake.QmlBlender.env in
      let bsl_client = client_finalenv.P.newFinalCompile_bsl in
      let server = server_finalenv.P.newFinalCompile_qml_milkshake in
      let client = client_finalenv.P.newFinalCompile_qml_milkshake in
      let closure_map = client_finalenv.P.newFinalCompile_closure_map in
      let renaming_server = client_finalenv.P.newFinalCompile_renaming_server in
      let renaming_client = client_finalenv.P.newFinalCompile_renaming_client in
      let bsl_pp =
        let ppenv = Pprocess.fill_with_sysenv Pprocess.empty_env in
        let ppenv = OpaEnv.Options.to_ppenv options ppenv in
        let ppopt = Pprocess.default_options ppenv in
        Pprocess.process Pplang.js_description ppopt in
      let server =
        Pass_JavascriptCompilation.process
          ~options
          ~closure_map
          ~renaming_server
          ~renaming_client
          ~client_roots
          ~typing
          ~bsl_pp
          ~bsl_client
          ~server
          ~client
      in
      let server_finalenv = {
        server_finalenv with P.
          newFinalCompile_qml_milkshake = server ;
      } in
      mk_final_server_env server_finalenv
  in
  (* invariants, and pre/post conds *)
  let pre_extract_ac env = make_extract_ac (fun (_, cenv) -> cenv) env in
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
      QmlCheck.Code.valrec pre_extract_ac ;
      QmlAlphaConv.Check.unbound (OpaMapToIdent.val_noerr ~side:`client) pre_extract_ac ;
    ] in
  let postcond =
    [
      (* TODO: add postcond *)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond pass

let pass_ResolveJsIdent =
  PassHandler.make_pass
    (fun e ->
       let env = e.PH.env in
       let annotmap, code =
         Opa_ResolveJsIdent.perform
           env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.annotmap
           env.P.newFinalCompile_qml_milkshake.QmlBlender.code in
       let env =
         { env with P.
             newFinalCompile_qml_milkshake =
             { QmlBlender.
                 code = code ;
                 env =
                   { env.P.newFinalCompile_qml_milkshake.QmlBlender.env with
                       QmlTypes.annotmap = annotmap;
                   }
             }
         } in
       { e with PH.env = env }
    )

let pass_GenerateServerAst generate =
  PassHandler.make_pass
    (fun e ->
       let env = e.PH.env in
       let {P.
         newFinalCompile_qml_milkshake = {
           QmlBlender.code;
           env = {QmlTypes.annotmap; gamma}
         };
         newFinalCompile_stdlib_gamma = stdlib_gamma;
         newFinalCompile_renaming_server = server_renaming;
         newFinalCompile_renaming_client = client_renaming;
       } = env in
       let val_ = OpaMapToIdent.val_noerr in
       let gamma, annotmap, code = Pass_GenerateServerAst.process ~generate ~gamma ~stdlib_gamma ~annotmap ~val_ ~server_renaming ~client_renaming ~code in
       let env =
         { env with P.
             newFinalCompile_qml_milkshake =
             { QmlBlender.
                 code ;
                 env =
                 { env.P.newFinalCompile_qml_milkshake.QmlBlender.env with QmlTypes.
                     annotmap;
                     gamma;
                 }
             }
         } in
       {e with PH.env = env}
    )


(* ***********************************************)
(* FINAL SERVER COMPILATION **********************)

(* extractors *)
let extract_final_ac env =
  env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.annotmap,
  env.P.newFinalCompile_qml_milkshake.QmlBlender.code
let extract_final_gamma env =
  env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.gamma
let extract_final_code env = env.P.newFinalCompile_qml_milkshake.QmlBlender.code
let extract_final_bypass_typer env = env.P.newFinalCompile_qml_milkshake.QmlBlender.env.QmlTypes.bypass_typer
let extract pass_env = (extract_final_bypass_typer pass_env, extract_final_code pass_env)

let pass_QmlLiftDeepRecords =
  make_process_code_pass
    (fun _ -> Pass_LiftDeepRecords.process_code ~typed:true)
    P.extract_env_NewFinalCompile
    P.rebuild_env_NewFinalCompile
    ()

let pass_InitializeBslValues =
  PH.make_pass
    (fun e ->
       let env = e.PH.env in
       let bypass_typer = extract_final_bypass_typer env in
       let annotmap, code = extract_final_ac env in
       let gamma = extract_final_gamma env in
       let gamma, annotmap, code = Pass_InitializeBslValues.process_code bypass_typer gamma annotmap code in
       let milkshake = { QmlBlender.
                          code = code;
                          env = {env.P.newFinalCompile_qml_milkshake.QmlBlender.env with QmlTypes.
                                   annotmap = annotmap;
                                   gamma = gamma;
                                }
                       } in
       let env = {env with P.newFinalCompile_qml_milkshake = milkshake} in
       {e with PH.env = env}
    )

let pass_ServerCpsRewriter =
  let transform pass_env =
    let options = pass_env.PassHandler.options in
    let env = pass_env.PassHandler.env in
    { pass_env with PassHandler.
        env = Passes.pass_QmlCpsRewriter false ~options env
    }
  in
  (* invariants, and pre/post conds *)
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
    ] in
  let postcond =
    [
      (*
This post condition is currently broken because of the second_order bypasses.
In bsl_ocaml_init.ml they take 1 extra argument, but the bypass_typer does not know
about it. This condition is desactivated until we solve this probleme.
QmlCheck.Bypass.applied extract
*)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform

let pass_ServerQmlClosure =
  PassHandler.make_pass
    (fun e ->
       { e with PH.env = P.pass_QmlClosure2 ~typed:false ~side:`server ~options:e.PH.options e.PH.env })

let pass_QmlConstantSharing_gen side =
  let transform pass_env =
    let typerEnv, code = P.extract_env_NewFinalCompile pass_env.PH.env in
    let gamma = typerEnv.QmlTypes.gamma
    and annotmap = typerEnv.QmlTypes.annotmap in
    let (gamma,annotmap), code =
      Pass_ConstantSharing.process_code ~side ~typed:false gamma annotmap code in
    let typerEnv =
      { typerEnv with
        QmlTypes.gamma = gamma;
        QmlTypes.annotmap = annotmap }
    in
    { pass_env with PH.env = P.rebuild_env_NewFinalCompile pass_env.PH.env typerEnv code
    }
  in
  let precond =
    [
      (* TODO: add pre condition *)
    ] in
  let postcond =
    [
      QmlAlphaConv.Check.alpha extract_final_ac ;
    ] in
  PassHandler.make_pass ~precond ~postcond transform

let pass_QmlConstantSharing =
  pass_QmlConstantSharing_gen `server
let pass_ClientQmlConstantSharing =
  let pass_QmlConstantSharing = pass_QmlConstantSharing_gen `client in
  Adapter.adapt_new_sliced_on_client pass_QmlConstantSharing

let pass_QmlCompilation =
  let transform pass_env =
    let options = pass_env.PH.options in
    let env = pass_env.PH.env in
    (* get env entities *)
    let qml2ocaml_env_bsl = env.Passes.newFinalCompile_bsl in
    let qml2ocaml_qml_milkshake = env.Passes.newFinalCompile_qml_milkshake in
    (* renaming is not used *)
    (* 1) transform options *)
    let qmlCompilation_options = Passes.pass_OpaOptionsToQmlOptions ~options qml2ocaml_qml_milkshake in
    (* 2) selection of the back-end *)
    let qml_to_ocaml =
      match options.O.back_end with
      | `qmlflat -> Flat_Compiler.qml_to_ocaml in
    (* proceed *)
    let qmlCompilation_env_ocaml_input = qml_to_ocaml qmlCompilation_options qml2ocaml_env_bsl qml2ocaml_qml_milkshake in
    (* build env *)
    let qmlCompilation_env =
      {
        qmlCompilation_options = qmlCompilation_options ;
        qmlCompilation_env_ocaml_input = qmlCompilation_env_ocaml_input
      }
    in
    let empty _ = [] in
    {
      pass_env with PassHandler.
        env = qmlCompilation_env ;
        printers = OcamlTrack.printers (fun env -> env.qmlCompilation_env_ocaml_input.Qml2ocaml.ocaml_code) ;
        trackers = empty
    }
  in
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
      (* TODO: add pre conditions *)
    ] in
  let postcond =
    [
      (* TODO: add pre conditions *)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform

let pass_OcamlSplitCode =
  let transform pass_env =
    let env = pass_env.PassHandler.env in
    (* get env entities *)
    let ocamlSplitCode_options = env.qmlCompilation_options in
    let qmlCompilation_env_ocaml_input = env.qmlCompilation_env_ocaml_input in
    (* proceed *)
    let ocamlSplitCode_env_ocaml_split =
      Qml2ocaml.OcamlCompilation.ocaml_split_code ocamlSplitCode_options qmlCompilation_env_ocaml_input in
    (* build env *)
    let env = {
      ocamlSplitCode_options = ocamlSplitCode_options ;
      ocamlSplitCode_env_ocaml_split = ocamlSplitCode_env_ocaml_split ;
    }
    in
    let empty _ = [] in
    {
      pass_env with PassHandler.
        env = env ;
        printers = empty ;
        trackers = empty
    }
  in
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
      (* TODO: add pre conditions *)
    ] in
  let postcond =
    [
      (* TODO: add pre conditions *)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform

let pass_OcamlGeneration =
  let transform pass_env =
    let env = pass_env.PassHandler.env in
    (* get env entities *)
    let ocamlGeneration_options = env.ocamlSplitCode_options in
    let ocamlSplitCode_env_ocaml_split = env.ocamlSplitCode_env_ocaml_split in
    (* proceed *)
    let ocamlGeneration_env_ocaml_output =
      Qml2ocaml.OcamlCompilation.ocaml_generation ocamlGeneration_options ocamlSplitCode_env_ocaml_split in
    (* build env *)
    let ocamlGeneration_env =
      {
        ocamlGeneration_options = ocamlGeneration_options ;
        ocamlGeneration_env_ocaml_output = ocamlGeneration_env_ocaml_output
      }
    in
    let empty _ = [] in
    {
      pass_env with PassHandler.
        env = ocamlGeneration_env ;
        printers = empty ;
        trackers = empty
    }
  in
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
      (* TODO: add pre conditions *)
    ] in
  let postcond =
    [
      (* TODO: add pre conditions *)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform

let pass_OcamlCompilation =
  let transform pass_env =
    let env = pass_env.PassHandler.env in
    (* get env entities *)
    let ocamlGeneration_options = env.ocamlGeneration_options in
    let ocamlGeneration_env_ocaml_output = env.ocamlGeneration_env_ocaml_output in
    (* proceed *)
    let ocamlCompilation_returned_code =
      Qml2ocaml.OcamlCompilation.ocaml_compilation ocamlGeneration_options ocamlGeneration_env_ocaml_output in
    (* build env *)
    let ocamlCompilation_env =
      {
        ocamlCompilation_returned_code = ocamlCompilation_returned_code
      }
    in
    let empty _ = [] in
    {
      pass_env with PassHandler.
        env = ocamlCompilation_env ;
        printers = empty ;
        trackers = empty
    }
  in
  let invariant =
    [
      (* TODO: add invariants *)
    ] in
  let precond =
    [
      (* TODO: add pre conditions *)
    ] in
  let postcond =
    [
      (* TODO: add pre conditions *)
    ] in
  PassHandler.make_pass ~invariant ~precond ~postcond transform

let pass_CleanUp =
  { PH.
      invariant = [];
      precond = [];
      postcond = [];
      f = (fun e ->
             QmlRefresh.clear ();
             OpaMapToIdent.reset ();
             let code = e.PH.env.ocamlCompilation_returned_code in
             if code = 0 then ObjectFiles.compilation_is_successfull ();
             e)
  }

let pass_ByeBye =
  (* Ocaml typer is stupid! (or I'm) *)
  (* make_pass (fun _ -> exit 0) *)
  { PH.
    invariant = [];
    precond = [];
    postcond = [];
    f = (fun env ->
           let code = env.PH.env.ocamlCompilation_returned_code in
           if code <> 0 then OManager.exit code;
           PH.make_env () ()
        );
  }


(*-----------------------------*)
(*---- register printers ------*)
(*-----------------------------*)
(*grep '".*"' main.ml | sed 's/.*"\(.*\)".*/ | "\1" ->/g'*)
let () =
  PassHandler.register_printer
    (function
     | "Opa.exe"
     | "Welcome"
     | "CheckOptions"
     | "AddStdlibFiles"
     | "OpenFiles"
     | "Parse"
     | "DumpParsed"
     | "ConvertStructure"
     | "LoadObjects"
     | "CheckTypesDuplication"
     | "CheckServerEntryPoint"
     | "ParserGeneration"
     | "CheckDuplication"
     | "BslLoading"
     | "AddingRoots"
     | "AddingCompileEnvVars"
     | "StaticInclusionDirectory"
     | "StaticFileMimeType"
     | "StaticInclusions"
     | "ServerEntryPoint"
     | "AddDocApiDirectives"
     | "TupleTypeGeneration"
     | "Reorder"
     | "RewriteModules"
     | "AddingServer"
     | "CheckBypass"
     | "SAtoQML" -> None

     | "AddCSS"
     | "CheckPatternMatching"
     | "ExtractDbExpr"
     | "FunActionLifting"
     | "ExtractLocalTypes"
     | "TypesDefinitions"
     | "DbSchemaGeneration"
     | "DbPathCoercion"
     | "Typing"
     | "BlenderDB"
     | "DocApiGeneration"
     | "WarnCoerce"
     | "MacroExpansion"
     | "BypassHoisting"
     | "Undot" -> Some (QmlTracker.printers Extract.EnvGen.agc)

     | "NoSlicerRemoveJsIdent"
     | "Slicing"
     | "NoSlicing"
     | "PrepareSlicedCleaning"
     | "FunActionEnvSerialize"
     | "ExplicitInstantiation"
     | "OptimizeExplicitInstantiation"
     | "SlicedCleaning"
     | "FunActionJsCallGeneration"
     | "PurgeTypeDirectives"
     | "ResolveRemoteCalls"
     | "DiscardSlicerDirectives"
     | "InsertFunInfos"
     | "JustReorder2" -> Some (Obj.magic sliced_printers)

     | "ClientQmlCpsRewriter"
     | "ClientLambdaLifting"
     | "ClientQmlBypassHoisting"
     | "ClientQmlUncurry"
     | "ClientQmlClosure"
     | "JavascriptCompilation" -> None

     | "ResolveJsIdent"
     | "QmlLiftDeepRecords"
     | "NoSlicerCleanClientBypass"
     | "ServerQmlCpsRewriter"
     | "ServerLambdaLifting"
     | "ServerQmlBypassHoisting"
     | "ServerQmlUncurry"
     | "ServerQmlClosure"
     | "QmlConstantSharing" -> Some (Obj.magic final_printers)

     | "QmlCompilation"
     | "OcamlGeneration"
     | "OcamlCompilation"
     | "ByeBye" -> None

     | _ -> None)
Something went wrong with that request. Please try again.