types.rs 11 KB

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