razeri-plugin-contract 0.16.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
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
// 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::{Concat, 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 {} after a `,`, and a thousands mark \
                 separates groups of three. Write `#,##0` for a number written `2,899`",
                if *places == 1 { "place" } else { "places" }
            ),
            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)
    ))
}

/// **How an engine asks whether a text holds a character of a class**, for
/// [`read_with_safe_cast`] and [`read_with_digit_check`].
///
/// The readers hold a value to the picture's shape. Flat, each rule is one
/// test beside the next, each naming the value once and nesting nothing, so a
/// value is no deeper than its marks' own `REPLACE`s: an engine whose parser
/// holds a hundred levels — `SQLite` 3.45's — reads a wide table. Two of the
/// rules need a class of characters (a digit; anything but a digit, a point
/// or a minus), and that is what an engine is asked for here.
#[derive(Clone, Copy)]
pub enum ClassTest<'a> {
    /// **The engine's own test**: given a text and a bracket class — `[0-9]`
    /// or `[^0-9.-]`, the spelling `GLOB`, SQL Server's `LIKE` and every
    /// regular expression share — a condition true where the text holds at
    /// least one character of the class: `x GLOB '*[0-9]*'`,
    /// `x LIKE '%[0-9]%'`, `REGEXP_LIKE(x, '[0-9]')`.
    Flat(&'a dyn Fn(&str, &str) -> String),
    /// **No such test**: the value's digits are folded with `REPLACE` into
    /// one shape and that is asked with `LIKE` alone, about twenty calls deep
    /// over the value. Ask for it only where the engine has neither a bracket
    /// class nor a regular expression.
    Folded,
}

/// **The picture's shape as flat tests** — the rules [`shape_conditions`]
/// states, each asked on its own: the symbol in `LIKE`'s words over the
/// value, and the digits, the point and the minus over the value with its
/// marks out, two of them through the engine's class test.
fn flat_shape_conditions(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    holds: &dyn Fn(&str, &str) -> String,
) -> Vec<String> {
    let prefix = spelling.lower.pattern_literal_prefix;
    let value = normalize_trim(spelling, expr);
    let stripped = strip_marks(format, spelling, expr);
    let not_like = |subject: &str, pattern: &str| {
        format!("{subject} NOT LIKE {prefix}'{}'", pattern.replace('\'', "''"))
    };
    let mut conditions = symbol_conditions(format, spelling, &value);
    conditions.push(holds(&stripped, "[0-9]"));
    conditions.push(format!("NOT {}", holds(&stripped, "[^0-9.-]")));
    let bracketed = format.negatives() == Negatives::Parentheses;
    conditions.push(not_like(&stripped, if bracketed { "%-%" } else { "_%-%" }));
    if format.decimals() > 0 {
        for shape in ["%.%.%", ".%", "-.%", "%."] {
            conditions.push(not_like(&stripped, shape));
        }
    } else {
        conditions.push(not_like(&stripped, "%.%"));
    }
    if !bracketed && !format.opens_with().is_empty() {
        conditions.push(not_like(&value, "_%-%"));
    }
    conditions
}

/// **A symbol at most once, and only at its own end of the value** — after a
/// leading minus, or inside an opening bracket, where the picture writes a
/// negative that way. A symbol holding `%`, `_` or `[` is not held to its
/// place: those are `LIKE`'s own wildcards somewhere.
fn symbol_conditions(format: &NumberFormat, spelling: SidSpelling, value: &str) -> Vec<String> {
    let prefix = spelling.lower.pattern_literal_prefix;
    let like = |pattern: &str| format!("{value} LIKE {prefix}'{}'", pattern.replace('\'', "''"));
    let not_like =
        |pattern: &str| format!("{value} NOT LIKE {prefix}'{}'", pattern.replace('\'', "''"));
    let mut conditions = Vec::new();
    let bracketed = format.negatives() == Negatives::Parentheses;
    let plain = |symbol: &str| !symbol.contains(['%', '_', '['].as_slice());
    let opens = format.opens_with();
    if !opens.is_empty() && plain(opens) {
        let before = if bracketed { "(" } else { "-" };
        conditions.push(not_like(&format!("%{opens}%{opens}%")));
        conditions.push(format!(
            "({} OR {} OR {})",
            not_like(&format!("%{opens}%")),
            like(&format!("{opens}%")),
            like(&format!("{before}{opens}%")),
        ));
    }
    let closes = format.closes_with();
    if !closes.is_empty() && plain(closes) {
        let after = if bracketed { ")" } else { "" };
        conditions.push(not_like(&format!("%{closes}%{closes}%")));
        conditions.push(format!(
            "({} OR {} OR {})",
            not_like(&format!("%{closes}%")),
            like(&format!("%{closes}")),
            like(&format!("%{closes}{after}")),
        ));
    }
    conditions
}

