mirror of
https://github.com/teo3300/rust-mal.git
synced 2026-01-12 01:05:32 +01:00
Added pointer for outer environment
Signed-off-by: teo3300 <matteo.rogora@live.it>
This commit is contained in:
@ -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
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -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)?)
|
||||
}
|
||||
|
||||
@ -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) => {
|
||||
|
||||
@ -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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user