ombre: Refactor lisp evaluator
9928a710b0321be1456b8de636adb226689bc4bd
1 parent
3094fa74
ombre/src/lisp.rs
+1 -1
| 15 | 15 | pub mod scanner; |
|
| 16 | 16 | ||
| 17 | 17 | use std::error; |
|
| 18 | 18 | ||
| 19 | 19 | pub use dynamic::{Dynamic, IsDynamic}; |
|
| 20 | - | pub use evaluator::{Env, Error, Evaluator, Expr, Result}; |
|
| 20 | + | pub use evaluator::{Env, Error, Evaluator, Expr, Result, Symbol}; |
|
| 21 | 21 | pub use parser::Parser; |
|
| 22 | 22 | pub use scanner::Scanner; |
|
| 23 | 23 | ||
| 24 | 24 | /// File extension for language files. |
|
| 25 | 25 | pub const FILE_EXTENSION: &str = "scm"; |
ombre/src/lisp/evaluator.rs
+297 -288
| 1 | 1 | //! Expression evaluator. |
|
| 2 | + | use std::borrow::Borrow; |
|
| 2 | 3 | use std::cell::RefCell; |
|
| 3 | 4 | use std::collections::HashSet; |
|
| 5 | + | use std::hash::{Hash, Hasher}; |
|
| 4 | 6 | use std::ops::{Deref, DerefMut}; |
|
| 5 | 7 | use std::path::PathBuf; |
|
| 6 | 8 | use std::rc::Rc; |
|
| 7 | 9 | use std::{collections::HashMap, iter::Peekable}; |
|
| 8 | 10 | use std::{fmt, fs, iter, result}; |
| 27 | 29 | /// Module not found when importing. |
|
| 28 | 30 | ModuleNotFound(Symbol), |
|
| 29 | 31 | /// Expected value of a certain type. |
|
| 30 | 32 | ExpectedValue(&'static str), |
|
| 31 | 33 | /// Expected value for named argument. |
|
| 32 | - | ExpectedNamedValue(Symbol), |
|
| 34 | + | ExpectedNamedValue(Rc<str>), |
|
| 33 | 35 | /// Unexpected value. |
|
| 34 | 36 | UnexpectedValue(Expr), |
|
| 35 | 37 | /// Unexpected named argument. |
|
| 36 | 38 | UnexpectedNamedArgument(Symbol), |
|
| 37 | 39 | /// Wrong number of arguments supplied. |
| 67 | 69 | } |
|
| 68 | 70 | ||
| 69 | 71 | impl std::error::Error for Error {} |
|
| 70 | 72 | ||
| 71 | 73 | /// A symbol is an immutable string. |
|
| 72 | - | pub type Symbol = Rc<str>; |
|
| 74 | + | #[derive(Debug, Clone, Eq, PartialOrd, Ord)] |
|
| 75 | + | pub struct Symbol(Rc<str>); |
|
| 76 | + | ||
| 77 | + | impl Hash for Symbol { |
|
| 78 | + | fn hash<H: Hasher>(&self, state: &mut H) { |
|
| 79 | + | self.0.hash(state) |
|
| 80 | + | } |
|
| 81 | + | } |
|
| 82 | + | ||
| 83 | + | impl PartialEq for Symbol { |
|
| 84 | + | fn eq(&self, other: &Self) -> bool { |
|
| 85 | + | self.0.eq(&other.0) |
|
| 86 | + | } |
|
| 87 | + | } |
|
| 88 | + | ||
| 89 | + | impl Borrow<str> for Symbol { |
|
| 90 | + | fn borrow(&self) -> &str { |
|
| 91 | + | &self.0 |
|
| 92 | + | } |
|
| 93 | + | } |
|
| 94 | + | ||
| 95 | + | impl From<Rc<str>> for Symbol { |
|
| 96 | + | fn from(value: Rc<str>) -> Self { |
|
| 97 | + | Symbol(value) |
|
| 98 | + | } |
|
| 99 | + | } |
|
| 100 | + | ||
| 101 | + | impl From<&str> for Symbol { |
|
| 102 | + | fn from(value: &str) -> Self { |
|
| 103 | + | Symbol(value.into()) |
|
| 104 | + | } |
|
| 105 | + | } |
|
| 106 | + | ||
| 107 | + | impl AsRef<str> for Symbol { |
|
| 108 | + | fn as_ref(&self) -> &str { |
|
| 109 | + | self.0.as_ref() |
|
| 110 | + | } |
|
| 111 | + | } |
|
| 112 | + | ||
| 113 | + | impl Deref for Symbol { |
|
| 114 | + | type Target = str; |
|
| 115 | + | ||
| 116 | + | fn deref(&self) -> &Self::Target { |
|
| 117 | + | self.0.deref() |
|
| 118 | + | } |
|
| 119 | + | } |
|
| 120 | + | ||
| 121 | + | impl fmt::Display for Symbol { |
|
| 122 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 123 | + | self.0.fmt(f) |
|
| 124 | + | } |
|
| 125 | + | } |
|
| 73 | 126 | ||
| 74 | 127 | /// Values that can be used as dictionary keys. |
|
| 75 | 128 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
|
| 76 | 129 | pub enum Key { |
|
| 77 | 130 | /// Eg. :true |
| 214 | 267 | pub fn vector(items: impl IntoIterator<Item = Expr>) -> Self { |
|
| 215 | 268 | Expr::Vector(items.into_iter().collect()) |
|
| 216 | 269 | } |
|
| 217 | 270 | ||
| 218 | 271 | /// Construct a symbol. |
|
| 219 | - | pub fn symbol(name: impl Into<Rc<str>>) -> Self { |
|
| 272 | + | pub fn symbol(name: impl Into<Symbol>) -> Self { |
|
| 220 | 273 | Expr::Symbol(name.into()) |
|
| 221 | 274 | } |
|
| 222 | 275 | ||
| 223 | 276 | /// Quote an expression. |
|
| 224 | 277 | pub fn quoted(self) -> Self { |
| 281 | 334 | fn from(value: Closure) -> Self { |
|
| 282 | 335 | Expr::Function(Function::Closure(Rc::new(value))) |
|
| 283 | 336 | } |
|
| 284 | 337 | } |
|
| 285 | 338 | ||
| 339 | + | impl TryFrom<Expr> for Function { |
|
| 340 | + | type Error = Expr; |
|
| 341 | + | ||
| 342 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 343 | + | match expr { |
|
| 344 | + | Expr::Function(f) => Ok(f), |
|
| 345 | + | _ => Err(expr), |
|
| 346 | + | } |
|
| 347 | + | } |
|
| 348 | + | } |
|
| 349 | + | ||
| 350 | + | impl TryFrom<Expr> for Rc<RefCell<Expr>> { |
|
| 351 | + | type Error = Expr; |
|
| 352 | + | ||
| 353 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 354 | + | match expr { |
|
| 355 | + | Expr::Ref(r) => Ok(r), |
|
| 356 | + | _ => Err(expr), |
|
| 357 | + | } |
|
| 358 | + | } |
|
| 359 | + | } |
|
| 360 | + | ||
| 286 | 361 | impl TryFrom<Expr> for f32 { |
|
| 287 | 362 | type Error = Expr; |
|
| 288 | 363 | ||
| 289 | 364 | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 290 | 365 | match expr { |
| 327 | 402 | _ => Err(expr), |
|
| 328 | 403 | } |
|
| 329 | 404 | } |
|
| 330 | 405 | } |
|
| 331 | 406 | ||
| 407 | + | impl TryFrom<Expr> for Symbol { |
|
| 408 | + | type Error = Expr; |
|
| 409 | + | ||
| 410 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 411 | + | match expr { |
|
| 412 | + | Expr::Symbol(s) => Ok(s), |
|
| 413 | + | _ => Err(expr), |
|
| 414 | + | } |
|
| 415 | + | } |
|
| 416 | + | } |
|
| 417 | + | ||
| 418 | + | impl TryFrom<Expr> for Vec<Expr> { |
|
| 419 | + | type Error = Expr; |
|
| 420 | + | ||
| 421 | + | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 422 | + | match expr { |
|
| 423 | + | Expr::Vector(v) => Ok(v), |
|
| 424 | + | _ => Err(expr), |
|
| 425 | + | } |
|
| 426 | + | } |
|
| 427 | + | } |
|
| 428 | + | ||
| 429 | + | impl TryFrom<Expr> for List<Expr> { |
|
| 430 | + | type Error = Expr; |
|
| 431 | + | ||
| 432 | + | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 433 | + | match expr { |
|
| 434 | + | Expr::List(l) => Ok(l), |
|
| 435 | + | _ => Err(expr), |
|
| 436 | + | } |
|
| 437 | + | } |
|
| 438 | + | } |
|
| 439 | + | ||
| 332 | 440 | impl TryFrom<Expr> for Vector2D<f64> { |
|
| 333 | 441 | type Error = Expr; |
|
| 442 | + | ||
| 334 | 443 | fn try_from(expr: Expr) -> Result<Self, Self::Error> { |
|
| 335 | 444 | match expr { |
|
| 336 | 445 | Expr::Vector2D(v) => Ok(v), |
|
| 337 | 446 | _ => Err(expr), |
|
| 338 | 447 | } |
| 375 | 484 | fn from(v: Vector4D<f64>) -> Self { |
|
| 376 | 485 | Expr::Vector4D(v) |
|
| 377 | 486 | } |
|
| 378 | 487 | } |
|
| 379 | 488 | ||
| 489 | + | /// Trait for converting from a vector of [`Expr`] values into a tuple of specific types. |
|
| 490 | + | pub trait TryFromArgs: Sized { |
|
| 491 | + | /// The number of arguments expected. |
|
| 492 | + | const ARITY: usize; |
|
| 493 | + | ||
| 494 | + | /// Try to convert from an arguments vector. |
|
| 495 | + | fn try_from_args(args: Vec<Expr>) -> Result<Self>; |
|
| 496 | + | } |
|
| 497 | + | ||
| 498 | + | /// Trait for converting from [`Expr`]. |
|
| 499 | + | /// This is required over [`TryFrom`] due to the blanket `TryFrom<Self>` implementation, |
|
| 500 | + | /// which gets in the way for [`Expr`] conversions. |
|
| 501 | + | trait FromExpr: Sized { |
|
| 502 | + | /// Convert an expression to some type. |
|
| 503 | + | fn from_expr(expr: Expr) -> Result<Self>; |
|
| 504 | + | } |
|
| 505 | + | ||
| 506 | + | impl<T: TryFrom<Expr, Error = Expr>> FromExpr for T { |
|
| 507 | + | fn from_expr(expr: Expr) -> Result<Self> { |
|
| 508 | + | expr.try_into().map_err(Error::UnexpectedValue) |
|
| 509 | + | } |
|
| 510 | + | } |
|
| 511 | + | ||
| 512 | + | impl FromExpr for Expr { |
|
| 513 | + | fn from_expr(expr: Expr) -> Result<Self> { |
|
| 514 | + | Ok(expr) |
|
| 515 | + | } |
|
| 516 | + | } |
|
| 517 | + | ||
| 518 | + | impl<T1: FromExpr> TryFromArgs for (T1,) { |
|
| 519 | + | const ARITY: usize = 1; |
|
| 520 | + | ||
| 521 | + | fn try_from_args(args: Vec<Expr>) -> Result<Self> { |
|
| 522 | + | let arity = args.len(); |
|
| 523 | + | let Ok([a]) = <[_; 1]>::try_from(args) else { |
|
| 524 | + | return Err(Error::WrongArgumentCount { |
|
| 525 | + | expected: Self::ARITY, |
|
| 526 | + | actual: arity, |
|
| 527 | + | }); |
|
| 528 | + | }; |
|
| 529 | + | Ok((T1::from_expr(a)?,)) |
|
| 530 | + | } |
|
| 531 | + | } |
|
| 532 | + | ||
| 533 | + | impl<T1: FromExpr, T2: FromExpr> TryFromArgs for (T1, T2) { |
|
| 534 | + | const ARITY: usize = 2; |
|
| 535 | + | ||
| 536 | + | fn try_from_args(args: Vec<Expr>) -> Result<Self> { |
|
| 537 | + | let arity = args.len(); |
|
| 538 | + | let Ok([a, b]) = <[_; 2]>::try_from(args) else { |
|
| 539 | + | return Err(Error::WrongArgumentCount { |
|
| 540 | + | expected: Self::ARITY, |
|
| 541 | + | actual: arity, |
|
| 542 | + | }); |
|
| 543 | + | }; |
|
| 544 | + | Ok((T1::from_expr(a)?, T2::from_expr(b)?)) |
|
| 545 | + | } |
|
| 546 | + | } |
|
| 547 | + | ||
| 548 | + | impl<T1: FromExpr, T2: FromExpr, T3: FromExpr> TryFromArgs for (T1, T2, T3) { |
|
| 549 | + | const ARITY: usize = 3; |
|
| 550 | + | ||
| 551 | + | fn try_from_args(args: Vec<Expr>) -> Result<Self> { |
|
| 552 | + | let arity = args.len(); |
|
| 553 | + | let Ok([a, b, c]) = <[_; 3]>::try_from(args) else { |
|
| 554 | + | return Err(Error::WrongArgumentCount { |
|
| 555 | + | expected: Self::ARITY, |
|
| 556 | + | actual: arity, |
|
| 557 | + | }); |
|
| 558 | + | }; |
|
| 559 | + | Ok((T1::from_expr(a)?, T2::from_expr(b)?, T3::from_expr(c)?)) |
|
| 560 | + | } |
|
| 561 | + | } |
|
| 562 | + | ||
| 563 | + | impl<T1: FromExpr, T2: FromExpr, T3: FromExpr, T4: FromExpr> TryFromArgs for (T1, T2, T3, T4) { |
|
| 564 | + | const ARITY: usize = 4; |
|
| 565 | + | ||
| 566 | + | fn try_from_args(args: Vec<Expr>) -> Result<Self> { |
|
| 567 | + | let arity = args.len(); |
|
| 568 | + | let Ok([a, b, c, d]) = <[_; 4]>::try_from(args) else { |
|
| 569 | + | return Err(Error::WrongArgumentCount { |
|
| 570 | + | expected: Self::ARITY, |
|
| 571 | + | actual: arity, |
|
| 572 | + | }); |
|
| 573 | + | }; |
|
| 574 | + | Ok(( |
|
| 575 | + | T1::from_expr(a)?, |
|
| 576 | + | T2::from_expr(b)?, |
|
| 577 | + | T3::from_expr(c)?, |
|
| 578 | + | T4::from_expr(d)?, |
|
| 579 | + | )) |
|
| 580 | + | } |
|
| 581 | + | } |
|
| 582 | + | ||
| 380 | 583 | impl fmt::Display for Expr { |
|
| 381 | 584 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 382 | 585 | match self { |
|
| 383 | 586 | Expr::List(list) => { |
|
| 384 | 587 | write!(f, "(")?; |
| 424 | 627 | Expr::Float(n) => write!(f, "{n}"), |
|
| 425 | 628 | Expr::Integer(n) => write!(f, "{n}"), |
|
| 426 | 629 | Expr::Char(c) => write!(f, "`{c}`"), |
|
| 427 | 630 | Expr::Color(c) => write!(f, "#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a), |
|
| 428 | 631 | Expr::Function(e) => write!(f, "<fn {:p}>", e.as_ptr()), |
|
| 429 | - | Expr::Ref(r) => write!(f, "<ref {}>", r.borrow()), |
|
| 632 | + | Expr::Ref(r) => write!(f, "<ref {}>", RefCell::borrow(r)), |
|
| 430 | 633 | Expr::Dynamic(d) => write!(f, "<dyn {:p}>", d.as_ptr()), |
|
| 431 | 634 | } |
|
| 432 | 635 | } |
|
| 433 | 636 | } |
|
| 434 | 637 |
| 543 | 746 | // Handle named arguments. |
|
| 544 | 747 | let mut named_args = HashMap::new(); |
|
| 545 | 748 | while let Some(arg) = args.next() { |
|
| 546 | 749 | if let Expr::Atom(name) = arg { |
|
| 547 | 750 | if let Some(value) = args.next() { |
|
| 548 | - | named_args.insert(name, value); |
|
| 751 | + | named_args.insert(Symbol(name), value); |
|
| 549 | 752 | } else { |
|
| 550 | 753 | return Err(Error::ExpectedNamedValue(name)); |
|
| 551 | 754 | } |
|
| 552 | 755 | } else { |
|
| 553 | 756 | return Err(Error::InvalidArgument); |
| 629 | 832 | self |
|
| 630 | 833 | } |
|
| 631 | 834 | ||
| 632 | 835 | /// Define a binding and return a new evaluator. |
|
| 633 | 836 | pub fn with_binding(mut self, name: &str, docstr: Option<&str>, expr: Expr) -> Self { |
|
| 634 | - | self.binding(name, docstr, expr); |
|
| 837 | + | self.binding(Symbol(name.into()), docstr, expr); |
|
| 635 | 838 | self |
|
| 636 | 839 | } |
|
| 637 | 840 | ||
| 638 | 841 | /// Lookup a symbol. |
|
| 639 | 842 | pub fn lookup(&self, name: &str) -> Option<&Expr> { |
| 667 | 870 | pub fn import(&mut self, module: &Module) { |
|
| 668 | 871 | let namespace = &module.name; |
|
| 669 | 872 | for sym in &module.env.exports { |
|
| 670 | 873 | if let Some(value) = module.env.lookup(sym) { |
|
| 671 | 874 | let docs = module.env.lookup_doc(sym); |
|
| 672 | - | self.binding(format!("{namespace}/{sym}").as_str(), docs, value.clone()); |
|
| 875 | + | self.binding( |
|
| 876 | + | Symbol(format!("{namespace}/{sym}").into()), |
|
| 877 | + | docs, |
|
| 878 | + | value.clone(), |
|
| 879 | + | ); |
|
| 673 | 880 | } else { |
|
| 674 | 881 | panic!("Env::import: missing module binding `{sym}` in module `{namespace}`"); |
|
| 675 | 882 | } |
|
| 676 | 883 | } |
|
| 677 | 884 | } |
| 686 | 893 | &mut self, |
|
| 687 | 894 | name: &str, |
|
| 688 | 895 | docstr: &str, |
|
| 689 | 896 | f: impl Fn(Vec<Expr>, &Env<'_>) -> Result<Expr> + 'static, |
|
| 690 | 897 | ) { |
|
| 691 | - | self.binding(name, Some(docstr), Intrinsic(Rc::new(f)).into()); |
|
| 898 | + | self.binding( |
|
| 899 | + | Symbol(name.into()), |
|
| 900 | + | Some(docstr), |
|
| 901 | + | Intrinsic(Rc::new(f)).into(), |
|
| 902 | + | ); |
|
| 692 | 903 | } |
|
| 693 | 904 | ||
| 694 | 905 | /// Define a binding. |
|
| 695 | - | pub fn binding(&mut self, name: &str, docstr: Option<&str>, expr: Expr) { |
|
| 696 | - | self.insert(name.into(), expr); |
|
| 906 | + | pub fn binding(&mut self, name: Symbol, docstr: Option<&str>, expr: Expr) { |
|
| 907 | + | self.insert(name.clone(), expr); |
|
| 697 | 908 | ||
| 698 | 909 | if let Some(doc) = docstr { |
|
| 699 | - | self.docs.insert(name.into(), doc.to_string()); |
|
| 910 | + | self.docs.insert(name, doc.to_string()); |
|
| 700 | 911 | } |
|
| 701 | 912 | } |
|
| 702 | 913 | ||
| 703 | 914 | /// Create a new env from a parent environemnt. |
|
| 704 | 915 | pub fn from_parent(parent: &'a Env<'_>) -> Env<'a> { |
| 965 | 1176 | ||
| 966 | 1177 | match eval(value, env)? { |
|
| 967 | 1178 | Expr::Function(Function::Closure(mut closure)) => { |
|
| 968 | 1179 | if closure.name.is_none() { |
|
| 969 | 1180 | if let Some(closure) = Rc::get_mut(&mut closure) { |
|
| 970 | - | closure.name = Some(Rc::clone(&name)); |
|
| 1181 | + | closure.name = Some(name.clone()); |
|
| 971 | 1182 | } |
|
| 972 | 1183 | } |
|
| 973 | 1184 | env.binding( |
|
| 974 | - | &name, |
|
| 1185 | + | name, |
|
| 975 | 1186 | docstr.as_deref(), |
|
| 976 | 1187 | Expr::Function(Function::Closure(closure)), |
|
| 977 | 1188 | ); |
|
| 978 | 1189 | } |
|
| 979 | 1190 | other => { |
|
| 980 | - | env.binding(&name, docstr.as_deref(), other); |
|
| 1191 | + | env.binding(name, docstr.as_deref(), other); |
|
| 981 | 1192 | } |
|
| 982 | 1193 | } |
|
| 983 | 1194 | Ok(Expr::nil()) |
|
| 984 | 1195 | } |
|
| 985 | 1196 | "module" => { |
| 1051 | 1262 | ||
| 1052 | 1263 | /// Evaluate a lambda expression, returning a closure object. |
|
| 1053 | 1264 | fn eval_lambda(formals: Vec<Expr>, body: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1054 | 1265 | let local = env.flatten(); |
|
| 1055 | 1266 | let mut positional = Vec::new(); |
|
| 1056 | - | let mut named = HashMap::new(); |
|
| 1267 | + | let mut named = HashMap::<Symbol, Expr>::new(); |
|
| 1057 | 1268 | let mut formals = formals.into_iter(); |
|
| 1058 | 1269 | ||
| 1059 | 1270 | while let Some(expr) = formals.next() { |
|
| 1060 | 1271 | match expr { |
|
| 1061 | 1272 | Expr::Symbol(param) => positional.push(param), |
|
| 1062 | 1273 | Expr::Atom(name) => { |
|
| 1063 | 1274 | let Some(default) = formals.next() else { |
|
| 1064 | 1275 | return Err(Error::ExpectedNamedValue(name)); |
|
| 1065 | 1276 | }; |
|
| 1066 | - | named.insert(name, default); |
|
| 1277 | + | named.insert(Symbol(name), default); |
|
| 1067 | 1278 | } |
|
| 1068 | 1279 | _ => return Err(Error::ExpectedValue("symbol or atom")), |
|
| 1069 | 1280 | } |
|
| 1070 | 1281 | } |
|
| 1071 | 1282 |
| 1130 | 1341 | }; |
|
| 1131 | 1342 | let Some(expr) = items.next() else { |
|
| 1132 | 1343 | return Err(Error::ExpectedValue("expression")); |
|
| 1133 | 1344 | }; |
|
| 1134 | 1345 | let expr = eval(expr, env)?; |
|
| 1135 | - | env.binding(&name, None, expr); |
|
| 1346 | + | env.binding(name, None, expr); |
|
| 1136 | 1347 | ||
| 1137 | 1348 | Ok(Expr::nil()) |
|
| 1138 | 1349 | } |
|
| 1139 | 1350 | "fn" => { |
|
| 1140 | 1351 | let formals = items.next().ok_or(Error::ExpectedValue("vector"))?; |
| 1268 | 1479 | mod intrinsic { |
|
| 1269 | 1480 | use super::*; |
|
| 1270 | 1481 | ||
| 1271 | 1482 | /// Raise an error. |
|
| 1272 | 1483 | pub fn error(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1273 | - | let arity = args.len(); |
|
| 1274 | - | let err = args.into_iter().next().ok_or(Error::WrongArgumentCount { |
|
| 1275 | - | expected: 1, |
|
| 1276 | - | actual: arity, |
|
| 1277 | - | })?; |
|
| 1484 | + | let (err,) = <(Expr,)>::try_from_args(args)?; |
|
| 1278 | 1485 | Err(Error::User(err)) |
|
| 1279 | 1486 | } |
|
| 1280 | 1487 | ||
| 1281 | 1488 | /// Get the docstring for a symbol. |
|
| 1282 | 1489 | pub fn doc(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1283 | - | let arity = args.len(); |
|
| 1284 | - | let Ok([expr]) = <[_; 1]>::try_from(args) else { |
|
| 1285 | - | return Err(Error::WrongArgumentCount { |
|
| 1286 | - | expected: 1, |
|
| 1287 | - | actual: arity, |
|
| 1288 | - | }); |
|
| 1289 | - | }; |
|
| 1290 | - | ||
| 1291 | - | let Expr::Symbol(name) = expr else { |
|
| 1292 | - | return Err(Error::ExpectedValue("symbol")); |
|
| 1293 | - | }; |
|
| 1294 | - | ||
| 1490 | + | let (name,) = <(Symbol,)>::try_from_args(args)?; |
|
| 1295 | 1491 | Ok(env |
|
| 1296 | 1492 | .lookup_doc(&name) |
|
| 1297 | 1493 | .map(|s| Expr::Str(s.to_string())) |
|
| 1298 | 1494 | .unwrap_or(Expr::nil())) |
|
| 1299 | 1495 | } |
| 1304 | 1500 | return Err(Error::WrongArgumentCount { |
|
| 1305 | 1501 | expected: 0, |
|
| 1306 | 1502 | actual: args.len(), |
|
| 1307 | 1503 | }); |
|
| 1308 | 1504 | } |
|
| 1309 | - | let dict = env.flatten().into_iter().map(|(k, v)| (Key::Atom(k), v)).collect(); |
|
| 1505 | + | let dict = env |
|
| 1506 | + | .flatten() |
|
| 1507 | + | .into_iter() |
|
| 1508 | + | .map(|(k, v)| (Key::Atom(k.0.clone()), v)) |
|
| 1509 | + | .collect(); |
|
| 1310 | 1510 | ||
| 1311 | 1511 | Ok(Expr::Dict(dict)) |
|
| 1312 | 1512 | } |
|
| 1313 | 1513 | ||
| 1314 | 1514 | /// Get the first item of a list. |
|
| 1315 | 1515 | pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1316 | - | let arity = args.len(); |
|
| 1317 | - | let Ok([expr]) = <[_; 1]>::try_from(args) else { |
|
| 1318 | - | return Err(Error::WrongArgumentCount { |
|
| 1319 | - | expected: 1, |
|
| 1320 | - | actual: arity, |
|
| 1321 | - | }); |
|
| 1322 | - | }; |
|
| 1323 | - | if let Expr::List(l) = expr { |
|
| 1324 | - | return Ok(l.head().cloned().unwrap_or(Expr::nil())); |
|
| 1325 | - | } |
|
| 1326 | - | if let Expr::Vector(v) = expr { |
|
| 1327 | - | return Ok(v.into_iter().next().unwrap_or(Expr::nil())); |
|
| 1516 | + | let (expr,) = <(Expr,)>::try_from_args(args)?; |
|
| 1517 | + | match expr { |
|
| 1518 | + | Expr::List(l) => Ok(l.head().cloned().unwrap_or(Expr::nil())), |
|
| 1519 | + | Expr::Vector(v) => Ok(v.into_iter().next().unwrap_or(Expr::nil())), |
|
| 1520 | + | _ => Err(Error::ExpectedValue("list or vector")), |
|
| 1328 | 1521 | } |
|
| 1329 | - | Err(Error::ExpectedValue("list")) |
|
| 1330 | 1522 | } |
|
| 1331 | 1523 | ||
| 1332 | 1524 | /// Get the last item of a vector. |
|
| 1333 | 1525 | pub fn last(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1334 | - | if args.len() != 1 { |
|
| 1335 | - | return Err(Error::WrongArgumentCount { |
|
| 1336 | - | expected: 1, |
|
| 1337 | - | actual: args.len(), |
|
| 1338 | - | }); |
|
| 1339 | - | } |
|
| 1340 | - | if let Some(Expr::Vector(l)) = args.into_iter().next() { |
|
| 1341 | - | return Ok(l.into_iter().next_back().unwrap_or(Expr::nil())); |
|
| 1342 | - | } |
|
| 1343 | - | Err(Error::ExpectedValue("vector")) |
|
| 1526 | + | let (v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1527 | + | Ok(v.into_iter().next_back().unwrap_or(Expr::nil())) |
|
| 1344 | 1528 | } |
|
| 1345 | 1529 | ||
| 1346 | 1530 | /// Get the nth item of a vector. |
|
| 1347 | 1531 | pub fn nth(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1348 | - | if args.len() != 2 { |
|
| 1349 | - | return Err(Error::WrongArgumentCount { |
|
| 1350 | - | expected: 2, |
|
| 1351 | - | actual: args.len(), |
|
| 1352 | - | }); |
|
| 1353 | - | } |
|
| 1354 | - | let mut args = args.into_iter(); |
|
| 1355 | - | let Some(Expr::Vector(l)) = args.next() else { |
|
| 1356 | - | return Err(Error::ExpectedValue("vector")); |
|
| 1357 | - | }; |
|
| 1358 | - | let Some(Expr::Integer(idx)) = args.next() else { |
|
| 1359 | - | return Err(Error::ExpectedValue("integer")); |
|
| 1360 | - | }; |
|
| 1361 | - | Ok(l.into_iter().nth(idx as usize).unwrap_or(Expr::nil())) |
|
| 1532 | + | let (vec, idx) = <(Vec<Expr>, i64)>::try_from_args(args)?; |
|
| 1533 | + | Ok(vec.into_iter().nth(idx as usize).unwrap_or(Expr::nil())) |
|
| 1362 | 1534 | } |
|
| 1363 | 1535 | ||
| 1364 | 1536 | /// Map function. |
|
| 1365 | 1537 | pub fn map(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1366 | - | if args.len() != 2 { |
|
| 1367 | - | return Err(Error::WrongArgumentCount { |
|
| 1368 | - | expected: 2, |
|
| 1369 | - | actual: args.len(), |
|
| 1370 | - | }); |
|
| 1371 | - | } |
|
| 1372 | - | let mut args = args.into_iter(); |
|
| 1373 | - | let Some(Expr::Function(f)) = args.next() else { |
|
| 1374 | - | return Err(Error::ExpectedValue("function")); |
|
| 1375 | - | }; |
|
| 1538 | + | let (f, collection) = <(Function, Expr)>::try_from_args(args)?; |
|
| 1376 | 1539 | let mut env = Env::from_parent(env); |
|
| 1377 | 1540 | ||
| 1378 | - | match args.next() { |
|
| 1379 | - | Some(Expr::List(l)) => l |
|
| 1541 | + | match collection { |
|
| 1542 | + | Expr::List(l) => l |
|
| 1380 | 1543 | .iter() |
|
| 1381 | 1544 | .cloned() |
|
| 1382 | 1545 | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1383 | 1546 | .collect::<Result<Vec<_>>>() |
|
| 1384 | 1547 | .map(List::from) |
|
| 1385 | 1548 | .map(Expr::List), |
|
| 1386 | - | Some(Expr::Vector(l)) => l |
|
| 1549 | + | Expr::Vector(l) => l |
|
| 1387 | 1550 | .into_iter() |
|
| 1388 | 1551 | .map(|i| f.apply([i].into_iter(), &mut env)) |
|
| 1389 | 1552 | .collect::<Result<Vec<_>>>() |
|
| 1390 | 1553 | .map(Expr::Vector), |
|
| 1391 | 1554 | _ => Err(Error::ExpectedValue("list or vector")), |
|
| 1392 | 1555 | } |
|
| 1393 | 1556 | } |
|
| 1394 | 1557 | ||
| 1395 | 1558 | /// Return the length of a value. |
|
| 1396 | 1559 | pub fn length(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1397 | - | let arity = args.len(); |
|
| 1398 | - | let Ok([value]) = <[_; 1]>::try_from(args) else { |
|
| 1399 | - | return Err(Error::WrongArgumentCount { |
|
| 1400 | - | expected: 1, |
|
| 1401 | - | actual: arity, |
|
| 1402 | - | }); |
|
| 1403 | - | }; |
|
| 1404 | - | ||
| 1560 | + | let (value,) = <(Expr,)>::try_from_args(args)?; |
|
| 1405 | 1561 | let length = match value { |
|
| 1406 | 1562 | Expr::Vector(l) => l.len(), |
|
| 1407 | 1563 | Expr::List(l) => l.len(), |
|
| 1408 | 1564 | Expr::Dict(d) => d.len(), |
|
| 1409 | 1565 | Expr::Str(s) => s.chars().count(), |
| 1414 | 1570 | ))) |
|
| 1415 | 1571 | } |
|
| 1416 | 1572 | ||
| 1417 | 1573 | /// Check if the collection is empty. |
|
| 1418 | 1574 | pub fn empty(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1419 | - | let arity = args.len(); |
|
| 1420 | - | let Ok([expr]) = <[_; 1]>::try_from(args) else { |
|
| 1421 | - | return Err(Error::WrongArgumentCount { |
|
| 1422 | - | expected: 1, |
|
| 1423 | - | actual: arity, |
|
| 1424 | - | }); |
|
| 1425 | - | }; |
|
| 1426 | - | ||
| 1575 | + | let (expr,) = <(Expr,)>::try_from_args(args)?; |
|
| 1427 | 1576 | let is_empty = match expr { |
|
| 1428 | 1577 | Expr::Vector(l) => l.is_empty(), |
|
| 1429 | 1578 | Expr::List(l) => l.is_empty(), |
|
| 1430 | 1579 | Expr::Str(s) => s.is_empty(), |
|
| 1431 | 1580 | Expr::Dict(d) => d.is_empty(), |
| 1551 | 1700 | /// Push elements to the front of a list. |
|
| 1552 | 1701 | pub fn cons(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1553 | 1702 | if args.is_empty() { |
|
| 1554 | 1703 | return Ok(Expr::nil()); |
|
| 1555 | 1704 | } |
|
| 1556 | - | if args.len() != 2 { |
|
| 1557 | - | return Err(Error::WrongArgumentCount { |
|
| 1558 | - | expected: 2, |
|
| 1559 | - | actual: args.len(), |
|
| 1560 | - | }); |
|
| 1561 | - | } |
|
| 1562 | - | let mut args = args.into_iter(); |
|
| 1563 | - | let Some(val) = args.next() else { |
|
| 1564 | - | return Err(Error::ExpectedValue("expr")); |
|
| 1565 | - | }; |
|
| 1566 | - | let Some(Expr::List(l)) = args.next() else { |
|
| 1567 | - | return Err(Error::ExpectedValue("list")); |
|
| 1568 | - | }; |
|
| 1705 | + | let (val, l) = <(Expr, List<Expr>)>::try_from_args(args)?; |
|
| 1706 | + | ||
| 1569 | 1707 | Ok(Expr::List(l.prepend(val))) |
|
| 1570 | 1708 | } |
|
| 1571 | 1709 | ||
| 1572 | 1710 | /// Reverse a vector. |
|
| 1573 | - | pub fn reverse(mut args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1574 | - | match args.pop() { |
|
| 1575 | - | Some(Expr::Vector(mut v)) => { |
|
| 1576 | - | v.reverse(); |
|
| 1577 | - | Ok(Expr::Vector(v)) |
|
| 1578 | - | } |
|
| 1579 | - | Some(_) => Err(Error::ExpectedValue("vector")), |
|
| 1580 | - | None => Err(Error::WrongArgumentCount { |
|
| 1581 | - | expected: 1, |
|
| 1582 | - | actual: args.len(), |
|
| 1583 | - | }), |
|
| 1584 | - | } |
|
| 1711 | + | pub fn reverse(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1712 | + | let (mut v,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1713 | + | v.reverse(); |
|
| 1714 | + | ||
| 1715 | + | Ok(Expr::Vector(v)) |
|
| 1585 | 1716 | } |
|
| 1586 | 1717 | ||
| 1587 | 1718 | /// Create a list of numbers in a specified range. |
|
| 1588 | 1719 | pub fn range(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1589 | 1720 | match args.as_slice() { |
| 1629 | 1760 | Ok(Expr::Bool(result)) |
|
| 1630 | 1761 | } |
|
| 1631 | 1762 | ||
| 1632 | 1763 | /// Not (!). |
|
| 1633 | 1764 | pub fn not(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1634 | - | if args.len() != 1 { |
|
| 1635 | - | return Err(Error::WrongArgumentCount { |
|
| 1636 | - | expected: 1, |
|
| 1637 | - | actual: args.len(), |
|
| 1638 | - | }); |
|
| 1639 | - | } |
|
| 1640 | - | let Some(Expr::Bool(b)) = args.into_iter().next() else { |
|
| 1641 | - | return Err(Error::ExpectedValue("bool")); |
|
| 1642 | - | }; |
|
| 1643 | - | Ok(Expr::Bool(!b)) |
|
| 1765 | + | <(bool,)>::try_from_args(args).map(|(b,)| Expr::Bool(!b)) |
|
| 1644 | 1766 | } |
|
| 1645 | 1767 | ||
| 1646 | 1768 | /// And (&&). |
|
| 1647 | 1769 | pub fn and(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1648 | 1770 | fold(args, true, |a, b| a && b) |
| 1801 | 1923 | } |
|
| 1802 | 1924 | } |
|
| 1803 | 1925 | ||
| 1804 | 1926 | /// Create a mutable reference. |
|
| 1805 | 1927 | pub fn create_ref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1806 | - | let arity = args.len(); |
|
| 1807 | - | let Ok([value]) = <[_; 1]>::try_from(args) else { |
|
| 1808 | - | return Err(Error::WrongArgumentCount { |
|
| 1809 | - | expected: 1, |
|
| 1810 | - | actual: arity, |
|
| 1811 | - | }); |
|
| 1812 | - | }; |
|
| 1813 | - | Ok(Expr::Ref(Rc::new(RefCell::new(value)))) |
|
| 1928 | + | <(Expr,)>::try_from_args(args).map(|(e,)| Expr::Ref(Rc::new(RefCell::new(e)))) |
|
| 1814 | 1929 | } |
|
| 1815 | 1930 | ||
| 1816 | 1931 | /// Dereference a mutable reference. |
|
| 1817 | 1932 | pub fn deref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1818 | - | let arity = args.len(); |
|
| 1819 | - | let Ok([value]) = <[_; 1]>::try_from(args) else { |
|
| 1820 | - | return Err(Error::WrongArgumentCount { |
|
| 1821 | - | expected: 1, |
|
| 1822 | - | actual: arity, |
|
| 1823 | - | }); |
|
| 1824 | - | }; |
|
| 1825 | - | match value { |
|
| 1826 | - | Expr::Ref(r) => Ok(r.borrow().clone()), |
|
| 1827 | - | _ => Err(Error::ExpectedValue("ref")), |
|
| 1828 | - | } |
|
| 1933 | + | <(Rc<RefCell<Expr>>,)>::try_from_args(args).map(|(r,)| RefCell::borrow(&r).clone()) |
|
| 1829 | 1934 | } |
|
| 1830 | 1935 | ||
| 1831 | 1936 | /// Set the value of a mutable reference. |
|
| 1832 | 1937 | pub fn set_ref(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1833 | - | let arity = args.len(); |
|
| 1834 | - | let Ok([r, v]) = <[_; 2]>::try_from(args) else { |
|
| 1835 | - | return Err(Error::WrongArgumentCount { |
|
| 1836 | - | expected: 2, |
|
| 1837 | - | actual: arity, |
|
| 1838 | - | }); |
|
| 1839 | - | }; |
|
| 1840 | - | match r { |
|
| 1841 | - | Expr::Ref(r) => { |
|
| 1842 | - | *r.borrow_mut() = v; |
|
| 1843 | - | Ok(Expr::nil()) |
|
| 1844 | - | } |
|
| 1845 | - | _ => Err(Error::ExpectedValue("ref")), |
|
| 1846 | - | } |
|
| 1938 | + | let (r, v) = <(Rc<RefCell<Expr>>, Expr)>::try_from_args(args)?; |
|
| 1939 | + | *r.borrow_mut() = v; |
|
| 1940 | + | Ok(Expr::nil()) |
|
| 1847 | 1941 | } |
|
| 1848 | 1942 | ||
| 1849 | 1943 | /// Modify a mutable reference in-place using a lambda. |
|
| 1850 | 1944 | pub fn modify(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> { |
|
| 1851 | - | let arity = args.len(); |
|
| 1852 | - | let Ok([r, f]) = <[_; 2]>::try_from(args) else { |
|
| 1853 | - | return Err(Error::WrongArgumentCount { |
|
| 1854 | - | expected: 2, |
|
| 1855 | - | actual: arity, |
|
| 1856 | - | }); |
|
| 1857 | - | }; |
|
| 1945 | + | let (r, f) = <(Rc<RefCell<Expr>>, Function)>::try_from_args(args)?; |
|
| 1858 | 1946 | let mut env = Env::from_parent(env); |
|
| 1947 | + | let mut old = r.borrow_mut(); |
|
| 1948 | + | let new = f.apply([old.clone()].into_iter(), &mut env)?; |
|
| 1859 | 1949 | ||
| 1860 | - | match (r, f) { |
|
| 1861 | - | (Expr::Ref(r), Expr::Function(f)) => { |
|
| 1862 | - | let mut old = r.borrow_mut(); |
|
| 1863 | - | let new = f.apply([old.clone()].into_iter(), &mut env)?; |
|
| 1950 | + | *old = new; |
|
| 1864 | 1951 | ||
| 1865 | - | *old = new; |
|
| 1952 | + | Ok(Expr::nil()) |
|
| 1953 | + | } |
|
| 1866 | 1954 | ||
| 1867 | - | Ok(Expr::nil()) |
|
| 1868 | - | } |
|
| 1869 | - | (_, _) => Err(Error::ExpectedValue("ref and function")), |
|
| 1870 | - | } |
|
| 1955 | + | /// Create a 2D vector. |
|
| 1956 | + | pub fn vec2(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1957 | + | let (x, y) = <(f64, f64)>::try_from_args(args)?; |
|
| 1958 | + | Ok(Expr::Vector2D(Vector2D::new(x, y))) |
|
| 1959 | + | } |
|
| 1960 | + | ||
| 1961 | + | /// Create a 3D vector. |
|
| 1962 | + | pub fn vec3(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1963 | + | let (x, y, z) = <(f64, f64, f64)>::try_from_args(args)?; |
|
| 1964 | + | Ok(Expr::Vector3D(Vector3D::new(x, y, z))) |
|
| 1965 | + | } |
|
| 1966 | + | ||
| 1967 | + | /// Create a 4D vector. |
|
| 1968 | + | pub fn vec4(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1969 | + | let (x, y, z, w) = <(f64, f64, f64, f64)>::try_from_args(args)?; |
|
| 1970 | + | Ok(Expr::Vector4D(Vector4D::new(x, y, z, w))) |
|
| 1871 | 1971 | } |
|
| 1872 | 1972 | ||
| 1873 | 1973 | fn fold<T: TryFrom<Expr, Error = Expr> + Into<Expr>>( |
|
| 1874 | 1974 | args: impl IntoIterator<Item = Expr>, |
|
| 1875 | 1975 | init: T, |
| 1884 | 1984 | fn binop<T>( |
|
| 1885 | 1985 | args: Vec<Expr>, |
|
| 1886 | 1986 | op: impl Fn(i64, i64) -> T, |
|
| 1887 | 1987 | opf: impl Fn(f64, f64) -> T, |
|
| 1888 | 1988 | ) -> Result<T> { |
|
| 1889 | - | if args.is_empty() { |
|
| 1890 | - | return Err(Error::WrongArgumentCount { |
|
| 1891 | - | expected: 2, |
|
| 1892 | - | actual: 0, |
|
| 1893 | - | }); |
|
| 1894 | - | } |
|
| 1895 | - | let mut args = args.into_iter(); |
|
| 1896 | - | match args.next() { |
|
| 1897 | - | Some(Expr::Integer(a)) => { |
|
| 1898 | - | let Some(Expr::Integer(b)) = args.next() else { |
|
| 1899 | - | return Err(Error::ExpectedValue("integer")); |
|
| 1900 | - | }; |
|
| 1901 | - | Ok(op(a, b)) |
|
| 1902 | - | } |
|
| 1903 | - | Some(Expr::Float(a)) => { |
|
| 1904 | - | let Some(Expr::Float(b)) = args.next() else { |
|
| 1905 | - | return Err(Error::ExpectedValue("float")); |
|
| 1906 | - | }; |
|
| 1907 | - | Ok(opf(a, b)) |
|
| 1908 | - | } |
|
| 1989 | + | let (l, r) = <(Expr, Expr)>::try_from_args(args)?; |
|
| 1990 | + | match (l, r) { |
|
| 1991 | + | (Expr::Integer(a), Expr::Integer(b)) => Ok(op(a, b)), |
|
| 1992 | + | (Expr::Float(a), Expr::Float(b)) => Ok(opf(a, b)), |
|
| 1909 | 1993 | _ => Err(Error::ExpectedValue("number")), |
|
| 1910 | 1994 | } |
|
| 1911 | 1995 | } |
|
| 1912 | - | ||
| 1913 | - | /// Create a 2D vector. |
|
| 1914 | - | pub fn vec2(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1915 | - | let arity = args.len(); |
|
| 1916 | - | let Ok([x, y]) = <[_; 2]>::try_from(args) else { |
|
| 1917 | - | return Err(Error::WrongArgumentCount { |
|
| 1918 | - | expected: 2, |
|
| 1919 | - | actual: arity, |
|
| 1920 | - | }); |
|
| 1921 | - | }; |
|
| 1922 | - | let x = match x { |
|
| 1923 | - | Expr::Float(n) => n, |
|
| 1924 | - | Expr::Integer(n) => n as f64, |
|
| 1925 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1926 | - | }; |
|
| 1927 | - | let y = match y { |
|
| 1928 | - | Expr::Float(n) => n, |
|
| 1929 | - | Expr::Integer(n) => n as f64, |
|
| 1930 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1931 | - | }; |
|
| 1932 | - | Ok(Expr::Vector2D(Vector2D::new(x, y))) |
|
| 1933 | - | } |
|
| 1934 | - | ||
| 1935 | - | /// Create a 3D vector. |
|
| 1936 | - | pub fn vec3(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1937 | - | let arity = args.len(); |
|
| 1938 | - | let Ok([x, y, z]) = <[_; 3]>::try_from(args) else { |
|
| 1939 | - | return Err(Error::WrongArgumentCount { |
|
| 1940 | - | expected: 3, |
|
| 1941 | - | actual: arity, |
|
| 1942 | - | }); |
|
| 1943 | - | }; |
|
| 1944 | - | let x = match x { |
|
| 1945 | - | Expr::Float(n) => n, |
|
| 1946 | - | Expr::Integer(n) => n as f64, |
|
| 1947 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1948 | - | }; |
|
| 1949 | - | let y = match y { |
|
| 1950 | - | Expr::Float(n) => n, |
|
| 1951 | - | Expr::Integer(n) => n as f64, |
|
| 1952 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1953 | - | }; |
|
| 1954 | - | let z = match z { |
|
| 1955 | - | Expr::Float(n) => n, |
|
| 1956 | - | Expr::Integer(n) => n as f64, |
|
| 1957 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1958 | - | }; |
|
| 1959 | - | Ok(Expr::Vector3D(Vector3D::new(x, y, z))) |
|
| 1960 | - | } |
|
| 1961 | - | ||
| 1962 | - | /// Create a 4D vector. |
|
| 1963 | - | pub fn vec4(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1964 | - | let arity = args.len(); |
|
| 1965 | - | let Ok([x, y, z, w]) = <[_; 4]>::try_from(args) else { |
|
| 1966 | - | return Err(Error::WrongArgumentCount { |
|
| 1967 | - | expected: 4, |
|
| 1968 | - | actual: arity, |
|
| 1969 | - | }); |
|
| 1970 | - | }; |
|
| 1971 | - | let x = match x { |
|
| 1972 | - | Expr::Float(n) => n, |
|
| 1973 | - | Expr::Integer(n) => n as f64, |
|
| 1974 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1975 | - | }; |
|
| 1976 | - | let y = match y { |
|
| 1977 | - | Expr::Float(n) => n, |
|
| 1978 | - | Expr::Integer(n) => n as f64, |
|
| 1979 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1980 | - | }; |
|
| 1981 | - | let z = match z { |
|
| 1982 | - | Expr::Float(n) => n, |
|
| 1983 | - | Expr::Integer(n) => n as f64, |
|
| 1984 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1985 | - | }; |
|
| 1986 | - | let w = match w { |
|
| 1987 | - | Expr::Float(n) => n, |
|
| 1988 | - | Expr::Integer(n) => n as f64, |
|
| 1989 | - | _ => return Err(Error::ExpectedValue("number")), |
|
| 1990 | - | }; |
|
| 1991 | - | Ok(Expr::Vector4D(Vector4D::new(x, y, z, w))) |
|
| 1992 | - | } |
|
| 1993 | 1996 | } |
|
| 1994 | 1997 | ||
| 1995 | 1998 | #[cfg(test)] |
|
| 1996 | 1999 | #[allow(clippy::unwrap_used)] |
|
| 1997 | 2000 | mod tests { |
| 2324 | 2327 | ||
| 2325 | 2328 | #[test] |
|
| 2326 | 2329 | fn test_nth() { |
|
| 2327 | 2330 | expect(&["(nth [4 3 1] 1)"], Expr::Integer(3)); |
|
| 2328 | 2331 | expect(&["(nth [4 3 1] 0)"], Expr::Integer(4)); |
|
| 2329 | - | expect_err(&["(nth [4 3 1] 1.2)"], Error::ExpectedValue("integer")); |
|
| 2332 | + | expect_err( |
|
| 2333 | + | &["(nth [4 3 1] 1.2)"], |
|
| 2334 | + | Error::UnexpectedValue(Expr::Float(1.2)), |
|
| 2335 | + | ); |
|
| 2330 | 2336 | } |
|
| 2331 | 2337 | ||
| 2332 | 2338 | #[test] |
|
| 2333 | 2339 | fn test_do() { |
|
| 2334 | 2340 | expect(&["(do (local x 1) (local y 2) (+ x y))"], Expr::Integer(3)); |
| 2694 | 2700 | Error::WrongArgumentCount { |
|
| 2695 | 2701 | expected: 2, |
|
| 2696 | 2702 | actual: 1, |
|
| 2697 | 2703 | }, |
|
| 2698 | 2704 | ); |
|
| 2699 | - | expect_err(&["(vec2 :x 1)"], Error::ExpectedValue("number")); |
|
| 2705 | + | expect_err( |
|
| 2706 | + | &["(vec2 :x 1)"], |
|
| 2707 | + | Error::UnexpectedValue(Expr::Atom("x".into())), |
|
| 2708 | + | ); |
|
| 2700 | 2709 | } |
|
| 2701 | 2710 | ||
| 2702 | 2711 | #[test] |
|
| 2703 | 2712 | fn test_vector_math() { |
|
| 2704 | 2713 | expect(&["(- (vec2 1 2))"], Expr::Vector2D(Vector2D::new(-1., -2.))); |
ombre/src/lisp/parser.rs
+3 -2
| 1 | 1 | //! Parser. |
|
| 2 | 2 | use std::fmt; |
|
| 3 | 3 | use std::iter::Peekable; |
|
| 4 | + | use std::rc::Rc; |
|
| 4 | 5 | use std::result; |
|
| 5 | 6 | ||
| 6 | - | use crate::lisp::evaluator::Expr; |
|
| 7 | + | use crate::lisp::evaluator::{Expr, Symbol}; |
|
| 7 | 8 | use crate::lisp::scanner; |
|
| 8 | 9 | use crate::lisp::scanner::Token; |
|
| 9 | 10 | ||
| 10 | 11 | /// Result type for all functions. |
|
| 11 | 12 | pub type Result<T> = result::Result<T, Error>; |
| 76 | 77 | Token::LBracket => self.parse_vector()?, |
|
| 77 | 78 | Token::RBracket => return Err(Error::UnexpectedToken(token.owned())), |
|
| 78 | 79 | Token::Quote => self.parse_quoted()?, |
|
| 79 | 80 | Token::Symbol(s) => { |
|
| 80 | 81 | self.tokens.next(); |
|
| 81 | - | Expr::Symbol(s.into()) |
|
| 82 | + | Expr::Symbol(Symbol::from(Rc::from(s))) |
|
| 82 | 83 | } |
|
| 83 | 84 | Token::Atom(s) => { |
|
| 84 | 85 | self.tokens.next(); |
|
| 85 | 86 | Expr::Atom(s.into()) |
|
| 86 | 87 | } |