lisp.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. #![allow(non_snake_case)]
  2. use crate::types::LispCircuit;
  3. use bellman::groth16::PreparedVerifyingKey;
  4. use sapvi::{BlsStringConversion, Decodable, Encodable, ZKContract, ZKProof};
  5. use simplelog::*;
  6. use bellman::groth16;
  7. use bls12_381::Bls12;
  8. use fnv::FnvHashMap;
  9. use itertools::Itertools;
  10. use rand::rngs::OsRng;
  11. use std::{borrow::{Borrow, BorrowMut}, fs};
  12. use std::fs::File;
  13. use std::rc::Rc;
  14. use std::time::Instant;
  15. use types::EnforceAllocation;
  16. #[macro_use]
  17. extern crate clap;
  18. #[macro_use]
  19. extern crate lazy_static;
  20. extern crate fnv;
  21. extern crate itertools;
  22. extern crate regex;
  23. #[macro_use]
  24. mod types;
  25. use crate::types::MalErr::{ErrMalVal, ErrString};
  26. use crate::types::MalVal::{Bool, Enforce, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector};
  27. use crate::types::VerifyKeyParams;
  28. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  29. mod env;
  30. mod printer;
  31. mod reader;
  32. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  33. #[macro_use]
  34. mod core;
  35. // read
  36. fn read(str: &str) -> MalRet {
  37. reader::read_str(str.to_string())
  38. }
  39. // eval
  40. fn qq_iter(elts: &MalArgs) -> MalVal {
  41. let mut acc = list![];
  42. for elt in elts.iter().rev() {
  43. if let List(v, _) = elt {
  44. if v.len() == 2 {
  45. if let Sym(ref s) = v[0] {
  46. if s == "splice-unquote" {
  47. acc = list![Sym("concat".to_string()), v[1].clone(), acc];
  48. continue;
  49. }
  50. }
  51. }
  52. }
  53. acc = list![Sym("cons".to_string()), quasiquote(&elt), acc];
  54. }
  55. return acc;
  56. }
  57. fn quasiquote(ast: &MalVal) -> MalVal {
  58. match ast {
  59. List(v, _) => {
  60. if v.len() == 2 {
  61. if let Sym(ref s) = v[0] {
  62. if s == "unquote" {
  63. return v[1].clone();
  64. }
  65. }
  66. }
  67. return qq_iter(&v);
  68. }
  69. Vector(v, _) => return list![Sym("vec".to_string()), qq_iter(&v)],
  70. Hash(_, _) | Sym(_) => return list![Sym("quote".to_string()), ast.clone()],
  71. _ => ast.clone(),
  72. }
  73. }
  74. fn is_macro_call(ast: &MalVal, env: &Env) -> Option<(MalVal, MalArgs)> {
  75. match ast {
  76. List(v, _) => match v[0] {
  77. Sym(ref s) => match env_find(env, s) {
  78. Some(e) => match env_get(&e, &v[0]) {
  79. Ok(f @ MalFunc { is_macro: true, .. }) => Some((f, v[1..].to_vec())),
  80. _ => None,
  81. },
  82. _ => None,
  83. },
  84. _ => None,
  85. },
  86. _ => None,
  87. }
  88. }
  89. fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
  90. let mut was_expanded = false;
  91. while let Some((mf, args)) = is_macro_call(&ast, env) {
  92. //println!("macroexpand 1: {:?}", ast);
  93. ast = match mf.apply(args) {
  94. Err(e) => return (false, Err(e)),
  95. Ok(a) => a,
  96. };
  97. //println!("macroexpand 2: {:?}", ast);
  98. was_expanded = true;
  99. }
  100. (was_expanded, Ok(ast))
  101. }
  102. fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
  103. match ast {
  104. Sym(_) => Ok(env_get(&env, &ast)?),
  105. List(v, _) => {
  106. let mut lst: MalArgs = vec![];
  107. for a in v.iter() {
  108. lst.push(eval(a.clone(), env.clone())?)
  109. }
  110. Ok(list!(lst))
  111. }
  112. Vector(v, _) => {
  113. let mut lst: MalArgs = vec![];
  114. for a in v.iter() {
  115. lst.push(eval(a.clone(), env.clone())?)
  116. }
  117. Ok(vector!(lst))
  118. }
  119. Hash(hm, _) => {
  120. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  121. for (k, v) in hm.iter() {
  122. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  123. }
  124. Ok(Hash(Rc::new(new_hm), Rc::new(Nil)))
  125. }
  126. _ => Ok(ast.clone()),
  127. }
  128. }
  129. fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
  130. let ret: MalRet;
  131. 'tco: loop {
  132. ret = match ast.clone() {
  133. List(l, _) => {
  134. if l.len() == 0 {
  135. return Ok(ast);
  136. }
  137. match macroexpand(ast.clone(), &env) {
  138. (true, Ok(new_ast)) => {
  139. ast = new_ast;
  140. continue 'tco;
  141. }
  142. (_, Err(e)) => return Err(e),
  143. _ => (),
  144. }
  145. if l.len() == 0 {
  146. return Ok(ast);
  147. }
  148. let a0 = &l[0];
  149. match a0 {
  150. Sym(ref a0sym) if a0sym == "def!" => {
  151. env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
  152. }
  153. Sym(ref a0sym) if a0sym == "zk*" => {
  154. println!("zk* {:?}", l[1]);
  155. let (a1, a2) = (l[1].clone(), l[2].clone());
  156. match a1 {
  157. List(ref binds, _) | Vector(ref binds, _) => {
  158. for (b, e) in binds.iter().tuples() {
  159. match b {
  160. Sym(_) => {
  161. let _ = env_set(
  162. &env,
  163. b.clone(),
  164. eval(e.clone(), env.clone())?,
  165. );
  166. }
  167. _ => {
  168. return error("let* with non-Sym binding");
  169. }
  170. }
  171. }
  172. }
  173. _ => {
  174. return error("let* with non-List bindings");
  175. }
  176. };
  177. ast = a2;
  178. continue 'tco;
  179. }
  180. Sym(ref a0sym) if a0sym == "let*" => {
  181. env = env_new(Some(env.clone()));
  182. let (a1, a2) = (l[1].clone(), l[2].clone());
  183. match a1 {
  184. List(ref binds, _) | Vector(ref binds, _) => {
  185. for (b, e) in binds.iter().tuples() {
  186. match b {
  187. Sym(_) => {
  188. let _ = env_set(
  189. &env,
  190. b.clone(),
  191. eval(e.clone(), env.clone())?,
  192. );
  193. }
  194. _ => {
  195. return error("let* with non-Sym binding");
  196. }
  197. }
  198. }
  199. }
  200. _ => {
  201. return error("let* with non-List bindings");
  202. }
  203. };
  204. ast = a2;
  205. continue 'tco;
  206. }
  207. Sym(ref a0sym) if a0sym == "quote" => Ok(l[1].clone()),
  208. Sym(ref a0sym) if a0sym == "quasiquoteexpand" => Ok(quasiquote(&l[1])),
  209. Sym(ref a0sym) if a0sym == "quasiquote" => {
  210. ast = quasiquote(&l[1]);
  211. continue 'tco;
  212. }
  213. Sym(ref a0sym) if a0sym == "defmacro!" => {
  214. let (a1, a2) = (l[1].clone(), l[2].clone());
  215. let r = eval(a2, env.clone())?;
  216. match r {
  217. MalFunc {
  218. eval,
  219. ast,
  220. env,
  221. params,
  222. ..
  223. } => Ok(env_set(
  224. &env,
  225. a1.clone(),
  226. MalFunc {
  227. eval: eval,
  228. ast: ast.clone(),
  229. env: env.clone(),
  230. params: params.clone(),
  231. is_macro: true,
  232. meta: Rc::new(Nil),
  233. },
  234. )?),
  235. _ => error("set_macro on non-function"),
  236. }
  237. }
  238. Sym(ref a0sym) if a0sym == "macroexpand" => {
  239. match macroexpand(l[1].clone(), &env) {
  240. (_, Ok(new_ast)) => Ok(new_ast),
  241. (_, e) => return e,
  242. }
  243. }
  244. Sym(ref a0sym) if a0sym == "try*" => match eval(l[1].clone(), env.clone()) {
  245. Err(ref e) if l.len() >= 3 => {
  246. let exc = match e {
  247. ErrMalVal(mv) => mv.clone(),
  248. ErrString(s) => Str(s.to_string()),
  249. };
  250. match l[2].clone() {
  251. List(c, _) => {
  252. let catch_env = env_bind(
  253. Some(env.clone()),
  254. list!(vec![c[1].clone()]),
  255. vec![exc],
  256. )?;
  257. eval(c[2].clone(), catch_env)
  258. }
  259. _ => error("invalid catch block"),
  260. }
  261. }
  262. res => res,
  263. },
  264. Sym(ref a0sym) if a0sym == "do" => {
  265. match eval_ast(&list!(l[1..l.len() - 1].to_vec()), &env)? {
  266. List(_, _) => {
  267. ast = l.last().unwrap_or(&Nil).clone();
  268. continue 'tco;
  269. }
  270. _ => error("invalid do form"),
  271. }
  272. }
  273. Sym(ref a0sym) if a0sym == "if" => {
  274. let cond = eval(l[1].clone(), env.clone())?;
  275. match cond {
  276. Bool(false) | Nil if l.len() >= 4 => {
  277. ast = l[3].clone();
  278. continue 'tco;
  279. }
  280. Bool(false) | Nil => Ok(Nil),
  281. _ if l.len() >= 3 => {
  282. ast = l[2].clone();
  283. continue 'tco;
  284. }
  285. _ => Ok(Nil),
  286. }
  287. }
  288. Sym(ref a0sym) if a0sym == "fn*" => {
  289. let (a1, a2) = (l[1].clone(), l[2].clone());
  290. Ok(MalFunc {
  291. eval: eval,
  292. ast: Rc::new(a2),
  293. env: env,
  294. params: Rc::new(a1),
  295. is_macro: false,
  296. meta: Rc::new(Nil),
  297. })
  298. }
  299. Sym(ref a0sym) if a0sym == "eval" => {
  300. ast = eval(l[1].clone(), env.clone())?;
  301. while let Some(ref e) = env.clone().outer {
  302. env = e.clone();
  303. }
  304. continue 'tco;
  305. }
  306. Sym(ref a0sym) if a0sym == "setup" => {
  307. let a1 = l[1].clone();
  308. // todo
  309. ast = eval(a1.clone(), env.clone())?;
  310. // let _pvk = setup(a1.clone(), env.clone())?;
  311. continue 'tco;
  312. }
  313. Sym(ref a0sym) if a0sym == "prove" => {
  314. let a1 = l[1].clone();
  315. ast = eval(a1.clone(), env.clone())?;
  316. prove(a1.clone(), env.clone())
  317. }
  318. Sym(ref a0sym) if a0sym == "alloc-const" => {
  319. let a1 = l[1].clone();
  320. let value = eval(l[2].clone(), env.clone())?;
  321. let result = eval(value.clone(), env.clone())?;
  322. let allocs = get_allocations(&env, "AllocationsConst");
  323. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  324. for (k, v) in allocs.iter() {
  325. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  326. }
  327. new_hm.insert(a1.pr_str(false), result.clone());
  328. env_set(
  329. &env,
  330. Sym("AllocationsConst".to_string()),
  331. Hash(Rc::new(new_hm), Rc::new(Nil)),
  332. )?;
  333. Ok(result.clone())
  334. }
  335. Sym(ref a0sym) if a0sym == "alloc-input" => {
  336. let a1 = l[1].clone();
  337. let value = eval(l[2].clone(), env.clone())?;
  338. let result = eval(value.clone(), env.clone())?;
  339. let allocs = get_allocations(&env, "AllocationsInput");
  340. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  341. for (k, v) in allocs.iter() {
  342. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  343. }
  344. new_hm.insert(a1.pr_str(false), result.clone());
  345. env_set(
  346. &env,
  347. Sym("AllocationsInput".to_string()),
  348. Hash(Rc::new(new_hm), Rc::new(Nil)),
  349. )?;
  350. Ok(result.clone())
  351. }
  352. Sym(ref a0sym) if a0sym == "alloc" => {
  353. let a1 = l[1].clone();
  354. let value = eval(l[2].clone(), env.clone())?;
  355. let result = eval(value.clone(), env.clone())?;
  356. let allocs = get_allocations(&env, "Allocations");
  357. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  358. for (k, v) in allocs.iter() {
  359. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  360. }
  361. new_hm.insert(a1.pr_str(false), result.clone());
  362. // TODO change it
  363. if let Some(e) = &env.outer {
  364. env_set(
  365. &e,
  366. Sym("Allocations".to_string()),
  367. Hash(Rc::new(new_hm), Rc::new(Nil)),
  368. )?;
  369. } else {
  370. env_set(
  371. &env,
  372. Sym("Allocations".to_string()),
  373. Hash(Rc::new(new_hm), Rc::new(Nil)),
  374. )?;
  375. }
  376. Ok(result.clone())
  377. }
  378. //Sym(ref a0sym) if a0sym == "verify" => {
  379. Sym(ref a0sym) if a0sym == "enforce" => {
  380. // here i'm considering that we always have tuple with only two elements
  381. // also it's important to keep in mind for the sake of brevity of this v0
  382. // we will not allow calculation or any lisp evaluations inside the enforce
  383. // it means that every symbol will be on allocations and we will do the
  384. // find/replace on the bellman circuit, it's nasty v0
  385. let mut left_vec = vec![];
  386. let mut right_vec = vec![];
  387. let mut out_vec = vec![];
  388. // todo extract a macro for this
  389. match l[1].clone() {
  390. List(v, _) | Vector(v, _) => {
  391. if let List(_, _) = &v.to_vec()[0] {
  392. for ele in v.to_vec().iter() {
  393. if let List(ele_vec, _) = ele {
  394. left_vec.push((
  395. ele_vec[0].pr_str(false),
  396. ele_vec[1].pr_str(false),
  397. ));
  398. }
  399. }
  400. } else {
  401. left_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  402. }
  403. }
  404. _ => {}
  405. };
  406. match l[2].clone() {
  407. List(v, _) | Vector(v, _) => {
  408. if let List(_, _) = &v.to_vec()[0] {
  409. for ele in v.to_vec().iter() {
  410. if let List(ele_vec, _) = ele {
  411. right_vec.push((
  412. ele_vec[0].pr_str(false),
  413. ele_vec[1].pr_str(false),
  414. ));
  415. }
  416. }
  417. } else {
  418. right_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  419. }
  420. }
  421. _ => {}
  422. };
  423. match l[3].clone() {
  424. List(v, _) | Vector(v, _) => {
  425. if let List(_, _) = &v.to_vec()[0] {
  426. for ele in v.to_vec().iter() {
  427. if let List(ele_vec, _) = ele {
  428. out_vec.push((
  429. ele_vec[0].pr_str(false),
  430. ele_vec[1].pr_str(false),
  431. ));
  432. }
  433. }
  434. } else {
  435. out_vec.push((v[0].pr_str(false), v[1].pr_str(false)));
  436. }
  437. }
  438. _ => {}
  439. };
  440. let enforce_vec = get_enforce_allocs(&env);
  441. let enforce = EnforceAllocation {
  442. idx: enforce_vec.len() + 1,
  443. left: left_vec,
  444. right: right_vec,
  445. output: out_vec,
  446. };
  447. let mut new_vec: Vec<EnforceAllocation> = vec![enforce];
  448. for value in enforce_vec.iter() {
  449. new_vec.push(value.clone());
  450. }
  451. // TODO change it
  452. if let Some(e) = &env.outer {
  453. env_set(
  454. &e,
  455. Sym("AllocationsEnforce".to_string()),
  456. vector![vec![Enforce(Rc::new(new_vec.clone()))]],
  457. )?;
  458. } else {
  459. env_set(
  460. &env,
  461. Sym("AllocationsEnforce".to_string()),
  462. vector![vec![Enforce(Rc::new(new_vec.clone()))]],
  463. )?;
  464. }
  465. Ok(MalVal::Nil)
  466. }
  467. _ => match eval_ast(&ast, &env)? {
  468. List(ref el, _) => {
  469. let ref f = el[0].clone();
  470. let args = el[1..].to_vec();
  471. match f {
  472. Func(_, _) => f.apply(args),
  473. MalFunc {
  474. ast: mast,
  475. env: menv,
  476. params,
  477. ..
  478. } => {
  479. let a = &**mast;
  480. let p = &**params;
  481. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  482. ast = a.clone();
  483. continue 'tco;
  484. }
  485. _ => {
  486. println!("{:?}", args);
  487. Ok(vector![el.to_vec()])
  488. //error("call non-function")
  489. }
  490. }
  491. }
  492. _ => error("expected a list"),
  493. },
  494. }
  495. }
  496. _ => eval_ast(&ast, &env),
  497. };
  498. break;
  499. } // end 'tco loop
  500. ret
  501. }
  502. pub fn get_enforce_allocs(env: &Env) -> Vec<EnforceAllocation> {
  503. if let Some(e) = &env.outer {
  504. get_enforce_allocs_nested(&e)
  505. } else {
  506. get_enforce_allocs_nested(&env)
  507. }
  508. }
  509. pub fn get_enforce_allocs_nested(env: &Env) -> Vec<EnforceAllocation> {
  510. match env_find(env, "AllocationsEnforce") {
  511. Some(e) => match env_get(&e, &Sym("AllocationsEnforce".to_string())) {
  512. Ok(f) => {
  513. if let Vector(val, _) = f {
  514. if let Enforce(ret) = &val[0] {
  515. ret.to_vec()
  516. } else {
  517. vec![]
  518. }
  519. } else {
  520. vec![]
  521. }
  522. }
  523. _ => vec![],
  524. },
  525. _ => vec![],
  526. }
  527. }
  528. pub fn get_allocations(env: &Env, key: &str) -> Rc<FnvHashMap<String, MalVal>> {
  529. if let Some(e) = &env.outer {
  530. get_allocations_nested(&e, key)
  531. } else {
  532. get_allocations_nested(&env, key)
  533. }
  534. }
  535. pub fn get_allocations_nested(env: &Env, key: &str) -> Rc<FnvHashMap<String, MalVal>> {
  536. let alloc_hm: Rc<FnvHashMap<String, MalVal>> = Rc::new(FnvHashMap::default());
  537. if let Some(e) = &env.outer {
  538. }
  539. match env_find(env, key) {
  540. Some(e) => match env_get(&e, &Sym(key.to_string())) {
  541. Ok(f) => {
  542. if let Hash(allocs, _) = f {
  543. allocs
  544. } else {
  545. alloc_hm
  546. }
  547. }
  548. _ => alloc_hm,
  549. },
  550. _ => alloc_hm,
  551. }
  552. }
  553. pub fn setup(_ast: MalVal, env: Env) -> Result<VerifyKeyParams, MalErr> {
  554. let start = Instant::now();
  555. let c = LispCircuit {
  556. params: FnvHashMap::default(),
  557. allocs: FnvHashMap::default(),
  558. alloc_inputs: FnvHashMap::default(),
  559. constraints: Vec::new(),
  560. };
  561. let random_parameters =
  562. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap();
  563. let pvk = groth16::prepare_verifying_key(&random_parameters.vk);
  564. println!("Setup: [{:?}]", start.elapsed());
  565. Ok(VerifyKeyParams {
  566. verifying_key: pvk,
  567. random_params: random_parameters,
  568. })
  569. }
  570. pub fn prove(_ast: MalVal, env: Env) -> MalRet {
  571. // let start = Instant::now();
  572. let allocs_input = get_allocations(&env, "AllocationsInput");
  573. let allocs = get_allocations(&env, "Allocations");
  574. let enforce_allocs = get_enforce_allocs(&env);
  575. let allocs_const = get_allocations(&env, "AllocationsConst");
  576. //setup
  577. let params = Some({
  578. let circuit = LispCircuit {
  579. params: allocs_const.as_ref().clone(),
  580. allocs: allocs.as_ref().clone(),
  581. alloc_inputs: allocs_input.as_ref().clone(),
  582. constraints: enforce_allocs.clone(),
  583. };
  584. groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng)?
  585. });
  586. let verifying_key = Some(groth16::prepare_verifying_key(&params.as_ref().unwrap().vk));
  587. // prove
  588. let circuit = LispCircuit {
  589. params: allocs_const.as_ref().clone(),
  590. allocs: allocs.as_ref().clone(),
  591. alloc_inputs: allocs_input.as_ref().clone(),
  592. constraints: enforce_allocs.clone(),
  593. };
  594. let proof = groth16::create_random_proof(circuit, params.as_ref().unwrap(), &mut OsRng)?;
  595. let mut vec_input = vec![];
  596. for (k, val) in allocs_input.iter() {
  597. match val {
  598. MalVal::Str(v) => {
  599. vec_input.push(bls12_381::Scalar::from_string(&v.to_string()));
  600. }
  601. MalVal::ZKScalar(v) => {
  602. vec_input.push(bls12_381::Scalar::from(*v));
  603. }
  604. _ => {}
  605. };
  606. }
  607. let result = groth16::verify_proof(verifying_key.as_ref().unwrap(), &proof, &vec_input);
  608. println!("vec public {:?}", vec_input);
  609. println!("result {:?}", result);
  610. Ok(MalVal::Nil)
  611. }
  612. pub fn verify(_ast: &MalVal) -> MalRet {
  613. let _public_input = vec![bls12_381::Scalar::from(27)];
  614. let start = Instant::now();
  615. println!("Verify: [{:?}]", start.elapsed());
  616. Ok(MalVal::Nil)
  617. }
  618. // print
  619. fn print(ast: &MalVal) -> String {
  620. ast.pr_str(true)
  621. }
  622. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  623. let ast = read(str)?;
  624. let exp = eval(ast, env.clone())?;
  625. Ok(print(&exp))
  626. }
  627. fn main() -> Result<(), ()> {
  628. let matches = clap_app!(zklisp =>
  629. (version: "0.1.0")
  630. (author: "mileschet <miles.chet@gmail.com>")
  631. (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
  632. (@subcommand load =>
  633. (about: "Load the file into the interpreter")
  634. (@arg FILE: +required "Lisp Contract filename")
  635. )
  636. )
  637. .get_matches();
  638. // CombinedLogger::init(vec![TermLogger::new(
  639. // LevelFilter::Debug,
  640. // Config::default(),
  641. // TerminalMode::Mixed,
  642. // )
  643. // .unwrap()])
  644. // .unwrap();
  645. match matches.subcommand() {
  646. Some(("load", matches)) => {
  647. let file: String = matches.value_of("FILE").unwrap().parse().unwrap();
  648. repl_load(file)?;
  649. }
  650. _ => {
  651. eprintln!("error: Invalid subcommand invoked");
  652. std::process::exit(-1);
  653. }
  654. }
  655. Ok(())
  656. }
  657. fn repl_load(file: String) -> Result<(), ()> {
  658. let repl_env = env_new(None);
  659. for (k, v) in core::ns() {
  660. env_sets(&repl_env, k, v);
  661. }
  662. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  663. let _ = rep(
  664. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  665. &repl_env,
  666. );
  667. //let _ = rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))", &repl_env);
  668. match rep(&format!("(load-file \"{}\")", file), &repl_env) {
  669. Ok(_) => std::process::exit(0),
  670. Err(e) => {
  671. println!("Error: {}", format_error(e));
  672. std::process::exit(1);
  673. }
  674. }
  675. }