use std::ops::Range;
use crate::parsers::error::Error;
pub(crate) const MAX_NESTING_DEPTH: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Node<'a> {
pub start: usize,
pub end: usize,
pub closed: bool,
pub kind: Kind<'a>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Kind<'a> {
Atom(&'a str),
List(Vec<Node<'a>>),
}
#[derive(Debug)]
pub(crate) struct Forest<'a> {
pub nodes: Vec<Node<'a>>,
pub unbalanced: Option<Error>,
pub comments: Vec<Range<usize>>,
}
pub(crate) fn read(input: &str) -> Result<Forest<'_>, Error> {
let bytes = input.as_bytes();
let mut open: Vec<(usize, Vec<Node>)> = Vec::new();
let mut top = Vec::new();
let mut comments = Vec::new();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b if b.is_ascii_whitespace() => i += 1,
b';' => {
let start = i;
while i < bytes.len() && bytes[i] != b'\n' && bytes[i] != b'\r' {
i += 1;
}
comments.push(start..i);
}
b'(' => {
if open.len() == MAX_NESTING_DEPTH {
return Err(Error::at(i, 1).reason("nesting too deep").fatal());
}
open.push((i, Vec::new()));
i += 1;
}
b')' => {
let Some((start, children)) = open.pop() else {
let unbalanced = Some(Error::at(i, 1));
return Ok(Forest {
nodes: top,
unbalanced,
comments,
});
};
let node = Node {
start,
end: i,
closed: true,
kind: Kind::List(children),
};
open.last_mut().map_or(&mut top, |(_, c)| c).push(node);
i += 1;
}
_ => {
let start = i;
let in_atom: fn(u8) -> bool = if is_operator(bytes[i]) {
is_operator
} else {
|b| !is_delimiter(b) && b != b'?' && b != b':'
};
i += 1;
while i < bytes.len() && in_atom(bytes[i]) {
i += 1;
}
let node = Node {
start,
end: i,
closed: true,
kind: Kind::Atom(&input[start..i]),
};
open.last_mut().map_or(&mut top, |(_, c)| c).push(node);
}
}
}
let unbalanced = open.last().map(|(innermost, _)| {
let mut error = Error::at(input.len(), 0).reason("expected `)`");
error.unclosed = Some(*innermost);
match innermost_keyword(&open) {
Some(keyword) => error.keyword(keyword.to_ascii_lowercase()),
None => error,
}
});
while let Some((start, children)) = open.pop() {
let node = Node {
start,
end: input.len(),
closed: false,
kind: Kind::List(children),
};
open.last_mut().map_or(&mut top, |(_, c)| c).push(node);
}
Ok(Forest {
nodes: top,
unbalanced,
comments,
})
}
fn innermost_keyword<'a>(open: &[(usize, Vec<Node<'a>>)]) -> Option<&'a str> {
open.iter()
.rev()
.find_map(|(_, children)| match children.first() {
Some(Node {
kind: Kind::Atom(head),
..
}) if head.starts_with(':') => Some(*head),
_ => None,
})
}
const fn is_operator(b: u8) -> bool {
matches!(b, b'+' | b'-' | b'*' | b'/' | b'<' | b'>' | b'=')
}
const fn is_delimiter(b: u8) -> bool {
b.is_ascii_whitespace() || matches!(b, b'(' | b')' | b';')
}
impl<'a> Node<'a> {
#[must_use]
pub fn atom(&self) -> Option<&'a str> {
match self.kind {
Kind::Atom(text) => Some(text),
Kind::List(_) => None,
}
}
#[must_use]
pub fn is(&self, word: &str) -> bool {
self.atom().is_some_and(|a| a.eq_ignore_ascii_case(word))
}
#[must_use]
pub fn children(&self) -> Option<&[Node<'a>]> {
match &self.kind {
Kind::List(children) => Some(children),
Kind::Atom(_) => None,
}
}
#[must_use]
pub fn head(&self) -> Option<&'a str> {
self.children()?.first()?.atom()
}
pub(crate) fn error(&self) -> Error {
let end = match &self.kind {
Kind::Atom(_) => self.end,
Kind::List(children) => match children.first() {
Some(
first @ Node {
kind: Kind::Atom(_),
..
},
) => first.end,
_ => self.start + 1,
},
};
Error::at(self.start, end - self.start)
}
pub(crate) fn error_at_close(&self) -> Error {
Error {
unclosed: (!self.closed).then_some(self.start),
..Error::at(self.end, usize::from(self.closed))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use assert2::check;
fn shape(nodes: &[Node]) -> String {
nodes
.iter()
.map(|n| match &n.kind {
Kind::Atom(a) => (*a).to_string(),
Kind::List(c) => format!("[{}]", shape(c)),
})
.collect::<Vec<_>>()
.join(" ")
}
#[test]
fn reads_atoms_lists_and_comments() {
let input = "(a ?b(c) ; (not this)\r\n :d-e 1.5)x;end";
let forest = read(input).unwrap();
check!(shape(&forest.nodes) == "[a ?b [c] :d-e 1.5] x");
check!(forest.unbalanced.is_none());
let comments: Vec<_> = forest.comments.iter().map(|c| &input[c.clone()]).collect();
check!(comments == ["; (not this)", ";end"]);
}
#[test]
fn operators_need_no_space_after_them() {
let forest = read("(+x 1) (-x) (>=(f) 1) (=a b) (?a -t) (a-b ?c-d)").unwrap();
check!(shape(&forest.nodes) == "[+ x 1] [- x] [>= [f] 1] [= a b] [?a - t] [a-b ?c-d]");
}
#[test]
fn a_question_mark_or_colon_starts_a_new_atom() {
let forest = read("(on?x ?y?z ?duration :requirements:strips)").unwrap();
check!(shape(&forest.nodes) == "[on ?x ?y ?z ?duration :requirements :strips]");
}
#[test]
fn positions_cover_atoms_and_parentheses() {
let forest = read(" (ab (c))").unwrap();
let outer = &forest.nodes[0];
check!((outer.start, outer.end) == (1, 8));
let inner = &outer.children().unwrap()[1];
check!((inner.start, inner.end) == (5, 7));
let atom = &outer.children().unwrap()[0];
check!((atom.start, atom.end) == (2, 4));
}
#[test]
fn unclosed_lists_end_at_the_end_of_input() {
let forest = read("(:action a (p)").unwrap();
check!(shape(&forest.nodes) == "[:action a [p]]");
let error = forest.unbalanced.unwrap();
check!(error.offset == 14);
check!(error.keyword.as_deref() == Some(":action"));
check!(error.reason == Some("expected `)`"));
}
#[test]
fn reading_stops_at_a_stray_close() {
let forest = read("(a)) (b)").unwrap();
check!(shape(&forest.nodes) == "[a]");
check!(forest.unbalanced.unwrap().offset == 3);
}
#[test]
fn nesting_is_limited() {
let ok = "(".repeat(MAX_NESTING_DEPTH) + &")".repeat(MAX_NESTING_DEPTH);
check!(read(&ok).is_ok());
let deep = "(".repeat(MAX_NESTING_DEPTH + 1);
let error = read(&deep).unwrap_err();
check!(error.offset == MAX_NESTING_DEPTH);
check!(error.reason == Some("nesting too deep"));
}
}