structured-email-address 0.0.5

RFC 5321/5322/6531 email address parser, validator, and normalizer. Subaddress extraction, provider-aware normalization, PSL domain validation, anti-homoglyph protection.
Documentation
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
//! Hand-rolled RFC 5321/5322/6531 email address parser.
//!
//! Grammar reference: RFC 5322 §3.4.1 (addr-spec), §3.2.3 (atom, dot-atom),
//! §3.2.4 (quoted-string), §3.2.2 (FWS, CFWS), §4.4 (obs-local-part, obs-domain),
//! RFC 6531 §3.3 (UTF8-non-ascii in atext/qtext/dtext).
//!
//! This parser produces zero-copy byte-offset spans into the input string.

use crate::config::Strictness;
use crate::error::{Error, ErrorKind};

/// Maximum nesting depth for comments and obs-domain recursion.
const MAX_RECURSION_DEPTH: usize = 128;

/// Raw parse result with byte-offset spans into the input.
#[derive(Debug, Clone)]
pub(crate) struct Parsed<'a> {
    /// The original input.
    pub input: &'a str,
    /// Display name (from `name-addr` syntax), if present.
    pub display_name: Option<Span>,
    /// Full local-part span (may include quotes for quoted-string).
    pub local_part: Span,
    /// Domain span.
    pub domain: Span,
    /// Comments found during parsing.
    #[allow(dead_code)]
    pub comments: Vec<Span>,
    /// Clean local-part with CFWS stripped (only set for obs-local-part with CFWS).
    pub local_part_clean: Option<String>,
    /// Clean domain with CFWS stripped (only set for obs-domain with CFWS).
    pub domain_clean: Option<String>,
}

impl<'a> Parsed<'a> {
    /// Effective local-part content: CFWS-stripped version if available, otherwise raw span.
    pub fn local_part_str(&self) -> &str {
        self.local_part_clean
            .as_deref()
            .unwrap_or_else(|| self.local_part.as_str(self.input))
    }

    /// Effective domain content: CFWS-stripped version if available, otherwise raw span.
    pub fn domain_str(&self) -> &str {
        self.domain_clean
            .as_deref()
            .unwrap_or_else(|| self.domain.as_str(self.input))
    }
}

/// A byte-offset range into the input string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Span {
    pub start: usize,
    pub end: usize,
}

impl Span {
    fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    pub fn as_str<'a>(&self, input: &'a str) -> &'a str {
        &input[self.start..self.end]
    }

    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.end - self.start
    }
}

/// Parser state: tracks current position in the input.
struct Parser<'a> {
    input: &'a str,
    pos: usize,
    comments: Vec<Span>,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        Self {
            input,
            pos: 0,
            comments: Vec::new(),
        }
    }

    /// Remaining unparsed input.
    fn remaining(&self) -> &'a str {
        &self.input[self.pos..]
    }

    /// Peek at the next character without consuming.
    fn peek(&self) -> Option<char> {
        self.remaining().chars().next()
    }

    /// Consume and return the next character.
    fn advance(&mut self) -> Option<char> {
        let ch = self.peek()?;
        self.pos += ch.len_utf8();
        Some(ch)
    }

    /// Consume the next character if it matches.
    fn eat(&mut self, expected: char) -> bool {
        if self.peek() == Some(expected) {
            self.pos += expected.len_utf8();
            true
        } else {
            false
        }
    }

    /// Check if we've consumed all input.
    fn at_end(&self) -> bool {
        self.pos >= self.input.len()
    }

    /// Create an error at the current position.
    fn error(&self, kind: ErrorKind) -> Error {
        Error::new(kind, self.pos)
    }

    /// Save current position for backtracking.
    fn save(&self) -> usize {
        self.pos
    }

    /// Restore position for backtracking.
    fn restore(&mut self, pos: usize) {
        self.pos = pos;
    }
}

