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

//! The diagnostic codes context resolution raises.
//!
//! Every refusal in this module tree renders into the one
//! [`openehr_mapping_core::diagnostic::Diagnostic`] the shared foundation
//! defines, carrying the file, the YAML position, the mapping name and the
//! path into the document model, and travels as
//! [`openehr_mapping_core::diagnostic::DiagnosticCode::Language`].

use core::fmt;

use openehr_mapping_core::diagnostic::LanguageCodes;

/// A refusal the resolver raises while compiling one context.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ResolveCode {
    /// The name handed to the compiler is no context mapping of the set.
    UnknownContext,
    /// A name the context lists is no model or extension mapping of the set.
    UnknownContextReference,
    /// A name the context lists under `extensions` is not an extension file.
    NotAnExtension,
    /// An extension file writes no `spec.extends`.
    ExtensionWithoutTarget,
    /// A top-level mapping of an extension file writes no `extension` method.
    ExtensionMethodMissing,
    /// A mapping nested under another carries an `extension` method.
    NestedExtensionMethod,
    /// An `add` carries the name of a mapping the model already has.
    AddNameCollision,
    /// An `append` carries a `with` or a condition.
    AppendCarriesMapping,
    /// An `append` names no `appendTo` target.
    AppendWithoutTarget,
    /// An `appendTo` or an `overwrite` names no mapping method of the model.
    UnknownExtensionTarget,
    /// Two extensions of one context overwrite one mapping name.
    RepeatedOverwrite,
    /// Two sibling mapping methods of one file carry one name.
    DuplicateMethodName,
    /// A listed extension extends a model mapping the program never reaches.
    UnreachedExtension,
    /// The model mapping writes no `spec.fhirConfig.structureDefinition`, so
    /// no resource type is named.
    ResourceTypeUnnamed,
    /// The named resource type is none the FHIR element table carries.
    UnknownResourceType,
    /// A `with.fhir` expression is outside the path grammar.
    MalformedFhirPath,
    /// A `with.fhir` expression does not bind to its anchor.
    UnanchoredFhirPath,
    /// A `with.fhir` expression names no element of the FHIR element table.
    UnknownFhirElement,
    /// A mapping that writes FHIR carries a read-only `with.fhir` expression.
    ReadOnlyFhirWrite,
    /// A mapping with no `type` key names a structural node and carries no
    /// child, so it writes nothing.
    AnchorWithoutChildren,
    /// A mapping with no `type` key writes a choice element that admits no
    /// data-type pair of the node's class.
    UnderivedAlternative,
    /// A mapping with no `type` key pairs an openEHR class with a FHIR type
    /// no page of the data-type chapter pairs in a direction it runs.
    UnpairedTypes,
    /// A `reference` writes a choice element that admits no `Reference`.
    ReferenceIntoChoice,
    /// A `link` whose FHIR side is neither a `Reference`, its `reference`
    /// string, nor the resource an enclosing `reference` mapping entered.
    LinkSide,
    /// An openEHR path names a tail below a node that no FLAT part of the
    /// node's class carries.
    UncarriedTail,
    /// A `with.openehr` path is outside the openEHR path grammar.
    MalformedOpenehrPath,
    /// A `with.openehr` path names no node of the operational template.
    UnknownTemplateNode,
    /// A `with.openehr` path names more than one node of the operational
    /// template, so nothing says which one it means.
    AmbiguousTemplateNode,
    /// A `with.openehr` path names a node the archetype defines and the
    /// operational template excludes, so the mapping is ignored.
    ExcludedTemplateNode,
    /// A path opens with a variable that names nothing here.
    UnboundPathVariable,
    /// The archetype a model mapping declares is not the archetype of the
    /// node its `$archetype` resolves to.
    ArchetypeMismatch,
    /// The archetype revision a model mapping pins is not the release version
    /// the template's archetype identifier carries.
    ArchetypeRevisionMismatch,
    /// The template carries no node for the archetype a model mapping
    /// declares, or carries more than one.
    UnresolvedArchetypeRoot,
    /// A slot chain enters one model mapping more often than
    /// [`crate::resolve::program::SLOT_DEPTH_LIMIT`] admits.
    SlotDepth,
    /// A mapping carries two mapping methods that exclude each other.
    ConflictingMappingMethods,
    /// A `hierarchy.split` `create` names no element the engine creates.
    UnknownSplitCreate,
    /// A `manual` value opens with `$context` and names no member of it.
    MalformedContextValue,
    /// The template the context names is not the template compiled against.
    TemplateIdMismatch,
    /// The template version the context pins is not the one the template
    /// carries.
    TemplateSemVerMismatch,
    /// A `slotContext` names a context the entering context does not list
    /// under `contexts`.
    UndeclaredSubContext,
    /// A `scope: sub` context is compiled as a root.
    SubContextAsRoot,
    /// The `start` of a `scope: sub` context slots a composition model.
    SubContextComposition,
    /// A `slotContext` enters a context already on the chain of entered
    /// contexts.
    CyclicSubContext,
    /// A sub-context's `template.id` is not the template the parent's
    /// operational template embeds at the slot node.
    SubContextTemplateMismatch,
    /// The parent's operational template states no embedded template at the
    /// slot node, so a sub-context's `template.id` cannot be checked.
    SubContextTemplateUndecided,
    /// A path in a party context opens with `$composition`, which names the
    /// root composition, and a party context has none.
    PartyCompositionVariable,
    /// A path in a party context names a composition attribute the
    /// composition defaults or the `ctx/` vocabulary set.
    PartyCompositionField,
    /// A party context carries a `participationsFunction`, and a party holds
    /// no `PARTICIPATION` list.
    PartyParticipation,
    /// A party context carries a `link`.
    PartyLink,
    /// A party context enters a context whose `start` slots a composition
    /// model.
    PartySubContextComposition,
    /// A mapping onto a `PARTY_REF` names a FHIR element whose reference
    /// admits no single resource type, so the reference it reads back has no
    /// type to name.
    PartyRefTarget,
    /// A port a programmed function declares adds a repeating node below the
    /// mapping's `with.openehr`, so one call would read or write many values.
    RepeatingFunctionPort,
    /// A programmed function declares openEHR ports, and the mapping that
    /// names it writes no `with.openehr` to anchor them.
    UnanchoredFunctionPort,
    /// A `manual` entry writes a `DV_TEXT` at a `DV_CODED_TEXT` node whose
    /// value set is closed.
    ClosedValueSet,
}

