1use std::fmt::{self, Write as _};
7use std::str::FromStr;
8
9use icedwright_types::Role;
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::error::Error;
13
14#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub enum Segment {
17 Role {
19 role: Role,
21 name: Option<String>,
23 index: u32,
25 },
26 TestId {
28 id: String,
30 index: u32,
32 },
33}
34
35impl Segment {
36 pub(crate) fn same_key(&self, other: &Segment) -> bool {
37 match (self, other) {
38 (
39 Segment::Role { role, name, .. },
40 Segment::Role {
41 role: other_role,
42 name: other_name,
43 ..
44 },
45 ) => role == other_role && name == other_name,
46 (Segment::TestId { id, .. }, Segment::TestId { id: other, .. }) => id == other,
47 _ => false,
48 }
49 }
50
51 pub(crate) fn set_index(&mut self, value: u32) {
52 match self {
53 Segment::Role { index, .. } | Segment::TestId { index, .. } => *index = value,
54 }
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
60pub struct NodePath {
61 segments: Vec<Segment>,
62}
63
64impl NodePath {
65 #[must_use]
67 pub fn new(segments: Vec<Segment>) -> Self {
68 Self { segments }
69 }
70
71 #[must_use]
73 pub fn segments(&self) -> &[Segment] {
74 &self.segments
75 }
76
77 #[must_use]
79 pub fn child(&self, segment: Segment) -> Self {
80 let mut segments = self.segments.clone();
81 segments.push(segment);
82 Self { segments }
83 }
84
85 #[must_use]
87 pub fn starts_with(&self, other: &NodePath) -> bool {
88 self.segments.starts_with(&other.segments)
89 }
90}
91
92pub(crate) fn write_quoted(out: &mut impl fmt::Write, text: &str) -> fmt::Result {
93 out.write_char('"')?;
94 for c in text.chars() {
95 match c {
96 '"' => out.write_str("\\\"")?,
97 '\\' => out.write_str("\\\\")?,
98 '\n' => out.write_str("\\n")?,
99 '\t' => out.write_str("\\t")?,
100 '\r' => out.write_str("\\r")?,
101 c if c.is_control() => write!(out, "\\u{{{:x}}}", u32::from(c))?,
102 c => out.write_char(c)?,
103 }
104 }
105 out.write_char('"')
106}
107
108fn is_bare_id(id: &str) -> bool {
109 !id.is_empty()
110 && id
111 .chars()
112 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
113}
114
115impl fmt::Display for Segment {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 let index = match self {
118 Segment::Role { role, name, index } => {
119 f.write_str(role.selector_name())?;
120 if let Some(name) = name {
121 f.write_char(' ')?;
122 write_quoted(f, name)?;
123 }
124 *index
125 }
126 Segment::TestId { id, index } => {
127 f.write_char('#')?;
128 if is_bare_id(id) {
129 f.write_str(id)?;
130 } else {
131 write_quoted(f, id)?;
132 }
133 *index
134 }
135 };
136 if index > 0 {
137 write!(f, "[{index}]")?;
138 }
139 Ok(())
140 }
141}
142
143impl fmt::Display for NodePath {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 for (i, segment) in self.segments.iter().enumerate() {
146 if i > 0 {
147 f.write_str(" / ")?;
148 }
149 segment.fmt(f)?;
150 }
151 Ok(())
152 }
153}
154
155pub(crate) struct Cursor<'a> {
157 pub(crate) input: &'a str,
158 pub(crate) offset: usize,
159}
160
161impl<'a> Cursor<'a> {
162 pub(crate) fn new(input: &'a str) -> Self {
163 Self { input, offset: 0 }
164 }
165
166 pub(crate) fn rest(&self) -> &'a str {
167 self.input.get(self.offset..).unwrap_or_default()
168 }
169
170 pub(crate) fn peek(&self) -> Option<char> {
171 self.rest().chars().next()
172 }
173
174 pub(crate) fn eat(&mut self, prefix: &str) -> bool {
175 if self.rest().starts_with(prefix) {
176 self.offset += prefix.len();
177 return true;
178 }
179 false
180 }
181
182 pub(crate) fn take_while(&mut self, keep: impl Fn(char) -> bool) -> &'a str {
183 let rest = self.rest();
184 let end = rest.find(|c: char| !keep(c)).unwrap_or(rest.len());
185 self.offset += end;
186 rest.get(..end).unwrap_or_default()
187 }
188
189 pub(crate) fn quoted(&mut self) -> Result<String, (usize, String)> {
191 let start = self.offset;
192 if !self.eat("\"") {
193 return Err((start, "expected `\"`".to_owned()));
194 }
195 let mut out = String::new();
196 loop {
197 let Some(c) = self.peek() else {
198 return Err((start, "unterminated string".to_owned()));
199 };
200 self.offset += c.len_utf8();
201 match c {
202 '"' => return Ok(out),
203 '\\' => out.push(self.escape()?),
204 c => out.push(c),
205 }
206 }
207 }
208
209 fn escape(&mut self) -> Result<char, (usize, String)> {
210 let at = self.offset.saturating_sub(1);
211 let Some(c) = self.peek() else {
212 return Err((at, "unterminated escape".to_owned()));
213 };
214 self.offset += c.len_utf8();
215 match c {
216 '"' => Ok('"'),
217 '\\' => Ok('\\'),
218 'n' => Ok('\n'),
219 't' => Ok('\t'),
220 'r' => Ok('\r'),
221 'u' if !self.rest().starts_with('{') => {
222 let hex = self.rest().get(..4).unwrap_or_default();
223 let code = hex
224 .chars()
225 .all(|c| c.is_ascii_hexdigit())
226 .then(|| u32::from_str_radix(hex, 16).ok())
227 .flatten()
228 .and_then(char::from_u32)
229 .ok_or((at, "expected `{` or four hex digits after `\\u`".to_owned()))?;
230 self.offset += 4;
231 Ok(code)
232 }
233 'u' => {
234 self.eat("{");
235 let hex = self.take_while(|c| c.is_ascii_hexdigit());
236 if !self.eat("}") {
237 return Err((at, "expected `}` to end `\\u{..}`".to_owned()));
238 }
239 u32::from_str_radix(hex, 16)
240 .ok()
241 .and_then(char::from_u32)
242 .ok_or((at, format!("`\\u{{{hex}}}` is not a character")))
243 }
244 other => Err((at, format!("unknown escape `\\{other}`"))),
245 }
246 }
247}
248
249fn parse_index(cursor: &mut Cursor<'_>) -> Result<u32, (usize, String)> {
250 if !cursor.eat("[") {
251 return Ok(0);
252 }
253 let at = cursor.offset;
254 let digits = cursor.take_while(|c| c.is_ascii_digit());
255 let index = digits
256 .parse::<u32>()
257 .map_err(|_| (at, "expected a sibling index".to_owned()))?;
258 if !cursor.eat("]") {
259 return Err((cursor.offset, "expected `]`".to_owned()));
260 }
261 Ok(index)
262}
263
264fn parse_segment(cursor: &mut Cursor<'_>) -> Result<Segment, (usize, String)> {
265 if cursor.eat("#") {
266 let id = if cursor.peek() == Some('"') {
267 cursor.quoted()?
268 } else {
269 let at = cursor.offset;
270 let id = cursor.take_while(|c| {
271 c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-')
272 });
273 if id.is_empty() {
274 return Err((at, "expected a test id after `#`".to_owned()));
275 }
276 id.to_owned()
277 };
278 let index = parse_index(cursor)?;
279 return Ok(Segment::TestId { id, index });
280 }
281 let at = cursor.offset;
282 let word = cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
283 let role = Role::from_selector_name(word).ok_or((at, format!("unknown role `{word}`")))?;
284 let name = if cursor.eat(" \"") {
285 cursor.offset -= 1;
286 Some(cursor.quoted()?)
287 } else {
288 None
289 };
290 let index = parse_index(cursor)?;
291 Ok(Segment::Role { role, name, index })
292}
293
294impl FromStr for NodePath {
295 type Err = Error;
296
297 fn from_str(input: &str) -> Result<Self, Error> {
298 let mut cursor = Cursor::new(input);
299 let mut segments = Vec::new();
300 let fail = |(offset, message): (usize, String)| Error::Path {
301 input: input.to_owned(),
302 offset,
303 message,
304 };
305 if input.is_empty() {
306 return Ok(NodePath::default());
307 }
308 loop {
309 segments.push(parse_segment(&mut cursor).map_err(fail)?);
310 if cursor.rest().is_empty() {
311 return Ok(NodePath { segments });
312 }
313 if !cursor.eat(" / ") {
314 return Err(fail((cursor.offset, "expected ` / `".to_owned())));
315 }
316 }
317 }
318}
319
320impl Serialize for NodePath {
321 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
322 serializer.collect_str(self)
323 }
324}
325
326impl<'de> Deserialize<'de> for NodePath {
327 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
328 let text = String::deserialize(deserializer)?;
329 text.parse().map_err(serde::de::Error::custom)
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 fn role(role: Role, name: Option<&str>, index: u32) -> Segment {
338 Segment::Role {
339 role,
340 name: name.map(str::to_owned),
341 index,
342 }
343 }
344
345 #[test]
346 fn paths_print_as_the_plan_shows_and_parse_back() -> Result<(), Error> {
347 let path = NodePath::new(vec![
348 role(Role::Window, Some("Todo"), 0),
349 Segment::TestId {
350 id: "todo-list".to_owned(),
351 index: 0,
352 },
353 role(Role::ListItem, Some("Buy milk"), 0),
354 role(Role::Button, Some("Delete"), 0),
355 ]);
356 let text = r#"window "Todo" / #todo-list / listitem "Buy milk" / button "Delete""#;
357 assert_eq!(path.to_string(), text);
358 assert_eq!(text.parse::<NodePath>()?, path);
359
360 let indexed = r#"window "Todo" / list / listitem[2]"#;
361 assert_eq!(indexed.parse::<NodePath>()?.to_string(), indexed);
362 Ok(())
363 }
364
365 #[test]
366 fn awkward_names_and_ids_round_trip() -> Result<(), Error> {
367 let path = NodePath::new(vec![
368 role(Role::Window, Some("a / \"b\" \\ c\n"), 1),
369 Segment::TestId {
370 id: "Has Space".to_owned(),
371 index: 2,
372 },
373 role(Role::Text, Some("\u{1}"), 0),
374 ]);
375 let text = path.to_string();
376 assert_eq!(text.parse::<NodePath>()?, path, "{text}");
377 Ok(())
378 }
379
380 #[test]
381 fn bad_paths_report_the_offset() {
382 for (input, offset) in [
383 ("window \"x", 7),
384 ("buton", 0),
385 ("window / #", 10),
386 ("window[x]", 7),
387 ("window \"x\"/list", 10),
388 ] {
389 match input.parse::<NodePath>() {
390 Err(Error::Path { offset: at, .. }) => assert_eq!(at, offset, "{input}"),
391 other => panic!("{input}: {other:?}"),
392 }
393 }
394 }
395
396 #[test]
397 fn serde_uses_the_display_form() -> Result<(), serde_json::Error> {
398 let path = NodePath::new(vec![role(Role::Window, Some("Todo"), 0)]);
399 let json = serde_json::to_string(&path)?;
400 assert_eq!(json, r#""window \"Todo\"""#);
401 assert_eq!(serde_json::from_str::<NodePath>(&json)?, path);
402 Ok(())
403 }
404}