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

//! The headers of a context: its profile, its template, the extensions it
//! applies and the archetype a model mapping is rooted at.

use openehr_mapping_core::diagnostic::Diagnostic;
use openehr_mapping_core::diagnostic::ModelPath;
use openehr_mapping_core::diagnostic::Severity;
use openehr_mapping_core::header::archetype::ArchetypeId;
use openehr_mapping_core::header::metadata::MappingType;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::matching::archetype_release_version;
use openehr_mapping_core::index::matching::node_id_matches;
use openehr_mapping_core::position::Located;
use openehr_rm::v1_2::paths::RmPath;

use crate::model::ast::ContextMappingFile;
use crate::model::ast::ModelMappingFile;
use crate::resolve::error::ResolveCode;
use crate::resolve::extensions::Merged;
use crate::resolve::extensions::apply;
use crate::resolve::extensions::diagnostic;
use crate::resolve::program::binding::ModelBinding;
use crate::resolve::program::binding::Pin;
use crate::resolve::program::binding::ProfileBinding;
use crate::resolve::program::binding::ProfileUrl;
use crate::resolve::program::binding::ResourceType;
use crate::resolve::program::binding::TemplateBinding;
use crate::resolve::program::binding::TemplateId;

use crate::resolve::compile::Compiler;

impl<'a> Compiler<'a> {
    /// Reports every listed extension whose target model the program never
    /// reached, and refuses the edits of one that would be refused if it were.
    ///
    /// An extension applies when the model mapping it extends is merged, so
    /// one whose model no slot of the chain reaches changes nothing. The
    /// context still compiles, and the listing is reported as a warning
    /// because an author who lists an extension expects it to act. Its edits
    /// are still applied to the model on their own, so an `overwrite` or an
    /// `appendTo` that names no single method is refused whether or not the
    /// chain reaches the model: a mapping name means nothing beyond the edits
    /// that address it (`basics/body.adoc`), and one context's reach must not
    /// decide whether such an edit is legal. No specification governs the
    /// warning: our own design.
    pub(super) fn unreached_extensions(&mut self, file: &ContextMappingFile) {
        let owner = file.header().name().value();
        let path = ModelPath::root().field("context").field("extensions");
        let mut unreached: Vec<(&'a ModelMappingFile, &'a ModelMappingFile)> = Vec::new();
        for (index, declared) in file.context().extensions.iter().enumerate() {
            let Some(extension) = self.set.model(declared.value()) else {
                continue;
            };
            let Some(extends) = extension.spec().extends.as_ref() else {
                continue;
            };
            let applied = self.models.iter().any(|model| {
                model
                    .extensions()
                    .iter()
                    .any(|name| name == declared.value())
            });
            if applied {
                continue;
            }
            if let Some(model) = self.set.model(extends.value()) {
                unreached.push((model, extension));
            }
            self.diagnostics.push(
                Diagnostic::warning(
                    file.file().to_path_buf(),
                    ResolveCode::UnreachedExtension.into(),
                    format!(
                        "`{}` extends `{}`, which no mapping of this context reaches, so the \
                         extension changes nothing",
                        declared.value(),
                        extends.value()
                    ),
                )
                .with_position(declared.position())
                .with_mapping_name(owner.clone())
                .with_model_path(path.index(index)),
            );
        }
        let mut models: Vec<&'a ModelMappingFile> = Vec::new();
        for &(model, _) in &unreached {
            if !models.iter().any(|seen| core::ptr::eq(*seen, model)) {
                models.push(model);
            }
        }
        for model in models {
            let edits: Vec<&'a ModelMappingFile> = unreached
                .iter()
                .filter(|&&(of, _)| core::ptr::eq(of, model))
                .map(|&(_, extension)| extension)
                .collect();
            let mut found = Vec::new();
            apply(model, &edits, &mut found);
            // NOTE: no specification governs this: our own design, the model's own warnings
            // belong to a merge that never happens, so only the refusals of the edits are kept.
            self.diagnostics.extend(
                found
                    .into_iter()
                    .filter(|found| found.severity() == Severity::Error),
            );
        }
    }

    /// Reads the profile the context pins.
    pub(super) fn profile_of(file: &ContextMappingFile) -> ProfileBinding {
        let profile = &file.context().profile;
        ProfileBinding::new(
            ProfileUrl::new(
                profile
                    .url
                    .as_ref()
                    .map_or("", |url| url.value().as_str())
                    .to_owned(),
            ),
            Pin::new(profile.version.as_ref().map(|v| v.value().as_str())),
        )
    }

