types.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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: FnvHashMap<String, MalVal>,
  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. println!("values {:?}", values);
  72. let (a, b) = values;
  73. let mut val_b = CS::one();
  74. if b != "cs::one" {
  75. val_b = *variables.get(b).unwrap();
  76. }
  77. if a == "scalar::one" {
  78. left = left + (coeff, val_b);
  79. } else if a == "scalar::one::neg" {
  80. left = left + (coeff.neg(), val_b);
  81. } else {
  82. if let Some(value) = self.params.get(a) {
  83. if let MalVal::ZKScalar(val) = value {
  84. left = left + (*val, val_b);
  85. }
  86. }
  87. }
  88. }
  89. for values in alloc_value.right.iter() {
  90. let (a, b) = values;
  91. let mut val_b = CS::one();
  92. if b != "cs::one" {
  93. val_b = *variables.get(b).unwrap();
  94. }
  95. if a == "scalar::one" {
  96. right = right + (coeff, val_b);
  97. } else if a == "scalar::one::neg" {
  98. right = right + (coeff.neg(), val_b);
  99. }
  100. }
  101. for values in alloc_value.output.iter() {
  102. let (a, b) = values;
  103. let mut val_b = CS::one();
  104. if b != "cs::one" {
  105. val_b = *variables.get(b).unwrap();
  106. }
  107. if a == "scalar::one" {
  108. output = output + (coeff, val_b);
  109. } else if a == "scalar::one::neg" {
  110. output = output + (coeff.neg(), val_b);
  111. }
  112. }
  113. cs.enforce(
  114. || "constraint",
  115. |_| left.clone(),
  116. |_| right.clone(),
  117. |_| output.clone(),
  118. );
  119. }
  120. Ok(())
  121. }
  122. }
  123. #[derive(Debug, Clone)]
  124. pub enum MalVal {
  125. Nil,
  126. Bool(bool),
  127. Int(i64),
  128. Str(String),
  129. Sym(String),
  130. List(Rc<Vec<MalVal>>, Rc<MalVal>),
  131. Vector(Rc<Vec<MalVal>>, Rc<MalVal>),
  132. Hash(Rc<FnvHashMap<String, MalVal>>, Rc<MalVal>),
  133. Func(fn(MalArgs) -> MalRet, Rc<MalVal>),
  134. MalFunc {
  135. eval: fn(ast: MalVal, env: Env) -> MalRet,
  136. ast: Rc<MalVal>,
  137. env: Env,
  138. params: Rc<MalVal>,
  139. is_macro: bool,
  140. meta: Rc<MalVal>,
  141. },
  142. Atom(Rc<RefCell<MalVal>>),
  143. Zk(Rc<LispCircuit>), // TODO remote it
  144. Enforce(Rc<Vec<EnforceAllocation>>),
  145. ZKScalar(bls12_381::Scalar),
  146. }
  147. #[derive(Debug)]
  148. pub enum MalErr {
  149. ErrString(String),
  150. ErrMalVal(MalVal),
  151. }
  152. pub type MalArgs = Vec<MalVal>;
  153. pub type MalRet = Result<MalVal, MalErr>;
  154. // type utility macros
  155. macro_rules! list {
  156. ($seq:expr) => {{
  157. List(Rc::new($seq),Rc::new(Nil))
  158. }};
  159. [$($args:expr),*] => {{
  160. let v: Vec<MalVal> = vec![$($args),*];
  161. List(Rc::new(v),Rc::new(Nil))
  162. }}
  163. }
  164. macro_rules! vector {
  165. ($seq:expr) => {{
  166. Vector(Rc::new($seq),Rc::new(Nil))
  167. }};
  168. [$($args:expr),*] => {{
  169. let v: Vec<MalVal> = vec![$($args),*];
  170. Vector(Rc::new(v),Rc::new(Nil))
  171. }}
  172. }
  173. // type utility functions
  174. pub fn error(s: &str) -> MalRet {
  175. Err(ErrString(s.to_string()))
  176. }
  177. pub fn format_error(e: MalErr) -> String {
  178. match e {
  179. ErrString(s) => s.clone(),
  180. ErrMalVal(mv) => mv.pr_str(true),
  181. }
  182. }
  183. pub fn atom(mv: &MalVal) -> MalVal {
  184. Atom(Rc::new(RefCell::new(mv.clone())))
  185. }
  186. impl MalVal {
  187. pub fn keyword(&self) -> MalRet {
  188. match self {
  189. Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
  190. Str(s) => Ok(Str(format!("\u{29e}{}", s))),
  191. _ => error("invalid type for keyword"),
  192. }
  193. }
  194. pub fn empty_q(&self) -> MalRet {
  195. match self {
  196. List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
  197. Nil => Ok(Bool(true)),
  198. _ => error("invalid type for empty?"),
  199. }
  200. }
  201. pub fn count(&self) -> MalRet {
  202. match self {
  203. List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
  204. Nil => Ok(Int(0)),
  205. _ => error("invalid type for count"),
  206. }
  207. }
  208. pub fn apply(&self, args: MalArgs) -> MalRet {
  209. match *self {
  210. Func(f, _) => f(args),
  211. MalFunc {
  212. eval,
  213. ref ast,
  214. ref env,
  215. ref params,
  216. ..
  217. } => {
  218. let a = &**ast;
  219. let p = &**params;
  220. let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
  221. Ok(eval(a.clone(), fn_env)?)
  222. }
  223. _ => error("attempt to call non-function"),
  224. }
  225. }
  226. pub fn keyword_q(&self) -> bool {
  227. match self {
  228. Str(s) if s.starts_with("\u{29e}") => true,
  229. _ => false,
  230. }
  231. }
  232. pub fn deref(&self) -> MalRet {
  233. match self {
  234. Atom(a) => Ok(a.borrow().clone()),
  235. _ => error("attempt to deref a non-Atom"),
  236. }
  237. }
  238. pub fn reset_bang(&self, new: &MalVal) -> MalRet {
  239. match self {
  240. Atom(a) => {
  241. *a.borrow_mut() = new.clone();
  242. Ok(new.clone())
  243. }
  244. _ => error("attempt to reset! a non-Atom"),
  245. }
  246. }
  247. pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
  248. match self {
  249. Atom(a) => {
  250. let f = &args[0];
  251. let mut fargs = args[1..].to_vec();
  252. fargs.insert(0, a.borrow().clone());
  253. *a.borrow_mut() = f.apply(fargs)?;
  254. Ok(a.borrow().clone())
  255. }
  256. _ => error("attempt to swap! a non-Atom"),
  257. }
  258. }
  259. pub fn get_meta(&self) -> MalRet {
  260. match self {
  261. List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
  262. Func(_, meta) => Ok((&**meta).clone()),
  263. MalFunc { meta, .. } => Ok((&**meta).clone()),
  264. _ => error("meta not supported by type"),
  265. }
  266. }
  267. pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
  268. match self {
  269. List(_, ref mut meta)
  270. | Vector(_, ref mut meta)
  271. | Hash(_, ref mut meta)
  272. | Func(_, ref mut meta)
  273. | MalFunc { ref mut meta, .. } => {
  274. *meta = Rc::new((&*new_meta).clone());
  275. }
  276. _ => return error("with-meta not supported by type"),
  277. };
  278. Ok(self.clone())
  279. }
  280. }
  281. impl PartialEq for MalVal {
  282. fn eq(&self, other: &MalVal) -> bool {
  283. match (self, other) {
  284. (Nil, Nil) => true,
  285. (Bool(ref a), Bool(ref b)) => a == b,
  286. (Int(ref a), Int(ref b)) => a == b,
  287. (Str(ref a), Str(ref b)) => a == b,
  288. (Sym(ref a), Sym(ref b)) => a == b,
  289. (List(ref a, _), List(ref b, _))
  290. | (Vector(ref a, _), Vector(ref b, _))
  291. | (List(ref a, _), Vector(ref b, _))
  292. | (Vector(ref a, _), List(ref b, _)) => a == b,
  293. (Hash(ref a, _), Hash(ref b, _)) => a == b,
  294. (MalFunc { .. }, MalFunc { .. }) => false,
  295. _ => false,
  296. }
  297. }
  298. }
  299. pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
  300. Func(f, Rc::new(Nil))
  301. }
  302. pub fn _assoc(mut hm: FnvHashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
  303. if kvs.len() % 2 != 0 {
  304. return error("odd number of elements");
  305. }
  306. for (k, v) in kvs.iter().tuples() {
  307. match k {
  308. Str(s) => {
  309. hm.insert(s.to_string(), v.clone());
  310. }
  311. _ => return error("key is not string"),
  312. }
  313. }
  314. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  315. }
  316. pub fn _dissoc(mut hm: FnvHashMap<String, MalVal>, ks: MalArgs) -> MalRet {
  317. for k in ks.iter() {
  318. match k {
  319. Str(ref s) => {
  320. hm.remove(s);
  321. }
  322. _ => return error("key is not string"),
  323. }
  324. }
  325. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  326. }
  327. pub fn hash_map(kvs: MalArgs) -> MalRet {
  328. let hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  329. _assoc(hm, kvs)
  330. }