types.rs 6.9 KB

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