Commit a86d671b authored by Qinxuan Chen's avatar Qinxuan Chen Committed by Hero Bird
Browse files

Fix format and clippy (#211)



* rustfmt

Signed-off-by: default avatarkoushiro <koushiro.cqx@gmail.com>

* Fix clippy

Signed-off-by: default avatarkoushiro <koushiro.cqx@gmail.com>

* Revert builder to new

Signed-off-by: default avatarkoushiro <koushiro.cqx@gmail.com>
parent 59867455
Pipeline #54963 failed with stages
in 21 seconds
......@@ -31,9 +31,9 @@ use syn::{
};
pub fn generate(input: TokenStream2) -> TokenStream2 {
match generate_impl(input.into()) {
Ok(output) => output.into(),
Err(err) => err.to_compile_error().into(),
match generate_impl(input) {
Ok(output) => output,
Err(err) => err.to_compile_error(),
}
}
......@@ -61,7 +61,7 @@ pub fn generate_impl(input: TokenStream2) -> Result<TokenStream2> {
}
};
Ok(wrap(ident, "HAS_LAYOUT", has_layout_impl).into())
Ok(wrap(ident, "HAS_LAYOUT", has_layout_impl))
}
fn generate_fields_layout<'a>(
......
......@@ -35,7 +35,7 @@ pub fn wrap(
trait_name: &'static str,
impl_quote: TokenStream2,
) -> TokenStream2 {
let mut renamed = String::from(format!("_IMPL_{}_FOR_", trait_name));
let mut renamed = format!("_IMPL_{}_FOR_", trait_name);
renamed.push_str(ident.to_string().trim_start_matches("r#"));
let dummy_const = Ident::new(&renamed, Span::call_site());
......
......@@ -356,6 +356,7 @@ impl MessageSpec {
/// Some of the fields are guarded by a type-state pattern to
/// fail at compile-time instead of at run-time. This is useful
/// to better debug code-gen macros.
#[allow(clippy::type_complexity)]
pub struct MessageSpecBuilder<Selector, Mutates, Returns> {
spec: MessageSpec,
marker: PhantomData<fn() -> (Selector, Mutates, Returns)>,
......
// Copyright 2019 Parity Technologies (UK) Ltd.
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
......@@ -52,7 +52,7 @@ fn load_contract_code(path: Option<&PathBuf>) -> Result<Vec<u8>> {
.map_err(|e| format!("Failed to open {}: {}", contract_wasm_path.display(), e))?;
file.read_to_end(&mut data)?;
return Ok(data)
Ok(data)
}
/// Attempt to extract the code hash from the extrinsic result.
......
......@@ -37,7 +37,7 @@ use std::{
/// Initializes a project structure for the `lang` abstraction layer.
fn initialize_for_lang(name: &str, target_dir: Option<&PathBuf>) -> Result<String> {
if name.contains("-") {
if name.contains('-') {
return Err("Contract names cannot contain hyphens".into())
}
......
......@@ -54,5 +54,5 @@ pub fn set_balance<T: EnvTypes>(balance: T::Balance) {
/// Returns an iterator over the uninterpreted bytes of all past emitted events.
pub fn emitted_events<T: EnvTypes>() -> impl Iterator<Item = Vec<u8>> {
ContractEnv::<T>::emitted_events().into_iter()
ContractEnv::<T>::emitted_events()
}
......@@ -59,11 +59,13 @@ impl<'a> From<&'a [u8]> for Selector {
impl Selector {
/// Returns the selector for the given name.
#[allow(clippy::should_implement_trait)]
pub fn from_str(name: &str) -> Self {
From::from(name.as_bytes())
}
/// Returns the underlying bytes of the selector.
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn to_bytes(&self) -> [u8; 4] {
self.bytes
}
......
......@@ -48,6 +48,11 @@ impl AccountsDb {
self.accounts.len()
}
/// Returns `true` if the number of accounts in the database is 0.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Inserts a new account to the data base.
pub fn insert(&mut self, account_id: AccountId, account: Account) {
self.accounts.insert(account_id, account);
......@@ -107,7 +112,7 @@ impl Account {
if let AccountKind::User(user_account) = &self.kind {
return Some(user_account)
}
return None
None
}
/// Returns the user account if `self` is a user account and otherwise return `None`.
......@@ -115,7 +120,7 @@ impl Account {
if let AccountKind::User(user_account) = &mut self.kind {
return Some(user_account)
}
return None
None
}
/// Returns `true` if `self` is a contract account.
......@@ -131,7 +136,7 @@ impl Account {
if let AccountKind::Contract(contract_account) = &self.kind {
return Some(contract_account)
}
return None
None
}
/// Returns the user account if `self` is a user account and otherwise return `None`.
......@@ -139,7 +144,7 @@ impl Account {
if let AccountKind::Contract(contract_account) = &mut self.kind {
return Some(contract_account)
}
return None
None
}
}
......
......@@ -113,7 +113,7 @@ pub struct CallContractRecord {
impl CallContractRecord {
/// Creates a new record for a contract call.
pub fn new<'a, E, C>(call_params: &'a C) -> Self
pub fn new<E, C>(call_params: &C) -> Self
where
E: EnvTypes,
C: CallParams<E>,
......@@ -142,7 +142,7 @@ pub struct CreateContractRecord {
impl CreateContractRecord {
/// Creates a new record for a contract instantiation.
pub fn new<'a, E, C>(create_params: &'a C) -> Self
pub fn new<E, C>(create_params: &C) -> Self
where
E: EnvTypes,
C: CreateParams<E>,
......@@ -167,7 +167,7 @@ pub struct EmitEventRecord {
impl EmitEventRecord {
/// Creates a new record for a contract instantiation.
pub fn new<'a, E, R>(emit_event: &'a R) -> Self
pub fn new<E, R>(emit_event: &R) -> Self
where
E: EnvTypes,
R: EmitEventParams<E>,
......
......@@ -90,7 +90,7 @@ impl<M> Clone for TypedEncoded<M> {
fn clone(&self) -> Self {
Self {
encoded: self.encoded.clone(),
type_id: self.type_id.clone(),
type_id: self.type_id,
marker: Default::default(),
}
}
......@@ -218,10 +218,7 @@ impl<M> TypedEncoded<M> {
/// # Errors
///
/// If the types of the current and new value do not match.
pub fn try_assign<'a, 'b, T>(
&'a mut self,
new_value: &'b T,
) -> Result<(), UnmatchingType>
pub fn try_assign<T>(&mut self, new_value: &T) -> Result<(), UnmatchingType>
where
T: scale::Encode + 'static,
{
......@@ -238,7 +235,7 @@ impl<M> TypedEncoded<M> {
/// # Panics
///
/// If the types of the current and new value do not match.
pub fn assign<'a, 'b, T>(&'a mut self, new_value: &'b T)
pub fn assign<T>(&mut self, new_value: &T)
where
T: scale::Encode + 'static,
{
......
......@@ -39,7 +39,7 @@ pub struct BumpAlloc {
impl BumpAlloc {
/// Creates a new forward allocator for the given raw parts.
///
/// # Note
/// # Safety
///
/// Do not use this directly!
/// This is meant to be used by pDSL internals only.
......
......@@ -286,11 +286,11 @@ where
where
F: FnOnce() -> T,
{
self.within_bounds(n).and_then(|n| {
Some(self.cells.put(n, f()).expect(
self.within_bounds(n).map(|n| {
self.cells.put(n, f()).expect(
"[ink_core::Vec::replace] Error: \
expected success due to access within bounds",
))
)
})
}
......
......@@ -177,7 +177,7 @@ where
V: Flush,
{
fn flush(&mut self) {
for (_key, val) in self {
for val in self.values_mut() {
// We do not need to write back keys since they are immutable.
val.flush();
}
......
......@@ -81,6 +81,7 @@ impl Contract {
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Item {
EnvMeta(ItemEnvMeta),
......@@ -127,14 +128,11 @@ pub struct EventArg {
impl EventArg {
/// Returns `true` if the event argument is indexed.
pub fn is_indexed(&self) -> bool {
self.attrs
.iter()
.find(|attr| {
attr.style == syn::AttrStyle::Outer
&& attr.path.is_ident("indexed")
&& attr.tts.is_empty()
})
.is_some()
self.attrs.iter().any(|attr| {
attr.style == syn::AttrStyle::Outer
&& attr.path.is_ident("indexed")
&& attr.tts.is_empty()
})
}
}
......@@ -320,6 +318,7 @@ impl FnDecl {
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum FnArg {
SelfRef(syn::ArgSelfRef),
......
......@@ -33,7 +33,7 @@ pub fn generate(input: TokenStream2) -> TokenStream2 {
}
pub fn generate_or_err(input: TokenStream2) -> Result<TokenStream2> {
let ast_contract = parser::parse_contract(input.clone())?;
let ast_contract = parser::parse_contract(input)?;
let hir_contract = hir::Contract::from_ast(&ast_contract)?;
#[cfg(feature = "ink-generate-abi")]
old_abi::generate_old_abi(&hir_contract)?;
......
......@@ -41,9 +41,9 @@ fn trim_doc_string(attr: &syn::Attribute) -> String {
.to_string()
.trim_start_matches('=')
.trim_start()
.trim_start_matches("r")
.trim_start_matches("\"")
.trim_end_matches("\"")
.trim_start_matches('r')
.trim_start_matches('\"')
.trim_end_matches('\"')
.trim()
.into()
}
......@@ -220,7 +220,7 @@ fn generate_type_spec_code(ty: &syn::Type) -> TokenStream2 {
return without_display_name(ty)
}
let path = &type_path.path;
if path.segments.len() == 0 {
if path.segments.is_empty() {
return without_display_name(ty)
}
let segs = path
......
......@@ -90,7 +90,6 @@ impl Contract {
Span::call_site(),
format!("unknown env attribute '{}'", meta.ident),
))
.into()
}
})
.collect::<Result<Vec<_>>>()?;
......@@ -98,8 +97,7 @@ impl Contract {
return Err(syn::Error::new(
Span::call_site(),
"couldn't find an `#![env = <EnvTypesImpl>]` attribute",
)
.into())
))
}
if env_types.len() > 1 {
return Err(syn::Error::new(
......@@ -108,8 +106,7 @@ impl Contract {
"requires exactly one `#![env = <EnvTypesImpl>]` attribute; found {:?}",
env_types.len()
),
)
.into())
))
}
Ok(env_types[0].clone())
}
......
......@@ -791,7 +791,7 @@ mod tests {
r#"{"Result<T,E>":{"T":["bool","i32"],"E":{"[T;n]":{"T":"u8","n":8}}}}"#,
);
assert_json_roundtrip(
parse_quote!(Result<Result<u8,i8>,Result<u16,i16>>),
parse_quote!(Result<Result<u8, i8>, Result<u16, i16>>),
r#"{"Result<T,E>":{"T":{"Result<T,E>":{"T":"u8","E":"i8"}},"E":{"Result<T,E>":{"T":"u16","E":"i16"}}}}"#,
);
}
......
......@@ -60,7 +60,7 @@ impl ast::Item {
impl Parse for ast::Item {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let inner_attrs: ast::ItemEnvMeta = input.parse()?;
if inner_attrs.env_types_metas.len() > 0 {
if !inner_attrs.env_types_metas.is_empty() {
return Ok(ast::Item::EnvMeta(inner_attrs))
}
let attrs_outer = syn::Attribute::parse_outer(input)?;
......
......@@ -205,6 +205,7 @@ where
/// # Note
///
/// Read-only message handlers do not mutate contract state.
#[allow(clippy::type_complexity)]
pub const fn on_msg<Msg>(
self,
handler: RawMessageHandler<Msg, State, Env>,
......@@ -227,6 +228,7 @@ where
/// # Note
///
/// Mutable message handlers may mutate contract state.
#[allow(clippy::type_complexity)]
pub const fn on_msg_mut<Msg>(
self,
handler: RawMessageHandlerMut<Msg, State, Env>,
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment