Repository: lambdaclass/cairo-vm (language: rust)

Issue:
Feature request: Enable Access to cairo1-run Functionality and Types in External Rust Projects
**Problem description**
Currently, when trying to include the `cairo1-run` package as a dependency in a Rust project, it's not possible to directly access its functionality and types defined inside. This limitation restricts the usability of `cairo1-run` in other Rust projects.

**Solution description**
I would like to be able to add `cairo1-run` as a package to other Rust projects and have access to its functionality and types defined inside. To achieve this, I propose adding a `lib` target to the existing `cairo1-run` package, allowing users to import it into their projects using a line like the following in `Cargo.toml`:
```toml
cairo1-run = { git = "https://github.com/lambdaclass/cairo-vm" }
```

Is it possible to include this in *branch:* `cairo-lang-2.6.3`?


Discussion / hints:

Fix patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6c15aaa681..1ce1f94d7b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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)
diff --git a/cairo1-run/src/cairo_run.rs b/cairo1-run/src/cairo_run.rs
index 3cbb4076b4..4dc4b3fa5b 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::{
     casm, casm_extend, hints::Hint, inline::CasmContext, instructions::Instruction,
 };
@@ -45,21 +46,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,
 }
 
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<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,
+    },
+}
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<Felt252>),
-    Single(Felt252),
-}
-
 #[derive(Debug, Clone, Default)]
 struct FuncArgs(Vec<FuncArg>);
 
@@ -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,
@@ -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()?;


Test patch: