fhirconnect 0.2.4

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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The walk of one expression over the element table, one step at a time.

use fhir_types::schema::FieldSchema;
use fhir_types::schema::Kind;
use fhir_types::schema::TypeSchema;
use fhir_types::schema::ValueKind;

use crate::tree::error::ResolveError;
use crate::tree::path::Step;

use crate::tree::element::Field;
use crate::tree::element::Location;
use crate::tree::element::Move;
use crate::tree::element::Table;
use crate::tree::element::Walk;

/// The primitive type codes `resolve()` accepts.
///
/// `resolve()` reads "a string that is a uri (or canonical or url)"
/// (<https://hl7.org/fhir/R4/fhirpath.html>, §Additional functions).
const REFERENTIAL: [&str; 3] = ["uri", "canonical", "url"];

/// The table entry a primitive's underscore sibling resolves against.
///
/// A primitive's `id` and `extension` live in the member named with a leading
/// underscore (<https://hl7.org/fhir/R4/json.html>), and both come from
/// `Element` itself (<https://hl7.org/fhir/R4/element.html>), which the table
/// carries as its own type.
const ELEMENT_TYPE: &str = "Element";

/// The element name of the extension list every element carries.
const EXTENSION_ELEMENT: &str = "extension";

/// The element name of a primitive's own value.
///
/// Every primitive type defines it beside `id` and `extension` (R4
/// `StructureDefinition-code`, `code.value`, "Primitive value for code"), and
/// the JSON representation carries it as the member itself
/// (<https://hl7.org/fhir/R4/json.html#primitive>). FHIRconnect reads a code
/// that way in a condition (`basics/Conditions.adoc` §not of).
const PRIMITIVE_VALUE: &str = "value";

