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