edtf-normalize 1.1.0

Deterministic prose-date to EDTF normalizer (English and Russian): '1980s' -> 198X, 'circa 1920' -> 1920~. Honest ambiguity, no silent guesses. no_std, zero dependencies.
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
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
//! The language-neutral pattern grammar: preprocessing, qualifier stripping,
//! and the ordered match arms. Everything language-specific comes in through
//! a [`Lang`] table set. Whole-input only — no substring extraction (N11);
//! anything unmatched is `NoMatch`, never a guess.
//!
//! Values are built through the `edtf_core` model and rendered via its
//! canonical `Display`, then re-parsed before being returned ([`render`]).
//! Core has no validating constructors, so the re-parse is the calendar
//! check (it rejects e.g. a constructed February 31) and the proof that
//! every output is valid EDTF.

use alloc::{
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};

use edtf_core::{Date, DateField, Edtf, Interval, IntervalEndpoint, Qualifier, Year, YearKind};

use crate::{
    Ambiguous, Interpretation, NoMatchReason, Normalized, Note, NumericOrder, Options, Outcome,
    tables::{Lang, Span, lang_for, season_name},
};

// ---------------------------------------------------------------------------
// Internal shapes

/// A matched expression before qualification and rendering.
#[derive(Debug, Clone, Copy)]
enum Expr {
    Date(Date),
    Interval(Interval),
}

/// One reading of an ambiguous input.
#[derive(Debug, Clone)]
struct Candidate {
    expr: Expr,
    reading: String,
    notes: Vec<Note>,
}

/// Result of the single-expression grammar.
#[derive(Debug, Clone)]
enum Single {
    One(Expr, Vec<Note>),
    Many(Vec<Candidate>),
}

// ---------------------------------------------------------------------------
// Construction helpers (core's fields are public; there are no constructors)

/// Single decimal digit as `u8`.
#[allow(
    clippy::cast_possible_truncation,
    reason = "callers reduce mod 10 (or divide down to one digit): always < 10"
)]
const fn digit(v: u32) -> u8 {
    (v % 10) as u8
}

fn quiet(v: u8) -> DateField {
    DateField {
        digits: [Some(digit(u32::from(v) / 10)), Some(digit(u32::from(v)))],
        qualifier: Qualifier::default(),
    }
}

fn year_of(y: i32) -> Option<Year> {
    if !(-9999..=9999).contains(&y) {
        return None;
    }
    let a = y.unsigned_abs();
    Some(Year {
        kind: YearKind::Standard {
            negative: y < 0,
            digits: [
                Some(digit(a / 1000)),
                Some(digit(a / 100)),
                Some(digit(a / 10)),
                Some(digit(a)),
            ],
        },
        significant_digits: None,
        qualifier: Qualifier::default(),
    })
}

fn date_y(y: i32) -> Option<Date> {
    Some(Date {
        year: year_of(y)?,
        month: None,
        day: None,
    })
}

fn date_ym(y: i32, m: u8) -> Option<Date> {
    Some(Date {
        month: Some(quiet(m)),
        ..date_y(y)?
    })
}

fn date_ymd(y: i32, m: u8, d: u8) -> Option<Date> {
    Some(Date {
        day: Some(quiet(d)),
        ..date_ym(y, m)?
    })
}

/// `XXXX` year for the missing-year forms (N9).
fn masked_year() -> Year {
    Year {
        kind: YearKind::Standard {
            negative: false,
            digits: [None; 4],
        },
        significant_digits: None,
        qualifier: Qualifier::default(),
    }
}

/// `198X` from the three leading digits (198).
fn decade_date(prefix3: u16) -> Date {
    Date {
        year: Year {
            kind: YearKind::Standard {
                negative: false,
                digits: [
                    Some(digit(u32::from(prefix3) / 100)),
                    Some(digit(u32::from(prefix3) / 10)),
                    Some(digit(u32::from(prefix3))),
                    None,
                ],
            },
            significant_digits: None,
            qualifier: Qualifier::default(),
        },
        month: None,
        day: None,
    }
}

/// `18XX` (or `-01XX`) from the two leading digits.
fn century_date(prefix2: u8, negative: bool) -> Date {
    Date {
        year: Year {
            kind: YearKind::Standard {
                negative,
                digits: [Some(prefix2 / 10), Some(prefix2 % 10), None, None],
            },
            significant_digits: None,
            qualifier: Qualifier::default(),
        },
        month: None,
        day: None,
    }
}

const fn interval(a: Date, b: Date) -> Expr {
    Expr::Interval(Interval {
        start: IntervalEndpoint::Date(a),
        end: IntervalEndpoint::Date(b),
    })
}

// ---------------------------------------------------------------------------
// Token classifiers

fn num(s: &str) -> Option<u32> {
    if s.is_empty() || s.len() > 5 || !s.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    s.parse().ok()
}

fn strip_dot(t: &str) -> &str {
    t.trim_end_matches('.')
}

/// Compare a token to a dotless table word, ignoring '.' in the token
/// ("н.э." matches "нэ", "b.c." matches "bc").
fn eq_dotless(token: &str, word: &str) -> bool {
    let mut w = word.chars();
    for c in token.chars() {
        if c == '.' {
            continue;
        }
        if w.next() != Some(c) {
            return false;
        }
    }
    w.next().is_none()
}

fn table_u8(t: &str, table: &[(&str, u8)]) -> Option<u8> {
    let t = strip_dot(t);
    table.iter().find(|(n, _)| *n == t).map(|&(_, v)| v)
}

/// "19", "19th", "19-й", or "nineteenth" as a cardinal.
fn ordinal_num(t: &str, lang: &Lang) -> Option<u32> {
    if let Some(v) = num(t) {
        return Some(v);
    }
    for suffix in lang.ordinal_suffixes {
        if let Some(v) = t.strip_suffix(suffix).and_then(num) {
            return Some(v);
        }
    }
    lang.ordinal_words
        .iter()
        .find(|(w, _)| *w == t)
        .map(|&(_, v)| v)
}

