fhirconnect 0.2.3

The FHIRconnect mapping language for Rust: the mapping file model and its validation, context resolution into an immutable program, and the bidirectional interpreter between openEHR compositions and FHIR resources
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The interpreter over a compiled program, one traversal for both
//! directions.
//!
//! The walk is top-down in program order. For each mapping it evaluates the
//! input-side conditions, reads the input occurrences, runs the data-type cell
//! the two classes fix, and writes the result where the recurrence rules put
//! it. A `followedBy` child runs once per occurrence its parent bound, which
//! is what pairs two repeating lists against each other
//! (`recurrence/PopulatingAnEntry.adoc`).
//!
//! Where a mapping writes is decided by one rule, applied on whichever side is
//! the output: the axes the parent bound keep their instance, and every
//! repeating element below them takes a fresh instance per input occurrence,
//! because "FHIRconnect always appends to a `0..n` path if it's not iterated"
//! (`recurrence/PopulatingAnEntry.adoc` §Wrong mapping). An output with no
//! repeating element below the parent holds one value, so a second write
//! overwrites the first (`recurrence/Overwriting.adoc`) and a `0..n` input
//! leaves only its last occurrence, with the rest declared lost
//! (`recurrence/TransformingList.adoc`).

pub mod build;
pub mod convert;
pub mod defaults;
pub mod demographic;
pub mod display;
pub mod error;
pub mod event;
mod frame;
pub mod functions;
pub mod links;
pub mod manual;
pub mod occurrence;
pub mod party;
pub mod place;
pub mod programmed;
pub mod reference;
pub mod split;
pub mod tail;
pub mod translate;
mod unread;
pub mod walk;

use std::collections::BTreeMap;

use fhir_types::codec::Object;
use fhir_types::codec::Value;
use fhir_types::r4::coding::Coding;
use openehr_mapping_core::composition::CanonicalComposition;
use openehr_mapping_core::composition::CanonicalDocument;
use openehr_mapping_core::composition::NodeValue;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::WebTemplateIndex;
use openehr_mapping_core::index::paths::FlatId;

use crate::engine::context::CallContext;
use crate::engine::family;
use crate::engine::invariant;
use crate::engine::lens::null_flavour::NullFlavour;
use crate::engine::outcome::Location;
use crate::engine::outcome::Outcome;
use crate::engine::outcome::Warning;
use crate::engine::rm::RmValue;
use crate::engine::seam::Seams;
use crate::engine::subject::SubjectIdentifier;
use crate::model::ast::keyword::Direction;
use crate::resolve::program::Program;
use crate::resolve::program::target::ListAxis;
use crate::resolve::program::target::OpenehrTarget;
use crate::tree::Occurrence;

use crate::tree::element::Table;

use crate::engine::traverse::defaults::Defaults;
use crate::engine::traverse::error::EngineError;

/// How many instances of one repeating node a read probes for.
///
/// The composition carries no instance count of its own, so the read stops at
/// the first absent instance and this is the ceiling on that probe. No
/// specification governs this: our own design.
const INSTANCE_CEILING: u32 = 1024;

/// The `LINK.type` a `link` mapping that names none writes.
///
/// `LINK.type` is mandatory
/// (<https://specifications.openehr.org/releases/RM/Release-1.1.0/common.html#_link_class>)
/// and the `link` key leaves it optional. No specification governs the
/// value: our own design.
const LINK_TYPE: &str = "reference";

/// The occurrence a mapping is bound to, on both sides.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Binding {
    fhir: Occurrence,
    openehr: Vec<RmPosition>,
    /// The repeating openEHR nodes `openehr` holds an instance of, one per
    /// position, outermost first.
    axes: Vec<FlatId>,
    /// The element of each `List` attribute below the node `elements` holds
    /// an instance of, one per position, outermost first.
    elements: Vec<RmPosition>,
    /// The `List` attributes `elements` holds an element of.
    lists: Vec<ListAxis>,
    /// How many references deep the document the FHIR occurrence indexes
    /// lies, the program's own resource being `0`.
    level: usize,
}

impl Binding {
    /// Returns how many of the leading repeating nodes of `axes` this
    /// binding holds an instance of.
    ///
    /// A path may leave the node its parent is anchored at
    /// (`basics/path_operators.adoc`, `../`), so only the repeating nodes the
    /// two share keep the parent's instance; one the target does not lie
    /// below binds nothing of it.
    fn shared(&self, axes: &[FlatId]) -> usize {
        self.axes
            .iter()
            .zip(axes)
            .zip(&self.openehr)
            .take_while(|&((held, wanted), _)| held == wanted)
            .count()
    }

