Browse Source

Improvements according to rust 1.51 clippy warnings

Signed-off-by: Sean Young <sean@mess.org>
Sean Young 4 years ago
parent
commit
c194daa4d1

+ 2 - 0
src/abi/ethereum.rs

@@ -4,6 +4,7 @@ use crate::sema::ast::{Namespace, Parameter, Type};
 use serde::Serialize;
 
 #[derive(Serialize)]
+#[allow(clippy::upper_case_acronyms)]
 pub struct ABIParam {
     pub name: String,
     #[serde(rename = "type")]
@@ -17,6 +18,7 @@ pub struct ABIParam {
 }
 
 #[derive(Serialize)]
+#[allow(clippy::upper_case_acronyms)]
 pub struct ABI {
     #[serde(skip_serializing_if = "String::is_empty")]
     pub name: String,

+ 1 - 1
src/emit/mod.rs

@@ -3035,7 +3035,7 @@ pub trait TargetRuntime<'a> {
             }
 
             BasicBlock { bb, phis }
-        };
+        }
 
         let mut work = VecDeque::new();
 

+ 1 - 1
src/emit/substrate.rs

@@ -4014,7 +4014,7 @@ impl<'a> TargetRuntime<'a> for SubstrateTarget {
                     $name,
                 )
             }};
