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

//! The `with.fhir` expression: its parts, its parser and its writability.
//!
//! The grammar is the one FHIRconnect writes. It is FHIRPath navigation plus
//! the two head forms the specification adds, `$resource` and `$fhirRoot`, and
//! the `^` parent operator it borrows from JSONPath Plus
//! (<https://sevkohler.github.io/FHIRconnect-spec/build/site/FHIRconnect/v1.0.0/basics/path_operators.html>).
//! The function forms are the ones FHIR profiles onto FHIRPath: `ofType()` and
//! the `as` operation on a polymorphic element, `extension(url)` and
//! `resolve()` (<https://hl7.org/fhir/R4/fhirpath.html>).
//!
//! ```text
//! path      := head ( "." step )*
//! head      := "$resource" | "$fhirRoot" | "^"+ | step
//! step      := function | name ( "[" digits "]" )?
//! function  := "ofType(" type ")" | "as(" type ")" | "extension(" string ")"
//!            | "resolve()" | "where(" expression ")" | "first()" | "last()"
//! ```
//!
//! Every expression is classified when it is parsed. A step that selects among
//! the values already in a document, rather than naming one element, makes the
//! whole expression [`Writability::ReadOnly`], and a mapping whose write side
//! names such an expression is refused when it is loaded.

use core::fmt;
use core::num::NonZeroUsize;
use core::str::FromStr;

use crate::tree::error::AnchorError;
use crate::tree::error::ParseError;

/// What a path expression starts from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Head {
    /// `$resource`, the root of the resource the mapping file names.
    Resource,
    /// `$fhirRoot`, the anchor the enclosing mapping step left.
    FhirRoot,
    /// A run of `^`, that many parents above the anchor.
    Parent(NonZeroUsize),
    /// No head variable, so the first step is a child of the anchor.
    Anchor,
}

impl fmt::Display for Head {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Resource => f.write_str("$resource"),
            Self::FhirRoot => f.write_str("$fhirRoot"),
            Self::Parent(hops) => {
                for _ in 0..hops.get() {
                    f.write_str("^")?;
                }
                Ok(())
            }
            Self::Anchor => Ok(()),
        }
    }
}

/// Which spelling a type filter used.
///
/// FHIR gives a polymorphic element two spellings, the `as` operation and the
/// `ofType()` function (<https://hl7.org/fhir/R4/fhirpath.html>, §Polymorphism
/// in FHIR and §Additional functions). They select the same alternative, and
/// this model keeps the spelling so a diagnostic renders the expression as it
/// was written.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TypeForm {
    /// `ofType(Period)`.
    OfType,
    /// `as(Period)`.
    As,
}

/// Which end of a repeating element an ordinal filter takes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ordinal {
    /// `first()`.
    First,
    /// `last()`.
    Last,
}

impl fmt::Display for Ordinal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::First => f.write_str("first()"),
            Self::Last => f.write_str("last()"),
        }
    }
}

/// One step of a path expression.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Step {
    /// An element name, or a choice element's suffixed name (`onsetPeriod`).
    Element {
        /// The name as written.
        name: String,
    },
    /// `ofType(T)` or `as(T)`.
    Type {
        /// The type the filter names, without any namespace qualifier.
        name: String,
        /// Which spelling was written.
        form: TypeForm,
    },
    /// `extension(url)`, the shortcut for the extension with that url.
    Extension {
        /// The url the literal carried.
        url: String,
    },
    /// `resolve()`, which hands the reference to the engine.
    Resolve,
    /// `first()` or `last()`.
    Ordinal(Ordinal),
    /// `[n]`, one position of a repeating element.
    Index(usize),
    /// `where(expression)`, a FHIRPath predicate.
    Predicate {
        /// The predicate as written, without the parentheses.
        expression: String,
    },
}

