ombre: Add REPL for lisp

2040ff04a6775a8ef0ea39ab3931a0cb4b662aff
Alexis Sellier committed ago 1 parent b8116e96
ombre/src/bin/repl.rs added +38 -0
1 +
use std::io::{self, Write};
2 +
3 +
use ombre::lisp::*;
4 +
5 +
pub fn run() -> io::Result<()> {
6 +
    let mut env = Env::default();
7 +
    let mut stdout = io::stdout().lock();
8 +
    let stdin = io::stdin();
9 +
    let mut input = String::new();
10 +
11 +
    loop {
12 +
        stdout.write_all(b"> ")?;
13 +
        stdout.flush()?;
14 +
        input.clear();
15 +
16 +
        if stdin.read_line(&mut input)? == 0 {
17 +
            // Ctrl-D.
18 +
            eprintln!();
19 +
            break;
20 +
        }
21 +
        match Parser::new(Scanner::new(&input)).next() {
22 +
            Some(Ok(expr)) => {
23 +
                match Evaluator::new([Ok::<_, parser::Error>(expr)].into_iter()).eval(&mut env) {
24 +
                    Ok(result) => println!("{result}"),
25 +
                    Err(e) => eprintln!("Error: {e}"),
26 +
                }
27 +
            }
28 +
            Some(Err(e)) => eprintln!("Error: {e}"),
29 +
            None => continue, // Empty input.
30 +
        }
31 +
    }
32 +
    Ok(())
33 +
}
34 +
35 +
fn main() -> io::Result<()> {
36 +
    println!("Ombre REPL (Ctrl-D to exit)");
37 +
    run()
38 +
}
ombre/src/lisp.rs +3 -0
18 18
19 19
pub use evaluator::{Env, Evaluator, Expr};
20 20
pub use parser::Parser;
21 21
pub use scanner::Scanner;
22 22
23 +
/// File extension for language files.
24 +
pub const FILE_EXTENSION: &str = "scm";
25 +
23 26
/// Build a syntax tree from the input string.
24 27
pub fn parse(input: &str) -> impl Iterator<Item = parser::Result<Expr>> + '_ {
25 28
    Parser::new(Scanner::new(input))
26 29
}
27 30
ombre/src/lisp/dynamic.rs +5 -0
13 13
    /// Create a new dynamic object.
14 14
    pub fn new<T: IsDynamic>(value: T) -> Self {
15 15
        Self(Rc::new(value))
16 16
    }
17 17
18 +
    /// Get the pointer to the internal object.
19 +
    pub fn as_ptr(&self) -> *const Dynamic {
20 +
        Rc::as_ptr(&self.0) as *const Dynamic
21 +
    }
22 +
18 23
    /// Try to cast to a concrete type.
19 24
    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
20 25
        self.0.as_any().downcast_ref()
21 26
    }
22 27
ombre/src/lisp/evaluator.rs +104 -7
1 1
//! Expression evaluator.
2 2
use std::cell::RefCell;
3 3
use std::collections::HashSet;
4 -
use std::fmt;
5 4
use std::ops::{Deref, DerefMut};
5 +
use std::path::PathBuf;
6 6
use std::rc::Rc;
7 -
use std::result;
8 7
use std::{collections::HashMap, iter::Peekable};
8 +
use std::{fmt, fs, iter, result};
9 9
10 10
use crate::gfx::Rgba8;
11 11
12 12
use crate::lisp::dynamic::Dynamic;
13 13
use crate::lisp::list::List;
14 14
15 +
use super::{Parser, Scanner, FILE_EXTENSION};
16 +
15 17
/// Result type for all functions.
16 18
pub type Result<T, E = Error> = result::Result<T, E>;
17 19
18 20
/// Evaluation error.
19 21
#[derive(Debug)]
54 56
            Error::ExpectedValue(s) => write!(f, "expected value: {s}"),
55 57
            Error::ExpectedNamedValue(s) => write!(f, "expected named value: {s}"),
56 58
            Error::UnexpectedValue(e) => write!(f, "unexpected value: {e:?}"),
57 59
            Error::UnexpectedNamedArgument(s) => write!(f, "unexpected named argument: {s}"),
58 60
            Error::WrongArgumentCount { expected, actual } => {
59 -
                write!(f, "expected {expected} arguments, got {actual}")
61 +
                write!(f, "expected {expected} argument(s), got {actual}")
60 62
            }
61 63
            Error::InvalidArgument => write!(f, "invalid argument"),
62 64
            Error::User(e) => write!(f, "user error: {e:?}"),
63 65
        }
64 66
    }
110 112
}
111 113
112 114
/// The global module registry.
113 115
#[derive(Debug, Clone, PartialEq, Default)]
114 116
pub struct ModuleRegistry {
117 +
    /// Loaded modules.
115 118
    modules: HashMap<Symbol, Module>,
119 +
    /// Search paths for module files.
120 +
    paths: Vec<PathBuf>,
116 121
}
117 122
118 123
impl ModuleRegistry {
119 124
    /// Lookup a module in the registry.
120 125
    fn lookup(&self, name: &Symbol) -> Option<&Module> {
121 126
        self.modules.get(name)
122 127
    }
123 128
129 +
    /// Load a module from the file system.
130 +
    fn load(&mut self, name: &Symbol) -> Result<&Module, Error> {
131 +
        for path in iter::once(&PathBuf::from(".")).chain(&self.paths) {
132 +
            let path = path.join(&**name).with_extension(FILE_EXTENSION);
133 +
134 +
            if let Ok(content) = fs::read_to_string(path) {
135 +
                let mut env = Env::default();
136 +
                Evaluator::new(Parser::new(Scanner::new(&content))).eval(&mut env)?;
137 +
138 +
                return Ok(self.modules.entry(name.clone()).or_insert(Module {
139 +
                    name: name.clone(),
140 +
                    docstr: None,
141 +
                    env,
142 +
                }));
143 +
            }
144 +
        }
145 +
        Err(Error::ModuleNotFound(name.clone()))
146 +
    }
147 +
124 148
    /// Register a new module.
125 149
    fn register(&mut self, name: Symbol, module: Module) {
126 150
        self.modules.insert(name, module);
127 151
    }
128 152
}
255 279
            _ => Err(expr),
256 280
        }
257 281
    }
258 282
}
259 283
284 +
impl fmt::Display for Expr {
285 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 +
        match self {
287 +
            Expr::List(list) => {
288 +
                write!(f, "(")?;
289 +
                let mut iter = list.iter();
290 +
                if let Some(first) = iter.next() {
291 +
                    write!(f, "{first}")?;
292 +
                    for item in iter {
293 +
                        write!(f, " {item}")?;
294 +
                    }
295 +
                }
296 +
                write!(f, ")")
297 +
            }
298 +
            Expr::Bool(b) => write!(f, ":{b}"),
299 +
            Expr::Quoted(e) => write!(f, "'{e}"),
300 +
            Expr::Vector(v) => {
301 +
                write!(f, "[")?;
302 +
                let mut iter = v.iter();
303 +
                if let Some(first) = iter.next() {
304 +
                    write!(f, "{first}")?;
305 +
                    for item in iter {
306 +
                        write!(f, " {item}")?;
307 +
                    }
308 +
                }
309 +
                write!(f, "]")
310 +
            }
311 +
            Expr::Dict(d) => {
312 +
                write!(f, "{{")?;
313 +
                let mut iter = d.iter();
314 +
                if let Some((k, v)) = iter.next() {
315 +
                    write!(f, "{k} {v}")?;
316 +
                    for (k, v) in iter {
317 +
                        write!(f, ", {k} {v}")?;
318 +
                    }
319 +
                }
320 +
                write!(f, "}}")
321 +
            }
322 +
            Expr::Symbol(s) => write!(f, "{s}"),
323 +
            Expr::Atom(s) => write!(f, ":{s}"),
324 +
            Expr::Str(s) => write!(f, "\"{}\"", s.escape_debug()),
325 +
            Expr::Float(n) => write!(f, "{n}"),
326 +
            Expr::Integer(n) => write!(f, "{n}"),
327 +
            Expr::Char(c) => write!(f, "`{c}`"),
328 +
            Expr::Color(c) => write!(f, "#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a),
329 +
            Expr::Function(e) => write!(f, "<function {:p}>", e.as_ptr()),
330 +
            Expr::Ref(r) => write!(f, "<ref {}>", r.borrow()),
331 +
            Expr::Dynamic(d) => write!(f, "<dynamic {:p}>", d.as_ptr()),
332 +
        }
333 +
    }
334 +
}
335 +
336 +
impl fmt::Display for Key {
337 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 +
        match self {
339 +
            Key::Bool(b) => write!(f, ":{b}"),
340 +
            Key::Atom(s) => write!(f, ":{s}"),
341 +
            Key::Str(s) => write!(f, "\"{}\"", s.escape_debug()),
342 +
            Key::Integer(n) => write!(f, "{n}"),
343 +
            Key::Char(c) => write!(f, "`{c}`"),
344 +
            Key::Color(c) => write!(f, "#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a),
345 +
        }
346 +
    }
347 +
}
348 +
260 349
/// Built-in or user-defined function.
261 350
#[derive(Debug, Clone)]
262 351
pub enum Function {
263 352
    /// A function that closes over some environment.
264 353
    Closure(Rc<Closure>),
265 354
    /// A built-in function implemented natively.
266 355
    Intrinsic(Rc<Intrinsic>),
267 356
}
268 357
269 358
impl Function {
359 +
    /// Get the pointer to the internal object.
360 +
    fn as_ptr(&self) -> *const () {
361 +
        match self {
362 +
            Self::Closure(f) => Rc::as_ptr(f) as *const (),
363 +
            Self::Intrinsic(f) => Rc::as_ptr(f) as *const (),
364 +
        }
365 +
    }
366 +
270 367
    /// Apply the function.
271 368
    fn apply(&self, args: impl Iterator<Item = Expr>, env: &mut Env<'_>) -> Result<Expr> {
272 369
        let args = args.map(|a| eval(a, env)).collect::<Result<Vec<_>>>()?;
273 370
274 371
        match self {
781 878
        "import" => {
782 879
            let mut items = tail.iter().cloned();
783 880
            let Some(Expr::Symbol(name)) = items.next() else {
784 881
                return Err(Error::ExpectedValue("symbol"));
785 882
            };
786 -
            let module = mods
787 -
                .lookup(&name)
788 -
                .ok_or_else(|| Error::ModuleNotFound(name.clone()))?;
789 -
883 +
            let module = match mods.lookup(&name) {
884 +
                Some(m) => m,
885 +
                None => mods.load(&name)?,
886 +
            };
790 887
            env.import(module);
791 888
792 889
            Ok(Expr::nil())
793 890
        }
794 891
        "export" => {