impl<T: Table + ?Sized> Walk<'_, T> {
    /// Takes one step, answering whether the walk is finished.
    pub(super) fn take(&mut self, step: &Step, rest: &[Step]) -> Result<bool, ResolveError> {
        match step {
            Step::Element { name }
                if name == PRIMITIVE_VALUE && matches!(self.location, Location::Primitive(_)) =>
            {
                self.primitive_value(rest).map(|()| false)
            }
            Step::Element { name } => self.element(name).map(|()| false),
            Step::Type { name, .. } => self.type_filter(name, rest),
            Step::Extension { url } => self.extension(url).map(|()| false),
            Step::Resolve => self.resolve_step(rest).map(|()| true),
            Step::Ordinal(ordinal) => {
                self.moves.push(Move::Ordinal(*ordinal));
                Ok(false)
            }
            Step::Index(position) => self.index(*position).map(|()| false),
            Step::Predicate { expression } => {
                self.moves.push(Move::Predicate(expression.clone()));
                Ok(false)
            }
        }
    }

    /// Steps into the element `name`.
    fn element(&mut self, name: &str) -> Result<(), ResolveError> {
        match &self.location {
            Location::Complex(schema) => self.member(schema, name),
            Location::Primitive(_) | Location::Attribute => {
                self.enter_primitive_element(name)?;
                self.primitive_member(name)
            }
            Location::PrimitiveElement => self.primitive_member(name),
            Location::Choice(element) => Err(ResolveError::UnresolvedChoice {
                element: element.clone(),
            }),
            Location::Resource => Err(ResolveError::ResourceContent {
                element: self.owner.clone(),
            }),
            Location::Deferred => Err(ResolveError::NoChildren {
                element: self.owner.clone(),
                name: String::from(name),
            }),
        }
    }

    /// Steps onto the value of the primitive the walk stands on.
    ///
    /// The value is the primitive member itself, so the walk stays where it
    /// is and adds no move; nothing lies below it, so a further step is
    /// refused.
    fn primitive_value(&self, rest: &[Step]) -> Result<(), ResolveError> {
        match rest.first() {
            None => Ok(()),
            Some(next) => Err(ResolveError::NoChildren {
                element: format!("{}.{PRIMITIVE_VALUE}", self.owner),
                name: match next {
                    Step::Element { name } | Step::Type { name, .. } => name.clone(),
                    Step::Extension { .. } => String::from(EXTENSION_ELEMENT),
                    Step::Resolve => String::from("resolve()"),
                    Step::Ordinal(_) | Step::Index(_) | Step::Predicate { .. } => {
                        String::from(PRIMITIVE_VALUE)
                    }
                },
            }),
        }
    }

    /// Steps into a member of the complex type the walk stands in.
    fn member(&mut self, schema: &'static TypeSchema, name: &str) -> Result<(), ResolveError> {
        let (field, kind, key, types) =
            named(schema, name).ok_or_else(|| ResolveError::UnknownElement {
                owner: String::from(schema.path),
                name: String::from(name),
            })?;
        let rivals = if let Kind::Choice(_) = kind {
            Vec::new()
        } else {
            rivals(field, &key)
        };
        let resolved = Field {
            path: String::from(field.path),
            key,
            kind,
            min: field.min,
            max: field.max,
            types,
            target_profiles: field.target_profiles,
            rivals,
        };
        self.owner = String::from(field.path);
        if let Kind::Choice(_) = kind {
            self.location = Location::Choice(String::from(field.path));
            self.moves.push(Move::Choice {
                field: resolved,
                schema: field,
            });
            return Ok(());
        }
        self.location = self.landing(kind)?;
        self.moves.push(Move::Member(resolved));
        Ok(())
    }

    /// Steps into the `id` or `extension` of a primitive's sibling object.
    fn primitive_member(&mut self, name: &str) -> Result<(), ResolveError> {
        let field = self.element_member(name)?;
        let path = format!("{}.{}", self.owner, field.name);
        self.owner.clone_from(&path);
        self.location = self.landing(field.kind)?;
        self.moves.push(Move::Member(single(path, field)));
        Ok(())
    }

    /// The `Element` member `name`, from the table's own `Element` entry.
    fn element_member(&self, name: &str) -> Result<&'static FieldSchema, ResolveError> {
        let schema =
            self.table
                .type_named(ELEMENT_TYPE)
                .ok_or_else(|| ResolveError::UnknownElement {
                    owner: self.owner.clone(),
                    name: String::from(ELEMENT_TYPE),
                })?;
        schema
            .fields
            .iter()
            .find(|field| field.name == name)
            .ok_or_else(|| ResolveError::NoChildren {
                element: self.owner.clone(),
                name: String::from(name),
            })
    }

    /// Moves the last member onto the sibling that carries a primitive's `id`
    /// and `extension`.
    fn enter_primitive_element(&mut self, name: &str) -> Result<(), ResolveError> {
        let last = self
            .moves
            .last_mut()
            .ok_or_else(|| ResolveError::NoChildren {
                element: self.owner.clone(),
                name: String::from(name),
            })?;
        let Move::Member(field) = last else {
            return Err(ResolveError::NoChildren {
                element: self.owner.clone(),
                name: String::from(name),
            });
        };
        *field = field.under(format!("_{}", field.key));
        self.location = Location::PrimitiveElement;
        Ok(())
    }

    /// Applies `ofType()` or `as()`, answering whether the walk is finished.
    fn type_filter(&mut self, name: &str, rest: &[Step]) -> Result<bool, ResolveError> {
        match self.location.clone() {
            Location::Choice(element) => self.choose(&element, name).map(|()| false),
            Location::Complex(schema) => self.assert_complex(schema, name, rest),
            Location::Resource => self.assert_resource(name),
            Location::Primitive(_) | Location::Attribute => {
                self.assert_primitive(name).map(|()| false)
            }
            Location::PrimitiveElement | Location::Deferred => Err(ResolveError::TypeAssertion {
                element: self.owner.clone(),
                requested: String::from(name),
                actual: String::from("Element"),
            }),
        }
    }

    /// Fixes the alternative of the choice element the walk stands on.
    fn choose(&mut self, element: &str, name: &str) -> Result<(), ResolveError> {
        let Some(Move::Choice { field, schema }) = self.moves.last() else {
            return Err(ResolveError::UnresolvedChoice {
                element: String::from(element),
            });
        };
        let (suffix, kind) = schema
            .choices()
            .find(|form| form.suffix.eq_ignore_ascii_case(name))
            .map(|form| (form.suffix, form.kind))
            .ok_or_else(|| ResolveError::ChoiceType {
                element: String::from(element),
                requested: String::from(name),
                admitted: schema
                    .choices()
                    .map(|form| form.suffix)
                    .collect::<Vec<_>>()
                    .join(", "),
            })?;
        let types = alternative(field.types, suffix);
        let chosen = Field {
            path: field.path.clone(),
            key: format!("{}{suffix}", field.key),
            kind,
            min: field.min,
            max: field.max,
            types,
            target_profiles: field.target_profiles,
            rivals: rivals(schema, &format!("{}{suffix}", field.key)),
        };
        self.location = self.landing(kind)?;
        let last = self.moves.len().saturating_sub(1);
        if let Some(slot) = self.moves.get_mut(last) {
            *slot = Move::Member(chosen);
        }
        Ok(())
    }

    /// Applies a type filter to the complex type the walk stands in.
    fn assert_complex(
        &mut self,
        schema: &'static TypeSchema,
        name: &str,
        rest: &[Step],
    ) -> Result<bool, ResolveError> {
        if schema.name.eq_ignore_ascii_case(name) {
            return Ok(false);
        }
        // NOTE: only `resolve()` reaches a reference target
        // (<https://hl7.org/fhir/R4/fhirpath.html>), so a resource type named
        // on a `Reference` is read as that same deferred resolution.
        if schema.name == "Reference" && self.table.is_resource(name) {
            self.defer(Some(String::from(name)), rest);
            return Ok(true);
        }
        Err(ResolveError::TypeAssertion {
            element: self.owner.clone(),
            requested: String::from(name),
            actual: String::from(schema.name),
        })
    }

    /// Applies a type filter to a resource-typed element.
    fn assert_resource(&mut self, name: &str) -> Result<bool, ResolveError> {
        let schema = self
            .table
            .type_named(name)
            .filter(|_| self.table.is_resource(name))
            .ok_or_else(|| ResolveError::TypeAssertion {
                element: self.owner.clone(),
                requested: String::from(name),
                actual: String::from("Resource"),
            })?;
        self.location = Location::Complex(schema);
        Ok(false)
    }

    /// Applies a type filter to a primitive element.
    fn assert_primitive(&mut self, name: &str) -> Result<(), ResolveError> {
        let Some(Move::Member(field)) = self.moves.last() else {
            return Err(ResolveError::TypeAssertion {
                element: self.owner.clone(),
                requested: String::from(name),
                actual: String::from("Element"),
            });
        };
        if field
            .types
            .iter()
            .any(|code| code.eq_ignore_ascii_case(name))
        {
            return Ok(());
        }
        Err(ResolveError::TypeAssertion {
            element: field.path.clone(),
            requested: String::from(name),
            actual: field.types.join(", "),
        })
    }

    /// Steps into the extension with `url`.
    fn extension(&mut self, url: &str) -> Result<(), ResolveError> {
        if matches!(self.location, Location::Primitive(_) | Location::Attribute) {
            self.enter_primitive_element(EXTENSION_ELEMENT)?;
        }
        let (field, path) = match &self.location {
            Location::Complex(schema) => {
                let (field, ..) = named(schema, EXTENSION_ELEMENT).ok_or_else(|| {
                    ResolveError::UnknownElement {
                        owner: String::from(schema.path),
                        name: String::from(EXTENSION_ELEMENT),
                    }
                })?;
                (field, String::from(field.path))
            }
            Location::PrimitiveElement => {
                let field = self.element_member(EXTENSION_ELEMENT)?;
                let path = format!("{}.{EXTENSION_ELEMENT}", self.owner);
                (field, path)
            }
            Location::Choice(choice) => {
                return Err(ResolveError::UnresolvedChoice {
                    element: choice.clone(),
                });
            }
            Location::Resource => {
                return Err(ResolveError::ResourceContent {
                    element: self.owner.clone(),
                });
            }
            Location::Primitive(_) | Location::Attribute | Location::Deferred => {
                return Err(ResolveError::NoChildren {
                    element: self.owner.clone(),
                    name: String::from(EXTENSION_ELEMENT),
                });
            }
        };
        self.owner.clone_from(&path);
        self.location = self.landing(field.kind)?;
        self.moves.push(Move::Extension {
            field: single(path, field),
            url: String::from(url),
        });
        Ok(())
    }

    /// Hands the reference the walk stands on to the engine.
    fn resolve_step(&mut self, rest: &[Step]) -> Result<(), ResolveError> {
        let referential = match &self.location {
            Location::Complex(schema) => schema.name == "Reference",
            Location::Primitive(_) => match self.moves.last() {
                Some(Move::Member(field)) => {
                    field.types.iter().any(|code| REFERENTIAL.contains(code))
                }
                _ => false,
            },
            Location::Attribute
            | Location::PrimitiveElement
            | Location::Choice(_)
            | Location::Resource
            | Location::Deferred => false,
        };
        if !referential {
            return Err(ResolveError::NotAReference {
                element: self.owner.clone(),
            });
        }
        let (expected, rest) = match rest.split_first() {
            Some((Step::Type { name, .. }, tail)) if self.table.is_resource(name) => {
                (Some(name.clone()), tail)
            }
            _ => (None, rest),
        };
        self.defer(expected, rest);
        Ok(())
    }

    /// Records the deferred resolution and what remains of the path.
    fn defer(&mut self, expected: Option<String>, rest: &[Step]) {
        self.location = Location::Deferred;
        self.moves.push(Move::Resolve {
            expected,
            continuation: rest.to_vec(),
        });
    }

    /// Records an index filter, which needs a repeating element.
    fn index(&mut self, position: usize) -> Result<(), ResolveError> {
        let repeats = match self.moves.last() {
            Some(Move::Member(field) | Move::Choice { field, .. }) => field.repeats(),
            Some(Move::Extension { .. }) => true,
            _ => false,
        };
        if !repeats {
            return Err(ResolveError::NotRepeating {
                element: self.owner.clone(),
                index: position,
            });
        }
        self.moves.push(Move::Index(position));
        Ok(())
    }

    /// Where a step lands, given the kind of the element it took.
    fn landing(&self, kind: Kind) -> Result<Location, ResolveError> {
        Ok(match kind {
            Kind::Attribute => Location::Attribute,
            Kind::Primitive(value) => Location::Primitive(value),
            Kind::Xhtml => Location::Primitive(ValueKind::Text),
            Kind::Resource => Location::Resource,
            Kind::Choice(_) => Location::Choice(self.owner.clone()),
            Kind::Complex(name) => {
                let schema =
                    self.table
                        .type_named(name)
                        .ok_or_else(|| ResolveError::UnknownElement {
                            owner: self.owner.clone(),
                            name: String::from(name),
                        })?;
                Location::Complex(schema)
            }
        })
    }
}

