Armani Ferrante 4 роки тому
батько
коміт
08f5a0e243

+ 3 - 3
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<Path>) -> Result<String> {
             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")),

+ 14 - 13
cli/src/main.rs

@@ -670,7 +670,9 @@ fn stream_logs(url: &str) -> Result<Vec<std::process::Child>> {
         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<Vec<String>>) -> Result<Child> {
     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<String>, keypair: Option<String>) -> Result<Vec<(Pubkey,
         build(None)?;
 
         // Fallback to config vars if not provided via CLI.
-        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());
 
         // Deploy the programs.
         println!("Deploying workspace: {}", url);
@@ -842,8 +844,8 @@ fn launch(url: Option<String>, keypair: Option<String>) -> 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<R>(f: impl FnOnce(&Config, PathBuf, Option<PathBuf>) -> 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<String>) -> 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<String>) -> 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")

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

+ 5 - 5
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<T: AccountDeserialize>(&self, address: Pubkey) -> Result<T, ClientError> {
         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(),

+ 1 - 4
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<proc_macro2::TokenStream> = 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())

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

+ 3 - 7
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<syn::Pat>> = 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)]

+ 2 - 2
lang/src/account_info.rs

@@ -10,7 +10,7 @@ impl<'info> Accounts<'info> for AccountInfo<'info> {
         _program_id: &Pubkey,
         accounts: &mut &[AccountInfo<'info>],
     ) -> Result<Self, ProgramError> {
-        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<Self, ProgramError> {
-        if accounts.len() == 0 {
+        if accounts.is_empty() {
             return Err(ProgramError::NotEnoughAccountKeys);
         }
 

+ 1 - 1
lang/src/cpi_account.rs

@@ -50,7 +50,7 @@ where
         _program_id: &Pubkey,
         accounts: &mut &[AccountInfo<'info>],
     ) -> Result<Self, ProgramError> {
-        if accounts.len() == 0 {
+        if accounts.is_empty() {
             return Err(ProgramError::NotEnoughAccountKeys);
         }
         let account = &accounts[0];

+ 2 - 2
lang/src/program_account.rs

@@ -71,7 +71,7 @@ where
         program_id: &Pubkey,
         accounts: &mut &[AccountInfo<'info>],
     ) -> Result<Self, ProgramError> {
-        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<Self, ProgramError> {
-        if accounts.len() == 0 {
+        if accounts.is_empty() {
             return Err(ProgramError::NotEnoughAccountKeys);
         }
         let account = &accounts[0];

+ 1 - 1
lang/src/state.rs

@@ -59,7 +59,7 @@ where
         program_id: &Pubkey,
         accounts: &mut &[AccountInfo<'info>],
     ) -> Result<Self, ProgramError> {
-        if accounts.len() == 0 {
+        if accounts.is_empty() {
             return Err(ProgramError::NotEnoughAccountKeys);
         }
         let account = &accounts[0];

+ 1 - 1
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<Self, ProgramError> {
-        if accounts.len() == 0 {
+        if accounts.is_empty() {
             return Err(ProgramError::NotEnoughAccountKeys);
         }
         let account = &accounts[0];

+ 19 - 19
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<proc_macro2::TokenStream> = 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<proc_macro2::TokenStream> = 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<syn::PatType> {
                 })
                 .collect()
         })
-        .unwrap_or(Vec::new())
+        .unwrap_or_default()
 }
 
-fn generate_ctor_args(state: &State) -> Vec<Box<syn::Pat>> {
+fn generate_ctor_args(state: &State) -> Vec<syn::Pat> {
     state
         .ctor_and_anchor
         .as_ref()
@@ -737,13 +737,13 @@ fn generate_ctor_args(state: &State) -> Vec<Box<syn::Pat>> {
                         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<proc_macro2::TokenStream> = 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;

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

+ 4 - 5
lang/syn/src/lib.rs

@@ -79,7 +79,7 @@ pub struct AccountsStruct {
 impl AccountsStruct {
     pub fn new(strct: syn::ItemStruct, fields: Vec<AccountField>) -> 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)?);
                 }
             }

+ 23 - 30
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"),
             }
         }

+ 15 - 27
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<Path>) -> Result<Idl> {
@@ -69,24 +69,21 @@ pub fn parse(filename: impl AsRef<Path>) -> Result<Idl> {
                             })
                             .collect::<Vec<_>>()
                     })
-                    .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<Path>) -> Result<Idl> {
     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::<Vec<_>>();
-                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<syn::ItemEnum> {
         .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::<Vec<_>>();
-                match attrs.len() {
+                    .count();
+                match attrs_count {
                     0 => None,
                     1 => Some(item_enum),
                     _ => panic!("Invalid syntax: one error attribute allowed"),

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

+ 2 - 2
spl/src/token.rs

@@ -141,7 +141,7 @@ impl anchor_lang::AccountDeserialize for TokenAccount {
     }
 
     fn try_deserialize_unchecked(buf: &mut &[u8]) -> Result<Self, ProgramError> {
-        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<Self, ProgramError> {
-        spl_token::state::Mint::unpack(buf).map(|a| Mint(a))
+        spl_token::state::Mint::unpack(buf).map(Mint)
     }
 }