Skip to content

Commit

Permalink
Feat: add basic clippy (#246)
Browse files Browse the repository at this point in the history
* Fix no-std dependencies to fix #243

* Add basic clippy level

* Extend clippy - #245

* Extend clippy

* Changed  use to alloca #243

* Remove lifetime

* Simplify  for code consistency. Extend CI

* Partly remove lifetime

* Remove resolver-lifetime, and remove CI repeat-checkout

* Restore CI checkout for tests
  • Loading branch information
mrLSD authored Nov 30, 2023
1 parent c0f4a1d commit 53d082f
Show file tree
Hide file tree
Showing 22 changed files with 147 additions and 125 deletions.
18 changes: 14 additions & 4 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,32 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Rustfmt
run: cargo fmt --all -- --check
- name: clippy
run: cargo clippy --workspace -- -D warnings
- name: clippy no-std
run: cargo clippy --workspace --no-default-features --all-targets -- -D warnings
- name: clippy with features
run: cargo clippy --workspace --all-features --all-targets -- -D warnings
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Build
run: cargo build --verbose
- name: Build no-std
run: cargo build --no-default-features
- name: Build all-features
run: cargo build --all-features
- name: Run tests
run: cargo test --verbose
jsontests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- uses: actions/checkout@v4
with:
path: jsontests/res/ethtests
repository: ethereum/tests
Expand Down
10 changes: 6 additions & 4 deletions interpreter/src/call_create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
Context, ExitError, ExitException, ExitResult, Machine, Memory, Opcode, RuntimeBackend,
RuntimeState, Transfer,
};
use alloc::vec::Vec;
use core::cmp::{max, min};
use primitive_types::{H160, H256, U256};
use sha3::{Digest, Keccak256};
Expand All @@ -31,7 +32,7 @@ pub enum CreateScheme {
impl CreateScheme {
pub fn address<H: RuntimeBackend>(&self, handler: &H) -> H160 {
match self {
CreateScheme::Create2 {
Self::Create2 {
caller,
code_hash,
salt,
Expand All @@ -43,7 +44,7 @@ impl CreateScheme {
hasher.update(&code_hash[..]);
H256::from_slice(hasher.finalize().as_slice()).into()
}
CreateScheme::Legacy { caller } => {
Self::Legacy { caller } => {
let nonce = handler.nonce(*caller);
let mut stream = rlp::RlpStream::new_list(2);
stream.append(caller);
Expand All @@ -53,7 +54,7 @@ impl CreateScheme {
}
}

pub fn caller(&self) -> H160 {
pub const fn caller(&self) -> H160 {
match self {
Self::Create2 { caller, .. } => *caller,
Self::Legacy { caller } => *caller,
Expand Down Expand Up @@ -83,7 +84,7 @@ pub enum CallCreateTrapData {
}

impl CallCreateTrapData {
pub fn target_gas(&self) -> Option<U256> {
pub const fn target_gas(&self) -> Option<U256> {
match self {
Self::Call(CallTrapData { gas, .. }) => Some(*gas),
Self::Create(_) => None,
Expand Down Expand Up @@ -137,6 +138,7 @@ pub struct CallTrapData {
}

impl CallTrapData {
#[allow(clippy::too_many_arguments)]
fn new_from_params<S: AsRef<RuntimeState> + AsMut<RuntimeState>>(
scheme: CallScheme,
memory: &mut Memory,
Expand Down
4 changes: 2 additions & 2 deletions interpreter/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ impl From<ExitException> for ExitResult {

impl From<ExitException> for ExitError {
fn from(s: ExitException) -> Self {
ExitError::Exception(s)
Self::Exception(s)
}
}

Expand Down Expand Up @@ -203,6 +203,6 @@ impl From<ExitFatal> for ExitResult {

impl From<ExitFatal> for ExitError {
fn from(s: ExitFatal) -> Self {
ExitError::Fatal(s)
Self::Fatal(s)
}
}
6 changes: 3 additions & 3 deletions interpreter/src/eval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ where
self.0.map(|f| {
let fr = wrapper(f, current_opcode);
if current_opcode != Opcode(255) {
current_opcode.0 = current_opcode.0 + 1;
current_opcode.0 += 1;
}
fr
}),
Expand All @@ -62,7 +62,7 @@ where

impl<S, H, Tr> Etable<S, H, Tr> {
/// Default core value for Etable.
pub const fn core() -> Etable<S, H, Tr> {
pub const fn core() -> Self {
let mut table = [eval_unknown as _; 256];

table[Opcode::STOP.as_usize()] = eval_stop as _;
Expand Down Expand Up @@ -186,7 +186,7 @@ impl<S: AsRef<RuntimeState>, H: RuntimeEnvironment + RuntimeBackend, Tr: CallCre
Etable<S, H, Tr>
{
/// Runtime Etable.
pub const fn runtime() -> Etable<S, H, Tr> {
pub const fn runtime() -> Self {
let mut table = Self::core();

table.0[Opcode::SHA3.as_usize()] = eval_sha3 as _;
Expand Down
2 changes: 1 addition & 1 deletion interpreter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub struct Machine<S> {

impl<S> Machine<S> {
/// Return a reference of the program counter.
pub fn position(&self) -> usize {
pub const fn position(&self) -> usize {
self.position
}

Expand Down
14 changes: 6 additions & 8 deletions interpreter/src/memory.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{ExitException, ExitFatal};
use alloc::vec;
use alloc::vec::Vec;
use core::ops::{BitAnd, Not, Range};
use core::{cmp::min, mem};
Expand All @@ -24,7 +25,7 @@ impl Memory {
}

/// Memory limit.
pub fn limit(&self) -> usize {
pub const fn limit(&self) -> usize {
self.limit
}

Expand All @@ -34,7 +35,7 @@ impl Memory {
}

/// Get the effective length.
pub fn effective_len(&self) -> U256 {
pub const fn effective_len(&self) -> U256 {
self.effective_len
}

Expand All @@ -44,7 +45,7 @@ impl Memory {
}

/// Return the full memory.
pub fn data(&self) -> &Vec<u8> {
pub const fn data(&self) -> &Vec<u8> {
&self.data
}

Expand Down Expand Up @@ -82,9 +83,7 @@ impl Memory {
/// Resize to range. Used for return value.
pub fn resize_to_range(&mut self, return_range: Range<U256>) {
let ret = if return_range.start > U256::from(usize::MAX) {
let mut ret = Vec::new();
ret.resize((return_range.end - return_range.start).as_usize(), 0);
ret
vec![0; (return_range.end - return_range.start).as_usize()]
} else if return_range.end > U256::from(usize::MAX) {
let mut ret = self.get(
return_range.start.as_usize(),
Expand All @@ -111,8 +110,7 @@ impl Memory {
/// Value of `size` is considered trusted. If they're too large,
/// the program can run out of memory, or it can overflow.
pub fn get(&self, offset: usize, size: usize) -> Vec<u8> {
let mut ret = Vec::new();
ret.resize(size, 0);
let mut ret = vec![0; size];

#[allow(clippy::needless_range_loop)]
for index in 0..size {
Expand Down
5 changes: 3 additions & 2 deletions interpreter/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{ExitError, Opcode};
use alloc::rc::Rc;
use alloc::vec::Vec;
use primitive_types::{H160, H256, U256};
use sha3::{Digest, Keccak256};

Expand All @@ -15,13 +16,13 @@ pub struct RuntimeState {
pub gas: U256,
}

impl AsRef<RuntimeState> for RuntimeState {
impl AsRef<Self> for RuntimeState {
fn as_ref(&self) -> &Self {
self
}
}

impl AsMut<RuntimeState> for RuntimeState {
impl AsMut<Self> for RuntimeState {
fn as_mut(&mut self) -> &mut Self {
self
}
Expand Down
6 changes: 3 additions & 3 deletions interpreter/src/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ macro_rules! impl_perform_popn_pushn {

impl Stack {
/// Create a new stack with given limit.
pub fn new(limit: usize) -> Self {
pub const fn new(limit: usize) -> Self {
Self {
data: Vec::new(),
limit,
Expand All @@ -57,7 +57,7 @@ impl Stack {

#[inline]
/// Stack limit.
pub fn limit(&self) -> usize {
pub const fn limit(&self) -> usize {
self.limit
}

Expand All @@ -75,7 +75,7 @@ impl Stack {

#[inline]
/// Stack data.
pub fn data(&self) -> &Vec<H256> {
pub const fn data(&self) -> &Vec<H256> {
&self.data
}

Expand Down
2 changes: 1 addition & 1 deletion interpreter/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub struct I256(pub Sign, pub U256);

impl I256 {
/// Zero value of I256.
pub fn zero() -> I256 {
pub const fn zero() -> I256 {
I256(Sign::Zero, U256::zero())
}
/// Minimum value of I256.
Expand Down
25 changes: 13 additions & 12 deletions interpreter/tests/usability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const RET1: &str = "000000000000000000000000000000000000000000000000000000000000

#[test]
fn etable_wrap() {
let code = hex::decode(&CODE1).unwrap();
let data = hex::decode(&DATA1).unwrap();
let code = hex::decode(CODE1).unwrap();
let data = hex::decode(DATA1).unwrap();

let wrapped_etable = Etable::<_, _, Opcode>::core().wrap(|f, opcode_t| {
move |machine, handle, opcode, position| {
Expand All @@ -24,14 +24,15 @@ fn etable_wrap() {

let mut vm = Machine::new(Rc::new(code), Rc::new(data), 1024, 10000, ());
let result = vm.run(&mut (), &wrapped_etable);
assert_eq!(result, Capture::Exit(Ok(ExitSucceed::Returned.into())));
assert_eq!(vm.retval, hex::decode(&RET1).unwrap());
assert_eq!(result, Capture::Exit(Ok(ExitSucceed::Returned)));
assert_eq!(vm.retval, hex::decode(RET1).unwrap());
}

#[test]
#[allow(clippy::type_complexity)]
fn etable_wrap2() {
let code = hex::decode(&CODE1).unwrap();
let data = hex::decode(&DATA1).unwrap();
let code = hex::decode(CODE1).unwrap();
let data = hex::decode(DATA1).unwrap();

let wrapped_etable = Etable::core().wrap(
|f, opcode_t| -> Box<dyn Fn(&mut Machine<()>, &mut (), Opcode, usize) -> Control<Opcode>> {
Expand Down Expand Up @@ -87,7 +88,7 @@ impl RuntimeEnvironment for UnimplementedHandler {
}
}

impl<'a> RuntimeBaseBackend for UnimplementedHandler {
impl RuntimeBaseBackend for UnimplementedHandler {
fn balance(&self, _address: H160) -> U256 {
unimplemented!()
}
Expand All @@ -113,7 +114,7 @@ impl<'a> RuntimeBaseBackend for UnimplementedHandler {
}
}

impl<'a> RuntimeBackend for UnimplementedHandler {
impl RuntimeBackend for UnimplementedHandler {
fn original_storage(&self, _address: H160, _index: H256) -> H256 {
unimplemented!()
}
Expand Down Expand Up @@ -167,8 +168,8 @@ static RUNTIME_ETABLE: Etable<RuntimeState, UnimplementedHandler, Opcode> = Etab

#[test]
fn etable_runtime() {
let code = hex::decode(&CODE1).unwrap();
let data = hex::decode(&DATA1).unwrap();
let code = hex::decode(CODE1).unwrap();
let data = hex::decode(DATA1).unwrap();
let mut handler = UnimplementedHandler;

let mut vm = Machine::new(
Expand All @@ -193,6 +194,6 @@ fn etable_runtime() {
);

let res = vm.run(&mut handler, &RUNTIME_ETABLE).exit().unwrap();
assert_eq!(res, Ok(ExitSucceed::Returned.into()));
assert_eq!(vm.retval, hex::decode(&RET1).unwrap());
assert_eq!(res, Ok(ExitSucceed::Returned));
assert_eq!(vm.retval, hex::decode(RET1).unwrap());
}
1 change: 1 addition & 0 deletions jsontests/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(clippy::upper_case_acronyms)]
use thiserror::Error;

#[derive(Error, Debug)]
Expand Down
8 changes: 4 additions & 4 deletions jsontests/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn run_file(filename: &str, debug: bool) -> Result<(), Error> {
}
}
if debug {
println!("");
println!();
}
}
}
Expand All @@ -57,14 +57,14 @@ fn run_file(filename: &str, debug: bool) -> Result<(), Error> {
}

fn run_single(filename: &str, debug: bool) -> Result<(), Error> {
if fs::metadata(&filename)?.is_dir() {
for filename in fs::read_dir(&filename)? {
if fs::metadata(filename)?.is_dir() {
for filename in fs::read_dir(filename)? {
let filepath = filename?.path();
let filename = filepath.to_str().ok_or(Error::NonUtf8Filename)?;
run_file(filename, debug)?;
}
} else {
run_file(&filename, debug)?;
run_file(filename, debug)?;
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion jsontests/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl TestMulti {
tests.push(Test {
info: self.info.clone(),
env: self.env.clone(),
fork: fork.clone(),
fork: *fork,
index,
post: post_state.clone(),
pre: self.pre.clone(),
Expand Down
1 change: 1 addition & 0 deletions precompile/src/modexp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ impl<G: StaticGasometer> PurePrecompile<G> for Modexp {

// always true except in the case of zero-length modulus, which leads to
// output of length and value 1.
#[allow(clippy::comparison_chain)]
if bytes.len() == mod_len {
(ExitSucceed::Returned.into(), bytes.to_vec())
} else if bytes.len() < mod_len {
Expand Down
4 changes: 2 additions & 2 deletions precompile/src/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl<G: StaticGasometer> PurePrecompile<G> for Sha256 {
)))));

let mut ret = [0u8; 32];
let hash = ripemd::Ripemd160::digest(&input[..]);
let hash = ripemd::Ripemd160::digest(input);
ret[12..32].copy_from_slice(&hash);

(ExitSucceed::Returned.into(), ret.to_vec())
Expand All @@ -89,7 +89,7 @@ impl<G: StaticGasometer> PurePrecompile<G> for Ripemd160 {
COST_WORD
)))));

let hash = sha2::Sha256::digest(&input[..]);
let hash = sha2::Sha256::digest(input);

(ExitSucceed::Returned.into(), hash.to_vec())
}
Expand Down
Loading

0 comments on commit 53d082f

Please sign in to comment.