veredictum 0.1.3

The independent conformance instrument for openEHR clinical data repositories: a machine-readable catalogue of spec-cited test cases, executed against any running CDR, judged by pure-function verdicts
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
// SPDX-FileCopyrightText: Veredictum contributors
// SPDX-License-Identifier: Apache-2.0

//! The closed `${…}` variable-reference grammar and the case-level capture
//! grammar.
//!
//! Case cores speak these forms and nothing else (CNF 2.0 artifact-set
//! design, case-core contract): `${row.<column>}`, `${fixture.<field>}`,
//! `${<capture>}`, `${ds:<corpus key>}`, `${ds:<corpus key>#<view>}`,
//! `${recipe:<name>(row)}`, the temporal expressions
//! `${time:before(<t>)}` / `${time:after(<t>)}` / `${time:between(<t1>,<t2>)}`,
//! and `${ixit:<field>}` for a party-declared SUT fact no released operation
//! discloses. There is no `${stepN}` form. Binding request templates may additionally
//! mark a reference optional (`${offset?}`). A string outside these forms is
//! a validator error, never runner latitude.

use std::fmt;

use thiserror::Error;

use crate::ids::{CaptureName, CorpusKey, IdError, RecipeName, ViewName};
use crate::vocab::OutcomeKind;

/// Reference-grammar parse error.
#[derive(Debug, Error)]
pub enum RefError {
    /// A `${` without a closing `}`.
    #[error("unterminated ${{…}} reference in {0:?}")]
    Unterminated(String),
    /// A reference body outside the closed grammar.
    #[error("illegal reference ${{{0}}}: {1}")]
    Illegal(String, String),
    /// An embedded identifier failed its lexical rule.
    #[error("in ${{{reference}}}: {source}")]
    BadIdent {
        /// The offending reference body.
        reference: String,
        /// The identifier error.
        source: IdError,
    },
}

/// The `${fixture.<field>}` fields — closed to the fixture-set entry
/// bindings (`data_set`, `expected`, `defect`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FixtureField {
    /// The entry's corpus key.
    DataSet,
    /// The entry's expected outcome kind.
    Expected,
    /// The entry's defect phrase (invalid fixtures).
    Defect,
}

impl FixtureField {
    fn parse(s: &str) -> Option<Self> {
        match s {
            "data_set" => Some(Self::DataSet),
            "expected" => Some(Self::Expected),
            "defect" => Some(Self::Defect),
            _ => None,
        }
    }

    /// The field token.
    #[must_use]
    pub fn token(self) -> &'static str {
        match self {
            Self::DataSet => "data_set",
            Self::Expected => "expected",
            Self::Defect => "defect",
        }
    }
}

/// The `${ixit:<field>}` fields — closed to the environment facts a party
/// DECLARES about its SUT because no released operation discloses them.
///
/// A case may read such a fact, never invent one; a party that declares none
/// makes the referencing cases not-applicable with that citation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IxitField {
    /// The SUT's own configured system identifier
    /// (`crate::ixit::Ixit::system_id`).
    SystemId,
    /// A writable location on the SUT's OWN file system that the admin
    /// dump/load operations may use (`crate::ixit::Ixit::dump_location`).
    DumpLocation,
}

impl IxitField {
    fn parse(s: &str) -> Option<Self> {
        match s {
            "system_id" => Some(Self::SystemId),
            "dump_location" => Some(Self::DumpLocation),
            _ => None,
        }
    }

    /// The field token.
    #[must_use]
    pub fn token(self) -> &'static str {
        match self {
            Self::SystemId => "system_id",
            Self::DumpLocation => "dump_location",
        }
    }
}

/// A temporal at-time expression over captured commit instants.
///
/// Resolution is fixed by the interpreter laws (before = t − 1 ms, after = t
/// + 1 ms, between = midpoint) so two runners query identical instants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimeExpr {
    /// One millisecond before the named capture's commit instant.
    Before(CaptureName),
    /// One millisecond after the named capture's commit instant.
    After(CaptureName),
    /// The midpoint between two captured commit instants.
    Between(CaptureName, CaptureName),
}

