calisp 0.2.2

MAL clone, lisp language
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#![allow(non_snake_case)]
#![allow(dead_code)]
//#![recursion_limit="512"]

use std::sync::{Arc, RwLock};

use fnv::FnvHashMap;
use itertools::Itertools;

#[macro_use]
extern crate lazy_static;
extern crate fnv;
extern crate itertools;
extern crate regex;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;

#[macro_use]
#[path = "types.rs"]
mod types;
use crate::types::CalispErr::{ErrCalispVal, ErrString};
use crate::types::CalispVal::{Bool, CalispFunc, Func, Hash, List, Nil, Str, Sym, Vector};
use crate::types::{error, format_error, CalispArgs, CalispErr, CalispRet, CalispVal};
#[path = "env.rs"]
mod env;
#[path = "printer.rs"]
mod printer;
#[path = "reader.rs"]
mod reader;
use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
#[macro_use]
#[path = "core.rs"]
mod core;
#[path = "interop.rs"]
mod interop;

/// Read function for reading plain text and parsing it into AST
fn read(str: &str) -> CalispRet {
  reader::read_str(str.to_string())
}

/// Handle quasiquotes `\``
fn quasiquote(ast: &CalispVal) -> CalispVal {
  match ast {
    List(v, _) | Vector(v, _) if v.read().unwrap().len() > 0 => {
      let a0 = &v.read().unwrap()[0];
      match a0 {
        Sym(ref s) if s == "unquote" => v.read().unwrap()[1].clone(),
        List(ref v0, _) | Vector(ref v0, _) if v0.read().unwrap().len() > 0 => {
          match v0.read().unwrap()[0] {
            Sym(ref s) if s == "splice-unquote" => list![
              Sym("concat".to_string()),
              v0.read().unwrap()[1].clone(),
              quasiquote(&list!(v.read().unwrap()[1..].to_vec()))
            ],
            _ => list![
              Sym("cons".to_string()),
              quasiquote(&a0),
              quasiquote(&list!(v.read().unwrap()[1..].to_vec()))
            ],
          }
        }
        _ => list![
          Sym("cons".to_string()),
          quasiquote(a0),
          quasiquote(&list!(v.read().unwrap()[1..].to_vec()))
        ],
      }
    }
    _ => list![Sym("quote".to_string()), ast.clone()],
  }
}

/// Check if call is macro call
fn is_macro_call(ast: &CalispVal, env: &Env) -> Option<(CalispVal, CalispArgs)> {
  match ast {
    List(v, _) => match v.read().unwrap()[0] {
      Sym(ref s) => match env_find(env, s) {
        Some(e) => match env_get(&e, &v.read().unwrap()[0]) {
          Ok(f @ CalispFunc { is_macro: true, .. }) => Some((f, v.read().unwrap()[1..].to_vec())),
          _ => None,
        },
        _ => None,
      },
      _ => None,
    },
    _ => None,
  }
}

/// Expand macro
fn macroexpand(mut ast: CalispVal, env: &Env) -> (bool, CalispRet) {
  let mut was_expanded = false;
  while let Some((mf, args)) = is_macro_call(&ast, env) {
    ast = match mf.apply(args) {
      Err(e) => return (false, Err(e)),
      Ok(a) => a,
    };
    was_expanded = true;
  }
  (was_expanded, Ok(ast))
}

/// Evaluate AST
fn eval_ast(ast: &CalispVal, env: &Env) -> CalispRet {
  match ast {
    Sym(_) => Ok(env_get(&env, &ast)?),
    List(v, _) => {
      let mut lst: CalispArgs = vec![];
      for a in v.read().unwrap().iter() {
        lst.push(eval(a.clone(), env.clone())?)
      }
      Ok(list!(lst))
    }
    Vector(v, _) => {
      let mut lst: CalispArgs = vec![];
      for a in v.read().unwrap().iter() {
        lst.push(eval(a.clone(), env.clone())?)
      }
      Ok(vector!(lst))
    }
    Hash(hm, _) => {
      let mut new_hm: FnvHashMap<String, CalispVal> = FnvHashMap::default();
      for (k, v) in hm.write().unwrap().iter() {
        new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
      }
      Ok(Hash(
        Arc::new(RwLock::new(new_hm)),
        Arc::new(RwLock::new(Nil)),
      ))
    }
    _ => Ok(ast.clone()),
  }
}