    /// Returns the binding of a FHIR occurrence at `level` that keeps this
    /// binding's openEHR instance, for a mapping with no openEHR node of
    /// its own.
    fn keeping_openehr(&self, fhir: Occurrence, level: usize) -> Self {
        Self {
            fhir,
            openehr: self.openehr.clone(),
            axes: self.axes.clone(),
            elements: self.elements.clone(),
            lists: self.lists.clone(),
            level,
        }
    }

    /// Returns how many of the `List` axes of `target` this binding holds an
    /// element of.
    ///
    /// A list lies inside the value of one node instance, so the binding
    /// holds its element only while it holds every repeating node of the
    /// target and names the same attributes below the same node.
    fn shared_lists(&self, target: &OpenehrTarget) -> usize {
        let depth = target.occurrences().len();
        if self.shared(target.occurrences()) != depth || self.openehr.len() != depth {
            return 0;
        }
        self.lists
            .iter()
            .zip(target.lists())
            .zip(&self.elements)
            .take_while(|&((held, wanted), _)| held == wanted)
            .count()
    }

    /// Returns the binding of an openEHR occurrence's `positions`, its node's
    /// instance followed by the element of each `List` axis of `target`.
    ///
    /// A mapping with no openEHR side reads the instance its parent bound, so
    /// it keeps the parent's elements.
    fn of_openehr(
        &self,
        target: Option<&OpenehrTarget>,
        fhir: Occurrence,
        mut positions: Vec<RmPosition>,
        level: usize,
    ) -> Self {
        let Some(target) = target else {
            return Self {
                fhir,
                axes: self.axes_of(None, positions.len()),
                openehr: positions,
                elements: self.elements.clone(),
                lists: self.lists.clone(),
                level,
            };
        };
        let depth = target.occurrences().len().min(positions.len());
        let elements = positions.split_off(depth);
        let lists = target
            .lists()
            .get(..elements.len())
            .unwrap_or(target.lists())
            .to_vec();
        Self {
            fhir,
            axes: self.axes_of(Some(target), positions.len()),
            openehr: positions,
            elements,
            lists,
            level,
        }
    }

    /// Returns the repeating nodes of `target` the positions `held` name,
    /// or the parent's when the mapping has no openEHR side.
    fn axes_of(&self, target: Option<&OpenehrTarget>, held: usize) -> Vec<FlatId> {
        let axes = target.map_or(self.axes.as_slice(), OpenehrTarget::occurrences);
        axes.get(..held).unwrap_or(axes).to_vec()
    }
}

/// A document a `reference` mapping left to run over the resource it
/// resolved or creates.
///
/// A `^` run can climb back out of the referenced resource
/// (`basics/path_operators.adoc`, §Recurrence and parent elements), so the
/// document stays reachable with the occurrence the reference was entered at.
#[derive(Debug)]
struct Frame {
    /// The document the reference mapping was written in.
    document: Value,
    /// The occurrence of the reference element in that document.
    occurrence: Occurrence,
    /// The split pin that document held.
    pin: Option<(Vec<String>, Occurrence)>,
    /// The instance counters of that document.
    counters: BTreeMap<(String, String), usize>,
}

/// One openEHR value the run produced.
#[derive(Debug, Clone, PartialEq)]
struct Written {
    flat_id: FlatId,
    positions: Vec<RmPosition>,
    value: Held,
}

/// What the run holds at one place of the composition.
#[derive(Debug, Clone, PartialEq)]
enum Held {
    /// A whole value a cell produced.
    Value(RmValue),
    /// A value written one tail attribute at a time, as canonical JSON, read
    /// as its class when the run builds the composition.
    Partial(serde_json::Map<String, serde_json::Value>),
    /// The canonical JSON of a whole value a registered function produced,
    /// which travels to the builder as written.
    Canonical(serde_json::Value),
}

/// The value at the end of an openEHR target, the node's own or its tail's.
#[derive(Debug, Clone, PartialEq)]
enum Leaf {
    /// A data value a cell reads.
    Value(Box<RmValue>),
    /// A scalar attribute, as its text.
    Scalar(String),
    /// An `ELEMENT`'s null flavour with its reason.
    NullFlavour(Box<NullFlavour>),
}

