diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 458fc9f02d1..bf65178b011 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,18 @@ on: types: [checks_requested] jobs: + ensure-no_std: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: nightly-2023-07-05 + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + - run: | + cd ensure-no_std && cargo build + parallel-tests: runs-on: ubuntu-latest strategy: @@ -41,6 +53,7 @@ jobs: - test -p cairo-lang-test-runner - test -p cairo-lang-test-utils - test -p cairo-lang-utils + - test -p cairo-lang-utils --no-default-features --features=serde - test -p tests steps: - uses: actions/checkout@v3 diff --git a/.gitignore b/.gitignore index b899c194d09..066863199e1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,7 @@ node_modules .DS_Store perf.data* flamegraph.svg + +ensure-no_std/Cargo.lock +ensure-no_std/target/ + diff --git a/Cargo.lock b/Cargo.lock index 94dfd8e194b..5499de5cabe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -995,6 +995,7 @@ name = "cairo-lang-utils" version = "2.4.1" dependencies = [ "env_logger", + "hashbrown 0.14.3", "indexmap 2.1.0", "itertools 0.11.0", "log", @@ -1053,7 +1054,7 @@ dependencies = [ "bitvec", "cairo-felt", "generic-array", - "hashbrown 0.14.2", + "hashbrown 0.14.3", "hex", "keccak", "lazy_static", @@ -1277,7 +1278,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown 0.14.2", + "hashbrown 0.14.3", "lock_api", "once_cell", "parking_lot_core 0.9.9", @@ -1637,9 +1638,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.2" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ "ahash 0.8.6", "allocator-api2", @@ -1762,7 +1763,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" dependencies = [ "equivalent", - "hashbrown 0.14.2", + "hashbrown 0.14.3", "serde", ] @@ -2204,10 +2205,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" dependencies = [ "arrayvec", - "bitvec", "byte-slice-cast", "impl-trait-for-tuples", - "serde", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 9da7bc07795..0fe18f47e72 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,6 +49,7 @@ members = [ "crates/bin/starknet-sierra-upgrade-validate", "tests", ] +exclude = ["ensure-no_std"] [workspace.package] version = "2.4.1" @@ -77,21 +78,22 @@ diffy = "0.3.0" env_logger = "0.10.0" genco = "0.17.8" good_lp = { version = "1.7.0", features = ["minilp"], default-features = false } +hashbrown = "0.14.3" id-arena = "2.2.1" ignore = "0.4.20" indent = "0.1.1" -indexmap = { version = "2.1.0", features = ["serde"] } +indexmap = { version = "2.1.0", default-features = false } indoc = "2.0.4" -itertools = "0.11.0" +itertools = { version = "0.11.0", default-features = false } keccak = "0.1.4" lalrpop-util = { version = "0.20.0", features = ["lexer"] } log = "0.4" lsp = { version = "0.94", package = "lsp-types" } -num-bigint = { version = "0.4", features = ["serde"] } +num-bigint = { version = "0.4", default-features = false } num-integer = "0.1" -num-traits = "0.2" +num-traits = { version = "0.2", default-features = false } once_cell = "1.18.0" -parity-scale-codec = "3.6.5" +parity-scale-codec = { version = "3.6.5", default-features = false } parity-scale-codec-derive = "3.6.5" path-clean = "1.0.1" pretty_assertions = "1.4.0" @@ -102,7 +104,7 @@ rstest = "0.18.2" salsa = "0.16.1" scarb-metadata = "1" schemars = { version = "0.8.15", features = ["preserve_order"] } -serde = { version = "1.0.192", features = ["derive"] } +serde = { version = "1.0.192", default-features = false, features = ["derive"] } serde_json = "1.0" sha3 = "0.10.8" smol_str = { version = "0.2.0", features = ["serde"] } diff --git a/crates/bin/generate-syntax/Cargo.toml b/crates/bin/generate-syntax/Cargo.toml index 209296af5b4..543f10a9629 100644 --- a/crates/bin/generate-syntax/Cargo.toml +++ b/crates/bin/generate-syntax/Cargo.toml @@ -8,7 +8,7 @@ license-file.workspace = true [dependencies] log.workspace = true -cairo-lang-utils = { path = "../../cairo-lang-utils", features = [ +cairo-lang-utils = { path = "../../cairo-lang-utils", version = "2.4.1", features = [ "env_logger", ] } -cairo-lang-syntax-codegen = { path = "../../cairo-lang-syntax-codegen" } +cairo-lang-syntax-codegen = { path = "../../cairo-lang-syntax-codegen", version = "2.4.1" } diff --git a/crates/bin/starknet-sierra-compile/Cargo.toml b/crates/bin/starknet-sierra-compile/Cargo.toml index 675207f1479..67ade337620 100644 --- a/crates/bin/starknet-sierra-compile/Cargo.toml +++ b/crates/bin/starknet-sierra-compile/Cargo.toml @@ -9,9 +9,9 @@ description = "Compiler executable for the Sierra intemediate representation wit [dependencies] anyhow.workspace = true clap.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } serde_json.workspace = true cairo-lang-sierra = { path = "../../cairo-lang-sierra", version = "2.4.1" } cairo-lang-starknet = { path = "../../cairo-lang-starknet", version = "2.4.1" } -cairo-lang-utils = { path = "../../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../../cairo-lang-utils", version = "2.4.1", features = ["serde"] } diff --git a/crates/bin/starknet-sierra-upgrade-validate/Cargo.toml b/crates/bin/starknet-sierra-upgrade-validate/Cargo.toml index 5091ffcef70..4268b77a60a 100644 --- a/crates/bin/starknet-sierra-upgrade-validate/Cargo.toml +++ b/crates/bin/starknet-sierra-upgrade-validate/Cargo.toml @@ -9,10 +9,10 @@ description = "Compiler executable for validating a Sierra upgrade is valid" [dependencies] anyhow.workspace = true clap.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } serde_json.workspace = true rayon.workspace = true indicatif = "0.17.7" cairo-lang-starknet = { path = "../../cairo-lang-starknet", version = "2.4.1" } -cairo-lang-utils = { path = "../../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../../cairo-lang-utils", version = "2.4.1", features = ["serde"] } diff --git a/crates/cairo-lang-casm/Cargo.toml b/crates/cairo-lang-casm/Cargo.toml index b80e320b92a..5206ad8cdcb 100644 --- a/crates/cairo-lang-casm/Cargo.toml +++ b/crates/cairo-lang-casm/Cargo.toml @@ -7,19 +7,19 @@ license-file.workspace = true description = "Cairo assembly encoding." [dependencies] -cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1", features = ["serde", "schemars"] } indoc.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } parity-scale-codec.workspace = true parity-scale-codec-derive.workspace = true schemars = { workspace = true, features = ["preserve_order"] } -serde.workspace = true +serde = { workspace = true, default-features = true } thiserror.workspace = true [dev-dependencies] env_logger.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } pretty_assertions.workspace = true test-case.workspace = true test-log.workspace = true diff --git a/crates/cairo-lang-defs/Cargo.toml b/crates/cairo-lang-defs/Cargo.toml index 160d47bd028..d8a78e99733 100644 --- a/crates/cairo-lang-defs/Cargo.toml +++ b/crates/cairo-lang-defs/Cargo.toml @@ -13,7 +13,7 @@ cairo-lang-filesystem = { path = "../cairo-lang-filesystem", version = "2.4.1" } cairo-lang-parser = { path = "../cairo-lang-parser", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -itertools.workspace = true +itertools = { workspace = true, default-features = true } salsa.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-defs/src/db.rs b/crates/cairo-lang-defs/src/db.rs index cd757e18349..82a7a6d3018 100644 --- a/crates/cairo-lang-defs/src/db.rs +++ b/crates/cairo-lang-defs/src/db.rs @@ -237,7 +237,7 @@ fn module_main_file(db: &dyn DefsGroup, module_id: ModuleId) -> Maybe { } ModuleId::Submodule(submodule_id) => { let parent = submodule_id.parent_module(db); - let item_module_ast = &db.priv_module_data(parent)?.submodules[submodule_id]; + let item_module_ast = &db.priv_module_data(parent)?.submodules[&submodule_id]; match item_module_ast.body(db.upcast()) { MaybeModuleBody::Some(_) => { // This is an inline module, we return the file where the inline module was @@ -361,7 +361,7 @@ fn priv_module_data(db: &dyn DefsGroup, module_id: ModuleId) -> Maybe file_syntax.items(syntax_db), ModuleId::Submodule(submodule_id) => { let parent_module_data = db.priv_module_data(submodule_id.parent_module(db))?; - let item_module_ast = &parent_module_data.submodules[submodule_id]; + let item_module_ast = &parent_module_data.submodules[&submodule_id]; match item_module_ast.body(syntax_db) { MaybeModuleBody::Some(body) => { @@ -956,7 +956,7 @@ fn module_item_name_stable_ptr( ) -> Maybe { let data = db.priv_module_data(module_id)?; let db = db.upcast(); - Ok(match item_id { + Ok(match &item_id { ModuleItemId::Constant(id) => data.constants[id].name(db).stable_ptr().untyped(), ModuleItemId::Submodule(id) => data.submodules[id].name(db).stable_ptr().untyped(), ModuleItemId::Use(id) => { diff --git a/crates/cairo-lang-diagnostics/Cargo.toml b/crates/cairo-lang-diagnostics/Cargo.toml index 65201e8f06e..a7a1e6cc402 100644 --- a/crates/cairo-lang-diagnostics/Cargo.toml +++ b/crates/cairo-lang-diagnostics/Cargo.toml @@ -10,7 +10,7 @@ description = "Diagnostic utilities." cairo-lang-debug = { path = "../cairo-lang-debug", version = "2.4.1" } cairo-lang-filesystem = { path = "../cairo-lang-filesystem", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -itertools.workspace = true +itertools = { workspace = true, default-features = true } [dev-dependencies] env_logger.workspace = true diff --git a/crates/cairo-lang-eq-solver/src/lib.rs b/crates/cairo-lang-eq-solver/src/lib.rs index bca1240c08b..9228d85b52d 100644 --- a/crates/cairo-lang-eq-solver/src/lib.rs +++ b/crates/cairo-lang-eq-solver/src/lib.rs @@ -70,7 +70,7 @@ fn try_solve_equations_iteration( target_vars: &[Var], ) -> Option> { let mut vars = variables!(); - let mut orig_to_solver_var = OrderedHashMap::default(); + let mut orig_to_solver_var = OrderedHashMap::new(); // Add all variables to structure and map. for eq in equations { for var in eq.var_to_coef.keys() { diff --git a/crates/cairo-lang-filesystem/Cargo.toml b/crates/cairo-lang-filesystem/Cargo.toml index 74c3509dbe9..7909ca91dc4 100644 --- a/crates/cairo-lang-filesystem/Cargo.toml +++ b/crates/cairo-lang-filesystem/Cargo.toml @@ -8,10 +8,10 @@ description = "Virtual filesystem for the compiler." [dependencies] cairo-lang-debug = { path = "../cairo-lang-debug", version = "2.4.1" } -cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1", features = ["serde"] } path-clean.workspace = true salsa.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } smol_str.workspace = true [dev-dependencies] diff --git a/crates/cairo-lang-formatter/Cargo.toml b/crates/cairo-lang-formatter/Cargo.toml index 5e4e977ccd8..c818a26d168 100644 --- a/crates/cairo-lang-formatter/Cargo.toml +++ b/crates/cairo-lang-formatter/Cargo.toml @@ -15,9 +15,9 @@ cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } diffy.workspace = true ignore.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } salsa.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } smol_str.workspace = true thiserror.workspace = true diff --git a/crates/cairo-lang-language-server/Cargo.toml b/crates/cairo-lang-language-server/Cargo.toml index 157886c4bad..4eedc8398af 100644 --- a/crates/cairo-lang-language-server/Cargo.toml +++ b/crates/cairo-lang-language-server/Cargo.toml @@ -25,7 +25,7 @@ log.workspace = true lsp.workspace = true salsa.workspace = true scarb-metadata.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } serde_json.workspace = true tokio.workspace = true tower-lsp.workspace = true diff --git a/crates/cairo-lang-lowering/Cargo.toml b/crates/cairo-lang-lowering/Cargo.toml index dcfe382d768..23d524dc5f2 100644 --- a/crates/cairo-lang-lowering/Cargo.toml +++ b/crates/cairo-lang-lowering/Cargo.toml @@ -17,10 +17,10 @@ cairo-lang-semantic = { path = "../cairo-lang-semantic", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } id-arena.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } log.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } once_cell.workspace = true salsa.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-lowering/src/db.rs b/crates/cairo-lang-lowering/src/db.rs index b19cda1ebe4..551bc160655 100644 --- a/crates/cairo-lang-lowering/src/db.rs +++ b/crates/cairo-lang-lowering/src/db.rs @@ -320,7 +320,7 @@ fn priv_function_with_body_lowering( ) -> Maybe> { let semantic_function_id = function_id.base_semantic_function(db); let multi_lowering = db.priv_function_with_body_multi_lowering(semantic_function_id)?; - let lowered = match db.lookup_intern_lowering_function_with_body(function_id) { + let lowered = match &db.lookup_intern_lowering_function_with_body(function_id) { ids::FunctionWithBodyLongId::Semantic(_) => multi_lowering.main_lowering.clone(), ids::FunctionWithBodyLongId::Generated { element, .. } => { multi_lowering.generated_lowerings[element].clone() diff --git a/crates/cairo-lang-lowering/src/lower/block_builder.rs b/crates/cairo-lang-lowering/src/lower/block_builder.rs index 135e056965c..8393c095cfe 100644 --- a/crates/cairo-lang-lowering/src/lower/block_builder.rs +++ b/crates/cairo-lang-lowering/src/lower/block_builder.rs @@ -127,8 +127,8 @@ impl BlockBuilder { MemberPath::Var(var) => ctx.semantic_defs[var].ty(), MemberPath::Member { member_id, concrete_struct_id, .. } => { ctx.db.concrete_struct_members(*concrete_struct_id).unwrap() - [member_id.name(ctx.db.upcast())] - .ty + [&member_id.name(ctx.db.upcast())] + .ty } } } diff --git a/crates/cairo-lang-lowering/src/lower/mod.rs b/crates/cairo-lang-lowering/src/lower/mod.rs index 31709dcc394..df5194ac96a 100644 --- a/crates/cairo-lang-lowering/src/lower/mod.rs +++ b/crates/cairo-lang-lowering/src/lower/mod.rs @@ -481,7 +481,7 @@ fn lower_single_pattern( .db .concrete_struct_members(structure.concrete_struct_id) .map_err(LoweringFlowError::Failed)?; - let mut required_members = UnorderedHashMap::from_iter( + let mut required_members = UnorderedHashMap::<_, _>::from_iter( structure.field_patterns.iter().map(|(member, pattern)| (member.id, pattern)), ); let generator = generators::StructDestructure { @@ -1016,7 +1016,7 @@ fn lower_expr_loop( _ => unreachable!("Loop expression must be either loop or while."), }; - let usage = &ctx.block_usages.block_usages[loop_expr_id]; + let usage = &ctx.block_usages.block_usages[&loop_expr_id]; // Determine signature. let params = usage.usage.iter().map(|(_, expr)| expr.clone()).collect_vec(); @@ -1740,7 +1740,7 @@ fn lower_expr_struct_ctor( .db .concrete_struct_members(expr.concrete_struct_id) .map_err(LoweringFlowError::Failed)?; - let member_expr = UnorderedHashMap::from_iter(expr.members.iter().cloned()); + let member_expr = UnorderedHashMap::<_, _>::from_iter(expr.members.iter().cloned()); Ok(LoweredExpr::AtVariable( generators::StructConstruct { inputs: members diff --git a/crates/cairo-lang-lowering/src/lower/usage.rs b/crates/cairo-lang-lowering/src/lower/usage.rs index 3deacf01489..c1f946d4d12 100644 --- a/crates/cairo-lang-lowering/src/lower/usage.rs +++ b/crates/cairo-lang-lowering/src/lower/usage.rs @@ -177,7 +177,7 @@ impl BlockUsages { Expr::Loop(expr) => { self.handle_expr(function_body, expr.body, current); // Copy body usage to loop usage. - self.block_usages.insert(expr_id, self.block_usages[expr.body].clone()); + self.block_usages.insert(expr_id, self.block_usages[&expr.body].clone()); } Expr::While(expr) => { let mut usage = Default::default(); diff --git a/crates/cairo-lang-lowering/src/optimizations/match_optimizer.rs b/crates/cairo-lang-lowering/src/optimizations/match_optimizer.rs index d0b3909942b..b60e5d50869 100644 --- a/crates/cairo-lang-lowering/src/optimizations/match_optimizer.rs +++ b/crates/cairo-lang-lowering/src/optimizations/match_optimizer.rs @@ -25,7 +25,7 @@ pub fn optimize_matches(lowered: &mut FlatLowered) { analysis.get_root_info(); let ctx = analysis.analyzer; - let mut target_blocks = UnorderedHashSet::default(); + let mut target_blocks = UnorderedHashSet::new(); for FixInfo { statement_location, target_block, remapping } in ctx.fixes.into_iter() { let block = &mut lowered.blocks[statement_location.0]; diff --git a/crates/cairo-lang-parser/Cargo.toml b/crates/cairo-lang-parser/Cargo.toml index c09a9f2ff37..75403b12010 100644 --- a/crates/cairo-lang-parser/Cargo.toml +++ b/crates/cairo-lang-parser/Cargo.toml @@ -13,9 +13,9 @@ cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-syntax-codegen = { path = "../cairo-lang-syntax-codegen", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } colored.workspace = true -itertools.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } salsa.workspace = true smol_str.workspace = true unescaper.workspace = true diff --git a/crates/cairo-lang-plugins/Cargo.toml b/crates/cairo-lang-plugins/Cargo.toml index 819e884a247..00c805c87f7 100644 --- a/crates/cairo-lang-plugins/Cargo.toml +++ b/crates/cairo-lang-plugins/Cargo.toml @@ -18,7 +18,7 @@ cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } indent.workspace = true indoc.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } salsa.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-plugins/src/test_utils.rs b/crates/cairo-lang-plugins/src/test_utils.rs index 513851ce1e2..f79bebdf710 100644 --- a/crates/cairo-lang-plugins/src/test_utils.rs +++ b/crates/cairo-lang-plugins/src/test_utils.rs @@ -14,7 +14,7 @@ pub fn expand_module_text( ) -> String { let mut output = String::new(); // A collection of all the use statements in the module. - let mut uses_list = UnorderedHashSet::default(); + let mut uses_list = UnorderedHashSet::new(); let syntax_db = db.upcast(); // Collect the module diagnostics. for (file_id, diag) in db.module_plugin_diagnostics(module_id).unwrap().iter() { diff --git a/crates/cairo-lang-project/Cargo.toml b/crates/cairo-lang-project/Cargo.toml index 4eaee216069..d81c5689115 100644 --- a/crates/cairo-lang-project/Cargo.toml +++ b/crates/cairo-lang-project/Cargo.toml @@ -9,7 +9,7 @@ description = "Cairo project specification. For example, crates and flags used f [dependencies] cairo-lang-filesystem = { path = "../cairo-lang-filesystem", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -serde.workspace = true +serde = { workspace = true, default-features = true } smol_str.workspace = true thiserror.workspace = true toml.workspace = true diff --git a/crates/cairo-lang-runner/Cargo.toml b/crates/cairo-lang-runner/Cargo.toml index c2cf3e18e2e..6104ef5c94e 100644 --- a/crates/cairo-lang-runner/Cargo.toml +++ b/crates/cairo-lang-runner/Cargo.toml @@ -20,11 +20,11 @@ cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version cairo-lang-starknet = { path = "../cairo-lang-starknet", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } cairo-vm.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } keccak.workspace = true -num-bigint.workspace = true +num-bigint = { workspace = true, default-features = true } num-integer.workspace = true -num-traits.workspace = true +num-traits = { workspace = true, default-features = true } thiserror.workspace = true starknet-crypto.workspace = true diff --git a/crates/cairo-lang-runner/src/lib.rs b/crates/cairo-lang-runner/src/lib.rs index 7e29acf3265..f776bf385ce 100644 --- a/crates/cairo-lang-runner/src/lib.rs +++ b/crates/cairo-lang-runner/src/lib.rs @@ -535,7 +535,7 @@ impl SierraCasmRunner { return None; } Some( - self.metadata.gas_info.function_costs[func.id.clone()] + self.metadata.gas_info.function_costs[&func.id] .iter() .map(|(token_type, val)| val.into_or_panic::() * token_gas_cost(*token_type)) .sum(), diff --git a/crates/cairo-lang-semantic/Cargo.toml b/crates/cairo-lang-semantic/Cargo.toml index fcaac0ece42..b2a9bbdfc39 100644 --- a/crates/cairo-lang-semantic/Cargo.toml +++ b/crates/cairo-lang-semantic/Cargo.toml @@ -19,12 +19,12 @@ cairo-lang-plugins = { path = "../cairo-lang-plugins", version = "2.4.1" } cairo-lang-proc-macros = { path = "../cairo-lang-proc-macros", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -cairo-lang-test-utils = { path = "../cairo-lang-test-utils", optional = true, features = ["testing"], version = "2.4.1" } +cairo-lang-test-utils = { path = "../cairo-lang-test-utils", version = "2.4.1", optional = true, features = ["testing"] } id-arena.workspace = true indoc.workspace = true -itertools.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } once_cell.workspace = true salsa.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-semantic/src/expr/compute.rs b/crates/cairo-lang-semantic/src/expr/compute.rs index f27fd9c4bd7..701d5241ae5 100644 --- a/crates/cairo-lang-semantic/src/expr/compute.rs +++ b/crates/cairo-lang-semantic/src/expr/compute.rs @@ -1350,7 +1350,7 @@ fn maybe_compute_pattern_semantic( let pattern_param_asts = pattern_struct.params(syntax_db).elements(syntax_db); let struct_id = concrete_struct_id.struct_id(ctx.db); let mut members = ctx.db.concrete_struct_members(concrete_struct_id)?; - let mut used_members = UnorderedHashSet::default(); + let mut used_members = UnorderedHashSet::new(); let mut get_member = |ctx: &mut ComputationContext<'_>, member_name: SmolStr, stable_ptr: SyntaxStablePtrId| { diff --git a/crates/cairo-lang-semantic/src/items/imp.rs b/crates/cairo-lang-semantic/src/items/imp.rs index b00c4d33fb6..910c4a72ed2 100644 --- a/crates/cairo-lang-semantic/src/items/imp.rs +++ b/crates/cairo-lang-semantic/src/items/imp.rs @@ -564,9 +564,9 @@ pub fn priv_impl_definition_data( // TODO(yuval): verify that all functions of `concrete_trait` appear in this impl. - let mut function_asts = OrderedHashMap::default(); - let mut item_type_asts = OrderedHashMap::default(); - let mut impl_item_names = OrderedHashSet::default(); + let mut function_asts = OrderedHashMap::new(); + let mut item_type_asts = OrderedHashMap::new(); + let mut impl_item_names = OrderedHashSet::new(); if let MaybeImplBody::Some(body) = impl_ast.body(syntax_db) { for item in body.items(syntax_db).elements(syntax_db) { @@ -1362,7 +1362,7 @@ pub fn priv_impl_function_generic_params_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let impl_def_id = impl_function_id.impl_def_id(db.upcast()); let data = db.priv_impl_definition_data(impl_def_id)?; - let function_syntax = &data.function_asts[impl_function_id]; + let function_syntax = &data.function_asts[&impl_function_id]; let syntax_db = db.upcast(); let declaration = function_syntax.declaration(syntax_db); let inference_id = InferenceId::LookupItemGenerics(LookupItemId::ImplItem( @@ -1461,7 +1461,7 @@ pub fn priv_impl_function_declaration_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let impl_def_id = impl_function_id.impl_def_id(db.upcast()); let data = db.priv_impl_definition_data(impl_def_id)?; - let function_syntax = &data.function_asts[impl_function_id]; + let function_syntax = &data.function_asts[&impl_function_id]; let syntax_db = db.upcast(); let declaration = function_syntax.declaration(syntax_db); @@ -1724,7 +1724,7 @@ pub fn priv_impl_function_body_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let impl_def_id = impl_function_id.impl_def_id(defs_db); let data = db.priv_impl_definition_data(impl_def_id)?; - let function_syntax = &data.function_asts[impl_function_id]; + let function_syntax = &data.function_asts[&impl_function_id]; // Compute declaration semantic. let declaration = db.priv_impl_function_declaration_data(impl_function_id)?; let parent_resolver_data = declaration.function_declaration_data.resolver_data; diff --git a/crates/cairo-lang-semantic/src/items/module.rs b/crates/cairo-lang-semantic/src/items/module.rs index e081083e812..328c9226890 100644 --- a/crates/cairo-lang-semantic/src/items/module.rs +++ b/crates/cairo-lang-semantic/src/items/module.rs @@ -47,7 +47,7 @@ pub fn priv_module_semantic_data( let mut items = OrderedHashMap::default(); let visibility_extractor = VisibilityExtractor { db: def_db, module_id }; for item_id in db.module_items(module_id)?.iter().copied() { - let (name, visibility) = match item_id { + let (name, visibility) = match &item_id { ModuleItemId::Constant(item_id) => { (item_id.name(def_db), visibility_extractor.constant(item_id)) } @@ -107,40 +107,40 @@ struct VisibilityExtractor<'a> { module_id: ModuleId, } impl<'a> VisibilityExtractor<'a> { - fn submodule(&self, item_id: SubmoduleId) -> Maybe { + fn submodule(&self, item_id: &SubmoduleId) -> Maybe { Ok(self.db.module_submodules(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn constant(&self, item_id: ConstantId) -> Maybe { + fn constant(&self, item_id: &ConstantId) -> Maybe { Ok(self.db.module_constants(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn free_function(&self, item_id: FreeFunctionId) -> Maybe { + fn free_function(&self, item_id: &FreeFunctionId) -> Maybe { Ok(self.db.module_free_functions(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn enum_(&self, item_id: EnumId) -> Maybe { + fn enum_(&self, item_id: &EnumId) -> Maybe { Ok(self.db.module_enums(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn struct_(&self, item_id: StructId) -> Maybe { + fn struct_(&self, item_id: &StructId) -> Maybe { Ok(self.db.module_structs(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn extern_function(&self, item_id: ExternFunctionId) -> Maybe { + fn extern_function(&self, item_id: &ExternFunctionId) -> Maybe { Ok(self.db.module_extern_functions(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn extern_type(&self, item_id: ExternTypeId) -> Maybe { + fn extern_type(&self, item_id: &ExternTypeId) -> Maybe { Ok(self.db.module_extern_types(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn type_alias(&self, item_id: ModuleTypeAliasId) -> Maybe { + fn type_alias(&self, item_id: &ModuleTypeAliasId) -> Maybe { Ok(self.db.module_type_aliases(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn impl_alias(&self, item_id: ImplAliasId) -> Maybe { + fn impl_alias(&self, item_id: &ImplAliasId) -> Maybe { Ok(self.db.module_impl_aliases(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn trait_(&self, item_id: TraitId) -> Maybe { + fn trait_(&self, item_id: &TraitId) -> Maybe { Ok(self.db.module_traits(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn impl_def(&self, item_id: ImplDefId) -> Maybe { + fn impl_def(&self, item_id: &ImplDefId) -> Maybe { Ok(self.db.module_impls(self.module_id)?[item_id].visibility(self.db.upcast())) } - fn use_(&self, item_id: UseId) -> Maybe { + fn use_(&self, item_id: &UseId) -> Maybe { let use_ast = &self.db.module_uses(self.module_id)?[item_id]; let use_path = ast::UsePath::Leaf(use_ast.clone()); let mut node = use_path.as_syntax_node(); @@ -179,7 +179,7 @@ pub fn module_item_info_by_name( /// Query implementation of [SemanticGroup::module_attributes]. pub fn module_attributes(db: &dyn SemanticGroup, module_id: ModuleId) -> Maybe> { - Ok(match module_id { + Ok(match &module_id { ModuleId::CrateRoot(_) => vec![], ModuleId::Submodule(submodule_id) => { let module_ast = diff --git a/crates/cairo-lang-semantic/src/items/trt.rs b/crates/cairo-lang-semantic/src/items/trt.rs index 47575fc30a2..f196d552dbc 100644 --- a/crates/cairo-lang-semantic/src/items/trt.rs +++ b/crates/cairo-lang-semantic/src/items/trt.rs @@ -381,9 +381,9 @@ pub fn priv_trait_semantic_definition_data( // the item instead of all the module data. let trait_ast = db.module_trait_by_id(trait_id)?.to_maybe()?; - let mut function_asts = OrderedHashMap::default(); - let mut item_type_asts = OrderedHashMap::default(); - let mut trait_item_names = OrderedHashSet::default(); + let mut function_asts = OrderedHashMap::new(); + let mut item_type_asts = OrderedHashMap::new(); + let mut trait_item_names = OrderedHashSet::new(); if let ast::MaybeTraitBody::Some(body) = trait_ast.body(syntax_db) { for item in body.items(syntax_db).elements(syntax_db) { match item { @@ -488,7 +488,7 @@ pub fn priv_trait_type_generic_params_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let trait_id = trait_type_id.trait_id(db.upcast()); let data = db.priv_trait_semantic_definition_data(trait_id)?; - let trait_type_ast = &data.item_type_asts[trait_type_id]; + let trait_type_ast = &data.item_type_asts[&trait_type_id]; let inference_id = InferenceId::LookupItemGenerics(LookupItemId::TraitItem(TraitItemId::Type(trait_type_id))); let parent_resolver_data = db.trait_resolver_data(trait_id)?; @@ -534,7 +534,7 @@ pub fn priv_trait_type_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let trait_id = trait_type_id.trait_id(db.upcast()); let data = db.priv_trait_semantic_definition_data(trait_id)?; - let type_syntax = &data.item_type_asts[trait_type_id]; + let type_syntax = &data.item_type_asts[&trait_type_id]; let type_generic_params_data = db.priv_trait_type_generic_params_data(trait_type_id)?; let type_generic_params = type_generic_params_data.generic_params; @@ -598,7 +598,7 @@ pub fn priv_trait_function_generic_params_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let trait_id = trait_function_id.trait_id(db.upcast()); let data = db.priv_trait_semantic_definition_data(trait_id)?; - let function_syntax = &data.function_asts[trait_function_id]; + let function_syntax = &data.function_asts[&trait_function_id]; let declaration = function_syntax.declaration(syntax_db); let inference_id = InferenceId::LookupItemGenerics(LookupItemId::TraitItem( TraitItemId::Function(trait_function_id), @@ -678,7 +678,7 @@ pub fn priv_trait_function_declaration_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let trait_id = trait_function_id.trait_id(db.upcast()); let data = db.priv_trait_semantic_definition_data(trait_id)?; - let function_syntax = &data.function_asts[trait_function_id]; + let function_syntax = &data.function_asts[&trait_function_id]; let declaration = function_syntax.declaration(syntax_db); let function_generic_params_data = db.priv_trait_function_generic_params_data(trait_function_id)?; @@ -832,7 +832,7 @@ pub fn priv_trait_function_body_data( let mut diagnostics = SemanticDiagnostics::new(module_file_id.file_id(db.upcast())?); let trait_id = trait_function_id.trait_id(defs_db); let data = db.priv_trait_semantic_definition_data(trait_id)?; - let function_syntax = &data.function_asts[trait_function_id]; + let function_syntax = &data.function_asts[&trait_function_id]; // Compute declaration semantic. let trait_function_declaration_data = db.priv_trait_function_declaration_data(trait_function_id)?; diff --git a/crates/cairo-lang-sierra-ap-change/Cargo.toml b/crates/cairo-lang-sierra-ap-change/Cargo.toml index 77e3173f6fe..b7eef3f8ee9 100644 --- a/crates/cairo-lang-sierra-ap-change/Cargo.toml +++ b/crates/cairo-lang-sierra-ap-change/Cargo.toml @@ -11,9 +11,9 @@ cairo-lang-eq-solver = { path = "../cairo-lang-eq-solver", version = "2.4.1" } cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.4.1" } cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -itertools.workspace = true +itertools = { workspace = true, default-features = true } thiserror.workspace = true -num-traits.workspace = true +num-traits = { workspace = true, default-features = true } [dev-dependencies] env_logger.workspace = true diff --git a/crates/cairo-lang-sierra-gas/Cargo.toml b/crates/cairo-lang-sierra-gas/Cargo.toml index 721116476e0..8e1be0b3e9b 100644 --- a/crates/cairo-lang-sierra-gas/Cargo.toml +++ b/crates/cairo-lang-sierra-gas/Cargo.toml @@ -11,9 +11,9 @@ cairo-lang-eq-solver = { path = "../cairo-lang-eq-solver", version = "2.4.1" } cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.4.1" } cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -itertools.workspace = true +itertools = { workspace = true, default-features = true } thiserror.workspace = true -num-traits.workspace = true +num-traits = { workspace = true, default-features = true } [dev-dependencies] cairo-lang-test-utils = { path = "../cairo-lang-test-utils", features = ["testing"] } diff --git a/crates/cairo-lang-sierra-gas/src/compute_costs.rs b/crates/cairo-lang-sierra-gas/src/compute_costs.rs index aa31e9b643e..f85df9a6a9e 100644 --- a/crates/cairo-lang-sierra-gas/src/compute_costs.rs +++ b/crates/cairo-lang-sierra-gas/src/compute_costs.rs @@ -780,7 +780,7 @@ impl<'a> PostcostContext<'a> { if with_builtin_costs { let steps = BuiltinCostWithdrawGasLibfunc::cost_computation_steps(|token_type| { - self.precost_gas_info.variable_values[(*idx, token_type)].into_or_panic() + self.precost_gas_info.variable_values[&(*idx, token_type)].into_or_panic() }) .into_or_panic::(); amount += ConstCost { steps, ..Default::default() }.cost(); diff --git a/crates/cairo-lang-sierra-gas/src/core_libfunc_cost_expr.rs b/crates/cairo-lang-sierra-gas/src/core_libfunc_cost_expr.rs index e28a6f00055..ca6244cd6f8 100644 --- a/crates/cairo-lang-sierra-gas/src/core_libfunc_cost_expr.rs +++ b/crates/cairo-lang-sierra-gas/src/core_libfunc_cost_expr.rs @@ -31,7 +31,7 @@ impl CostOperations for Ops<'_> { ) -> Self::CostType { Self::CostType::from_iter([( token_type, - self.statement_future_cost.get_future_cost(&function.entry_point)[token_type].clone(), + self.statement_future_cost.get_future_cost(&function.entry_point)[&token_type].clone(), )]) } diff --git a/crates/cairo-lang-sierra-gas/src/gas_info.rs b/crates/cairo-lang-sierra-gas/src/gas_info.rs index 56d6ab436e7..2bfb0699ef4 100644 --- a/crates/cairo-lang-sierra-gas/src/gas_info.rs +++ b/crates/cairo-lang-sierra-gas/src/gas_info.rs @@ -108,7 +108,7 @@ impl Display for GasInfo { } for statement_idx in var_values.keys().sorted_by(|a, b| a.0.cmp(&b.0)) { - writeln!(f, "#{statement_idx}: {:?}", var_values[*statement_idx])?; + writeln!(f, "#{statement_idx}: {:?}", var_values[statement_idx])?; } writeln!(f)?; for (function_id, costs) in self.function_costs.iter() { diff --git a/crates/cairo-lang-sierra-gas/src/generate_equations.rs b/crates/cairo-lang-sierra-gas/src/generate_equations.rs index 1ec0568225f..f4c333f768d 100644 --- a/crates/cairo-lang-sierra-gas/src/generate_equations.rs +++ b/crates/cairo-lang-sierra-gas/src/generate_equations.rs @@ -78,7 +78,7 @@ impl EquationGenerator { let entry = &mut self.future_costs[idx.0]; if let Some(other) = entry { for (token_type, val) in sub_maps(other.clone(), cost) { - self.equations[token_type].push(val); + self.equations[&token_type].push(val); } } else { *entry = Some(cost); diff --git a/crates/cairo-lang-sierra-gas/src/generate_equations_test.rs b/crates/cairo-lang-sierra-gas/src/generate_equations_test.rs index 14a7a1ea98d..43b9acc082d 100644 --- a/crates/cairo-lang-sierra-gas/src/generate_equations_test.rs +++ b/crates/cairo-lang-sierra-gas/src/generate_equations_test.rs @@ -111,7 +111,7 @@ fn generate( .map(|x| CostExprMap::from_iter([(CostTokenType::Const, x.clone())])) .collect() }, - )?[CostTokenType::Const] + )?[&CostTokenType::Const] .clone()) } diff --git a/crates/cairo-lang-sierra-gas/src/lib.rs b/crates/cairo-lang-sierra-gas/src/lib.rs index 782a6810202..05dd6627873 100644 --- a/crates/cairo-lang-sierra-gas/src/lib.rs +++ b/crates/cairo-lang-sierra-gas/src/lib.rs @@ -150,7 +150,7 @@ pub fn calc_gas_postcost_info usize>( &InvocationCostInfoProviderForEqGen { type_sizes: &type_sizes, token_usages: |token_type| { - precost_gas_info.variable_values[(*idx, token_type)].into_or_panic() + precost_gas_info.variable_values[&(*idx, token_type)].into_or_panic() }, ap_change_var_value: || ap_change_var_value(*idx), }, @@ -179,7 +179,7 @@ fn calc_gas_info_inner< .collect(); for (func_id, cost_terms) in function_set_costs { for token_type in CostTokenType::iter() { - equations[*token_type].push( + equations[token_type].push( Expr::from_var(Var::StatementFuture( registry.get_function(&func_id)?.entry_point, *token_type, @@ -246,7 +246,7 @@ fn calc_gas_info_inner< if !function_costs.contains_key(id) { function_costs.insert(id.clone(), OrderedHashMap::default()); } - let value = solution[Var::StatementFuture(func.entry_point, token_type)]; + let value = solution[&Var::StatementFuture(func.entry_point, token_type)]; if value != 0 { function_costs.get_mut(id).unwrap().insert(token_type, value); } diff --git a/crates/cairo-lang-sierra-generator/Cargo.toml b/crates/cairo-lang-sierra-generator/Cargo.toml index cdcaf878ea4..e1747d74fb9 100644 --- a/crates/cairo-lang-sierra-generator/Cargo.toml +++ b/crates/cairo-lang-sierra-generator/Cargo.toml @@ -19,10 +19,10 @@ cairo-lang-parser = { path = "../cairo-lang-parser", version = "2.4.1" } cairo-lang-semantic = { path = "../cairo-lang-semantic", version = "2.4.1" } cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } -cairo-lang-test-utils = { path = "../cairo-lang-test-utils", optional = true, features = ["testing"], version = "2.4.1" } +cairo-lang-test-utils = { path = "../cairo-lang-test-utils", version = "2.4.1", optional = true, features = ["testing"] } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -itertools.workspace = true -num-bigint.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } once_cell.workspace = true salsa.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-sierra-generator/src/store_variables/known_stack_test.rs b/crates/cairo-lang-sierra-generator/src/store_variables/known_stack_test.rs index 8d945673f57..c96abd17338 100644 --- a/crates/cairo-lang-sierra-generator/src/store_variables/known_stack_test.rs +++ b/crates/cairo-lang-sierra-generator/src/store_variables/known_stack_test.rs @@ -21,7 +21,7 @@ fn assert_eq_stacks(a: &KnownStack, b: &KnownStack) { for (var, a_index) in a.variables_on_stack.iter() { assert_eq!( a.offset - *a_index, - b.offset - b.variables_on_stack[var.clone()], + b.offset - b.variables_on_stack[var], "Wrong value found for {var}.\na: {a:?}\nb: {b:?}" ); } diff --git a/crates/cairo-lang-sierra-to-casm/Cargo.toml b/crates/cairo-lang-sierra-to-casm/Cargo.toml index c4479cd5303..8a98b109b79 100644 --- a/crates/cairo-lang-sierra-to-casm/Cargo.toml +++ b/crates/cairo-lang-sierra-to-casm/Cargo.toml @@ -14,11 +14,11 @@ cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.4.1" } cairo-lang-sierra-ap-change = { path = "../cairo-lang-sierra-ap-change", version = "2.4.1" } cairo-lang-sierra-gas = { path = "../cairo-lang-sierra-gas", version = "2.4.1" } cairo-lang-sierra-type-size = { path = "../cairo-lang-sierra-type-size", version = "2.4.1" } -cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1", features = ["serde"] } indoc.workspace = true -itertools.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } thiserror.workspace = true [dev-dependencies] diff --git a/crates/cairo-lang-sierra-to-casm/src/annotations.rs b/crates/cairo-lang-sierra-to-casm/src/annotations.rs index 62eb695fead..19bbd575ee1 100644 --- a/crates/cairo-lang-sierra-to-casm/src/annotations.rs +++ b/crates/cairo-lang-sierra-to-casm/src/annotations.rs @@ -134,7 +134,7 @@ impl ProgramAnnotations { function_id: func.id.clone(), convergence_allowed: false, environment: Environment::new(if gas_usage_check { - GasWallet::Value(metadata.gas_info.function_costs[func.id.clone()].clone()) + GasWallet::Value(metadata.gas_info.function_costs[&func.id].clone()) } else { GasWallet::Disabled }), diff --git a/crates/cairo-lang-sierra-to-casm/src/invocations/gas.rs b/crates/cairo-lang-sierra-to-casm/src/invocations/gas.rs index c612f22e70a..4971770f8f2 100644 --- a/crates/cairo-lang-sierra-to-casm/src/invocations/gas.rs +++ b/crates/cairo-lang-sierra-to-casm/src/invocations/gas.rs @@ -144,11 +144,11 @@ fn build_builtin_withdraw_gas( deref gas_counter; deref builtin_cost; }; - let requested_count: i64 = variable_values[(builder.idx, CostTokenType::Const)]; + let requested_count: i64 = variable_values[&(builder.idx, CostTokenType::Const)]; let mut total_requested_count = casm_builder.add_var(CellExpression::Immediate(BigInt::from(requested_count))); for token_type in CostTokenType::iter_precost() { - let requested_count = variable_values[(builder.idx, *token_type)]; + let requested_count = variable_values[&(builder.idx, *token_type)]; if requested_count == 0 { continue; } diff --git a/crates/cairo-lang-sierra-to-casm/src/metadata.rs b/crates/cairo-lang-sierra-to-casm/src/metadata.rs index 7399a80459a..6d8ddd4bb1c 100644 --- a/crates/cairo-lang-sierra-to-casm/src/metadata.rs +++ b/crates/cairo-lang-sierra-to-casm/src/metadata.rs @@ -97,7 +97,7 @@ pub fn calc_metadata( let ap_change_info = if config.linear_ap_change_solver { linear_calc_ap_changes } else { calc_ap_changes }( program, - |idx, token_type| pre_gas_info.variable_values[(idx, token_type)] as usize, + |idx, token_type| pre_gas_info.variable_values[&(idx, token_type)] as usize, )?; let post_function_set_costs = config @@ -122,7 +122,7 @@ pub fn calc_metadata( let enforced_function_costs: OrderedHashMap = config .function_set_costs .iter() - .map(|(func, costs)| (func.clone(), costs[CostTokenType::Const])) + .map(|(func, costs)| (func.clone(), costs[&CostTokenType::Const])) .collect(); let post_gas_info2 = compute_postcost_info( program, diff --git a/crates/cairo-lang-sierra/Cargo.toml b/crates/cairo-lang-sierra/Cargo.toml index b06223d153d..5099d484172 100644 --- a/crates/cairo-lang-sierra/Cargo.toml +++ b/crates/cairo-lang-sierra/Cargo.toml @@ -14,16 +14,16 @@ regex = "1" [dependencies] anyhow.workspace = true cairo-felt.workspace = true -cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1", features = ["serde", "schemars"] } const-fnv1a-hash.workspace = true convert_case.workspace = true derivative.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } lalrpop-util.workspace = true -num-bigint.workspace = true -num-traits.workspace = true +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } salsa.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } serde_json.workspace = true sha3.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-starknet/Cargo.toml b/crates/cairo-lang-starknet/Cargo.toml index 20a3849e604..bca46daad6d 100644 --- a/crates/cairo-lang-starknet/Cargo.toml +++ b/crates/cairo-lang-starknet/Cargo.toml @@ -20,16 +20,16 @@ cairo-lang-sierra = { path = "../cairo-lang-sierra", version = "2.4.1" } cairo-lang-sierra-generator = { path = "../cairo-lang-sierra-generator", version = "2.4.1" } cairo-lang-sierra-to-casm = { path = "../cairo-lang-sierra-to-casm", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } -cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } +cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1", features = ["serde"] } const_format.workspace = true convert_case.workspace = true indoc.workspace = true -itertools.workspace = true -num-bigint.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } num-integer.workspace = true -num-traits.workspace = true +num-traits = { workspace = true, default-features = true } once_cell.workspace = true -serde.workspace = true +serde = { workspace = true, default-features = true } serde_json.workspace = true sha3.workspace = true smol_str.workspace = true diff --git a/crates/cairo-lang-starknet/src/abi.rs b/crates/cairo-lang-starknet/src/abi.rs index e9d076ca4fd..ff4813bc536 100644 --- a/crates/cairo-lang-starknet/src/abi.rs +++ b/crates/cairo-lang-starknet/src/abi.rs @@ -611,7 +611,7 @@ impl<'a> AbiBuilder<'a> { let event_fields = members .into_iter() .map(|(name, kind)| { - let concrete_member = &concrete_members[name.clone()]; + let concrete_member = &concrete_members[&name]; let ty = concrete_member.ty; self.add_event_field(kind, ty, name, Source::Member(concrete_member.id)) }) diff --git a/crates/cairo-lang-starknet/src/casm_contract_class.rs b/crates/cairo-lang-starknet/src/casm_contract_class.rs index 41f346e25e3..cbf751d8c61 100644 --- a/crates/cairo-lang-starknet/src/casm_contract_class.rs +++ b/crates/cairo-lang-starknet/src/casm_contract_class.rs @@ -430,7 +430,7 @@ impl CasmContractClass { .ok_or(StarknetSierraCompilationError::EntryPointError)? .code_offset; assert_eq!( - metadata.gas_info.function_costs[function.id.clone()], + metadata.gas_info.function_costs[&function.id], OrderedHashMap::from_iter([(CostTokenType::Const, ENTRY_POINT_COST as i64)]), "Unexpected entry point cost." ); diff --git a/crates/cairo-lang-syntax/Cargo.toml b/crates/cairo-lang-syntax/Cargo.toml index 08fef5192d2..1873f9ba197 100644 --- a/crates/cairo-lang-syntax/Cargo.toml +++ b/crates/cairo-lang-syntax/Cargo.toml @@ -10,8 +10,8 @@ description = "Cairo syntax representation." cairo-lang-debug = { path = "../cairo-lang-debug", version = "2.4.1" } cairo-lang-filesystem = { path = "../cairo-lang-filesystem", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } -num-bigint.workspace = true -num-traits.workspace = true +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } salsa.workspace = true smol_str.workspace = true unescaper.workspace = true diff --git a/crates/cairo-lang-test-plugin/Cargo.toml b/crates/cairo-lang-test-plugin/Cargo.toml index a0c942148a0..7c1bf124c48 100644 --- a/crates/cairo-lang-test-plugin/Cargo.toml +++ b/crates/cairo-lang-test-plugin/Cargo.toml @@ -22,7 +22,7 @@ cairo-lang-starknet = { path = "../cairo-lang-starknet", version = "2.4.1" } cairo-lang-syntax = { path = "../cairo-lang-syntax", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } indoc.workspace = true -itertools.workspace = true -num-bigint.workspace = true -num-traits.workspace = true -serde.workspace = true +itertools = { workspace = true, default-features = true } +num-bigint = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } +serde = { workspace = true, default-features = true } diff --git a/crates/cairo-lang-test-runner/Cargo.toml b/crates/cairo-lang-test-runner/Cargo.toml index 0cc3927fe6a..d7480dd42f6 100644 --- a/crates/cairo-lang-test-runner/Cargo.toml +++ b/crates/cairo-lang-test-runner/Cargo.toml @@ -18,8 +18,8 @@ cairo-lang-starknet = { path = "../cairo-lang-starknet", version = "2.4.1" } cairo-lang-test-plugin = { path = "../cairo-lang-test-plugin", version = "2.4.1" } cairo-lang-utils = { path = "../cairo-lang-utils", version = "2.4.1" } colored.workspace = true -itertools.workspace = true -num-traits.workspace = true +itertools = { workspace = true, default-features = true } +num-traits = { workspace = true, default-features = true } rayon.workspace = true [dev-dependencies] diff --git a/crates/cairo-lang-utils/Cargo.toml b/crates/cairo-lang-utils/Cargo.toml index aaf768d7f94..6079bcf7b6f 100644 --- a/crates/cairo-lang-utils/Cargo.toml +++ b/crates/cairo-lang-utils/Cargo.toml @@ -7,15 +7,16 @@ license-file.workspace = true description = "General utilities for the Cairo compiler project." [dependencies] -indexmap.workspace = true -itertools.workspace = true +indexmap = { workspace = true } +itertools = { workspace = true, features = ["use_alloc"] } num-bigint.workspace = true num-traits.workspace = true parity-scale-codec.workspace = true -schemars = { workspace = true, features = ["preserve_order"] } -serde.workspace = true +hashbrown = { workspace = true, features = ["serde"] } # Optional +serde = { workspace = true, features = ["alloc"], optional = true } +schemars = { workspace = true, features = ["preserve_order"], optional = true } env_logger = { workspace = true, optional = true } time = { workspace = true, optional = true } log = { workspace = true, optional = true } @@ -27,5 +28,14 @@ test-log.workspace = true env_logger.workspace = true [features] +default = ["std"] +std = [ + "indexmap/std", + "num-bigint/std", + "num-traits/std", + "serde?/std" +] +serde = ["dep:serde", "num-bigint/serde", "indexmap/serde"] +schemars = ["std", "serde", "dep:schemars"] testing = [] -env_logger = ["dep:env_logger", "dep:time", "dep:log"] +env_logger = ["std", "dep:env_logger", "dep:time", "dep:log"] diff --git a/crates/cairo-lang-utils/src/bigint.rs b/crates/cairo-lang-utils/src/bigint.rs index d5acfceec2b..bb69b0bbbb7 100644 --- a/crates/cairo-lang-utils/src/bigint.rs +++ b/crates/cairo-lang-utils/src/bigint.rs @@ -2,12 +2,13 @@ #[path = "bigint_test.rs"] mod test; -use std::ops::Neg; +#[cfg(not(feature = "std"))] +use alloc::{format, string::String, vec}; +use core::ops::Neg; use num_bigint::{BigInt, BigUint, ToBigInt}; use num_traits::{Num, Signed}; use parity_scale_codec::{Decode, Encode}; -use schemars::JsonSchema; use serde::ser::Serializer; use serde::{Deserialize, Deserializer, Serialize}; @@ -47,17 +48,21 @@ where } // A wrapper for BigInt that serializes as hex. -#[derive(Default, Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[derive(Default, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(transparent)] pub struct BigIntAsHex { /// A field element that encodes the signature of the called function. #[serde(serialize_with = "serialize_big_int", deserialize_with = "deserialize_big_int")] - #[schemars(schema_with = "big_int_schema")] + #[cfg_attr(feature = "schemars", schemars(schema_with = "big_int_schema"))] pub value: BigInt, } // BigInt doesn't implement JsonSchema, so we need to manually define it. +#[cfg(feature = "schemars")] fn big_int_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { + use schemars::JsonSchema; + #[allow(dead_code)] #[allow(clippy::enum_variant_names)] #[derive(JsonSchema)] diff --git a/crates/cairo-lang-utils/src/bigint_test.rs b/crates/cairo-lang-utils/src/bigint_test.rs index 547ce8febbd..7d0377033e3 100644 --- a/crates/cairo-lang-utils/src/bigint_test.rs +++ b/crates/cairo-lang-utils/src/bigint_test.rs @@ -1,5 +1,7 @@ -use std::ops::Neg; -use std::str::FromStr; +#[cfg(not(feature = "std"))] +use alloc::format; +use core::ops::Neg; +use core::str::FromStr; use num_bigint::BigInt; use num_traits::Num; diff --git a/crates/cairo-lang-utils/src/collection_arithmetics.rs b/crates/cairo-lang-utils/src/collection_arithmetics.rs index 1d0e6e45760..24409028e96 100644 --- a/crates/cairo-lang-utils/src/collection_arithmetics.rs +++ b/crates/cairo-lang-utils/src/collection_arithmetics.rs @@ -2,8 +2,8 @@ #[path = "collection_arithmetics_test.rs"] mod test; -use std::hash::Hash; -use std::ops::{Add, Sub}; +use core::hash::{BuildHasher, Hash}; +use core::ops::{Add, Sub}; use crate::ordered_hash_map::{Entry, OrderedHashMap}; @@ -33,10 +33,11 @@ pub fn add_maps< Key: Hash + Eq, Value: HasZero + Add + Clone + Eq, Rhs: IntoIterator, + BH: BuildHasher, >( - lhs: OrderedHashMap, + lhs: OrderedHashMap, rhs: Rhs, -) -> OrderedHashMap { +) -> OrderedHashMap { merge_maps(lhs, rhs, |a, b| a + b) } @@ -47,10 +48,11 @@ pub fn sub_maps< Key: Hash + Eq, Value: HasZero + Sub + Clone + Eq, Rhs: IntoIterator, + BH: BuildHasher, >( - lhs: OrderedHashMap, + lhs: OrderedHashMap, rhs: Rhs, -) -> OrderedHashMap { +) -> OrderedHashMap { merge_maps(lhs, rhs, |a, b| a - b) } @@ -63,11 +65,12 @@ fn merge_maps< Value: HasZero + Clone + Eq, Rhs: IntoIterator, Action: Fn(Value, Value) -> Value, + BH: BuildHasher, >( - lhs: OrderedHashMap, + lhs: OrderedHashMap, rhs: Rhs, action: Action, -) -> OrderedHashMap { +) -> OrderedHashMap { let mut res = lhs; for (key, rhs_val) in rhs { match res.entry(key) { diff --git a/crates/cairo-lang-utils/src/collection_arithmetics_test.rs b/crates/cairo-lang-utils/src/collection_arithmetics_test.rs index 4dc5e3a2fbf..14eb048f0c4 100644 --- a/crates/cairo-lang-utils/src/collection_arithmetics_test.rs +++ b/crates/cairo-lang-utils/src/collection_arithmetics_test.rs @@ -1,3 +1,8 @@ +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState as HashBuilderType; + +#[cfg(not(feature = "std"))] +use hashbrown::hash_map::DefaultHashBuilder as HashBuilderType; use test_log::test; use crate::collection_arithmetics::{add_maps, sub_maps}; @@ -5,15 +10,30 @@ use crate::ordered_hash_map::OrderedHashMap; #[test] fn test_add_map_and_sub_map() { - let x = OrderedHashMap::::from_iter([(10, 3), (20, 7), (30, 3), (40, 3)]); - let y = OrderedHashMap::::from_iter([(0, 2), (10, 5), (30, -3), (40, 3)]); + let x = OrderedHashMap::::from_iter([ + (10, 3), + (20, 7), + (30, 3), + (40, 3), + ]); + let y = OrderedHashMap::::from_iter([ + (0, 2), + (10, 5), + (30, -3), + (40, 3), + ]); assert_eq!( add_maps(x.clone(), y.iter().map(|(k, v)| (*k, *v))), - OrderedHashMap::::from_iter([(10, 8), (20, 7), (0, 2), (40, 6)]) + OrderedHashMap::::from_iter([(10, 8), (20, 7), (0, 2), (40, 6)]) ); assert_eq!( sub_maps(x, y), - OrderedHashMap::::from_iter([(10, -2), (20, 7), (30, 6), (0, -2)]) + OrderedHashMap::::from_iter([ + (10, -2), + (20, 7), + (30, 6), + (0, -2) + ]) ); } diff --git a/crates/cairo-lang-utils/src/graph_algos/feedback_set.rs b/crates/cairo-lang-utils/src/graph_algos/feedback_set.rs index c77fb305590..6e2587fa38e 100644 --- a/crates/cairo-lang-utils/src/graph_algos/feedback_set.rs +++ b/crates/cairo-lang-utils/src/graph_algos/feedback_set.rs @@ -29,8 +29,8 @@ struct FeedbackSetAlgoContext { impl FeedbackSetAlgoContext { fn new() -> Self { FeedbackSetAlgoContext { - feedback_set: OrderedHashSet::default(), - in_flight: UnorderedHashSet::default(), + feedback_set: OrderedHashSet::new(), + in_flight: UnorderedHashSet::new(), } } } diff --git a/crates/cairo-lang-utils/src/graph_algos/graph_node.rs b/crates/cairo-lang-utils/src/graph_algos/graph_node.rs index 450dc05eae9..826dee28c85 100644 --- a/crates/cairo-lang-utils/src/graph_algos/graph_node.rs +++ b/crates/cairo-lang-utils/src/graph_algos/graph_node.rs @@ -1,3 +1,5 @@ +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; use core::hash::Hash; /// A trait for a node in a graph. Note that a GraphNode has to be able to provide its neighbors diff --git a/crates/cairo-lang-utils/src/graph_algos/scc_graph_node.rs b/crates/cairo-lang-utils/src/graph_algos/scc_graph_node.rs index d5e70eba81a..bdf8c95d4c4 100644 --- a/crates/cairo-lang-utils/src/graph_algos/scc_graph_node.rs +++ b/crates/cairo-lang-utils/src/graph_algos/scc_graph_node.rs @@ -1,3 +1,6 @@ +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; + use super::graph_node::GraphNode; use super::strongly_connected_components::ComputeScc; diff --git a/crates/cairo-lang-utils/src/graph_algos/strongly_connected_components.rs b/crates/cairo-lang-utils/src/graph_algos/strongly_connected_components.rs index a4186f5698b..ed76cc67830 100644 --- a/crates/cairo-lang-utils/src/graph_algos/strongly_connected_components.rs +++ b/crates/cairo-lang-utils/src/graph_algos/strongly_connected_components.rs @@ -84,7 +84,7 @@ fn compute_scc_recursive(ctx: &mut SccAlgoContext, curren // neighbor was not visited yet. Visit it and maybe apply its lowlink to root. compute_scc_recursive(ctx, &neighbor); // Now neighbor should be in known_nodes. - current_wrapper_node.lowlink = std::cmp::min( + current_wrapper_node.lowlink = core::cmp::min( current_wrapper_node.lowlink, ctx.known_nodes[&neighbor_id].lowlink, ); @@ -93,7 +93,7 @@ fn compute_scc_recursive(ctx: &mut SccAlgoContext, curren if ctx.known_nodes[&neighbor_id].on_stack { // This is a back edge, meaning neighbor is in current_node's SCC. current_wrapper_node.lowlink = - std::cmp::min(current_wrapper_node.lowlink, neighbor_node.index); + core::cmp::min(current_wrapper_node.lowlink, neighbor_node.index); } else { // If neighbor is known but not on stack, it's in a concluded dropped SCC. // Ignore it. diff --git a/crates/cairo-lang-utils/src/lib.rs b/crates/cairo-lang-utils/src/lib.rs index 338fc1f2483..04ded5281ac 100644 --- a/crates/cairo-lang-utils/src/lib.rs +++ b/crates/cairo-lang-utils/src/lib.rs @@ -1,11 +1,21 @@ //! Cairo utilities. -use std::fmt; +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(not(feature = "std"))] +extern crate alloc; + +#[cfg(not(feature = "std"))] +use alloc::boxed::Box; +use core::fmt; + +#[cfg(feature = "serde")] pub mod bigint; pub mod byte_array; pub mod casts; pub mod collection_arithmetics; pub mod extract_matches; +#[cfg(feature = "std")] pub mod graph_algos; pub mod iterators; #[cfg(feature = "env_logger")] @@ -23,7 +33,7 @@ where fn option_from(other: T) -> Option; } -pub fn write_comma_separated, V: std::fmt::Display>( +pub fn write_comma_separated, V: core::fmt::Display>( f: &mut fmt::Formatter<'_>, values: Iter, ) -> fmt::Result { @@ -83,7 +93,7 @@ impl ResultHelper for Result { pub fn borrow_as_box) -> (R, Box)>(ptr: &mut T, f: F) -> R { // TODO(spapini): Consider replacing take with something the leaves the memory dangling, instead // of filling with default(). - let (res, boxed) = f(Box::new(std::mem::take(ptr))); + let (res, boxed) = f(Box::new(core::mem::take(ptr))); *ptr = *boxed; res } @@ -115,7 +125,7 @@ macro_rules! define_short_id { cairo_lang_debug::DebugWithDb for $short_id { fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &T) -> std::fmt::Result { - use std::fmt::Debug; + use core::fmt::Debug; use cairo_lang_debug::helper::Fallback; let db = db.upcast(); diff --git a/crates/cairo-lang-utils/src/ordered_hash_map.rs b/crates/cairo-lang-utils/src/ordered_hash_map.rs index 6db13da453c..843e33b6201 100644 --- a/crates/cairo-lang-utils/src/ordered_hash_map.rs +++ b/crates/cairo-lang-utils/src/ordered_hash_map.rs @@ -1,36 +1,26 @@ -use std::hash::Hash; -use std::ops::{Index, IndexMut}; +use core::hash::{BuildHasher, Hash}; +use core::ops::{Index, IndexMut}; +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState; use indexmap::{Equivalent, IndexMap}; -use itertools::{zip_eq, Itertools}; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; - -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct OrderedHashMap(IndexMap); - -impl OrderedHashMap { - /// Returns a reference to the value stored for key, if it is present, else None. - /// - /// Computes in O(1) time (average). - pub fn get>(&self, key: &Q) -> Option<&Value> { - self.0.get(key) - } - - /// Returns a mutable reference to the value stored for key, if it is present, else None. - /// - /// Computes in O(1) time (average). - pub fn get_mut>(&mut self, key: &Q) -> Option<&mut Value> { - self.0.get_mut(key) - } - - /// Gets the given key’s corresponding entry in the map for insertion and/or in-place - /// manipulation. - /// - /// Computes in O(1) time (amortized average). - pub fn entry(&mut self, key: Key) -> Entry<'_, Key, Value> { - self.0.entry(key) +use itertools::zip_eq; + +#[cfg(feature = "std")] +#[derive(Clone, Debug)] +pub struct OrderedHashMap(IndexMap); +#[cfg(not(feature = "std"))] +#[derive(Clone, Debug)] +pub struct OrderedHashMap(IndexMap); + +#[cfg(feature = "std")] +impl OrderedHashMap { + pub fn new() -> Self { + Self(IndexMap::new()) } +} +impl OrderedHashMap { /// Returns an iterator over the key-value pairs of the map, in their order. pub fn iter(&self) -> indexmap::map::Iter<'_, Key, Value> { self.0.iter() @@ -56,6 +46,52 @@ impl OrderedHashMap { self.0.values() } + /// Returns the number of key-value pairs in the map. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Returns true if the map contains no elements. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Removes all the entries for the map. + pub fn clear(&mut self) { + self.0.clear() + } + + /// Removes the entry at the given index. + /// + /// Returns the key-value pair at the given index (if present). + pub fn shift_remove_index(&mut self, index: usize) -> Option<(Key, Value)> { + self.0.shift_remove_index(index) + } +} + +impl OrderedHashMap { + /// Returns a reference to the value stored for key, if it is present, else None. + /// + /// Computes in O(1) time (average). + pub fn get>(&self, key: &Q) -> Option<&Value> { + self.0.get(key) + } + + /// Returns a mutable reference to the value stored for key, if it is present, else None. + /// + /// Computes in O(1) time (average). + pub fn get_mut>(&mut self, key: &Q) -> Option<&mut Value> { + self.0.get_mut(key) + } + + /// Gets the given key’s corresponding entry in the map for insertion and/or in-place + /// manipulation. + /// + /// Computes in O(1) time (amortized average). + pub fn entry(&mut self, key: Key) -> Entry<'_, Key, Value> { + self.0.entry(key) + } + /// Insert a key-value pair in the map. /// /// If an equivalent key already exists in the map: the key remains and retains in its place in @@ -83,21 +119,6 @@ impl OrderedHashMap { self.0.contains_key(key) } - /// Returns the number of key-value pairs in the map. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Returns true if the map contains no elements. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - - /// Removes all the entries for the map. - pub fn clear(&mut self) { - self.0.clear() - } - /// Removes the entry for the given key, preserving the order of entries. /// /// Returns the value associated with the key (if present). @@ -113,13 +134,6 @@ impl OrderedHashMap { self.0.swap_remove(key) } - /// Removes the entry at the given index. - /// - /// Returns the key-value pair at the given index (if present). - pub fn shift_remove_index(&mut self, index: usize) -> Option<(Key, Value)> { - self.0.shift_remove_index(index) - } - /// Returns true if the maps are equal, ignoring the order of the entries. pub fn eq_unordered(&self, other: &Self) -> bool where @@ -135,7 +149,7 @@ impl OrderedHashMap { /// Entry for an existing key-value pair or a vacant location to insert one. pub type Entry<'a, Key, Value> = indexmap::map::Entry<'a, Key, Value>; -impl IntoIterator for OrderedHashMap { +impl IntoIterator for OrderedHashMap { type Item = (Key, Value); type IntoIter = indexmap::map::IntoIter; fn into_iter(self) -> Self::IntoIter { @@ -144,23 +158,31 @@ impl IntoIterator for OrderedHashMap { } } -impl, Value> Index for OrderedHashMap { +impl Index<&Q> for OrderedHashMap +where + Q: Hash + Equivalent, + Key: Hash + Eq, + BH: BuildHasher, +{ type Output = Value; - fn index(&self, index: IndexType) -> &Self::Output { - &self.0[&index.into()] + fn index(&self, index: &Q) -> &Self::Output { + self.0.index(index) } } -impl, Value> IndexMut - for OrderedHashMap +impl IndexMut<&Q> for OrderedHashMap +where + Q: Hash + Equivalent, + Key: Hash + Eq, + BH: BuildHasher, { - fn index_mut(&mut self, index: IndexType) -> &mut Value { - self.0.index_mut(&index.into()) + fn index_mut(&mut self, index: &Q) -> &mut Value { + self.0.index_mut(index) } } -impl PartialEq for OrderedHashMap { +impl PartialEq for OrderedHashMap { fn eq(&self, other: &Self) -> bool { if self.0.len() != other.0.len() { return false; @@ -170,47 +192,81 @@ impl PartialEq for OrderedHashMap { } } -impl Eq for OrderedHashMap { - fn assert_receiver_is_total_eq(&self) {} -} +impl Eq for OrderedHashMap {} -impl Default for OrderedHashMap { +impl Default for OrderedHashMap { fn default() -> Self { - Self(Default::default()) + Self(IndexMap::default()) } } -impl FromIterator<(Key, Value)> for OrderedHashMap { +impl FromIterator<(Key, Value)> + for OrderedHashMap +{ fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect()) } } -impl From<[(Key, Value); N]> for OrderedHashMap { +impl From<[(Key, Value); N]> + for OrderedHashMap +{ fn from(init_map: [(Key, Value); N]) -> Self { - Self(init_map.into()) + Self(IndexMap::from_iter(init_map)) } } -pub fn serialize_ordered_hashmap_vec<'de, K, V, S>( - v: &OrderedHashMap, - serializer: S, -) -> Result -where - S: Serializer, - K: Serialize + Deserialize<'de> + Hash + Eq, - V: Serialize + Deserialize<'de>, -{ - v.iter().collect_vec().serialize(serializer) -} +#[cfg(feature = "serde")] +mod impl_serde { + #[cfg(not(feature = "std"))] + use alloc::vec::Vec; -pub fn deserialize_ordered_hashmap_vec<'de, K, V, D>( - deserializer: D, -) -> Result, D::Error> -where - D: Deserializer<'de>, - K: Serialize + Deserialize<'de> + Hash + Eq, - V: Serialize + Deserialize<'de>, -{ - Ok(Vec::<(K, V)>::deserialize(deserializer)?.into_iter().collect()) + use itertools::Itertools; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::*; + + impl Serialize + for OrderedHashMap + { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.0.serialize(serializer) + } + } + + impl<'de, K: Hash + Eq + Deserialize<'de>, V: Deserialize<'de>, BH: BuildHasher + Default> + Deserialize<'de> for OrderedHashMap + { + fn deserialize>(deserializer: D) -> Result { + IndexMap::::deserialize(deserializer).map(|s| OrderedHashMap(s)) + } + } + + pub fn serialize_ordered_hashmap_vec<'de, K, V, BH, S>( + v: &OrderedHashMap, + serializer: S, + ) -> Result + where + S: Serializer, + K: Serialize + Deserialize<'de> + Hash + Eq, + V: Serialize + Deserialize<'de>, + { + v.iter().collect_vec().serialize(serializer) + } + + pub fn deserialize_ordered_hashmap_vec<'de, K, V, BH: BuildHasher + Default, D>( + deserializer: D, + ) -> Result, D::Error> + where + D: Deserializer<'de>, + K: Serialize + Deserialize<'de> + Hash + Eq, + V: Serialize + Deserialize<'de>, + { + Ok(Vec::<(K, V)>::deserialize(deserializer)?.into_iter().collect()) + } } +#[cfg(feature = "serde")] +pub use impl_serde::*; diff --git a/crates/cairo-lang-utils/src/ordered_hash_set.rs b/crates/cairo-lang-utils/src/ordered_hash_set.rs index b5cdac31d55..6dcd003beb6 100644 --- a/crates/cairo-lang-utils/src/ordered_hash_set.rs +++ b/crates/cairo-lang-utils/src/ordered_hash_set.rs @@ -1,17 +1,22 @@ +use core::hash::{BuildHasher, Hash}; +use core::ops::Sub; +#[cfg(feature = "std")] use std::collections::hash_map::RandomState; -use std::hash::{BuildHasher, Hash}; -use std::ops::Sub; use indexmap::{Equivalent, IndexSet}; use itertools::zip_eq; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; +#[cfg(feature = "std")] #[derive(Clone, Debug)] -pub struct OrderedHashSet(IndexSet); +pub struct OrderedHashSet(IndexSet); +#[cfg(not(feature = "std"))] +#[derive(Clone, Debug)] +pub struct OrderedHashSet(IndexSet); pub type Iter<'a, Key> = indexmap::set::Iter<'a, Key>; -impl OrderedHashSet { +#[cfg(feature = "std")] +impl OrderedHashSet { /// Creates an empty `OrderedHashSet`. /// /// The hash set is initially created with a capacity of 0, so it will not allocate until it @@ -19,29 +24,16 @@ impl OrderedHashSet { pub fn new() -> Self { Self(IndexSet::new()) } +} +impl OrderedHashSet { /// Returns an iterator over the values of the set, in their order. pub fn iter(&self) -> Iter<'_, Key> { self.0.iter() } +} - /// Inserts the value into the set. - /// - /// If an equivalent item already exists in the set, returns `false`. Otherwise, returns `true`. - pub fn insert(&mut self, key: Key) -> bool { - self.0.insert(key) - } - - /// Extends the set with the content of the given iterator. - pub fn extend>(&mut self, iter: I) { - self.0.extend(iter) - } - - /// Returns true if an equivalent to value exists in the set. - pub fn contains>(&self, value: &Q) -> bool { - self.0.contains(value) - } - +impl OrderedHashSet { /// Returns the number of elements in the set. pub fn len(&self) -> usize { self.0.len() @@ -58,6 +50,25 @@ impl OrderedHashSet { pub fn clear(&mut self) { self.0.clear() } +} + +impl OrderedHashSet { + /// Inserts the value into the set. + /// + /// If an equivalent item already exists in the set, returns `false`. Otherwise, returns `true`. + pub fn insert(&mut self, key: Key) -> bool { + self.0.insert(key) + } + + /// Extends the set with the content of the given iterator. + pub fn extend>(&mut self, iter: I) { + self.0.extend(iter) + } + + /// Returns true if an equivalent to value exists in the set. + pub fn contains>(&self, value: &Q) -> bool { + self.0.contains(value) + } /// Removes the value from the set, preserving the order of elements. /// @@ -79,7 +90,7 @@ impl OrderedHashSet { other: &'a OrderedHashSet, ) -> indexmap::set::Difference<'a, Key, S2> where - S2: std::hash::BuildHasher, + S2: core::hash::BuildHasher, { self.0.difference(&other.0) } @@ -93,40 +104,38 @@ impl OrderedHashSet { pub fn is_superset(&self, other: &OrderedHashSet) -> bool { self.0.is_superset(&other.0) } -} -impl OrderedHashSet { /// Return an iterator over all values that are either in `self` or `other`. /// /// Values from `self` are produced in their original order, followed by /// values that are unique to `other` in their original order. - pub fn union<'a, S2: BuildHasher>( + pub fn union<'a, BH2: BuildHasher>( &'a self, - other: &'a OrderedHashSet, - ) -> indexmap::set::Union<'a, Key, S> { + other: &'a OrderedHashSet, + ) -> indexmap::set::Union<'a, Key, BH> { self.0.union(&other.0) } } -impl IntoIterator for OrderedHashSet { +impl IntoIterator for OrderedHashSet { type Item = Key; - type IntoIter = as IntoIterator>::IntoIter; + type IntoIter = as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } -impl<'a, Key: Hash + Eq> IntoIterator for &'a OrderedHashSet { +impl<'a, Key, BH> IntoIterator for &'a OrderedHashSet { type Item = &'a Key; - type IntoIter = <&'a IndexSet as IntoIterator>::IntoIter; + type IntoIter = <&'a IndexSet as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.iter() } } -impl PartialEq for OrderedHashSet { +impl PartialEq for OrderedHashSet { fn eq(&self, other: &Self) -> bool { if self.0.len() != other.0.len() { return false; @@ -136,37 +145,48 @@ impl PartialEq for OrderedHashSet { } } -impl Eq for OrderedHashSet { - fn assert_receiver_is_total_eq(&self) {} -} +impl Eq for OrderedHashSet {} -impl Default for OrderedHashSet { +impl Default for OrderedHashSet { fn default() -> Self { Self(Default::default()) } } -impl FromIterator for OrderedHashSet { +impl FromIterator for OrderedHashSet { fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect()) } } -impl<'a, Key: Hash + Eq + Clone> Sub<&'a OrderedHashSet> for &'a OrderedHashSet { - type Output = OrderedHashSet; +impl<'a, Key, BH> Sub<&'a OrderedHashSet> for &'a OrderedHashSet +where + &'a IndexSet: Sub>, +{ + type Output = OrderedHashSet; fn sub(self, rhs: Self) -> Self::Output { - OrderedHashSet::(&self.0 - &rhs.0) + OrderedHashSet::(&self.0 - &rhs.0) } } -impl Serialize for OrderedHashSet { - fn serialize(&self, serializer: S) -> Result { - self.0.serialize(serializer) +#[cfg(feature = "serde")] +mod impl_serde { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + use super::*; + + impl Serialize for OrderedHashSet { + fn serialize(&self, serializer: S) -> Result { + self.0.serialize(serializer) + } } -} -impl<'de, K: Hash + Eq + Deserialize<'de>> Deserialize<'de> for OrderedHashSet { - fn deserialize>(deserializer: D) -> Result { - IndexSet::::deserialize(deserializer).map(|s| OrderedHashSet(s)) + + impl<'de, K: Hash + Eq + Deserialize<'de>, BH: BuildHasher + Default> Deserialize<'de> + for OrderedHashSet + { + fn deserialize>(deserializer: D) -> Result { + IndexSet::::deserialize(deserializer).map(|s| OrderedHashSet(s)) + } } } diff --git a/crates/cairo-lang-utils/src/unordered_hash_map.rs b/crates/cairo-lang-utils/src/unordered_hash_map.rs index c3d47a2b5a9..c6aa92903dd 100644 --- a/crates/cairo-lang-utils/src/unordered_hash_map.rs +++ b/crates/cairo-lang-utils/src/unordered_hash_map.rs @@ -1,15 +1,63 @@ -use std::borrow::Borrow; -use std::collections::{hash_map, HashMap}; -use std::hash::Hash; -use std::ops::Index; +use core::borrow::Borrow; +use core::hash::{BuildHasher, Hash}; +use core::ops::Index; +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState; +#[cfg(feature = "std")] +use std::collections::HashMap; + +#[cfg(not(feature = "std"))] +use hashbrown::HashMap; /// A hash map that does not care about the order of insertion. /// In particular, it does not support iterating, in order to guarantee deterministic compilation. /// For an iterable version see [OrderedHashMap](crate::ordered_hash_map::OrderedHashMap). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct UnorderedHashMap(HashMap); +#[cfg(feature = "std")] +#[derive(Clone, Debug)] +pub struct UnorderedHashMap(HashMap); +#[cfg(not(feature = "std"))] +#[derive(Clone, Debug)] +pub struct UnorderedHashMap(HashMap); + +#[cfg(feature = "std")] +impl UnorderedHashMap { + pub fn new() -> Self { + Self(HashMap::new()) + } +} + +impl PartialEq for UnorderedHashMap +where + Key: Eq + Hash, + Value: PartialEq, + BH: BuildHasher, +{ + fn eq(&self, other: &Self) -> bool { + self.0.eq(&other.0) + } +} + +impl Eq for UnorderedHashMap +where + Key: Eq + Hash, + Value: Eq, + BH: BuildHasher, +{ +} + +impl UnorderedHashMap { + /// Returns the number of elements in the map. + pub fn len(&self) -> usize { + self.0.len() + } -impl UnorderedHashMap { + /// Returns true if the map contains no elements. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl UnorderedHashMap { /// Returns a reference to the value corresponding to the key. /// /// The key may be any borrowed form of the map's key type, but [`Hash`] and [`Eq`] on the @@ -58,8 +106,15 @@ impl UnorderedHashMap { self.0.remove(key) } + #[cfg(feature = "std")] + /// Gets the given key's corresponding entry in the map for in-place manipulation. + pub fn entry(&mut self, key: Key) -> std::collections::hash_map::Entry<'_, Key, Value> { + self.0.entry(key) + } + + #[cfg(not(feature = "std"))] /// Gets the given key's corresponding entry in the map for in-place manipulation. - pub fn entry(&mut self, key: Key) -> hash_map::Entry<'_, Key, Value> { + pub fn entry(&mut self, key: Key) -> hashbrown::hash_map::Entry<'_, Key, Value, BH> { self.0.entry(key) } @@ -72,19 +127,9 @@ impl UnorderedHashMap { { self.0.contains_key(key) } - - /// Returns the number of elements in the map. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Returns true if the map contains no elements. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } } -impl Index<&Q> for UnorderedHashMap +impl Index<&Q> for UnorderedHashMap where Key: Eq + Hash + Borrow, Q: Eq + Hash, @@ -96,22 +141,24 @@ where } } -impl Default for UnorderedHashMap { +impl Default for UnorderedHashMap { fn default() -> Self { Self(Default::default()) } } -impl FromIterator<(Key, Value)> for UnorderedHashMap { +impl FromIterator<(Key, Value)> + for UnorderedHashMap +{ fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect()) } } -impl From<[(Key, Value); N]> - for UnorderedHashMap +impl From<[(Key, Value); N]> + for UnorderedHashMap { fn from(items: [(Key, Value); N]) -> Self { - Self(HashMap::from(items)) + Self(HashMap::from_iter(items)) } } diff --git a/crates/cairo-lang-utils/src/unordered_hash_set.rs b/crates/cairo-lang-utils/src/unordered_hash_set.rs index f0e7569b810..6c09a17347d 100644 --- a/crates/cairo-lang-utils/src/unordered_hash_set.rs +++ b/crates/cairo-lang-utils/src/unordered_hash_set.rs @@ -1,15 +1,66 @@ -use std::borrow::Borrow; +use core::borrow::Borrow; +use core::hash::{BuildHasher, Hash}; +use core::ops::Sub; +#[cfg(feature = "std")] +use std::collections::hash_map::RandomState; +#[cfg(feature = "std")] use std::collections::HashSet; -use std::hash::Hash; -use std::ops::Sub; + +#[cfg(not(feature = "std"))] +use hashbrown::HashSet; /// A hash set that does not care about the order of insertion. /// In particular, it does not support iterating, in order to guarantee deterministic compilation. /// For an iterable version see [OrderedHashSet](crate::ordered_hash_set::OrderedHashSet). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct UnorderedHashSet(HashSet); +#[cfg(feature = "std")] +#[derive(Clone, Debug)] +pub struct UnorderedHashSet(HashSet); +#[cfg(not(feature = "std"))] +#[derive(Clone, Debug)] +pub struct UnorderedHashSet(HashSet); + +#[cfg(feature = "std")] +impl UnorderedHashSet { + pub fn new() -> Self { + Self(HashSet::new()) + } +} + +impl PartialEq for UnorderedHashSet +where + K: Eq + Hash, + BH: BuildHasher, +{ + fn eq(&self, other: &Self) -> bool { + self.0.eq(&other.0) + } +} + +impl Eq for UnorderedHashSet +where + K: Eq + Hash, + BH: BuildHasher, +{ +} + +impl UnorderedHashSet { + /// Returns the number of elements in the set. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Returns true if the set contains no elements. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Clears the set, removing all values. + pub fn clear(&mut self) { + self.0.clear() + } +} -impl UnorderedHashSet { +impl UnorderedHashSet { /// Inserts the value into the set. /// /// If an equivalent item already exists in the set, returns `false`. Otherwise, returns `true`. @@ -42,39 +93,27 @@ impl UnorderedHashSet { { self.0.contains(value) } - - /// Returns the number of elements in the set. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Returns true if the set contains no elements. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - - /// Clears the set, removing all values. - pub fn clear(&mut self) { - self.0.clear() - } } -impl Default for UnorderedHashSet { +impl Default for UnorderedHashSet { fn default() -> Self { Self(Default::default()) } } -impl FromIterator for UnorderedHashSet { +impl FromIterator for UnorderedHashSet { fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect()) } } -impl<'a, Key: Hash + Eq + Clone> Sub<&'a UnorderedHashSet> for &'a UnorderedHashSet { - type Output = UnorderedHashSet; +impl<'a, Key, BH> Sub<&'a UnorderedHashSet> for &'a UnorderedHashSet +where + &'a HashSet: Sub>, +{ + type Output = UnorderedHashSet; fn sub(self, rhs: Self) -> Self::Output { - UnorderedHashSet::(&self.0 - &rhs.0) + UnorderedHashSet::(&self.0 - &rhs.0) } } diff --git a/ensure-no_std/.cargo/config.toml b/ensure-no_std/.cargo/config.toml new file mode 100644 index 00000000000..f4e8c002fc2 --- /dev/null +++ b/ensure-no_std/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +target = "wasm32-unknown-unknown" diff --git a/ensure-no_std/Cargo.toml b/ensure-no_std/Cargo.toml new file mode 100644 index 00000000000..aab3b73013b --- /dev/null +++ b/ensure-no_std/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "ensure-no_std" +version = "0.1.0" +edition = "2021" + +[dependencies] +cairo-lang-utils = { path = "../crates/cairo-lang-utils", default-features = false, features = ["serde"] } + +esp-alloc = "0.3.0" diff --git a/ensure-no_std/src/main.rs b/ensure-no_std/src/main.rs new file mode 100644 index 00000000000..79d4894f811 --- /dev/null +++ b/ensure-no_std/src/main.rs @@ -0,0 +1,22 @@ +#![no_std] +#![no_main] + +use core::panic::PanicInfo; + +/// This function is called on panic. +#[panic_handler] +fn panic(_info: &PanicInfo) -> ! { + loop {} +} + +#[no_mangle] +pub extern "C" fn _start() -> ! { + loop {} +} + +#[global_allocator] +// NOTE: this should be initialized before use +static ALLOC: esp_alloc::EspHeap = esp_alloc::EspHeap::empty(); + +#[allow(unused_imports)] +use cairo_lang_utils; diff --git a/tests/Cargo.toml b/tests/Cargo.toml index b76547550d7..c8f141833bc 100644 --- a/tests/Cargo.toml +++ b/tests/Cargo.toml @@ -27,9 +27,9 @@ cairo-lang-syntax = { path = "../crates/cairo-lang-syntax" } cairo-lang-test-utils = { path = "../crates/cairo-lang-test-utils", features = ["testing"] } cairo-lang-utils = { path = "../crates/cairo-lang-utils" } env_logger.workspace = true -itertools.workspace = true +itertools = { workspace = true, default-features = true } log.workspace = true -num-bigint.workspace = true +num-bigint = { workspace = true, default-features = true } once_cell.workspace = true pretty_assertions.workspace = true rstest.workspace = true