types.rs 9.1 KB

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