/// Runs `program` over a FHIR document, producing a composition.
///
/// `seams` carries what the run calls out to: the `mappingCode` registry, the
/// source a `reference` mapping fetches the referenced resource from, and the
/// terminology server a `conceptmap` translates through, which every
/// translation reaches before the composition is built.
/// `context` carries the per-call values a `manual` path reads through
/// `$context`; pass [`CallContext::new`] when the caller supplied none.
///
/// # Errors
///
/// Returns [`EngineError`] for any element the program cannot map, and for a
/// set of values the template does not admit as a composition.
pub fn to_openehr<T: Table + ?Sized>(
    program: &Program,
    table: &T,
    index: &WebTemplateIndex,
    document: &Value,
    seams: &Seams<'_>,
    defaults: &Defaults,
    context: &CallContext,
) -> Result<Outcome<CanonicalComposition>, EngineError> {
    composition_program(program)?;
    let mut run = Run::new(
        program,
        table,
        index,
        Direction::FhirToOpenehr,
        *seams,
        context,
        document.clone(),
        None,
    );
    // NOTE: basics/Variables.adoc, `$archetype` is the root as `$resource` is, so one
    // resource maps into one instance of the start archetype and its axes are bound.
    run.pins = program
        .root_axes()
        .iter()
        .map(|axis| (axis.clone(), RmPosition::first()))
        .collect();
    run.whole_program()?;
    let mut defaulted = run.apply_defaults(defaults)?;
    let unplaced = run.place_facility(defaults, &mut defaulted)?;
    if let Some(origin) = defaults.origin() {
        run.families.extend(family::feeder_audit(
            index.root(),
            origin,
            &defaulted,
            defaults.facility.as_ref().filter(|_| unplaced),
        ));
    }
    let (values, routed) = run.node_values()?;
    let built = index
        .build_composition(&values, &defaults.start_time)
        .map_err(|source| EngineError::Build {
            source: Box::new(source),
        })?;
    let built = run.amend_intervals(built)?;
    run.carried_whole(&built, &routed)?;
    Ok(Outcome::new(built, run.warnings)
        .with_consumed(run.consumed)
        .with_subject(run.subject)
        .with_reads(run.reads))
}

/// Runs `program` over a composition, producing a FHIR resource.
///
/// The run maps the first occurrence of the context's start archetype. When
/// the composition holds it more than once, the further occurrences are
/// declared as [`crate::engine::outcome::Loss::UnmappedOccurrences`], never
/// mixed into the resource; [`to_fhir_each`] maps every occurrence on its own.
///
/// `seams` carries what the run calls out to: the `mappingCode` registry and
/// the sink that assigns the id of every resource a `reference` mapping or a
/// `hierarchy.split` creates. Those resources travel as
/// [`Outcome::created`]. A `conceptmap` translates the code the composition
/// holds through the seams' terminology server. `context` carries the per-call values a `manual`
/// path reads through `$context`; pass [`CallContext::new`] when the caller
/// supplied none.
///
/// # Errors
///
/// Returns [`EngineError::NotApplicable`] when the program's own
/// `openehrCondition` does not hold over the composition,
/// [`EngineError::Invariant`] when the produced resource or one it created
/// breaks a constraint [`crate::engine::invariant::check`] holds it to, and
/// [`EngineError`]
/// for any element the program cannot map.
pub fn to_fhir<T: Table + ?Sized>(
    program: &Program,
    table: &T,
    index: &WebTemplateIndex,
    composition: &CanonicalComposition,
    seams: &Seams<'_>,
    context: &CallContext,
) -> Result<Outcome<Value>, EngineError> {
    composition_program(program)?;
    let instances = root_instances(program, index, composition)?;
    let first = instances.first().cloned().unwrap_or_default();
    let mut outcome = read_out(
        program,
        table,
        index,
        composition,
        Some(composition),
        seams,
        context,
        &first,
    )?;
    let further = instances.len().saturating_sub(1);
    if further > 0 {
        outcome.warn(Warning::new(
            crate::engine::outcome::Loss::UnmappedOccurrences {
                archetype: start_archetype(program),
                count: further,
            },
            Location::default(),
        ));
    }
    Ok(outcome)
}