/// One parsed `${…}` reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueRef {
    /// `${row.<column>}` — the current parameter-matrix row cell.
    Row(String),
    /// `${fixture.<field>}` — the current fixture-set entry.
    Fixture(FixtureField),
    /// `${<capture>}` — a case-scoped capture or `requires` handle.
    /// `optional` is the binding-template `${name?}` marker.
    Capture {
        /// The capture (or `requires` handle) the reference addresses.
        name: CaptureName,
        /// The `${name?}` marker: unresolved means "omit", not "fail".
        optional: bool,
    },
    /// `${ds:<key>}` / `${ds:<key>#<view>}` — a corpus data set or a named
    /// projection over it.
    DataSet {
        /// The corpus manifest key.
        key: CorpusKey,
        /// The named projection over the set, when one is addressed.
        view: Option<ViewName>,
    },
    /// `${ds:fixture}` — the current fixture-set entry's payload (legal only
    /// in cases carrying `parameters.fixture_set`).
    FixtureDataSet,
    /// `${recipe:<name>(row)}` — row-to-instance synthesis.
    Recipe(RecipeName),
    /// `${ixit:<field>}` — a party-declared environment fact about the SUT.
    Ixit(IxitField),
    /// `${time:…}` — temporal reference.
    Time(TimeExpr),
}

impl ValueRef {
    /// Parse one reference body (the text between `${` and `}`).
    ///
    /// # Errors
    /// Returns [`RefError`] when the body is outside the closed grammar.
    pub fn parse(body: &str) -> Result<Self, RefError> {
        let bad_ident = |source| RefError::BadIdent {
            reference: body.to_owned(),
            source,
        };
        let illegal = |why: &str| RefError::Illegal(body.to_owned(), why.to_owned());

        if let Some(column) = body.strip_prefix("row.") {
            // Braces are refused like whitespace: a column containing `}`
            // renders back to a `${row.…}` form that cuts at the first `}`,
            // so the accepted value could not survive its own Display.
            if column.is_empty()
                || column.contains(char::is_whitespace)
                || column.contains(['{', '}'])
            {
                return Err(illegal("row column must be a non-empty brace-free name"));
            }
            return Ok(Self::Row(column.to_owned()));
        }
        if let Some(field) = body.strip_prefix("fixture.") {
            return FixtureField::parse(field)
                .map(Self::Fixture)
                .ok_or_else(|| illegal("fixture field must be data_set | expected | defect"));
        }
        if body == "ds:fixture" {
            return Ok(Self::FixtureDataSet);
        }
        if let Some(rest) = body.strip_prefix("ds:") {
            let (key, view) = match rest.split_once('#') {
                Some((key, view)) => (key, Some(ViewName::parse(view).map_err(bad_ident)?)),
                None => (rest, None),
            };
            let key = CorpusKey::parse(key).map_err(bad_ident)?;
            return Ok(Self::DataSet { key, view });
        }
        if let Some(rest) = body.strip_prefix("recipe:") {
            let name = rest
                .strip_suffix("(row)")
                .ok_or_else(|| illegal("recipe reference must end in (row)"))?;
            return Ok(Self::Recipe(RecipeName::parse(name).map_err(bad_ident)?));
        }
        if let Some(rest) = body.strip_prefix("time:") {
            return Self::parse_time(rest).map(Self::Time).ok_or_else(|| {
                illegal("time expression must be before(<t>) | after(<t>) | between(<t1>,<t2>)")
            });
        }
        if let Some(field) = body.strip_prefix("ixit:") {
            return IxitField::parse(field)
                .map(Self::Ixit)
                .ok_or_else(|| illegal("ixit field must be system_id | dump_location"));
        }
        if body.contains(':') || body.contains('.') {
            return Err(illegal(
                "unknown reference form (closed grammar: row./fixture./ds:/recipe:/time:/ixit:/<capture>)",
            ));
        }
        let (name, optional) = match body.strip_suffix('?') {
            Some(name) => (name, true),
            None => (body, false),
        };
        Ok(Self::Capture {
            name: CaptureName::parse(name).map_err(bad_ident)?,
            optional,
        })
    }

    fn parse_time(rest: &str) -> Option<TimeExpr> {
        let inner = |prefix: &str| -> Option<&str> {
            rest.strip_prefix(prefix)?
                .strip_prefix('(')?
                .strip_suffix(')')
        };
        if let Some(arg) = inner("before") {
            return CaptureName::parse(arg.trim()).ok().map(TimeExpr::Before);
        }
        if let Some(arg) = inner("after") {
            return CaptureName::parse(arg.trim()).ok().map(TimeExpr::After);
        }
        if let Some(args) = inner("between") {
            let (a, b) = args.split_once(',')?;
            return Some(TimeExpr::Between(
                CaptureName::parse(a.trim()).ok()?,
                CaptureName::parse(b.trim()).ok()?,
            ));
        }
        None
    }
}

