razeri-plugin-contract 0.8.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
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
// 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 writes an amount** — the picture a design states, read once
//! and handed to every engine as a small set of facts rather than as text.
//!
//! A file writes a price `$2,899.99 `. The dollar sign is not part of the
//! number, the comma is not a decimal point, and the trailing space is not
//! anything at all. Handed to an engine as it stands, that text converts to
//! nothing on one engine, to `2` on another and to an error on a third. So the
//! design says how the source writes it, and this is what that statement is.
//!
//! ## The picture
//!
//! A format is written the way a spreadsheet writes one: the value with its
//! digits replaced by digit places.
//!
//! ```text
//! $#,##0.00      $2,899.99        a dollar sign, thousands in groups of
//!                                 three, two places after the point
//! #,##0          2,899            a whole number written in groups
//! 0.000          1.158            three places after the point and no
//!                                 grouping
//! #,##0.00 kr    2 899,00 kr      no — see below
//! ```
//!
//! - `0` and `#` are digit places. Both mean *digits go here*; a reader does
//!   not care which, and the two are allowed side by side because that is how
//!   the picture is normally written.
//! - `,` is the thousands mark and `.` is the decimal point. They mean that
//!   whichever characters the picture uses, so a picture writing them the
//!   other way round is refused rather than read backwards. A source that
//!   writes `2.899,99` is not covered today, and the refusal says so.
//! - Everything before the first digit place is the symbol that opens the
//!   value, and everything after the last digit place is the symbol that
//!   closes it. Either may be empty.
//! - A space around the whole value is always allowed and never written in
//!   the picture. `$2,899.99 ` and `$2,899.99` are the same value.
//! - A minus sign in front of the value is always allowed. A source that
//!   writes a negative in brackets instead says so with a second picture
//!   after a semicolon: `$#,##0.00;($#,##0.00)`.
//!
//! ## What an engine does with it
//!
//! The picture names the marks that are not part of the number. A reader takes
//! those marks out and converts what is left, so the work every engine has to
//! do is the same work, and the value that lands is the same value. What
//! differs between engines is only how each one spells *take this out* and
//! *convert this, and answer nothing if you cannot* —
//! [`read_with_safe_cast`], [`read_with_pattern_guard`] and
//! [`read_with_digit_check`] are those three answers, written once here so an
//! engine states its own vocabulary rather than its own rules.

use std::fmt;

use crate::DataType;
use crate::sid::normalize_trim;
use crate::sid_spelling::SidSpelling;

/// How the source writes a value below zero.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Negatives {
    /// A minus sign in front of the value — `-2,899.99`. The ordinary case,
    /// and what a picture with no second half means.
    Minus,
    /// Brackets around the whole value — `($2,899.99)`, the way a ledger
    /// writes one. Stated with a second picture after a semicolon.
    Parentheses,
}

/// What is wrong with a picture, in the words the refusal uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NumberFormatError {
    /// A picture saying nothing at all.
    Empty,
    /// A picture with no digit place in it.
    NoDigits,
    /// A thousands mark after the decimal point.
    MarkAfterPoint,
    /// More than one decimal point.
    TwoPoints,
    /// A thousands mark with something other than three digit places after it.
    GroupIsNotThree(usize),
    /// A digit place after the symbol that closes the value.
    DigitsAfterSymbol,
    /// More than two pictures separated by semicolons.
    TooManyPictures,
    /// A second picture that is not the first one in brackets.
    NegativeIsNotBracketed,
}

