compiler.rs 5.3 KB

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