impl fmt::Display for ValueRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Row(c) => write!(f, "${{row.{c}}}"),
            Self::Fixture(field) => write!(f, "${{fixture.{}}}", field.token()),
            Self::Capture { name, optional } => {
                write!(f, "${{{name}{}}}", if *optional { "?" } else { "" })
            }
            Self::DataSet {
                key,
                view: Some(view),
            } => write!(f, "${{ds:{key}#{view}}}"),
            Self::DataSet { key, view: None } => write!(f, "${{ds:{key}}}"),
            Self::FixtureDataSet => f.write_str("${ds:fixture}"),
            Self::Recipe(name) => write!(f, "${{recipe:{name}(row)}}"),
            Self::Ixit(field) => write!(f, "${{ixit:{}}}", field.token()),
            Self::Time(TimeExpr::Before(t)) => write!(f, "${{time:before({t})}}"),
            Self::Time(TimeExpr::After(t)) => write!(f, "${{time:after({t})}}"),
            Self::Time(TimeExpr::Between(a, b)) => write!(f, "${{time:between({a},{b})}}"),
        }
    }
}

/// One segment of a templated string.
#[derive(Debug, Clone, PartialEq)]
pub enum Segment {
    /// Literal text.
    Lit(String),
    /// A `${…}` reference.
    Ref(ValueRef),
}

/// A string value that may interleave literal text with `${…}` references
/// (`"${versioned_object_uid}::<system>::2"`). Parsing validates every
/// embedded reference against the closed grammar.
#[derive(Debug, Clone, PartialEq)]
pub struct Template {
    raw: String,
    segments: Vec<Segment>,
}

impl Template {
    /// Parse a raw string, validating every `${…}` occurrence.
    ///
    /// # Errors
    /// Returns [`RefError`] on an unterminated or illegal reference.
    pub fn parse(raw: &str) -> Result<Self, RefError> {
        let mut segments = Vec::new();
        let mut rest = raw;
        while let Some(start) = rest.find("${") {
            let (lit, tail) = rest.split_at(start);
            if !lit.is_empty() {
                segments.push(Segment::Lit(lit.to_owned()));
            }
            let body_and_more = tail.get(2..).unwrap_or_default();
            let end = body_and_more
                .find('}')
                .ok_or_else(|| RefError::Unterminated(raw.to_owned()))?;
            let body = body_and_more.get(..end).unwrap_or_default();
            segments.push(Segment::Ref(ValueRef::parse(body)?));
            rest = body_and_more.get(end + 1..).unwrap_or_default();
        }
        if !rest.is_empty() {
            segments.push(Segment::Lit(rest.to_owned()));
        }
        Ok(Self {
            raw: raw.to_owned(),
            segments,
        })
    }

    /// The raw authored text.
    #[must_use]
    pub fn raw(&self) -> &str {
        &self.raw
    }

    /// The parsed segments.
    #[must_use]
    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    /// Every reference in the template, in order.
    pub fn refs(&self) -> impl Iterator<Item = &ValueRef> {
        self.segments.iter().filter_map(|s| match s {
            Segment::Ref(r) => Some(r),
            Segment::Lit(_) => None,
        })
    }

    /// Whether the whole template is exactly one reference (no literal text).
    #[must_use]
    pub fn as_single_ref(&self) -> Option<&ValueRef> {
        match self.segments.as_slice() {
            [Segment::Ref(r)] => Some(r),
            _ => None,
        }
    }
}

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

impl serde::Serialize for Template {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.raw)
    }
}

impl<'de> serde::Deserialize<'de> for Template {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

/// What part of the step outcome a case-level capture reads. Sources are
/// closed: a logical field mapped by the binding, the full response body, or
/// the committed audit time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CaptureField {
    /// `<outcome>.body` — the full response representation.
    Body,
    /// `<outcome>.commit_time` — the committed audit time (the anchor for
    /// temporal at-time cases).
    CommitTime,
    /// `<outcome>.<field>` (`list` for the `<field>[]` list-capture form).
    Field {
        /// The field of the outcome's capture mapping.
        name: CaptureName,
        /// The `<field>[]` form: capture every match as a list.
        list: bool,
    },
}

/// A case-level capture source: `<outcome kind>.<capture field>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureValueSource {
    /// The outcome kind whose mapping supplies the value.
    pub outcome: OutcomeKind,
    /// What is read.
    pub field: CaptureField,
}

