compiler.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{io::Result, str::Chars};
  19. use darkfi_serial::{serialize, VarInt};
  20. use super::{
  21. ast::{Arg, Constant, Literal, Statement, StatementType, Witness},
  22. error::ErrorEmitter,
  23. types::HeapType,
  24. };
  25. /// Version of the binary
  26. pub const BINARY_VERSION: u8 = 2;
  27. /// Magic bytes prepended to the binary
  28. pub const MAGIC_BYTES: [u8; 4] = [0x0b, 0x01, 0xb1, 0x35];
  29. pub struct Compiler {
  30. namespace: String,
  31. k: u32,
  32. constants: Vec<Constant>,
  33. witnesses: Vec<Witness>,
  34. statements: Vec<Statement>,
  35. literals: Vec<Literal>,
  36. debug_info: bool,
  37. error: ErrorEmitter,
  38. }
  39. impl Compiler {
  40. #[allow(clippy::too_many_arguments)]
  41. pub fn new(
  42. filename: &str,
  43. source: Chars,
  44. namespace: String,
  45. k: u32,
  46. constants: Vec<Constant>,
  47. witnesses: Vec<Witness>,
  48. statements: Vec<Statement>,
  49. literals: Vec<Literal>,
  50. debug_info: bool,
  51. ) -> Self {
  52. // For nice error reporting, we'll load everything into a string
  53. // vector so we have references to lines.
  54. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  55. let error = ErrorEmitter::new("Compiler", filename, lines);
  56. Self { namespace, k, constants, witnesses, statements, literals, debug_info, error }
  57. }
  58. pub fn compile(&self) -> Result<Vec<u8>> {
  59. let mut bincode = vec![];
  60. // Write the magic bytes and version
  61. bincode.extend_from_slice(&MAGIC_BYTES);
  62. bincode.push(BINARY_VERSION);
  63. // Write the circuit's k param
  64. bincode.extend_from_slice(&serialize(&self.k));
  65. // Write the circuit's namespace
  66. bincode.extend_from_slice(&serialize(&self.namespace));
  67. // Temporary heap vector for lookups
  68. let mut tmp_heap = vec![];
  69. // In the .constant section of the binary, we write the constant's type,
  70. // and the name so the VM can look it up from `src/crypto/constants/`.
  71. bincode.extend_from_slice(b".constant");
  72. for i in &self.constants {
  73. tmp_heap.push(i.name.as_str());
  74. bincode.push(i.typ as u8);
  75. bincode.extend_from_slice(&serialize(&i.name));
  76. }
  77. // Currently, our literals are only Uint64 types, in the binary we'll
  78. // add them here in the .literal section. In the VM, they will be on
  79. // their own heap, used for reference by opcodes.
  80. bincode.extend_from_slice(b".literal");
  81. for i in &self.literals {
  82. bincode.push(i.typ as u8);
  83. bincode.extend_from_slice(&serialize(&i.name));
  84. }
  85. // In the .witness section, we write all our witness types, on the heap
  86. // they're in order of appearance.
  87. bincode.extend_from_slice(b".witness");
  88. for i in &self.witnesses {
  89. tmp_heap.push(i.name.as_str());
  90. bincode.push(i.typ as u8);
  91. }
  92. bincode.extend_from_slice(b".circuit");
  93. for i in &self.statements {
  94. match i.typ {
  95. StatementType::Assign => tmp_heap.push(&i.lhs.as_ref().unwrap().name),
  96. // In case of a simple call, we don't append anything to the heap
  97. StatementType::Call => {}
  98. _ => unreachable!("Invalid statement type in circuit: {:?}", i.typ),
  99. }
  100. bincode.push(i.opcode as u8);
  101. bincode.extend_from_slice(&serialize(&VarInt(i.rhs.len() as u64)));
  102. for arg in &i.rhs {
  103. match arg {
  104. Arg::Var(arg) => {
  105. if let Some(found) = Compiler::lookup_heap(&tmp_heap, &arg.name) {
  106. bincode.push(HeapType::Var as u8);
  107. bincode.extend_from_slice(&serialize(&VarInt(found as u64)));
  108. continue
  109. }
  110. return Err(self.error.abort(
  111. &format!("Failed finding a heap reference for `{}`", arg.name),
  112. arg.line,
  113. arg.column,
  114. ))
  115. }
  116. Arg::Lit(lit) => {
  117. if let Some(found) = Compiler::lookup_literal(&self.literals, &lit.name) {
  118. bincode.push(HeapType::Lit as u8);
  119. bincode.extend_from_slice(&serialize(&VarInt(found as u64)));
  120. continue
  121. }
  122. return Err(self.error.abort(
  123. &format!("Failed finding literal `{}`", lit.name),
  124. lit.line,
  125. lit.column,
  126. ))
  127. }
  128. _ => unreachable!(),
  129. };
  130. }
  131. }
  132. // If we're not doing debug info, we're done here and can return.
  133. if !self.debug_info {
  134. return Ok(bincode)
  135. }
  136. // TODO: Otherwise, we proceed appending debug info.
  137. Ok(bincode)
  138. }
  139. fn lookup_heap(heap: &[&str], name: &str) -> Option<usize> {
  140. for (idx, n) in heap.iter().enumerate() {
  141. if n == &name {
  142. return Some(idx)
  143. }
  144. }
  145. None
  146. }
  147. fn lookup_literal(literals: &[Literal], name: &str) -> Option<usize> {
  148. for (idx, n) in literals.iter().enumerate() {
  149. if n.name == name {
  150. return Some(idx)
  151. }
  152. }
  153. None
  154. }
  155. }