-        };
+        }
 
         match expr {
             ast::Expression::Builtin(_, _, ast::Builtin::Calldata, _) => {

+ 4 - 4
src/file_cache.rs

@@ -1,7 +1,7 @@
 use std::collections::HashMap;
 use std::fs::File;
 use std::io::prelude::*;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
 use std::sync::Arc;
 
 pub struct FileCache {
@@ -61,14 +61,14 @@ impl FileCache {
 
     /// Get file with contents. This must be a file which was previously
     /// add to the cache
-    pub fn get_file_contents(&mut self, file: &PathBuf) -> Arc<str> {
+    pub fn get_file_contents(&mut self, file: &Path) -> Arc<str> {
         let file_no = self.cached_paths[file];
 
         self.files[file_no].clone()
     }
 
     /// Populate the cache with absolute file path
-    fn load_file(&mut self, path: &PathBuf) -> Result<usize, String> {
+    fn load_file(&mut self, path: &Path) -> Result<usize, String> {
         if let Some(file_no) = self.cached_paths.get(path) {
             return Ok(*file_no);
         }
@@ -98,7 +98,7 @@ impl FileCache {
 
         self.files.push(Arc::from(contents));
 
-        self.cached_paths.insert(path.clone(), pos);
+        self.cached_paths.insert(path.to_path_buf(), pos);
 
         Ok(pos)
     }

+ 8 - 13
src/linker/bpf.rs

@@ -57,31 +57,26 @@ SECTIONS
         )
         .expect("failed to write linker script to temp file");
 
-    let mut command_line = Vec::new();
-
-    command_line.push(CString::new("-z").unwrap());
-    command_line.push(CString::new("notext").unwrap());
-    command_line.push(CString::new("-shared").unwrap());
-    command_line.push(CString::new("--Bdynamic").unwrap());
-    command_line.push(
+    let command_line = vec![
+        CString::new("-z").unwrap(),
+        CString::new("notext").unwrap(),
+        CString::new("-shared").unwrap(),
+        CString::new("--Bdynamic").unwrap(),
         CString::new(
             linker_script_filename
                 .to_str()
                 .expect("temp path should be unicode"),
         )
         .unwrap(),
-    );
-    command_line.push(
         CString::new(
             object_filename
                 .to_str()
                 .expect("temp path should be unicode"),
         )
         .unwrap(),
-    );
-    command_line.push(CString::new("-o").unwrap());
-    command_line
-        .push(CString::new(res_filename.to_str().expect("temp path should be unicode")).unwrap());
+        CString::new("-o").unwrap(),
+        CString::new(res_filename.to_str().expect("temp path should be unicode")).unwrap(),
+    ];
 
     if super::elf_linker(&command_line) {
         panic!("linker failed");

+ 7 - 7
src/linker/wasm.rs

@@ -25,13 +25,13 @@ pub fn link(input: &[u8], name: &str, target: Target) -> Vec<u8> {
         .write_all(input)
         .expect("failed to write object file to temp file");
 
-    let mut command_line = Vec::new();
-
-    command_line.push(CString::new("-O3").unwrap());
-    command_line.push(CString::new("--no-entry").unwrap());
-    command_line.push(CString::new("--allow-undefined").unwrap());
-    command_line.push(CString::new("--gc-sections").unwrap());
-    command_line.push(CString::new("--global-base=0").unwrap());
+    let mut command_line = vec![
+        CString::new("-O3").unwrap(),
+        CString::new("--no-entry").unwrap(),
+        CString::new("--allow-undefined").unwrap(),
+        CString::new("--gc-sections").unwrap(),
+        CString::new("--global-base=0").unwrap(),
+    ];
 
     match target {
         Target::Ewasm => {

+ 2 - 4
src/parser/mod.rs

@@ -15,10 +15,8 @@ pub fn parse(src: &str, file_no: usize) -> Result<pt::SourceUnit, Vec<Diagnostic
 
     let s = solidity::SourceUnitParser::new().parse(src, file_no, lex);
 
-    let mut errors = Vec::new();
-
     if let Err(e) = s {
-        errors.push(match e {
+        let errors = vec![match e {
             ParseError::InvalidToken { location } => Diagnostic::parser_error(
                 pt::Loc(file_no, location, location),
                 "invalid token".to_string(),
@@ -45,7 +43,7 @@ pub fn parse(src: &str, file_no: usize) -> Result<pt::SourceUnit, Vec<Diagnostic
                 pt::Loc(file_no, location, location),
                 format!("unexpected end of file, expecting {}", expected.join(", ")),
             ),
-        });
+        }];
 
         Err(errors)
     } else {

+ 2 - 1
src/sema/mod.rs

@@ -1268,6 +1268,7 @@ impl ast::Namespace {
     // An array type can look like foo[2] foo.baz.bar, if foo is an enum type. The lalrpop parses
     // this as an expression, so we need to convert it to Type and check there are
     // no unexpected expressions types.
+    #[allow(clippy::vec_init_then_push)]
     pub fn expr_to_type<'a>(
         &mut self,
         file_no: usize,
@@ -1276,7 +1277,7 @@ impl ast::Namespace {
         diagnostics: &mut Vec<ast::Diagnostic>,
     ) -> Result<(Vec<&'a pt::Identifier>, pt::Expression, Vec<ArrayDimension>), ()> {
         let mut expr = expr;
-        let mut dimensions = Vec::new();
+        let mut dimensions = vec![];
 
         loop {
             expr = match expr {

+ 3 - 7
src/sema/printer.rs

@@ -432,12 +432,10 @@ fn print_statement(stmts: &[Statement], func: &Function, ns: &Namespace) -> Vec<
                 catch_stmt,
                 ..
             } => {
-                let mut list = Vec::new();
-
-                list.push(Tree::Branch(
+                let mut list = vec![Tree::Branch(
                     String::from("expr"),
                     vec![print_expr(expr, Some(func), ns)],
-                ));
+                )];
 
                 if !returns.is_empty() {
                     let returns = returns
@@ -626,9 +624,7 @@ impl Namespace {
 }
 
 fn print_func(func: &Function, ns: &Namespace) -> Tree {
-    let mut list = Vec::new();
-
-    list.push(Tree::Leaf(format!("visibility {}", func.visibility)));
+    let mut list = vec![Tree::Leaf(format!("visibility {}", func.visibility))];
 
     if func.ty == pt::FunctionTy::Constructor && func.ty == pt::FunctionTy::Function {
         list.push(Tree::Leaf(format!("signature {}", func.signature)));

+ 1 - 1
src/sema/types.rs

@@ -135,7 +135,7 @@ pub fn resolve_fields(delay: ResolveFields, file_no: usize, ns: &mut Namespace)
                     }
                 }
             }
-        };
+        }
 
         check(s, file_no, &mut vec![s], ns);
     }

+ 10 - 10
tests/ewasm.rs

@@ -28,7 +28,7 @@ fn address_new() -> Address {
     a
 }
 
-struct VM {
+struct VirtualMachine {
     memory: MemoryRef,
     cur: Address,
     code: Vec<u8>,
@@ -37,9 +37,9 @@ struct VM {
     returndata: Vec<u8>,
 }
 
-impl VM {
+impl VirtualMachine {
     fn new(code: Vec<u8>, address: Address) -> Self {
-        VM {
+        VirtualMachine {
             memory: MemoryInstance::alloc(Pages(2), Some(Pages(2))).unwrap(),
             input: Vec::new(),
             output: Vec::new(),
@@ -56,7 +56,7 @@ struct TestRuntime {
     value: u128,
     accounts: HashMap<Address, (Vec<u8>, u128)>,
     store: HashMap<(Address, [u8; 32]), [u8; 32]>,
-    vm: VM,
+    vm: VirtualMachine,
     events: Vec<Event>,
 }
 
@@ -303,7 +303,7 @@ impl Externals for TestRuntime {
                     .unwrap()
                     .clone();
 
-                let mut vm = VM::new(buf, addr);
+                let mut vm = VirtualMachine::new(buf, addr);
 
                 std::mem::swap(&mut self.vm, &mut vm);
 
@@ -401,7 +401,7 @@ impl Externals for TestRuntime {
                 // wasm validator will trip
                 let (code, _) = self.accounts.get(&addr).unwrap().clone();
 
-                let mut vm = VM::new(code.to_vec(), addr);
+                let mut vm = VirtualMachine::new(code.to_vec(), addr);
 
                 std::mem::swap(&mut self.vm, &mut vm);
 
@@ -611,7 +611,7 @@ impl TestRuntime {
     fn function(&mut self, name: &str, args: &[Token]) -> Vec<Token> {
         let calldata = match self.abi.functions[name][0].encode_input(args) {
             Ok(n) => n,
-            Err(x) => panic!(format!("{}", x)),
+            Err(x) => panic!("{}", x),
         };
 
         let module = self.create_module(&self.accounts[&self.vm.cur].0);
@@ -646,7 +646,7 @@ impl TestRuntime {
     fn function_abi_fail(&mut self, name: &str, args: &[Token], patch: fn(&mut Vec<u8>)) {
         let mut calldata = match self.abi.functions[name][0].encode_input(args) {
             Ok(n) => n,
-            Err(x) => panic!(format!("{}", x)),
+            Err(x) => panic!("{}", x),
         };
 
         patch(&mut calldata);
@@ -677,7 +677,7 @@ impl TestRuntime {
     fn function_revert(&mut self, name: &str, args: &[Token]) -> Option<String> {
         let calldata = match self.abi.functions[name][0].encode_input(args) {
             Ok(n) => n,
-            Err(x) => panic!(format!("{}", x)),
+            Err(x) => panic!("{}", x),
         };
 
         let module = self.create_module(&self.accounts[&self.vm.cur].0);
@@ -811,7 +811,7 @@ fn build_solidity(src: &str) -> TestRuntime {
 
     TestRuntime {
         accounts: HashMap::new(),
-        vm: VM::new(bc, [0u8; 20]),
+        vm: VirtualMachine::new(bc, [0u8; 20]),
         value: 0,
         store: HashMap::new(),
         abi: ethabi::Contract::load(abi.as_bytes()).unwrap(),

+ 8 - 8
tests/solana.rs

@@ -3,7 +3,7 @@ mod solana_helpers;
 use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
 use ethabi::Token;
 use libc::c_char;
-use solana_helpers::allocator_bump::BPFAllocator;
+use solana_helpers::allocator_bump::Allocator;
 use solana_rbpf::{
     error::EbpfError,
     memory_region::{AccessType, MemoryMapping, MemoryRegion},
@@ -17,7 +17,7 @@ use std::mem::{align_of, size_of};
 
 mod solana_tests;
 
-fn build_solidity(src: &str) -> VM {
+fn build_solidity(src: &str) -> Program {
     let mut cache = FileCache::new();
 
     cache.set_file_contents("test.sol", src.to_string());
@@ -41,7 +41,7 @@ fn build_solidity(src: &str) -> VM {
     // resolve
     let (code, abi) = res.last().unwrap().clone();
 
-    VM {
+    Program {
         code,
         abi: ethabi::Contract::load(abi.as_bytes()).unwrap(),
         printbuf: String::new(),
@@ -138,7 +138,7 @@ fn deserialize_parameters(input: &[u8]) -> Vec<Vec<u8>> {
     res
 }
 
-struct VM {
+struct Program {
     code: Vec<u8>,
     abi: ethabi::Contract,
     printbuf: String,
@@ -190,7 +190,7 @@ impl<'a> SyscallObject<UserError> for Printer<'a> {
 /// information about that memory (start address and size) is passed
 /// to the VM to use for enforcement.
 pub struct SyscallAllocFree {
-    allocator: BPFAllocator,
+    allocator: Allocator,
 }
 
 const DEFAULT_HEAP_SIZE: usize = 32 * 1024;
@@ -221,7 +221,7 @@ impl SyscallObject<UserError> for SyscallAllocFree {
     }
 }
 
-impl VM {
+impl Program {
     fn execute(&mut self, buf: &mut String, calldata: &[u8]) {
         println!("running bpf with calldata:{}", hex::encode(calldata));
 
@@ -244,7 +244,7 @@ impl VM {
         vm.register_syscall_ex(
             "sol_alloc_free_",
             Syscall::Object(Box::new(SyscallAllocFree {
-                allocator: BPFAllocator::new(heap, MM_HEAP_START),
+                allocator: Allocator::new(heap, MM_HEAP_START),
             })),
         )
         .unwrap();
@@ -282,7 +282,7 @@ impl VM {
     fn function(&mut self, name: &str, args: &[Token]) -> Vec<Token> {
         let calldata = match self.abi.functions[name][0].encode_input(args) {
             Ok(n) => n,
-            Err(x) => panic!(format!("{}", x)),
+            Err(x) => panic!("{}", x),
         };
 
         println!("input: {}", hex::encode(&calldata));

+ 4 - 4
tests/solana_helpers/allocator_bump.rs

@@ -1,17 +1,17 @@
 use std::alloc::Layout;
 
 #[derive(Debug)]
-pub struct BPFAllocator {
+pub struct Allocator {
     heap: Vec<u8>,
     start: u64,
     len: u64,
     pos: u64,
 }
 
-impl BPFAllocator {
+impl Allocator {
     pub fn new(heap: Vec<u8>, virtual_address: u64) -> Self {
         let len = heap.len() as u64;
-        Self {
+        Allocator {
             heap,
             start: virtual_address,
             len,
@@ -20,7 +20,7 @@ impl BPFAllocator {
     }
 }
 
-impl BPFAllocator {
+impl Allocator {
     pub fn alloc(&mut self, layout: Layout) -> u64 {
         let bytes_to_align = (self.pos as *const u8).align_offset(layout.align()) as u64;
         if self

+ 9 - 9
tests/substrate.rs

@@ -88,7 +88,7 @@ pub struct Event {
     data: Vec<u8>,
 }
 
-pub struct VM {
+pub struct VirtualMachine {
     address: Address,
     caller: Address,
     memory: MemoryRef,
@@ -97,9 +97,9 @@ pub struct VM {
     pub value: u128,
 }
 
-impl VM {
+impl VirtualMachine {
     fn new(address: Address, caller: Address, value: u128) -> Self {
-        VM {
+        VirtualMachine {
             memory: MemoryInstance::alloc(Pages(16), Some(Pages(16))).unwrap(),
             input: Vec::new(),
             output: Vec::new(),
@@ -116,7 +116,7 @@ pub struct TestRuntime {
     pub printbuf: String,
     pub accounts: HashMap<Address, (Vec<u8>, u128)>,
     pub abi: abi::substrate::Abi,
-    pub vm: VM,
+    pub vm: VirtualMachine,
     pub events: Vec<Event>,
 }
 
@@ -497,7 +497,7 @@ impl Externals for TestRuntime {
                     hex::encode(&input)
                 );
 
-                let mut vm = VM::new(address, self.vm.address, value);
+                let mut vm = VirtualMachine::new(address, self.vm.address, value);
 
                 std::mem::swap(&mut self.vm, &mut vm);
 
@@ -647,7 +647,7 @@ impl Externals for TestRuntime {
                     panic!("seal_instantiate: {}", e);
                 }
 
-                let mut vm = VM::new(address, self.vm.address, value);
+                let mut vm = VirtualMachine::new(address, self.vm.address, value);
 
                 std::mem::swap(&mut self.vm, &mut vm);
 
@@ -1013,7 +1013,7 @@ impl TestRuntime {
 
         if let Some(RuntimeValue::I32(ret)) = self.invoke_call(module) {
             if ret != 0 {
-                panic!(format!("non zero return: {}", ret));
+                panic!("non zero return: {}", ret);
             }
         }
     }
@@ -1174,7 +1174,7 @@ pub fn build_solidity(src: &'static str) -> TestRuntime {
         printbuf: String::new(),
         store: HashMap::new(),
         contracts: res,
-        vm: VM::new(address, address_new(), 0),
+        vm: VirtualMachine::new(address, address_new(), 0),
         abi: abi::substrate::load(&abistr).unwrap(),
         events: Vec::new(),
     };
@@ -1210,7 +1210,7 @@ pub fn build_solidity_with_overflow_check(src: &'static str) -> TestRuntime {
         printbuf: String::new(),
         store: HashMap::new(),
         contracts: res,
-        vm: VM::new(address, address_new(), 0),
+        vm: VirtualMachine::new(address, address_new(), 0),
         abi: abi::substrate::load(&abistr).unwrap(),
         events: Vec::new(),
     };

+ 12 - 12
tests/substrate_tests/structs.rs

@@ -330,7 +330,7 @@ fn structs_encode() {
     struct Foo {
         f1: [u8; 3],
         f2: bool,
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -363,7 +363,7 @@ fn structs_decode() {
     struct Foo {
         f1: [u8; 3],
         f2: i32,
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -447,7 +447,7 @@ fn structs_decode() {
         f3: String,
         f4: Vec<i64>,
         f5: [bool; 4],
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -534,13 +534,13 @@ fn structs_in_structs_decode() {
     struct Foo {
         f1: [u8; 3],
         f2: i32,
-    };
+    }
     #[derive(Debug, PartialEq, Encode, Decode)]
     struct Bar {
         a: bool,
         b: Foo,
         c: Foo,
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -589,13 +589,13 @@ fn structs_in_structs_encode() {
     struct Foo {
         f1: [u8; 3],
         f2: i32,
-    };
+    }
     #[derive(Debug, PartialEq, Encode, Decode)]
     struct Bar {
         a: bool,
         b: Foo,
         c: Foo,
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -673,7 +673,7 @@ fn return_from_struct_storage() {
     struct Foo {
         f1: [u8; 3],
         f2: u32,
-    };
+    }
 
     let mut runtime = build_solidity(
         r##"
@@ -715,7 +715,7 @@ fn struct_in_init_return() {
     struct Card {
         value: u8,
         suit: u8,
-    };
+    }
 
     #[derive(Debug, PartialEq, Encode, Decode)]
     struct Hand {
@@ -724,7 +724,7 @@ fn struct_in_init_return() {
         card3: Card,
         card4: Card,
         card5: Card,
-    };
+    }
 
     let mut runtime = build_solidity(
         r#"
@@ -767,7 +767,7 @@ fn struct_struct_in_init_and_return() {
     struct Card {
         v: u8,
         s: u8,
-    };
+    }
 
     #[derive(Debug, PartialEq, Encode, Decode)]
     struct Hand {
@@ -776,7 +776,7 @@ fn struct_struct_in_init_and_return() {
         card3: Card,
         card4: Card,
         card5: Card,
-    };
+    }
 
     let mut runtime = build_solidity(
         r#"