impl CaptureValueSource {
    /// Parse `created.ehr_id`, `ok.body`, `created.version_uids[]`, ….
    ///
    /// # Errors
    /// Returns [`RefError`] when the source is outside the closed grammar.
    pub fn parse(raw: &str) -> Result<Self, RefError> {
        let illegal = |why: &str| RefError::Illegal(raw.to_owned(), why.to_owned());
        let (outcome, field) = raw
            .split_once('.')
            .ok_or_else(|| illegal("capture source must be <outcome>.<field>"))?;
        let outcome = OutcomeKind::from_token(outcome)
            .ok_or_else(|| illegal("capture source outcome must be an outcome kind"))?;
        let field = match field {
            "body" => CaptureField::Body,
            "commit_time" => CaptureField::CommitTime,
            other => {
                let (name, list) = match other.strip_suffix("[]") {
                    Some(name) => (name, true),
                    None => (other, false),
                };
                CaptureField::Field {
                    name: CaptureName::parse(name).map_err(|source| RefError::BadIdent {
                        reference: raw.to_owned(),
                        source,
                    })?,
                    list,
                }
            }
        };
        Ok(Self { outcome, field })
    }
}

impl fmt::Display for CaptureValueSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let token = self.outcome.token();
        match &self.field {
            CaptureField::Body => write!(f, "{token}.body"),
            CaptureField::CommitTime => write!(f, "{token}.commit_time"),
            CaptureField::Field { name, list } => {
                write!(f, "{token}.{name}{}", if *list { "[]" } else { "" })
            }
        }
    }
}

impl serde::Serialize for CaptureValueSource {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> serde::Deserialize<'de> for CaptureValueSource {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Self::parse(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
#[expect(
    clippy::panic_in_result_fn,
    reason = "Result-returning tests in the Book ch11 shape, each asserting; \
              clippy offers no allow-in-tests knob for this lint"
)]
mod tests {
    use super::*;

    fn parse_ref(body: &str) -> ValueRef {
        ValueRef::parse(body).unwrap()
    }

    #[test]
    fn row_column_refuses_braces() {
        // A column containing `}` would render to a `${row.…}` form that cuts
        // at the first `}` and cannot survive its own Display (fuzz review,
        // #11): the parse refuses it up front.
        assert!(ValueRef::parse("row.a}b").is_err());
        assert!(ValueRef::parse("row.a{b").is_err());
    }

    #[test]
    fn closed_forms_parse() {
        assert_eq!(parse_ref("row.ehr_id"), ValueRef::Row("ehr_id".into()));
        assert_eq!(
            parse_ref("fixture.expected"),
            ValueRef::Fixture(FixtureField::Expected)
        );
        assert!(matches!(
            parse_ref("first_ehr_id"),
            ValueRef::Capture {
                optional: false,
                ..
            }
        ));
        assert!(matches!(
            parse_ref("offset?"),
            ValueRef::Capture { optional: true, .. }
        ));
        assert!(matches!(
            parse_ref("ds:cnf.set.bp-10"),
            ValueRef::DataSet { view: None, .. }
        ));
        assert!(matches!(
            parse_ref("ds:cnf.set.bp-10#magnitude_ge_140_by_uid"),
            ValueRef::DataSet { view: Some(_), .. }
        ));
        assert!(matches!(
            parse_ref("recipe:ehr_status(row)"),
            ValueRef::Recipe(_)
        ));
        assert!(matches!(
            parse_ref("time:before(t1)"),
            ValueRef::Time(TimeExpr::Before(_))
        ));
        assert!(matches!(
            parse_ref("time:between(t1,t2)"),
            ValueRef::Time(TimeExpr::Between(..))
        ));
        assert_eq!(
            parse_ref("ixit:system_id"),
            ValueRef::Ixit(IxitField::SystemId)
        );
    }

    #[test]
    fn ixit_references_round_trip_and_stay_closed() {
        let r = parse_ref("ixit:system_id");
        assert_eq!(r.to_string(), "${ixit:system_id}");
        // The rendered form parses back inside a template.
        let template = Template::parse(&r.to_string()).unwrap();
        assert_eq!(template.as_single_ref(), Some(&r));
        // The field set is closed: no invented environment facts.
        assert!(ValueRef::parse("ixit:hardware_class").is_err());
        assert!(ValueRef::parse("ixit:").is_err());
    }

    #[test]
    fn illegal_forms_rejected() {
        assert!(ValueRef::parse("step2.body").is_err()); // no ${stepN} form
        assert!(ValueRef::parse("fixture.payload").is_err());
        assert!(ValueRef::parse("recipe:ehr_status").is_err());
        assert!(ValueRef::parse("time:around(t1)").is_err());
        assert!(ValueRef::parse("ds:Not.A.Key").is_err());
    }

