Fill out support for operators

This commit is contained in:
jonathandturner 2016-03-01 09:40:48 -05:00
parent 02935fd8cf
commit 419781cfb6
5 changed files with 331 additions and 439 deletions

View File

@ -6,14 +6,16 @@ use std::fmt;
use parser::{lex, parse, Expr, Stmt }; use parser::{lex, parse, Expr, Stmt };
use fn_register::FnRegister; use fn_register::FnRegister;
use ops::{add_boxes, sub_boxes, mult_boxes, div_boxes}; //use ops::{add_boxes, sub_boxes, mult_boxes, div_boxes};
use std::ops::{Add, Sub, Mul, Div};
use std::cmp::{Ord, Eq};
#[derive(Debug)] #[derive(Debug)]
pub enum EvalError { pub enum EvalError {
FunctionNotFound, FunctionNotFound,
FunctionArgMismatch, FunctionArgMismatch,
FunctionCallNotSupported, FunctionCallNotSupported,
TypeMismatchForOperands,
IfGuardMismatch, IfGuardMismatch,
VariableNotFound VariableNotFound
} }
@ -23,8 +25,7 @@ impl Error for EvalError {
match *self { match *self {
EvalError::FunctionNotFound => "Function not found", EvalError::FunctionNotFound => "Function not found",
EvalError::FunctionArgMismatch => "Function argument types do not match", EvalError::FunctionArgMismatch => "Function argument types do not match",
EvalError::FunctionCallNotSupported => "Function call with > 1 argument not supported", EvalError::FunctionCallNotSupported => "Function call with > 2 argument not supported",
EvalError::TypeMismatchForOperands => "Operand types incompatible with operator",
EvalError::IfGuardMismatch => "If guards expect boolean expression", EvalError::IfGuardMismatch => "If guards expect boolean expression",
EvalError::VariableNotFound => "Variable not found", EvalError::VariableNotFound => "Variable not found",
} }
@ -41,7 +42,56 @@ impl fmt::Display for EvalError {
} }
} }
fn add<T: Add>(x: T, y: T) -> <T as Add>::Output {
x + y
}
fn sub<T: Sub>(x: T, y: T) -> <T as Sub>::Output {
x - y
}
fn mul<T: Mul>(x: T, y: T) -> <T as Mul>::Output {
x * y
}
fn div<T: Div>(x: T, y: T) -> <T as Div>::Output {
x / y
}
fn lt<T: Ord>(x: T, y: T) -> bool {
x < y
}
fn lte<T: Ord>(x: T, y: T) -> bool {
x <= y
}
fn gt<T: Ord>(x: T, y: T) -> bool {
x > y
}
fn gte<T: Ord>(x: T, y: T) -> bool {
x >= y
}
fn eq<T: Eq>(x: T, y: T) -> bool {
x == y
}
fn ne<T: Eq>(x: T, y: T) -> bool {
x != y
}
fn and(x: bool, y: bool) -> bool {
x && y
}
fn or(x: bool, y: bool) -> bool {
x || y
}
pub struct Engine { pub struct Engine {
pub fns_arity_2: HashMap<String, Vec<Box<Fn(&mut Box<Any>, &mut Box<Any>)->Result<Box<Any>, EvalError>>>>,
pub fns_arity_1: HashMap<String, Vec<Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>>>>, pub fns_arity_1: HashMap<String, Vec<Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>>>>,
pub fns_arity_0: HashMap<String, Vec<Box<Fn()->Result<Box<Any>, EvalError>>>>, pub fns_arity_0: HashMap<String, Vec<Box<Fn()->Result<Box<Any>, EvalError>>>>,
pub scope: Vec<(String, Box<Any>)> pub scope: Vec<(String, Box<Any>)>
@ -80,6 +130,22 @@ impl Engine {
} }
} }
pub fn call_fn_2_arg(&self, name: &str, arg1: &mut Box<Any>, arg2: &mut Box<Any>) -> Result<Box<Any>, EvalError> {
match self.fns_arity_2.get(name) {
Some(vf) => {
for f in vf {
let invoke = f(arg1, arg2);
match invoke {
Ok(v) => return Ok(v),
_ => ()
}
};
Err(EvalError::FunctionArgMismatch)
}
None => Err(EvalError::FunctionNotFound)
}
}
fn register_type<T: Clone+Any>(&mut self) { fn register_type<T: Clone+Any>(&mut self) {
fn clone_helper<T: Clone>(t:T)->T { t.clone() }; fn clone_helper<T: Clone>(t:T)->T { t.clone() };
@ -139,30 +205,16 @@ impl Engine {
self.call_fn_1_arg(&fn_name, &mut arg) self.call_fn_1_arg(&fn_name, &mut arg)
} }
else if args.len() == 2 {
let mut arg1 = try!(self.eval_expr(&args[0]));
let mut arg2 = try!(self.eval_expr(&args[1]));
self.call_fn_2_arg(&fn_name, &mut arg1, &mut arg2)
}
else { else {
Err(EvalError::FunctionCallNotSupported) Err(EvalError::FunctionCallNotSupported)
} }
} }
Expr::Plus(ref a, ref b) => {
let arg1 = try!(self.eval_expr(a));
let arg2 = try!(self.eval_expr(b));
add_boxes(arg1, arg2)
}
Expr::Minus(ref a, ref b) => {
let arg1 = try!(self.eval_expr(a));
let arg2 = try!(self.eval_expr(b));
sub_boxes(arg1, arg2)
}
Expr::Multiply(ref a, ref b) => {
let arg1 = try!(self.eval_expr(a));
let arg2 = try!(self.eval_expr(b));
mult_boxes(arg1, arg2)
}
Expr::Divide(ref a, ref b) => {
let arg1 = try!(self.eval_expr(a));
let arg2 = try!(self.eval_expr(b));
div_boxes(arg1, arg2)
}
Expr::True => { Expr::True => {
Ok(Box::new(true)) Ok(Box::new(true))
} }
@ -254,20 +306,161 @@ impl Engine {
} }
} }
pub fn register_default_lib(engine: &mut Engine) {
engine.register_type::<i32>();
engine.register_type::<u32>();
engine.register_type::<i64>();
engine.register_type::<u64>();
engine.register_type::<f32>();
engine.register_type::<f64>();
engine.register_type::<String>();
engine.register_type::<char>();
engine.register_type::<bool>();
macro_rules! reg_op {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
($op as fn(x: $y, y: $y)->$y).register($engine, $x);
)*
)
}
macro_rules! reg_cmp {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
($op as fn(x: $y, y: $y)->bool).register($engine, $x);
)*
)
}
reg_op!(engine, "+", add, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "-", sub, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "*", mul, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "/", div, i32, i64, u32, u64, f32, f64);
reg_cmp!(engine, "<", lt, i32, i64, u32, u64);
reg_cmp!(engine, "<=", lte, i32, i64, u32, u64);
reg_cmp!(engine, ">", gt, i32, i64, u32, u64);
reg_cmp!(engine, ">=", gte, i32, i64, u32, u64);
reg_cmp!(engine, "==", eq, i32, i64, u32, u64);
reg_cmp!(engine, "!=", ne, i32, i64, u32, u64);
reg_op!(engine, "||", or, bool);
reg_op!(engine, "&&", and, bool);
}
pub fn new() -> Engine { pub fn new() -> Engine {
let mut output = Engine { fns_arity_0: HashMap::new(), fns_arity_1: HashMap::new(), scope: Vec::new() }; let mut engine = Engine {
fns_arity_0: HashMap::new(),
fns_arity_1: HashMap::new(),
fns_arity_2: HashMap::new(),
scope: Vec::new()
};
output.register_type::<i32>(); Engine::register_default_lib(&mut engine);
output.register_type::<u32>();
output.register_type::<i64>();
output.register_type::<u64>();
output.register_type::<f32>();
output.register_type::<f64>();
output.register_type::<String>();
output.register_type::<char>();
output.register_type::<bool>();
output engine
} }
} }
#[test]
fn test_number_literal() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("65".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 65);
}
else {
assert!(false);
}
}
#[test]
fn test_addition() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("60 + 5".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 65);
}
else {
assert!(false);
}
}
#[test]
fn test_bool_op() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("true && (false || true)".to_string()).unwrap().downcast::<bool>() {
assert_eq!(*result, true);
}
else {
assert!(false);
}
if let Ok(result) = engine.eval("false && (false || true)".to_string()).unwrap().downcast::<bool>() {
assert_eq!(*result, false);
}
else {
assert!(false);
}
}
#[test]
fn test_op_prec() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("var x = 0; if x == 10 || true { x = 1} x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 1);
}
else {
assert!(false);
}
}
#[test]
fn test_if() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("if true { 55 }".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 55);
}
else {
assert!(false);
}
}
#[test]
fn test_var_scope() {
let mut engine = Engine::new();
if let Ok(_) = engine.eval("var x = 4 + 5".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 9);
}
else {
assert!(false);
}
if let Ok(_) = engine.eval("x = x + 1; x = x + 2;".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 12);
}
else {
assert!(false);
}
if let Ok(_) = engine.eval("{var x = 3}".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 12);
}
else {
assert!(false);
}
}

