types.rs 7.4 KB

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