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
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
This crate provides a regular expression parser and an abstract syntax for
regular expressions. The abstract syntax is defined by the `Expr` type. The
concrete syntax is enumerated in the
[`regex`](../regex/index.html#syntax)
crate documentation.

Note that since this crate is first and foremost an implementation detail for
the `regex` crate, it may experience more frequent breaking changes. It is
exposed as a separate crate so that others may use it to do analysis on regular
expressions or even build their own matching engine.

# Example: parsing an expression

Parsing a regular expression can be done with the `Expr::parse` function.

```rust
use regex_syntax::Expr;

assert_eq!(Expr::parse(r"ab|yz").unwrap(), Expr::Alternate(vec![
    Expr::Literal { chars: vec!['a', 'b'], casei: false },
    Expr::Literal { chars: vec!['y', 'z'], casei: false },
]));
```

# Example: inspecting an error

The parser in this crate provides very detailed error values. For example,
if an invalid character class range is given:

```rust
use regex_syntax::{Expr, ErrorKind};

let err = Expr::parse(r"[z-a]").unwrap_err();
assert_eq!(err.position(), 4);
assert_eq!(err.kind(), &ErrorKind::InvalidClassRange {
    start: 'z',
    end: 'a',
});
```

Or unbalanced parentheses:

```rust
use regex_syntax::{Expr, ErrorKind};

let err = Expr::parse(r"ab(cd").unwrap_err();
assert_eq!(err.position(), 2);
assert_eq!(err.kind(), &ErrorKind::UnclosedParen);
```
*/

#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]

#[cfg(test)] extern crate quickcheck;
#[cfg(test)] extern crate rand;

mod literals;
mod parser;
mod unicode;

use std::ascii;
use std::char;
use std::cmp::{Ordering, max, min};
use std::fmt;
use std::iter::IntoIterator;
use std::ops::Deref;
use std::result;
use std::slice;
use std::u8;
use std::vec;

use unicode::case_folding;

use self::Expr::*;
use self::Repeater::*;

use parser::{Flags, Parser};

pub use literals::{Literals, Lit};

/// A regular expression abstract syntax tree.
///
/// An `Expr` represents the abstract syntax of a regular expression.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Expr {
    /// An empty regex (which never matches any text).
    Empty,
    /// A sequence of one or more literal characters to be matched.
    Literal {
        /// The characters.
        chars: Vec<char>,
        /// Whether to match case insensitively.
        casei: bool,
    },
    /// A sequence of one or more literal bytes to be matched.
    LiteralBytes {
        /// The bytes.
        bytes: Vec<u8>,
        /// Whether to match case insensitively.
        ///
        /// The interpretation of "case insensitive" in this context is
        /// ambiguous since `bytes` can be arbitrary. However, a good heuristic
        /// is to assume that the bytes are ASCII-compatible and do simple
        /// ASCII case folding.
        casei: bool,
    },
    /// Match any character.
    AnyChar,
    /// Match any character, excluding new line (`0xA`).
    AnyCharNoNL,
    /// Match any byte.
    AnyByte,
    /// Match any byte, excluding new line (`0xA`).
    AnyByteNoNL,
    /// A character class.
    Class(CharClass),
    /// A character class with byte ranges only.
    ClassBytes(ByteClass),
    /// Match the start of a line or beginning of input.
    StartLine,
    /// Match the end of a line or end of input.
    EndLine,
    /// Match the beginning of input.
    StartText,
    /// Match the end of input.
    EndText,
    /// Match a word boundary (word character on one side and a non-word
    /// character on the other).
    WordBoundary,
    /// Match a position that is not a word boundary (word or non-word
    /// characters on both sides).
    NotWordBoundary,
    /// Match an ASCII word boundary.
    WordBoundaryAscii,
    /// Match a position that is not an ASCII word boundary.
    NotWordBoundaryAscii,
    /// A group, possibly non-capturing.
    Group {
        /// The expression inside the group.
        e: Box<Expr>,
        /// The capture index (starting at `1`) only for capturing groups.
        i: Option<usize>,
        /// The capture name, only for capturing named groups.
        name: Option<String>,
    },
    /// A repeat operator (`?`, `*`, `+` or `{m,n}`).
    Repeat {
        /// The expression to be repeated. Limited to literals, `.`, classes
        /// or grouped expressions.
        e: Box<Expr>,
        /// The type of repeat operator used.
        r: Repeater,
        /// Whether the repeat is greedy (match the most) or not (match the
        /// least).
        greedy: bool,
    },
    /// A concatenation of expressions. Must be matched one after the other.
    ///
    /// N.B. A concat expression can only appear at the top-level or
    /// immediately inside a group expression.
    Concat(Vec<Expr>),
    /// An alternation of expressions. Only one must match.
    ///
    /// N.B. An alternate expression can only appear at the top-level or
    /// immediately inside a group expression.
    Alternate(Vec<Expr>),
}

type CaptureIndex = Option<usize>;

type CaptureName = Option<String>;

/// The type of a repeat operator expression.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Repeater {
    /// Match zero or one (`?`).
    ZeroOrOne,
    /// Match zero or more (`*`).
    ZeroOrMore,
    /// Match one or more (`+`).
    OneOrMore,
    /// Match for at least `min` and at most `max` (`{m,n}`).
    ///
    /// When `max` is `None`, there is no upper bound on the number of matches.
    Range {
        /// Lower bound on the number of matches.
        min: u32,
        /// Optional upper bound on the number of matches.
        max: Option<u32>,
    },
}

impl Repeater {
    /// Returns true if and only if this repetition can match the empty string.
    fn matches_empty(&self) -> bool {
        use self::Repeater::*;
        match *self {
            ZeroOrOne => true,
            ZeroOrMore => true,
            OneOrMore => false,
            Range { min, .. } => min == 0,
        }
    }
}

/// A character class.
///
/// A character class has a canonical format that the parser guarantees. Its
/// canonical format is defined by the following invariants:
///
/// 1. Given any Unicode scalar value, it is matched by *at most* one character
///    range in a canonical character class.
/// 2. Every adjacent character range is separated by at least one Unicode
///    scalar value.
/// 3. Given any pair of character ranges `r1` and `r2`, if
///    `r1.end < r2.start`, then `r1` comes before `r2` in a canonical
///    character class.
///
/// In sum, any `CharClass` produced by this crate's parser is a sorted
/// sequence of non-overlapping ranges. This makes it possible to test whether
/// a character is matched by a class with a binary search.
///
/// If the case insensitive flag was set when parsing a character class, then
/// simple case folding is done automatically. For example, `(?i)[a-c]` is
/// automatically translated to `[a-cA-C]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CharClass {
    ranges: Vec<ClassRange>,
}

/// A single inclusive range in a character class.
///
/// Since range boundaries are defined by Unicode scalar values, the boundaries
/// can never be in the open interval `(0xD7FF, 0xE000)`. However, a range may
/// *cover* codepoints that are not scalar values.
///
/// Note that this has a few convenient impls on `PartialEq` and `PartialOrd`
/// for testing whether a character is contained inside a given range.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub struct ClassRange {
    /// The start character of the range.
    ///
    /// This must be less than or equal to `end`.
    pub start: char,

    /// The end character of the range.
    ///
    /// This must be greater than or equal to `start`.
    pub end: char,
}

/// A byte class for byte ranges only.
///
/// A byte class has a canonical format that the parser guarantees. Its
/// canonical format is defined by the following invariants:
///
/// 1. Given any byte, it is matched by *at most* one byte range in a canonical
///    character class.
/// 2. Every adjacent byte range is separated by at least one byte.
/// 3. Given any pair of byte ranges `r1` and `r2`, if
///    `r1.end < r2.start`, then `r1` comes before `r2` in a canonical
///    character class.
///
/// In sum, any `ByteClass` produced by this crate's parser is a sorted
/// sequence of non-overlapping ranges. This makes it possible to test whether
/// a byte is matched by a class with a binary search.
///
/// If the case insensitive flag was set when parsing a character class,
/// then simple ASCII-only case folding is done automatically. For example,
/// `(?i)[a-c]` is automatically translated to `[a-cA-C]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ByteClass {
    ranges: Vec<ByteRange>,
}

/// A single inclusive range in a byte class.
///
/// Note that this has a few convenient impls on `PartialEq` and `PartialOrd`
/// for testing whether a byte is contained inside a given range.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord)]
pub struct ByteRange {
    /// The start byte of the range.
    ///
    /// This must be less than or equal to `end`.
    pub start: u8,

    /// The end byte of the range.
    ///
    /// This must be greater than or equal to `end`.
    pub end: u8,
}

/// A builder for configuring regular expression parsing.
///
/// This allows setting the default values of flags and other options, such
/// as the maximum nesting depth.
#[derive(Clone, Debug)]
pub struct ExprBuilder {
    flags: Flags,
    nest_limit: usize,
}

impl ExprBuilder {
    /// Create a new builder for configuring expression parsing.
    ///
    /// Note that all flags are disabled by default.
    pub fn new() -> ExprBuilder {
        ExprBuilder {
            flags: Flags::default(),
            nest_limit: 200,
        }
    }