/// Parse an email address string according to the given strictness level.
///
/// If `allow_display_name` is true, accepts `name-addr` format: `"Name" <addr>` or `Name <addr>`.
pub(crate) fn parse(
    input: &str,
    strictness: Strictness,
    allow_display_name: bool,
    allow_domain_literal: bool,
) -> Result<Parsed<'_>, Error> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Err(Error::new(ErrorKind::Empty, 0));
    }

    let mut parser = Parser::new(trimmed);

    // Try name-addr format: display-name? "<" addr-spec ">"
    let display_name = if allow_display_name {
        try_parse_display_name(&mut parser)
    } else {
        None
    };

    let is_angle = display_name.is_some() || parser.peek() == Some('<');
    if is_angle {
        // Skip optional CFWS before <
        skip_cfws(&mut parser, 0);
        if !parser.eat('<') {
            return Err(parser.error(ErrorKind::Unexpected {
                ch: parser.peek().unwrap_or('\0'),
            }));
        }
    }

    // Parse addr-spec: local-part "@" domain
    let (local_part, local_part_clean) = parse_local_part(&mut parser, strictness)?;
    // RFC 5322 allows CFWS around "@" in Standard/Lax modes.
    if !matches!(strictness, Strictness::Strict) {
        skip_cfws(&mut parser, 0);
    }
    if !parser.eat('@') {
        return Err(parser.error(ErrorKind::MissingAtSign));
    }
    if !matches!(strictness, Strictness::Strict) {
        skip_cfws(&mut parser, 0);
    }
    let (domain, domain_clean) = parse_domain(&mut parser, strictness, allow_domain_literal)?;

    if is_angle {
        if !matches!(strictness, Strictness::Strict) {
            skip_cfws(&mut parser, 0);
        }
        if !parser.eat('>') {
            return Err(parser.error(ErrorKind::Unexpected {
                ch: parser.peek().unwrap_or('\0'),
            }));
        }
    }

    // Skip trailing CFWS (not in Strict mode — RFC 5321 forbids comments/CFWS).
    if !matches!(strictness, Strictness::Strict) {
        skip_cfws(&mut parser, 0);
    }

    if !parser.at_end() {
        let ch = parser.peek().unwrap_or('\0');
        return Err(parser.error(ErrorKind::Unexpected { ch }));
    }

    Ok(Parsed {
        input: trimmed,
        display_name,
        local_part,
        domain,
        comments: parser.comments,
        local_part_clean,
        domain_clean,
    })
}

/// Try to parse a display name before `<`. Returns None and resets position on failure.
fn try_parse_display_name(parser: &mut Parser<'_>) -> Option<Span> {
    let save = parser.save();

    // Quoted display name: "Name" <addr>
    if parser.peek() == Some('"') {
        let start = parser.pos;
        if parse_quoted_string(parser).is_err() {
            parser.restore(save);
            return None;
        }
        let end = parser.pos;
        skip_cfws(parser, 0);
        if parser.peek() == Some('<') {
            // Span excludes quotes
            return Some(Span::new(start + 1, end - 1));
        }
        parser.restore(save);
        return None;
    }

    // Unquoted display name: word+ before <
    let start = parser.pos;
    let mut found_content = false;
    loop {
        match parser.peek() {
            Some('<') if found_content => {
                // Trim trailing whitespace from display name
                let name = &parser.input[start..parser.pos];
                let trimmed_end = start + name.trim_end().len();
                return Some(Span::new(start, trimmed_end));
            }
            Some(ch) if ch == '@' || ch == '>' => {
                // Not a display name — probably bare addr-spec
                parser.restore(save);
                return None;
            }
            Some(ch) if ch < '\u{20}' && ch != '\t' => {
                // Control characters are not valid in display names.
                parser.restore(save);
                return None;
            }
            Some(_) => {
                found_content = true;
                parser.advance();
            }
            None => {
                parser.restore(save);
                return None;
            }
        }
    }
}

/// Parse local-part: dot-atom / quoted-string / obs-local-part.
///
/// Returns `(span, clean)` where `clean` is `Some(String)` when obs-local-part
/// contained CFWS that was stripped from the semantic value.
fn parse_local_part(
    parser: &mut Parser<'_>,
    strictness: Strictness,
) -> Result<(Span, Option<String>), Error> {
    let start = parser.pos;
    let allow_obs = matches!(strictness, Strictness::Lax);

    // Reject quoted-string local parts in Strict mode (RFC 5321 envelope).
    if parser.peek() == Some('"') {
        if matches!(strictness, Strictness::Strict) {
            return Err(parser.error(ErrorKind::InvalidLocalPartChar { ch: '"' }));
        }
        if !allow_obs {
            // Standard mode: quoted-string is the entire local-part.
            parse_quoted_string(parser)?;
            return Ok((Span::new(start, parser.pos), None));
        }
        // Lax mode: fall through — obs-local-part allows quoted-string as first word,
        // followed by optional "." word segments.
    }

    // dot-atom (or obs-local-part if Lax)
    let clean = parse_dot_atom_local(parser, allow_obs)?;

    let end = parser.pos;
    if end == start {
        return Err(parser.error(ErrorKind::EmptyLocalPart));
    }

    Ok((Span::new(start, end), clean))
}