/// Evaluate
/// This function loops through the whole AST and evaluates every expression accordingly
fn eval(mut ast: CalispVal, mut env: Env) -> CalispRet {
  let ret: CalispRet;

  'tco: loop {
    ret = match ast.clone() {
      List(l, _) => {
        if l.read().unwrap().len() == 0 {
          return Ok(ast);
        }
        match macroexpand(ast.clone(), &env) {
          (true, Ok(new_ast)) => {
            ast = new_ast;
            continue 'tco;
          }
          (_, Err(e)) => return Err(e),
          _ => (),
        }

        if l.read().unwrap().len() == 0 {
          return Ok(ast);
        }
        let a0 = &l.read().unwrap()[0];
        match a0 {
          Sym(ref a0sym) if a0sym == "def!" => env_set(
            &env,
            l.read().unwrap()[1].clone(),
            eval(l.read().unwrap()[2].clone(), env.clone())?,
          ),
          Sym(ref a0sym) if a0sym == "let*" => {
            env = env_new(Some(env.clone()));
            let (a1, a2) = (l.read().unwrap()[1].clone(), l.read().unwrap()[2].clone());
            match a1 {
              List(ref binds, _) | Vector(ref binds, _) => {
                for (b, e) in binds.read().unwrap().iter().tuples() {
                  match b {
                    Sym(_) => {
                      let _ = env_set(&env, b.clone(), eval(e.clone(), env.clone())?);
                    }
                    _ => {
                      return error("let* with non-Sym binding");
                    }
                  }
                }
              }
              _ => {
                return error("let* with non-List bindings");
              }
            };
            ast = a2;
            continue 'tco;
          }
          Sym(ref a0sym) if a0sym == "quote" => Ok(l.read().unwrap()[1].clone()),
          Sym(ref a0sym) if a0sym == "quasiquote" => {
            ast = quasiquote(&l.read().unwrap()[1]);
            continue 'tco;
          }
          Sym(ref a0sym) if a0sym == "defmacro!" => {
            let (a1, a2) = (l.read().unwrap()[1].clone(), l.read().unwrap()[2].clone());
            let mut docstring = String::default();
            let a3 = match a2 {
              Str(s) => {
                docstring = s;
                l.read().unwrap()[3].clone()
              }
              _ => a2,
            };
            let r = eval(a3, env.clone())?;
            match r {
              CalispFunc {
                eval,
                ast,
                env,
                params,
                ..
              } => Ok(env_set(
                &env,
                a1.clone(),
                CalispFunc {
                  eval: eval,
                  ast: ast.clone(),
                  env: env.clone(),
                  params: params.clone(),
                  is_macro: true,
                  meta: Arc::new(RwLock::new(Nil)),
                  docstring: docstring,
                },
              )?),
              _ => error("set_macro on non-function"),
            }
          }
          Sym(ref a0sym) if a0sym == "macroexpand" => {
            match macroexpand(l.read().unwrap()[1].clone(), &env) {
              (_, Ok(new_ast)) => Ok(new_ast),
              (_, e) => return e,
            }
          }
          Sym(ref a0sym) if a0sym == "try*" => {
            match eval(l.read().unwrap()[1].clone(), env.clone()) {
              Err(ref e) if l.read().unwrap().len() >= 3 => {
                let exc = match e {
                  ErrCalispVal(cv) => cv.clone(),
                  ErrString(s) => Str(s.to_string()),
                };
                match l.read().unwrap()[2].clone() {
                  List(c, _) => {
                    let catch_env = env_bind(
                      Some(env.clone()),
                      list!(vec![c.read().unwrap()[1].clone()]),
                      vec![exc],
                    )?;
                    eval(c.read().unwrap()[2].clone(), catch_env)
                  }
                  _ => error("invalid catch block"),
                }
              }
              res => res,
            }
          }
          Sym(ref a0sym) if a0sym == "do" => {
            match eval_ast(
              &list!(l.read().unwrap()[1..l.read().unwrap().len() - 1].to_vec()),
              &env,
            )? {
              List(_, _) => {
                ast = l.read().unwrap().last().unwrap_or(&Nil).clone();
                continue 'tco;
              }
              _ => error("invalid do form"),
            }
          }
          Sym(ref a0sym) if a0sym == "if" => {
            let cond = eval(l.read().unwrap()[1].clone(), env.clone())?;
            match cond {
              Bool(false) | Nil if l.read().unwrap().len() >= 4 => {
                ast = l.read().unwrap()[3].clone();
                continue 'tco;
              }
              Bool(false) | Nil => Ok(Nil),
              _ if l.read().unwrap().len() >= 3 => {
                ast = l.read().unwrap()[2].clone();
                continue 'tco;
              }
              _ => Ok(Nil),
            }
          }
          Sym(ref a0sym) if a0sym == "fn*" => {
            let (a1, a2) = (l.read().unwrap()[1].clone(), l.read().unwrap()[2].clone());
            let mut docstring = String::default();
            let a3 = match a2 {
              Str(s) => {
                docstring = s;
                l.read().unwrap()[3].clone()
              }
              _ => a2,
            };
            Ok(CalispFunc {
              eval: eval,
              ast: Arc::new(RwLock::new(a3)),
              env: env,
              params: Arc::new(RwLock::new(a1)),
              is_macro: false,
              meta: Arc::new(RwLock::new(Nil)),
              docstring: docstring,
            })
          }
          Sym(ref a0sym) if a0sym == "eval" => {
            ast = eval(l.read().unwrap()[1].clone(), env.clone())?;
            while let Some(ref e) = env.clone().read().unwrap().outer {
              env = e.clone();
            }
            continue 'tco;
          }
          _ => match eval_ast(&ast, &env)? {
            List(ref el, _) => {
              let ref f = el.read().unwrap()[0].clone();
              let args = el.read().unwrap()[1..].to_vec();
              match f {
                Func(_, _, _) => f.apply(args),
                CalispFunc {
                  ast: mast,
                  env: menv,
                  params,
                  ..
                } => {
                  let a = &**mast;
                  let p = &**params;
                  env = env_bind(Some(menv.clone()), p.read().unwrap().clone(), args)?;
                  ast = a.read().unwrap().clone();
                  continue 'tco;
                }
                _ => error("attempt to call non-function"),
              }
            }
            _ => error("expected a list"),
          },
        }
      }
      _ => eval_ast(&ast, &env),
    };
    break;
  }

  ret
}