View File

@ -7,7 +7,47 @@ pub trait FnRegister {
fn register(self, engine: &mut Engine, name: &str); fn register(self, engine: &mut Engine, name: &str);
} }
impl<T: Any, U: Any> FnRegister for fn(&mut T)->U { impl<T: Any+Clone, U: Any+Clone, V: Any+Clone> FnRegister for fn(&mut T, U)->V {
fn register(self, engine: &mut Engine, name: &str) {
let wrapped : Box<Fn(&mut Box<Any>, &mut Box<Any>)->Result<Box<Any>, EvalError>> =
Box::new(
move |x: &mut Box<Any>, y: &mut Box<Any>| {
let inside1 = (*x).downcast_mut() as Option<&mut T>;
let inside2 = (*y).downcast_mut() as Option<&mut U>;
match (inside1, inside2) {
(Some(b), Some(c)) => Ok(Box::new(self(b, c.clone())) as Box<Any>),
_ => Err(EvalError::FunctionArgMismatch)
}
}
);
let ent = engine.fns_arity_2.entry(name.to_string()).or_insert(Vec::new());
(*ent).push(wrapped);
}
}
impl<T: Any+Clone, U: Any+Clone, V: Any+Clone> FnRegister for fn(T, U)->V {
fn register(self, engine: &mut Engine, name: &str) {
let wrapped : Box<Fn(&mut Box<Any>, &mut Box<Any>)->Result<Box<Any>, EvalError>> =
Box::new(
move |x: &mut Box<Any>, y: &mut Box<Any>| {
let inside1 = (*x).downcast_mut() as Option<&mut T>;
let inside2 = (*y).downcast_mut() as Option<&mut U>;
match (inside1, inside2) {
(Some(b), Some(c)) => Ok(Box::new(self(b.clone(), c.clone())) as Box<Any>),
_ => Err(EvalError::FunctionArgMismatch)
}
}
);
let ent = engine.fns_arity_2.entry(name.to_string()).or_insert(Vec::new());
(*ent).push(wrapped);
}
}
impl<T: Any+Clone, U: Any+Clone> FnRegister for fn(&mut T)->U {
fn register(self, engine: &mut Engine, name: &str) { fn register(self, engine: &mut Engine, name: &str) {
let wrapped : Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>> = let wrapped : Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>> =
Box::new( Box::new(
@ -26,7 +66,7 @@ impl<T: Any, U: Any> FnRegister for fn(&mut T)->U {
} }
} }
impl<T: Any+Clone, U: Any> FnRegister for fn(T)->U { impl<T: Any+Clone, U: Any+Clone> FnRegister for fn(T)->U {
fn register(self, engine: &mut Engine, name: &str) { fn register(self, engine: &mut Engine, name: &str) {
let wrapped : Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>> = let wrapped : Box<Fn(&mut Box<Any>)->Result<Box<Any>, EvalError>> =
Box::new( Box::new(
@ -44,7 +84,7 @@ impl<T: Any+Clone, U: Any> FnRegister for fn(T)->U {
} }
} }
impl<T: Any> FnRegister for fn()->T { impl<T: Any+Clone> FnRegister for fn()->T {
fn register(self, engine: &mut Engine, name: &str) { fn register(self, engine: &mut Engine, name: &str) {
let wrapped : Box<Fn()->Result<Box<Any>, EvalError>> = let wrapped : Box<Fn()->Result<Box<Any>, EvalError>> =
Box::new( Box::new(

View File

@ -9,8 +9,6 @@ use engine::Engine;
mod fn_register; mod fn_register;
use fn_register::FnRegister; use fn_register::FnRegister;
mod ops;
mod parser; mod parser;
// Todo (in no particular order): // Todo (in no particular order):
@ -18,8 +16,7 @@ mod parser;
// * Doc some examples // * Doc some examples
// * Refactor identifer to not require inlining of clone lookup in engine // * Refactor identifer to not require inlining of clone lookup in engine
// * Remove empty box values? // * Remove empty box values?
// * Method/dot access // * Methods
// * Comparison ops
/* /*
fn simple_fn(x: i32) -> bool { x == 1 } fn simple_fn(x: i32) -> bool { x == 1 }
@ -90,86 +87,6 @@ fn engine_test() {
} }
*/ */
#[test]
fn test_number_literal() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("65".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 65);
}
else {
assert!(false);
}
}
#[test]
fn test_addition() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("60 + 5".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 65);
}
else {
assert!(false);
}
}
#[test]
fn test_boolean() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("true".to_string()).unwrap().downcast::<bool>() {
assert_eq!(*result, true);
}
else {
assert!(false);
}
}
#[test]
fn test_if() {
let mut engine = Engine::new();
if let Ok(result) = engine.eval("if true { 55 }".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 55);
}
else {
assert!(false);
}
}
#[test]
fn test_var_scope() {
let mut engine = Engine::new();
if let Ok(_) = engine.eval("var x = 4 + 5".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 9);
}
else {
assert!(false);
}
if let Ok(_) = engine.eval("x = x + 1; x = x + 2;".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 12);
}
else {
assert!(false);
}
if let Ok(_) = engine.eval("{var x = 3}".to_string()) { } else { assert!(false); }
if let Ok(result) = engine.eval("x".to_string()).unwrap().downcast::<i32>() {
assert_eq!(*result, 12);
}
else {
assert!(false);
}
}
fn showit<T: Display>(x: &mut T) -> () { fn showit<T: Display>(x: &mut T) -> () {
println!("{}", x) println!("{}", x)
} }

View File

@ -1,308 +0,0 @@
use std::any::Any;
use std::boxed::Box;
use engine::{EvalError};
pub fn add_boxes(arg1: Box<Any>, arg2: Box<Any>) -> Result<Box<Any>, EvalError> {
match arg1.downcast::<i32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i32>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u32>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<i64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i64>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u64>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f32>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f64>() {
return Ok(Box::new(*v1 + *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(_) => {
return Err(EvalError::TypeMismatchForOperands)
}
}
}
}
}
}
}
}
}
}
}
}
}
pub fn sub_boxes(arg1: Box<Any>, arg2: Box<Any>) -> Result<Box<Any>, EvalError> {
match arg1.downcast::<i32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i32>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u32>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<i64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i64>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u64>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f32>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f64>() {
return Ok(Box::new(*v1 - *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(_) => {
return Err(EvalError::TypeMismatchForOperands)
}
}
}
}
}
}
}
}
}
}
}
}
}
pub fn mult_boxes(arg1: Box<Any>, arg2: Box<Any>) -> Result<Box<Any>, EvalError> {
match arg1.downcast::<i32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i32>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u32>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<i64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i64>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u64>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f32>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f64>() {
return Ok(Box::new(*v1 * *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(_) => {
return Err(EvalError::TypeMismatchForOperands)
}
}
}
}
}
}
}
}
}
}
}
}
}
pub fn div_boxes(arg1: Box<Any>, arg2: Box<Any>) -> Result<Box<Any>, EvalError> {
match arg1.downcast::<i32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i32>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u32>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<i64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<i64>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<u64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<u64>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f32>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f32>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(arg1_again) => {
match arg1_again.downcast::<f64>() {
Ok(v1) => {
if let Ok(v2) = arg2.downcast::<f64>() {
return Ok(Box::new(*v1 / *v2))
}
else {
return Err(EvalError::TypeMismatchForOperands)
}
},
Err(_) => {
return Err(EvalError::TypeMismatchForOperands)
}
}
}
}
}
}
}
}
}
}
}
}
}