/// Roman numeral 1–99 ("xix" → 19), tolerating Cyrillic lookalike letters —
/// real Russian sources routinely type "ХІХ век" with Cyrillic Х.
fn roman_num(t: &str) -> Option<u32> {
    let mut vals = Vec::new();
    for c in t.chars() {
        vals.push(match c {
            'i' | '\u{456}' => 1, // і (Cyrillic/Ukrainian i)
            'v' => 5,
            'x' | '\u{445}' => 10,   // х
            'l' | '\u{43b}' => 50,   // л
            'c' | '\u{441}' => 100,  // с
            'd' | '\u{434}' => 500,  // д
            'm' | '\u{43c}' => 1000, // м
            _ => return None,
        });
    }
    // Signed accumulation: numerals STARTING with a subtractive pair (IV,
    // IX, XL, XC) go negative on the first symbol and recover on the next.
    let mut total: i64 = 0;
    for (i, &v) in vals.iter().enumerate() {
        if vals[i + 1..].iter().any(|&n| n > v) {
            total -= i64::from(v);
        } else {
            total += i64::from(v);
        }
    }
    u32::try_from(total).ok().filter(|t| (1..=99).contains(t))
}

/// Ordinal in century position: digits, suffixed digits, ordinal words, and
/// Roman numerals where the language uses them. The bool records the
/// Roman-numeral provenance (surfaced as `Note::RomanCentury`, N15).
fn century_ordinal(t: &str, lang: &Lang) -> Option<(u32, bool)> {
    if let Some(n) = ordinal_num(t, lang) {
        return Some((n, false));
    }
    if lang.roman_centuries {
        return Some((roman_num(t)?, true));
    }
    None
}

/// Day-of-month token: 1–2 digits with optional ordinal suffix.
fn day_num(t: &str, lang: &Lang) -> Option<u8> {
    let digits = lang
        .ordinal_suffixes
        .iter()
        .find_map(|s| t.strip_suffix(s))
        .unwrap_or(t);
    if digits.len() > 2 {
        return None;
    }
    let v = num(digits)?;
    u8::try_from(v).ok().filter(|d| (1..=31).contains(d))
}

/// Year token: 3–4 digits, nonzero.
fn year_num(t: &str) -> Option<i32> {
    if t.len() < 3 || t.len() > 4 {
        return None;
    }
    let v = num(t)?;
    (v >= 1).then(|| i32::try_from(v).ok())?
}

// ---------------------------------------------------------------------------
// Preprocessing and qualifier stripping

/// Lowercase, unify dashes/apostrophes, drop commas, collapse whitespace.
fn preprocess(input: &str) -> String {
    let mut s = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '\u{2013}' | '\u{2014}' => s.push('-'),
            '\u{2019}' => s.push('\''),
            ',' => s.push(' '),
            c => s.extend(c.to_lowercase()),
        }
    }
    let mut out = String::with_capacity(s.len());
    for tok in s.split_whitespace() {
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(tok);
    }
    out
}

/// Strip leading noise ("the", "в"), trailing noise ("гг.", "года"), leading
/// and trailing qualifier words, and attached approximate prefixes ("c1860",
/// "ок.1920"). Returns the remainder and the accumulated whole-expression
/// qualifier (N10).
fn strip_qualifiers(s: &str, lang: &Lang) -> (String, Qualifier) {
    let mut toks: Vec<&str> = s.split(' ').filter(|t| !t.is_empty()).collect();
    let mut q = Qualifier::default();
    'outer: loop {
        if toks.len() > 1 {
            let head = strip_dot(toks[0].trim_end_matches(':'));
            if lang.noise_leading.contains(&head) {
                toks.remove(0);
                continue;
            }
            if lang.approx_leading.contains(&head) {
                q.approximate = true;
                toks.remove(0);
                continue;
            }
            if lang.uncertain_leading.contains(&head) {
                q.uncertain = true;
                toks.remove(0);
                continue;
            }
        }
        if let Some(&t0) = toks.first() {
            for p in lang.approx_attached {
                if let Some(rest) = t0.strip_prefix(p) {
                    if rest.starts_with(|c: char| c.is_ascii_digit()) {
                        q.approximate = true;
                        toks[0] = rest;
                        continue 'outer;
                    }
                }
            }
        }
        if toks.len() > 1 {
            let tail = strip_dot(toks[toks.len() - 1]);
            if lang.noise_trailing.contains(&tail) {
                toks.pop();
                continue;
            }
            if lang.approx_trailing.contains(&tail) {
                q.approximate = true;
                toks.pop();
                continue;
            }
            if lang.uncertain_trailing.contains(&tail) {
                q.uncertain = true;
                toks.pop();
                continue;
            }
        }
        break;
    }
    (toks.join(" "), q)
}

// ---------------------------------------------------------------------------
// Eras