/// One occurrence of a context's start archetype, run on its own by
/// [`to_fhir_each`].
#[derive(Debug)]
pub enum Each {
    /// The occurrence mapped to a resource.
    Mapped {
        /// The 1-based instance of each repeating axis down to the start
        /// archetype.
        occurrence: Vec<u32>,
        /// The path that names the occurrence in the composition
        /// ([`openehr_mapping_core::index::WebTemplateIndex::entry_path`]),
        /// the entry path its deterministic id derives from
        /// ([`crate::engine::identity::deterministic_id`]).
        path: String,
        /// The resource and what its run declared.
        outcome: Outcome<Value>,
    },
    /// The context's `openehrCondition` does not hold at the occurrence.
    NotApplicable {
        /// The 1-based instance of each repeating axis down to the start
        /// archetype.
        occurrence: Vec<u32>,
        /// The path that names the occurrence in the composition.
        path: String,
    },
}

/// Runs `program` once per occurrence of its start archetype in a
/// composition, producing one resource per occurrence.
///
/// Each run reads its own occurrence's subtree alone, the start archetype's
/// axes pinned to it the way a `hierarchy.split` pins its node
/// (`types-of-mappings/concept-type/HierarchyMappings.adoc`, §split), and the
/// context's `openehrCondition` is evaluated at that occurrence, so one
/// occurrence may map while another is not applicable. FHIRconnect v1.0.0
/// does not say how a context binds to a start archetype a composition holds
/// more than once: no specification governs this, our own design. A
/// composition that holds no occurrence answers an empty list.
///
/// # Errors
///
/// [`EngineError`] for any element one occurrence cannot map, and the
/// [`EngineError::Invariant`] of a resource that breaks a constraint; a
/// condition that does not hold is [`Each::NotApplicable`], never an error.
pub fn to_fhir_each<T: Table + ?Sized>(
    program: &Program,
    table: &T,
    index: &WebTemplateIndex,
    composition: &CanonicalComposition,
    seams: &Seams<'_>,
    context: &CallContext,
) -> Result<Vec<Each>, EngineError> {
    composition_program(program)?;
    let mut each = Vec::new();
    for instance in root_instances(program, index, composition)? {
        let occurrence: Vec<u32> = instance.iter().map(|position| position.get()).collect();
        // NOTE: an instance of the axes that holds no start archetype root is
        // no occurrence of it, a legitimate absence; no specification governs
        // this, our own design.
        let Some(path) = entry_path(program, index, composition, &instance)? else {
            continue;
        };
        match read_out(
            program,
            table,
            index,
            composition,
            Some(composition),
            seams,
            context,
            &instance,
        ) {
            Ok(outcome) => each.push(Each::Mapped {
                occurrence,
                path,
                outcome,
            }),
            Err(EngineError::NotApplicable { .. }) => {
                each.push(Each::NotApplicable { occurrence, path });
            }
            Err(error) => return Err(error),
        }
    }
    Ok(each)
}

/// Returns every instance of the program's start archetype the composition
/// holds, as the positions of its repeating axes, in document order.
///
/// A start archetype on no repeating axis has the one instance `[]`.
fn root_instances(
    program: &Program,
    index: &WebTemplateIndex,
    composition: &CanonicalComposition,
) -> Result<Vec<Vec<RmPosition>>, EngineError> {
    let mut found: Vec<Vec<RmPosition>> = vec![Vec::new()];
    for axis in program.root_axes() {
        let refuse = |source| EngineError::Template {
            mapping: String::from(program.context().as_str()),
            node: String::from(axis.as_str()),
            source: Box::new(source),
        };
        let node = index.node_by_flat_id(axis).map_err(refuse)?;
        let mut deeper = Vec::new();
        for prefix in found {
            let mut instance = 1u32;
            while instance <= INSTANCE_CEILING {
                let mut positions = prefix.clone();
                positions.push(RmPosition::new(instance).map_err(|source| {
                    EngineError::Position {
                        mapping: String::from(program.context().as_str()),
                        source,
                    }
                })?);
                if !index.holds(composition, node, &positions).map_err(refuse)? {
                    break;
                }
                deeper.push(positions);
                instance = instance.saturating_add(1);
            }
        }
        found = deeper;
    }
    Ok(found)
}