impl fmt::Display for NumberFormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str(
                "the format is empty. Write how the source writes the value, with its digits \
                 replaced by digit places — `$#,##0.00` for `$2,899.99`, `0.000` for `1.158`",
            ),
            Self::NoDigits => f.write_str(
                "the format holds no digit place, so there is no number in it. A digit place is \
                 `0` or `#` — `$#,##0.00` for `$2,899.99`",
            ),
            Self::MarkAfterPoint => f.write_str(
                "the format puts a `,` after the `.`. In a picture `,` is the thousands mark and \
                 `.` is the decimal point, whichever characters the source itself uses, so the \
                 thousands come first. A source that writes `2.899,99` is not covered today",
            ),
            Self::TwoPoints => f.write_str(
                "the format has two decimal points, and a number has one. If one of them is the \
                 thousands mark, write it as `,` — `$#,##0.00` is two thousand eight hundred and \
                 ninety-nine point nine nine",
            ),
            Self::GroupIsNotThree(places) => write!(
                f,
                "the format puts {places} digit place(s) after a `,`, and a thousands mark \
                 separates groups of three. Write `#,##0` for a number written `2,899`"
            ),
            Self::DigitsAfterSymbol => f.write_str(
                "the format has digit places on both sides of the symbol. The symbol opens the \
                 value or closes it — `$#,##0.00` or `#,##0.00 kr` — and a number written in two \
                 halves is not covered",
            ),
            Self::TooManyPictures => f.write_str(
                "the format holds more than two pictures. One picture says how the source writes \
                 a value; a second, after a `;`, says how it writes a negative one",
            ),
            Self::NegativeIsNotBracketed => f.write_str(
                "the second picture is not the first one in brackets. It says the source writes a \
                 negative the way a ledger does, so it is the first picture inside `(` and `)` — \
                 `$#,##0.00;($#,##0.00)`. A source that writes a leading minus needs no second \
                 picture at all",
            ),
        }
    }
}

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

/// **How a source writes an amount, read once.**
///
/// Built from the authored picture and never rebuilt: every engine is handed
/// the same facts, so two engines cannot disagree about what the design said.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumberFormat {
    spelled: String,
    opens_with: String,
    closes_with: String,
    grouped: bool,
    decimals: usize,
    negatives: Negatives,
}

/// The characters a picture reserves for itself.
const DIGIT_PLACES: [char; 2] = ['#', '0'];
const THOUSANDS_MARK: char = ',';
const DECIMAL_POINT: char = '.';

impl NumberFormat {
    /// Read a picture, or say what is wrong with it.
    ///
    /// # Errors
    ///
    /// Nothing at all, no digit place, a thousands mark in the wrong place or
    /// with the wrong number of places after it, two decimal points, digits on
    /// both sides of the symbol, or a second picture that is not the first one
    /// in brackets.
    pub fn parse(spelled: &str) -> Result<Self, NumberFormatError> {
        if spelled.is_empty() {
            return Err(NumberFormatError::Empty);
        }
        let mut pictures = spelled.split(';');
        let positive = pictures.next().unwrap_or_default();
        let negative = pictures.next();
        if pictures.next().is_some() {
            return Err(NumberFormatError::TooManyPictures);
        }
        let mut read = Self::read_one(positive)?;
        if let Some(negative) = negative {
            if negative != format!("({positive})") {
                return Err(NumberFormatError::NegativeIsNotBracketed);
            }
            read.negatives = Negatives::Parentheses;
        }
        spelled.clone_into(&mut read.spelled);
        Ok(read)
    }

    /// One picture — the symbol that opens the value, the number, the symbol
    /// that closes it.
    fn read_one(picture: &str) -> Result<Self, NumberFormatError> {
        let is_body = |c: char| DIGIT_PLACES.contains(&c) || c == THOUSANDS_MARK;
        let first =
            picture.find(|c| DIGIT_PLACES.contains(&c)).ok_or(NumberFormatError::NoDigits)?;
        let opens_with = picture[..first].to_owned();
        let rest = &picture[first..];

        // The number runs to the end of the digit places, the thousands marks
        // and the one decimal point with its places.
        let mut body = String::new();
        let mut seen_point = false;
        let mut closes_at = rest.len();
        for (at, character) in rest.char_indices() {
            if is_body(character) {
                if seen_point && character == THOUSANDS_MARK {
                    return Err(NumberFormatError::MarkAfterPoint);
                }
                body.push(character);
                continue;
            }
            if character == DECIMAL_POINT {
                if seen_point {
                    return Err(NumberFormatError::TwoPoints);
                }
                seen_point = true;
                body.push(character);
                continue;
            }
            closes_at = at;
            break;
        }
        let closes_with = rest[closes_at..].to_owned();
        if closes_with.contains(DIGIT_PLACES) {
            return Err(NumberFormatError::DigitsAfterSymbol);
        }

        let (whole, fraction) = match body.split_once(DECIMAL_POINT) {
            Some((whole, fraction)) => (whole, fraction),
            None => (body.as_str(), ""),
        };
        if fraction.contains(THOUSANDS_MARK) {
            return Err(NumberFormatError::MarkAfterPoint);
        }
        let grouped = whole.contains(THOUSANDS_MARK);
        if grouped {
            for group in whole.split(THOUSANDS_MARK).skip(1) {
                if group.chars().count() != 3 {
                    return Err(NumberFormatError::GroupIsNotThree(group.chars().count()));
                }
            }
        }

        Ok(Self {
            spelled: picture.to_owned(),
            opens_with,
            closes_with,
            grouped,
            decimals: fraction.chars().count(),
            negatives: Negatives::Minus,
        })
    }

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

