fhirbolt-shared 0.4.0

Internal shared library of the fhirbolt project
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
//! Module to track paths in the FHIR data model.

use std::mem;

use crate::{
    element_map::{self, ElementMap, ElementSet},
    type_hints::{self, TypeHints},
    FhirRelease, FhirReleases,
};

const RESOURCE_COMMON_PRIMITIVE_FIELDS: &[&str] = &["implicitRules", "language"];
const COMMON_SEQUENCE_FIELDS: &[&str] = &["extension", "modifierExtension"];

fn type_hints(fhir_release: FhirRelease) -> &'static TypeHints {
    match fhir_release {
        FhirReleases::R4 => &type_hints::r4::TYPE_HINTS,
        FhirReleases::R4B => &type_hints::r4b::TYPE_HINTS,
        FhirReleases::R5 => &type_hints::r5::TYPE_HINTS,
        _ => panic!("invalid FHIR release"),
    }
}

fn element_map(fhir_release: FhirRelease) -> &'static ElementMap {
    match fhir_release {
        FhirReleases::R4 => &element_map::r4::ELEMENT_MAP,
        FhirReleases::R4B => &element_map::r4b::ELEMENT_MAP,
        FhirReleases::R5 => &element_map::r5::ELEMENT_MAP,
        _ => panic!("invalid FHIR release"),
    }
}

trait FirstLetterUppercase {
    fn is_first_letter_uppercase(&self) -> bool;
}

impl FirstLetterUppercase for &str {
    fn is_first_letter_uppercase(&self) -> bool {
        self.chars()
            .next()
            .map(|c| c.is_uppercase())
            .unwrap_or(false)
    }
}

/// ElementPath is aware of the FHIR data model and tracks its position in the tree.
///
/// It can be used to query type information of its current path.
#[derive(Debug, Clone)]
pub struct ElementPath {
    fhir_release: FhirRelease,
    type_stack: TypeStack,
}