/// Parse dot-atom for local-part: `atext+ ("." atext+)*`.
/// If `allow_obs` is true, allows CFWS between atoms (obs-local-part).
///
/// Returns `Some(clean)` when obs-mode CFWS was present and stripped,
/// `None` when the span is already clean (zero-copy path).
fn parse_dot_atom_local(parser: &mut Parser<'_>, allow_obs: bool) -> Result<Option<String>, Error> {
    if !allow_obs {
        // Standard mode: no CFWS between atoms, span is always clean.
        if !eat_atext_run(parser) {
            return Err(match parser.peek() {
                Some(ch) if ch != '@' => parser.error(ErrorKind::InvalidLocalPartChar { ch }),
                _ => parser.error(ErrorKind::EmptyLocalPart),
            });
        }
        loop {
            let save = parser.save();
            if !parser.eat('.') {
                parser.restore(save);
                break;
            }
            if !eat_atext_run(parser) {
                return Err(parser.error(ErrorKind::EmptyLocalPart));
            }
        }
        return Ok(None);
    }

    // Obs mode: parse atoms, building a clean string only when CFWS is present.
    // Zero allocation in the common no-CFWS path. When CFWS is first detected,
    // the contiguous prefix (all prior atoms+dots, no CFWS gaps) is copied
    // from the raw span, then subsequent atoms are appended incrementally.
    let mut clean: Option<String> = None;
    let outer_start = parser.pos;

    // First word: no leading CFWS — bare addr-spec does not permit CFWS
    // before the local-part. CFWS stripping only applies between segments.
    if !eat_atext_run(parser) && !try_quoted_string(parser) {
        return Err(match parser.peek() {
            Some(ch) if ch != '@' => parser.error(ErrorKind::InvalidLocalPartChar { ch }),
            _ => parser.error(ErrorKind::EmptyLocalPart),
        });
    }

    // Subsequent ".atom" segments
    loop {
        // `last_clean_end` marks the end of contiguous clean content before
        // any CFWS in this iteration. Used as prefix boundary if CFWS is
        // detected for the first time.
        let last_clean_end = parser.pos;
        let save = parser.save();
        let comments_len = parser.comments.len();
        skip_cfws(parser, 0);
        let had_cfws_before_dot = parser.pos > last_clean_end;
        if !parser.eat('.') {
            parser.restore(save);
            parser.comments.truncate(comments_len);
            break;
        }
        if had_cfws_before_dot && clean.is_none() {
            let mut s = String::with_capacity(last_clean_end - outer_start);
            s.push_str(&parser.input[outer_start..last_clean_end]);
            clean = Some(s);
        }
        skip_cfws(parser, 0);
        // If CFWS after dot and we haven't started clean yet, seed with
        // content before the dot — the dot is appended below via push('.').
        if clean.is_none() && parser.pos > last_clean_end + 1 {
            let mut s = String::with_capacity(last_clean_end - outer_start);
            s.push_str(&parser.input[outer_start..last_clean_end]);
            clean = Some(s);
        }
        let atom_start = parser.pos;
        if !eat_atext_run(parser) && !try_quoted_string(parser) {
            return Err(parser.error(ErrorKind::EmptyLocalPart));
        }
        if let Some(ref mut s) = clean {
            s.push('.');
            s.push_str(&parser.input[atom_start..parser.pos]);
        }
    }

    Ok(clean)
}

/// Consume one or more atext characters. Returns true if any consumed.
fn eat_atext_run(parser: &mut Parser<'_>) -> bool {
    let start = parser.pos;
    while let Some(ch) = parser.peek() {
        if is_atext(ch) {
            parser.advance();
        } else {
            break;
        }
    }
    parser.pos > start
}

/// Parse quoted-string: `"` (qtext | quoted-pair)* `"`.
fn parse_quoted_string(parser: &mut Parser<'_>) -> Result<(), Error> {
    if !parser.eat('"') {
        return Err(parser.error(ErrorKind::UnterminatedQuotedString));
    }

    loop {
        match parser.peek() {
            Some('"') => {
                parser.advance();
                return Ok(());
            }
            Some('\\') => {
                parser.advance();
                match parser.advance() {
                    Some(ch) if is_quoted_pair_char(ch) => {}
                    _ => return Err(parser.error(ErrorKind::InvalidQuotedPair)),
                }
            }
            Some(ch) if is_qtext(ch) => {
                parser.advance();
            }
            // RFC 5322 FWS: plain WSP or CRLF + WSP (folded whitespace).
            Some(ch) if is_wsp(ch) || ch == '\r' => {
                if !try_eat_fws(parser) {
                    return Err(parser.error(ErrorKind::InvalidLocalPartChar { ch: '\r' }));
                }
            }
            None => return Err(parser.error(ErrorKind::UnterminatedQuotedString)),
            Some(ch) => {
                return Err(parser.error(ErrorKind::InvalidLocalPartChar { ch }));
            }
        }
    }
}

/// Try to parse a quoted-string without error on failure.
fn try_quoted_string(parser: &mut Parser<'_>) -> bool {
    if parser.peek() != Some('"') {
        return false;
    }
    let save = parser.save();
    if parse_quoted_string(parser).is_ok() {
        true
    } else {
        parser.restore(save);
        false
    }
}

/// Parse domain: dot-atom / domain-literal / obs-domain.
///
/// Returns `(span, clean)` where `clean` is `Some(String)` when obs-domain
/// contained CFWS that was stripped from the semantic value.
fn parse_domain(
    parser: &mut Parser<'_>,
    strictness: Strictness,
    allow_domain_literal: bool,
) -> Result<(Span, Option<String>), Error> {
    let start = parser.pos;

    // Domain literal: [...]
    if parser.peek() == Some('[') {
        if !allow_domain_literal {
            return Err(parser.error(ErrorKind::InvalidDomainChar { ch: '[' }));
        }
        parse_domain_literal(parser, strictness)?;
        return Ok((Span::new(start, parser.pos), None));
    }

    // dot-atom domain
    let allow_obs = matches!(strictness, Strictness::Lax);
    let clean = parse_dot_atom_domain(parser, allow_obs)?;

    let end = parser.pos;
    if end == start {
        return Err(parser.error(ErrorKind::EmptyDomain));
    }

    Ok((Span::new(start, end), clean))
}

