aboutsummaryrefslogtreecommitdiff
path: root/src/lisp/prelude.rs
blob: 6153e4faf35c9a41d1346d5e6c249e4f09cc0d69 (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use crate::{
    lisp::{
        error::{EvalError, LispError},
        expr::{Arity, LispExpr},
        number::LispNumber,
        Environment,
    },
    primitive,
};

use std::{convert::TryInto, fs::File, io::Write, path::PathBuf};

use log::info;

#[macro_export]
macro_rules! primitive {
    ($env:expr, $arity:expr, $name:expr, $closure:expr) => {
        let val = crate::lisp::expr::LispExpr::PrimitiveFunc(crate::lisp::expr::PrimitiveFunc {
            arity: $arity,
            closure: $closure,
        });
        let _ = $env.insert($name.to_string(), val);
    };
}

pub fn new_env() -> Environment {
    let mut env = Environment::new();

    primitive!(env, Arity::Atleast(2), "+", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        return Ok(LispExpr::Number(
            nums.iter().fold(LispNumber::Integer(0), |acc, &x| acc + *x),
        ));
    });

    primitive!(env, Arity::Atleast(2), "-", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let mut acc = nums[0].clone();
        for arg in nums.into_iter().skip(1) {
            acc = acc - *arg;
        }
        Ok(LispExpr::Number(acc))
    });

    primitive!(env, Arity::Atleast(2), "*", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        return Ok(LispExpr::Number(
            nums.iter().fold(LispNumber::Integer(1), |acc, &x| acc * *x),
        ));
    });

    primitive!(env, Arity::Atleast(2), "/", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let mut acc = nums[0].clone();
        for arg in nums.into_iter().skip(1) {
            acc = acc.div(*arg)?;
        }
        Ok(LispExpr::Number(acc))
    });

    primitive!(env, Arity::Exact(0), "toggle-grid", |_, app| {
        app.toggle_grid();
        Ok(LispExpr::Unit)
    });

    primitive!(env, Arity::Atleast(2), "and", |args, _| {
        if args
            .iter()
            .any(|arg| matches!(arg, LispExpr::BoolLit(false)))
        {
            Ok(LispExpr::BoolLit(false))
        } else {
            Ok(LispExpr::BoolLit(true))
        }
    });

    primitive!(env, Arity::Atleast(2), "or", |args, _| {
        if args
            .iter()
            .any(|arg| matches!(arg, LispExpr::BoolLit(true)))
        {
            Ok(LispExpr::BoolLit(true))
        } else {
            Ok(LispExpr::BoolLit(false))
        }
    });

    primitive!(env, Arity::Exact(1), "not", |args, _| {
        if matches!(&args[0], LispExpr::BoolLit(false)) {
            Ok(LispExpr::BoolLit(true))
        } else {
            Ok(LispExpr::BoolLit(false))
        }
    });

    primitive!(env, Arity::Atleast(1), "begin", |args, _| {
        if args.is_empty() {
            Err(EvalError::ArgumentCount(Arity::Atleast(1)).into())
        } else {
            Ok(args.into_iter().last().unwrap().clone())
        }
    });

    primitive!(env, Arity::Exact(0), "quit", |_, app| {
        app.quit();
        Ok(LispExpr::Unit)
    });

    primitive!(env, Arity::Exact(2), "eq?", |args, app| {
        let s = &args[0];
        let o = &args[1];
        info!("comparing {} {}", s, o);
        let result = s.compare(o, &app.lisp_env);
        result.map(LispExpr::BoolLit)
    });

    primitive!(env, Arity::Exact(2), ">", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let acc = nums[0].clone();
        Ok(LispExpr::BoolLit(
            nums.into_iter().skip(1).all(|&arg| acc > arg),
        ))
    });

    primitive!(env, Arity::Exact(2), ">=", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let acc = nums[0].clone();
        Ok(LispExpr::BoolLit(
            nums.into_iter().skip(1).all(|&arg| acc >= arg),
        ))
    });

    primitive!(env, Arity::Exact(2), "<", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let acc = nums[0].clone();
        Ok(LispExpr::BoolLit(
            nums.into_iter().skip(1).all(|&arg| acc < arg),
        ))
    });

    primitive!(env, Arity::Exact(2), "<=", |args, _| {
        let nums = args
            .into_iter()
            .map(|arg| arg.try_into())
            .collect::<Result<Vec<&LispNumber>, LispError>>()?;
        let acc = nums[0].clone();
        Ok(LispExpr::BoolLit(
            nums.into_iter().skip(1).all(|&arg| acc <= arg),
        ))
    });

    primitive!(env, Arity::Exact(1), "string-len", |args, _| {
        match &args[0] {
            LispExpr::StringLit(s) => Ok(LispExpr::Number(LispNumber::Integer(s.len() as i64))),
            _ => Err(EvalError::TypeMismatch.into()),
        }
    });

    primitive!(env, Arity::Atmost(1), "save", |args, app| {
        let image = app.export().encode().unwrap();
        if args.len() == 1 && matches!(&args[0], LispExpr::StringLit(_)) {
            let mut buffer = File::create(&args[0].as_ref()).unwrap();
            buffer.write_all(&image[..]).unwrap();
        } else if let Some(p) = app.file_name {
            let file_name = p;
            let mut buffer = File::create(&file_name).unwrap();
            buffer.write_all(&image[..]).unwrap();
        } else {
            return Err(EvalError::NoFileName.into());
        }

        return Ok(LispExpr::Unit);
    });

    env
}