ombre: Implement mutable vectors
d8b6f591936d57aa4f26e91706cbf7e7aefc8ef0
1 parent
81945747
ombre/src/lisp/evaluator.rs
+225 -88
| 1 | 1 | //! Expression evaluator. |
|
| 2 | - | use std::borrow::Borrow; |
|
| 3 | 2 | use std::cell::RefCell; |
|
| 4 | 3 | use std::collections::HashSet; |
|
| 5 | 4 | use std::hash::{Hash, Hasher}; |
|
| 6 | 5 | use std::ops::{Deref, DerefMut}; |
|
| 7 | 6 | use std::path::PathBuf; |
| 83 | 82 | fn eq(&self, other: &Self) -> bool { |
|
| 84 | 83 | self.0.eq(&other.0) |
|
| 85 | 84 | } |
|
| 86 | 85 | } |
|
| 87 | 86 | ||
| 88 | - | impl Borrow<str> for Symbol { |
|
| 87 | + | impl std::borrow::Borrow<str> for Symbol { |
|
| 89 | 88 | fn borrow(&self) -> &str { |
|
| 90 | 89 | &self.0 |
|
| 91 | 90 | } |
|
| 92 | 91 | } |
|
| 93 | 92 |
| 155 | 154 | } |
|
| 156 | 155 | ||
| 157 | 156 | /// A code module. Defines a namespace with bindings that can be imported. |
|
| 158 | 157 | #[derive(Debug, Clone, PartialEq)] |
|
| 159 | 158 | pub struct Module { |
|
| 159 | + | /// The module's name. |
|
| 160 | 160 | name: Symbol, |
|
| 161 | + | /// Optional documentation string. |
|
| 161 | 162 | docstr: Option<String>, |
|
| 163 | + | /// The module's environment. |
|
| 162 | 164 | env: Env<'static>, |
|
| 163 | 165 | } |
|
| 164 | 166 | ||
| 165 | 167 | /// The global module registry. |
|
| 166 | 168 | #[derive(Debug, Clone, PartialEq, Default)] |
| 200 | 202 | fn register(&mut self, name: Symbol, module: Module) { |
|
| 201 | 203 | self.modules.insert(name, module); |
|
| 202 | 204 | } |
|
| 203 | 205 | } |
|
| 204 | 206 | ||
| 207 | + | /// A reference-counted mutable cell containing a value of type `T`. |
|
| 208 | + | pub type Mut<T> = Rc<RefCell<T>>; |
|
| 209 | + | ||
| 210 | + | /// A sequence of expressions. |
|
| 211 | + | #[derive(Debug, Clone, PartialEq)] |
|
| 212 | + | pub struct Tuple { |
|
| 213 | + | /// The expressions contained in the tuple. |
|
| 214 | + | data: Vec<Expr>, |
|
| 215 | + | /// Whether this tuple should be evaluated literally. |
|
| 216 | + | literal: bool, |
|
| 217 | + | } |
|
| 218 | + | ||
| 219 | + | impl Tuple { |
|
| 220 | + | /// Creates a new tuple from a collection of expressions. |
|
| 221 | + | /// Eg. `(f 3 2)`. |
|
| 222 | + | pub fn new(data: impl Into<Vec<Expr>>) -> Self { |
|
| 223 | + | Self { |
|
| 224 | + | data: data.into(), |
|
| 225 | + | literal: false, |
|
| 226 | + | } |
|
| 227 | + | } |
|
| 228 | + | ||
| 229 | + | /// Creates a new tuple that will not be evaluated as a function call. |
|
| 230 | + | /// Eg. `[1 2 3]`. |
|
| 231 | + | pub fn literal(data: impl Into<Vec<Expr>>) -> Self { |
|
| 232 | + | Self { |
|
| 233 | + | data: data.into(), |
|
| 234 | + | literal: true, |
|
| 235 | + | } |
|
| 236 | + | } |
|
| 237 | + | } |
|
| 238 | + | ||
| 239 | + | impl std::ops::Deref for Tuple { |
|
| 240 | + | type Target = [Expr]; |
|
| 241 | + | ||
| 242 | + | fn deref(&self) -> &Self::Target { |
|
| 243 | + | &self.data |
|
| 244 | + | } |
|
| 245 | + | } |
|
| 246 | + | ||
| 205 | 247 | /// Expression in the language. |
|
| 206 | 248 | #[derive(Debug, Clone, PartialEq)] |
|
| 207 | 249 | pub enum Expr { |
|
| 208 | - | /// Eg. (1 2 3) |
|
| 209 | - | Tuple(Vec<Expr>), |
|
| 250 | + | /// Eg. (1 2 3) or [1 2 3] |
|
| 251 | + | Tuple(Tuple), |
|
| 210 | 252 | /// Eg. :true |
|
| 211 | 253 | Bool(bool), |
|
| 212 | 254 | /// Eg. 'fnord |
|
| 213 | 255 | Quoted(Box<Expr>), |
|
| 214 | - | /// Eg. [1 2 3] |
|
| 215 | - | Vector(Vec<Expr>), |
|
| 256 | + | /// Eg. @[1 2 3] |
|
| 257 | + | Vector(Mut<Vec<Expr>>), |
|
| 216 | 258 | /// Eg. (vec2 x y) |
|
| 217 | 259 | Vector2D(Vector2D<f64>), |
|
| 218 | 260 | /// Eg. (vec3 x y z) |
|
| 219 | 261 | Vector3D(Vector3D<f64>), |
|
| 220 | 262 | /// Eg. (vec4 x y z w) |
| 241 | 283 | Ref(Rc<RefCell<Expr>>), |
|
| 242 | 284 | /// Dynamic type. Can be any Rust type. |
|
| 243 | 285 | Dynamic(Dynamic), |
|
| 244 | 286 | } |
|
| 245 | 287 | ||
| 288 | + | impl Default for Expr { |
|
| 289 | + | fn default() -> Self { |
|
| 290 | + | Expr::nil() |
|
| 291 | + | } |
|
| 292 | + | } |
|
| 293 | + | ||
| 246 | 294 | impl Expr { |
|
| 247 | 295 | /// The empty list, or "nil". |
|
| 248 | 296 | pub fn nil() -> Self { |
|
| 249 | - | Self::Tuple(vec![]) |
|
| 297 | + | Self::Tuple(Tuple::new(vec![])) |
|
| 250 | 298 | } |
|
| 251 | 299 | ||
| 252 | 300 | /// Check if this expression is the empty list. |
|
| 253 | 301 | pub fn is_nil(&self) -> bool { |
|
| 254 | 302 | matches!(self, Self::Tuple(l) if l.is_empty()) |
|
| 255 | 303 | } |
|
| 256 | 304 | ||
| 257 | 305 | /// Construct a tuple. |
|
| 258 | 306 | pub fn tuple(items: impl Into<Vec<Expr>>) -> Self { |
|
| 259 | - | Expr::Tuple(items.into()) |
|
| 307 | + | Expr::Tuple(Tuple::new(items.into())) |
|
| 260 | 308 | } |
|
| 261 | 309 | ||
| 262 | 310 | /// Construct a vector. |
|
| 263 | - | pub fn vector(items: impl IntoIterator<Item = Expr>) -> Self { |
|
| 264 | - | Expr::Vector(items.into_iter().collect()) |
|
| 311 | + | pub fn vector(items: impl Into<Vec<Expr>>) -> Self { |
|
| 312 | + | Expr::Vector(Rc::from(RefCell::new(items.into()))) |
|
| 265 | 313 | } |
|
| 266 | 314 | ||
| 267 | 315 | /// Construct a symbol. |
|
| 268 | 316 | pub fn symbol(name: impl Into<Symbol>) -> Self { |
|
| 269 | 317 | Expr::Symbol(name.into()) |
| 330 | 378 | fn from(value: Closure) -> Self { |
|
| 331 | 379 | Expr::Function(Function::Closure(Rc::new(value))) |
|
| 332 | 380 | } |
|
| 333 | 381 | } |
|
| 334 | 382 | ||
| 383 | + | impl From<Tuple> for Expr { |
|
| 384 | + | fn from(value: Tuple) -> Self { |
|
| 385 | + | Expr::Tuple(value) |
|
| 386 | + | } |
|
| 387 | + | } |
|
| 388 | + | ||
| 335 | 389 | impl TryFrom<Expr> for Function { |
|
| 336 | 390 | type Error = Expr; |
|
| 337 | 391 | ||
| 338 | 392 | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 339 | 393 | match expr { |
| 352 | 406 | _ => Err(expr), |
|
| 353 | 407 | } |
|
| 354 | 408 | } |
|
| 355 | 409 | } |
|
| 356 | 410 | ||
| 411 | + | impl TryFrom<Expr> for Rc<RefCell<Vec<Expr>>> { |
|
| 412 | + | type Error = Expr; |
|
| 413 | + | ||
| 414 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 415 | + | match expr { |
|
| 416 | + | Expr::Vector(v) => Ok(v), |
|
| 417 | + | _ => Err(expr), |
|
| 418 | + | } |
|
| 419 | + | } |
|
| 420 | + | } |
|
| 421 | + | ||
| 357 | 422 | impl TryFrom<Expr> for f32 { |
|
| 358 | 423 | type Error = Expr; |
|
| 359 | 424 | ||
| 360 | 425 | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 361 | 426 | match expr { |
| 414 | 479 | impl TryFrom<Expr> for Vec<Expr> { |
|
| 415 | 480 | type Error = Expr; |
|
| 416 | 481 | ||
| 417 | 482 | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 418 | 483 | match expr { |
|
| 419 | - | Expr::Tuple(v) => Ok(v), |
|
| 420 | - | Expr::Vector(v) => Ok(v), |
|
| 484 | + | Expr::Tuple(v) => Ok(v.data), |
|
| 421 | 485 | _ => Err(expr), |
|
| 422 | 486 | } |
|
| 423 | 487 | } |
|
| 424 | 488 | } |
|
| 425 | 489 |
| 470 | 534 | fn from(v: Vector4D<f64>) -> Self { |
|
| 471 | 535 | Expr::Vector4D(v) |
|
| 472 | 536 | } |
|
| 473 | 537 | } |
|
| 474 | 538 | ||
| 539 | + | /// Helper enum for handling multiple possible types. |
|
| 540 | + | enum Either<L, R> { |
|
| 541 | + | Left(L), |
|
| 542 | + | Right(R), |
|
| 543 | + | } |
|
| 544 | + | ||
| 545 | + | impl<L: TryFrom<Expr, Error = Expr>, R: TryFrom<Expr, Error = Expr>> TryFrom<Expr> |
|
| 546 | + | for Either<L, R> |
|
| 547 | + | { |
|
| 548 | + | type Error = Expr; |
|
| 549 | + | ||
| 550 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Expr> { |
|
| 551 | + | L::try_from(expr) |
|
| 552 | + | .map(Either::Left) |
|
| 553 | + | .or_else(|e| R::try_from(e).map(Either::Right)) |
|
| 554 | + | } |
|
| 555 | + | } |
|
| 556 | + | ||
| 475 | 557 | /// Trait for converting from a vector of [`Expr`] values into a tuple of specific types. |
|
| 476 | 558 | pub trait TryFromArgs: Sized { |
|
| 477 | 559 | /// The number of arguments expected. |
|
| 478 | 560 | const ARITY: usize; |
|
| 479 | 561 |
| 581 | 663 | write!(f, ")") |
|
| 582 | 664 | } |
|
| 583 | 665 | Expr::Bool(b) => write!(f, ":{b}"), |
|
| 584 | 666 | Expr::Quoted(e) => write!(f, "'{e}"), |
|
| 585 | 667 | Expr::Vector(v) => { |
|
| 586 | - | write!(f, "[")?; |
|
| 668 | + | write!(f, "@[")?; |
|
| 669 | + | let v = v.borrow(); |
|
| 587 | 670 | let mut iter = v.iter(); |
|
| 588 | 671 | if let Some(first) = iter.next() { |
|
| 589 | 672 | write!(f, "{first}")?; |
|
| 590 | 673 | for item in iter { |
|
| 591 | 674 | write!(f, " {item}")?; |
| 631 | 714 | Key::Char(c) => write!(f, "`{c}`"), |
|
| 632 | 715 | } |
|
| 633 | 716 | } |
|
| 634 | 717 | } |
|
| 635 | 718 | ||
| 636 | - | /// Built-in or user-defined function. |
|
| 719 | + | /// A function that can be called with arguments. |
|
| 720 | + | /// |
|
| 721 | + | /// Functions can be either built-in intrinsics implemented natively in Rust, |
|
| 722 | + | /// or user-defined closures that capture their lexical environment. |
|
| 637 | 723 | #[derive(Debug, Clone)] |
|
| 638 | 724 | pub enum Function { |
|
| 639 | 725 | /// A function that closes over some environment. |
|
| 640 | 726 | Closure(Rc<Closure>), |
|
| 641 | 727 | /// A built-in function implemented natively. |
| 1049 | 1135 | "contains?", |
|
| 1050 | 1136 | "Check if a collection contains the given key", |
|
| 1051 | 1137 | intrinsic::contains, |
|
| 1052 | 1138 | ); |
|
| 1053 | 1139 | env.intrinsic("empty?", "Check if a collection is empty", intrinsic::empty); |
|
| 1054 | - | env.intrinsic("append", "Append elements to a vector", intrinsic::append); |
|
| 1140 | + | env.intrinsic( |
|
| 1141 | + | "push", |
|
| 1142 | + | "Push elements to the end of a vector", |
|
| 1143 | + | intrinsic::push, |
|
| 1144 | + | ); |
|
| 1055 | 1145 | env.intrinsic("reverse", "Reverse a tuple or vector", intrinsic::reverse); |
|
| 1056 | 1146 | env.intrinsic( |
|
| 1057 | 1147 | "range", |
|
| 1058 | 1148 | "Create a vector of numbers in a specified range", |
|
| 1059 | 1149 | intrinsic::range, |
| 1144 | 1234 | }; |
|
| 1145 | 1235 | ||
| 1146 | 1236 | // Handle special top-level forms. |
|
| 1147 | 1237 | match head.deref() { |
|
| 1148 | 1238 | "module" => { |
|
| 1149 | - | let mut items = tuple.into_iter().skip(1).peekable(); |
|
| 1239 | + | let mut items = tuple.data.into_iter().skip(1).peekable(); |
|
| 1150 | 1240 | let Some(Expr::Symbol(name)) = items.next() else { |
|
| 1151 | 1241 | return Err(Error::ExpectedValue("symbol")); |
|
| 1152 | 1242 | }; |
|
| 1153 | 1243 | // Get optional doc string. |
|
| 1154 | 1244 | let docstr = if let Some(Expr::Str(ref docstr)) = items.peek().cloned() { |
| 1166 | 1256 | mods.register(name.clone(), Module { name, docstr, env }); |
|
| 1167 | 1257 | ||
| 1168 | 1258 | Ok(Expr::nil()) |
|
| 1169 | 1259 | } |
|
| 1170 | 1260 | "import" => { |
|
| 1171 | - | let mut iter = tuple.into_iter().skip(1); |
|
| 1261 | + | let mut iter = tuple.iter().skip(1); |
|
| 1172 | 1262 | let Some(Expr::Symbol(name)) = iter.next() else { |
|
| 1173 | 1263 | return Err(Error::ExpectedValue("symbol")); |
|
| 1174 | 1264 | }; |
|
| 1175 | - | let module = match mods.lookup(&name) { |
|
| 1265 | + | let module = match mods.lookup(name) { |
|
| 1176 | 1266 | Some(m) => m, |
|
| 1177 | - | None => mods.load(&name)?, |
|
| 1267 | + | None => mods.load(name)?, |
|
| 1178 | 1268 | }; |
|
| 1179 | 1269 | env.import(module); |
|
| 1180 | 1270 | ||
| 1181 | 1271 | Ok(Expr::nil()) |
|
| 1182 | 1272 | } |
|
| 1183 | 1273 | "export" => { |
|
| 1184 | - | let mut iter = tuple.into_iter().skip(1).peekable(); |
|
| 1274 | + | let mut iter = tuple.data.into_iter().skip(1).peekable(); |
|
| 1185 | 1275 | if iter.peek().is_none() { |
|
| 1186 | 1276 | return Err(Error::WrongArgumentCount { |
|
| 1187 | 1277 | expected: 1, |
|
| 1188 | 1278 | actual: 0, |
|
| 1189 | 1279 | }); |
| 1256 | 1346 | .collect::<Result<Vec<_>>>()? |
|
| 1257 | 1347 | .pop() |
|
| 1258 | 1348 | .unwrap_or(Expr::nil())) |
|
| 1259 | 1349 | } |
|
| 1260 | 1350 | ||
| 1261 | - | /// Evaluate special forms and function application. |
|
| 1262 | - | fn eval_tuple(tuple: Vec<Expr>, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1263 | - | let mut items = tuple.into_iter(); |
|
| 1351 | + | /// Evaluate a [`Tuple`]. |
|
| 1352 | + | fn eval_tuple(mut tuple: Tuple, env: &mut Env<'_>) -> Result<Expr> { |
|
| 1353 | + | // Literal tuples are not evaluated as function calls. |
|
| 1354 | + | if tuple.literal { |
|
| 1355 | + | tuple.data = tuple.data.into_iter().map(|a| eval(a, env)).collect::<Result<_>>()?; |
|
| 1356 | + | tuple.literal = false; |
|
| 1357 | + | ||
| 1358 | + | return Ok(Expr::Tuple(tuple)); |
|
| 1359 | + | } |
|
| 1360 | + | // Evaluate special forms and function application. |
|
| 1361 | + | let mut items = tuple.data.into_iter(); |
|
| 1264 | 1362 | let Some(head) = items.next() else { |
|
| 1265 | 1363 | return Ok(Expr::nil()); |
|
| 1266 | 1364 | }; |
|
| 1267 | 1365 | if let Expr::Symbol(ref name) = head { |
|
| 1268 | 1366 | match name.deref() { |
| 1309 | 1407 | } |
|
| 1310 | 1408 | "let" => { |
|
| 1311 | 1409 | let assignments = items.next().ok_or(Error::ExpectedValue("vector"))?; |
|
| 1312 | 1410 | let body = items.collect::<Vec<_>>(); |
|
| 1313 | 1411 | ||
| 1314 | - | let Expr::Vector(assignments) = assignments else { |
|
| 1412 | + | let Expr::Tuple(tuple) = assignments else { |
|
| 1315 | 1413 | return Err(Error::UnexpectedValue(assignments)); |
|
| 1316 | 1414 | }; |
|
| 1317 | 1415 | if body.is_empty() { |
|
| 1318 | 1416 | return Err(Error::ExpectedValue("expression")); |
|
| 1319 | 1417 | } |
|
| 1320 | - | eval_let(assignments, body, env) |
|
| 1418 | + | eval_let(tuple.data, body, env) |
|
| 1321 | 1419 | } |
|
| 1322 | 1420 | "fn" => { |
|
| 1323 | 1421 | let formals = items.next().ok_or(Error::ExpectedValue("vector"))?; |
|
| 1324 | 1422 | let body = items.collect::<Vec<_>>(); |
|
| 1325 | 1423 | ||
| 1326 | - | let Expr::Vector(formals) = formals else { |
|
| 1424 | + | let Expr::Tuple(formals) = formals else { |
|
| 1327 | 1425 | return Err(Error::UnexpectedValue(formals)); |
|
| 1328 | 1426 | }; |
|
| 1329 | 1427 | if body.is_empty() { |
|
| 1330 | 1428 | return Err(Error::ExpectedValue("expression")); |
|
| 1331 | 1429 | } |
|
| 1332 | - | eval_lambda(formals, body, env) |
|
| 1430 | + | eval_lambda(formals.data, body, env) |
|
| 1333 | 1431 | } |
|
| 1334 | 1432 | "if" => { |
|
| 1335 | 1433 | let cond = items.next().ok_or(Error::ExpectedValue("bool"))?; |
|
| 1336 | 1434 | let left = items.next().ok_or(Error::ExpectedValue("expression"))?; |
|
| 1337 | 1435 | let right = items.next().ok_or(Error::ExpectedValue("expression"))?; |
| 1372 | 1470 | "true" => Expr::Bool(true), |
|
| 1373 | 1471 | "false" => Expr::Bool(false), |
|
| 1374 | 1472 | _ => Expr::Atom(s), |
|
| 1375 | 1473 | }), |
|
| 1376 | 1474 | Expr::Vector(v) => v |
|
| 1475 | + | .borrow() |
|
| 1476 | + | .clone() |
|
| 1377 | 1477 | .into_iter() |
|
| 1378 | 1478 | .map(|e| eval(e, env)) |
|
| 1379 | 1479 | .collect::<Result<Vec<_>>>() |
|
| 1380 | - | .map(Expr::Tuple), |
|
| 1480 | + | .map(Expr::vector), |
|
| 1381 | 1481 | Expr::Vector2D(v) => Ok(Expr::Vector2D(v)), |
|
| 1382 | 1482 | Expr::Vector3D(v) => Ok(Expr::Vector3D(v)), |
|
| 1383 | 1483 | Expr::Vector4D(v) => Ok(Expr::Vector4D(v)), |
|
| 1384 | 1484 | Expr::Dict(d) => d |
|
| 1385 | 1485 | .into_iter() |
| 1481 | 1581 | .collect(); |
|
| 1482 | 1582 | ||
| 1483 | 1583 | Ok(Expr::Dict(dict)) |
|
| 1484 | 1584 | } |
|
| 1485 | 1585 | ||
| 1486 | - | /// Get the first item of a list. |
|
| 1586 | + | /// Get the first item of a tuple or vector. |
|
| 1487 | 1587 | pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1488 | - | let (list,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1489 | - | Ok(list.into_iter().next().unwrap_or(Expr::nil())) |
|
| 1588 | + | let (list,) = <(Either<Vec<Expr>, Mut<Vec<Expr>>>,)>::try_from_args(args)?; |
|
| 1589 | + | match list { |
|
| 1590 | + | Either::Left(tuple) => Ok(tuple.into_iter().next().unwrap_or_default()), |
|
| 1591 | + | Either::Right(vec) => Ok(vec.borrow().first().cloned().unwrap_or_default()), |
|
| 1592 | + | } |
|
| 1490 | 1593 | } |
|
| 1491 | 1594 | ||
| 1492 | - | /// Get the last item of a vector. |
|
| 1595 | + | /// Get the last item of a tuple or vector. |
|
| 1493 | 1596 | pub fn last(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1494 | - | let (v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1495 | - | Ok(v.into_iter().next_back().unwrap_or(Expr::nil())) |
|
| 1597 | + | let (list,) = <(Either<Vec<Expr>, Mut<Vec<Expr>>>,)>::try_from_args(args)?; |
|
| 1598 | + | match list { |
|
| 1599 | + | Either::Left(tuple) => Ok(tuple.into_iter().next_back().unwrap_or_default()), |
|
| 1600 | + | Either::Right(vec) => Ok(vec.borrow().last().cloned().unwrap_or_default()), |
|
| 1601 | + | } |
|
| 1496 | 1602 | } |
|
| 1497 | 1603 | ||
| 1498 | - | /// Get the nth item of a vector. |
|
| 1604 | + | /// Get the nth item of a tuple or vector. |
|
| 1499 | 1605 | pub fn nth(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1500 | - | let (vec, idx) = <(Vec<Expr>, i64)>::try_from_args(args)?; |
|
| 1501 | - | Ok(vec.into_iter().nth(idx as usize).unwrap_or(Expr::nil())) |
|
| 1606 | + | let (list, idx) = <(Either<Vec<Expr>, Mut<Vec<Expr>>>, i64)>::try_from_args(args)?; |
|
| 1607 | + | match list { |
|
| 1608 | + | Either::Left(tuple) => Ok(tuple.into_iter().nth(idx as usize).unwrap_or_default()), |
|
| 1609 | + | Either::Right(vec) => Ok(vec.borrow().get(idx as usize).cloned().unwrap_or_default()), |
|
| 1610 | + | } |
|
| 1502 | 1611 | } |
|
| 1503 | 1612 | ||
| 1504 | 1613 | /// Map function. |
|
| 1505 | 1614 | pub fn map(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1506 | - | let (f, list) = <(Function, Vec<Expr>)>::try_from_args(args)?; |
|
| 1615 | + | let (f, list) = <(Function, Either<Vec<Expr>, Mut<Vec<Expr>>>)>::try_from_args(args)?; |
|
| 1507 | 1616 | let mut env = Env::from_parent(env); |
|
| 1508 | 1617 | ||
| 1509 | - | list.into_iter() |
|
| 1510 | - | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1511 | - | .collect::<Result<Vec<_>>>() |
|
| 1512 | - | .map(Expr::Vector) |
|
| 1618 | + | // TODO: Avoid creating a new list and instead modify in-place and return? |
|
| 1619 | + | ||
| 1620 | + | match list { |
|
| 1621 | + | Either::Left(tuple) => { |
|
| 1622 | + | let mapped = tuple |
|
| 1623 | + | .into_iter() |
|
| 1624 | + | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1625 | + | .collect::<Result<Vec<_>>>()?; |
|
| 1626 | + | ||
| 1627 | + | Ok(Expr::Vector(Rc::new(RefCell::new(mapped)))) |
|
| 1628 | + | } |
|
| 1629 | + | Either::Right(vec) => { |
|
| 1630 | + | let mut borrowed = vec.borrow_mut(); |
|
| 1631 | + | let mapped = borrowed |
|
| 1632 | + | .drain(..) |
|
| 1633 | + | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1634 | + | .collect::<Result<Vec<_>>>()?; |
|
| 1635 | + | ||
| 1636 | + | *borrowed = mapped; |
|
| 1637 | + | ||
| 1638 | + | Ok(Expr::Vector(Rc::clone(&vec))) |
|
| 1639 | + | } |
|
| 1640 | + | } |
|
| 1513 | 1641 | } |
|
| 1514 | 1642 | ||
| 1515 | 1643 | /// Return the length of a value. |
|
| 1516 | 1644 | pub fn length(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1517 | 1645 | let (value,) = <(Expr,)>::try_from_args(args)?; |
|
| 1518 | 1646 | let length = match value { |
|
| 1519 | - | Expr::Vector(l) => l.len(), |
|
| 1647 | + | Expr::Vector(l) => l.borrow().len(), |
|
| 1520 | 1648 | Expr::Tuple(l) => l.len(), |
|
| 1521 | 1649 | Expr::Dict(d) => d.len(), |
|
| 1522 | 1650 | Expr::Str(s) => s.chars().count(), |
|
| 1523 | 1651 | _ => return Err(Error::UnexpectedValue(value)), |
|
| 1524 | 1652 | }; |
| 1529 | 1657 | ||
| 1530 | 1658 | /// Check if the collection is empty. |
|
| 1531 | 1659 | pub fn empty(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1532 | 1660 | let (expr,) = <(Expr,)>::try_from_args(args)?; |
|
| 1533 | 1661 | let is_empty = match expr { |
|
| 1534 | - | Expr::Vector(l) => l.is_empty(), |
|
| 1662 | + | Expr::Vector(l) => l.borrow().is_empty(), |
|
| 1535 | 1663 | Expr::Tuple(l) => l.is_empty(), |
|
| 1536 | 1664 | Expr::Str(s) => s.is_empty(), |
|
| 1537 | 1665 | Expr::Dict(d) => d.is_empty(), |
|
| 1538 | 1666 | _ => return Err(Error::UnexpectedValue(expr)), |
|
| 1539 | 1667 | }; |
| 1599 | 1727 | let mut args = args.into_iter(); |
|
| 1600 | 1728 | let Some(key) = args.next() else { |
|
| 1601 | 1729 | return Err(Error::ExpectedValue("key or value")); |
|
| 1602 | 1730 | }; |
|
| 1603 | 1731 | let is_contained = match args.next() { |
|
| 1604 | - | Some(Expr::Vector(l)) => l.contains(&key), |
|
| 1732 | + | Some(Expr::Vector(l)) => l.borrow().contains(&key), |
|
| 1605 | 1733 | Some(Expr::Tuple(l)) => l.contains(&key), |
|
| 1606 | 1734 | Some(Expr::Str(s)) => match key { |
|
| 1607 | 1735 | Expr::Str(k) => s.contains(&k), |
|
| 1608 | 1736 | Expr::Char(c) => s.contains(c), |
|
| 1609 | 1737 | _ => return Err(Error::ExpectedValue("string or character")), |
| 1619 | 1747 | }; |
|
| 1620 | 1748 | Ok(Expr::Bool(is_contained)) |
|
| 1621 | 1749 | } |
|
| 1622 | 1750 | ||
| 1623 | 1751 | /// Push elements to the end of a vector. |
|
| 1624 | - | pub fn append(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1625 | - | if args.is_empty() { |
|
| 1626 | - | return Ok(Expr::nil()); |
|
| 1752 | + | pub fn push(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1753 | + | if args.len() < 2 { |
|
| 1754 | + | return Err(Error::WrongArgumentCount { |
|
| 1755 | + | expected: 2, |
|
| 1756 | + | actual: args.len(), |
|
| 1757 | + | }); |
|
| 1627 | 1758 | } |
|
| 1628 | 1759 | let mut args = args.into_iter(); |
|
| 1760 | + | let Some(Expr::Vector(v)) = args.next() else { |
|
| 1761 | + | return Err(Error::ExpectedValue("vector")); |
|
| 1762 | + | }; |
|
| 1763 | + | v.borrow_mut().extend(args); |
|
| 1629 | 1764 | ||
| 1630 | - | match args.next() { |
|
| 1631 | - | Some(Expr::Tuple(mut l)) => { |
|
| 1632 | - | l.extend(args); |
|
| 1633 | - | Ok(Expr::Vector(l)) |
|
| 1634 | - | } |
|
| 1635 | - | Some(Expr::Vector(mut v)) => { |
|
| 1636 | - | v.extend(args); |
|
| 1637 | - | Ok(Expr::Vector(v)) |
|
| 1638 | - | } |
|
| 1639 | - | _ => Err(Error::ExpectedValue("vector")), |
|
| 1640 | - | } |
|
| 1765 | + | Ok(Expr::nil()) |
|
| 1641 | 1766 | } |
|
| 1642 | 1767 | ||
| 1643 | 1768 | /// Reverse a vector. |
|
| 1644 | 1769 | pub fn reverse(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1645 | - | let (mut v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1646 | - | v.reverse(); |
|
| 1770 | + | let (v,) = <(Mut<Vec<Expr>>,)>::try_from_args(args)?; |
|
| 1771 | + | v.borrow_mut().reverse(); |
|
| 1647 | 1772 | ||
| 1648 | - | Ok(Expr::Vector(v)) |
|
| 1773 | + | Ok(Expr::nil()) |
|
| 1649 | 1774 | } |
|
| 1650 | 1775 | ||
| 1651 | 1776 | /// Create a list of numbers in a specified range. |
|
| 1652 | 1777 | pub fn range(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1653 | 1778 | match args.as_slice() { |
|
| 1654 | - | [Expr::Integer(end)] => Ok(Expr::Vector((0..*end).map(Expr::Integer).collect())), |
|
| 1779 | + | [Expr::Integer(end)] => { |
|
| 1780 | + | Ok(Tuple::new((0..*end).map(Expr::Integer).collect::<Vec<_>>()).into()) |
|
| 1781 | + | } |
|
| 1655 | 1782 | [Expr::Integer(start), Expr::Integer(end)] => { |
|
| 1656 | - | Ok(Expr::Vector((*start..*end).map(Expr::Integer).collect())) |
|
| 1783 | + | Ok(Tuple::new((*start..*end).map(Expr::Integer).collect::<Vec<_>>()).into()) |
|
| 1657 | 1784 | } |
|
| 1658 | - | [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] => Ok(Expr::Vector( |
|
| 1785 | + | [Expr::Integer(start), Expr::Integer(end), Expr::Integer(step)] => Ok(Tuple::new( |
|
| 1659 | 1786 | (0..) |
|
| 1660 | 1787 | .map(|n| *start + n * *step) |
|
| 1661 | 1788 | .take_while(|&x| x < *end) |
|
| 1662 | 1789 | .map(Expr::Integer) |
|
| 1663 | - | .collect(), |
|
| 1664 | - | )), |
|
| 1790 | + | .collect::<Vec<_>>(), |
|
| 1791 | + | ) |
|
| 1792 | + | .into()), |
|
| 1665 | 1793 | _ => Err(Error::WrongArgumentCount { |
|
| 1666 | 1794 | expected: 3, |
|
| 1667 | 1795 | actual: args.len(), |
|
| 1668 | 1796 | }), |
|
| 1669 | 1797 | } |
| 1909 | 2037 | Ok(Expr::Color(Rgba::new(r, g, b, a))) |
|
| 1910 | 2038 | } |
|
| 1911 | 2039 | ||
| 1912 | 2040 | /// Create a tuple from arguments. |
|
| 1913 | 2041 | pub fn tuple(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1914 | - | Ok(Expr::Tuple(args)) |
|
| 2042 | + | Ok(Tuple::new(args).into()) |
|
| 1915 | 2043 | } |
|
| 1916 | 2044 | ||
| 1917 | 2045 | fn fold<T: TryFrom<Expr, Error = Expr> + Into<Expr>>( |
|
| 1918 | 2046 | args: impl IntoIterator<Item = Expr>, |
|
| 1919 | 2047 | init: T, |
| 2375 | 2503 | expect(&["[(+ 1 2)]"], Expr::tuple([Expr::Integer(3)])); |
|
| 2376 | 2504 | expect_err(&["[(4 2)]"], Error::UnexpectedValue(Expr::Integer(4))); |
|
| 2377 | 2505 | expect(&["(eq? () [])"], Expr::Bool(true)); |
|
| 2378 | 2506 | } |
|
| 2379 | 2507 | ||
| 2508 | + | #[test] |
|
| 2509 | + | fn test_push() { |
|
| 2510 | + | expect( |
|
| 2511 | + | &[ |
|
| 2512 | + | "(def vec @[1 2 3])", |
|
| 2513 | + | "(push vec 4)", |
|
| 2514 | + | "(push vec 5 6)", |
|
| 2515 | + | "vec", |
|
| 2516 | + | ], |
|
| 2517 | + | Expr::vector([ |
|
| 2518 | + | Expr::Integer(1), |
|
| 2519 | + | Expr::Integer(2), |
|
| 2520 | + | Expr::Integer(3), |
|
| 2521 | + | Expr::Integer(4), |
|
| 2522 | + | Expr::Integer(5), |
|
| 2523 | + | Expr::Integer(6), |
|
| 2524 | + | ]), |
|
| 2525 | + | ); |
|
| 2526 | + | } |
|
| 2527 | + | ||
| 2380 | 2528 | #[test] |
|
| 2381 | 2529 | fn test_tuple() { |
|
| 2382 | 2530 | expect( |
|
| 2383 | 2531 | &["'(+ 1)"], |
|
| 2384 | 2532 | Expr::tuple([Expr::Symbol("+".into()), Expr::Integer(1)]), |
| 2439 | 2587 | expect(&["(contains? `z` \"hello\")"], Expr::Bool(false)); |
|
| 2440 | 2588 | expect(&["(contains? :x (dict [:x 1]))"], Expr::Bool(true)); |
|
| 2441 | 2589 | expect(&["(contains? :y (dict [:x 1]))"], Expr::Bool(false)); |
|
| 2442 | 2590 | } |
|
| 2443 | 2591 | ||
| 2444 | - | #[test] |
|
| 2445 | - | fn test_append() { |
|
| 2446 | - | expect( |
|
| 2447 | - | &["(append [1 2] 3 4)"], |
|
| 2448 | - | Expr::vector([ |
|
| 2449 | - | Expr::Integer(1), |
|
| 2450 | - | Expr::Integer(2), |
|
| 2451 | - | Expr::Integer(3), |
|
| 2452 | - | Expr::Integer(4), |
|
| 2453 | - | ]), |
|
| 2454 | - | ); |
|
| 2455 | - | expect(&["(append [] 1)"], Expr::vector([Expr::Integer(1)])); |
|
| 2456 | - | } |
|
| 2457 | - | ||
| 2458 | 2592 | #[test] |
|
| 2459 | 2593 | fn test_reverse() { |
|
| 2460 | 2594 | expect( |
|
| 2461 | - | &["(reverse [1 2 3])"], |
|
| 2595 | + | &["(def list @[1 2 3])", "(reverse list)", "list"], |
|
| 2462 | 2596 | Expr::vector([Expr::Integer(3), Expr::Integer(2), Expr::Integer(1)]), |
|
| 2463 | 2597 | ); |
|
| 2464 | - | expect(&["(reverse [])"], Expr::vector([])); |
|
| 2598 | + | expect( |
|
| 2599 | + | &["(def list @[])", "(reverse list)", "list"], |
|
| 2600 | + | Expr::vector([]), |
|
| 2601 | + | ); |
|
| 2465 | 2602 | } |
|
| 2466 | 2603 | ||
| 2467 | 2604 | #[test] |
|
| 2468 | 2605 | fn test_range() { |
|
| 2469 | 2606 | expect( |
|
| 2470 | 2607 | &["(range 5)"], |
|
| 2471 | - | Expr::vector([ |
|
| 2608 | + | Expr::tuple([ |
|
| 2472 | 2609 | Expr::Integer(0), |
|
| 2473 | 2610 | Expr::Integer(1), |
|
| 2474 | 2611 | Expr::Integer(2), |
|
| 2475 | 2612 | Expr::Integer(3), |
|
| 2476 | 2613 | Expr::Integer(4), |
|
| 2477 | 2614 | ]), |
|
| 2478 | 2615 | ); |
|
| 2479 | 2616 | expect( |
|
| 2480 | 2617 | &["(range 2 5)"], |
|
| 2481 | - | Expr::vector([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]), |
|
| 2618 | + | Expr::tuple([Expr::Integer(2), Expr::Integer(3), Expr::Integer(4)]), |
|
| 2482 | 2619 | ); |
|
| 2483 | 2620 | expect( |
|
| 2484 | 2621 | &["(range 0 10 2)"], |
|
| 2485 | - | Expr::vector([ |
|
| 2622 | + | Expr::tuple([ |
|
| 2486 | 2623 | Expr::Integer(0), |
|
| 2487 | 2624 | Expr::Integer(2), |
|
| 2488 | 2625 | Expr::Integer(4), |
|
| 2489 | 2626 | Expr::Integer(6), |
|
| 2490 | 2627 | Expr::Integer(8), |
|
| 2491 | 2628 | ]), |
|
| 2492 | 2629 | ); |
|
| 2493 | - | expect(&["(range 0)"], Expr::vector([])); |
|
| 2630 | + | expect(&["(range 0)"], Expr::tuple([])); |
|
| 2494 | 2631 | } |
|
| 2495 | 2632 | ||
| 2496 | 2633 | #[test] |
|
| 2497 | 2634 | fn test_quote() { |
|
| 2498 | 2635 | expect(&["'symbol"], Expr::Symbol("symbol".into())); |
ombre/src/lisp/parser.rs
+33 -22
| 1 | 1 | //! Parser. |
|
| 2 | + | use std::cell::RefCell; |
|
| 2 | 3 | use std::collections::HashMap; |
|
| 3 | 4 | use std::fmt; |
|
| 4 | 5 | use std::iter::Peekable; |
|
| 5 | 6 | use std::rc::Rc; |
|
| 6 | 7 | use std::result; |
|
| 7 | 8 | ||
| 8 | - | use crate::lisp::evaluator::{Expr, Key, Symbol}; |
|
| 9 | + | use crate::lisp::evaluator::{Expr, Key, Symbol, Tuple}; |
|
| 9 | 10 | use crate::lisp::scanner; |
|
| 10 | 11 | use crate::lisp::scanner::Token; |
|
| 11 | 12 | ||
| 12 | 13 | /// Result type for all functions. |
|
| 13 | 14 | pub type Result<T> = result::Result<T, Error>; |
| 75 | 76 | } |
|
| 76 | 77 | ||
| 77 | 78 | fn parse_expr(&mut self) -> Result<Expr> { |
|
| 78 | 79 | let token = self.peek()?; |
|
| 79 | 80 | let expr = match token { |
|
| 80 | - | Token::LParen => self.parse_sexpr()?, |
|
| 81 | + | Token::LParen => self.parse_tuple().map(Expr::tuple)?, |
|
| 81 | 82 | Token::RParen => return Err(Error::UnexpectedToken(token.owned())), |
|
| 82 | 83 | Token::LBrace => self.parse_dict()?, |
|
| 83 | 84 | Token::RBrace => return Err(Error::UnexpectedToken(token.owned())), |
|
| 84 | - | Token::LBracket => self.parse_vector()?, |
|
| 85 | + | Token::LBracket => self.parse_tuple_lit().map(|es| { |
|
| 86 | + | if es.is_empty() { |
|
| 87 | + | Expr::nil() |
|
| 88 | + | } else { |
|
| 89 | + | Expr::Tuple(Tuple::literal(es)) |
|
| 90 | + | } |
|
| 91 | + | })?, |
|
| 85 | 92 | Token::RBracket => return Err(Error::UnexpectedToken(token.owned())), |
|
| 86 | 93 | Token::Quote => self.parse_quoted()?, |
|
| 94 | + | Token::Ref => self.parse_ref()?, |
|
| 87 | 95 | Token::Symbol(s) => { |
|
| 88 | 96 | self.tokens.next(); |
|
| 89 | 97 | Expr::Symbol(Symbol::from(Rc::from(s))) |
|
| 90 | 98 | } |
|
| 91 | 99 | Token::Atom(s) => { |
| 114 | 122 | } |
|
| 115 | 123 | }; |
|
| 116 | 124 | Ok(expr) |
|
| 117 | 125 | } |
|
| 118 | 126 | ||
| 119 | - | fn parse_sexpr(&mut self) -> Result<Expr> { |
|
| 127 | + | fn parse_tuple(&mut self) -> Result<Vec<Expr>> { |
|
| 120 | 128 | self.next_if(|t| t == &Token::LParen)?; |
|
| 121 | 129 | let exprs = self.parse_until(|t| t == &Token::RParen)?; |
|
| 122 | 130 | self.next_if(|t| t == &Token::RParen)?; |
|
| 123 | 131 | ||
| 124 | - | Ok(Expr::tuple(exprs)) |
|
| 132 | + | Ok(exprs) |
|
| 125 | 133 | } |
|
| 126 | 134 | ||
| 127 | 135 | fn parse_dict(&mut self) -> Result<Expr> { |
|
| 128 | 136 | self.next_if(|t| t == &Token::LBrace)?; |
|
| 129 | 137 | let mut exprs = self.parse_until(|t| t == &Token::RBrace)?.into_iter(); |
| 141 | 149 | dict.insert(k, v); |
|
| 142 | 150 | } |
|
| 143 | 151 | Ok(Expr::Dict(dict)) |
|
| 144 | 152 | } |
|
| 145 | 153 | ||
| 146 | - | fn parse_vector(&mut self) -> Result<Expr> { |
|
| 154 | + | fn parse_tuple_lit(&mut self) -> Result<Vec<Expr>> { |
|
| 147 | 155 | self.next_if(|t| t == &Token::LBracket)?; |
|
| 148 | 156 | let exprs = self.parse_until(|t| t == &Token::RBracket)?; |
|
| 149 | 157 | self.next_if(|t| t == &Token::RBracket)?; |
|
| 150 | 158 | ||
| 151 | - | Ok(Expr::vector(exprs)) |
|
| 159 | + | Ok(exprs) |
|
| 152 | 160 | } |
|
| 153 | 161 | ||
| 154 | 162 | fn parse_quoted(&mut self) -> Result<Expr> { |
|
| 155 | 163 | self.next_if(|t| t == &Token::Quote)?; |
|
| 156 | 164 | let expr = self.parse_expr()?; |
|
| 157 | 165 | ||
| 158 | 166 | Ok(Expr::Quoted(expr.into())) |
|
| 159 | 167 | } |
|
| 160 | 168 | ||
| 169 | + | fn parse_ref(&mut self) -> Result<Expr> { |
|
| 170 | + | self.next_if(|t| t == &Token::Ref)?; |
|
| 171 | + | ||
| 172 | + | let e = match self.peek()? { |
|
| 173 | + | Token::LParen => self.parse_tuple(), |
|
| 174 | + | Token::LBracket => self.parse_tuple_lit(), |
|
| 175 | + | t => return Err(Error::UnexpectedToken(t.owned())), |
|
| 176 | + | }?; |
|
| 177 | + | Ok(Expr::Vector(Rc::new(RefCell::new(e)))) |
|
| 178 | + | } |
|
| 179 | + | ||
| 161 | 180 | fn next_if(&mut self, condition: impl FnOnce(&Token<'_>) -> bool) -> Result<Token<'a>> { |
|
| 162 | 181 | let tok = self.tokens.next().ok_or(Error::EndOfInput)?.map_err(Error::Scanner)?; |
|
| 163 | 182 | ||
| 164 | 183 | if condition(&tok) { |
|
| 165 | 184 | return Ok(tok); |
| 226 | 245 | err("(const 1 nil}"); |
|
| 227 | 246 | err("{const 1 nil)"); |
|
| 228 | 247 | } |
|
| 229 | 248 | ||
| 230 | 249 | #[test] |
|
| 231 | - | fn test_parse_sexpr() { |
|
| 250 | + | fn test_parse_tuple() { |
|
| 232 | 251 | ok("()", &[Expr::nil()]); |
|
| 233 | 252 | ok("(cons)", &[Expr::tuple([Expr::Symbol("cons".into())])]); |
|
| 234 | 253 | ok( |
|
| 235 | 254 | "(+ 4 2)", |
|
| 236 | 255 | &[Expr::tuple([ |
|
| 237 | 256 | Expr::Symbol("+".into()), |
|
| 238 | 257 | Expr::Integer(4), |
|
| 239 | 258 | Expr::Integer(2), |
|
| 240 | 259 | ])], |
|
| 241 | 260 | ); |
|
| 261 | + | ok("[]", &[Expr::nil()]); |
|
| 262 | + | ok( |
|
| 263 | + | "[1 2 3]", |
|
| 264 | + | &[Tuple::literal([Expr::Integer(1), Expr::Integer(2), Expr::Integer(3)]).into()], |
|
| 265 | + | ); |
|
| 242 | 266 | } |
|
| 243 | 267 | ||
| 244 | 268 | #[test] |
|
| 245 | - | fn test_parse_sexpr_nested() { |
|
| 269 | + | fn test_parse_tuple_nested() { |
|
| 246 | 270 | ok( |
|
| 247 | 271 | "(cons 1 (cons 2 (cons 3 nil)))", |
|
| 248 | 272 | &[Expr::tuple([ |
|
| 249 | 273 | Expr::Symbol("cons".into()), |
|
| 250 | 274 | Expr::Integer(1), |
| 282 | 306 | err("{:x}"); |
|
| 283 | 307 | err("{:x 1 :y}"); |
|
| 284 | 308 | err("{#00ff11 42}"); |
|
| 285 | 309 | } |
|
| 286 | 310 | ||
| 287 | - | #[test] |
|
| 288 | - | fn test_parse_vector() { |
|
| 289 | - | ok("[]", &[Expr::vector(vec![])]); |
|
| 290 | - | ok( |
|
| 291 | - | "[1 2 3]", |
|
| 292 | - | &[Expr::vector([ |
|
| 293 | - | Expr::Integer(1), |
|
| 294 | - | Expr::Integer(2), |
|
| 295 | - | Expr::Integer(3), |
|
| 296 | - | ])], |
|
| 297 | - | ); |
|
| 298 | - | } |
|
| 299 | - | ||
| 300 | 311 | #[test] |
|
| 301 | 312 | fn test_parse_quoted() { |
|
| 302 | 313 | ok( |
|
| 303 | 314 | "'(sym)", |
|
| 304 | 315 | &[Expr::Quoted(Box::new(Expr::tuple([Expr::Symbol( |
ombre/src/lisp/scanner.rs
+7 -0
| 62 | 62 | LBracket, |
|
| 63 | 63 | /// Eg. `]` |
|
| 64 | 64 | RBracket, |
|
| 65 | 65 | /// Eg. ' |
|
| 66 | 66 | Quote, |
|
| 67 | + | /// Eg. @ |
|
| 68 | + | Ref, |
|
| 67 | 69 | /// Eg. fnord |
|
| 68 | 70 | Symbol(Cow<'a, str>), |
|
| 69 | 71 | /// Eg. :fnord |
|
| 70 | 72 | Atom(Cow<'a, str>), |
|
| 71 | 73 | /// Eg. `z` |
| 91 | 93 | LParen => LParen, |
|
| 92 | 94 | RParen => RParen, |
|
| 93 | 95 | LBracket => LBracket, |
|
| 94 | 96 | RBracket => RBracket, |
|
| 95 | 97 | Quote => Quote, |
|
| 98 | + | Ref => Ref, |
|
| 96 | 99 | Symbol(s) => Symbol(Cow::Owned(s.into_owned())), |
|
| 97 | 100 | Atom(s) => Atom(Cow::Owned(s.into_owned())), |
|
| 98 | 101 | Char(c) => Char(c), |
|
| 99 | 102 | Str(s) => Str(Cow::Owned(s.into_owned())), |
|
| 100 | 103 | Float(n) => Float(n), |
| 319 | 322 | } |
|
| 320 | 323 | '\'' => { |
|
| 321 | 324 | self.chars.next(); |
|
| 322 | 325 | return Some(Ok(Token::Quote)); |
|
| 323 | 326 | } |
|
| 327 | + | '@' => { |
|
| 328 | + | self.chars.next(); |
|
| 329 | + | return Some(Ok(Token::Ref)); |
|
| 330 | + | } |
|
| 324 | 331 | c if c.is_ascii_whitespace() => { |
|
| 325 | 332 | self.chars.next(); |
|
| 326 | 333 | } |
|
| 327 | 334 | c if c.is_ascii_digit() => { |
|
| 328 | 335 | return Some(self.scan_number()); |