types.rs 11 KB

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