Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lang: allow cfg_attr for the ix data structs #2963

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ The minor version will be incremented upon a breaking change and the patch versi

### Features

- lang: Allow to conditionally include attributes in the autogenerated instruction data structures ([#2963](https://github.com/coral-xyz/anchor/pull/2963)).
- idl: Allow overriding the idl build toolchain with the `RUSTUP_TOOLCHAIN` environment variable ([#2941](https://github.com/coral-xyz/anchor/pull/2941])).
- avm: Support customizing the installation location using `AVM_HOME` environment variable ([#2917](https://github.com/coral-xyz/anchor/pull/2917)).
- idl, ts: Add accounts resolution for associated token accounts ([#2927](https://github.com/coral-xyz/anchor/pull/2927)).
Expand Down
3 changes: 3 additions & 0 deletions lang/syn/src/codegen/program/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
.iter()
.map(|ix| {
let name = &ix.raw_method.sig.ident.to_string();
let ix_cfg_attrs = &ix.cfg_attrs;
let ix_name_camel =
proc_macro2::Ident::new(&name.to_camel_case(), ix.raw_method.sig.ident.span());
let raw_args: Vec<proc_macro2::TokenStream> = ix
Expand Down Expand Up @@ -43,6 +44,7 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
if ix.args.is_empty() {
quote! {
/// Instruction.
#(#ix_cfg_attrs)*
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct #ix_name_camel;

Expand All @@ -51,6 +53,7 @@ pub fn generate(program: &Program) -> proc_macro2::TokenStream {
} else {
quote! {
/// Instruction.
#(#ix_cfg_attrs)*
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct #ix_name_camel {
#(#raw_args),*
Expand Down
5 changes: 3 additions & 2 deletions lang/syn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::{
Expr, Generics, Ident, ItemEnum, ItemFn, ItemMod, ItemStruct, LitInt, PatType, Token, Type,
TypePath,
Attribute, Expr, Generics, Ident, ItemEnum, ItemFn, ItemMod, ItemStruct, LitInt, PatType,
Token, Type, TypePath,
};

#[derive(Debug)]
Expand Down Expand Up @@ -63,6 +63,7 @@ pub struct Ix {
pub raw_method: ItemFn,
pub ident: Ident,
pub docs: Option<Vec<String>>,
pub cfg_attrs: Vec<Attribute>,
pub args: Vec<IxArg>,
pub returns: IxReturn,
// The ident for the struct deriving Accounts.
Expand Down
20 changes: 18 additions & 2 deletions lang/syn/src/parser/program/instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ use crate::parser::docs;
use crate::parser::program::ctx_accounts_ident;
use crate::parser::spl_interface;
use crate::{FallbackFn, Ix, IxArg, IxReturn};
use syn::parse::{Error as ParseError, Result as ParseResult};
use syn::spanned::Spanned;
use syn::{
parse::{Error as ParseError, Result as ParseResult},
spanned::Spanned,
Attribute,
};

// Parse all non-state ix handlers from the program mod definition.
pub fn parse(program_mod: &syn::ItemMod) -> ParseResult<(Vec<Ix>, Option<FallbackFn>)> {
Expand All @@ -27,12 +30,14 @@ pub fn parse(program_mod: &syn::ItemMod) -> ParseResult<(Vec<Ix>, Option<Fallbac
let (ctx, args) = parse_args(method)?;
let interface_discriminator = spl_interface::parse(&method.attrs);
let docs = docs::parse(&method.attrs);
let cfg_attrs = parse_cfg_attr(method);
let returns = parse_return(method)?;
let anchor_ident = ctx_accounts_ident(&ctx.raw_arg)?;
Ok(Ix {
raw_method: method.clone(),
ident: method.sig.ident.clone(),
docs,
cfg_attrs,
args,
anchor_ident,
returns,
Expand Down Expand Up @@ -132,3 +137,14 @@ pub fn parse_return(method: &syn::ItemFn) -> ParseResult<IxReturn> {
)),
}
}

fn parse_cfg_attr(method: &syn::ItemFn) -> Vec<Attribute> {
method
.attrs
.iter()
.filter_map(|attr| match attr.path.is_ident("cfg_attr") {
true => Some(attr.to_owned()),
false => None,
})
.collect()
}
22 changes: 21 additions & 1 deletion lang/syn/src/parser/program/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,31 @@ pub fn parse(program_mod: syn::ItemMod) -> ParseResult<Program> {
ixs,
name: program_mod.ident.clone(),
docs,
program_mod,
program_mod: remove_cfg_attr_from_fns(program_mod),
fallback_fn,
})
}

fn remove_cfg_attr_from_fns(program_mod: syn::ItemMod) -> syn::ItemMod {
let mut program_mod = program_mod;
if let Some((brace, items)) = program_mod.content.as_mut() {
for item in items.iter_mut() {
if let syn::Item::Fn(item_fn) = item {
let new_attrs = item_fn
.attrs
.iter()
.filter(|attr| !attr.path.is_ident("cfg_attr"))
.cloned()
.collect();
item_fn.attrs = new_attrs;
*item = syn::Item::Fn(item_fn.clone());
}
}
program_mod.content = Some((*brace, items.to_vec()));
}
program_mod
}

fn ctx_accounts_ident(path_ty: &syn::PatType) -> ParseResult<proc_macro2::Ident> {
let p = match &*path_ty.ty {
syn::Type::Path(p) => &p.path,
Expand Down
3 changes: 2 additions & 1 deletion tests/misc/programs/misc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ crate-type = ["cdylib", "lib"]
name = "misc"

[features]
default = ["my-feature-derive"]
no-entrypoint = []
no-idl = []
cpi = ["no-entrypoint"]
default = []
idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"]
my-feature-derive = []

[dependencies]
anchor-lang = { path = "../../../../lang", features = ["init-if-needed"] }
Expand Down
3 changes: 3 additions & 0 deletions tests/misc/programs/misc/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -751,3 +751,6 @@ pub struct TestUsedIdentifiers<'info> {
/// CHECK: ignore
pub test4: AccountInfo<'info>,
}

#[derive(Accounts)]
pub struct EmptyWithCloneDerived {}
7 changes: 7 additions & 0 deletions tests/misc/programs/misc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,4 +385,11 @@ pub mod misc {
) -> Result<()> {
Ok(())
}

#[cfg_attr(feature = "my-feature-derive", derive(Clone))]
pub fn test_derive_feature(_ctx: Context<EmptyWithCloneDerived>) -> Result<()> {
let ix_data = instruction::TestDeriveFeature {};
let _ = ix_data.clone();
Ok(())
}
}
Loading