Skip to content

Commit

Permalink
Added require util.
Browse files Browse the repository at this point in the history
Used all around.

commit-id:ec6469b5
  • Loading branch information
orizi committed Apr 14, 2024
1 parent 5627462 commit 50f0be8
Show file tree
Hide file tree
Showing 27 changed files with 94 additions and 151 deletions.
8 changes: 3 additions & 5 deletions crates/cairo-lang-defs/src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::kind::SyntaxKind;
use cairo_lang_syntax::node::stable_ptr::SyntaxStablePtr;
use cairo_lang_syntax::node::{ast, Terminal, TypedStablePtr, TypedSyntaxNode};
use cairo_lang_utils::{define_short_id, OptionFrom};
use cairo_lang_utils::{define_short_id, require, OptionFrom};
use smol_str::SmolStr;

use crate::db::DefsGroup;
Expand Down Expand Up @@ -518,12 +518,10 @@ impl GenericParamLongId {
else {
unreachable!()
};
if matches!(
require(!matches!(
kind,
SyntaxKind::GenericParamImplAnonymous | SyntaxKind::GenericParamNegativeImpl
) {
return None;
}
))?;

let name_green = TerminalIdentifierGreen(key_fields[0]);
Some(name_green.identifier(db))
Expand Down
5 changes: 2 additions & 3 deletions crates/cairo-lang-defs/src/plugin_utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::helpers::WrappedArgListHelper;
use cairo_lang_syntax::node::{ast, SyntaxNode, TypedSyntaxNode};
use cairo_lang_utils::require;
use itertools::Itertools;

use crate::plugin::{InlinePluginResult, PluginDiagnostic, PluginResult};
Expand Down Expand Up @@ -89,9 +90,7 @@ pub fn extract_unnamed_args(
n: usize,
) -> Option<Vec<ast::Expr>> {
let elements = macro_arguments.elements(db);
if elements.len() != n {
return None;
}
require(elements.len() == n)?;
elements.iter().map(|x| try_extract_unnamed_arg(db, x)).collect()
}

Expand Down
5 changes: 2 additions & 3 deletions crates/cairo-lang-lowering/src/lower/block_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use cairo_lang_semantic as semantic;
use cairo_lang_syntax::node::TypedStablePtr;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::ordered_hash_set::OrderedHashSet;
use cairo_lang_utils::require;
use itertools::{chain, zip_eq, Itertools};
use semantic::items::structure::SemanticStructEx;
use semantic::{ConcreteTypeId, ExprVarMemberPath, TypeLongId};
Expand Down Expand Up @@ -276,9 +277,7 @@ impl BlockBuilder {
}
}

if n_reachable_blocks == 0 {
return None;
}
require(n_reachable_blocks != 0)?;

// If there are reachable blocks, create a new empty block for the code after this match.
let following_block = ctx.blocks.alloc_empty();
Expand Down
5 changes: 2 additions & 3 deletions crates/cairo-lang-lowering/src/objects/blocks.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::ops::{Index, IndexMut};

use cairo_lang_diagnostics::{DiagnosticAdded, Maybe};
use cairo_lang_utils::require;

use crate::FlatBlock;

Expand Down Expand Up @@ -56,9 +57,7 @@ impl<T: Default> BlocksBuilder<T> {
}

