Skip to content

Commit

Permalink
Add lib.rs to cairo1-run (#1714)
Browse files Browse the repository at this point in the history
* Add lib.rs

* Add changelog entry

* Add FuncArg docs

* Add Cairo1RunConfig  docs

* fix

* fmt

* fmt
  • Loading branch information
fmoletta authored Apr 24, 2024
1 parent 5e19e9d commit 87dcd17
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 76 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 30 additions & 5 deletions cairo1-run/src/cairo_run.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::error::Error;
use cairo_lang_casm::{
builder::{CasmBuilder, Var},
casm, casm_build_extend,
Expand Down Expand Up @@ -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<Felt252>),
Single(Felt252),
}

impl From<Felt252> for FuncArg {
fn from(value: Felt252) -> Self {
Self::Single(value)
}
}

impl From<Vec<Felt252>> for FuncArg {
fn from(value: Vec<Felt252>) -> 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,
}

Expand Down
62 changes: 62 additions & 0 deletions cairo1-run/src/error.rs
Original file line number Diff line number Diff line change
@@ -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<ProgramRegistryError>),
#[error(transparent)]
Compilation(#[from] Box<CompilationError>),
#[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<Felt252>),
#[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,
},
}
10 changes: 10 additions & 0 deletions cairo1-run/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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,
};
76 changes: 5 additions & 71 deletions cairo1-run/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
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;
use std::{
io::{self, Write},
path::PathBuf,
};
use thiserror::Error;

pub mod cairo_run;

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
Expand Down Expand Up @@ -65,12 +55,6 @@ struct Args {
append_return_values: bool,
}

#[derive(Debug, Clone)]
pub enum FuncArg {
Array(Vec<Felt252>),
Single(Felt252),
}

#[derive(Debug, Clone, Default)]
struct FuncArgs(Vec<FuncArg>);

Expand Down Expand Up @@ -109,55 +93,6 @@ fn process_args(value: &str) -> Result<FuncArgs, String> {
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<ProgramRegistryError>),
#[error(transparent)]
Compilation(#[from] Box<CompilationError>),
#[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<Felt252>),
#[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<std::fs::File>,
bytes_written: usize,
Expand Down Expand Up @@ -220,8 +155,7 @@ fn run(args: impl Iterator<Item = String>) -> Result<Option<String>, 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()?;
Expand Down

0 comments on commit 87dcd17

Please sign in to comment.