Skip to content

Commit

Permalink
Refactored the compile to not directly print the values. (#6685)
Browse files Browse the repository at this point in the history
  • Loading branch information
orizi authored Nov 18, 2024
1 parent 5019f4f commit 0fc4bd5
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 37 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion crates/cairo-lang-runnable-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
48 changes: 20 additions & 28 deletions crates/cairo-lang-runnable-utils/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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<BuiltinName>), BuildError> {
) -> Result<CasmProgramWrapperInfo, BuildError> {
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<String, BuildError> {
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<BuiltinName>), 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
Expand Down Expand Up @@ -265,6 +247,16 @@ impl EntryCodeConfig {
}
}

/// Information about a CASM program.
pub struct CasmProgramWrapperInfo {
/// The builtins used in the program.
pub builtins: Vec<BuiltinName>,
/// The instructions before the program.
pub header: Vec<Instruction>,
/// The instructions after the program.
pub footer: Vec<Instruction>,
}

/// 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,
Expand Down
1 change: 1 addition & 0 deletions crates/cairo-lang-runnable/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
45 changes: 39 additions & 6 deletions crates/cairo-lang-runnable/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
) -> Result<CompiledFunction> {
let mut db = RootDatabase::builder()
.detect_corelib()
.with_plugin_suite(runnable_plugin_suite())
Expand All @@ -41,7 +73,7 @@ pub fn compile_runnable_in_prepared_db(
runnable_path: Option<&str>,
main_crate_ids: Vec<CrateId>,
mut diagnostics_reporter: DiagnosticsReporter<'_>,
) -> Result<String> {
) -> Result<CompiledFunction> {
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))
Expand Down Expand Up @@ -101,7 +133,7 @@ pub fn compile_runnable_function_in_prepared_db(
db: &RootDatabase,
runnable: ConcreteFunctionWithBodyId,
mut diagnostics_reporter: DiagnosticsReporter<'_>,
) -> Result<String> {
) -> Result<CompiledFunction> {
diagnostics_reporter.ensure(db)?;
let SierraProgramWithDebug { program: sierra_program, debug_info: _ } = Arc::unwrap_or_clone(
db.get_sierra_program_for_functions(vec![runnable])
Expand All @@ -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 })
}
2 changes: 1 addition & 1 deletion crates/cairo-lang-runnable/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 0fc4bd5

Please sign in to comment.