use core::str::FromStr;
use fhir_types::schema::Kind;
use fhir_types::schema::ValueKind;
use openehr_mapping_core::diagnostic::Diagnostic;
use openehr_mapping_core::diagnostic::ModelPath;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::position::Position;
use openehr_rm::v1_2::model;
use crate::model::ast::ModelMappingFile;
use crate::model::ast::keyword::Direction;
use crate::resolve::derive;
use crate::resolve::error::ResolveCode;
use crate::resolve::extensions::diagnostic;
use crate::resolve::program::mapping::Alternative;
use crate::resolve::program::mapping::Derived;
use crate::resolve::program::mapping::EventTime;
use crate::resolve::program::mapping::Pairing;
use crate::resolve::program::target::FhirTarget;
use crate::resolve::program::target::OpenehrTarget;
use crate::tree::element;
use crate::tree::element::Location;
use crate::tree::element::Move;
use crate::tree::path::FhirPath;
use crate::resolve::compile::Compiler;
use crate::resolve::compile::Derivation;
#[derive(Debug, Clone, Copy)]
struct Sides<'target> {
fhir: &'target FhirTarget,
openehr: &'target OpenehrTarget,
direction: Option<Direction>,
children: bool,
}
const EXTENSION_TYPE: &str = "Extension";
const EXTENSION_VALUE: &str = "value";
const ELEMENT: &str = "ELEMENT";
const EVENT: &str = "EVENT";
const POINT_EVENT: &str = "POINT_EVENT";
const INTERVAL_EVENT: &str = "INTERVAL_EVENT";
const TIME: &str = "time";
const DATE_TIME: &str = "dateTime";
const PERIOD: &str = "Period";
const POINT_CODES: &[&str] = &["instant", "date", "time"];
impl<'a> Compiler<'a> {
pub(super) fn derived_of(
&mut self,
file: &'a ModelMappingFile,
derivation: &Derivation<'_>,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
let fhir = derivation.fhir?;
match (derivation.openehr, derivation.data_type) {
(Some(openehr), None) if derivation.plain => self.derive(
file,
Sides {
fhir,
openehr,
direction: derivation.direction,
children: derivation.children,
},
position,
path,
),
(_, Some(data_type))
if derivation.plain
&& matches!(*fhir.resolved().location(), Location::Choice(_)) =>
{
let code = derive::declared(data_type)?;
self.declared_alternative(file, fhir, code, position, path)
}
_ => None,
}
}
fn derive(
&mut self,
file: &'a ModelMappingFile,
sides: Sides<'_>,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
let owner = file.header().name().value();
let Sides {
fhir,
openehr,
direction,
children,
} = sides;
let class = openehr.leaf_class().unwrap_or(openehr.node().rm_type());
if openehr.ends_on_list() {
return children.then_some(Derived::Anchor);
}
if model::is_a(class, derive::STRUCTURAL) {
if let Some(event) = self.event_time(file, fhir, openehr, position, path) {
return Some(event);
}
if let Some(polymorphic) = self.element_choice(file, fhir, openehr, position, path) {
return Some(polymorphic);
}
if let Some(value) = self.element_value(fhir, openehr) {
return Some(value);
}
if children {
return Some(Derived::Anchor);
}
self.diagnostics.push(
Diagnostic::warning(
file.file().to_path_buf(),
ResolveCode::AnchorWithoutChildren.into(),
format!(
"`{}` names the {class} node `{}`, which holds other nodes, and no \
`type` or child says what to write into it, so a run that carries \
the element refuses",
fhir.expression(),
openehr.path()
),
)
.with_position(position)
.with_mapping_name(owner.clone())
.with_model_path(path.clone()),
);
return None;
}
let read = match *fhir.resolved().location() {
Location::Choice(_) => fhir.clone(),
Location::Complex(schema)
if schema.name == EXTENSION_TYPE && !derive::pairs(class).is_empty() =>
{
self.derived_target(file, fhir, EXTENSION_VALUE, position, path)?
}
Location::Complex(_) | Location::Primitive(_) | Location::Attribute => {
return self.element_pair(file, sides, class, position, path);
}
Location::Resource
if openehr.leaf_class().is_none() && !derive::pairs(class).is_empty() =>
{
let resource = fhir.resolved().leaf();
self.unpaired(file, (fhir, openehr), class, resource, position, path);
return None;
}
Location::PrimitiveElement | Location::Resource | Location::Deferred => return None,
};
if direction == Some(Direction::FhirToOpenehr) {
return Some(Derived::Choice { read, write: None });
}
let variants = match read.resolved().moves().last() {
Some(Move::Choice { schema, .. }) => match schema.kind {
Kind::Choice(variants) => variants,
_ => &[],
},
_ => &[],
};
let Some(suffix) = derive::alternative(class, variants) else {
self.diagnostics.push(diagnostic(
file.file(),
owner,
ResolveCode::UnderivedAlternative,
position,
path,
format!(
"`{}` is written from the {class} node `{}`, and the choice admits none of \
the types {class} pairs with ({}); a `type` or an `as()` says which to write",
read.resolved().leaf(),
openehr.path(),
derive::pairs(class).join(", ")
),
));
return None;
};
let written = self.derived_target(file, &read, &format!("as({suffix})"), position, path)?;
let code = written.resolved().type_code().unwrap_or(suffix);
Some(Derived::Choice {
read,
write: Some(Alternative::new(code, written)),
})
}
fn element_pair(
&mut self,
file: &'a ModelMappingFile,
sides: Sides<'_>,
class: &str,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
let Sides {
fhir,
openehr,
direction,
..
} = sides;
let code = fhir.resolved().type_code()?;
let text = matches!(
*fhir.resolved().location(),
Location::Primitive(ValueKind::Text) | Location::Attribute
);
let pair = derive::element(class, code, text);
if openehr.leaf_class().is_none()
&& !derive::pairs(class).is_empty()
&& !derive::pairs_in(class, pair, direction)
{
self.unpaired(file, (fhir, openehr), class, code, position, path);
return None;
}
Some(Derived::Element(pair))
}
fn unpaired(
&mut self,
file: &'a ModelMappingFile,
(fhir, openehr): (&FhirTarget, &OpenehrTarget),
class: &str,
named: &str,
position: Position,
path: &ModelPath,
) {
self.diagnostics.push(diagnostic(
file.file(),
file.header().name().value(),
ResolveCode::UnpairedTypes,
position,
path,
format!(
"`{}` ({named}) is mapped onto the {class} node `{}`, and the data-type chapter \
pairs {class} only with {}; a `manual`, a `mappingCode` or a path to a paired \
element says how to carry it",
fhir.expression(),
openehr.path(),
derive::pairs(class).join(", ")
),
));
}
fn element_value(&self, fhir: &FhirTarget, openehr: &OpenehrTarget) -> Option<Derived> {
if openehr.node().rm_type() != ELEMENT || !openehr.tail().segments.is_empty() {
return None;
}
let location = fhir.resolved().location();
let text = match *location {
Location::Primitive(ValueKind::Text) | Location::Attribute => true,
Location::Complex(_) | Location::Primitive(_) => false,
Location::Choice(_)
| Location::PrimitiveElement
| Location::Resource
| Location::Deferred => return None,
};
let code = fhir.resolved().type_code()?;
let mut chosen: Option<((bool, usize), &ResolvedNode, &'static str)> = None;
for flat_id in openehr.node().children() {
let Ok(child) = self.template.node_by_flat_id(flat_id) else {
continue;
};
let class = child.rm_type();
let pair = derive::element(class, code, text);
let Some(rank) = derive::pairs(class)
.iter()
.position(|&paired| paired == pair)
else {
continue;
};
let key = (pair != code, rank);
if chosen.is_none_or(|(best, _, _)| key < best) {
chosen = Some((key, child, pair));
}
}
let (_, child, pair) = chosen?;
let target = OpenehrTarget::new(
child.rm_path().clone(),
child.clone(),
openehr.tail().clone(),
openehr.occurrences().to_vec(),
);
Some(Derived::Value { code: pair, target })
}
fn event_time(
&mut self,
file: &'a ModelMappingFile,
fhir: &FhirTarget,
openehr: &OpenehrTarget,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
let class = openehr.node().rm_type();
if !model::is_a(class, EVENT) || !openehr.tail().segments.is_empty() {
return None;
}
let points = model::is_a(POINT_EVENT, class);
let intervals = model::is_a(INTERVAL_EVENT, class);
let time = self.event_time_node(openehr)?;
let (point, interval) = match *fhir.resolved().location() {
Location::Choice(_) => {
let variants = match fhir.resolved().moves().last() {
Some(Move::Choice { schema, .. }) => match schema.kind {
Kind::Choice(variants) => variants,
_ => &[],
},
_ => &[],
};
let point = derive::suffix_of(DATE_TIME, variants).filter(|_| points);
let interval = derive::suffix_of(PERIOD, variants).filter(|_| intervals);
if point.is_none() && interval.is_none() {
return None;
}
let mut written = |suffix: Option<&str>| match suffix {
Some(suffix) => self
.derived_target(file, fhir, &format!("as({suffix})"), position, path)
.map(Some),
None => Some(None),
};
(written(point)?, written(interval)?)
}
Location::Complex(_) | Location::Primitive(_) => match fhir.resolved().type_code()? {
PERIOD if intervals => (None, Some(fhir.clone())),
DATE_TIME if points => (Some(fhir.clone()), None),
code if points && POINT_CODES.contains(&code) => (None, None),
_ => return None,
},
Location::Attribute
| Location::PrimitiveElement
| Location::Resource
| Location::Deferred => return None,
};
Some(Derived::Event(Box::new(EventTime::new(
fhir.clone(),
time,
point,
interval,
))))
}
fn event_time_node(&self, openehr: &OpenehrTarget) -> Option<OpenehrTarget> {
let child = openehr.node().children().iter().find_map(|flat_id| {
self.template.node_by_flat_id(flat_id).ok().filter(|child| {
child
.rm_path()
.segments
.last()
.is_some_and(|segment| segment.attribute == TIME)
})
})?;
Some(OpenehrTarget::new(
child.rm_path().clone(),
child.clone(),
openehr.tail().clone(),
openehr.occurrences().to_vec(),
))
}
fn element_choice(
&mut self,
file: &'a ModelMappingFile,
fhir: &FhirTarget,
openehr: &OpenehrTarget,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
if openehr.node().rm_type() != ELEMENT
|| !openehr.tail().segments.is_empty()
|| !matches!(*fhir.resolved().location(), Location::Choice(_))
{
return None;
}
let variants = match fhir.resolved().moves().last() {
Some(Move::Choice { schema, .. }) => match schema.kind {
Kind::Choice(variants) => variants,
_ => &[],
},
_ => &[],
};
let mut pairings = Vec::new();
for flat_id in openehr.node().children() {
let Ok(child) = self.template.node_by_flat_id(flat_id) else {
continue;
};
let target = OpenehrTarget::new(
child.rm_path().clone(),
child.clone(),
openehr.tail().clone(),
openehr.occurrences().to_vec(),
);
for (rank, code) in derive::pairs(child.rm_type()).iter().enumerate() {
let Some(suffix) = derive::suffix_of(code, variants) else {
continue;
};
let written =
self.derived_target(file, fhir, &format!("as({suffix})"), position, path)?;
let code = written.resolved().type_code().unwrap_or(code);
pairings.push(Pairing::new(
Alternative::new(code, written),
suffix,
rank,
target.clone(),
));
}
}
(!pairings.is_empty()).then(|| Derived::Polymorphic {
read: fhir.clone(),
pairings,
})
}
fn declared_alternative(
&mut self,
file: &'a ModelMappingFile,
fhir: &FhirTarget,
code: &'static str,
position: Position,
path: &ModelPath,
) -> Option<Derived> {
let variants = match fhir.resolved().moves().last() {
Some(Move::Choice { schema, .. }) => match schema.kind {
Kind::Choice(variants) => variants,
_ => &[],
},
_ => &[],
};
let Some(suffix) = derive::suffix_of(code, variants) else {
self.diagnostics.push(diagnostic(
file.file(),
file.header().name().value(),
ResolveCode::UnderivedAlternative,
position,
path,
format!(
"the `type` of `{}` names {code}, which the choice `{}` does not admit",
fhir.expression(),
fhir.resolved().leaf()
),
));
return None;
};
let written = self.derived_target(file, fhir, &format!("as({suffix})"), position, path)?;
Some(Derived::Declared(Alternative::new(code, written)))
}
fn derived_target(
&mut self,
file: &'a ModelMappingFile,
target: &FhirTarget,
step: &str,
position: Position,
path: &ModelPath,
) -> Option<FhirTarget> {
let written = format!("{}.{step}", target.expression());
let (code, reason) = match FhirPath::from_str(&written) {
Ok(expression) => {
match element::resolve(self.table, target.resolved().resource(), &expression) {
Ok(resolved) => {
return Some(
FhirTarget::new(expression, resolved).at_level(target.level()),
);
}
Err(error) => (ResolveCode::UnknownFhirElement, error.to_string()),
}
}
Err(error) => (ResolveCode::MalformedFhirPath, error.to_string()),
};
self.diagnostics.push(diagnostic(
file.file(),
file.header().name().value(),
code,
position,
path,
format!("the derived `{written}` does not resolve: {reason}"),
));
None
}
}