/// Parse dot-atom for domain: `label ("." label)*` where label avoids leading/trailing hyphen.
///
/// Returns `Some(clean)` when obs-mode CFWS was present and stripped,
/// `None` when the span is already clean (zero-copy path).
fn parse_dot_atom_domain(
    parser: &mut Parser<'_>,
    allow_obs: bool,
) -> Result<Option<String>, Error> {
    if !allow_obs {
        // Standard mode: no CFWS between labels, span is always clean.
        parse_domain_label(parser)?;
        loop {
            let save = parser.save();
            if !parser.eat('.') {
                parser.restore(save);
                break;
            }
            parse_domain_label(parser)?;
        }
        return Ok(None);
    }

    // Obs mode: parse labels, building a clean string only when CFWS is present.
    // Zero allocation in the common no-CFWS path. Same incremental strategy
    // as parse_dot_atom_local — see that function for detailed comments.
    let mut clean: Option<String> = None;
    let outer_start = parser.pos;

    parse_domain_label(parser)?;

    loop {
        let last_clean_end = parser.pos;
        let save = parser.save();
        let comments_len = parser.comments.len();
        skip_cfws(parser, 0);
        let had_cfws_before_dot = parser.pos > last_clean_end;
        if !parser.eat('.') {
            parser.restore(save);
            parser.comments.truncate(comments_len);
            break;
        }
        if had_cfws_before_dot && clean.is_none() {
            let mut s = String::with_capacity(last_clean_end - outer_start);
            s.push_str(&parser.input[outer_start..last_clean_end]);
            clean = Some(s);
        }
        skip_cfws(parser, 0);
        if clean.is_none() && parser.pos > last_clean_end + 1 {
            let mut s = String::with_capacity(last_clean_end - outer_start);
            s.push_str(&parser.input[outer_start..last_clean_end]);
            clean = Some(s);
        }
        let label_start = parser.pos;
        parse_domain_label(parser)?;
        if let Some(ref mut s) = clean {
            s.push('.');
            s.push_str(&parser.input[label_start..parser.pos]);
        }
    }

    Ok(clean)
}

/// Parse a single domain label: starts and ends with alnum, may contain hyphens.
fn parse_domain_label(parser: &mut Parser<'_>) -> Result<(), Error> {
    // First char must be alnum (or UTF-8 non-ASCII for IDN)
    match parser.peek() {
        Some(ch) if ch.is_ascii_alphanumeric() || is_utf8_non_ascii(ch) => {
            parser.advance();
        }
        Some('-') => return Err(parser.error(ErrorKind::DomainLabelHyphen)),
        _ => return Err(parser.error(ErrorKind::EmptyDomain)),
    }

    // Continue with alnum and hyphens
    let mut last_was_hyphen = false;
    while let Some(ch) = parser.peek() {
        if ch.is_ascii_alphanumeric() || is_utf8_non_ascii(ch) {
            last_was_hyphen = false;
            parser.advance();
        } else if ch == '-' {
            last_was_hyphen = true;
            parser.advance();
        } else {
            break;
        }
    }

    if last_was_hyphen {
        return Err(parser.error(ErrorKind::DomainLabelHyphen));
    }

    Ok(())
}

/// Parse domain literal: `[` dtext* `]`.
fn parse_domain_literal(parser: &mut Parser<'_>, strictness: Strictness) -> Result<(), Error> {
    if !parser.eat('[') {
        return Err(parser.error(ErrorKind::UnterminatedDomainLiteral));
    }

    loop {
        match parser.peek() {
            Some(']') => {
                parser.advance();
                return Ok(());
            }
            // obs-dtext allows quoted-pair in Lax mode.
            Some('\\') if matches!(strictness, Strictness::Lax) => {
                parser.advance();
                match parser.advance() {
                    Some(ch) if is_quoted_pair_char(ch) => {}
                    _ => return Err(parser.error(ErrorKind::InvalidQuotedPair)),
                }
            }
            Some(ch) if is_dtext(ch) => {
                parser.advance();
            }
            // RFC 5322 FWS: plain WSP or CRLF + WSP (folded whitespace).
            Some(ch) if is_wsp(ch) || ch == '\r' => {
                if !try_eat_fws(parser) {
                    return Err(parser.error(ErrorKind::InvalidDomainChar { ch: '\r' }));
                }
            }
            None => return Err(parser.error(ErrorKind::UnterminatedDomainLiteral)),
            Some(ch) => {
                return Err(parser.error(ErrorKind::InvalidDomainChar { ch }));
            }
        }
    }
}