    #[test]
    fn templates_scan_all_refs() {
        let t = Template::parse("${versioned_object_uid}::<system>::2").unwrap();
        assert_eq!(t.refs().count(), 1);
        assert!(t.as_single_ref().is_none());
        assert!(Template::parse("${unclosed").is_err());
        assert!(Template::parse("prefix ${step2.body} suffix").is_err());
        let single = Template::parse("${ds:cnf.composition.minimal_event.v1}").unwrap();
        assert!(single.as_single_ref().is_some());
    }

    #[test]
    fn capture_sources() {
        let s = CaptureValueSource::parse("created.version_uids[]").unwrap();
        assert_eq!(s.outcome, OutcomeKind::Created);
        assert!(matches!(s.field, CaptureField::Field { list: true, .. }));
        assert!(matches!(
            CaptureValueSource::parse("ok.body").unwrap().field,
            CaptureField::Body
        ));
        assert!(matches!(
            CaptureValueSource::parse("created.commit_time")
                .unwrap()
                .field,
            CaptureField::CommitTime
        ));
        assert!(CaptureValueSource::parse("nonsense.ehr_id").is_err());
        assert!(CaptureValueSource::parse("created").is_err());
    }

    /// Every closed form renders back to the text it was parsed from, and the
    /// rendered text parses to the same reference. A catalogue artifact that
    /// is read and re-emitted therefore carries the same reference, so a
    /// `Display` that dropped a field could not survive its own round trip.
    #[test]
    fn every_reference_form_renders_to_the_text_it_parsed_from() -> Result<(), RefError> {
        for body in [
            "row.magnitude",
            "fixture.data_set",
            "fixture.expected",
            "fixture.defect",
            "ehr_id",
            "offset?",
            "ds:cnf.set.bp-10",
            "ds:cnf.set.bp-10#magnitude_ge_140_by_uid",
            "ds:fixture",
            "recipe:ehr_status(row)",
            "ixit:system_id",
            "ixit:dump_location",
            "time:before(t1)",
            "time:after(t1)",
            "time:between(t1,t2)",
        ] {
            let parsed = ValueRef::parse(body)?;
            assert_eq!(parsed.to_string(), format!("${{{body}}}"));
            let template = Template::parse(&parsed.to_string())?;
            assert_eq!(template.as_single_ref(), Some(&parsed));
        }
        Ok(())
    }

    /// A template keeps its authored text: `Display` and the serialized form
    /// both give back the raw string, and deserializing that string yields the
    /// same template. Re-emitting a case core cannot rewrite its templates.
    #[test]
    fn a_template_renders_and_serializes_as_its_authored_text()
    -> Result<(), Box<dyn std::error::Error>> {
        let raw = "${versioned_object_uid}::<system>::2";
        let template = Template::parse(raw)?;
        assert_eq!(template.to_string(), raw);
        assert_eq!(template.raw(), raw);
        let json = serde_json::to_string(&template)?;
        assert_eq!(json, format!("\"{raw}\""));
        let back: Template = serde_json::from_str(&json)?;
        assert_eq!(back, template);
        Ok(())
    }

    /// A capture source renders back to the text it parsed from, the `[]` list
    /// marker included, and serializes as that same string.
    #[test]
    fn a_capture_source_renders_and_serializes_as_the_text_it_parsed_from()
    -> Result<(), Box<dyn std::error::Error>> {
        for raw in [
            "created.ehr_id",
            "created.version_uids[]",
            "ok.body",
            "created.commit_time",
        ] {
            let source = CaptureValueSource::parse(raw)?;
            assert_eq!(source.to_string(), raw);
            assert_eq!(serde_json::to_string(&source)?, format!("\"{raw}\""));
            let back: CaptureValueSource = serde_json::from_str(&format!("\"{raw}\""))?;
            assert_eq!(back, source);
        }
        Ok(())
    }

    /// A capture source's field is a lexical capture name. A field that is not
    /// one fails as a `BadIdent` naming the whole source, so the error points
    /// at the authored text rather than at a bare fragment.
    #[test]
    fn a_capture_source_field_must_be_a_lexical_capture_name() {
        let error = CaptureValueSource::parse("created.9lives").unwrap_err();
        assert!(
            matches!(&error, RefError::BadIdent { reference, .. } if reference == "created.9lives"),
            "{error}"
        );
    }
}