edtf-core 1.1.0

EDTF (ISO 8601-2:2019 Annex A) parsing, validation, bounds, temporal relations and canonical formatting, levels 0-2. 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
//! Hand-written recursive-descent parser and validator for EDTF levels 0–2.
//!
//! Grammar and validation rules follow docs/spec-notes.md, which cites the
//! ISO 8601-1/-2:2019 sections for every production. The D-decisions are
//! implemented as resolved there.
//!
//! Every error carries the byte offset (into the original input) where the
//! problem was detected; sub-parsers receive a `base` offset so positions
//! stay absolute inside intervals, sets and date-times.

use alloc::{vec, vec::Vec};

use crate::{
    bounds::{Bound, date_bounds, is_leap},
    types::{
        Date, DateField, DateTime, Edtf, Interval, IntervalEndpoint, ParseError, Precision,
        Qualifier, Set, SetElement, SetKind, Time, TimeShift, Year, YearKind,
    },
};

pub(crate) fn parse(input: &str) -> Result<Edtf, ParseError> {
    if input.is_empty() {
        return Err(err(0, "empty input"));
    }
    if let Some(pos) = input.bytes().position(|b| !b.is_ascii()) {
        return Err(err(pos, "EDTF permits ASCII characters only"));
    }
    if let Some(pos) = input
        .bytes()
        .position(|b| b == b' ' || b.is_ascii_control())
    {
        return Err(err(pos, "whitespace is not allowed"));
    }
    match input.as_bytes()[0] {
        b'{' | b'[' => parse_set(input),
        _ if input.contains('/') => parse_interval(input),
        _ if input.contains('T') => parse_datetime(input),
        _ => parse_date_at(input, 0).map(Edtf::Date),
    }
}

const fn err(offset: usize, message: &'static str) -> ParseError {
    ParseError { message, offset }
}

/// Byte offset of `part` (a slice borrowed from `whole`) within `whole`.
fn offset_in(whole: &str, part: &str) -> usize {
    (part.as_ptr() as usize).saturating_sub(whole.as_ptr() as usize)
}

// ---------------------------------------------------------------- cursor

struct Cur<'a> {
    b: &'a [u8],
    i: usize,
    base: usize,
}

impl<'a> Cur<'a> {
    const fn new(s: &'a str, base: usize) -> Self {
        Self {
            b: s.as_bytes(),
            i: 0,
            base,
        }
    }

    const fn pos(&self) -> usize {
        self.base + self.i
    }

    const fn fail(&self, message: &'static str) -> ParseError {
        err(self.pos(), message)
    }

    fn peek(&self) -> Option<u8> {
        self.b.get(self.i).copied()
    }

    fn bump(&mut self) -> Option<u8> {
        let c = self.peek();
        if c.is_some() {
            self.i += 1;
        }
        c
    }

    fn eat(&mut self, c: u8) -> bool {
        if self.peek() == Some(c) {
            self.i += 1;
            true
        } else {
            false
        }
    }

    const fn eof(&self) -> bool {
        self.i >= self.b.len()
    }

    fn take_qualifier(&mut self) -> Option<Qualifier> {
        let q = match self.peek()? {
            b'?' => Qualifier {
                uncertain: true,
                approximate: false,
            },
            b'~' => Qualifier {
                uncertain: false,
                approximate: true,
            },
            b'%' => Qualifier {
                uncertain: true,
                approximate: true,
            },
            _ => return None,
        };
        self.i += 1;
        Some(q)
    }

    /// Consume consecutive digits into an i64; returns (value, digit count).
    fn take_number(&mut self) -> Result<(i64, usize), ParseError> {
        let start = self.i;
        let mut v: i64 = 0;
        while let Some(d @ b'0'..=b'9') = self.peek() {
            self.i += 1;
            v = v
                .checked_mul(10)
                .and_then(|x| x.checked_add(i64::from(d - b'0')))
                .ok_or_else(|| err(self.base + start, "number out of supported range"))?;
        }
        Ok((v, self.i - start))
    }

    /// Two characters, each a digit or `X`.
    fn take_two(&mut self, what: &'static str) -> Result<[Option<u8>; 2], ParseError> {
        let mut out = [None; 2];
        for slot in &mut out {
            match self.bump() {
                Some(d @ b'0'..=b'9') => *slot = Some(d - b'0'),
                Some(b'X') => *slot = None,
                _ => {
                    return Err(ParseError {
                        message: match what {
                            "month" => "month must be two digits (or X)",
                            _ => "day must be two digits (or X)",
                        },
                        offset: self.base + self.i.saturating_sub(1),
                    });
                },
            }
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------- dates

#[allow(
    clippy::too_many_lines,
    reason = "one linear scan; splitting scatters the offset bookkeeping"
)]
pub(crate) fn parse_date_at(s: &str, base: usize) -> Result<Date, ParseError> {
    if s.is_empty() {
        return Err(err(base, "empty date"));
    }
    if s.as_bytes()[0] == b'Y' {
        return parse_prefixed_year(s, base);
    }
    let mut c = Cur::new(s, base);

    // Year: optional individual qualifier, optional '-', exactly four digit/X.
    let mut year_qual = Qualifier::default();
    if let Some(q) = c.take_qualifier() {
        year_qual.merge(q);
    }
    let negative = c.eat(b'-');
    let year_off = c.pos();
    let mut ydigits = [None; 4];
    for slot in &mut ydigits {
        match c.bump() {
            Some(d @ b'0'..=b'9') => *slot = Some(d - b'0'),
            Some(b'X') => *slot = None,
            _ => {
                return Err(err(
                    c.pos().saturating_sub(1),
                    "year must have exactly four digits (or X)",
                ));
            },
        }
    }
    let year_has_x = ydigits.iter().any(Option::is_none);
    if negative && year_has_x {
        return Err(err(
            year_off,
            "negative years cannot contain unspecified digits",
        ));
    }
    if negative && ydigits == [Some(0); 4] {
        return Err(err(year_off - 1, "-0000 is not a valid year"));
    }

    // Optional S<digits> significant-digit suffix (year-precision only).
    let significant = if c.eat(b'S') {
        if year_has_x {
            return Err(err(
                c.pos() - 1,
                "significant digits cannot combine with unspecified digits",
            ));
        }
        let sig_off = c.pos();
        let (n, len) = c.take_number()?;
        let sig = u32::try_from(n).ok().filter(|s| (1..=4).contains(s));
        if len == 0 || sig.is_none() {
            return Err(err(
                sig_off,
                "significant digits must be 1-4 for a four-digit year",
            ));
        }
        sig
    } else {
        None
    };

    // Optional trailing qualifier (group: year, or complete if year-only).
    if let Some(q) = c.take_qualifier() {
        year_qual.merge(q);
    }

    if c.eof() {
        return finish_date(
            negative,
            ydigits,
            significant,
            year_qual,
            None,
            None,
            year_off,
            year_off,
        );
    }
    if significant.is_some() {
        return Err(c.fail("significant-digit years are year-precision only"));
    }
    if !c.eat(b'-') {
        return Err(c.fail("expected '-' before month"));
    }

    // Month.
    let mut month_qual = Qualifier::default();
    if let Some(q) = c.take_qualifier() {
        month_qual.merge(q);
    }
    let month_off = c.pos();
    let month_digits = c.take_two("month")?;
    if let Some(q) = c.take_qualifier() {
        // Group qualification: applies to this component and everything left.
        month_qual.merge(q);
        year_qual.merge(q);
    }
    let mut month = DateField {
        digits: month_digits,
        qualifier: month_qual,
    };

    if c.eof() {
        return finish_date(
            negative,
            ydigits,
            None,
            year_qual,
            Some(month),
            None,
            month_off,
            month_off,
        );
    }
    if !c.eat(b'-') {
        return Err(c.fail("expected '-' before day"));
    }

    // Day.
    let mut day_qual = Qualifier::default();
    if let Some(q) = c.take_qualifier() {
        day_qual.merge(q);
    }
    let day_off = c.pos();
    let day_digits = c.take_two("day")?;
    if let Some(q) = c.take_qualifier() {
        // Trailing qualifier after the last component = complete qualification.
        day_qual.merge(q);
        month.qualifier.merge(q);
        year_qual.merge(q);
    }
    if !c.eof() {
        return Err(c.fail("unexpected characters after day"));
    }
    let day = DateField {
        digits: day_digits,
        qualifier: day_qual,
    };
    finish_date(
        negative,
        ydigits,
        None,
        year_qual,
        Some(month),
        Some(day),
        month_off,
        day_off,
    )
}

#[allow(
    clippy::too_many_arguments,
    reason = "finisher taking every parsed component; it has one caller"
)]
fn finish_date(
    negative: bool,
    ydigits: [Option<u8>; 4],
    significant: Option<u32>,
    year_qual: Qualifier,
    month: Option<DateField>,
    day: Option<DateField>,
    month_off: usize,
    day_off: usize,
) -> Result<Date, ParseError> {
    let year = Year {
        kind: YearKind::Standard {
            negative,
            digits: ydigits,
        },
        significant_digits: significant,
        qualifier: year_qual,
    };
    validate_month_day(&year.kind, month.as_ref(), day.as_ref(), month_off, day_off)?;
    Ok(Date { year, month, day })
}

fn validate_month_day(
    year: &YearKind,
    month: Option<&DateField>,
    day: Option<&DateField>,
    month_off: usize,
    day_off: usize,
) -> Result<(), ParseError> {
    let Some(m) = month else {
        return Ok(());
    };
    match m.value() {
        Some(v) => {
            if !((1..=12).contains(&v) || (21..=41).contains(&v)) {
                return Err(err(
                    month_off,
                    "month must be 01-12 or a sub-year code 21-41",
                ));
            }
            if (21..=41).contains(&v) && day.is_some() {
                return Err(err(day_off, "sub-year groupings cannot carry a day"));
            }
        },
        None => {
            // Masked months match calendar months 01-12 only (decision D14);
            // sub-year codes must be written explicitly.
            if month_candidates(*m).is_empty() {
                return Err(err(
                    month_off,
                    "no calendar month matches the unspecified digits",
                ));
            }
        },
    }
    if let Some(d) = day {
        if !day_has_valid_completion(year, *m, *d) {
            return Err(err(day_off, "day is out of range for the month"));
        }
    }
    Ok(())
}

fn month_candidates(m: DateField) -> Vec<u8> {
    match m.value() {
        Some(v) if (1..=12).contains(&v) => vec![v],
        Some(_) => Vec::new(),
        None => (1..=12).filter(|v| field_matches(m, *v)).collect(),
    }
}

fn day_candidates(d: DateField) -> Vec<u8> {
    match d.value() {
        Some(v) if (1..=31).contains(&v) => vec![v],
        Some(_) => Vec::new(),
        None => (1..=31).filter(|v| field_matches(d, *v)).collect(),
    }
}

fn field_matches(f: DateField, v: u8) -> bool {
    f.digits[0].is_none_or(|p| p == v / 10) && f.digits[1].is_none_or(|p| p == v % 10)
}

/// Decision D11: a (possibly masked) year-month-day needs at least one valid
/// calendar completion.
fn day_has_valid_completion(year: &YearKind, m: DateField, d: DateField) -> bool {
    let months = month_candidates(m);
    let days = day_candidates(d);
    let mut leap_possible: Option<bool> = None;
    for &mm in &months {
        for &dd in &days {
            let max = match mm {
                1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
                4 | 6 | 9 | 11 => 30,
                2 => {
                    if dd <= 28 {
                        28
                    } else {
                        let leap = *leap_possible.get_or_insert_with(|| year_leap_possible(year));
                        if leap { 29 } else { 28 }
                    }
                },
                _ => unreachable!("month candidates are 1-12"),
            };
            if dd <= max {
                return true;
            }
        }
    }
    false
}

fn year_leap_possible(year: &YearKind) -> bool {
    match year {
        YearKind::Standard { negative, digits } => {
            if digits.iter().all(Option::is_some) {
                let mut v: i64 = 0;
                for d in digits.iter().flatten() {
                    v = v * 10 + i64::from(*d);
                }
                is_leap(if *negative { -v } else { v })
            } else {
                (0..=9999i64).any(|y| year_matches(*digits, y) && is_leap(y))
            }
        },
        // Y-prefixed years never carry months, so this is only reachable in
        // theory; be permissive.
        YearKind::Big { value } => is_leap(*value),
        YearKind::Exponential { .. } => true,
    }
}

fn year_matches(digits: [Option<u8>; 4], y: i64) -> bool {
    let actual = [(y / 1000) % 10, (y / 100) % 10, (y / 10) % 10, y % 10];
    digits
        .iter()
        .zip(actual)
        .all(|(pat, a)| pat.is_none_or(|p| i64::from(p) == a))
}

/// `Y…` years (ISO 8601-2 §4.7.2-4.7.4): year precision only, |value| > 9999.
fn parse_prefixed_year(s: &str, base: usize) -> Result<Date, ParseError> {
    let mut c = Cur::new(s, base);
    c.eat(b'Y');
    let negative = c.eat(b'-');
    let value_off = c.pos();
    let (mantissa, mantissa_len) = c.take_number()?;
    if mantissa_len == 0 {
        return Err(c.fail("expected digits after 'Y'"));
    }
    // Leading zeros are only meaningful in four-digit years (P1 4.5); in a
    // Y-year they would also desynchronize the S-digit budget from the
    // canonical (zero-stripped) rendering (decision D20).
    if mantissa > 0 && mantissa_len as u64 != u64::from(mantissa.ilog10() + 1) {
        return Err(err(
            value_off,
            "leading zeros are not allowed in Y-prefixed years",
        ));
    }
    let (kind, digit_count) = if c.eat(b'E') {
        let exp_off = c.pos();
        let (exp, exp_len) = c.take_number()?;
        if exp_len == 0 {
            return Err(err(exp_off, "expected digits after exponent 'E'"));
        }
        if mantissa == 0 {
            return Err(err(
                value_off,
                "exponential year significand cannot be zero",
            ));
        }
        let Some(exponent) = u32::try_from(exp).ok().filter(|e| *e <= 100_000) else {
            return Err(err(exp_off, "exponent out of supported range"));
        };
        let significand = if negative { -mantissa } else { mantissa };
        // Reject values expressible as a plain four-digit year (decision D1).
        if let Some(v) = 10i64
            .checked_pow(exponent)
            .and_then(|p| significand.checked_mul(p))
        {
            if v.abs() <= 9999 {
                return Err(err(value_off, "Y-prefixed years require |year| > 9999"));
            }
        }
        (
            YearKind::Exponential {
                significand,
                exponent,
            },
            mantissa_len as u64 + u64::from(exponent),
        )
    } else {
        if mantissa <= 9999 {
            return Err(err(value_off, "Y-prefixed years require |year| > 9999"));
        }
        (
            YearKind::Big {
                value: if negative { -mantissa } else { mantissa },
            },
            mantissa_len as u64,
        )
    };
    let significant = if c.eat(b'S') {
        let sig_off = c.pos();
        let (n, len) = c.take_number()?;
        let sig = u32::try_from(n)
            .ok()
            .filter(|s| *s >= 1 && u64::from(*s) <= digit_count);
        if len == 0 || sig.is_none() {
            return Err(err(
                sig_off,
                "significant digits exceed the year's digit count",
            ));
        }
        sig
    } else {
        None
    };
    let mut qualifier = Qualifier::default();
    if let Some(q) = c.take_qualifier() {
        qualifier.merge(q);
    }
    if !c.eof() {
        return Err(c.fail("Y-prefixed years are year-precision only"));
    }
    Ok(Date {
        year: Year {
            kind,
            significant_digits: significant,
            qualifier,
        },
        month: None,
        day: None,
    })
}

