use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::template::PathError;
use openehr_rm::v1_2::paths::RmPath;
use crate::engine::rm::tail_walk;
use crate::engine::rm::tail_walk::concrete_leaf;
use crate::resolve::compile::Compiler;
use crate::resolve::compile::openehr::LocateError;
use crate::resolve::compile::openehr::Reached;
use crate::resolve::compile::openehr::constrains;
use crate::resolve::compile::openehr::names_same_place;
impl<'a> Compiler<'a> {
pub(in crate::resolve::compile) fn locate(
&self,
path: &RmPath,
) -> Result<Reached<'a>, LocateError> {
let total = path.segments.len();
for taken in (0..=total).rev() {
let head = path.segments.get(..taken).unwrap_or_default();
let tail = path.segments.get(taken..).unwrap_or_default();
let prefix = RmPath {
absolute: path.absolute,
segments: head.to_vec(),
};
let rest = RmPath {
absolute: false,
segments: tail.to_vec(),
};
let mut compacted = false;
let node = match self.template.at_rm_path(&prefix) {
Ok(node) => node,
Err(PathError::AmbiguousPath { .. }) => {
let candidates = self.template.all_at_rm_path(&prefix);
match *carrying(&candidates, &rest).as_slice() {
[only] => only,
_ => return Err(self.ambiguity(&prefix, &candidates)),
}
}
Err(_) => {
let found: Vec<&ResolvedNode> = self
.compacted
.iter()
.filter(|entry| names_same_place(&prefix, &entry.0))
.map(|&(_, node)| node)
.collect();
match *found.as_slice() {
[only] => {
compacted = true;
only
}
[] => continue,
_ => return Err(self.ambiguity(&prefix, &found)),
}
}
};
let constrained = rest.segments.iter().find(|segment| constrains(segment));
if let Some(segment) = constrained
&& !self
.interior
.iter()
.any(|interior| names_same_place(path, interior))
{
if let Some((code, root)) = self.excluded_code(node, path, taken) {
return Err(LocateError::Excluded(format!(
"`{path}` names `{code}`, which the archetype at `{}` defines and the \
template `{}` excludes",
root.aql_path().as_str(),
self.template.template_id()
)));
}
return Err(LocateError::Unknown(format!(
"the template `{}` has no node at `{path}`; the deepest node it reaches is \
`{}` and `{}` below it names a node identity the template does not carry",
self.template.template_id(),
node.aql_path().as_str(),
segment.attribute
)));
}
let (leaf, on_element) = match rm_tail(node.rm_type(), &rest) {
Ok(leaf) => (leaf, false),
Err(message) => match element_tail(node, &rest, compacted) {
Some(leaf) => (Some(leaf), true),
None => {
return Err(LocateError::Unknown(format!(
"the template `{}` reaches `{}` and `{path}` walks `{rest}` below \
it: {message}",
self.template.template_id(),
node.aql_path().as_str()
)));
}
},
};
return Ok(Reached {
node,
tail: rest,
leaf,
on_element,
});
}
Err(LocateError::Unknown(format!(
"the template `{}` has no node at `{path}`",
self.template.template_id()
)))
}
fn ambiguity(&self, path: &RmPath, candidates: &[&ResolvedNode]) -> LocateError {
let named: Vec<&str> = candidates
.iter()
.map(|node| node.flat_id().as_str())
.collect();
LocateError::Ambiguous(format!(
"`{path}` names {} nodes of the template `{}`: {}",
named.len(),
self.template.template_id(),
named.join(", ")
))
}
}
fn carrying<'a>(candidates: &[&'a ResolvedNode], tail: &RmPath) -> Vec<&'a ResolvedNode> {
if tail.segments.is_empty() {
return Vec::new();
}
candidates
.iter()
.copied()
.filter(|node| rm_tail(node.rm_type(), tail).is_ok())
.collect()
}
fn element_tail(node: &ResolvedNode, tail: &RmPath, compacted: bool) -> Option<String> {
let holds_value = node.rm_path().segments.last().is_some_and(|last| {
last.attribute == ELEMENT_VALUE && last.predicate.archetype_node_id.is_none()
});
if !compacted || !holds_value {
return None;
}
rm_tail(ELEMENT_CLASS, tail).ok().flatten()
}
const ELEMENT_CLASS: &str = "ELEMENT";
const ELEMENT_VALUE: &str = "value";
pub(super) fn rm_tail(rm_type: &str, tail: &RmPath) -> Result<Option<String>, String> {
tail_walk::steps(rm_type, tail)
.map(|steps| {
steps.and_then(|steps| steps.last().map(|step| concrete_leaf(step.item().name())))
})
.map_err(|error| error.to_string())
}
#[cfg(test)]
mod tests {
use core::str::FromStr;
use openehr_rm::v1_2::paths::RmPath;
use super::rm_tail;
fn leaf(rm_type: &str, tail: &str) -> Option<String> {
let path = RmPath::from_str(tail).expect("the tail parses");
rm_tail(rm_type, &path).expect("the tail walks")
}
#[test]
fn a_bound_of_another_reference_range_is_the_quantity_the_range_belongs_to() {
assert_eq!(
leaf("DV_QUANTITY", "other_reference_ranges/range/lower").as_deref(),
Some("DV_QUANTITY")
);
assert_eq!(
leaf("DV_COUNT", "other_reference_ranges/range/upper").as_deref(),
Some("DV_COUNT")
);
assert_eq!(
leaf("DV_QUANTITY", "other_reference_ranges/meaning").as_deref(),
Some("DV_TEXT")
);
}
#[test]
fn an_element_of_a_list_reads_as_the_class_the_list_holds() {
assert_eq!(leaf("DV_TEXT", "mappings").as_deref(), Some("TERM_MAPPING"));
assert_eq!(
leaf("DV_TEXT", "mappings/target").as_deref(),
Some("CODE_PHRASE")
);
}
}