impl ResolveCode {
    /// Returns the stable spelling of the code.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UnknownContext => "fc-unknown-context",
            Self::UnknownContextReference => "fc-unknown-context-reference",
            Self::NotAnExtension => "fc-not-an-extension",
            Self::ExtensionWithoutTarget => "fc-extension-without-target",
            Self::ExtensionMethodMissing => "fc-extension-method-missing",
            Self::NestedExtensionMethod => "fc-nested-extension-method",
            Self::AddNameCollision => "fc-add-name-collision",
            Self::AppendCarriesMapping => "fc-append-carries-mapping",
            Self::AppendWithoutTarget => "fc-append-without-target",
            Self::UnknownExtensionTarget => "fc-unknown-extension-target",
            Self::RepeatedOverwrite => "fc-repeated-overwrite",
            Self::DuplicateMethodName => "fc-duplicate-method-name",
            Self::UnreachedExtension => "fc-unreached-extension",
            Self::ResourceTypeUnnamed => "fc-resource-type-unnamed",
            Self::UnknownResourceType => "fc-unknown-resource-type",
            Self::MalformedFhirPath => "fc-malformed-fhir-path",
            Self::UnanchoredFhirPath => "fc-unanchored-fhir-path",
            Self::UnknownFhirElement => "fc-unknown-fhir-element",
            Self::ReadOnlyFhirWrite => "fc-read-only-fhir-write",
            Self::AnchorWithoutChildren => "fc-anchor-without-children",
            Self::UnderivedAlternative => "fc-underived-alternative",
            Self::UnpairedTypes => "fc-unpaired-types",
            Self::ReferenceIntoChoice => "fc-reference-into-choice",
            Self::LinkSide => "fc-link-side",
            Self::UncarriedTail => "fc-uncarried-tail",
            Self::MalformedOpenehrPath => "fc-malformed-openehr-path",
            Self::UnknownTemplateNode => "fc-unknown-template-node",
            Self::AmbiguousTemplateNode => "fc-ambiguous-template-node",
            Self::ExcludedTemplateNode => "fc-excluded-template-node",
            Self::UnboundPathVariable => "fc-unbound-path-variable",
            Self::ArchetypeMismatch => "fc-archetype-mismatch",
            Self::ArchetypeRevisionMismatch => "fc-archetype-revision-mismatch",
            Self::UnresolvedArchetypeRoot => "fc-unresolved-archetype-root",
            Self::SlotDepth => "fc-slot-depth",
            Self::ConflictingMappingMethods => "fc-conflicting-mapping-methods",
            Self::UnknownSplitCreate => "fc-unknown-split-create",
            Self::MalformedContextValue => "fc-malformed-context-value",
            Self::TemplateIdMismatch => "fc-template-id-mismatch",
            Self::TemplateSemVerMismatch => "fc-template-sem-ver-mismatch",
            Self::UndeclaredSubContext => "fc-undeclared-sub-context",
            Self::SubContextAsRoot => "fc-sub-context-as-root",
            Self::SubContextComposition => "fc-sub-context-composition",
            Self::CyclicSubContext => "fc-cyclic-sub-context",
            Self::SubContextTemplateMismatch => "fc-sub-context-template-mismatch",
            Self::SubContextTemplateUndecided => "fc-sub-context-template-undecided",
            Self::PartyCompositionVariable => "fc-party-composition-variable",
            Self::PartyCompositionField => "fc-party-composition-field",
            Self::PartyParticipation => "fc-party-participation",
            Self::PartyLink => "fc-party-link",
            Self::PartySubContextComposition => "fc-party-sub-context-composition",
            Self::PartyRefTarget => "fc-party-ref-target",
            Self::RepeatingFunctionPort => "fc-repeating-function-port",
            Self::UnanchoredFunctionPort => "fc-unanchored-function-port",
            Self::ClosedValueSet => "fc-closed-value-set",
        }
    }

    /// Every code this enum defines, in declaration order.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::UnknownContext,
            Self::UnknownContextReference,
            Self::NotAnExtension,
            Self::ExtensionWithoutTarget,
            Self::ExtensionMethodMissing,
            Self::NestedExtensionMethod,
            Self::AddNameCollision,
            Self::AppendCarriesMapping,
            Self::AppendWithoutTarget,
            Self::UnknownExtensionTarget,
            Self::RepeatedOverwrite,
            Self::DuplicateMethodName,
            Self::UnreachedExtension,
            Self::ResourceTypeUnnamed,
            Self::UnknownResourceType,
            Self::MalformedFhirPath,
            Self::UnanchoredFhirPath,
            Self::UnknownFhirElement,
            Self::ReadOnlyFhirWrite,
            Self::AnchorWithoutChildren,
            Self::UnderivedAlternative,
            Self::UnpairedTypes,
            Self::ReferenceIntoChoice,
            Self::LinkSide,
            Self::UncarriedTail,
            Self::MalformedOpenehrPath,
            Self::UnknownTemplateNode,
            Self::AmbiguousTemplateNode,
            Self::ExcludedTemplateNode,
            Self::UnboundPathVariable,
            Self::ArchetypeMismatch,
            Self::ArchetypeRevisionMismatch,
            Self::UnresolvedArchetypeRoot,
            Self::SlotDepth,
            Self::ConflictingMappingMethods,
            Self::UnknownSplitCreate,
            Self::MalformedContextValue,
            Self::TemplateIdMismatch,
            Self::TemplateSemVerMismatch,
            Self::UndeclaredSubContext,
            Self::SubContextAsRoot,
            Self::SubContextComposition,
            Self::CyclicSubContext,
            Self::SubContextTemplateMismatch,
            Self::SubContextTemplateUndecided,
            Self::PartyCompositionVariable,
            Self::PartyCompositionField,
            Self::PartyParticipation,
            Self::PartyLink,
            Self::PartySubContextComposition,
            Self::PartyRefTarget,
            Self::RepeatingFunctionPort,
            Self::UnanchoredFunctionPort,
            Self::ClosedValueSet,
        ]
    }
}

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

impl LanguageCodes for ResolveCode {
    fn spelling(self) -> &'static str {
        self.as_str()
    }
}

#[cfg(test)]
mod tests {
    use openehr_mapping_core::diagnostic::DiagnosticCode;
    use openehr_mapping_core::diagnostic::LanguageCode;

    use super::ResolveCode;

    #[test]
    fn every_code_is_a_language_code() {
        for code in ResolveCode::all() {
            assert!(
                LanguageCode::new(code.as_str()).is_ok(),
                "the code `{code}` is outside the language-code alphabet"
            );
        }
    }

    #[test]
    fn every_code_has_a_distinct_spelling() {
        let mut spellings: Vec<&str> = ResolveCode::all()
            .iter()
            .map(|code| code.as_str())
            .collect();
        let total = spellings.len();
        spellings.sort_unstable();
        spellings.dedup();
        assert_eq!(spellings.len(), total, "two resolve codes share a spelling");
    }

    #[test]
    fn a_code_renders_as_its_diagnostic_code() {
        assert_eq!(
            DiagnosticCode::from(ResolveCode::SlotDepth).to_string(),
            "fc-slot-depth"
        );
    }
}