From 87dcd173612d9b78a20fbd2210bdaa4748df9781 Mon Sep 17 00:00:00 2001 From: fmoletta <99273364+fmoletta@users.noreply.github.com> Date: Wed, 24 Apr 2024 18:59:06 -0300 Subject: [PATCH] Add `lib.rs` to cairo1-run (#1714) * Add lib.rs * Add changelog entry * Add FuncArg docs * Add Cairo1RunConfig docs * fix * fmt * fmt --- CHANGELOG.md | 2 + cairo1-run/src/cairo_run.rs | 35 ++++++++++++++--- cairo1-run/src/error.rs | 62 ++++++++++++++++++++++++++++++ cairo1-run/src/lib.rs | 10 +++++ cairo1-run/src/main.rs | 76 +++---------------------------------- 5 files changed, 109 insertions(+), 76 deletions(-) create mode 100644 cairo1-run/src/error.rs create mode 100644 cairo1-run/src/lib.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b9bbce6259..2227c49154 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ * Added segment merging of the dictionary segments. * Added validation of the generated segment arena in cairo1 run. +* refactor: Add `lib.rs` to cairo1-run[#1714](https://github.com/lambdaclass/cairo-vm/pull/1714) + * feat: Implement `extend_additional_data` for `BuiltinRunner`[#1726](https://github.com/lambdaclass/cairo-vm/pull/1726) * BREAKING: Set dynamic params as null by default on air public input [#1716](https://github.com/lambdaclass/cairo-vm/pull/1716) diff --git a/cairo1-run/src/cairo_run.rs b/cairo1-run/src/cairo_run.rs index b3b9e8f20a..d4f46d4bac 100644 --- a/cairo1-run/src/cairo_run.rs +++ b/cairo1-run/src/cairo_run.rs @@ -1,3 +1,4 @@ +use crate::error::Error; use cairo_lang_casm::{ builder::{CasmBuilder, Var}, casm, casm_build_extend, @@ -51,21 +52,45 @@ use itertools::{chain, Itertools}; use num_traits::{cast::ToPrimitive, Zero}; use std::{collections::HashMap, iter::Peekable}; -use crate::{Error, FuncArg}; +/// Representation of a cairo argument +/// Can consist of a single Felt or an array of Felts +#[derive(Debug, Clone)] +pub enum FuncArg { + Array(Vec), + Single(Felt252), +} + +impl From for FuncArg { + fn from(value: Felt252) -> Self { + Self::Single(value) + } +} + +impl From> for FuncArg { + fn from(value: Vec) -> Self { + Self::Array(value) + } +} +/// Configuration parameters for a cairo run #[derive(Debug)] pub struct Cairo1RunConfig<'a> { + /// Input arguments for the `main` function in the cairo progran pub args: &'a [FuncArg], - // Serializes program output into a user-friendly format + /// Serialize program output into a user-friendly format pub serialize_output: bool, + /// Compute cairo trace during execution pub trace_enabled: bool, + /// Relocate cairo memory at the end of the run pub relocate_mem: bool, + /// Cairo layout chosen for the run pub layout: LayoutName, + /// Run in proof_mode pub proof_mode: bool, - // Should be true if either air_public_input or cairo_pie_output are needed - // Sets builtins stop_ptr by calling `final_stack` on each builtin + /// Should be true if either air_public_input or cairo_pie_output are needed + /// Sets builtins stop_ptr by calling `final_stack` on each builtin pub finalize_builtins: bool, - // Appends return values to the output segment. This is performed by default when running in proof_mode + /// Appends return values to the output segment. This is performed by default when running in proof_mode pub append_return_values: bool, } diff --git a/cairo1-run/src/error.rs b/cairo1-run/src/error.rs new file mode 100644 index 0000000000..7629b18001 --- /dev/null +++ b/cairo1-run/src/error.rs @@ -0,0 +1,62 @@ +use cairo_lang_sierra::{ids::ConcreteTypeId, program_registry::ProgramRegistryError}; +use cairo_lang_sierra_to_casm::{compiler::CompilationError, metadata::MetadataError}; +use cairo_vm::{ + air_public_input::PublicInputError, + cairo_run::EncodeTraceError, + types::errors::program_errors::ProgramError, + vm::errors::{ + memory_errors::MemoryError, runner_errors::RunnerError, trace_errors::TraceError, + vm_errors::VirtualMachineError, + }, + Felt252, +}; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("Invalid arguments")] + Cli(#[from] clap::Error), + #[error("Failed to interact with the file system")] + IO(#[from] std::io::Error), + #[error(transparent)] + EncodeTrace(#[from] EncodeTraceError), + #[error(transparent)] + VirtualMachine(#[from] VirtualMachineError), + #[error(transparent)] + Trace(#[from] TraceError), + #[error(transparent)] + PublicInput(#[from] PublicInputError), + #[error(transparent)] + Runner(#[from] RunnerError), + #[error(transparent)] + ProgramRegistry(#[from] Box), + #[error(transparent)] + Compilation(#[from] Box), + #[error("Failed to compile to sierra:\n {0}")] + SierraCompilation(String), + #[error(transparent)] + Metadata(#[from] MetadataError), + #[error(transparent)] + Program(#[from] ProgramError), + #[error(transparent)] + Memory(#[from] MemoryError), + #[error("Program panicked with {0:?}")] + RunPanic(Vec), + #[error("Function signature has no return types")] + NoRetTypesInSignature, + #[error("No size for concrete type id: {0}")] + NoTypeSizeForId(ConcreteTypeId), + #[error("Concrete type id has no debug name: {0}")] + TypeIdNoDebugName(ConcreteTypeId), + #[error("No info in sierra program registry for concrete type id: {0}")] + NoInfoForType(ConcreteTypeId), + #[error("Failed to extract return values from VM")] + FailedToExtractReturnValues, + #[error("Function expects arguments of size {expected} and received {actual} instead.")] + ArgumentsSizeMismatch { expected: i16, actual: i16 }, + #[error("Function param {param_index} only partially contains argument {arg_index}.")] + ArgumentUnaligned { + param_index: usize, + arg_index: usize, + }, +} diff --git a/cairo1-run/src/lib.rs b/cairo1-run/src/lib.rs new file mode 100644 index 0000000000..7eab2fdf1b --- /dev/null +++ b/cairo1-run/src/lib.rs @@ -0,0 +1,10 @@ +pub mod cairo_run; +pub mod error; +// Re-export main struct and functions from crate for convenience +pub use crate::cairo_run::{cairo_run_program, Cairo1RunConfig, FuncArg}; +// Re-export cairo_vm structs returned by this crate for ease of use +pub use cairo_vm::{ + types::relocatable::{MaybeRelocatable, Relocatable}, + vm::{runners::cairo_runner::CairoRunner, vm_core::VirtualMachine}, + Felt252, +}; diff --git a/cairo1-run/src/main.rs b/cairo1-run/src/main.rs index e538a68c97..310e8d490d 100644 --- a/cairo1-run/src/main.rs +++ b/cairo1-run/src/main.rs @@ -1,17 +1,10 @@ use bincode::enc::write::Writer; +use cairo1_run::error::Error; +use cairo1_run::{cairo_run_program, Cairo1RunConfig, FuncArg}; use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; -use cairo_lang_sierra::{ids::ConcreteTypeId, program_registry::ProgramRegistryError}; -use cairo_lang_sierra_to_casm::{compiler::CompilationError, metadata::MetadataError}; -use cairo_run::Cairo1RunConfig; use cairo_vm::{ - air_public_input::PublicInputError, - cairo_run::EncodeTraceError, - types::{errors::program_errors::ProgramError, layout_name::LayoutName}, - vm::errors::{ - memory_errors::MemoryError, runner_errors::RunnerError, trace_errors::TraceError, - vm_errors::VirtualMachineError, - }, - Felt252, + air_public_input::PublicInputError, types::layout_name::LayoutName, + vm::errors::trace_errors::TraceError, Felt252, }; use clap::{Parser, ValueHint}; use itertools::Itertools; @@ -19,9 +12,6 @@ use std::{ io::{self, Write}, path::PathBuf, }; -use thiserror::Error; - -pub mod cairo_run; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -65,12 +55,6 @@ struct Args { append_return_values: bool, } -#[derive(Debug, Clone)] -pub enum FuncArg { - Array(Vec), - Single(Felt252), -} - #[derive(Debug, Clone, Default)] struct FuncArgs(Vec); @@ -109,55 +93,6 @@ fn process_args(value: &str) -> Result { Ok(FuncArgs(args)) } -#[derive(Debug, Error)] -pub enum Error { - #[error("Invalid arguments")] - Cli(#[from] clap::Error), - #[error("Failed to interact with the file system")] - IO(#[from] std::io::Error), - #[error(transparent)] - EncodeTrace(#[from] EncodeTraceError), - #[error(transparent)] - VirtualMachine(#[from] VirtualMachineError), - #[error(transparent)] - Trace(#[from] TraceError), - #[error(transparent)] - PublicInput(#[from] PublicInputError), - #[error(transparent)] - Runner(#[from] RunnerError), - #[error(transparent)] - ProgramRegistry(#[from] Box), - #[error(transparent)] - Compilation(#[from] Box), - #[error("Failed to compile to sierra:\n {0}")] - SierraCompilation(String), - #[error(transparent)] - Metadata(#[from] MetadataError), - #[error(transparent)] - Program(#[from] ProgramError), - #[error(transparent)] - Memory(#[from] MemoryError), - #[error("Program panicked with {0:?}")] - RunPanic(Vec), - #[error("Function signature has no return types")] - NoRetTypesInSignature, - #[error("No size for concrete type id: {0}")] - NoTypeSizeForId(ConcreteTypeId), - #[error("Concrete type id has no debug name: {0}")] - TypeIdNoDebugName(ConcreteTypeId), - #[error("No info in sierra program registry for concrete type id: {0}")] - NoInfoForType(ConcreteTypeId), - #[error("Failed to extract return values from VM")] - FailedToExtractReturnValues, - #[error("Function expects arguments of size {expected} and received {actual} instead.")] - ArgumentsSizeMismatch { expected: i16, actual: i16 }, - #[error("Function param {param_index} only partially contains argument {arg_index}.")] - ArgumentUnaligned { - param_index: usize, - arg_index: usize, - }, -} - pub struct FileWriter { buf_writer: io::BufWriter, bytes_written: usize, @@ -220,8 +155,7 @@ fn run(args: impl Iterator) -> Result, Error> { } }; - let (runner, vm, _, serialized_output) = - cairo_run::cairo_run_program(&sierra_program, cairo_run_config)?; + let (runner, vm, _, serialized_output) = cairo_run_program(&sierra_program, cairo_run_config)?; if let Some(file_path) = args.air_public_input { let json = runner.get_air_public_input(&vm)?.serialize_json()?;