From 0fc4bd539bf90004dea8c4d787965e4548c67088 Mon Sep 17 00:00:00 2001 From: orizi <104711814+orizi@users.noreply.github.com> Date: Mon, 18 Nov 2024 16:32:50 +0200 Subject: [PATCH] Refactored the compile to not directly print the values. (#6685) --- Cargo.lock | 2 +- crates/cairo-lang-runnable-utils/Cargo.toml | 1 - .../cairo-lang-runnable-utils/src/builder.rs | 48 ++++++++----------- crates/cairo-lang-runnable/Cargo.toml | 1 + crates/cairo-lang-runnable/src/compile.rs | 45 ++++++++++++++--- crates/cairo-lang-runnable/src/test.rs | 2 +- 6 files changed, 62 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6652b520dcb..534b677a4b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -780,6 +780,7 @@ dependencies = [ "cairo-lang-runnable-utils", "cairo-lang-semantic", "cairo-lang-sierra-generator", + "cairo-lang-sierra-to-casm", "cairo-lang-syntax", "cairo-lang-test-utils", "cairo-lang-utils", @@ -803,7 +804,6 @@ dependencies = [ "cairo-lang-sierra-type-size", "cairo-lang-utils", "cairo-vm", - "itertools 0.12.1", "thiserror", ] diff --git a/crates/cairo-lang-runnable-utils/Cargo.toml b/crates/cairo-lang-runnable-utils/Cargo.toml index 4455ff8f174..7248554ad78 100644 --- a/crates/cairo-lang-runnable-utils/Cargo.toml +++ b/crates/cairo-lang-runnable-utils/Cargo.toml @@ -15,7 +15,6 @@ cairo-lang-sierra-to-casm = { path = "../cairo-lang-sierra-to-casm", version = " cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version = "~2.8.5" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "~2.8.5" } cairo-vm.workspace = true -itertools.workspace = true thiserror.workspace = true [dev-dependencies] diff --git a/crates/cairo-lang-runnable-utils/src/builder.rs b/crates/cairo-lang-runnable-utils/src/builder.rs index b1b3718009e..a73ff90848e 100644 --- a/crates/cairo-lang-runnable-utils/src/builder.rs +++ b/crates/cairo-lang-runnable-utils/src/builder.rs @@ -29,7 +29,6 @@ use cairo_lang_utils::casts::IntoOrPanic; use cairo_lang_utils::unordered_hash_map::UnorderedHashMap; use cairo_lang_utils::unordered_hash_set::UnorderedHashSet; use cairo_vm::types::builtin_name::BuiltinName; -use itertools::{Itertools, chain}; use thiserror::Error; #[derive(Debug, Error)] @@ -155,42 +154,25 @@ impl RunnableBuilder { !self.non_args_types.contains(ty) } - /// Assembles a function program for a given function. - pub fn assemble_function_program( + /// Creates the wrapper info for a given function. + pub fn create_wrapper_info( &self, func: &Function, config: EntryCodeConfig, - ) -> Result<(AssembledCairoProgram, Vec), BuildError> { + ) -> Result { let (header, builtins) = self.create_entry_code(func, config)?; - let footer = create_code_footer(); - - let assembled_cairo_program = self.casm_program.assemble_ex(&header, &footer); - Ok((assembled_cairo_program, builtins)) + Ok(CasmProgramWrapperInfo { header, builtins, footer: create_code_footer() }) } - /// CASM style string representation of the program. - pub fn casm_function_program( + /// Assembles a function program for a given function. + pub fn assemble_function_program( &self, func: &Function, config: EntryCodeConfig, - ) -> Result { - let (header, builtins) = self.create_entry_code(func, config)?; - let footer = create_code_footer(); - - Ok(chain!( - [ - format!("# builtins: {}\n", builtins.into_iter().map(|b| b.to_str()).join(", ")), - "# header #\n".to_string() - ], - header.into_iter().map(|i| format!("{i};\n")), - [ - "# sierra based code #\n".to_string(), - self.casm_program.to_string(), - "# footer #\n".to_string() - ], - footer.into_iter().map(|i| format!("{i};\n")), - ) - .join("")) + ) -> Result<(AssembledCairoProgram, Vec), BuildError> { + let info = self.create_wrapper_info(func, config)?; + let assembled_cairo_program = self.casm_program.assemble_ex(&info.header, &info.footer); + Ok((assembled_cairo_program, info.builtins)) } /// Returns the instructions to add to the beginning of the code to successfully call the main @@ -265,6 +247,16 @@ impl EntryCodeConfig { } } +/// Information about a CASM program. +pub struct CasmProgramWrapperInfo { + /// The builtins used in the program. + pub builtins: Vec, + /// The instructions before the program. + pub header: Vec, + /// The instructions after the program. + pub footer: Vec, +} + /// Returns the entry code to call the function with `param_types` as its inputs and /// `return_types` as outputs, located at `code_offset`. If `finalize_for_proof` is true, /// will make sure to remove the segment arena after calling the function. For testing purposes, diff --git a/crates/cairo-lang-runnable/Cargo.toml b/crates/cairo-lang-runnable/Cargo.toml index 80dccb32703..3040d35385d 100644 --- a/crates/cairo-lang-runnable/Cargo.toml +++ b/crates/cairo-lang-runnable/Cargo.toml @@ -16,6 +16,7 @@ cairo-lang-plugins = { path = "../cairo-lang-plugins", version = "~2.8.5" } cairo-lang-runnable-utils = { path = "../cairo-lang-runnable-utils", version = "~2.8.5" } cairo-lang-semantic = { path = "../cairo-lang-semantic", version = "~2.8.5" } cairo-lang-sierra-generator = { path = "../cairo-lang-sierra-generator", version = "~2.8.5" } +cairo-lang-sierra-to-casm = { path = "../cairo-lang-sierra-to-casm", version = "~2.8.5" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "~2.8.5" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "~2.8.5" } itertools = { workspace = true, default-features = true } diff --git a/crates/cairo-lang-runnable/src/compile.rs b/crates/cairo-lang-runnable/src/compile.rs index b921cdbd435..213402ae7d8 100644 --- a/crates/cairo-lang-runnable/src/compile.rs +++ b/crates/cairo-lang-runnable/src/compile.rs @@ -7,22 +7,54 @@ use cairo_lang_compiler::diagnostics::DiagnosticsReporter; use cairo_lang_compiler::project::setup_project; use cairo_lang_filesystem::ids::CrateId; use cairo_lang_lowering::ids::ConcreteFunctionWithBodyId; -use cairo_lang_runnable_utils::builder::{EntryCodeConfig, RunnableBuilder}; +use cairo_lang_runnable_utils::builder::{ + CasmProgramWrapperInfo, EntryCodeConfig, RunnableBuilder, +}; use cairo_lang_sierra_generator::db::SierraGenGroup; use cairo_lang_sierra_generator::executables::find_executable_function_ids; use cairo_lang_sierra_generator::program_generator::SierraProgramWithDebug; -use cairo_lang_utils::Upcast; +use cairo_lang_sierra_to_casm::compiler::CairoProgram; +use cairo_lang_utils::{Upcast, write_comma_separated}; use itertools::Itertools; use crate::plugin::{RUNNABLE_PREFIX, RUNNABLE_RAW_ATTR, runnable_plugin_suite}; +/// The CASM compilation result. +pub struct CompiledFunction { + /// The compiled CASM program. + pub program: CairoProgram, + /// The wrapper information for the program. + pub wrapper: CasmProgramWrapperInfo, +} +impl std::fmt::Display for CompiledFunction { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "# builtins:")?; + if !self.wrapper.builtins.is_empty() { + write!(f, " ")?; + write_comma_separated(f, self.wrapper.builtins.iter().map(|b| b.to_str()))?; + } + writeln!(f)?; + writeln!(f, "# header #")?; + for instruction in &self.wrapper.header { + writeln!(f, "{};", instruction)?; + } + writeln!(f, "# sierra based code #")?; + write!(f, "{}", self.program)?; + writeln!(f, "# footer #")?; + for instruction in &self.wrapper.footer { + writeln!(f, "{};", instruction)?; + } + Ok(()) + } +} + /// Compile the function given by path. /// Errors if there is ambiguity. pub fn compile_runnable( path: &Path, runnable_path: Option<&str>, diagnostics_reporter: DiagnosticsReporter<'_>, -) -> Result { +) -> Result { let mut db = RootDatabase::builder() .detect_corelib() .with_plugin_suite(runnable_plugin_suite()) @@ -41,7 +73,7 @@ pub fn compile_runnable_in_prepared_db( runnable_path: Option<&str>, main_crate_ids: Vec, mut diagnostics_reporter: DiagnosticsReporter<'_>, -) -> Result { +) -> Result { let mut runnables: Vec<_> = find_executable_function_ids(db, main_crate_ids) .into_iter() .filter_map(|(id, labels)| labels.into_iter().any(|l| l == RUNNABLE_RAW_ATTR).then_some(id)) @@ -101,7 +133,7 @@ pub fn compile_runnable_function_in_prepared_db( db: &RootDatabase, runnable: ConcreteFunctionWithBodyId, mut diagnostics_reporter: DiagnosticsReporter<'_>, -) -> Result { +) -> Result { diagnostics_reporter.ensure(db)?; let SierraProgramWithDebug { program: sierra_program, debug_info: _ } = Arc::unwrap_or_clone( db.get_sierra_program_for_functions(vec![runnable]) @@ -110,5 +142,6 @@ pub fn compile_runnable_function_in_prepared_db( ); let runnable_func = sierra_program.funcs[0].clone(); let builder = RunnableBuilder::new(sierra_program, None)?; - Ok(builder.casm_function_program(&runnable_func, EntryCodeConfig::provable())?) + let wrapper = builder.create_wrapper_info(&runnable_func, EntryCodeConfig::provable())?; + Ok(CompiledFunction { program: builder.casm_program().clone(), wrapper }) } diff --git a/crates/cairo-lang-runnable/src/test.rs b/crates/cairo-lang-runnable/src/test.rs index be11c42d468..dd672ad79ce 100644 --- a/crates/cairo-lang-runnable/src/test.rs +++ b/crates/cairo-lang-runnable/src/test.rs @@ -80,7 +80,7 @@ impl TestFileRunner for CompileRunnableTestRunner { let error = verify_diagnostics_expectation(args, &semantic_diagnostics); TestRunnerResult { outputs: OrderedHashMap::from([ - ("generated_casm_code".into(), result), + ("generated_casm_code".into(), result.to_string()), ("expected_diagnostics".into(), semantic_diagnostics), ]), error,