Browse Source

chore: fix clippy complains (#3776)

* chore: fix clippy complains

* fix lints

* simplify some parts

---------

Co-authored-by: Aursen <aursen@users.noreply.github.com>
Jean (Exotic Markets) 2 months ago
parent
commit
bf495ac3df

+ 1 - 1
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);

+ 6 - 3
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

+ 3 - 5
cli/src/config.rs

@@ -318,8 +318,7 @@ impl WithPath<Config> {
                             .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<Config> {
     fn process_single_path(&self, path: &PathBuf) -> Result<PathBuf, Error> {
         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}")
     }
 }
 

+ 8 - 11
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<u64> {
     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

+ 2 - 3
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,
     )
 }
 

+ 1 - 1
client/src/blocking.rs

@@ -101,7 +101,7 @@ impl<C: Deref<Target = impl Signer> + Clone> Program<C> {
     pub fn on<T: anchor_lang::Event + anchor_lang::AnchorDeserialize>(
         &self,
         f: impl Fn(&EventContext, T) + Send + 'static,
-    ) -> Result<EventUnsubscriber, ClientError> {
+    ) -> Result<EventUnsubscriber<'_>, ClientError> {
         let (handle, rx) = self.rt.block_on(self.on_internal(f))?;
 
         Ok(EventUnsubscriber {

+ 2 - 2
idl/src/build.rs

@@ -140,7 +140,7 @@ fn build(
 ) -> Result<Idl> {
     // `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() {

+ 14 - 24
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 } => {

+ 8 - 8
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)),
                         }
                     };
 

+ 3 - 3
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<Ref<T>> {
+    pub fn load(&self) -> Result<Ref<'_, T>> {
         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<RefMut<T>> {
+    pub fn load_mut(&self) -> Result<RefMut<'_, T>> {
         // 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<RefMut<T>> {
+    pub fn load_init(&self) -> Result<RefMut<'_, T>> {
         // 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 {

+ 1 - 1
lang/src/error.rs

@@ -319,7 +319,7 @@ impl From<TryFromIntError> 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,
         }))

+ 1 - 1
lang/syn/src/codegen/accounts/bumps.rs

@@ -7,7 +7,7 @@ use std::fmt::Display;
 use super::constraints;
 
 pub fn generate_bumps_name<T: Display>(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 {

+ 1 - 2
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,

+ 1 - 1
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 {

+ 2 - 2
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<Item = ModuleContext> {
+    pub fn modules(&self) -> impl Iterator<Item = ModuleContext<'_>> {
         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(),
         }