use std::fmt::{self, Write as _};
use std::str::FromStr;
use icedwright_types::Role;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::error::Error;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Segment {
Role {
role: Role,
name: Option<String>,
index: u32,
},
TestId {
id: String,
index: u32,
},
}
impl Segment {
pub(crate) fn same_key(&self, other: &Segment) -> bool {
match (self, other) {
(
Segment::Role { role, name, .. },
Segment::Role {
role: other_role,
name: other_name,
..
},
) => role == other_role && name == other_name,
(Segment::TestId { id, .. }, Segment::TestId { id: other, .. }) => id == other,
_ => false,
}
}
pub(crate) fn set_index(&mut self, value: u32) {
match self {
Segment::Role { index, .. } | Segment::TestId { index, .. } => *index = value,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct NodePath {
segments: Vec<Segment>,
}
impl NodePath {
#[must_use]
pub fn new(segments: Vec<Segment>) -> Self {
Self { segments }
}
#[must_use]
pub fn segments(&self) -> &[Segment] {
&self.segments
}
#[must_use]
pub fn child(&self, segment: Segment) -> Self {
let mut segments = self.segments.clone();
segments.push(segment);
Self { segments }
}
#[must_use]
pub fn starts_with(&self, other: &NodePath) -> bool {
self.segments.starts_with(&other.segments)
}
}
pub(crate) fn write_quoted(out: &mut impl fmt::Write, text: &str) -> fmt::Result {
out.write_char('"')?;
for c in text.chars() {
match c {
'"' => out.write_str("\\\"")?,
'\\' => out.write_str("\\\\")?,
'\n' => out.write_str("\\n")?,
'\t' => out.write_str("\\t")?,
'\r' => out.write_str("\\r")?,
c if c.is_control() => write!(out, "\\u{{{:x}}}", u32::from(c))?,
c => out.write_char(c)?,
}
}
out.write_char('"')
}
fn is_bare_id(id: &str) -> bool {
!id.is_empty()
&& id
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
}
impl fmt::Display for Segment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let index = match self {
Segment::Role { role, name, index } => {
f.write_str(role.selector_name())?;
if let Some(name) = name {
f.write_char(' ')?;
write_quoted(f, name)?;
}
*index
}
Segment::TestId { id, index } => {
f.write_char('#')?;
if is_bare_id(id) {
f.write_str(id)?;
} else {
write_quoted(f, id)?;
}
*index
}
};
if index > 0 {
write!(f, "[{index}]")?;
}
Ok(())
}
}
impl fmt::Display for NodePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, segment) in self.segments.iter().enumerate() {
if i > 0 {
f.write_str(" / ")?;
}
segment.fmt(f)?;
}
Ok(())
}
}
pub(crate) struct Cursor<'a> {
pub(crate) input: &'a str,
pub(crate) offset: usize,
}
impl<'a> Cursor<'a> {
pub(crate) fn new(input: &'a str) -> Self {
Self { input, offset: 0 }
}
pub(crate) fn rest(&self) -> &'a str {
self.input.get(self.offset..).unwrap_or_default()
}
pub(crate) fn peek(&self) -> Option<char> {
self.rest().chars().next()
}
pub(crate) fn eat(&mut self, prefix: &str) -> bool {
if self.rest().starts_with(prefix) {
self.offset += prefix.len();
return true;
}
false
}
pub(crate) fn take_while(&mut self, keep: impl Fn(char) -> bool) -> &'a str {
let rest = self.rest();
let end = rest.find(|c: char| !keep(c)).unwrap_or(rest.len());
self.offset += end;
rest.get(..end).unwrap_or_default()
}
pub(crate) fn quoted(&mut self) -> Result<String, (usize, String)> {
let start = self.offset;
if !self.eat("\"") {
return Err((start, "expected `\"`".to_owned()));
}
let mut out = String::new();
loop {
let Some(c) = self.peek() else {
return Err((start, "unterminated string".to_owned()));
};
self.offset += c.len_utf8();
match c {
'"' => return Ok(out),
'\\' => out.push(self.escape()?),
c => out.push(c),
}
}
}
fn escape(&mut self) -> Result<char, (usize, String)> {
let at = self.offset.saturating_sub(1);
let Some(c) = self.peek() else {
return Err((at, "unterminated escape".to_owned()));
};
self.offset += c.len_utf8();
match c {
'"' => Ok('"'),
'\\' => Ok('\\'),
'n' => Ok('\n'),
't' => Ok('\t'),
'r' => Ok('\r'),
'u' if !self.rest().starts_with('{') => {
let hex = self.rest().get(..4).unwrap_or_default();
let code = hex
.chars()
.all(|c| c.is_ascii_hexdigit())
.then(|| u32::from_str_radix(hex, 16).ok())
.flatten()
.and_then(char::from_u32)
.ok_or((at, "expected `{` or four hex digits after `\\u`".to_owned()))?;
self.offset += 4;
Ok(code)
}
'u' => {
self.eat("{");
let hex = self.take_while(|c| c.is_ascii_hexdigit());
if !self.eat("}") {
return Err((at, "expected `}` to end `\\u{..}`".to_owned()));
}
u32::from_str_radix(hex, 16)
.ok()
.and_then(char::from_u32)
.ok_or((at, format!("`\\u{{{hex}}}` is not a character")))
}
other => Err((at, format!("unknown escape `\\{other}`"))),
}
}
}
fn parse_index(cursor: &mut Cursor<'_>) -> Result<u32, (usize, String)> {
if !cursor.eat("[") {
return Ok(0);
}
let at = cursor.offset;
let digits = cursor.take_while(|c| c.is_ascii_digit());
let index = digits
.parse::<u32>()
.map_err(|_| (at, "expected a sibling index".to_owned()))?;
if !cursor.eat("]") {
return Err((cursor.offset, "expected `]`".to_owned()));
}
Ok(index)
}
fn parse_segment(cursor: &mut Cursor<'_>) -> Result<Segment, (usize, String)> {
if cursor.eat("#") {
let id = if cursor.peek() == Some('"') {
cursor.quoted()?
} else {
let at = cursor.offset;
let id = cursor.take_while(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-')
});
if id.is_empty() {
return Err((at, "expected a test id after `#`".to_owned()));
}
id.to_owned()
};
let index = parse_index(cursor)?;
return Ok(Segment::TestId { id, index });
}
let at = cursor.offset;
let word = cursor.take_while(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'));
let role = Role::from_selector_name(word).ok_or((at, format!("unknown role `{word}`")))?;
let name = if cursor.eat(" \"") {
cursor.offset -= 1;
Some(cursor.quoted()?)
} else {
None
};
let index = parse_index(cursor)?;
Ok(Segment::Role { role, name, index })
}
impl FromStr for NodePath {
type Err = Error;
fn from_str(input: &str) -> Result<Self, Error> {
let mut cursor = Cursor::new(input);
let mut segments = Vec::new();
let fail = |(offset, message): (usize, String)| Error::Path {
input: input.to_owned(),
offset,
message,
};
if input.is_empty() {
return Ok(NodePath::default());
}
loop {
segments.push(parse_segment(&mut cursor).map_err(fail)?);
if cursor.rest().is_empty() {
return Ok(NodePath { segments });
}
if !cursor.eat(" / ") {
return Err(fail((cursor.offset, "expected ` / `".to_owned())));
}
}
}
}
impl Serialize for NodePath {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for NodePath {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn role(role: Role, name: Option<&str>, index: u32) -> Segment {
Segment::Role {
role,
name: name.map(str::to_owned),
index,
}
}
#[test]
fn paths_print_as_the_plan_shows_and_parse_back() -> Result<(), Error> {
let path = NodePath::new(vec![
role(Role::Window, Some("Todo"), 0),
Segment::TestId {
id: "todo-list".to_owned(),
index: 0,
},
role(Role::ListItem, Some("Buy milk"), 0),
role(Role::Button, Some("Delete"), 0),
]);
let text = r#"window "Todo" / #todo-list / listitem "Buy milk" / button "Delete""#;
assert_eq!(path.to_string(), text);
assert_eq!(text.parse::<NodePath>()?, path);
let indexed = r#"window "Todo" / list / listitem[2]"#;
assert_eq!(indexed.parse::<NodePath>()?.to_string(), indexed);
Ok(())
}
#[test]
fn awkward_names_and_ids_round_trip() -> Result<(), Error> {
let path = NodePath::new(vec![
role(Role::Window, Some("a / \"b\" \\ c\n"), 1),
Segment::TestId {
id: "Has Space".to_owned(),
index: 2,
},
role(Role::Text, Some("\u{1}"), 0),
]);
let text = path.to_string();
assert_eq!(text.parse::<NodePath>()?, path, "{text}");
Ok(())
}
#[test]
fn bad_paths_report_the_offset() {
for (input, offset) in [
("window \"x", 7),
("buton", 0),
("window / #", 10),
("window[x]", 7),
("window \"x\"/list", 10),
] {
match input.parse::<NodePath>() {
Err(Error::Path { offset: at, .. }) => assert_eq!(at, offset, "{input}"),
other => panic!("{input}: {other:?}"),
}
}
}
#[test]
fn serde_uses_the_display_form() -> Result<(), serde_json::Error> {
let path = NodePath::new(vec![role(Role::Window, Some("Todo"), 0)]);
let json = serde_json::to_string(&path)?;
assert_eq!(json, r#""window \"Todo\"""#);
assert_eq!(serde_json::from_str::<NodePath>(&json)?, path);
Ok(())
}
}