completed index op on hashtable, added puts builtin

This commit is contained in:
Ishan Jain 2024-05-28 11:14:11 +05:30
parent f51ead1641
commit 4e4cec0732
Signed by: ishan
GPG Key ID: 0506DB2A1CC75C27
4 changed files with 24 additions and 5 deletions

View File

@ -1,4 +1,5 @@
# Monkey Interpreter
This project is my attempt at writing an interpreter while working through the book, [Writing an Interpreter in Go](https://interpreterbook.com/).
It supports all the features from the book.
This language supports integers, strings, hashtables, functions, closures, arrays, if/else and more!

View File

@ -19,6 +19,7 @@ pub const BUILTINS: LazyCell<HashMap<&'static str, Object>> = LazyCell::new(|| {
match &args[0] {
Object::String(s) => Object::Integer(s.len() as i64),
Object::Array(s) => Object::Integer(s.elements.len() as i64),
Object::Hash(h) => Object::Integer(h.pairs.len() as i64),
v => Object::Error(format!("argument to `len` not supported, got {}", v)),
}
}),
@ -110,5 +111,17 @@ pub const BUILTINS: LazyCell<HashMap<&'static str, Object>> = LazyCell::new(|| {
}),
}),
);
map.insert(
"puts",
Object::Builtin(BuiltinFunction {
func: Box::new(|args: Vec<Object>| {
for arg in args {
println!("{}", arg.inspect());
}
Object::Null
}),
}),
);
map
});

View File

@ -517,6 +517,7 @@ mod tests {
elements: vec![Object::Integer(1), Object::Integer(5)],
})),
),
("len({\"foo\": \"bar\"})", Some(Object::Integer(1))),
];
run_test_cases(&test_cases);

View File

@ -318,10 +318,14 @@ impl TreeWalker {
}
fn eval_hash_index_expression(&self, left: &HashObject, index: Object) -> Option<Object> {
Some(Object::Error(format!(
"index operator not supported: {:?}",
left
)))
if let Object::Function(_) = index {
return Some(Object::Error(format!("unusable as hash key: {}", index)));
}
match left.pairs.get(&index) {
Some(v) => Some(v.clone()),
None => Some(Object::Null),
}
}
fn eval_array_index_expression(array: &Array, index: i64) -> Object {
let max = array.elements.len() as i64;