Source

ocaml-iteratees / iteratees.ml

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
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
(* 34567890123456789 1234567890123456789 1234567890123456789 1234567890123456 *)

(* todo: string_of_*err* -- вытащить так, чтобы wrapped-exns учитывались. *)
(* todo: разбить на файлы. *)

(* +
   The comments in this source are taken from original source file
   ( http://okmij.org/ftp/Haskell/Iteratee/IterateeM.hs ),
   except for comments that have "+" sign in first line (like this comment).
   Comments with "+" were added by Dmitry Grebeniuk (gdsfh1 at gmail dot com),
   who have ported Iteratees to OCaml.
*)

(* +
   If you are using "=<<" or "%<<" infix operators, and they will probably
   occur in some commented code.  Preprocessor will treat "<<" in comments
   as the beginning of quotation.  The best way to deal with it is to add
   "-no_quot" to your preprocessor's command line:
   -pp "camlp4 your_pp_modules" => -pp "camlp4 -no_quot your_pp_modules"
   or add ocamlbuild's "camlp4:no_quot" tag to some files
   (target "your_file.ml") or all your ml- and mli-files
   (target <*.ml> | <*.mli>).  (see for example "_tags" in this library.)
*)

value enum_fd_buffer_size = ref 4096
;

value break_chars_buf_init_size = 25
;

open It_Ops
;

open Dbg
;

open It_Types
;

module Make (IO : MonadIO)
=
struct

module It_IO = IO;

module Subarray = Subarray
;

module S = Subarray
;

(* +
   In OCaml, Iteratees' [err_msg] is represented by simple exception.
   [err_msg] can be Iteratees' internal exception, user-defined Iteratees'
   exception, or an IO exception with place, wrapped into [Types.EIO]
   exception.

   IO exceptions (see MonadIO signature) carry the tuple of exception and
   the place where exception was raised (similar to
   [Unix.Unix_error (error, place, argument)] exception; I find it useful).

   Sometimes we need to wrap Iteratees' error into IO error:
   [Iteratees_err_msg err_msg] represents such wrapped exception.

   Functions [merr_of_ierr] (IO-monad error of Iteratees' error) and
   [ierr_of_merr] know about wrapping, and they unwrap such exceptions.
*)

type err_msg = exn;

exception EIO = It_Types.EIO;

exception Iteratees_err_msg of err_msg;


(* +
   Some iteratees do not follow conventions described by Oleg
   (not every iteratee is `good').  When library founds that
   iteratee is `bad', the exception [Divergent_iteratee place]
   is the result of computation.  [place] is the name of function
   that found that iteratee is `bad', sometimes it's useful for
   debugging.
*)

exception Divergent_iteratee of place;


(* +
   Function [merr_of_ierr] implemented inside functor, since
   it depends on [IO.error] to return the value of [IO.m 'a] type.
*)

value ierr_of_merr (e : exn) : err_msg =
  match e with
  [ Iteratees_err_msg e | e -> e
  ]
;


(* A stream is a (continuing) sequence of elements bundled in Chunks.
   The first variant means no more data will be coming: the stream
   is exhausted, either due to EOF or some error.
   Chunk [a] gives the currently available part of the stream.
   The stream is not terminated yet.
   The case (Chunk []) signifies a stream with no currently available
   data but which is still continuing. A stream processor should,
   informally speaking, ``suspend itself'' and wait for more data
   to arrive.
*)

type stream 'el =
  [ EOF of option err_msg
  | Chunk of Subarray.t 'el
  ]
;

value chunk_of elem = Chunk (S.of_elem elem)
;


value dbgstream s =
  match s with
  [ EOF eopt ->
      Printf.sprintf "s:EOF{e=%s}" &
      match eopt with
      [ None -> "None"
      | Some exn -> Printf.sprintf "Some{%s}" & Printexc.to_string exn
      ]
  | Chunk b -> Printf.sprintf "s:Chunk{arr[%i],ofs=%i,len=%i}"
      (Array.length b.S.arr) b.S.ofs b.S.len
  ]
;

value ( >>% ) m f = IO.bind f m;

(* +
   OCaml operators' priorities allow to use
   "  a          >>% fun _ ->
      f %<< m    >>% fun _ ->
      ..
   "
   without parenthesis around "f %<< m".
*)

value ( %<< ) = IO.bind;


(* Iteratee -- a generic stream processor, what is being folded over
   a stream
   This is the monadic version of Iteratee from Iteratee.hs
   + ported to OCaml +
   Please see the file Iteratee.hs for the discussion
   of design decisions.
   The basic design: Iteratee takes the chunk of the input stream and
   returns one of:
      -- the computed result and the remaining part of the stream.
         If the stream is finished (i.e., the EOF x is received), 
         that EOF value is returned as the  `remaining part of the stream';
      -- the indication that Iteratee needs more data, along
         with the continuation to process these data;
      -- a message to the stream producer (e.g., to rewind the stream)
         or an error indication.
   We assume that all iteratees are `good' -- given bounded input,
   they do the bounded amount of computation and take the bounded amount
   of resources.
   We also assume that given a terminated stream, an iteratee
   moves to the done state, so the results computed so far could be returned.
   The monad m describes the sort of computations done
   by the iteratee as it processes the stream. The monad m could be
   the identity monad (for pure computations) or the IO monad
   (to let the iteratee store the stream processing results as they
   are computed).
*)

type iteratee 'el 'a =
  [ IE_done of 'a
  | IE_cont of option err_msg
            and (stream 'el -> IO.m (iteratee 'el 'a  *  stream 'el))
  ]
;


(* It turns out, Iteratee forms a monad. *)

value return res = IE_done res
;


value rec
(bindI : ('a -> iteratee 'el 'b) -> iteratee 'el 'a -> iteratee 'el 'b)
f it =
  match it with
  [ IE_done a -> f a
  | IE_cont e k ->
      IE_cont e
        (fun s ->
           k s >>% fun
           [ (IE_done a, stream) ->
               match f a with
               [ IE_cont None m -> m stream
               | (IE_cont (Some _) _ | IE_done _) as i ->
                   IO.return (i, stream)
               ]
           | (((IE_cont _) as i), s) -> IO.return (bindI f i, s)
           ]
        )
  ]
;

value ( =<< ) = bindI
;

value ( >>= ) m f = bindI f m
;


value (lift : IO.m 'a -> iteratee 'el 'a) m =
  IE_cont None (fun s -> m >>% fun x -> IO.return (return x, s))
;


(* Throw an irrecoverable error *)

value rec throw_err e : iteratee 'el 'a =
  IE_cont (Some e) (throw_err_cont e)
and throw_err_cont e =
  fun s -> IO.return (throw_err e, s)
;


(* Throw a recoverable error *)

value throw_recoverable_err e cont : iteratee 'el 'a =
  IE_cont (Some e) cont
;


(* Produce the EOF error message to be passed to throwErr. 
   If the stream was terminated because of an error, keep the original 
   error message.
*)

value (set_eof : stream 'el -> err_msg) s =
  match s with
  [ EOF (Some e) -> e
  | EOF None | Chunk _ -> End_of_file
  ]
;


(* Useful combinators for implementing iteratees and enumerators *)

value empty_stream = Chunk Subarray.empty
;


(* +
   [ie_doneM] and [ie_contM] are useful inside [IE_cont] continuation,
   they return from [IE_cont] either "iteratee returns [x] and maybe
   some data left in stream [s]", or "we have processed stream (1),
   but we have no result yet -- pass more data to the function [k]".
   "empty_stream" in ie_contM code is the reflection of fact (1).
*)

value
  ( ie_doneM : 'a -> stream 'el -> IO.m (iteratee 'el 'a  *  stream 'el) )
  x s = IO.return (IE_done x, s)
;

value ie_contM k = IO.return (IE_cont None k, empty_stream)
;


(* +
   Almost unusable in OCaml, since value monomorphism/restriction(?)
   for function applications (for [ie_cont some_cont]) bound to
   top-level values.  For top-level values, [IE_cont None some_cont]
   should be used instead.
*)

value (ie_cont : (stream 'el -> IO.m (iteratee 'el 'a * stream 'el)) ->
                 iteratee 'el 'a)
cont =
  IE_cont None cont
;


value (liftI : IO.m (iteratee 'el 'a) -> iteratee 'el 'a) m =
  ie_cont (fun s -> m >>% run' s)
  where run' s i =
    match i with
    [ IE_cont None k -> k s
    | IE_cont (Some _) _ | IE_done _ -> IO.return (i, s)
    ]
;


value merr_of_ierr (e : err_msg) : IO.m 'a =
  IO.error &
  match e with
  [ EIO _ -> e
  | e -> Iteratees_err_msg e
  ]
;



(* The following is a `variant' of join in the Iteratee el m monad.
   When el' is the same as el, the type of joinI is indeed that of
   true monadic join. However, joinI is subtly different: since
   generally el' is different from el, it makes no sense to
   continue using the internal, Iteratee el' m a: we no longer
   have elements of the type el' to feed to that iteratee.
   We thus send EOF to the internal Iteratee and propagate its result.
   This join function is useful for Enumeratees, for embedded/nested streams. 
   For example, the common pattern is
     do
       lines <- joinI $ enum_lines stream2list
   The tests below show many examples (e.g., read_lines_and_one_more_line).
  
   joinI can be implemented as
     joinI outer = outer >>= lift . run
   The following is an optimized implementation, obtained by inlining.
*)

(* +
   And even more optimized and simplified version:
*)

value (joinI : iteratee 'el (iteratee 'el' 'a) -> iteratee 'el 'a)
outer_iter =
  outer_iter >>= fun inner_iter ->
  match inner_iter with
  [ IE_done inner_result -> return inner_result
  | IE_cont (Some e) _ -> throw_err e
  | IE_cont None inner_k ->
      ie_cont & fun outer_stream ->
      (inner_k (EOF None)) >>% fun (inner_iter2, _el'_stream) ->
      match inner_iter2 with
      [ IE_done inner_result -> ie_doneM inner_result outer_stream
      | IE_cont opt_err _inner_k2 ->
          match opt_err with
          [ Some e -> merr_of_ierr e
          | None -> IO.error (Divergent_iteratee "joinI")
          ]
      ]
  ]
;


(* Send EOF to Iteratee and disregard the unconsumed part of the stream
run' :: Monad m => Iteratee el m a -> m a
run' iter = check $ joinI (return iter)
 where
 check (IE_done x)   = return x
 check (IE_cont e _) = error $ "control message: " ++ show e

   The following is a more optimized implementation
*)

value (run : iteratee 'el 'a -> IO.m 'a) it =
  match it with
  [ IE_done a -> IO.return a
  | IE_cont (Some e) _ -> merr_of_ierr e
  | IE_cont None k ->
      k (EOF None) >>% fun (i, _s) ->
      match i with
      [ IE_done x -> IO.return x
      | IE_cont opt_exn _ ->
let () = dbg "run: exn=%s\n" &
  match opt_exn with
  [ None -> "none"
  | Some e -> Printexc.to_string e
  ]
in
          IO.error & match opt_exn with
          [ None -> (Divergent_iteratee "run")
          | Some e -> e
          ]
      ]
  ]
;


(* Primitive iteratees *)

(* Read a stream to the end and return all of its elements as a list
   This primitive iteratee is quite useful when writing test cases.
*)

value (stream2list : iteratee 'el (list 'el)) =
  IE_cont None (fun s -> step [] s
    where rec step rev_acc s =
let () = dbg "s2l: step: acc=%i\n" & List.length rev_acc in
      match s with
      [ Chunk c ->
          if S.is_empty c
          then ie_contM (step rev_acc)
          else ie_contM (step (S.append_to_list_rev c rev_acc))
      | EOF _ as stream -> ie_doneM (List.rev rev_acc) stream
      ]
  )
;


(* Check if the stream is finished or harbors an error *)

value (is_stream_finished : iteratee 'el (option err_msg)) =
  IE_cont None (fun s ->
    match s with
    [ EOF opt_err_msg -> ie_doneM
        (if opt_err_msg = None
         then Some End_of_file
         else opt_err_msg
        )
        s
    | Chunk _ -> ie_doneM None s
    ]
  )
;


(* Primitive iteratees: parser combinators *)

(* The analogue of hs' List.break
   It takes an el predicate and returns a string of els,
   which is the (possibly empty) prefix of the stream. None of the
   characters in the string satisfy the el predicate.
   If the stream is not terminated, the first el of the remaining
   stream satisfies the predicate
*)

(* +
   Generalized to [break_fold].
*)

value (break_fold : ('el -> bool) -> ('a -> 'el -> 'a) -> 'a ->
                    iteratee 'el 'a ) cpred func init =
  IE_cont None
    (let rec step acc s =
       match s with
       [ Chunk c ->
           if S.is_empty c
           then ie_contM (step acc)
           else
             let (matches, tail) = S.break cpred c in
let () = dbg "S.break: %i -> %i+%i\n" (S.length c) (S.length matches) (S.length tail) in
             let new_acc = S.fold S.L func acc matches in
             if S.is_empty tail
             then ie_contM (step new_acc)
             else ie_doneM (new_acc) (Chunk tail)
       | EOF _  as e -> ie_doneM acc e
       ]
     in
       step init
    )
;


value (mapI : ('a -> 'b) -> iteratee 'el 'a -> iteratee 'el 'b) f i =
  i >>= return % f
;


value (break : ('el -> bool) -> iteratee 'el (list 'el)) cpred =
  mapI List.rev &
  break_fold cpred (fun acc elem -> [elem :: acc]) []
;


(* +
   [prepend f (fun x -> i)] returns an iteratee [ires]
   which behaves exactly as [i], but each time when [ires] begins
   to process data, [f ()] is called and its result is given to
   [fun x -> i] function.
*)

value (prepend : (unit -> 'x) -> ('x -> iteratee 'el 'a) -> iteratee 'el 'a)
f i =
  ie_cont & fun s ->
    match i (f ()) with
    [ IE_done x -> ie_doneM x s
    | IE_cont None k -> k s
    | IE_cont (Some e) _ -> merr_of_ierr e
    ]
;


value (break_chars : (char -> bool) -> iteratee char string) cpred =
  mapI (fun b ->
     let r = Buffer.contents b in (dbg "break_chars: b=%i, cont=%S\n"
       (Obj.magic b) r; r)
  ) &
  prepend
    (fun () -> Buffer.create break_chars_buf_init_size)
    (fun buf ->
       break_fold
         cpred
         (fun buf c -> (Buffer.add_char buf c; buf))
         buf
    )
;


(* A particular optimized case of the above: skip all elements of the stream
   satisfying the given predicate -- until the first element
   that does not satisfy the predicate, or the end of the stream.
   This is the analogue of hs' List.dropWhile
*)

value (drop_while : ('el -> bool) -> iteratee 'el unit) cpred =
  IE_cont None step
  where rec step s =
    match s with
    [ Chunk c ->
        let str = S.drop_while cpred c in
let () = dbg "drop_while: %i -> %i\n" (S.length c) (S.length str) in
        if S.is_empty str
        then ie_contM step
        else ie_doneM () (Chunk str)
    | EOF _ -> ie_doneM () s
    ]
;


(* Look ahead at the next element of the stream, without removing
   it from the stream.
   Return (Just c) if successful, return Nothing if the stream is
   terminated (by EOF or an error)
*)

value (peek : iteratee 'el (option 'el)) =
  IE_cont None
    (let rec step s =
       match s with
       [ Chunk c ->
           match S.get_first_item c with
           [ None -> ie_contM step
           | Some el -> ie_doneM (Some el) s
           ]
       | EOF _ -> ie_doneM None s
       ]
     in
       step
    )
;


(* Attempt to read the next element of the stream and return it.
   Raise a (recoverable) error if the stream is terminated
*)

value (head : iteratee 'el 'el) =
  IE_cont None step
  where rec step s =
    match s with
    [ Chunk c ->
        match S.destruct_first_item c with
        [ None -> ie_contM step
        | Some (h, t) -> ie_doneM h (Chunk t)
        ]
    | EOF _ -> IO.return (IE_cont (Some (set_eof s)) step, s)
    ]
;


value pervasives_eq x y = (0 = Pervasives.compare x y)
;


(* Given a sequence of elements, attempt to match them against
   the elements on the stream. Return the count of how many
   elements matched. The matched elements are removed from the
   stream.
   For example, if the stream contains "abd", then (heads "abc") 
   will remove the characters "ab" and return 2.
*)

value (heads : ?eq:('el->'el->bool) -> list 'el -> iteratee 'el int)
?(eq=pervasives_eq) str =
  let rec loop cnt str =
    if str = []
    then return cnt
    else ie_cont (fun s -> step cnt str s)
  and step cnt str s =
    match (str, s) with
    [ (_, EOF _) | ([], _) -> ie_doneM cnt s
    | ([strh :: strt], Chunk c) ->
        match S.destruct_first_item c with
        [ None -> ie_contM (step cnt str)
        | Some (h, t) ->
            if eq strh h
            then step (cnt + 1) strt (Chunk t)
            else ie_doneM cnt s
        ]
    ]
  in
    loop 0 str
;


(* Skip the rest of the stream *)

value (skip_till_eof : iteratee 'el unit) =
  IE_cont None step
  where rec step s =
    match s with
    [ Chunk _ -> ie_contM step
    | EOF _ -> ie_doneM () s
    ]
;


(* Skip n elements of the stream, if there are that many
   This is the analogue of hs' List.drop
*)

value rec drop_step n s =
  match s with
  [ Chunk c ->
      let len = c.S.len in
      if len < n
      then ie_contM (drop_step (n - len))
      else ie_doneM () (Chunk (S.drop n c))
  | EOF _ -> ie_doneM () s
  ]
;

value (drop : int -> iteratee 'el unit) n =
  if n = 0
  then return ()
  else IE_cont None (drop_step n)
;


value rec (io_iter : ('a -> IO.m unit) -> list 'a -> IO.m unit) f l =
  match l with
  [ [] -> IO.return ()
  | [h :: t] -> f h >>% fun () -> io_iter f t
  ]
;


value print_line s =
  IO.write IO.stdout (s ^ "\n")
;


(* Enumerators
   Each enumerator takes an iteratee and returns an iteratee:
   an Enumerator is an iteratee transformer.
   The enumerator normally stops when the stream is terminated
   or when the iteratee moves to the done state, whichever comes first.
*)

type enumerator 'el 'a = iteratee 'el 'a -> IO.m (iteratee 'el 'a);


(* It is typical for an enumerator to disregard the remaining-stream
   part of the state of the Iteratee computations. Some enumerators
   may use this remaining stream data to report a location of an error
   in stream terms, for example.
*)

(* The most primitive enumerator: applies the iteratee to the terminated
   stream. The result is the iteratee usually in the done state.
   A `good' iteratee must move to the done state or error state
   upon receiving the EOF.
*)

value (enum_eof : enumerator 'el 'a) i =
  match i with
  [ (IE_cont (Some _) _) | IE_done _ -> IO.return i
  | IE_cont None k ->
      k (EOF None) >>% fun (i, _s) ->
      IO.return &
      match i with
      [ IE_done _ -> i  (* done state *)
      | IE_cont None _ -> throw_err & Divergent_iteratee "enum_eof"
      | IE_cont (Some e) _ -> throw_err e   (* error state *)
      ]
  ]
;


(* Another primitive enumerator: tell the Iteratee the stream terminated
   with an error
*)

value (enum_err : err_msg -> enumerator 'el 'a) e i =
  match i with
  [ IE_cont None k -> k (EOF (Some e)) >>% fun (i, _s) ->
      IO.return &
      match i with
      [ IE_done _ -> i  (* done state *)
      | IE_cont None _ -> throw_err & Divergent_iteratee "enum_err"
      | IE_cont (Some e) _ -> throw_err e  (* error state *)
      ]
  | IE_done _ | IE_cont (Some _) _ -> IO.return i
  ]
;


(* The composition of two enumerators: just the functional composition.
   It is convenient to flip the order of the arguments of the composition
   though: in e1 >>> e2, e1 is executed first.
   The composition of enumerators is not exactly (.): we take care
   to force the result of the enumerator e1 before passing it to e2.
   We are thus certain that all effects of enumerating e1 happen before
   the effects of e2.
*)

value ( (>>>) : enumerator 'el 'a -> enumerator 'el 'a -> enumerator 'el 'a)
e1 e2 =
  fun i -> e1 i >>% e2
;


(* The pure 1-chunk enumerator
   It passes a given string to the iteratee in one chunk
   This enumerator does no IO and is useful for testing of base parsing
*)

value (enum_pure_1chunk : list 'el -> enumerator 'el 'a) lst i =
  let c = S.of_list lst in
  match i with
  [ IE_cont None k -> k (Chunk c) >>% IO.return % fst
  | IE_cont (Some _) _ | IE_done _ -> IO.return i
  ]
;


(* The pure n-chunk enumerator
   It passes a given string to the iteratee in chunks no larger than n.
   This enumerator does no IO and is useful for testing of base parsing
   and handling of chunk boundaries
*)

value (enum_pure_nchunk : list 'el -> int -> enumerator 'el 'a) lst n i =
  let rec loop str i =
    let ret () = IO.return i in
    if S.is_empty str
    then ret ()
    else
      match i with
      [ IE_cont None k ->
          let (s1, s2) = S.split_at n str in
          k (Chunk s1) >>% loop s2 % fst
      | IE_cont (Some _) _ | IE_done _ -> ret ()
      ]
  in
    loop (S.of_list lst) i
;


value mprintf fmt = Printf.ksprintf (IO.write IO.stdout) fmt
;


value (mres : IO.m 'a -> IO.m (res 'a)) m =
  IO.catch
    (fun () -> m >>% fun r -> IO.return & `Ok r)
    (fun e -> IO.return & `Error e)
;

value (_munres : res 'a -> IO.m 'a) r =
  match r with
  [ `Ok x -> IO.return x
  | `Error ep -> IO.error ep
  ]
;


(* The enumerator of M's channels
   We use the same buffer all throughout enumeration
*)

value (enum_fd : IO.input_channel -> enumerator char 'a) inch i =
  let buffer_size = enum_fd_buffer_size.val in
  let buf_str = String.create buffer_size
  and buf_arr = Array.make buffer_size '\x00' in
  let rec loop k =
    mres (IO.read_into inch buf_str 0 buffer_size) >>% fun read_res ->
    match read_res with
    [ `Error e ->
        k (EOF (some & ierr_of_merr e)) >>% IO.return % fst
    | `Ok have_read ->
        mprintf "Read buffer, size %i\n" have_read >>% fun () ->
        let () = assert (have_read >= 0) in
        if have_read = 0
        then
          IO.return (ie_cont k)
        else
          let c = S.replace_with_substring buf_arr buf_str 0 have_read in
          k (Chunk c) >>% check % fst
    ]
  and check i =
    match i with
    [ IE_cont None k -> loop k
    | IE_cont (Some _) _ | IE_done _ -> IO.return i
    ]
  in
    check i
;


value (enum_file : string -> enumerator char 'a) filepath iterv =
  mprintf "opened file %S\n" filepath >>% fun () ->
  IO.open_in filepath >>% fun inch ->
  enum_fd inch iterv >>% fun r ->
  IO.close_in inch >>% fun () ->
  mprintf "closed file %S\n" filepath >>% fun () ->
  IO.return r
;



(* Stream adapters: Iteratees and Enumerators at the same time *)

(* Stream adapters, or Enumeratees, handle nested streams. Stream nesting, 
   or encapsulation, is rather common: buffering, character encoding, 
   compression, encryption, SSL are all examples of stream nesting. On one
   hand, an Enumeratee is an Enumerator of a nested stream:
   it takes an iteratee for a nested stream, feeds its some data,
   returning the resulting iteratee when the nested stream is finished
   or when the iteratee is done. On the other hand, an Enumeratee
   is the Iteratee for the outer stream, taking data from the parent
   enumerator.
   One can view an Enumeratee as a AC/DC or voltage converter, or as
   a `vertical' composition of iteratees (compared to monadic bind, which
   plumbs two iteratees `horizontally')

   In the trivial case (e.g., Word8 to Char conversion), one element
   of the output stream is mapped to one element of the nested stream.
   Generally, we may need to read several elements from the outer stream to
   produce one element for the nested stream. Sometimes we can produce
   several nested stream elements from a single outer stream element.
  
   That many-to-many correspondence between the outer and the nested streams
   brings a complication. Suppose an enumeratee received an outer
   stream chunk of two elements elo1 and elo2. The enumeratee picked 
   elo1 and decoded it into a chunk of three elements eli1, eli2, and
   eli3, passing the chunk to the nested iteratee. The latter has read 
   eli1 and declared itself Done. The enumeratee has to return a value
   that contains the result of the nested Iteratee, and the 
   fact the element elo2 of the outer stream is left unprocessed.
   (We stress that we do _not_ report that there  are two elements left on
   the nested stream (eli2 and eli3): the nested stream is an internal
   resource of an enumeratee, which we do not leak out.)  We can
   report all these pieces of data if we pack them in a value
   of the following type
*)

type enumeratee 'elo 'eli 'a = 
  iteratee 'eli 'a -> iteratee 'elo (iteratee 'eli 'a)
;

(* We come to the same type in a different way. Suppose that the
   enumeratee has received EOF on its stream (that is, the outer stream).
   The enumeratee, as the outer iteratee, must move to the Done state. 
   Yet the nested iteratee is not finished. The enumeratee then has to
   return the nested iteratee as its result.
   The type of Enumeratee makes it clear that all effects of the inner
   Iteratee are absorbed into the outer Iteratee.
*)


(* One of the simplest Enumeratee: the nested stream is the prefix
   of the outer stream of exactly n elements long. Such nesting arises
   when several independent streams are concatenated.

   Read n elements from a stream and apply the given (nested) iteratee to the
   stream of the read elements. Unless the stream is terminated early, we
   read exactly n elements (even if the iteratee has accepted fewer).
   The last phrase implies that
          take n iter1 >> take m iter2
       is different from
          take (n+m) (iter1 >> iter2)
    in the case iter1 receives a chunk, moves to a done state after
    consuming a part of it. Then in (iter1 >> iter2), iter2 would get
    the rest of the chunk. In
          take n iter1 >> take m iter2
    iter2 would not get the rest of iter1's chunk. In fact, 
          take n iter1 >> take m iter2 
    is the same as
          drop n >> take m iter2 
   This behavior is intended: `take' reinforces fixed-length frame boundaries.
*)

value (take : int -> enumeratee 'el 'el 'a) n i =
  let rec take n i =
    if n = 0
    then return i
    else
      match i with
      [ IE_cont None k -> ie_cont (step n k)
      | IE_cont (Some _) _ | IE_done _ -> drop n >>= fun () -> return i
      ]
  and step n k s =
    match s with
    [ Chunk c ->
        let len = S.length c in
        if len = 0
        then ie_contM (step n k)
        else
          if len < n
          then
            k s >>% fun (i, _) ->
            IO.return (take (n - len) i, empty_stream)
          else
            let (s1, s2) = S.split_at n c in
            k (Chunk s1) >>% fun (i, _) ->
            ie_doneM i (Chunk s2)
    | EOF _ -> k s >>% fun (i, _) -> ie_doneM i s
    ]
  in
    take n i
;


(* Map the stream: yet another Enumeratee
   Given the stream of elements of the type elo and the function elo->eli,
   build a nested stream of elements of the type eli and apply the
   given iteratee to it.
   Note the contravariance.
   The difficult question is about left-over elements.
   Suppose the enumeratee received a chunk of elo elements,
   mapped them to eli elements and passed the chunk to the inner iteratee.
   The inner iteratee moved to a done state and reported N eli elements
   as not consumed.
   There are two choices for the result of the Enumeratee:
    no left-over elo elements; the inner iteratee in the Done state
    with N left-over eli elements
    N left-over elo elements; the inner iteratee in the Done state
    with 0 left-over eli elements.
   The second choice assumes that we can map from left-over eli elements
   back to the left-over elo elements. Since we map one elo
   element to one eli element, we can always determine how many
   elo elements left over from the number of remaining eli elements.
   For now, we go for the first choice, which seems simpler and
   more general.
*)

value (map_stream : ('elo -> 'eli) -> enumeratee 'elo 'eli 'a) f i =
  let rec map_stream i =
    match i with
    [ IE_cont None k -> ie_cont (step k)
    | IE_cont (Some _) _ | IE_done _ -> return i
    ]
  and step k s =
    match s with
    [ Chunk c ->
        if S.is_empty c
        then ie_contM (step k)
        else
          k (Chunk (S.map f c)) >>% fun (iv, _) ->
          IO.return (map_stream iv, empty_stream)
    | EOF _ ->
        ie_doneM (ie_cont k) s
    ]
  in
    map_stream i
;


(* Convert one stream into another, not necessarily in `lockstep'
   The transformer map_stream maps one element of the outer stream
   to one element of the nested stream. The transformer below is more
   general: it may take several elements of the outer stream to produce
   one element of the inner stream.
   The transformation from one stream to the other is specified as
   Iteratee elo m eli.
   This is a generalization for Monad.sequence
*)

value (sequence_stream : iteratee 'elo 'eli -> enumeratee 'elo 'eli 'a) fi i =
  let rec sequence_stream i =
    match i with
    [ IE_cont None k ->
        is_stream_finished >>= fun is_fin ->
        match is_fin with
        [ None -> step k
        | Some _ -> return i
        ]
    | IE_cont (Some _) _ | IE_done _ -> return i
    ]
  and step k =
    fi >>= fun v ->
    liftI ((k & chunk_of v) >>% fun (i, _s) ->
           IO.return (sequence_stream i))
  in
    sequence_stream i
;


value is_space c = (c = '\x20' || c = '\x09' || c = '\x0D' || c = '\x0A')
;


(* Convert the stream of characters to the stream of words, and
   apply the given iteratee to enumerate the latter.
   Words are delimited by white space.
   This is the analogue of hs' List.words
   More generally, we could have used sequence_stream to implement enum_words.
*)

value rec (enum_words : enumeratee char string 'a) i =
  match i with
  [ IE_cont None k ->
      drop_while is_space >>= fun () ->
      break_chars is_space >>= fun w ->
let () = dbg "enum_words: %S\n" w in
      if w = ""
      then return i  (* finished *)
      else
        liftI (
          k (chunk_of w) >>% fun (i, _s) ->
          (IO.return (enum_words i))
        )
  | IE_cont (Some _) _ | IE_done _ -> return i
  ]
;


module SC = Subarray_cat
;

module UTF8
 :
  sig
    type uchar = private int;
    value utf8_of_char : enumeratee char uchar 'a;
  end
 =
  struct
    type uchar = int;

    exception Bad_utf8 of string
    ;

(*  without actual conversion:
    value sc_ulen sc =
      let len = SC.length sc in
      (len, len, None)
    ;
    value sc_recode ~scfrom ~arrto ~uchars =
      for i = 0 to uchars-1 do
      ( arrto.(i) := Char.code & SC.get scfrom i
      )
      done
    ;
*)

    value relaxed_utf8 = ref False  (* TODO: check it. *)
    ;


    value in_tail byte =
      byte land 0b11_000_000 = 0b10_000_000

    and bad_tail =
      some & Bad_utf8 "tail != 0x80..0xBF"
    ;


    value decode_4bytes a b c d =
      ((a land 0b00_000_111) lsl 18) lor
      ((b land 0b00_111_111) lsl 12) lor
      ((c land 0b00_111_111) lsl 6) lor
      (d land 0b00_111_111)
    ;


    (* returns (count_of_chars, length_in_bytes, option error) *)
    value (sc_ulen : SC.t char -> (int * int * option exn)) sc =
      let sc_len = SC.length sc in
      let get i = Char.code (SC.get sc i) in
      let rec loop ~ch ~i =
        if i = sc_len
        then
          (ch, i, None)
        else
          let byte = get i in
          if byte < 0x80
          then loop ~ch:(ch+1) ~i:(i+1)
          else if byte <= 0xBF
          then (ch, i, some & Bad_utf8 "head 0x80..0xBF")
          else if byte <= 0xC1
          then
            (if relaxed_utf8.val
             then skip_tail ~ch ~i ~sz:2
             else (ch, i, some & Bad_utf8 "head 0xC0..0xC1 (overlong)")
            )
          else if byte < 0xE0
          then skip_tail ~ch ~i ~sz:2
          else if byte < 0xF0
          then skip_tail ~ch ~i ~sz:3
          else if byte <= 0xF4
          then skip_tail ~ch ~i ~sz:4
          else (ch, i, some & Bad_utf8 "head 0xF5..0xFF")
      and skip_tail ~ch ~sz ~i =  (* check len, then check_tail *)
        if i + sz > sc_len
        then (ch, i, None)
        else
          (if sz = 4 && not relaxed_utf8.val
           then check_tail4  (* check for codepoint too *)
           else check_tail ~len:(sz-1)
          ) ~i ~ch ~ifrom:(i+1)
      and check_tail ~i ~ch ~ifrom ~len =  (* just check for 0b10xxxxxx *)
        if len = 0
        then loop ~ch:(ch+1) ~i:ifrom
        else
          let byte = get ifrom in
          if in_tail byte
          then check_tail ~i ~ch ~ifrom:(ifrom+1) ~len:(len-1)
          else (ch, i, bad_tail)
      and check_tail4 ~i ~ch ~ifrom =  (* 0b10xxxxxx and codepoint *)
        let a = get i and b = get (i+1) and c = get (i+2) and d = get (i+3) in
        if not (in_tail b && in_tail c && in_tail d)
        then
          (ch, i, bad_tail)
        else
          let codepoint = decode_4bytes a b c d in
          if codepoint > 0x10FFFF
          then (ch, i, some & Bad_utf8 "codepoint > 0x10FFFF")
          else loop ~ch:(ch+1) ~i:(ifrom+4)
      in
        loop ~ch:0 ~i:0
    ;


    value sc_recode ~scfrom ~arrto ~uchars =
      let get i = Char.code (SC.get scfrom i) in
      let rec loop ~ifrom ~ito =
        if ito = uchars
        then ()
        else
          let a = get ifrom in
          if a < 0x80
          then put ~i:(ifrom+1) ~ito ~char:a
          else if a < 0xC0
          then assert False  (* sc_ulen checks this *)
          else
          let b = get (ifrom+1) in
          if a < 0xE0
          then
            put ~i:(ifrom+2) ~ito ~char:(
              ((a land     0b11_111) lsl 6) lor
              ( b land 0b00_111_111)
            )
          else
          let c = get (ifrom+2) in
          if a < 0xF0
          then
            put ~i:(ifrom+3) ~ito ~char:(
              ((a land      0b1_111) lsl 12) lor
              ((b land 0b00_111_111) lsl  6) lor
              ( c land 0b00_111_111)
            )
          else
          let d = get (ifrom+3) in
          put ~i:(ifrom+4) ~ito ~char:(decode_4bytes a b c d)

      and put ~i ~ito ~char =
        ( arrto.(ito) := char
        ; loop ~ifrom:i ~ito:(ito+1)
        )
      in
        loop ~ifrom:0 ~ito:0
    ;


    value ensure_size array_option_ref size =
      let realloc () =
        let r = Array.make size (-1) in
        ( array_option_ref.val := Some r
        ; r
        )
      in
      match array_option_ref.val with
      [ None -> realloc ()
      | Some array ->
          if Array.length array < size
          then realloc ()
          else
            (* for debugging: *)
            let () = Array.fill array 0 (Array.length array) (-2) in
            array
      ]
    ;

    value utf8_of_char uit =
      let arr_ref = ref None in
      let rec utf8_of_char ~acc uit =
        match uit with
        [ IE_cont None k -> ie_cont & fun s -> step ~acc ~k s
        | IE_cont (Some _) _ | IE_done _ -> return uit
        ]
      and step ~acc ~k stream =
        let err oe =
          k (EOF oe) >>% fun (iv, _s) ->
          IO.return (return iv, stream)
        in
        match (acc, stream) with
        [ (`Error e, _) ->
            (* TODO: test this branch. *)
            (* let () = Printf.eprintf "utf8: (`Error, _)\n%!" in *)
            err & Some e
        | (_, EOF oe) ->
            (* mprintf "utf8: (_, `EOF None=%b)\n%!" (oe=None) >>% fun () -> *)
            err oe
        | (`Acc acc, Chunk c) ->
            let sc = SC.make [acc; c] in
            let (ulen_chars, ulen_bytes, error_opt) = sc_ulen sc in
            let res_arr = ensure_size arr_ref ulen_chars in
            let () = sc_recode ~scfrom:sc ~arrto:res_arr ~uchars:ulen_chars in
            k (Chunk (S.of_array_sub res_arr 0 ulen_chars)) >>% fun (iv, _) ->
            let acc' = match error_opt with
              [ None -> `Acc (SC.sub_copy_out sc ~ofs:ulen_bytes
                              ~len:(SC.length sc - ulen_bytes)
                             )
              | Some e -> `Error e
              ]
            in
            IO.return (utf8_of_char ~acc:acc' iv, empty_stream)
        ]
      in
        utf8_of_char ~acc:(`Acc S.empty) uit
    ;

  end;  (* `UTF8' functor *)



(* [break_copy ~cpred ~outch] reads input just like [break ~cpred],
   but writes the input it has read into output channel [outch].
*)

value break_copy ~cpred ~outch : iteratee char unit =
  IE_cont None step
  where rec step s =
    match s with
    [ EOF _ as e -> ie_doneM () e
    | Chunk c ->
        if S.is_empty c
        then ie_contM step
        else
          let (matches, tail) = S.break cpred c in
          let matches_str = S.to_string matches in
          ( IO.write outch matches_str >>% fun () ->
            if S.is_empty tail
            then ie_contM step
            else ie_doneM () (Chunk tail)
          )
    ]
;


(* [break_limit ~pred ~limit] reads at most [limit] elements that
   don't satisfy predicate [pred], and returns when it either
   found element that satisfy [pred], or when [limit] elements were
   read and no satisfying element was found, or when there were an
   EOF or error found and neither any satisfying element was found
   nor [limit] elements was read.
   Returns: tuple [(status, subarray)], where
     [status = [= `Found | `Hit_limit | `Hit_eof ]]
     and [subarray] contains all the elements read.
   If the stream has exactly [limit] elements and no elements
   found, [`Hit_limit] is returned (limit has more priority
   than stream's end).
*)

value break_limit ~pred ~limit
: iteratee 'a ([= `Found | `Hit_limit | `Hit_eof] * Subarray.t 'a) =
  IE_cont None (step ~sc:(SC.make [S.empty]) ~left:limit)
  where rec step ~sc ~left s =
    let ret status sc s =
      ie_doneM (status, SC.sub_copy_out sc) s
    in
    if left = 0
    then
      ret `Hit_limit sc s
    else
      match s with
      [ EOF _ -> ret `Hit_eof sc s
      | Chunk c ->
          match S.break_limit ~limit:left pred c with
          [ `Found (prefix, rest) ->
              ret `Found (SC.append sc prefix) (Chunk rest)
              (* not copying here, since [ret->sub_copy_out] will copy *)
          | `Hit_limit ->
              let (prefix, rest) = S.split_at left c in
              step ~sc:(SC.append sc prefix) ~left:0 (Chunk rest)
              (* not copying here, since [step->ret->sub_copy_out] will copy *)
          | `Hit_end ->
              ie_contM &
                step
                  ~sc:(SC.append sc (S.copy c))
                  ~left:(left - S.length c)
          ]
      ]
;


value (limit : int -> enumeratee 'el 'el 'a) lim = fun it ->
  let rec limit ~lim ~it =
    let () = dbg "limit: lim=%i\n%!" lim in
    match (lim, it) with
    [ (_, (IE_done _ | IE_cont (Some _) _))
      | (0, IE_cont None _) -> return it
    | (lim, IE_cont None k) ->
        ie_cont & step ~left:lim ~k
    ]
  and step ~left ~k s
   : IO.m (iteratee 'el (iteratee 'el 'a) * stream 'el) =
    match (s : stream 'el) with
    [ EOF _ -> k s >>% fun (i, _) -> ie_doneM i s
    | Chunk c ->
        let len = S.length c in
        let () = dbg "limit/step: len=%i\n%!" len in
        if len <= left
        then
          k s >>% fun (it, s) ->
          IO.return (limit ~lim:(left - len) ~it, s)
        else
          let (c1, c2) = S.split_at left c in
          k (Chunk c1) >>% fun (it, s1') ->
            let s' = Chunk (
              match s1' with
              [ Chunk c1' -> S.concat_splitted c1' c2
              | EOF _ -> c2
              ]) in
            let () = dbg "limit: concated: %s\n%!" & dbgstream s' in
            ie_doneM it s'
    ]
  in
    limit ~lim ~it
;


value
  (catchk : (unit -> iteratee 'el 'a) ->
            ( err_msg ->
              (stream 'el -> IO.m (iteratee 'el 'a  *  stream 'el)) ->
              iteratee 'el 'a
            ) ->
            iteratee 'el 'a
  ) itf handler =
  let rec catchk it =
    match it with
    [ IE_done _ -> it
    | IE_cont (Some e) k ->
        try
          handler e k
        with
        [ e -> throw_err e ]
    | IE_cont None k -> ie_cont (step k)
    ]
  and step k s =
    (IO.catch
       (fun () -> k s >>% fun r -> IO.return (`Ok r))
       (fun e -> IO.return (`Error e))
    ) >>% fun
    [ `Ok (it, s') -> IO.return (catchk it, s')
    | `Error e -> IO.return (catchk (throw_err e), s)
    ]
  in
    let () = dbg "catchk: entered\n%!" in
    let it =
      try
        itf ()
      with
      [ e -> throw_err e ]
    in
      catchk it
;


value
  (catch : (unit -> iteratee 'el 'a) ->
           ( err_msg ->
             iteratee 'el 'a
           ) ->
           iteratee 'el 'a
  ) itf handler =
  catchk itf (fun err_msg _cont -> handler err_msg)
;




value printf fmt =
  Printf.ksprintf (fun s -> lift & IO.write IO.stdout s) fmt
;


value gather_to_string : iteratee char string =
  prepend
    (fun () -> Buffer.create 50)
    (fun buf ->
       ie_cont step
       where rec step s =
         match s with
         [ Chunk c ->
             ( Subarray.buffer_add buf c ; ie_contM step )
         | EOF None ->
             ie_doneM (Buffer.contents buf) s
         | EOF (Some e) ->
             IO.error e
         ]
    )
;

  module Ops
   :
    sig
      (* IO binds: *)
      value ( %<< ) : ('a -> It_IO.m 'b) -> It_IO.m 'a -> It_IO.m 'b;
      value ( >>% ) : It_IO.m 'a -> ('a -> It_IO.m 'b) -> It_IO.m 'b;

      (* Iteratees binds: *)
      value ( =<< ) :
        ('a -> iteratee 'el 'b) -> iteratee 'el 'a -> iteratee 'el 'b;
      value ( >>= ) :
        iteratee 'el 'a -> ('a -> iteratee 'el 'b) -> iteratee 'el 'b;

      (* Enumerators sequence: *)
      value ( >>> ) :
        enumerator 'el 'a -> enumerator 'el 'a -> enumerator 'el 'a
      ;

    end
   =
    struct
      value ( %<< ) = ( %<< );
      value ( >>% ) = ( >>% );

      value ( =<< ) = ( =<< );
      value ( >>= ) = ( >>= );

      (* Enumerators sequence: *)
      value ( >>> ) = ( >>> );
    end
  ;


(* Feed Iteratee a piece of stream. Disregard the remaining stream
   (the operation typically used by enumerators)
*)

value feedI
  (k : stream 'el -> IO.m (iteratee 'el 'a  *  stream 'el))
  (str : stream 'el)
 :
  IO.m (iteratee 'el 'a)
 =
  k str >>% (IO.return % fst)
;


exception Itlist_empty;

module Anyresult_lasterror
 =
  struct

        value itlist_step_firstresult_lasterror
          (lst : list (iteratee 'el 'a))
          (s : stream 'el)
         :
          IO.m [= `First_result of (iteratee 'el 'a * stream 'el)
               |  `Last_error of err_msg
               |  `Cont of list (iteratee 'el 'a)
               ]
         =
          let rec loop lasterropt acc lst =
            match lst with
            [ [] ->
                if acc = []
                then
                  match lasterropt with
                  [ None -> assert False
                  | Some err -> IO.return & `Last_error err
                  ]
                else
                  IO.return & `Cont (List.rev acc)
            | [hd :: tl] ->
                match hd with
                [ (IE_done _) as it -> IO.return & `First_result (it, s)
                | IE_cont ((Some _) as someerr) _ ->
                    loop someerr acc tl
                | IE_cont None k ->
                    k s >>% fun
                    [ (IE_done _, _) as r ->
                        IO.return & `First_result r
                    | (IE_cont (Some _ as someerr) _, _) ->
                        loop someerr acc tl
                    | ((IE_cont None _ as hd'), _s) ->
                        loop lasterropt [hd' :: acc] tl
                    ]
                ]
            ]
          in
            if lst = []
            then IO.return & `Last_error Itlist_empty
            else loop None [] lst
        ;

        value get_any_done lst =
          loop lst
          where rec loop lst =
            match lst with
            [ [ ((IE_done _) as x) :: _ ] -> Some x
            | [] -> None
            | [ (IE_cont _ _) :: _ ] -> loop lst
            ]
        ;

        value itlist_anyresult_lasterror
          (lst : list (iteratee 'el 'a))
         :
          iteratee 'el 'a
         =
          match get_any_done lst with
          [ Some x -> x
          | None -> ie_cont & step lst
              where rec step lst s =
                itlist_step_firstresult_lasterror lst s >>% fun
                [ `First_result r -> IO.return r
                | `Last_error e -> IO.error e
                | `Cont [] -> assert False
                | `Cont [it :: []] ->  IO.return (it, empty_stream)
                | `Cont lst -> ie_contM & step lst
                ]
          ]
        ;

  end
;

(* +
   [itlist_anyresult_lasterror it_lst] takes a list of iteratees,
   passes input to all of them, and returns either the iteratee
   that left alone (when others are failed with error), or
   the last met error (when all iteratees have failed).
   When the empty list is given, error [Itlist_empty] is returned.
*)

value itlist_anyresult_lasterror
 :
  list (iteratee 'el 'a) -> iteratee 'el 'a
 =
  Anyresult_lasterror.itlist_anyresult_lasterror
;


(* +
   [junk] = [drop 1]
*)

value junk = IE_cont None (fun s -> drop_step 1 s)
;


exception SInt_overflow;
exception SInt_not_a_number of string;

module Reading_ints
 :
  sig
    value read_uint : iteratee char int;
    value read_uint_nz : iteratee char int;
    value read_int : iteratee char int;
    value read_int_nz : iteratee char int;

    value read_uint32 : iteratee char int32;
    value read_uint32_nz : iteratee char int32;
    value read_int32 : iteratee char int32;
    value read_int32_nz : iteratee char int32;

    value read_uint64 : iteratee char int64;
    value read_uint64_nz : iteratee char int64;
    value read_int64 : iteratee char int64;
    value read_int64_nz : iteratee char int64;
  end
 =
  struct

(*
    value ( & ) f x = f x;
*)

    module type SIGNED_INT
     =
      sig
        type t;
        value max_int : t;
        (* min_int = -max_int - 1 *)

        (* must work for small ints and small numbers:t : *)
        value of_int : int -> t;
        value to_int : t -> int;

        (* may overflow silently: *)
        value ( + ) : t -> t -> t;
        value ( - ) : t -> t -> t;
        value ( * ) : t -> t -> t;

        (* should truncate towards zero: *)
        value ( / ) : t -> t -> t;

        value ( <? ) : t -> t -> bool;
        value ( =? ) : t -> t -> bool;
      end
    ;

    module SInt_T : SIGNED_INT with type t = int
     =
      struct
        type t = int;
        value max_int = Pervasives.max_int;
        value of_int x = x;
        value to_int x = x;
        value ( + ) = Pervasives.( + );
        value ( - ) = Pervasives.( - );
        value ( * ) = Pervasives.( * );
        value ( / ) = Pervasives.( / );
        value ( <? ) = Pervasives.( < );
        value ( =? ) = Pervasives.( == );
      end
    ;

    module SInt32_T : SIGNED_INT with type t = int32
     =
      struct
        type t = int32;
        value max_int = Int32.max_int;
        value of_int = Int32.of_int;
        value to_int = Int32.to_int;
        value ( + ) = Int32.add;
        value ( - ) = Int32.sub;
        value ( * ) = Int32.mul;
        value ( / ) = Int32.div;
        value ( <? ) a b = (Int32.compare a b) < 0;
        value ( =? ) a b = (Int32.compare a b) = 0;
      end
    ;

    module SInt64_T : SIGNED_INT with type t = int64
     =
      struct
        type t = int64;
        value max_int = Int64.max_int;
        value of_int = Int64.of_int;
        value to_int = Int64.to_int;
        value ( + ) = Int64.add;
        value ( - ) = Int64.sub;
        value ( * ) = Int64.mul;
        value ( / ) = Int64.div;
        value ( <? ) a b = (Int64.compare a b) < 0;
        value ( =? ) a b = (Int64.compare a b) = 0;
      end
    ;

    module SInt_F (S : SIGNED_INT)
     :
      sig
        (* value digits : S.t -> int; *)

        value read_unsigned_gen : ~allow0:bool -> iteratee char S.t;
        value read_signed_gen : ~allow0:bool -> iteratee char S.t;
      end
     =
      struct
        open S;

        value zero = of_int 0
        ;

        value ( ~- ) n = zero - n
          and ( >? ) a b = not (a <? b) && not (a =? b)
          and ( >=? ) a b = not (a <? b)
          and ( <>? ) a b = not (a =? b)
        ;

        value one = of_int 1
        ;

        value minus_one = (- one)
        ;

        value min_int = (- max_int) - one
        ;

        value ten = of_int 10
        ;

        value rec digits_count n =
          Pervasives.( + )
            1
            (let n' = n / ten in
             if n' =? zero
             then 0
             else digits_count n'
            )
        ;

        value rem a b = (a - (a / b) * b)
        ;

        module P = Pervasives;

        value string_reverse_inplace str = P.(
          let len = String.length str in
          let len1 = len - 1 in
          let len2 = len / 2 - 1 in
          ( for i = 0 to len2
            do
              let j = P.( - ) len1 i in
              let tmp = str.[i] in
              ( str.[i] := str.[j]
              ; str.[j] := tmp
              )
            done
          ; str
          )
        );

        value min_int_digits = digits_count min_int;
        value max_int_digits = digits_count max_int;

        value to_base_abs b n =
          let buf = Buffer.create max_int_digits in
          let intb = to_int b in
          let digit n =
            let n = abs (to_int n) in
            ( assert (n < intb)
            ; assert (n < 10)
            ; Char.chr (P.( + ) n (Char.code '0'))
            ) in
          let rec loop n =
            let d = rem n b in
            let c = digit d in
            let () = Buffer.add_char buf c in
            let n' = n / b in
            if n' =? zero
            then string_reverse_inplace (Buffer.contents buf)
            else loop n'
          in
            loop n
        ;

        value to_dec_abs = to_base_abs ten
        ;

        value max_int_dec_abs = to_dec_abs max_int;

        value min_int_dec_abs = to_dec_abs min_int;


        value from_base_neg b ~maxstr str =
          let len = String.length str in
          let rec loop acc i =
            if i = len
            then acc
            else
              let digit ch =
                if (ch >= '0' && ch <= '9')
                then
                  let d = of_int (P.( - ) (Char.code ch) (Char.code '0')) in
                  if d >=? b
                  then raise (SInt_not_a_number "")
                  else d
                else assert False
              in
              let ch = str.[i] in
              let acc' = acc * b - digit ch in
              loop acc' (P.( + ) i 1)
          in
            if len = 0
            then `Empty
            else
            let maxlen = String.length maxstr in
            if len > maxlen
            then
              (* let () = dbgn "(from_base: len>maxlen) %!" in *)
              `Overflow
            else if len = maxlen && str > maxstr
            then
              (* let () = dbgn "(from_base: str>maxstr: %S > %S) %!"
                str maxstr
              in *)
              `Overflow
            else
              try
                `Ok (loop zero 0)
              with
              [ SInt_not_a_number _ -> `Not_a_number ]
        ;

        value from_dec_neg ~maxstr = from_base_neg ~maxstr ten
        ;

        value is_digit c = (c <= '9' && c >= '0')
        ;

        value is_not_digit c = not (is_digit c)
        ;

        value inan msg = throw_err (SInt_not_a_number msg)
        ;

        value peek_digit =
          peek >>= fun optc ->
          return (
            match optc with
            [ Some c when is_digit c -> optc
            | None | Some _ -> None
            ]
          )
        ;

        value read_gen
          ~allow0
          ~max_num_digits
          ~maxstr
          ~sign
         :
          iteratee char S.t
         =
          let rec read_beginning ~read0 =
            peek_digit >>= fun optd ->
            match optd with
            [ None ->
                if read0
                then return (Some zero)
                else inan "begins with not a digit"
            | Some d ->
                match (d, read0, allow0) with
                [ ('0', _, True)
                | ('0', False, False) ->
                  junk >>= fun () ->
                  read_beginning ~read0:True
                | (_, True, False) -> inan "leading zeroes"
                | (_, False, _) -> return None
                | (_, True, True) -> return None
                ]
            ]
          in
          read_beginning ~read0:False >>= fun
          [ Some r -> return r
          | None ->
               (limit max_num_digits &
                break_chars is_not_digit
               ) >>= fun it ->
               joinI (return it) >>= fun res ->
               peek_digit >>= fun optd ->
               match (it, res, optd) with
               [ (IE_done _, _, Some _) ->
                   assert False
                   (* limit should return IE_cont *)
               | (IE_cont (Some _) _, _, _) ->
                   assert False
                   (* joinI should raise this error *)
               | (IE_done str, _, None)
               | (IE_cont None _, str, None) ->
                   let () = assert
                     (String.length str <= max_num_digits) in
                   match from_dec_neg ~maxstr str with
                   [ `Not_a_number -> assert False
                   | `Empty -> assert False
                   | `Ok r -> return (r * (-sign))
                   | `Overflow -> throw_err SInt_overflow
                   ]

               | (IE_cont _ _, _, Some _) ->
                   (* let () = dbgn "(read_gen: cont/digit) %!" in *)
                   throw_err SInt_overflow
               ]
          ]
        ;

        value read_unsigned_gen ~allow0 =
          read_gen
            ~allow0
            ~max_num_digits:max_int_digits
            ~sign:one
            ~maxstr:max_int_dec_abs
        ;

        value read_negative_gen ~allow0 =
          read_gen
            ~allow0
            ~max_num_digits:min_int_digits
            ~sign:minus_one
            ~maxstr:min_int_dec_abs
        ;

        value read_signed_gen
          ~allow0
         :
          iteratee char S.t
         =
          peek >>= fun
          [ Some '-' -> junk >>= fun () -> read_negative_gen ~allow0
          | Some '+' -> junk >>= fun () -> read_unsigned_gen ~allow0
          | _ -> read_unsigned_gen ~allow0
          ]
        ;

      end
    ;

    module SInt = SInt_F(SInt_T)
    ;

    module SInt32 = SInt_F(SInt32_T)
    ;

    module SInt64 = SInt_F(SInt64_T)
    ;

    value read_uint_nz = SInt.read_unsigned_gen ~allow0:False;
    value read_uint = SInt.read_unsigned_gen ~allow0:True;
    value read_int_nz = SInt.read_signed_gen ~allow0:False;
    value read_int = SInt.read_signed_gen ~allow0:True;

    value read_uint32_nz = SInt32.read_unsigned_gen ~allow0:False;
    value read_uint32 = SInt32.read_unsigned_gen ~allow0:True;
    value read_int32_nz = SInt32.read_signed_gen ~allow0:False;
    value read_int32 = SInt32.read_signed_gen ~allow0:True;

    value read_uint64_nz = SInt64.read_unsigned_gen ~allow0:False;
    value read_uint64 = SInt64.read_unsigned_gen ~allow0:True;
    value read_int64_nz = SInt64.read_signed_gen ~allow0:False;
    value read_int64 = SInt64.read_signed_gen ~allow0:True;

  end
;

(* +
   Functions for reading decimal integers have names like
   [read_uint32_nz].  The pattern for functions' names is:

   read_[u]int{,32,64}[_nz]

   - Optional "u" means "read unsigned int", without '+' or '-' as
   the first char.
   - Type of the int to read is "int", "int32" or "int64".
   - "_nz" means "do not allow leading zeroes".  (note that "0" and "-0"
     does not have leading zeroes).

   The errors possible while reading ints are:
   - [SInt_overflow] when integer does not fit the range
   - [SInt_not_a_number (reason : string)] when the stream does not
     have the integer you need: for example, when there is EOF,
     not-a-digit char, any sign while you want to read unsigned integer,
     or leading zero while you want to read integer without leading zeroes.
*)
include Reading_ints
;



end
;  (* `Make' functor *)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.