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
//! This crates provides support for parsing a subset of [RFC 2822].
//! In particular, it exports functions that parse a string according
//! to the [`name-addr`] production, and the [`addr-spec`] production.
//!
//! This crate does not yet parse [RFC 2822] [`dates and times`] or
//! [`message headers`].  Given the infrastructure, adding support for
//! these productions should be straightforward.  However, the main
//! user of this crate is [Sequoia], an [OpenPGP implementation], and
//! it only uses this crate to parse [User IDs], which usually include
//! an [RFC 2822] mail [`name-addr`].  If you require this
//! functionality, please feel free to open an [issue].
//!
//!   [RFC 2822]: https://tools.ietf.org/html/rfc2822
//!   [`name-addr`]: https://tools.ietf.org/html/rfc2822#section-3.4
//!   [`addr-spec`]: https://tools.ietf.org/html/rfc2822#section-3.4.1
//!   [`dates and times`]: https://tools.ietf.org/html/rfc2822#section-3.3
//!   [`message headers`]: https://tools.ietf.org/html/rfc2822#section-3.6
//!   [Sequoia]: https://sequoia-pgp.org/
//!   [OpenPGP implementation]: https://tools.ietf.org/html/rfc4880
//!   [User IDs]: https://tools.ietf.org/html/rfc4880#section-5.11
//!   [issue]: https://gitlab.com/sequoia-pgp/sequoia/issues
//!
//! # Examples
//!
//! Parsing a [`name-addr`]:
//!
//! ```
//! use sequoia_rfc2822::NameAddr;
//!
//! let nameaddr = NameAddr::parse(
//!     "Professor Pippy P. Poopypants <pippy@jerome-horwitz.k12.oh.us>")
//!     .expect("Valid name-addr");
//! assert_eq!(nameaddr.name(), Some("Professor Pippy P. Poopypants"));
//! assert_eq!(nameaddr.comment(), None);
//! assert_eq!(nameaddr.address(), Some("pippy@jerome-horwitz.k12.oh.us"));
//!
//! // Extra angle brackets.
//! assert!(NameAddr::parse("Invalid <<pippy@jerome-horwitz.k12.oh.us>>")
//!        .is_err());
//!
//! // No angle brackets.
//! assert!(NameAddr::parse("pippy@jerome-horwitz.k12.oh.us")
//!        .is_err());
//! ```
//!
//! Parsing an [`addr-spec`]:
//!
//! ```
//! use sequoia_rfc2822::AddrSpec;
//!
//! let addrspec = AddrSpec::parse(
//!     "pippy@jerome-horwitz.k12.oh.us")
//!     .expect("Valid addr-spec");
//! assert_eq!(addrspec.address(), "pippy@jerome-horwitz.k12.oh.us");
//!
//! // Angle brackets are not allowed.
//! assert!(AddrSpec::parse("<pippy@jerome-horwitz.k12.oh.us>")
//!        .is_err());
//! ```

extern crate failure;
extern crate lalrpop_util;

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

use lalrpop_util::ParseError;

#[macro_use] mod macros;
#[macro_use] mod trace;
mod strings;
#[macro_use] mod component;
use crate::component::{
    Component
};
mod lexer;
use crate::lexer::LexicalError;

// We expose a number of productions for testing purposes.
// Unfortunately, lalrpop doesn't understand the #[cfg(test)]
// attribute.  So, to avoid warnings, we allow unused imports and dead
// code when not testing.
#[cfg(test)]
mod grammar;
#[cfg(not(test))]
#[allow(unused_imports, dead_code)]
mod grammar;

#[cfg(test)]
mod roundtrip;

const TRACE : bool = false;

pub type Result<T> = ::std::result::Result<T, failure::Error>;

// A failure needs to have a 'static life time.  lexer::Tokens don't.
// Convert tokens into strings.
//
// Unfortunately, we can't implement From, because we don't define the
// ParseError in this crate.
fn parse_error_downcast<'a>(e: ParseError<usize, lexer::Token<'a>, LexicalError>)
    -> ParseError<usize, String, LexicalError>
{
    match e {
        ParseError::UnrecognizedToken {
            token: (start, t, end),
            expected,
        } => ParseError::UnrecognizedToken {
            token: (start, t.into(), end),
            expected,
        },

        ParseError::ExtraToken {
            token: (start, t, end),
        } => ParseError::ExtraToken {
            token: (start, t.into(), end),
        },

        ParseError::InvalidToken { location }
        => ParseError::InvalidToken { location },

        ParseError::User { error }
        => ParseError::User { error },

        ParseError::UnrecognizedEOF { location, expected }
        => ParseError::UnrecognizedEOF { location, expected },
    }
}

/// A `DisplayName`.
pub struct Name {
}

impl Name {
    /// Returns an escaped version of `name`, which is appropriate for
    /// use in a `name-addr`.
    ///
    /// Returns an error if `name` contains characters that cannot be
    /// escaped (NUL, CR and LF).
    pub fn escaped<S>(name: S) -> Result<String>
        where S: AsRef<str>
    {
        let name = name.as_ref();

        let lexer = lexer::Lexer::new(name);
        grammar::EscapedDisplayNameParser::new().parse(name, lexer)
            .map_err(|e| parse_error_downcast(e).into())
    }
}

/// A parsed RFC 2822 `addr-spec`.
///
/// The address must not include angle brackets.  That is, this parser
/// recognizes addresses of the form:
///
/// ```text
/// email@example.org
/// ```
///
/// But not:
///
/// ```text
/// <email@example.org>
/// ```
///
/// RFC 2822 comments are ignored.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AddrSpec {
    components: Vec<Component>,
}

impl AddrSpec {
    /// Create an RFC 2822 `addr-spec`.
    ///
    /// Not yet exported as this function does *not* do any escaping.
    #[allow(dead_code)]
    fn new<S>(address: S)
        -> Result<Self>
        where S: AsRef<str> + Eq + std::fmt::Debug,
    {
        let address = address.as_ref();

        // Make sure the input is valid.
        let a = match Self::parse(address) {
            Err(err) => return Err(err.into()),
            Ok(a) => a,
        };

        assert_eq!(a.address(), address);

        Ok(a)
    }

