types.rs 9.2 KB

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