View File

@ -46,13 +46,12 @@ pub enum Stmt { If(Box<Expr>, Box<Stmt>), While(Box<Expr>, Box<Stmt>), Var(Strin
Block(Box<Vec<Stmt>>), Expr(Box<Expr>) } Block(Box<Vec<Stmt>>), Expr(Box<Expr>) }
#[derive(Debug)] #[derive(Debug)]
pub enum Expr { IntConst(i32), Identifier(String), Plus(Box<Expr>, Box<Expr>), Minus(Box<Expr>, Box<Expr>), pub enum Expr { IntConst(i32), Identifier(String), Call(String, Box<Vec<Expr>>), Assignment(Box<Expr>, Box<Expr>), True, False }
Multiply(Box<Expr>, Box<Expr>), Divide(Box<Expr>, Box<Expr>), Call(String, Box<Vec<Expr>>),
Assignment(Box<Expr>, Box<Expr>), True, False }
#[derive(Debug)] #[derive(Debug)]
pub enum Token { Int(i32), Id(String), LCurly, RCurly, LParen, RParen, LSquare, RSquare, pub enum Token { Int(i32), Id(String), LCurly, RCurly, LParen, RParen, LSquare, RSquare,
Plus, Minus, Multiply, Divide, Semicolon, Colon, Comma, Equals, True, False, Var, If, While } Plus, Minus, Multiply, Divide, Semicolon, Colon, Comma, Equals, True, False, Var, If, While,
LessThan, GreaterThan, Bang, LessThanEqual, GreaterThanEqual, EqualTo, NotEqualTo, Pipe, Or, Ampersand, And }
pub struct TokenIterator<'a> { pub struct TokenIterator<'a> {
char_stream: Peekable<Chars<'a>> char_stream: Peekable<Chars<'a>>
@ -128,7 +127,42 @@ impl<'a> Iterator for TokenIterator<'a> {
';' => { return Some(Token::Semicolon); }, ';' => { return Some(Token::Semicolon); },
':' => { return Some(Token::Colon); }, ':' => { return Some(Token::Colon); },
',' => { return Some(Token::Comma); }, ',' => { return Some(Token::Comma); },
'=' => { return Some(Token::Equals); }, '=' => {
match self.char_stream.peek() {
Some(&'=') => {self.char_stream.next(); return Some(Token::EqualTo); },
_ => { return Some(Token::Equals); }
}
},
'<' => {
match self.char_stream.peek() {
Some(&'=') => {self.char_stream.next(); return Some(Token::LessThanEqual); },
_ => { return Some(Token::LessThan); }
}
}
'>' => {
match self.char_stream.peek() {
Some(&'=') => {self.char_stream.next(); return Some(Token::GreaterThanEqual); },
_ => { return Some(Token::GreaterThan); }
}
},
'!' => {
match self.char_stream.peek() {
Some(&'=') => {self.char_stream.next(); return Some(Token::NotEqualTo); },
_ => { return Some(Token::Bang); }
}
},
'|' => {
match self.char_stream.peek() {
Some(&'|') => {self.char_stream.next(); return Some(Token::Or); },
_ => { return Some(Token::Pipe); }
}
},
'&' => {
match self.char_stream.peek() {
Some(&'&') => {self.char_stream.next(); return Some(Token::And); },
_ => { return Some(Token::Ampersand); }
}
},
' ' | '\n' | '\r' => (), ' ' | '\n' | '\r' => (),
_ => return None _ => return None
} }
@ -145,6 +179,14 @@ pub fn lex<'a>(input: &'a String) -> TokenIterator<'a> {
fn get_precedence(token: &Token) -> i32 { fn get_precedence(token: &Token) -> i32 {
match *token { match *token {
Token::Equals => 10, Token::Equals => 10,
Token::Or => 11,
Token::And => 12,
Token::LessThan => 15,
Token::LessThanEqual => 15,
Token::GreaterThan => 15,
Token::GreaterThanEqual => 15,
Token::EqualTo => 15,
Token::NotEqualTo => 15,
Token::Plus => 20, Token::Plus => 20,
Token::Minus => 20, Token::Minus => 20,
Token::Multiply => 40, Token::Multiply => 40,
@ -238,11 +280,19 @@ fn parse_binop<'a>(input: &mut Peekable<TokenIterator<'a>>, prec: i32, lhs: Expr
} }
lhs_curr = match op_token { lhs_curr = match op_token {
Token::Plus => Expr::Plus(Box::new(lhs_curr), Box::new(rhs)), Token::Plus => Expr::Call("+".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::Minus => Expr::Minus(Box::new(lhs_curr), Box::new(rhs)), Token::Minus => Expr::Call("-".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::Multiply => Expr::Multiply(Box::new(lhs_curr), Box::new(rhs)), Token::Multiply => Expr::Call("*".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::Divide => Expr::Divide(Box::new(lhs_curr), Box::new(rhs)), Token::Divide => Expr::Call("/".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::Equals => Expr::Assignment(Box::new(lhs_curr), Box::new(rhs)), Token::Equals => Expr::Assignment(Box::new(lhs_curr), Box::new(rhs)),
Token::EqualTo => Expr::Call("==".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::NotEqualTo => Expr::Call("!=".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::LessThan => Expr::Call("<".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::LessThanEqual => Expr::Call("<=".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::GreaterThan => Expr::Call(">".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::GreaterThanEqual => Expr::Call(">=".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::Or => Expr::Call("||".to_string(), Box::new(vec![lhs_curr, rhs])),
Token::And => Expr::Call("&&".to_string(), Box::new(vec![lhs_curr, rhs])),
_ => return Err(ParseError::UnknownOperator) _ => return Err(ParseError::UnknownOperator)
}; };
} }