impl fmt::Display for Step {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Element { name } => f.write_str(name),
            Self::Type {
                name,
                form: TypeForm::OfType,
            } => write!(f, "ofType({name})"),
            Self::Type {
                name,
                form: TypeForm::As,
            } => write!(f, "as({name})"),
            Self::Extension { url } => write!(f, "extension('{url}')"),
            Self::Resolve => f.write_str("resolve()"),
            Self::Ordinal(ordinal) => write!(f, "{ordinal}"),
            Self::Index(index) => write!(f, "[{index}]"),
            Self::Predicate { expression } => write!(f, "where({expression})"),
        }
    }
}

impl Step {
    /// Why this step cannot be written through, `None` when it can be.
    const fn read_only(&self) -> Option<&'static str> {
        match self {
            Self::Predicate { .. } => {
                Some("is a predicate over the values a document already holds")
            }
            Self::Ordinal(_) => Some("picks one of the values a document already holds"),
            Self::Index(_) => Some("picks one position of the values a document already holds"),
            Self::Resolve => Some("names a resource the engine resolves, not an element to set"),
            Self::Element { .. } | Self::Type { .. } | Self::Extension { .. } => None,
        }
    }
}

/// Whether a path expression can be written through.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Writability {
    /// Every step names or creates one element.
    Writable,
    /// A step selects among the values a document already holds.
    ReadOnly {
        /// The step that makes it read-only, as written.
        step: String,
        /// Why that step cannot be written through.
        reason: &'static str,
    },
}

/// A parsed `with.fhir` expression.
///
/// # Examples
///
/// ```
/// use fhirconnect::tree::path::{FhirPath, Head, Writability};
///
/// let path: FhirPath = "$resource.onset.ofType(Period).start".parse()?;
/// assert_eq!(path.head(), Head::Resource);
/// assert_eq!(path.steps().len(), 3);
/// assert_eq!(path.writability(), &Writability::Writable);
///
/// let filtered: FhirPath = "$resource.category.first().coding".parse()?;
/// assert!(matches!(filtered.writability(), Writability::ReadOnly { .. }));
/// # Ok::<(), fhirconnect::tree::error::ParseError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FhirPath {
    text: String,
    head: Head,
    steps: Vec<Step>,
    writability: Writability,
}

impl FhirPath {
    /// Returns the expression as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Returns what the expression starts from.
    #[must_use]
    pub const fn head(&self) -> Head {
        self.head
    }

    /// Returns the steps, in path order.
    #[must_use]
    pub fn steps(&self) -> &[Step] {
        &self.steps
    }

    /// Returns whether the expression can be written through.
    #[must_use]
    pub const fn writability(&self) -> &Writability {
        &self.writability
    }

    /// Builds the `$resource`-rooted expression this one names under `anchor`.
    ///
    /// `$fhirRoot` and a bare first step name the anchor itself, and each `^`
    /// names one parent above it
    /// (<https://sevkohler.github.io/FHIRconnect-spec/build/site/FHIRconnect/v1.0.0/basics/path_operators.html>).
    /// A `$resource`-rooted expression is already absolute and comes back
    /// unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`AnchorError::RelativeAnchor`] when `anchor` is itself not
    /// rooted at `$resource`, and [`AnchorError::AboveResource`] when the run
    /// of `^` passes the resource root.
    pub fn anchored(&self, anchor: &Self) -> Result<Self, AnchorError> {
        if self.head == Head::Resource {
            return Ok(self.clone());
        }
        if anchor.head != Head::Resource {
            return Err(AnchorError::RelativeAnchor {
                anchor: anchor.text.clone(),
            });
        }
        let hops = match self.head {
            Head::Parent(hops) => hops.get(),
            Head::Resource | Head::FhirRoot | Head::Anchor => 0,
        };
        let kept =
            anchor
                .steps
                .len()
                .checked_sub(hops)
                .ok_or_else(|| AnchorError::AboveResource {
                    expression: self.text.clone(),
                    anchor: anchor.text.clone(),
                    hops,
                })?;
        let mut steps: Vec<Step> = anchor.steps.iter().take(kept).cloned().collect();
        steps.extend(self.steps.iter().cloned());
        Ok(Self::assembled(Head::Resource, steps))
    }