pub fn build(self) -> Option<Blocks<T>> {
if self.is_empty() {
return None;
}
require(!self.is_empty())?;
Some(Blocks(self.0))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
mod test;

use cairo_lang_semantic as semantic;
use cairo_lang_utils::extract_matches;
use cairo_lang_utils::{extract_matches, require};
use itertools::Itertools;
use semantic::MatchArmSelector;

Expand Down Expand Up @@ -84,19 +84,15 @@ impl ReturnOptimizerContext<'_> {
let MatchInfo::Enum(MatchEnumInfo { input, arms, .. }) = match_info else {
return None;
};
if arms.is_empty() {
return None;
}
require(!arms.is_empty())?;

let input_info = self.get_var_info(input);
let mut opt_last_info = None;
for (arm, info) in arms.iter().zip(infos) {
let mut curr_info = info.clone();
curr_info.apply_match_arm(self.is_droppable(input.var_id), &input_info, arm);

if !curr_info.early_return_possible() {
return None;
}
require(curr_info.early_return_possible())?;

match curr_info.opt_return_info {
Some(return_info)
Expand Down
5 changes: 2 additions & 3 deletions crates/cairo-lang-parser/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use cairo_lang_syntax::node::ast::{
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::kind::SyntaxKind;
use cairo_lang_syntax::node::Token;
use cairo_lang_utils::require;
use smol_str::SmolStr;

pub struct Lexer<'a> {
Expand Down Expand Up @@ -323,9 +324,7 @@ impl Iterator for Lexer<'_> {
/// Returns the next token. Once there are no more tokens left, returns token EOF.
/// One should not call this after EOF was returned. If one does, None is returned.
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
require(!self.done)?;
let lexer_terminal = self.match_terminal();
if lexer_terminal.kind == SyntaxKind::TerminalEndOfFile {
self.done = true;
Expand Down
6 changes: 2 additions & 4 deletions crates/cairo-lang-parser/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use cairo_lang_syntax::node::ast::*;
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::kind::SyntaxKind;
use cairo_lang_syntax::node::{SyntaxNode, Token, TypedSyntaxNode};
use cairo_lang_utils::extract_matches;
use cairo_lang_utils::{extract_matches, require};
use syntax::node::green::{GreenNode, GreenNodeDetails};
use syntax::node::ids::GreenId;

Expand Down Expand Up @@ -667,9 +667,7 @@ impl<'a> Parser<'a> {

/// Returns a GreenId of node with pub visibility or None if not starting with "pub".
fn try_parse_visibility_pub(&mut self) -> Option<VisibilityPubGreen> {
if self.peek().kind != SyntaxKind::TerminalPub {
return None;
}
require(self.peek().kind == SyntaxKind::TerminalPub)?;
let pub_kw = self.take::<TerminalPub>();
let argument_clause = if self.peek().kind != SyntaxKind::TerminalLParen {
OptionVisibilityPubArgumentClauseEmpty::new_green(self.db).into()
Expand Down
6 changes: 2 additions & 4 deletions crates/cairo-lang-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ use cairo_lang_sierra_to_casm::metadata::{
use cairo_lang_sierra_type_size::{get_type_size_map, TypeSizeMap};
use cairo_lang_starknet::contract::ContractInfo;
use cairo_lang_utils::casts::IntoOrPanic;
use cairo_lang_utils::extract_matches;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::{extract_matches, require};
use cairo_vm::hint_processor::hint_processor_definition::HintProcessor;
use cairo_vm::serde::deserialize_program::{BuiltinName, HintParams};
use cairo_vm::vm::errors::cairo_run_errors::CairoRunError;
Expand Down Expand Up @@ -736,9 +736,7 @@ impl SierraCasmRunner {
}

pub fn initial_required_gas(&self, func: &Function) -> Option<usize> {
if self.metadata.gas_info.function_costs.is_empty() {
return None;
}
require(!self.metadata.gas_info.function_costs.is_empty())?;
Some(
self.metadata.gas_info.function_costs[&func.id]
.iter()
Expand Down
9 changes: 3 additions & 6 deletions crates/cairo-lang-runner/src/profiling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use cairo_lang_sierra::ids::ConcreteLibfuncId;
use cairo_lang_sierra::program::{GenStatement, Program, StatementIdx};
use cairo_lang_sierra_generator::db::SierraGenGroup;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::require;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use smol_str::SmolStr;

Expand Down Expand Up @@ -290,9 +291,7 @@ impl<'a> ProfilingInfoProcessor<'a> {
sierra_statement_weights_iter: std::vec::IntoIter<(&StatementIdx, &usize)>,
params: &ProfilingInfoProcessorParams,
) -> Option<OrderedHashMap<StatementIdx, (usize, GenStatement<StatementIdx>)>> {
if !params.process_by_statement {
return None;
}
require(params.process_by_statement)?;

Some(
sierra_statement_weights_iter
Expand Down Expand Up @@ -472,9 +471,7 @@ impl<'a> ProfilingInfoProcessor<'a> {
sierra_statement_weights: std::vec::IntoIter<(&StatementIdx, &usize)>,
params: &ProfilingInfoProcessorParams,
) -> Option<OrderedHashMap<String, usize>> {
if !params.process_by_cairo_function {
return None;
}
require(params.process_by_cairo_function)?;

let mut cairo_functions = UnorderedHashMap::<_, _>::default();
for (statement_idx, weight) in sierra_statement_weights {
Expand Down
6 changes: 2 additions & 4 deletions crates/cairo-lang-semantic/src/expr/inference/infers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cairo_lang_defs::ids::{ImplAliasId, ImplDefId, TraitFunctionId};
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_utils::extract_matches;
use cairo_lang_utils::{extract_matches, require};
use itertools::Itertools;

use super::canonic::ResultNoErrEx;
Expand Down Expand Up @@ -261,9 +261,7 @@ impl<'db> InferenceEmbeddings for Inference<'db> {
let trait_id = trait_function.trait_id(self.db.upcast());
let signature = self.db.trait_function_signature(trait_function).ok()?;
let first_param = signature.params.into_iter().next()?;
if first_param.name != "self" {
return None;
}
require(first_param.name == "self")?;
let generic_params = self.db.trait_generic_params(trait_id).ok()?;
let generic_args =
match self.infer_generic_args(&generic_params, lookup_context, stable_ptr) {
Expand Down
6 changes: 2 additions & 4 deletions crates/cairo-lang-semantic/src/items/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use cairo_lang_proc_macros::{DebugWithDb, SemanticObject};
use cairo_lang_syntax as syntax;
use cairo_lang_syntax::attribute::structured::Attribute;
use cairo_lang_syntax::node::{ast, Terminal, TypedSyntaxNode};
use cairo_lang_utils::{define_short_id, try_extract_matches, OptionFrom};
use cairo_lang_utils::{define_short_id, require, try_extract_matches, OptionFrom};
use itertools::{chain, Itertools};
use smol_str::SmolStr;
use syntax::attribute::consts::MUST_USE_ATTR;
Expand Down Expand Up @@ -391,9 +391,7 @@ impl ConcreteFunctionWithBody {
db: &dyn SemanticGroup,
free_function_id: FreeFunctionId,
) -> Option<Self> {
if !db.free_function_generic_params(free_function_id).ok()?.is_empty() {
return None;
}
require(db.free_function_generic_params(free_function_id).ok()?.is_empty())?;
Some(ConcreteFunctionWithBody {
generic_function: GenericFunctionWithBodyId::Free(free_function_id),
generic_args: vec![],
Expand Down
10 changes: 3 additions & 7 deletions crates/cairo-lang-semantic/src/literals.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use cairo_lang_defs::ids::NamedLanguageElementId;
use cairo_lang_diagnostics::ToOption;
use cairo_lang_utils::try_extract_matches;
use cairo_lang_utils::{require, try_extract_matches};
use id_arena::Arena;
use num_bigint::BigInt;

Expand All @@ -19,17 +19,13 @@ pub fn try_extract_minus_literal(
let [ExprFunctionCallArg::Value(expr_id)] = &expr.args[..] else {
return None;
};
if expr.coupon_arg.is_some() {
return None;
}
require(expr.coupon_arg.is_none())?;
let literal = try_extract_matches!(&exprs[*expr_id], Expr::Literal)?;
let imp = try_extract_matches!(
expr.function.get_concrete(db).generic_function,
GenericFunctionId::Impl
)?;
let trait_id = imp.impl_id.concrete_trait(db).to_option()?.trait_id(db);
if trait_id != get_core_trait(db, "Neg".into()) {
return None;
}
require(trait_id == get_core_trait(db, "Neg".into()))?;
if imp.function.name(db.upcast()) != "neg" { None } else { Some(-literal.value.clone()) }
}
10 changes: 3 additions & 7 deletions crates/cairo-lang-semantic/src/resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::{ast, Terminal, TypedSyntaxNode};
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::ordered_hash_set::OrderedHashSet;
use cairo_lang_utils::try_extract_matches;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::{require, try_extract_matches};
pub use item::{ResolvedConcreteItem, ResolvedGenericItem};
use itertools::Itertools;
use smol_str::SmolStr;
Expand Down Expand Up @@ -803,9 +803,7 @@ impl<'db> Resolver<'db> {
// If the first segment is a name of a crate, use the crate's root module as the base
// module.
let crate_id = self.db.intern_crate(CrateLongId::Real(ident));
if self.db.crate_config(crate_id).is_some() {
return None;
}
require(self.db.crate_config(crate_id).is_none())?;
// Last resort, use the `prelude` module as the base module.
Some(self.prelude_submodule())
}
Expand Down Expand Up @@ -1147,9 +1145,7 @@ fn resolve_self_segment(
identifier: &ast::TerminalIdentifier,
trait_or_impl_ctx: TraitOrImplContext,
) -> Option<Maybe<ResolvedConcreteItem>> {
if identifier.text(db.upcast()) != "Self" {
return None;
}
require(identifier.text(db.upcast()) == "Self")?;

Some(match trait_or_impl_ctx {
TraitOrImplContext::None => Err(diagnostics.report(identifier, SelfNotSupportedInContext)),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::ops::Shl;

use cairo_felt::Felt252;
use cairo_lang_utils::require;
use itertools::Itertools;
use num_bigint::{BigInt, ToBigInt};
use num_traits::{One, Signed};
Expand Down Expand Up @@ -234,13 +235,9 @@ impl BoundedIntDivRemAlgorithm {
let q_max = (&lhs.upper - 1) / &rhs.lower;
let u128_limit = BigInt::one().shl(128);
// `q` is range checked in all algorithm variants, so `q_max` must be smaller than `2**128`.
if q_max >= u128_limit {
return None;
}
require(q_max < u128_limit)?;
// `r` is range checked in all algorithm variants, so `lhs.upper` must be at most `2**128`.
if rhs.upper > u128_limit {
return None;
};
require(rhs.upper <= u128_limit)?;
if &rhs.upper * &u128_limit < prime {
return Some(Self::KnownSmallRhs);
}
Expand Down
Loading

0 comments on commit 50f0be8

Please sign in to comment.