types.rs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. use std::cell::RefCell;
  2. use std::rc::Rc;
  3. //use std::collections::HashMap;
  4. use fnv::FnvHashMap;
  5. use itertools::Itertools;
  6. use crate::env::{env_bind, Env};
  7. use crate::types::MalErr::{ErrMalVal, ErrString};
  8. use crate::types::MalVal::{Atom, Bool, Func, Hash, Int, List, MalFunc, Nil, Str, Sym, Vector};
  9. #[derive(Debug, Clone)]
  10. pub enum MalVal {
  11. Nil,
  12. Bool(bool),
  13. Int(i64),
  14. //Float(f64),
  15. Str(String),
  16. Sym(String),
  17. List(Rc<Vec<MalVal>>, Rc<MalVal>),
  18. Vector(Rc<Vec<MalVal>>, Rc<MalVal>),
  19. Hash(Rc<FnvHashMap<String, MalVal>>, Rc<MalVal>),
  20. Func(fn(MalArgs) -> MalRet, Rc<MalVal>),
  21. MalFunc {
  22. eval: fn(ast: MalVal, env: Env) -> MalRet,
  23. ast: Rc<MalVal>,
  24. env: Env,
  25. params: Rc<MalVal>,
  26. is_macro: bool,
  27. meta: Rc<MalVal>,
  28. },
  29. Atom(Rc<RefCell<MalVal>>),
  30. }
  31. #[derive(Debug)]
  32. pub enum MalErr {
  33. ErrString(String),
  34. ErrMalVal(MalVal),
  35. }
  36. pub type MalArgs = Vec<MalVal>;
  37. pub type MalRet = Result<MalVal, MalErr>;
  38. // type utility macros
  39. macro_rules! list {
  40. ($seq:expr) => {{
  41. List(Rc::new($seq),Rc::new(Nil))
  42. }};
  43. [$($args:expr),*] => {{
  44. let v: Vec<MalVal> = vec![$($args),*];
  45. List(Rc::new(v),Rc::new(Nil))
  46. }}
  47. }
  48. macro_rules! vector {
  49. ($seq:expr) => {{
  50. Vector(Rc::new($seq),Rc::new(Nil))
  51. }};
  52. [$($args:expr),*] => {{
  53. let v: Vec<MalVal> = vec![$($args),*];
  54. Vector(Rc::new(v),Rc::new(Nil))
  55. }}
  56. }
  57. // type utility functions
  58. pub fn error(s: &str) -> MalRet {
  59. Err(ErrString(s.to_string()))
  60. }
  61. pub fn format_error(e: MalErr) -> String {
  62. match e {
  63. ErrString(s) => s.clone(),
  64. ErrMalVal(mv) => mv.pr_str(true),
  65. }
  66. }
  67. pub fn atom(mv: &MalVal) -> MalVal {
  68. Atom(Rc::new(RefCell::new(mv.clone())))
  69. }
  70. impl MalVal {
  71. pub fn keyword(&self) -> MalRet {
  72. match self {
  73. Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
  74. Str(s) => Ok(Str(format!("\u{29e}{}", s))),
  75. _ => error("invalid type for keyword"),
  76. }
  77. }
  78. pub fn empty_q(&self) -> MalRet {
  79. match self {
  80. List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
  81. Nil => Ok(Bool(true)),
  82. _ => error("invalid type for empty?"),
  83. }
  84. }
  85. pub fn count(&self) -> MalRet {
  86. match self {
  87. List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
  88. Nil => Ok(Int(0)),
  89. _ => error("invalid type for count"),
  90. }
  91. }
  92. pub fn apply(&self, args: MalArgs) -> MalRet {
  93. match *self {
  94. Func(f, _) => f(args),
  95. MalFunc {
  96. eval,
  97. ref ast,
  98. ref env,
  99. ref params,
  100. ..
  101. } => {
  102. let a = &**ast;
  103. let p = &**params;
  104. let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
  105. Ok(eval(a.clone(), fn_env)?)
  106. }
  107. _ => error("attempt to call non-function"),
  108. }
  109. }
  110. pub fn keyword_q(&self) -> bool {
  111. match self {
  112. Str(s) if s.starts_with("\u{29e}") => true,
  113. _ => false,
  114. }
  115. }
  116. pub fn deref(&self) -> MalRet {
  117. match self {
  118. Atom(a) => Ok(a.borrow().clone()),
  119. _ => error("attempt to deref a non-Atom"),
  120. }
  121. }
  122. pub fn reset_bang(&self, new: &MalVal) -> MalRet {
  123. match self {
  124. Atom(a) => {
  125. *a.borrow_mut() = new.clone();
  126. Ok(new.clone())
  127. }
  128. _ => error("attempt to reset! a non-Atom"),
  129. }
  130. }
  131. pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
  132. match self {
  133. Atom(a) => {
  134. let f = &args[0];
  135. let mut fargs = args[1..].to_vec();
  136. fargs.insert(0, a.borrow().clone());
  137. *a.borrow_mut() = f.apply(fargs)?;
  138. Ok(a.borrow().clone())
  139. }
  140. _ => error("attempt to swap! a non-Atom"),
  141. }
  142. }
  143. pub fn get_meta(&self) -> MalRet {
  144. match self {
  145. List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
  146. Func(_, meta) => Ok((&**meta).clone()),
  147. MalFunc { meta, .. } => Ok((&**meta).clone()),
  148. _ => error("meta not supported by type"),
  149. }
  150. }
  151. pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
  152. match self {
  153. List(_, ref mut meta)
  154. | Vector(_, ref mut meta)
  155. | Hash(_, ref mut meta)
  156. | Func(_, ref mut meta)
  157. | MalFunc { ref mut meta, .. } => {
  158. *meta = Rc::new((&*new_meta).clone());
  159. }
  160. _ => return error("with-meta not supported by type"),
  161. };
  162. Ok(self.clone())
  163. }
  164. }
  165. impl PartialEq for MalVal {
  166. fn eq(&self, other: &MalVal) -> bool {
  167. match (self, other) {
  168. (Nil, Nil) => true,
  169. (Bool(ref a), Bool(ref b)) => a == b,
  170. (Int(ref a), Int(ref b)) => a == b,
  171. (Str(ref a), Str(ref b)) => a == b,
  172. (Sym(ref a), Sym(ref b)) => a == b,
  173. (List(ref a, _), List(ref b, _))
  174. | (Vector(ref a, _), Vector(ref b, _))
  175. | (List(ref a, _), Vector(ref b, _))
  176. | (Vector(ref a, _), List(ref b, _)) => a == b,
  177. (Hash(ref a, _), Hash(ref b, _)) => a == b,
  178. (MalFunc { .. }, MalFunc { .. }) => false,
  179. _ => false,
  180. }
  181. }
  182. }
  183. pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
  184. Func(f, Rc::new(Nil))
  185. }
  186. pub fn _assoc(mut hm: FnvHashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
  187. if kvs.len() % 2 != 0 {
  188. return error("odd number of elements");
  189. }
  190. for (k, v) in kvs.iter().tuples() {
  191. match k {
  192. Str(s) => {
  193. hm.insert(s.to_string(), v.clone());
  194. }
  195. _ => return error("key is not string"),
  196. }
  197. }
  198. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  199. }
  200. pub fn _dissoc(mut hm: FnvHashMap<String, MalVal>, ks: MalArgs) -> MalRet {
  201. for k in ks.iter() {
  202. match k {
  203. Str(ref s) => {
  204. hm.remove(s);
  205. }
  206. _ => return error("key is not string"),
  207. }
  208. }
  209. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  210. }
  211. pub fn hash_map(kvs: MalArgs) -> MalRet {
  212. let hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  213. _assoc(hm, kvs)
  214. }