types.rs 7.3 KB

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