    /// The symbol in front of the value, empty where there is none.
    #[must_use]
    pub fn opens_with(&self) -> &str {
        &self.opens_with
    }

    /// The symbol after the value, empty where there is none.
    #[must_use]
    pub fn closes_with(&self) -> &str {
        &self.closes_with
    }

    /// Whether the source writes the thousands in groups.
    #[must_use]
    pub fn grouped(&self) -> bool {
        self.grouped
    }

    /// How many places the source writes after the decimal point.
    #[must_use]
    pub fn decimals(&self) -> usize {
        self.decimals
    }

    /// How the source writes a value below zero.
    #[must_use]
    pub fn negatives(&self) -> Negatives {
        self.negatives
    }

    /// **The marks that are not part of the number**, in the order a reader
    /// takes them out.
    ///
    /// The symbol that opens the value, the symbol that closes it, the
    /// thousands mark, and the brackets where the source writes a negative in
    /// them. What is left is digits, at most one decimal point and at most a
    /// leading minus.
    #[must_use]
    pub fn marks(&self) -> Vec<String> {
        let mut marks = Vec::new();
        if !self.opens_with.is_empty() {
            marks.push(self.opens_with.clone());
        }
        if !self.closes_with.is_empty() {
            marks.push(self.closes_with.clone());
        }
        if self.grouped {
            marks.push(THOUSANDS_MARK.to_string());
        }
        if self.negatives == Negatives::Parentheses {
            marks.push("(".to_owned());
            marks.push(")".to_owned());
        }
        marks
    }

    /// **The shape a value has to have**, as a regular expression, for an
    /// engine whose own conversion raises rather than answering nothing.
    ///
    /// It is built from the same picture the marks come from, so the guard and
    /// the reading cannot hold two opinions about one spelling. The value is
    /// matched with its surrounding spaces already gone.
    #[must_use]
    pub fn shape_pattern(&self) -> String {
        let digits = if self.grouped { "[0-9][0-9,]*" } else { "[0-9]+" };
        let fraction = if self.decimals > 0 { "([.][0-9]+)?" } else { "" };
        let (open, close) = match self.negatives {
            Negatives::Minus => ("-?", ""),
            Negatives::Parentheses => ("[(]?", "[)]?"),
        };
        format!(
            "^{open}{}{digits}{fraction}{}{close}$",
            optional_literal(&self.opens_with),
            optional_literal(&self.closes_with),
        )
    }
}

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

/// One literal run, made safe for a regular expression and made optional.
///
/// Optional because a file that writes `$6.62` on most lines and `6.62` on one
/// has still written a price on both, and a reader that demanded the symbol
/// would set aside a row nothing is wrong with.
fn optional_literal(text: &str) -> String {
    if text.is_empty() {
        return String::new();
    }
    let mut pattern = String::new();
    for character in text.chars() {
        if character.is_ascii_alphanumeric() {
            pattern.push(character);
        } else {
            pattern.push('[');
            pattern.push(character);
            pattern.push(']');
        }
    }
    format!("({pattern})?")
}

/// **Whether this is a type an amount can land in.**
///
/// A picture says how a number is written down. On a name or a day there is
/// nothing for it to be about, so an engine asked to read one into anything
/// else states nothing and razeri refuses the column by name.
#[must_use]
pub fn is_a_number(target: &DataType) -> bool {
    matches!(target, DataType::Integer(_) | DataType::Decimal(_) | DataType::Float(_))
}