    /// Parses a string that allegedly contains an [RFC 2822
    /// `addr-spec`].
    ///
    /// [RFC 2822 `addr-spec`]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn parse<S>(input: S) -> Result<Self>
        where S: AsRef<str>
    {
        let input = input.as_ref();
        let lexer = lexer::Lexer::new(input);
        let components = match grammar::AddrSpecParser::new().parse(input, lexer) {
            Ok(components) => components,
            Err(err) => return Err(parse_error_downcast(err).into()),
        };

        Ok(Self {
            components,
        })
    }

    /// Returns the address.
    pub fn address(&self) -> &str {
        for c in self.components.iter() {
            if let Component::Address(t) = c {
                return &t[..];
            }
        }
        // An addr-spec always has an Address.
        unreachable!();
    }
}

/// A parsed RFC 2822 `addr-spec`, which also recognizes invalid email
/// addresses.
///
/// For this parser to recognize an email address, the input must not
/// include angle brackets.  That is, this parser recognizes addresses
/// of the form:
///
/// ```text
/// email@example.org
/// ```
///
/// But not:
///
/// ```text
/// <email@example.org>
/// ```
///
/// When parsing valid email addresses, RFC 2822 comments are ignored.
///
/// If the input is not a valid email address, no error is returned by
/// `AddrSpecOrOther::parse()` (unlike `AddrSpec::parse()`).  Instead,
/// the invalid email address can be obtained using
/// `AddrSpecOrOther::other()`.  Consider:
///
/// ```text
/// ssh://server.example.net
/// ```
///
/// In this case, `AddrSpecOrOther::other()` returns
/// `ssh://server.example.net`.  The parse error can still be obtained
/// using `AddrSpecOrOther::address()`.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct AddrSpecOrOther {
    components: Vec<Component>,
}

impl AddrSpecOrOther {
    /// Creates an RFC 2822 `addr-spec` or other.
    ///
    /// Not yet exported as this function does *not* do any escaping.
    #[allow(dead_code)]
    fn new<S>(address: S)
        -> Result<Self>
        where S: AsRef<str> + Eq + std::fmt::Debug,
    {
        let address = address.as_ref();

        // Make sure the input is valid.
        let a = match Self::parse(address) {
            Err(err) => return Err(err.into()),
            Ok(a) => a,
        };

        Ok(a)
    }

    /// Parses a string that allegedly contains an [RFC 2822
    /// `addr-spec`] or other.
    ///
    /// [RFC 2822 `addr-spec`]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn parse<S>(input: S) -> Result<Self>
        where S: AsRef<str>
    {
        let input = input.as_ref();
        let lexer = lexer::Lexer::new(input);
        let components = match grammar::AddrSpecOrOtherParser::new().parse(input, lexer) {
            Ok(components) => components,
            Err(err) => return Err(parse_error_downcast(err).into()),
        };

        Ok(Self {
            components,
        })
    }

    /// Returns the address, if any.
    ///
    /// If the address is invalid, then the parse error is returned.
    pub fn address(&self) -> Result<&str> {
        for c in self.components.iter() {
            if let Component::Address(t) = c {
                return Ok(&t[..]);
            }
            if let Component::InvalidAddress(e, _) = c {
                return Err(e.clone().into());
            }
        }

        unreachable!();
    }

    /// Returns the invalid address, if any.
    ///
    /// If the address is valid, then this returns None.
    pub fn other(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Address(_) = c {
                return None;
            }
            if let Component::InvalidAddress(_, t) = c {
                return Some(&t[..]);
            }
        }

        unreachable!();
    }
}

/// A parsed [RFC 2822 `name-addr`].
///
/// `name-addr`s are typically of the form:
///
/// ```text
/// First Last (Comment) <email@example.org>
/// ```
///
/// The name and comment are optional, but the comment is only allowed
/// if there is also a name.
///
/// Note: this does not recognize bare addresses.  That is the angle
/// brackets are required and the following is not recognized as a
/// `name-addr`:
///
/// ```text
/// email@example.org
/// ```
///
/// [RFC 2822 `name-addr`]: https://tools.ietf.org/html/rfc2822#section-3.4
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NameAddr {
    components: Vec<Component>,
}

impl NameAddr {
    /// Create an RFC 2822 `name-addr`.
    ///
    /// Not yet exported as this function does *not* do any escaping.
    #[allow(dead_code)]
    fn new<S>(name: Option<S>, comment: Option<S>, address: Option<S>)
        -> Result<Self>
        where S: AsRef<str> + Eq + std::fmt::Debug,
    {
        let mut s = if let Some(ref name) = name {
            String::from(name.as_ref())
        } else {
            String::new()
        };

        if let Some(ref comment) = comment {
            if name.is_some() {
                s.push(' ');
            }
            s.push_str(&format!("({})", comment.as_ref())[..]);
        }

        if let Some(ref address) = address {
            if name.is_some() || comment.is_some() {
                s.push(' ');
            }
            s.push_str(&format!("<{}>", address.as_ref())[..]);
        }

        // Make sure the input is valid.
        let na = match Self::parse(s) {
            Err(err) => return Err(err.into()),
            Ok(na) => na,
        };

        if let Some(name_reparsed) = na.name() {
            assert!(name.is_some());
            assert_eq!(name_reparsed, name.unwrap().as_ref());
        } else {
            assert!(name.is_none());
        }
        if let Some(comment_reparsed) = na.comment() {
            assert!(comment.is_some());
            assert_eq!(comment_reparsed, comment.unwrap().as_ref());
        } else {
            assert!(comment.is_none());
        }
        if let Some(address_reparsed) = na.address() {
            assert!(address.is_some());
            assert_eq!(address_reparsed, address.unwrap().as_ref());
        } else {
            assert!(address.is_none());
        }

        Ok(na)
    }

    /// Parses a string that allegedly contains an [RFC 2822
    /// `name-addr`].
    ///
    /// [RFC 2822 `name-addr`]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn parse<S>(input: S) -> Result<Self>
        where S: AsRef<str>
    {
        let input = input.as_ref();
        let lexer = lexer::Lexer::new(input);
        let components = match grammar::NameAddrParser::new().parse(input, lexer) {
            Ok(components) => components,
            Err(err) => return Err(parse_error_downcast(err).into()),
        };

        Ok(Self {
            components,
        })
    }

