From 97f02715345851f9a0107a7a9002d931453a94de Mon Sep 17 00:00:00 2001 From: Erin Date: Mon, 7 Jun 2021 09:17:18 +0200 Subject: [PATCH] Binary operator boilerplate reduction --- src/ast.rs | 21 ++++++++++++++++++++ src/parser.rs | 55 +++++++++++++++------------------------------------ 2 files changed, 37 insertions(+), 39 deletions(-) diff --git a/src/ast.rs b/src/ast.rs index bbf6d691..a5fbae01 100644 --- a/src/ast.rs +++ b/src/ast.rs @@ -112,3 +112,24 @@ pub enum BinOpKind { And, Or, } + +impl BinOpKind { + pub fn from_token(t: crate::lexer::Token) -> Result { + use crate::lexer::Token; + use crate::error::*; + + match t { + Token::Plus => Ok(Self::Add), + Token::Minus => Ok(Self::Subtract), + Token::Star => Ok(Self::Multiply), + Token::FwdSlash => Ok(Self::Divide), + Token::GreaterThan => Ok(Self::Greater), + Token::LessThan => Ok(Self::Less), + Token::EqualEqual => Ok(Self::Equal), + Token::NotEqual => Ok(Self::NotEqual), + Token::And => Ok(Self::And), + Token::Or => Ok(Self::Or), + t=> Err(ErrorKind::UnexpectedToken(t)), + } + } +} diff --git a/src/parser.rs b/src/parser.rs index 0a51fc79..7f66de1f 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -111,44 +111,21 @@ impl<'source> Parser<'source> { )), // Operations - Token::Plus => Ok(Expr::new( - self.op_flow(BinOpKind::Add, buf)?, - start..self.lexer.span().end, - )), - Token::Minus => Ok(Expr::new( - self.op_flow(BinOpKind::Subtract, buf)?, - start..self.lexer.span().end, - )), - Token::Star => Ok(Expr::new( - self.op_flow(BinOpKind::Multiply, buf)?, - start..self.lexer.span().end, - )), - Token::FwdSlash => Ok(Expr::new( - self.op_flow(BinOpKind::Divide, buf)?, - start..self.lexer.span().end, - )), - Token::EqualEqual => Ok(Expr::new( - self.op_flow(BinOpKind::Equal, buf)?, - start..self.lexer.span().end, - )), - Token::NotEqual => Ok(Expr::new( - self.op_flow(BinOpKind::NotEqual, buf)?, - start..self.lexer.span().end, - )), - Token::And => Ok(Expr::new( - self.op_flow(BinOpKind::And, buf)?, - start..self.lexer.span().end, - )), - Token::Or => Ok(Expr::new( - self.op_flow(BinOpKind::Or, buf)?, - start..self.lexer.span().end, - )), - Token::LessThan => Ok(Expr::new( - self.op_flow(BinOpKind::Less, buf)?, - start..self.lexer.span().end, - )), - Token::GreaterThan => Ok(Expr::new( - self.op_flow(BinOpKind::Greater, buf)?, + Token::Plus + | Token::Minus + | Token::Star + | Token::FwdSlash + | Token::EqualEqual + | Token::NotEqual + | Token::LessThan + | Token::GreaterThan => Ok(Expr::new( + self.op_flow( + match BinOpKind::from_token(token) { + Ok(op) => op, + Err(e) => return Err(Error::new(e, self.lexer.span())), + }, + buf, + )?, start..self.lexer.span().end, )), @@ -218,7 +195,7 @@ impl<'source> Parser<'source> { self.require(Token::LeftParen)?; let cond = self.expr_flow(Token::RightParen)?; - + let body = self.parse_block()?; Ok(StmtKind::If { cond, body })