/// **The value with the picture's marks taken out**, in this engine's own
/// spelling of `TRIM` and `REPLACE`.
///
/// Those two words are already written down per engine, on the vocabulary the
/// surrogate key is derived through, and a second table of the same two words
/// would be a second answer to one question.
///
/// Parameters:
/// - `format`: the picture the design stated;
/// - `spelling`: this engine's vocabulary;
/// - `expr`: an already-rendered text expression.
#[must_use]
pub fn strip_marks(format: &NumberFormat, spelling: SidSpelling, expr: &str) -> String {
    let replace = spelling.lower.replace;
    let prefix = spelling.lower.pattern_literal_prefix;
    format.marks().iter().fold(normalize_trim(spelling, expr), |text, mark| {
        format!("{replace}({text}, {prefix}'{}', {prefix}'')", mark.replace('\'', "''"))
    })
}

/// **The one thing the picture's marks cannot come out of a value without.**
///
/// Taking the thousands mark out of `2.899,99` leaves `2.89999`, which
/// converts on every engine to a price nobody wrote — the worst answer
/// available, because it is a number and it is wrong. The picture says the
/// thousands come before the decimal point, so a value writing them after it
/// is not written that way, and this is that sentence as a condition.
///
/// `LIKE` and nothing else, because this has to hold on the engines with no
/// way to match a pattern as much as on the ones that have. `None` where the
/// picture names no thousands mark: there is nothing to take out of the wrong
/// place.
fn separators_in_order(format: &NumberFormat, spelling: SidSpelling, expr: &str) -> Option<String> {
    if !format.grouped() {
        return None;
    }
    let prefix = spelling.lower.pattern_literal_prefix;
    Some(format!(
        "{} NOT LIKE {prefix}'%{DECIMAL_POINT}%{THOUSANDS_MARK}%'",
        normalize_trim(spelling, expr)
    ))
}

/// **The sign a bracketed negative carries**, as a factor to multiply by.
///
/// A picture that says nothing about brackets needs no factor: the minus sign
/// the source writes survives the marks coming out, and the conversion reads
/// it.
fn bracket_sign(format: &NumberFormat, spelling: SidSpelling, expr: &str) -> Option<String> {
    if format.negatives() != Negatives::Parentheses {
        return None;
    }
    Some(format!("CASE WHEN {} LIKE '(%' THEN -1 ELSE 1 END", normalize_trim(spelling, expr)))
}

/// Multiply the reading by the sign, where the picture asks for one.
fn signed(reading: String, sign: Option<String>) -> String {
    match sign {
        None => reading,
        Some(sign) => format!("({reading}) * ({sign})"),
    }
}

/// **For an engine whose own conversion answers nothing for a value it cannot
/// read** — `TRY_CAST`, `SAFE_CAST`, `TRY_CONVERT` and their neighbours.
///
/// The marks come out and the engine converts what is left. A value the
/// picture does not cover converts to nothing, which is what razeri reads as
/// *this row did not parse*.
///
/// Parameters:
/// - `format`: the picture the design stated;
/// - `spelling`: this engine's vocabulary;
/// - `expr`: an already-rendered text expression;
/// - `safe_cast`: this engine's conversion, given the stripped text.
#[must_use]
pub fn read_with_safe_cast(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    safe_cast: &dyn Fn(&str) -> String,
) -> String {
    let reading = safe_cast(&strip_marks(format, spelling, expr));
    let reading = match separators_in_order(format, spelling, expr) {
        None => reading,
        Some(ordered) => format!("CASE WHEN {ordered} THEN {reading} END"),
    };
    signed(reading, bracket_sign(format, spelling, expr))
}

/// **For an engine whose own conversion raises, or answers a number for text
/// that is not one** — the shape is checked first, and a value that fails the
/// check is never handed to the conversion at all.
///
/// Parameters:
/// - `format`: the picture the design stated;
/// - `spelling`: this engine's vocabulary;
/// - `expr`: an already-rendered text expression;
/// - `cast`: this engine's conversion, given the stripped text;
/// - `matches`: this engine's own test of a value against a regular
///   expression, given the value and the pattern as a quoted literal.
#[must_use]
pub fn read_with_pattern_guard(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    cast: &dyn Fn(&str) -> String,
    matches: &dyn Fn(&str, &str) -> String,
) -> String {
    let trimmed = normalize_trim(spelling, expr);
    let pattern = format!("'{}'", format.shape_pattern().replace('\'', "''"));
    let reading = cast(&strip_marks(format, spelling, expr));
    // The pattern already holds the thousands mark in front of the decimal
    // point, so this arm needs no second condition for it.
    let guarded = format!("CASE WHEN {} THEN {reading} END", matches(&trimmed, &pattern));
    signed(guarded, bracket_sign(format, spelling, expr))
}