/// What [`named`] selects: the table entry, the kind and JSON key it lands on,
/// and the type codes the landing element admits.
type Named = (&'static FieldSchema, Kind, String, &'static [&'static str]);

/// The element `name` selects in `schema`, with the kind, the JSON key and
/// the type codes it lands on.
///
/// A name is an element name, or a choice element's name with the suffix of
/// one alternative, which is how the JSON representation spells a resolved
/// choice (<https://hl7.org/fhir/R4/json.html>).
fn named(schema: &'static TypeSchema, name: &str) -> Option<Named> {
    if let Some(field) = schema.fields.iter().find(|field| field.name == name) {
        return Some((field, field.kind, String::from(name), field.types));
    }
    let member = schema.member(name).filter(|member| !member.sibling)?;
    let field = member.field;
    let types = match member.choice {
        Some(code) => alternative(field.types, code),
        None => field.types,
    };
    Some((field, member.kind, String::from(name), types))
}

/// The type codes of the choice alternative `suffix` names, out of the
/// choice's `types`.
fn alternative(types: &'static [&'static str], suffix: &str) -> &'static [&'static str] {
    // NOTE: a chosen alternative has the one type its suffix names
    // (<https://hl7.org/fhir/R4/formats.html#choice>), so the field keeps that code alone.
    types
        .iter()
        .position(|code| code.eq_ignore_ascii_case(suffix))
        .and_then(|at| types.get(at))
        .map_or(types, core::slice::from_ref)
}

/// The JSON keys of every alternative of the choice element `field` other
/// than `chosen`, none when `field` is no choice.
///
/// A choice element is written under one suffixed key at a time
/// (<https://hl7.org/fhir/R4/formats.html#choice>).
fn rivals(field: &'static FieldSchema, chosen: &str) -> Vec<String> {
    field
        .choices()
        .map(|form| format!("{}{}", field.name, form.suffix))
        .filter(|key| key != chosen)
        .collect()
}

/// The element `field` defines at `path`, written under its own name, which
/// is no alternative of a choice.
fn single(path: String, field: &'static FieldSchema) -> Field {
    Field {
        path,
        key: String::from(field.name),
        kind: field.kind,
        min: field.min,
        max: field.max,
        types: field.types,
        target_profiles: field.target_profiles,
        rivals: Vec::new(),
    }
}