ferrobridge-validator 0.0.0

A FHIR R4 profile validator over packages read offline, the generated fhir-types model and its element table
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
// SPDX-FileCopyrightText: Cadasto B.V.
// SPDX-License-Identifier: BUSL-1.1

//! The walk over an instance: every object against its type in the R4
//! element table, every member's occurrences counted per parent, and every
//! element definition in play applied to each occurrence.

use std::sync::Arc;

mod content;
pub(crate) mod members;

use fhir_types::codec::Object;
use fhir_types::codec::Value;
use fhir_types::r4::element_definition::ElementDefinition;
use fhir_types::r4::schema::SCHEMAS;
use fhir_types::schema::FieldSchema;
use fhir_types::schema::Kind;
use fhir_types::schema::TypeSchema;

use crate::canonical::Canonical;
use crate::issue::IssueType;
use crate::issue::MessageId;
use crate::issue::Severity;
use crate::report::Collector;
use crate::report::Constraint;
use crate::report::Reason;
use crate::report::Report;
use crate::validate::ValidateError;
use crate::validate::Validator;
use crate::validate::slicing::Item;
use crate::validate::slicing::Site;
use crate::validate::structure::Structure;
use members::forms;
use members::knows;

/// The definition an object is held to: a snapshot and the id of the
/// object's own element in it.
#[derive(Debug, Clone)]
pub(crate) struct Cursor {
    /// The snapshot.
    pub(crate) structure: Arc<Structure>,
    /// The id of the object's own element.
    pub(crate) prefix: String,
}

impl Cursor {
    /// Creates a cursor at element `prefix` of `structure`.
    pub(crate) fn new(structure: Arc<Structure>, prefix: &str) -> Self {
        Self {
            structure,
            prefix: prefix.to_owned(),
        }
    }
}

/// One occurrence of a member: its value, its `_` sibling for a primitive,
/// and where it sits.
#[derive(Debug)]
pub(crate) struct Occurrence<'v> {
    /// The value, absent for a primitive written only as its `_` sibling.
    pub(crate) value: Option<&'v Value>,
    /// The `_` sibling of a primitive.
    pub(crate) element: Option<&'v Value>,
    /// The FHIRPath location.
    pub(crate) location: String,
}

/// The form a member takes in one object: the element itself, or one type
/// of a choice.
#[derive(Debug, Clone)]
pub(crate) struct Form {
    /// The JSON member name.
    pub(crate) key: String,
    /// The kind it carries.
    pub(crate) kind: Kind,
    /// The type code of a choice form.
    pub(crate) choice: Option<&'static str>,
}

/// The element one occurrence is held to: the element of its member, and
/// the slices it was matched to, outermost first.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Held<'a> {
    /// The element id of the member.
    pub(crate) id: &'a str,
    /// The member's element definition, when the snapshot carries one.
    pub(crate) element: Option<&'a ElementDefinition>,
    /// The ids of the slices the occurrence belongs to.
    pub(crate) slices: &'a [String],
}

/// One validation in progress.
#[derive(Debug)]
pub(crate) struct Walk<'v, 'set, 'i> {
    validator: &'v Validator<'set>,
    out: Collector,
    /// The resources the walk is inside, the outermost first.
    scope: Vec<&'i Value>,
}

impl<'v, 'set, 'i> Walk<'v, 'set, 'i> {
    /// Starts a validation.
    pub(crate) fn new(validator: &'v Validator<'set>) -> Self {
        Self {
            validator,
            out: Collector::default(),
            scope: Vec::new(),
        }
    }

    /// Starts a speculative validation inside the scope of this one, whose
    /// findings are its own.
    pub(crate) fn fork(&self) -> Self {
        Self {
            validator: self.validator,
            out: Collector::default(),
            scope: self.scope.clone(),
        }
    }

    /// Returns the validator.
    pub(crate) const fn validator(&self) -> &'v Validator<'set> {
        self.validator
    }

    /// Returns the collector.
    pub(crate) const fn out(&mut self) -> &mut Collector {
        &mut self.out
    }

    /// Returns the collector, ending the walk.
    pub(crate) fn into_out(self) -> Collector {
        self.out
    }

    /// Returns the resources the walk is inside, the outermost first.
    pub(crate) fn scope(&self) -> &[&'i Value] {
        &self.scope
    }

    /// Validates `resource`, against `profile` or its core definition.
    pub(crate) fn run(
        mut self,
        resource: &'i Value,
        profile: Option<&str>,
    ) -> Result<Report, ValidateError> {
        let profile = profile
            .map(|profile| self.validator.structure(profile, None))
            .transpose()?;
        self.resource(resource, None, profile)?;
        Ok(self.out.finish())
    }

