lisp.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. #![allow(non_snake_case)]
  2. use sapvi::ZKVMCircuit;
  3. use sapvi::bls_extensions::BlsStringConversion;
  4. use simplelog::*;
  5. use bellman::{
  6. gadgets::{
  7. Assignment,
  8. },
  9. groth16, Circuit, ConstraintSystem, SynthesisError,
  10. };
  11. use bls12_381::Bls12;
  12. use bls12_381::Scalar;
  13. use ff::{Field, PrimeField};
  14. use rand::rngs::OsRng;
  15. use std::ops::{AddAssign, MulAssign, SubAssign};
  16. use std::time::Instant;
  17. use std::rc::Rc;
  18. //use std::collections::HashMap;
  19. use fnv::FnvHashMap;
  20. use itertools::Itertools;
  21. #[macro_use]
  22. extern crate clap;
  23. #[macro_use]
  24. extern crate lazy_static;
  25. extern crate fnv;
  26. extern crate itertools;
  27. extern crate regex;
  28. #[macro_use]
  29. mod types;
  30. use crate::types::MalErr::{ErrMalVal, ErrString};
  31. use crate::types::MalVal::{
  32. Bool, Func, Hash, List, MalFunc, Nil, Str,
  33. Sym, Vector,
  34. };
  35. use crate::types::ZKCircuit;
  36. use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
  37. mod env;
  38. mod printer;
  39. mod reader;
  40. use crate::env::{env_bind, env_find, env_get, env_new, env_set, env_sets, Env};
  41. #[macro_use]
  42. mod core;
  43. // read
  44. fn read(str: &str) -> MalRet {
  45. reader::read_str(str.to_string())
  46. }
  47. // eval
  48. fn qq_iter(elts: &MalArgs) -> MalVal {
  49. let mut acc = list![];
  50. for elt in elts.iter().rev() {
  51. if let List(v, _) = elt {
  52. if v.len() == 2 {
  53. if let Sym(ref s) = v[0] {
  54. if s == "splice-unquote" {
  55. acc = list![Sym("concat".to_string()), v[1].clone(), acc];
  56. continue;
  57. }
  58. }
  59. }
  60. }
  61. acc = list![Sym("cons".to_string()), quasiquote(&elt), acc];
  62. }
  63. return acc;
  64. }
  65. fn quasiquote(ast: &MalVal) -> MalVal {
  66. match ast {
  67. List(v, _) => {
  68. if v.len() == 2 {
  69. if let Sym(ref s) = v[0] {
  70. if s == "unquote" {
  71. return v[1].clone();
  72. }
  73. }
  74. }
  75. return qq_iter(&v);
  76. }
  77. Vector(v, _) => return list![Sym("vec".to_string()), qq_iter(&v)],
  78. Hash(_, _) | Sym(_) => return list![Sym("quote".to_string()), ast.clone()],
  79. _ => ast.clone(),
  80. }
  81. }
  82. fn is_macro_call(ast: &MalVal, env: &Env) -> Option<(MalVal, MalArgs)> {
  83. match ast {
  84. List(v, _) => match v[0] {
  85. Sym(ref s) => match env_find(env, s) {
  86. Some(e) => match env_get(&e, &v[0]) {
  87. Ok(f @ MalFunc { is_macro: true, .. }) => Some((f, v[1..].to_vec())),
  88. _ => None,
  89. },
  90. _ => None,
  91. },
  92. _ => None,
  93. },
  94. _ => None,
  95. }
  96. }
  97. fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
  98. let mut was_expanded = false;
  99. while let Some((mf, args)) = is_macro_call(&ast, env) {
  100. //println!("macroexpand 1: {:?}", ast);
  101. ast = match mf.apply(args) {
  102. Err(e) => return (false, Err(e)),
  103. Ok(a) => a,
  104. };
  105. //println!("macroexpand 2: {:?}", ast);
  106. was_expanded = true;
  107. }
  108. (was_expanded, Ok(ast))
  109. }
  110. fn eval_ast(ast: &MalVal, env: &Env) -> MalRet {
  111. match ast {
  112. Sym(_) => Ok(env_get(&env, &ast)?),
  113. List(v, _) => {
  114. let mut lst: MalArgs = vec![];
  115. for a in v.iter() {
  116. lst.push(eval(a.clone(), env.clone())?)
  117. }
  118. Ok(list!(lst))
  119. }
  120. Vector(v, _) => {
  121. let mut lst: MalArgs = vec![];
  122. for a in v.iter() {
  123. lst.push(eval(a.clone(), env.clone())?)
  124. }
  125. Ok(vector!(lst))
  126. }
  127. Hash(hm, _) => {
  128. let mut new_hm: FnvHashMap<String, MalVal> = FnvHashMap::default();
  129. for (k, v) in hm.iter() {
  130. new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
  131. }
  132. Ok(Hash(Rc::new(new_hm), Rc::new(Nil)))
  133. }
  134. _ => Ok(ast.clone()),
  135. }
  136. }
  137. fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
  138. let ret: MalRet;
  139. 'tco: loop {
  140. ret = match ast.clone() {
  141. List(l, _) => {
  142. if l.len() == 0 {
  143. return Ok(ast);
  144. }
  145. match macroexpand(ast.clone(), &env) {
  146. (true, Ok(new_ast)) => {
  147. ast = new_ast;
  148. continue 'tco;
  149. }
  150. (_, Err(e)) => return Err(e),
  151. _ => (),
  152. }
  153. if l.len() == 0 {
  154. return Ok(ast);
  155. }
  156. let a0 = &l[0];
  157. match a0 {
  158. Sym(ref a0sym) if a0sym == "def!" => {
  159. env_set(&env, l[1].clone(), eval(l[2].clone(), env.clone())?)
  160. }
  161. Sym(ref a0sym) if a0sym == "let*" => {
  162. env = env_new(Some(env.clone()));
  163. let (a1, a2) = (l[1].clone(), l[2].clone());
  164. match a1 {
  165. List(ref binds, _) | Vector(ref binds, _) => {
  166. for (b, e) in binds.iter().tuples() {
  167. match b {
  168. Sym(_) => {
  169. let _ = env_set(
  170. &env,
  171. b.clone(),
  172. eval(e.clone(), env.clone())?,
  173. );
  174. }
  175. _ => {
  176. return error("let* with non-Sym binding");
  177. }
  178. }
  179. }
  180. }
  181. _ => {
  182. return error("let* with non-List bindings");
  183. }
  184. };
  185. ast = a2;
  186. continue 'tco;
  187. }
  188. Sym(ref a0sym) if a0sym == "quote" => Ok(l[1].clone()),
  189. Sym(ref a0sym) if a0sym == "quasiquoteexpand" => Ok(quasiquote(&l[1])),
  190. Sym(ref a0sym) if a0sym == "quasiquote" => {
  191. ast = quasiquote(&l[1]);
  192. continue 'tco;
  193. }
  194. Sym(ref a0sym) if a0sym == "defmacro!" => {
  195. let (a1, a2) = (l[1].clone(), l[2].clone());
  196. let r = eval(a2, env.clone())?;
  197. match r {
  198. MalFunc {
  199. eval,
  200. ast,
  201. env,
  202. params,
  203. ..
  204. } => Ok(env_set(
  205. &env,
  206. a1.clone(),
  207. MalFunc {
  208. eval: eval,
  209. ast: ast.clone(),
  210. env: env.clone(),
  211. params: params.clone(),
  212. is_macro: true,
  213. meta: Rc::new(Nil),
  214. },
  215. )?),
  216. _ => error("set_macro on non-function"),
  217. }
  218. }
  219. Sym(ref a0sym) if a0sym == "macroexpand" => {
  220. match macroexpand(l[1].clone(), &env) {
  221. (_, Ok(new_ast)) => Ok(new_ast),
  222. (_, e) => return e,
  223. }
  224. }
  225. Sym(ref a0sym) if a0sym == "try*" => match eval(l[1].clone(), env.clone()) {
  226. Err(ref e) if l.len() >= 3 => {
  227. let exc = match e {
  228. ErrMalVal(mv) => mv.clone(),
  229. ErrString(s) => Str(s.to_string()),
  230. };
  231. match l[2].clone() {
  232. List(c, _) => {
  233. let catch_env = env_bind(
  234. Some(env.clone()),
  235. list!(vec![c[1].clone()]),
  236. vec![exc],
  237. )?;
  238. eval(c[2].clone(), catch_env)
  239. }
  240. _ => error("invalid catch block"),
  241. }
  242. }
  243. res => res,
  244. },
  245. Sym(ref a0sym) if a0sym == "do" => {
  246. match eval_ast(&list!(l[1..l.len() - 1].to_vec()), &env)? {
  247. List(_, _) => {
  248. ast = l.last().unwrap_or(&Nil).clone();
  249. continue 'tco;
  250. }
  251. _ => error("invalid do form"),
  252. }
  253. }
  254. Sym(ref a0sym) if a0sym == "if" => {
  255. let cond = eval(l[1].clone(), env.clone())?;
  256. match cond {
  257. Bool(false) | Nil if l.len() >= 4 => {
  258. ast = l[3].clone();
  259. continue 'tco;
  260. }
  261. Bool(false) | Nil => Ok(Nil),
  262. _ if l.len() >= 3 => {
  263. ast = l[2].clone();
  264. continue 'tco;
  265. }
  266. _ => Ok(Nil),
  267. }
  268. }
  269. Sym(ref a0sym) if a0sym == "setup" => {
  270. let a1 = l[1].clone();
  271. eval(a1.clone(), env.clone())
  272. }
  273. //Sym(ref a0sym) if a0sym == "prove" => {
  274. //Sym(ref a0sym) if a0sym == "verify" => {
  275. Sym(ref a0sym) if a0sym == "enforce" => {
  276. let (a1, a2) = (l[1].clone(), l[2].clone());
  277. let value = eval_ast(&a2, &env)?;
  278. match value {
  279. List(ref el, _) => {
  280. //let val = zkcons_eval(el.to_vec(), &a1, &env)?;
  281. //val.clone();
  282. println!("{:?}", el.to_vec());
  283. }
  284. _ => println!("invalid format"),
  285. }
  286. // println!("3 {:?}", eval(a1.clone(), env.clone()));
  287. env_set(&env, a1.clone(), eval(a1.clone(), env.clone())?);
  288. eval(a1.clone(), env.clone())
  289. }
  290. Sym(ref a0sym) if a0sym == "fn*" => {
  291. let (a1, a2) = (l[1].clone(), l[2].clone());
  292. Ok(MalFunc {
  293. eval: eval,
  294. ast: Rc::new(a2),
  295. env: env,
  296. params: Rc::new(a1),
  297. is_macro: false,
  298. meta: Rc::new(Nil),
  299. })
  300. }
  301. Sym(ref a0sym) if a0sym == "eval" => {
  302. ast = eval(l[1].clone(), env.clone())?;
  303. while let Some(ref e) = env.clone().outer {
  304. env = e.clone();
  305. }
  306. continue 'tco;
  307. }
  308. _ => match eval_ast(&ast, &env)? {
  309. List(ref el, _) => {
  310. let ref f = el[0].clone();
  311. let args = el[1..].to_vec();
  312. match f {
  313. Func(_, _) => f.apply(args),
  314. MalFunc {
  315. ast: mast,
  316. env: menv,
  317. params,
  318. ..
  319. } => {
  320. let a = &**mast;
  321. let p = &**params;
  322. env = env_bind(Some(menv.clone()), p.clone(), args)?;
  323. ast = a.clone();
  324. continue 'tco;
  325. }
  326. _ => {
  327. Ok(Nil)
  328. //error("call non-function")
  329. }
  330. }
  331. }
  332. _ => error("expected a list"),
  333. },
  334. }
  335. }
  336. _ => eval_ast(&ast, &env),
  337. };
  338. break;
  339. } // end 'tco loop
  340. ret
  341. }
  342. struct MyCircuit {
  343. params: Vec<Option<bls12_381::Scalar>>,
  344. }
  345. impl Circuit<bls12_381::Scalar> for MyCircuit {
  346. fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>(
  347. self,
  348. cs: &mut CS,
  349. ) -> Result<(), SynthesisError> {
  350. Ok(())
  351. }
  352. }
  353. pub fn setup(ast: &MalVal) -> MalRet {
  354. let start = Instant::now();
  355. // Create parameters for our circuit. In a production deployment these would
  356. // be generated securely using a multiparty computation.
  357. let params = {
  358. let c = MyCircuit { params: vec![None] };
  359. groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap()
  360. };
  361. println!("Setup: [{:?}]", start.elapsed());
  362. // Prepare the verification key (for proof verification).
  363. let pvk = groth16::prepare_verifying_key(&params.vk);
  364. Ok(MalVal::Str("k".to_string()))
  365. /*
  366. // Pick a preimage and compute its hash.
  367. let quantity = bls12_381::Scalar::from(3);
  368. // Create an instance of our circuit (with the preimage as a witness).
  369. let c = MyCircuit {
  370. params: vec![
  371. Some(quantity),
  372. Some(quantity * quantity),
  373. Some(quantity * quantity * quantity),
  374. ],
  375. };
  376. let start = Instant::now();
  377. // Create a Groth16 proof with our parameters.
  378. let proof = groth16::create_random_proof(c, &params, &mut OsRng).unwrap();
  379. println!("Prove: [{:?}]", start.elapsed());
  380. let public_input = vec![bls12_381::Scalar::from(27)];
  381. let start = Instant::now();
  382. // Check the proof!
  383. assert!(groth16::verify_proof(&pvk, &proof, &public_input).is_ok());
  384. println!("Verify: [{:?}]", start.elapsed());
  385. */
  386. }
  387. // print
  388. fn print(ast: &MalVal) -> String {
  389. ast.pr_str(true)
  390. }
  391. fn rep(str: &str, env: &Env) -> Result<String, MalErr> {
  392. let ast = read(str)?;
  393. let exp = eval(ast, env.clone())?;
  394. Ok(print(&exp))
  395. }
  396. fn main() -> Result<(), ()> {
  397. let matches = clap_app!(zklisp =>
  398. (version: "0.1.0")
  399. (author: "mileschet <miles.chet@gmail.com>")
  400. (about: "A Lisp Interpreter for Zero Knowledge Virtual Machine")
  401. (@subcommand load =>
  402. (about: "Load the file into the interpreter")
  403. (@arg FILE: +required "Lisp Contract filename")
  404. )
  405. )
  406. .get_matches();
  407. CombinedLogger::init(vec![TermLogger::new(
  408. LevelFilter::Debug,
  409. Config::default(),
  410. TerminalMode::Mixed,
  411. )
  412. .unwrap()])
  413. .unwrap();
  414. match matches.subcommand() {
  415. Some(("load", matches)) => {
  416. let file: String = matches.value_of("FILE").unwrap().parse().unwrap();
  417. repl_load(file);
  418. }
  419. _ => {
  420. eprintln!("error: Invalid subcommand invoked");
  421. std::process::exit(-1);
  422. }
  423. }
  424. Ok(())
  425. }
  426. fn repl_load(file: String) -> Result<(), ()> {
  427. let repl_env = env_new(None);
  428. for (k, v) in core::ns() {
  429. env_sets(&repl_env, k, v);
  430. }
  431. let _ = rep("(def! not (fn* (a) (if a false true)))", &repl_env);
  432. let _ = rep(
  433. "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))",
  434. &repl_env,
  435. );
  436. 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);
  437. match rep(&format!("(load-file \"{}\")", file), &repl_env) {
  438. Ok(_) => std::process::exit(0),
  439. Err(e) => {
  440. println!("Error: {}", format_error(e));
  441. std::process::exit(1);
  442. }
  443. }
  444. Ok(())
  445. }