diff options
Diffstat (limited to 'src/simple.rs')
-rw-r--r-- | src/simple.rs | 32 |
1 files changed, 19 insertions, 13 deletions
diff --git a/src/simple.rs b/src/simple.rs index 9393c00..b7ef94a 100644 --- a/src/simple.rs +++ b/src/simple.rs @@ -12,27 +12,33 @@ pub fn check(context: Context, expression: Expression) { /// Evaluates an expression given a context (of variables) to a term. /// Panics on non-evaluatable code. -pub fn execute(context: Context, expression: Expression) -> Term { +pub fn execute(context: Context, expression: Expression) -> Result<Term, &'static str> { match expression { - Expression::Annotation { expr, .. } => return execute(context, *expr), - Expression::Constant { term } => return term, - Expression::Variable { id } => return context[&id], - Expression::Abstraction { .. } => panic!("attempting to execute an abstraction"), + Expression::Annotation { expr, .. } => execute(context, *expr), + Expression::Constant { term } => Ok(term), + Expression::Variable { id } => context.get(&id).ok_or("no such variable in context").map(|x| *x), + Expression::Abstraction { .. } => Err("attempting to execute an abstraction"), Expression::Application { func, arg } => { match *func { Expression::Abstraction { param, func } => { - let mut context = context; - context.insert(param, execute(context.clone(), *arg)); - return execute(context, *func); + let result = execute(context.clone(), *arg); + match result { + Ok(value) => { + let mut context = context; + context.insert(param, value); + return execute(context, *func); + }, + Err(e) => Err(e) + } }, - _ => panic!("attempting to execute an application to nothing") + _ => Err("attempting to execute an application to nothing") } }, Expression::Conditional { if_cond, if_then, if_else } => { - match execute(context.clone(), *if_cond).val { - 1 => execute(context, *if_then), - 0 => execute(context, *if_else), - _ => panic!("invalid type for a conditional") + match execute(context.clone(), *if_cond) { + Ok(Term { val: 1, .. }) => execute(context, *if_then), + Ok(Term { val: 0, .. }) => execute(context, *if_else), + _ => Err("invalid type for a conditional") } }, } |