    /// Set the default value for the case insensitive (`i`) flag.
    pub fn case_insensitive(mut self, yes: bool) -> ExprBuilder {
        self.flags.casei = yes;
        self
    }

    /// Set the default value for the multi-line matching (`m`) flag.
    pub fn multi_line(mut self, yes: bool) -> ExprBuilder {
        self.flags.multi = yes;
        self
    }

    /// Set the default value for the any character (`s`) flag.
    pub fn dot_matches_new_line(mut self, yes: bool) -> ExprBuilder {
        self.flags.dotnl = yes;
        self
    }

    /// Set the default value for the greedy swap (`U`) flag.
    pub fn swap_greed(mut self, yes: bool) -> ExprBuilder {
        self.flags.swap_greed = yes;
        self
    }

    /// Set the default value for the ignore whitespace (`x`) flag.
    pub fn ignore_whitespace(mut self, yes: bool) -> ExprBuilder {
        self.flags.ignore_space = yes;
        self
    }

    /// Set the default value for the Unicode (`u`) flag.
    ///
    /// If `yes` is false, then `allow_bytes` is set to true.
    pub fn unicode(mut self, yes: bool) -> ExprBuilder {
        self.flags.unicode = yes;
        if !yes {
            self.allow_bytes(true)
        } else {
            self
        }
    }

    /// Whether the parser allows matching arbitrary bytes or not.
    ///
    /// When the `u` flag is disabled (either with this builder or in the
    /// expression itself), the parser switches to interpreting the expression
    /// as matching arbitrary bytes instead of Unicode codepoints. For example,
    /// the expression `(?u:\xFF)` matches the *codepoint* `\xFF`, which
    /// corresponds to the UTF-8 byte sequence `\xCE\xBF`. Conversely,
    /// `(?-u:\xFF)` matches the *byte* `\xFF`, which is not valid UTF-8.
    ///
    /// When `allow_bytes` is disabled (the default), an expression like
    /// `(?-u:\xFF)` will cause the parser to return an error, since it would
    /// otherwise match invalid UTF-8. When enabled, it will be allowed.
    pub fn allow_bytes(mut self, yes: bool) -> ExprBuilder {
        self.flags.allow_bytes = yes;
        self
    }

    /// Set the nesting limit for regular expression parsing.
    ///
    /// Regular expressions that nest more than this limit will result in a
    /// `StackExhausted` error.
    pub fn nest_limit(mut self, limit: usize) -> ExprBuilder {
        self.nest_limit = limit;
        self
    }

    /// Parse a string as a regular expression using the current configuraiton.
    pub fn parse(self, s: &str) -> Result<Expr> {
        Parser::parse(s, self.flags).and_then(|e| e.simplify(self.nest_limit))
    }
}

impl Expr {
    /// Parses a string in a regular expression syntax tree.
    ///
    /// This is a convenience method for parsing an expression using the
    /// default configuration. To tweak parsing options (such as which flags
    /// are enabled by default), use the `ExprBuilder` type.
    pub fn parse(s: &str) -> Result<Expr> {
        ExprBuilder::new().parse(s)
    }

    /// Returns true iff the expression can be repeated by a quantifier.
    fn can_repeat(&self) -> bool {
        match *self {
            Literal{..} | LiteralBytes{..}
            | AnyChar | AnyCharNoNL | AnyByte | AnyByteNoNL
            | Class(_) | ClassBytes(_)
            | StartLine | EndLine | StartText | EndText
            | WordBoundary | NotWordBoundary
            | WordBoundaryAscii | NotWordBoundaryAscii
            | Group{..}
            => true,
            _ => false,
        }
    }

    fn simplify(self, nest_limit: usize) -> Result<Expr> {
        fn combine_literals(es: &mut Vec<Expr>, e: Expr) {
            match (es.pop(), e) {
                (None, e) => es.push(e),
                (Some(Literal { chars: mut chars1, casei: casei1 }),
                      Literal { chars: chars2, casei: casei2 }) => {
                    if casei1 == casei2 {
                        chars1.extend(chars2);
                        es.push(Literal { chars: chars1, casei: casei1 });
                    } else {
                        es.push(Literal { chars: chars1, casei: casei1 });
                        es.push(Literal { chars: chars2, casei: casei2 });
                    }
                }
                (Some(LiteralBytes { bytes: mut bytes1, casei: casei1 }),
                      LiteralBytes { bytes: bytes2, casei: casei2 }) => {
                    if casei1 == casei2 {
                        bytes1.extend(bytes2);
                        es.push(LiteralBytes { bytes: bytes1, casei: casei1 });
                    } else {
                        es.push(LiteralBytes { bytes: bytes1, casei: casei1 });
                        es.push(LiteralBytes { bytes: bytes2, casei: casei2 });
                    }
                }
                (Some(e1), e2) => {
                    es.push(e1);
                    es.push(e2);
                }
            }
        }
        fn simp(expr: Expr, recurse: usize, limit: usize) -> Result<Expr> {
            if recurse > limit {
                return Err(Error {
                    pos: 0,
                    surround: "".to_owned(),
                    kind: ErrorKind::StackExhausted,
                });
            }
            let simplify = |e| simp(e, recurse + 1, limit);
            Ok(match expr {
                Repeat { e, r, greedy } => Repeat {
                    e: Box::new(try!(simplify(*e))),
                    r: r,
                    greedy: greedy,
                },
                Group { e, i, name } => {
                    let e = try!(simplify(*e));
                    if i.is_none() && name.is_none() && e.can_repeat() {
                        e
                    } else {
                        Group { e: Box::new(e), i: i, name: name }
                    }
                }
                Concat(es) => {
                    let mut new_es = Vec::with_capacity(es.len());
                    for e in es {
                        combine_literals(&mut new_es, try!(simplify(e)));
                    }
                    if new_es.len() == 1 {
                        new_es.pop().unwrap()
                    } else {
                        Concat(new_es)
                    }
                }
                Alternate(es) => {
                    let mut new_es = Vec::with_capacity(es.len());
                    for e in es {
                        new_es.push(try!(simplify(e)));
                    }
                    Alternate(new_es)
                }
                e => e,
            })
        }
        simp(self, 0, nest_limit)
    }

    /// Returns a set of literal prefixes extracted from this expression.
    pub fn prefixes(&self) -> Literals {
        let mut lits = Literals::empty();
        lits.union_prefixes(self);
        lits
    }

    /// Returns a set of literal suffixes extracted from this expression.
    pub fn suffixes(&self) -> Literals {
        let mut lits = Literals::empty();
        lits.union_suffixes(self);
        lits
    }

    /// Returns true if and only if the expression is required to match from
    /// the beginning of text.
    pub fn is_anchored_start(&self) -> bool {
        match *self {
            Repeat { ref e, r, .. } => {
                !r.matches_empty() && e.is_anchored_start()
            }
            Group { ref e, .. } => e.is_anchored_start(),
            Concat(ref es) => es[0].is_anchored_start(),
            Alternate(ref es) => es.iter().all(|e| e.is_anchored_start()),
            StartText => true,
            _ => false,
        }
    }

    /// Returns true if and only if the expression has at least one matchable
    /// sub-expression that must match the beginning of text.
    pub fn has_anchored_start(&self) -> bool {
        match *self {
            Repeat { ref e, r, .. } => {
                !r.matches_empty() && e.has_anchored_start()
            }
            Group { ref e, .. } => e.has_anchored_start(),
            Concat(ref es) => es[0].has_anchored_start(),
            Alternate(ref es) => es.iter().any(|e| e.has_anchored_start()),
            StartText => true,
            _ => false,
        }
    }

    /// Returns true if and only if the expression is required to match at the
    /// end of the text.
    pub fn is_anchored_end(&self) -> bool {
        match *self {
            Repeat { ref e, r, .. } => {
                !r.matches_empty() && e.is_anchored_end()
            }
            Group { ref e, .. } => e.is_anchored_end(),
            Concat(ref es) => es[es.len() - 1].is_anchored_end(),
            Alternate(ref es) => es.iter().all(|e| e.is_anchored_end()),
            EndText => true,
            _ => false,
        }
    }

    /// Returns true if and only if the expression has at least one matchable
    /// sub-expression that must match the beginning of text.
    pub fn has_anchored_end(&self) -> bool {
        match *self {
            Repeat { ref e, r, .. } => {
                !r.matches_empty() && e.has_anchored_end()
            }
            Group { ref e, .. } => e.has_anchored_end(),
            Concat(ref es) => es[es.len() - 1].has_anchored_end(),
            Alternate(ref es) => es.iter().any(|e| e.has_anchored_end()),
            EndText => true,
            _ => false,
        }
    }

    /// Returns true if and only if the expression contains sub-expressions
    /// that can match arbitrary bytes.
    pub fn has_bytes(&self) -> bool {
        match *self {
            Repeat { ref e, .. } => e.has_bytes(),
            Group { ref e, .. } => e.has_bytes(),
            Concat(ref es) => es.iter().any(|e| e.has_bytes()),
            Alternate(ref es) => es.iter().any(|e| e.has_bytes()),
            LiteralBytes{..} => true,
            AnyByte | AnyByteNoNL => true,
            ClassBytes(_) => true,
            WordBoundaryAscii | NotWordBoundaryAscii => true,
            _ => false,
        }
    }
}

