types.rs 10 KB

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