eclisp 0.1.7

Bindings for Embeddable Common Lisp
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::{
    ffi::{CStr, CString},
    ptr::{self, NonNull},
    rc::Rc,
};

use crate::{Class, Function, Lisp, LispError, Value, ValueRef, sys};

#[derive(Clone, Copy)]
pub struct LispContext<'rt> {
    pub(crate) runtime: &'rt Lisp,
}

impl LispContext<'_> {
    pub fn defun<F>(&self, name: &str, callback: F) -> Result<(), LispError>
    where
        F: for<'a, 'call> Fn(LispContext<'a>, &[ValueRef<'call>]) -> Result<Value<'a>, LispError>
            + 'static,
    {
        if !valid_symbol(name) {
            return Err(LispError::InvalidSymbol(name.to_string()));
        }

        let id = self
            .runtime
            .callbacks
            .borrow_mut()
            .insert(Rc::new(callback));

        let definition = format!("(defun {name} (&rest args) (%eclisp-dispatch {id} args))");

        if let Err(error) = self.eval(definition) {
            self.runtime.callbacks.borrow_mut().remove(id);
            return Err(error);
        }

        Ok(())
    }

    pub fn defclass(&self, class: &Class) -> Result<(), LispError> {
        let mut names = vec![class.name.as_str()];

        names.extend(class.supers.iter().map(String::as_str));

        for slot in &class.slots {
            names.push(&slot.name);

            if let Some(name) = &slot.initarg {
                names.push(name);
            }

            if let Some(name) = &slot.accessor {
                names.push(name);
            }
        }

        for name in names {
            if !valid_symbol(name) {
                return Err(LispError::InvalidSymbol(name.to_string()));
            }
        }

        let supers = class.supers.join(" ");

        let slots = class
            .slots
            .iter()
            .map(|slot| {
                let mut form = format!("({}", slot.name);

                if let Some(initarg) = &slot.initarg {
                    form.push_str(&format!(" :initarg :{initarg}"));
                }

                if let Some(accessor) = &slot.accessor {
                    form.push_str(&format!(" :accessor {accessor}"));
                }

                if let Some(initform) = &slot.initform {
                    form.push_str(&format!(" :initform {initform}"));
                }

                form.push(')');
                form
            })
            .collect::<Vec<_>>()
            .join(" ");

        self.eval(format!("(defclass {} ({supers}) ({slots}))", class.name))?;

        Ok(())
    }

    pub fn defmethod<F>(
        &self,
        name: &str,
        parameters: &[(&str, &str)],
        callback: F,
    ) -> Result<(), LispError>
    where
        F: for<'a, 'call> Fn(LispContext<'a>, &[ValueRef<'call>]) -> Result<Value<'a>, LispError>
            + 'static,
    {
        if !valid_symbol(name)
            || parameters
                .iter()
                .any(|(parameter, class)| !valid_symbol(parameter) || !valid_symbol(class))
        {
            return Err(LispError::InvalidSymbol(name.to_string()));
        }

        let id = self
            .runtime
            .callbacks
            .borrow_mut()
            .insert(Rc::new(callback));

        let lambda_list = parameters
            .iter()
            .map(|(parameter, class)| format!("({parameter} {class})"))
            .collect::<Vec<_>>()
            .join(" ");

        let arguments = parameters
            .iter()
            .map(|(parameter, _)| *parameter)
            .collect::<Vec<_>>()
            .join(" ");

        let definition = format!(
            "(defmethod {name} ({lambda_list}) \
           (%eclisp-dispatch {id} (list {arguments})))"
        );

        if let Err(error) = self.eval(definition) {
            self.runtime.callbacks.borrow_mut().remove(id);
            return Err(error);
        }

        Ok(())
    }
}

impl<'rt> LispContext<'rt> {
    pub fn load(&self, code: impl AsRef<str>) -> Result<(), LispError> {
        self.eval(code).map(|_| ())
    }

