From fb718814091722e7d1dde90c1403c5d6ad747b2e Mon Sep 17 00:00:00 2001 From: greg Date: Sun, 19 Aug 2018 20:33:50 -0700 Subject: [PATCH] Refactor binop parsing --- schala-lang/src/builtin.rs | 24 ++++++++++++++++++++++-- schala-lang/src/parsing.rs | 19 ++++++------------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/schala-lang/src/builtin.rs b/schala-lang/src/builtin.rs index 81291d7..7e5cf08 100644 --- a/schala-lang/src/builtin.rs +++ b/schala-lang/src/builtin.rs @@ -2,6 +2,7 @@ use std::rc::Rc; use std::collections::HashMap; use std::fmt; +use tokenizing::TokenType; use self::Type::*; use self::TConstOld::*; @@ -39,6 +40,17 @@ impl BinOp { pub fn sigil(&self) -> &Rc { &self.sigil } + pub fn from_sigil_token(tok: &TokenType) -> Option { + 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 { let s = self.sigil.as_str(); @@ -48,9 +60,17 @@ impl BinOp { pub fn min_precedence() -> i32 { i32::min_value() } - pub fn get_precedence(op: &str) -> i32 { + pub fn get_precedence_from_token(op: &TokenType) -> Option { + use self::TokenType::*; + let s = match op { + Operator(op) => op, + Period => ".", + Pipe => "|", + Slash => "/", + _ => return None + }; 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)) } } diff --git a/schala-lang/src/parsing.rs b/schala-lang/src/parsing.rs index 9735790..a515651 100644 --- a/schala-lang/src/parsing.rs +++ b/schala-lang/src/parsing.rs @@ -496,26 +496,19 @@ impl Parser { let mut lhs = self.prefix_expr()?; loop { - let new_precedence = match self.peek() { - Operator(op) => BinOp::get_precedence(&*op), - Period => BinOp::get_precedence("."), - Pipe => BinOp::get_precedence("|"), - Slash => BinOp::get_precedence("/"), - _ => break, + let new_precedence = match BinOp::get_precedence_from_token(&self.peek()) { + Some(p) => p, + None => break, }; if precedence >= new_precedence { break; } - let sigil = match self.next() { - Operator(op) => op, - Period => Rc::new(".".to_string()), - Pipe => Rc::new("|".to_string()), - Slash => Rc::new("/".to_string()), - _ => unreachable!(), + let operation = match BinOp::from_sigil_token(&self.next()) { + Some(sigil) => sigil, + None => unreachable!() }; 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); } self.parse_level -= 1;