impl Deref for CharClass {
    type Target = Vec<ClassRange>;
    fn deref(&self) -> &Vec<ClassRange> { &self.ranges }
}

impl IntoIterator for CharClass {
    type Item = ClassRange;
    type IntoIter = vec::IntoIter<ClassRange>;
    fn into_iter(self) -> vec::IntoIter<ClassRange> { self.ranges.into_iter() }
}

impl<'a> IntoIterator for &'a CharClass {
    type Item = &'a ClassRange;
    type IntoIter = slice::Iter<'a, ClassRange>;
    fn into_iter(self) -> slice::Iter<'a, ClassRange> { self.iter() }
}

impl CharClass {
    /// Create a new class from an existing set of ranges.
    pub fn new(ranges: Vec<ClassRange>) -> CharClass {
        CharClass { ranges: ranges }
    }

    /// Create an empty class.
    fn empty() -> CharClass {
        CharClass::new(Vec::new())
    }

    /// Returns true if `c` is matched by this character class.
    pub fn matches(&self, c: char) -> bool {
        self.binary_search_by(|range| c.partial_cmp(range).unwrap()).is_ok()
    }

    /// Removes the given character from the class if it exists.
    ///
    /// Note that this takes `O(n)` time in the number of ranges.
    pub fn remove(&mut self, c: char) {
        let mut i = match self.binary_search_by(|r| c.partial_cmp(r).unwrap()) {
            Ok(i) => i,
            Err(_) => return,
        };
        let mut r = self.ranges.remove(i);
        if r.start == c {
            r.start = inc_char(c);
            if r.start > r.end || c == char::MAX {
                return;
            }
            self.ranges.insert(i, r);
        } else if r.end == c {
            r.end = dec_char(c);
            if r.end < r.start || c == '\x00' {
                return;
            }
            self.ranges.insert(0, r);
        } else {
            let (mut r1, mut r2) = (r.clone(), r.clone());
            r1.end = dec_char(c);
            if r1.start <= r1.end {
                self.ranges.insert(i, r1);
                i += 1;
            }
            r2.start = inc_char(c);
            if r2.start <= r2.end {
                self.ranges.insert(i, r2);
            }
        }
    }

    /// Create a new empty class from this one.
    fn to_empty(&self) -> CharClass {
        CharClass { ranges: Vec::with_capacity(self.len()) }
    }

    /// Create a byte class from this character class.
    ///
    /// Codepoints above 0xFF are removed.
    fn to_byte_class(self) -> ByteClass {
        ByteClass::new(
            self.ranges.into_iter()
                       .filter_map(|r| r.to_byte_range())
                       .collect()).canonicalize()
    }

    /// Merge two classes and canonicalize them.
    #[cfg(test)]
    fn merge(mut self, other: CharClass) -> CharClass {
        self.ranges.extend(other);
        self.canonicalize()
    }

    /// Canonicalize any sequence of ranges.
    ///
    /// This is responsible for enforcing the canonical format invariants
    /// as described on the docs for the `CharClass` type.
    fn canonicalize(mut self) -> CharClass {
        // TODO: Save some cycles here by checking if already canonicalized.
        self.ranges.sort();
        let mut ordered = self.to_empty(); // TODO: Do this in place?
        for candidate in self {
            // If the candidate overlaps with an existing range, then it must
            // be the most recent range added because we process the candidates
            // in order.
            if let Some(or) = ordered.ranges.last_mut() {
                if or.overlapping(candidate) {
                    *or = or.merge(candidate);
                    continue;
                }
            }
            ordered.ranges.push(candidate);
        }
        ordered
    }

    /// Calculate the intersection of two canonical character classes.
    ///
    /// The returned intersection is canonical.
    fn intersection(&self, other: &CharClass) -> CharClass {
        if self.ranges.is_empty() || other.ranges.is_empty() {
            return CharClass::empty();
        }

        let mut intersection = CharClass::empty();

        let mut iter_a = self.ranges.iter();
        let mut iter_b = other.ranges.iter();
        let mut a = iter_a.next().unwrap();
        let mut b = iter_b.next().unwrap();
        loop {
            if let Some(i) = a.intersection(&b) {
                intersection.ranges.push(i);
            }

            // If the range with the smaller end didn't match this time,
            // it won't ever match, so move on to the next one.
            let (iter, item) = if a.end < b.end {
                (&mut iter_a, &mut a)
            } else {
                (&mut iter_b, &mut b)
            };
            match iter.next() {
                Some(v) => *item = v,
                None => break, // no more ranges to check, done
            }
        }

        intersection.canonicalize()
    }

    /// Negates the character class.
    ///
    /// For all `c` where `c` is a Unicode scalar value, `c` matches `self`
    /// if and only if `c` does not match `self.negate()`.
    pub fn negate(mut self) -> CharClass {
        fn range(s: char, e: char) -> ClassRange { ClassRange::new(s, e) }

        if self.is_empty() {
            // Inverting an empty range yields all of Unicode.
            return CharClass {
                ranges: vec![ClassRange { start: '\x00', end: '\u{10ffff}' }],
            };
        }
        self = self.canonicalize();
        let mut inv = self.to_empty();
        if self[0].start > '\x00' {
            inv.ranges.push(range('\x00', dec_char(self[0].start)));
        }
        for win in self.windows(2) {
            inv.ranges.push(range(inc_char(win[0].end),
                                  dec_char(win[1].start)));
        }
        if self[self.len() - 1].end < char::MAX {
            inv.ranges.push(range(inc_char(self[self.len() - 1].end),
                                  char::MAX));
        }
        inv
    }

    /// Apply case folding to this character class.
    ///
    /// N.B. Applying case folding to a negated character class probably
    /// won't produce the expected result. e.g., `(?i)[^x]` really should
    /// match any character sans `x` and `X`, but if `[^x]` is negated
    /// before being case folded, you'll end up matching any character.
    pub fn case_fold(self) -> CharClass {
        let mut folded = self.to_empty();
        for r in self {
            // Applying case folding to a range is expensive because *every*
            // character needs to be examined. Thus, we avoid that drudgery
            // if no character in the current range is in our case folding
            // table.
            if r.needs_case_folding() {
                folded.ranges.extend(r.case_fold());
            }
            folded.ranges.push(r);
        }
        folded.canonicalize()
    }

    /// Returns the number of characters that match this class.
    fn num_chars(&self) -> usize {
        self.ranges.iter()
            .map(|&r| 1 + (r.end as u32) - (r.start as u32))
            .fold(0, |acc, len| acc + len)
            as usize
    }
}

impl ClassRange {
    /// Create a new class range.
    ///
    /// If `end < start`, then the two values are swapped so that
    /// the invariant `start <= end` is preserved.
    fn new(start: char, end: char) -> ClassRange {
        if start <= end {
            ClassRange { start: start, end: end }
        } else {
            ClassRange { start: end, end: start }
        }
    }

    /// Translate this to a byte class.
    ///
    /// If the start codepoint exceeds 0xFF, then this returns `None`.
    ///
    /// If the end codepoint exceeds 0xFF, then it is set to 0xFF.
    fn to_byte_range(self) -> Option<ByteRange> {
        if self.start > '\u{FF}' {
            None
        } else {
            let s = self.start as u8;
            let e = min('\u{FF}', self.end) as u8;
            Some(ByteRange::new(s, e))
        }
    }

    /// Create a range of one character.
    fn one(c: char) -> ClassRange {
        ClassRange { start: c, end: c }
    }

    /// Returns true if and only if the two ranges are overlapping. Note that
    /// since ranges are inclusive, `a-c` and `d-f` are overlapping!
    fn overlapping(self, other: ClassRange) -> bool {
        max(self.start, other.start) <= inc_char(min(self.end, other.end))
    }

    /// Returns the intersection of the two ranges if they have common
    /// characters, `None` otherwise.
    fn intersection(&self, other: &ClassRange) -> Option<ClassRange> {
        let start = max(self.start, other.start);
        let end = min(self.end, other.end);
        if start <= end {
            Some(ClassRange::new(start, end))
        } else {
            None
        }
    }

    /// Creates a new range representing the union of `self` and `other.
    fn merge(self, other: ClassRange) -> ClassRange {
        ClassRange {
            start: min(self.start, other.start),
            end: max(self.end, other.end),
        }
    }

    /// Returns true if and only if this range contains a character that is
    /// in the case folding table.
    fn needs_case_folding(self) -> bool {
        case_folding::C_plus_S_both_table
        .binary_search_by(|&(c, _)| self.partial_cmp(&c).unwrap()).is_ok()
    }