    /// Validates one resource: the root, or one inside another, against
    /// `profile` or the core definition of its type.
    pub(crate) fn resource(
        &mut self,
        value: &'i Value,
        location: Option<&str>,
        profile: Option<Arc<Structure>>,
    ) -> Result<(), ValidateError> {
        let severity = if location.is_none() {
            Severity::Fatal
        } else {
            Severity::Error
        };
        let Some(object) = value.as_object() else {
            self.out.issue(
                severity,
                IssueType::Structure,
                MessageId::NotAnObject,
                location.unwrap_or_default(),
                "a resource is a JSON object".to_owned(),
            );
            return Ok(());
        };
        let resource_type = object.get("resourceType").and_then(Value::as_str);
        let Some((name, schema)) = resource_type
            .filter(|name| SCHEMAS.is_resource(name))
            .and_then(|name| Some((name, SCHEMAS.type_named(name)?)))
        else {
            self.out.issue(
                severity,
                IssueType::Structure,
                MessageId::UnknownResourceType,
                location.unwrap_or_default(),
                "resourceType names no R4 resource".to_owned(),
            );
            return Ok(());
        };
        let location = location.unwrap_or(name).to_owned();
        let mut structure = match profile {
            Some(profile) => profile,
            None => self.validator.core(name)?,
        };
        if structure.type_name() != name {
            self.out.issue(
                Severity::Error,
                IssueType::Structure,
                MessageId::ProfileTypeMismatch,
                &location,
                format!(
                    "the profile {} constrains {}, not {name}",
                    structure.url(),
                    structure.type_name()
                ),
            );
            structure = self.validator.core(name)?;
        }
        self.claims(object, &structure, name, &location);
        self.scope.push(value);
        let walked = self.object(
            object,
            schema,
            &Cursor::new(structure, name),
            &location,
            true,
        );
        self.scope.pop();
        walked
    }

    /// Lists each profile the resource claims and is not validated against.
    fn claims(&mut self, object: &Object, structure: &Structure, name: &str, location: &str) {
        let claimed = object
            .get("meta")
            .and_then(|meta| meta.get("profile"))
            .and_then(Value::as_array)
            .unwrap_or_default();
        for url in claimed.iter().filter_map(Value::as_str) {
            if Canonical::parse(url).url() != structure.url() {
                // TODO(#441): validate the resource against every profile it claims.
                self.out.unevaluated(
                    url,
                    name,
                    Constraint::ClaimedProfile {
                        url: url.to_owned(),
                    },
                    location,
                    Reason::Profiles,
                );
            }
        }
    }

    /// Walks one object of the type `schema` against `cursor`.
    fn object(
        &mut self,
        object: &'i Object,
        schema: &'static TypeSchema,
        cursor: &Cursor,
        location: &str,
        resource: bool,
    ) -> Result<(), ValidateError> {
        if object.is_empty() {
            // NOTE: json.html §2.6.2: "Objects are never empty".
            self.out.issue(
                Severity::Error,
                IssueType::Structure,
                MessageId::EmptyObject,
                location,
                "the object is empty".to_owned(),
            );
        }
        if let Some(element) = cursor.structure.element(&cursor.prefix) {
            self.list(&cursor.structure, &cursor.prefix, element, location);
        }
        for key in object.keys() {
            if resource && key == "resourceType" {
                continue;
            }
            if !knows(schema, key) {
                self.out.issue(
                    Severity::Error,
                    IssueType::Structure,
                    MessageId::UnknownElement,
                    &format!("{location}.{key}"),
                    format!("{} defines no element {key}", schema.path),
                );
            }
        }
        for field in schema.fields {
            self.field(object, schema, field, cursor, location)?;
        }
        Ok(())
    }

