core.rs 11 KB

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