types.rs 7.3 KB

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