1use std::fmt;
5use std::num::NonZeroUsize;
6use std::str::FromStr;
7
8use f_office_xml::{Document, NodeId};
9
10use super::EditFault;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct Path {
32 steps: Vec<Step>,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38struct Step {
39 name: QualifiedName,
41 test: Option<Test>,
43}
44
45#[derive(Clone, Debug, PartialEq, Eq)]
47struct QualifiedName {
48 prefix: Option<String>,
50 local: String,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
56enum Test {
57 Position(NonZeroUsize),
59 Attribute {
61 name: QualifiedName,
63 value: String,
65 },
66}
67
68#[derive(Clone, Debug, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum PathError {
72 Empty,
74 LeadingSlash,
76 Name {
78 step: usize,
80 },
81 Test {
83 step: usize,
85 },
86 Zero {
88 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
166fn 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
187fn 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
202fn 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
231fn 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 #[must_use]
256 pub fn len(&self) -> usize {
257 self.steps.len()
258 }
259
260 #[must_use]
262 pub fn is_empty(&self) -> bool {
263 self.steps.is_empty()
264 }
265
266 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
311fn 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
329fn 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}