parser.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. use std::{io, io::Write, iter::Peekable, process, str::Chars};
  2. use indexmap::IndexMap;
  3. use itertools::Itertools;
  4. use termion::{color, style};
  5. use super::{
  6. ast::{
  7. Constant, Constants, Statement, StatementType, Statements, UnparsedConstants,
  8. UnparsedWitnesses, Variable, Witness, Witnesses,
  9. },
  10. lexer::{Token, TokenType},
  11. opcode::Opcode,
  12. types::Type,
  13. };
  14. pub struct Parser {
  15. file: String,
  16. lines: Vec<String>,
  17. tokens: Vec<Token>,
  18. }
  19. impl Parser {
  20. pub fn new(filename: &str, source: Chars, tokens: Vec<Token>) -> Self {
  21. // For nice error reporting, we'll load everything into a string
  22. // vector so we have references to lines.
  23. let lines = source.as_str().lines().map(|x| x.to_string()).collect();
  24. Parser { file: filename.to_string(), lines, tokens }
  25. }
  26. pub fn parse(self) -> (Constants, Witnesses, Statements) {
  27. // We use these to keep state when iterating
  28. let mut declaring_constant = false;
  29. let mut declaring_contract = false;
  30. let mut declaring_circuit = false;
  31. let mut constant_tokens = vec![];
  32. let mut contract_tokens = vec![];
  33. let mut circuit_tokens = vec![];
  34. // Single statement in the circuit
  35. let mut circuit_statement = vec![];
  36. // All the circuit statements
  37. let mut circuit_statements = vec![];
  38. let mut ast = IndexMap::new();
  39. let mut namespace = String::new();
  40. let mut ast_inner = IndexMap::new();
  41. let mut namespace_found = false; // Nasty
  42. let mut iter = self.tokens.iter();
  43. while let Some(t) = iter.next() {
  44. // Start by declaring a section
  45. if !declaring_constant && !declaring_contract && !declaring_circuit {
  46. if t.token_type != TokenType::Symbol {
  47. // TODO: Revisit
  48. // TODO: Visit this again when we are allowing imports
  49. unimplemented!();
  50. }
  51. // The sections we must be declaring in our source code
  52. match t.token.as_str() {
  53. "constant" => {
  54. declaring_constant = true;
  55. // Eat all the tokens within the `constant` section
  56. for inner in iter.by_ref() {
  57. constant_tokens.push(inner.clone());
  58. if inner.token_type == TokenType::RightBrace {
  59. break
  60. }
  61. }
  62. }
  63. "contract" => {
  64. declaring_contract = true;
  65. // Eat all the tokens within the `contract` section
  66. for inner in iter.by_ref() {
  67. contract_tokens.push(inner.clone());
  68. if inner.token_type == TokenType::RightBrace {
  69. break
  70. }
  71. }
  72. }
  73. "circuit" => {
  74. declaring_circuit = true;
  75. // Eat all the tokens within the `circuit` section
  76. // TODO: Revisit when we support if/else and loops
  77. for inner in iter.by_ref() {
  78. circuit_tokens.push(inner.clone());
  79. if inner.token_type == TokenType::RightBrace {
  80. break
  81. }
  82. }
  83. }
  84. x => self.error(format!("Unknown `{}` proof section", x), t.line, t.column),
  85. }
  86. }
  87. // We shouldn't be reaching these states
  88. if declaring_constant && (declaring_contract || declaring_circuit) {
  89. unreachable!()
  90. }
  91. if declaring_contract && (declaring_constant || declaring_circuit) {
  92. unreachable!()
  93. }
  94. if declaring_circuit && (declaring_constant || declaring_contract) {
  95. unreachable!()
  96. }
  97. // Now go through the token vectors and work it through
  98. if declaring_constant {
  99. self.check_section_structure("constant", constant_tokens.clone());
  100. // TODO: Do we need this?
  101. if namespace_found && namespace != constant_tokens[0].token {
  102. self.error(
  103. format!(
  104. "Found `{}` namespace. Expected `{}`.",
  105. constant_tokens[0].token, namespace
  106. ),
  107. constant_tokens[0].line,
  108. constant_tokens[0].column,
  109. );
  110. } else {
  111. namespace = constant_tokens[0].token.clone();
  112. namespace_found = true;
  113. }
  114. let constants_cloned = constant_tokens.clone();
  115. let mut constants_map = IndexMap::new();
  116. // This is everything between the braces: { .. }
  117. let mut constants_inner = constants_cloned[2..constant_tokens.len() - 1].iter();
  118. while let Some((typ, name, comma)) = constants_inner.next_tuple() {
  119. if comma.token_type != TokenType::Comma {
  120. self.error(
  121. "Separator is not a comma".to_string(),
  122. comma.line,
  123. comma.column,
  124. );
  125. }
  126. if constants_map.contains_key(name.token.as_str()) {
  127. self.error(
  128. format!(
  129. "Section `constant` already contains the token `{}`.",
  130. &name.token
  131. ),
  132. name.line,
  133. name.column,
  134. );
  135. }
  136. constants_map.insert(name.token.clone(), (name.clone(), typ.clone()));
  137. }
  138. ast_inner.insert("constant".to_string(), constants_map);
  139. declaring_constant = false;
  140. }
  141. if declaring_contract {
  142. self.check_section_structure("contract", contract_tokens.clone());
  143. // TODO: Do we need this?
  144. if namespace_found && namespace != contract_tokens[0].token {
  145. self.error(
  146. format!(
  147. "Found `{}` namespace. Expected `{}`.",
  148. contract_tokens[0].token, namespace
  149. ),
  150. contract_tokens[0].line,
  151. contract_tokens[0].column,
  152. );
  153. } else {
  154. namespace = contract_tokens[0].token.clone();
  155. namespace_found = true;
  156. }
  157. let contract_cloned = contract_tokens.clone();
  158. let mut contract_map = IndexMap::new();
  159. // This is everything between the braces: { .. }
  160. let mut contract_inner = contract_cloned[2..contract_tokens.len() - 1].iter();
  161. while let Some((typ, name, comma)) = contract_inner.next_tuple() {
  162. if comma.token_type != TokenType::Comma {
  163. self.error(
  164. "Separator is not a comma".to_string(),
  165. comma.line,
  166. comma.column,
  167. );
  168. }
  169. if contract_map.contains_key(name.token.as_str()) {
  170. self.error(
  171. format!(
  172. "Section `contract` already contains the token `{}`.",
  173. &name.token
  174. ),
  175. name.line,
  176. name.column,
  177. );
  178. }
  179. contract_map.insert(name.token.clone(), (name.clone(), typ.clone()));
  180. }
  181. ast_inner.insert("contract".to_string(), contract_map);
  182. declaring_contract = false;
  183. }
  184. if declaring_circuit {
  185. self.check_section_structure("circuit", contract_tokens.clone());
  186. if circuit_tokens[circuit_tokens.len() - 2].token_type != TokenType::Semicolon {
  187. self.error(
  188. "Circuit section does not end with a semicolon. Would never finish parsing.".to_string(),
  189. circuit_tokens[circuit_tokens.len()-2].line,
  190. circuit_tokens[circuit_tokens.len()-2].column
  191. );
  192. }
  193. // TODO: Do we need this?
  194. if namespace_found && namespace != circuit_tokens[0].token {
  195. self.error(
  196. format!(
  197. "Found `{}` namespace. Expected `{}`.",
  198. circuit_tokens[0].token, namespace
  199. ),
  200. circuit_tokens[0].line,
  201. circuit_tokens[0].column,
  202. );
  203. } else {
  204. namespace = circuit_tokens[0].token.clone();
  205. namespace_found = true;
  206. }
  207. for i in circuit_tokens.clone()[2..circuit_tokens.len() - 1].iter() {
  208. if i.token_type == TokenType::Semicolon {
  209. circuit_statements.push(circuit_statement.clone());
  210. // println!("{:?}", circuit_statement);
  211. circuit_statement = vec![];
  212. continue
  213. }
  214. circuit_statement.push(i.clone());
  215. }
  216. declaring_circuit = false;
  217. }
  218. }
  219. ast.insert(namespace.clone(), ast_inner);
  220. // TODO: Verify there are both constant/contract sections
  221. // TODO: Verify there is a circuit section
  222. // TODO: Check that there are no duplicate names in constants, contract
  223. // and circuit assignments
  224. // Clean up the `constant` section
  225. let c = ast.get(&namespace).unwrap().get("constant").unwrap();
  226. let constants = self.parse_ast_constants(c);
  227. // Clean up the `contract` section
  228. let c = ast.get(&namespace).unwrap().get("contract").unwrap();
  229. let witnesses = self.parse_ast_contract(c);
  230. // Clean up the `circuit` section
  231. let stmt = self.parse_ast_circuit(circuit_statements);
  232. (constants, witnesses, stmt)
  233. }
  234. fn check_section_structure(&self, section: &str, tokens: Vec<Token>) {
  235. if tokens[0].token_type != TokenType::String {
  236. self.error(
  237. format!("{} section declaration must start with a naming string.", section),
  238. tokens[0].line,
  239. tokens[0].column,
  240. );
  241. }
  242. if tokens[1].token_type != TokenType::LeftBrace {
  243. self.error(
  244. format!(
  245. "{} section opening is not correct. Must be opened with a left brace `{{`",
  246. section
  247. ),
  248. tokens[0].line,
  249. tokens[0].column,
  250. );
  251. }
  252. if tokens[tokens.len() - 1].token_type != TokenType::RightBrace {
  253. self.error(
  254. format!(
  255. "{} section closing is not correct. Must be closed with a right brace `}}`",
  256. section
  257. ),
  258. tokens[0].line,
  259. tokens[0].column,
  260. );
  261. }
  262. if (section == "constant" || section == "contract") &&
  263. tokens[2..tokens.len() - 1].len() % 3 != 0
  264. {
  265. self.error(
  266. format!(
  267. "Invalid number of elements in `{}` section. Must be pairs of `type:name` separated with a comma `,`",
  268. section
  269. ),
  270. tokens[0].line,
  271. tokens[0].column,
  272. );
  273. }
  274. }
  275. fn parse_ast_constants(&self, ast: &UnparsedConstants) -> Constants {
  276. let mut ret = vec![];
  277. for (k, v) in ast {
  278. if &v.0.token != k {
  279. self.error(
  280. format!("Constant name `{}` doesn't match token `{}`.", v.0.token, k),
  281. v.0.line,
  282. v.0.column,
  283. );
  284. }
  285. if v.0.token_type != TokenType::Symbol {
  286. self.error(
  287. format!("Constant name `{}` is not a symbol.", v.0.token),
  288. v.0.line,
  289. v.0.column,
  290. );
  291. }
  292. if v.1.token_type != TokenType::Symbol {
  293. self.error(
  294. format!("Constant type `{}` is not a symbol.", v.1.token),
  295. v.1.line,
  296. v.1.column,
  297. );
  298. }
  299. match v.1.token.as_str() {
  300. "EcFixedPoint" => {
  301. ret.push(Constant {
  302. name: k.to_string(),
  303. typ: Type::EcFixedPoint,
  304. line: v.0.line,
  305. column: v.0.column,
  306. });
  307. }
  308. x => {
  309. self.error(
  310. format!("`{}` is an illegal constant type", x),
  311. v.1.line,
  312. v.1.column,
  313. );
  314. }
  315. }
  316. }
  317. ret
  318. }
  319. fn parse_ast_contract(&self, ast: &UnparsedWitnesses) -> Witnesses {
  320. let mut ret = vec![];
  321. for (k, v) in ast {
  322. if &v.0.token != k {
  323. self.error(
  324. format!("Witness name `{}` doesn't match token `{}`.", v.0.token, k),
  325. v.0.line,
  326. v.0.column,
  327. );
  328. }
  329. if v.0.token_type != TokenType::Symbol {
  330. self.error(
  331. format!("Witness name `{}` is not a symbol.", v.0.token),
  332. v.0.line,
  333. v.0.column,
  334. );
  335. }
  336. if v.1.token_type != TokenType::Symbol {
  337. self.error(
  338. format!("Witness type `{}` is not a symbol.", v.1.token),
  339. v.1.line,
  340. v.1.column,
  341. );
  342. }
  343. match v.1.token.as_str() {
  344. "Base" => {
  345. ret.push(Witness {
  346. name: k.to_string(),
  347. typ: Type::Base,
  348. line: v.0.line,
  349. column: v.0.column,
  350. });
  351. }
  352. "Scalar" => {
  353. ret.push(Witness {
  354. name: k.to_string(),
  355. typ: Type::Scalar,
  356. line: v.0.line,
  357. column: v.0.column,
  358. });
  359. }
  360. "MerklePath" => {
  361. ret.push(Witness {
  362. name: k.to_string(),
  363. typ: Type::MerklePath,
  364. line: v.0.line,
  365. column: v.0.column,
  366. });
  367. }
  368. "Uint32" => {
  369. ret.push(Witness {
  370. name: k.to_string(),
  371. typ: Type::Uint32,
  372. line: v.0.line,
  373. column: v.0.column,
  374. });
  375. }
  376. "Uint64" => {
  377. ret.push(Witness {
  378. name: k.to_string(),
  379. typ: Type::Uint64,
  380. line: v.0.line,
  381. column: v.0.column,
  382. });
  383. }
  384. x => {
  385. self.error(format!("`{}` is an illegal witness type", x), v.1.line, v.1.column);
  386. }
  387. }
  388. }
  389. ret
  390. }
  391. fn parse_ast_circuit(&self, statements: Vec<Vec<Token>>) -> Vec<Statement> {
  392. let mut stmts = vec![];
  393. for statement in statements {
  394. let (mut left_paren, mut right_paren) = (0, 0);
  395. for i in &statement {
  396. match i.token.as_str() {
  397. "(" => left_paren += 1,
  398. ")" => right_paren += 1,
  399. _ => {}
  400. }
  401. }
  402. if left_paren != right_paren {
  403. self.error(
  404. "Incorrect number of left and right parenthesis for statement.".to_string(),
  405. statement[0].line,
  406. statement[0].column,
  407. );
  408. }
  409. // C = poseidon_hash(pub_x, pub_y, value, token, serial, coin_blind)
  410. // | | | |
  411. // V V V V
  412. // variable opcode args
  413. // assign
  414. // constrain_instance(C)
  415. // | |
  416. // V V
  417. // opcode args
  418. let mut iter = statement.iter().peekable();
  419. let mut stmt = Statement::default();
  420. let mut parsing = false;
  421. while let Some(token) = iter.next() {
  422. if !parsing {
  423. if let Some(next_token) = iter.peek() {
  424. if next_token.token_type == TokenType::Assign {
  425. stmt.typ = StatementType::Assignment;
  426. stmt.variable = Some(Variable {
  427. name: token.token.clone(),
  428. typ: Type::Dummy,
  429. line: token.line,
  430. column: token.column,
  431. });
  432. // Skip over the `=` token.
  433. iter.next();
  434. parsing = true;
  435. continue
  436. }
  437. if next_token.token_type == TokenType::LeftParen {
  438. stmt.typ = StatementType::Call;
  439. stmt.variable = None;
  440. parsing = true;
  441. }
  442. if !parsing {
  443. self.error(
  444. format!("Illegal token `{}`", next_token.token),
  445. next_token.line,
  446. next_token.column,
  447. );
  448. }
  449. }
  450. }
  451. // This matching could be moved over into the semantic analyzer.
  452. // We could just parse any kind of symbol here, and then do lookup
  453. // from the analyzer, to see if the calls actually exist and are
  454. // supported.
  455. // But for now, we'll just leave it here and expand later.
  456. match token.token.as_str() {
  457. "poseidon_hash" => {
  458. stmt.args = self.parse_function_call(token, &mut iter);
  459. stmt.opcode = Opcode::PoseidonHash;
  460. stmt.line = token.line;
  461. stmts.push(stmt.clone());
  462. parsing = false;
  463. continue
  464. }
  465. "constrain_instance" => {
  466. stmt.args = self.parse_function_call(token, &mut iter);
  467. stmt.opcode = Opcode::ConstrainInstance;
  468. stmt.line = token.line;
  469. stmts.push(stmt.clone());
  470. parsing = false;
  471. continue
  472. }
  473. "calculate_merkle_root" => {
  474. stmt.args = self.parse_function_call(token, &mut iter);
  475. stmt.opcode = Opcode::CalculateMerkleRoot;
  476. stmt.line = token.line;
  477. stmts.push(stmt.clone());
  478. parsing = false;
  479. continue
  480. }
  481. "ec_mul_short" => {
  482. stmt.args = self.parse_function_call(token, &mut iter);
  483. stmt.opcode = Opcode::EcMulShort;
  484. stmt.line = token.line;
  485. stmts.push(stmt.clone());
  486. parsing = false;
  487. continue
  488. }
  489. "ec_mul_base" => {
  490. stmt.args = self.parse_function_call(token, &mut iter);
  491. stmt.opcode = Opcode::EcMulBase;
  492. stmt.line = token.line;
  493. stmts.push(stmt.clone());
  494. parsing = false;
  495. continue
  496. }
  497. "ec_mul" => {
  498. stmt.args = self.parse_function_call(token, &mut iter);
  499. stmt.opcode = Opcode::EcMul;
  500. stmt.line = token.line;
  501. stmts.push(stmt.clone());
  502. parsing = false;
  503. continue
  504. }
  505. "ec_get_x" => {
  506. stmt.args = self.parse_function_call(token, &mut iter);
  507. stmt.opcode = Opcode::EcGetX;
  508. stmt.line = token.line;
  509. stmts.push(stmt.clone());
  510. parsing = false;
  511. continue
  512. }
  513. "ec_get_y" => {
  514. stmt.args = self.parse_function_call(token, &mut iter);
  515. stmt.opcode = Opcode::EcGetY;
  516. stmt.line = token.line;
  517. stmts.push(stmt.clone());
  518. parsing = false;
  519. continue
  520. }
  521. "ec_add" => {
  522. stmt.args = self.parse_function_call(token, &mut iter);
  523. stmt.opcode = Opcode::EcAdd;
  524. stmt.line = token.line;
  525. stmts.push(stmt.clone());
  526. parsing = false;
  527. continue
  528. }
  529. x => {
  530. self.error(
  531. format!("Unimplemented function call `{}`", x),
  532. token.line,
  533. token.column,
  534. );
  535. }
  536. }
  537. }
  538. }
  539. // println!("{:#?}", stmts);
  540. stmts
  541. }
  542. fn parse_function_call(
  543. &self,
  544. token: &Token,
  545. iter: &mut Peekable<std::slice::Iter<'_, Token>>,
  546. ) -> Vec<Variable> {
  547. if let Some(next_token) = iter.peek() {
  548. if next_token.token_type != TokenType::LeftParen {
  549. self.error(
  550. "Invalid function call opening. Must start with a `(`".to_string(),
  551. next_token.line,
  552. next_token.column,
  553. );
  554. }
  555. // Skip the opening parenthesis
  556. iter.next();
  557. } else {
  558. self.error("Premature ending of statement".to_string(), token.line, token.column);
  559. }
  560. // Eat up function arguments
  561. let mut args = vec![];
  562. while let Some((arg, sep)) = iter.next_tuple() {
  563. args.push(Variable {
  564. name: arg.token.clone(),
  565. typ: Type::Dummy,
  566. line: arg.line,
  567. column: arg.column,
  568. });
  569. if sep.token_type == TokenType::RightParen {
  570. // Reached end of args
  571. break
  572. }
  573. if sep.token_type != TokenType::Comma {
  574. self.error(
  575. "Argument separator is not a comma (`,`)".to_string(),
  576. sep.line,
  577. sep.column,
  578. );
  579. }
  580. }
  581. args
  582. }
  583. fn error(&self, msg: String, ln: usize, col: usize) {
  584. let err_msg = format!("{} (line {}, column {})", msg, ln, col);
  585. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  586. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  587. let caret = format!("{:width$}^", "", width = pad);
  588. let msg = format!("{}\n{}\n{}\n", err_msg, dbg_msg, caret);
  589. Parser::abort(&msg);
  590. }
  591. fn abort(msg: &str) {
  592. let stderr = io::stderr();
  593. let mut handle = stderr.lock();
  594. write!(
  595. handle,
  596. "{}{}Parser error:{} {}",
  597. style::Bold,
  598. color::Fg(color::Red),
  599. style::Reset,
  600. msg,
  601. )
  602. .unwrap();
  603. handle.flush().unwrap();
  604. process::exit(1);
  605. }
  606. }