    /// Returns the [display name].
    ///
    /// [display name]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn name(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Text(t) = c {
                return Some(&t[..]);
            }
        }
        None
    }

    /// Returns the first comment.
    pub fn comment(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Comment(t) = c {
                return Some(&t[..]);
            }
        }
        None
    }

    /// Returns the address.
    pub fn address(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Address(t) = c {
                return Some(&t[..]);
            }
        }
        None
    }
}

/// A parsed [RFC 2822 `name-addr`], which also recognizes invalid
/// email addresses.
///
/// `name-addr`s are typically of the form:
///
/// ```text
/// First Last (Comment) <email@example.org>
/// ```
///
/// The name and comment are optional, but the comment is only allowed
/// if there is also a name.
///
/// Note: this does not recognize bare addresses.  That is, the angle
/// brackets are required and the following is not recognized (even as
/// an invalid address) as a `name-addr`:
///
/// ```text
/// email@example.org
/// ```
///
/// [RFC 2822 `name-addr`]: https://tools.ietf.org/html/rfc2822#section-3.4
///
/// This version of the `name-addr` parser also recognizes invalid
/// email addresses.  For instance:
///
/// ```text
/// First Last (Comment) <ssh://server.example.net>
/// ```
///
/// will be successfully parsed.  In this case,
/// `NameAddrOrOther::address()` will return the parse error, and the
/// invalid address can be obtained using `NameAddrOrOther::other()`.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NameAddrOrOther {
    components: Vec<Component>,
}

impl NameAddrOrOther {
    /// Creates an RFC 2822 `name-addr` with an optionally invalid
    /// email address.
    ///
    /// Not yet exported as this function does *not* do any escaping.
    #[allow(dead_code)]
    fn new<S>(name: Option<S>, comment: Option<S>, address: Option<S>)
        -> Result<Self>
        where S: AsRef<str> + Eq + std::fmt::Debug,
    {
        let mut s = if let Some(ref name) = name {
            String::from(name.as_ref())
        } else {
            String::new()
        };

        if let Some(ref comment) = comment {
            if name.is_some() {
                s.push(' ');
            }
            s.push_str(&format!("({})", comment.as_ref())[..]);
        }

        if let Some(ref address) = address {
            if name.is_some() || comment.is_some() {
                s.push(' ');
            }
            s.push_str(&format!("<{}>", address.as_ref())[..]);
        }

        // Make sure the input is valid.
        let na = match Self::parse(s) {
            Err(err) => return Err(err.into()),
            Ok(na) => na,
        };

        if let Some(name_reparsed) = na.name() {
            assert!(name.is_some());
            assert_eq!(name_reparsed, name.unwrap().as_ref());
        } else {
            assert!(name.is_none());
        }
        if let Some(comment_reparsed) = na.comment() {
            assert!(comment.is_some());
            assert_eq!(comment_reparsed, comment.unwrap().as_ref());
        } else {
            assert!(comment.is_none());
        }

        Ok(na)
    }

    /// Parses a string that allegedly contains an [RFC 2822
    /// `name-addr`] with an optionally invalid email address.
    ///
    /// [RFC 2822 `name-addr`]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn parse<S>(input: S) -> Result<Self>
        where S: AsRef<str>
    {
        let input = input.as_ref();
        let lexer = lexer::Lexer::new(input);
        let components = match grammar::NameAddrOrOtherParser::new().parse(input, lexer) {
            Ok(components) => components,
            Err(err) => return Err(parse_error_downcast(err).into()),
        };

        Ok(Self {
            components,
        })
    }