/// **A digit before the first thousands mark** (`fr-1021-02`): `,123` opens
/// with the mark, after nothing or after a leading minus, bracket or symbol,
/// and is not written the picture's way — the pattern-guard engines' shape
/// asks for a digit there, and so does every reading. Nothing where the
/// picture names no thousands mark.
fn thousands_after_a_digit(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
) -> Vec<String> {
    if !format.grouped() {
        return Vec::new();
    }
    let prefix = spelling.lower.pattern_literal_prefix;
    let value = normalize_trim(spelling, expr);
    let sign = if format.negatives() == Negatives::Parentheses { "(" } else { "-" };
    let opens = format.opens_with();
    let mut openings = vec![String::new(), sign.to_owned()];
    if !opens.is_empty() && !opens.contains(['%', '_', '['].as_slice()) {
        openings.push(opens.to_owned());
        openings.push(format!("{sign}{opens}"));
    }
    openings
        .iter()
        .map(|opening| {
            format!(
                "{value} NOT LIKE {prefix}'{}'",
                format!("{opening}{THOUSANDS_MARK}%").replace('\'', "''")
            )
        })
        .collect()
}

/// **The picture's shape, as conditions an engine with no pattern match can
/// hold a value to** — `LIKE` and nothing else.
///
/// [`NumberFormat::shape_pattern`] is the shape a pattern-matching engine
/// holds a value to before its marks come out. An engine that converts with a
/// cast that answers nothing, or checks the digits left, used to hold none:
/// the marks came out wherever they stood, so `12$`, `$$12`, `+5` and `.5`
/// read as numbers there while a pattern-matching engine set them aside
/// (`fr-1019-86`). These are the same rules in `LIKE`'s words:
///
/// - a symbol at most once, and only at its own end of the value — after a
///   leading minus, or inside an opening bracket, where the picture writes a
///   negative that way;
/// - with the marks out, nothing left but digits, at most one decimal point
///   and at most a minus, so a plus sign, an exponent or a word is not a
///   number here;
/// - a digit before the decimal point, and at least one after it;
/// - no decimal point at all where the picture has no places;
/// - a minus only as the value's first character, and none where the picture
///   writes a negative in brackets.
///
/// **The value is named as few times as the rules allow**, because it is often
/// a long expression of its own and every mention repeats it. The digits,
/// the point and the minus are asked in one condition ([`canonical_shape`]):
/// a value of the picture's shape comes out as the text `x0` and nothing
/// else. Only a symbol opening the value needs the minus asked again, of the
/// value as written, since `$-12` and `-$12` are the same once it is out.
///
/// A symbol holding `%`, `_` or `[` is not held to its place: those are
/// `LIKE`'s own wildcards somewhere.
fn shape_conditions(format: &NumberFormat, spelling: SidSpelling, expr: &str) -> Vec<String> {
    let prefix = spelling.lower.pattern_literal_prefix;
    let value = normalize_trim(spelling, expr);
    let stripped = strip_marks(format, spelling, expr);
    let mut conditions = symbol_conditions(format, spelling, &value);
    conditions.push(format!("{} LIKE {prefix}'x0'", canonical_shape(format, spelling, &stripped)));
    if format.negatives() != Negatives::Parentheses && !format.opens_with().is_empty() {
        conditions.push(format!("{value} NOT LIKE {prefix}'_%-%'"));
    }
    conditions
}

