Skip to content

Commit

Permalink
Merge branch 'main' into feat/compile-contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
edg-l authored Sep 23, 2024
2 parents a0b9bda + 0e96dff commit 8155c8e
Show file tree
Hide file tree
Showing 87 changed files with 3,211 additions and 4,821 deletions.
4 changes: 2 additions & 2 deletions examples/easy_api.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cairo_native::{
context::NativeContext, executor::JitNativeExecutor, utils::cairo_to_sierra, values::JitValue,
context::NativeContext, executor::JitNativeExecutor, utils::cairo_to_sierra, Value,
};
use starknet_types_core::felt::Felt;
use std::path::Path;
Expand All @@ -18,7 +18,7 @@ fn main() {
let native_program = native_context.compile(&sierra_program, false).unwrap();

// The parameters of the entry point.
let params = &[JitValue::Felt252(Felt::from_bytes_be_slice(b"user"))];
let params = &[Value::Felt252(Felt::from_bytes_be_slice(b"user"))];

// Find the entry point id by its name.
let entry_point = "hello::hello::greet";
Expand Down
4 changes: 2 additions & 2 deletions examples/invoke.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cairo_native::{
context::NativeContext, executor::JitNativeExecutor, utils::find_entry_point, values::JitValue,
context::NativeContext, executor::JitNativeExecutor, utils::find_entry_point, Value,
};
use std::path::Path;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
Expand Down Expand Up @@ -30,7 +30,7 @@ fn main() {

let native_executor = JitNativeExecutor::from_native_module(native_program, Default::default());

let output = native_executor.invoke_dynamic(fn_id, &[JitValue::Felt252(1.into())], None);
let output = native_executor.invoke_dynamic(fn_id, &[Value::Felt252(1.into())], None);

println!();
println!("Cairo program was compiled and executed successfully.");
Expand Down
50 changes: 25 additions & 25 deletions src/arch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
error,
starknet::{ArrayAbi, U256},
types::TypeBuilder,
values::JitValue,
values::Value,
};
use bumpalo::Bump;
use cairo_lang_sierra::{
Expand All @@ -28,7 +28,7 @@ pub trait AbiArgument {
/// A wrapper that implements `AbiArgument` for `JitValue`s. It contains all the required stuff to
/// serialize all possible `JitValue`s.
pub struct JitValueWithInfoWrapper<'a> {
pub value: &'a JitValue,
pub value: &'a Value,
pub type_id: &'a ConcreteTypeId,
pub info: &'a CoreTypeConcrete,

Expand All @@ -39,7 +39,7 @@ pub struct JitValueWithInfoWrapper<'a> {
impl<'a> JitValueWithInfoWrapper<'a> {
fn map<'b>(
&'b self,
value: &'b JitValue,
value: &'b Value,
type_id: &'b ConcreteTypeId,
) -> Result<JitValueWithInfoWrapper<'b>, error::Error>
where
Expand Down Expand Up @@ -71,7 +71,7 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
heap_ptr.to_bytes(buffer)?;
}
(value, CoreTypeConcrete::Nullable(info)) => {
if matches!(value, JitValue::Null) {
if matches!(value, Value::Null) {
null::<()>().to_bytes(buffer)?;
} else {
let ptr = value.to_jit(self.arena, self.registry, self.type_id)?;
Expand All @@ -90,7 +90,7 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
self.map(value, &info.ty)?.to_bytes(buffer)?
}

(JitValue::Array(_), CoreTypeConcrete::Array(_)) => {
(Value::Array(_), CoreTypeConcrete::Array(_)) => {
// TODO: Assert that `info.ty` matches all the values' types.

let abi_ptr = self.value.to_jit(self.arena, self.registry, self.type_id)?;
Expand All @@ -101,19 +101,19 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
abi.until.to_bytes(buffer)?;
abi.capacity.to_bytes(buffer)?;
}
(JitValue::BoundedInt { .. }, CoreTypeConcrete::BoundedInt(_)) => todo!(),
(JitValue::Bytes31(value), CoreTypeConcrete::Bytes31(_)) => value.to_bytes(buffer)?,
(JitValue::EcPoint(x, y), CoreTypeConcrete::EcPoint(_)) => {
(Value::BoundedInt { .. }, CoreTypeConcrete::BoundedInt(_)) => todo!(),
(Value::Bytes31(value), CoreTypeConcrete::Bytes31(_)) => value.to_bytes(buffer)?,
(Value::EcPoint(x, y), CoreTypeConcrete::EcPoint(_)) => {
x.to_bytes(buffer)?;
y.to_bytes(buffer)?;
}
(JitValue::EcState(x, y, x0, y0), CoreTypeConcrete::EcState(_)) => {
(Value::EcState(x, y, x0, y0), CoreTypeConcrete::EcState(_)) => {
x.to_bytes(buffer)?;
y.to_bytes(buffer)?;
x0.to_bytes(buffer)?;
y0.to_bytes(buffer)?;
}
(JitValue::Enum { tag, value, .. }, CoreTypeConcrete::Enum(info)) => {
(Value::Enum { tag, value, .. }, CoreTypeConcrete::Enum(info)) => {
if self.info.is_memory_allocated(self.registry)? {
let abi_ptr = self.value.to_jit(self.arena, self.registry, self.type_id)?;

Expand All @@ -129,7 +129,7 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
}
}
(
JitValue::Felt252(value),
Value::Felt252(value),
CoreTypeConcrete::Felt252(_)
| CoreTypeConcrete::StarkNet(
StarkNetTypeConcrete::ClassHash(_)
Expand All @@ -138,7 +138,7 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
| StarkNetTypeConcrete::StorageBaseAddress(_),
),
) => value.to_bytes(buffer)?,
(JitValue::Felt252Dict { .. }, CoreTypeConcrete::Felt252Dict(_)) => {
(Value::Felt252Dict { .. }, CoreTypeConcrete::Felt252Dict(_)) => {
#[cfg(not(feature = "with-runtime"))]
unimplemented!("enable the `with-runtime` feature to use felt252 dicts");

Expand All @@ -150,13 +150,13 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
.to_bytes(buffer)?
}
(
JitValue::Secp256K1Point { x, y },
Value::Secp256K1Point { x, y },
CoreTypeConcrete::StarkNet(StarkNetTypeConcrete::Secp256Point(
Secp256PointTypeConcrete::K1(_),
)),
)
| (
JitValue::Secp256R1Point { x, y },
Value::Secp256R1Point { x, y },
CoreTypeConcrete::StarkNet(StarkNetTypeConcrete::Secp256Point(
Secp256PointTypeConcrete::R1(_),
)),
Expand All @@ -167,23 +167,23 @@ impl<'a> AbiArgument for JitValueWithInfoWrapper<'a> {
x.to_bytes(buffer)?;
y.to_bytes(buffer)?;
}
(JitValue::Sint128(value), CoreTypeConcrete::Sint128(_)) => value.to_bytes(buffer)?,
(JitValue::Sint16(value), CoreTypeConcrete::Sint16(_)) => value.to_bytes(buffer)?,
(JitValue::Sint32(value), CoreTypeConcrete::Sint32(_)) => value.to_bytes(buffer)?,
(JitValue::Sint64(value), CoreTypeConcrete::Sint64(_)) => value.to_bytes(buffer)?,
(JitValue::Sint8(value), CoreTypeConcrete::Sint8(_)) => value.to_bytes(buffer)?,
(JitValue::Struct { fields, .. }, CoreTypeConcrete::Struct(info)) => {
(Value::Sint128(value), CoreTypeConcrete::Sint128(_)) => value.to_bytes(buffer)?,
(Value::Sint16(value), CoreTypeConcrete::Sint16(_)) => value.to_bytes(buffer)?,
(Value::Sint32(value), CoreTypeConcrete::Sint32(_)) => value.to_bytes(buffer)?,
(Value::Sint64(value), CoreTypeConcrete::Sint64(_)) => value.to_bytes(buffer)?,
(Value::Sint8(value), CoreTypeConcrete::Sint8(_)) => value.to_bytes(buffer)?,
(Value::Struct { fields, .. }, CoreTypeConcrete::Struct(info)) => {
fields
.iter()
.zip(&info.members)
.map(|(value, type_id)| self.map(value, type_id))
.try_for_each(|wrapper| wrapper?.to_bytes(buffer))?;
}
(JitValue::Uint128(value), CoreTypeConcrete::Uint128(_)) => value.to_bytes(buffer)?,
(JitValue::Uint16(value), CoreTypeConcrete::Uint16(_)) => value.to_bytes(buffer)?,
(JitValue::Uint32(value), CoreTypeConcrete::Uint32(_)) => value.to_bytes(buffer)?,
(JitValue::Uint64(value), CoreTypeConcrete::Uint64(_)) => value.to_bytes(buffer)?,
(JitValue::Uint8(value), CoreTypeConcrete::Uint8(_)) => value.to_bytes(buffer)?,
(Value::Uint128(value), CoreTypeConcrete::Uint128(_)) => value.to_bytes(buffer)?,
(Value::Uint16(value), CoreTypeConcrete::Uint16(_)) => value.to_bytes(buffer)?,
(Value::Uint32(value), CoreTypeConcrete::Uint32(_)) => value.to_bytes(buffer)?,
(Value::Uint64(value), CoreTypeConcrete::Uint64(_)) => value.to_bytes(buffer)?,
(Value::Uint8(value), CoreTypeConcrete::Uint8(_)) => value.to_bytes(buffer)?,
_ => todo!(
"abi argument unimplemented for ({:?}, {:?})",
self.value,
Expand Down
33 changes: 25 additions & 8 deletions src/bin/cairo-native-run.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
mod utils;

use anyhow::Context;
use cairo_lang_compiler::{
compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig,
};
use cairo_lang_runner::short_string::as_cairo_short_string;
use cairo_native::{
context::NativeContext,
executor::{AotNativeExecutor, JitNativeExecutor, NativeExecutor},
executor::{AotNativeExecutor, JitNativeExecutor},
metadata::gas::{GasMetadata, MetadataComputationConfig},
starknet_stub::StubSyscallHandler,
};
Expand All @@ -16,6 +14,8 @@ use std::path::PathBuf;
use tracing_subscriber::{EnvFilter, FmtSubscriber};
use utils::{find_function, result_to_runresult};

mod utils;

#[derive(Clone, Debug, ValueEnum)]
enum RunMode {
Aot,
Expand Down Expand Up @@ -74,12 +74,30 @@ fn main() -> anyhow::Result<()> {
// Compile the sierra program into a MLIR module.
let native_module = native_context.compile(&sierra_program, false).unwrap();

let native_executor: NativeExecutor = match args.run_mode {
let native_executor: Box<dyn Fn(_, _, _, &mut StubSyscallHandler) -> _> = match args.run_mode {
RunMode::Aot => {
AotNativeExecutor::from_native_module(native_module, args.opt_level.into()).into()
let executor =
AotNativeExecutor::from_native_module(native_module, args.opt_level.into());
Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
)
})
}
RunMode::Jit => {
JitNativeExecutor::from_native_module(native_module, args.opt_level.into()).into()
let executor =
JitNativeExecutor::from_native_module(native_module, args.opt_level.into());
Box::new(move |function_id, args, gas, syscall_handler| {
executor.invoke_dynamic_with_syscall_handler(
function_id,
args,
gas,
syscall_handler,
)
})
}
};

Expand All @@ -94,8 +112,7 @@ fn main() -> anyhow::Result<()> {

let mut syscall_handler = StubSyscallHandler::default();

let result = native_executor
.invoke_dynamic_with_syscall_handler(&func.id, &[], Some(initial_gas), &mut syscall_handler)
let result = native_executor(&func.id, &[], Some(initial_gas), &mut syscall_handler)
.with_context(|| "Failed to run the function.")?;

let run_result = result_to_runresult(&result)?;
Expand Down
43 changes: 24 additions & 19 deletions src/bin/cairo-native-stress/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,38 @@
//!
//! For documentation on the specific cache used, see `NaiveAotCache`.
use cairo_lang_sierra::ids::FunctionId;
use cairo_lang_sierra::program::{GenericArg, Program};
use cairo_lang_sierra::program_registry::ProgramRegistry;
use cairo_lang_sierra::{
ids::FunctionId,
program::{GenericArg, Program},
program_registry::ProgramRegistry,
};
use cairo_lang_starknet::compile::compile_path;
use cairo_native::metadata::gas::GasMetadata;
use cairo_native::utils::SHARED_LIBRARY_EXT;
use cairo_native::{
context::NativeContext, executor::AotNativeExecutor, starknet::DummySyscallHandler,
utils::find_entry_point_by_idx,
context::NativeContext,
executor::AotNativeExecutor,
metadata::gas::GasMetadata,
module_to_object, object_to_shared_lib,
starknet::DummySyscallHandler,
utils::{find_entry_point_by_idx, SHARED_LIBRARY_EXT},
OptLevel,
};
use cairo_native::{module_to_object, object_to_shared_lib, OptLevel};
use clap::Parser;
use libloading::Library;
use num_bigint::BigInt;
use stats_alloc::{Region, StatsAlloc, INSTRUMENTED_SYSTEM};
use std::alloc::System;
use std::fmt::{Debug, Display};
use std::fs::{create_dir_all, read_dir, OpenOptions};
use std::hash::Hash;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{collections::HashMap, fs, time::Instant};
use std::{
alloc::System,
collections::HashMap,
fmt::{Debug, Display},
fs::{self, create_dir_all, read_dir, OpenOptions},
hash::Hash,
io,
path::{Path, PathBuf},
sync::Arc,
time::Instant,
};
use tracing::{debug, info, info_span, warn};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};

#[global_allocator]
static GLOBAL_ALLOC: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;
Expand Down
4 changes: 2 additions & 2 deletions src/bin/cairo-native-test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
mod utils;

use anyhow::bail;
use cairo_lang_compiler::{
db::RootDatabase,
Expand All @@ -17,6 +15,8 @@ use utils::{
RunArgs, RunMode,
};

mod utils;

/// Compiles a Cairo project and runs all the functions marked as `#[test]`.
/// Exits with 1 if the compilation or run fails, otherwise 0.
#[derive(Parser, Debug)]
Expand Down
8 changes: 3 additions & 5 deletions src/bin/scarb-native-dump.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
mod utils;

use std::{env, fs};

use anyhow::Context;
use cairo_lang_sierra::program::VersionedProgram;
use cairo_native::context::NativeContext;
use melior::ir::operation::OperationPrintingFlags;
use scarb_metadata::{MetadataCommand, ScarbCommand};
use std::{env, fs};

/// Compiles all packages from a Scarb project on the current directory.
mod utils;

/// Compiles all packages from a Scarb project on the current directory.
fn main() -> anyhow::Result<()> {
let metadata = MetadataCommand::new().inherit_stderr().exec()?;

Expand Down
15 changes: 7 additions & 8 deletions src/bin/scarb-native-test.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
mod utils;

use std::collections::HashSet;
use std::path::Path;
use std::{env, fs};

use anyhow::Context;
use cairo_lang_sierra::program::VersionedProgram;
use cairo_lang_test_plugin::{TestCompilation, TestCompilationMetadata};
use clap::{Parser, ValueEnum};
use scarb_metadata::{Metadata, MetadataCommand, ScarbCommand};
use scarb_ui::args::PackagesFilter;
use utils::test::{display_tests_summary, filter_test_cases, find_testable_targets, run_tests};
use utils::{RunArgs, RunMode};
use std::{collections::HashSet, env, fs, path::Path};
use utils::{
test::{display_tests_summary, filter_test_cases, find_testable_targets, run_tests},
RunArgs, RunMode,
};

mod utils;

/// Compiles all packages from a Scarb project matching `packages_filter` and
/// runs all functions marked with `#[test]`. Exits with 1 if the compilation
Expand Down
Loading

0 comments on commit 8155c8e

Please sign in to comment.