use core::fmt;
use fhir_types::codec::Value;
use openehr_rm::v1_2::data_types::text::code_phrase::CodePhrase;
use crate::engine::lens::Fallback;
use crate::engine::lens::term_mapping::Cause;
use crate::engine::lens::term_mapping::Withheld;
use crate::engine::subject::SubjectIdentifier;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Outcome<T> {
value: T,
warnings: Vec<Warning>,
created: Vec<Value>,
consumed: Vec<String>,
subject: Vec<SubjectIdentifier>,
reads: Vec<Location>,
}
impl<T> Outcome<T> {
#[must_use]
pub const fn clean(value: T) -> Self {
Self {
value,
warnings: Vec::new(),
created: Vec::new(),
consumed: Vec::new(),
subject: Vec::new(),
reads: Vec::new(),
}
}
#[must_use]
pub const fn new(value: T, warnings: Vec<Warning>) -> Self {
Self {
value,
warnings,
created: Vec::new(),
consumed: Vec::new(),
subject: Vec::new(),
reads: Vec::new(),
}
}
#[must_use]
pub fn with_created(mut self, created: Vec<Value>) -> Self {
self.created = created;
self
}
#[must_use]
pub fn with_consumed(mut self, consumed: Vec<String>) -> Self {
self.consumed = consumed;
self
}
#[must_use]
pub fn with_subject(mut self, subject: Vec<SubjectIdentifier>) -> Self {
self.subject = subject;
self
}
#[must_use]
pub fn with_reads(mut self, reads: Vec<Location>) -> Self {
self.reads = reads;
self
}
#[must_use]
pub fn reads(&self) -> &[Location] {
&self.reads
}
#[must_use]
pub fn subject(&self) -> &[SubjectIdentifier] {
&self.subject
}
#[must_use]
pub fn consumed(&self) -> &[String] {
&self.consumed
}
#[must_use]
pub fn created(&self) -> &[Value] {
&self.created
}
#[must_use]
pub fn into_parts(self) -> (T, Vec<Value>) {
(self.value, self.created)
}
#[must_use]
pub const fn value(&self) -> &T {
&self.value
}
#[must_use]
pub fn into_value(self) -> T {
self.value
}
#[must_use]
pub fn warnings(&self) -> &[Warning] {
&self.warnings
}
pub fn warn(&mut self, warning: Warning) {
self.warnings.push(warning);
}
#[must_use]
pub fn map<U>(self, transform: impl FnOnce(T) -> U) -> Outcome<U> {
Outcome {
value: transform(self.value),
warnings: self.warnings,
created: self.created,
consumed: self.consumed,
subject: self.subject,
reads: self.reads,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Location {
fhir: Option<String>,
openehr: Option<String>,
resource: Option<String>,
}
impl Location {
#[must_use]
pub fn with_fhir(mut self, path: impl Into<String>) -> Self {
self.fhir = Some(path.into());
self
}
#[must_use]
pub fn with_openehr(mut self, path: impl Into<String>) -> Self {
self.openehr = Some(path.into());
self
}
#[must_use]
pub fn with_resource(mut self, reference: impl Into<String>) -> Self {
self.resource = Some(reference.into());
self
}
#[must_use]
pub fn resource(&self) -> Option<&str> {
self.resource.as_deref()
}
#[must_use]
pub fn fhir(&self) -> Option<&str> {
self.fhir.as_deref()
}
#[must_use]
pub fn openehr(&self) -> Option<&str> {
self.openehr.as_deref()
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Warning {
loss: Loss,
location: Location,
}
impl Warning {
#[must_use]
pub const fn new(loss: Loss, location: Location) -> Self {
Self { loss, location }
}
#[must_use]
pub fn fallback(taken: &Fallback, location: Location) -> Self {
Self::new(
Loss::OneWayFallback {
cell: String::from(taken.cell()),
field: String::from(taken.field()),
},
location,
)
}
#[must_use]
pub fn withheld(mapping: &str, taken: &Withheld, location: Location) -> Self {
let terminology = String::from(taken.terminology());
let code = String::from(taken.code());
let reason = match taken.cause() {
Cause::Match => SkipReason::TermMappingMatch {
match_code: taken.match_code(),
terminology,
code,
},
Cause::Uncarried => SkipReason::TermMappingUncarried { terminology, code },
};
Self::new(
Loss::Skipped {
mapping: String::from(mapping),
reason,
},
location,
)
}
#[must_use]
pub fn uncarried_code(mapping: &str, code: &CodePhrase, location: Location) -> Self {
Self::new(
Loss::Skipped {
mapping: String::from(mapping),
reason: SkipReason::DefiningCodeUncarried {
terminology: code.terminology_id.value.clone(),
code: code.code_string.clone(),
},
},
location,
)
}
#[must_use]
pub const fn loss(&self) -> &Loss {
&self.loss
}
#[must_use]
pub const fn location(&self) -> &Location {
&self.location
}
#[must_use]
pub fn into_parts(self) -> (Loss, Location) {
(self.loss, self.location)
}
}
impl fmt::Display for Warning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.loss, f)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Loss {
Skipped {
mapping: String,
reason: SkipReason,
},
Defaulted {
field: String,
},
LastOfMany {
path: String,
dropped: usize,
},
OneWayFallback {
cell: String,
field: String,
},
UnmappedOccurrences {
archetype: String,
count: usize,
},
InapplicableOccurrences {
archetype: String,
count: usize,
},
Absent {
reason: String,
},
Unread {
node: String,
},
}
impl fmt::Display for Loss {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Skipped {
ref mapping,
ref reason,
} => write!(f, "the mapping {mapping} did not run: {reason}"),
Self::Defaulted { ref field } => write!(f, "the engine filled {field}"),
Self::LastOfMany { ref path, dropped } => write!(
f,
"{path} holds one value, so the write dropped {dropped} earlier occurrences"
),
Self::OneWayFallback {
ref cell,
ref field,
} => write!(f, "{cell} filled {field} by a rule that runs one way"),
Self::UnmappedOccurrences {
ref archetype,
count,
} => write!(
f,
"the composition holds {archetype} {count} more times, which this run over its first occurrence did not map"
),
Self::InapplicableOccurrences {
ref archetype,
count,
} => write!(
f,
"the context's condition does not hold at {count} occurrences of {archetype}, so no resource maps them"
),
Self::Absent { ref reason } => write!(
f,
"the element is written absent, data-absent-reason `{reason}`"
),
Self::Unread { ref node } => write!(
f,
"the composition holds the element {node}, which no mapping carries into the resource"
),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SkipReason {
Unidirectional,
PreprocessorGate {
model: String,
},
UnresolvedReference {
reference: String,
},
EmptyReference,
UnmappedLink {
reference: String,
},
LinkedResource {
target: String,
},
Untranslated {
conceptmap: String,
},
TermMappingMatch {
match_code: char,
terminology: String,
code: String,
},
TermMappingUncarried {
terminology: String,
code: String,
},
DefiningCodeUncarried {
terminology: String,
code: String,
},
EhrStatusSubject,
EventFunctionUncarried {
code: String,
},
NullReasonUncarried,
}
impl fmt::Display for SkipReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Unidirectional => {
f.write_str("its unidirectional marker names the other direction")
}
Self::PreprocessorGate { ref model } => {
write!(
f,
"the preprocessor gate of {model} did not admit the input"
)
}
Self::UnresolvedReference { ref reference } => {
write!(f, "the reference {reference} resolves to no resource")
}
Self::EmptyReference => f.write_str("the Reference names no resource"),
Self::UnmappedLink { ref reference } => {
write!(f, "no context mapping maps the resource {reference} links")
}
Self::LinkedResource { ref target } => write!(
f,
"the resource stands in the linked composition {target}, so no copy is created"
),
Self::Untranslated { ref conceptmap } => {
write!(
f,
"{conceptmap} translates its code to no equivalent concept"
)
}
Self::TermMappingMatch {
match_code,
ref terminology,
ref code,
} => write!(
f,
"its TERM_MAPPING `{match_code}` to {code} of {terminology} is no equivalence, \
and only `=` maps to a Coding"
),
Self::TermMappingUncarried {
ref terminology,
ref code,
} => write!(
f,
"its TERM_MAPPING to {code} of {terminology} has no place in an element \
that carries no coding"
),
Self::DefiningCodeUncarried {
ref terminology,
ref code,
} => write!(
f,
"its defining_code {code} of {terminology} has no place in a string, \
which carries the rubric only"
),
Self::EhrStatusSubject => f.write_str(
"it writes the subject of the EHR, which the EHR_STATUS holds and no composition does",
),
Self::EventFunctionUncarried { ref code } => write!(
f,
"the math_function {code} of its interval event has no place in a Period"
),
Self::NullReasonUncarried => f.write_str(
"its null_reason names no data-absent-reason code, and the extension has no \
place for text",
),
}
}
}
#[cfg(test)]
mod tests {
use super::Location;
use super::Loss;
use super::Outcome;
use super::SkipReason;
use super::Warning;
use crate::engine::lens::Fallback;
#[test]
fn a_clean_outcome_declares_no_loss() {
let outcome = Outcome::clean(7);
assert_eq!(*outcome.value(), 7);
assert!(
outcome.warnings().is_empty(),
"a clean run declares no loss"
);
}
#[test]
fn the_losses_keep_the_order_the_run_took_them() {
let mut outcome = Outcome::clean(String::from("document"));
outcome.warn(Warning::new(
Loss::Skipped {
mapping: String::from("bodySite"),
reason: SkipReason::Unidirectional,
},
Location::default(),
));
outcome.warn(Warning::fallback(
&Fallback::new("DV_CODED_TEXT against CodeableConcept", "DV_TEXT.value"),
Location::default(),
));
assert_eq!(outcome.warnings().len(), 2);
assert_eq!(
outcome.warnings().first().map(ToString::to_string),
Some(String::from(
"the mapping bodySite did not run: its unidirectional marker names the other direction"
))
);
}
#[test]
fn a_dropped_occurrence_names_its_path_and_its_count() {
let warning = Warning::new(
Loss::LastOfMany {
path: String::from("$archetype/data[at0001]/items[at0002]"),
dropped: 2,
},
Location::default(),
);
assert!(
warning
.to_string()
.contains("dropped 2 earlier occurrences"),
"the warning states how much was lost: {warning}"
);
}
#[test]
fn a_location_carries_each_side_it_was_given() {
let location = Location::default()
.with_fhir("Condition.code.coding[0]")
.with_openehr("/content[openEHR-EHR-EVALUATION.problem_diagnosis.v1]/data[at0001]");
assert_eq!(location.fhir(), Some("Condition.code.coding[0]"));
assert_eq!(
location.openehr(),
Some("/content[openEHR-EHR-EVALUATION.problem_diagnosis.v1]/data[at0001]")
);
assert_eq!(Location::default().fhir(), None);
assert_eq!(Location::default().openehr(), None);
}
}