types.rs 6.9 KB

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