use core::fmt;
use core::num::NonZeroUsize;
use core::str::FromStr;
use crate::tree::error::AnchorError;
use crate::tree::error::ParseError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Head {
Resource,
FhirRoot,
Parent(NonZeroUsize),
Anchor,
}
impl fmt::Display for Head {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Resource => f.write_str("$resource"),
Self::FhirRoot => f.write_str("$fhirRoot"),
Self::Parent(hops) => {
for _ in 0..hops.get() {
f.write_str("^")?;
}
Ok(())
}
Self::Anchor => Ok(()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TypeForm {
OfType,
As,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ordinal {
First,
Last,
}
impl fmt::Display for Ordinal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::First => f.write_str("first()"),
Self::Last => f.write_str("last()"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Step {
Element {
name: String,
},
Type {
name: String,
form: TypeForm,
},
Extension {
url: String,
},
Resolve,
Ordinal(Ordinal),
Index(usize),
Predicate {
expression: String,
},
}
impl fmt::Display for Step {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Element { name } => f.write_str(name),
Self::Type {
name,
form: TypeForm::OfType,
} => write!(f, "ofType({name})"),
Self::Type {
name,
form: TypeForm::As,
} => write!(f, "as({name})"),
Self::Extension { url } => write!(f, "extension('{url}')"),
Self::Resolve => f.write_str("resolve()"),
Self::Ordinal(ordinal) => write!(f, "{ordinal}"),
Self::Index(index) => write!(f, "[{index}]"),
Self::Predicate { expression } => write!(f, "where({expression})"),
}
}
}
impl Step {
const fn read_only(&self) -> Option<&'static str> {
match self {
Self::Predicate { .. } => {
Some("is a predicate over the values a document already holds")
}
Self::Ordinal(_) => Some("picks one of the values a document already holds"),
Self::Index(_) => Some("picks one position of the values a document already holds"),
Self::Resolve => Some("names a resource the engine resolves, not an element to set"),
Self::Element { .. } | Self::Type { .. } | Self::Extension { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Writability {
Writable,
ReadOnly {
step: String,
reason: &'static str,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FhirPath {
text: String,
head: Head,
steps: Vec<Step>,
writability: Writability,
}
impl FhirPath {
#[must_use]
pub fn as_str(&self) -> &str {
&self.text
}
#[must_use]
pub const fn head(&self) -> Head {
self.head
}
#[must_use]
pub fn steps(&self) -> &[Step] {
&self.steps
}
#[must_use]
pub const fn writability(&self) -> &Writability {
&self.writability
}
pub fn anchored(&self, anchor: &Self) -> Result<Self, AnchorError> {
if self.head == Head::Resource {
return Ok(self.clone());
}
if anchor.head != Head::Resource {
return Err(AnchorError::RelativeAnchor {
anchor: anchor.text.clone(),
});
}
let hops = match self.head {
Head::Parent(hops) => hops.get(),
Head::Resource | Head::FhirRoot | Head::Anchor => 0,
};
let kept =
anchor
.steps
.len()
.checked_sub(hops)
.ok_or_else(|| AnchorError::AboveResource {
expression: self.text.clone(),
anchor: anchor.text.clone(),
hops,
})?;
let mut steps: Vec<Step> = anchor.steps.iter().take(kept).cloned().collect();
steps.extend(self.steps.iter().cloned());
Ok(Self::assembled(Head::Resource, steps))
}
#[must_use]
pub fn rooted_at(&self, root: &Self) -> Option<Self> {
if self.head != Head::Resource || root.head != Head::Resource {
return None;
}
let mut steps = root.steps.clone();
steps.extend(self.steps.iter().cloned());
Some(Self::assembled(Head::Resource, steps))
}
pub fn anchored_in(&self, anchors: &[&Self]) -> Result<(Self, usize), AnchorError> {
if self.head == Head::Resource {
return Ok((self.clone(), 0));
}
let requested = match self.head {
Head::Parent(count) => count.get(),
Head::Resource | Head::FhirRoot | Head::Anchor => 0,
};
let mut hops = requested;
for (index, anchor) in anchors.iter().enumerate() {
if anchor.head != Head::Resource {
return Err(AnchorError::RelativeAnchor {
anchor: anchor.text.clone(),
});
}
if let Some(kept) = anchor.steps.len().checked_sub(hops) {
let mut steps: Vec<Step> = anchor.steps.iter().take(kept).cloned().collect();
steps.extend(self.steps.iter().cloned());
return Ok((Self::assembled(Head::Resource, steps), index));
}
hops = hops.saturating_sub(anchor.steps.len());
}
let outermost = anchors
.last()
.map_or_else(String::new, |anchor| anchor.text.clone());
Err(AnchorError::AboveResource {
expression: self.text.clone(),
anchor: outermost,
hops: requested,
})
}
fn assembled(head: Head, steps: Vec<Step>) -> Self {
let writability = classify(&steps);
let text = render(head, &steps);
Self {
text,
head,
steps,
writability,
}
}
}
impl fmt::Display for FhirPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl FromStr for FhirPath {
type Err = ParseError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let mut scanner = Scanner {
text,
at: 0usize,
steps: Vec::new(),
};
let head = scanner.head()?;
scanner.tail(head)?;
let steps = scanner.steps;
let writability = classify(&steps);
Ok(Self {
text: String::from(text),
head,
steps,
writability,
})
}
}
fn render(head: Head, steps: &[Step]) -> String {
let mut text = head.to_string();
for step in steps {
if matches!(step, Step::Index(_)) {
text.push_str(&step.to_string());
continue;
}
if !text.is_empty() {
text.push('.');
}
text.push_str(&step.to_string());
}
text
}
fn classify(steps: &[Step]) -> Writability {
for step in steps {
if let Some(reason) = step.read_only() {
return Writability::ReadOnly {
step: step.to_string(),
reason,
};
}
}
Writability::Writable
}
struct Scanner<'a> {
text: &'a str,
at: usize,
steps: Vec<Step>,
}
impl<'a> Scanner<'a> {
fn rest(&self) -> &'a str {
self.text.get(self.at..).unwrap_or_default()
}
fn peek(&self) -> Option<char> {
self.rest().chars().next()
}
fn bump(&mut self) -> Option<char> {
let next = self.peek()?;
self.at = self.at.saturating_add(next.len_utf8());
Some(next)
}
fn eat(&mut self, wanted: char) -> bool {
if self.peek() == Some(wanted) {
self.at = self.at.saturating_add(wanted.len_utf8());
return true;
}
false
}
fn expect(&mut self, wanted: char, expected: &'static str) -> Result<(), ParseError> {
if self.eat(wanted) {
return Ok(());
}
Err(self.expected(expected))
}
fn expected(&self, expected: &'static str) -> ParseError {
let found = self
.peek()
.map_or_else(|| String::from("<end of input>"), String::from);
ParseError::Expected {
expected,
found,
at: self.at,
}
}
fn take_while(&mut self, accept: impl Fn(char) -> bool) -> &'a str {
let start = self.at;
while self.peek().is_some_and(&accept) {
let _consumed = self.bump();
}
self.text.get(start..self.at).unwrap_or_default()
}
fn head(&mut self) -> Result<Head, ParseError> {
if self.text.is_empty() {
return Err(ParseError::Empty);
}
if self.peek() == Some('$') {
return self.variable();
}
if self.peek() == Some('^') {
let start = self.at;
let carets = self.take_while(|c| c == '^').chars().count();
let hops = NonZeroUsize::new(carets).ok_or(ParseError::Expected {
expected: "a `^` parent operator",
found: String::from("^"),
at: start,
})?;
return Ok(Head::Parent(hops));
}
self.step()?;
Ok(Head::Anchor)
}
fn variable(&mut self) -> Result<Head, ParseError> {
let start = self.at;
let _dollar = self.bump();
let name = self.take_while(char::is_alphanumeric);
match name {
"resource" => Ok(Head::Resource),
"fhirRoot" => Ok(Head::FhirRoot),
_ => Err(ParseError::UnknownVariable {
name: String::from(name),
at: start,
}),
}
}
fn tail(&mut self, head: Head) -> Result<(), ParseError> {
if head != Head::Anchor && self.peek().is_some() {
self.expect('.', "`.` or the end of the expression")?;
self.step()?;
}
while self.peek().is_some() {
self.expect('.', "`.` or the end of the expression")?;
self.step()?;
}
Ok(())
}
fn step(&mut self) -> Result<(), ParseError> {
let start = self.at;
let name = self.take_while(|c| c.is_alphanumeric() || c == '_');
if name.is_empty() {
return Err(self.expected("an element name or a path function"));
}
if self.eat('(') {
let step = self.call(name, start)?;
self.steps.push(step);
return Ok(());
}
self.steps.push(Step::Element {
name: String::from(name),
});
self.index(start)
}
fn index(&mut self, start: usize) -> Result<(), ParseError> {
if !self.eat('[') {
return Ok(());
}
let digits = self.take_while(|c| c.is_ascii_digit());
self.expect(']', "`]`")?;
let index = digits.parse().map_err(|_error| ParseError::Index {
text: String::from(digits),
at: start,
})?;
self.steps.push(Step::Index(index));
Ok(())
}
fn call(&mut self, name: &str, start: usize) -> Result<Step, ParseError> {
match name {
"ofType" => self.type_filter(TypeForm::OfType),
"as" => self.type_filter(TypeForm::As),
"extension" => {
let url = self.string()?;
self.expect(')', "`)`")?;
Ok(Step::Extension { url })
}
"resolve" => {
self.expect(')', "`)`")?;
Ok(Step::Resolve)
}
"first" => {
self.expect(')', "`)`")?;
Ok(Step::Ordinal(Ordinal::First))
}
"last" => {
self.expect(')', "`)`")?;
Ok(Step::Ordinal(Ordinal::Last))
}
"where" => {
let expression = self.balanced(name, start)?;
Ok(Step::Predicate { expression })
}
_ => Err(ParseError::UnknownFunction {
name: String::from(name),
at: start,
}),
}
}
fn type_filter(&mut self, form: TypeForm) -> Result<Step, ParseError> {
let mut name;
loop {
let segment = self.take_while(|c| c.is_alphanumeric() || c == '_');
if segment.is_empty() {
return Err(self.expected("a type name"));
}
name = String::from(segment);
if !self.eat('.') {
break;
}
}
self.expect(')', "`)`")?;
Ok(Step::Type { name, form })
}
fn string(&mut self) -> Result<String, ParseError> {
let start = self.at;
if !self.eat('\'') {
return Err(self.expected("a string literal in single quotes"));
}
let mut text = String::new();
loop {
let Some(next) = self.bump() else {
return Err(ParseError::UnterminatedString { at: start });
};
match next {
'\'' => return Ok(text),
'\\' => text.push(self.escape()?),
other => text.push(other),
}
}
}
fn escape(&mut self) -> Result<char, ParseError> {
let at = self.at.saturating_sub(1);
let Some(next) = self.bump() else {
return Err(ParseError::UnterminatedString { at });
};
match next {
'\'' | '"' | '`' | '\\' | '/' => Ok(next),
'r' => Ok('\r'),
'n' => Ok('\n'),
't' => Ok('\t'),
'f' => Ok('\u{c}'),
other => Err(ParseError::InvalidEscape { escape: other, at }),
}
}
fn balanced(&mut self, name: &str, start: usize) -> Result<String, ParseError> {
let opened = self.at;
let mut depth = 1usize;
loop {
let Some(next) = self.bump() else {
return Err(ParseError::UnterminatedCall {
name: String::from(name),
at: start,
});
};
match next {
'(' => depth = depth.saturating_add(1),
')' => {
depth = depth.saturating_sub(1);
if depth == 0 {
let end = self.at.saturating_sub(1);
let text = self.text.get(opened..end).unwrap_or_default();
return Ok(String::from(text));
}
}
'\'' => {
self.at = self.at.saturating_sub(1);
let _literal = self.string()?;
}
_ => {}
}
}
}
}