razeri-plugin-contract 0.7.0

The dialect contract Razeri plugins are written against — rendering traits, data types, platform identity
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
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! **How a source spells a day** — the format a design states, read once and
//! handed to every engine as a list rather than as text.
//!
//! One import arrives with `1/1/2015` in one column and `2015-01-01T00:00:00Z`
//! in the next, and a warehouse that converts either of them by asking the
//! engine to guess gets a different answer on every engine and on some of them
//! a different answer on a different server. So the design says the spelling,
//! and this is what the spelling is.
//!
//! ## Why a list and not a string
//!
//! No two engines share a pattern language. `%m/%d/%Y` is `MM/DD/YYYY` on one
//! family, `MM/dd/yyyy` on another, and a style number on a third. Handing the
//! authored text through to an engine would mean each engine parsing it again,
//! each one accepting a slightly different set of directives, and a directive
//! nobody supports arriving at the database rather than at the door. Reading
//! it once, here, gives every engine the same list to translate directive by
//! directive — and gives a directive an engine cannot spell a refusal that
//! names it.
//!
//! ## The two patterns
//!
//! Some engines answer nothing for a value they cannot read; some read it
//! anyway and hand back the wrong day. For the second kind a guard has to be
//! written beside the parse, and it has to come from the same list, or the
//! guard and the parse would be two opinions about one spelling.
//! [`DateFormat::shape_pattern`] is that guard, and
//! [`DateFormat::capture_pattern`] reads one field back out of the value so a
//! parse can be checked against what was written.

use std::fmt;

/// One thing a format says, in the strftime family's own vocabulary.
///
/// The list is what the family agrees on. A directive outside it is refused
/// by name when the design is read, rather than being passed to an engine that
/// would either ignore it or read it as something else.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FormatDirective {
    /// `%Y` — the year in four digits.
    Year4,
    /// `%y` — the year in two digits.
    Year2,
    /// `%m` — the month as a number.
    MonthNumber,
    /// `%d` — the day of the month, zero-padded or not.
    DayOfMonth,
    /// `%e` — the day of the month, space-padded or not.
    DayOfMonthSpaced,
    /// `%H` — the hour on a twenty-four hour clock.
    Hour24,
    /// `%I` — the hour on a twelve hour clock, read with [`Self::Meridiem`].
    Hour12,
    /// `%M` — the minute.
    Minute,
    /// `%S` — the second.
    Second,
    /// `%f` — the fraction of a second.
    Fraction,
    /// `%p` — `AM` or `PM`.
    Meridiem,
    /// `%j` — the day of the year.
    DayOfYear,
    /// `%b` — the month's name, abbreviated.
    MonthAbbrev,
    /// `%B` — the month's name in full.
    MonthName,
    /// `%a` — the weekday's name, abbreviated.
    WeekdayAbbrev,
    /// `%A` — the weekday's name in full.
    WeekdayName,
    /// `%z` — the offset from UTC, as `+0000` or `+00:00`.
    Offset,
    /// `%Z` — the time zone's name.
    ZoneName,
}