    /// Apply case folding to this range.
    ///
    /// Since case folding might add characters such that the range is no
    /// longer contiguous, this returns multiple class ranges. They are in
    /// canonical order.
    fn case_fold(self) -> Vec<ClassRange> {
        let table = &case_folding::C_plus_S_both_table;
        let (s, e) = (self.start as u32, self.end as u32 + 1);
        let mut start = self.start;
        let mut end = start;
        let mut next_case_fold = '\x00';
        let mut ranges = Vec::with_capacity(10);
        for mut c in (s..e).filter_map(char::from_u32) {
            if c >= next_case_fold {
                c = match simple_case_fold_both_result(c) {
                    Ok(i) => {
                        for &(c1, c2) in &table[i..] {
                            if c1 != c {
                                break;
                            }
                            if c2 != inc_char(end) {
                                ranges.push(ClassRange::new(start, end));
                                start = c2;
                            }
                            end = c2;
                        }
                        continue;
                    }
                    Err(i) => {
                        if i < table.len() {
                            next_case_fold = table[i].0;
                        } else {
                            next_case_fold = '\u{10FFFF}';
                        }
                        c
                    }
                };
            }
            // The fast path. We know this character doesn't have an entry
            // in the case folding table.
            if c != inc_char(end) {
                ranges.push(ClassRange::new(start, end));
                start = c;
            }
            end = c;
        }
        ranges.push(ClassRange::new(start, end));
        ranges
    }
}

impl PartialEq<char> for ClassRange {
    #[inline]
    fn eq(&self, other: &char) -> bool {
        self.start <= *other && *other <= self.end
    }
}

impl PartialEq<ClassRange> for char {
    #[inline]
    fn eq(&self, other: &ClassRange) -> bool {
        other.eq(self)
    }
}

impl PartialOrd<char> for ClassRange {
    #[inline]
    fn partial_cmp(&self, other: &char) -> Option<Ordering> {
        Some(if self == other {
            Ordering::Equal
        } else if *other > self.end {
            Ordering::Greater
        } else {
            Ordering::Less
        })
    }
}

impl PartialOrd<ClassRange> for char {
    #[inline]
    fn partial_cmp(&self, other: &ClassRange) -> Option<Ordering> {
        other.partial_cmp(self).map(|o| o.reverse())
    }
}

impl ByteClass {
    /// Create a new class from an existing set of ranges.
    pub fn new(ranges: Vec<ByteRange>) -> ByteClass {
        ByteClass { ranges: ranges }
    }

    /// Returns true if `b` is matched by this byte class.
    pub fn matches(&self, b: u8) -> bool {
        self.binary_search_by(|range| b.partial_cmp(range).unwrap()).is_ok()
    }

    /// Removes the given byte from the class if it exists.
    ///
    /// Note that this takes `O(n)` time in the number of ranges.
    pub fn remove(&mut self, b: u8) {
        let mut i = match self.binary_search_by(|r| b.partial_cmp(r).unwrap()) {
            Ok(i) => i,
            Err(_) => return,
        };
        let mut r = self.ranges.remove(i);
        if r.start == b {
            r.start = b.saturating_add(1);
            if r.start > r.end || b == u8::MAX {
                return;
            }
            self.ranges.insert(i, r);
        } else if r.end == b {
            r.end = b.saturating_sub(1);
            if r.end < r.start || b == b'\x00' {
                return;
            }
            self.ranges.insert(0, r);
        } else {
            let (mut r1, mut r2) = (r.clone(), r.clone());
            r1.end = b.saturating_sub(1);
            if r1.start <= r1.end {
                self.ranges.insert(i, r1);
                i += 1;
            }
            r2.start = b.saturating_add(1);
            if r2.start <= r2.end {
                self.ranges.insert(i, r2);
            }
        }
    }

    /// Create a new empty class from this one.
    fn to_empty(&self) -> ByteClass {
        ByteClass { ranges: Vec::with_capacity(self.len()) }
    }

    /// Canonicalze any sequence of ranges.
    ///
    /// This is responsible for enforcing the canonical format invariants
    /// as described on the docs for the `ByteClass` type.
    fn canonicalize(mut self) -> ByteClass {
        // TODO: Save some cycles here by checking if already canonicalized.
        self.ranges.sort();
        let mut ordered = self.to_empty(); // TODO: Do this in place?
        for candidate in self {
            // If the candidate overlaps with an existing range, then it must
            // be the most recent range added because we process the candidates
            // in order.
            if let Some(or) = ordered.ranges.last_mut() {
                if or.overlapping(candidate) {
                    *or = or.merge(candidate);
                    continue;
                }
            }
            ordered.ranges.push(candidate);
        }
        ordered
    }

    /// Negates the byte class.
    ///
    /// For all `b` where `b` is a byte, `b` matches `self` if and only if `b`
    /// does not match `self.negate()`.
    pub fn negate(mut self) -> ByteClass {
        fn range(s: u8, e: u8) -> ByteRange { ByteRange::new(s, e) }

        if self.is_empty() {
            // Inverting an empty range yields all bytes.
            return ByteClass {
                ranges: vec![ByteRange { start: b'\x00', end: b'\xff' }],
            };
        }
        self = self.canonicalize();
        let mut inv = self.to_empty();
        if self[0].start > b'\x00' {
            inv.ranges.push(range(b'\x00', self[0].start.saturating_sub(1)));
        }
        for win in self.windows(2) {
            inv.ranges.push(range(win[0].end.saturating_add(1),
                                  win[1].start.saturating_sub(1)));
        }
        if self[self.len() - 1].end < u8::MAX {
            inv.ranges.push(range(self[self.len() - 1].end.saturating_add(1),
                                  u8::MAX));
        }
        inv
    }

    /// Apply case folding to this byte class.
    ///
    /// This assumes that the bytes in the ranges are ASCII compatible.
    ///
    /// N.B. Applying case folding to a negated character class probably
    /// won't produce the expected result. e.g., `(?i)[^x]` really should
    /// match any character sans `x` and `X`, but if `[^x]` is negated
    /// before being case folded, you'll end up matching any character.
    pub fn case_fold(self) -> ByteClass {
        let mut folded = self.to_empty();
        for r in self {
            folded.ranges.extend(r.case_fold());
        }
        folded.canonicalize()
    }

    /// Returns the number of bytes that match this class.
    fn num_bytes(&self) -> usize {
        self.ranges.iter()
            .map(|&r| 1 + (r.end as u32) - (r.start as u32))
            .fold(0, |acc, len| acc + len)
            as usize
    }
}

impl ByteRange {
    /// Create a new class range.
    ///
    /// If `end < start`, then the two values are swapped so that
    /// the invariant `start <= end` is preserved.
    fn new(start: u8, end: u8) -> ByteRange {
        if start <= end {
            ByteRange { start: start, end: end }
        } else {
            ByteRange { start: end, end: start }
        }
    }

    /// Returns true if and only if the two ranges are overlapping. Note that
    /// since ranges are inclusive, `a-c` and `d-f` are overlapping!
    fn overlapping(self, other: ByteRange) -> bool {
        max(self.start, other.start)
        <= min(self.end, other.end).saturating_add(1)
    }

    /// Returns true if and only if the intersection of self and other is non
    /// empty.
    fn is_intersect_empty(self, other: ByteRange) -> bool {
        max(self.start, other.start) > min(self.end, other.end)
    }

    /// Creates a new range representing the union of `self` and `other.
    fn merge(self, other: ByteRange) -> ByteRange {
        ByteRange {
            start: min(self.start, other.start),
            end: max(self.end, other.end),
        }
    }

    /// Apply case folding to this range.
    ///
    /// Since case folding might add bytes such that the range is no
    /// longer contiguous, this returns multiple byte ranges.
    ///
    /// This assumes that the bytes in this range are ASCII compatible.
    fn case_fold(self) -> Vec<ByteRange> {
        // So much easier than Unicode case folding!
        let mut ranges = vec![self];
        if !ByteRange::new(b'a', b'z').is_intersect_empty(self) {
            let lower = max(self.start, b'a');
            let upper = min(self.end, b'z');
            ranges.push(ByteRange::new(lower - 32, upper - 32));
        }
        if !ByteRange::new(b'A', b'Z').is_intersect_empty(self) {
            let lower = max(self.start, b'A');
            let upper = min(self.end, b'Z');
            ranges.push(ByteRange::new(lower + 32, upper + 32));
        }
        ranges
    }
}

impl Deref for ByteClass {
    type Target = Vec<ByteRange>;
    fn deref(&self) -> &Vec<ByteRange> { &self.ranges }
}

impl IntoIterator for ByteClass {
    type Item = ByteRange;
    type IntoIter = vec::IntoIter<ByteRange>;
    fn into_iter(self) -> vec::IntoIter<ByteRange> { self.ranges.into_iter() }
}

impl<'a> IntoIterator for &'a ByteClass {
    type Item = &'a ByteRange;
    type IntoIter = slice::Iter<'a, ByteRange>;
    fn into_iter(self) -> slice::Iter<'a, ByteRange> { self.iter() }
}

impl PartialEq<u8> for ByteRange {
    #[inline]
    fn eq(&self, other: &u8) -> bool {
        self.start <= *other && *other <= self.end
    }
}

impl PartialEq<ByteRange> for u8 {
    #[inline]
    fn eq(&self, other: &ByteRange) -> bool {
        other.eq(self)
    }
}

