use cas_error::Error;
use crate::parser::{
ast::expr::Expr,
fmt::Latex,
keyword::While as WhileToken,
Parse,
Parser,
};
use std::{fmt, ops::Range};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct While {
pub condition: Box<Expr>,
pub body: Box<Expr>,
pub span: Range<usize>,
pub while_span: Range<usize>,
}
impl While {
pub fn span(&self) -> Range<usize> {
self.span.clone()
}
}
impl<'source> Parse<'source> for While {
fn std_parse(
input: &mut Parser<'source>,
recoverable_errors: &mut Vec<Error>
) -> Result<Self, Vec<Error>> {
let while_token = input.try_parse::<WhileToken>().forward_errors(recoverable_errors)?;
let condition = input.try_parse::<Expr>().forward_errors(recoverable_errors)?;
let then_body = input.try_parse_with_state::<_, Expr>(|state| {
state.allow_then = true;
state.allow_loop_control = true;
}).forward_errors(recoverable_errors)?;
let span = while_token.span.start..then_body.span().end;
Ok(Self {
condition: Box::new(condition),
body: Box::new(then_body),
span,
while_span: while_token.span,
})
}
}
impl std::fmt::Display for While {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "while {} {}", self.condition, self.body)
}
}
impl Latex for While {
fn fmt_latex(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\\text{{while }}")?;
self.condition.fmt_latex(f)?;
self.body.fmt_latex(f)?;
Ok(())
}
}