Moved Assignable creation functions

This commit is contained in:
Erin 2021-10-21 20:51:24 +02:00 committed by ondra05
parent 610ba7fc40
commit bcd446c5d1
2 changed files with 34 additions and 31 deletions

View file

@ -50,6 +50,39 @@ pub enum AssignableKind {
Index { indices: Vec<Expr> }, Index { indices: Vec<Expr> },
} }
impl Assignable {
pub fn from_expr(expr: Expr) -> Result<Assignable, ()> {
match expr.kind {
ExprKind::Variable(ident) => Ok(Assignable {
ident: Ident::new(ident, expr.span),
kind: AssignableKind::Variable,
}),
ExprKind::Index { expr, index } => Self::from_index(*expr, *index),
_ => Err(()),
}
}
fn from_index(mut buf: Expr, index: Expr) -> Result<Assignable, ()> {
let mut indices = vec![index];
let ident = loop {
match buf.kind {
ExprKind::Variable(ident) => break ident,
ExprKind::Index { expr, index } => {
indices.push(*index);
buf = *expr;
}
_ => return Err(()),
}
};
indices.reverse();
Ok(Assignable {
ident: Ident::new(ident, buf.span),
kind: AssignableKind::Index { indices },
})
}
}
#[derive(Debug, PartialEq, Clone, Hash)] #[derive(Debug, PartialEq, Clone, Hash)]
pub struct Block { pub struct Block {
pub block: Vec<Stmt>, pub block: Vec<Stmt>,

View file

@ -355,16 +355,7 @@ impl<'source> Parser<'source> {
// Variable Assignment // Variable Assignment
Token::Equal => { Token::Equal => {
let assignable = buf.take().and_then(|buf| match buf.kind { if let Some(Ok(assignable)) = buf.take().map(Assignable::from_expr) {
ExprKind::Variable(ident) => Some(Assignable {
ident: Ident::new(ident, buf.span),
kind: AssignableKind::Variable,
}),
ExprKind::Index { expr, index } => self.cart_assignable_flow(*expr, *index),
_ => None,
});
if let Some(assignable) = assignable {
break StmtKind::Assign { break StmtKind::Assign {
assignable, assignable,
value: self.expr_flow(Token::Semicolon)?, value: self.expr_flow(Token::Semicolon)?,
@ -395,27 +386,6 @@ impl<'source> Parser<'source> {
Ok(r) Ok(r)
} }
/// Parse Cart Assignable flow
fn cart_assignable_flow(&mut self, mut buf: Expr, index: Expr) -> Option<Assignable> {
let mut indices = vec![index];
let ident = loop {
match buf.kind {
ExprKind::Variable(ident) => break ident,
ExprKind::Index { expr, index } => {
indices.push(*index);
buf = *expr;
}
_ => return None,
}
};
indices.reverse();
Some(Assignable {
ident: Ident::new(ident, buf.span),
kind: AssignableKind::Index { indices },
})
}
/// Parse If flow /// Parse If flow
/// ///
/// Consists of condition and block, there is no else /// Consists of condition and block, there is no else