primase-core 0.2.0

primase core: the world store, core components, frames, the pass manager and gates
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
//! A pass's options declared once ([`PassSpec`]): each option's key, whether a pipeline must give it, an example value
//! and what it means ([`OptionSpec`]). The registry derives the rest from the declaration
//! ([`crate::pass::PassRegistry::add`]): it refuses an undeclared key, a missing required option and a value outside a
//! [`Choice`]'s, each in one form, before the pass is made; it makes the pass from the examples to read its declarations
//! (a pass with a required option is never run so); and it checks at registration that the pass made from the
//! examples prints back what it was made with. The pass reads what the declaration let through ([`Given`]): a required
//! option is there, a choice is its enum.
//!
//! What stays the pass's: parsing and checking a value (numbers, `;` lists, values the data names), and how options
//! constrain each other beyond one-of groups (all four of a rectangle or none; one value that needs another).
//!
//! A program's choices that are not a pass (how a reader reads) take the same form ([`TextForm`]): a name and declared
//! options, checked by the same declaration and read through the same [`Given`], so a program can state them as text
//! another program runs as written.

use std::collections::BTreeSet;

use crate::pass::{Options, Pass};

/// The values of an option that are a fixed set of names, listed once: the registry refuses any other and names these;
/// the pass reads the enum ([`Given::choice`]), never the text, so there is no second list to drift from.
pub trait Choice: Copy + PartialEq + 'static {
    /// Each value's text and the value; the first is the option's example.
    const VALUES: &'static [(&'static str, Self)];

    /// The text of `self`, as a pass prints it back ([`Pass::options`]).
    fn text(self) -> &'static str {
        Self::VALUES
            .iter()
            .find(|(_, v)| *v == self)
            .map(|(t, _)| *t)
            .expect("every value of a Choice is listed in its VALUES")
    }
}

impl Choice for bool {
    const VALUES: &'static [(&'static str, Self)] = &[("false", false), ("true", true)];
}

/// Whether a pipeline must give an option.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Need {
    /// It must: nothing is assumed for the caller.
    Required,
    /// Exactly one of the options sharing this group name must be given.
    OneOf(&'static str),
    /// It may: its absence has the meaning its declaration states ([`OptionSpec::absent`]; never a choice made for the
    /// caller: CONTRIBUTING "Drift").
    Optional,
}

/// One option a pass takes: its key, whether it is needed, an example value and what it means. Built only by its
/// constructors, so a required option always has its example and an optional one always says what its absence means.
#[derive(Clone, Copy, Debug)]
pub struct OptionSpec {
    key: &'static str,
    need: Need,
    example: &'static str,
    doc: &'static str,
    /// What no value means, for an optional option (empty for the others).
    absent: &'static str,
    /// The texts of a [`Choice`]'s values, for a choice option.
    values: Option<fn() -> Vec<&'static str>>,
}

fn texts<T: Choice>() -> Vec<&'static str> {
    T::VALUES.iter().map(|(t, _)| *t).collect()
}

impl OptionSpec {
    /// An option a pipeline must give.
    pub const fn required(key: &'static str, example: &'static str, doc: &'static str) -> Self {
        OptionSpec {
            key,
            need: Need::Required,
            example,
            doc,
            absent: "",
            values: None,
        }
    }

    /// An option a pipeline may give; `absent` says what no value means (the registry refuses an empty one). Its
    /// example only documents it: optional options may exclude each other (`at=centre` or `east` and `north`), so the
    /// registry makes no pass from them.
    pub const fn optional(
        key: &'static str,
        example: &'static str,
        doc: &'static str,
        absent: &'static str,
    ) -> Self {
        OptionSpec {
            key,
            need: Need::Optional,
            example,
            doc,
            absent,
            values: None,
        }
    }

    /// One of the options of `group`, of which a pipeline gives exactly one.
    pub const fn one_of(
        group: &'static str,
        key: &'static str,
        example: &'static str,
        doc: &'static str,
    ) -> Self {
        OptionSpec {
            key,
            need: Need::OneOf(group),
            example,
            doc,
            absent: "",
            values: None,
        }
    }

