leo/compiler/src/compiler.rs

60 lines
2.0 KiB
Rust
Raw Normal View History

2020-05-02 08:10:40 +03:00
use crate::{ast, Program, ResolvedProgram, ResolvedValue};
use crate::errors::CompilerError;
2020-04-25 11:47:10 +03:00
use snarkos_errors::gadgets::SynthesisError;
use snarkos_models::{
curves::{Field, PrimeField},
gadgets::r1cs::{ConstraintSynthesizer, ConstraintSystem},
};
use from_pest::FromPest;
2020-04-28 00:36:05 +03:00
use std::{fs, marker::PhantomData, path::PathBuf};
2020-04-25 11:47:10 +03:00
#[derive(Clone)]
2020-04-25 11:47:10 +03:00
pub struct Compiler<F: Field + PrimeField> {
2020-05-02 08:10:40 +03:00
package_name: String,
2020-04-25 11:47:10 +03:00
main_file_path: PathBuf,
2020-05-02 08:10:40 +03:00
output: Option<ResolvedValue<F>>,
2020-04-25 11:47:10 +03:00
_engine: PhantomData<F>,
}
impl<F: Field + PrimeField> Compiler<F> {
2020-05-02 08:10:40 +03:00
pub fn init(package_name: String, main_file_path: PathBuf) -> Self {
2020-04-28 00:36:05 +03:00
Self {
2020-05-02 08:10:40 +03:00
package_name,
2020-04-28 00:36:05 +03:00
main_file_path,
2020-05-02 08:10:40 +03:00
output: None,
2020-04-28 00:36:05 +03:00
_engine: PhantomData,
}
2020-04-25 11:47:10 +03:00
}
2020-05-02 08:10:40 +03:00
pub fn evaluate_program<CS: ConstraintSystem<F>>(self, cs: &mut CS) -> Result<ResolvedValue<F>, CompilerError> {
2020-04-25 11:47:10 +03:00
// Read in the main file as string
2020-05-02 08:10:40 +03:00
let unparsed_file = fs::read_to_string(&self.main_file_path).map_err(|_| CompilerError::FileReadError(self.main_file_path.clone()))?;
2020-04-25 11:47:10 +03:00
// Parse the file using leo.pest
2020-05-02 08:10:40 +03:00
let mut file = ast::parse(&unparsed_file).map_err(|_| CompilerError::FileParsingError)?;
2020-04-25 11:47:10 +03:00
// Build the abstract syntax tree
2020-05-02 08:10:40 +03:00
let syntax_tree = ast::File::from_pest(&mut file).map_err(|_| CompilerError::SyntaxTreeError)?;
log::debug!("{:#?}", syntax_tree);
2020-04-25 11:47:10 +03:00
2020-05-02 08:10:40 +03:00
// Build program from abstract syntax tree
let package_name = self.package_name.clone();
let program = Program::<'_, F>::from(syntax_tree).name(package_name);
2020-05-03 03:28:20 +03:00
log::info!("Compilation complete:\n{:#?}", program);
2020-04-25 11:47:10 +03:00
2020-05-02 08:10:40 +03:00
Ok(ResolvedProgram::generate_constraints(cs, program))
}
}
2020-04-25 11:47:10 +03:00
2020-05-02 08:10:40 +03:00
impl<F: Field + PrimeField> ConstraintSynthesizer<F> for Compiler<F> {
fn generate_constraints<CS: ConstraintSystem<F>>(
self,
cs: &mut CS,
) -> Result<(), SynthesisError> {
2020-05-03 04:08:04 +03:00
self.evaluate_program(cs).expect("error compiling program");
2020-04-25 11:47:10 +03:00
Ok(())
}
2020-04-28 00:36:05 +03:00
}