/// Split a trailing era phrase ("bc", "до н. э.") off the token list.
/// `Some(true)` = BC. Table order is longest-first, so "до н э" wins
/// over "н э".
fn split_era<'a>(toks: &[&'a str], lang: &Lang) -> Option<(bool, Vec<&'a str>)> {
    for (phrase, bc) in lang.eras {
        if toks.len() > phrase.len() {
            let tail = &toks[toks.len() - phrase.len()..];
            if tail.iter().zip(*phrase).all(|(t, w)| eq_dotless(t, w)) {
                return Some((*bc, toks[..toks.len() - phrase.len()].to_vec()));
            }
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Decades

#[derive(Clone, Copy)]
enum DecadeParse {
    /// "1860s", "1980-е" — three leading digits fixed.
    Exact(u16),
    /// "1900s" — decade `190X` or century `19XX` (N6).
    CenturyAmbig(u16, u8),
    /// "80s", "80-е" — tens digit only; century unknown (N6).
    Bare(u8),
}

fn decade_tok(t: &str, lang: &Lang) -> Option<DecadeParse> {
    let t = t.strip_prefix('\'').unwrap_or(t);
    let digits = lang
        .decade_suffixes
        .iter()
        .find_map(|s| t.strip_suffix(s))?;
    let v = num(digits)?;
    if v % 10 != 0 {
        return None;
    }
    match digits.len() {
        4 => {
            let prefix3 = u16::try_from(v / 10).ok()?;
            if v % 100 == 0 {
                Some(DecadeParse::CenturyAmbig(
                    prefix3,
                    u8::try_from(v / 100).ok()?,
                ))
            } else {
                Some(DecadeParse::Exact(prefix3))
            }
        },
        2 => Some(DecadeParse::Bare(u8::try_from(v / 10).ok()?)),
        _ => None,
    }
}

fn decade_single(parse: DecadeParse, opts: Options) -> Single {
    match parse {
        DecadeParse::Exact(p3) => Single::One(Expr::Date(decade_date(p3)), Vec::new()),
        DecadeParse::CenturyAmbig(p3, p2) => Single::Many(vec![
            Candidate {
                expr: Expr::Date(decade_date(p3)),
                reading: format!("decade ({p3}X)"),
                notes: vec![Note::DecadeAmbiguity],
            },
            Candidate {
                expr: Expr::Date(century_date(p2, false)),
                reading: format!("century ({p2}XX)"),
                notes: vec![Note::DecadeAmbiguity],
            },
        ]),
        DecadeParse::Bare(tens) => {
            // Domain 0..=9999 (documented on Options); larger values would
            // build unrenderable years, so they are ignored as if unset.
            opts.default_century.filter(|c| *c <= 9999).map_or_else(
                || {
                    let mk = |p3: u16| Candidate {
                        expr: Expr::Date(decade_date(p3)),
                        reading: format!("the {p3}0s"),
                        notes: vec![Note::DecadeAmbiguity],
                    };
                    Single::Many(vec![mk(180 + u16::from(tens)), mk(190 + u16::from(tens))])
                },
                |century| {
                    let p3 = century / 100 * 10 + u16::from(tens);
                    Single::One(
                        Expr::Date(decade_date(p3)),
                        vec![Note::DefaultCenturyApplied],
                    )
                },
            )
        },
    }
}

// ---------------------------------------------------------------------------
// Centuries

/// "19th century", "19c", "XIX век", bare "xix" (Roman-numeral languages
/// only) → century number, plus the Roman-numeral provenance flag (N15).
/// Era is split off by the caller.
fn century_toks(toks: &[&str], lang: &Lang) -> Option<(u32, bool)> {
    let word = |t: &str| lang.century_words.contains(&strip_dot(t));
    // Attached single-letter century word: "19c", "19в".
    let attached = |t: &str| -> Option<(u32, bool)> {
        let t = strip_dot(t);
        let d = lang
            .century_words
            .iter()
            .filter(|w| w.chars().count() == 1)
            .find_map(|w| t.strip_suffix(w))?;
        century_ordinal(d, lang)
    };
    let (n, roman) = match toks {
        [t] => attached(t).or_else(|| {
            // A bare Roman numeral reads as a century where the language
            // writes centuries that way ("XIX—XX вв." endpoints) — but a
            // lone letter with no century word is too weak a signal.
            (lang.roman_centuries && t.chars().count() >= 2)
                .then(|| roman_num(t).map(|n| (n, true)))
                .flatten()
        })?,
        [o, w] if word(w) => century_ordinal(o, lang)?,
        _ => return None,
    };
    (1..=99).contains(&n).then_some((n, roman))
}

/// Astronomical year span of century `n`: 19th CE = 1801..=1900,
/// 2nd BC = -0199..=-0100, 1st BC = -0099..=0000 (year 0 exists; N2/N3).
#[allow(
    clippy::cast_possible_wrap,
    reason = "n <= 99 (century_ordinal range filter); i32::try_from is not usable in const fn"
)]
const fn century_span(n: u32, bc: bool) -> (i32, i32) {
    let n = n as i32;
    if bc {
        (-(100 * n - 1), -(100 * (n - 1)))
    } else {
        (100 * (n - 1) + 1, 100 * n)
    }
}

/// Whole century as a date/interval expression (masked when possible).
fn century_expr(n: u32, bc: bool) -> Option<(Expr, Vec<Note>)> {
    if bc {
        // edtf-core rejects unspecified digits in negative years (Annex A's
        // mask shapes are positive-only), and the 1st century BC would need
        // year -0000 anyway — BC centuries are exact intervals, and the
        // CenturyMask note would be a lie for them (N2).
        let notes = vec![Note::AstronomicalYear, Note::BcCenturyInterval];
        let (s, e) = century_span(n, true);
        return Some((interval(date_y(s)?, date_y(e)?), notes));
    }
    let prefix2 = u8::try_from(n - 1).ok()?;
    Some((
        Expr::Date(century_date(prefix2, bc)),
        vec![Note::CenturyMask],
    ))
}

/// Early/mid/late/half of a century as a decade-rounded interval (N1).
#[allow(
    clippy::many_single_char_names,
    reason = "s/e/a/b are interval-endpoint arithmetic; longer names obscure the span algebra"
)]
fn century_part_expr(span: Span, n: u32, bc: bool) -> Option<(Expr, Vec<Note>)> {
    let (s, e) = century_span(n, bc);
    let (a, b) = match span {
        Span::Early => (s, s + 29),
        Span::Mid => (s + 30, s + 69),
        Span::Late => (s + 70, e),
        Span::FirstHalf => (s, s + 49),
        Span::SecondHalf => (s + 50, e),
    };
    let mut notes = vec![Note::CenturyPartInterval];
    if bc {
        notes.push(Note::AstronomicalYear);
    }
    Some((interval(date_y(a)?, date_y(b)?), notes))
}

// ---------------------------------------------------------------------------
// Numeric tokens ("12/04/1985", "1914-1918", "7/2008", "1914-18")

fn numeric_sep(t: &str) -> Option<char> {
    let mut sep = None;
    for c in ['/', '-', '.'] {
        if t.contains(c) {
            if sep.is_some() {
                return None; // mixed separators
            }
            sep = Some(c);
        }
    }
    sep
}

fn dmy(d: u32, m: u32, y: i32) -> Option<Expr> {
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    let (m, d) = (u8::try_from(m).ok()?, u8::try_from(d).ok()?);
    Some(Expr::Date(date_ymd(y, m, d)?))
}

