types.rs 10 KB

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