    /// One of the options of `group`, of which a pipeline gives exactly one, whose value is one of `T`'s; the example
    /// is the first. Read by [`Given::optional_choice`].
    pub const fn one_of_choice<T: Choice>(group: &'static str, key: &'static str, doc: &'static str) -> Self {
        OptionSpec {
            key,
            need: Need::OneOf(group),
            example: T::VALUES[0].0,
            doc,
            absent: "",
            values: Some(texts::<T>),
        }
    }

    /// A required option whose value is one of `T`'s; the example is the first.
    pub const fn choice<T: Choice>(key: &'static str, doc: &'static str) -> Self {
        OptionSpec {
            key,
            need: Need::Required,
            example: T::VALUES[0].0,
            doc,
            absent: "",
            values: Some(texts::<T>),
        }
    }

    /// An optional option whose value, when given, is one of `T`'s; `absent` says what no value means.
    pub const fn optional_choice<T: Choice>(
        key: &'static str,
        doc: &'static str,
        absent: &'static str,
    ) -> Self {
        OptionSpec {
            key,
            need: Need::Optional,
            example: T::VALUES[0].0,
            doc,
            absent,
            values: Some(texts::<T>),
        }
    }

    pub fn key(&self) -> &'static str {
        self.key
    }

    pub fn example(&self) -> &'static str {
        self.example
    }

    pub fn doc(&self) -> &'static str {
        self.doc
    }

    /// What no value means, for an optional option.
    pub fn absent(&self) -> Option<&'static str> {
        (self.need == Need::Optional).then_some(self.absent)
    }

    /// Whether a pipeline must give it (alone, or as one of its group).
    pub fn is_needed(&self) -> bool {
        self.need != Need::Optional
    }

    /// The group it is one of, if it is.
    pub fn group(&self) -> Option<&'static str> {
        match self.need {
            Need::OneOf(g) => Some(g),
            _ => None,
        }
    }

    /// The texts of its values, for a choice option.
    pub fn values(&self) -> Option<Vec<&'static str>> {
        self.values.map(|f| f())
    }
}

/// `items` as `a`, `a or b`, `a, b or c`.
fn alternatives(items: &[&str]) -> String {
    match items {
        [] => String::new(),
        [one] => (*one).to_owned(),
        [rest @ .., last] => format!("{} or {last}", rest.join(", ")),
    }
}