#[allow(
    clippy::many_single_char_names,
    clippy::too_many_lines,
    reason = "y/m/d/a/b are date-field names; the arms ARE the grammar"
)]
fn numeric_token(t: &str, opts: Options, lang: &Lang) -> Option<Single> {
    let sep = numeric_sep(t)?;
    let parts: Vec<&str> = t.split(sep).collect();
    let vals: Vec<u32> = parts.iter().map(|p| num(p)).collect::<Option<_>>()?;
    match (parts.as_slice(), vals.as_slice()) {
        // Year first is order-unambiguous: 1985/04/12.
        ([py, _, _], &[y, m, d]) if py.len() == 4 => Some(Single::One(
            dmy(d, m, i32::try_from(y).ok()?)?,
            vec![Note::NumericUnambiguous],
        )),
        // Two small fields then a 4-digit year: the DMY/MDY minefield (N5).
        ([pa, pb, py], &[a, b, y]) if py.len() == 4 && pa.len() <= 2 && pb.len() <= 2 => {
            let y = i32::try_from(y).ok()?;
            let day_first = dmy(a, b, y);
            let month_first = dmy(b, a, y);
            match (a > 12, b > 12) {
                (true, false) => Some(Single::One(day_first?, vec![Note::NumericUnambiguous])),
                (false, true) => Some(Single::One(month_first?, vec![Note::NumericUnambiguous])),
                (true, true) => None,
                (false, false) if a == b => {
                    Some(Single::One(day_first?, vec![Note::NumericOrderIrrelevant]))
                },
                (false, false) => {
                    let (order, note) = match (opts.numeric_order, lang.implied_numeric_order) {
                        (Some(o), _) => (Some(o), Note::NumericResolvedByOption),
                        (None, Some(o)) => (Some(o), Note::NumericResolvedByLocale),
                        (None, None) => (None, Note::NumericOrderAmbiguous),
                    };
                    match order {
                        Some(NumericOrder::DayFirst) => Some(Single::One(day_first?, vec![note])),
                        Some(NumericOrder::MonthFirst) => {
                            Some(Single::One(month_first?, vec![note]))
                        },
                        None => {
                            let cand = |e: Option<Expr>, reading: &str| {
                                e.map(|expr| Candidate {
                                    expr,
                                    reading: String::from(reading),
                                    notes: vec![Note::NumericOrderAmbiguous],
                                })
                            };
                            let readings: Vec<Candidate> = [
                                cand(day_first, "day-month-year"),
                                cand(month_first, "month-day-year"),
                            ]
                            .into_iter()
                            .flatten()
                            .collect();
                            (!readings.is_empty()).then_some(Single::Many(readings))
                        },
                    }
                },
            }
        },
        // Month and year: 7/2008, 04.1985.
        ([pa, py], &[m, y]) if pa.len() <= 2 && py.len() == 4 && (1..=12).contains(&m) => {
            let (y, m) = (i32::try_from(y).ok()?, u8::try_from(m).ok()?);
            Some(Single::One(Expr::Date(date_ym(y, m)?), Vec::new()))
        },
        // Year then small field: 1985/4, 1985-4 (a full "1985-04" is already
        // valid EDTF and never reaches the grammar).
        ([py, pb], &[y, m]) if py.len() == 4 && pb.len() <= 2 && (1..=12).contains(&m) => {
            let (y, m) = (i32::try_from(y).ok()?, u8::try_from(m).ok()?);
            Some(Single::One(Expr::Date(date_ym(y, m)?), Vec::new()))
        },
        // Hyphenated year pair or elided end year: 1914-1918, 1914-18 (N4).
        // 21..=41 collides with EDTF sub-year codes: honest ambiguity (N13).
        ([py, pb], &[y, b]) if py.len() == 4 && sep == '-' => {
            let y = i32::try_from(y).ok()?;
            match pb.len() {
                4 => {
                    let e = i32::try_from(b).ok()?;
                    if e > y {
                        Some(Single::One(interval(date_y(y)?, date_y(e)?), Vec::new()))
                    } else {
                        None
                    }
                },
                2 => {
                    let b_u8 = u8::try_from(b).ok()?;
                    let elided = y / 100 * 100 + i32::from(b_u8);
                    if elided <= y || b <= 12 {
                        return None;
                    }
                    if (21..=41).contains(&b) {
                        Some(Single::Many(vec![
                            Candidate {
                                expr: Expr::Date(Date {
                                    month: Some(quiet(b_u8)),
                                    ..date_y(y)?
                                }),
                                reading: format!("sub-year code {b} ({})", season_name(b_u8)),
                                notes: vec![Note::SeasonRangeCollision],
                            },
                            Candidate {
                                expr: interval(date_y(y)?, date_y(elided)?),
                                reading: format!("year range {y}/{elided}"),
                                notes: vec![Note::ElidedEndYear, Note::SeasonRangeCollision],
                            },
                        ]))
                    } else {
                        Some(Single::One(
                            interval(date_y(y)?, date_y(elided)?),
                            vec![Note::ElidedEndYear],
                        ))
                    }
                },
                _ => None,
            }
        },
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// The single-expression grammar

/// Match one date-ish expression. `in_range` suppresses interval-producing
/// forms (century parts) so range endpoints stay dates (N1 scope).
#[allow(
    clippy::too_many_lines,
    reason = "the ordered arms ARE the grammar (N11); order carries meaning"
)]
fn parse_single(s: &str, opts: Options, lang: &Lang, in_range: bool) -> Option<Single> {
    let toks: Vec<&str> = s.split(' ').filter(|t| !t.is_empty()).collect();
    if toks.is_empty() {
        return None;
    }

    // Trailing era phrase, if any ("500 bc", "xix век до н. э.").
    let (era, mut core_toks) = match split_era(&toks, lang) {
        Some((bc, rest)) => (Some(bc), rest),
        None => (None, toks.clone()),
    };
    // A year marker may sit BEFORE the era phrase ("44 г. до н. э.") — strip
    // trailing noise again now that the era is off (N3 scope).
    while core_toks.len() > 1
        && lang
            .noise_trailing
            .contains(&strip_dot(core_toks[core_toks.len() - 1]))
    {
        core_toks.pop();
    }
    let bc = era == Some(true);

    // Part-of-century / decade modifier, spaced or attached ("mid-1930s").
    if let Some((span, rest)) = split_modifier(&core_toks, lang) {
        if era.is_none() {
            if let [t] = rest.as_slice() {
                if let Some(d) = decade_tok(t, lang) {
                    // Sub-decade parts would be false precision: the modifier
                    // is dropped and recorded (N1).
                    return Some(with_note(decade_single(d, opts), Note::ModifierDropped));
                }
            }
        }
        if let Some((n, roman)) = century_toks(&rest, lang) {
            let (expr, mut notes) = if in_range {
                let (e, mut ns) = century_expr(n, bc)?;
                ns.push(Note::ModifierDropped);
                (e, ns)
            } else {
                century_part_expr(span, n, bc)?
            };
            if roman {
                notes.push(Note::RomanCentury);
            }
            return Some(Single::One(expr, notes));
        }
        return None;
    }

    if let Some((n, roman)) = century_toks(&core_toks, lang) {
        let (expr, mut notes) = century_expr(n, bc)?;
        if roman {
            notes.push(Note::RomanCentury);
        }
        return Some(Single::One(expr, notes));
    }

    // Decade of an explicit century: "60-е годы XIX века" → 186X (N6).
    if era.is_none() && core_toks.len() >= 2 {
        if let Some(DecadeParse::Bare(tens)) = decade_tok(core_toks[0], lang) {
            let mut rest = core_toks[1..].to_vec();
            while rest.len() > 1 && lang.noise_trailing.contains(&strip_dot(rest[0])) {
                rest.remove(0);
            }
            if let Some((n, roman)) = century_toks(&rest, lang) {
                let prefix3 = (u16::try_from(n).ok()? - 1) * 10 + u16::from(tens);
                let mut notes = vec![Note::DecadeOfCentury];
                if roman {
                    notes.push(Note::RomanCentury);
                }
                return Some(Single::One(Expr::Date(decade_date(prefix3)), notes));
            }
        }
    }

    // Era-qualified plain year: "500 bc" → -0499, "79 ce" → 0079 (N3).
    if let Some(bc) = era {
        if let [t] = core_toks.as_slice() {
            let v = num(t)?;
            if v >= 1 && t.len() <= if bc { 5 } else { 4 } {
                let y = i32::try_from(if bc { 1 - i64::from(v) } else { i64::from(v) }).ok()?;
                let notes = if bc {
                    vec![Note::AstronomicalYear]
                } else {
                    Vec::new()
                };
                return Some(Single::One(Expr::Date(date_y(y)?), notes));
            }
        }
        return None;
    }

    match core_toks.as_slice() {
        [t] => {
            if let Some(y) = year_num(t) {
                return Some(Single::One(Expr::Date(date_y(y)?), Vec::new()));
            }
            if let Some(d) = decade_tok(t, lang) {
                return Some(decade_single(d, opts));
            }
            if let Some(m) = table_u8(t, lang.months) {
                // "January" → XXXX-01 (N9).
                return Some(Single::One(
                    Expr::Date(Date {
                        year: masked_year(),
                        month: Some(quiet(m)),
                        day: None,
                    }),
                    vec![Note::MissingYearMasked],
                ));
            }
            numeric_token(t, opts, lang)
        },
        [a, b] => {
            // "spring 2001" / "весной 2001" / "2001 spring" (N7).
            for (st, yt) in [(a, b), (b, a)] {
                if let (Some(code), Some(y)) = (table_u8(st, lang.seasons), year_num(yt)) {
                    return Some(Single::One(
                        Expr::Date(Date {
                            month: Some(quiet(code)),
                            ..date_y(y)?
                        }),
                        vec![Note::SeasonCode],
                    ));
                }
            }
            // "June 1940" / "1940 June".
            for (mt, yt) in [(a, b), (b, a)] {
                if let (Some(m), Some(y)) = (table_u8(mt, lang.months), year_num(yt)) {
                    return Some(Single::One(Expr::Date(date_ym(y, m)?), Vec::new()));
                }
            }
            // "January 12" / "12 January" → XXXX-01-12 (N9).
            for (mt, dt) in [(a, b), (b, a)] {
                if let (Some(m), Some(d)) = (table_u8(mt, lang.months), day_num(dt, lang)) {
                    return Some(Single::One(
                        Expr::Date(Date {
                            year: masked_year(),
                            month: Some(quiet(m)),
                            day: Some(quiet(d)),
                        }),
                        vec![Note::MissingYearMasked],
                    ));
                }
            }
            None
        },
        [a, b, c] => {
            // "12 April 1985" / "April 12, 1985" / "12-го апреля 1985".
            for (dt, mt) in [(a, b), (b, a)] {
                if let (Some(d), Some(m), Some(y)) =
                    (day_num(dt, lang), table_u8(mt, lang.months), year_num(c))
                {
                    return Some(Single::One(Expr::Date(date_ymd(y, m, d)?), Vec::new()));
                }
            }
            None
        },
        _ => None,
    }
}

