ombre: Simplify list handling to only one type
c762818817e0f710e33afc5b0aa3bd4ef08874c6
1 parent
1c2549c9
ombre/src/lisp.rs
+0 -1
| 8 | 8 | //! 3. Evaluator: Evaluates the program represented by the AST |
|
| 9 | 9 | //! |
|
| 10 | 10 | //! Each phase is an iterator which feeds into the next. |
|
| 11 | 11 | pub mod dynamic; |
|
| 12 | 12 | pub mod evaluator; |
|
| 13 | - | pub mod list; |
|
| 14 | 13 | pub mod parser; |
|
| 15 | 14 | pub mod scanner; |
|
| 16 | 15 | ||
| 17 | 16 | use std::error; |
|
| 18 | 17 |
ombre/src/lisp/evaluator.rs
+40 -99
| 9 | 9 | use std::{collections::HashMap, iter::Peekable}; |
|
| 10 | 10 | use std::{fmt, fs, iter, result}; |
|
| 11 | 11 | ||
| 12 | 12 | use crate::gfx::Rgba; |
|
| 13 | 13 | use crate::lisp::dynamic::{Dynamic, IsDynamic}; |
|
| 14 | - | use crate::lisp::list::List; |
|
| 15 | 14 | use crate::math::{Vector2D, Vector3D, Vector4D}; |
|
| 16 | 15 | ||
| 17 | 16 | use super::{Parser, Scanner, FILE_EXTENSION}; |
|
| 18 | 17 | ||
| 19 | 18 | /// Result type for all functions. |
| 205 | 204 | ||
| 206 | 205 | /// Expression in the language. |
|
| 207 | 206 | #[derive(Debug, Clone, PartialEq)] |
|
| 208 | 207 | pub enum Expr { |
|
| 209 | 208 | /// Eg. (1 2 3) |
|
| 210 | - | List(List<Expr>), |
|
| 209 | + | List(Vec<Expr>), |
|
| 211 | 210 | /// Eg. :true |
|
| 212 | 211 | Bool(bool), |
|
| 213 | 212 | /// Eg. 'fnord |
|
| 214 | 213 | Quoted(Box<Expr>), |
|
| 215 | 214 | /// Eg. [1 2 3] |
| 245 | 244 | } |
|
| 246 | 245 | ||
| 247 | 246 | impl Expr { |
|
| 248 | 247 | /// The empty list, or "nil". |
|
| 249 | 248 | pub fn nil() -> Self { |
|
| 250 | - | Self::List(List::default()) |
|
| 249 | + | Self::List(vec![]) |
|
| 251 | 250 | } |
|
| 252 | 251 | ||
| 253 | 252 | /// Check if this expression is the empty list. |
|
| 254 | 253 | pub fn is_nil(&self) -> bool { |
|
| 255 | 254 | matches!(self, Self::List(l) if l.is_empty()) |
|
| 256 | 255 | } |
|
| 257 | 256 | ||
| 258 | 257 | /// Construct a list. |
|
| 259 | - | pub fn list(items: impl Into<List<Expr>>) -> Self { |
|
| 258 | + | pub fn list(items: impl Into<Vec<Expr>>) -> Self { |
|
| 260 | 259 | Expr::List(items.into()) |
|
| 261 | 260 | } |
|
| 262 | 261 | ||
| 263 | 262 | /// Construct a vector. |
|
| 264 | 263 | pub fn vector(items: impl IntoIterator<Item = Expr>) -> Self { |
| 415 | 414 | impl TryFrom<Expr> for Vec<Expr> { |
|
| 416 | 415 | type Error = Expr; |
|
| 417 | 416 | ||
| 418 | 417 | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 419 | 418 | match expr { |
|
| 419 | + | Expr::List(v) => Ok(v), |
|
| 420 | 420 | Expr::Vector(v) => Ok(v), |
|
| 421 | 421 | _ => Err(expr), |
|
| 422 | 422 | } |
|
| 423 | 423 | } |
|
| 424 | 424 | } |
|
| 425 | 425 | ||
| 426 | - | impl TryFrom<Expr> for List<Expr> { |
|
| 427 | - | type Error = Expr; |
|
| 428 | - | ||
| 429 | - | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 430 | - | match expr { |
|
| 431 | - | Expr::List(l) => Ok(l), |
|
| 432 | - | _ => Err(expr), |
|
| 433 | - | } |
|
| 434 | - | } |
|
| 435 | - | } |
|
| 436 | - | ||
| 437 | 426 | impl TryFrom<Expr> for Vector2D<f64> { |
|
| 438 | 427 | type Error = Expr; |
|
| 439 | 428 | ||
| 440 | 429 | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 441 | 430 | match expr { |
| 1048 | 1037 | env.intrinsic( |
|
| 1049 | 1038 | "lookup", |
|
| 1050 | 1039 | "Lookup a value in a dictionary, under the given key", |
|
| 1051 | 1040 | intrinsic::lookup, |
|
| 1052 | 1041 | ); |
|
| 1053 | - | env.intrinsic( |
|
| 1054 | - | "cons", |
|
| 1055 | - | "Construct a new list from a value and an existing list", |
|
| 1056 | - | intrinsic::cons, |
|
| 1057 | - | ); |
|
| 1058 | 1042 | env.intrinsic( |
|
| 1059 | 1043 | "map", |
|
| 1060 | 1044 | "Apply a function to each element of a list or vector", |
|
| 1061 | 1045 | intrinsic::map, |
|
| 1062 | 1046 | ); |
| 1136 | 1120 | modules: ModuleRegistry::default(), |
|
| 1137 | 1121 | exprs: exprs.peekable(), |
|
| 1138 | 1122 | } |
|
| 1139 | 1123 | } |
|
| 1140 | 1124 | ||
| 1141 | - | /// Evaluate expressions one by one and return the result of the last one. |
|
| 1125 | + | /// Evaluate top-level expressions one by one and return the result of the last one. |
|
| 1142 | 1126 | pub fn eval(mut self, env: &mut Env<'_>) -> Result<Expr, Error> { |
|
| 1143 | 1127 | let mut result = Expr::nil(); |
|
| 1144 | 1128 | ||
| 1145 | 1129 | for expr in self.exprs { |
|
| 1146 | 1130 | let expr = expr.map_err(|e| Error::Parser(Box::new(e)))?; |
| 1148 | 1132 | } |
|
| 1149 | 1133 | Ok(result) |
|
| 1150 | 1134 | } |
|
| 1151 | 1135 | } |
|
| 1152 | 1136 | ||
| 1153 | - | /// Evaluate a module definition. Modules can only exist at the root, or at the top level of |
|
| 1154 | - | /// another module. |
|
| 1137 | + | /// Evaluate a top-level expression. |
|
| 1138 | + | /// These expressions can only exist at the root, or at the top level of a module. |
|
| 1155 | 1139 | pub fn eval_module(expr: Expr, env: &mut Env<'_>, mods: &mut ModuleRegistry) -> Result<Expr> { |
|
| 1156 | 1140 | let Expr::List(list) = expr else { |
|
| 1141 | + | // If the expression is not a list, then it's not a special form and can be evaluated |
|
| 1142 | + | // with the regular eval function. |
|
| 1157 | 1143 | return eval(expr, env); |
|
| 1158 | 1144 | }; |
|
| 1159 | - | let Some(Expr::Symbol(ref head)) = list.head() else { |
|
| 1145 | + | let Some(Expr::Symbol(head)) = list.first() else { |
|
| 1146 | + | // If the list doesn't start with a symbol, we just evaluate it as a regular list. |
|
| 1160 | 1147 | return eval_list(list, env); |
|
| 1161 | 1148 | }; |
|
| 1162 | - | let tail = list.tail(); |
|
| 1163 | 1149 | ||
| 1150 | + | // Handle special top-level forms. |
|
| 1164 | 1151 | match head.deref() { |
|
| 1165 | 1152 | "def" => { |
|
| 1166 | - | let mut items = tail.iter().cloned(); // TODO: Can we avoid cloning here? |
|
| 1167 | - | let sym = items.next().ok_or(Error::ExpectedValue("symbol"))?; |
|
| 1153 | + | let mut iter = list.into_iter().skip(1); |
|
| 1154 | + | let sym = iter.next().ok_or(Error::ExpectedValue("symbol"))?; |
|
| 1168 | 1155 | let Expr::Symbol(name) = sym else { |
|
| 1169 | 1156 | return Err(Error::UnexpectedValue(sym)); |
|
| 1170 | 1157 | }; |
|
| 1171 | - | let (docstr, value) = match (items.next(), items.next()) { |
|
| 1158 | + | let (docstr, value) = match (iter.next(), iter.next()) { |
|
| 1172 | 1159 | (Some(Expr::Str(docstr)), Some(value)) => (Some(docstr), value), |
|
| 1173 | 1160 | (Some(value), None) => (None, value), |
|
| 1174 | 1161 | ||
| 1175 | 1162 | _ => return Err(Error::ExpectedValue("expression")), |
|
| 1176 | 1163 | }; |
| 1193 | 1180 | } |
|
| 1194 | 1181 | } |
|
| 1195 | 1182 | Ok(Expr::nil()) |
|
| 1196 | 1183 | } |
|
| 1197 | 1184 | "module" => { |
|
| 1198 | - | let mut items = tail.iter().cloned().peekable(); |
|
| 1185 | + | let mut items = list.into_iter().skip(1).peekable(); |
|
| 1199 | 1186 | let Some(Expr::Symbol(name)) = items.next() else { |
|
| 1200 | 1187 | return Err(Error::ExpectedValue("symbol")); |
|
| 1201 | 1188 | }; |
|
| 1202 | 1189 | // Get optional doc string. |
|
| 1203 | 1190 | let docstr = if let Some(Expr::Str(ref docstr)) = items.peek().cloned() { |
| 1215 | 1202 | mods.register(name.clone(), Module { name, docstr, env }); |
|
| 1216 | 1203 | ||
| 1217 | 1204 | Ok(Expr::nil()) |
|
| 1218 | 1205 | } |
|
| 1219 | 1206 | "import" => { |
|
| 1220 | - | let mut items = tail.iter().cloned(); |
|
| 1221 | - | let Some(Expr::Symbol(name)) = items.next() else { |
|
| 1207 | + | let mut iter = list.into_iter().skip(1); |
|
| 1208 | + | let Some(Expr::Symbol(name)) = iter.next() else { |
|
| 1222 | 1209 | return Err(Error::ExpectedValue("symbol")); |
|
| 1223 | 1210 | }; |
|
| 1224 | 1211 | let module = match mods.lookup(&name) { |
|
| 1225 | 1212 | Some(m) => m, |
|
| 1226 | 1213 | None => mods.load(&name)?, |
| 1228 | 1215 | env.import(module); |
|
| 1229 | 1216 | ||
| 1230 | 1217 | Ok(Expr::nil()) |
|
| 1231 | 1218 | } |
|
| 1232 | 1219 | "export" => { |
|
| 1233 | - | if tail.is_empty() { |
|
| 1220 | + | let mut iter = list.into_iter().skip(1).peekable(); |
|
| 1221 | + | if iter.peek().is_none() { |
|
| 1234 | 1222 | return Err(Error::WrongArgumentCount { |
|
| 1235 | 1223 | expected: 1, |
|
| 1236 | 1224 | actual: 0, |
|
| 1237 | 1225 | }); |
|
| 1238 | 1226 | } |
|
| 1239 | - | for s in tail.iter().cloned() { |
|
| 1227 | + | for s in iter { |
|
| 1240 | 1228 | let Expr::Symbol(s) = s else { |
|
| 1241 | 1229 | return Err(Error::UnexpectedValue(s)); |
|
| 1242 | 1230 | }; |
|
| 1243 | 1231 | env.export(s); |
|
| 1244 | 1232 | } |
| 1305 | 1293 | .pop() |
|
| 1306 | 1294 | .unwrap_or(Expr::nil())) |
|
| 1307 | 1295 | } |
|
| 1308 | 1296 | ||
| 1309 | 1297 | /// Evaluate special forms and function application. |
|
| 1310 | - | fn eval_list(sexpr: List<Expr>, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1311 | - | let mut items = sexpr.iter().cloned(); // TODO: Can we avoid cloning here? |
|
| 1298 | + | fn eval_list(sexpr: Vec<Expr>, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1299 | + | let mut items = sexpr.into_iter(); |
|
| 1312 | 1300 | let Some(head) = items.next() else { |
|
| 1313 | 1301 | return Ok(Expr::nil()); |
|
| 1314 | 1302 | }; |
|
| 1315 | 1303 | if let Expr::Symbol(ref name) = head { |
|
| 1316 | 1304 | match name.deref() { |
| 1451 | 1439 | } |
|
| 1452 | 1440 | } |
|
| 1453 | 1441 | _ => Ok(Expr::nil()), |
|
| 1454 | 1442 | } |
|
| 1455 | 1443 | } |
|
| 1456 | - | _ => Err(Error::ExpectedValue("function or atom")), |
|
| 1444 | + | e => Err(Error::UnexpectedValue(e)), |
|
| 1457 | 1445 | } |
|
| 1458 | 1446 | } |
|
| 1459 | 1447 | ||
| 1460 | 1448 | /// Return pairs from a list of expressions. |
|
| 1461 | 1449 | fn pairs(exprs: Vec<Expr>) -> Result<Vec<(Expr, Expr)>> { |
| 1512 | 1500 | Ok(Expr::Dict(dict)) |
|
| 1513 | 1501 | } |
|
| 1514 | 1502 | ||
| 1515 | 1503 | /// Get the first item of a list. |
|
| 1516 | 1504 | pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1517 | - | let (expr,) = <(Expr,)>::try_from_args(args)?; |
|
| 1518 | - | match expr { |
|
| 1519 | - | Expr::List(l) => Ok(l.head().cloned().unwrap_or(Expr::nil())), |
|
| 1520 | - | Expr::Vector(v) => Ok(v.into_iter().next().unwrap_or(Expr::nil())), |
|
| 1521 | - | _ => Err(Error::ExpectedValue("list or vector")), |
|
| 1522 | - | } |
|
| 1505 | + | let (list,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1506 | + | Ok(list.into_iter().next().unwrap_or(Expr::nil())) |
|
| 1523 | 1507 | } |
|
| 1524 | 1508 | ||
| 1525 | 1509 | /// Get the last item of a vector. |
|
| 1526 | 1510 | pub fn last(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1527 | 1511 | let (v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
| 1534 | 1518 | Ok(vec.into_iter().nth(idx as usize).unwrap_or(Expr::nil())) |
|
| 1535 | 1519 | } |
|
| 1536 | 1520 | ||
| 1537 | 1521 | /// Map function. |
|
| 1538 | 1522 | pub fn map(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1539 | - | let (f, collection) = <(Function, Expr)>::try_from_args(args)?; |
|
| 1523 | + | let (f, list) = <(Function, Vec<Expr>)>::try_from_args(args)?; |
|
| 1540 | 1524 | let mut env = Env::from_parent(env); |
|
| 1541 | 1525 | ||
| 1542 | - | match collection { |
|
| 1543 | - | Expr::List(l) => l |
|
| 1544 | - | .iter() |
|
| 1545 | - | .cloned() |
|
| 1546 | - | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1547 | - | .collect::<Result<Vec<_>>>() |
|
| 1548 | - | .map(List::from) |
|
| 1549 | - | .map(Expr::List), |
|
| 1550 | - | Expr::Vector(l) => l |
|
| 1551 | - | .into_iter() |
|
| 1552 | - | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1553 | - | .collect::<Result<Vec<_>>>() |
|
| 1554 | - | .map(Expr::Vector), |
|
| 1555 | - | _ => Err(Error::ExpectedValue("list or vector")), |
|
| 1556 | - | } |
|
| 1526 | + | list.into_iter() |
|
| 1527 | + | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1528 | + | .collect::<Result<Vec<_>>>() |
|
| 1529 | + | .map(Expr::Vector) |
|
| 1557 | 1530 | } |
|
| 1558 | 1531 | ||
| 1559 | 1532 | /// Return the length of a value. |
|
| 1560 | 1533 | pub fn length(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1561 | 1534 | let (value,) = <(Expr,)>::try_from_args(args)?; |
| 1584 | 1557 | Ok(Expr::Bool(is_empty)) |
|
| 1585 | 1558 | } |
|
| 1586 | 1559 | ||
| 1587 | 1560 | /// Create a list. |
|
| 1588 | 1561 | pub fn list(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1589 | - | Ok(Expr::List(args.into())) |
|
| 1562 | + | Ok(Expr::List(args)) |
|
| 1590 | 1563 | } |
|
| 1591 | 1564 | ||
| 1592 | 1565 | /// Create a dictionary. |
|
| 1593 | 1566 | pub fn dict(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1594 | 1567 | if args.is_empty() { |
|
| 1595 | 1568 | return Ok(Expr::Dict(HashMap::new())); |
|
| 1596 | 1569 | } |
|
| 1597 | - | let arity = args.len(); |
|
| 1598 | - | let Ok([expr]) = <[_; 1]>::try_from(args) else { |
|
| 1599 | - | return Err(Error::WrongArgumentCount { |
|
| 1600 | - | expected: 1, |
|
| 1601 | - | actual: arity, |
|
| 1602 | - | }); |
|
| 1603 | - | }; |
|
| 1604 | - | ||
| 1605 | - | let mut iter: Box<dyn Iterator<Item = Expr>> = match expr { |
|
| 1606 | - | Expr::Vector(v) => Box::new(v.into_iter()), |
|
| 1607 | - | Expr::List(l) => Box::new(l.into_iter()), |
|
| 1608 | - | _ => return Err(Error::ExpectedValue("list")), |
|
| 1609 | - | }; |
|
| 1570 | + | let (list,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1610 | 1571 | let mut dict = HashMap::new(); |
|
| 1572 | + | let mut iter = list.into_iter(); |
|
| 1611 | 1573 | ||
| 1612 | 1574 | while let Some(k) = iter.next() { |
|
| 1613 | 1575 | let Some(v) = iter.next() else { |
|
| 1614 | 1576 | return Err(Error::ExpectedValue("any")); |
|
| 1615 | 1577 | }; |
| 1694 | 1656 | } |
|
| 1695 | 1657 | _ => Err(Error::ExpectedValue("vector")), |
|
| 1696 | 1658 | } |
|
| 1697 | 1659 | } |
|
| 1698 | 1660 | ||
| 1699 | - | /// Push elements to the front of a list. |
|
| 1700 | - | pub fn cons(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1701 | - | if args.is_empty() { |
|
| 1702 | - | return Ok(Expr::nil()); |
|
| 1703 | - | } |
|
| 1704 | - | let (val, l) = <(Expr, List<Expr>)>::try_from_args(args)?; |
|
| 1705 | - | ||
| 1706 | - | Ok(Expr::List(l.prepend(val))) |
|
| 1707 | - | } |
|
| 1708 | - | ||
| 1709 | 1661 | /// Reverse a vector. |
|
| 1710 | 1662 | pub fn reverse(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1711 | 1663 | let (mut v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1712 | 1664 | v.reverse(); |
|
| 1713 | 1665 |
| 2389 | 2341 | ])), |
|
| 2390 | 2342 | ); |
|
| 2391 | 2343 | expect(&["(dict)"], Expr::Dict(HashMap::new())); |
|
| 2392 | 2344 | expect(&["(dict [])"], Expr::Dict(HashMap::new())); |
|
| 2393 | 2345 | expect_err(&["(dict [:x])"], Error::ExpectedValue("any")); |
|
| 2394 | - | expect_err(&["(dict :who)"], Error::ExpectedValue("list")); |
|
| 2346 | + | expect_err( |
|
| 2347 | + | &["(dict :who)"], |
|
| 2348 | + | Error::UnexpectedValue(Expr::Atom("who".into())), |
|
| 2349 | + | ); |
|
| 2395 | 2350 | } |
|
| 2396 | 2351 | ||
| 2397 | 2352 | #[test] |
|
| 2398 | 2353 | fn test_map() { |
|
| 2399 | 2354 | expect( |
|
| 2400 | 2355 | &["(map (fn [x] (+ x 1)) (list 1 2 3))"], |
|
| 2401 | - | Expr::list([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]), |
|
| 2356 | + | Expr::vector([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]), |
|
| 2402 | 2357 | ); |
|
| 2403 | 2358 | expect( |
|
| 2404 | 2359 | &["(map (fn [x] (+ x x)) [1 2 3])"], |
|
| 2405 | 2360 | Expr::vector([Expr::Integer(2), Expr::Integer(4), Expr::Integer(6)]), |
|
| 2406 | 2361 | ); |
| 2442 | 2397 | Expr::Integer(1), |
|
| 2443 | 2398 | Expr::list([Expr::Integer(2), Expr::Integer(3)]), |
|
| 2444 | 2399 | ]), |
|
| 2445 | 2400 | ); |
|
| 2446 | 2401 | expect(&["(eq? {} ())"], Expr::Bool(true)); |
|
| 2447 | - | expect_err(&["(list (4 2))"], Error::ExpectedValue("function or atom")); |
|
| 2448 | - | } |
|
| 2449 | - | ||
| 2450 | - | #[test] |
|
| 2451 | - | fn test_cons() { |
|
| 2452 | - | expect(&["(cons)"], Expr::list([])); |
|
| 2453 | - | expect(&["(cons 1 ())"], Expr::list([Expr::Integer(1)])); |
|
| 2454 | - | expect( |
|
| 2455 | - | &["(cons 3 (cons 2 (cons 1 ())))"], |
|
| 2456 | - | Expr::list([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]), |
|
| 2457 | - | ); |
|
| 2458 | - | expect( |
|
| 2459 | - | &["(cons 3 '(2 1))"], |
|
| 2460 | - | Expr::list([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]), |
|
| 2461 | - | ); |
|
| 2402 | + | expect_err(&["(list (4 2))"], Error::UnexpectedValue(Expr::Integer(4))); |
|
| 2462 | 2403 | } |
|
| 2463 | 2404 | ||
| 2464 | 2405 | #[test] |
|
| 2465 | 2406 | fn test_length() { |
|
| 2466 | 2407 | expect(&["(length '(1 2 3))"], Expr::Integer(3)); |
ombre/src/lisp/list.rs
deleted
+0 -234
| 1 | - | //! Defines the [`List`] type. |
|
| 2 | - | use std::{ops::Deref, rc::Rc}; |
|
| 3 | - | ||
| 4 | - | /// Traditional persistent "cons" list. |
|
| 5 | - | #[derive(Debug, Clone, PartialEq, Eq)] |
|
| 6 | - | pub struct List<T> { |
|
| 7 | - | head: Link<T>, |
|
| 8 | - | } |
|
| 9 | - | ||
| 10 | - | impl<T> Default for List<T> { |
|
| 11 | - | fn default() -> Self { |
|
| 12 | - | Self { head: None } |
|
| 13 | - | } |
|
| 14 | - | } |
|
| 15 | - | ||
| 16 | - | /// Link to the next list node. |
|
| 17 | - | type Link<T> = Option<Rc<Node<T>>>; |
|
| 18 | - | ||
| 19 | - | /// List node. |
|
| 20 | - | #[derive(Debug, Clone, PartialEq, Eq)] |
|
| 21 | - | struct Node<T> { |
|
| 22 | - | elem: T, |
|
| 23 | - | next: Link<T>, |
|
| 24 | - | } |
|
| 25 | - | ||
| 26 | - | impl<T> Deref for Node<T> { |
|
| 27 | - | type Target = T; |
|
| 28 | - | ||
| 29 | - | fn deref(&self) -> &Self::Target { |
|
| 30 | - | &self.elem |
|
| 31 | - | } |
|
| 32 | - | } |
|
| 33 | - | ||
| 34 | - | impl<T> Drop for List<T> { |
|
| 35 | - | fn drop(&mut self) { |
|
| 36 | - | let mut head = self.head.take(); |
|
| 37 | - | while let Some(node) = head { |
|
| 38 | - | if let Ok(mut node) = Rc::try_unwrap(node) { |
|
| 39 | - | head = node.next.take(); |
|
| 40 | - | } else { |
|
| 41 | - | break; |
|
| 42 | - | } |
|
| 43 | - | } |
|
| 44 | - | } |
|
| 45 | - | } |
|
| 46 | - | ||
| 47 | - | impl<T, const N: usize> From<[T; N]> for List<T> { |
|
| 48 | - | fn from(value: [T; N]) -> Self { |
|
| 49 | - | List::build(value.into_iter()) |
|
| 50 | - | } |
|
| 51 | - | } |
|
| 52 | - | ||
| 53 | - | impl<T> From<Vec<T>> for List<T> { |
|
| 54 | - | fn from(value: Vec<T>) -> Self { |
|
| 55 | - | List::build(value.into_iter()) |
|
| 56 | - | } |
|
| 57 | - | } |
|
| 58 | - | ||
| 59 | - | impl<T> List<T> { |
|
| 60 | - | /// Create a new list from a value. |
|
| 61 | - | pub fn new(head: T) -> Self { |
|
| 62 | - | Self { |
|
| 63 | - | head: Some(Rc::new(Node { |
|
| 64 | - | elem: head, |
|
| 65 | - | next: None, |
|
| 66 | - | })), |
|
| 67 | - | } |
|
| 68 | - | } |
|
| 69 | - | ||
| 70 | - | /// Take the head of the list. |
|
| 71 | - | pub fn head(&self) -> Option<&T> { |
|
| 72 | - | self.head.as_ref().map(|node| &node.elem) |
|
| 73 | - | } |
|
| 74 | - | ||
| 75 | - | /// Take the tail of the list. |
|
| 76 | - | pub fn tail(&self) -> List<T> { |
|
| 77 | - | List { |
|
| 78 | - | head: self.head.as_ref().and_then(|node| node.next.clone()), |
|
| 79 | - | } |
|
| 80 | - | } |
|
| 81 | - | ||
| 82 | - | /// Return a list with the value added to its head. |
|
| 83 | - | pub fn prepend(&self, elem: T) -> List<T> { |
|
| 84 | - | List { |
|
| 85 | - | head: Some(Rc::new(Node { |
|
| 86 | - | elem, |
|
| 87 | - | next: self.head.clone(), |
|
| 88 | - | })), |
|
| 89 | - | } |
|
| 90 | - | } |
|
| 91 | - | ||
| 92 | - | /// Get the length of the list. |
|
| 93 | - | pub fn len(&self) -> usize { |
|
| 94 | - | let mut len = 0; |
|
| 95 | - | let mut current = &self.head; |
|
| 96 | - | ||
| 97 | - | while let Some(node) = current { |
|
| 98 | - | len += 1; |
|
| 99 | - | current = &node.next; |
|
| 100 | - | } |
|
| 101 | - | len |
|
| 102 | - | } |
|
| 103 | - | ||
| 104 | - | /// Return an iterator over the list. |
|
| 105 | - | pub fn iter(&self) -> Iter<'_, T> { |
|
| 106 | - | Iter { |
|
| 107 | - | next: self.head.as_deref(), |
|
| 108 | - | } |
|
| 109 | - | } |
|
| 110 | - | ||
| 111 | - | /// Check if the list is empty. |
|
| 112 | - | pub fn is_empty(&self) -> bool { |
|
| 113 | - | self.head.is_none() |
|
| 114 | - | } |
|
| 115 | - | ||
| 116 | - | /// Build a list in-order from an iterator. |
|
| 117 | - | pub fn build(iter: impl DoubleEndedIterator<Item = T>) -> Self { |
|
| 118 | - | let mut list = Self::default(); |
|
| 119 | - | for item in iter.rev() { |
|
| 120 | - | list = list.prepend(item); |
|
| 121 | - | } |
|
| 122 | - | list |
|
| 123 | - | } |
|
| 124 | - | } |
|
| 125 | - | ||
| 126 | - | impl<T: Clone> List<T> { |
|
| 127 | - | /// Split the list into its head element and tail. |
|
| 128 | - | pub fn uncons(&mut self) -> Option<(T, List<T>)> { |
|
| 129 | - | self.head.take().map(|node| match Rc::try_unwrap(node) { |
|
| 130 | - | Ok(mut node) => { |
|
| 131 | - | let tail = List { |
|
| 132 | - | head: node.next.take(), |
|
| 133 | - | }; |
|
| 134 | - | (node.elem, tail) |
|
| 135 | - | } |
|
| 136 | - | Err(rc) => { |
|
| 137 | - | let tail = List { |
|
| 138 | - | head: rc.next.clone(), |
|
| 139 | - | }; |
|
| 140 | - | (rc.elem.clone(), tail) |
|
| 141 | - | } |
|
| 142 | - | }) |
|
| 143 | - | } |
|
| 144 | - | } |
|
| 145 | - | ||
| 146 | - | impl<T: PartialEq> List<T> { |
|
| 147 | - | /// Check if the list contains an item. |
|
| 148 | - | pub fn contains(&self, item: &T) -> bool { |
|
| 149 | - | self.iter().any(|i| i == item) |
|
| 150 | - | } |
|
| 151 | - | } |
|
| 152 | - | ||
| 153 | - | /// List iterator. |
|
| 154 | - | pub struct Iter<'a, T> { |
|
| 155 | - | next: Option<&'a Node<T>>, |
|
| 156 | - | } |
|
| 157 | - | ||
| 158 | - | impl<'a, T> Iterator for Iter<'a, T> { |
|
| 159 | - | type Item = &'a T; |
|
| 160 | - | ||
| 161 | - | fn next(&mut self) -> Option<Self::Item> { |
|
| 162 | - | self.next.map(|node| { |
|
| 163 | - | self.next = node.next.as_deref(); |
|
| 164 | - | &node.elem |
|
| 165 | - | }) |
|
| 166 | - | } |
|
| 167 | - | } |
|
| 168 | - | ||
| 169 | - | /// Owned list iterator. |
|
| 170 | - | pub struct IntoIter<T> { |
|
| 171 | - | list: List<T>, |
|
| 172 | - | } |
|
| 173 | - | ||
| 174 | - | impl<T: Clone> Iterator for IntoIter<T> { |
|
| 175 | - | type Item = T; |
|
| 176 | - | ||
| 177 | - | fn next(&mut self) -> Option<Self::Item> { |
|
| 178 | - | let (head, tail) = self.list.uncons()?; |
|
| 179 | - | self.list = tail; |
|
| 180 | - | Some(head) |
|
| 181 | - | } |
|
| 182 | - | } |
|
| 183 | - | ||
| 184 | - | impl<T: Clone + std::fmt::Debug> IntoIterator for List<T> { |
|
| 185 | - | type Item = T; |
|
| 186 | - | type IntoIter = IntoIter<T>; |
|
| 187 | - | ||
| 188 | - | fn into_iter(self) -> Self::IntoIter { |
|
| 189 | - | IntoIter { list: self } |
|
| 190 | - | } |
|
| 191 | - | } |
|
| 192 | - | ||
| 193 | - | /// Nb. This function creates a list in reverse order. |
|
| 194 | - | impl<T> FromIterator<T> for List<T> { |
|
| 195 | - | fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { |
|
| 196 | - | let mut list = List::default(); |
|
| 197 | - | for item in iter { |
|
| 198 | - | list = list.prepend(item); |
|
| 199 | - | } |
|
| 200 | - | list |
|
| 201 | - | } |
|
| 202 | - | } |
|
| 203 | - | ||
| 204 | - | #[cfg(test)] |
|
| 205 | - | #[allow(clippy::unwrap_used)] |
|
| 206 | - | mod tests { |
|
| 207 | - | use super::*; |
|
| 208 | - | ||
| 209 | - | #[test] |
|
| 210 | - | fn test_list_type() { |
|
| 211 | - | let list = List::new('o').prepend('l').prepend('l').prepend('e').prepend('h'); |
|
| 212 | - | let result = list.iter().collect::<String>(); |
|
| 213 | - | assert_eq!(result.as_str(), "hello"); |
|
| 214 | - | assert_eq!(list.len(), 5); |
|
| 215 | - | assert_eq!(list.is_empty(), false); |
|
| 216 | - | assert_eq!(list.head(), Some(&'h')); |
|
| 217 | - | assert_eq!(list.tail().tail(), List::new('o').prepend('l').prepend('l')); |
|
| 218 | - | assert_eq!(list.tail().tail().tail(), List::new('o').prepend('l')); |
|
| 219 | - | ||
| 220 | - | let list = List::build(result.chars()); |
|
| 221 | - | assert_eq!( |
|
| 222 | - | list, |
|
| 223 | - | List::new('o').prepend('l').prepend('l').prepend('e').prepend('h') |
|
| 224 | - | ); |
|
| 225 | - | ||
| 226 | - | let list = List::from_iter(result.chars()); |
|
| 227 | - | assert_eq!( |
|
| 228 | - | list, |
|
| 229 | - | List::new('h').prepend('e').prepend('l').prepend('l').prepend('o') |
|
| 230 | - | ); |
|
| 231 | - | assert_eq!(List::<()>::default().is_empty(), true); |
|
| 232 | - | assert_eq!(List::<()>::default().head(), None); |
|
| 233 | - | } |
|
| 234 | - | } |
ombre/src/lisp/parser.rs
+1 -1
| 277 | 277 | ); |
|
| 278 | 278 | } |
|
| 279 | 279 | ||
| 280 | 280 | #[test] |
|
| 281 | 281 | fn test_parse_vector() { |
|
| 282 | - | ok("[]", &[Expr::Vector(vec![])]); |
|
| 282 | + | ok("[]", &[Expr::vector(vec![])]); |
|
| 283 | 283 | ok( |
|
| 284 | 284 | "[1 2 3]", |
|
| 285 | 285 | &[Expr::vector([ |
|
| 286 | 286 | Expr::Integer(1), |
|
| 287 | 287 | Expr::Integer(2), |