    /// Returns this `$resource`-rooted expression with `root` in place of the
    /// resource root, `None` for an expression rooted elsewhere.
    #[must_use]
    pub fn rooted_at(&self, root: &Self) -> Option<Self> {
        if self.head != Head::Resource || root.head != Head::Resource {
            return None;
        }
        let mut steps = root.steps.clone();
        steps.extend(self.steps.iter().cloned());
        Some(Self::assembled(Head::Resource, steps))
    }

    /// Builds the expression this one names under a stack of anchors.
    ///
    /// `anchors` runs innermost first. A run of `^` that exhausts one anchor
    /// carries on in the next, which is what the worked `^^` example needs:
    /// its two `^` start at the root of a resource a `reference` mapping
    /// initializes and reach an element of the enclosing resource
    /// (<https://sevkohler.github.io/FHIRconnect-spec/build/site/FHIRconnect/v1.0.0/basics/path_operators.html>,
    /// §Recurrence and parent elements). Crossing from one anchor to the next
    /// costs no `^`, because the boundary is not a step of either path. The
    /// index that comes back is the anchor the expression bound in.
    ///
    /// # Errors
    ///
    /// Returns [`AnchorError::RelativeAnchor`] when an anchor it reaches is
    /// itself not rooted at `$resource`, and [`AnchorError::AboveResource`]
    /// when the run of `^` passes the root of the outermost anchor.
    pub fn anchored_in(&self, anchors: &[&Self]) -> Result<(Self, usize), AnchorError> {
        if self.head == Head::Resource {
            return Ok((self.clone(), 0));
        }
        let requested = match self.head {
            Head::Parent(count) => count.get(),
            Head::Resource | Head::FhirRoot | Head::Anchor => 0,
        };
        let mut hops = requested;
        for (index, anchor) in anchors.iter().enumerate() {
            if anchor.head != Head::Resource {
                return Err(AnchorError::RelativeAnchor {
                    anchor: anchor.text.clone(),
                });
            }
            if let Some(kept) = anchor.steps.len().checked_sub(hops) {
                let mut steps: Vec<Step> = anchor.steps.iter().take(kept).cloned().collect();
                steps.extend(self.steps.iter().cloned());
                return Ok((Self::assembled(Head::Resource, steps), index));
            }
            hops = hops.saturating_sub(anchor.steps.len());
        }
        let outermost = anchors
            .last()
            .map_or_else(String::new, |anchor| anchor.text.clone());
        Err(AnchorError::AboveResource {
            expression: self.text.clone(),
            anchor: outermost,
            hops: requested,
        })
    }

    /// Assembles a path from a head and its steps, rendering and classifying
    /// it.
    fn assembled(head: Head, steps: Vec<Step>) -> Self {
        let writability = classify(&steps);
        let text = render(head, &steps);
        Self {
            text,
            head,
            steps,
            writability,
        }
    }
}

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

impl FromStr for FhirPath {
    type Err = ParseError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let mut scanner = Scanner {
            text,
            at: 0usize,
            steps: Vec::new(),
        };
        let head = scanner.head()?;
        scanner.tail(head)?;
        let steps = scanner.steps;
        let writability = classify(&steps);
        Ok(Self {
            text: String::from(text),
            head,
            steps,
            writability,
        })
    }
}

/// Renders a head and its steps as an expression.
fn render(head: Head, steps: &[Step]) -> String {
    let mut text = head.to_string();
    for step in steps {
        if matches!(step, Step::Index(_)) {
            text.push_str(&step.to_string());
            continue;
        }
        if !text.is_empty() {
            text.push('.');
        }
        text.push_str(&step.to_string());
    }
    text
}

/// Classifies a step sequence as writable or read-only.
fn classify(steps: &[Step]) -> Writability {
    for step in steps {
        if let Some(reason) = step.read_only() {
            return Writability::ReadOnly {
                step: step.to_string(),
                reason,
            };
        }
    }
    Writability::Writable
}