/// **For an engine with neither a conversion that answers nothing nor a way to
/// match a pattern** — the value less its digits is what says whether it was a
/// number.
///
/// With the picture's marks already out, a value that was a number holds
/// digits, at most one decimal point and at most a leading minus. Take the
/// digits out of it and what remains can only be one of four short strings, so
/// the check is an equality rather than a search.
///
/// Parameters:
/// - `format`: the picture the design stated;
/// - `spelling`: this engine's vocabulary;
/// - `expr`: an already-rendered text expression;
/// - `cast`: this engine's conversion, given the stripped text.
#[must_use]
pub fn read_with_digit_check(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    cast: &dyn Fn(&str) -> String,
) -> String {
    let replace = spelling.lower.replace;
    let prefix = spelling.lower.pattern_literal_prefix;
    let stripped = strip_marks(format, spelling, expr);
    let bare = (0..10u8).fold(stripped.clone(), |text, digit| {
        format!("{replace}({text}, {prefix}'{digit}', {prefix}'')")
    });
    let reading = cast(&stripped);
    // **A picture with no places after the point leaves no point behind.** A
    // whole number written `1.5` is not a whole number, and this engine's own
    // conversion would answer `1` — so the remainder a value may leave follows
    // the picture rather than being one fixed list.
    let remainders = if format.decimals() > 0 {
        format!("{prefix}'', {prefix}'.', {prefix}'-', {prefix}'-.'")
    } else {
        format!("{prefix}'', {prefix}'-'")
    };
    let mut conditions =
        vec![format!("{stripped} <> {prefix}''"), format!("{bare} IN ({remainders})")];
    conditions.extend(separators_in_order(format, spelling, expr));
    let guarded = format!("CASE WHEN {} THEN {reading} END", conditions.join(" AND "));
    signed(guarded, bracket_sign(format, spelling, expr))
}

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

    #[test]
    fn a_price_picture_says_a_symbol_thousands_and_two_places() {
        let format = NumberFormat::parse("$#,##0.00").expect("a lawful picture");
        assert_eq!(format.opens_with(), "$");
        assert_eq!(format.closes_with(), "");
        assert!(format.grouped());
        assert_eq!(format.decimals(), 2);
        assert_eq!(format.negatives(), Negatives::Minus);
        assert_eq!(format.marks(), vec!["$".to_owned(), ",".to_owned()]);
    }

    #[test]
    fn a_symbol_may_close_the_value_instead_of_opening_it() {
        let format = NumberFormat::parse("#,##0.00 kr").expect("a lawful picture");
        assert_eq!(format.opens_with(), "");
        assert_eq!(format.closes_with(), " kr");
        assert_eq!(format.marks(), vec![" kr".to_owned(), ",".to_owned()]);
    }

    #[test]
    fn a_plain_picture_names_no_marks_at_all() {
        let format = NumberFormat::parse("0.000").expect("a lawful picture");
        assert!(!format.grouped());
        assert_eq!(format.decimals(), 3);
        assert!(format.marks().is_empty());
        assert_eq!(format.shape_pattern(), "^-?[0-9]+([.][0-9]+)?$");
    }

    #[test]
    fn a_ledger_negative_is_the_same_picture_in_brackets() {
        let format = NumberFormat::parse("$#,##0.00;($#,##0.00)").expect("a lawful picture");
        assert_eq!(format.negatives(), Negatives::Parentheses);
        assert_eq!(
            format.marks(),
            vec!["$".to_owned(), ",".to_owned(), "(".to_owned(), ")".to_owned()]
        );
        assert_eq!(format.spelled(), "$#,##0.00;($#,##0.00)");
    }

    #[test]
    fn the_shape_holds_the_symbol_and_the_groups_where_the_picture_put_them() {
        let format = NumberFormat::parse("$#,##0.00").expect("a lawful picture");
        assert_eq!(format.shape_pattern(), "^-?([$])?[0-9][0-9,]*([.][0-9]+)?$");
    }

    #[test]
    fn the_reading_holds_the_thousands_mark_in_front_of_the_decimal_point() {
        let format = NumberFormat::parse("$#,##0.00").expect("a lawful picture");
        let read = read_with_safe_cast(&format, crate::ANSI_SID_SPELLING, "v", &|text| {
            format!("TRY_CAST({text} AS DECIMAL(12, 2))")
        });
        // Taking the thousands mark out of `2.899,99` leaves `2.89999`, which
        // converts to a price nobody wrote. The condition is what stops it.
        assert!(read.contains("TRIM(v) NOT LIKE '%.%,%'"), "{read}");
    }

    #[test]
    fn a_picture_with_no_thousands_mark_needs_no_such_condition() {
        let format = NumberFormat::parse("0.00").expect("a lawful picture");
        let read = read_with_safe_cast(&format, crate::ANSI_SID_SPELLING, "v", &|text| {
            format!("TRY_CAST({text} AS DECIMAL(12, 2))")
        });
        assert_eq!(
            read, "TRY_CAST(TRIM(v) AS DECIMAL(12, 2))",
            "nothing to take out, nothing to hold"
        );
    }

    #[test]
    fn a_whole_numbers_digit_check_leaves_no_room_for_a_decimal_point() {
        let whole = NumberFormat::parse("#0").expect("a lawful picture");
        let read = read_with_digit_check(&whole, crate::ANSI_SID_SPELLING, "v", &|text| {
            format!("CAST({text} AS INTEGER)")
        });
        // `1.5` is not a whole number, and an engine with no safe conversion
        // would otherwise answer `1`.
        assert!(read.contains("IN ('', '-')"), "{read}");
        let fractional = NumberFormat::parse("#0.0").expect("a lawful picture");
        let read = read_with_digit_check(&fractional, crate::ANSI_SID_SPELLING, "v", &|text| {
            format!("CAST({text} AS DECIMAL(18, 6))")
        });
        assert!(read.contains("IN ('', '.', '-', '-.')"), "{read}");
    }

    #[test]
    fn a_bracketed_negative_is_read_as_a_sign_rather_than_a_mark() {
        let format = NumberFormat::parse("$#,##0.00;($#,##0.00)").expect("a lawful picture");
        let read = read_with_safe_cast(&format, crate::ANSI_SID_SPELLING, "v", &|text| {
            format!("TRY_CAST({text} AS DECIMAL(12, 2))")
        });
        assert!(read.contains("CASE WHEN TRIM(v) LIKE '(%' THEN -1 ELSE 1 END"), "{read}");
        assert!(read.contains("REPLACE(REPLACE(REPLACE(REPLACE(TRIM(v)"), "{read}");
    }

    #[test]
    fn a_picture_with_no_digits_is_refused() {
        assert_eq!(NumberFormat::parse("$"), Err(NumberFormatError::NoDigits));
        assert_eq!(NumberFormat::parse(""), Err(NumberFormatError::Empty));
    }

    #[test]
    fn a_source_writing_the_separators_the_other_way_round_is_refused_by_name() {
        let refused = NumberFormat::parse("#.##0,00").expect_err("not covered");
        assert_eq!(refused, NumberFormatError::MarkAfterPoint);
        assert!(refused.to_string().contains("2.899,99"), "{refused}");
    }

    #[test]
    fn a_thousands_mark_separates_groups_of_three() {
        assert_eq!(NumberFormat::parse("#,##0,0"), Err(NumberFormatError::GroupIsNotThree(1)));
    }

    #[test]
    fn two_decimal_points_are_refused() {
        assert_eq!(NumberFormat::parse("0.0.0"), Err(NumberFormatError::TwoPoints));
    }

    #[test]
    fn digits_on_both_sides_of_the_symbol_are_refused() {
        assert_eq!(NumberFormat::parse("0 kr 0"), Err(NumberFormatError::DigitsAfterSymbol));
    }

    #[test]
    fn a_second_picture_that_is_not_the_first_in_brackets_is_refused() {
        assert_eq!(
            NumberFormat::parse("$#,##0.00;-$#,##0.00"),
            Err(NumberFormatError::NegativeIsNotBracketed)
        );
        assert_eq!(NumberFormat::parse("0;(0);0"), Err(NumberFormatError::TooManyPictures));
    }
}