Added pointer for outer environment

Signed-off-by: teo3300 <matteo.rogora@live.it>
This commit is contained in:
teo3300
2023-06-12 00:54:15 +02:00
parent 58cf35a039
commit d1c56b02bb
5 changed files with 10 additions and 8 deletions

View File

@ -5,12 +5,14 @@ use crate::types::{int_op, MalArgs, MalRet, MalType};
pub struct Env {
map: HashMap<String, MalType>,
outer: Option<Box<Env>>,
}
impl Env {
pub fn new() -> Self {
pub fn new(outer: Option<Box<Env>>) -> Self {
let mut env = Env {
map: HashMap::new(),
outer,
};
env.init();
env

View File

@ -14,7 +14,7 @@ use step2_eval::rep;
fn main() {
let mut num = 0;
let env = Env::new();
let env = Env::new(None);
loop {
let mut input = String::new();

View File

@ -5,7 +5,7 @@ use crate::types::{MalArgs, MalRet, MalType};
fn call_func(func: &MalType, args: MalArgs) -> MalRet {
match func {
Fun(func) => func(args),
_ => panic!("Calling not a function"),
_ => Err(format!("{:?} is not a function", func)),
}
}
@ -28,8 +28,8 @@ pub fn eval(ast: MalType, env: &Env) -> MalRet {
match &ast {
List(list) => {
if list.is_empty() {
Ok(Nil)
// Previously Ok(ast)
// Ok(Nil) // Should be the normal behavior
Ok(ast)
} else {
eval_func(eval_ast(ast, env)?)
}

View File

@ -6,7 +6,7 @@ pub fn pr_str(ast: &MalType, print_readably: bool) -> String {
match ast {
Nil => "nil".to_string(),
Sym(sym) => sym.to_string(),
Key(sym) => sym[1..sym.len() - 1].to_string(),
Key(sym) => sym[2..].to_string(),
Int(val) => val.to_string(),
Bool(val) => val.to_string(),
Str(str) => {

View File

@ -31,7 +31,7 @@ pub type MalErr = String;
pub type MalArgs = Vec<MalType>;
pub type MalRet = Result<MalType, MalErr>;
use MalType::{Key, Map, Str, Sym};
use MalType::{Key, Map, Str};
pub fn make_map(list: MalArgs) -> MalRet {
if list.len() % 2 != 0 {
@ -42,7 +42,7 @@ pub fn make_map(list: MalArgs) -> MalRet {
for i in (0..list.len()).step_by(2) {
match &list[i] {
Sym(k) | Key(k) | Str(k) => {
Key(k) | Str(k) => {
let v = list[i + 1].clone();
map.insert(k.clone(), v);
}