schala/schala-lang/src/eval.rs

466 lines
15 KiB
Rust
Raw Normal View History

2018-08-14 21:17:43 -07:00
use std::cell::RefCell;
2017-10-13 03:05:18 -07:00
use std::rc::Rc;
2018-03-03 13:26:22 -08:00
use std::fmt::Write;
2018-05-12 02:27:54 -07:00
use std::io;
2018-03-03 13:26:22 -08:00
use itertools::Itertools;
2018-05-11 01:56:12 -07:00
use util::StateStack;
2018-06-04 19:12:48 -07:00
use reduced_ast::{ReducedAST, Stmt, Expr, Lit, Func};
use symbol_table::{SymbolSpec, Symbol, SymbolTable};
2017-09-30 23:30:02 -07:00
pub struct State<'a> {
values: StateStack<'a, Rc<String>, ValueEntry>,
symbol_table_handle: Rc<RefCell<SymbolTable>>,
2017-10-13 03:05:18 -07:00
}
2018-05-11 01:56:12 -07:00
2018-05-12 01:18:44 -07:00
macro_rules! builtin_binding {
($name:expr, $values:expr) => {
2018-08-13 23:28:03 -07:00
$values.insert(Rc::new(format!($name)), ValueEntry::Binding { constant: true, val: Node::Expr(Expr::Func(Func::BuiltIn(Rc::new(format!($name))))) });
2018-05-12 01:18:44 -07:00
}
}
2018-08-14 21:17:43 -07:00
//TODO add a more concise way of getting a new frame
2018-05-11 01:56:12 -07:00
impl<'a> State<'a> {
pub fn new(symbol_table_handle: Rc<RefCell<SymbolTable>>) -> State<'a> {
2018-05-12 01:18:44 -07:00
let mut values = StateStack::new(Some(format!("global")));
builtin_binding!("print", values);
builtin_binding!("println", values);
2018-05-12 02:27:54 -07:00
builtin_binding!("getline", values);
State { values, symbol_table_handle }
2018-05-11 01:56:12 -07:00
}
2018-05-11 02:33:19 -07:00
pub fn debug_print(&self) -> String {
format!("Values: {:?}", self.values)
}
2018-05-11 01:56:12 -07:00
}
2018-08-13 23:28:03 -07:00
#[derive(Debug, Clone)]
enum Node {
Expr(Expr),
PrimObject {
name: Rc<String>,
tag: usize,
items: Vec<Node>,
2018-08-14 02:03:05 -07:00
},
PrimTuple {
items: Vec<Node>
2018-08-13 23:28:03 -07:00
}
}
fn paren_wrapped_vec(terms: impl Iterator<Item=String>) -> String {
let mut buf = String::new();
write!(buf, "(").unwrap();
for term in terms.map(|e| Some(e)).intersperse(None) {
match term {
Some(e) => write!(buf, "{}", e).unwrap(),
None => write!(buf, ", ").unwrap(),
};
}
write!(buf, ")").unwrap();
buf
}
impl Node {
fn to_repl(&self) -> String {
match self {
Node::Expr(e) => e.to_repl(),
2018-08-14 23:19:27 -07:00
Node::PrimObject { name, items, .. } if items.len() == 0 => format!("{}", name),
Node::PrimObject { name, items, .. } => format!("{}{}", name, paren_wrapped_vec(items.iter().map(|x| x.to_repl()))),
2018-08-14 02:03:05 -07:00
Node::PrimTuple { items } => format!("{}", paren_wrapped_vec(items.iter().map(|x| x.to_repl()))),
2018-08-13 23:28:03 -07:00
}
}
}
2018-05-11 01:57:29 -07:00
#[derive(Debug)]
enum ValueEntry {
Binding {
2018-05-11 02:24:38 -07:00
constant: bool,
2018-08-13 23:28:03 -07:00
val: /*FullyEvaluatedExpr*/ Node, //TODO make this use a subtype to represent fully evaluatedness
2018-05-11 01:57:29 -07:00
}
}
type EvalResult<T> = Result<T, String>;
2018-05-11 00:25:43 -07:00
impl Expr {
2018-08-13 23:28:03 -07:00
fn to_node(self) -> Node {
Node::Expr(self)
}
2018-05-11 00:25:43 -07:00
fn to_repl(&self) -> String {
2018-05-11 01:07:18 -07:00
use self::Lit::*;
2018-05-11 23:23:54 -07:00
use self::Func::*;
2018-06-04 18:17:03 -07:00
2018-05-11 01:07:18 -07:00
match self {
Expr::Lit(ref l) => match l {
Nat(n) => format!("{}", n),
Int(i) => format!("{}", i),
Float(f) => format!("{}", f),
Bool(b) => format!("{}", b),
2018-05-12 12:58:57 -07:00
StringLit(s) => format!("\"{}\"", s),
2018-05-11 01:07:18 -07:00
},
2018-05-11 23:23:54 -07:00
Expr::Func(f) => match f {
BuiltIn(name) => format!("<built-in function '{}'>", name),
2018-05-11 23:23:54 -07:00
UserDefined { name: None, .. } => format!("<function>"),
UserDefined { name: Some(name), .. } => format!("<function '{}'>", name),
2018-05-11 23:23:54 -07:00
},
2018-08-05 19:14:02 -07:00
Expr::Constructor {
2018-08-19 15:06:01 -07:00
type_name: _, name, tag, arity,
} => if *arity == 0 {
format!("{}", name)
} else {
format!("<data constructor '{}'>", name)
},
2018-08-13 23:28:03 -07:00
Expr::Tuple(exprs) => paren_wrapped_vec(exprs.iter().map(|x| x.to_repl())),
2018-05-11 01:07:18 -07:00
_ => format!("{:?}", self),
}
2018-05-11 00:25:43 -07:00
}
}
2018-05-09 02:27:57 -07:00
impl<'a> State<'a> {
2018-05-12 02:20:50 -07:00
pub fn evaluate(&mut self, ast: ReducedAST, repl: bool) -> Vec<Result<String, String>> {
2018-05-09 03:38:02 -07:00
let mut acc = vec![];
// handle prebindings
for statement in ast.0.iter() {
self.prebinding(statement);
}
2018-05-09 03:38:02 -07:00
for statement in ast.0 {
2018-05-11 00:25:43 -07:00
match self.statement(statement) {
Ok(Some(ref output)) if repl => acc.push(Ok(output.to_repl())),
Ok(_) => (),
2018-05-09 03:38:02 -07:00
Err(error) => {
2018-05-12 12:37:05 -07:00
acc.push(Err(format!("Runtime error: {}", error)));
2018-05-09 03:38:02 -07:00
return acc;
},
}
}
acc
}
fn prebinding(&mut self, stmt: &Stmt) {
match stmt {
Stmt::PreBinding { name, func } => {
2018-08-13 23:28:03 -07:00
let v_entry = ValueEntry::Binding { constant: true, val: Node::Expr(Expr::Func(func.clone())) };
self.values.insert(name.clone(), v_entry);
},
Stmt::Expr(_expr) => {
//TODO have this support things like nested function defs
},
_ => ()
}
}
2018-08-13 23:28:03 -07:00
fn statement(&mut self, stmt: Stmt) -> EvalResult<Option<Node>> {
2018-05-11 01:07:18 -07:00
match stmt {
2018-05-11 02:24:38 -07:00
Stmt::Binding { name, constant, expr } => {
2018-08-13 23:28:03 -07:00
let val = self.expression(Node::Expr(expr))?;
2018-05-11 02:24:38 -07:00
self.values.insert(name.clone(), ValueEntry::Binding { constant, val });
2018-05-11 01:07:18 -07:00
Ok(None)
},
2018-08-13 23:28:03 -07:00
Stmt::Expr(expr) => Ok(Some(self.expression(expr.to_node())?)),
Stmt::PreBinding {..} | Stmt::Noop => Ok(None),
2018-05-11 01:07:18 -07:00
}
}
2018-08-13 23:28:03 -07:00
fn block(&mut self, stmts: Vec<Stmt>) -> EvalResult<Node> {
2018-05-12 13:51:12 -07:00
let mut ret = None;
for stmt in stmts {
ret = self.statement(stmt)?;
}
2018-08-13 23:28:03 -07:00
Ok(ret.unwrap_or(Node::Expr(Expr::Unit)))
2018-05-12 13:51:12 -07:00
}
2018-08-13 23:28:03 -07:00
fn expression(&mut self, node: Node) -> EvalResult<Node> {
2018-05-11 01:07:18 -07:00
use self::Expr::*;
2018-08-13 23:28:03 -07:00
match node {
2018-08-14 02:03:05 -07:00
t @ Node::PrimTuple { .. } => Ok(t),
2018-08-13 23:28:03 -07:00
obj @ Node::PrimObject { .. } => Ok(obj),
Node::Expr(expr) => match expr {
literal @ Lit(_) => Ok(Node::Expr(literal)),
2018-08-14 02:03:05 -07:00
Call { box f, args } => match self.expression(Node::Expr(f))? {
Node::Expr(Constructor { type_name, name, tag, arity }) => self.apply_data_constructor(type_name, name, tag, arity, args),
Node::Expr(Func(f)) => self.apply_function(f, args),
other => return Err(format!("Tried to call {:?} which is not a function or data constructor", other)),
2018-08-13 23:28:03 -07:00
},
Val(v) => self.value(v),
2018-08-14 21:17:43 -07:00
Constructor { arity, ref name, tag, .. } if arity == 0 => Ok(Node::PrimObject { name: name.clone(), tag, items: vec![] }),
2018-08-13 23:28:03 -07:00
constructor @ Constructor { .. } => Ok(Node::Expr(constructor)),
func @ Func(_) => Ok(Node::Expr(func)),
Tuple(exprs) => {
2018-08-14 02:03:05 -07:00
let nodes = exprs.into_iter().map(|expr| self.expression(Node::Expr(expr))).collect::<Result<Vec<Node>,_>>()?;
Ok(Node::PrimTuple { items: nodes })
2018-08-13 23:28:03 -07:00
},
Conditional { box cond, then_clause, else_clause } => self.conditional(cond, then_clause, else_clause),
Assign { box val, box expr } => {
let name = match val {
Expr::Val(name) => name,
_ => return Err(format!("Trying to assign to a non-value")),
};
let constant = match self.values.lookup(&name) {
None => return Err(format!("{} is undefined", name)),
Some(ValueEntry::Binding { constant, .. }) => constant.clone(),
};
if constant {
return Err(format!("trying to update {}, a non-mutable binding", name));
}
let val = self.expression(Node::Expr(expr))?;
self.values.insert(name.clone(), ValueEntry::Binding { constant: false, val });
Ok(Node::Expr(Expr::Unit))
},
2018-08-14 12:43:06 -07:00
Unit => Ok(Node::Expr(Unit)),
2018-08-14 21:17:43 -07:00
CaseMatch { box cond, alternatives } => match self.expression(Node::Expr(cond))? {
Node::PrimObject { name, tag, items } => {
for alt in alternatives {
if alt.tag.map(|t| t == tag).unwrap_or(true) {
let mut inner_state = State {
2018-08-14 21:45:45 -07:00
values: self.values.new_scope(None),
2018-08-14 21:17:43 -07:00
symbol_table_handle: self.symbol_table_handle.clone(),
};
for (bound_var, val) in alt.bound_vars.iter().zip(items.iter()) {
if let Some(bv) = bound_var.as_ref() {
inner_state.values.insert(bv.clone(), ValueEntry::Binding { constant: true, val: val.clone() });
}
}
return inner_state.block(alt.item)
}
}
return Err(format!("No matches found"));
},
Node::PrimTuple { .. } => Err(format!("Tuples don't work")),
Node::Expr(e) => Err(format!("Exprs don't work {:?}", e))
},
2018-08-14 12:43:06 -07:00
UnimplementedSigilValue => Err(format!("Sigil value eval not implemented"))
2018-08-13 23:28:03 -07:00
}
2018-05-11 01:07:18 -07:00
}
2018-05-09 02:27:57 -07:00
}
2018-05-11 01:30:02 -07:00
2018-08-13 23:28:03 -07:00
fn apply_data_constructor(&mut self, type_name: Rc<String>, name: Rc<String>, tag: usize, arity: usize, args: Vec<Expr>) -> EvalResult<Node> {
if arity != args.len() {
return Err(format!("Data constructor {} requires {} args", name, arity));
2018-06-04 18:17:03 -07:00
}
2018-08-13 23:28:03 -07:00
let evaled_args = args.into_iter().map(|expr| self.expression(Node::Expr(expr))).collect::<Result<Vec<Node>,_>>()?;
2018-06-12 19:37:53 -07:00
//let evaled_args = vec![];
2018-08-13 23:28:03 -07:00
Ok(Node::PrimObject {
name: name.clone(),
items: evaled_args,
2018-08-14 02:03:05 -07:00
tag
2018-08-13 23:28:03 -07:00
})
2018-06-04 18:17:03 -07:00
}
2018-08-13 23:28:03 -07:00
fn apply_function(&mut self, f: Func, args: Vec<Expr>) -> EvalResult<Node> {
2018-05-11 01:30:02 -07:00
match f {
2018-08-13 23:28:03 -07:00
Func::BuiltIn(sigil) => Ok(Node::Expr(self.apply_builtin(sigil, args)?)),
2018-05-12 00:59:50 -07:00
Func::UserDefined { params, body, name } => {
if params.len() != args.len() {
2018-05-12 12:37:05 -07:00
return Err(format!("calling a {}-argument function with {} args", params.len(), args.len()))
2018-05-12 00:59:50 -07:00
}
let mut func_state = State {
2018-08-14 21:45:45 -07:00
values: self.values.new_scope(name.map(|n| format!("{}", n))),
symbol_table_handle: self.symbol_table_handle.clone(),
};
2018-05-12 00:59:50 -07:00
for (param, val) in params.into_iter().zip(args.into_iter()) {
2018-08-13 23:28:03 -07:00
let val = func_state.expression(Node::Expr(val))?;
2018-05-12 00:59:50 -07:00
func_state.values.insert(param, ValueEntry::Binding { constant: true, val });
}
// TODO figure out function return semantics
2018-05-12 13:51:12 -07:00
func_state.block(body)
2018-05-11 01:30:02 -07:00
}
}
}
2018-05-11 01:57:29 -07:00
fn apply_builtin(&mut self, name: Rc<String>, args: Vec<Expr>) -> EvalResult<Expr> {
2018-05-11 01:30:02 -07:00
use self::Expr::*;
use self::Lit::*;
2018-08-13 23:28:03 -07:00
let evaled_args: Result<Vec<Expr>, String> = args.into_iter().map(|arg| {
match self.expression(Node::Expr(arg)) {
Ok(Node::Expr(e)) => Ok(e),
2018-08-19 15:06:01 -07:00
Ok(Node::PrimTuple { .. }) => Err(format!("Trying to apply a builtin to a tuple")),
2018-08-13 23:28:03 -07:00
Ok(Node::PrimObject { .. }) => Err(format!("Trying to apply a builtin to a primitive object")),
Err(e) => Err(e)
}
}).collect();
2018-05-11 01:30:02 -07:00
let evaled_args = evaled_args?;
Ok(match (name.as_str(), evaled_args.as_slice()) {
2018-05-11 01:46:42 -07:00
/* binops */
2018-05-11 01:30:02 -07:00
("+", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l + r)),
2018-05-11 01:35:39 -07:00
("++", &[Lit(StringLit(ref s1)), Lit(StringLit(ref s2))]) => Lit(StringLit(Rc::new(format!("{}{}", s1, s2)))),
("-", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l - r)),
("*", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l * r)),
("/", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Float((l as f64)/ (r as f64))),
("//", &[Lit(Nat(l)), Lit(Nat(r))]) => if r == 0 {
2018-05-12 12:37:05 -07:00
return Err(format!("divide by zero"));
2018-05-11 01:30:02 -07:00
} else {
2018-05-11 01:35:39 -07:00
Lit(Nat(l / r))
2018-05-11 01:30:02 -07:00
},
2018-05-11 01:35:39 -07:00
("%", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l % r)),
("^", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l ^ r)),
("&", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l & r)),
("|", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Nat(l | r)),
2018-05-11 01:46:42 -07:00
2018-05-12 13:58:21 -07:00
("==", &[Lit(Nat(l)), Lit(Nat(r))]) => Lit(Bool(l == r)),
("==", &[Lit(Int(l)), Lit(Int(r))]) => Lit(Bool(l == r)),
("==", &[Lit(Float(l)), Lit(Float(r))]) => Lit(Bool(l == r)),
("==", &[Lit(Bool(l)), Lit(Bool(r))]) => Lit(Bool(l == r)),
("==", &[Lit(StringLit(ref l)), Lit(StringLit(ref r))]) => Lit(Bool(l == r)),
2018-05-11 01:46:42 -07:00
/* prefix ops */
("!", &[Lit(Bool(true))]) => Lit(Bool(false)),
("!", &[Lit(Bool(false))]) => Lit(Bool(true)),
("-", &[Lit(Nat(n))]) => Lit(Int(-1*(n as i64))),
("-", &[Lit(Int(n))]) => Lit(Int(-1*(n as i64))),
("+", &[Lit(Int(n))]) => Lit(Int(n)),
("+", &[Lit(Nat(n))]) => Lit(Nat(n)),
2018-05-12 01:18:44 -07:00
2018-05-12 03:51:42 -07:00
/* builtin functions */
2018-05-12 01:18:44 -07:00
("print", &[ref anything]) => {
print!("{}", anything.to_repl());
Expr::Unit
},
("println", &[ref anything]) => {
println!("{}", anything.to_repl());
Expr::Unit
},
2018-05-12 02:27:54 -07:00
("getline", &[]) => {
let mut buf = String::new();
io::stdin().read_line(&mut buf).expect("Error readling line in 'getline'");
Lit(StringLit(Rc::new(buf.trim().to_string())))
2018-05-12 02:27:54 -07:00
},
2018-05-12 12:37:05 -07:00
(x, args) => return Err(format!("bad or unimplemented builtin {:?} | {:?}", x, args)),
2018-05-11 01:30:02 -07:00
})
}
2018-05-11 17:24:11 -07:00
2018-08-13 23:28:03 -07:00
fn conditional(&mut self, cond: Expr, then_clause: Vec<Stmt>, else_clause: Vec<Stmt>) -> EvalResult<Node> {
let cond = self.expression(Node::Expr(cond))?;
2018-05-12 13:51:12 -07:00
Ok(match cond {
2018-08-13 23:28:03 -07:00
Node::Expr(Expr::Lit(Lit::Bool(true))) => self.block(then_clause)?,
Node::Expr(Expr::Lit(Lit::Bool(false))) => self.block(else_clause)?,
2018-05-12 13:51:12 -07:00
_ => return Err(format!("Conditional with non-boolean condition"))
})
}
2018-08-13 23:28:03 -07:00
fn value(&mut self, name: Rc<String>) -> EvalResult<Node> {
2018-05-11 17:24:11 -07:00
use self::ValueEntry::*;
2018-05-14 22:55:53 -07:00
use self::Func::*;
//TODO add a layer of indirection here to talk to the symbol table first, and only then look up
//in the values table
2018-05-14 09:46:25 -07:00
let symbol_table = self.symbol_table_handle.borrow();
2018-08-05 18:19:48 -07:00
let value = symbol_table.lookup_by_name(&name);
2018-06-12 19:37:53 -07:00
Ok(match value {
2018-05-15 23:48:36 -07:00
Some(Symbol { name, spec }) => match spec {
2018-08-14 23:19:27 -07:00
//TODO I'll need this type_name later to do a table lookup
SymbolSpec::DataConstructor { type_name: _type_name, type_args, .. } => {
2018-05-30 23:54:24 -07:00
if type_args.len() == 0 {
2018-08-13 23:28:03 -07:00
Node::PrimObject { name: name.clone(), tag: 0, items: vec![] }
2018-05-30 23:54:24 -07:00
} else {
return Err(format!("This data constructor thing not done"))
}
2018-05-14 22:55:53 -07:00
},
2018-06-03 02:39:49 -07:00
SymbolSpec::Func(_) => match self.values.lookup(&name) {
2018-08-13 23:28:03 -07:00
Some(Binding { val: Node::Expr(Expr::Func(UserDefined { name, params, body })), .. }) => {
Node::Expr(Expr::Func(UserDefined { name: name.clone(), params: params.clone(), body: body.clone() }))
2018-05-14 22:55:53 -07:00
},
_ => unreachable!(),
},
},
/* see if it's an ordinary variable TODO make variables go in symbol table */
None => match self.values.lookup(&name) {
Some(Binding { val, .. }) => val.clone(),
None => return Err(format!("Couldn't find value {}", name)),
2018-05-11 17:24:11 -07:00
}
2018-05-14 22:55:53 -07:00
})
2018-05-11 23:23:54 -07:00
}
2018-05-09 02:27:57 -07:00
}
2018-05-12 02:18:34 -07:00
#[cfg(test)]
mod eval_tests {
2018-05-14 23:25:28 -07:00
use std::cell::RefCell;
use std::rc::Rc;
use symbol_table::SymbolTable;
2018-05-12 02:18:34 -07:00
use tokenizing::tokenize;
use parsing::parse;
use eval::State;
2018-08-14 21:39:33 -07:00
macro_rules! all_output {
($string:expr) => {
{
let symbol_table = Rc::new(RefCell::new(SymbolTable::new()));
let mut state = State::new(symbol_table);
let ast = parse(tokenize($string)).0.unwrap();
2018-08-14 21:46:48 -07:00
state.symbol_table_handle.borrow_mut().add_top_level_symbols(&ast).unwrap();
2018-08-14 21:39:33 -07:00
let reduced = ast.reduce(&state.symbol_table_handle.borrow());
let all_output = state.evaluate(reduced, true);
all_output
}
}
}
2018-05-12 02:18:34 -07:00
macro_rules! fresh_env {
($string:expr, $correct:expr) => {
2018-08-14 21:39:33 -07:00
{
let all_output = all_output!($string);
let ref output = all_output.last().unwrap();
assert_eq!(**output, Ok($correct.to_string()));
}
2018-05-12 02:18:34 -07:00
}
}
#[test]
fn test_basic_eval() {
fresh_env!("1 + 2", "3");
2018-07-11 16:44:15 -07:00
fresh_env!("let mut a = 1; a = 2", "Unit");
fresh_env!("let mut a = 1; a = 2; a", "2");
2018-05-12 12:58:57 -07:00
fresh_env!(r#"("a", 1 + 2)"#, r#"("a", 3)"#);
2018-05-12 02:18:34 -07:00
}
2018-05-14 23:33:11 -07:00
#[test]
fn function_eval() {
fresh_env!("fn oi(x) { x + 1 }; oi(4)", "5");
fresh_env!("fn oi(x) { x + 1 }; oi(1+2)", "4");
}
2018-05-14 23:33:11 -07:00
#[test]
fn scopes() {
let scope_ok = r#"
2018-07-11 16:44:15 -07:00
let a = 20
2018-05-14 23:33:11 -07:00
fn haha() {
2018-07-11 16:44:15 -07:00
let a = 10
2018-05-14 23:33:11 -07:00
a
}
haha()
"#;
fresh_env!(scope_ok, "10");
let scope_ok = r#"
2018-07-11 16:44:15 -07:00
let a = 20
2018-05-14 23:33:11 -07:00
fn haha() {
2018-07-11 16:44:15 -07:00
let a = 10
2018-05-14 23:33:11 -07:00
a
}
a
"#;
fresh_env!(scope_ok, "20");
}
2018-08-14 21:39:33 -07:00
#[test]
fn basic_patterns() {
let source = r#"
type Option<T> = Some(T) | None
let x = Some(9); if x is Some(q) then { q } else { 0 }"#;
fresh_env!(source, "9");
let source = r#"
type Option<T> = Some(T) | None
let x = None; if x is Some(q) then { q } else { 0 }"#;
fresh_env!(source, "0");
}
2018-05-12 02:18:34 -07:00
}