Skip to content

Commit

Permalink
Moved linear cost solving to configuration. (#4372)
Browse files Browse the repository at this point in the history
  • Loading branch information
orizi authored Nov 7, 2023
1 parent 26ac757 commit 61c2a05
Show file tree
Hide file tree
Showing 12 changed files with 56 additions and 61 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/bin/sierra-compile/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn main() -> anyhow::Result<()> {
let gas_usage_check = true;
let cairo_program = cairo_lang_sierra_to_casm::compiler::compile(
&program,
&calc_metadata(&program, Default::default(), false)
&calc_metadata(&program, Default::default())
.with_context(|| "Failed calculating Sierra variables.")?,
gas_usage_check,
)
Expand Down
1 change: 0 additions & 1 deletion crates/cairo-lang-runner/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ cairo-felt.workspace = true
cairo-lang-casm = { path = "../cairo-lang-casm", version = "2.3.1" }
cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.3.1" }
cairo-lang-sierra-ap-change = { path = "../cairo-lang-sierra-ap-change", version = "2.3.1" }
cairo-lang-sierra-gas = { path = "../cairo-lang-sierra-gas", version = "2.3.1" }
cairo-lang-sierra-to-casm = { path = "../cairo-lang-sierra-to-casm", version = "2.3.1" }
cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version = "2.3.1" }
cairo-lang-starknet = { path = "../cairo-lang-starknet", version = "2.3.1" }
Expand Down
22 changes: 8 additions & 14 deletions crates/cairo-lang-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@ use cairo_lang_sierra::extensions::starknet::syscalls::SystemType;
use cairo_lang_sierra::extensions::{ConcreteType, NamedType};
use cairo_lang_sierra::program::{Function, GenericArg};
use cairo_lang_sierra::program_registry::{ProgramRegistry, ProgramRegistryError};
use cairo_lang_sierra_ap_change::{calc_ap_changes, ApChangeError};
use cairo_lang_sierra_gas::gas_info::GasInfo;
use cairo_lang_sierra_ap_change::ApChangeError;
use cairo_lang_sierra_to_casm::compiler::{CairoProgram, CompilationError};
use cairo_lang_sierra_to_casm::metadata::{
calc_metadata, Metadata, MetadataComputationConfig, MetadataError,
calc_metadata, calc_metadata_ap_change_only, Metadata, MetadataComputationConfig, MetadataError,
};
use cairo_lang_sierra_type_size::{get_type_size_map, TypeSizeMap};
use cairo_lang_starknet::contract::ContractInfo;
Expand Down Expand Up @@ -563,17 +562,12 @@ fn create_metadata(
metadata_config: Option<MetadataComputationConfig>,
) -> Result<Metadata, RunnerError> {
if let Some(metadata_config) = metadata_config {
calc_metadata(sierra_program, metadata_config, false).map_err(|err| match err {
MetadataError::ApChangeError(err) => RunnerError::ApChangeError(err),
MetadataError::CostError(_) => RunnerError::FailedGasCalculation,
})
calc_metadata(sierra_program, metadata_config)
} else {
Ok(Metadata {
ap_change_info: calc_ap_changes(sierra_program, |_, _| 0)?,
gas_info: GasInfo {
variable_values: Default::default(),
function_costs: Default::default(),
},
})
calc_metadata_ap_change_only(sierra_program)
}
.map_err(|err| match err {
MetadataError::ApChangeError(err) => RunnerError::ApChangeError(err),
MetadataError::CostError(_) => RunnerError::FailedGasCalculation,
})
}
2 changes: 1 addition & 1 deletion crates/cairo-lang-sierra-ap-change/src/ap_change_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use itertools::Itertools;

/// Ap change information for a Sierra program.
#[derive(Debug, Eq, PartialEq)]
#[derive(Debug, Default, Eq, PartialEq)]
pub struct ApChangeInfo {
/// The values of variables at matching libfuncs at given statements indices.
pub variable_values: OrderedHashMap<StatementIdx, usize>,
Expand Down
19 changes: 14 additions & 5 deletions crates/cairo-lang-sierra-to-casm/src/compiler_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use pretty_assertions;
use test_case::test_case;

use crate::compiler::compile;
use crate::test_utils::{build_metadata, read_sierra_example_file, strip_comments_and_linebreaks};
use crate::metadata::{calc_metadata, calc_metadata_ap_change_only};
use crate::test_utils::{read_sierra_example_file, strip_comments_and_linebreaks};

#[test_case(indoc! {"
type felt252 = felt252;
Expand Down Expand Up @@ -389,9 +390,17 @@ use crate::test_utils::{build_metadata, read_sierra_example_file, strip_comments
fn sierra_to_casm(sierra_code: &str, check_gas_usage: bool, expected_casm: &str) {
let program = ProgramParser::new().parse(sierra_code).unwrap();
pretty_assertions::assert_eq!(
compile(&program, &build_metadata(&program, check_gas_usage, false), check_gas_usage)
.expect("Compilation failed.")
.to_string(),
compile(
&program,
&if check_gas_usage {
calc_metadata(&program, Default::default()).unwrap_or_default()
} else {
calc_metadata_ap_change_only(&program).unwrap_or_default()
},
check_gas_usage
)
.expect("Compilation failed.")
.to_string(),
strip_comments_and_linebreaks(expected_casm)
);
}
Expand Down Expand Up @@ -798,7 +807,7 @@ of the libfunc or return statement.";
fn compiler_errors(sierra_code: &str, expected_result: &str) {
let program = ProgramParser::new().parse(sierra_code).unwrap();
pretty_assertions::assert_eq!(
compile(&program, &build_metadata(&program, false, false), false)
compile(&program, &calc_metadata_ap_change_only(&program).unwrap_or_default(), false)
.expect_err("Compilation is expected to fail.")
.to_string(),
expected_result
Expand Down
19 changes: 17 additions & 2 deletions crates/cairo-lang-sierra-to-casm/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use cairo_lang_sierra_gas::{
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use thiserror::Error;

#[derive(Default)]
/// Metadata provided with a Sierra program to simplify the compilation to casm.
pub struct Metadata {
/// AP changes information for Sierra user functions.
Expand All @@ -31,14 +32,28 @@ pub enum MetadataError {
/// Configuration for metadata computation.
#[derive(Clone, Default)]
pub struct MetadataComputationConfig {
/// Functions to enforce costs for, as well as the costs to enforce.
pub function_set_costs: OrderedHashMap<FunctionId, OrderedHashMap<CostTokenType, i32>>,
/// If true, uses a linear-time algorithm for calculating the gas, instead of solving
/// equations.
pub linear_gas_solver: bool,
}

/// Calculates the metadata for a Sierra program, with ap change info only.
pub fn calc_metadata_ap_change_only(program: &Program) -> Result<Metadata, MetadataError> {
Ok(Metadata {
ap_change_info: calc_ap_changes(program, |_, _| 0)?,
gas_info: GasInfo {
variable_values: Default::default(),
function_costs: Default::default(),
},
})
}

/// Calculates the metadata for a Sierra program.
pub fn calc_metadata(
program: &Program,
config: MetadataComputationConfig,
no_eq_solver: bool,
) -> Result<Metadata, MetadataError> {
let pre_function_set_costs = config
.function_set_costs
Expand Down Expand Up @@ -79,7 +94,7 @@ pub fn calc_metadata(
ap_change_info.variable_values.get(&idx).copied().unwrap_or_default()
})?;

if no_eq_solver {
if config.linear_gas_solver {
let enforced_function_costs: OrderedHashMap<FunctionId, i32> = config
.function_set_costs
.iter()
Expand Down
28 changes: 0 additions & 28 deletions crates/cairo-lang-sierra-to-casm/src/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,8 @@
use std::fs;
use std::path::PathBuf;

use cairo_lang_sierra::program::Program;
use cairo_lang_sierra_ap_change::ap_change_info::ApChangeInfo;
use cairo_lang_sierra_ap_change::calc_ap_changes;
use cairo_lang_sierra_gas::gas_info::GasInfo;
use itertools::Itertools;

use crate::metadata::{calc_metadata, Metadata, MetadataComputationConfig};

/// Builds the metadata for a Sierra program.
///
/// `no_eq_solver` uses a linear-time algorithm for calculating the gas, instead of solving
/// equations.
pub fn build_metadata(program: &Program, calculate_gas_info: bool, no_eq_solver: bool) -> Metadata {
if calculate_gas_info {
calc_metadata(program, MetadataComputationConfig::default(), no_eq_solver)
.expect("Failed calculating gas or ap change.")
} else {
Metadata {
ap_change_info: calc_ap_changes(program, |_, _| 0).unwrap_or(ApChangeInfo {
function_ap_change: Default::default(),
variable_values: Default::default(),
}),
gas_info: GasInfo {
variable_values: Default::default(),
function_costs: Default::default(),
},
}
}
}

/// Reads an example Sierra program that matches `name`.
pub fn read_sierra_example_file(name: &str) -> String {
// Pop the "/sierra_to_casm" suffix.
Expand Down
3 changes: 2 additions & 1 deletion crates/cairo-lang-starknet/src/casm_contract_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,8 +283,9 @@ impl CasmContractClass {
function_set_costs: entrypoint_ids
.map(|id| (id, [(CostTokenType::Const, ENTRY_POINT_COST)].into()))
.collect(),
linear_gas_solver: false,
};
let metadata = calc_metadata(&program, metadata_computation_config, false)?;
let metadata = calc_metadata(&program, metadata_computation_config)?;

let gas_usage_check = true;
let cairo_program =
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-lang-test-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ pub fn run_tests(
) -> Result<TestsSummary> {
let runner = SierraCasmRunner::new(
sierra_program,
Some(MetadataComputationConfig { function_set_costs }),
Some(MetadataComputationConfig { function_set_costs, linear_gas_solver: true }),
contracts_info,
)
.with_context(|| "Failed setting up runner.")?;
Expand Down
8 changes: 5 additions & 3 deletions tests/e2e_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,9 @@ fn run_e2e_test(
};

// Compute the metadata.
let metadata_config = MetadataComputationConfig { function_set_costs: enforced_costs };
let metadata = calc_metadata(&sierra_program, metadata_config.clone(), false).unwrap();
let mut metadata_config =
MetadataComputationConfig { function_set_costs: enforced_costs, linear_gas_solver: false };
let metadata = calc_metadata(&sierra_program, metadata_config.clone()).unwrap();

// Compile to casm.
let casm = cairo_lang_sierra_to_casm::compiler::compile(&sierra_program, &metadata, true)
Expand All @@ -199,7 +200,8 @@ fn run_e2e_test(
let mut res: OrderedHashMap<String, String> =
OrderedHashMap::from([("casm".into(), casm), ("sierra_code".into(), sierra_program_str)]);
if params.metadata_computation {
let metadata_no_solver = calc_metadata(&sierra_program, metadata_config, true).unwrap();
metadata_config.linear_gas_solver = true;
let metadata_no_solver = calc_metadata(&sierra_program, metadata_config).unwrap();
res.insert("gas_solution".into(), format!("{}", metadata.gas_info));
res.insert("gas_solution_no_solver".into(), format!("{}", metadata_no_solver.gas_info));
res.insert("ap_solution".into(), format!("{}", metadata.ap_change_info));
Expand Down
10 changes: 7 additions & 3 deletions tests/examples_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use cairo_lang_runner::{token_gas_cost, Arg, RunResultValue, SierraCasmRunner};
use cairo_lang_sierra::extensions::gas::CostTokenType;
use cairo_lang_sierra_generator::db::SierraGenGroup;
use cairo_lang_sierra_generator::replace_ids::replace_sierra_ids_in_program;
use cairo_lang_sierra_to_casm::test_utils::build_metadata;
use cairo_lang_sierra_to_casm::metadata::{calc_metadata, calc_metadata_ap_change_only};
use cairo_lang_test_utils::compare_contents_or_fix_with_path;
use cairo_lang_utils::{extract_matches, Upcast};
use itertools::Itertools;
Expand Down Expand Up @@ -151,7 +151,11 @@ fn cairo_to_casm(
"casm",
cairo_lang_sierra_to_casm::compiler::compile(
&program,
&build_metadata(&program, enable_gas_checks, false),
&if enable_gas_checks {
calc_metadata(&program, Default::default()).unwrap()
} else {
calc_metadata_ap_change_only(&program).unwrap()
},
enable_gas_checks,
)
.unwrap()
Expand All @@ -169,7 +173,7 @@ fn cairo_to_casm_auto_gas(#[case] name: &str, example_dir_data: &ExampleDirData)
"casm",
cairo_lang_sierra_to_casm::compiler::compile(
&program,
&build_metadata(&program, true, false),
&calc_metadata(&program, Default::default()).unwrap(),
true,
)
.unwrap()
Expand Down

0 comments on commit 61c2a05

Please sign in to comment.