Variable assignment implemented

This commit is contained in:
Erin 2021-05-03 09:54:27 +02:00 committed by ondra05
parent 8c6f415ac9
commit 29bf01935c
3 changed files with 22 additions and 1 deletions

View file

@ -75,6 +75,11 @@ pub enum Stmt {
Loop { Loop {
body: Vec<Item>, body: Vec<Item>,
}, },
VarAssignment {
iden: Iden,
value: Expr,
},
Break, Break,
HopBack, HopBack,
Print(Expr), Print(Expr),

View file

@ -69,6 +69,7 @@ impl<'a> Parser<'a> {
| Token::String(_) | Token::String(_)
| Token::Nul | Token::Nul
| Token::LeftParenthesis | Token::LeftParenthesis
| Token::Assignment
| Token::LogNot => self.parse_ops(token), | Token::LogNot => self.parse_ops(token),
// Control flow // Control flow

View file

@ -38,6 +38,7 @@ impl<'a> Parser<'a> {
Some(Token::OpNeq) => self.cmpneq(buf)?, Some(Token::OpNeq) => self.cmpneq(buf)?,
Some(Token::LogAnd) => self.logand(buf)?, Some(Token::LogAnd) => self.logand(buf)?,
Some(Token::LogOr) => self.logor(buf)?, Some(Token::LogOr) => self.logor(buf)?,
Some(Token::Assignment) => return self.set_variable(buf),
Some(Token::Print) => { Some(Token::Print) => {
self.lexer.next(); self.lexer.next();
self.require(Token::Semicolon)?; self.require(Token::Semicolon)?;
@ -62,8 +63,22 @@ impl<'a> Parser<'a> {
logor => Or; logor => Or;
} }
fn set_variable(&mut self, iden: Expr) -> ParseResult {
self.lexer.next();
if let Expr::Identifier(iden) = iden {
let next = self.lexer.next();
let value = self.parse_expr(next)?;
self.require(Token::Semicolon)?;
Ok(Stmt::VarAssignment { iden, value }.into())
} else {
Err(Error {
kind: ErrorKind::InvalidIdentifier,
position: self.lexer.span(),
})
}
}
/// Ensure that input token is an expression /// Ensure that input token is an expression
pub(super) fn parse_expr(&mut self, token: Option<Token>) -> ExprResult { fn parse_expr(&mut self, token: Option<Token>) -> ExprResult {
let token = token.ok_or(Error { let token = token.ok_or(Error {
kind: ErrorKind::EndOfTokenStream, kind: ErrorKind::EndOfTokenStream,
position: self.lexer.span(), position: self.lexer.span(),