impl PartialOrd<u8> for ByteRange {
    #[inline]
    fn partial_cmp(&self, other: &u8) -> Option<Ordering> {
        Some(if self == other {
            Ordering::Equal
        } else if *other > self.end {
            Ordering::Greater
        } else {
            Ordering::Less
        })
    }
}

impl PartialOrd<ByteRange> for u8 {
    #[inline]
    fn partial_cmp(&self, other: &ByteRange) -> Option<Ordering> {
        other.partial_cmp(self).map(|o| o.reverse())
    }
}

/// This implementation of `Display` will write a regular expression from the
/// syntax tree. It does not write the original string parsed.
impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Empty => write!(f, ""),
            Literal { ref chars, casei } => {
                if casei {
                    try!(write!(f, "(?iu:"));
                } else {
                    try!(write!(f, "(?u:"));
                }
                for &c in chars {
                    try!(write!(f, "{}", quote_char(c)));
                }
                try!(write!(f, ")"));
                Ok(())
            }
            LiteralBytes { ref bytes, casei } => {
                if casei {
                    try!(write!(f, "(?i-u:"));
                } else {
                    try!(write!(f, "(?-u:"));
                }
                for &b in bytes {
                    try!(write!(f, "{}", quote_byte(b)));
                }
                try!(write!(f, ")"));
                Ok(())
            }
            AnyChar => write!(f, "(?su:.)"),
            AnyCharNoNL => write!(f, "(?u:.)"),
            AnyByte => write!(f, "(?s-u:.)"),
            AnyByteNoNL => write!(f, "(?-u:.)"),
            Class(ref cls) => write!(f, "{}", cls),
            ClassBytes(ref cls) => write!(f, "{}", cls),
            StartLine => write!(f, "(?m:^)"),
            EndLine => write!(f, "(?m:$)"),
            StartText => write!(f, r"^"),
            EndText => write!(f, r"$"),
            WordBoundary => write!(f, r"(?u:\b)"),
            NotWordBoundary => write!(f, r"(?u:\B)"),
            WordBoundaryAscii => write!(f, r"(?-u:\b)"),
            NotWordBoundaryAscii => write!(f, r"(?-u:\B)"),
            Group { ref e, i: None, name: None } => write!(f, "(?:{})", e),
            Group { ref e, name: None, .. } => write!(f, "({})", e),
            Group { ref e, name: Some(ref n), .. } => {
                write!(f, "(?P<{}>{})", n, e)
            }
            Repeat { ref e, r, greedy } => {
                match &**e {
                    &Literal { ref chars, .. } if chars.len() > 1 => {
                        try!(write!(f, "(?:{}){}", e, r))
                    }
                    _ => try!(write!(f, "{}{}", e, r)),
                }
                if !greedy { try!(write!(f, "?")); }
                Ok(())
            }
            Concat(ref es) => {
                for e in es {
                    try!(write!(f, "{}", e));
                }
                Ok(())
            }
            Alternate(ref es) => {
                for (i, e) in es.iter().enumerate() {
                    if i > 0 { try!(write!(f, "|")); }
                    try!(write!(f, "{}", e));
                }
                Ok(())
            }
        }
    }
}

impl fmt::Display for Repeater {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ZeroOrOne => write!(f, "?"),
            ZeroOrMore => write!(f, "*"),
            OneOrMore => write!(f, "+"),
            Range { min: s, max: None } => write!(f, "{{{},}}", s),
            Range { min: s, max: Some(e) } if s == e => write!(f, "{{{}}}", s),
            Range { min: s, max: Some(e) } => write!(f, "{{{}, {}}}", s, e),
        }
    }
}

impl fmt::Display for CharClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "(?u:["));
        for range in self.iter() {
            if range.start == '-' || range.end == '-' {
                try!(write!(f, "-"));
                break;
            }
        }
        for range in self.iter() {
            let mut range = *range;
            if range.start == '-' {
                range.start = ((range.start as u8) + 1) as char;
            }
            if range.end == '-' {
                range.end = ((range.end as u8) - 1) as char;
            }
            if range.start > range.end {
                continue;
            }
            try!(write!(f, "{}", range));
        }
        try!(write!(f, "])"));
        Ok(())
    }
}

impl fmt::Display for ClassRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}-{}", quote_char(self.start), quote_char(self.end))
    }
}

impl fmt::Display for ByteClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "(?-u:["));
        for range in self.iter() {
            if range.start == b'-' || range.end == b'-' {
                try!(write!(f, "-"));
                break;
            }
        }
        for range in self.iter() {
            let mut range = *range;
            if range.start == b'-' {
                range.start += 1;
            }
            if range.end == b'-' {
                range.start -= 1;
            }
            if range.start > range.end {
                continue;
            }
            try!(write!(f, "{}", range));
        }
        try!(write!(f, "])"));
        Ok(())
    }
}

impl fmt::Display for ByteRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}-{}", quote_byte(self.start), quote_byte(self.end))
    }
}

/// An alias for computations that can return a `Error`.
pub type Result<T> = ::std::result::Result<T, Error>;

/// A parse error.
///
/// This includes details about the specific type of error and a rough
/// approximation of where it occurred.
#[derive(Clone, Debug, PartialEq)]
pub struct Error {
    pos: usize,
    surround: String,
    kind: ErrorKind,
}

/// The specific type of parse error that can occur.
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorKind {
    /// A negation symbol is used twice in flag settings.
    /// e.g., `(?-i-s)`.
    DoubleFlagNegation,
    /// The same capture name was used more than once.
    /// e.g., `(?P<a>.)(?P<a>.)`.
    DuplicateCaptureName(String),
    /// An alternate is empty. e.g., `(|a)`.
    EmptyAlternate,
    /// A capture group name is empty. e.g., `(?P<>a)`.
    EmptyCaptureName,
    /// A negation symbol was not proceded by any flags. e.g., `(?i-)`.
    EmptyFlagNegation,
    /// A group is empty. e.g., `()`.
    EmptyGroup,
    /// An invalid number was used in a counted repetition. e.g., `a{b}`.
    InvalidBase10(String),
    /// An invalid hexadecimal number was used in an escape sequence.
    /// e.g., `\xAG`.
    InvalidBase16(String),
    /// An invalid capture name was used. e.g., `(?P<0a>b)`.
    InvalidCaptureName(String),
    /// An invalid class range was givien. Specifically, when the start of the
    /// range is greater than the end. e.g., `[z-a]`.
    InvalidClassRange {
        /// The first character specified in the range.
        start: char,
        /// The second character specified in the range.
        end: char,
    },
    /// An escape sequence was used in a character class where it is not
    /// allowed. e.g., `[a-\pN]` or `[\A]`.
    InvalidClassEscape(Expr),
    /// An invalid counted repetition min/max was given. e.g., `a{2,1}`.
    InvalidRepeatRange {
        /// The first number specified in the repetition.
        min: u32,
        /// The second number specified in the repetition.
        max: u32,
    },
    /// An invalid Unicode scalar value was used in a long hexadecimal
    /// sequence. e.g., `\x{D800}`.
    InvalidScalarValue(u32),
    /// An empty counted repetition operator. e.g., `a{}`.
    MissingBase10,
    /// A repetition operator was not applied to an expression. e.g., `*`.
    RepeaterExpectsExpr,
    /// A repetition operator was applied to an expression that cannot be
    /// repeated. e.g., `a+*` or `a|*`.
    RepeaterUnexpectedExpr(Expr),
    /// A capture group name that is never closed. e.g., `(?P<a`.
    UnclosedCaptureName(String),
    /// An unclosed hexadecimal literal. e.g., `\x{a`.
    UnclosedHex,
    /// An unclosed parenthesis. e.g., `(a`.
    UnclosedParen,
    /// An unclosed counted repetition operator. e.g., `a{2`.
    UnclosedRepeat,
    /// An unclosed named Unicode class. e.g., `\p{Yi`.
    UnclosedUnicodeName,
    /// Saw end of regex before class was closed. e.g., `[a`.
    UnexpectedClassEof,
    /// Saw end of regex before escape sequence was closed. e.g., `\`.
    UnexpectedEscapeEof,
    /// Saw end of regex before flags were closed. e.g., `(?i`.
    UnexpectedFlagEof,
    /// Saw end of regex before two hexadecimal digits were seen. e.g., `\xA`.
    UnexpectedTwoDigitHexEof,
    /// Unopened parenthesis. e.g., `)`.
    UnopenedParen,
    /// Unrecognized escape sequence. e.g., `\q`.
    UnrecognizedEscape(char),
    /// Unrecognized flag. e.g., `(?a)`.
    UnrecognizedFlag(char),
    /// Unrecognized named Unicode class. e.g., `\p{Foo}`.
    UnrecognizedUnicodeClass(String),
    /// Indicates that the regex uses too much nesting.
    ///
    /// (N.B. This error exists because traversing the Expr is recursive and
    /// an explicit heap allocated stack is not (yet?) used. Regardless, some
    /// sort of limit must be applied to avoid unbounded memory growth.
    StackExhausted,
    /// A disallowed flag was found (e.g., `u`).
    FlagNotAllowed(char),
    /// A Unicode class was used when the Unicode (`u`) flag was disabled.
    UnicodeNotAllowed,
    /// InvalidUtf8 indicates that the expression may match non-UTF-8 bytes.
    /// This never returned if the parser is permitted to allow expressions
    /// that match arbitrary bytes.
    InvalidUtf8,
    /// A character class was constructed such that it is empty.
    /// e.g., `[^\d\D]`.
    EmptyClass,
    /// Indicates that unsupported notation was used in a character class.
    ///
    /// The char in this error corresponds to the illegal character.
    ///
    /// The intent of this error is to carve a path to support set notation
    /// as described in UTS#18 RL1.3. We do this by rejecting regexes that
    /// would use the notation.
    ///
    /// The work around for end users is to escape the character included in
    /// this error message.
    UnsupportedClassChar(char),
    /// Hints that destructuring should not be exhaustive.
    ///
    /// This enum may grow additional variants, so this makes sure clients
    /// don't count on exhaustive matching. (Otherwise, adding a new variant
    /// could break existing code.)
    #[doc(hidden)]
    __Nonexhaustive,
}