/// Returns the path that names one instance of the program's start archetype
/// root in `composition`, or `None` when the instance holds no root.
///
/// A program with no root node in its template, a context whose start is the
/// composition itself, names [`crate::engine::identity::ROOT_PATH`].
fn entry_path(
    program: &Program,
    index: &WebTemplateIndex,
    composition: &CanonicalComposition,
    instance: &[RmPosition],
) -> Result<Option<String>, EngineError> {
    let Some(root) = program.root() else {
        return Ok(Some(String::from(crate::engine::identity::ROOT_PATH)));
    };
    let refuse = |source| EngineError::Template {
        mapping: String::from(program.context().as_str()),
        node: String::from(root.as_str()),
        source: Box::new(source),
    };
    let node = index.node_by_flat_id(root).map_err(refuse)?;
    let named = index
        .entry_path(composition, node, instance)
        .map_err(refuse)?;
    Ok(named.map(|path| {
        let rendered = path.to_string();
        if rendered.is_empty() {
            String::from(crate::engine::identity::ROOT_PATH)
        } else {
            rendered
        }
    }))
}

/// Returns the archetype id the context's start model mapping declares.
pub(crate) fn start_archetype(program: &Program) -> String {
    program
        .models()
        .iter()
        .find(|model| model.name() == program.start())
        .and_then(|model| model.archetype())
        .map(ToString::to_string)
        .unwrap_or_default()
}

/// Runs `program` over a canonical document, a composition or a party,
/// producing a FHIR resource, with the start archetype's axes pinned to
/// `instance` when it names one.
#[expect(
    clippy::too_many_arguments,
    reason = "the three composition entry points and the party one share this one run"
)]
fn read_out<T: Table + ?Sized>(
    program: &Program,
    table: &T,
    index: &WebTemplateIndex,
    document: &dyn CanonicalDocument,
    composition: Option<&CanonicalComposition>,
    seams: &Seams<'_>,
    context: &CallContext,
    instance: &[RmPosition],
) -> Result<Outcome<Value>, EngineError> {
    let mut run = Run::new(
        program,
        table,
        index,
        Direction::OpenehrToFhir,
        *seams,
        context,
        empty_resource(program.resource().as_str()),
        Some(document),
    );
    run.pins = program
        .root_axes()
        .iter()
        .cloned()
        .zip(instance.iter().copied())
        .collect();
    run.whole_program()?;
    if let Some(composition) = composition {
        let read = run.carried.take();
        let unread = unread::unread(program, index, composition, instance, &read)?;
        // NOTE: no specification governs this: our own design, an element a warning of the run
        // already names (a mapping it skipped) is declared once.
        let named: std::collections::BTreeSet<String> = run
            .warnings
            .iter()
            .filter_map(|warning| warning.location().openehr().map(String::from))
            .collect();
        run.warnings.extend(unread.into_iter().filter(|warning| {
            warning
                .location()
                .openehr()
                .is_none_or(|path| !named.contains(path))
        }));
    }
    let created = core::mem::take(&mut run.created);
    for document in core::iter::once(&run.fhir).chain(&created) {
        invariant::check(document).map_err(|breach| EngineError::Invariant {
            context: String::from(program.context().as_str()),
            breach,
        })?;
    }
    Ok(Outcome::new(run.fhir, run.warnings).with_created(created))
}

/// Refuses a party program at an entry point that runs over a composition.
///
/// A party program reads and builds a `PARTY`, and the composition builder
/// applies the composition defaults and the `ctx/` vocabulary, so a party
/// program never reaches it; it runs through [`party::to_party`] and
/// [`party::from_party`]. No specification governs this: our own design.
fn composition_program(program: &Program) -> Result<(), EngineError> {
    match program.party() {
        Some(party) => Err(EngineError::PartyProgram {
            context: String::from(program.context().as_str()),
            party,
        }),
        None => Ok(()),
    }
}

/// Returns a resource of `resource_type` that holds nothing else yet.
fn empty_resource(resource_type: &str) -> Value {
    let mut resource = Object::new();
    resource.insert(
        String::from("resourceType"),
        Value::String(String::from(resource_type)),
    );
    Value::Object(resource)
}

