Binary operator boilerplate reduction

This commit is contained in:
Erin 2021-06-07 09:17:18 +02:00 committed by ondra05
parent a5a048728c
commit 97f0271534
2 changed files with 37 additions and 39 deletions

View file

@ -112,3 +112,24 @@ pub enum BinOpKind {
And, And,
Or, Or,
} }
impl BinOpKind {
pub fn from_token(t: crate::lexer::Token) -> Result<Self, crate::error::ErrorKind> {
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)),
}
}
}

View file

@ -111,44 +111,21 @@ impl<'source> Parser<'source> {
)), )),
// Operations // Operations
Token::Plus => Ok(Expr::new( Token::Plus
self.op_flow(BinOpKind::Add, buf)?, | Token::Minus
start..self.lexer.span().end, | Token::Star
)), | Token::FwdSlash
Token::Minus => Ok(Expr::new( | Token::EqualEqual
self.op_flow(BinOpKind::Subtract, buf)?, | Token::NotEqual
start..self.lexer.span().end, | Token::LessThan
)), | Token::GreaterThan => Ok(Expr::new(
Token::Star => Ok(Expr::new( self.op_flow(
self.op_flow(BinOpKind::Multiply, buf)?, match BinOpKind::from_token(token) {
start..self.lexer.span().end, Ok(op) => op,
)), Err(e) => return Err(Error::new(e, self.lexer.span())),
Token::FwdSlash => Ok(Expr::new( },
self.op_flow(BinOpKind::Divide, buf)?, 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)?,
start..self.lexer.span().end, start..self.lexer.span().end,
)), )),
@ -218,7 +195,7 @@ impl<'source> Parser<'source> {
self.require(Token::LeftParen)?; self.require(Token::LeftParen)?;
let cond = self.expr_flow(Token::RightParen)?; let cond = self.expr_flow(Token::RightParen)?;
let body = self.parse_block()?; let body = self.parse_block()?;
Ok(StmtKind::If { cond, body }) Ok(StmtKind::If { cond, body })