/// **A value with its marks out, written as the shape it has**: `x0` for one
/// of digits — with a point between two runs of them where the picture has
/// places, and a leading minus where it writes a negative that way — and
/// anything else for any other value.
///
/// Every digit becomes `0`, a run of zeros becomes one, `0.0` becomes `0`, the
/// text is put behind a letter, and a minus straight after the letter comes
/// out: `-1,234.50` is `x0`, while `.5` is left `x.0`, `5.` is `x0.`, `1.2.3`
/// is `x0.0`, `1e3` is `x0e0` and `--5` is `x-0`. Eight halvings take a run of
/// up to 256 digits to one, far past any number a column holds. `REPLACE`,
/// joining and `LIKE` alone, so it reads the same on every engine, a large
/// object included; the letter keeps an engine that reads an empty text as
/// nothing from comparing nothing.
fn canonical_shape(format: &NumberFormat, spelling: SidSpelling, stripped: &str) -> String {
    let replace = spelling.lower.replace;
    let prefix = spelling.lower.pattern_literal_prefix;
    let swap = |text: String, from: &str, to: &str| {
        format!("{replace}({text}, {prefix}'{from}', {prefix}'{to}')")
    };
    let zeros =
        (1..10u8).fold(stripped.to_owned(), |text, digit| swap(text, &digit.to_string(), "0"));
    let run = (0..8).fold(zeros, |text, _| swap(text, "00", "0"));
    let pointed =
        if format.decimals() > 0 { swap(run, &format!("0{DECIMAL_POINT}0"), "0") } else { run };
    let lettered = join_text(spelling, &format!("{prefix}'x'"), &pointed);
    if format.negatives() == Negatives::Parentheses {
        // A bracketed picture writes no minus, so one left is not its shape.
        lettered
    } else {
        swap(lettered, "x-", "x")
    }
}

/// **Two texts joined**, in this engine's own words for joining strings
/// ([`SidSpelling::concat`]).
fn join_text(spelling: SidSpelling, left: &str, right: &str) -> String {
    match spelling.concat {
        Concat::Function(name) | Concat::FunctionBinary(name) => format!("{name}({left}, {right})"),
        Concat::Plus => format!("{left} + {right}"),
        Concat::Operator(operator) => format!("{left} {operator} {right}"),
    }
}

/// **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 value is held to the picture's shape first, in `LIKE`'s words and the
/// engine's class test (the rules [`NumberFormat::shape_pattern`] states);
/// then the marks come out and the engine converts what is left. A value
/// outside the shape, or one the conversion cannot read, answers 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;
/// - `class`: how this engine tests a text for a character of a class —
///   [`ClassTest::Flat`] unless it has no such test.
#[must_use]
pub fn read_with_safe_cast(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    safe_cast: &dyn Fn(&str) -> String,
    class: ClassTest<'_>,
) -> String {
    let reading = safe_cast(&strip_marks(format, spelling, expr));
    guarded_reading(format, spelling, expr, &reading, class)
}

