//! Compiles a Leo program from a file path. use crate::{ constraints::{generate_constraints, generate_test_constraints, ConstrainedValue}, errors::CompilerError, GroupType, }; use leo_ast::LeoParser; use leo_types::{InputValue, Program}; use snarkos_errors::gadgets::SynthesisError; use snarkos_models::{ curves::{Field, PrimeField}, gadgets::r1cs::{ConstraintSynthesizer, ConstraintSystem, TestConstraintSystem}, }; use sha2::{Digest, Sha256}; use std::{fs, marker::PhantomData, path::PathBuf}; #[derive(Clone)] pub struct Compiler> { package_name: String, main_file_path: PathBuf, program: Program, program_inputs: Vec>, output: Option>, _engine: PhantomData, } impl> Compiler { pub fn init(package_name: String, main_file_path: PathBuf) -> Result { let mut program = Self { package_name, main_file_path, program: Program::new(), program_inputs: vec![], output: None, _engine: PhantomData, }; // Generate the abstract syntax tree and assemble the program program.parse_program()?; Ok(program) } pub fn set_inputs(&mut self, program_inputs: Vec>) { self.program_inputs = program_inputs; } pub fn checksum(&self) -> Result { // Read in the main file as string let unparsed_file = fs::read_to_string(&self.main_file_path) .map_err(|_| CompilerError::FileReadError(self.main_file_path.clone()))?; // Hash the file contents let mut hasher = Sha256::new(); hasher.input(unparsed_file.as_bytes()); let hash = hasher.result(); Ok(hex::encode(hash)) } pub fn compile_constraints>( self, cs: &mut CS, ) -> Result, CompilerError> { generate_constraints(cs, self.program, self.program_inputs) } pub fn compile_test_constraints(self, cs: &mut TestConstraintSystem) -> Result<(), CompilerError> { generate_test_constraints::(cs, self.program) } fn parse_program(&mut self) -> Result<(), CompilerError> { // Build the program syntax tree let file_path = &self.main_file_path; let input_file = &LeoParser::load_file(file_path)?; let syntax_tree = LeoParser::parse_file(file_path, input_file)?; // Build program from syntax tree let package_name = self.package_name.clone(); self.program = Program::from(syntax_tree, package_name); self.program_inputs = vec![None; self.program.num_parameters]; log::debug!("Program parsing complete\n{:#?}", self.program); Ok(()) } } impl> ConstraintSynthesizer for Compiler { fn generate_constraints>(self, cs: &mut CS) -> Result<(), SynthesisError> { let _result = generate_constraints::<_, G, _>(cs, self.program, self.program_inputs).unwrap(); // Write results to file or something Ok(()) } }