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

Cairo 2.1.1 #138

Merged
merged 12 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Reverting old changes
  • Loading branch information
shramee committed Aug 20, 2023
commit ef1423bd01d175ec5179caf4f802455d37affc0b
24 changes: 7 additions & 17 deletions src/exercise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use regex::Regex;
use serde::Deserialize;

use crate::starklings_runner::{run_cairo_program, Args as RunnerArgs};
use cairo_lang_test_runner::TestRunner;
use crate::starklings_tester::TestRunner;
use std::fmt::{self, Display, Formatter};
use std::fs::{remove_file, File};
use std::io::Read;
Expand Down Expand Up @@ -92,27 +92,16 @@ impl Drop for FileHandle {

impl Exercise {
pub fn run_cairo(&self) -> anyhow::Result<String> {
let res = run_cairo_program(RunnerArgs {
run_cairo_program(&RunnerArgs {
path: self.path.to_str().unwrap().parse()?,
single_file: true,
available_gas: None,
available_gas: Some(20000000000),
print_full_memory: false,
});

match res {
Ok(_) => Ok("Compiled successfully!".into()), // Logs already printed, Silence
Err(_) => anyhow::bail!("Error compiling the file."),
}
})
}

pub fn test_cairo(&self) -> anyhow::Result<String> {
let runner = TestRunner::new(&self.path, "", false, false, true)?;
let run_result = runner.run();

match run_result {
Ok(_) => Ok("Tests passed!".into()),
Err(_) => anyhow::bail!("Error running tests"),
}
let runner = TestRunner::new(self.path.to_str().unwrap(), "", false, false, true)?;
runner.run()
}

pub fn state(&self) -> State {
Expand Down Expand Up @@ -183,6 +172,7 @@ fn clean() {
mod test {
use super::*;
// use std::path::Path;

#[test]
fn test_finished_exercise() {
let exercise = Exercise {
Expand Down
8 changes: 8 additions & 0 deletions src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ fn run_cairo(exercise: &Exercise) -> Result<(), ()> {

if let Some(error) = output.as_ref().err() {
progress_bar.finish_and_clear();
println!("Err");
println!("{error}");

println!("Normal");
println!("{error}");
Err(())
} else {
Expand All @@ -60,6 +64,10 @@ fn test_cairo(exercise: &Exercise) -> Result<(), ()> {

if let Some(error) = output.as_ref().err() {
progress_bar.finish_and_clear();
println!("Err");
println!("{error}");

println!("Normal");
println!("{error}");
Err(())
} else {
Expand Down
80 changes: 41 additions & 39 deletions src/starklings_runner.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
//! Compiles and runs a Cairo program.

use std::path::{Path, PathBuf};
use std::path::Path;
use std::sync::Arc;

use anyhow::{Context, Ok};
use cairo_lang_compiler::db::RootDatabase;
use cairo_lang_compiler::diagnostics::DiagnosticsReporter;
use cairo_lang_compiler::project::{check_compiler_path, setup_project};
use cairo_lang_compiler::project::setup_project;
use cairo_lang_diagnostics::ToOption;
use cairo_lang_runner::short_string::as_cairo_short_string;
use cairo_lang_filesystem::db::init_dev_corelib;

use cairo_lang_runner::{SierraCasmRunner, StarknetState};

use cairo_lang_sierra::extensions::gas::{
BuiltinCostWithdrawGasLibfunc, RedepositGasLibfunc, WithdrawGasLibfunc,
};
use cairo_lang_sierra::extensions::NamedLibfunc;
use cairo_lang_sierra_generator::db::SierraGenGroup;
use cairo_lang_sierra_generator::replace_ids::{DebugReplacer, SierraIdReplacer};
use cairo_lang_starknet::contract::get_contracts_info;
use cairo_lang_starknet::plugin::StarkNetPlugin;
use clap::Parser;

const CORELIB_DIR_NAME: &str = "corelib/src";

/// Command line args parser.
/// Exits with 0/1 if the input is formatted correctly/incorrectly.
#[derive(Parser, Debug)]
#[clap(version, verbatim_doc_comment)]
pub struct Args {
/// The file to compile and run.
pub path: PathBuf,
/// Whether path is a single file.
#[arg(short, long)]
pub single_file: bool,
pub path: String,
/// In cases where gas is available, the amount of provided gas.
#[arg(long)]
pub available_gas: Option<usize>,
Expand All @@ -36,22 +40,40 @@ pub struct Args {
pub print_full_memory: bool,
}

pub fn main() -> anyhow::Result<()> {
run_cairo_program(Args::parse())
fn main() -> anyhow::Result<()> {
let args = Args::parse();
let res = run_cairo_program(&args);
if let Err(e) = res {
eprintln!("{e}");
std::process::exit(1);
}
Ok(())
}

pub fn run_cairo_program(args: Args) -> anyhow::Result<()> {
// Check if args.path is a file or a directory.
check_compiler_path(args.single_file, &args.path)?;
pub fn run_cairo_program(args: &Args) -> anyhow::Result<String> {
let db = &mut {
let mut b = RootDatabase::builder();
b.detect_corelib();
b.with_semantic_plugin(Arc::new(StarkNetPlugin::default()));

let db = &mut RootDatabase::builder().detect_corelib().build()?;
b.build()?
};
let mut corelib_dir = std::env::current_exe()
.unwrap_or_else(|e| panic!("Problem getting the executable path: {e:?}"));
corelib_dir.pop();
corelib_dir.pop();
corelib_dir.pop();
corelib_dir.push(CORELIB_DIR_NAME);
init_dev_corelib(db, corelib_dir);

let main_crate_ids = setup_project(db, Path::new(&args.path))?;

if DiagnosticsReporter::stderr().check(db) {
anyhow::bail!("failed to compile: {}", args.path.display());
anyhow::bail!("failed to compile: {}", args.path);
}

let mut ret_string = String::new();

let sierra_program = db
.get_sierra_program(main_crate_ids.clone())
.to_option()
Expand Down Expand Up @@ -83,40 +105,20 @@ pub fn run_cairo_program(args: Args) -> anyhow::Result<()> {
)
.with_context(|| "Failed setting up runner.")?;
let result = runner
.run_function_with_starknet_context(
.run_function(
runner.find_function("::main")?,
&[],
args.available_gas,
StarknetState::default(),
)
.with_context(|| "Failed to run the function.")?;
match result.value {
cairo_lang_runner::RunResultValue::Success(values) => {
println!("Run completed successfully, returning {values:?}")
}
cairo_lang_runner::RunResultValue::Success(values) => ret_string
.push_str(format!("Run completed successfully, returning {values:?}").as_str()),
cairo_lang_runner::RunResultValue::Panic(values) => {
print!("Run panicked with [");
for value in &values {
match as_cairo_short_string(value) {
Some(as_string) => print!("{value} ('{as_string}'), "),
None => print!("{value}, "),
}
}
println!("].")
ret_string.push_str(format!("Run panicked with err values: {values:?}").as_str());
}
}
if let Some(gas) = result.gas_counter {
println!("Remaining gas: {gas}");
}
if args.print_full_memory {
print!("Full memory: [");
for cell in &result.memory {
match cell {
None => print!("_, "),
Some(value) => print!("{value}, "),
}
}
println!("]");
}
Ok(())
println!("{ret_string}");
Ok(ret_string)
}
Loading