// ---------------------------------------------------------------- datetime

fn parse_datetime(s: &str) -> Result<Edtf, ParseError> {
    // The dispatcher only routes strings containing 'T' here; a graceful
    // error beats a library panic if that invariant ever breaks.
    let Some((date_part, time_part)) = s.split_once('T') else {
        return Err(err(0, "datetime requires 'T'"));
    };
    let date = parse_plain_complete_date(date_part)?;
    let time = parse_time(time_part, date_part.len() + 1)?;
    Ok(Edtf::DateTime(DateTime { date, time }))
}

/// Date-times exist only at level 0: a plain, complete, unqualified
/// YYYY-MM-DD (Annex A.4.3).
fn parse_plain_complete_date(s: &str) -> Result<Date, ParseError> {
    let b = s.as_bytes();
    if b.len() != 10 || b[4] != b'-' || b[7] != b'-' {
        return Err(err(0, "date-times require a complete YYYY-MM-DD date"));
    }
    let digit = |i: usize| -> Result<u8, ParseError> {
        match b[i] {
            d @ b'0'..=b'9' => Ok(d - b'0'),
            _ => Err(err(i, "date-times require a plain all-digit date")),
        }
    };
    let ydigits = [
        Some(digit(0)?),
        Some(digit(1)?),
        Some(digit(2)?),
        Some(digit(3)?),
    ];
    let month = DateField {
        digits: [Some(digit(5)?), Some(digit(6)?)],
        qualifier: Qualifier::default(),
    };
    let day = DateField {
        digits: [Some(digit(8)?), Some(digit(9)?)],
        qualifier: Qualifier::default(),
    };
    // Both digits were just parsed; a graceful error beats a panic if that
    // invariant ever breaks.
    let Some(m) = month.value() else {
        return Err(err(5, "month must be fully specified"));
    };
    if !(1..=12).contains(&m) {
        return Err(err(5, "month must be 01-12"));
    }
    let kind = YearKind::Standard {
        negative: false,
        digits: ydigits,
    };
    if !day_has_valid_completion(&kind, month, day) {
        return Err(err(8, "day is out of range for the month"));
    }
    Ok(Date {
        year: Year {
            kind,
            significant_digits: None,
            qualifier: Qualifier::default(),
        },
        month: Some(month),
        day: Some(day),
    })
}

fn parse_time(s: &str, base: usize) -> Result<Time, ParseError> {
    let b = s.as_bytes();
    if b.len() < 8 || b[2] != b':' || b[5] != b':' {
        return Err(err(base, "time must be hh:mm:ss"));
    }
    let two = |i: usize| -> Result<u8, ParseError> {
        match (b[i], b[i + 1]) {
            (t @ b'0'..=b'9', o @ b'0'..=b'9') => Ok((t - b'0') * 10 + (o - b'0')),
            _ => Err(err(base + i, "time components must be two digits")),
        }
    };
    let hour = two(0)?;
    let minute = two(3)?;
    let second = two(6)?;
    if hour > 23 {
        return Err(err(base, "hour must be 00-23 (24 is not allowed)"));
    }
    if minute > 59 {
        return Err(err(base + 3, "minute must be 00-59"));
    }
    // 60 admits a leap second; not verified against the leap-second table
    // (decision D3).
    if second > 60 {
        return Err(err(base + 6, "second must be 00-60"));
    }
    let rest = &s[8..];
    let shift = if rest.is_empty() {
        None
    } else if rest == "Z" {
        Some(TimeShift::Utc)
    } else {
        Some(parse_shift(rest, base + 8)?)
    };
    Ok(Time {
        hour,
        minute,
        second,
        shift,
    })
}