impl FormatDirective {
    /// The directive as a format writes it, `%` and all.
    #[must_use]
    pub fn spelled(self) -> &'static str {
        match self {
            Self::Year4 => "%Y",
            Self::Year2 => "%y",
            Self::MonthNumber => "%m",
            Self::DayOfMonth => "%d",
            Self::DayOfMonthSpaced => "%e",
            Self::Hour24 => "%H",
            Self::Hour12 => "%I",
            Self::Minute => "%M",
            Self::Second => "%S",
            Self::Fraction => "%f",
            Self::Meridiem => "%p",
            Self::DayOfYear => "%j",
            Self::MonthAbbrev => "%b",
            Self::MonthName => "%B",
            Self::WeekdayAbbrev => "%a",
            Self::WeekdayName => "%A",
            Self::Offset => "%z",
            Self::ZoneName => "%Z",
        }
    }

    /// What this directive is, in the words a refusal uses.
    #[must_use]
    pub fn means(self) -> &'static str {
        match self {
            Self::Year4 => "a four-digit year",
            Self::Year2 => "a two-digit year",
            Self::MonthNumber => "the month as a number",
            Self::DayOfMonth | Self::DayOfMonthSpaced => "the day of the month",
            Self::Hour24 => "the hour on a twenty-four hour clock",
            Self::Hour12 => "the hour on a twelve hour clock",
            Self::Minute => "the minute",
            Self::Second => "the second",
            Self::Fraction => "the fraction of a second",
            Self::Meridiem => "AM or PM",
            Self::DayOfYear => "the day of the year",
            Self::MonthAbbrev => "the month's name, abbreviated",
            Self::MonthName => "the month's name in full",
            Self::WeekdayAbbrev => "the weekday's name, abbreviated",
            Self::WeekdayName => "the weekday's name in full",
            Self::Offset => "the offset from UTC",
            Self::ZoneName => "the time zone's name",
        }
    }

    /// **True where this directive says something about a moment within a
    /// day** — an offset or a zone name, which a column holding a day alone
    /// has nowhere to put.
    #[must_use]
    pub fn names_a_zone(self) -> bool {
        matches!(self, Self::Offset | Self::ZoneName)
    }

    /// The directive one letter stands for, or `None` for a letter the family
    /// does not use.
    fn from_letter(letter: char) -> Option<Self> {
        Some(match letter {
            'Y' => Self::Year4,
            'y' => Self::Year2,
            'm' => Self::MonthNumber,
            'd' => Self::DayOfMonth,
            'e' => Self::DayOfMonthSpaced,
            'H' => Self::Hour24,
            'I' => Self::Hour12,
            'M' => Self::Minute,
            'S' => Self::Second,
            'f' => Self::Fraction,
            'p' => Self::Meridiem,
            'j' => Self::DayOfYear,
            'b' => Self::MonthAbbrev,
            'B' => Self::MonthName,
            'a' => Self::WeekdayAbbrev,
            'A' => Self::WeekdayName,
            'z' => Self::Offset,
            'Z' => Self::ZoneName,
            _ => return None,
        })
    }

    /// What a value spelled this way looks like, as a POSIX regular
    /// expression that holds each field to its own range. Grouped, because
    /// several of them are alternations; the group is never read back.
    fn shape(self) -> &'static str {
        match self {
            Self::Year4 => "([0-9]{4})",
            Self::Year2 => "([0-9]{2})",
            Self::MonthNumber | Self::Hour12 => "(0?[1-9]|1[0-2])",
            Self::DayOfMonth => "(0?[1-9]|[12][0-9]|3[01])",
            Self::DayOfMonthSpaced => "( ?[1-9]|[12][0-9]|3[01])",
            Self::Hour24 => "([01]?[0-9]|2[0-3])",
            Self::Minute | Self::Second => "([0-5]?[0-9])",
            Self::Fraction => "([0-9]{1,9})",
            Self::Meridiem => "([AaPp][Mm])",
            Self::DayOfYear => "(0{0,2}[1-9]|0?[1-9][0-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])",
            // **The names, written out.** A shape that accepted any run of
            // letters would hand `Xyz` to a reader that raises on a month it
            // does not know, which is the one thing a guard exists to stop.
            // Written in both cases per letter because the engines reading
            // this pattern match case as it stands.
            Self::MonthAbbrev => {
                "([Jj][Aa][Nn]|[Ff][Ee][Bb]|[Mm][Aa][Rr]|[Aa][Pp][Rr]|[Mm][Aa][Yy]|[Jj][Uu][Nn]|[Jj][Uu][Ll]|[Aa][Uu][Gg]|[Ss][Ee][Pp]|[Oo][Cc][Tt]|[Nn][Oo][Vv]|[Dd][Ee][Cc])"
            }
            Self::MonthName => {
                "([Jj][Aa][Nn][Uu][Aa][Rr][Yy]|[Ff][Ee][Bb][Rr][Uu][Aa][Rr][Yy]|[Mm][Aa][Rr][Cc][Hh]|[Aa][Pp][Rr][Ii][Ll]|[Mm][Aa][Yy]|[Jj][Uu][Nn][Ee]|[Jj][Uu][Ll][Yy]|[Aa][Uu][Gg][Uu][Ss][Tt]|[Ss][Ee][Pp][Tt][Ee][Mm][Bb][Ee][Rr]|[Oo][Cc][Tt][Oo][Bb][Ee][Rr]|[Nn][Oo][Vv][Ee][Mm][Bb][Ee][Rr]|[Dd][Ee][Cc][Ee][Mm][Bb][Ee][Rr])"
            }
            Self::WeekdayAbbrev => {
                "([Mm][Oo][Nn]|[Tt][Uu][Ee]|[Ww][Ee][Dd]|[Tt][Hh][Uu]|[Ff][Rr][Ii]|[Ss][Aa][Tt]|[Ss][Uu][Nn])"
            }
            Self::WeekdayName => {
                "([Mm][Oo][Nn][Dd][Aa][Yy]|[Tt][Uu][Ee][Ss][Dd][Aa][Yy]|[Ww][Ee][Dd][Nn][Ee][Ss][Dd][Aa][Yy]|[Tt][Hh][Uu][Rr][Ss][Dd][Aa][Yy]|[Ff][Rr][Ii][Dd][Aa][Yy]|[Ss][Aa][Tt][Uu][Rr][Dd][Aa][Yy]|[Ss][Uu][Nn][Dd][Aa][Yy])"
            }
            Self::Offset => "([+-][0-9]{2}:?[0-9]{2}|[Zz])",
            Self::ZoneName => "([A-Za-z_/+-]+)",
        }
    }

    /// The loosest thing this directive can stand for, written without a
    /// group so that a pattern reading one field back has exactly one.
    fn loose(self) -> &'static str {
        match self {
            Self::Year4 => "[0-9]{4}",
            Self::Year2 => "[0-9]{2}",
            Self::MonthNumber
            | Self::DayOfMonth
            | Self::Hour24
            | Self::Hour12
            | Self::Minute
            | Self::Second => "[0-9]{1,2}",
            Self::DayOfMonthSpaced => "[ 0-9]{1,2}",
            Self::Fraction => "[0-9]{1,9}",
            Self::Meridiem => "[AaPp][Mm]",
            Self::DayOfYear => "[0-9]{1,3}",
            Self::MonthAbbrev | Self::MonthName | Self::WeekdayAbbrev | Self::WeekdayName => {
                "[A-Za-z]+"
            }
            Self::Offset => "[Zz+:0-9-]{1,6}",
            Self::ZoneName => "[A-Za-z_/+-]+",
        }
    }
}

