types.rs 6.9 KB

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