types.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. use bellman::groth16::PreparedVerifyingKey;
  2. use bellman::Circuit;
  3. use bellman::ConstraintSystem;
  4. use bellman::SynthesisError;
  5. use bls12_381::Bls12;
  6. use std::cell::RefCell;
  7. use std::rc::Rc;
  8. //use std::collections::HashMap;
  9. use fnv::FnvHashMap;
  10. use itertools::Itertools;
  11. use crate::env;
  12. use crate::env::{env_bind, Env};
  13. use crate::types::MalErr::{ErrMalVal, ErrString};
  14. use crate::types::MalVal::{Atom, Bool, Func, Hash, Int, List, MalFunc, Nil, Str, Sym, Vector};
  15. use bls12_381::Scalar;
  16. use sapvi::{BlsStringConversion, ConstraintInstruction};
  17. #[derive(Debug, Clone)]
  18. pub struct Allocation {
  19. pub symbol: String,
  20. pub value: Scalar,
  21. }
  22. #[derive(Debug, Clone)]
  23. pub struct EnforceAllocation {
  24. pub left: (String, String),
  25. pub right: (String, String),
  26. pub output: (String, String)
  27. }
  28. #[derive(Debug, Clone)]
  29. pub struct LispCircuit {
  30. // TODO refactor to vec
  31. pub params: Vec<Option<Scalar>>,
  32. pub allocs: Vec<Option<Allocation>>,
  33. pub alloc_inputs: Vec<Option<Allocation>>,
  34. pub constraints: Vec<Option<Scalar>>,
  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. for alloc_value in &self.allocs {
  43. // let var = cs.alloc(|| "private alloc", ||)?;
  44. // TODO use env
  45. println!("{:?}", alloc_value);
  46. }
  47. Ok(())
  48. }
  49. }
  50. #[derive(Debug, Clone)]
  51. pub enum MalVal {
  52. Nil,
  53. Bool(bool),
  54. Int(i64),
  55. Str(String),
  56. Sym(String),
  57. List(Rc<Vec<MalVal>>, Rc<MalVal>),
  58. Vector(Rc<Vec<MalVal>>, Rc<MalVal>),
  59. Hash(Rc<FnvHashMap<String, MalVal>>, Rc<MalVal>),
  60. Func(fn(MalArgs) -> MalRet, Rc<MalVal>),
  61. MalFunc {
  62. eval: fn(ast: MalVal, env: Env) -> MalRet,
  63. ast: Rc<MalVal>,
  64. env: Env,
  65. params: Rc<MalVal>,
  66. is_macro: bool,
  67. meta: Rc<MalVal>,
  68. },
  69. Atom(Rc<RefCell<MalVal>>),
  70. Zk(Rc<LispCircuit>), // TODO remote it
  71. Enforce(Rc<Vec<EnforceAllocation>>),
  72. ZKScalar(bls12_381::Scalar),
  73. }
  74. #[derive(Debug)]
  75. pub enum MalErr {
  76. ErrString(String),
  77. ErrMalVal(MalVal),
  78. }
  79. pub type MalArgs = Vec<MalVal>;
  80. pub type MalRet = Result<MalVal, MalErr>;
  81. // type utility macros
  82. macro_rules! list {
  83. ($seq:expr) => {{
  84. List(Rc::new($seq),Rc::new(Nil))
  85. }};
  86. [$($args:expr),*] => {{
  87. let v: Vec<MalVal> = vec![$($args),*];
  88. List(Rc::new(v),Rc::new(Nil))
  89. }}
  90. }
  91. macro_rules! vector {
  92. ($seq:expr) => {{
  93. Vector(Rc::new($seq),Rc::new(Nil))
  94. }};
  95. [$($args:expr),*] => {{
  96. let v: Vec<MalVal> = vec![$($args),*];
  97. Vector(Rc::new(v),Rc::new(Nil))
  98. }}
  99. }
  100. // type utility functions
  101. pub fn error(s: &str) -> MalRet {
  102. Err(ErrString(s.to_string()))
  103. }
  104. pub fn format_error(e: MalErr) -> String {
  105. match e {
  106. ErrString(s) => s.clone(),
  107. ErrMalVal(mv) => mv.pr_str(true),
  108. }
  109. }
  110. pub fn atom(mv: &MalVal) -> MalVal {
  111. Atom(Rc::new(RefCell::new(mv.clone())))
  112. }
  113. impl MalVal {
  114. pub fn keyword(&self) -> MalRet {
  115. match self {
  116. Str(s) if s.starts_with("\u{29e}") => Ok(Str(s.to_string())),
  117. Str(s) => Ok(Str(format!("\u{29e}{}", s))),
  118. _ => error("invalid type for keyword"),
  119. }
  120. }
  121. pub fn empty_q(&self) -> MalRet {
  122. match self {
  123. List(l, _) | Vector(l, _) => Ok(Bool(l.len() == 0)),
  124. Nil => Ok(Bool(true)),
  125. _ => error("invalid type for empty?"),
  126. }
  127. }
  128. pub fn count(&self) -> MalRet {
  129. match self {
  130. List(l, _) | Vector(l, _) => Ok(Int(l.len() as i64)),
  131. Nil => Ok(Int(0)),
  132. _ => error("invalid type for count"),
  133. }
  134. }
  135. pub fn apply(&self, args: MalArgs) -> MalRet {
  136. match *self {
  137. Func(f, _) => f(args),
  138. MalFunc {
  139. eval,
  140. ref ast,
  141. ref env,
  142. ref params,
  143. ..
  144. } => {
  145. let a = &**ast;
  146. let p = &**params;
  147. let fn_env = env_bind(Some(env.clone()), p.clone(), args)?;
  148. Ok(eval(a.clone(), fn_env)?)
  149. }
  150. _ => error("attempt to call non-function"),
  151. }
  152. }
  153. pub fn keyword_q(&self) -> bool {
  154. match self {
  155. Str(s) if s.starts_with("\u{29e}") => true,
  156. _ => false,
  157. }
  158. }
  159. pub fn deref(&self) -> MalRet {
  160. match self {
  161. Atom(a) => Ok(a.borrow().clone()),
  162. _ => error("attempt to deref a non-Atom"),
  163. }
  164. }
  165. pub fn reset_bang(&self, new: &MalVal) -> MalRet {
  166. match self {
  167. Atom(a) => {
  168. *a.borrow_mut() = new.clone();
  169. Ok(new.clone())
  170. }
  171. _ => error("attempt to reset! a non-Atom"),
  172. }
  173. }
  174. pub fn swap_bang(&self, args: &MalArgs) -> MalRet {
  175. match self {
  176. Atom(a) => {
  177. let f = &args[0];
  178. let mut fargs = args[1..].to_vec();
  179. fargs.insert(0, a.borrow().clone());
  180. *a.borrow_mut() = f.apply(fargs)?;
  181. Ok(a.borrow().clone())
  182. }
  183. _ => error("attempt to swap! a non-Atom"),
  184. }
  185. }
  186. pub fn get_meta(&self) -> MalRet {
  187. match self {
  188. List(_, meta) | Vector(_, meta) | Hash(_, meta) => Ok((&**meta).clone()),
  189. Func(_, meta) => Ok((&**meta).clone()),
  190. MalFunc { meta, .. } => Ok((&**meta).clone()),
  191. _ => error("meta not supported by type"),
  192. }
  193. }
  194. pub fn with_meta(&mut self, new_meta: &MalVal) -> MalRet {
  195. match self {
  196. List(_, ref mut meta)
  197. | Vector(_, ref mut meta)
  198. | Hash(_, ref mut meta)
  199. | Func(_, ref mut meta)
  200. | MalFunc { ref mut meta, .. } => {
  201. *meta = Rc::new((&*new_meta).clone());
  202. }
  203. _ => return error("with-meta not supported by type"),
  204. };
  205. Ok(self.clone())
  206. }
  207. }
  208. impl PartialEq for MalVal {
  209. fn eq(&self, other: &MalVal) -> bool {
  210. match (self, other) {
  211. (Nil, Nil) => true,
  212. (Bool(ref a), Bool(ref b)) => a == b,
  213. (Int(ref a), Int(ref b)) => a == b,
  214. (Str(ref a), Str(ref b)) => a == b,
  215. (Sym(ref a), Sym(ref b)) => a == b,
  216. (List(ref a, _), List(ref b, _))
  217. | (Vector(ref a, _), Vector(ref b, _))
  218. | (List(ref a, _), Vector(ref b, _))
  219. | (Vector(ref a, _), List(ref b, _)) => a == b,
  220. (Hash(ref a, _), Hash(ref b, _)) => a == b,
  221. (MalFunc { .. }, MalFunc { .. }) => false,
  222. _ => false,
  223. }
  224. }
  225. }
  226. pub fn func(f: fn(MalArgs) -> MalRet) -> MalVal {
  227. Func(f, Rc::new(Nil))
  228. }
  229. pub fn _assoc(mut hm: FnvHashMap<String, MalVal>, kvs: MalArgs) -> MalRet {
  230. if kvs.len() % 2 != 0 {
  231. return error("odd number of elements");
  232. }
  233. for (k, v) in kvs.iter().tuples() {
  234. match k {
  235. Str(s) => {
  236. hm.insert(s.to_string(), v.clone());
  237. }
  238. _ => return error("key is not string"),
  239. }
  240. }
  241. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  242. }
  243. pub fn _dissoc(mut hm: FnvHashMap<String, MalVal>, ks: MalArgs) -> MalRet {
  244. for k in ks.iter() {
  245. match k {
  246. Str(ref s) => {
  247. hm.remove(s);
  248. }
  249. _ => return error("key is not string"),
  250. }
  251. }
  252. Ok(Hash(Rc::new(hm), Rc::new(Nil)))
  253. }
  254. pub fn hash_map(kvs: MalArgs) -> MalRet {
  255. let hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  256. _assoc(hm, kvs)
  257. }