/// Try to consume one FWS token: either plain WSP, or CRLF followed by at least one WSP.
/// Returns true if any whitespace was consumed.
fn try_eat_fws(parser: &mut Parser<'_>) -> bool {
    match parser.peek() {
        Some(ch) if is_wsp(ch) => {
            parser.advance();
            // Consume any additional WSP
            while let Some(ch) = parser.peek() {
                if is_wsp(ch) {
                    parser.advance();
                } else {
                    break;
                }
            }
            true
        }
        Some('\r') => {
            let pos = parser.pos;
            let bytes = parser.input.as_bytes();
            if pos + 2 < bytes.len()
                && bytes[pos] == b'\r'
                && bytes[pos + 1] == b'\n'
                && (bytes[pos + 2] == b' ' || bytes[pos + 2] == b'\t')
            {
                parser.advance(); // '\r'
                parser.advance(); // '\n'
                while let Some(ch) = parser.peek() {
                    if is_wsp(ch) {
                        parser.advance();
                    } else {
                        break;
                    }
                }
                true
            } else {
                false
            }
        }
        _ => false,
    }
}

/// Skip CFWS (comments and folding whitespace).
fn skip_cfws(parser: &mut Parser<'_>, depth: usize) {
    if depth >= MAX_RECURSION_DEPTH {
        return;
    }
    loop {
        // Skip whitespace and RFC 5322 Folding White Space (CRLF + WSP).
        loop {
            match parser.peek() {
                // Regular WSP (space / tab)
                Some(ch) if is_wsp(ch) => {
                    parser.advance();
                }
                // Potential FWS: CRLF followed by WSP
                Some('\r') => {
                    let pos = parser.pos;
                    let bytes = parser.input.as_bytes();
                    // Check for CRLF + WSP as per RFC 5322 FWS
                    if pos + 2 < bytes.len()
                        && bytes[pos] == b'\r'
                        && bytes[pos + 1] == b'\n'
                        && (bytes[pos + 2] == b' ' || bytes[pos + 2] == b'\t')
                    {
                        // Consume CRLF
                        parser.advance(); // '\r'
                        parser.advance(); // '\n', then consume following WSP
                        while let Some(wch) = parser.peek() {
                            if is_wsp(wch) {
                                parser.advance();
                            } else {
                                break;
                            }
                        }
                    } else {
                        // Bare CR is not valid FWS; stop treating as CFWS here.
                        break;
                    }
                }
                // Bare LF is not valid FWS; stop here.
                Some('\n') => {
                    break;
                }
                _ => break,
            }
        }
        // Try comment
        if parser.peek() == Some('(') {
            let comment_start = parser.pos;
            match parse_comment(parser, depth) {
                Ok(()) => {
                    parser.comments.push(Span::new(comment_start, parser.pos));
                    continue;
                }
                Err(_) => {
                    // Intentionally swallowing comment parse errors here.
                    // skip_cfws is called in contexts where '(' may not start a comment
                    // (e.g., trailing garbage after addr-spec). Propagating the error
                    // would mask the real issue. Instead, restore position and let the
                    // caller produce a context-appropriate error (Unexpected, MissingAtSign, etc.).
                    parser.pos = comment_start;
                    break;
                }
            }
        }
        break;
    }
}

/// Parse a comment: `(` ccontent* `)`.
fn parse_comment(parser: &mut Parser<'_>, depth: usize) -> Result<(), Error> {
    if depth >= MAX_RECURSION_DEPTH || !parser.eat('(') {
        return Err(parser.error(ErrorKind::UnterminatedComment));
    }

    loop {
        match parser.peek() {
            Some(')') => {
                parser.advance();
                return Ok(());
            }
            Some('(') => {
                // Nested comment
                parse_comment(parser, depth + 1)?;
            }
            Some('\\') => {
                parser.advance();
                match parser.advance() {
                    Some(ch) if is_quoted_pair_char(ch) => {}
                    _ => return Err(parser.error(ErrorKind::InvalidQuotedPair)),
                }
            }
            Some(ch) if is_ctext(ch) || is_wsp(ch) => {
                parser.advance();
            }
            None => return Err(parser.error(ErrorKind::UnterminatedComment)),
            Some(_) => {
                parser.advance(); // be lenient in comments
            }
        }
    }
}

// ── Character class predicates (RFC 5322 §3.2.3 + RFC 6531) ──

/// atext: ALPHA / DIGIT / special chars / UTF-8 non-ASCII.
fn is_atext(ch: char) -> bool {
    ch.is_ascii_alphanumeric()
        || is_utf8_non_ascii(ch)
        || matches!(
            ch,
            '!' | '#'
                | '$'
                | '%'
                | '&'
                | '\''
                | '*'
                | '+'
                | '-'
                | '/'
                | '='
                | '?'
                | '^'
                | '_'
                | '`'
                | '{'
                | '|'
                | '}'
                | '~'
        )
}

