Refactor binop parsing

This commit is contained in:
greg 2018-08-19 20:33:50 -07:00
parent d1c3b4a81b
commit fb71881409
2 changed files with 28 additions and 15 deletions

View File

@ -2,6 +2,7 @@ use std::rc::Rc;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use tokenizing::TokenType;
use self::Type::*; use self::TConstOld::*; use self::Type::*; use self::TConstOld::*;
@ -39,6 +40,17 @@ impl BinOp {
pub fn sigil(&self) -> &Rc<String> { pub fn sigil(&self) -> &Rc<String> {
&self.sigil &self.sigil
} }
pub fn from_sigil_token(tok: &TokenType) -> Option<BinOp> {
use self::TokenType::*;
let s = match tok {
Operator(op) => op,
Period => ".",
Pipe => "|",
Slash => "/",
_ => return None
};
Some(BinOp::from_sigil(s))
}
/* /*
pub fn get_type(&self) -> Result<Type, String> { pub fn get_type(&self) -> Result<Type, String> {
let s = self.sigil.as_str(); let s = self.sigil.as_str();
@ -48,9 +60,17 @@ impl BinOp {
pub fn min_precedence() -> i32 { pub fn min_precedence() -> i32 {
i32::min_value() i32::min_value()
} }
pub fn get_precedence(op: &str) -> i32 { pub fn get_precedence_from_token(op: &TokenType) -> Option<i32> {
use self::TokenType::*;
let s = match op {
Operator(op) => op,
Period => ".",
Pipe => "|",
Slash => "/",
_ => return None
};
let default = 10_000_000; let default = 10_000_000;
BINOPS.get(op).map(|x| x.2.clone()).unwrap_or(default) Some(BINOPS.get(s).map(|x| x.2.clone()).unwrap_or(default))
} }
} }

View File

@ -496,26 +496,19 @@ impl Parser {
let mut lhs = self.prefix_expr()?; let mut lhs = self.prefix_expr()?;
loop { loop {
let new_precedence = match self.peek() { let new_precedence = match BinOp::get_precedence_from_token(&self.peek()) {
Operator(op) => BinOp::get_precedence(&*op), Some(p) => p,
Period => BinOp::get_precedence("."), None => break,
Pipe => BinOp::get_precedence("|"),
Slash => BinOp::get_precedence("/"),
_ => break,
}; };
if precedence >= new_precedence { if precedence >= new_precedence {
break; break;
} }
let sigil = match self.next() { let operation = match BinOp::from_sigil_token(&self.next()) {
Operator(op) => op, Some(sigil) => sigil,
Period => Rc::new(".".to_string()), None => unreachable!()
Pipe => Rc::new("|".to_string()),
Slash => Rc::new("/".to_string()),
_ => unreachable!(),
}; };
let rhs = self.precedence_expr(new_precedence)?; let rhs = self.precedence_expr(new_precedence)?;
let operation = BinOp::from_sigil(sigil.as_ref());
lhs = Expression(ExpressionType::BinExp(operation, bx!(lhs), bx!(rhs)), None); lhs = Expression(ExpressionType::BinExp(operation, bx!(lhs), bx!(rhs)), None);
} }
self.parse_level -= 1; self.parse_level -= 1;