types.rs 7.5 KB

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