impl fmt::Display for FormatDirective {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.spelled())
    }
}

/// One piece of a format: something the source writes literally, or one of the
/// things the format says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormatPart {
    /// Text the value carries as it stands — a slash, a dash, a space, a `T`.
    Literal(String),
    /// One of the values the format reads.
    Directive(FormatDirective),
}

/// What is wrong with a format, in the words the refusal uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DateFormatError {
    /// A `%` followed by a letter no format directive uses.
    UnknownDirective(char),
    /// A `%` with nothing after it.
    DanglingPercent,
    /// A format saying nothing at all.
    Empty,
}

impl fmt::Display for DateFormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownDirective(letter) => write!(
                f,
                "`%{letter}` is not something a format can say. The directives are `%Y` `%y` \
                 `%m` `%d` `%e` `%H` `%I` `%M` `%S` `%f` `%p` `%j` `%b` `%B` `%a` `%A` `%z` `%Z` \
                 and `%%` for a literal percent sign; everything else in a format is written the \
                 way the value writes it"
            ),
            Self::DanglingPercent => f.write_str(
                "the format ends in a `%` with nothing after it. Name what comes there, or write \
                 `%%` for a literal percent sign",
            ),
            Self::Empty => f.write_str(
                "the format is empty. Write how the source spells the value — `%m/%d/%Y` for \
                 `1/1/2015`, `%Y-%m-%d` for `2015-01-01`",
            ),
        }
    }
}