fn groups(declarations: &[OptionSpec]) -> Vec<(&'static str, Vec<&OptionSpec>)> {
    let mut groups: Vec<(&'static str, Vec<&OptionSpec>)> = Vec::new();
    for o in declarations {
        if let Need::OneOf(g) = o.need {
            match groups.iter_mut().find(|(name, _)| *name == g) {
                Some((_, members)) => members.push(o),
                None => groups.push((g, vec![o])),
            }
        }
    }
    groups
}

pub(crate) fn check_options(
    name: &str,
    declarations: &[OptionSpec],
    options: &Options,
) -> Result<(), String> {
    if let Some(k) = options
        .keys()
        .find(|k| !declarations.iter().any(|option| option.key == k.as_str()))
    {
        let keys: Vec<&str> = declarations.iter().map(|o| o.key).collect();
        return Err(if keys.is_empty() {
            format!("unknown option {k} ({} takes none)", name)
        } else {
            format!("unknown option {k} ({} takes {})", name, keys.join(", "))
        });
    }
    if let Some(o) = declarations
        .iter()
        .find(|o| o.need == Need::Required && !options.contains_key(o.key))
    {
        return Err(format!("{} is required: {}", o.key, o.doc));
    }
    for (_, members) in groups(declarations) {
        let keys: Vec<&str> = members.iter().map(|o| o.key).collect();
        match members.iter().filter(|o| options.contains_key(o.key)).count() {
            0 => {
                let docs: Vec<String> = members.iter().map(|o| format!("{}: {}", o.key, o.doc)).collect();
                return Err(format!(
                    "one of {} is required ({})",
                    alternatives(&keys),
                    docs.join("; ")
                ));
            }
            1 => {}
            _ => return Err(format!("only one of {} may be given", alternatives(&keys))),
        }
    }
    for (k, v) in options {
        if let Some(values) = declarations
            .iter()
            .find(|option| option.key == k.as_str())
            .and_then(OptionSpec::values)
            && !values.contains(&v.as_str())
        {
            return Err(format!("{k}={v} is none of {}", alternatives(&values)));
        }
    }
    Ok(())
}

pub(crate) fn validate_options(name: &str, declarations: &[OptionSpec]) {
    let mut keys = BTreeSet::new();
    for o in declarations {
        assert!(
            keys.insert(o.key),
            "pass {}: option {} declared twice",
            name,
            o.key
        );
        assert!(
            o.absent().is_none_or(|a| !a.trim().is_empty()),
            "pass {}: optional option {} says nothing of what its absence means",
            name,
            o.key
        );
        if let Some(values) = o.values() {
            let distinct: BTreeSet<&str> = values.iter().copied().collect();
            assert!(
                !values.is_empty() && distinct.len() == values.len(),
                "pass {}: option {}: a choice's values are none or one twice: {values:?}",
                name,
                o.key
            );
        }
    }
    for (g, members) in groups(declarations) {
        assert!(
            members.len() > 1,
            "pass {}: the one-of group {g} has one option",
            name
        );
    }
}

/// A pass as the registry knows it: its name, the options it takes, and how it is made from what the declaration let
/// through.
pub struct PassSpec {
    pub name: &'static str,
    pub options: &'static [OptionSpec],
    pub make: fn(&Given) -> Result<Box<dyn Pass>, String>,
}

impl std::fmt::Debug for PassSpec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PassSpec")
            .field("name", &self.name)
            .field("options", &self.options)
            .finish_non_exhaustive()
    }
}

impl PassSpec {
    /// The groups of one-of options, in the order they are first declared, each with its members.
    fn groups(&self) -> Vec<(&'static str, Vec<&OptionSpec>)> {
        groups(self.options)
    }

    /// Whether a pipeline must give it options: a required option or a one-of group.
    pub fn requires_options(&self) -> bool {
        self.options.iter().any(OptionSpec::is_needed)
    }

    /// The options it is made with to read its declarations: each required option's example and the first option's of
    /// each group.
    pub fn example(&self) -> Options {
        let mut seen = BTreeSet::new();
        self.options
            .iter()
            .filter(|o| match o.need {
                Need::Required => true,
                Need::OneOf(g) => seen.insert(g),
                Need::Optional => false,
            })
            .map(|o| (o.key.to_owned(), o.example.to_owned()))
            .collect()
    }

    /// `options` against the declaration: the refusal of the first undeclared key, missing required option, one-of
    /// group given none or more than one of, or choice value outside its values.
    pub fn check(&self, options: &Options) -> Result<(), String> {
        check_options(self.name, self.options, options)
    }

    /// The pass made from `options`, once [`PassSpec::check`] lets them through.
    pub fn instance(&self, options: &Options) -> Result<Box<dyn Pass>, String> {
        self.check(options)?;
        (self.make)(&Given::new(self.name, self.options, options))
    }

