use openehr_mapping_core::composition::FlatIndex;
use openehr_mapping_core::composition::PositionError;
use openehr_mapping_core::composition::RmPosition;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::paths::FlatId;
use crate::engine::fhir::FhirKind;
use crate::engine::fhir::FhirValue;
use crate::engine::outcome::Loss;
use crate::engine::outcome::Warning;
use crate::engine::recurrence::Cardinality;
use crate::engine::recurrence::Placement;
use crate::engine::rm::RmValue;
use crate::model::ast::keyword::Direction;
use crate::resolve::derive;
use crate::resolve::program::mapping::Derived;
use crate::resolve::program::mapping::Mapping;
use crate::resolve::program::mapping::Pairing;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::ListAxis;
use crate::resolve::program::target::OpenehrTarget;
use crate::tree::Occurrence;
use crate::tree::element::Move;
use crate::tree::element::Table;
use crate::tree::read::read;
use crate::tree::write::write;
use crate::engine::traverse::Binding;
use crate::engine::traverse::Held;
use crate::engine::traverse::Run;
use crate::engine::traverse::Written;
use crate::engine::traverse::error::EngineError;
impl<T: Table + ?Sized> Run<'_, T> {
pub(super) fn kind(mapping: &Mapping, target: &FhirTarget) -> Result<FhirKind, EngineError> {
let kind = match (mapping.data_type(), mapping.derived()) {
(Some(data_type), _) => FhirKind::of(data_type),
(None, Some(Derived::Element(code) | Derived::Value { code, .. })) => {
FhirKind::of_code(code)
}
(None, _) => FhirKind::at(target.resolved().location()),
};
kind.ok_or_else(|| EngineError::UnknownElement {
mapping: String::from(mapping.name()),
element: String::from(target.resolved().leaf()),
})
}
pub(super) fn choice_at(
&self,
mapping: &Mapping,
read_at: &FhirTarget,
openehr: &OpenehrTarget,
occurrence: &Occurrence,
) -> Result<Option<FhirValue>, EngineError> {
let matches = read(self.table, self.document_for(read_at), read_at.expression()).map_err(
|source| EngineError::Read {
mapping: String::from(mapping.name()),
expression: String::from(read_at.expression().as_str()),
source: Box::new(source),
},
)?;
let Some(found) = matches
.iter()
.find(|matched| matched.occurrence() == occurrence)
else {
return Ok(None);
};
let (Some(value), Some((suffix, variant))) = (found.value(), found.alternative()) else {
return Ok(None);
};
let element = read_at.resolved().leaf();
let class = openehr.leaf_class().unwrap_or(openehr.node().rm_type());
let kind = derive::carried(class, suffix, variant)
.and_then(FhirKind::of_code)
.ok_or_else(|| EngineError::UnknownElement {
mapping: String::from(mapping.name()),
element: format!("{element} as {suffix}"),
})?;
FhirValue::read(kind, element, value)
.map(Some)
.map_err(|source| EngineError::Fhir {
mapping: String::from(mapping.name()),
element: String::from(element),
source: Box::new(source),
})
}
pub(super) fn polymorphic_in<'mapping>(
&self,
mapping: &Mapping,
read_at: &FhirTarget,
pairings: &'mapping [Pairing],
occurrence: &Occurrence,
) -> Result<Option<(&'mapping OpenehrTarget, FhirValue)>, EngineError> {
let matches = read(self.table, self.document_for(read_at), read_at.expression()).map_err(
|source| EngineError::Read {
mapping: String::from(mapping.name()),
expression: String::from(read_at.expression().as_str()),
source: Box::new(source),
},
)?;
let Some(found) = matches
.iter()
.find(|matched| matched.occurrence() == occurrence)
else {
return Ok(None);
};
let (Some(value), Some((suffix, _variant))) = (found.value(), found.alternative()) else {
return Ok(None);
};
let element = read_at.resolved().leaf();
let unknown = || EngineError::UnknownElement {
mapping: String::from(mapping.name()),
element: format!("{element} as {suffix}"),
};
let pairing = pairings
.iter()
.filter(|pairing| pairing.suffix() == suffix)
.reduce(|best, next| {
if next.rank() < best.rank() {
next
} else {
best
}
})
.ok_or_else(unknown)?;
let kind = FhirKind::of_code(pairing.alternative().code()).ok_or_else(unknown)?;
FhirValue::read(kind, element, value)
.map(|view| Some((pairing.target(), view)))
.map_err(|source| EngineError::Fhir {
mapping: String::from(mapping.name()),
element: String::from(element),
source: Box::new(source),
})
}
pub(super) fn element_at(
&self,
mapping: &Mapping,
target: &FhirTarget,
occurrence: &Occurrence,
kind: FhirKind,
) -> Result<Option<FhirValue>, EngineError> {
let matches =
read(self.table, self.document_for(target), target.expression()).map_err(|source| {
EngineError::Read {
mapping: String::from(mapping.name()),
expression: String::from(target.expression().as_str()),
source: Box::new(source),
}
})?;
let Some(found) = matches
.iter()
.find(|matched| matched.occurrence() == occurrence)
.and_then(crate::tree::read::Match::value)
else {
return Ok(None);
};
FhirValue::read(kind, target.resolved().leaf(), found)
.map(Some)
.map_err(|source| EngineError::Fhir {
mapping: String::from(mapping.name()),
element: String::from(target.resolved().leaf()),
source: Box::new(source),
})
}
pub(super) fn binding_of(&self, node: &ResolvedNode) -> Option<String> {
self.index
.bindings(node)
.ok()
.and_then(<[openehr_mapping_core::template::Binding]>::first)
.map(|binding| String::from(binding.system()))
}
pub(super) fn held(&self, positions: &[RmPosition], flat_id: &FlatId) -> Option<RmValue> {
self.written
.iter()
.find(|written| written.flat_id == *flat_id && written.positions == positions)
.and_then(|written| match written.value {
Held::Value(ref value) => Some(value.clone()),
Held::Partial(_) | Held::Canonical(_) => None,
})
}
pub(super) fn put_openehr_at(
&mut self,
target: &OpenehrTarget,
binding: &Binding,
value: RmValue,
) {
self.store(Written {
flat_id: target.node().flat_id().clone(),
positions: binding.openehr.clone(),
value: Held::Value(value),
});
}
pub(super) fn put_fhir_at(
&mut self,
mapping: &Mapping,
target: &FhirTarget,
binding: &Binding,
view: &FhirValue,
) -> Result<(), EngineError> {
let element = String::from(target.resolved().leaf());
let value = view.write(&element).map_err(|source| EngineError::Fhir {
mapping: String::from(mapping.name()),
element: element.clone(),
source: Box::new(source),
})?;
let table = self.table;
write(
table,
self.document_for_mut(target),
target.expression(),
&binding.fhir,
value,
)
.map_err(|source| EngineError::Write {
mapping: String::from(mapping.name()),
element,
source: Box::new(source),
})
}
pub(super) fn bound_positions(
&self,
target: &OpenehrTarget,
bound: &Binding,
) -> Vec<RmPosition> {
let shared = bound.shared(target.occurrences());
target
.occurrences()
.iter()
.enumerate()
.map(|(depth, axis)| {
bound
.openehr
.get(..shared)
.and_then(|held| held.get(depth))
.copied()
.or_else(|| self.pin(axis.as_str()))
.unwrap_or_else(RmPosition::first)
})
.collect()
}
pub(super) fn bound_elements(target: &OpenehrTarget, bound: &Binding) -> Vec<RmPosition> {
let shared = bound.shared_lists(target);
bound.elements.get(..shared).unwrap_or_default().to_vec()
}
pub(super) fn next_index(&mut self, level: usize, axis: &str, prefix: &[usize]) -> usize {
let key = (String::from(axis), render(prefix));
let counters = match self.direction {
Direction::FhirToOpenehr => &mut self.counters,
Direction::OpenehrToFhir => self.counters_at(level),
};
let next = counters.entry(key).or_insert(0);
let taken = *next;
*next = next.saturating_add(1);
taken
}
pub(super) fn bindings(
&mut self,
mapping: &Mapping,
parent: &Binding,
inputs: &[Occurrence],
) -> Result<Vec<Binding>, EngineError> {
let parent = &self.scoped(mapping.fhir(), parent);
let axes = self.output_axes(mapping);
let mut bound = parent_depth(parent, mapping, self.direction);
while axes.get(bound).is_some_and(|axis| self.pin(axis).is_some()) {
bound = bound.saturating_add(1);
}
let cardinality = Cardinality::of(axes.len() > bound);
let placement = Placement::decide(inputs.len(), cardinality, 0);
if placement.lossy() {
let location = self.locate(mapping, &parent.fhir);
self.warnings.push(Warning::new(
Loss::LastOfMany {
path: self.output_name(mapping),
dropped: placement.dropped(),
},
location,
));
}
let mut bindings = Vec::with_capacity(inputs.len());
for (position, input) in inputs.iter().enumerate() {
let taken = placement.slots().get(position).copied().flatten();
bindings.push(self.bind(mapping, parent, input, &axes, taken)?);
}
Ok(bindings)
}
fn bind(
&mut self,
mapping: &Mapping,
parent: &Binding,
input: &Occurrence,
axes: &[String],
taken: Option<usize>,
) -> Result<Binding, EngineError> {
let level = mapping.fhir().map_or(parent.level, FhirTarget::level);
let bound = parent_depth(parent, mapping, self.direction);
let mut indices: Vec<usize> = match self.direction {
Direction::FhirToOpenehr => {
let mut held = Vec::with_capacity(parent.openehr.len());
for position in parent.openehr.iter().chain(&parent.elements) {
let index = FlatIndex::from(*position).get();
held.push(usize::try_from(index).map_err(|_refused| {
EngineError::Position {
mapping: String::from(mapping.name()),
source: PositionError::Overflow,
}
})?);
}
if let Some(target) = mapping.openehr()
&& parent.shared_lists(target) == 0
{
held.truncate(parent.openehr.len());
}
held
}
Direction::OpenehrToFhir => parent.fhir.indices().to_vec(),
};
indices.truncate(bound);
if taken.is_some() {
let mut fresh = false;
for axis in axes.iter().skip(bound) {
let index = if let Some(pinned) = self.pin(axis) {
usize::try_from(FlatIndex::from(pinned).get()).map_err(|_refused| {
EngineError::Position {
mapping: String::from(mapping.name()),
source: PositionError::Overflow,
}
})?
} else if fresh {
0
} else {
fresh = true;
let key = (axis.clone(), render(&indices));
let counters = match self.direction {
Direction::FhirToOpenehr => &mut self.counters,
Direction::OpenehrToFhir => self.counters_at(level),
};
let next = counters.entry(key).or_insert(0);
let taken = *next;
*next = next.saturating_add(1);
taken
};
indices.push(index);
}
}
match self.direction {
Direction::FhirToOpenehr => {
let mut positions = Vec::with_capacity(indices.len());
for index in &indices {
let index =
u32::try_from(*index).map_err(|_refused| EngineError::Position {
mapping: String::from(mapping.name()),
source: PositionError::Overflow,
})?;
positions.push(RmPosition::try_from(FlatIndex::new(index)).map_err(
|source| EngineError::Position {
mapping: String::from(mapping.name()),
source,
},
)?);
}
Ok(parent.of_openehr(mapping.openehr(), input.clone(), positions, level))
}
Direction::OpenehrToFhir => {
let openehr = rm_positions(mapping.name(), input.indices())?;
Ok(parent.of_openehr(mapping.openehr(), Occurrence::new(indices), openehr, level))
}
}
}
fn output_axes(&self, mapping: &Mapping) -> Vec<String> {
match self.direction {
Direction::FhirToOpenehr => mapping.openehr().map_or_else(Vec::new, |target| {
target
.occurrences()
.iter()
.map(|axis| String::from(axis.as_str()))
.chain(target.lists().iter().map(ListAxis::key))
.collect()
}),
Direction::OpenehrToFhir => mapping.fhir().map_or_else(Vec::new, fhir_axes),
}
}
fn output_name(&self, mapping: &Mapping) -> String {
match self.direction {
Direction::FhirToOpenehr => mapping
.openehr()
.map(|target| String::from(target.node().aql_path().as_str()))
.unwrap_or_default(),
Direction::OpenehrToFhir => mapping
.fhir()
.map(|target| String::from(target.resolved().leaf()))
.unwrap_or_default(),
}
}
}
fn parent_depth(parent: &Binding, mapping: &Mapping, direction: Direction) -> usize {
match direction {
Direction::FhirToOpenehr => mapping.openehr().map_or(parent.openehr.len(), |target| {
parent
.shared(target.occurrences())
.saturating_add(parent.shared_lists(target))
}),
Direction::OpenehrToFhir => parent.fhir.indices().len(),
}
}
pub(super) fn fhir_axes(target: &FhirTarget) -> Vec<String> {
let mut walked = String::from(target.resolved().resource());
let mut axes = Vec::new();
for step in target.resolved().moves() {
match *step {
Move::Member(ref field) => {
walked.push('.');
walked.push_str(field.key());
if field.repeats() {
axes.push(walked.clone());
}
}
Move::Choice { ref field, .. } => {
walked.push('.');
walked.push_str(field.key());
}
Move::Extension { ref field, ref url } => {
walked.push('.');
walked.push_str(field.key());
walked.push('(');
walked.push_str(url);
walked.push(')');
axes.push(walked.clone());
}
Move::Ordinal(_) | Move::Index(_) | Move::Predicate(_) | Move::Resolve { .. } => {}
}
}
axes
}
pub(super) fn rm_positions(name: &str, indices: &[usize]) -> Result<Vec<RmPosition>, EngineError> {
let refuse = |source: PositionError| EngineError::Position {
mapping: String::from(name),
source,
};
let mut positions = Vec::with_capacity(indices.len());
for &index in indices {
let index = u32::try_from(index).map_err(|_refused| refuse(PositionError::Overflow))?;
positions.push(RmPosition::new(index).map_err(refuse)?);
}
Ok(positions)
}
pub(super) fn openehr_occurrence(
name: &str,
positions: &[RmPosition],
) -> Result<Occurrence, EngineError> {
let mut indices = Vec::with_capacity(positions.len());
for position in positions {
indices.push(usize::try_from(position.get()).map_err(|_refused| {
EngineError::Position {
mapping: String::from(name),
source: PositionError::Overflow,
}
})?);
}
Ok(Occurrence::new(indices))
}
fn render(indices: &[usize]) -> String {
indices
.iter()
.map(ToString::to_string)
.collect::<Vec<String>>()
.join(".")
}
#[cfg(test)]
mod tests {
use core::str::FromStr;
use openehr_mapping_core::composition::PositionError;
use super::fhir_axes;
use super::render;
use super::rm_positions;
use crate::engine::traverse::error::EngineError;
use crate::resolve::program::target::FhirTarget;
use crate::tree::element::resolve;
use crate::tree::path::FhirPath;
fn target(expression: &str) -> FhirTarget {
let path = FhirPath::from_str(expression).expect("the expression parses");
let resolved = resolve(&fhir_types::r4::schema::SCHEMAS, "Condition", &path)
.expect("the expression resolves");
FhirTarget::new(path, resolved)
}
#[test]
fn two_elements_that_share_a_definition_count_their_instances_apart() {
let code = fhir_axes(&target("$resource.code.coding.code"));
let status = fhir_axes(&target("$resource.verificationStatus.coding.code"));
assert_eq!(code, vec![String::from("Condition.code.coding")]);
assert_eq!(
status,
vec![String::from("Condition.verificationStatus.coding")]
);
}
#[test]
fn an_index_past_u32_is_an_overflow_and_never_a_zero() {
let past = usize::try_from(u64::from(u32::MAX) + 1).expect("a 64-bit usize");
let error = rm_positions("site", &[1, past]).expect_err("the index has no position");
assert!(
matches!(
error,
EngineError::Position {
source: PositionError::Overflow,
..
}
),
"an overflow names itself: {error}"
);
}
#[test]
fn a_zero_position_is_refused_and_never_dropped() {
let error = rm_positions("site", &[1, 0]).expect_err("0 is no openEHR position");
assert!(matches!(
error,
EngineError::Position {
source: PositionError::Zero,
..
}
));
assert_eq!(
rm_positions("site", &[2, 1])
.expect("both are positions")
.iter()
.map(|position| position.get())
.collect::<Vec<u32>>(),
[2, 1]
);
}
#[test]
fn an_index_prefix_renders_as_the_counter_key() {
assert_eq!(render(&[]), "");
assert_eq!(render(&[0, 2]), "0.2");
}
}