/// One run of one program, in one direction.
struct Run<'a, T: Table + ?Sized> {
    program: &'a Program,
    table: &'a T,
    index: &'a WebTemplateIndex,
    direction: Direction,
    seams: Seams<'a>,
    context: &'a CallContext,
    warnings: Vec<Warning>,
    /// The FHIR document the mappings read or write: the run's own resource,
    /// or the referenced or created one a nested run swapped in.
    fhir: Value,
    composition: Option<&'a dyn CanonicalDocument>,
    written: Vec<Written>,
    families: Vec<NodeValue>,
    /// Whether a mapping wrote `EVENT_CONTEXT.health_care_facility`.
    facility_written: bool,
    /// The defaults the run writes as `ctx/` keys.
    context_keys: Vec<NodeValue>,
    /// The values the built composition must carry at the nodes a `ctx/`
    /// default sets, where the key holds less than the value.
    expected: Vec<Routed>,
    counters: BTreeMap<(String, String), usize>,
    chain: Vec<String>,
    /// The references the current reference chain entered, outermost first.
    references: Vec<String>,
    /// The `ehr:` URI a resource-side `link` named for the resource the
    /// innermost `reference` mapping creates going out of openEHR.
    linked_to: Option<String>,
    /// The documents the current reference chain left, outermost first, so
    /// the frame at index `n` is the document of level `n`.
    frames: Vec<Frame>,
    /// The resources the run created beside its own.
    created: Vec<Value>,
    /// The literal references a `slotContext` consumed.
    consumed: Vec<String>,
    /// The instance a `hierarchy.split` fixes for each openEHR axis it pins.
    pins: Vec<(FlatId, RmPosition)>,
    /// The FHIR element a split out of FHIR fixes, as its repeating axes and
    /// its occurrence.
    fhir_pin: Option<(Vec<String>, Occurrence)>,
    /// The concept each distinct code translated to, so the seam is asked
    /// once per code in a run.
    translations: BTreeMap<translate::TranslationKey, Option<Coding>>,
    /// The identifiers a `mappingCode` function offered as the subject of the EHR.
    subject: Vec<SubjectIdentifier>,
    /// The interval events the run wrote, set on the built composition.
    intervals: Vec<event::Interval>,
    /// The FHIR elements the run read going into openEHR.
    reads: Vec<Location>,
    /// The template node instances whose value the run read going out of
    /// openEHR.
    carried: core::cell::RefCell<std::collections::BTreeSet<unread::Instance>>,
}

impl<T: Table + ?Sized> Run<'_, T> {
    /// Runs the whole program from its start, once the program's own
    /// condition admits the input.
    fn whole_program(&mut self) -> Result<(), EngineError> {
        self.admits_context()?;
        let program = self.program;
        self.split_or_run(
            program.mappings(),
            program.hierarchy(),
            program.start().as_str(),
            &Binding::default(),
        )
    }
}

impl<'a, T: Table + ?Sized> Run<'a, T> {
    /// Creates a run with nothing written yet.
    #[expect(
        clippy::too_many_arguments,
        reason = "a run is assembled once per entry point from exactly the inputs the two entry points take"
    )]
    fn new(
        program: &'a Program,
        table: &'a T,
        index: &'a WebTemplateIndex,
        direction: Direction,
        seams: Seams<'a>,
        context: &'a CallContext,
        fhir: Value,
        composition: Option<&'a dyn CanonicalDocument>,
    ) -> Self {
        Self {
            program,
            table,
            index,
            direction,
            seams,
            context,
            warnings: Vec::new(),
            fhir,
            composition,
            written: Vec::new(),
            families: Vec::new(),
            facility_written: false,
            context_keys: Vec::new(),
            expected: Vec::new(),
            counters: BTreeMap::new(),
            chain: Vec::new(),
            references: Vec::new(),
            linked_to: None,
            frames: Vec::new(),
            created: Vec::new(),
            consumed: Vec::new(),
            pins: Vec::new(),
            fhir_pin: None,
            translations: BTreeMap::new(),
            subject: Vec::new(),
            intervals: Vec::new(),
            reads: Vec::new(),
            carried: core::cell::RefCell::default(),
        }
    }
}

/// Returns the archetype path of an openEHR target: its node's `aqlPath` with
/// the attribute tail appended.
///
/// The `aqlPath` carries the node ids and the names the template gives the
/// node, so the path holds no value of the composition.
fn openehr_path(target: &OpenehrTarget) -> String {
    let mut path = String::from(target.node().aql_path().as_str());
    for segment in &target.tail().segments {
        path.push('/');
        path.push_str(segment.attribute.as_str());
    }
    if path.is_empty() {
        path.push('/');
    }
    path
}

/// A value written at a composition attribute the FLAT builder sets from the
/// context vocabulary, beside the node it belongs to.
type Routed = (FlatId, RmValue);