From bf495ac3df5483a80c37b51ad534ee8fb47821bc Mon Sep 17 00:00:00 2001 From: "Jean (Exotic Markets)" Date: Thu, 17 Jul 2025 22:21:27 +0700 Subject: [PATCH] chore: fix clippy complains (#3776) * chore: fix clippy complains * fix lints * simplify some parts --------- Co-authored-by: Aursen --- avm/src/lib.rs | 2 +- cli/src/checks.rs | 9 +++-- cli/src/config.rs | 8 ++-- cli/src/lib.rs | 19 ++++------ cli/src/rust_template.rs | 5 +-- client/src/blocking.rs | 2 +- idl/src/build.rs | 4 +- .../program/src/declare_program/common.rs | 38 +++++++------------ .../src/declare_program/mods/internal.rs | 16 ++++---- lang/src/accounts/account_loader.rs | 6 +-- lang/src/error.rs | 2 +- lang/syn/src/codegen/accounts/bumps.rs | 2 +- lang/syn/src/codegen/accounts/constraints.rs | 3 +- lang/syn/src/codegen/program/common.rs | 2 +- lang/syn/src/parser/context.rs | 4 +- 15 files changed, 54 insertions(+), 68 deletions(-) diff --git a/avm/src/lib.rs b/avm/src/lib.rs index 646041e43..c4f25188b 100644 --- a/avm/src/lib.rs +++ b/avm/src/lib.rs @@ -194,7 +194,7 @@ pub fn install_version( AVM_HOME.to_str().unwrap().into(), ]; let conditional_args = match install_target { - InstallTarget::Version(version) => ["--tag".into(), format!("v{}", version)], + InstallTarget::Version(version) => ["--tag".into(), format!("v{version}")], InstallTarget::Commit(commit) => ["--rev".into(), commit], }; args.extend_from_slice(&conditional_args); diff --git a/cli/src/checks.rs b/cli/src/checks.rs index 462e2c98e..383b99e8e 100644 --- a/cli/src/checks.rs +++ b/cli/src/checks.rs @@ -131,12 +131,15 @@ pub fn check_idl_build_feature() -> Result<()> { .iter() .any(|(feature, _)| feature == "idl-build"); if !has_idl_build_feature { - let anchor_spl_idl_build = manifest + let anchor_spl_idl_build = if manifest .dependencies .iter() .any(|dep| dep.0 == "anchor-spl") - .then_some(r#", "anchor-spl/idl-build""#) - .unwrap_or_default(); + { + r#", "anchor-spl/idl-build""# + } else { + "" + }; return Err(anyhow!( r#"`idl-build` feature is missing. To solve, add diff --git a/cli/src/config.rs b/cli/src/config.rs index e8fdb7c54..976d1783b 100644 --- a/cli/src/config.rs +++ b/cli/src/config.rs @@ -318,8 +318,7 @@ impl WithPath { .map(|entry| self.process_single_path(&entry.path())) .collect(), Err(e) => vec![Err(Error::new(io::Error::other(format!( - "Error reading directory {:?}: {}", - dir, e + "Error reading directory {dir:?}: {e}" ))))], } } else { @@ -332,8 +331,7 @@ impl WithPath { fn process_single_path(&self, path: &PathBuf) -> Result { path.canonicalize().map_err(|e| { Error::new(io::Error::other(format!( - "Error canonicalizing path {:?}: {}", - path, e + "Error canonicalizing path {path:?}: {e}" ))) }) } @@ -685,7 +683,7 @@ impl fmt::Display for Config { }; let cfg = toml::to_string(&cfg).expect("Must be well formed"); - write!(f, "{}", cfg) + write!(f, "{cfg}") } } diff --git a/cli/src/lib.rs b/cli/src/lib.rs index 9533ead52..e20c6041f 100644 --- a/cli/src/lib.rs +++ b/cli/src/lib.rs @@ -1086,10 +1086,7 @@ fn init( let package_manager_result = install_node_modules(&package_manager_cmd)?; if !package_manager_result.status.success() && package_manager_cmd != "npm" { - println!( - "Failed {} install will attempt to npm install", - package_manager_cmd - ); + println!("Failed {package_manager_cmd} install will attempt to npm install"); install_node_modules("npm")?; } else { eprintln!("Failed to install node modules"); @@ -2017,7 +2014,7 @@ fn _build_solidity_cwd( // idl is written to idl_out or . let idl_path = idl_out .unwrap_or(PathBuf::from(".")) - .join(format!("{}.json", name)); + .join(format!("{name}.json")); let idl = fs::read(idl_path)?; let idl = convert_idl(&idl)?; @@ -3852,14 +3849,14 @@ fn deploy( let solana_args = add_recommended_deployment_solana_args(&client, solana_args)?; // Deploy the programs. - println!("Deploying cluster: {}", url); - println!("Upgrade authority: {}", keypair); + println!("Deploying cluster: {url}"); + println!("Upgrade authority: {keypair}"); for mut program in cfg.get_programs(program_name)? { let binary_path = program.binary_path(verifiable).display().to_string(); println!("Deploying program {:?}...", program.lib_name); - println!("Program path: {}...", binary_path); + println!("Program path: {binary_path}..."); let (program_keypair_filepath, program_id) = match &program_keypair { Some(path) => (path.clone(), get_keypair(path)?.pubkey()), @@ -4036,7 +4033,7 @@ fn create_idl_account( if retries == 19 { return Err(anyhow!("Error creating IDL account: {}", err)); } - println!("Error creating IDL account: {}. Retrying...", err); + println!("Error creating IDL account: {err}. Retrying..."); } } } @@ -4118,7 +4115,7 @@ fn create_idl_buffer( if retries == 19 { return Err(anyhow!("Error creating buffer account: {}", err)); } - println!("Error creating buffer account: {}. Retrying...", err); + println!("Error creating buffer account: {err}. Retrying..."); } } } @@ -4825,7 +4822,7 @@ fn get_recommended_micro_lamport_fee(client: &RpcClient) -> Result { fees.sort_unstable_by_key(|fee| fee.prioritization_fee); let median_index = fees.len() / 2; - let median_priority_fee = if fees.len() % 2 == 0 { + let median_priority_fee = if fees.len().is_multiple_of(2) { (fees[median_index - 1].prioritization_fee + fees[median_index].prioritization_fee) / 2 } else { fees[median_index].prioritization_fee diff --git a/cli/src/rust_template.rs b/cli/src/rust_template.rs index 9d496d353..ced98081f 100644 --- a/cli/src/rust_template.rs +++ b/cli/src/rust_template.rs @@ -751,10 +751,9 @@ description = "Created with Anchor" edition = "2021" [dependencies] -anchor-client = "{0}" -{1} = {{ version = "0.1.0", path = "../programs/{1}" }} +anchor-client = "{VERSION}" +{name} = {{ version = "0.1.0", path = "../programs/{name}" }} "#, - VERSION, name, ) } diff --git a/client/src/blocking.rs b/client/src/blocking.rs index 5de6cdba4..89ccb63f1 100644 --- a/client/src/blocking.rs +++ b/client/src/blocking.rs @@ -101,7 +101,7 @@ impl + Clone> Program { pub fn on( &self, f: impl Fn(&EventContext, T) + Send + 'static, - ) -> Result { + ) -> Result, ClientError> { let (handle, rx) = self.rt.block_on(self.on_internal(f))?; Ok(EventUnsubscriber { diff --git a/idl/src/build.rs b/idl/src/build.rs index ccd897452..b2f1727b3 100644 --- a/idl/src/build.rs +++ b/idl/src/build.rs @@ -140,7 +140,7 @@ fn build( ) -> Result { // `nightly` toolchain is currently required for building the IDL. let toolchain = std::env::var("RUSTUP_TOOLCHAIN") - .map(|toolchain| format!("+{}", toolchain)) + .map(|toolchain| format!("+{toolchain}")) .unwrap_or_else(|_| "+nightly".to_string()); install_toolchain_if_needed(&toolchain)?; @@ -174,7 +174,7 @@ fn build( let stdout = String::from_utf8_lossy(&output.stdout); if env::var("ANCHOR_LOG").is_ok() { - eprintln!("{}", stdout); + eprintln!("{stdout}"); } if !output.status.success() { diff --git a/lang/attribute/program/src/declare_program/common.rs b/lang/attribute/program/src/declare_program/common.rs index f316fc55b..0df84578d 100644 --- a/lang/attribute/program/src/declare_program/common.rs +++ b/lang/attribute/program/src/declare_program/common.rs @@ -126,9 +126,8 @@ pub fn convert_idl_type_def_to_ts( let attrs = { let debug_attr = quote!(#[derive(Debug)]); - let default_attr = can_derive_default(ty_def, ty_defs) - .then(|| quote!(#[derive(Default)])) - .unwrap_or_default(); + let default_attr = + can_derive_default(ty_def, ty_defs).then_some(quote!(#[derive(Default)])); let ser_attr = match &ty_def.serialization { IdlSerialization::Borsh => quote!(#[derive(AnchorSerialize, AnchorDeserialize)]), @@ -155,7 +154,7 @@ pub fn convert_idl_type_def_to_ts( } }; - let repr = if let Some(repr) = &ty_def.repr { + let repr = ty_def.repr.as_ref().map(|repr| { let kind = match repr { IdlRepr::Rust(_) => "Rust", IdlRepr::C(_) => "C", @@ -166,33 +165,24 @@ pub fn convert_idl_type_def_to_ts( let modifier = match repr { IdlRepr::Rust(modifier) | IdlRepr::C(modifier) => { - let packed = modifier.packed.then(|| quote!(packed)).unwrap_or_default(); + let packed = modifier.packed.then_some(quote!(packed)); let align = modifier .align .map(Literal::usize_unsuffixed) - .map(|align| quote!(align(#align))) - .unwrap_or_default(); + .map(|align| quote!(align(#align))); - if packed.is_empty() { - align - } else if align.is_empty() { - packed - } else { - quote! { #packed, #align } + match (packed, align) { + (None, None) => None, + (Some(p), None) => Some(quote!(#p)), + (None, Some(a)) => Some(quote!(#a)), + (Some(p), Some(a)) => Some(quote!(#p, #a)), } } - _ => quote!(), - }; - let modifier = if modifier.is_empty() { - modifier - } else { - quote! { , #modifier } - }; - + _ => None, + } + .map(|m| quote!(, #m)); quote! { #[repr(#kind #modifier)] } - } else { - quote!() - }; + }); match &ty_def.ty { IdlTypeDefTy::Struct { fields } => { diff --git a/lang/attribute/program/src/declare_program/mods/internal.rs b/lang/attribute/program/src/declare_program/mods/internal.rs index 12b1e8d15..1ae08a167 100644 --- a/lang/attribute/program/src/declare_program/mods/internal.rs +++ b/lang/attribute/program/src/declare_program/mods/internal.rs @@ -167,14 +167,14 @@ fn gen_internal_accounts_common( let name = format_ident!("{}", acc.name); let attrs = { - let signer = acc.signer.then(|| quote!(signer)).unwrap_or_default(); - let mt = acc.writable.then(|| quote!(mut)).unwrap_or_default(); - if signer.is_empty() { - mt - } else if mt.is_empty() { - signer - } else { - quote! { #signer, #mt } + let signer = acc.signer.then_some(quote!(signer)); + let mt = acc.writable.then_some(quote!(mut)); + + match (signer, mt) { + (None, None) => None, + (Some(s), None) => Some(quote!(#s)), + (None, Some(m)) => Some(quote!(#m)), + (Some(s), Some(m)) => Some(quote!(#s, #m)), } }; diff --git a/lang/src/accounts/account_loader.rs b/lang/src/accounts/account_loader.rs index 8bc2ef6d7..c7bfbc56e 100644 --- a/lang/src/accounts/account_loader.rs +++ b/lang/src/accounts/account_loader.rs @@ -151,7 +151,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> { } /// Returns a Ref to the account data structure for reading. - pub fn load(&self) -> Result> { + pub fn load(&self) -> Result> { let data = self.acc_info.try_borrow_data()?; let disc = T::DISCRIMINATOR; if data.len() < disc.len() { @@ -169,7 +169,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> { } /// Returns a `RefMut` to the account data structure for reading or writing. - pub fn load_mut(&self) -> Result> { + pub fn load_mut(&self) -> Result> { // AccountInfo api allows you to borrow mut even if the account isn't // writable, so add this check for a better dev experience. if !self.acc_info.is_writable { @@ -196,7 +196,7 @@ impl<'info, T: ZeroCopy + Owner> AccountLoader<'info, T> { /// Returns a `RefMut` to the account data structure for reading or writing. /// Should only be called once, when the account is being initialized. - pub fn load_init(&self) -> Result> { + pub fn load_init(&self) -> Result> { // AccountInfo api allows you to borrow mut even if the account isn't // writable, so add this check for a better dev experience. if !self.acc_info.is_writable { diff --git a/lang/src/error.rs b/lang/src/error.rs index 6652811a7..bda97cca8 100644 --- a/lang/src/error.rs +++ b/lang/src/error.rs @@ -319,7 +319,7 @@ impl From for Error { Self::AnchorError(Box::new(AnchorError { error_name: ErrorCode::InvalidNumericConversion.name(), error_code_number: ErrorCode::InvalidNumericConversion.into(), - error_msg: format!("{}", e), + error_msg: format!("{e}"), error_origin: None, compared_values: None, })) diff --git a/lang/syn/src/codegen/accounts/bumps.rs b/lang/syn/src/codegen/accounts/bumps.rs index bd895410b..d7776eeb6 100644 --- a/lang/syn/src/codegen/accounts/bumps.rs +++ b/lang/syn/src/codegen/accounts/bumps.rs @@ -7,7 +7,7 @@ use std::fmt::Display; use super::constraints; pub fn generate_bumps_name(anchor_ident: &T) -> Ident { - Ident::new(&format!("{}Bumps", anchor_ident), Span::call_site()) + Ident::new(&format!("{anchor_ident}Bumps"), Span::call_site()) } pub fn generate(accs: &AccountsStruct) -> proc_macro2::TokenStream { diff --git a/lang/syn/src/codegen/accounts/constraints.rs b/lang/syn/src/codegen/accounts/constraints.rs index dd4bdef90..feac5058c 100644 --- a/lang/syn/src/codegen/accounts/constraints.rs +++ b/lang/syn/src/codegen/accounts/constraints.rs @@ -365,8 +365,7 @@ pub fn generate_constraint_owner(f: &Field, c: &ConstraintOwner) -> proc_macro2: | Ty::InterfaceAccount(InterfaceAccountTy { boxed, .. }) => *boxed, _ => false, } - .then(|| quote!(*)) - .unwrap_or_default(); + .then_some(quote!(*)); let owner_address = &c.owner_address; let error = generate_custom_error( ident, diff --git a/lang/syn/src/codegen/program/common.rs b/lang/syn/src/codegen/program/common.rs index 969b30f2f..0065fadc9 100644 --- a/lang/syn/src/codegen/program/common.rs +++ b/lang/syn/src/codegen/program/common.rs @@ -20,7 +20,7 @@ pub fn sighash(namespace: &str, name: &str) -> [u8; 8] { pub fn gen_discriminator(namespace: &str, name: impl ToString) -> proc_macro2::TokenStream { let discriminator = sighash(namespace, name.to_string().as_str()); - format!("&{:?}", discriminator).parse().unwrap() + format!("&{discriminator:?}").parse().unwrap() } pub fn generate_ix_variant(name: &str, args: &[IxArg]) -> proc_macro2::TokenStream { diff --git a/lang/syn/src/parser/context.rs b/lang/syn/src/parser/context.rs index 6ec4dc36d..0ffb48798 100644 --- a/lang/syn/src/parser/context.rs +++ b/lang/syn/src/parser/context.rs @@ -38,11 +38,11 @@ impl CrateContext { self.modules.iter().flat_map(|(_, ctx)| ctx.type_aliases()) } - pub fn modules(&self) -> impl Iterator { + pub fn modules(&self) -> impl Iterator> { self.modules.values().map(|detail| ModuleContext { detail }) } - pub fn root_module(&self) -> ModuleContext { + pub fn root_module(&self) -> ModuleContext<'_> { ModuleContext { detail: self.modules.get("crate").unwrap(), }