f-office 0.2.2

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! The path of a raw edit: where one element lies in an XML part, by the steps from the part's
//! root element down to it.

use std::fmt;
use std::num::NonZeroUsize;
use std::str::FromStr;

use f_office_xml::{Document, NodeId};

use super::EditFault;

/// Where one element of an XML part lies: steps from the part's root element down, each the
/// name of a child element with an optional test, such as `w:body/w:p[3]` or
/// `w:style[@w:styleId='Heading1']`.
///
/// - A step names a child element by its qualified name. The prefix resolves with the
///   namespace declarations of the part's root element, and an element matches by its
///   namespace URI and local name, so a part that uses another prefix for the same URI still
///   matches. A name without a prefix takes the root element's default namespace, if it has
///   one.
/// - `[N]` picks the child at the place `N` among the child elements that match the step's
///   name, counted from 1, as in the XML Path Language and as in the addresses of
///   `foffice read`; other children do not count.
/// - `[@name='value']` picks the one matching child whose attribute `name` has the value
///   `value`, with `'` or `"` as the quote. An attribute name without a prefix has no
///   namespace, as in XML.
/// - Without a test, the step must match exactly one child.
///
/// The root element itself is not a step, so a path never names it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Path {
    /// The steps, from the root element's children down.
    steps: Vec<Step>,
}

/// One step of a [`Path`].
#[derive(Clone, Debug, PartialEq, Eq)]
struct Step {
    /// The name of the child element.
    name: QualifiedName,
    /// Which of the matching children the step picks.
    test: Option<Test>,
}

/// A name as a path writes it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct QualifiedName {
    /// The prefix, if any.
    prefix: Option<String>,
    /// The local name.
    local: String,
}

/// Which of the children that match a step's name the step picks.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Test {
    /// The child at this place among them, from 1.
    Position(NonZeroUsize),
    /// The one child whose attribute has this value.
    Attribute {
        /// The attribute's name.
        name: QualifiedName,
        /// Its value.
        value: String,
    },
}

/// Why a text is not a [`Path`]. A step counts from 1.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PathError {
    /// The text is empty.
    Empty,
    /// The text starts with `/`.
    LeadingSlash,
    /// A step has no name, or a name with a character that a name does not hold.
    Name {
        /// The step.
        step: usize,
    },
    /// A step's test is neither `[N]` nor `[@name='value']`.
    Test {
        /// The step.
        step: usize,
    },
    /// A step's position is 0, and positions count from 1.
    Zero {
        /// The step.
        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),
        }
    }
}

/// The steps of `text`, split at each `/` outside a test.
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
}

/// The step `text`, which is step `step` of its path.
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 })
}

/// The test `inner`, between the brackets of step `step`.
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 })
}

/// The name `text`: `prefix:local` or `local`, each part without a character that a path uses
/// or a name does not hold.
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 {
    /// The number of steps.
    #[must_use]
    pub fn len(&self) -> usize {
        self.steps.len()
    }

    /// Whether the path has no step, which a parsed path never is.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.steps.is_empty()
    }

    /// The element of `document` that the path names, with its parent.
    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))
    }
}

/// The namespace URI of `prefix` at the root element `root`: the root's default namespace for
/// an element name without a prefix (`element`), and none for an attribute name without one.
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),
    }
}

/// Whether the element `id` has the namespace URI `uri` and the local name `local`.
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),
    }
}