/// Print the result from output AST
fn print(ast: &CalispVal) -> String {
  ast.pr_str(true)
}

/// This function is called when text needs to be evaluated
/// Calls [`read`]
/// Then [`eval`]
/// And lastly [`print`]
fn rep(str: &str, env: &Env) -> Result<String, CalispErr> {
  let ast = read(str)?;
  let exp = eval(ast, env.clone())?;

  Ok(print(&exp))
}

/// Struct for handling the execution of Calisp code
/// If you want to use this as an library, use [`new`] and [`run`] functions
#[doc(inline)]
pub struct CalispInterpreter {
  input_file: String,
  repl_env: Env,
}

impl CalispInterpreter {
  #[doc(inline)]
  /// Create new instance of [`CalispInterpreter`]
  pub fn new(input_file: String, arguments: &Vec<std::string::String>) -> CalispInterpreter {
    CalispInterpreter {
      input_file: input_file,
      repl_env: CalispInterpreter::new_env(arguments.to_vec()),
    }
  }

  #[doc(inline)]
  /// Create new environment for Calisp
  fn new_env(arguments: Vec<String>) -> Env {
    let repl_env = env_new(None);
    for (k, v) in core::ns() {
      env_sets(&repl_env, k, v);
    }

    env_sets(
      &repl_env,
      "*ARGV*",
      list!(arguments.iter().map(|arg| Str(arg.to_string())).collect()),
    );

    let _ = rep("(def! *host-language* \"rust\")", &repl_env);
    let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
    let _ = rep(
      "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
      &repl_env,
    );
    let _ = rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", &repl_env);

    repl_env.clone()
  }

  #[doc(inline)]
  /// Load file in Calisp and eval it
  pub fn run(&self) -> Result<String, CalispErr> {
    match rep(
      &format!("(load-file \"{}\")", self.input_file),
      &self.repl_env,
    ) {
      Ok(_) => std::process::exit(0),
      Err(e) => {
        println!("Error: {}", format_error(e));
        std::process::exit(1);
      }
    }
  }

  #[doc(inline)]
  /// Read code from the stdin interactively
  pub fn run_interactive(&self) {
    println!("running interactive");
    let mut rl = Editor::<()>::new();

    if rl.load_history(".calisp-history").is_err() {
      eprintln!("No previous history.");
    }

    let _ = rep(
      "(println (str \"Calisp [\" *host-language* \"]\"))",
      &self.repl_env,
    );
    loop {
      let readline = rl.readline("calisp interactive: ");
      match readline {
        Ok(line) => {
          rl.add_history_entry(&line);
          rl.save_history(".calisp-history").unwrap();
          if line.len() > 0 {
            match rep(&line, &self.repl_env) {
              Ok(out) => println!("{}", out),
              Err(e) => println!("Error: {}", format_error(e)),
            }
          }
        }
        Err(ReadlineError::Interrupted) => break,
        Err(ReadlineError::Eof) => break,
        Err(err) => {
          println!("Error: {:?}", err);
          break;
        }
      }
    }
  }
}