core.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. // (unpack-bits x 256 it produces a Vec
  138. fn unpack_bits(a: MalArgs) -> MalRet {
  139. // Scalar::from_string(
  140. match (a[0].clone(), a[1].clone()) {
  141. (List(seq, _), Int(idx)) | (Vector(seq, _), Int(idx)) => {
  142. if seq.len() <= idx as usize {
  143. return error("nth: index out of range");
  144. }
  145. Ok(seq[idx as usize].clone())
  146. }
  147. _ => error("invalid args to nth"),
  148. }
  149. }
  150. fn first(a: MalArgs) -> MalRet {
  151. match a[0].clone() {
  152. List(ref seq, _) | Vector(ref seq, _) if seq.len() == 0 => Ok(Nil),
  153. List(ref seq, _) | Vector(ref seq, _) => Ok(seq[0].clone()),
  154. Nil => Ok(Nil),
  155. _ => error("invalid args to first"),
  156. }
  157. }
  158. fn rest(a: MalArgs) -> MalRet {
  159. match a[0].clone() {
  160. List(ref seq, _) | Vector(ref seq, _) => {
  161. if seq.len() > 1 {
  162. Ok(list!(seq[1..].to_vec()))
  163. } else {
  164. Ok(list![])
  165. }
  166. }
  167. Nil => Ok(list![]),
  168. _ => error("invalid args to first"),
  169. }
  170. }
  171. fn apply(a: MalArgs) -> MalRet {
  172. match a[a.len() - 1] {
  173. List(ref v, _) | Vector(ref v, _) => {
  174. let f = &a[0];
  175. let mut fargs = a[1..a.len() - 1].to_vec();
  176. fargs.extend_from_slice(&v);
  177. f.apply(fargs)
  178. }
  179. _ => error("apply called with non-seq"),
  180. }
  181. }
  182. fn map(a: MalArgs) -> MalRet {
  183. match a[1] {
  184. List(ref v, _) | Vector(ref v, _) => {
  185. let mut res = vec![];
  186. for mv in v.iter() {
  187. res.push(a[0].apply(vec![mv.clone()])?)
  188. }
  189. Ok(list!(res))
  190. }
  191. _ => error("map called with non-seq"),
  192. }
  193. }
  194. fn conj(a: MalArgs) -> MalRet {
  195. match a[0] {
  196. List(ref v, _) => {
  197. let sl = a[1..]
  198. .iter()
  199. .rev()
  200. .map(|a| a.clone())
  201. .collect::<Vec<MalVal>>();
  202. Ok(list!([&sl[..], v].concat()))
  203. }
  204. Vector(ref v, _) => Ok(vector!([v, &a[1..]].concat())),
  205. _ => error("conj: called with non-seq"),
  206. }
  207. }
  208. fn seq(a: MalArgs) -> MalRet {
  209. match a[0] {
  210. List(ref v, _) | Vector(ref v, _) if v.len() == 0 => Ok(Nil),
  211. List(ref v, _) | Vector(ref v, _) => Ok(list!(v.to_vec())),
  212. Str(ref s) if s.len() == 0 => Ok(Nil),
  213. Str(ref s) if !a[0].keyword_q() => {
  214. Ok(list!(s.chars().map(|c| { Str(c.to_string()) }).collect()))
  215. }
  216. Nil => Ok(Nil),
  217. _ => error("seq: called with non-seq"),
  218. }
  219. }
  220. pub fn ns() -> Vec<(&'static str, MalVal)> {
  221. vec![
  222. ("=", func(|a| Ok(Bool(a[0] == a[1])))),
  223. ("throw", func(|a| Err(ErrMalVal(a[0].clone())))),
  224. ("nil?", func(fn_is_type!(Nil))),
  225. ("true?", func(fn_is_type!(Bool(true)))),
  226. ("false?", func(fn_is_type!(Bool(false)))),
  227. ("symbol", func(symbol)),
  228. ("symbol?", func(fn_is_type!(Sym(_)))),
  229. (
  230. "string?",
  231. func(fn_is_type!(Str(ref s) if !s.starts_with("\u{29e}"))),
  232. ),
  233. ("keyword", func(|a| a[0].keyword())),
  234. (
  235. "keyword?",
  236. func(fn_is_type!(Str(ref s) if s.starts_with("\u{29e}"))),
  237. ),
  238. ("number?", func(fn_is_type!(Int(_)))),
  239. (
  240. "fn?",
  241. func(fn_is_type!(MalFunc{is_macro,..} if !is_macro,Func(_,_))),
  242. ),
  243. (
  244. "macro?",
  245. func(fn_is_type!(MalFunc{is_macro,..} if is_macro)),
  246. ),
  247. ("pr-str", func(|a| Ok(Str(pr_seq(&a, true, "", "", " "))))),
  248. ("str", func(|a| Ok(Str(pr_seq(&a, false, "", "", ""))))),
  249. (
  250. "prn",
  251. func(|a| {
  252. println!("{}", pr_seq(&a, true, "", "", " "));
  253. Ok(Nil)
  254. }),
  255. ),
  256. (
  257. "println",
  258. func(|a| {
  259. println!("{}", pr_seq(&a, false, "", "", " "));
  260. Ok(Nil)
  261. }),
  262. ),
  263. ("read-string", func(fn_str!(|s| { read_str(s) }))),
  264. ("slurp", func(fn_str!(|f| { slurp(f) }))),
  265. ("<", func(fn_t_int_int!(Bool, |i, j| { i < j }))),
  266. ("<=", func(fn_t_int_int!(Bool, |i, j| { i <= j }))),
  267. (">", func(fn_t_int_int!(Bool, |i, j| { i > j }))),
  268. (">=", func(fn_t_int_int!(Bool, |i, j| { i >= j }))),
  269. ("+", func(fn_t_int_int!(Int, |i, j| { i + j }))),
  270. ("-", func(fn_t_int_int!(Int, |i, j| { i - j }))),
  271. ("*", func(fn_t_int_int!(Int, |i, j| { i * j }))),
  272. ("/", func(fn_t_int_int!(Int, |i, j| { i / j }))),
  273. ("time-ms", func(time_ms)),
  274. ("sequential?", func(fn_is_type!(List(_, _), Vector(_, _)))),
  275. ("list", func(|a| Ok(list!(a)))),
  276. ("list?", func(fn_is_type!(List(_, _)))),
  277. ("vector", func(|a| Ok(vector!(a)))),
  278. ("vector?", func(fn_is_type!(Vector(_, _)))),
  279. ("hash-map", func(|a| hash_map(a))),
  280. ("map?", func(fn_is_type!(Hash(_, _)))),
  281. ("assoc", func(assoc)),
  282. ("dissoc", func(dissoc)),
  283. ("get", func(get)),
  284. ("contains?", func(contains_q)),
  285. ("keys", func(keys)),
  286. ("vals", func(vals)),
  287. ("vec", func(vec)),
  288. ("cons", func(cons)),
  289. ("concat", func(concat)),
  290. ("empty?", func(|a| a[0].empty_q())),
  291. ("nth", func(nth)),
  292. ("first", func(first)),
  293. ("rest", func(rest)),
  294. ("count", func(|a| a[0].count())),
  295. ("apply", func(apply)),
  296. ("map", func(map)),
  297. ("conj", func(conj)),
  298. ("seq", func(seq)),
  299. ("meta", func(|a| a[0].get_meta())),
  300. ("with-meta", func(|a| a[0].clone().with_meta(&a[1]))),
  301. ("atom", func(|a| Ok(atom(&a[0])))),
  302. ("atom?", func(fn_is_type!(Atom(_)))),
  303. ("deref", func(|a| a[0].deref())),
  304. ("reset!", func(|a| a[0].reset_bang(&a[1]))),
  305. ("swap!", func(|a| a[0].swap_bang(&a[1..].to_vec()))),
  306. ("unpack_bits", func(unpack_bits)),
  307. ]
  308. }