ombre: Some additions to lisp evaluator

b9f7c9d442fd58943cf06066591d6dfa23fb0e3a
Alexis Sellier committed ago 1 parent e6126efd
ombre/src/lisp/evaluator.rs +56 -22
6 6
use std::rc::Rc;
7 7
use std::{collections::HashMap, iter::Peekable};
8 8
use std::{fmt, fs, iter, result};
9 9
10 10
use crate::gfx::Rgba8;
11 -
12 -
use crate::lisp::dynamic::Dynamic;
11 +
use crate::lisp::dynamic::{Dynamic, IsDynamic};
13 12
use crate::lisp::list::List;
14 13
15 14
use super::{Parser, Scanner, FILE_EXTENSION};
16 15
17 16
/// Result type for all functions.
64 63
            Error::User(e) => write!(f, "user error: {e:?}"),
65 64
        }
66 65
    }
67 66
}
68 67
68 +
impl std::error::Error for Error {}
69 +
69 70
/// A symbol is an immutable string.
70 71
pub type Symbol = Rc<str>;
71 72
72 73
/// Values that can be used as dictionary keys.
73 74
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
214 215
215 216
    /// Quote an expression.
216 217
    pub fn quoted(self) -> Self {
217 218
        Expr::Quoted(Box::new(self))
218 219
    }
220 +
221 +
    /// Create a [`Dynamic`] expression.
222 +
    pub fn dynamic<T: IsDynamic>(value: T) -> Self {
223 +
        Self::Dynamic(Dynamic::new(value))
224 +
    }
219 225
}
220 226
221 227
impl From<f64> for Expr {
222 228
    fn from(value: f64) -> Self {
223 229
        Expr::Float(value)
224 230
    }
225 231
}
226 232
233 +
impl From<f32> for Expr {
234 +
    fn from(value: f32) -> Self {
235 +
        Expr::Float(value as f64)
236 +
    }
237 +
}
238 +
227 239
impl From<i64> for Expr {
228 240
    fn from(value: i64) -> Self {
229 241
        Expr::Integer(value)
230 242
    }
231 243
}
246 258
    fn from(value: Closure) -> Self {
247 259
        Expr::Function(Function::Closure(Rc::new(value)))
248 260
    }
249 261
}
250 262
263 +
impl TryFrom<Expr> for f32 {
264 +
    type Error = Expr;
265 +
266 +
    fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> {
267 +
        match expr {
268 +
            Expr::Float(n) => Ok(n as f32),
269 +
            Expr::Integer(n) => Ok(n as f32),
270 +
            _ => Err(expr),
271 +
        }
272 +
    }
273 +
}
274 +
251 275
impl TryFrom<Expr> for f64 {
252 276
    type Error = Expr;
253 277
254 278
    fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> {
255 279
        match expr {
256 280
            Expr::Float(n) => Ok(n),
281 +
            Expr::Integer(n) => Ok(n as f64),
257 282
            _ => Err(expr),
258 283
        }
259 284
    }
260 285
}
261 286
472 497
        };
473 498
        eval_iter(self.body.clone(), &mut env)
474 499
    }
475 500
}
476 501
502 +
/// A natively implemented function.
503 +
pub type IntrinsicFn = fn(Vec<Expr>, &Env<'_>) -> Result<Expr>;
504 +
477 505
/// Built-in function intrinsic to the language.
478 506
pub struct Intrinsic(Rc<dyn Fn(Vec<Expr>, &Env<'_>) -> Result<Expr>>);
479 507
480 508
impl PartialEq for Intrinsic {
481 509
    fn eq(&self, other: &Self) -> bool {
512 540
}
513 541
514 542
impl<'a> Env<'a> {
515 543
    /// Add intrinsics to this evaluator. Returns a new evaluator with the specified
516 544
    /// intrinsics.
517 -
    pub fn intrinsics<'b, 'c, F>(
545 +
    pub fn with_intrinsics<'b, 'c>(
518 546
        mut self,
519 -
        fns: impl IntoIterator<Item = (&'b str, &'c str, F)>,
520 -
    ) -> Self
521 -
    where
522 -
        F: Fn(Vec<Expr>, &Env<'_>) -> Result<Expr> + 'static,
523 -
    {
547 +
        fns: impl IntoIterator<Item = (&'b str, &'c str, IntrinsicFn)>,
548 +
    ) -> Self {
524 549
        for (name, docs, f) in fns.into_iter() {
525 550
            self.intrinsic(name, docs, f);
526 551
        }
527 552
        self
528 553
    }
529 554
555 +
    /// Define a binding and return a new evaluator.
556 +
    pub fn with_binding(mut self, name: &str, docstr: Option<&str>, expr: Expr) -> Self {
557 +
        self.binding(name, docstr, expr);
558 +
        self
559 +
    }
560 +
530 561
    /// Lookup a symbol.
531 562
    pub fn lookup(&self, name: &str) -> Option<&Expr> {
532 563
        if let Some(expr) = self.local.get(name) {
533 564
            return Some(expr);
534 565
        }
796 827
{
797 828
    /// Create a new evaluator.
798 829
    pub fn new(exprs: T) -> Self {
799 830
        Self {
800 831
            modules: ModuleRegistry::default(),
801 -
            exprs: exprs.into_iter().peekable(),
832 +
            exprs: exprs.peekable(),
802 833
        }
803 834
    }
804 835
805 836
    /// Evaluate expressions one by one and return the result of the last one.
806 837
    pub fn eval(mut self, env: &mut Env<'_>) -> Result<Expr, Error> {
2332 2363
    #[test]
2333 2364
    fn test_foreign_function() {
2334 2365
        let input = "(rust-reverse \"alice\")";
2335 2366
        let tokens = Scanner::new(input);
2336 2367
        let parser = Parser::new(tokens);
2337 -
        let mut env = Env::default().intrinsics([(
2368 +
2369 +
        fn intrinsic(args: Vec<Expr>, _: &Env<'_>) -> Result<Expr> {
2370 +
            if args.len() != 1 {
2371 +
                return Err(Error::WrongArgumentCount {
2372 +
                    expected: 1,
2373 +
                    actual: args.len(),
2374 +
                });
2375 +
            }
2376 +
            match &args[0] {
2377 +
                Expr::Str(s) => Ok(Expr::Str(s.chars().rev().collect())),
2378 +
                _ => Err(Error::ExpectedValue("string")),
2379 +
            }
2380 +
        }
2381 +
2382 +
        let mut env = Env::default().with_intrinsics([(
2338 2383
            "rust-reverse",
2339 2384
            "Reverse a string",
2340 -
            |args: Vec<Expr>, _: &Env<'_>| {
2341 -
                if args.len() != 1 {
2342 -
                    return Err(Error::WrongArgumentCount {
2343 -
                        expected: 1,
2344 -
                        actual: args.len(),
2345 -
                    });
2346 -
                }
2347 -
                match &args[0] {
2348 -
                    Expr::Str(s) => Ok(Expr::Str(s.chars().rev().collect())),
2349 -
                    _ => Err(Error::ExpectedValue("string")),
2350 -
                }
2351 -
            },
2385 +
            intrinsic as IntrinsicFn,
2352 2386
        )]);
2353 2387
2354 2388
        let result = Evaluator::new(parser).eval(&mut env).unwrap();
2355 2389
        assert_eq!(result, Expr::Str("ecila".to_owned()));
2356 2390
    }