core.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. use std::fs::File;
  2. use std::io::Read;
  3. use std::rc::Rc;
  4. use std::sync::Mutex;
  5. use std::time::{SystemTime, UNIX_EPOCH};
  6. use crate::printer::pr_seq;
  7. use crate::reader::read_str;
  8. use crate::types::MalErr::ErrMalVal;
  9. use crate::types::MalVal::{Atom, Bool, Func, Hash, Int, List, MalFunc, Nil, Str, Sym, Vector};
  10. use crate::types::{MalArgs, MalRet, MalVal, _assoc, _dissoc, atom, error, func, hash_map};
  11. macro_rules! fn_t_int_int {
  12. ($ret:ident, $fn:expr) => {{
  13. |a: MalArgs| match (a[0].clone(), a[1].clone()) {
  14. (Int(a0), Int(a1)) => Ok($ret($fn(a0, a1))),
  15. _ => error("expecting (int,int) args"),
  16. }
  17. }};
  18. }
  19. macro_rules! fn_is_type {
  20. ($($ps:pat),*) => {{
  21. |a:MalArgs| { Ok(Bool(match a[0] { $($ps => true,)* _ => false})) }
  22. }};
  23. ($p:pat if $e:expr) => {{
  24. |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, _ => false})) }
  25. }};
  26. ($p:pat if $e:expr,$($ps:pat),*) => {{
  27. |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, $($ps => true,)* _ => false})) }
  28. }};
  29. }
  30. macro_rules! fn_str {
  31. ($fn:expr) => {{
  32. |a: MalArgs| match a[0].clone() {
  33. Str(a0) => $fn(a0),
  34. _ => error("expecting (str) arg"),
  35. }
  36. }};
  37. }
  38. fn symbol(a: MalArgs) -> MalRet {
  39. match a[0] {
  40. Str(ref s) => Ok(Sym(s.to_string())),
  41. _ => error("illegal symbol call"),
  42. }
  43. }
  44. fn slurp(f: String) -> MalRet {
  45. let mut s = String::new();
  46. match File::open(f).and_then(|mut f| f.read_to_string(&mut s)) {
  47. Ok(_) => Ok(Str(s)),
  48. Err(e) => error(&e.to_string()),
  49. }
  50. }
  51. fn time_ms(_a: MalArgs) -> MalRet {
  52. let ms_e = match SystemTime::now().duration_since(UNIX_EPOCH) {
  53. Ok(d) => d,
  54. Err(e) => return error(&format!("{:?}", e)),
  55. };
  56. Ok(Int(
  57. ms_e.as_secs() as i64 * 1000 + ms_e.subsec_nanos() as i64 / 1_000_000
  58. ))
  59. }
  60. fn get(a: MalArgs) -> MalRet {
  61. match (a[0].clone(), a[1].clone()) {
  62. (Nil, _) => Ok(Nil),
  63. (Hash(ref hm, _), Str(ref s)) => match hm.get(s) {
  64. Some(mv) => Ok(mv.clone()),
  65. None => Ok(Nil),
  66. },
  67. _ => error("illegal get args"),
  68. }
  69. }
  70. fn assoc(a: MalArgs) -> MalRet {
  71. match a[0] {
  72. Hash(ref hm, _) => _assoc((**hm).clone(), a[1..].to_vec()),
  73. _ => error("assoc on non-Hash Map"),
  74. }
  75. }
  76. fn dissoc(a: MalArgs) -> MalRet {
  77. match a[0] {
  78. Hash(ref hm, _) => _dissoc((**hm).clone(), a[1..].to_vec()),
  79. _ => error("dissoc on non-Hash Map"),
  80. }
  81. }
  82. fn contains_q(a: MalArgs) -> MalRet {
  83. match (a[0].clone(), a[1].clone()) {
  84. (Hash(ref hm, _), Str(ref s)) => Ok(Bool(hm.contains_key(s))),
  85. _ => error("illegal get args"),
  86. }
  87. }
  88. fn keys(a: MalArgs) -> MalRet {
  89. match a[0] {
  90. Hash(ref hm, _) => Ok(list!(hm.keys().map(|k| { Str(k.to_string()) }).collect())),
  91. _ => error("keys requires Hash Map"),
  92. }
  93. }
  94. fn vals(a: MalArgs) -> MalRet {
  95. match a[0] {
  96. Hash(ref hm, _) => Ok(list!(hm.values().map(|v| { v.clone() }).collect())),
  97. _ => error("keys requires Hash Map"),
  98. }
  99. }
  100. fn vec(a: MalArgs) -> MalRet {
  101. match a[0] {
  102. List(ref v, _) | Vector(ref v, _) => Ok(vector!(v.to_vec())),
  103. _ => error("non-seq passed to vec"),
  104. }
  105. }
  106. fn cons(a: MalArgs) -> MalRet {
  107. match a[1].clone() {
  108. List(v, _) | Vector(v, _) => {
  109. let mut new_v = vec![a[0].clone()];
  110. new_v.extend_from_slice(&v);
  111. Ok(list!(new_v.to_vec()))
  112. }
  113. _ => error("cons expects seq as second arg"),
  114. }
  115. }
  116. fn concat(a: MalArgs) -> MalRet {
  117. let mut new_v = vec![];
  118. for seq in a.iter() {
  119. match seq {
  120. List(v, _) | Vector(v, _) => new_v.extend_from_slice(v),
  121. _ => return error("non-seq passed to concat"),
  122. }
  123. }
  124. Ok(list!(new_v.to_vec()))
  125. }
  126. fn nth(a: MalArgs) -> MalRet {
  127. match (a[0].clone(), a[1].clone()) {
  128. (List(seq, _), Int(idx)) | (Vector(seq, _), Int(idx)) => {
  129. if seq.len() <= idx as usize {
  130. return error("nth: index out of range");
  131. }
  132. Ok(seq[idx as usize].clone())
  133. }
  134. _ => error("invalid args to nth"),
  135. }
  136. }
  137. fn first(a: MalArgs) -> MalRet {
  138. match a[0].clone() {
  139. List(ref seq, _) | Vector(ref seq, _) if seq.len() == 0 => Ok(Nil),
  140. List(ref seq, _) | Vector(ref seq, _) => Ok(seq[0].clone()),
  141. Nil => Ok(Nil),
  142. _ => error("invalid args to first"),
  143. }
  144. }
  145. fn rest(a: MalArgs) -> MalRet {
  146. match a[0].clone() {
  147. List(ref seq, _) | Vector(ref seq, _) => {
  148. if seq.len() > 1 {
  149. Ok(list!(seq[1..].to_vec()))
  150. } else {
  151. Ok(list![])
  152. }
  153. }
  154. Nil => Ok(list![]),
  155. _ => error("invalid args to first"),
  156. }
  157. }
  158. fn apply(a: MalArgs) -> MalRet {
  159. match a[a.len() - 1] {
  160. List(ref v, _) | Vector(ref v, _) => {
  161. let f = &a[0];
  162. let mut fargs = a[1..a.len() - 1].to_vec();
  163. fargs.extend_from_slice(&v);
  164. f.apply(fargs)
  165. }
  166. _ => error("apply called with non-seq"),
  167. }
  168. }
  169. fn map(a: MalArgs) -> MalRet {
  170. match a[1] {
  171. List(ref v, _) | Vector(ref v, _) => {
  172. let mut res = vec![];
  173. for mv in v.iter() {
  174. res.push(a[0].apply(vec![mv.clone()])?)
  175. }
  176. Ok(list!(res))
  177. }
  178. _ => error("map called with non-seq"),
  179. }
  180. }
  181. fn conj(a: MalArgs) -> MalRet {
  182. match a[0] {
  183. List(ref v, _) => {
  184. let sl = a[1..]
  185. .iter()
  186. .rev()
  187. .map(|a| a.clone())
  188. .collect::<Vec<MalVal>>();
  189. Ok(list!([&sl[..], v].concat()))
  190. }
  191. Vector(ref v, _) => Ok(vector!([v, &a[1..]].concat())),
  192. _ => error("conj: called with non-seq"),
  193. }
  194. }
  195. fn seq(a: MalArgs) -> MalRet {
  196. match a[0] {
  197. List(ref v, _) | Vector(ref v, _) if v.len() == 0 => Ok(Nil),
  198. List(ref v, _) | Vector(ref v, _) => Ok(list!(v.to_vec())),
  199. Str(ref s) if s.len() == 0 => Ok(Nil),
  200. Str(ref s) if !a[0].keyword_q() => {
  201. Ok(list!(s.chars().map(|c| { Str(c.to_string()) }).collect()))
  202. }
  203. Nil => Ok(Nil),
  204. _ => error("seq: called with non-seq"),
  205. }
  206. }
  207. pub fn ns() -> Vec<(&'static str, MalVal)> {
  208. vec![
  209. ("=", func(|a| Ok(Bool(a[0] == a[1])))),
  210. ("throw", func(|a| Err(ErrMalVal(a[0].clone())))),
  211. ("nil?", func(fn_is_type!(Nil))),
  212. ("true?", func(fn_is_type!(Bool(true)))),
  213. ("false?", func(fn_is_type!(Bool(false)))),
  214. ("symbol", func(symbol)),
  215. ("symbol?", func(fn_is_type!(Sym(_)))),
  216. (
  217. "string?",
  218. func(fn_is_type!(Str(ref s) if !s.starts_with("\u{29e}"))),
  219. ),
  220. ("keyword", func(|a| a[0].keyword())),
  221. (
  222. "keyword?",
  223. func(fn_is_type!(Str(ref s) if s.starts_with("\u{29e}"))),
  224. ),
  225. ("number?", func(fn_is_type!(Int(_)))),
  226. (
  227. "fn?",
  228. func(fn_is_type!(MalFunc{is_macro,..} if !is_macro,Func(_,_))),
  229. ),
  230. (
  231. "macro?",
  232. func(fn_is_type!(MalFunc{is_macro,..} if is_macro)),
  233. ),
  234. ("pr-str", func(|a| Ok(Str(pr_seq(&a, true, "", "", " "))))),
  235. ("str", func(|a| Ok(Str(pr_seq(&a, false, "", "", ""))))),
  236. (
  237. "prn",
  238. func(|a| {
  239. println!("{}", pr_seq(&a, true, "", "", " "));
  240. Ok(Nil)
  241. }),
  242. ),
  243. (
  244. "println",
  245. func(|a| {
  246. println!("{}", pr_seq(&a, false, "", "", " "));
  247. Ok(Nil)
  248. }),
  249. ),
  250. ("read-string", func(fn_str!(|s| { read_str(s) }))),
  251. ("slurp", func(fn_str!(|f| { slurp(f) }))),
  252. ("<", func(fn_t_int_int!(Bool, |i, j| { i < j }))),
  253. ("<=", func(fn_t_int_int!(Bool, |i, j| { i <= j }))),
  254. (">", func(fn_t_int_int!(Bool, |i, j| { i > j }))),
  255. (">=", func(fn_t_int_int!(Bool, |i, j| { i >= j }))),
  256. ("+", func(fn_t_int_int!(Int, |i, j| { i + j }))),
  257. ("-", func(fn_t_int_int!(Int, |i, j| { i - j }))),
  258. ("*", func(fn_t_int_int!(Int, |i, j| { i * j }))),
  259. ("/", func(fn_t_int_int!(Int, |i, j| { i / j }))),
  260. ("time-ms", func(time_ms)),
  261. ("sequential?", func(fn_is_type!(List(_, _), Vector(_, _)))),
  262. ("list", func(|a| Ok(list!(a)))),
  263. ("list?", func(fn_is_type!(List(_, _)))),
  264. ("vector", func(|a| Ok(vector!(a)))),
  265. ("vector?", func(fn_is_type!(Vector(_, _)))),
  266. ("hash-map", func(|a| hash_map(a))),
  267. ("map?", func(fn_is_type!(Hash(_, _)))),
  268. ("assoc", func(assoc)),
  269. ("dissoc", func(dissoc)),
  270. ("get", func(get)),
  271. ("contains?", func(contains_q)),
  272. ("keys", func(keys)),
  273. ("vals", func(vals)),
  274. ("vec", func(vec)),
  275. ("cons", func(cons)),
  276. ("concat", func(concat)),
  277. ("empty?", func(|a| a[0].empty_q())),
  278. ("nth", func(nth)),
  279. ("first", func(first)),
  280. ("rest", func(rest)),
  281. ("count", func(|a| a[0].count())),
  282. ("apply", func(apply)),
  283. ("map", func(map)),
  284. ("conj", func(conj)),
  285. ("seq", func(seq)),
  286. ("meta", func(|a| a[0].get_meta())),
  287. ("with-meta", func(|a| a[0].clone().with_meta(&a[1]))),
  288. ("atom", func(|a| Ok(atom(&a[0])))),
  289. ("atom?", func(fn_is_type!(Atom(_)))),
  290. ("deref", func(|a| a[0].deref())),
  291. ("reset!", func(|a| a[0].reset_bang(&a[1]))),
  292. ("swap!", func(|a| a[0].swap_bang(&a[1..].to_vec()))),
  293. ]
  294. }