types.rs 7.6 KB

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