types.rs 6.9 KB

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