impl std::error::Error for DateFormatError {}

/// **A source's spelling, read once.**
///
/// Built from the authored text and never rebuilt: every engine translates the
/// same list, so two engines cannot disagree about what the design said.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DateFormat {
    spelled: String,
    parts: Vec<FormatPart>,
}

impl DateFormat {
    /// Read a format, or say what is wrong with it.
    ///
    /// # Errors
    ///
    /// A `%` followed by a letter outside the family, a `%` at the end with
    /// nothing after it, or nothing at all.
    pub fn parse(spelled: &str) -> Result<Self, DateFormatError> {
        if spelled.is_empty() {
            return Err(DateFormatError::Empty);
        }
        let mut parts: Vec<FormatPart> = Vec::new();
        let mut literal = String::new();
        let mut letters = spelled.chars();
        while let Some(character) = letters.next() {
            if character != '%' {
                literal.push(character);
                continue;
            }
            let Some(next) = letters.next() else {
                return Err(DateFormatError::DanglingPercent);
            };
            if next == '%' {
                literal.push('%');
                continue;
            }
            let Some(directive) = FormatDirective::from_letter(next) else {
                return Err(DateFormatError::UnknownDirective(next));
            };
            if !literal.is_empty() {
                parts.push(FormatPart::Literal(std::mem::take(&mut literal)));
            }
            parts.push(FormatPart::Directive(directive));
        }
        if !literal.is_empty() {
            parts.push(FormatPart::Literal(literal));
        }
        Ok(Self { spelled: spelled.to_owned(), parts })
    }

    /// The format as the design wrote it — what a refusal quotes back.
    #[must_use]
    pub fn spelled(&self) -> &str {
        &self.spelled
    }

    /// The pieces, in the order the value writes them.
    #[must_use]
    pub fn parts(&self) -> &[FormatPart] {
        &self.parts
    }

