rust_lisp 0.7.2

A Rust-embeddable Lisp, with support for interop with native Rust functions
Documentation
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
use crate::{
    lisp,
    model::{FloatType, IntType, List, Value},
};

use std::fmt::Display;

/// A slightly more convenient data structure for building the parse tree, before
/// eventually converting it into proper s-expressions.
#[derive(Debug, Clone)]
enum ParseTree {
    Atom { atom: Value, quoted: bool },
    List { vec: Vec<ParseTree>, quoted: bool },
}

impl ParseTree {
    pub fn into_expression(self) -> Value {
        match self {
            ParseTree::Atom { atom, quoted } => {
                if quoted {
                    lisp! { (quote {atom}) }
                } else {
                    atom
                }
            }
            ParseTree::List { vec, quoted } => {
                let list = Value::List(
                    vec.into_iter()
                        .map(|parse_tree| parse_tree.into_expression())
                        .collect::<List>(),
                );

                if quoted {
                    lisp! { (quote {list}) }
                } else {
                    list
                }
            }
        }
    }
}

/// Tokenize Lisp code
fn tokenize(code: &str) -> impl Iterator<Item = &str> {
    let mut skip_to: Option<usize> = None;

    code.char_indices().filter_map(move |(index, ch)| {
        if skip_to
            .map(|destination| destination > index)
            .unwrap_or(false)
        {
            return None;
        } else {
            skip_to = None;
        }

        // whitespace
        if ch.is_whitespace() {
            return None;
        }

        // special tokens
        for special in &SPECIAL_TOKENS {
            if match_front(&code[index..], special) {
                skip_to = Some(index + special.len());
                return Some(*special);
            }
        }

        // strings
        if ch == '"' {
            if let Some(contents_end_index) = code[index + 1..].find(|c| c == '"') {
                    let string_end_index = index + contents_end_index + 2;

                    skip_to = Some(string_end_index);
                    return Some(&code[index..string_end_index]);
            } else {
                    skip_to = Some(code.len());
                    return None;
            }
        }

        // comments
        if ch == ';' {
            if let Some(newline_index) = code[index..].find(|c| c == '\n') {
                skip_to = Some(index + newline_index + 1);
            } else {
                skip_to = Some(code.len());
            }
            return None;
        }

        // numbers
        if ch.is_numeric() {
            let front_end = index + match_pred(&code[index..], |c| c.is_numeric()).unwrap() + 1;

            if front_end < code.len() - 1 && &code[front_end..front_end + 1] == "." {
                let back_end = front_end
                    + 1
                    + match_pred(&code[front_end + 1..], |c| c.is_numeric()).unwrap()
                    + 1;

                skip_to = Some(back_end);
                return Some(&code[index..back_end]);
            } else {
                skip_to = Some(front_end);
                return Some(&code[index..front_end]);
            }
        }

        // symbols
        if is_symbol_start(ch) {
            let match_end = match_pred(&code[index..], is_symbolic);

            if let Some(symbol_last) = match_end {
                let symbol_end = index + symbol_last + 1;

                skip_to = Some(symbol_end);
                return Some(&code[index..symbol_end]);
            }
        }

        None
    })
}

const SPECIAL_TOKENS: [&str; 4] = ["(", ")", "'", "..."];

fn is_symbol_start(c: char) -> bool {
    !c.is_numeric() && is_symbolic(c)
}

fn is_symbolic(c: char) -> bool {
    !c.is_whitespace()
        && !SPECIAL_TOKENS
            .iter()
            .any(|t| t.chars().any(|other| other == c))
}

fn match_front(code: &str, segment: &str) -> bool {
    segment.chars().zip(code.chars()).all(|(a, b)| a == b)
}

fn match_pred<F: Fn(char) -> bool>(code: &str, pred: F) -> Option<usize> {
    code.char_indices()
        .take_while(|(_, c)| pred(*c))
        .last()
        .map(|(i, _)| i)
}

#[test]
fn tokenize_simplest() {
    let source = "
  (1 2 3)";
    let tokens: Vec<&str> = tokenize(source).collect();

    assert_eq!(tokens, vec!["(", "1", "2", "3", ")"]);
}