fn parse_shift(s: &str, base: usize) -> Result<TimeShift, ParseError> {
    let b = s.as_bytes();
    let negative = match b[0] {
        b'+' => false,
        b'-' => true,
        _ => return Err(err(base, "time shift must be Z, +hh, +hh:mm or negative")),
    };
    let (hours, minutes, hours_only) = match b.len() {
        3 => {
            let h = shift_two(b, 1, base)?;
            (h, 0, true)
        },
        6 if b[3] == b':' => {
            let h = shift_two(b, 1, base)?;
            let m = shift_two(b, 4, base)?;
            (h, m, false)
        },
        _ => return Err(err(base, "time shift must be ±hh or ±hh:mm")),
    };
    if minutes > 59 {
        return Err(err(base + 4, "shift minutes must be 00-59"));
    }
    let total = i16::from(hours) * 60 + i16::from(minutes);
    if total > 14 * 60 {
        return Err(err(base, "time shift exceeds ±14:00"));
    }
    if negative && total == 0 {
        return Err(err(base, "negative zero time shift is not allowed"));
    }
    Ok(TimeShift::Offset {
        minutes: if negative { -total } else { total },
        hours_only,
    })
}

fn shift_two(b: &[u8], i: usize, base: usize) -> Result<u8, ParseError> {
    match (b[i], b[i + 1]) {
        (t @ b'0'..=b'9', o @ b'0'..=b'9') => Ok((t - b'0') * 10 + (o - b'0')),
        _ => Err(err(base + i, "time shift components must be two digits")),
    }
}

// ---------------------------------------------------------------- intervals

fn parse_interval(s: &str) -> Result<Edtf, ParseError> {
    let mut parts = s.splitn(3, '/');
    let start_str = parts.next().unwrap_or("");
    let end_str = parts
        .next()
        .ok_or_else(|| err(s.len(), "interval requires '/'"))?;
    if parts.next().is_some() {
        return Err(err(
            offset_in(s, end_str) + end_str.len(),
            "interval must contain exactly one '/'",
        ));
    }
    let start = parse_endpoint(start_str, offset_in(s, start_str), true)?;
    let end = parse_endpoint(end_str, offset_in(s, end_str), false)?;
    if !start.is_dated() && !end.is_dated() {
        return Err(err(0, "interval needs at least one dated endpoint"));
    }
    // The end must not precede the start (decision D18; cf. ISO 8601-2
    // §7.14.2 Example 2). Comparable only when both endpoints are dates.
    if let (IntervalEndpoint::Date(a), IntervalEndpoint::Date(b)) = (&start, &end) {
        if dates_out_of_order(a, b) {
            return Err(err(
                offset_in(s, end_str),
                "interval end precedes interval start",
            ));
        }
    }
    Ok(Edtf::Interval(Interval { start, end }))
}

fn parse_endpoint(s: &str, base: usize, is_start: bool) -> Result<IntervalEndpoint, ParseError> {
    if s.is_empty() {
        return Ok(IntervalEndpoint::Unknown);
    }
    if s == ".." {
        return Ok(IntervalEndpoint::Open);
    }
    if let Some(rest) = s.strip_prefix("..") {
        if !is_start {
            return Err(err(
                base,
                "'..'-prefixed date is only allowed as interval start",
            ));
        }
        return Ok(IntervalEndpoint::OnOrBefore(parse_date_at(rest, base + 2)?));
    }
    if let Some(rest) = s.strip_suffix("..") {
        if is_start {
            return Err(err(
                base + rest.len(),
                "'..'-suffixed date is only allowed as interval end",
            ));
        }
        return Ok(IntervalEndpoint::OnOrAfter(parse_date_at(rest, base)?));
    }
    Ok(IntervalEndpoint::Date(parse_date_at(s, base)?))
}