    /// Reads the template the context pins and checks it against the template
    /// the program compiles against.
    pub(super) fn template_of(&mut self, file: &ContextMappingFile) -> TemplateBinding {
        let declared = &file.context().template;
        let name = file.header().name().value();
        let path = ModelPath::root().field("context").field("template");
        let id = declared.id.as_ref().map_or_else(
            || self.template.template_id().to_owned(),
            |id| {
                if id.value() != self.template.template_id() {
                    self.diagnostics.push(diagnostic(
                        file.file(),
                        name,
                        ResolveCode::TemplateIdMismatch,
                        id.position(),
                        &path.field("id"),
                        format!(
                            "the context names the template `{}` and the program compiles against \
                             `{}`",
                            id.value(),
                            self.template.template_id()
                        ),
                    ));
                }
                id.value().clone()
            },
        );
        let sem_ver = declared.sem_ver.as_ref();
        if let (Some(declared_version), Some(carried)) = (sem_ver, self.template.sem_ver())
            && declared_version.value() != carried
        {
            self.diagnostics.push(diagnostic(
                file.file(),
                name,
                ResolveCode::TemplateSemVerMismatch,
                declared_version.position(),
                &path.field("sem_ver"),
                format!(
                    "the context pins `template.sem_ver` `{}` and the template carries `{carried}`",
                    declared_version.value()
                ),
            ));
        }
        TemplateBinding::new(
            TemplateId::new(id),
            Pin::new(sem_ver.map(|version| version.value().as_str())),
            self.template.generation(),
        )
    }