/// Split a leading part-of-century modifier phrase off the token list, then
/// drop any noise between it and the rest ("first half OF THE 19th century").
fn split_modifier<'a>(toks: &[&'a str], lang: &Lang) -> Option<(Span, Vec<&'a str>)> {
    let matched = lang.modifiers.iter().find_map(|(phrase, span)| {
        (toks.len() > phrase.len() && toks.iter().zip(*phrase).all(|(t, w)| strip_dot(t) == *w))
            .then(|| (*span, toks[phrase.len()..].to_vec()))
    });
    let (span, mut rest) = matched.or_else(|| {
        // Attached single-word modifier: "mid-1930s", "late-19th".
        let (head, tail_toks) = toks.split_first()?;
        let (word, tail) = head.split_once('-')?;
        let span = lang
            .modifiers
            .iter()
            .find(|(p, _)| p.len() == 1 && p[0] == word)
            .map(|&(_, s)| s)?;
        if tail.is_empty() {
            return None;
        }
        let mut out = vec![tail];
        out.extend_from_slice(tail_toks);
        Some((span, out))
    })?;
    while rest.len() > 1 && lang.noise_leading.contains(&strip_dot(rest[0])) {
        rest.remove(0);
    }
    Some((span, rest))
}

fn with_note(s: Single, note: Note) -> Single {
    match s {
        Single::One(e, mut notes) => {
            notes.push(note);
            Single::One(e, notes)
        },
        Single::Many(mut cands) => {
            for c in &mut cands {
                c.notes.push(note);
            }
            Single::Many(cands)
        },
    }
}

// ---------------------------------------------------------------------------
// Open-ended and two-sided ranges

/// Match a leading phrase from a longest-first phrase list.
fn match_head<'a>(toks: &[&'a str], phrases: &[&[&str]]) -> Option<Vec<&'a str>> {
    for phrase in phrases {
        if toks.len() > phrase.len() && toks.iter().zip(*phrase).all(|(t, w)| strip_dot(t) == *w) {
            return Some(toks[phrase.len()..].to_vec());
        }
    }
    None
}

