Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lib.rs to cairo1-run #1714

Merged
merged 11 commits into from
Apr 24, 2024
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#### Upcoming Changes

* 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::{
casm, casm_extend, hints::Hint, inline::CasmContext, instructions::Instruction,
};
juanbono marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -45,21 +46,45 @@
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)]

Check warning on line 51 in cairo1-run/src/cairo_run.rs

View check run for this annotation

Codecov / codecov/patch

cairo1-run/src/cairo_run.rs#L51

Added line #L51 was not covered by tests
pub enum FuncArg {
juanbono marked this conversation as resolved.
Show resolved Hide resolved
Array(Vec<Felt252>),
Single(Felt252),
}

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

Check warning on line 60 in cairo1-run/src/cairo_run.rs

View check run for this annotation

Codecov / codecov/patch

cairo1-run/src/cairo_run.rs#L58-L60

Added lines #L58 - L60 were not covered by tests
}

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

Check warning on line 66 in cairo1-run/src/cairo_run.rs

View check run for this annotation

Codecov / codecov/patch

cairo1-run/src/cairo_run.rs#L64-L66

Added lines #L64 - L66 were not covered by tests
}

/// Configuration parameters for a cairo run
#[derive(Debug)]
pub struct Cairo1RunConfig<'a> {
juanbono marked this conversation as resolved.
Show resolved Hide resolved
/// 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)]

Check warning on line 15 in cairo1-run/src/error.rs

View check run for this annotation

Codecov / codecov/patch

cairo1-run/src/error.rs#L15

Added line #L15 was not covered by tests
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
Loading