    pub fn root(&self, value: ValueRef<'_>) -> Result<Value<'rt>, LispError> {
        let mut root = std::ptr::null_mut();

        let success = unsafe { sys::eclisp_root_copy(value.as_raw(), &mut root) };

        if success == 0 {
            return Err(LispError::RuntimeError("Failed to create Lisp root".into()));
        }

        let root = NonNull::new(root)
            .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

        Ok(unsafe { Value::from_root(self.runtime, root) })
    }

    pub fn eval(&self, code: impl AsRef<str>) -> Result<Value<'rt>, LispError> {
        let source =
            CString::new(code.as_ref()).map_err(|e| LispError::RuntimeError(e.to_string()))?;

        let mut root = ptr::null_mut();
        let mut error = ptr::null_mut();

        let status = unsafe { sys::eclisp_eval(source.as_ptr(), &mut root, &mut error) };

        if status != 0 {
            let message = if error.is_null() {
                format!("ECL evaluation failed: {status}")
            } else {
                let message = unsafe { CStr::from_ptr(error).to_string_lossy().into_owned() };

                unsafe {
                    sys::eclisp_string_free(error);
                }

                message
            };

            return Err(LispError::RuntimeError(message));
        }

        let root = NonNull::new(root)
            .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

        Ok(unsafe { Value::from_root(self.runtime, root) })
    }

    pub fn run(&self, path: impl AsRef<std::path::Path>) -> Result<Value<'rt>, LispError> {
        let path = path
            .as_ref()
            .to_str()
            .ok_or_else(|| LispError::RuntimeError("Invalid file path".into()))?;

        let source =
            std::fs::read_to_string(path).map_err(|e| LispError::RuntimeError(e.to_string()))?;

