use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;
use crate::atom::lower;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Plan {
steps: Vec<PlanStep>,
}
impl Plan {
#[must_use]
pub const fn new(steps: Vec<PlanStep>) -> Self {
Self { steps }
}
#[must_use]
pub fn steps(&self) -> &[PlanStep] {
&self.steps
}
#[must_use]
pub fn len(&self) -> usize {
self.steps.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
}
impl FromIterator<PlanStep> for Plan {
fn from_iter<T: IntoIterator<Item = PlanStep>>(iter: T) -> Self {
Self::new(iter.into_iter().collect())
}
}
impl FromStr for Plan {
type Err = PlanError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Scanner::new(text).plan()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PlanStep {
action: String,
arguments: Vec<String>,
line: usize,
time: Option<f64>,
duration: Option<f64>,
}
impl PlanStep {
#[must_use]
pub fn new<S, I, A>(action: S, arguments: I) -> Self
where
S: AsRef<str>,
I: IntoIterator<Item = A>,
A: AsRef<str>,
{
Self {
action: lower(action.as_ref()),
arguments: arguments.into_iter().map(|a| lower(a.as_ref())).collect(),
line: 0,
time: None,
duration: None,
}
}
#[must_use]
pub const fn at(mut self, time: f64) -> Self {
self.time = Some(time);
self
}
#[must_use]
pub const fn lasting(mut self, duration: f64) -> Self {
self.duration = Some(duration);
self
}
#[must_use]
pub const fn time(&self) -> Option<f64> {
self.time
}
#[must_use]
pub const fn duration(&self) -> Option<f64> {
self.duration
}
#[must_use]
pub fn action(&self) -> &str {
&self.action
}
#[must_use]
pub fn arguments(&self) -> &[String] {
&self.arguments
}
#[must_use]
pub const fn line(&self) -> usize {
self.line
}
}
impl fmt::Display for PlanStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}", self.action)?;
for argument in &self.arguments {
write!(f, " {argument}")?;
}
f.write_str(")")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlanError {
pub line: usize,
pub column: usize,
pub kind: PlanErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlanErrorKind {
Unclosed,
Unopened,
Nested,
EmptyStep,
UnexpectedText(String),
DanglingTimestamp,
MalformedDuration,
InvalidNumber(String),
}
impl fmt::Display for PlanError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "line {}, column {}: ", self.line, self.column)?;
match &self.kind {
PlanErrorKind::Unclosed => f.write_str("`(` is never closed"),
PlanErrorKind::Unopened => f.write_str("`)` has no matching `(`"),
PlanErrorKind::Nested => f.write_str("a step cannot contain `(`"),
PlanErrorKind::EmptyStep => f.write_str("a step needs an action name"),
PlanErrorKind::UnexpectedText(text) => {
write!(f, "unexpected `{text}` outside a step")
}
PlanErrorKind::DanglingTimestamp => f.write_str("a timestamp needs a step after it"),
PlanErrorKind::MalformedDuration => {
f.write_str("a duration is one number in `[` and `]`")
}
PlanErrorKind::InvalidNumber(text) => {
write!(f, "`{text}` is not a finite, non-negative number")
}
}
}
}
impl core::error::Error for PlanError {}
#[derive(Debug, Clone, Copy)]
struct Position {
line: usize,
column: usize,
}
struct Scanner<'t> {
chars: core::iter::Peekable<core::str::Chars<'t>>,
at: Position,
}
impl<'t> Scanner<'t> {
fn new(text: &'t str) -> Self {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
Self {
chars: text.chars().peekable(),
at: Position { line: 1, column: 1 },
}
}
fn plan(mut self) -> Result<Plan, PlanError> {
let mut steps = Vec::new();
while let Some(c) = self.skip_blank() {
let start = self.at;
match c {
'(' => {
self.bump();
let step = self.step(start)?;
steps.push(self.duration(step)?);
}
')' => return Err(error(start, PlanErrorKind::Unopened)),
_ => {
let time = self.timestamp(start)?;
let at = self.at;
if self.skip_blank() != Some('(') {
return Err(error(at, PlanErrorKind::DanglingTimestamp));
}
let step_start = self.at;
self.bump();
let step = self.step(step_start)?.at(time);
steps.push(self.duration(step)?);
}
}
}
Ok(Plan::new(steps))
}
fn timestamp(&mut self, start: Position) -> Result<f64, PlanError> {
let mut word = self.word();
if word.is_empty() {
word.extend(self.chars.next());
}
let Some(number) = word.strip_suffix(':') else {
return Err(error(start, PlanErrorKind::UnexpectedText(word)));
};
number_at(start, number)
}
fn duration(&mut self, step: PlanStep) -> Result<PlanStep, PlanError> {
if self.skip_blank() != Some('[') {
return Ok(step);
}
let start = self.at;
self.bump();
if self.skip_blank().is_none() {
return Err(error(start, PlanErrorKind::MalformedDuration));
}
let number_start = self.at;
let word = self.word();
let duration = number_at(number_start, &word)?;
if self.skip_blank() != Some(']') {
return Err(error(start, PlanErrorKind::MalformedDuration));
}
self.bump();
Ok(step.lasting(duration))
}
fn step(&mut self, start: Position) -> Result<PlanStep, PlanError> {
let mut names = Vec::new();
loop {
match self.skip_blank() {
None => return Err(error(start, PlanErrorKind::Unclosed)),
Some(')') => {
self.bump();
break;
}
Some('(') => return Err(error(self.at, PlanErrorKind::Nested)),
Some(c @ ('[' | ']')) => {
let kind = PlanErrorKind::UnexpectedText(String::from(c));
return Err(error(self.at, kind));
}
Some(_) => names.push(lower(&self.word())),
}
}
let mut names = names.into_iter();
let action = names
.next()
.ok_or_else(|| error(start, PlanErrorKind::EmptyStep))?;
Ok(PlanStep {
action,
arguments: names.collect(),
line: start.line,
time: None,
duration: None,
})
}
fn skip_blank(&mut self) -> Option<char> {
loop {
let c = *self.chars.peek()?;
if c == ';' {
while self.chars.peek().is_some_and(|&c| c != '\n' && c != '\r') {
self.bump();
}
} else if c.is_whitespace() {
self.bump();
} else {
return Some(c);
}
}
}
fn word(&mut self) -> String {
let mut word = String::new();
while let Some(&c) = self.chars.peek() {
if c.is_whitespace() || matches!(c, '(' | ')' | ';' | '[' | ']') {
break;
}
word.push(c);
self.bump();
}
word
}
fn bump(&mut self) {
match self.chars.next() {
Some('\r') if self.chars.peek() == Some(&'\n') => {}
Some('\n' | '\r') => {
self.at.line += 1;
self.at.column = 1;
}
Some(_) => self.at.column += 1,
None => {}
}
}
}
const fn error(at: Position, kind: PlanErrorKind) -> PlanError {
PlanError {
line: at.line,
column: at.column,
kind,
}
}
fn number_at(at: Position, text: &str) -> Result<f64, PlanError> {
match text.parse::<f64>() {
Ok(value) if value.is_finite() && value >= 0.0 => Ok(value),
_ => Err(error(at, PlanErrorKind::InvalidNumber(String::from(text)))),
}
}