// 🦀 Testing, testing!
#[test]
fn tokenize_basic_expression() {
    let source = "
  (list 
    (* 1 2)  ;; a comment
    (/ 6 3 \"foo\"))";
    let tokens: Vec<&str> = tokenize(source).collect();

    assert_eq!(
        tokens,
        vec!["(", "list", "(", "*", "1", "2", ")", "(", "/", "6", "3", "\"foo\"", ")", ")"]
    );
}

#[test]
fn tokenize_complex_expression() {
    let source = "
  (begin
    (define fib-normal
      (lambda (n)
        (+ (fib (- n 1)) (fib (- n 2)) )))

    (define fib 
      (lambda (n)
        (cond           ;; some comment
          ((== n 0) 0)
          ((== n 1) 1)
          (T (fib-normal n))))) ;;another comment";

    let tokens: Vec<&str> = tokenize(source).collect();

    assert_eq!(
        tokens,
        vec![
            "(",
            "begin",
            "(",
            "define",
            "fib-normal",
            "(",
            "lambda",
            "(",
            "n",
            ")",
            "(",
            "+",
            "(",
            "fib",
            "(",
            "-",
            "n",
            "1",
            ")",
            ")",
            "(",
            "fib",
            "(",
            "-",
            "n",
            "2",
            ")",
            ")",
            ")",
            ")",
            ")",
            "(",
            "define",
            "fib",
            "(",
            "lambda",
            "(",
            "n",
            ")",
            "(",
            "cond",
            "(",
            "(",
            "==",
            "n",
            "0",
            ")",
            "0",
            ")",
            "(",
            "(",
            "==",
            "n",
            "1",
            ")",
            "1",
            ")",
            "(",
            "T",
            "(",
            "fib-normal",
            "n",
            ")",
            ")",
            ")",
            ")",
            ")"
        ]
    );
}

#[test]
fn tokenize_identifier_with_digits() {
    let tokens: Vec<&str> = tokenize("(i32)").collect();

    assert_eq!(tokens, vec!["(", "i32", ")"]);
}

/// Parse tokens (created by `tokenize()`) into a series of s-expressions. There
/// are more than one when the base string has more than one independent
/// parenthesized lists at its root.
fn read<'a>(
    tokens: impl Iterator<Item = &'a str> + 'a,
) -> impl Iterator<Item = Result<Value, ParseError>> + 'a {
    let mut stack: Vec<ParseTree> = vec![];
    let mut parenths = 0;
    let mut quote_next = false;

    tokens.filter_map(move |token| {
        match token {
            "(" => {
                parenths += 1;

                stack.push(ParseTree::List {
                    vec: vec![],
                    quoted: quote_next,
                });
                quote_next = false;

                None
            }
            ")" => {
                parenths -= 1;

                if stack.is_empty() {
                    Some(Err(ParseError::new("Unexpected ')'")))
                } else {
                    let mut finished = stack.pop().unwrap();

                    if parenths == 0 {
                        stack = vec![];
                        Some(Ok(finished.into_expression()))
                    } else {
                        let destination = stack.last_mut().unwrap();

                        // () is Nil
                        if let ParseTree::List { vec, quoted } = &finished {
                            if vec.is_empty() {
                                finished = ParseTree::Atom {
                                    atom: Value::NIL,
                                    quoted: *quoted,
                                };
                            }
                        }

                        if let ParseTree::List { vec, quoted: _ } = destination {
                            vec.push(finished);
                        }

                        None
                    }
                }
            }
            "'" => {
                quote_next = true;

                None
            }
            _ => {
                // atom
                let expr = ParseTree::Atom {
                    atom: read_atom(token),
                    quoted: quote_next,
                };
                quote_next = false;

                if let Some(last) = stack.last_mut() {
                    if let ParseTree::List { vec, quoted: _ } = last {
                        vec.push(expr);
                    }
                    None
                } else {
                    Some(Ok(expr.into_expression()))
                }
            }
        }
    })
}

fn read_atom(token: &str) -> Value {
    let token_lowercase = token.to_lowercase();

    if token_lowercase == "t" {
        return Value::True;
    }

    if token_lowercase == "f" {
        return Value::False;
    }

    if token_lowercase == "nil" {
        return Value::NIL;
    }

    if let Ok(as_int) = token.parse::<IntType>() {
        return Value::Int(as_int);
    }

    if let Ok(as_float) = token.parse::<FloatType>() {
        return Value::Float(as_float);
    }

    if token.chars().next().map_or(false, |c| c == '"') {
        // TODO: Implement escaped characters
        return Value::String(String::from(&token[1..token.chars().count() - 1]));
    }

    Value::Symbol(String::from(token))
}

/// Parse a string of Lisp code into a series of s-expressions. There
/// are more than one expressions when the base string has more than one
/// independent parenthesized lists at its root.
pub fn parse(code: &str) -> impl Iterator<Item = Result<Value, ParseError>> + '_ {
    read(tokenize(code))
}

#[derive(Debug)]
pub struct ParseError {
    pub msg: String,
    // pub line: i32,
}

impl ParseError {
    fn new(s: impl Into<String>) -> ParseError {
        ParseError { msg: s.into() }
    }
}

impl Display for ParseError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        return write!(formatter, "Parse error: {}", self.msg);
    }
}