From 08f5a0e24376a1a474951af16c127f9e5cf9802d Mon Sep 17 00:00:00 2001 From: Armani Ferrante Date: Tue, 16 Feb 2021 13:52:54 +0800 Subject: [PATCH] Clippy fixes --- cli/src/config.rs | 6 +-- cli/src/main.rs | 27 ++++++------ cli/src/template.rs | 6 +-- client/src/lib.rs | 10 ++--- lang/attribute/access-control/src/lib.rs | 5 +-- lang/attribute/account/src/lib.rs | 2 +- lang/attribute/interface/src/lib.rs | 10 ++--- lang/src/account_info.rs | 4 +- lang/src/cpi_account.rs | 2 +- lang/src/program_account.rs | 4 +- lang/src/state.rs | 2 +- lang/src/sysvar.rs | 2 +- lang/syn/src/codegen/program.rs | 38 ++++++++--------- lang/syn/src/idl.rs | 4 +- lang/syn/src/lib.rs | 9 ++-- lang/syn/src/parser/accounts.rs | 53 ++++++++++-------------- lang/syn/src/parser/file.rs | 42 +++++++------------ lang/syn/src/parser/program.rs | 11 ++--- spl/src/token.rs | 4 +- 19 files changed, 105 insertions(+), 136 deletions(-) diff --git a/cli/src/config.rs b/cli/src/config.rs index 4f6a9814..2936bd9b 100644 --- a/cli/src/config.rs +++ b/cli/src/config.rs @@ -33,13 +33,13 @@ impl Config { let p = f?.path(); if let Some(filename) = p.file_name() { if filename.to_str() == Some("Cargo.toml") { - cargo_toml_level = Some(PathBuf::from(p)); + cargo_toml_level = Some(p); } else if filename.to_str() == Some("Anchor.toml") { let mut cfg_file = File::open(&p)?; let mut cfg_contents = String::new(); cfg_file.read_to_string(&mut cfg_contents)?; let cfg = cfg_contents.parse()?; - anchor_toml = Some((cfg, PathBuf::from(p))); + anchor_toml = Some((cfg, p)); } } } @@ -121,7 +121,7 @@ pub fn extract_lib_name(path: impl AsRef) -> Result { None => Err(anyhow!("lib not found in Cargo.toml")), Some(lib) => match lib .get("name") - .ok_or(anyhow!("lib name not found in Cargo.toml"))? + .ok_or_else(|| anyhow!("lib name not found in Cargo.toml"))? { toml::Value::String(n) => Ok(n.to_string()), _ => Err(anyhow!("lib name must be a string")), diff --git a/cli/src/main.rs b/cli/src/main.rs index 48f97838..506c5bd4 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -670,7 +670,9 @@ fn stream_logs(url: &str) -> Result> { let mut contents = vec![]; file.read_to_end(&mut contents)?; let idl: Idl = serde_json::from_slice(&contents)?; - let metadata = idl.metadata.ok_or(anyhow!("Program address not found."))?; + let metadata = idl + .metadata + .ok_or_else(|| anyhow!("Program address not found."))?; let metadata: IdlTestMetadata = serde_json::from_value(metadata)?; let log_file = File::create(format!( @@ -713,7 +715,7 @@ fn start_test_validator(flags: Option>) -> Result { let validator_handle = std::process::Command::new("solana-test-validator") .arg("--ledger") .arg(test_ledger_filename) - .args(flags.unwrap_or(Vec::new())) + .args(flags.unwrap_or_default()) .stdout(Stdio::from(test_validator_stdout)) .stderr(Stdio::from(test_validator_stderr)) .spawn() @@ -750,8 +752,8 @@ fn _deploy(url: Option, keypair: Option) -> Result, keypair: Option) -> Result<()> { let programs = _deploy(url.clone(), keypair.clone())?; with_workspace(|cfg, _path, _cargo| { - let url = url.unwrap_or(cfg.cluster.url().to_string()); - let keypair = keypair.unwrap_or(cfg.wallet.to_string()); + let url = url.unwrap_or_else(|| cfg.cluster.url().to_string()); + let keypair = keypair.unwrap_or_else(|| cfg.wallet.to_string()); // Add metadata to all IDLs. for (address, program) in programs { @@ -886,7 +888,7 @@ fn with_workspace(f: impl FnOnce(&Config, PathBuf, Option) -> R) -> // The Solana CLI doesn't redeploy a program if this file exists. // So remove it to make all commands explicit. fn clear_program_keys() -> Result<()> { - for program in read_all_programs().expect("Programs dir doesn't exist") { + for program in read_all_programs()? { let anchor_keypair_path = program.anchor_keypair_path(); if Path::exists(&anchor_keypair_path) { std::fs::remove_file(anchor_keypair_path).expect("Always remove"); @@ -966,7 +968,7 @@ fn migrate(url: Option) -> Result<()> { with_workspace(|cfg, _path, _cargo| { println!("Running migration deploy script"); - let url = url.unwrap_or(cfg.cluster.url().to_string()); + let url = url.unwrap_or_else(|| cfg.cluster.url().to_string()); let cur_dir = std::env::current_dir()?; let module_path = format!("{}/migrations/deploy.js", cur_dir.display()); let deploy_script_host_str = template::deploy_script_host(&url, &module_path); @@ -1005,20 +1007,19 @@ fn set_workspace_dir_or_exit() { None => { println!("Unable to make new program"); } - Some(parent) => match std::env::set_current_dir(&parent) { - Err(_) => { + Some(parent) => { + if std::env::set_current_dir(&parent).is_err() { println!("Not in anchor workspace."); std::process::exit(1); } - Ok(_) => {} - }, + } }; } } } fn airdrop(url: Option) -> Result<()> { - let url = url.unwrap_or("https://devnet.solana.com".to_string()); + let url = url.unwrap_or_else(|| "https://devnet.solana.com".to_string()); loop { let exit = std::process::Command::new("solana") .arg("airdrop") diff --git a/cli/src/template.rs b/cli/src/template.rs index bc27e317..1ffbee30 100644 --- a/cli/src/template.rs +++ b/cli/src/template.rs @@ -29,7 +29,7 @@ cpi = ["no-entrypoint"] default = [] [dependencies] -anchor-lang = {{ git = "https://github.com/project-serum/anchor", features = ["derive"] }} +anchor-lang = "0.2.1" "#, name, name.to_snake_case(), @@ -65,7 +65,7 @@ main(); } pub fn deploy_script() -> String { - return r#" + r#" // Migrations are an early feature. Currently, they're nothing more than this // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. @@ -79,7 +79,7 @@ module.exports = async function (provider) { // Add your deploy script here. } "# - .to_string(); + .to_string() } pub fn xargo_toml() -> String { r#"[target.bpfel-unknown-unknown.dependencies.std] diff --git a/client/src/lib.rs b/client/src/lib.rs index 20ee66f0..6dc31e16 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -50,7 +50,7 @@ impl Client { program_id, cfg: Config { cluster: self.cfg.cluster.clone(), - options: self.cfg.options.clone(), + options: self.cfg.options, payer: Keypair::from_bytes(&self.cfg.payer.to_bytes()).unwrap(), }, } @@ -81,7 +81,7 @@ impl Program { self.program_id, &self.cfg.cluster, Keypair::from_bytes(&self.cfg.payer.to_bytes()).unwrap(), - self.cfg.options.clone(), + self.cfg.options, ) } @@ -89,7 +89,7 @@ impl Program { pub fn account(&self, address: Pubkey) -> Result { let rpc_client = RpcClient::new_with_commitment( self.cfg.cluster.clone(), - self.cfg.options.unwrap_or(Default::default()), + self.cfg.options.unwrap_or_default(), ); let account = rpc_client .get_account_with_commitment(&address, CommitmentConfig::recent())? @@ -102,7 +102,7 @@ impl Program { pub fn rpc(&self) -> RpcClient { RpcClient::new_with_commitment( self.cfg.cluster.clone(), - self.cfg.options.unwrap_or(Default::default()), + self.cfg.options.unwrap_or_default(), ) } @@ -147,7 +147,7 @@ impl<'a> RequestBuilder<'a> { payer, cluster: cluster.to_string(), accounts: Vec::new(), - options: options.unwrap_or(Default::default()), + options: options.unwrap_or_default(), instructions: Vec::new(), instruction_data: None, signers: Vec::new(), diff --git a/lang/attribute/access-control/src/lib.rs b/lang/attribute/access-control/src/lib.rs index da2daeed..1f655d5f 100644 --- a/lang/attribute/access-control/src/lib.rs +++ b/lang/attribute/access-control/src/lib.rs @@ -54,10 +54,7 @@ pub fn access_control( args.retain(|c| !c.is_whitespace()); let access_control: Vec = args .split(')') - .filter_map(|ac| match ac { - "" => None, - _ => Some(ac), - }) + .filter(|ac| !ac.is_empty()) .map(|ac| format!("{})", ac)) // Put back on the split char. .map(|ac| format!("{}?;", ac)) // Add `?;` syntax. .map(|ac| ac.parse().unwrap()) diff --git a/lang/attribute/account/src/lib.rs b/lang/attribute/account/src/lib.rs index 99e525c9..906cf651 100644 --- a/lang/attribute/account/src/lib.rs +++ b/lang/attribute/account/src/lib.rs @@ -30,7 +30,7 @@ pub fn account( let discriminator: proc_macro2::TokenStream = { // Namespace the discriminator to prevent collisions. let discriminator_preimage = { - if namespace == "" { + if namespace.is_empty() { format!("account:{}", account_name.to_string()) } else { format!("{}:{}", namespace, account_name.to_string()) diff --git a/lang/attribute/interface/src/lib.rs b/lang/attribute/interface/src/lib.rs index 8fe53b31..3d15d049 100644 --- a/lang/attribute/interface/src/lib.rs +++ b/lang/attribute/interface/src/lib.rs @@ -175,14 +175,10 @@ pub fn interface( // TODO: just map this to None once we allow this feature. _ => panic!("Invalid syntax. No self allowed."), }) - .filter_map(|pat_ty: &syn::PatType| { + .filter(|pat_ty| { let mut ty = parser::tts_to_string(&pat_ty.ty); ty.retain(|s| !s.is_whitespace()); - if ty.starts_with("Context<") { - None - } else { - Some(pat_ty) - } + !ty.starts_with("Context<") }) .collect(); let args_no_tys: Vec<&Box> = args @@ -192,7 +188,7 @@ pub fn interface( }) .collect(); let args_struct = { - if args.len() == 0 { + if args.is_empty() { quote! { use anchor_lang::prelude::borsh; #[derive(anchor_lang::AnchorSerialize, anchor_lang::AnchorDeserialize)] diff --git a/lang/src/account_info.rs b/lang/src/account_info.rs index 5bba8b40..2a4c583d 100644 --- a/lang/src/account_info.rs +++ b/lang/src/account_info.rs @@ -10,7 +10,7 @@ impl<'info> Accounts<'info> for AccountInfo<'info> { _program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; @@ -24,7 +24,7 @@ impl<'info> AccountsInit<'info> for AccountInfo<'info> { _program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } diff --git a/lang/src/cpi_account.rs b/lang/src/cpi_account.rs index 0a2da258..62fe58d6 100644 --- a/lang/src/cpi_account.rs +++ b/lang/src/cpi_account.rs @@ -50,7 +50,7 @@ where _program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; diff --git a/lang/src/program_account.rs b/lang/src/program_account.rs index 56ad5586..ae81b964 100644 --- a/lang/src/program_account.rs +++ b/lang/src/program_account.rs @@ -71,7 +71,7 @@ where program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; @@ -93,7 +93,7 @@ where _program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; diff --git a/lang/src/state.rs b/lang/src/state.rs index 4c12e7c3..6b519b19 100644 --- a/lang/src/state.rs +++ b/lang/src/state.rs @@ -59,7 +59,7 @@ where program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; diff --git a/lang/src/sysvar.rs b/lang/src/sysvar.rs index 8cf9bb50..fd2b2f24 100644 --- a/lang/src/sysvar.rs +++ b/lang/src/sysvar.rs @@ -37,7 +37,7 @@ impl<'info, T: solana_program::sysvar::Sysvar> Accounts<'info> for Sysvar<'info, _program_id: &Pubkey, accounts: &mut &[AccountInfo<'info>], ) -> Result { - if accounts.len() == 0 { + if accounts.is_empty() { return Err(ProgramError::NotEnoughAccountKeys); } let account = &accounts[0]; diff --git a/lang/syn/src/codegen/program.rs b/lang/syn/src/codegen/program.rs index a6cef902..cf50afd4 100644 --- a/lang/syn/src/codegen/program.rs +++ b/lang/syn/src/codegen/program.rs @@ -4,11 +4,11 @@ use heck::{CamelCase, SnakeCase}; use quote::quote; // Namespace for calculating state instruction sighash signatures. -const SIGHASH_STATE_NAMESPACE: &'static str = "state"; +const SIGHASH_STATE_NAMESPACE: &str = "state"; // Namespace for calculating instruction sighash signatures for any instruction // not affecting program state. -const SIGHASH_GLOBAL_NAMESPACE: &'static str = "global"; +const SIGHASH_GLOBAL_NAMESPACE: &str = "global"; pub fn generate(program: Program) -> proc_macro2::TokenStream { let mod_name = &program.name; @@ -127,7 +127,7 @@ pub fn generate_dispatch(program: &Program) -> proc_macro2::TokenStream { }) .collect() }) - .unwrap_or(vec![]), + .unwrap_or_default(), }; // Dispatch all trait interface implementations. @@ -157,7 +157,7 @@ pub fn generate_dispatch(program: &Program) -> proc_macro2::TokenStream { let sighash_tts: proc_macro2::TokenStream = format!("{:?}", sighash_arr).parse().unwrap(); let args_struct = { - if m.args.len() == 0 { + if m.args.is_empty() { quote! { #[derive(anchor_lang::AnchorSerialize, anchor_lang::AnchorDeserialize)] struct Args; @@ -187,7 +187,7 @@ pub fn generate_dispatch(program: &Program) -> proc_macro2::TokenStream { }) .collect() }) - .unwrap_or(vec![]) + .unwrap_or_default() }; // Dispatch all global instructions. @@ -470,7 +470,7 @@ pub fn generate_non_inlined_handlers(program: &Program) -> proc_macro2::TokenStr ) -> ProgramResult { let mut remaining_accounts: &[AccountInfo] = accounts; - if remaining_accounts.len() == 0 { + if remaining_accounts.is_empty() { return Err(ProgramError::Custom(1)); // todo } @@ -510,7 +510,7 @@ pub fn generate_non_inlined_handlers(program: &Program) -> proc_macro2::TokenStr }) .collect() }) - .unwrap_or(vec![]), + .unwrap_or_default() }; let non_inlined_state_trait_handlers: Vec = match &program.state { None => Vec::new(), @@ -546,7 +546,7 @@ pub fn generate_non_inlined_handlers(program: &Program) -> proc_macro2::TokenStr ) -> ProgramResult { let mut remaining_accounts: &[AccountInfo] = accounts; - if remaining_accounts.len() == 0 { + if remaining_accounts.is_empty() { return Err(ProgramError::Custom(1)); // todo } @@ -610,7 +610,7 @@ pub fn generate_non_inlined_handlers(program: &Program) -> proc_macro2::TokenStr }) .collect() }) - .unwrap_or(Vec::new()), + .unwrap_or_default(), }; let non_inlined_handlers: Vec = program .ixs @@ -652,7 +652,7 @@ pub fn generate_non_inlined_handlers(program: &Program) -> proc_macro2::TokenStr pub fn generate_ctor_variant(state: &State) -> proc_macro2::TokenStream { let ctor_args = generate_ctor_args(state); let ctor_variant_name: proc_macro2::TokenStream = generate_ctor_variant_name().parse().unwrap(); - if ctor_args.len() == 0 { + if ctor_args.is_empty() { quote! { #ctor_variant_name } @@ -681,7 +681,7 @@ pub fn generate_ctor_typed_variant_with_semi(program: &Program) -> proc_macro2:: .unwrap() }) .collect(); - if ctor_args.len() == 0 { + if ctor_args.is_empty() { quote! { #[derive(AnchorSerialize, AnchorDeserialize)] pub struct __Ctor; @@ -719,10 +719,10 @@ fn generate_ctor_typed_args(state: &State) -> Vec { }) .collect() }) - .unwrap_or(Vec::new()) + .unwrap_or_default() } -fn generate_ctor_args(state: &State) -> Vec> { +fn generate_ctor_args(state: &State) -> Vec { state .ctor_and_anchor .as_ref() @@ -737,13 +737,13 @@ fn generate_ctor_args(state: &State) -> Vec> { if arg_str.starts_with("Context<") { return None; } - Some(pat_ty.pat.clone()) + Some(*pat_ty.pat.clone()) } _ => panic!(""), }) .collect() }) - .unwrap_or(Vec::new()) + .unwrap_or_default() } pub fn generate_ix_variant( @@ -761,7 +761,7 @@ pub fn generate_ix_variant( } }; - if args.len() == 0 { + if args.is_empty() { quote! { #ix_name_camel } @@ -835,7 +835,7 @@ pub fn generate_ixs(program: &Program) -> proc_macro2::TokenStream { }; // If no args, output a "unit" variant instead of a struct variant. - if method.args.len() == 0 { + if method.args.is_empty() { quote! { #[derive(AnchorSerialize, AnchorDeserialize)] pub struct #ix_name_camel; @@ -855,7 +855,7 @@ pub fn generate_ixs(program: &Program) -> proc_macro2::TokenStream { }) .collect() }) - .unwrap_or(Vec::new()), + .unwrap_or_default(), }; let variants: Vec = program .ixs @@ -888,7 +888,7 @@ pub fn generate_ixs(program: &Program) -> proc_macro2::TokenStream { } }; // If no args, output a "unit" variant instead of a struct variant. - if ix.args.len() == 0 { + if ix.args.is_empty() { quote! { #[derive(AnchorSerialize, AnchorDeserialize)] pub struct #ix_name_camel; diff --git a/lang/syn/src/idl.rs b/lang/syn/src/idl.rs index f90286a6..760092d6 100644 --- a/lang/syn/src/idl.rs +++ b/lang/syn/src/idl.rs @@ -147,7 +147,7 @@ impl std::str::FromStr for IdlType { let inner_ty = Self::from_str( inner .strip_suffix(">") - .ok_or(anyhow::anyhow!("Invalid option"))?, + .ok_or_else(|| anyhow::anyhow!("Invalid option"))?, )?; IdlType::Vec(Box::new(inner_ty)) } @@ -156,7 +156,7 @@ impl std::str::FromStr for IdlType { let inner_ty = Self::from_str( inner .strip_suffix(">") - .ok_or(anyhow::anyhow!("Invalid option"))?, + .ok_or_else(|| anyhow::anyhow!("Invalid option"))?, )?; IdlType::Option(Box::new(inner_ty)) } diff --git a/lang/syn/src/lib.rs b/lang/syn/src/lib.rs index db01923c..141fc308 100644 --- a/lang/syn/src/lib.rs +++ b/lang/syn/src/lib.rs @@ -79,7 +79,7 @@ pub struct AccountsStruct { impl AccountsStruct { pub fn new(strct: syn::ItemStruct, fields: Vec) -> Self { let ident = strct.ident.clone(); - let generics = strct.generics.clone(); + let generics = strct.generics; Self { ident, generics, @@ -104,10 +104,9 @@ impl AccountsStruct { } } AccountField::AccountsStruct(comp_f) => { - let accs = global_accs.get(&comp_f.symbol).ok_or(anyhow::format_err!( - "Invalid account type: {}", - comp_f.symbol - ))?; + let accs = global_accs.get(&comp_f.symbol).ok_or_else(|| { + anyhow::format_err!("Invalid account type: {}", comp_f.symbol) + })?; tys.extend(accs.account_tys(global_accs)?); } } diff --git a/lang/syn/src/parser/accounts.rs b/lang/syn/src/parser/accounts.rs index 887d7971..b37aec77 100644 --- a/lang/syn/src/parser/accounts.rs +++ b/lang/syn/src/parser/accounts.rs @@ -21,14 +21,14 @@ fn parse_account_attr(f: &syn::Field) -> Option<&syn::Attribute> { let anchor_attrs: Vec<&syn::Attribute> = f .attrs .iter() - .filter_map(|attr: &syn::Attribute| { + .filter(|attr| { if attr.path.segments.len() != 1 { - return None; + return false; } - if attr.path.segments[0].ident.to_string() != "account" { - return None; + if attr.path.segments[0].ident != "account" { + return false; } - Some(attr) + true }) .collect(); match anchor_attrs.len() { @@ -66,10 +66,10 @@ fn parse_field(f: &syn::Field, anchor: Option<&syn::Attribute>) -> AccountField } fn is_field_primitive(f: &syn::Field) -> bool { - match ident_string(f).as_str() { - "ProgramState" | "ProgramAccount" | "CpiAccount" | "Sysvar" | "AccountInfo" => true, - _ => false, - } + matches!( + ident_string(f).as_str(), + "ProgramState" | "ProgramAccount" | "CpiAccount" | "Sysvar" | "AccountInfo" + ) } fn parse_ty(f: &syn::Field) -> Ty { @@ -115,26 +115,22 @@ fn parse_program_account(path: &syn::Path) -> ProgramAccountTy { fn parse_account(path: &syn::Path) -> syn::Ident { let segments = &path.segments[0]; - let account_ident = match &segments.arguments { + match &segments.arguments { syn::PathArguments::AngleBracketed(args) => { // Expected: <'info, MyType>. assert!(args.args.len() == 2); match &args.args[1] { - syn::GenericArgument::Type(ty) => match ty { - syn::Type::Path(ty_path) => { - // TODO: allow segmented paths. - assert!(ty_path.path.segments.len() == 1); - let path_segment = &ty_path.path.segments[0]; - path_segment.ident.clone() - } - _ => panic!("Invalid ProgramAccount"), - }, + syn::GenericArgument::Type(syn::Type::Path(ty_path)) => { + // TODO: allow segmented paths. + assert!(ty_path.path.segments.len() == 1); + let path_segment = &ty_path.path.segments[0]; + path_segment.ident.clone() + } _ => panic!("Invalid ProgramAccount"), } } _ => panic!("Invalid ProgramAccount"), - }; - account_ident + } } fn parse_sysvar(path: &syn::Path) -> SysvarTy { @@ -144,15 +140,12 @@ fn parse_sysvar(path: &syn::Path) -> SysvarTy { // Expected: <'info, MyType>. assert!(args.args.len() == 2); match &args.args[1] { - syn::GenericArgument::Type(ty) => match ty { - syn::Type::Path(ty_path) => { - // TODO: allow segmented paths. - assert!(ty_path.path.segments.len() == 1); - let path_segment = &ty_path.path.segments[0]; - path_segment.ident.clone() - } - _ => panic!("Invalid Sysvar"), - }, + syn::GenericArgument::Type(syn::Type::Path(ty_path)) => { + // TODO: allow segmented paths. + assert!(ty_path.path.segments.len() == 1); + let path_segment = &ty_path.path.segments[0]; + path_segment.ident.clone() + } _ => panic!("Invalid Sysvar"), } } diff --git a/lang/syn/src/parser/file.rs b/lang/syn/src/parser/file.rs index 942d77e9..b8583227 100644 --- a/lang/syn/src/parser/file.rs +++ b/lang/syn/src/parser/file.rs @@ -9,7 +9,7 @@ use std::fs::File; use std::io::Read; use std::path::Path; -static DERIVE_NAME: &'static str = "Accounts"; +const DERIVE_NAME: &str = "Accounts"; // Parse an entire interface file. pub fn parse(filename: impl AsRef) -> Result { @@ -69,24 +69,21 @@ pub fn parse(filename: impl AsRef) -> Result { }) .collect::>() }) - .unwrap_or(Vec::new()); + .unwrap_or_default(); let ctor = { let name = "new".to_string(); let args = ctor .sig .inputs .iter() - .filter_map(|arg: &syn::FnArg| match arg { + .filter(|arg| match arg { syn::FnArg::Typed(pat_ty) => { // TODO: this filtering should be donein the parser. let mut arg_str = parser::tts_to_string(&pat_ty.ty); arg_str.retain(|c| !c.is_whitespace()); - if arg_str.starts_with("Context<") { - return None; - } - Some(arg) + !arg_str.starts_with("Context<") } - _ => None, + _ => false, }) .map(|arg: &syn::FnArg| match arg { syn::FnArg::Typed(arg_typed) => { @@ -184,7 +181,7 @@ pub fn parse(filename: impl AsRef) -> Result { let mut types = vec![]; let ty_defs = parse_ty_defs(&f)?; - let error_name = error.map(|e| e.name).unwrap_or("".to_string()); + let error_name = error.map(|e| e.name).unwrap_or_else(|| "".to_string()); for ty_def in ty_defs { // Don't add the error type to the types or accounts sections. @@ -216,18 +213,12 @@ fn parse_program_mod(f: &syn::File) -> syn::ItemMod { .iter() .filter_map(|i| match i { syn::Item::Mod(item_mod) => { - let mods = item_mod + let mod_count = item_mod .attrs .iter() - .filter_map(|attr| { - let segment = attr.path.segments.last().unwrap(); - if segment.ident.to_string() == "program" { - return Some(attr); - } - None - }) - .collect::>(); - if mods.len() != 1 { + .filter(|attr| attr.path.segments.last().unwrap().ident == "program") + .count(); + if mod_count != 1 { return None; } Some(item_mod) @@ -246,18 +237,15 @@ fn parse_error_enum(f: &syn::File) -> Option { .iter() .filter_map(|i| match i { syn::Item::Enum(item_enum) => { - let attrs = item_enum + let attrs_count = item_enum .attrs .iter() - .filter_map(|attr| { + .filter(|attr| { let segment = attr.path.segments.last().unwrap(); - if segment.ident.to_string() == "error" { - return Some(attr); - } - None + segment.ident == "error" }) - .collect::>(); - match attrs.len() { + .count(); + match attrs_count { 0 => None, 1 => Some(item_enum), _ => panic!("Invalid syntax: one error attribute allowed"), diff --git a/lang/syn/src/parser/program.rs b/lang/syn/src/parser/program.rs index 580a2afd..6c965479 100644 --- a/lang/syn/src/parser/program.rs +++ b/lang/syn/src/parser/program.rs @@ -58,7 +58,7 @@ pub fn parse(program_mod: syn::ItemMod) -> Program { .iter() .filter_map(|item: &syn::ImplItem| match item { syn::ImplItem::Method(m) => { - if m.sig.ident.to_string() == "new" { + if m.sig.ident == "new" { let ctx_arg = m.sig.inputs.first().unwrap(); // todo: unwrap. match ctx_arg { syn::FnArg::Receiver(_) => panic!("invalid syntax"), @@ -73,7 +73,6 @@ pub fn parse(program_mod: syn::ItemMod) -> Program { _ => None, }) .next() - .clone() } }; // Parse all methods in the above `impl` block. @@ -141,9 +140,6 @@ pub fn parse(program_mod: syn::ItemMod) -> Program { .clone() .to_string(), }; - if item_impl.trait_.is_none() { - return None; - } let methods = item_impl .items .iter() @@ -207,10 +203,9 @@ pub fn parse(program_mod: syn::ItemMod) -> Program { State { name: strct.ident.to_string(), - strct: strct.clone(), + strct, interfaces: trait_impls, - impl_block_and_methods: impl_block - .map(|impl_block| (impl_block.clone(), methods.unwrap())), + impl_block_and_methods: impl_block.map(|impl_block| (impl_block, methods.unwrap())), ctor_and_anchor, } }) diff --git a/spl/src/token.rs b/spl/src/token.rs index a47e69e8..643eb7fd 100644 --- a/spl/src/token.rs +++ b/spl/src/token.rs @@ -141,7 +141,7 @@ impl anchor_lang::AccountDeserialize for TokenAccount { } fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result { - spl_token::state::Account::unpack(buf).map(|a| TokenAccount(a)) + spl_token::state::Account::unpack(buf).map(TokenAccount) } } @@ -162,7 +162,7 @@ impl anchor_lang::AccountDeserialize for Mint { } fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result { - spl_token::state::Mint::unpack(buf).map(|a| Mint(a)) + spl_token::state::Mint::unpack(buf).map(Mint) } }