summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 49c916a90be7d1c1a7fccfe19e67e3d67e1f6ea9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#[cfg(test)]
pub mod tests;

pub mod lib;

use rustyline::error::ReadlineError;
use rustyline::Editor;

use lib::environment::Environment;

fn read<T: rustyline::Helper>(rl: &mut Editor<T>) -> Option<String> {
    let readline = rl.readline(">> ");
    match readline {
        Ok(line) => {
            rl.add_history_entry(line.as_str());
            Some(line)
        },
        Err(ReadlineError::Interrupted) => {
            println!("CTRL-C");
            None
        },
        Err(ReadlineError::Eof) => {
            println!("CTRL-D");
            None
        },
        Err(err) => {
            println!("Error: {:?}", err);
            None
        }
    }
}

fn means_exit(input: &str) -> bool {
    match input {
        "exit" | "quit" | ",q" => true,
        _ => false
    }
}

fn eval(env: &mut Environment, input: &str) -> String {
    let sexp = match lib::parse::parse(input) {
        Ok(x) => x,
        Err(f) => return f
    };

    let res = lib::eval::eval(&sexp, env);
    match res {
        Ok(x) => format!("{:?}", x),
        Err(f) => f
    }
}

fn main() {
    let mut env = Environment::new();
    let hist_file = "history.txt";

    // `()` can be used when no completer is required
    let mut rl = Editor::<()>::new();
    if rl.load_history(hist_file).is_err() {
        println!("No previous history.");
    }
    loop {
        let input_line = read(&mut rl);
        let line = match input_line {
            None => break,
            Some(expr) if means_exit(&expr) => break,
            Some(expr) => expr
        };
        println!("{}", eval(&mut env, &line));
    }
    rl.save_history(hist_file).unwrap();
}