impl Error {
    /// Returns an approximate *character* offset at which the error occurred.
    ///
    /// The character offset may be equal to the number of characters in the
    /// string, in which case it should be interpreted as pointing to the end
    /// of the regex.
    pub fn position(&self) -> usize {
        self.pos
    }

    /// Returns the type of the regex parse error.
    pub fn kind(&self) -> &ErrorKind {
        &self.kind
    }
}

impl ErrorKind {
    fn description(&self) -> &str {
        use ErrorKind::*;
        match *self {
            DoubleFlagNegation => "double flag negation",
            DuplicateCaptureName(_) => "duplicate capture name",
            EmptyAlternate => "empty alternate",
            EmptyCaptureName => "empty capture name",
            EmptyFlagNegation => "flag negation without any flags",
            EmptyGroup => "empty group (e.g., '()')",
            InvalidBase10(_) => "invalid base 10 number",
            InvalidBase16(_) => "invalid base 16 number",
            InvalidCaptureName(_) => "invalid capture name",
            InvalidClassRange{..} => "invalid character class range",
            InvalidClassEscape(_) => "invalid escape sequence in class",
            InvalidRepeatRange{..} => "invalid counted repetition range",
            InvalidScalarValue(_) => "invalid Unicode scalar value",
            MissingBase10 => "missing count in repetition operator",
            RepeaterExpectsExpr => "repetition operator missing expression",
            RepeaterUnexpectedExpr(_) => "expression cannot be repeated",
            UnclosedCaptureName(_) => "unclosed capture group name",
            UnclosedHex => "unclosed hexadecimal literal",
            UnclosedParen => "unclosed parenthesis",
            UnclosedRepeat => "unclosed counted repetition operator",
            UnclosedUnicodeName => "unclosed Unicode class literal",
            UnexpectedClassEof => "unexpected EOF in character class",
            UnexpectedEscapeEof => "unexpected EOF in escape sequence",
            UnexpectedFlagEof => "unexpected EOF in flags",
            UnexpectedTwoDigitHexEof => "unexpected EOF in hex literal",
            UnopenedParen => "unopened parenthesis",
            UnrecognizedEscape(_) => "unrecognized escape sequence",
            UnrecognizedFlag(_) => "unrecognized flag",
            UnrecognizedUnicodeClass(_) => "unrecognized Unicode class name",
            StackExhausted => "stack exhausted, too much nesting",
            FlagNotAllowed(_) => "flag not allowed",
            UnicodeNotAllowed => "Unicode features not allowed",
            InvalidUtf8 => "matching arbitrary bytes is not allowed",
            EmptyClass => "empty character class",
            UnsupportedClassChar(_) => "unsupported class notation",
            __Nonexhaustive => unreachable!(),
        }
    }
}

impl ::std::error::Error for Error {
    fn description(&self) -> &str {
        self.kind.description()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let ErrorKind::StackExhausted = self.kind {
            write!(f, "Error parsing regex: {}", self.kind)
        } else {
            write!(
                f, "Error parsing regex near '{}' at character offset {}: {}",
                self.surround, self.pos, self.kind)
        }
    }
}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ErrorKind::*;
        match *self {
            DoubleFlagNegation =>
                write!(f, "Only one negation symbol is allowed in flags."),
            DuplicateCaptureName(ref s) =>
                write!(f, "Capture name '{}' is used more than once.", s),
            EmptyAlternate =>
                write!(f, "Alternations cannot be empty."),
            EmptyCaptureName =>
                write!(f, "Capture names cannot be empty."),
            EmptyFlagNegation =>
                write!(f, "Flag negation requires setting at least one flag."),
            EmptyGroup =>
                write!(f, "Empty regex groups (e.g., '()') are not allowed."),
            InvalidBase10(ref s) =>
                write!(f, "Not a valid base 10 number: '{}'", s),
            InvalidBase16(ref s) =>
                write!(f, "Not a valid base 16 number: '{}'", s),
            InvalidCaptureName(ref s) =>
                write!(f, "Invalid capture name: '{}'. Capture names must \
                           consist of [_a-zA-Z0-9] and are not allowed to \
                           start with with a number.", s),
            InvalidClassRange { start, end } =>
                write!(f, "Invalid character class range '{}-{}'. \
                           Character class ranges must start with the smaller \
                           character, but {} > {}", start, end, start, end),
            InvalidClassEscape(_) =>
                write!(f, "Invalid escape sequence in character class."),
            InvalidRepeatRange { min, max } =>
                write!(f, "Invalid counted repetition range: {{{}, {}}}. \
                           Counted repetition ranges must start with the \
                           minimum, but {} > {}", min, max, min, max),
            InvalidScalarValue(c) =>
                write!(f, "Number does not correspond to a Unicode scalar \
                           value: '{}'.", c),
            MissingBase10 =>
                write!(f, "Missing maximum in counted repetition operator."),
            RepeaterExpectsExpr =>
                write!(f, "Missing expression for repetition operator."),
            RepeaterUnexpectedExpr(_) =>
                write!(f, "Invalid application of repetition operator."),
            UnclosedCaptureName(ref s) =>
                write!(f, "Capture name group for '{}' is not closed. \
                           (Missing a '>'.)", s),
            UnclosedHex =>
                write!(f, "Unclosed hexadecimal literal (missing a '}}')."),
            UnclosedParen =>
                write!(f, "Unclosed parenthesis."),
            UnclosedRepeat =>
                write!(f, "Unclosed counted repetition (missing a '}}')."),
            UnclosedUnicodeName =>
                write!(f, "Unclosed Unicode literal (missing a '}}')."),
            UnexpectedClassEof =>
                write!(f, "Character class was not closed before the end of \
                           the regex (missing a ']')."),
            UnexpectedEscapeEof =>
                write!(f, "Started an escape sequence that didn't finish \
                           before the end of the regex."),
            UnexpectedFlagEof =>
                write!(f, "Inline flag settings was not closed before the end \
                           of the regex (missing a ')' or ':')."),
            UnexpectedTwoDigitHexEof =>
                write!(f, "Unexpected end of two digit hexadecimal literal."),
            UnopenedParen =>
                write!(f, "Unopened parenthesis."),
            UnrecognizedEscape(c) =>
                write!(f, "Unrecognized escape sequence: '\\{}'.", c),
            UnrecognizedFlag(c) =>
                write!(f, "Unrecognized flag: '{}'. \
                           (Allowed flags: i, m, s, U, u, x.)", c),
            UnrecognizedUnicodeClass(ref s) =>
                write!(f, "Unrecognized Unicode class name: '{}'.", s),
            StackExhausted =>
                write!(f, "Exhausted space required to parse regex with too \
                           much nesting."),
            FlagNotAllowed(flag) =>
                write!(f, "Use of the flag '{}' is not allowed.", flag),
            UnicodeNotAllowed =>
                write!(f, "Unicode features are not allowed when the Unicode \
                           (u) flag is not set."),
            InvalidUtf8 =>
                write!(f, "Matching arbitrary bytes is not allowed."),
            EmptyClass =>
                write!(f, "Empty character classes are not allowed."),
            UnsupportedClassChar(c) =>
                write!(f, "Use of unescaped '{}' in character class is \
                           not allowed.", c),
            __Nonexhaustive => unreachable!(),
        }
    }
}

/// The result of binary search on the simple case folding table.
///
/// Note that this binary search is done on the "both" table, such that
/// the index returned corresponds to the *first* location of `c1` in the
/// table. The table can then be scanned linearly starting from the position
/// returned to find other case mappings for `c1`.
fn simple_case_fold_both_result(c1: char) -> result::Result<usize, usize> {
    let table = &case_folding::C_plus_S_both_table;
    let i = binary_search(table, |&(c2, _)| c1 <= c2);
    if i >= table.len() || table[i].0 != c1 {
        Err(i)
    } else {
        Ok(i)
    }
}

