use fhir_types::codec::Value;
use fhir_types::schema::FieldSchema;
use fhir_types::schema::Kind;
use crate::tree::Occurrence;
use crate::tree::element::Location;
use crate::tree::element::Move;
use crate::tree::element::Table;
use crate::tree::element::resolve;
use crate::tree::error::ReadError;
use crate::tree::json_kind;
use crate::tree::path::FhirPath;
use crate::tree::path::Ordinal;
use crate::tree::path::Step;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Deferred<'tree> {
source: &'tree Value,
expected: Option<String>,
continuation: Vec<Step>,
}
impl<'tree> Deferred<'tree> {
#[must_use]
pub const fn source(&self) -> &'tree Value {
self.source
}
#[must_use]
pub fn expected(&self) -> Option<&str> {
self.expected.as_deref()
}
#[must_use]
pub fn continuation(&self) -> &[Step] {
&self.continuation
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Selected<'tree> {
Value(&'tree Value),
Deferred(Deferred<'tree>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match<'tree> {
occurrence: Occurrence,
selected: Selected<'tree>,
alternative: Option<(&'static str, Kind)>,
}
impl<'tree> Match<'tree> {
#[must_use]
pub const fn occurrence(&self) -> &Occurrence {
&self.occurrence
}
#[must_use]
pub const fn selected(&self) -> &Selected<'tree> {
&self.selected
}
#[must_use]
pub const fn alternative(&self) -> Option<(&'static str, Kind)> {
self.alternative
}
#[must_use]
pub const fn value(&self) -> Option<&'tree Value> {
match self.selected {
Selected::Value(value) => Some(value),
Selected::Deferred(_) => None,
}
}
}
pub fn read<'tree, T: Table + ?Sized>(
table: &T,
document: &'tree Value,
path: &FhirPath,
) -> Result<Vec<Match<'tree>>, ReadError> {
let resource = document
.get("resourceType")
.and_then(Value::as_str)
.ok_or(ReadError::NoResourceType)?;
let resolved =
resolve(table, resource, path).map_err(|source| ReadError::Resolve { source })?;
let mut cursors = vec![Cursor {
value: document,
occurrence: Occurrence::default(),
alternative: None,
}];
for step in resolved.moves() {
cursors = advance(cursors, step)?;
}
let deferred = matches!(resolved.location(), Location::Deferred);
Ok(cursors
.into_iter()
.map(|cursor| cursor.into_match(resolved.moves(), deferred))
.collect())
}
#[derive(Debug, Clone)]
struct Cursor<'tree> {
value: &'tree Value,
occurrence: Occurrence,
alternative: Option<(&'static str, Kind)>,
}
impl<'tree> Cursor<'tree> {
fn into_match(self, moves: &[Move], deferred: bool) -> Match<'tree> {
let selected = match moves.last() {
Some(Move::Resolve {
expected,
continuation,
}) if deferred => Selected::Deferred(Deferred {
source: self.value,
expected: expected.clone(),
continuation: continuation.clone(),
}),
_ => Selected::Value(self.value),
};
Match {
occurrence: self.occurrence,
selected,
alternative: self.alternative,
}
}
fn indexed(&self, value: &'tree Value, index: usize) -> Self {
let mut occurrence = self.occurrence.clone();
occurrence.push(index);
Self {
value,
occurrence,
alternative: None,
}
}
}
fn advance<'tree>(
cursors: Vec<Cursor<'tree>>,
step: &Move,
) -> Result<Vec<Cursor<'tree>>, ReadError> {
match step {
Move::Member(field) => {
let mut next = Vec::new();
for cursor in &cursors {
member(
cursor,
field.path(),
field.key(),
field.repeats(),
&mut next,
)?;
}
Ok(next)
}
Move::Choice { field, schema } => {
let mut next = Vec::new();
for cursor in &cursors {
let Some((suffix, kind)) = alternative(cursor, field.path(), field.key(), schema)?
else {
continue;
};
let key = format!("{}{suffix}", field.key());
let start = next.len();
member(cursor, field.path(), &key, field.repeats(), &mut next)?;
for taken in next.iter_mut().skip(start) {
taken.alternative = Some((suffix, kind));
}
}
Ok(next)
}
Move::Extension { field, url } => {
let mut next = Vec::new();
for cursor in &cursors {
extension(cursor, field.path(), field.key(), url, &mut next)?;
}
Ok(next)
}
Move::Ordinal(Ordinal::First) => Ok(cursors.into_iter().take(1).collect()),
Move::Ordinal(Ordinal::Last) => Ok(cursors.into_iter().next_back().into_iter().collect()),
Move::Index(position) => Ok(cursors.into_iter().skip(*position).take(1).collect()),
Move::Predicate(expression) => Err(ReadError::Predicate {
expression: expression.clone(),
}),
Move::Resolve { .. } => Ok(cursors),
}
}
fn member<'tree>(
cursor: &Cursor<'tree>,
element: &str,
key: &str,
repeats: bool,
next: &mut Vec<Cursor<'tree>>,
) -> Result<(), ReadError> {
let object = cursor.value.as_object().ok_or_else(|| ReadError::Shape {
element: String::from(element),
expected: "an object",
found: json_kind(cursor.value),
})?;
let Some(value) = object.get(key) else {
return Ok(());
};
if !repeats {
if value.as_array().is_some() {
return Err(ReadError::Shape {
element: String::from(element),
expected: "a single value",
found: json_kind(value),
});
}
next.push(Cursor {
value,
occurrence: cursor.occurrence.clone(),
alternative: None,
});
return Ok(());
}
let items = value.as_array().ok_or_else(|| ReadError::Shape {
element: String::from(element),
expected: "an array",
found: json_kind(value),
})?;
for (index, item) in items.iter().enumerate() {
if item.is_null() {
continue;
}
next.push(cursor.indexed(item, index));
}
Ok(())
}
fn alternative(
cursor: &Cursor<'_>,
element: &str,
stem: &str,
schema: &'static FieldSchema,
) -> Result<Option<(&'static str, Kind)>, ReadError> {
let object = cursor.value.as_object().ok_or_else(|| ReadError::Shape {
element: String::from(element),
expected: "an object",
found: json_kind(cursor.value),
})?;
let mut found: Option<(&'static str, Kind)> = None;
for form in schema.choices() {
let (suffix, kind) = (form.suffix, form.kind);
let key = format!("{stem}{suffix}");
if !object.contains_key(&key) {
continue;
}
if let Some((first, _)) = found {
return Err(ReadError::AmbiguousChoice {
element: String::from(element),
first: format!("{stem}{first}"),
second: key,
});
}
found = Some((suffix, kind));
}
Ok(found)
}
fn extension<'tree>(
cursor: &Cursor<'tree>,
element: &str,
key: &str,
url: &str,
next: &mut Vec<Cursor<'tree>>,
) -> Result<(), ReadError> {
let object = cursor.value.as_object().ok_or_else(|| ReadError::Shape {
element: String::from(element),
expected: "an object",
found: json_kind(cursor.value),
})?;
let Some(value) = object.get(key) else {
return Ok(());
};
let items = value.as_array().ok_or_else(|| ReadError::Shape {
element: String::from(element),
expected: "an array",
found: json_kind(value),
})?;
let mut position = 0usize;
for item in items {
if item.get("url").and_then(Value::as_str) != Some(url) {
continue;
}
next.push(cursor.indexed(item, position));
position = position.saturating_add(1);
}
Ok(())
}