    /// Walks every occurrence of `field` in `object`.
    fn field(
        &mut self,
        object: &'i Object,
        schema: &'static TypeSchema,
        field: &'static FieldSchema,
        cursor: &Cursor,
        location: &str,
    ) -> Result<(), ValidateError> {
        let forms = forms(field, object);
        if forms.len() > 1 {
            self.out.issue(
                Severity::Error,
                IssueType::Structure,
                MessageId::DuplicateChoice,
                &format!("{location}.{}", field.name),
                format!("{} carries more than one type", field.path),
            );
        }
        let segment = field.path.rsplit('.').next().unwrap_or(field.name);
        let element_id = format!("{}.{segment}", cursor.prefix);
        let mut count = 0_usize;
        let mut walked = Vec::new();
        for form in forms {
            let occurrences = self.occurrences(object, field, &form, location);
            count = count.saturating_add(occurrences.len());
            walked.push((form, occurrences));
        }
        let profiled = cursor.structure.element(&element_id);
        self.cardinality(field, profiled, count, &element_id, location);
        let items: Vec<Item<'_, 'i>> = walked
            .iter()
            .flat_map(|(form, occurrences)| {
                occurrences
                    .iter()
                    .map(move |occurrence| Item { form, occurrence })
            })
            .collect();
        let site = Site {
            schema,
            field,
            cursor,
            id: &element_id,
            element: profiled,
            location,
        };
        let mut chains = match profiled.filter(|element| element.slicing.is_some()) {
            Some(entry) => self.slicing(&site, entry, &items)?,
            None => Vec::new(),
        }
        .into_iter();
        for (form, occurrences) in &walked {
            // NOTE: no specification governs this lookup: our own design; a snapshot that
            // names a choice by one type's form (`Observation.valueQuantity`) wins over `[x]`.
            let renamed = format!("{}.{}", cursor.prefix, form.key);
            let (id, element) = match cursor.structure.element(&renamed) {
                Some(element) if form.choice.is_some() => (renamed, Some(element)),
                _ => (element_id.clone(), profiled),
            };
            if let (Some(code), Some(element)) = (form.choice, element)
                && !element.r#type.is_empty()
                && !element
                    .r#type
                    .iter()
                    .any(|kind| kind.code.value.as_deref() == Some(code))
            {
                let at = occurrences
                    .first()
                    .map_or(location, |first| first.location.as_str());
                self.out.issue(
                    Severity::Error,
                    IssueType::Structure,
                    MessageId::ChoiceTypeNotAllowed,
                    at,
                    format!("{id} does not allow the type {code}"),
                );
            }
            for occurrence in occurrences {
                let slices = chains.next().unwrap_or_default();
                let held = Held {
                    id: &id,
                    element,
                    slices: &slices,
                };
                self.apply(schema, field, form, occurrence, cursor, held)?;
            }
        }
        Ok(())
    }

    /// Holds one occurrence to its member's element and to every slice it
    /// was matched to, and walks its content against the innermost of them
    /// that the snapshot defines children for.
    pub(crate) fn apply(
        &mut self,
        schema: &'static TypeSchema,
        field: &'static FieldSchema,
        form: &Form,
        occurrence: &Occurrence<'i>,
        cursor: &Cursor,
        held: Held<'_>,
    ) -> Result<(), ValidateError> {
        let structure = Arc::clone(&cursor.structure);
        let mut content = held.id;
        let mut element = held.element;
        if let Some(base) = held.element {
            self.checks(&structure, held.id, base, occurrence)?;
        }
        for slice in held.slices {
            let Some(defined) = structure.element(slice) else {
                continue;
            };
            self.checks(&structure, slice, defined, occurrence)?;
            element = Some(defined);
            if structure.has_children(slice) {
                content = slice;
            }
        }
        let target = Held {
            id: content,
            element,
            slices: if content == held.id { &[] } else { held.slices },
        };
        self.occurrence(schema, field, form, occurrence, cursor, target)
    }

    /// Applies one element definition's own constraints to an occurrence.
    pub(crate) fn checks(
        &mut self,
        structure: &Structure,
        id: &str,
        element: &ElementDefinition,
        occurrence: &Occurrence<'_>,
    ) -> Result<(), ValidateError> {
        self.list(structure, id, element, &occurrence.location);
        self.fixed_and_pattern(
            element,
            structure.url(),
            id,
            occurrence.value,
            &occurrence.location,
        )?;
        let limit = element.max_length.as_ref().and_then(|length| length.value);
        self.max_length(occurrence.value, limit, id, &occurrence.location);
        Ok(())
    }

    /// Walks a value that SHALL be an object of the type `name`.
    pub(crate) fn complex(
        &mut self,
        value: &'i Value,
        name: &str,
        cursor: &Cursor,
        location: &str,
    ) -> Result<(), ValidateError> {
        let Some(object) = value.as_object() else {
            self.out.issue(
                Severity::Error,
                IssueType::Structure,
                MessageId::WrongJsonType,
                location,
                format!("a {name} is written as a JSON object"),
            );
            return Ok(());
        };
        self.object(object, type_named(name)?, cursor, location, false)
    }
}

/// Returns the element-table entry of the type `name`.
fn type_named(name: &str) -> Result<&'static TypeSchema, ValidateError> {
    SCHEMAS
        .type_named(name)
        .ok_or_else(|| ValidateError::UnknownType {
            name: name.to_owned(),
        })
}