/// True when `a` cannot possibly precede-or-touch `b`: a's earliest possible
/// day is later than b's latest possible day.
fn dates_out_of_order(a: &Date, b: &Date) -> bool {
    match (date_bounds(a).earliest, date_bounds(b).latest) {
        (Bound::Date(lo), Bound::Date(hi)) => lo > hi,
        _ => false,
    }
}

// ---------------------------------------------------------------- sets

fn parse_set(s: &str) -> Result<Edtf, ParseError> {
    let b = s.as_bytes();
    let (kind, close) = match b[0] {
        b'{' => (SetKind::AllMembers, b'}'),
        _ => (SetKind::OneMember, b']'),
    };
    if b.len() < 2 || b[b.len() - 1] != close {
        return Err(err(s.len().saturating_sub(1), "unterminated set"));
    }
    let inner = &s[1..s.len() - 1];
    if inner.is_empty() {
        return Err(err(1, "set must contain at least one element"));
    }
    if let Some(pos) = inner
        .bytes()
        .position(|c| matches!(c, b'{' | b'}' | b'[' | b']'))
    {
        return Err(err(1 + pos, "sets cannot nest"));
    }
    let mut elements = Vec::new();
    for part in inner.split(',') {
        let part_off = offset_in(s, part);
        if part.is_empty() {
            return Err(err(part_off, "empty set element"));
        }
        elements.push(parse_set_element(part, part_off)?);
    }
    Ok(Edtf::Set(Set { kind, elements }))
}

fn parse_set_element(p: &str, base: usize) -> Result<SetElement, ParseError> {
    if p == ".." {
        return Err(err(base, "'..' alone is not a set element"));
    }
    if let Some(rest) = p.strip_prefix("..") {
        return Ok(SetElement::OnOrBefore(parse_date_at(rest, base + 2)?));
    }
    if let Some(rest) = p.strip_suffix("..") {
        return Ok(SetElement::OnOrAfter(parse_date_at(rest, base)?));
    }
    if let Some(idx) = p.find("..") {
        let (a, b) = (&p[..idx], &p[idx + 2..]);
        if b.contains("..") {
            return Err(err(
                base + idx + 2,
                "set element cannot contain multiple '..'",
            ));
        }
        let from = parse_date_at(a, base)?;
        let to = parse_date_at(b, base + idx + 2)?;
        check_range_endpoint(&from, base)?;
        check_range_endpoint(&to, base + idx + 2)?;
        if from.precision() != to.precision() {
            return Err(err(
                base + idx + 2,
                "set range endpoints must share precision",
            ));
        }
        if dates_out_of_order(&from, &to) {
            return Err(err(base + idx + 2, "set range end precedes range start"));
        }
        return Ok(SetElement::Range(from, to));
    }
    Ok(SetElement::Date(parse_date_at(p, base)?))
}

/// A `..` range endpoint must denote a single concrete calendar value at
/// year, month or day precision (decision D27): every expansion example in
/// ISO 8601-2 §6.3 c/§6.4 uses plain dates, both sides "should be of the
/// same precision", a mask-carrying endpoint would make the range a relation
/// between value *sets*, seasons have no spec-defined successor, and a
/// qualifier on an endpoint has no defined spread over the expanded members.
fn check_range_endpoint(d: &Date, off: usize) -> Result<(), ParseError> {
    if d.has_unspecified() {
        return Err(err(
            off,
            "set range endpoints cannot contain unspecified digits",
        ));
    }
    if d.is_uncertain() || d.is_approximate() {
        return Err(err(off, "set range endpoints cannot be qualified"));
    }
    if d.precision() == Precision::Season {
        return Err(err(off, "set range endpoints cannot be seasons"));
    }
    if d.year.significant_digits.is_some() {
        return Err(err(
            off,
            "set range endpoints cannot carry significant digits",
        ));
    }
    Ok(())
}