/// "before X" → `../X`, "after X" → `X/..` (interval reading, N8).
fn parse_open(toks: &[&str], opts: Options, lang: &Lang) -> Option<Single> {
    let (before, rest) = match_head(toks, lang.before_phrases)
        .map(|rest| (true, rest))
        .or_else(|| match_head(toks, lang.after_phrases).map(|rest| (false, rest)))?;
    let (inner, q) = strip_qualifiers(&rest.join(" "), lang);
    let single = parse_single(&inner, opts, lang, true)?;
    let wrap = |expr: Expr| -> Option<Expr> {
        let Expr::Date(mut d) = expr else { return None };
        qualify_date(&mut d, q);
        let (start, end) = if before {
            (IntervalEndpoint::Open, IntervalEndpoint::Date(d))
        } else {
            (IntervalEndpoint::Date(d), IntervalEndpoint::Open)
        };
        Some(Expr::Interval(Interval { start, end }))
    };
    map_single(single, wrap, Note::OpenInterval)
}

/// "1863 or 1864" → honest ambiguity (N14).
fn parse_or(toks: &[&str], opts: Options, lang: &Lang) -> Option<Single> {
    let pos = toks.iter().position(|t| lang.or_words.contains(t))?;
    if pos == 0 || pos == toks.len() - 1 {
        return None;
    }
    let sides = [toks[..pos].join(" "), toks[pos + 1..].join(" ")];
    let mut cands = Vec::new();
    for side in sides {
        let (inner, q) = strip_qualifiers(&side, lang);
        match parse_single(&inner, opts, lang, true)? {
            Single::One(mut expr, mut notes) => {
                qualify_expr(&mut expr, q);
                notes.push(Note::OrAlternatives);
                cands.push(Candidate {
                    expr,
                    reading: String::from("alternative"),
                    notes,
                });
            },
            Single::Many(_) => return None, // nested ambiguity: refuse to guess
        }
    }
    Some(Single::Many(cands))
}

/// Two-sided ranges: "from X to Y", "с X по Y", "X to Y", "X-Y".
fn parse_range(s: &str, toks: &[&str], opts: Options, lang: &Lang) -> Option<Single> {
    let word_split = |toks: &[&str], sep: &str| -> Option<(String, String)> {
        let pos = toks.iter().position(|t| *t == sep)?;
        (pos > 0 && pos < toks.len() - 1)
            .then(|| (toks[..pos].join(" "), toks[pos + 1..].join(" ")))
    };
    for (lead, sep) in lang.range_pairs {
        let inner = match lead {
            Some(l) if toks.first() == Some(l) => &toks[1..],
            Some(_) => continue,
            None => toks,
        };
        if let Some((l, r)) = word_split(inner, sep) {
            if let Some(single) = endpoint_pair(&l, &r, opts, lang) {
                return Some(single);
            }
        }
    }
    // Hyphen split: try each '-' position left to right.
    for (i, c) in s.char_indices() {
        if c != '-' {
            continue;
        }
        let (l, r) = (s[..i].trim(), s[i + 1..].trim());
        if l.is_empty() || r.is_empty() {
            continue;
        }
        if let Some(single) = endpoint_pair(l, r, opts, lang) {
            return Some(single);
        }
    }
    None
}

/// Parse both endpoints of a range, with per-endpoint qualifiers
/// ("1856-ca. 1865" → `1856/1865~`), elided end years ("1914-18", N4), and
/// bare-ordinal left centuries ("17-19th centuries" → `16XX/18XX`).
#[allow(
    clippy::too_many_lines,
    clippy::many_single_char_names,
    reason = "endpoint pairing is one decision table; l/r/a/b/e its algebra"
)]
fn endpoint_pair(left: &str, right: &str, opts: Options, lang: &Lang) -> Option<Single> {
    let (ls, lq) = strip_qualifiers(left, lang);
    let (rs, rq) = strip_qualifiers(right, lang);
    let lres = parse_single(&ls, opts, lang, true);
    let rres = parse_single(&rs, opts, lang, true);

    let (lres, rres) = match (lres, rres) {
        (Some(l), Some(r)) => (l, r),
        // "17-19th centuries", "XVII-XIX вв.": a bare ordinal on the left
        // inherits century-ness from the right endpoint.
        (None, Some(r)) => {
            let Single::One(Expr::Date(rd), rnotes) = &r else {
                return None;
            };
            if !rnotes.contains(&Note::CenturyMask) || ls.contains(' ') {
                return None;
            }
            let (n, roman) = century_ordinal(&ls, lang)?;
            let bc = matches!(rd.year.kind, YearKind::Standard { negative: true, .. });
            let (expr, mut ns) = century_expr(n, bc)?;
            if roman {
                ns.push(Note::RomanCentury);
            }
            (Single::One(expr, ns), r)
        },
        // "1914 - 18": the right side elides the left year's century (N4).
        (Some(l), None) => {
            let Single::One(Expr::Date(ld), _) = &l else {
                return None;
            };
            let y = i32::try_from(ld.year.value()?).ok()?;
            // Elision needs an AD start with a real century prefix. A BC
            // (negative astronomical) start has no deterministic elided
            // reading — truncating arithmetic would fabricate one (N4).
            if y < 100 {
                return None;
            }
            let v = num(&rs).filter(|_| rs.len() <= 2)?;
            let v_u8 = u8::try_from(v).ok()?;
            let elided = y / 100 * 100 + i32::from(v_u8);
            // Mirror the unspaced NNNN-NN limits: 01–12 read as months and
            // are never ranges (N4); 21–41 collide with sub-year codes (N13).
            if elided <= y || v <= 12 {
                return None;
            }
            if (21..=41).contains(&v) && ld.month.is_none() && ld.day.is_none() {
                let mut season = *ld;
                season.month = Some(quiet(v_u8));
                qualify_date(&mut season, lq);
                let (mut a, mut b) = (*ld, date_y(elided)?);
                qualify_date(&mut a, lq);
                qualify_date(&mut b, rq);
                return Some(Single::Many(vec![
                    Candidate {
                        expr: Expr::Date(season),
                        reading: format!("sub-year code {v} ({})", season_name(v_u8)),
                        notes: vec![Note::SeasonRangeCollision],
                    },
                    Candidate {
                        expr: interval(a, b),
                        reading: format!("year range {y}/{elided}"),
                        notes: vec![Note::ElidedEndYear, Note::SeasonRangeCollision],
                    },
                ]));
            }
            let r = Single::One(Expr::Date(date_y(elided)?), vec![Note::ElidedEndYear]);
            (l, r)
        },
        (None, None) => return None,
    };

    let build = |ld: &Date, rd: &Date| -> Option<Expr> {
        let (mut ld, mut rd) = (*ld, *rd);
        qualify_date(&mut ld, lq);
        qualify_date(&mut rd, rq);
        if let (Some(a), Some(b)) = (ld.year.value(), rd.year.value()) {
            if a > b {
                return None; // reversed ranges are prose errors, not dates
            }
        }
        Some(interval(ld, rd))
    };
    match (lres, rres) {
        (Single::One(Expr::Date(ld), ln), Single::One(Expr::Date(rd), rn)) => {
            // "June-July 1940": an endpoint without a year inherits the other
            // endpoint's stated year — the year is elided, not missing (N16).
            let (ld, ln, rd, rn) = distribute_year(ld, ln, rd, rn)?;
            // "winter 1941-42": one boundary-spanning winter, or winter 1941
            // through the whole of 1942? Both readings, honestly (N17).
            if let Some(many) = cross_year_season(&ld, &ln, &rd, &rn, lq, &build) {
                return Some(many);
            }
            let expr = build(&ld, &rd)?;
            let mut notes = ln;
            notes.extend(rn);
            Some(Single::One(expr, notes))
        },
        (Single::One(Expr::Date(ld), ln), Single::Many(cands)) => {
            // A candidate eliminated here (reversed range) is a prose error
            // poisoning the whole input, not a disambiguation — refuse.
            let total = cands.len();
            let out: Vec<Candidate> = cands
                .into_iter()
                .filter_map(|c| {
                    let Expr::Date(cd) = c.expr else { return None };
                    let expr = build(&ld, &cd)?;
                    let mut notes = ln.clone();
                    notes.extend(c.notes);
                    Some(Candidate {
                        expr,
                        reading: c.reading,
                        notes,
                    })
                })
                .collect();
            (out.len() == total && !out.is_empty()).then_some(Single::Many(out))
        },
        (Single::Many(cands), Single::One(Expr::Date(rd), rn)) => {
            let total = cands.len();
            let out: Vec<Candidate> = cands
                .into_iter()
                .filter_map(|c| {
                    let Expr::Date(cd) = c.expr else { return None };
                    let expr = build(&cd, &rd)?;
                    let mut notes = c.notes;
                    notes.extend(rn.clone());
                    Some(Candidate {
                        expr,
                        reading: c.reading,
                        notes,
                    })
                })
                .collect();
            (out.len() == total && !out.is_empty()).then_some(Single::Many(out))
        },
        // A two-sided ambiguity would be a 4-way product — refuse to guess.
        _ => None,
    }
}

