core.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. use std::fs::File;
  2. use std::io::Read;
  3. use std::rc::Rc;
  4. use std::sync::Mutex;
  5. use std::time::{SystemTime, UNIX_EPOCH};
  6. use crate::printer::pr_seq;
  7. use crate::reader::read_str;
  8. use crate::types::MalErr::ErrMalVal;
  9. use crate::types::MalVal::{
  10. Add, Atom, Bool, Func, Hash, Int, Lc0, List, MalFunc, Nil, Str, Sub, Sym, Vector,
  11. };
  12. use crate::types::{MalArgs, MalRet, MalVal, _assoc, _dissoc, atom, error, func, hash_map};
  13. use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError};
  14. use bls12_381::Bls12;
  15. use bls12_381::Scalar;
  16. use ff::{Field, PrimeField};
  17. use rand::rngs::OsRng;
  18. use sapvi::bls_extensions::BlsStringConversion;
  19. use sapvi::error::{Error, Result};
  20. use sapvi::serial::{Decodable, Encodable};
  21. use sapvi::vm::{
  22. AllocType, ConstraintInstruction, CryptoOperation, VariableIndex, VariableRef, ZKVMCircuit,
  23. ZKVirtualMachine,
  24. };
  25. use std::ops::{AddAssign, MulAssign, SubAssign};
  26. use std::time::Instant;
  27. macro_rules! fn_t_int_int {
  28. ($ret:ident, $fn:expr) => {{
  29. |a: MalArgs| match (a[0].clone(), a[1].clone()) {
  30. (Int(a0), Int(a1)) => Ok($ret($fn(a0, a1))),
  31. _ => error("expecting (int,int) args"),
  32. }
  33. }};
  34. }
  35. macro_rules! fn_is_type {
  36. ($($ps:pat),*) => {{
  37. |a:MalArgs| { Ok(Bool(match a[0] { $($ps => true,)* _ => false})) }
  38. }};
  39. ($p:pat if $e:expr) => {{
  40. |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, _ => false})) }
  41. }};
  42. ($p:pat if $e:expr,$($ps:pat),*) => {{
  43. |a:MalArgs| { Ok(Bool(match a[0] { $p if $e => true, $($ps => true,)* _ => false})) }
  44. }};
  45. }
  46. macro_rules! fn_str {
  47. ($fn:expr) => {{
  48. |a: MalArgs| match a[0].clone() {
  49. Str(a0) => $fn(a0),
  50. _ => error("expecting (str) arg"),
  51. }
  52. }};
  53. }
  54. fn symbol(a: MalArgs) -> MalRet {
  55. match a[0] {
  56. Str(ref s) => Ok(Sym(s.to_string())),
  57. _ => error("illegal symbol call"),
  58. }
  59. }
  60. fn slurp(f: String) -> MalRet {
  61. let mut s = String::new();
  62. match File::open(f).and_then(|mut f| f.read_to_string(&mut s)) {
  63. Ok(_) => Ok(Str(s)),
  64. Err(e) => error(&e.to_string()),
  65. }
  66. }
  67. fn time_ms(_a: MalArgs) -> MalRet {
  68. let ms_e = match SystemTime::now().duration_since(UNIX_EPOCH) {
  69. Ok(d) => d,
  70. Err(e) => return error(&format!("{:?}", e)),
  71. };
  72. Ok(Int(
  73. ms_e.as_secs() as i64 * 1000 + ms_e.subsec_nanos() as i64 / 1_000_000
  74. ))
  75. }
  76. fn get(a: MalArgs) -> MalRet {
  77. match (a[0].clone(), a[1].clone()) {
  78. (Nil, _) => Ok(Nil),
  79. (Hash(ref hm, _), Str(ref s)) => match hm.get(s) {
  80. Some(mv) => Ok(mv.clone()),
  81. None => Ok(Nil),
  82. },
  83. _ => error("illegal get args"),
  84. }
  85. }
  86. fn assoc(a: MalArgs) -> MalRet {
  87. match a[0] {
  88. Hash(ref hm, _) => _assoc((**hm).clone(), a[1..].to_vec()),
  89. _ => error("assoc on non-Hash Map"),
  90. }
  91. }
  92. fn dissoc(a: MalArgs) -> MalRet {
  93. match a[0] {
  94. Hash(ref hm, _) => _dissoc((**hm).clone(), a[1..].to_vec()),
  95. _ => error("dissoc on non-Hash Map"),
  96. }
  97. }
  98. fn contains_q(a: MalArgs) -> MalRet {
  99. match (a[0].clone(), a[1].clone()) {
  100. (Hash(ref hm, _), Str(ref s)) => Ok(Bool(hm.contains_key(s))),
  101. _ => error("illegal get args"),
  102. }
  103. }
  104. fn keys(a: MalArgs) -> MalRet {
  105. match a[0] {
  106. Hash(ref hm, _) => Ok(list!(hm.keys().map(|k| { Str(k.to_string()) }).collect())),
  107. _ => error("keys requires Hash Map"),
  108. }
  109. }
  110. fn vals(a: MalArgs) -> MalRet {
  111. match a[0] {
  112. Hash(ref hm, _) => Ok(list!(hm.values().map(|v| { v.clone() }).collect())),
  113. _ => error("keys requires Hash Map"),
  114. }
  115. }
  116. fn vec(a: MalArgs) -> MalRet {
  117. match a[0] {
  118. List(ref v, _) | Vector(ref v, _) => Ok(vector!(v.to_vec())),
  119. _ => error("non-seq passed to vec"),
  120. }
  121. }
  122. fn cons(a: MalArgs) -> MalRet {
  123. match a[1].clone() {
  124. List(v, _) | Vector(v, _) => {
  125. let mut new_v = vec![a[0].clone()];
  126. new_v.extend_from_slice(&v);
  127. Ok(list!(new_v.to_vec()))
  128. }
  129. _ => error("cons expects seq as second arg"),
  130. }
  131. }
  132. fn concat(a: MalArgs) -> MalRet {
  133. let mut new_v = vec![];
  134. for seq in a.iter() {
  135. match seq {
  136. List(v, _) | Vector(v, _) => new_v.extend_from_slice(v),
  137. _ => return error("non-seq passed to concat"),
  138. }
  139. }
  140. Ok(list!(new_v.to_vec()))
  141. }
  142. fn nth(a: MalArgs) -> MalRet {
  143. match (a[0].clone(), a[1].clone()) {
  144. (List(seq, _), Int(idx)) | (Vector(seq, _), Int(idx)) => {
  145. if seq.len() <= idx as usize {
  146. return error("nth: index out of range");
  147. }
  148. Ok(seq[idx as usize].clone())
  149. }
  150. _ => error("invalid args to nth"),
  151. }
  152. }
  153. fn unpack_bits(a: MalArgs) -> MalRet {
  154. let mut result = vec![];
  155. match (a[0].clone()) {
  156. (Str(ref s)) => {
  157. let value = Scalar::from_string(s);
  158. for (_, bit) in value.to_le_bits().into_iter().cloned().enumerate() {
  159. match bit {
  160. true => result.push(Scalar::one()),
  161. false => result.push(Scalar::zero()),
  162. }
  163. }
  164. Ok(list!(result
  165. .iter()
  166. .map(|a| Str(std::string::ToString::to_string(&a)[2..].to_string()))
  167. .collect::<Vec<MalVal>>()))
  168. }
  169. _ => error("invalid args to unpack-bits"),
  170. }
  171. }
  172. fn first(a: MalArgs) -> MalRet {
  173. match a[0].clone() {
  174. List(ref seq, _) | Vector(ref seq, _) if seq.len() == 0 => Ok(Nil),
  175. List(ref seq, _) | Vector(ref seq, _) => Ok(seq[0].clone()),
  176. Nil => Ok(Nil),
  177. _ => error("invalid args to first"),
  178. }
  179. }
  180. fn rest(a: MalArgs) -> MalRet {
  181. match a[0].clone() {
  182. List(ref seq, _) | Vector(ref seq, _) => {
  183. if seq.len() > 1 {
  184. Ok(list!(seq[1..].to_vec()))
  185. } else {
  186. Ok(list![])
  187. }
  188. }
  189. Nil => Ok(list![]),
  190. _ => error("invalid args to first"),
  191. }
  192. }
  193. fn apply(a: MalArgs) -> MalRet {
  194. match a[a.len() - 1] {
  195. List(ref v, _) | Vector(ref v, _) => {
  196. let f = &a[0];
  197. let mut fargs = a[1..a.len() - 1].to_vec();
  198. fargs.extend_from_slice(&v);
  199. f.apply(fargs)
  200. }
  201. _ => error("apply called with non-seq"),
  202. }
  203. }
  204. fn map(a: MalArgs) -> MalRet {
  205. match a[1] {
  206. List(ref v, _) | Vector(ref v, _) => {
  207. let mut res = vec![];
  208. for mv in v.iter() {
  209. res.push(a[0].apply(vec![mv.clone()])?)
  210. }
  211. Ok(list!(res))
  212. }
  213. _ => error("map called with non-seq"),
  214. }
  215. }
  216. fn conj(a: MalArgs) -> MalRet {
  217. match a[0] {
  218. List(ref v, _) => {
  219. let sl = a[1..]
  220. .iter()
  221. .rev()
  222. .map(|a| a.clone())
  223. .collect::<Vec<MalVal>>();
  224. Ok(list!([&sl[..], v].concat()))
  225. }
  226. Vector(ref v, _) => Ok(vector!([v, &a[1..]].concat())),
  227. _ => error("conj: called with non-seq"),
  228. }
  229. }
  230. fn sub(a: MalArgs) -> MalRet {
  231. // get next symbol should be lc0 lc1 lc2
  232. Ok(Sub(Rc::new(a[0].clone()), Rc::new(a[1].clone())))
  233. }
  234. fn add(a: MalArgs) -> MalRet {
  235. // get next symbol should be lc0 lc1 lc2
  236. Ok(Add(Rc::new(a[0].clone()), Rc::new(a[1].clone())))
  237. }
  238. fn seq(a: MalArgs) -> MalRet {
  239. match a[0] {
  240. List(ref v, _) | Vector(ref v, _) if v.len() == 0 => Ok(Nil),
  241. List(ref v, _) | Vector(ref v, _) => Ok(list!(v.to_vec())),
  242. Str(ref s) if s.len() == 0 => Ok(Nil),
  243. Str(ref s) if !a[0].keyword_q() => {
  244. Ok(list!(s.chars().map(|c| { Str(c.to_string()) }).collect()))
  245. }
  246. Nil => Ok(Nil),
  247. _ => error("seq: called with non-seq"),
  248. }
  249. }
  250. pub fn ns() -> Vec<(&'static str, MalVal)> {
  251. vec![
  252. ("=", func(|a| Ok(Bool(a[0] == a[1])))),
  253. ("throw", func(|a| Err(ErrMalVal(a[0].clone())))),
  254. ("nil?", func(fn_is_type!(Nil))),
  255. ("true?", func(fn_is_type!(Bool(true)))),
  256. ("false?", func(fn_is_type!(Bool(false)))),
  257. ("symbol", func(symbol)),
  258. ("symbol?", func(fn_is_type!(Sym(_)))),
  259. (
  260. "string?",
  261. func(fn_is_type!(Str(ref s) if !s.starts_with("\u{29e}"))),
  262. ),
  263. ("keyword", func(|a| a[0].keyword())),
  264. (
  265. "keyword?",
  266. func(fn_is_type!(Str(ref s) if s.starts_with("\u{29e}"))),
  267. ),
  268. ("number?", func(fn_is_type!(Int(_)))),
  269. (
  270. "fn?",
  271. func(fn_is_type!(MalFunc{is_macro,..} if !is_macro,Func(_,_))),
  272. ),
  273. (
  274. "macro?",
  275. func(fn_is_type!(MalFunc{is_macro,..} if is_macro)),
  276. ),
  277. ("pr-str", func(|a| Ok(Str(pr_seq(&a, true, "", "", " "))))),
  278. ("str", func(|a| Ok(Str(pr_seq(&a, false, "", "", ""))))),
  279. (
  280. "prn",
  281. func(|a| {
  282. println!("{}", pr_seq(&a, true, "", "", " "));
  283. Ok(Nil)
  284. }),
  285. ),
  286. (
  287. "println",
  288. func(|a| {
  289. println!("{}", pr_seq(&a, false, "", "", " "));
  290. Ok(Nil)
  291. }),
  292. ),
  293. ("read-string", func(fn_str!(|s| { read_str(s) }))),
  294. ("slurp", func(fn_str!(|f| { slurp(f) }))),
  295. ("<", func(fn_t_int_int!(Bool, |i, j| { i < j }))),
  296. ("<=", func(fn_t_int_int!(Bool, |i, j| { i <= j }))),
  297. (">", func(fn_t_int_int!(Bool, |i, j| { i > j }))),
  298. (">=", func(fn_t_int_int!(Bool, |i, j| { i >= j }))),
  299. ("+", func(fn_t_int_int!(Int, |i, j| { i + j }))),
  300. ("-", func(fn_t_int_int!(Int, |i, j| { i - j }))),
  301. ("*", func(fn_t_int_int!(Int, |i, j| { i * j }))),
  302. ("/", func(fn_t_int_int!(Int, |i, j| { i / j }))),
  303. ("time-ms", func(time_ms)),
  304. ("sequential?", func(fn_is_type!(List(_, _), Vector(_, _)))),
  305. ("list", func(|a| Ok(list!(a)))),
  306. ("list?", func(fn_is_type!(List(_, _)))),
  307. ("vector", func(|a| Ok(vector!(a)))),
  308. ("vector?", func(fn_is_type!(Vector(_, _)))),
  309. ("hash-map", func(|a| hash_map(a))),
  310. ("map?", func(fn_is_type!(Hash(_, _)))),
  311. ("assoc", func(assoc)),
  312. ("dissoc", func(dissoc)),
  313. ("get", func(get)),
  314. ("contains?", func(contains_q)),
  315. ("keys", func(keys)),
  316. ("vals", func(vals)),
  317. ("vec", func(vec)),
  318. ("cons", func(cons)),
  319. ("concat", func(concat)),
  320. ("empty?", func(|a| a[0].empty_q())),
  321. ("nth", func(nth)),
  322. ("first", func(first)),
  323. ("rest", func(rest)),
  324. ("count", func(|a| a[0].count())),
  325. ("apply", func(apply)),
  326. ("map", func(map)),
  327. ("conj", func(conj)),
  328. ("seq", func(seq)),
  329. ("meta", func(|a| a[0].get_meta())),
  330. ("with-meta", func(|a| a[0].clone().with_meta(&a[1]))),
  331. ("atom", func(|a| Ok(atom(&a[0])))),
  332. ("atom?", func(fn_is_type!(Atom(_)))),
  333. ("deref", func(|a| a[0].deref())),
  334. ("reset!", func(|a| a[0].reset_bang(&a[1]))),
  335. ("swap!", func(|a| a[0].swap_bang(&a[1..].to_vec()))),
  336. ("unpack-bits", func(unpack_bits)),
  337. ("add", func(add)),
  338. ("sub", func(sub)),
  339. ("lc0", func(|a| Ok(MalVal::Lc0))),
  340. ("lc1", func(|a| Ok(MalVal::Lc1))),
  341. ]
  342. }