        self.eval(source)
    }

    pub fn call(&self, function: &str, args: &[&Value<'_>]) -> Result<Value<'rt>, LispError> {
        let function =
            CString::new(function).map_err(|e| LispError::RuntimeError(e.to_string()))?;

        if args.iter().any(|value| !value.belongs_to(self.runtime)) {
            return Err(LispError::RuntimeError(
                "Argument belongs to another Lisp runtime".into(),
            ));
        }

        let raw_args: Vec<sys::cl_object> = args.iter().map(|value| value.as_raw()).collect();

        let mut root = ptr::null_mut();
        let mut error = ptr::null_mut();

        let status = unsafe {
            sys::eclisp_call(
                function.as_ptr(),
                raw_args.len(),
                raw_args.as_ptr(),
                &mut root,
                &mut error,
            )
        };

        if status != 0 {
            let message = if !error.is_null() {
                let message = unsafe { CStr::from_ptr(error).to_string_lossy().into_owned() };

                unsafe { sys::eclisp_string_free(error) };

                message
            } else if status == 3 {
                format!("Unknown function: {}", function.to_string_lossy())
            } else {
                format!("Lisp function call failed: {status}")
            };

            return Err(LispError::RuntimeError(message));
        }

        let root = NonNull::new(root)
            .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

        Ok(unsafe { Value::from_root(self.runtime, root) })
    }

    pub fn fun(&self, name: &str) -> Result<Option<Function<'rt>>, LispError> {
        let name = CString::new(name).map_err(|e| LispError::RuntimeError(e.to_string()))?;

        let mut root = ptr::null_mut();
        let mut error = ptr::null_mut();

        let status = unsafe { sys::eclisp_function_get(name.as_ptr(), &mut root, &mut error) };

        match status {
            sys::ECLISP_NOT_FOUND => return Ok(None),
            sys::ECLISP_OK => {
                let root = NonNull::new(root)
                    .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

                Ok(Some(Function {
                    value: Rc::new(unsafe { Value::from_root(self.runtime, root) }),
                }))
            }
            _ => {
                let message = if !error.is_null() {
                    let message = unsafe { CStr::from_ptr(error).to_string_lossy().into_owned() };

                    unsafe { sys::eclisp_string_free(error) };
                    message
                } else {
                    format!("Unknown function: {}", name.to_string_lossy())
                };

                return Err(LispError::RuntimeError(message));
            }
        }
    }

    pub fn callfun(
        &self,
        function: &Function<'_>,
        args: &[&Value<'_>],
    ) -> Result<Value<'rt>, LispError> {
        if !function.value.belongs_to(self.runtime)
            || args.iter().any(|v| !v.belongs_to(self.runtime))
        {
            return Err(LispError::RuntimeError(
                "Value belongs to another Lisp runtime".into(),
            ));
        }

        let raw_args: Vec<sys::cl_object> = args.iter().map(|v| v.as_raw()).collect();

        let mut root = ptr::null_mut();
        let mut error = ptr::null_mut();

        let status = unsafe {
            sys::eclisp_function_call(
                function.value.as_raw(),
                raw_args.len(),
                raw_args.as_ptr(),
                &mut root,
                &mut error,
            )
        };

        if status != 0 {
            let message = if !error.is_null() {
                let message = unsafe { CStr::from_ptr(error).to_string_lossy().into_owned() };

                unsafe { sys::eclisp_string_free(error) };
                message
            } else {
                format!("Lisp function call failed: {status}")
            };

            return Err(LispError::RuntimeError(message));
        }

        let root = NonNull::new(root)
            .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

        Ok(unsafe { Value::from_root(self.runtime, root) })
    }

    pub fn int(&self, value: i64) -> Result<Value<'rt>, LispError> {
        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_int_new(value, &mut root) };
        self.value_from_result(status, root)
    }

    pub fn float(&self, value: f64) -> Result<Value<'rt>, LispError> {
        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_float_new(value, &mut root) };
        self.value_from_result(status, root)
    }

    pub fn cons(&self, car: &Value<'_>, cdr: &Value<'_>) -> Result<Value<'rt>, LispError> {
        if !car.belongs_to(self.runtime) || !cdr.belongs_to(self.runtime) {
            return Err(LispError::RuntimeError(
                "Value belongs to another Lisp runtime".into(),
            ));
        }

        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_cons_new(car.as_raw(), cdr.as_raw(), &mut root) };
        self.value_from_result(status, root)
    }

    pub fn list(&self, values: &[&Value<'_>]) -> Result<Value<'rt>, LispError> {
        if values.iter().any(|v| !v.belongs_to(self.runtime)) {
            return Err(LispError::RuntimeError(
                "Value belongs to another Lisp runtime".into(),
            ));
        }

        let objects: Vec<sys::cl_object> = values.iter().map(|v| v.as_raw()).collect();

        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_list_new(objects.len(), objects.as_ptr(), &mut root) };
        self.value_from_result(status, root)
    }

    pub fn string(&self, contents: impl AsRef<str>) -> Result<Value<'rt>, LispError> {
        let bytes = contents.as_ref().as_bytes();
        let mut root = ptr::null_mut();

        let status =
            unsafe { sys::eclisp_string_new(bytes.as_ptr().cast(), bytes.len(), &mut root) };
        self.value_from_result(status, root)
    }

    pub fn nil(&self) -> Result<Value<'rt>, LispError> {
        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_nil_new(&mut root) };
        self.value_from_result(status, root)
    }

    pub fn t(&self) -> Result<Value<'rt>, LispError> {
        let mut root = ptr::null_mut();
        let status = unsafe { sys::eclisp_t_new(&mut root) };
        self.value_from_result(status, root)
    }

    fn value_from_result(
        &self,
        status: i32,
        root: *mut sys::eclisp_root,
    ) -> Result<Value<'rt>, LispError> {
        if status != 0 {
            return Err(LispError::RuntimeError(format!(
                "Failed to create Lisp value: {status}"
            )));
        }

        let root = NonNull::new(root)
            .ok_or_else(|| LispError::RuntimeError("Missing Lisp root".into()))?;

        Ok(unsafe { Value::from_root(self.runtime, root) })
    }
}

fn valid_symbol(name: &str) -> bool {
    let mut bytes = name.bytes();

    matches!(bytes.next(), Some(b'a'..=b'z' | b'A'..=b'Z'))
        && bytes.all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
}