    /// Its text form and what each option means: `translate-world{by*}` (`*` a required option, `|` between the
    /// options of a group), then a line per option, an optional one's ending with what its absence means.
    pub fn describe(&self) -> String {
        let mut out = String::from(self.name);
        if !self.options.is_empty() {
            let mut keys: Vec<String> = Vec::new();
            for o in self.options {
                match o.need {
                    Need::Required => keys.push(format!("{}*", o.key)),
                    Need::Optional => keys.push(o.key.to_owned()),
                    Need::OneOf(g) => {
                        if self
                            .groups()
                            .iter()
                            .any(|(name, m)| *name == g && m[0].key == o.key)
                        {
                            let members: Vec<&str> = self
                                .options
                                .iter()
                                .filter(|m| m.need == Need::OneOf(g))
                                .map(|m| m.key)
                                .collect();
                            keys.push(format!("({})*", members.join("|")));
                        }
                    }
                }
            }
            out.push_str(&format!("{{{}}}", keys.join(",")));
        }
        for o in self.options {
            let need = match o.need {
                Need::Required => "required".to_owned(),
                Need::OneOf(g) => format!("one of {g}"),
                Need::Optional => "optional".to_owned(),
            };
            let values = o
                .values()
                .map(|v| format!("; {}", v.join(" | ")))
                .unwrap_or_default();
            out.push_str(&format!(
                "\n  {} ({need}{values}; e.g. {}): {}",
                o.key, o.example, o.doc
            ));
            if let Some(absent) = o.absent() {
                out.push_str(&format!("; without it: {absent}"));
            }
        }
        out
    }

    /// Panics where the declaration itself is wrong: a key twice, a group of one, a choice with no values or a value
    /// twice, an optional option that says nothing of its absence.
    pub(crate) fn validate(&self) {
        validate_options(self.name, self.options);
    }
}

/// The options a pass (or a [`TextForm`]) is made from, after its declaration let them through ([`PassSpec::check`]).
/// Reading a key the declaration does not have, or reading it as what it is not declared as, is a bug in the pass: a
/// panic.
#[derive(Debug)]
pub struct Given<'a> {
    /// The name of what is made, for the panics.
    name: &'a str,
    declarations: &'a [OptionSpec],
    options: &'a Options,
}

impl<'a> Given<'a> {
    pub(crate) fn new(name: &'a str, declarations: &'a [OptionSpec], options: &'a Options) -> Self {
        Given {
            name,
            declarations,
            options,
        }
    }

    fn declared(&self, key: &str) -> &'a OptionSpec {
        self.declarations
            .iter()
            .find(|o| o.key == key)
            .unwrap_or_else(|| {
                panic!(
                    "{} reads option {key}, which its declaration does not have",
                    self.name
                )
            })
    }

    /// A required option's value: always there.
    pub fn required(&self, key: &str) -> &'a str {
        let o = self.declared(key);
        assert!(
            o.need == Need::Required,
            "{} reads option {key} as required, which it declares optional or one of a group",
            self.name
        );
        self.options
            .get(key)
            .map(String::as_str)
            .expect("the declaration's check lets no required option be missing")
    }

    /// An optional option's value, or a one-of option's, if given.
    pub fn optional(&self, key: &str) -> Option<&'a str> {
        self.declared(key);
        self.options.get(key).map(String::as_str)
    }

    fn of<T: Choice>(&self, key: &str, text: &str) -> T {
        T::VALUES
            .iter()
            .find(|(t, _)| *t == text)
            .map(|(_, v)| *v)
            .unwrap_or_else(|| {
                panic!(
                    "{} reads option {key} as a choice its declaration does not give it",
                    self.name
                )
            })
    }

    /// A required choice's value.
    pub fn choice<T: Choice>(&self, key: &str) -> T {
        let text = self.required(key);
        self.of(key, text)
    }

    /// An optional choice's value, if given.
    pub fn optional_choice<T: Choice>(&self, key: &str) -> Option<T> {
        self.optional(key).map(|text| self.of(key, text))
    }
}

/// A program's choices that are not a pass, stated as a pass is (`read-fromsoft-area{area=m10_00_00_00,margin=30}`): a
/// name, the options it takes declared once, made from what the declaration let through, and printing back what it was
/// made with. [`crate::pass::parse_text_form`] reads it and [`crate::pass::text_form`] writes it, with the declaration's
/// refusals (an undeclared key, a missing required option, a value outside a choice's) in a pass's words;
/// [`crate::pass::validate_text_form`] checks the declaration as [`crate::pass::PassRegistry::add`] checks a pass's.
pub trait TextForm: Sized {
    /// The name its text starts with.
    const NAME: &'static str;
    /// The options it takes.
    const OPTIONS: &'static [OptionSpec];

