Skip to content

Commit

Permalink
Fix clippy issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Cem Eliguzel committed Aug 11, 2023
1 parent 2d64750 commit 2dd3489
Show file tree
Hide file tree
Showing 13 changed files with 78 additions and 94 deletions.
2 changes: 1 addition & 1 deletion utils/precompiles/macro/src/derive_codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub fn main(input: TokenStream) -> TokenStream {
};
let fields = fields.named;

if fields.len() == 0 {
if fields.is_empty() {
return quote_spanned! { ident.span() =>
compile_error!("Codec can only be derived for structs with at least one field");
}
Expand Down
44 changes: 24 additions & 20 deletions utils/precompiles/macro/src/precompile/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ impl Precompile {

// Fallback method cannot have custom parameters.
if is_fallback {
if let Some(input) = method.sig.inputs.iter().skip(initial_arguments).next() {
if let Some(input) = method.sig.inputs.iter().nth(initial_arguments) {
let msg = if self.tagged_as_precompile_set {
"Fallback methods cannot take any parameter outside of the discriminant and \
PrecompileHandle"
Expand Down Expand Up @@ -291,16 +291,20 @@ impl Precompile {
};

// We insert the collected data in self.
if let Some(_) = self.variants_content.insert(
method_name.clone(),
Variant {
arguments,
solidity_arguments_type: solidity_arguments_type.unwrap_or(String::from("()")),
modifier,
selectors,
fn_output: output_type.as_ref().clone(),
},
) {
if self
.variants_content
.insert(
method_name.clone(),
Variant {
arguments,
solidity_arguments_type: solidity_arguments_type.unwrap_or(String::from("()")),
modifier,
selectors,
fn_output: output_type.as_ref().clone(),
},
)
.is_some()
{
let msg = "Duplicate method name";
return Err(syn::Error::new(method_name.span(), msg));
}
Expand Down Expand Up @@ -335,7 +339,7 @@ impl Precompile {

let input_type = input.ty.as_ref();

self.try_register_discriminant_type(&input_type)?;
self.try_register_discriminant_type(input_type)?;
}

// Precompile handle input
Expand Down Expand Up @@ -364,7 +368,7 @@ impl Precompile {

let input_type = input.ty.as_ref();

if !is_same_type(&input_type, &syn::parse_quote! {&mut impl PrecompileHandle}) {
if !is_same_type(input_type, &syn::parse_quote! {&mut impl PrecompileHandle}) {
let msg = "This parameter must have type `&mut impl PrecompileHandle`";
return Err(syn::Error::new(input_type.span(), msg));
}
Expand All @@ -376,7 +380,7 @@ impl Precompile {
/// Records the type of the discriminant and ensure they all have the same type.
fn try_register_discriminant_type(&mut self, ty: &syn::Type) -> syn::Result<()> {
if let Some(known_type) = &self.precompile_set_discriminant_type {
if !is_same_type(&known_type, &ty) {
if !is_same_type(known_type, ty) {
let msg = format!(
"All discriminants must have the same type (found {} before)",
known_type.to_token_stream()
Expand Down Expand Up @@ -439,7 +443,7 @@ impl Precompile {

let return_segment = &return_path.segments[0];

if return_segment.ident.to_string() != "DiscriminantResult" {
if return_segment.ident != "DiscriminantResult" {
return Err(syn::Error::new(return_segment.ident.span(), msg));
}

Expand All @@ -458,7 +462,7 @@ impl Precompile {
_ => return Err(syn::Error::new(result_arguments.args.span(), msg)),
};

self.try_register_discriminant_type(&discriminant_type)?;
self.try_register_discriminant_type(discriminant_type)?;

self.precompile_set_discriminant_fn = Some(method.sig.ident.clone());

Expand Down Expand Up @@ -504,7 +508,7 @@ impl Precompile {
) -> syn::Result<u32> {
let signature = signature_lit.value();
// Split signature to get arguments type.
let split: Vec<_> = signature.splitn(2, "(").collect();
let split: Vec<_> = signature.splitn(2, '(').collect();
if split.len() != 2 {
let msg = "Selector must have form \"foo(arg1,arg2,...)\"";
return Err(syn::Error::new(signature_lit.span(), msg));
Expand Down Expand Up @@ -545,7 +549,7 @@ impl Precompile {
return Ok(());
}

const ERR_MESSAGE: &'static str =
const ERR_MESSAGE: &str =
"impl type parameter is used in functions arguments. Arguments should not have a type
depending on a type parameter, unless it is a length bound for BoundedBytes,
BoundedString or alike, which doesn't affect the Solidity type.
Expand All @@ -560,7 +564,7 @@ ensuring the Solidity function signatures are correct.";
| syn::Type::Paren(syn::TypeParen { elem, .. })
| syn::Type::Reference(syn::TypeReference { elem, .. })
| syn::Type::Ptr(syn::TypePtr { elem, .. })
| syn::Type::Slice(syn::TypeSlice { elem, .. }) => self.check_type_parameter_usage(&elem)?,
| syn::Type::Slice(syn::TypeSlice { elem, .. }) => self.check_type_parameter_usage(elem)?,

syn::Type::Path(syn::TypePath {
path: syn::Path { segments, .. },
Expand Down Expand Up @@ -589,7 +593,7 @@ ensuring the Solidity function signatures are correct.";
});

for ty in types {
self.check_type_parameter_usage(&ty)?;
self.check_type_parameter_usage(ty)?;
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions utils/precompiles/macro/src/precompile_name_from_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ pub fn main(_: TokenStream, input: TokenStream) -> TokenStream {
})
.into()
} else {
return quote_spanned! {
quote_spanned! {
ty.span() => compile_error!("Expected tuple");
}
.into();
.into()
}
}

Expand Down Expand Up @@ -112,7 +112,7 @@ fn extract_precompile_name_and_prefix_for_precompile_at(
if let Ok(precompile_id) = int.base10_parse() {
if &path_segment_2.ident.to_string() == "CollectivePrecompile" {
if let Some(instance_ident) =
precompile_instance_ident(&path_segment_2)
precompile_instance_ident(path_segment_2)
{
return Some((instance_ident, precompile_id));
}
Expand Down
12 changes: 0 additions & 12 deletions utils/precompiles/src/evm/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,37 +27,30 @@ use fp_evm::{Log, PrecompileHandle};
pub trait PrecompileHandleExt: PrecompileHandle {
/// Record cost of one DB read manually.
/// The max encoded lenght of the data that will be read should be provided.
#[must_use]
fn record_db_read<Runtime: pallet_evm::Config>(
&mut self,
data_max_encoded_len: usize,
) -> Result<(), evm::ExitError>;

/// Record cost of a log manually.
/// This can be useful to record log costs early when their content have static size.
#[must_use]
fn record_log_costs_manual(&mut self, topics: usize, data_len: usize) -> EvmResult;

/// Record cost of logs.
#[must_use]
fn record_log_costs(&mut self, logs: &[&Log]) -> EvmResult;

#[must_use]
/// Check that a function call is compatible with the context it is
/// called into.
fn check_function_modifier(&self, modifier: FunctionModifier) -> MayRevert;

#[must_use]
/// Read the selector from the input data.
fn read_u32_selector(&self) -> MayRevert<u32>;

#[must_use]
/// Returns a reader of the input, skipping the selector.
fn read_after_selector(&self) -> MayRevert<Reader>;
}

impl<T: PrecompileHandle> PrecompileHandleExt for T {
#[must_use]
fn record_db_read<Runtime: pallet_evm::Config>(
&mut self,
data_max_encoded_len: usize,
Expand All @@ -69,15 +62,13 @@ impl<T: PrecompileHandle> PrecompileHandleExt for T {

/// Record cost of a log manualy.
/// This can be useful to record log costs early when their content have static size.
#[must_use]
fn record_log_costs_manual(&mut self, topics: usize, data_len: usize) -> EvmResult {
self.record_cost(crate::evm::costs::log_costs(topics, data_len)?)?;

Ok(())
}

/// Record cost of logs.
#[must_use]
fn record_log_costs(&mut self, logs: &[&Log]) -> EvmResult {
for log in logs {
self.record_log_costs_manual(log.topics.len(), log.data.len())?;
Expand All @@ -86,7 +77,6 @@ impl<T: PrecompileHandle> PrecompileHandleExt for T {
Ok(())
}

#[must_use]
/// Check that a function call is compatible with the context it is
/// called into.
fn check_function_modifier(&self, modifier: FunctionModifier) -> MayRevert {
Expand All @@ -97,14 +87,12 @@ impl<T: PrecompileHandle> PrecompileHandleExt for T {
)
}

#[must_use]
/// Read the selector from the input data as u32.
fn read_u32_selector(&self) -> MayRevert<u32> {
crate::solidity::codec::selector(self.input())
.ok_or(RevertReason::read_out_of_bounds("selector").into())
}

#[must_use]
/// Returns a reader of the input, skipping the selector.
fn read_after_selector(&self) -> MayRevert<Reader> {
Reader::new_skip_selector(self.input())
Expand Down
69 changes: 33 additions & 36 deletions utils/precompiles/src/precompile_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,18 +108,18 @@ pub enum DiscriminantResult<T> {
OutOfGas,
}

impl<T> Into<IsPrecompileResult> for DiscriminantResult<T> {
fn into(self) -> IsPrecompileResult {
match self {
Self::Some(_, extra_cost) => IsPrecompileResult::Answer {
impl<T> From<DiscriminantResult<T>> for IsPrecompileResult {
fn from(val: DiscriminantResult<T>) -> Self {
match val {
DiscriminantResult::<T>::Some(_, extra_cost) => IsPrecompileResult::Answer {
is_precompile: true,
extra_cost,
},
Self::None(extra_cost) => IsPrecompileResult::Answer {
DiscriminantResult::<T>::None(extra_cost) => IsPrecompileResult::Answer {
is_precompile: false,
extra_cost,
},
Self::OutOfGas => IsPrecompileResult::OutOfGas,
DiscriminantResult::<T>::OutOfGas => IsPrecompileResult::OutOfGas,
}
}
}
Expand Down Expand Up @@ -336,7 +336,7 @@ pub fn get_address_type<R: pallet_evm::Config>(
// check code matches dummy code
handle.record_db_read::<R>(code_len as usize)?;
let code = pallet_evm::AccountCodes::<R>::get(address);
if &code == &[0x60, 0x00, 0x60, 0x00, 0xfd] {
if code == [0x60, 0x00, 0x60, 0x00, 0xfd] {
return Ok(AddressType::Precompile);
}

Expand Down Expand Up @@ -377,10 +377,8 @@ fn common_checks<R: pallet_evm::Config, C: PrecompileChecks>(
// Is this selector callable from a smart contract?
let callable_by_smart_contract =
C::callable_by_smart_contract(caller, selector).unwrap_or(false);
if !callable_by_smart_contract {
if !is_address_eoa_or_precompile::<R>(handle, caller)? {
return Err(revert("Function not callable by smart contracts"));
}
if !callable_by_smart_contract && !is_address_eoa_or_precompile::<R>(handle, caller)? {
return Err(revert("Function not callable by smart contracts"));
}

// Is this selector callable from a precompile?
Expand Down Expand Up @@ -567,16 +565,14 @@ where
match self.current_recursion_level.try_borrow_mut() {
Ok(mut recursion_level) => {
if *recursion_level > max_recursion_level {
return Some(Err(
revert("Precompile is called with too high nesting").into()
));
return Some(Err(revert("Precompile is called with too high nesting")));
}

*recursion_level += 1;
}
// We don't hold the borrow and are in single-threaded code, thus we should
// not be able to fail borrowing in nested calls.
Err(_) => return Some(Err(revert("Couldn't check precompile nesting").into())),
Err(_) => return Some(Err(revert("Couldn't check precompile nesting"))),
}
}

Expand All @@ -597,7 +593,7 @@ where
}
// We don't hold the borrow and are in single-threaded code, thus we should
// not be able to fail borrowing in nested calls.
Err(_) => return Some(Err(revert("Couldn't check precompile nesting").into())),
Err(_) => return Some(Err(revert("Couldn't check precompile nesting"))),
}
}

Expand Down Expand Up @@ -921,15 +917,13 @@ impl PrecompileSetFragment for Tuple {
#[inline(always)]
fn is_precompile(&self, address: H160, gas: u64) -> IsPrecompileResult {
for_tuples!(#(
match self.Tuple.is_precompile(address, gas) {
IsPrecompileResult::Answer {
is_precompile: true,
..
} => return IsPrecompileResult::Answer {
is_precompile: true,
extra_cost: 0,
},
_ => {}
if let IsPrecompileResult::Answer {
is_precompile: true,
..
} = self.Tuple.is_precompile(address, gas) { return IsPrecompileResult::Answer {
is_precompile: true,
extra_cost: 0,
}
};
)*);
IsPrecompileResult::Answer {
Expand Down Expand Up @@ -967,16 +961,13 @@ impl IsActivePrecompile for Tuple {
#[inline(always)]
fn is_active_precompile(&self, address: H160, gas: u64) -> IsPrecompileResult {
for_tuples!(#(
match self.Tuple.is_active_precompile(address, gas) {
IsPrecompileResult::Answer {
is_precompile: true,
..
} => return IsPrecompileResult::Answer {
is_precompile: true,
extra_cost: 0,
},
_ => {}
};
if let IsPrecompileResult::Answer {
is_precompile: true,
..
} = self.Tuple.is_active_precompile(address, gas) { return IsPrecompileResult::Answer {
is_precompile: true,
extra_cost: 0,
} };
)*);
IsPrecompileResult::Answer {
is_precompile: false,
Expand Down Expand Up @@ -1076,6 +1067,12 @@ impl<R, P: IsActivePrecompile> IsActivePrecompile for PrecompileSetBuilder<R, P>
}
}

impl<R: pallet_evm::Config, P: PrecompileSetFragment> Default for PrecompileSetBuilder<R, P> {
fn default() -> Self {
Self::new()
}
}

impl<R: pallet_evm::Config, P: PrecompileSetFragment> PrecompileSetBuilder<R, P> {
/// Create a new instance of the PrecompileSet.
pub fn new() -> Self {
Expand All @@ -1091,7 +1088,7 @@ impl<R: pallet_evm::Config, P: PrecompileSetFragment> PrecompileSetBuilder<R, P>
.inner
.used_addresses()
.into_iter()
.map(|x| R::AddressMapping::into_account_id(x))
.map(R::AddressMapping::into_account_id)
}

pub fn summarize_checks(&self) -> Vec<PrecompileCheckSummary> {
Expand Down
Loading

0 comments on commit 2dd3489

Please sign in to comment.