lisp.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #![allow(non_snake_case)]
  2. use std::rc::Rc;
  3. //use std::collections::HashMap;
  4. use fnv::FnvHashMap;
  5. use itertools::Itertools;
  6. #[macro_use]
  7. extern crate lazy_static;
  8. extern crate fnv;
  9. extern crate itertools;
  10. extern crate regex;
  11. #[macro_use]
  12. mod types;
  13. use crate::types::MalErr::{ErrMalVal, ErrString};
  14. use crate::types::MalVal::{Bool, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector};
  15. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  16. mod env;
  17. mod printer;
  18. mod reader;
  19. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  20. #[macro_use]
  21. mod core;
  22. // read
  23. fn read(str: &str) -> MalRet {
  24. reader::read_str(str.to_string())
  25. }
  26. // eval
  27. fn qq_iter(elts: &MalArgs) -> MalVal {
  28. let mut acc = list![];
  29. for elt in elts.iter().rev() {
  30. if let List(v, _) = elt {
  31. if v.len() == 2 {
  32. if let Sym(ref s) = v[0] {
  33. if s == "splice-unquote" {
  34. acc = list![Sym("concat".to_string()), v[1].clone(), acc];
  35. continue;
  36. }
  37. }
  38. }
  39. }
  40. acc = list![Sym("cons".to_string()), quasiquote(&elt), acc];
  41. }
  42. return acc;
  43. }
  44. fn quasiquote(ast: &MalVal) -> MalVal {
  45. match ast {
  46. List(v, _) => {
  47. if v.len() == 2 {
  48. if let Sym(ref s) = v[0] {
  49. if s == "unquote" {
  50. return v[1].clone();
  51. }
  52. }
  53. }
  54. return qq_iter(&v);
  55. },
  56. Vector(v, _) => return list![Sym("vec".to_string()), qq_iter(&v)],
  57. Hash(_, _) | Sym(_)=> return list![Sym("quote".to_string()), ast.clone()],
  58. _ => ast.clone(),
  59. }
  60. }
  61. fn is_macro_call(ast: &MalVal, env: &Env) -> Option<(MalVal, MalArgs)> {
  62. match ast {
  63. List(v, _) => match v[0] {
  64. Sym(ref s) => match env_find(env, s) {
  65. Some(e) => match env_get(&e, &v[0]) {
  66. Ok(f @ MalFunc { is_macro: true, .. }) => Some((f, v[1..].to_vec())),
  67. _ => None,
  68. },
  69. _ => None,
  70. },
  71. _ => None,
  72. },
  73. _ => None,
  74. }
  75. }
  76. fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
  77. let mut was_expanded = false;
  78. while let Some((mf, args)) = is_macro_call(&ast, env) {
  79. //println!("macroexpand 1: {:?}", ast);
  80. ast = match mf.apply(args) {
  81. Err(e) => return (false, Err(e)),
  82. Ok(a) => a,
  83. };
  84. //println!("macroexpand 2: {:?}", ast);
  85. was_expanded = true;
  86. }
  87. ((was_expanded, Ok(ast)))
  88. }
  89. fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
  90. match ast {
  91. Sym(_) => Ok(env_get(&env, &ast)?),
  92. List(v, _) => {
  93. let mut lst: MalArgs = vec![];
  94. for a in v.iter() {
  95. lst.push(eval(a.clone(), env.clone())?)
  96. }
  97. Ok(list!(lst))
  98. }
  99. Vector(v, _) => {
  100. let mut lst: MalArgs = vec![];
  101. for a in v.iter() {
  102. lst.push(eval(a.clone(), env.clone())?)
  103. }
  104. Ok(vector!(lst))
  105. }
  106. Hash(hm, _) => {
  107. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  108. for (k, v) in hm.iter() {
  109. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  110. }
  111. Ok(Hash(Rc::new(new_hm), Rc::new(Nil)))
  112. }
  113. _ => Ok(ast.clone()),
  114. }
  115. }
  116. fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
  117. let ret: MalRet;
  118. 'tco: loop {
  119. ret = match ast.clone() {
  120. List(l, _) => {
  121. if l.len() == 0 {
  122. return Ok(ast);
  123. }
  124. match macroexpand(ast.clone(), &env) {
  125. (true, Ok(new_ast)) => {
  126. ast = new_ast;
  127. continue 'tco;
  128. }
  129. (_, Err(e)) => return Err(e),
  130. _ => (),
  131. }
  132. if l.len() == 0 {
  133. return Ok(ast);
  134. }
  135. let a0 = &l[0];
  136. match a0 {
  137. Sym(ref a0sym) if a0sym == "def!" => {
  138. env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
  139. }
  140. Sym(ref a0sym) if a0sym == "let*" => {
  141. env = env_new(Some(env.clone()));
  142. let (a1, a2) = (l[1].clone(), l[2].clone());
  143. match a1 {
  144. List(ref binds, _) | Vector(ref binds, _) => {
  145. for (b, e) in binds.iter().tuples() {
  146. match b {
  147. Sym(_) => {
  148. let _ = env_set(
  149. &env,
  150. b.clone(),
  151. eval(e.clone(), env.clone())?,
  152. );
  153. }
  154. _ => {
  155. return error("let* with non-Sym binding");
  156. }
  157. }
  158. }
  159. }
  160. _ => {
  161. return error("let* with non-List bindings");
  162. }
  163. };
  164. ast = a2;
  165. continue 'tco;
  166. }
  167. Sym(ref a0sym) if a0sym == "quote" => Ok(l[1].clone()),
  168. Sym(ref a0sym) if a0sym == "quasiquoteexpand" => Ok(quasiquote(&l[1])),
  169. Sym(ref a0sym) if a0sym == "quasiquote" => {
  170. ast = quasiquote(&l[1]);
  171. continue 'tco;
  172. }
  173. Sym(ref a0sym) if a0sym == "defmacro!" => {
  174. let (a1, a2) = (l[1].clone(), l[2].clone());
  175. let r = eval(a2, env.clone())?;
  176. match r {
  177. MalFunc {
  178. eval,
  179. ast,
  180. env,
  181. params,
  182. ..
  183. } => Ok(env_set(
  184. &env,
  185. a1.clone(),
  186. MalFunc {
  187. eval: eval,
  188. ast: ast.clone(),
  189. env: env.clone(),
  190. params: params.clone(),
  191. is_macro: true,
  192. meta: Rc::new(Nil),
  193. },
  194. )?),
  195. _ => error("set_macro on non-function"),
  196. }
  197. }
  198. Sym(ref a0sym) if a0sym == "macroexpand" => {
  199. match macroexpand(l[1].clone(), &env) {
  200. (_, Ok(new_ast)) => Ok(new_ast),
  201. (_, e) => return e,
  202. }
  203. }
  204. Sym(ref a0sym) if a0sym == "try*" => match eval(l[1].clone(), env.clone()) {
  205. Err(ref e) if l.len() >= 3 => {
  206. let exc = match e {
  207. ErrMalVal(mv) => mv.clone(),
  208. ErrString(s) => Str(s.to_string()),
  209. };
  210. match l[2].clone() {
  211. List(c, _) => {
  212. let catch_env = env_bind(
  213. Some(env.clone()),
  214. list!(vec![c[1].clone()]),
  215. vec![exc],
  216. )?;
  217. eval(c[2].clone(), catch_env)
  218. }
  219. _ => error("invalid catch block"),
  220. }
  221. }
  222. res => res,
  223. },
  224. Sym(ref a0sym) if a0sym == "do" => {
  225. match eval_ast(&list!(l[1..l.len() - 1].to_vec()), &env)? {
  226. List(_, _) => {
  227. ast = l.last().unwrap_or(&Nil).clone();
  228. continue 'tco;
  229. }
  230. _ => error("invalid do form"),
  231. }
  232. }
  233. Sym(ref a0sym) if a0sym == "if" => {
  234. let cond = eval(l[1].clone(), env.clone())?;
  235. match cond {
  236. Bool(false) | Nil if l.len() >= 4 => {
  237. ast = l[3].clone();
  238. continue 'tco;
  239. }
  240. Bool(false) | Nil => Ok(Nil),
  241. _ if l.len() >= 3 => {
  242. ast = l[2].clone();
  243. continue 'tco;
  244. }
  245. _ => Ok(Nil),
  246. }
  247. }
  248. Sym(ref a0sym) if a0sym == "fn*" => {
  249. let (a1, a2) = (l[1].clone(), l[2].clone());
  250. Ok(MalFunc {
  251. eval: eval,
  252. ast: Rc::new(a2),
  253. env: env,
  254. params: Rc::new(a1),
  255. is_macro: false,
  256. meta: Rc::new(Nil),
  257. })
  258. }
  259. Sym(ref a0sym) if a0sym == "eval" => {
  260. ast = eval(l[1].clone(), env.clone())?;
  261. while let Some(ref e) = env.clone().outer {
  262. env = e.clone();
  263. }
  264. continue 'tco;
  265. }
  266. _ => match eval_ast(&ast, &env)? {
  267. List(ref el, _) => {
  268. let ref f = el[0].clone();
  269. let args = el[1..].to_vec();
  270. match f {
  271. Func(_, _) => f.apply(args),
  272. MalFunc {
  273. ast: mast,
  274. env: menv,
  275. params,
  276. ..
  277. } => {
  278. let a = &**mast;
  279. let p = &**params;
  280. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  281. ast = a.clone();
  282. continue 'tco;
  283. }
  284. _ => error("attempt to call non-function"),
  285. }
  286. }
  287. _ => error("expected a list"),
  288. },
  289. }
  290. }
  291. _ => eval_ast(&ast, &env),
  292. };
  293. break;
  294. } // end 'tco loop
  295. ret
  296. }
  297. // print
  298. fn print(ast: &MalVal) -> String {
  299. ast.pr_str(true)
  300. }
  301. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  302. let ast = read(str)?;
  303. let exp = eval(ast, env.clone())?;
  304. Ok(print(&exp))
  305. }
  306. fn main() {
  307. let mut args = std::env::args();
  308. let arg1 = args.nth(1);
  309. // core.rs: defined using rust
  310. let repl_env = env_new(None);
  311. for (k, v) in core::ns() {
  312. env_sets(&repl_env, k, v);
  313. }
  314. env_sets(&repl_env, "*ARGV*", list!(args.map(Str).collect()));
  315. // core.mal: defined using the language itself
  316. let _ = rep("(def! *host-language* \"rust\")", &repl_env);
  317. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  318. let _ = rep(
  319. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  320. &repl_env,
  321. );
  322. 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);
  323. // Invoked with arguments
  324. if let Some(f) = arg1 {
  325. match rep(&format!("(load-file \"{}\")", f), &repl_env) {
  326. Ok(_) => std::process::exit(0),
  327. Err(e) => {
  328. println!("Error: {}", format_error(e));
  329. std::process::exit(1);
  330. }
  331. }
  332. }
  333. }