    /// Every directive the format says, in order, literals passed over.
    pub fn directives(&self) -> impl Iterator<Item = FormatDirective> + '_ {
        self.parts.iter().filter_map(|part| match part {
            FormatPart::Directive(directive) => Some(*directive),
            FormatPart::Literal(_) => None,
        })
    }

    /// **True where the format carries an offset or a zone name** — the two
    /// things a column holding a day alone has nowhere to put.
    #[must_use]
    pub fn names_a_zone(&self) -> bool {
        self.directives().any(FormatDirective::names_a_zone)
    }

    /// **True where the format says anything about the time within a day.**
    #[must_use]
    pub fn says_a_time_of_day(&self) -> bool {
        self.directives().any(|directive| {
            matches!(
                directive,
                FormatDirective::Hour24
                    | FormatDirective::Hour12
                    | FormatDirective::Minute
                    | FormatDirective::Second
                    | FormatDirective::Fraction
                    | FormatDirective::Meridiem
            )
        })
    }

    /// **Translate the format into one engine's own pattern language**,
    /// directive by directive.
    ///
    /// `spell` answers with this engine's token for one directive, or `None`
    /// where the engine has no way to say it; `literal` writes a run of
    /// literal text the way this engine's patterns want it, which on some is
    /// the text as it stands and on others is the text in quotes.
    ///
    /// # Errors
    ///
    /// The first directive `spell` answered `None` for — which is what the
    /// refusal names, so an author is told which part of their format this
    /// engine cannot read rather than that the format failed.
    pub fn translate(
        &self,
        spell: &dyn Fn(FormatDirective) -> Option<&'static str>,
        literal: &dyn Fn(&str) -> String,
    ) -> Result<String, FormatDirective> {
        let mut pattern = String::new();
        for part in &self.parts {
            match part {
                FormatPart::Literal(text) => pattern.push_str(&literal(text)),
                FormatPart::Directive(directive) => {
                    pattern.push_str(spell(*directive).ok_or(*directive)?);
                }
            }
        }
        Ok(pattern)
    }

    /// **A guard against a value spelled some other way**, as an anchored
    /// POSIX regular expression that holds every field to its own range.
    ///
    /// It is for the engines that read a value they cannot read: hand
    /// `13/45/2015` to a parse that rolls fields over and it answers a day in
    /// 2016 rather than answering nothing. The guard is built from the same
    /// list the parse is, so the two cannot disagree about what the design
    /// said.
    ///
    /// **What it holds and what it does not.** Every field is held to its own
    /// range — a month is 1 to 12, an hour is 0 to 23 — so a value written
    /// some other way, or holding a number no calendar has, is caught. A day
    /// that is in range and yet not in its month, the thirty-first of a
    /// thirty-day month, is not a question a shape can answer; the engines
    /// that need this guard say in their own rendering what they do about it.
    #[must_use]
    pub fn shape_pattern(&self) -> String {
        let mut pattern = String::from("^");
        for part in &self.parts {
            match part {
                FormatPart::Literal(text) => pattern.push_str(&escape_posix(text)),
                FormatPart::Directive(directive) => pattern.push_str(directive.shape()),
            }
        }
        pattern.push('$');
        pattern
    }

    /// **Read one field back out of the value**, as an anchored POSIX regular
    /// expression with exactly one capturing group around the field asked for.
    ///
    /// Everything else in it is loose and ungrouped, so the group an engine
    /// reads back is the first one and the only one — which is the most any
    /// of the engines needing it can address.
    ///
    /// `None` where the format does not say that field at all.
    #[must_use]
    pub fn capture_pattern(&self, wanted: FormatDirective) -> Option<String> {
        let mut found = false;
        let mut pattern = String::from("^");
        for part in &self.parts {
            match part {
                FormatPart::Literal(text) => pattern.push_str(&escape_posix(text)),
                FormatPart::Directive(directive) if *directive == wanted && !found => {
                    found = true;
                    pattern.push('(');
                    pattern.push_str(directive.loose());
                    pattern.push(')');
                }
                FormatPart::Directive(directive) => pattern.push_str(directive.loose()),
            }
        }
        pattern.push('$');
        found.then_some(pattern)
    }
}

impl fmt::Display for DateFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.spelled)
    }
}