/// Binary search to find first element such that `pred(T) == true`.
///
/// Assumes that if `pred(xs[i]) == true` then `pred(xs[i+1]) == true`.
///
/// If all elements yield `pred(T) == false`, then `xs.len()` is returned.
fn binary_search<T, F>(xs: &[T], mut pred: F) -> usize
        where F: FnMut(&T) -> bool {
    let (mut left, mut right) = (0, xs.len());
    while left < right {
        let mid = (left + right) / 2;
        if pred(&xs[mid]) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    left
}

/// Escapes all regular expression meta characters in `text`.
///
/// The string returned may be safely used as a literal in a regular
/// expression.
pub fn escape(text: &str) -> String {
    let mut quoted = String::with_capacity(text.len());
    for c in text.chars() {
        if parser::is_punct(c) {
            quoted.push('\\');
        }
        quoted.push(c);
    }
    quoted
}

fn quote_char(c: char) -> String {
    let mut s = String::new();
    if parser::is_punct(c) {
        s.push('\\');
    }
    s.push(c);
    s
}

fn quote_byte(b: u8) -> String {
    if parser::is_punct(b as char) || b == b'\'' || b == b'"' {
        quote_char(b as char)
    } else {
        let escaped: Vec<u8> = ascii::escape_default(b).collect();
        String::from_utf8(escaped).unwrap()
    }
}

fn inc_char(c: char) -> char {
    match c {
        char::MAX => char::MAX,
        '\u{D7FF}' => '\u{E000}',
        c => char::from_u32(c as u32 + 1).unwrap(),
    }
}

fn dec_char(c: char) -> char {
    match c {
        '\x00' => '\x00',
        '\u{E000}' => '\u{D7FF}',
        c => char::from_u32(c as u32 - 1).unwrap(),
    }
}

/// Returns true if and only if `c` is a word character.
#[doc(hidden)]
pub fn is_word_char(c: char) -> bool {
    match c {
        '_' | '0' ... '9' | 'a' ... 'z' | 'A' ... 'Z'  => true,
        _ => ::unicode::regex::PERLW.binary_search_by(|&(start, end)| {
            if c >= start && c <= end {
                Ordering::Equal
            } else if start > c {
                Ordering::Greater
            } else {
                Ordering::Less
            }
        }).is_ok(),
    }
}

/// Returns true if and only if `c` is an ASCII word byte.
#[doc(hidden)]
pub fn is_word_byte(b: u8) -> bool {
    match b {
        b'_' | b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z'  => true,
        _ => false,
    }
}

#[cfg(test)]
mod properties;

#[cfg(test)]
mod tests {
    use {CharClass, ClassRange, ByteClass, ByteRange, Expr};

    fn class(ranges: &[(char, char)]) -> CharClass {
        let ranges = ranges.iter().cloned()
                           .map(|(c1, c2)| ClassRange::new(c1, c2)).collect();
        CharClass::new(ranges)
    }

    fn bclass(ranges: &[(u8, u8)]) -> ByteClass {
        let ranges = ranges.iter().cloned()
                           .map(|(c1, c2)| ByteRange::new(c1, c2)).collect();
        ByteClass::new(ranges)
    }

    fn e(re: &str) -> Expr { Expr::parse(re).unwrap() }

    #[test]
    fn stack_exhaustion() {
        use std::iter::repeat;

        let open: String = repeat('(').take(200).collect();
        let close: String = repeat(')').take(200).collect();
        assert!(Expr::parse(&format!("{}a{}", open, close)).is_ok());

        let open: String = repeat('(').take(200 + 1).collect();
        let close: String = repeat(')').take(200 + 1).collect();
        assert!(Expr::parse(&format!("{}a{}", open, close)).is_err());
    }

    #[test]
    fn anchored_start() {
        assert!(e("^a").is_anchored_start());
        assert!(e("(^a)").is_anchored_start());
        assert!(e("^a|^b").is_anchored_start());
        assert!(e("(^a)|(^b)").is_anchored_start());
        assert!(e("(^(a|b))").is_anchored_start());

        assert!(!e("^a|b").is_anchored_start());
        assert!(!e("a|^b").is_anchored_start());
    }

    #[test]
    fn anchored_end() {
        assert!(e("a$").is_anchored_end());
        assert!(e("(a$)").is_anchored_end());
        assert!(e("a$|b$").is_anchored_end());
        assert!(e("(a$)|(b$)").is_anchored_end());
        assert!(e("((a|b)$)").is_anchored_end());

        assert!(!e("a$|b").is_anchored_end());
        assert!(!e("a|b$").is_anchored_end());
    }

    #[test]
    fn class_canon_no_change() {
        let cls = class(&[('a', 'c'), ('x', 'z')]);
        assert_eq!(cls.clone().canonicalize(), cls);
    }

    #[test]
    fn class_canon_unordered() {
        let cls = class(&[('x', 'z'), ('a', 'c')]);
        assert_eq!(cls.canonicalize(), class(&[
            ('a', 'c'), ('x', 'z'),
        ]));
    }

    #[test]
    fn class_canon_overlap() {
        let cls = class(&[('x', 'z'), ('w', 'y')]);
        assert_eq!(cls.canonicalize(), class(&[
            ('w', 'z'),
        ]));
    }

    #[test]
    fn class_canon_overlap_many() {
        let cls = class(&[
            ('c', 'f'), ('a', 'g'), ('d', 'j'), ('a', 'c'),
            ('m', 'p'), ('l', 's'),
        ]);
        assert_eq!(cls.clone().canonicalize(), class(&[
            ('a', 'j'), ('l', 's'),
        ]));
    }

    #[test]
    fn class_canon_overlap_boundary() {
        let cls = class(&[('x', 'z'), ('u', 'w')]);
        assert_eq!(cls.canonicalize(), class(&[
            ('u', 'z'),
        ]));
    }

    #[test]
    fn class_canon_extreme_edge_case() {
        let cls = class(&[('\x00', '\u{10FFFF}'), ('\x00', '\u{10FFFF}')]);
        assert_eq!(cls.canonicalize(), class(&[
            ('\x00', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_canon_singles() {
        let cls = class(&[('a', 'a'), ('b', 'b')]);
        assert_eq!(cls.canonicalize(), class(&[('a', 'b')]));
    }

    #[test]
    fn class_negate_single() {
        let cls = class(&[('a', 'a')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\x60'), ('\x62', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_singles() {
        let cls = class(&[('a', 'a'), ('b', 'b')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\x60'), ('\x63', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_multiples() {
        let cls = class(&[('a', 'c'), ('x', 'z')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\x60'), ('\x64', '\x77'), ('\x7b', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_min_scalar() {
        let cls = class(&[('\x00', 'a')]);
        assert_eq!(cls.negate(), class(&[
            ('\x62', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_max_scalar() {
        let cls = class(&[('a', '\u{10FFFF}')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\x60'),
        ]));
    }

    #[test]
    fn class_negate_everything() {
        let cls = class(&[('\x00', '\u{10FFFF}')]);
        assert_eq!(cls.negate(), class(&[]));
    }

    #[test]
    fn class_negate_everything_sans_one() {
        let cls = class(&[
            ('\x00', '\u{10FFFD}'), ('\u{10FFFF}', '\u{10FFFF}')
        ]);
        assert_eq!(cls.negate(), class(&[
            ('\u{10FFFE}', '\u{10FFFE}'),
        ]));
    }

    #[test]
    fn class_negate_surrogates_min() {
        let cls = class(&[('\x00', '\u{D7FF}')]);
        assert_eq!(cls.negate(), class(&[
            ('\u{E000}', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_surrogates_min_edge() {
        let cls = class(&[('\x00', '\u{D7FE}')]);
        assert_eq!(cls.negate(), class(&[
            ('\u{D7FF}', '\u{10FFFF}'),
        ]));
    }

    #[test]
    fn class_negate_surrogates_max() {
        let cls = class(&[('\u{E000}', '\u{10FFFF}')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\u{D7FF}'),
        ]));
    }

    #[test]
    fn class_negate_surrogates_max_edge() {
        let cls = class(&[('\u{E001}', '\u{10FFFF}')]);
        assert_eq!(cls.negate(), class(&[
            ('\x00', '\u{E000}'),
        ]));
    }

    #[test]
    fn class_intersection_empty() {
        let cls1 = class(&[]);
        let cls2 = class(&[('a', 'a')]);
        assert_intersection(cls1, cls2, class(&[]));
    }

    #[test]
    fn class_intersection_single_equal() {
        let cls1 = class(&[('a', 'a')]);
        let cls2 = class(&[('a', 'a')]);
        assert_intersection(cls1, cls2, class(&[('a', 'a')]));
    }

    #[test]
    fn class_intersection_single_unequal() {
        let cls1 = class(&[('a', 'a')]);
        let cls2 = class(&[('b', 'b')]);
        assert_intersection(cls1, cls2, class(&[]));
    }

    #[test]
    fn class_intersection_single_in_other() {
        let cls1 = class(&[('a', 'a')]);
        let cls2 = class(&[('a', 'c')]);
        assert_intersection(cls1, cls2, class(&[('a', 'a')]));
    }

    #[test]
    fn class_intersection_range_in_other() {
        let cls1 = class(&[('a', 'b')]);
        let cls2 = class(&[('a', 'c')]);
        assert_intersection(cls1, cls2, class(&[('a', 'b')]));
    }

    #[test]
    fn class_intersection_range_intersection() {
        let cls1 = class(&[('a', 'b')]);
        let cls2 = class(&[('b', 'c')]);
        assert_intersection(cls1, cls2, class(&[('b', 'b')]));
    }

    #[test]
    fn class_intersection_only_adjacent() {
        let cls1 = class(&[('a', 'b')]);
        let cls2 = class(&[('c', 'd')]);
        assert_intersection(cls1, cls2, class(&[]));
    }

    #[test]
    fn class_intersection_range_subset() {
        let cls1 = class(&[('b', 'c')]);
        let cls2 = class(&[('a', 'd')]);
        assert_intersection(cls1, cls2, class(&[('b', 'c')]));
    }

    #[test]
    fn class_intersection_many_ranges_in_one_big() {
        let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
        let cls2 = class(&[('a', 'h')]);
        assert_intersection(cls1, cls2, class(&[
            ('a', 'b'), ('d', 'e'), ('g', 'h')
        ]));
    }

    #[test]
    fn class_intersection_many_ranges_same() {
        let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
        let cls2 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
        assert_intersection(cls1, cls2, class(&[
            ('a', 'b'), ('d', 'e'), ('g', 'h')
        ]));
    }

    #[test]
    fn class_intersection_multiple_non_intersecting() {
        let cls1 = class(&[('a', 'b'), ('g', 'h')]);
        let cls2 = class(&[('d', 'e'), ('k', 'l')]);
        assert_intersection(cls1, cls2, class(&[]));
    }

    #[test]
    fn class_intersection_non_intersecting_then_intersecting() {
        let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]);
        let cls2 = class(&[('h', 'h')]);
        assert_intersection(cls1, cls2, class(&[('h', 'h')]));
    }

    #[test]
    fn class_intersection_adjacent_alternating() {
        let cls1 = class(&[('a', 'b'), ('e', 'f'), ('i', 'j')]);
        let cls2 = class(&[('c', 'd'), ('g', 'h'), ('k', 'l')]);
        assert_intersection(cls1, cls2, class(&[]));
    }

    #[test]
    fn class_intersection_overlapping_alternating() {
        let cls1 = class(&[('a', 'b'), ('c', 'd'), ('e', 'f')]);
        let cls2 = class(&[('b', 'c'), ('d', 'e'), ('f', 'g')]);
        assert_intersection(cls1, cls2, class(&[('b', 'f')]));
    }

    #[test]
    fn class_canon_overlap_many_case_fold() {
        let cls = class(&[
            ('C', 'F'), ('A', 'G'), ('D', 'J'), ('A', 'C'),
            ('M', 'P'), ('L', 'S'), ('c', 'f'),
        ]);
        assert_eq!(cls.case_fold(), class(&[
            ('A', 'J'), ('L', 'S'),
            ('a', 'j'), ('l', 's'),
            ('\u{17F}', '\u{17F}'),
        ]));

        let cls = bclass(&[
            (b'C', b'F'), (b'A', b'G'), (b'D', b'J'), (b'A', b'C'),
            (b'M', b'P'), (b'L', b'S'), (b'c', b'f'),
        ]);
        assert_eq!(cls.case_fold(), bclass(&[
            (b'A', b'J'), (b'L', b'S'),
            (b'a', b'j'), (b'l', b's'),
        ]));
    }

    #[test]
    fn class_fold_az() {
        let cls = class(&[('A', 'Z')]);
        assert_eq!(cls.case_fold(), class(&[
            ('A', 'Z'), ('a', 'z'),
            ('\u{17F}', '\u{17F}'),
            ('\u{212A}', '\u{212A}'),
        ]));
        let cls = class(&[('a', 'z')]);
        assert_eq!(cls.case_fold(), class(&[
            ('A', 'Z'), ('a', 'z'),
            ('\u{17F}', '\u{17F}'),
            ('\u{212A}', '\u{212A}'),
        ]));

        let cls = bclass(&[(b'A', b'Z')]);
        assert_eq!(cls.case_fold(), bclass(&[
            (b'A', b'Z'), (b'a', b'z'),
        ]));
        let cls = bclass(&[(b'a', b'z')]);
        assert_eq!(cls.case_fold(), bclass(&[
            (b'A', b'Z'), (b'a', b'z'),
        ]));
    }

    #[test]
    fn class_fold_a_underscore() {
        let cls = class(&[('A', 'A'), ('_', '_')]);
        assert_eq!(cls.clone().canonicalize(), class(&[
            ('A', 'A'), ('_', '_'),
        ]));
        assert_eq!(cls.case_fold(), class(&[
            ('A', 'A'), ('_', '_'), ('a', 'a'),
        ]));

        let cls = bclass(&[(b'A', b'A'), (b'_', b'_')]);
        assert_eq!(cls.clone().canonicalize(), bclass(&[
            (b'A', b'A'), (b'_', b'_'),
        ]));
        assert_eq!(cls.case_fold(), bclass(&[
            (b'A', b'A'), (b'_', b'_'), (b'a', b'a'),
        ]));
    }

    #[test]
    fn class_fold_a_equals() {
        let cls = class(&[('A', 'A'), ('=', '=')]);
        assert_eq!(cls.clone().canonicalize(), class(&[
            ('=', '='), ('A', 'A'),
        ]));
        assert_eq!(cls.case_fold(), class(&[
            ('=', '='), ('A', 'A'), ('a', 'a'),
        ]));

        let cls = bclass(&[(b'A', b'A'), (b'=', b'=')]);
        assert_eq!(cls.clone().canonicalize(), bclass(&[
            (b'=', b'='), (b'A', b'A'),
        ]));
        assert_eq!(cls.case_fold(), bclass(&[
            (b'=', b'='), (b'A', b'A'), (b'a', b'a'),
        ]));
    }

    #[test]
    fn class_fold_no_folding_needed() {
        let cls = class(&[('\x00', '\x10')]);
        assert_eq!(cls.case_fold(), class(&[
            ('\x00', '\x10'),
        ]));

        let cls = bclass(&[(b'\x00', b'\x10')]);
        assert_eq!(cls.case_fold(), bclass(&[
            (b'\x00', b'\x10'),
        ]));
    }

    #[test]
    fn class_fold_negated() {
        let cls = class(&[('x', 'x')]);
        assert_eq!(cls.clone().case_fold(), class(&[
            ('X', 'X'), ('x', 'x'),
        ]));
        assert_eq!(cls.case_fold().negate(), class(&[
            ('\x00', 'W'), ('Y', 'w'), ('y', '\u{10FFFF}'),
        ]));

        let cls = bclass(&[(b'x', b'x')]);
        assert_eq!(cls.clone().case_fold(), bclass(&[
            (b'X', b'X'), (b'x', b'x'),
        ]));
        assert_eq!(cls.case_fold().negate(), bclass(&[
            (b'\x00', b'W'), (b'Y', b'w'), (b'y', b'\xff'),
        ]));
    }

    #[test]
    fn class_fold_single_to_multiple() {
        let cls = class(&[('k', 'k')]);
        assert_eq!(cls.case_fold(), class(&[
            ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'),
        ]));

        let cls = bclass(&[(b'k', b'k')]);
        assert_eq!(cls.case_fold(), bclass(&[
            (b'K', b'K'), (b'k', b'k'),
        ]));
    }

    #[test]
    fn class_fold_at() {
        let cls = class(&[('@', '@')]);
        assert_eq!(cls.clone().canonicalize(), class(&[('@', '@')]));
        assert_eq!(cls.case_fold(), class(&[('@', '@')]));

        let cls = bclass(&[(b'@', b'@')]);
        assert_eq!(cls.clone().canonicalize(), bclass(&[(b'@', b'@')]));
        assert_eq!(cls.case_fold(), bclass(&[(b'@', b'@')]));
    }

    #[test]
    fn is_word_char() {
        use super::is_word_char;
        assert!(is_word_char('a'), "ASCII");
        assert!(is_word_char('à'), "Latin-1");
        assert!(is_word_char('\u{11011}'), "Brahmi (Unicode 6.0)");
        assert!(is_word_char('\u{11611}'), "Modi (Unicode 7.0)");
        assert!(is_word_char('\u{11711}'), "Ahom (Unicode 8.0)");
        assert!(is_word_char('\u{17828}'), "Tangut (Unicode 9.0)");
        assert!(is_word_char('\u{1B1B1}'), "Nushu (Unicode 10.0)");
    }

    #[test]
    fn roundtrip_class_hypen() {
        let expr = e("[-./]");
        assert_eq!("(?u:[-\\.-/])", expr.to_string());

        let expr = e("(?-u)[-./]");
        assert_eq!("(?-u:[-\\.-/])", expr.to_string());
    }

    fn assert_intersection(cls1: CharClass, cls2: CharClass, expected: CharClass) {
        // intersection operation should be commutative
        assert_eq!(cls1.intersection(&cls2), expected);
        assert_eq!(cls2.intersection(&cls1), expected);
    }
}