compiler.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. use std::str::Chars;
  2. use super::{
  3. ast::{Arg, Constant, Literal, Statement, StatementType, Witness},
  4. error::ErrorEmitter,
  5. types::StackType,
  6. };
  7. use crate::serial::{serialize, VarInt};
  8. /// Version of the binary
  9. pub const BINARY_VERSION: u8 = 2;
  10. /// Magic bytes prepended to the binary
  11. pub const MAGIC_BYTES: [u8; 4] = [0x0b, 0x01, 0xb1, 0x35];
  12. pub struct Compiler {
  13. constants: Vec<Constant>,
  14. witnesses: Vec<Witness>,
  15. statements: Vec<Statement>,
  16. literals: Vec<Literal>,
  17. debug_info: bool,
  18. error: ErrorEmitter,
  19. }
  20. impl Compiler {
  21. pub fn new(
  22. filename: &str,
  23. source: Chars,
  24. constants: Vec<Constant>,
  25. witnesses: Vec<Witness>,
  26. statements: Vec<Statement>,
  27. literals: Vec<Literal>,
  28. debug_info: bool,
  29. ) -> Self {
  30. // For nice error reporting, we'll load everything into a string
  31. // vector so we have references to lines.
  32. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  33. let error = ErrorEmitter::new("Compiler", filename, lines);
  34. Self { constants, witnesses, statements, literals, debug_info, error }
  35. }
  36. pub fn compile(&self) -> Vec<u8> {
  37. let mut bincode = vec![];
  38. // Write the magic bytes and version
  39. bincode.extend_from_slice(&MAGIC_BYTES);
  40. bincode.push(BINARY_VERSION);
  41. // Temporaty stack vector for lookups
  42. let mut tmp_stack = vec![];
  43. // In the .constant section of the binary, we write the constant's type,
  44. // and the name so the VM can look it up from `src/crypto/constants/`.
  45. bincode.extend_from_slice(b".constant");
  46. for i in &self.constants {
  47. tmp_stack.push(i.name.as_str());
  48. bincode.push(i.typ as u8);
  49. bincode.extend_from_slice(&serialize(&i.name));
  50. }
  51. // Currently, our literals are only Uint64 types, in the binary we'll
  52. // add them here in the .literal section. In the VM, they will be on
  53. // their own stack, used for reference by opcodes.
  54. bincode.extend_from_slice(b".literal");
  55. for i in &self.literals {
  56. bincode.push(i.typ as u8);
  57. bincode.extend_from_slice(&serialize(&i.name));
  58. }
  59. // In the .contract section, we write all our witness types, on the stack
  60. // they're in order of appearance.
  61. bincode.extend_from_slice(b".contract");
  62. for i in &self.witnesses {
  63. tmp_stack.push(i.name.as_str());
  64. bincode.push(i.typ as u8);
  65. }
  66. bincode.extend_from_slice(b".circuit");
  67. for i in &self.statements {
  68. match i.typ {
  69. StatementType::Assign => tmp_stack.push(&i.lhs.as_ref().unwrap().name),
  70. // In case of a simple call, we don't append anything to the stack
  71. StatementType::Call => {}
  72. // TODO: FIXME: unreachable is reached with missing semicolons in the code
  73. _ => unreachable!(),
  74. }
  75. bincode.push(i.opcode as u8);
  76. bincode.extend_from_slice(&serialize(&VarInt(i.rhs.len() as u64)));
  77. for arg in &i.rhs {
  78. match arg {
  79. Arg::Var(arg) => {
  80. if let Some(found) = Compiler::lookup_stack(&tmp_stack, &arg.name) {
  81. bincode.push(StackType::Var as u8);
  82. bincode.extend_from_slice(&serialize(&VarInt(found as u64)));
  83. continue
  84. }
  85. self.error.abort(
  86. &format!("Failed finding a stack reference for `{}`", arg.name),
  87. arg.line,
  88. arg.column,
  89. );
  90. }
  91. Arg::Lit(lit) => {
  92. if let Some(found) = Compiler::lookup_literal(&self.literals, &lit.name) {
  93. bincode.push(StackType::Lit as u8);
  94. bincode.extend_from_slice(&serialize(&VarInt(found as u64)));
  95. continue
  96. }
  97. self.error.abort(
  98. &format!("Failed finding literal `{}`", lit.name),
  99. lit.line,
  100. lit.column,
  101. );
  102. }
  103. _ => unreachable!(),
  104. };
  105. }
  106. }
  107. // If we're not doing debug info, we're done here and can return.
  108. if !self.debug_info {
  109. return bincode
  110. }
  111. // TODO: Otherwise, we proceed appending debug info.
  112. bincode
  113. }
  114. fn lookup_stack(stack: &[&str], name: &str) -> Option<usize> {
  115. for (idx, n) in stack.iter().enumerate() {
  116. if n == &name {
  117. return Some(idx)
  118. }
  119. }
  120. None
  121. }
  122. fn lookup_literal(literals: &[Literal], name: &str) -> Option<usize> {
  123. for (idx, n) in literals.iter().enumerate() {
  124. if n.name == name {
  125. return Some(idx)
  126. }
  127. }
  128. None
  129. }
  130. }