/// N16: when exactly one range endpoint lacks a year (`XXXX` via N9) and the
/// other states one, the year scopes both endpoints — copy it over and swap
/// the note. Fails (→ `NoMatch`) when the year-less endpoint cannot inherit.
type Endpoints = (Date, Vec<Note>, Date, Vec<Note>);

fn distribute_year(
    mut ld: Date,
    mut ln: Vec<Note>,
    mut rd: Date,
    mut rn: Vec<Note>,
) -> Option<Endpoints> {
    let l_masked = ln.contains(&Note::MissingYearMasked);
    let r_masked = rn.contains(&Note::MissingYearMasked);
    if l_masked != r_masked {
        let (masked_d, masked_n, source_d) = if l_masked {
            (&mut ld, &mut ln, &rd)
        } else {
            (&mut rd, &mut rn, &ld)
        };
        // Only a fully-specified year is worth inheriting; pairing a masked
        // month with a masked decade would compound the guessing.
        source_d.year.value()?;
        masked_d.year.kind = source_d.year.kind;
        masked_n.retain(|n| *n != Note::MissingYearMasked);
        masked_n.push(Note::EndpointYearDistributed);
    }
    Some((ld, ln, rd, rn))
}

/// N17: "winter 1941-42" (and "winter 1941-1942") — EDTF's winter code 24
/// wraps the year boundary, so the prose may name ONE winter or a
/// winter-to-year range. Emit both readings.
fn cross_year_season(
    ld: &Date,
    ln: &[Note],
    rd: &Date,
    rn: &[Note],
    lq: Qualifier,
    build: &impl Fn(&Date, &Date) -> Option<Expr>,
) -> Option<Single> {
    const WINTER: u8 = 24;
    if ld.month.and_then(DateField::value) != Some(WINTER) || rd.month.is_some() || rd.day.is_some()
    {
        return None;
    }
    let (a, b) = (ld.year.value()?, rd.year.value()?);
    if b != a + 1 {
        return None;
    }
    let mut season = *ld;
    qualify_date(&mut season, lq);
    let mut season_notes = ln.to_vec();
    season_notes.push(Note::CrossYearSeason);
    let range = build(ld, rd)?;
    let mut range_notes = ln.to_vec();
    range_notes.extend(rn.iter().copied());
    range_notes.push(Note::CrossYearSeason);
    Some(Single::Many(vec![
        Candidate {
            expr: Expr::Date(season),
            reading: String::from("one winter spanning the year boundary"),
            notes: season_notes,
        },
        Candidate {
            expr: range,
            reading: format!("winter {a} through the whole of {b}"),
            notes: range_notes,
        },
    ]))
}

/// Apply a `Single`-level transform that may reject candidates.
fn map_single(single: Single, wrap: impl Fn(Expr) -> Option<Expr>, note: Note) -> Option<Single> {
    match single {
        Single::One(expr, mut notes) => {
            let expr = wrap(expr)?;
            notes.push(note);
            Some(Single::One(expr, notes))
        },
        Single::Many(cands) => {
            let out: Vec<Candidate> = cands
                .into_iter()
                .filter_map(|mut c| {
                    c.expr = wrap(c.expr)?;
                    c.notes.push(note);
                    Some(c)
                })
                .collect();
            (!out.is_empty()).then_some(Single::Many(out))
        },
    }
}

// ---------------------------------------------------------------------------
// Qualification and rendering

fn merge(into: &mut Qualifier, q: Qualifier) {
    into.uncertain |= q.uncertain;
    into.approximate |= q.approximate;
}

