ombre: Strongly typed `nil`
1a46e757b794ca140878824ade6aa7db4052aac3
1 parent
608ba45f
ombre/src/lisp/evaluator.rs
+33 -39
| 243 | 243 | &self.data |
|
| 244 | 244 | } |
|
| 245 | 245 | } |
|
| 246 | 246 | ||
| 247 | 247 | /// Expression in the language. |
|
| 248 | - | #[derive(Debug, Clone, PartialEq)] |
|
| 248 | + | #[derive(Debug, Clone, PartialEq, Default)] |
|
| 249 | 249 | pub enum Expr { |
|
| 250 | + | /// Eg. nil |
|
| 251 | + | #[default] |
|
| 252 | + | Nil, |
|
| 250 | 253 | /// Eg. (1 2 3) or [1 2 3] |
|
| 251 | 254 | Tuple(Tuple), |
|
| 252 | 255 | /// Eg. true |
|
| 253 | 256 | Bool(bool), |
|
| 254 | 257 | /// Eg. 'fnord |
| 283 | 286 | Ref(Rc<RefCell<Expr>>), |
|
| 284 | 287 | /// Dynamic type. Can be any Rust type. |
|
| 285 | 288 | Dynamic(Dynamic), |
|
| 286 | 289 | } |
|
| 287 | 290 | ||
| 288 | - | impl Default for Expr { |
|
| 289 | - | fn default() -> Self { |
|
| 290 | - | Expr::nil() |
|
| 291 | - | } |
|
| 292 | - | } |
|
| 293 | - | ||
| 294 | 291 | impl Expr { |
|
| 295 | - | /// The empty list, or "nil". |
|
| 296 | - | pub fn nil() -> Self { |
|
| 297 | - | Self::Tuple(Tuple::new(vec![])) |
|
| 298 | - | } |
|
| 299 | - | ||
| 300 | 292 | /// Check if this expression is the empty list. |
|
| 301 | 293 | pub fn is_nil(&self) -> bool { |
|
| 302 | - | matches!(self, Self::Tuple(l) if l.is_empty()) |
|
| 294 | + | matches!(self, Self::Nil) |
|
| 303 | 295 | } |
|
| 304 | 296 | ||
| 305 | 297 | /// Construct a tuple. |
|
| 306 | 298 | pub fn tuple(items: impl Into<Vec<Expr>>) -> Self { |
|
| 307 | 299 | Expr::Tuple(Tuple::new(items.into())) |
| 649 | 641 | } |
|
| 650 | 642 | ||
| 651 | 643 | impl fmt::Display for Expr { |
|
| 652 | 644 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 653 | 645 | match self { |
|
| 646 | + | Expr::Nil => write!(f, "nil"), |
|
| 654 | 647 | Expr::Tuple(t) => { |
|
| 655 | 648 | write!(f, "(")?; |
|
| 656 | 649 | let mut iter = t.iter(); |
|
| 657 | 650 | if let Some(first) = iter.next() { |
|
| 658 | 651 | write!(f, "{first}")?; |
| 1219 | 1212 | } |
|
| 1220 | 1213 | } |
|
| 1221 | 1214 | ||
| 1222 | 1215 | /// Evaluate top-level expressions one by one and return the result of the last one. |
|
| 1223 | 1216 | pub fn eval(mut self, env: &mut Env<'_>) -> Result<Expr, Error> { |
|
| 1224 | - | let mut result = Expr::nil(); |
|
| 1217 | + | let mut result = Expr::Nil; |
|
| 1225 | 1218 | ||
| 1226 | 1219 | for expr in self.exprs { |
|
| 1227 | 1220 | let expr = expr.map_err(|e| Error::Parser(Box::new(e)))?; |
|
| 1228 | 1221 | result = eval_module(expr, env, &mut self.modules)?; |
|
| 1229 | 1222 | } |
| 1264 | 1257 | for expr in items { |
|
| 1265 | 1258 | eval_module(expr, &mut env, mods)?; |
|
| 1266 | 1259 | } |
|
| 1267 | 1260 | mods.register(name.clone(), Module { name, docstr, env }); |
|
| 1268 | 1261 | ||
| 1269 | - | Ok(Expr::nil()) |
|
| 1262 | + | Ok(Expr::Nil) |
|
| 1270 | 1263 | } |
|
| 1271 | 1264 | "import" => { |
|
| 1272 | 1265 | let mut iter = tuple.iter().skip(1); |
|
| 1273 | 1266 | let Some(Expr::Symbol(name)) = iter.next() else { |
|
| 1274 | 1267 | return Err(Error::ExpectedValue("symbol")); |
| 1277 | 1270 | Some(m) => m, |
|
| 1278 | 1271 | None => mods.load(name)?, |
|
| 1279 | 1272 | }; |
|
| 1280 | 1273 | env.import(module); |
|
| 1281 | 1274 | ||
| 1282 | - | Ok(Expr::nil()) |
|
| 1275 | + | Ok(Expr::Nil) |
|
| 1283 | 1276 | } |
|
| 1284 | 1277 | "export" => { |
|
| 1285 | 1278 | let mut iter = tuple.data.into_iter().skip(1).peekable(); |
|
| 1286 | 1279 | if iter.peek().is_none() { |
|
| 1287 | 1280 | return Err(Error::WrongArgumentCount { |
| 1293 | 1286 | let Expr::Symbol(s) = s else { |
|
| 1294 | 1287 | return Err(Error::UnexpectedValue(s)); |
|
| 1295 | 1288 | }; |
|
| 1296 | 1289 | env.export(s); |
|
| 1297 | 1290 | } |
|
| 1298 | - | Ok(Expr::nil()) |
|
| 1291 | + | Ok(Expr::Nil) |
|
| 1299 | 1292 | } |
|
| 1300 | 1293 | _ => eval_tuple(tuple, env), |
|
| 1301 | 1294 | } |
|
| 1302 | 1295 | } |
|
| 1303 | 1296 |
| 1354 | 1347 | Ok(iter |
|
| 1355 | 1348 | .into_iter() |
|
| 1356 | 1349 | .map(|e| eval(e, env)) |
|
| 1357 | 1350 | .collect::<Result<Vec<_>>>()? |
|
| 1358 | 1351 | .pop() |
|
| 1359 | - | .unwrap_or(Expr::nil())) |
|
| 1352 | + | .unwrap_or(Expr::Nil)) |
|
| 1360 | 1353 | } |
|
| 1361 | 1354 | ||
| 1362 | 1355 | /// Evaluate a [`Tuple`]. |
|
| 1363 | 1356 | fn eval_tuple(mut tuple: Tuple, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1364 | 1357 | // Literal tuples are not evaluated as function calls. |
| 1369 | 1362 | return Ok(Expr::Tuple(tuple)); |
|
| 1370 | 1363 | } |
|
| 1371 | 1364 | // Evaluate special forms and function application. |
|
| 1372 | 1365 | let mut items = tuple.data.into_iter(); |
|
| 1373 | 1366 | let Some(head) = items.next() else { |
|
| 1374 | - | return Ok(Expr::nil()); |
|
| 1367 | + | return Ok(Expr::tuple([])); |
|
| 1375 | 1368 | }; |
|
| 1376 | 1369 | if let Expr::Symbol(ref name) = head { |
|
| 1377 | 1370 | match name.deref() { |
|
| 1378 | 1371 | "do" => eval_iter(items, env), |
|
| 1379 | 1372 | "def" => { |
| 1403 | 1396 | } |
|
| 1404 | 1397 | other => { |
|
| 1405 | 1398 | env.binding(name, docstr.as_deref(), other); |
|
| 1406 | 1399 | } |
|
| 1407 | 1400 | } |
|
| 1408 | - | Ok(Expr::nil()) |
|
| 1401 | + | Ok(Expr::Nil) |
|
| 1409 | 1402 | } |
|
| 1410 | 1403 | "eval" => { |
|
| 1411 | 1404 | let Some(expr) = items.next() else { |
|
| 1412 | 1405 | return Err(Error::ExpectedValue("expression")); |
|
| 1413 | 1406 | }; |
| 1459 | 1452 | } |
|
| 1460 | 1453 | ||
| 1461 | 1454 | /// The top-level recursive evaluation function. |
|
| 1462 | 1455 | fn eval(expr: Expr, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1463 | 1456 | match expr { |
|
| 1457 | + | Expr::Nil => Ok(Expr::Nil), |
|
| 1464 | 1458 | Expr::Char(c) => Ok(Expr::Char(c)), |
|
| 1465 | 1459 | Expr::Float(n) => Ok(Expr::Float(n)), |
|
| 1466 | 1460 | Expr::Integer(n) => Ok(Expr::Integer(n)), |
|
| 1467 | 1461 | Expr::Function(f) => Ok(Expr::Function(f)), |
|
| 1468 | 1462 | Expr::Color(c) => Ok(Expr::Color(c)), |
| 1523 | 1517 | ("w", Expr::Vector4D(v)) => Ok(Expr::Float(v.w)), |
|
| 1524 | 1518 | (_, Expr::Dict(dict)) => { |
|
| 1525 | 1519 | if let Some(value) = dict.get(&Key::Atom(s)) { |
|
| 1526 | 1520 | Ok(value.clone()) |
|
| 1527 | 1521 | } else { |
|
| 1528 | - | Ok(Expr::nil()) |
|
| 1522 | + | Ok(Expr::Nil) |
|
| 1529 | 1523 | } |
|
| 1530 | 1524 | } |
|
| 1531 | - | _ => Ok(Expr::nil()), |
|
| 1525 | + | _ => Ok(Expr::Nil), |
|
| 1532 | 1526 | } |
|
| 1533 | 1527 | } |
|
| 1534 | 1528 | e => Err(Error::UnexpectedValue(e)), |
|
| 1535 | 1529 | } |
|
| 1536 | 1530 | } |
| 1568 | 1562 | pub fn doc(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1569 | 1563 | let (name,) = <(Symbol,)>::try_from_args(args)?; |
|
| 1570 | 1564 | Ok(env |
|
| 1571 | 1565 | .lookup_doc(&name) |
|
| 1572 | 1566 | .map(|s| Expr::Str(s.to_string())) |
|
| 1573 | - | .unwrap_or(Expr::nil())) |
|
| 1567 | + | .unwrap_or(Expr::Nil)) |
|
| 1574 | 1568 | } |
|
| 1575 | 1569 | ||
| 1576 | 1570 | /// Return the program environment. |
|
| 1577 | 1571 | pub fn env(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1578 | 1572 | if !args.is_empty() { |
| 1717 | 1711 | Err(e) => return Err(Error::UnexpectedValue(e)), |
|
| 1718 | 1712 | }; |
|
| 1719 | 1713 | if let Some(v) = d.get(&k) { |
|
| 1720 | 1714 | Ok(v.clone()) |
|
| 1721 | 1715 | } else { |
|
| 1722 | - | Ok(Expr::nil()) |
|
| 1716 | + | Ok(Expr::Nil) |
|
| 1723 | 1717 | } |
|
| 1724 | 1718 | } |
|
| 1725 | 1719 | ||
| 1726 | 1720 | /// Check if a collection contains a key. |
|
| 1727 | 1721 | pub fn contains(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
| 1767 | 1761 | let Some(Expr::Vector(v)) = args.next() else { |
|
| 1768 | 1762 | return Err(Error::ExpectedValue("vector")); |
|
| 1769 | 1763 | }; |
|
| 1770 | 1764 | v.borrow_mut().extend(args); |
|
| 1771 | 1765 | ||
| 1772 | - | Ok(Expr::nil()) |
|
| 1766 | + | Ok(Expr::Nil) |
|
| 1773 | 1767 | } |
|
| 1774 | 1768 | ||
| 1775 | 1769 | /// Reverse a vector. |
|
| 1776 | 1770 | pub fn reverse(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1777 | 1771 | let (v,) = <(Mut<Vec<Expr>>,)>::try_from_args(args)?; |
|
| 1778 | 1772 | v.borrow_mut().reverse(); |
|
| 1779 | 1773 | ||
| 1780 | - | Ok(Expr::nil()) |
|
| 1774 | + | Ok(Expr::Nil) |
|
| 1781 | 1775 | } |
|
| 1782 | 1776 | ||
| 1783 | 1777 | /// Create a list of numbers in a specified range. |
|
| 1784 | 1778 | pub fn range(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1785 | 1779 | match args.as_slice() { |
| 2008 | 2002 | ||
| 2009 | 2003 | /// Set the value of a mutable reference. |
|
| 2010 | 2004 | pub fn set_ref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 2011 | 2005 | let (r, v) = <(Rc<RefCell<Expr>>, Expr)>::try_from_args(args)?; |
|
| 2012 | 2006 | *r.borrow_mut() = v; |
|
| 2013 | - | Ok(Expr::nil()) |
|
| 2007 | + | Ok(Expr::Nil) |
|
| 2014 | 2008 | } |
|
| 2015 | 2009 | ||
| 2016 | 2010 | /// Modify a mutable reference in-place using a lambda. |
|
| 2017 | 2011 | pub fn modify(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 2018 | 2012 | let (r, f) = <(Rc<RefCell<Expr>>, Function)>::try_from_args(args)?; |
| 2020 | 2014 | let mut old = r.borrow_mut(); |
|
| 2021 | 2015 | let new = f.apply([old.clone()].into_iter(), &mut env)?; |
|
| 2022 | 2016 | ||
| 2023 | 2017 | *old = new; |
|
| 2024 | 2018 | ||
| 2025 | - | Ok(Expr::nil()) |
|
| 2019 | + | Ok(Expr::Nil) |
|
| 2026 | 2020 | } |
|
| 2027 | 2021 | ||
| 2028 | 2022 | /// Create a 2D vector. |
|
| 2029 | 2023 | pub fn vec2(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 2030 | 2024 | let (x, y) = <(f64, f64)>::try_from_args(args)?; |
| 2072 | 2066 | let err = args |
|
| 2073 | 2067 | .next() |
|
| 2074 | 2068 | .unwrap_or_else(|| Expr::Str("assertion failed".to_owned())); |
|
| 2075 | 2069 | return Err(Error::User(err)); |
|
| 2076 | 2070 | } |
|
| 2077 | - | Ok(Expr::nil()) |
|
| 2071 | + | Ok(Expr::Bool(true)) |
|
| 2078 | 2072 | } |
|
| 2079 | 2073 | ||
| 2080 | 2074 | fn fold<T: TryFrom<Expr, Error = Expr> + Into<Expr>>( |
|
| 2081 | 2075 | args: impl IntoIterator<Item = Expr>, |
|
| 2082 | 2076 | init: T, |
| 2456 | 2450 | expect(&["(first [4 3 1])"], Expr::Integer(4)); |
|
| 2457 | 2451 | expect( |
|
| 2458 | 2452 | &["(first [[4 2] 3 1])"], |
|
| 2459 | 2453 | Expr::tuple([Expr::Integer(4), Expr::Integer(2)]), |
|
| 2460 | 2454 | ); |
|
| 2461 | - | expect(&["(first ())"], Expr::nil()); |
|
| 2462 | - | expect(&["(first [])"], Expr::nil()); |
|
| 2455 | + | expect(&["(first ())"], Expr::Nil); |
|
| 2456 | + | expect(&["(first [])"], Expr::Nil); |
|
| 2463 | 2457 | } |
|
| 2464 | 2458 | ||
| 2465 | 2459 | #[test] |
|
| 2466 | 2460 | fn test_last() { |
|
| 2467 | 2461 | expect(&["(last [4 3 1])"], Expr::Integer(1)); |
|
| 2468 | - | expect(&["(last [])"], Expr::nil()); |
|
| 2462 | + | expect(&["(last [])"], Expr::Nil); |
|
| 2469 | 2463 | } |
|
| 2470 | 2464 | ||
| 2471 | 2465 | #[test] |
|
| 2472 | 2466 | fn test_nth() { |
|
| 2473 | 2467 | expect(&["(nth [4 3 1] 1)"], Expr::Integer(3)); |
| 2555 | 2549 | ); |
|
| 2556 | 2550 | } |
|
| 2557 | 2551 | ||
| 2558 | 2552 | #[test] |
|
| 2559 | 2553 | fn test_vector() { |
|
| 2560 | - | expect(&["[]"], Expr::nil()); |
|
| 2554 | + | expect(&["[]"], Expr::tuple([])); |
|
| 2561 | 2555 | expect( |
|
| 2562 | 2556 | &["[1 2 3]"], |
|
| 2563 | 2557 | Expr::tuple([Expr::Integer(1), Expr::Integer(2), Expr::Integer(3)]), |
|
| 2564 | 2558 | ); |
|
| 2565 | 2559 | expect(&["[(+ 1 2)]"], Expr::tuple([Expr::Integer(3)])); |
| 2849 | 2843 | expect(&["(def d (dict [:x 1 :y 2]))", "(:x d)"], Expr::Integer(1)); |
|
| 2850 | 2844 | expect( |
|
| 2851 | 2845 | &["(def d (dict [:a \"hello\" :b \"world\"]))", "(:b d)"], |
|
| 2852 | 2846 | Expr::Str("world".to_owned()), |
|
| 2853 | 2847 | ); |
|
| 2854 | - | expect(&["(def d (dict [:x 1]))", "(:y d)"], Expr::nil()); |
|
| 2848 | + | expect(&["(def d (dict [:x 1]))", "(:y d)"], Expr::Nil); |
|
| 2855 | 2849 | } |
|
| 2856 | 2850 | ||
| 2857 | 2851 | #[test] |
|
| 2858 | 2852 | fn test_vectors() { |
|
| 2859 | 2853 | expect(&["(vec2 1 2)"], Expr::Vector2D(Vector2D::new(1.0, 2.0))); |
| 2898 | 2892 | "(def answer \"The answer to life, the universe and everything.\" 42)", |
|
| 2899 | 2893 | "(doc 'answer)", |
|
| 2900 | 2894 | ], |
|
| 2901 | 2895 | Expr::Str("The answer to life, the universe and everything.".to_string()), |
|
| 2902 | 2896 | ); |
|
| 2903 | - | expect(&["(doc 'undefined)"], Expr::nil()); |
|
| 2897 | + | expect(&["(doc 'undefined)"], Expr::Nil); |
|
| 2904 | 2898 | } |
|
| 2905 | 2899 | ||
| 2906 | 2900 | #[test] |
|
| 2907 | 2901 | fn test_assert() { |
|
| 2908 | - | expect(&["(assert true)"], Expr::nil()); |
|
| 2902 | + | expect(&["(assert true)"], Expr::Bool(true)); |
|
| 2909 | 2903 | expect_err( |
|
| 2910 | 2904 | &["(assert false)"], |
|
| 2911 | 2905 | Error::User(Expr::Str("assertion failed".to_owned())), |
|
| 2912 | 2906 | ); |
|
| 2913 | 2907 | expect_err( |
| 2944 | 2938 | expect(&["(:x (vec4 1 2 3 4))"], Expr::Float(1.0)); |
|
| 2945 | 2939 | expect(&["(:y (vec4 1 2 3 4))"], Expr::Float(2.0)); |
|
| 2946 | 2940 | expect(&["(:z (vec4 1 2 3 4))"], Expr::Float(3.0)); |
|
| 2947 | 2941 | expect(&["(:w (vec4 1 2 3 4))"], Expr::Float(4.0)); |
|
| 2948 | 2942 | ||
| 2949 | - | expect(&["(:w (vec2 1 2))"], Expr::nil()); |
|
| 2950 | - | expect(&["(:w (vec3 1 2 3))"], Expr::nil()); |
|
| 2951 | - | expect(&["(:q (vec4 1 2 3 4))"], Expr::nil()); |
|
| 2943 | + | expect(&["(:w (vec2 1 2))"], Expr::Nil); |
|
| 2944 | + | expect(&["(:w (vec3 1 2 3))"], Expr::Nil); |
|
| 2945 | + | expect(&["(:q (vec4 1 2 3 4))"], Expr::Nil); |
|
| 2952 | 2946 | } |
|
| 2953 | 2947 | ||
| 2954 | 2948 | #[test] |
|
| 2955 | 2949 | #[ignore = "not implemented yet"] |
|
| 2956 | 2950 | fn test_modules_nested() { |
ombre/src/lisp/parser.rs
+5 -8
| 83 | 83 | Token::RParen => return Err(Error::UnexpectedToken(token.owned())), |
|
| 84 | 84 | Token::LBrace => self.parse_dict()?, |
|
| 85 | 85 | Token::RBrace => return Err(Error::UnexpectedToken(token.owned())), |
|
| 86 | 86 | Token::LBracket => self.parse_tuple_lit().map(|es| { |
|
| 87 | 87 | if es.is_empty() { |
|
| 88 | - | Expr::nil() |
|
| 88 | + | Expr::Tuple(Tuple::new([])) |
|
| 89 | 89 | } else { |
|
| 90 | 90 | Expr::Tuple(Tuple::literal(es)) |
|
| 91 | 91 | } |
|
| 92 | 92 | })?, |
|
| 93 | 93 | Token::RBracket => return Err(Error::UnexpectedToken(token.owned())), |
|
| 94 | 94 | Token::Quote => self.parse_quoted()?, |
|
| 95 | 95 | Token::Ref => self.parse_ref()?, |
|
| 96 | 96 | Token::Symbol(s) => { |
|
| 97 | 97 | self.tokens.next(); |
|
| 98 | 98 | match s.deref() { |
|
| 99 | + | "nil" => Expr::Nil, |
|
| 99 | 100 | "true" => Expr::Bool(true), |
|
| 100 | 101 | "false" => Expr::Bool(false), |
|
| 101 | 102 | _ => Expr::Symbol(Symbol::from(Rc::from(s))), |
|
| 102 | 103 | } |
|
| 103 | 104 | } |
| 274 | 275 | ); |
|
| 275 | 276 | } |
|
| 276 | 277 | ||
| 277 | 278 | #[test] |
|
| 278 | 279 | fn test_parse_tuple() { |
|
| 279 | - | ok("()", &[Expr::nil()]); |
|
| 280 | + | ok("()", &[Expr::tuple([])]); |
|
| 280 | 281 | ok("(cons)", &[Expr::tuple([Expr::Symbol("cons".into())])]); |
|
| 281 | 282 | ok( |
|
| 282 | 283 | "(+ 4 2)", |
|
| 283 | 284 | &[Expr::tuple([ |
|
| 284 | 285 | Expr::Symbol("+".into()), |
|
| 285 | 286 | Expr::Integer(4), |
|
| 286 | 287 | Expr::Integer(2), |
|
| 287 | 288 | ])], |
|
| 288 | 289 | ); |
|
| 289 | - | ok("[]", &[Expr::nil()]); |
|
| 290 | + | ok("[]", &[Expr::tuple([])]); |
|
| 290 | 291 | ok( |
|
| 291 | 292 | "[1 2 3]", |
|
| 292 | 293 | &[Tuple::literal([Expr::Integer(1), Expr::Integer(2), Expr::Integer(3)]).into()], |
|
| 293 | 294 | ); |
|
| 294 | 295 | } |
| 301 | 302 | Expr::Symbol("cons".into()), |
|
| 302 | 303 | Expr::Integer(1), |
|
| 303 | 304 | Expr::tuple([ |
|
| 304 | 305 | Expr::Symbol("cons".into()), |
|
| 305 | 306 | Expr::Integer(2), |
|
| 306 | - | Expr::tuple([ |
|
| 307 | - | Expr::Symbol("cons".into()), |
|
| 308 | - | Expr::Integer(3), |
|
| 309 | - | Expr::Symbol("nil".into()), |
|
| 310 | - | ]), |
|
| 307 | + | Expr::tuple([Expr::Symbol("cons".into()), Expr::Integer(3), Expr::Nil]), |
|
| 311 | 308 | ]), |
|
| 312 | 309 | ])], |
|
| 313 | 310 | ); |
|
| 314 | 311 | } |
|
| 315 | 312 |