/// The reading behind the picture's shape, the thousands mark held in front
/// of the decimal point and behind a digit, and the bracket's sign.
fn guarded_reading(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    reading: &str,
    class: ClassTest<'_>,
) -> String {
    let mut conditions = match class {
        ClassTest::Flat(holds) => flat_shape_conditions(format, spelling, expr, holds),
        ClassTest::Folded => shape_conditions(format, spelling, expr),
    };
    conditions.extend(separators_in_order(format, spelling, expr));
    conditions.extend(thousands_after_a_digit(format, spelling, expr));
    let guarded = format!("CASE WHEN {} THEN {reading} END", conditions.join(" AND "));
    signed(guarded, 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 whole pattern** — the value's shape, asked in `LIKE`'s words and
/// the engine's class test, 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 with a digit either side, and at most a
/// leading minus — the same conditions [`read_with_safe_cast`] holds a value
/// to, and a value that fails them is never handed to the conversion.
///
/// 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;
/// - `class`: how this engine tests a text for a character of a class —
///   [`ClassTest::Flat`] unless it has no such test.
#[must_use]
pub fn read_with_digit_check(
    format: &NumberFormat,
    spelling: SidSpelling,
    expr: &str,
    cast: &dyn Fn(&str) -> String,
    class: ClassTest<'_>,
) -> String {
    let reading = cast(&strip_marks(format, spelling, expr));
    guarded_reading(format, spelling, expr, &reading, class)
}

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

    /// SQL Server's class test, the shape every test here asks with.
    fn like_class(text: &str, class: &str) -> String {
        format!("{text} LIKE '%{class}%'")
    }
    const LIKE_CLASS: fn(&str, &str) -> String = like_class;

    #[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))"),
            ClassTest::Folded,
        );
        // 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))"),
            ClassTest::Folded,
        );
        assert!(!read.contains("'%.%,%'"), "no thousands mark to put in its place: {read}");
        assert!(read.ends_with("THEN TRY_CAST(TRIM(v) AS DECIMAL(12, 2)) END"), "{read}");
    }

    /// **A safe-cast reading holds the value to the picture's shape first**
    /// (`fr-1019-86`): a symbol at most once and at its own end, nothing but
    /// digits, a point and a minus left, a digit either side of the point, a
    /// minus only first. Executed on SQL
    /// Server, `DuckDB` and `SQLite` over `12$`, `$$12`, `+5`, `.5` and `$-12`,
    /// each set aside on all three.
    #[test]
    fn a_safe_cast_reading_holds_the_value_to_the_pictures_shape() {
        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))"),
            ClassTest::Folded,
        );
        for guard in [
            "TRIM(v) NOT LIKE '%$%$%'",
            "TRIM(v) LIKE '-$%'",
            "'00', '0'), '0.0', '0'))",
            "'x-', 'x') LIKE 'x0'",
            "TRIM(v) NOT LIKE '_%-%'",
        ] {
            assert!(read.contains(guard), "no {guard}: {read}");
        }
        let closing = NumberFormat::parse("#,##0.00 kr").expect("a lawful picture");
        let read = read_with_safe_cast(
            &closing,
            crate::ANSI_SID_SPELLING,
            "v",
            &|text| format!("TRY_CAST({text} AS DECIMAL(12, 2))"),
            ClassTest::Folded,
        );
        assert!(read.contains("TRIM(v) LIKE '% kr'"), "{read}");
    }

    #[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)"),
            ClassTest::Folded,
        );
        // `1.5` is not a whole number, and an engine with no safe conversion
        // would otherwise answer `1`.
        assert!(read.contains("'x-', 'x') LIKE 'x0'") && !read.contains("'0.0', '0')"), "{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))"),
            ClassTest::Folded,
        );
        assert!(read.contains("'0.0', '0')), 'x-', 'x') LIKE 'x0'"), "{read}");
    }

    /// **The value is named a fixed few times, however its shape is asked.**
    /// It is often a long expression of its own — a column read through a
    /// guard of its width — and every mention repeats it, so a check that
    /// named it once per digit doubled a whole load's text.
    #[test]
    fn a_reading_names_the_value_a_fixed_few_times() {
        let value = "COLUMN_VALUE";
        for picture in ["#0", "#0.0", "0.00"] {
            let format = NumberFormat::parse(picture).expect("a lawful picture");
            let read = read_with_safe_cast(
                &format,
                crate::ANSI_SID_SPELLING,
                value,
                &|text| format!("TRY_CAST({text} AS DECIMAL(12, 2))"),
                ClassTest::Folded,
            );
            // The shape and the reading itself.
            assert_eq!(read.matches(value).count(), 2, "{picture}: {read}");
        }
    }

    /// How deep the calls in `sql` nest, string literals left out: the
    /// measure an engine's parser stack holds a reading to.
    fn depth(sql: &str) -> usize {
        let (mut depth, mut deepest, mut quoted) = (0usize, 0usize, false);
        for c in sql.chars() {
            match c {
                '\'' => quoted = !quoted,
                '(' if !quoted => {
                    depth += 1;
                    deepest = deepest.max(depth);
                }
                ')' if !quoted => depth = depth.saturating_sub(1),
                _ => {}
            }
        }
        deepest
    }

    /// **The shared reading is flat** (`fr-1021-01`): a value is no deeper
    /// than its picture's marks' own `REPLACE`s and the test around them, so
    /// an engine with a shallow parser stack reads a wide table. Folded, a
    /// `$#,##0.00` reading nested 23 deep over the value.
    #[test]
    fn the_shared_reading_is_flat() {
        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))"),
            ClassTest::Flat(&LIKE_CLASS),
        );
        assert!(depth(&read) <= 6, "{} deep: {read}", depth(&read));
    }

    /// **A value that opens with the thousands mark is not a number**
    /// (`fr-1021-02`): `,123` is set aside, as the pattern-guard engines set it
    /// aside, never read as `123`.
    #[test]
    fn a_value_opening_with_the_thousands_mark_is_set_aside() {
        let format = NumberFormat::parse("$#,##0.00").expect("a lawful picture");
        for class in [ClassTest::Flat(&LIKE_CLASS), ClassTest::Folded] {
            let read = read_with_safe_cast(
                &format,
                crate::ANSI_SID_SPELLING,
                "v",
                &|text| format!("TRY_CAST({text} AS DECIMAL(12, 2))"),
                class,
            );
            for opening in ["',%'", "'-,%'", "'$,%'", "'-$,%'"] {
                assert!(read.contains(&format!("TRIM(v) NOT LIKE {opening}")), "{opening}: {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))"),
            ClassTest::Folded,
        );
        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));
    }
}