impl ElementPath {
    #[inline]
    pub fn new(fhir_release: FhirRelease) -> ElementPath {
        ElementPath {
            fhir_release,
            type_stack: TypeStack::new(fhir_release),
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.type_stack.is_empty()
    }

    #[inline]
    pub fn current_element(&self) -> Option<&str> {
        self.current_type_path().last_split()
    }

    #[inline]
    pub fn current_element_is_resource(&self) -> bool {
        self.resolve_current_type() == Some("Resource")
    }

    #[inline]
    pub fn current_element_is_extension(&self) -> bool {
        matches!(
            self.current_type_path().last_split(),
            Some("extension") | Some("modifierExtension")
        )
    }

    #[inline]
    pub fn current_element_is_primitive(&self) -> bool {
        if self.in_resource() {
            return false;
        }

        let current_type_path = self.current_type_path();

        let is_id = current_type_path.last_split() == Some("id");
        if is_id {
            return true;
        }

        if self.parent_element_is_resource()
            && current_type_path
                .last_split()
                .map(|s| RESOURCE_COMMON_PRIMITIVE_FIELDS.contains(&s))
                .unwrap_or(false)
        {
            return true;
        }

        type_hints(self.fhir_release)
            .all_primitives_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_sequence(&self) -> bool {
        let current_type_path = self.current_type_path();

        let is_common_sequence_field = current_type_path
            .last_split()
            .map(|p| COMMON_SEQUENCE_FIELDS.contains(&p))
            .unwrap_or(false);

        if is_common_sequence_field {
            return true;
        }

        let is_contained =
            current_type_path.len() == 2 && current_type_path.last_split() == Some("contained");

        if is_contained {
            return true;
        }

        type_hints(self.fhir_release)
            .array_paths
            .contains(&current_type_path.path)
    }

    #[inline]
    pub fn current_element_is_boolean(&self) -> bool {
        type_hints(self.fhir_release)
            .boolean_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_integer(&self) -> bool {
        type_hints(self.fhir_release)
            .integer_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_integer64(&self) -> bool {
        type_hints(self.fhir_release)
            .integer64_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_unsigned_integer(&self) -> bool {
        type_hints(self.fhir_release)
            .unsigned_integer_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_positive_integer(&self) -> bool {
        type_hints(self.fhir_release)
            .positive_integer_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn current_element_is_decimal(&self) -> bool {
        type_hints(self.fhir_release)
            .decimal_paths
            .contains(&self.current_type_path().path)
    }

    #[inline]
    pub fn parent_element_is_resource(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            path.is_first_letter_uppercase() && !path.contains('.')
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_boolean(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release).boolean_paths.contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_integer(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release).integer_paths.contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_integer64(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release).integer64_paths.contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_unsigned_integer(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release)
                .unsigned_integer_paths
                .contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_positive_integer(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release)
                .positive_integer_paths
                .contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn parent_element_is_decimal(&self) -> bool {
        if let Some(path) = self.current_type_path().parent() {
            type_hints(self.fhir_release).decimal_paths.contains(path)
        } else {
            false
        }
    }

    #[inline]
    pub fn push(&mut self, element: &str) {
        match self.resolve_current_type() {
            Some("Resource") => self
                .type_stack
                .push(TypePath::new(element, self.fhir_release)),
            Some(ty) => {
                let mut type_path = TypePath::new(ty, self.fhir_release);
                type_path.push(element);
                self.type_stack.push(type_path);
            }
            None => self.type_stack.last_mut().push(element),
        }
    }

    #[inline]
    pub fn pop(&mut self) {
        self.type_stack.last_mut().pop();

        if self.type_stack.len() > 1
            && self.type_stack.last().len() <= 1
            && !self.in_contained_resource()
        {
            self.type_stack.pop();
        }
    }

    #[inline]
    pub fn children(&self) -> Option<&'static ElementSet> {
        let mut type_path = self.current_type_path().path.as_str();

        if let Some(current_type) = self.resolve_current_type() {
            if current_type != "Resource" {
                type_path = current_type;
            }
        } else if let Some(content_reference) = type_hints(self.fhir_release)
            .content_reference_paths
            .get(type_path)
        {
            type_path = content_reference;
        }

        element_map(self.fhir_release).get(type_path).copied()
    }

    #[inline]
    pub fn position_of_child(&self, child: &str) -> usize {
        if child == "resourceType"
            // on R4 ExampleScenario.instance contains a field named "resourceType"
            && !self.current_type_path().path.starts_with("ExampleScenario.instance")
            // on R5 Consent.provision contains a field named "resourceType"
            && !self.current_type_path().path.starts_with("Consent.provision")
            // on R5 Subscription.filterBy contains a field named "resourceType"
            && !self.current_type_path().path.starts_with("Subscription.filterBy")
        {
            0
        } else {
            self.children()
                .and_then(|set| set.get_index(child))
                .map(|i| i + 1)
                // move unknown to the end
                .unwrap_or(usize::MAX)
        }
    }

    fn current_type_path(&self) -> &TypePath {
        self.type_stack.last()
    }

    fn resolve_current_type(&self) -> Option<&str> {
        if self.current_element_is_extension() {
            return Some("Extension");
        }

        let current_type_path = self.current_type_path();

        if current_type_path.len() == 2 {
            match current_type_path.last_split() {
                Some("meta") => return Some("Meta"),
                Some("text") => return Some("Narrative"),
                Some("contained") => return Some("Resource"),
                _ => (),
            }
        }

        type_hints(self.fhir_release)
            .type_paths
            .get(&current_type_path.path)
            .copied()
    }

    fn in_resource(&self) -> bool {
        let current_type_path = self.current_type_path();

        current_type_path.len() == 1 && current_type_path.path.as_str().is_first_letter_uppercase()
    }

    fn in_contained_resource(&self) -> bool {
        if !self.in_resource() {
            return false;
        }

        let previous_type_path = if let Some(previous) = self.type_stack.second_last() {
            previous
        } else {
            return false;
        };

        let in_contained_field = previous_type_path.last_split() == Some("contained");

        if in_contained_field {
            return true;
        }

        type_hints(self.fhir_release)
            .type_paths
            .get(&previous_type_path.path)
            == Some(&"Resource")
    }
}

#[derive(Debug, Clone)]
struct TypeStack {
    root: TypePath,
    stack: Vec<TypePath>,
}

impl TypeStack {
    fn new(fhir_release: FhirRelease) -> TypeStack {
        TypeStack {
            root: TypePath::empty(fhir_release),
            stack: vec![],
        }
    }

    fn push(&mut self, value: TypePath) {
        self.stack.push(value)
    }

    fn pop(&mut self) {
        self.stack.pop();
    }

    fn is_empty(&self) -> bool {
        self.stack.is_empty() && self.root.is_empty()
    }

    fn len(&self) -> usize {
        self.stack.len() + 1
    }

    fn last(&self) -> &TypePath {
        if let Some(last) = self.stack.last() {
            last
        } else {
            &self.root
        }
    }

    fn last_mut(&mut self) -> &mut TypePath {
        if let Some(last) = self.stack.last_mut() {
            last
        } else {
            &mut self.root
        }
    }

    fn second_last(&self) -> Option<&TypePath> {
        match self.stack.as_slice() {
            [_] => Some(&self.root),
            [.., second_last, _] => Some(second_last),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
struct TypePath {
    fhir_release: FhirRelease,
    path: String,
    content_reference_replacement_stack: Vec<ContentReferenceReplacement>,
}

#[derive(Debug, Clone)]
struct ContentReferenceReplacement {
    content_reference: &'static str,
    replaced: String,
}

impl TypePath {
    fn new(typ_name: &str, fhir_release: FhirRelease) -> TypePath {
        TypePath {
            fhir_release,
            path: typ_name.to_string(),
            content_reference_replacement_stack: vec![],
        }
    }

    fn empty(fhir_release: FhirRelease) -> TypePath {
        TypePath {
            fhir_release,
            path: String::new(),
            content_reference_replacement_stack: vec![],
        }
    }

    fn parent(&self) -> Option<&str> {
        self.path.rsplit_once('.').map(|s| s.0)
    }

    fn last_split(&self) -> Option<&str> {
        self.path.rsplit_once('.').map(|s| s.1)
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn len(&self) -> usize {
        if self.path.is_empty() {
            0
        } else {
            1 + self.path.chars().filter(|c| *c == '.').count()
        }
    }

    fn push(&mut self, element: &str) {
        if let Some(content_reference) = type_hints(self.fhir_release)
            .content_reference_paths
            .get(&self.path)
        {
            self.content_reference_replacement_stack
                .push(ContentReferenceReplacement {
                    content_reference,
                    replaced: mem::replace(&mut self.path, content_reference.to_string()),
                })
        }

        if !self.path.is_empty() {
            self.path.push('.');
        }
        self.path.push_str(element);
    }

    fn pop(&mut self) {
        self.path.truncate(self.path.rfind('.').unwrap_or(0));

        let last_replacement = match self.content_reference_replacement_stack.last_mut() {
            Some(last_replacement) => last_replacement,
            None => return,
        };

        if last_replacement.content_reference == self.path {
            self.path = mem::take(&mut last_replacement.replaced);

            self.content_reference_replacement_stack.pop();
        };
    }
}