core.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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_scalar(a: MalArgs) -> MalRet {
  235. println!("{:?}", a);
  236. match (a[0].clone(), a[1].clone()) {
  237. (Sym(a0), Sym(a1)) => {
  238. println!("{:?}", a0);
  239. //let (mut s0, mut s1) = (Scalar::from_string(&a0), Scalar::from_string(&a1));
  240. //let result = s0.add_assign(&s1);
  241. //println!("{:?}", result);
  242. Ok(Str(std::string::ToString::to_string(&Scalar::one())[2..].to_string()))
  243. }
  244. _ => error("expected (scalar, scalar"),
  245. };
  246. Ok(Str(std::string::ToString::to_string(&Scalar::one())[2..].to_string()))
  247. }
  248. fn add(a: MalArgs) -> MalRet {
  249. // get next symbol should be lc0 lc1 lc2
  250. Ok(Add(Rc::new(a[0].clone()), Rc::new(a[1].clone())))
  251. }
  252. fn seq(a: MalArgs) -> MalRet {
  253. match a[0] {
  254. List(ref v, _) | Vector(ref v, _) if v.len() == 0 => Ok(Nil),
  255. List(ref v, _) | Vector(ref v, _) => Ok(list!(v.to_vec())),
  256. Str(ref s) if s.len() == 0 => Ok(Nil),
  257. Str(ref s) if !a[0].keyword_q() => {
  258. Ok(list!(s.chars().map(|c| { Str(c.to_string()) }).collect()))
  259. }
  260. Nil => Ok(Nil),
  261. _ => error("seq: called with non-seq"),
  262. }
  263. }
  264. pub fn ns() -> Vec<(&'static str, MalVal)> {
  265. vec![
  266. ("=", func(|a| Ok(Bool(a[0] == a[1])))),
  267. ("throw", func(|a| Err(ErrMalVal(a[0].clone())))),
  268. ("nil?", func(fn_is_type!(Nil))),
  269. ("true?", func(fn_is_type!(Bool(true)))),
  270. ("false?", func(fn_is_type!(Bool(false)))),
  271. ("symbol", func(symbol)),
  272. ("symbol?", func(fn_is_type!(Sym(_)))),
  273. (
  274. "string?",
  275. func(fn_is_type!(Str(ref s) if !s.starts_with("\u{29e}"))),
  276. ),
  277. ("keyword", func(|a| a[0].keyword())),
  278. (
  279. "keyword?",
  280. func(fn_is_type!(Str(ref s) if s.starts_with("\u{29e}"))),
  281. ),
  282. ("number?", func(fn_is_type!(Int(_)))),
  283. (
  284. "fn?",
  285. func(fn_is_type!(MalFunc{is_macro,..} if !is_macro,Func(_,_))),
  286. ),
  287. (
  288. "macro?",
  289. func(fn_is_type!(MalFunc{is_macro,..} if is_macro)),
  290. ),
  291. ("pr-str", func(|a| Ok(Str(pr_seq(&a, true, "", "", " "))))),
  292. ("str", func(|a| Ok(Str(pr_seq(&a, false, "", "", ""))))),
  293. (
  294. "prn",
  295. func(|a| {
  296. println!("{}", pr_seq(&a, true, "", "", " "));
  297. Ok(Nil)
  298. }),
  299. ),
  300. (
  301. "println",
  302. func(|a| {
  303. println!("{}", pr_seq(&a, false, "", "", " "));
  304. Ok(Nil)
  305. }),
  306. ),
  307. ("read-string", func(fn_str!(|s| { read_str(s) }))),
  308. ("slurp", func(fn_str!(|f| { slurp(f) }))),
  309. ("<", func(fn_t_int_int!(Bool, |i, j| { i < j }))),
  310. ("<=", func(fn_t_int_int!(Bool, |i, j| { i <= j }))),
  311. (">", func(fn_t_int_int!(Bool, |i, j| { i > j }))),
  312. (">=", func(fn_t_int_int!(Bool, |i, j| { i >= j }))),
  313. ("+", func(add_scalar)),
  314. ("-", func(fn_t_int_int!(Int, |i, j| { i - j }))),
  315. // ("*", func(mul_scalar)),
  316. ("/", func(fn_t_int_int!(Int, |i, j| { i / j }))),
  317. ("time-ms", func(time_ms)),
  318. ("i+", func(fn_t_int_int!(Int, |i, j| { i + j }))),
  319. ("i-", func(fn_t_int_int!(Int, |i, j| { i - j }))),
  320. ("i*", func(fn_t_int_int!(Int, |i, j| { i * j }))),
  321. ("i/", func(fn_t_int_int!(Int, |i, j| { i / j }))),
  322. ("time-ms", func(time_ms)),
  323. ("sequential?", func(fn_is_type!(List(_, _), Vector(_, _)))),
  324. ("list", func(|a| Ok(list!(a)))),
  325. ("list?", func(fn_is_type!(List(_, _)))),
  326. ("vector", func(|a| Ok(vector!(a)))),
  327. ("vector?", func(fn_is_type!(Vector(_, _)))),
  328. ("hash-map", func(|a| hash_map(a))),
  329. ("map?", func(fn_is_type!(Hash(_, _)))),
  330. ("assoc", func(assoc)),
  331. ("dissoc", func(dissoc)),
  332. ("get", func(get)),
  333. ("contains?", func(contains_q)),
  334. ("keys", func(keys)),
  335. ("vals", func(vals)),
  336. ("vec", func(vec)),
  337. ("cons", func(cons)),
  338. ("concat", func(concat)),
  339. ("empty?", func(|a| a[0].empty_q())),
  340. ("nth", func(nth)),
  341. ("first", func(first)),
  342. ("rest", func(rest)),
  343. ("count", func(|a| a[0].count())),
  344. ("apply", func(apply)),
  345. ("map", func(map)),
  346. ("conj", func(conj)),
  347. ("seq", func(seq)),
  348. ("meta", func(|a| a[0].get_meta())),
  349. ("with-meta", func(|a| a[0].clone().with_meta(&a[1]))),
  350. ("atom", func(|a| Ok(atom(&a[0])))),
  351. ("atom?", func(fn_is_type!(Atom(_)))),
  352. ("deref", func(|a| a[0].deref())),
  353. ("reset!", func(|a| a[0].reset_bang(&a[1]))),
  354. ("swap!", func(|a| a[0].swap_bang(&a[1..].to_vec()))),
  355. ("unpack-bits", func(unpack_bits)),
  356. ("add", func(add)),
  357. ("sub", func(sub)),
  358. ("lc0", func(|a| Ok(MalVal::Lc0))),
  359. ("lc1", func(|a| Ok(MalVal::Lc1))),
  360. ("lc2", func(|a| Ok(MalVal::Lc2))),
  361. ("enforce", func(|a| Ok(MalVal::Enforce))),
  362. ]
  363. }