ombre: Support lisp dictionary lookups with `:x`
9236b3332af7986c648e3b6768f1971c45479470
1 parent
b9f7c9d4
ombre/src/lisp/evaluator.rs
+28 -2
| 1114 | 1114 | ||
| 1115 | 1115 | /// Function application. |
|
| 1116 | 1116 | fn apply(f: Expr, args: impl Iterator<Item = Expr>, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1117 | 1117 | match eval(f, env)? { |
|
| 1118 | 1118 | Expr::Function(f) => f.apply(args, env), |
|
| 1119 | - | _ => Err(Error::ExpectedValue("function")), |
|
| 1119 | + | Expr::Atom(s) => { |
|
| 1120 | + | let args: Vec<_> = args.map(|a| eval(a, env)).collect::<Result<_>>()?; |
|
| 1121 | + | let arity = args.len(); |
|
| 1122 | + | let Ok([dict]) = <[_; 1]>::try_from(args) else { |
|
| 1123 | + | return Err(Error::WrongArgumentCount { |
|
| 1124 | + | expected: 1, |
|
| 1125 | + | actual: arity, |
|
| 1126 | + | }); |
|
| 1127 | + | }; |
|
| 1128 | + | if let Expr::Dict(dict) = dict { |
|
| 1129 | + | if let Some(value) = dict.get(&Key::Atom(s)) { |
|
| 1130 | + | return Ok(value.clone()); |
|
| 1131 | + | } |
|
| 1132 | + | } |
|
| 1133 | + | Ok(Expr::nil()) |
|
| 1134 | + | } |
|
| 1135 | + | _ => Err(Error::ExpectedValue("function or atom")), |
|
| 1120 | 1136 | } |
|
| 1121 | 1137 | } |
|
| 1122 | 1138 | ||
| 1123 | 1139 | /// Return pairs from a list of expressions. |
|
| 1124 | 1140 | fn pairs(exprs: Vec<Expr>) -> Result<Vec<(Expr, Expr)>> { |
| 2149 | 2165 | expect( |
|
| 2150 | 2166 | &["{+ 1 2}"], |
|
| 2151 | 2167 | Expr::list([Expr::Symbol("+".into()), Expr::Integer(1), Expr::Integer(2)]), |
|
| 2152 | 2168 | ); |
|
| 2153 | 2169 | expect(&["(eq? {} ())"], Expr::Bool(true)); |
|
| 2154 | - | expect_err(&["(list (4 2))"], Error::ExpectedValue("function")); |
|
| 2170 | + | expect_err(&["(list (4 2))"], Error::ExpectedValue("function or atom")); |
|
| 2155 | 2171 | } |
|
| 2156 | 2172 | ||
| 2157 | 2173 | #[test] |
|
| 2158 | 2174 | fn test_cons() { |
|
| 2159 | 2175 | expect(&["(cons)"], Expr::list([])); |
| 2403 | 2419 | ], |
|
| 2404 | 2420 | Expr::Integer(6), |
|
| 2405 | 2421 | ); |
|
| 2406 | 2422 | } |
|
| 2407 | 2423 | ||
| 2424 | + | #[test] |
|
| 2425 | + | fn test_atom_dict_lookup() { |
|
| 2426 | + | expect(&["(def d (dict [:x 1 :y 2]))", "(:x d)"], Expr::Integer(1)); |
|
| 2427 | + | expect( |
|
| 2428 | + | &["(def d (dict [:a \"hello\" :b \"world\"]))", "(:b d)"], |
|
| 2429 | + | Expr::Str("world".to_owned()), |
|
| 2430 | + | ); |
|
| 2431 | + | expect(&["(def d (dict [:x 1]))", "(:y d)"], Expr::nil()); |
|
| 2432 | + | } |
|
| 2433 | + | ||
| 2408 | 2434 | #[test] |
|
| 2409 | 2435 | #[ignore = "not implemented yet"] |
|
| 2410 | 2436 | fn test_modules_nested() { |
|
| 2411 | 2437 | expect( |
|
| 2412 | 2438 | &[ |