From c0ecf5f2a3572a3529738deed339429d9d4138c7 Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 3 May 2021 09:54:27 +0200 Subject: [PATCH] Variable assignment implemented --- src/parser/item.rs | 5 +++++ src/parser/mod.rs | 1 + src/parser/ops.rs | 17 ++++++++++++++++- 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/parser/item.rs b/src/parser/item.rs index 2e229680..c6b7caf0 100644 --- a/src/parser/item.rs +++ b/src/parser/item.rs @@ -75,6 +75,11 @@ pub enum Stmt { Loop { body: Vec, }, + + VarAssignment { + iden: Iden, + value: Expr, + }, Break, HopBack, Print(Expr), diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 1fbeb680..5e8aa298 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -69,6 +69,7 @@ impl<'a> Parser<'a> { | Token::String(_) | Token::Nul | Token::LeftParenthesis + | Token::Assignment | Token::LogNot => self.parse_ops(token), // Control flow diff --git a/src/parser/ops.rs b/src/parser/ops.rs index a8104ca6..84970765 100644 --- a/src/parser/ops.rs +++ b/src/parser/ops.rs @@ -38,6 +38,7 @@ impl<'a> Parser<'a> { Some(Token::OpNeq) => self.cmpneq(buf)?, Some(Token::LogAnd) => self.logand(buf)?, Some(Token::LogOr) => self.logor(buf)?, + Some(Token::Assignment) => return self.set_variable(buf), Some(Token::Print) => { self.lexer.next(); self.require(Token::Semicolon)?; @@ -62,8 +63,22 @@ impl<'a> Parser<'a> { 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 - pub(super) fn parse_expr(&mut self, token: Option) -> ExprResult { + fn parse_expr(&mut self, token: Option) -> ExprResult { let token = token.ok_or(Error { kind: ErrorKind::EndOfTokenStream, position: self.lexer.span(),