Initial version of environment model

This commit is contained in:
2021-05-27 21:02:18 -04:00
parent 56f5426426
commit 794cad2219
4 changed files with 74 additions and 36 deletions

View File

@@ -1,8 +1,9 @@
use crate::parser::Datum;
use crate::parser::Datum::*;
use crate::primitives::*;
use crate::environment;
use crate::environment::Env;
use std::mem;
fn is_true(exp: &Datum) -> bool {
match exp {
Boolean(b) => *b,
@@ -12,28 +13,20 @@ fn is_true(exp: &Datum) -> bool {
}
}
fn lookup_variable_value(exp: &Datum) -> Datum {
if let Symbol(string) = exp {
match string.as_str() {
"+" => Procedure(add),
"*" => Procedure(mul),
"-" => Procedure(sub),
_ => panic!("LOOKUP-VARIABLE-VALUE -- unbound-variable {:?}", string),
}
} else {
panic!("LOOKUP-VARIABLE-VALUE -- not-a-symbol {:?}", exp)
}
}
fn application(exp: Datum) -> Datum {
fn application(exp: &Datum, env: &Env) -> Datum {
if let List(vector) = exp {
if vector.len() == 0 {
panic!("APPLICATION -- no-procedure")
}
let mut args = vec![];
for v in vector {
let a = interpret(v, env);
args.push(a)
}
let mut args: Vec<Datum> = vector.into_iter().map(interpret).collect();
// let mut args: Vec<Datum> = vector.into_iter().map(interpret).collect();
if let Procedure(proc) = mem::take(&mut args[0]) {
// FIXME: call procedures with args only
proc(args)
} else {
panic!("APPLICATION -- not-aplicable {:?}", args[0])
@@ -57,34 +50,39 @@ fn has_tag(exp: &Datum, tag: &str) -> bool {
false
}
fn interpret_if(mut args: Vec<Datum>) -> Datum {
let predicate = mem::take(&mut args[1]);
let alternative = mem::take(&mut args[2]);
fn interpret_if(args: &Vec<Datum>, env: &Env) -> Datum {
let predicate = &args[1];
let alternative = &args[2];
if is_true(&predicate) {
interpret(alternative)
interpret(&alternative, env)
} else {
if args.len() == 4 {
let consequent = mem::take(&mut args[3]);
interpret(consequent)
let consequent = &args[3];
interpret(&consequent, env)
} else {
Unspecified
}
}
}
pub fn interpret(exp: Datum) -> Datum {
fn interpret_define(_args: &Vec<Datum>) -> Datum {
Number(42)
}
pub fn interpret(exp: &Datum, env: &Env) -> Datum {
match exp {
Boolean(_) => exp,
Number(_) => exp,
Symbol(_) => lookup_variable_value(&exp),
List(v) if has_tag(&exp, "if") => interpret_if(v),
Boolean(b) => Boolean(*b),
Number(n) => Number(*n),
Symbol(_) => environment::lookup_variable_value(&exp, &env),
List(v) if has_tag(&exp, "if") => interpret_if(v, &env),
List(_) if has_tag(&exp, "set!") => panic!("assignment-not-supported"),
List(_) if has_tag(&exp, "define") => panic!("define-not-supported"),
List(v) if has_tag(&exp, "define") => interpret_define(v),
List(_) if has_tag(&exp, "cond") => panic!("cond-not-supported"),
List(_) if has_tag(&exp, "let") => panic!("let-not-supported"),
List(_) if has_tag(&exp, "begin") => panic!("begin-not-supported"),
List(_) => application(exp),
List(_) => application(exp, env),
// TODO: quoted
_ => panic!("unknown-expression {:?}", exp),
}