    /// It, from what the declaration let through; the refusal names the option whose value it cannot take.
    fn make(given: &Given) -> Result<Self, String>;

    /// Its options, as text: what it was made with.
    fn options(&self) -> Options;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::World;
    use crate::pass::PassLog;

    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum Detail {
        Plain,
        High,
    }

    impl Choice for Detail {
        const VALUES: &'static [(&'static str, Self)] = &[("plain", Detail::Plain), ("high", Detail::High)];
    }

    /// A pass that prints back what it was made with.
    #[derive(Debug)]
    struct Toy(Options);

    impl Pass for Toy {
        fn name(&self) -> &'static str {
            "toy"
        }
        fn options(&self) -> Options {
            self.0.clone()
        }
        fn run(&self, _w: &mut World, _log: &mut PassLog) -> Result<(), String> {
            Ok(())
        }
    }

    const TOY: PassSpec = PassSpec {
        name: "toy",
        options: &[
            OptionSpec::required("cell", "4", "metres, above 0: the grid's cell"),
            OptionSpec::choice::<Detail>("detail", "which collision is written"),
            OptionSpec::one_of("by", "factor", "2", "the enlargement"),
            OptionSpec::one_of("by", "size", "64", "the larger side to reach"),
            OptionSpec::optional("halo", "1", "metres around each cell", "no halo"),
            OptionSpec::optional_choice::<Detail>(
                "fallback",
                "the detail used where one is missing",
                "no fallback",
            ),
        ],
        make: |g| {
            // every way of reading what the declaration let through
            let _ = (
                g.required("cell"),
                g.choice::<Detail>("detail"),
                g.optional("halo"),
            );
            let _ = (
                g.optional("factor"),
                g.optional("size"),
                g.optional_choice::<Detail>("fallback"),
            );
            Ok(Box::new(Toy(Options::new())))
        },
    };

    fn options(items: &[(&str, &str)]) -> Options {
        items
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect()
    }

    /// The example is each required option's and the first of the group's; a choice's example is its first value.
    #[test]
    fn the_examples_come_from_the_declaration() {
        TOY.validate();
        assert!(TOY.requires_options());
        assert_eq!(
            TOY.example(),
            options(&[("cell", "4"), ("detail", "plain"), ("factor", "2")])
        );
        assert!(TOY.instance(&TOY.example()).is_ok());
    }

    /// Each refusal in its one form, before the pass is made.
    #[test]
    fn the_declaration_refuses_before_the_pass_is_made() {
        let refusal = |items: &[(&str, &str)]| TOY.check(&options(items)).unwrap_err();
        let base = [("cell", "4"), ("detail", "plain"), ("factor", "2")];
        let with = |extra: (&'static str, &'static str)| {
            let mut o = base.to_vec();
            o.push(extra);
            o
        };
        assert_eq!(
            refusal(&with(("colour", "red"))),
            "unknown option colour (toy takes cell, detail, factor, size, halo, fallback)"
        );
        assert_eq!(
            refusal(&[("detail", "plain"), ("factor", "2")]),
            "cell is required: metres, above 0: the grid's cell"
        );
        assert_eq!(
            refusal(&[("cell", "4"), ("detail", "plain")]),
            "one of factor or size is required (factor: the enlargement; size: the larger side to reach)"
        );
        assert_eq!(
            refusal(&with(("size", "64"))),
            "only one of factor or size may be given"
        );
        assert_eq!(
            refusal(&[("cell", "4"), ("detail", "fine"), ("factor", "2")]),
            "detail=fine is none of plain or high"
        );
        assert_eq!(
            refusal(&with(("fallback", "low"))),
            "fallback=low is none of plain or high"
        );
        let none = PassSpec {
            name: "bare",
            options: &[],
            make: |_| Ok(Box::new(Toy(Options::new()))),
        };
        assert_eq!(
            none.check(&options(&[("x", "1")])).unwrap_err(),
            "unknown option x (bare takes none)"
        );
        assert!(!none.requires_options());
    }

    /// A choice reads back as its enum and prints as its text.
    #[test]
    fn a_choice_is_read_as_its_enum() {
        const READ: PassSpec = PassSpec {
            name: "read",
            options: &[OptionSpec::choice::<Detail>("detail", "which")],
            make: |g| {
                let detail = g.choice::<Detail>("detail");
                Ok(Box::new(Toy(options(&[("detail", detail.text())]))))
            },
        };
        let pass = READ.instance(&options(&[("detail", "high")])).unwrap();
        assert_eq!(pass.options(), options(&[("detail", "high")]));
        assert_eq!(Detail::High.text(), "high");
    }

    /// A one-of choice is one of its group, refused outside its values, and read as its enum when given.
    #[test]
    fn a_one_of_choice_is_a_group_member_with_values() {
        const SOURCE: PassSpec = PassSpec {
            name: "source",
            options: &[
                OptionSpec::one_of_choice::<Detail>("source", "preset", "a preset detail"),
                OptionSpec::one_of("source", "file", "d.txt", "a file stating the detail"),
            ],
            make: |g| {
                let printed = match (g.optional_choice::<Detail>("preset"), g.optional("file")) {
                    (Some(d), None) => options(&[("preset", d.text())]),
                    (None, Some(f)) => options(&[("file", f)]),
                    _ => unreachable!("the group gives one"),
                };
                Ok(Box::new(Toy(printed)))
            },
        };
        SOURCE.validate();
        assert_eq!(SOURCE.example(), options(&[("preset", "plain")]));
        let pass = SOURCE.instance(&options(&[("preset", "high")])).unwrap();
        assert_eq!(pass.options(), options(&[("preset", "high")]));
        assert_eq!(
            SOURCE.check(&options(&[("preset", "fine")])).unwrap_err(),
            "preset=fine is none of plain or high"
        );
        assert_eq!(
            SOURCE
                .check(&options(&[("preset", "high"), ("file", "d.txt")]))
                .unwrap_err(),
            "only one of preset or file may be given"
        );
        assert!(
            SOURCE
                .describe()
                .contains("\n  preset (one of source; plain | high; e.g. plain): a preset detail"),
            "{}",
            SOURCE.describe()
        );
    }

    /// The text form marks required options and groups, and each option's line says its need, values and example.
    #[test]
    fn a_declaration_describes_its_options() {
        let text = TOY.describe();
        assert!(
            text.starts_with("toy{cell*,detail*,(factor|size)*,halo,fallback}\n"),
            "{text}"
        );
        assert!(
            text.contains("\n  detail (required; plain | high; e.g. plain): which collision is written"),
            "{text}"
        );
        assert!(
            text.contains("\n  size (one of by; e.g. 64): the larger side to reach"),
            "{text}"
        );
        assert!(
            text.contains("\n  halo (optional; e.g. 1): metres around each cell; without it: no halo"),
            "{text}"
        );
    }

    /// Reading an option the declaration does not have is a bug in the pass.
    #[test]
    #[should_panic(expected = "bad reads option other, which its declaration does not have")]
    fn reading_an_undeclared_option_panics() {
        const BAD: PassSpec = PassSpec {
            name: "bad",
            options: &[OptionSpec::optional("one", "1", "nothing", "nothing either")],
            make: |g| {
                let _ = g.optional("other");
                Ok(Box::new(Toy(Options::new())))
            },
        };
        let _ = BAD.instance(&Options::new());
    }

    /// An optional option that says nothing of its absence is a wrong declaration: what no value means is part of
    /// declaring it, as a required option's example is.
    #[test]
    #[should_panic(expected = "pass silent: optional option halo says nothing of what its absence means")]
    fn an_optional_option_states_its_absence() {
        const SILENT: PassSpec = PassSpec {
            name: "silent",
            options: &[OptionSpec::optional("halo", "1", "metres around each cell", " ")],
            make: |_| Ok(Box::new(Toy(Options::new()))),
        };
        SILENT.validate();
    }

    /// A group of one is a wrong declaration.
    #[test]
    #[should_panic(expected = "pass lonely: the one-of group by has one option")]
    fn a_group_of_one_is_refused() {
        const LONELY: PassSpec = PassSpec {
            name: "lonely",
            options: &[OptionSpec::one_of("by", "factor", "2", "the enlargement")],
            make: |_| Ok(Box::new(Toy(Options::new()))),
        };
        LONELY.validate();
    }

    /// A reader's choices in a pass's form: a cell size and a detail, and a name it may leave out.
    #[derive(Debug, PartialEq)]
    struct Read {
        name: Option<String>,
        cell: f32,
        detail: Detail,
    }

    impl TextForm for Read {
        const NAME: &'static str = "read-toy";
        const OPTIONS: &'static [OptionSpec] = &[
            OptionSpec::optional("name", "a", "what is read", "the caller names it"),
            OptionSpec::required("cell", "4", "metres, above 0: the grid's cell"),
            OptionSpec::choice::<Detail>("detail", "which collision is read"),
        ];
        fn make(given: &Given) -> Result<Self, String> {
            let cell = given.required("cell");
            Ok(Read {
                name: given.optional("name").map(str::to_owned),
                cell: cell
                    .parse()
                    .ok()
                    .filter(|c: &f32| *c > 0.)
                    .ok_or_else(|| format!("cell={cell} is not a number of metres above 0"))?,
                detail: given.choice("detail"),
            })
        }
        fn options(&self) -> Options {
            let mut options = options(&[("cell", &self.cell.to_string()), ("detail", self.detail.text())]);
            if let Some(name) = &self.name {
                options.insert("name".into(), name.clone());
            }
            options
        }
    }

    /// A text form reads back what it prints, field by field, and refuses as a pass's declaration does, naming the
    /// option; a text that is not one item of its name is refused.
    #[test]
    fn a_text_form_reads_back_what_it_prints() {
        use crate::pass::{parse_text_form, text_form, validate_text_form};
        validate_text_form::<Read>();
        for read in [
            Read {
                name: Some("m10".into()),
                cell: 2.5,
                detail: Detail::High,
            },
            Read {
                name: None,
                cell: 4.,
                detail: Detail::Plain,
            },
        ] {
            let text = text_form(&read);
            assert_eq!(parse_text_form::<Read>(&text).unwrap(), read, "{text}");
        }
        assert_eq!(
            text_form(&Read {
                name: Some("m10".into()),
                cell: 2.5,
                detail: Detail::High
            }),
            "read-toy{cell=2.5,detail=high,name=m10}"
        );
        let refusal = |text: &str| parse_text_form::<Read>(text).unwrap_err().to_string();
        assert_eq!(
            refusal("read-toy{detail=plain}"),
            "read-toy: cell is required: metres, above 0: the grid's cell"
        );
        assert_eq!(
            refusal("read-toy{cell=4,detail=fine}"),
            "read-toy: detail=fine is none of plain or high"
        );
        assert_eq!(
            refusal("read-toy{cell=4,detail=plain,colour=red}"),
            "read-toy: unknown option colour (read-toy takes name, cell, detail)"
        );
        assert_eq!(
            refusal("read-toy{cell=-1,detail=plain}"),
            "read-toy: cell=-1 is not a number of metres above 0"
        );
        assert_eq!(refusal("toy{cell=4,detail=plain}"), "toy is not read-toy");
        assert!(
            refusal("read-toy{cell=4,detail=plain}, read-toy{cell=4,detail=plain}")
                .contains("is not one read-toy")
        );
        assert!(refusal("").contains("is not one read-toy"));
    }
}