/// The parser state: the expression, the byte offset reached and the steps
/// taken so far.
struct Scanner<'a> {
    text: &'a str,
    at: usize,
    steps: Vec<Step>,
}

impl<'a> Scanner<'a> {
    /// The text from the current offset on.
    fn rest(&self) -> &'a str {
        self.text.get(self.at..).unwrap_or_default()
    }

    /// The next character, without consuming it.
    fn peek(&self) -> Option<char> {
        self.rest().chars().next()
    }

    /// Consumes and returns the next character.
    fn bump(&mut self) -> Option<char> {
        let next = self.peek()?;
        self.at = self.at.saturating_add(next.len_utf8());
        Some(next)
    }

    /// Consumes `wanted` when it stands next.
    fn eat(&mut self, wanted: char) -> bool {
        if self.peek() == Some(wanted) {
            self.at = self.at.saturating_add(wanted.len_utf8());
            return true;
        }
        false
    }

    /// Consumes `wanted` when it stands next, refusing anything else.
    fn expect(&mut self, wanted: char, expected: &'static str) -> Result<(), ParseError> {
        if self.eat(wanted) {
            return Ok(());
        }
        Err(self.expected(expected))
    }

    /// The refusal for whatever stands at the current offset.
    fn expected(&self, expected: &'static str) -> ParseError {
        let found = self
            .peek()
            .map_or_else(|| String::from("<end of input>"), String::from);
        ParseError::Expected {
            expected,
            found,
            at: self.at,
        }
    }

    /// Consumes the run of characters `accept` admits.
    fn take_while(&mut self, accept: impl Fn(char) -> bool) -> &'a str {
        let start = self.at;
        while self.peek().is_some_and(&accept) {
            let _consumed = self.bump();
        }
        self.text.get(start..self.at).unwrap_or_default()
    }

    /// Reads the head of the expression.
    fn head(&mut self) -> Result<Head, ParseError> {
        if self.text.is_empty() {
            return Err(ParseError::Empty);
        }
        if self.peek() == Some('$') {
            return self.variable();
        }
        if self.peek() == Some('^') {
            let start = self.at;
            let carets = self.take_while(|c| c == '^').chars().count();
            let hops = NonZeroUsize::new(carets).ok_or(ParseError::Expected {
                expected: "a `^` parent operator",
                found: String::from("^"),
                at: start,
            })?;
            return Ok(Head::Parent(hops));
        }
        self.step()?;
        Ok(Head::Anchor)
    }

    /// Reads a `$name` head.
    fn variable(&mut self) -> Result<Head, ParseError> {
        let start = self.at;
        let _dollar = self.bump();
        let name = self.take_while(char::is_alphanumeric);
        match name {
            "resource" => Ok(Head::Resource),
            "fhirRoot" => Ok(Head::FhirRoot),
            _ => Err(ParseError::UnknownVariable {
                name: String::from(name),
                at: start,
            }),
        }
    }

    /// Reads every step after the head.
    fn tail(&mut self, head: Head) -> Result<(), ParseError> {
        if head != Head::Anchor && self.peek().is_some() {
            self.expect('.', "`.` or the end of the expression")?;
            self.step()?;
        }
        while self.peek().is_some() {
            self.expect('.', "`.` or the end of the expression")?;
            self.step()?;
        }
        Ok(())
    }

    /// Reads one step, plus the index filter that may follow it.
    fn step(&mut self) -> Result<(), ParseError> {
        let start = self.at;
        let name = self.take_while(|c| c.is_alphanumeric() || c == '_');
        if name.is_empty() {
            return Err(self.expected("an element name or a path function"));
        }
        if self.eat('(') {
            let step = self.call(name, start)?;
            self.steps.push(step);
            return Ok(());
        }
        self.steps.push(Step::Element {
            name: String::from(name),
        });
        self.index(start)
    }

    /// Reads the `[n]` filter that may follow an element name.
    fn index(&mut self, start: usize) -> Result<(), ParseError> {
        if !self.eat('[') {
            return Ok(());
        }
        let digits = self.take_while(|c| c.is_ascii_digit());
        self.expect(']', "`]`")?;
        let index = digits.parse().map_err(|_error| ParseError::Index {
            text: String::from(digits),
            at: start,
        })?;
        self.steps.push(Step::Index(index));
        Ok(())
    }

    /// Reads a function call whose `(` is already consumed.
    fn call(&mut self, name: &str, start: usize) -> Result<Step, ParseError> {
        match name {
            "ofType" => self.type_filter(TypeForm::OfType),
            "as" => self.type_filter(TypeForm::As),
            "extension" => {
                let url = self.string()?;
                self.expect(')', "`)`")?;
                Ok(Step::Extension { url })
            }
            "resolve" => {
                self.expect(')', "`)`")?;
                Ok(Step::Resolve)
            }
            "first" => {
                self.expect(')', "`)`")?;
                Ok(Step::Ordinal(Ordinal::First))
            }
            "last" => {
                self.expect(')', "`)`")?;
                Ok(Step::Ordinal(Ordinal::Last))
            }
            "where" => {
                let expression = self.balanced(name, start)?;
                Ok(Step::Predicate { expression })
            }
            _ => Err(ParseError::UnknownFunction {
                name: String::from(name),
                at: start,
            }),
        }
    }

    /// Reads the type specifier of `ofType()` or `as()`.
    ///
    /// FHIRPath writes a type specifier as an identifier that may carry a
    /// namespace (`FHIR.Period`), and FHIR admits only concrete core types
    /// there (<https://hl7.org/fhir/R4/fhirpath.html>, §Additional functions).
    fn type_filter(&mut self, form: TypeForm) -> Result<Step, ParseError> {
        let mut name;
        loop {
            let segment = self.take_while(|c| c.is_alphanumeric() || c == '_');
            if segment.is_empty() {
                return Err(self.expected("a type name"));
            }
            name = String::from(segment);
            if !self.eat('.') {
                break;
            }
        }
        self.expect(')', "`)`")?;
        Ok(Step::Type { name, form })
    }

    /// Reads a FHIRPath string literal.
    fn string(&mut self) -> Result<String, ParseError> {
        let start = self.at;
        if !self.eat('\'') {
            return Err(self.expected("a string literal in single quotes"));
        }
        let mut text = String::new();
        loop {
            let Some(next) = self.bump() else {
                return Err(ParseError::UnterminatedString { at: start });
            };
            match next {
                '\'' => return Ok(text),
                '\\' => text.push(self.escape()?),
                other => text.push(other),
            }
        }
    }

    /// Reads the character after a backslash in a string literal.
    fn escape(&mut self) -> Result<char, ParseError> {
        let at = self.at.saturating_sub(1);
        let Some(next) = self.bump() else {
            return Err(ParseError::UnterminatedString { at });
        };
        match next {
            '\'' | '"' | '`' | '\\' | '/' => Ok(next),
            'r' => Ok('\r'),
            'n' => Ok('\n'),
            't' => Ok('\t'),
            'f' => Ok('\u{c}'),
            other => Err(ParseError::InvalidEscape { escape: other, at }),
        }
    }

    /// Reads the text up to the `)` that balances the already-consumed `(`.
    fn balanced(&mut self, name: &str, start: usize) -> Result<String, ParseError> {
        let opened = self.at;
        let mut depth = 1usize;
        loop {
            let Some(next) = self.bump() else {
                return Err(ParseError::UnterminatedCall {
                    name: String::from(name),
                    at: start,
                });
            };
            match next {
                '(' => depth = depth.saturating_add(1),
                ')' => {
                    depth = depth.saturating_sub(1);
                    if depth == 0 {
                        let end = self.at.saturating_sub(1);
                        let text = self.text.get(opened..end).unwrap_or_default();
                        return Ok(String::from(text));
                    }
                }
                '\'' => {
                    self.at = self.at.saturating_sub(1);
                    let _literal = self.string()?;
                }
                _ => {}
            }
        }
    }
}