lisp.rs 19 KB

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