mod excluded;
mod free_text;
mod locate;
use core::str::FromStr;
use std::collections::BTreeMap;
use std::path::Path;
use openehr_mapping_core::diagnostic::ModelPath;
use openehr_mapping_core::header::metadata::MappingName;
use openehr_mapping_core::index::ResolvedNode;
use openehr_mapping_core::index::WebTemplateIndex;
use openehr_mapping_core::index::matching::segment_matches;
use openehr_mapping_core::path::MappingPath;
use openehr_mapping_core::position::Located;
use openehr_mapping_core::template::PathError;
use openehr_rm::v1_2::paths::PathSegment;
use openehr_rm::v1_2::paths::RmPath;
use crate::model::ast::ModelMappingFile;
use crate::model::ast::With;
use crate::model::ast::keyword::Variable;
use crate::resolve::error::ResolveCode;
use crate::resolve::extensions::diagnostic;
use crate::resolve::program::target::OpenehrTarget;
use crate::resolve::compile::Compiler;
use crate::resolve::compile::Scope;
use crate::resolve::compile::party;
impl<'a> Compiler<'a> {
pub(super) fn openehr_side(
&mut self,
file: &'a ModelMappingFile,
with: &With,
scope: &Scope,
path: &ModelPath,
) -> Option<OpenehrTarget> {
let written = with.openehr.as_ref()?;
self.openehr_target(
file.file(),
file.header().name().value(),
written,
scope,
&path.field("openehr"),
)
}
pub(super) fn openehr_target(
&mut self,
file: &Path,
owner: &MappingName,
written: &Located<String>,
scope: &Scope,
path: &ModelPath,
) -> Option<OpenehrTarget> {
let parsed = match MappingPath::from_str(written.value()) {
Ok(parsed) => parsed,
Err(error) => {
self.diagnostics.push(diagnostic(
file,
owner,
ResolveCode::MalformedOpenehrPath,
written.position(),
path,
error.to_string(),
));
return None;
}
};
let anchor = self.openehr_anchor(file, owner, written, scope, path, &parsed)?;
let resolved = match parsed.resolve(&anchor) {
Ok(resolved) => resolved,
Err(error) => {
self.diagnostics
.push(error.to_diagnostic(file.to_path_buf()));
return None;
}
};
if let Some(segment) = resolved
.segments
.iter()
.find(|segment| segment.predicate.position.is_some())
{
self.diagnostics.push(diagnostic(
file,
owner,
ResolveCode::MalformedOpenehrPath,
written.position(),
path,
format!(
"`{resolved}` selects the instance `{}` inside a path, and occurrences are \
structured",
segment.attribute
),
));
return None;
}
let site = party::Site {
file,
owner,
position: written.position(),
path,
};
if self.party_refuses_field(&site, &resolved) {
return None;
}
match self.locate(&resolved) {
Ok(reached) => self.target_of(&site, resolved, reached),
Err(error) => {
let (code, message) = match error {
LocateError::Unknown(message) | LocateError::Excluded(message) => {
(ResolveCode::UnknownTemplateNode, message)
}
LocateError::Ambiguous(message) => {
(ResolveCode::AmbiguousTemplateNode, message)
}
};
self.diagnostics.push(diagnostic(
file,
owner,
code,
written.position(),
path,
message,
));
None
}
}
}
fn target_of(
&mut self,
site: &party::Site<'_>,
resolved: RmPath,
reached: Reached<'a>,
) -> Option<OpenehrTarget> {
let Reached {
node,
tail,
leaf,
on_element,
} = reached;
let occurrences = match occurrences(self.template, node) {
Ok(axes) => axes,
Err(error) => {
self.diagnostics.push(diagnostic(
site.file,
site.owner,
ResolveCode::UnknownTemplateNode,
site.position,
site.path,
format!(
"the occurrence axes of `{}` do not resolve: {error}",
node.flat_id().as_str()
),
));
return None;
}
};
let mut target = OpenehrTarget::new(resolved, node.clone(), tail, occurrences);
if on_element {
target = target.with_element_tail();
}
Some(match leaf {
Some(class) => target.with_leaf_class(class),
None => target,
})
}
fn openehr_anchor(
&mut self,
file: &Path,
owner: &MappingName,
written: &Located<String>,
scope: &Scope,
path: &ModelPath,
parsed: &MappingPath,
) -> Option<RmPath> {
let Some(name) = parsed
.variable()
.map(openehr_mapping_core::path::PathVariable::name)
else {
return Some(scope.openehr.clone());
};
match Variable::from_str(name) {
Ok(Variable::Archetype) => Some(scope.archetype.clone()),
Ok(Variable::OpenehrRoot) => Some(scope.openehr.clone()),
Ok(Variable::Composition) => {
let site = party::Site {
file,
owner,
position: written.position(),
path,
};
if self.party_refuses_composition(&site, written.value()) {
return None;
}
Some(RmPath {
absolute: true,
segments: Vec::new(),
})
}
Ok(Variable::Reference) => None,
Ok(Variable::Resource | Variable::FhirRoot | Variable::Context) | Err(_) => {
self.diagnostics.push(diagnostic(
file,
owner,
ResolveCode::UnboundPathVariable,
written.position(),
path,
format!(
"`{}` opens an openEHR path with `${name}`, which names no openEHR anchor",
written.value()
),
));
None
}
}
}
}
#[derive(Debug)]
pub(super) struct Reached<'a> {
pub(super) node: &'a ResolvedNode,
pub(super) tail: RmPath,
pub(super) leaf: Option<String>,
pub(super) on_element: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum LocateError {
Unknown(String),
Ambiguous(String),
Excluded(String),
}
pub(super) fn walks_below(candidate: &str, ancestor: &str) -> bool {
candidate
.strip_prefix(ancestor)
.is_some_and(|tail| tail.starts_with(['.', '/', '[']))
}
fn constrains(segment: &PathSegment) -> bool {
segment.predicate.archetype_node_id.is_some()
|| segment.predicate.name_value.is_some()
|| segment.predicate.position.is_some()
}
pub(crate) fn occurrences(
template: &WebTemplateIndex,
node: &ResolvedNode,
) -> Result<Vec<openehr_mapping_core::index::paths::FlatId>, PathError> {
let mut axes = Vec::new();
let mut prefix = String::new();
for segment in node.flat_id().as_str().split('/') {
if !prefix.is_empty() {
prefix.push('/');
}
prefix.push_str(segment);
let flat_id = openehr_mapping_core::index::paths::FlatId::new(prefix.clone());
let found = match template.node_by_flat_id(&flat_id) {
Ok(found) => found,
Err(PathError::UnknownNode { .. }) => continue,
Err(error) => return Err(error),
};
if found.repeats() {
axes.push(flat_id);
}
}
Ok(axes)
}
pub(super) fn interior_paths(template: &WebTemplateIndex) -> Vec<RmPath> {
let mut found: BTreeMap<String, RmPath> = BTreeMap::new();
for node in template.nodes() {
let path = node.rm_path();
for taken in 1..path.segments.len() {
let prefix = RmPath {
absolute: path.absolute,
segments: path.segments.get(..taken).unwrap_or_default().to_vec(),
};
found.entry(prefix.to_string()).or_insert(prefix);
}
}
found.into_values().collect()
}
pub(super) fn compaction_map(template: &WebTemplateIndex) -> Vec<(RmPath, &ResolvedNode)> {
let indexed: std::collections::BTreeSet<String> = template
.nodes()
.map(|node| node.rm_path().to_string())
.collect();
let mut found: Vec<(RmPath, &ResolvedNode)> = Vec::new();
for node in template.nodes() {
let path = node.rm_path();
let kept = path
.segments
.iter()
.rposition(constrains)
.map_or(0, |last| last.saturating_add(1));
if kept == path.segments.len() {
continue;
}
let below_indexed = (kept.saturating_add(1)..path.segments.len()).any(|end| {
let ancestor = RmPath {
absolute: path.absolute,
segments: path.segments.get(..end).unwrap_or_default().to_vec(),
};
indexed.contains(&ancestor.to_string())
});
if below_indexed {
continue;
}
let shortened = RmPath {
absolute: path.absolute,
segments: path.segments.get(..kept).unwrap_or_default().to_vec(),
};
found.push((shortened, node));
}
found
}
fn names_same_place(written: &RmPath, carried: &RmPath) -> bool {
written.absolute == carried.absolute
&& written.segments.len() == carried.segments.len()
&& written
.segments
.iter()
.zip(&carried.segments)
.all(|(wanted, held)| {
segment_matches(wanted, held, held.predicate.name_value.as_deref())
})
}