use std::fmt;
use std::num::NonZeroUsize;
use std::str::FromStr;
use f_office_xml::{Document, NodeId};
use super::EditFault;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Path {
steps: Vec<Step>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Step {
name: QualifiedName,
test: Option<Test>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct QualifiedName {
prefix: Option<String>,
local: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Test {
Position(NonZeroUsize),
Attribute {
name: QualifiedName,
value: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathError {
Empty,
LeadingSlash,
Name {
step: usize,
},
Test {
step: usize,
},
Zero {
step: usize,
},
}
impl fmt::Display for PathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str("the path is empty: name the steps below the root element, such as w:body/w:p[3]"),
Self::LeadingSlash => f.write_str(
"the path starts with '/': start it with the step below the root element, such as w:body/w:p[3]",
),
Self::Name { step } => write!(
f,
"step {step} of the path has no valid name: write prefix:local or local"
),
Self::Test { step } => write!(
f,
"step {step} of the path has a test that does not read: write [N] or [@prefix:name='value']"
),
Self::Zero { step } => write!(
f,
"step {step} of the path has the position 0: positions count from 1"
),
}
}
}
impl std::error::Error for PathError {}
impl FromStr for Path {
type Err = PathError;
fn from_str(text: &str) -> Result<Self, PathError> {
if text.is_empty() {
return Err(PathError::Empty);
}
if text.starts_with('/') {
return Err(PathError::LeadingSlash);
}
let steps = split_steps(text)
.into_iter()
.enumerate()
.map(|(index, step)| parse_step(step, index + 1))
.collect::<Result<Vec<Step>, PathError>>()?;
Ok(Self { steps })
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, step) in self.steps.iter().enumerate() {
if index > 0 {
f.write_str("/")?;
}
write!(f, "{}", step.name)?;
match &step.test {
Some(Test::Position(position)) => write!(f, "[{position}]")?,
Some(Test::Attribute { name, value }) => {
let quote = if value.contains('\'') { '"' } else { '\'' };
write!(f, "[@{name}={quote}{value}{quote}]")?;
}
None => {}
}
}
Ok(())
}
}
impl fmt::Display for QualifiedName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.prefix {
Some(prefix) => write!(f, "{prefix}:{}", self.local),
None => f.write_str(&self.local),
}
}
}
fn split_steps(text: &str) -> Vec<&str> {
let mut steps = Vec::new();
let (mut start, mut quote, mut in_test) = (0, None, false);
for (at, character) in text.char_indices() {
match (character, quote) {
('\'' | '"', None) if in_test => quote = Some(character),
(_, Some(open)) if character == open => quote = None,
('[', None) => in_test = true,
(']', None) => in_test = false,
('/', None) if !in_test => {
steps.push(text.get(start..at).unwrap_or_default());
start = at + 1;
}
_ => {}
}
}
steps.push(text.get(start..).unwrap_or_default());
steps
}
fn parse_step(text: &str, step: usize) -> Result<Step, PathError> {
let (name, choice) = match text.split_once('[') {
Some((name, bracketed)) => {
let inner = bracketed
.strip_suffix(']')
.ok_or(PathError::Test { step })?;
(name, Some(parse_test(inner, step)?))
}
None => (text, None),
};
let name = parse_name(name).ok_or(PathError::Name { step })?;
Ok(Step { name, test: choice })
}
fn parse_test(inner: &str, step: usize) -> Result<Test, PathError> {
if let Some(attribute) = inner.strip_prefix('@') {
let (name, quoted) = attribute.split_once('=').ok_or(PathError::Test { step })?;
let name = parse_name(name).ok_or(PathError::Test { step })?;
let mut characters = quoted.chars();
let quote = characters
.next()
.filter(|quote| matches!(quote, '\'' | '"'))
.ok_or(PathError::Test { step })?;
let value = characters
.as_str()
.strip_suffix(quote)
.filter(|value| !value.contains(quote))
.ok_or(PathError::Test { step })?;
return Ok(Test::Attribute {
name,
value: value.to_owned(),
});
}
if inner.is_empty() || !inner.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(PathError::Test { step });
}
let position: usize = inner.parse().map_err(|_| PathError::Test { step })?;
NonZeroUsize::new(position)
.map(Test::Position)
.ok_or(PathError::Zero { step })
}
fn parse_name(text: &str) -> Option<QualifiedName> {
let part = |part: &str| {
let valid = !part.is_empty()
&& part
.chars()
.all(|c| !c.is_whitespace() && !"/[]:@='\"<>&".contains(c));
valid.then(|| part.to_owned())
};
match text.split_once(':') {
Some((prefix, local)) => Some(QualifiedName {
prefix: Some(part(prefix)?),
local: part(local)?,
}),
None => Some(QualifiedName {
prefix: None,
local: part(text)?,
}),
}
}
impl Path {
#[must_use]
pub fn len(&self) -> usize {
self.steps.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
pub(super) fn resolve(&self, document: &Document) -> Result<(NodeId, NodeId), EditFault> {
let root = document.root().map_err(EditFault::PartNotXml)?;
let (mut at, mut parent) = (root, root);
for (index, step) in self.steps.iter().enumerate() {
let number = index + 1;
let uri = resolve_prefix(document, root, step.name.prefix.as_deref(), true)?;
let matching: Vec<NodeId> = document
.child_elements(at)
.filter(|&child| has_name(document, child, uri, &step.name.local))
.collect();
let picked: Vec<NodeId> = match &step.test {
Some(Test::Position(position)) => matching
.get(position.get() - 1)
.copied()
.into_iter()
.collect(),
Some(Test::Attribute { name, value }) => {
let namespace = resolve_prefix(document, root, name.prefix.as_deref(), false)?;
matching
.into_iter()
.filter(|&child| {
document.attribute(child, namespace, &name.local)
== Some(value.as_str())
})
.collect()
}
None => matching,
};
parent = at;
at = match picked.as_slice() {
[one] => *one,
[] => return Err(EditFault::NoElement { step: number }),
many => {
return Err(EditFault::Ambiguous {
step: number,
count: many.len(),
});
}
};
}
Ok((at, parent))
}
}
fn resolve_prefix<'d>(
document: &'d Document,
root: NodeId,
prefix: Option<&str>,
element: bool,
) -> Result<Option<&'d str>, EditFault> {
match prefix {
Some(prefix) => document
.prefix_namespace(root, prefix)
.map(Some)
.ok_or_else(|| EditFault::UndeclaredPathPrefix(prefix.to_owned())),
None if element => Ok(document.prefix_namespace(root, "")),
None => Ok(None),
}
}
fn has_name(document: &Document, id: NodeId, uri: Option<&str>, local: &str) -> bool {
match uri {
Some(uri) => document.is(id, uri, local),
None => document
.element(id)
.is_some_and(|element| element.name.namespace.is_none() && element.name.local == local),
}
}