    /// Returns the [display name].
    ///
    /// [display name]: https://tools.ietf.org/html/rfc2822#section-3.4
    pub fn name(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Text(t) = c {
                return Some(&t[..]);
            }
        }
        None
    }

    /// Returns the first comment.
    pub fn comment(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Comment(t) = c {
                return Some(&t[..]);
            }
        }
        None
    }

    /// Returns the address, if any.
    ///
    /// If the address is invalid, then the parse error is returned.
    pub fn address(&self) -> Result<&str> {
        for c in self.components.iter() {
            if let Component::Address(t) = c {
                return Ok(&t[..]);
            }
            if let Component::InvalidAddress(e, _) = c {
                return Err(e.clone().into());
            }
        }

        unreachable!()
    }

    /// Returns the invalid address, if any.
    ///
    /// If the address is valid, then this returns None.
    pub fn other(&self) -> Option<&str> {
        for c in self.components.iter() {
            if let Component::Address(_) = c {
                return None;
            }
            if let Component::InvalidAddress(_, t) = c {
                return Some(&t[..]);
            }
        }

        unreachable!()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! c {
        ( $parser:expr, $t:ty) => {
            fn c<S>(input: S, expected: Option<$t>)
                where S: AsRef<str>
            {
                let input = input.as_ref();
                eprintln!("\n\ninput: '{:?}'", input);

                let lexer = lexer::Lexer::new(&input[..]);
                let result = $parser.parse(input, lexer);

                if let Some(expected) = expected {
                    if let Ok(result) = result {
                        assert_eq!(result, expected,
                                   "Parsing: '{:?}'\n     got: '{:?}'\nexpected: '{:?}'",
                                   input, result, expected);
                    } else {
                        panic!("Parsing: '{:?}': {:?}", input, result);
                    }
                } else {
                    assert!(result.is_err(), "Parsing '{:?}'\n     got: '{:?}'\nexpected: '{:?}'",
                            input, result, expected);
                }
            }
        };
    }

    // comment         =       "(" *([FWS] ccontent) [FWS] ")"
    // ccontent        =       ctext / quoted-pair / comment
    // ctext           =       NO-WS-CTL /     ; Non white space controls
    //                         %d33-39 /       ; The rest of the US-ASCII
    //                         %d42-91 /       ;  characters not including "(",
    //                         %d93-126        ;  ")", or "\"
    // quoted-pair     =       ("\" text) / obs-qp
    // text            =       %d1-9 /         ; Characters excluding CR and LF
    //                         %d11 /
    //                         %d12 /
    //                         %d14-127 /
    //                         obs-text

    // The comment production parses a single comment.
    //
    // A comment can contain pretty much anything, but any parenthesis
    // need to be balanced (or escaped).
    #[test]
    fn comment_parser() {
        c!(grammar::CommentParser::new(), Component);

        // A comment must be surrounded by ().
        c("foobar", None);
        c("(foobar)",
          Some(Component::Comment("foobar".into())));
        c("(foo bar)",
          Some(Component::Comment("foo bar".into())));
        // Unbalanced parenthesis are not allowed.
        c("((foobar)", None);
        // Unless they are escaped.
        c("(\\(foobar)",
          Some(Component::Comment("(foobar".into())));
        c("((foobar))",
          Some(Component::Comment("(foobar)".into())));
        c("((fo()ob()ar))",
          Some(Component::Comment("(fo()ob()ar)".into())));

        // The comment parser doesn't remove leading or trailing
        // whitespace.
        c("  \r\n   ((abc))", None);
        c("((abc))  ", None);

        // Folding whitespace is compressed to a single space.
        c("(   a)",
          Some(Component::Comment(" a".into())));
        c("(a      )",
          Some(Component::Comment("a ".into())));
        c("(      a        )",
          Some(Component::Comment(" a ".into())));
        c("(   a  b    )",
          Some(Component::Comment(" a b ".into())));

        c("( \r\n  a  b)",
          Some(Component::Comment(" a b".into())));
        c("(a    \r\n b )",
          Some(Component::Comment("a b ".into())));
        c("(a  b  \r\n  )",
          Some(Component::Comment("a b ".into())));
        c("(      a   b     )",
          Some(Component::Comment(" a b ".into())));
        c("(  \r\n    a    \r\n  b   \r\n  )",
          Some(Component::Comment(" a b ".into())));

        c("(   a  \r\n   bc      \r\n       d   )",
          Some(Component::Comment(" a bc d ".into())));
        c("((     a  \r\n   bc      \r\n       d ))",
          Some(Component::Comment("( a bc d )".into())));

        // The crlf in folding white space must be followed by a
        // space.
        c("(foo\r\n)", None);
        c("(foo\r\n )",
          Some(Component::Comment("foo ".into())));

        // Multiple folding white spaces in a row are not allowed.
        c("(( \r\n  \r\n    a ))", None);
        c("(( abcd \r\n  \r\n    a ))", None);
        c("(( abcd \r\n  \r\n    ))", None);
    }

    // CFWS            =       *([FWS] comment) (([FWS] comment) / FWS)
    //
    // The CFWS production allows for multiple comments preceded,
    // separated and followed by folding whitespace.
    #[test]
    fn cfws_parser() {
        c!(grammar::CfwsParser::new(), Vec<Component>);

        // A comment must be surrounded by ().
        c("foobar", None);
        c("(foobar)",
          Some(vec![Component::Comment("foobar".into())]));
        // Unbalanced parenthesis are not allowed.
        c("((foobar)", None);
        c("((foobar))",
          Some(vec![Component::Comment("(foobar)".into())]));
        c("((fo()ob()ar))",
          Some(vec![Component::Comment("(fo()ob()ar)".into())]));

        // Folding white space before and after is okay.  It appears
        // as a single space character.
        c("  \r\n   ((abc))",
          Some(vec![
              Component::WS,
              Component::Comment("(abc)".into()),
          ]));
        c("((abc)) \r\n  ",
          Some(vec![
              Component::Comment("(abc)".into()),
              Component::WS,
          ]));

        c("((a  \r\n   bc      \r\n       d))",
          Some(vec![Component::Comment("(a bc d)".into())]));

        // Multiple comments are also allowed.
        c("((foobar   buz)) (bam)\r\n (quuz)  \r\n   ",
          Some(vec![
              Component::Comment("(foobar buz)".into()),
              Component::WS,
              Component::Comment("bam".into()),
              Component::WS,
              Component::Comment("quuz".into()),
              Component::WS,
          ]));
        c("(xy(z)zy)   ((foobar))      (bam)",
          Some(vec![
              Component::Comment("xy(z)zy".into()),
              Component::WS,
              Component::Comment("(foobar)".into()),
              Component::WS,
              Component::Comment("bam".into())
          ]));

        // Adjacent comments don't have any spaces between them.
        c("((foobar   buz))(bam)(quuz)",
          Some(vec![
              Component::Comment("(foobar buz)".into()),
              Component::Comment("bam".into()),
              Component::Comment("quuz".into()),
          ]));

    }

    // atom            =       [CFWS] 1*atext [CFWS]
    //
    // Note: our atom parser also allows for dots and ats.
    //
    // An atom is a sequence of characters.
    //
    // They may be preceded or followed by a CFWS (zero or more
    // comments and folding white space).
    //
    // Note: no spaces are allowed in the atext!  They can't even be
    // escaped.
    #[test]
    fn atom_parser() {
        c!(grammar::AtomParser::new(), Vec<Component>);

        c("foobar", Some(vec![Component::Text("foobar".into())]));

        // "Any character except controls, SP, and specials."
        for &s in ["a", "1", "ß", "ü", "é", "あ", "fooゔヲ", "ℝ💣東京",
                  "!", "#", "$", "%", "&", "'", "*", "+", "-",
                   "/", "=", "?", "^", "_", "`", "{", "|", "}", "~",
                   // Extension:
                   ".", "@"]
            .into_iter()
        {
            c(s, Some(vec![Component::Text(s.to_string())]))
        }

        for &s in ["\x02", " ",
                  "(", ")", "<", ">", "[", "]", ":", ";",
                  "\\", ",", "\""]
            .into_iter()
        {
            c(s, None)
        }

        // No internal white space.
        c("foo bar", None);

        // If a CFWS precedes an atom, any comments are retained, but
        // trailing white space is removed.
        c("\r\n foobar  \r\n ",
          Some(vec![
              Component::WS,
              Component::Text("foobar".into()),
              Component::WS,
          ]));
        c("  \r\n foobar  ",
          Some(vec![
              Component::WS,
              Component::Text("foobar".into()),
              Component::WS,
          ]));

        c("(some comment)foobar",
          Some(vec![
              Component::Comment("some comment".into()),
              Component::Text("foobar".into())
          ]));
        c("(some comment) foobar",
          Some(vec![
              Component::Comment("some comment".into()),
              Component::WS,
              Component::Text("foobar".into())
          ]));
        c("(so\r\n m   \r\n e co\r\n   mme  \r\n   nt\r\n ) \r\n    foobar",
          Some(vec![
              Component::Comment("so m e co mme nt ".into()),
              Component::WS,
              Component::Text("foobar".into())
          ]));

        c("(a)(b)(c)foobar(d)(e)",
          Some(vec![
              Component::Comment("a".into()),
              Component::Comment("b".into()),
              Component::Comment("c".into()),
              Component::Text("foobar".into()),
              Component::Comment("d".into()),
              Component::Comment("e".into())
          ]));
        c(" \r\n  (a)\r\n (b)\r\n   (c)\r\n    foobar \r\n (d)(e) \r\n ",
          Some(vec![
              Component::WS,
              Component::Comment("a".into()),
              Component::WS,
              Component::Comment("b".into()),
              Component::WS,
              Component::Comment("c".into()),
              Component::WS,
              Component::Text("foobar".into()),
              Component::WS,
              Component::Comment("d".into()),
              Component::Comment("e".into()),
              Component::WS,
          ]));
    }

    // quoted-string   =       [CFWS]
    //                         DQUOTE *([FWS] qcontent) [FWS] DQUOTE
    //                         [CFWS]
    //
    // qcontent        =       qtext / quoted-pair
    //
    // qtext           =       NO-WS-CTL /     ; Non white space controls
    //                         %d33 /          ; The rest of the US-ASCII
    //                         %d35-91 /       ;  characters not including "\"
    //                         %d93-126        ;  or the quote character
    //
    // quoted-pair     =       ("\" text) / obs-qp
    #[test]
    fn quoted_string_parser() {
        c!(grammar::QuotedStringParser::new(), Vec<Component>);

        c("\"foobar\"", Some(vec![Component::Text("foobar".into())]));
        c("\"   foobar\"", Some(vec![Component::Text(" foobar".into())]));
        c("\"foobar  \"", Some(vec![Component::Text("foobar ".into())]));
        c("\"foo  bar bam \"",
          Some(vec![Component::Text("foo bar bam ".into())]));
        c("\"   foo  bar bam \"",
          Some(vec![Component::Text(" foo bar bam ".into())]));
        c("\r\n \"(some comment)\"",
          Some(vec![
              Component::WS,
              Component::Text("(some comment)".into()),
          ]));
        c("\"(some comment)\" \r\n ",
          Some(vec![
              Component::Text("(some comment)".into()),
              Component::WS,
          ]));


        c("\"\\f\\o\\o\\b\\a\\r\"",
          Some(vec![Component::Text("foobar".into())]));

        // comments in a quoted string aren't.
        c("(not a comment)\"foobar\"",
          Some(vec![
              Component::Comment("not a comment".into()),
              Component::Text("foobar".into())
          ]));
        c("\"(not a comment)foobar\"",
          Some(vec![Component::Text("(not a comment)foobar".into())]));
        c("\"))((((not a comment)foobar\"",
          Some(vec![Component::Text("))((((not a comment)foobar".into())]));
    }

    // word            =       atom / quoted-string
    #[test]
    fn word_parser() {
        c!(grammar::WordParser::new(), Vec<Component>);

        c("foobar", Some(vec![Component::Text("foobar".into())]));
        c("\"foobar\"", Some(vec![Component::Text("foobar".into())]));
        c("\"\\f\\o\\o\\b\\a\\r\"", Some(vec![Component::Text("foobar".into())]));
    }

    // phrase          =       1*word / obs-phrase
    #[test]
    fn phrase_parser() {
        c!(grammar::PhraseParser::new(), Vec<Component>);

        c("foobar", Some(vec![Component::Text("foobar".into())]));
        c("foobar bam", Some(vec![Component::Text("foobar bam".into())]));
        c("foobar  bam", Some(vec![Component::Text("foobar bam".into())]));
        c(" foobar  bam ",
          Some(vec![
              Component::WS,
              Component::Text("foobar bam".into()),
              Component::WS,
          ]));

        c("\"foobar\"", Some(vec![Component::Text("foobar".into())]));
        c("\"foobar\" \"bam\"", Some(vec![Component::Text("foobar bam".into())]));
        c("\"foobar\"  \"bam\"", Some(vec![Component::Text("foobar bam".into())]));
        c(" \"foobar\"  \"bam\" ",
          Some(vec![
              Component::WS,
              Component::Text("foobar bam".into()),
              Component::WS,
          ]));

        c("\"foobar\"\"bam\"",
          Some(vec![Component::Text("foobarbam".into())]));
        c("\"foobar\"quuz\"bam\"",
          Some(vec![Component::Text("foobarquuzbam".into())]));
        c("\"foobar\"quuz \"bam\"",
          Some(vec![Component::Text("foobarquuz bam".into())]));
        c("\"foobar\"quuz  \"bam\"",
          Some(vec![Component::Text("foobarquuz bam".into())]));

        c("\"foobar\"", Some(vec![Component::Text("foobar".into())]));
        // Just a comment is not allowed.
        c("(foobar)", None);
        c("(foobar) quux",
          Some(vec![
              Component::Comment("foobar".into()),
              Component::WS,
              Component::Text("quux".into())
          ]));
        c("xyzzy (foobar) quux",
          Some(vec![Component::Text("xyzzy".into()),
                    Component::WS,
                    Component::Comment("foobar".into()),
                    Component::WS,
                    Component::Text("quux".into())]));
        c("foobar (comment) \"quoted string\"",
          Some(vec![
              Component::Text("foobar".into()),
              Component::WS,
              Component::Comment("comment".into()),
              Component::WS,
              Component::Text("quoted string".into())]));
        c("foobar (comment) \"   quoted string\"",
          Some(vec![
              Component::Text("foobar".into()),
              Component::WS,
              Component::Comment("comment".into()),
              Component::WS,
              Component::Text(" quoted string".into())]));
        c("foobar bam   quuz",
          Some(vec![Component::Text("foobar bam quuz".into())]));
    }

    // dot-atom        =       [CFWS] dot-atom-text [CFWS]
    // dot-atom-text   =       1*atext *("." 1*atext)
    #[test]
    fn dot_atom_parser() {
        c!(grammar::DotAtomParser::new(), Vec<Component>);

        c("f",
          Some(vec![Component::Text("f".into())]));
        c("foo",
          Some(vec![Component::Text("foo".into())]));
        c("f.o",
          Some(vec![Component::Text("f.o".into())]));
        c("foo.bar",
          Some(vec![Component::Text("foo.bar".into())]));

        c("foo.", None);
        c("foo.bar.", None);
        c("foo..bar", None);
        c(".foo.bar", None);
        c(".", None);
        c("..", None);

        // Internal space is not allowed.
        c("foo bar", None);

        // But leading and trailing space is okay.
        c(" f",
          Some(vec![
              Component::WS,
              Component::Text("f".into()),
          ]));
        c("  f",
          Some(vec![
              Component::WS,
              Component::Text("f".into()),
          ]));
        c("f ",
          Some(vec![
              Component::Text("f".into()),
              Component::WS,
          ]));
        c("f  ",
          Some(vec![
              Component::Text("f".into()),
              Component::WS,
          ]));

        // Comments are also okay.
        c("(comment) f",
          Some(vec![
              Component::Comment("comment".into()),
              Component::WS,
              Component::Text("f".into()),
          ]));
        c(" (comment) f",
          Some(vec![
              Component::WS,
              Component::Comment("comment".into()),
              Component::WS,
              Component::Text("f".into()),
          ]));
        c(" f (comment) ",
          Some(vec![
              Component::WS,
              Component::Text("f".into()),
              Component::WS,
              Component::Comment("comment".into()),
              Component::WS,
          ]));
        c(" f (comment)",
          Some(vec![
              Component::WS,
              Component::Text("f".into()),
              Component::WS,
              Component::Comment("comment".into()),
          ]));
    }


    // domain-literal  =       [CFWS] "[" *([FWS] dcontent) [FWS] "]" [CFWS]
    #[test]
    fn domain_literal_parser() {
        c!(grammar::DomainLiteralParser::new(), Vec<Component>);

        c("[foo]",
          Some(vec![Component::Text("[foo]".into())]));
        c("[\\[foo\\[]",
          Some(vec![Component::Text("[[foo[]".into())]));
        c("[foo.bar.com quux:biz]",
          Some(vec![Component::Text("[foo.bar.com quux:biz]".into())]));
        c(" \r\n   [\r\n   foo.bar.com \r\n   quux:biz\r\n   ]\r\n   ",
          Some(vec![
              Component::WS,
              Component::Text("[ foo.bar.com quux:biz ]".into()),
              Component::WS,
          ]));
    }

    // addr-spec-or-other     =       local-part "@" domain
    //                        |       anything
    #[test]
    fn or_other_parsers() {
        fn e() -> ParseError<usize, String, LexicalError> {
            ParseError::User { error: LexicalError::NoError }
        }

        struct Test<'a> {
            input: &'a str,
            output: Option<Vec<Component>>,
        };

        let tests : &[Test] = &[
            // First, some normal, valid email addresses.
            Test {
                input: "foo@bar.com",
                output: Some(vec![Component::Address("foo@bar.com".into())])
            },
            Test {
                input: "foo@bar",
                output: Some(vec![Component::Address("foo@bar".into())])
            },
            Test {
                input: "foo.bar@x",
                output: Some(vec![Component::Address("foo.bar@x".into())])
            },
            // Last character is a multibyte character.
            Test {
                input: "foo.bar@ß",
                output: Some(vec![Component::Address("foo.bar@ß".into())])
            },

            // Then some invalid email addresses...

            // [ is not a valid localpart.
            Test {
                input: "[@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[@x".into())
                ])
            },
            Test {
                input: "[ß@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[ß@x".into())
                ])
            },
            // Last character is a multibyte character.
            Test {
                input: "[@xß",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[@xß".into())
                ])
            },
            Test {
                input: "[@xßℝ",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[@xßℝ".into())
                ])
            },
            Test {
                input: "foo[@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo[@x".into())
                ])
            },

            // What happens with comments?
            Test {
                input: "(c)[@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "(c)[@x".into())
                ])
            },
            Test {
                input: "[(c)@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[(c)@x".into())
                ])
            },
            Test {
                input: "[@(c)x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[@(c)x".into())
                ])
            },

            Test {
                input: "foo(c)[@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo(c)[@x".into())
                ])
            },
            Test {
                input: "foo[(c)@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo[(c)@x".into())
                ])
            },
            Test {
                input: "foo[@(c)x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo[@(c)x".into())
                ])
            },

            Test {
                input: "[@x (c)",
                output: Some(vec![
                    Component::InvalidAddress(e(), "[@x (c)".into())
                ])
            },

            Test {
                input: "(c) foo[@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "(c) foo[@x".into())
                ])
            },
            Test {
                input: "foo[ (c)@x",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo[ (c)@x".into())
                ])
            },

            // @ is not a valid domain part.
            Test {
                input: "foo.bar@@dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@@dings".into())
                ])
            },
            Test {
                input: "foo.bar@x@dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@x@dings".into())
                ])
            },

            // Again, what happens with comments?
            Test {
                input: "foo.bar  (1)@@(2)dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar  (1)@@(2)dings".into())
                ])
            },
            Test {
                input: "foo.bar  (1) @@ (2)dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar  (1) @@ (2)dings".into())
                ])
            },

            Test {
                input: "foo.bar(1)@x@dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar(1)@x@dings".into())
                ])
            },
            Test {
                input: "foo.bar@(1)x@dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@(1)x@dings".into())
                ])
            },
            Test {
                input: "foo.bar@x(1)@dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@x(1)@dings".into())
                ])
            },
            Test {
                input: "foo.bar@x@(1)dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@x@(1)dings".into())
                ])
            },
            Test {
                input: "foo.bar@x@  (1)  dings",
                output: Some(vec![
                    Component::InvalidAddress(e(), "foo.bar@x@  (1)  dings".into())
                ])
            },



            // Try some URIs for completeness.
            Test {
                input: "ssh://user:pasword@example.org/resource",
                output: Some(vec![
                    Component::InvalidAddress(
                        e(), "ssh://user:pasword@example.org/resource".into())
                ])
            },

            Test {
                input: "(not a comment)   ssh://user:pasword@example.org/resource",
                output: Some(vec![
                    Component::InvalidAddress(
                        e(), "(not a comment)   ssh://user:pasword@example.org/resource".into())
                ])
            },

            Test {
                input: "shark://grrrr/39874293847092837443987492834",
                output: Some(vec![
                    Component::InvalidAddress(
                        e(), "shark://grrrr/39874293847092837443987492834".into())
                ])
            },

            Test {
                input: "shark://bait/8uyoi3lu4hl2..dfoif983j4b@%",
                output: Some(vec![
                    Component::InvalidAddress(
                        e(), "shark://bait/8uyoi3lu4hl2..dfoif983j4b@%".into())
                ])
            },
        ][..];

        for t in tests.iter() {
            {
                c!(grammar::AddrSpecOrOtherParser::new(), Vec<Component>);
                c(t.input.to_string(), t.output.clone())
            }

            {
                c!(grammar::AngleAddrOrOtherParser::new(), Vec<Component>);
                c(format!("<{}>", t.input), t.output.clone())
            }

            {
                c!(grammar::NameAddrOrOtherParser::new(), Vec<Component>);
                c(format!("Foo Bar <{}>", t.input),
                  t.output.clone().map(|mut x| {
                      x.insert(0, Component::WS);
                      x.insert(0, Component::Text("Foo Bar".into()));
                      x
                  }))
            }
        }
    }

    // angle-addr      =       [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
    // addr-spec       =       local-part "@" domain
    // local-part      =       dot-atom / quoted-string / obs-local-part
    // dot-atom        =       [CFWS] dot-atom-text [CFWS]
    // dot-atom-text   =       1*atext *("." 1*atext)
    // domain          =       dot-atom / domain-literal / obs-domain
    // domain-literal  =       [CFWS] "[" *([FWS] dcontent) [FWS] "]" [CFWS]
    #[test]
    fn angle_addr_parser() {
        c!(grammar::AngleAddrParser::new(), Vec<Component>);

        c("[foo]", None);

        // Normal email addresses.
        c("<foo@bar.com>", Some(vec![Component::Address("foo@bar.com".into())]));
        c("<foo@bar>", Some(vec![Component::Address("foo@bar".into())]));
        c("<foo.bar@x>", Some(vec![Component::Address("foo.bar@x".into())]));
        c("<foo@bar>", Some(vec![Component::Address("foo@bar".into())]));

        c("<foo@@bar>", None);
        c("<f@oo@bar>", None);

        // Quote the local part.
        c("<\"foo\"@bar.com>",
          Some(vec![Component::Address("foo@bar.com".into())]));
        c("<\"f\\\"oo\"@bar.com>",
          Some(vec![Component::Address("f\"oo@bar.com".into())]));
        // The whole thing has to be quoted.
        c("<\"foo\".bar@x>", None);

        c("<foo@[bar.com]>",
          Some(vec![Component::Address("foo@[bar.com]".into())]));
        c("<foo@[bar]>",
          Some(vec![Component::Address("foo@[bar]".into())]));
        c("<foo.bar@[x]>",
          Some(vec![Component::Address("foo.bar@[x]".into())]));

        c("<foo.bar@x.>", None);

        // White space is ignored at the beginning and ending of the
        // local part, but not in the middle.
        c("<  \r\n   foo.bar@x>",
          Some(vec![
              Component::WS,
              Component::Address("foo.bar@x".into()),
          ]));
        c("<  \r\n   foo.bar \r\n @x>",
          Some(vec![
              Component::WS,
              Component::Address("foo.bar@x".into())
          ]));
        c("<  (quuz) \r\n   foo.bar@x>",
          Some(vec![
              Component::WS,
              Component::Comment("quuz".into()),
              Component::WS,
              Component::Address("foo.bar@x".into()),
          ]));
        c("<  \r\n   foo.bar \r\n @x>",
          Some(vec![
              Component::WS,
              Component::Address("foo.bar@x".into()),
          ]));
        c("<f  \r\n   oo.bar@x>", None);

        c("<foo.bar@x \r\n >",
          Some(vec![
              Component::Address("foo.bar@x".into()),
              Component::WS,
          ]));
        c("<f  \r\n   oo.bar@x \r\n y>", None);

        c("  <foo.bar@x>  ",
          Some(vec![
              Component::WS,
              Component::Address("foo.bar@x".into()),
              Component::WS,
          ]));

        // And don't forget comments...
        c("< (Hello!) foo.bar@x \r\n >",
          Some(vec![
              Component::WS,
              Component::Comment("Hello!".into()),
              Component::WS,
              Component::Address("foo.bar@x".into()),
              Component::WS,
          ]));
        // Comments in the local part are always moved left.
        c("< (Hello!) foo.bar (bye?) \r\n @x \r\n >",
          Some(vec![
              Component::WS,
              Component::Comment("Hello!".into()),
              Component::WS,
              Component::Comment("bye?".into()),
              Component::WS,
              Component::Address("foo.bar@x".into()),
              Component::WS,
          ]));
        c("< (Hello!) foo.bar@x \r\n >",
          Some(vec![
              Component::WS,
              Component::Comment("Hello!".into()),
              Component::WS,
              Component::Address("foo.bar@x".into()),
              Component::WS,
          ]));
        // Comments in the domain part are always moved right.
        c("< x@  (Hello!) foo.bar (bye?) >",
          Some(vec![
              Component::WS,
              Component::Address("x@foo.bar".into()),
              Component::WS,
              Component::Comment("Hello!".into()),
              Component::WS,
              Component::Comment("bye?".into()),
              Component::WS,
          ]));

        // Try the same with quoted strings.
        c("< (Hello!) \"f oo.bar\"@x \r\n >",
          Some(vec![
              Component::WS,
              Component::Comment("Hello!".into()),
              Component::WS,
              Component::Address("f oo.bar@x".into()),
              Component::WS,
          ]));
    }

    #[test]
    fn name_addr_parser() {
        c!(grammar::NameAddrParser::new(), Vec<Component>);

        // A name-addr doesn't match a bare email address.
        c("foo@example.org", None);

        // Tricky, tricky: the local part is the empty string.
        c("<\"\"@example.org>",
          Some(vec![ Component::Address("@example.org".into()) ]));
        c("Willi Wonka <\"\"@無.com>",
          Some(vec![ Component::Text("Willi Wonka".into()),
                     Component::WS,
                     Component::Address("@無.com".into()) ]));
    }

    #[test]
    fn display_name_parser() {
        c!(grammar::DisplayNameParser::new(), Vec<Component>);

        c("Willi Wonka",
          Some(vec![ Component::Text("Willi Wonka".into()) ]));

        // As an extention we unquoted dots.
        c("Willi A. Wonka",
          Some(vec![ Component::Text("Willi A. Wonka".into()) ]));

        // As an extention we unquoted ats.
        c("foo@example.org",
          Some(vec![ Component::Text("foo@example.org".into()) ]));
    }

    #[test]
    fn name_addr_api() {
        fn c_(name: Option<&str>, comment: Option<&str>, email: Option<&str>)
        {
            eprintln!("checking: name: {:?}, comment: {:?}, email: {:?}",
                      name, comment, email);
            let na = NameAddr::new(name, comment, email).unwrap();
            assert_eq!(na.name(), name);
            assert_eq!(na.comment(), comment);
            assert_eq!(na.address(), email);
        }

        fn c(name: &str, comment: &str, email: &str)
        {
            // A name-addr requires an address.  And, it only allows a
            // comment if there is also a name.

            c_(Some(name), Some(comment), Some(email));
            // c_(None, Some(comment), Some(email));
            c_(Some(name), None, Some(email));
            // c_(Some(name), Some(comment), None);
            c_(None, None, Some(email));
            // c_(None, Some(comment), None);
            // c_(Some(name), None, None);
        }

        c("Harold Hutchins", "(artist)", "harold.hutchins@captain-underpants.com");
        c("Mr. Meaner", "(Gym Teacher)", "kenny@jerome-horwitz.k12.us");
        c("foo@bar.com", "display name with at", "foo@bar.com");
    }

    #[test]
    fn name_addr_or_other_api() {
        fn c_(name: Option<&str>, comment: Option<&str>,
              email: Option<&str>, valid: bool)
        {
            eprintln!("checking: name: {:?}, comment: {:?}, email: {:?}",
                      name, comment, email);
            let na = NameAddrOrOther::new(name, comment, email).unwrap();
            assert_eq!(na.name(), name);
            assert_eq!(na.comment(), comment);
            if let Some(email) = email {
                if valid {
                    assert_eq!(na.address().unwrap(), email);
                    assert!(na.other().is_none());
                } else {
                    assert!(na.address().is_err());
                    assert_eq!(na.other().unwrap(), email);
                }
            }
        }

        fn c(name: &str, comment: &str, email: &str, valid: bool)
        {
            // A name-addr requires an address.  And, it only allows a
            // comment if there is also a name.

            c_(Some(name), Some(comment), Some(email), valid);
            // c_(None, Some(comment), Some(email), valid);
            c_(Some(name), None, Some(email), valid);
            // c_(Some(name), Some(comment), None, valid);
            c_(None, None, Some(email), valid);
            // c_(None, Some(comment), None, valid);
            // c_(Some(name), None, None, valid);
        }

        c("Harold Hutchins", "(artist)", "harold.hutchins@captain-underpants.com", true);
        c("Mr. Meaner", "(Gym Teacher)", "kenny@jerome-horwitz.k12.us", true);
        c("Mr. Meaner", "(Gym Teacher)", "ssh://nas.jerome-horwitz.k12.us", false);
    }

    #[test]
    fn addr_spec_api() {
        fn c(email: &str, ok: bool)
        {
            match AddrSpec::new(email) {
                Ok(ref a) if ok => assert_eq!(a.address(), email),
                Ok(ref a) if !ok =>
                    panic!("Expected parser to fail for '{:?}': got '{:?}'",
                           email, a),
                Err(ref err) if ok =>
                    panic!("Expected parser to succeed for '{:?}': {:?}",
                           email, err),
                Err(_) if !ok => (),
                _ => unreachable!(),
            }
        }

        c("example@foo.com", true);
        c("<example@foo.com>", false);
        c("example@@foo.com", false);
    }

    #[test]
    fn addr_spec_or_other_api() {
        fn c(email: &str, ok: bool)
        {
            match AddrSpecOrOther::new(email) {
                Ok(ref a) if ok => {
                    assert_eq!(a.address().unwrap(), email);
                    assert_eq!(a.other(), None);
                }
                Ok(ref a) if !ok => {
                    assert!(a.address().is_err());
                    assert_eq!(a.other(), Some(email));
                }
                Err(ref err) if ok =>
                    panic!("Expected parser to succeed for '{:?}': {:?}",
                           email, err),
                Err(_) if !ok => (),
                _ => unreachable!(),
            }
        }

        c("example@foo.com", true);
        c("<example@foo.com>", false);
        c("example@@foo.com", false);
    }

    #[test]
    fn name_escape_test() {
        fn c(raw: &str, escaped_expected: &str) {
            eprintln!("\nInput: {:?}", raw);
            eprintln!("Expecting escaped version to be: {:?}", escaped_expected);
            let escaped_got = Name::escaped(raw).expect("Parse error");
            eprintln!("             Escaped version is: {:?}", escaped_got);

            // There are often multiple ways to validly escape a name.
            // This check relies on knowing how a name is escaped.  In
            // other words: if the implementation changes and this
            // test fails, then this failure may not be indicative of
            // a bug; we may just need to adjust what this test
            // expects.
            assert_eq!(escaped_got, escaped_expected);

            // Make sure when we parse it, we get the original back.
            let lexer = lexer::Lexer::new(&escaped_got);
            let raw_got = grammar::DisplayNameParser::new()
                .parse(&escaped_got, lexer)
                .expect(&format!("Parse error: {}", escaped_got));

            eprintln!("Parsing escaped version, got: {:?}", raw_got);

            assert_eq!(raw_got, vec![ Component::Text(raw.to_string()) ]);
        }

        c("Foo Q. Bar", r#""Foo Q. Bar""#);
        c(r#""Foo Q. Bar""#, r#""\"Foo Q. Bar\"""#);
        c(r#""Foo Q Bar""#, r#""\"Foo Q Bar\"""#);
        c("Foo, the Bar", r#""Foo, the Bar""#);

        // Make sure leading and trailing spaces are quoted.
        c(" Foo Bar", r#"" Foo Bar""#);
        c("Foo Bar ", r#""Foo Bar ""#);
    }
}