/// qtext: printable ASCII except `"` and `\`, plus UTF-8 non-ASCII.
fn is_qtext(ch: char) -> bool {
    ch != '"' && ch != '\\' && (is_printable_ascii(ch) || is_utf8_non_ascii(ch))
}

/// ctext: printable ASCII except `(`, `)`, `\`, plus UTF-8 non-ASCII.
fn is_ctext(ch: char) -> bool {
    ch != '(' && ch != ')' && ch != '\\' && (is_printable_ascii(ch) || is_utf8_non_ascii(ch))
}

/// dtext: printable ASCII except `[`, `]`, `\`, plus UTF-8 non-ASCII.
fn is_dtext(ch: char) -> bool {
    ch != '[' && ch != ']' && ch != '\\' && (is_printable_ascii(ch) || is_utf8_non_ascii(ch))
}

/// Characters valid in a quoted-pair after `\`.
fn is_quoted_pair_char(ch: char) -> bool {
    is_printable_ascii(ch) || is_wsp(ch) || is_utf8_non_ascii(ch)
}

fn is_printable_ascii(ch: char) -> bool {
    matches!(ch as u32, 0x21..=0x7e)
}

fn is_utf8_non_ascii(ch: char) -> bool {
    (ch as u32) >= 0x80
}

fn is_wsp(ch: char) -> bool {
    ch == ' ' || ch == '\t'
}

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

    fn parse_ok(input: &str) -> Parsed<'_> {
        parse(input, Strictness::Standard, false, false)
            .unwrap_or_else(|e| panic!("failed to parse '{input}': {e}"))
    }

    fn parse_ok_lax(input: &str) -> Parsed<'_> {
        parse(input, Strictness::Lax, false, false)
            .unwrap_or_else(|e| panic!("failed to parse '{input}': {e}"))
    }

    fn parse_err(input: &str) -> Error {
        parse(input, Strictness::Standard, false, false)
            .expect_err(&format!("expected error for '{input}'"))
    }

    // ── Basic valid addresses ──

    #[test]
    fn simple_address() {
        let p = parse_ok("user@example.com");
        assert_eq!(p.local_part.as_str(p.input), "user");
        assert_eq!(p.domain.as_str(p.input), "example.com");
    }

    #[test]
    fn subaddress_preserved() {
        let p = parse_ok("user+tag@example.com");
        assert_eq!(p.local_part.as_str(p.input), "user+tag");
    }

    #[test]
    fn dotted_local() {
        let p = parse_ok("first.last@example.com");
        assert_eq!(p.local_part.as_str(p.input), "first.last");
    }

    #[test]
    fn utf8_local() {
        let p = parse_ok("дмитрий@example.com");
        assert_eq!(p.local_part.as_str(p.input), "дмитрий");
    }

    #[test]
    fn utf8_domain() {
        let p = parse_ok("user@münchen.de");
        assert_eq!(p.domain.as_str(p.input), "münchen.de");
    }

    #[test]
    fn quoted_local_part() {
        let p = parse_ok("\"user@name\"@example.com");
        assert_eq!(p.local_part.as_str(p.input), "\"user@name\"");
    }

    #[test]
    fn quoted_local_with_spaces() {
        let p = parse_ok("\"user name\"@example.com");
        assert_eq!(p.local_part.as_str(p.input), "\"user name\"");
    }

    // ── Invalid addresses ──

    #[test]
    fn empty_input() {
        let e = parse_err("");
        assert_eq!(e.kind(), &ErrorKind::Empty);
    }

    #[test]
    fn no_at_sign() {
        let e = parse_err("userexample.com");
        assert_eq!(e.kind(), &ErrorKind::MissingAtSign);
    }

    #[test]
    fn empty_local() {
        let e = parse_err("@example.com");
        assert_eq!(e.kind(), &ErrorKind::EmptyLocalPart);
    }

    #[test]
    fn empty_domain() {
        let e = parse_err("user@");
        assert_eq!(e.kind(), &ErrorKind::EmptyDomain);
    }

    // ── Dot-atom edge cases ──

    #[test]
    fn trailing_dot_in_local_part_is_not_missing_at_sign() {
        let e = parse_err("user.@example.com");
        // Ensure this is treated as a local-part syntax error, not as a missing '@'.
        assert_ne!(e.kind(), &ErrorKind::MissingAtSign);
    }

    #[test]
    fn obs_local_part_quoted_first_word() {
        // obs-local-part: word *("." word), where word can be quoted-string.
        // "a".b@example.com must parse in Lax mode.
        let p = parse("\"a\".b@example.com", Strictness::Lax, false, false).unwrap_or_else(|e| {
            panic!("Lax must accept obs-local-part starting with quoted word: {e}")
        });
        assert_eq!(p.local_part.as_str(p.input), "\"a\".b");
        assert_eq!(p.domain.as_str(p.input), "example.com");
    }

    #[test]
    fn obs_local_part_rejected_in_standard() {
        let e = parse("a.\"b\"@example.com", Strictness::Standard, false, false)
            .expect_err("expected obs-local-part to be rejected in Standard strictness");
        // Should fail due to local-part syntax, not due to a missing '@'.
        assert_ne!(e.kind(), &ErrorKind::MissingAtSign);
    }

    #[test]
    fn obs_local_part_accepted_in_lax() {
        let p = parse("a.\"b\"@example.com", Strictness::Lax, false, false)
            .unwrap_or_else(|e| panic!("parse failed in Lax strictness: {e}"));
        assert_eq!(p.local_part.as_str(p.input), "a.\"b\"");
        assert_eq!(p.domain.as_str(p.input), "example.com");
    }

    // ── Display name ──

    #[test]
    fn display_name_angle() {
        let p = parse(
            "John Doe <user@example.com>",
            Strictness::Standard,
            true,
            false,
        )
        .unwrap_or_else(|e| panic!("parse failed: {e}"));
        assert_eq!(p.display_name.map(|s| s.as_str(p.input)), Some("John Doe"));
        assert_eq!(p.local_part.as_str(p.input), "user");
        assert_eq!(p.domain.as_str(p.input), "example.com");
    }

    #[test]
    fn quoted_display_name() {
        let p = parse(
            "\"John Doe\" <user@example.com>",
            Strictness::Standard,
            true,
            false,
        )
        .unwrap_or_else(|e| panic!("parse failed: {e}"));
        assert_eq!(p.display_name.map(|s| s.as_str(p.input)), Some("John Doe"));
    }

    // ── Domain literal ──

    #[test]
    fn domain_literal_allowed() {
        let p = parse("user@[192.168.1.1]", Strictness::Standard, false, true)
            .unwrap_or_else(|e| panic!("parse failed: {e}"));
        assert_eq!(p.domain.as_str(p.input), "[192.168.1.1]");
    }

    #[test]
    fn trailing_dot_in_domain_gives_domain_error() {
        // "user@example." — once '.' is consumed, error should be domain-specific.
        let e = parse_err("user@example.");
        assert!(
            matches!(e.kind(), ErrorKind::EmptyDomain),
            "expected EmptyDomain, got {:?}",
            e.kind()
        );
    }

    #[test]
    fn consecutive_dots_in_domain_gives_domain_error() {
        let e = parse_err("user@example..com");
        assert!(
            matches!(e.kind(), ErrorKind::EmptyDomain),
            "expected EmptyDomain, got {:?}",
            e.kind()
        );
    }

    #[test]
    fn strict_rejects_trailing_comment() {
        // RFC 5321 Strict mode must not accept trailing comments/CFWS.
        let e = parse(
            "user@example.com (comment)",
            Strictness::Strict,
            false,
            false,
        )
        .expect_err("Strict mode must reject trailing comment");
        assert!(matches!(e.kind(), ErrorKind::Unexpected { .. }));
    }

    #[test]
    fn strict_rejects_trailing_cfws_in_angle() {
        // Trailing CFWS between domain and '>' in Strict mode.
        let e = parse(
            "<user@example.com (comment)>",
            Strictness::Strict,
            false,
            false,
        )
        .expect_err("Strict mode must reject CFWS before closing angle bracket");
        assert!(matches!(e.kind(), ErrorKind::Unexpected { .. }));
    }

    #[test]
    fn strict_rejects_quoted_local_part() {
        // RFC 5321 Strict mode must reject quoted-string local parts.
        let e = parse("\"quoted\"@example.com", Strictness::Strict, false, false)
            .expect_err("Strict mode must reject quoted-string local part");
        assert_eq!(e.kind(), &ErrorKind::InvalidLocalPartChar { ch: '"' });
    }

    #[test]
    fn strict_rejects_leading_comment() {
        // RFC 5321 Strict mode must reject leading comments/CFWS.
        let e = parse(
            "(comment)user@example.com",
            Strictness::Strict,
            false,
            false,
        )
        .expect_err("Strict mode must reject leading comment");
        // Leading `(` is not valid atext — parser reports the offending char.
        assert_eq!(e.kind(), &ErrorKind::InvalidLocalPartChar { ch: '(' });
    }

    #[test]
    fn standard_accepts_quoted_string_and_comments() {
        // Standard mode (RFC 5322) must accept quoted-string local parts.
        let p = parse("\"quoted\"@example.com", Strictness::Standard, false, false)
            .unwrap_or_else(|e| panic!("Standard must accept quoted-string: {e}"));
        assert_eq!(p.local_part.as_str(p.input), "\"quoted\"");
        assert_eq!(p.domain.as_str(p.input), "example.com");

        // Standard mode must accept trailing comments.
        let p = parse(
            "user@example.com (comment)",
            Strictness::Standard,
            false,
            false,
        )
        .unwrap_or_else(|e| panic!("Standard must accept trailing comment: {e}"));
        assert_eq!(p.local_part.as_str(p.input), "user");
        assert_eq!(p.domain.as_str(p.input), "example.com");
    }

    #[test]
    fn domain_literal_rejected_by_default() {
        let e = parse("user@[192.168.1.1]", Strictness::Standard, false, false)
            .expect_err("expected error");
        assert_eq!(e.kind(), &ErrorKind::InvalidDomainChar { ch: '[' });
    }

    // ── Regression tests for #13: CFWS stripping in obs-local-part / obs-domain ──

    #[test]
    fn obs_local_part_cfws_comment_stripped() {
        // obs-local-part with comment between atoms: span must not include CFWS.
        let p = parse_ok_lax("user (comment) . name@example.com");
        assert_eq!(
            p.local_part_str(),
            "user.name",
            "CFWS comment must be stripped from obs-local-part"
        );
    }

    #[test]
    fn obs_local_part_whitespace_stripped() {
        // obs-local-part with plain whitespace between atoms.
        let p = parse_ok_lax("user . name@example.com");
        assert_eq!(
            p.local_part_str(),
            "user.name",
            "whitespace must be stripped from obs-local-part"
        );
    }

    #[test]
    fn obs_domain_cfws_comment_stripped() {
        // obs-domain with comment between labels: span must not include CFWS.
        let p = parse_ok_lax("user@example (comment) . com");
        assert_eq!(
            p.domain_str(),
            "example.com",
            "CFWS comment must be stripped from obs-domain"
        );
    }

    #[test]
    fn obs_domain_whitespace_stripped() {
        // obs-domain with plain whitespace between labels.
        let p = parse_ok_lax("user@example . com");
        assert_eq!(
            p.domain_str(),
            "example.com",
            "whitespace must be stripped from obs-domain"
        );
    }

    #[test]
    fn obs_local_no_cfws_zero_copy() {
        // obs-local-part without CFWS: clean field is None (zero-copy path).
        let p = parse_ok_lax("user.name@example.com");
        assert!(
            p.local_part_clean.is_none(),
            "no CFWS → local_part_clean must be None (zero-copy)"
        );
        assert_eq!(p.local_part_str(), "user.name");
    }

    #[test]
    fn obs_domain_no_cfws_zero_copy() {
        // obs-domain without CFWS: clean field is None (zero-copy path).
        let p = parse_ok_lax("user@example.com");
        assert!(
            p.domain_clean.is_none(),
            "no CFWS → domain_clean must be None (zero-copy)"
        );
        assert_eq!(p.domain_str(), "example.com");
    }

    #[test]
    fn obs_local_part_multiple_comments_stripped() {
        // Multiple CFWS segments between atoms.
        let p = parse_ok_lax("a (c1) . b (c2) . c@example.com");
        assert_eq!(p.local_part_str(), "a.b.c");
    }

    #[test]
    fn obs_leading_comment_rejected_in_bare_addr_spec() {
        // Leading RFC 5322 comments before local-part are rejected in bare
        // addr-spec. Note: leading plain whitespace is handled by input.trim()
        // before parsing, so this test covers comments specifically.
        let e = parse(
            "(leading) user . name@example.com",
            Strictness::Lax,
            false,
            false,
        )
        .expect_err("leading comment in bare addr-spec must be rejected");
        assert_eq!(e.kind(), &ErrorKind::InvalidLocalPartChar { ch: '(' });
    }

    #[test]
    fn obs_local_cfws_after_dot_no_double_dots() {
        // CFWS only after dot: "user. name" must produce "user.name", not "user..name".
        let p = parse_ok_lax("user. name@example.com");
        assert_eq!(p.local_part_str(), "user.name");
    }

    #[test]
    fn obs_domain_cfws_after_dot_no_double_dots() {
        // CFWS only after dot: "example. com" must produce "example.com", not "example..com".
        let p = parse_ok_lax("user@example. com");
        assert_eq!(p.domain_str(), "example.com");
    }

    #[test]
    fn obs_trailing_cfws_before_at_preserves_zero_copy() {
        // Trailing CFWS before '@' is NOT between atoms — it's excluded from
        // the span by backtracking. Must not trigger allocation or duplicate
        // comment spans.
        let p = parse_ok_lax("user (trailing)@example.com");
        assert!(
            p.local_part_clean.is_none(),
            "trailing CFWS before @ must not trigger allocation"
        );
        assert_eq!(p.local_part_str(), "user");
        assert_eq!(
            p.comments.len(),
            1,
            "backtracked comment must not be duplicated"
        );
    }

    #[test]
    fn obs_trailing_cfws_after_domain_preserves_zero_copy() {
        // Trailing CFWS after domain is NOT between labels — must not allocate
        // or duplicate comment spans.
        let p = parse_ok_lax("user@example.com (trailing)");
        assert!(
            p.domain_clean.is_none(),
            "trailing CFWS after domain must not trigger allocation"
        );
        assert_eq!(p.domain_str(), "example.com");
        assert_eq!(
            p.comments.len(),
            1,
            "backtracked comment must not be duplicated"
        );
    }
}