/// Distribute a whole-expression qualifier over every present component;
/// uniform qualification renders as the trailing form ("1940-06~") via
/// core's canonical Display (N10).
fn qualify_date(d: &mut Date, q: Qualifier) {
    if !q.uncertain && !q.approximate {
        return;
    }
    merge(&mut d.year.qualifier, q);
    if let Some(m) = &mut d.month {
        merge(&mut m.qualifier, q);
    }
    if let Some(day) = &mut d.day {
        merge(&mut day.qualifier, q);
    }
}

fn qualify_expr(e: &mut Expr, q: Qualifier) {
    match e {
        Expr::Date(d) => qualify_date(d, q),
        Expr::Interval(iv) => {
            for ep in [&mut iv.start, &mut iv.end] {
                if let IntervalEndpoint::Date(d)
                | IntervalEndpoint::OnOrBefore(d)
                | IntervalEndpoint::OnOrAfter(d) = ep
                {
                    qualify_date(d, q);
                }
            }
        },
    }
}

/// Render through core's canonical Display and re-parse: the calendar check
/// and the "every output is valid EDTF" guarantee in one step.
fn render(expr: Expr) -> Option<(Edtf, String)> {
    let value = match expr {
        Expr::Date(d) => Edtf::Date(d),
        Expr::Interval(iv) => Edtf::Interval(iv),
    };
    let s = value.to_string();
    let reparsed = Edtf::parse(&s).ok()?;
    Some((reparsed, s))
}

const fn no_match(reason: NoMatchReason) -> Outcome {
    Outcome::NoMatch { reason }
}

fn outcome_from(single: Single, q: Qualifier, base_notes: Vec<Note>) -> Outcome {
    match single {
        Single::One(mut expr, mut notes) => {
            let distributed = q.is_qualified() && matches!(expr, Expr::Interval(_));
            qualify_expr(&mut expr, q);
            match render(expr) {
                Some((value, edtf)) => {
                    let mut all = base_notes;
                    all.append(&mut notes);
                    if distributed {
                        all.push(Note::QualifierDistributed);
                    }
                    Outcome::Normalized(Normalized {
                        edtf,
                        value,
                        notes: all,
                    })
                },
                None => no_match(NoMatchReason::ImpossibleDate),
            }
        },
        Single::Many(cands) => {
            // Fail closed: a reading that dies at the calendar check
            // (February 30, a reversed masked range) is a prose error, and
            // silently promoting the survivor would fake certainty the input
            // never had (N14).
            let total = cands.len();
            let mut interps: Vec<Interpretation> = cands
                .into_iter()
                .filter_map(|mut c| {
                    qualify_expr(&mut c.expr, q);
                    let (value, edtf) = render(c.expr)?;
                    let mut notes = base_notes.clone();
                    notes.extend(c.notes);
                    Some(Interpretation {
                        edtf,
                        value,
                        reading: c.reading,
                        notes,
                    })
                })
                .collect();
            if interps.len() < total {
                return no_match(NoMatchReason::ImpossibleDate);
            }
            match interps.len() {
                0 => no_match(NoMatchReason::ImpossibleDate),
                1 => {
                    let i = interps.remove(0);
                    Outcome::Normalized(Normalized {
                        edtf: i.edtf,
                        value: i.value,
                        notes: i.notes,
                    })
                },
                _ => Outcome::Ambiguous(Ambiguous {
                    interpretations: interps,
                }),
            }
        },
    }
}

// ---------------------------------------------------------------------------
// Entry point

pub(crate) fn run(input: &str, opts: Options) -> Outcome {
    let lang = lang_for(opts.language);
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return no_match(NoMatchReason::OutOfGrammar);
    }

    // Dash-unified copy of the verbatim input (EDTF is case-sensitive:
    // X/Y/E/S must survive, so no lowercasing here).
    let dashed: String = trimmed
        .chars()
        .map(|c| match c {
            '\u{2013}' | '\u{2014}' => '-',
            c => c,
        })
        .collect();

    // "1914-21" is valid EDTF (spring 1914) AND a plausible elided range —
    // the collision must surface before the passthrough swallows it (N13).
    if let Some(outcome) = collision_check(&dashed, opts, lang) {
        return outcome;
    }

    if let Ok(v) = Edtf::parse(&dashed) {
        let edtf = v.to_string();
        let value = Edtf::parse(&edtf).unwrap_or(v);
        return Outcome::Normalized(Normalized {
            edtf,
            value,
            notes: vec![Note::AlreadyValidEdtf],
        });
    }

    let mut pre = preprocess(trimmed);
    let mut q = Qualifier::default();
    if pre.ends_with('?') {
        q.uncertain = true;
        pre.pop();
        while pre.ends_with(' ') {
            pre.pop();
        }
    }
    let (rest, q2) = strip_qualifiers(&pre, lang);
    merge(&mut q, q2);
    if rest.is_empty() {
        return no_match(NoMatchReason::OutOfGrammar);
    }
    if lang.explicit_no_date.contains(&rest.as_str()) {
        // The form decides what "unknown" means; the reason lets it (N12).
        return no_match(NoMatchReason::ExplicitNoDate);
    }
    let toks: Vec<&str> = rest.split(' ').collect();

    if let Some(single) = parse_single(&rest, opts, lang, false) {
        return outcome_from(single, q, Vec::new());
    }
    if let Some(single) = parse_open(&toks, opts, lang) {
        return outcome_from(single, q, Vec::new());
    }
    if let Some(single) = parse_or(&toks, opts, lang) {
        return outcome_from(single, q, Vec::new());
    }
    if let Some(single) = parse_range(&rest, &toks, opts, lang) {
        return outcome_from(single, q, Vec::new());
    }
    no_match(NoMatchReason::OutOfGrammar)
}

/// `NNNN-NN` with a sub-year code 21–41 and a plausible elided range (N13).
fn collision_check(s: &str, opts: Options, lang: &Lang) -> Option<Outcome> {
    let b = s.as_bytes();
    if b.len() != 7 || b[4] != b'-' {
        return None;
    }
    if !b[..4].iter().all(u8::is_ascii_digit) || !b[5..].iter().all(u8::is_ascii_digit) {
        return None;
    }
    let code: u32 = s[5..].parse().ok()?;
    let year: i32 = s[..4].parse().ok()?;
    if !(21..=41).contains(&code) || year / 100 * 100 + i32::try_from(code).ok()? <= year {
        return None;
    }
    match numeric_token(s, opts, lang)? {
        many @ Single::Many(_) => Some(outcome_from(many, Qualifier::default(), Vec::new())),
        _ => None,
    }
}