/// Write literal text so a regular expression reads it as itself.
fn escape_posix(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for character in text.chars() {
        if "\\^$.[]|()*+?{}".contains(character) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped
}

#[cfg(test)]
mod tests {
    use super::{DateFormat, DateFormatError, FormatDirective, FormatPart};

    /// The retailer's own spelling, read into the three things it says and the
    /// two slashes between them.
    #[test]
    fn a_day_spelled_with_slashes_reads_as_five_pieces() {
        let format = DateFormat::parse("%m/%d/%Y").expect("a lawful format");
        assert_eq!(
            format.parts(),
            [
                FormatPart::Directive(FormatDirective::MonthNumber),
                FormatPart::Literal("/".into()),
                FormatPart::Directive(FormatDirective::DayOfMonth),
                FormatPart::Literal("/".into()),
                FormatPart::Directive(FormatDirective::Year4),
            ]
        );
        assert_eq!(format.spelled(), "%m/%d/%Y");
        assert!(!format.says_a_time_of_day());
        assert!(!format.names_a_zone());
    }

    /// Every directive the family has is read, and each one keeps its letter.
    #[test]
    fn every_directive_in_the_family_is_read() {
        let every = "%Y %y %m %d %e %H %I %M %S %f %p %j %b %B %a %A %z %Z";
        let format = DateFormat::parse(every).expect("a lawful format");
        let read: Vec<_> = format.directives().map(FormatDirective::spelled).collect();
        assert_eq!(
            read,
            [
                "%Y", "%y", "%m", "%d", "%e", "%H", "%I", "%M", "%S", "%f", "%p", "%j", "%b", "%B",
                "%a", "%A", "%z", "%Z"
            ]
        );
        assert!(format.names_a_zone());
        assert!(format.says_a_time_of_day());
    }

    /// A doubled percent sign is one literal percent sign, and says nothing.
    #[test]
    fn a_doubled_percent_is_a_literal_one() {
        let format = DateFormat::parse("%d%%%m").expect("a lawful format");
        assert_eq!(
            format.parts(),
            [
                FormatPart::Directive(FormatDirective::DayOfMonth),
                FormatPart::Literal("%".into()),
                FormatPart::Directive(FormatDirective::MonthNumber),
            ]
        );
    }

    /// A letter the family does not use is refused by name rather than passed
    /// through to an engine that would read it as something else.
    #[test]
    fn a_letter_the_family_does_not_use_is_refused_by_name() {
        assert_eq!(DateFormat::parse("%Q-%m"), Err(DateFormatError::UnknownDirective('Q')));
        assert!(DateFormat::parse("%Q").unwrap_err().to_string().contains("`%Q`"));
    }

    /// A trailing percent sign says nothing and is refused as itself.
    #[test]
    fn a_trailing_percent_is_refused() {
        assert_eq!(DateFormat::parse("%Y-%m-%d %"), Err(DateFormatError::DanglingPercent));
        assert_eq!(DateFormat::parse(""), Err(DateFormatError::Empty));
    }

    /// A translation is directive by directive, and the first directive an
    /// engine cannot say is what comes back.
    #[test]
    fn a_translation_names_the_directive_the_engine_cannot_say() {
        let format = DateFormat::parse("%Y-%m-%dT%H:%M:%S%z").expect("a lawful format");
        let spell = |directive: FormatDirective| match directive {
            FormatDirective::Year4 => Some("yyyy"),
            FormatDirective::MonthNumber => Some("MM"),
            FormatDirective::DayOfMonth => Some("dd"),
            FormatDirective::Hour24 => Some("HH"),
            FormatDirective::Minute => Some("mm"),
            FormatDirective::Second => Some("ss"),
            _ => None,
        };
        assert_eq!(
            format.translate(&spell, &|text| format!("'{text}'")),
            Err(FormatDirective::Offset)
        );
        let without = DateFormat::parse("%Y-%m-%d").expect("a lawful format");
        assert_eq!(
            without.translate(&spell, &|text: &str| text.to_owned()),
            Ok("yyyy-MM-dd".to_owned())
        );
    }

    /// The guard holds each field to its own range, and the field it reads
    /// back is the only group in its own pattern.
    #[test]
    fn the_guard_and_the_read_back_come_from_one_list() {
        let format = DateFormat::parse("%m/%d/%Y").expect("a lawful format");
        assert_eq!(
            format.shape_pattern(),
            "^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/([0-9]{4})$"
        );
        assert_eq!(
            format.capture_pattern(FormatDirective::DayOfMonth).as_deref(),
            Some("^[0-9]{1,2}/([0-9]{1,2})/[0-9]{4}$")
        );
        assert_eq!(format.capture_pattern(FormatDirective::Hour24), None);
    }

    /// A literal that would mean something to a regular expression is written
    /// so that it means itself.
    #[test]
    fn a_literal_dot_means_a_dot() {
        let format = DateFormat::parse("%d.%m.%Y").expect("a lawful format");
        assert!(format.shape_pattern().contains("\\."));
    }
}