types.rs 6.6 KB

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