    /// Reads the extension files the context declares, in declaration order.
    pub(super) fn extensions_of(&mut self, file: &ContextMappingFile) -> Vec<&'a ModelMappingFile> {
        let name = file.header().name().value();
        let path = ModelPath::root().field("context").field("extensions");
        let mut found = Vec::new();
        for (index, declared) in file.context().extensions.iter().enumerate() {
            let at = path.index(index);
            let Some(extension) = self.set.model(declared.value()) else {
                self.diagnostics.push(diagnostic(
                    file.file(),
                    name,
                    ResolveCode::UnknownContextReference,
                    declared.position(),
                    &at,
                    format!(
                        "`{}` is no model mapping of the loaded set",
                        declared.value()
                    ),
                ));
                continue;
            };
            let is_extension = extension.header().mapping_type().map(|kind| *kind.value())
                == Some(MappingType::Extension);
            if !is_extension {
                self.diagnostics.push(diagnostic(
                    file.file(),
                    name,
                    ResolveCode::NotAnExtension,
                    declared.position(),
                    &at,
                    format!(
                        "`{}` is loaded as a `{}` file, and `context.extensions` names extensions",
                        declared.value(),
                        extension
                            .header()
                            .mapping_type()
                            .map_or("model", |kind| kind.value().as_str())
                    ),
                ));
                continue;
            }
            if extension.spec().extends.is_none() {
                self.diagnostics.push(diagnostic(
                    extension.file(),
                    extension.header().name().value(),
                    ResolveCode::ExtensionWithoutTarget,
                    extension.spec().position,
                    &ModelPath::root().field("spec").field("extends"),
                    format!(
                        "`{}` extends no model mapping, so nothing says what it applies to",
                        declared.value()
                    ),
                ));
                continue;
            }
            found.push(extension);
        }
        found
    }

    /// Returns the extensions that extend `model`, in declaration order.
    pub(super) fn extensions_for(&self, model: &'a ModelMappingFile) -> Vec<&'a ModelMappingFile> {
        let name = model.header().name().value();
        self.extensions
            .iter()
            .copied()
            .filter(|extension| {
                extension
                    .spec()
                    .extends
                    .as_ref()
                    .is_some_and(|extends| extends.value() == name)
            })
            .collect()
    }

    /// Applies the extensions that extend `model`, in declaration order.
    pub(super) fn merge(&mut self, model: &'a ModelMappingFile) -> Merged<'a> {
        let name = model.header().name().value();
        let mine = self.extensions_for(model);
        let merged = apply(model, &mine, &mut self.diagnostics);
        // NOTE: no specification governs this: our own design; a model a sub-context slots under its
        // own extensions is listed once per distinct set of applied extensions.
        if !self
            .models
            .iter()
            .any(|model| model.name() == name && model.extensions() == merged.applied.as_slice())
        {
            self.models.push(ModelBinding::new(
                name.clone(),
                model.header().version().value().clone(),
                archetype_of(model).cloned(),
                Pin::new(
                    model
                        .header()
                        .revision()
                        .and_then(openehr_mapping_core::value::PositionedValue::as_text),
                ),
                merged.applied.clone(),
            ));
        }
        merged
    }

    /// Reads the resource type the start model mapping names.
    ///
    /// FHIRconnect calls `fhirConfig.structureDefinition` information for the
    /// user (`docs/specs/fhirconnect/modules/ROOT/pages/basics/main.adoc`,
    /// §Spec) and names no other source for the resource type, so the compiler
    /// reads the last segment of that canonical URL, which is the resource
    /// name for a base resource
    /// (<https://hl7.org/fhir/R4/structuredefinition.html>). Requiring the key
    /// and deriving the resource type from it is FerroBRIDGE's own decision:
    /// no specification governs this: our own design.
    pub(super) fn resource_of(&mut self, model: &ModelMappingFile) -> Option<ResourceType> {
        let name = model.header().name().value();
        let path = ModelPath::root()
            .field("spec")
            .field("fhirConfig")
            .field("structureDefinition");
        let Some(ref definition) = model.spec().structure_definition else {
            self.diagnostics.push(diagnostic(
                model.file(),
                name,
                ResolveCode::ResourceTypeUnnamed,
                model.spec().position,
                &path,
                String::from(
                    "the start model mapping names no `fhirConfig.structureDefinition`, so no \
                     resource type is named",
                ),
            ));
            return None;
        };
        let text = definition.value();
        let candidate = text.rsplit('/').next().unwrap_or(text.as_str());
        if !self.table.is_resource(candidate) {
            self.diagnostics.push(diagnostic(
                model.file(),
                name,
                ResolveCode::UnknownResourceType,
                definition.position(),
                &path,
                format!("`{candidate}` names no resource type of this FHIR version"),
            ));
            return None;
        }
        Some(ResourceType::new(candidate))
    }

    /// Returns the path of the node the model mapping's archetype is rooted
    /// at.
    ///
    /// Every refusal here names the model mapping's own file, because the
    /// position it carries is a position in that file.
    pub(super) fn archetype_root(&mut self, model: &ModelMappingFile) -> Option<RmPath> {
        let file = model.file();
        let owner = model.header().name().value();
        let path = ModelPath::root()
            .field("spec")
            .field("openEhrConfig")
            .field("archetype");
        let Some(archetype) = archetype_of(model) else {
            self.diagnostics.push(diagnostic(
                file,
                owner,
                ResolveCode::UnresolvedArchetypeRoot,
                model.spec().position,
                &path,
                format!(
                    "`{}` names no `openEhrConfig.archetype`, so `$archetype` names nothing",
                    model.header().name().value()
                ),
            ));
            return None;
        };
        let template = self.template;
        // NOTE: AM Release-2.3.0 AOM2 §3.6.4 and §3.6.6: a template and its OPT specialise the
        // root archetype, so the root carries every archetype its lineage names.
        let lineage = template
            .root_lineage()
            .iter()
            .find(|carried| node_id_matches(archetype.as_str(), carried));
        let found: Vec<(&ResolvedNode, Option<&str>)> = template
            .nodes()
            .filter_map(|node| match node.node_id() {
                Some(carried) if node_id_matches(archetype.as_str(), carried) => {
                    Some((node, Some(carried)))
                }
                _ if node.rm_path() == template.root().rm_path() => {
                    lineage.map(|carried| (node, Some(carried.as_str())))
                }
                _ => None,
            })
            .collect();
        if let [(only, carried)] = *found.as_slice() {
            let root = only.rm_path().clone();
            self.check_revision(model, carried);
            return Some(root);
        }
        self.diagnostics.push(diagnostic(
            file,
            owner,
            ResolveCode::UnresolvedArchetypeRoot,
            model.spec().position,
            &path,
            format!(
                "the template `{}` carries {} nodes for the archetype `{archetype}`",
                template.template_id(),
                found.len()
            ),
        ));
        None
    }

    /// Checks the revision a model mapping pins against the archetype the
    /// template carries.
    ///
    /// `openEhrConfig.revision` "states what revision of the archetype this
    /// mapping applies for"
    /// (`docs/specs/fhirconnect/modules/ROOT/pages/basics/main.adoc`, §Spec),
    /// and an ADL 2 archetype identifier carries that release version below
    /// its major. A template served over the ADL 1.4 route carries the
    /// interface form alone, so there the pin is recorded and nothing is
    /// compared.
    pub(super) fn check_revision(&mut self, model: &ModelMappingFile, carried: Option<&str>) {
        let Some(revision) = model.header().revision() else {
            return;
        };
        let Some(pinned) = revision.as_text() else {
            return;
        };
        let Some(release) = carried.and_then(archetype_release_version) else {
            return;
        };
        if pinned == release {
            return;
        }
        self.diagnostics.push(diagnostic(
            model.file(),
            model.header().name().value(),
            ResolveCode::ArchetypeRevisionMismatch,
            revision.position(),
            &ModelPath::root()
                .field("spec")
                .field("openEhrConfig")
                .field("revision"),
            format!(
                "`{}` pins the archetype revision `{pinned}` and the template carries \
                 `{release}`",
                model.header().name().value()
            ),
        ));
    }
}

/// Returns the archetype a model mapping declares.
pub(super) fn archetype_of(model: &ModelMappingFile) -> Option<&ArchetypeId> {
    model.header().archetype().map(Located::value)
}