Skip to main content

f_office/edit/
path.rs

1//! The path of a raw edit: where one element lies in an XML part, by the steps from the part's
2//! root element down to it.
3
4use std::fmt;
5use std::num::NonZeroUsize;
6use std::str::FromStr;
7
8use f_office_xml::{Document, NodeId};
9
10use super::EditFault;
11
12/// Where one element of an XML part lies: steps from the part's root element down, each the
13/// name of a child element with an optional test, such as `w:body/w:p[3]` or
14/// `w:style[@w:styleId='Heading1']`.
15///
16/// - A step names a child element by its qualified name. The prefix resolves with the
17///   namespace declarations of the part's root element, and an element matches by its
18///   namespace URI and local name, so a part that uses another prefix for the same URI still
19///   matches. A name without a prefix takes the root element's default namespace, if it has
20///   one.
21/// - `[N]` picks the child at the place `N` among the child elements that match the step's
22///   name, counted from 1, as in the XML Path Language and as in the addresses of
23///   `foffice read`; other children do not count.
24/// - `[@name='value']` picks the one matching child whose attribute `name` has the value
25///   `value`, with `'` or `"` as the quote. An attribute name without a prefix has no
26///   namespace, as in XML.
27/// - Without a test, the step must match exactly one child.
28///
29/// The root element itself is not a step, so a path never names it.
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct Path {
32    /// The steps, from the root element's children down.
33    steps: Vec<Step>,
34}
35
36/// One step of a [`Path`].
37#[derive(Clone, Debug, PartialEq, Eq)]
38struct Step {
39    /// The name of the child element.
40    name: QualifiedName,
41    /// Which of the matching children the step picks.
42    test: Option<Test>,
43}
44
45/// A name as a path writes it.
46#[derive(Clone, Debug, PartialEq, Eq)]
47struct QualifiedName {
48    /// The prefix, if any.
49    prefix: Option<String>,
50    /// The local name.
51    local: String,
52}
53
54/// Which of the children that match a step's name the step picks.
55#[derive(Clone, Debug, PartialEq, Eq)]
56enum Test {
57    /// The child at this place among them, from 1.
58    Position(NonZeroUsize),
59    /// The one child whose attribute has this value.
60    Attribute {
61        /// The attribute's name.
62        name: QualifiedName,
63        /// Its value.
64        value: String,
65    },
66}
67
68/// Why a text is not a [`Path`]. A step counts from 1.
69#[derive(Clone, Debug, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum PathError {
72    /// The text is empty.
73    Empty,
74    /// The text starts with `/`.
75    LeadingSlash,
76    /// A step has no name, or a name with a character that a name does not hold.
77    Name {
78        /// The step.
79        step: usize,
80    },
81    /// A step's test is neither `[N]` nor `[@name='value']`.
82    Test {
83        /// The step.
84        step: usize,
85    },
86    /// A step's position is 0, and positions count from 1.
87    Zero {
88        /// The step.
89        step: usize,
90    },
91}
92
93impl fmt::Display for PathError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            Self::Empty => f.write_str("the path is empty: name the steps below the root element, such as w:body/w:p[3]"),
97            Self::LeadingSlash => f.write_str(
98                "the path starts with '/': start it with the step below the root element, such as w:body/w:p[3]",
99            ),
100            Self::Name { step } => write!(
101                f,
102                "step {step} of the path has no valid name: write prefix:local or local"
103            ),
104            Self::Test { step } => write!(
105                f,
106                "step {step} of the path has a test that does not read: write [N] or [@prefix:name='value']"
107            ),
108            Self::Zero { step } => write!(
109                f,
110                "step {step} of the path has the position 0: positions count from 1"
111            ),
112        }
113    }
114}
115
116impl std::error::Error for PathError {}
117
118impl FromStr for Path {
119    type Err = PathError;
120
121    fn from_str(text: &str) -> Result<Self, PathError> {
122        if text.is_empty() {
123            return Err(PathError::Empty);
124        }
125        if text.starts_with('/') {
126            return Err(PathError::LeadingSlash);
127        }
128        let steps = split_steps(text)
129            .into_iter()
130            .enumerate()
131            .map(|(index, step)| parse_step(step, index + 1))
132            .collect::<Result<Vec<Step>, PathError>>()?;
133        Ok(Self { steps })
134    }
135}
136
137impl fmt::Display for Path {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        for (index, step) in self.steps.iter().enumerate() {
140            if index > 0 {
141                f.write_str("/")?;
142            }
143            write!(f, "{}", step.name)?;
144            match &step.test {
145                Some(Test::Position(position)) => write!(f, "[{position}]")?,
146                Some(Test::Attribute { name, value }) => {
147                    let quote = if value.contains('\'') { '"' } else { '\'' };
148                    write!(f, "[@{name}={quote}{value}{quote}]")?;
149                }
150                None => {}
151            }
152        }
153        Ok(())
154    }
155}
156
157impl fmt::Display for QualifiedName {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        match &self.prefix {
160            Some(prefix) => write!(f, "{prefix}:{}", self.local),
161            None => f.write_str(&self.local),
162        }
163    }
164}
165
166/// The steps of `text`, split at each `/` outside a test.
167fn split_steps(text: &str) -> Vec<&str> {
168    let mut steps = Vec::new();
169    let (mut start, mut quote, mut in_test) = (0, None, false);
170    for (at, character) in text.char_indices() {
171        match (character, quote) {
172            ('\'' | '"', None) if in_test => quote = Some(character),
173            (_, Some(open)) if character == open => quote = None,
174            ('[', None) => in_test = true,
175            (']', None) => in_test = false,
176            ('/', None) if !in_test => {
177                steps.push(text.get(start..at).unwrap_or_default());
178                start = at + 1;
179            }
180            _ => {}
181        }
182    }
183    steps.push(text.get(start..).unwrap_or_default());
184    steps
185}
186
187/// The step `text`, which is step `step` of its path.
188fn parse_step(text: &str, step: usize) -> Result<Step, PathError> {
189    let (name, choice) = match text.split_once('[') {
190        Some((name, bracketed)) => {
191            let inner = bracketed
192                .strip_suffix(']')
193                .ok_or(PathError::Test { step })?;
194            (name, Some(parse_test(inner, step)?))
195        }
196        None => (text, None),
197    };
198    let name = parse_name(name).ok_or(PathError::Name { step })?;
199    Ok(Step { name, test: choice })
200}
201
202/// The test `inner`, between the brackets of step `step`.
203fn parse_test(inner: &str, step: usize) -> Result<Test, PathError> {
204    if let Some(attribute) = inner.strip_prefix('@') {
205        let (name, quoted) = attribute.split_once('=').ok_or(PathError::Test { step })?;
206        let name = parse_name(name).ok_or(PathError::Test { step })?;
207        let mut characters = quoted.chars();
208        let quote = characters
209            .next()
210            .filter(|quote| matches!(quote, '\'' | '"'))
211            .ok_or(PathError::Test { step })?;
212        let value = characters
213            .as_str()
214            .strip_suffix(quote)
215            .filter(|value| !value.contains(quote))
216            .ok_or(PathError::Test { step })?;
217        return Ok(Test::Attribute {
218            name,
219            value: value.to_owned(),
220        });
221    }
222    if inner.is_empty() || !inner.bytes().all(|byte| byte.is_ascii_digit()) {
223        return Err(PathError::Test { step });
224    }
225    let position: usize = inner.parse().map_err(|_| PathError::Test { step })?;
226    NonZeroUsize::new(position)
227        .map(Test::Position)
228        .ok_or(PathError::Zero { step })
229}
230
231/// The name `text`: `prefix:local` or `local`, each part without a character that a path uses
232/// or a name does not hold.
233fn parse_name(text: &str) -> Option<QualifiedName> {
234    let part = |part: &str| {
235        let valid = !part.is_empty()
236            && part
237                .chars()
238                .all(|c| !c.is_whitespace() && !"/[]:@='\"<>&".contains(c));
239        valid.then(|| part.to_owned())
240    };
241    match text.split_once(':') {
242        Some((prefix, local)) => Some(QualifiedName {
243            prefix: Some(part(prefix)?),
244            local: part(local)?,
245        }),
246        None => Some(QualifiedName {
247            prefix: None,
248            local: part(text)?,
249        }),
250    }
251}
252
253impl Path {
254    /// The number of steps.
255    #[must_use]
256    pub fn len(&self) -> usize {
257        self.steps.len()
258    }
259
260    /// Whether the path has no step, which a parsed path never is.
261    #[must_use]
262    pub fn is_empty(&self) -> bool {
263        self.steps.is_empty()
264    }
265
266    /// The element of `document` that the path names, with its parent.
267    pub(super) fn resolve(&self, document: &Document) -> Result<(NodeId, NodeId), EditFault> {
268        let root = document.root().map_err(EditFault::PartNotXml)?;
269        let (mut at, mut parent) = (root, root);
270        for (index, step) in self.steps.iter().enumerate() {
271            let number = index + 1;
272            let uri = resolve_prefix(document, root, step.name.prefix.as_deref(), true)?;
273            let matching: Vec<NodeId> = document
274                .child_elements(at)
275                .filter(|&child| has_name(document, child, uri, &step.name.local))
276                .collect();
277            let picked: Vec<NodeId> = match &step.test {
278                Some(Test::Position(position)) => matching
279                    .get(position.get() - 1)
280                    .copied()
281                    .into_iter()
282                    .collect(),
283                Some(Test::Attribute { name, value }) => {
284                    let namespace = resolve_prefix(document, root, name.prefix.as_deref(), false)?;
285                    matching
286                        .into_iter()
287                        .filter(|&child| {
288                            document.attribute(child, namespace, &name.local)
289                                == Some(value.as_str())
290                        })
291                        .collect()
292                }
293                None => matching,
294            };
295            parent = at;
296            at = match picked.as_slice() {
297                [one] => *one,
298                [] => return Err(EditFault::NoElement { step: number }),
299                many => {
300                    return Err(EditFault::Ambiguous {
301                        step: number,
302                        count: many.len(),
303                    });
304                }
305            };
306        }
307        Ok((at, parent))
308    }
309}
310
311/// The namespace URI of `prefix` at the root element `root`: the root's default namespace for
312/// an element name without a prefix (`element`), and none for an attribute name without one.
313fn resolve_prefix<'d>(
314    document: &'d Document,
315    root: NodeId,
316    prefix: Option<&str>,
317    element: bool,
318) -> Result<Option<&'d str>, EditFault> {
319    match prefix {
320        Some(prefix) => document
321            .prefix_namespace(root, prefix)
322            .map(Some)
323            .ok_or_else(|| EditFault::UndeclaredPathPrefix(prefix.to_owned())),
324        None if element => Ok(document.prefix_namespace(root, "")),
325        None => Ok(None),
326    }
327}
328
329/// Whether the element `id` has the namespace URI `uri` and the local name `local`.
330fn has_name(document: &Document, id: NodeId, uri: Option<&str>, local: &str) -> bool {
331    match uri {
332        Some(uri) => document.is(id, uri, local),
333        None => document
334            .element(id)
335            .is_some_and(|element| element.name.namespace.is_none() && element.name.local == local),
336    }
337}