types.rs 7.1 KB

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