anchor_attribute_access_control/lib.rs
1extern crate proc_macro;
2
3use {quote::quote, syn::parse_macro_input};
4
5/// Executes the given access control method before running the decorated
6/// instruction handler. Any method in scope of the attribute can be invoked
7/// with any arguments from the associated instruction handler.
8///
9/// # Example
10///
11/// ```ignore
12/// use anchor_lang::prelude::*;
13///
14/// #[program]
15/// mod errors {
16/// use super::*;
17///
18/// #[access_control(Create::accounts(&ctx, bump_seed))]
19/// pub fn create(ctx: Context<Create>, bump_seed: u8) -> Result<()> {
20/// let my_account = &mut ctx.accounts.my_account;
21/// my_account.bump_seed = bump_seed;
22/// }
23/// }
24///
25/// #[derive(Accounts)]
26/// pub struct Create {
27/// #[account(init)]
28/// my_account: Account<'info, MyAccount>,
29/// }
30///
31/// impl Create {
32/// pub fn accounts(ctx: &Context<Create>, bump_seed: u8) -> Result<()> {
33/// let seeds = &[ctx.accounts.my_account.to_account_info().key.as_ref(), &[bump_seed]];
34/// Pubkey::create_program_address(seeds, ctx.program_id)
35/// .map_err(|_| ErrorCode::InvalidNonce)?;
36/// Ok(())
37/// }
38/// }
39/// ```
40///
41/// This example demonstrates a useful pattern. Not only can you use
42/// `#[access_control]` to ensure any invariants or preconditions hold prior to
43/// executing an instruction, but also it can be used to finish any validation
44/// on the `Accounts` struct, particularly when instruction arguments are
45/// needed. Here, we use the given `bump_seed` to verify it creates a valid
46/// program-derived address.
47#[proc_macro_attribute]
48pub fn access_control(
49 args: proc_macro::TokenStream,
50 input: proc_macro::TokenStream,
51) -> proc_macro::TokenStream {
52 let mut args = args.to_string();
53 args.retain(|c| !c.is_whitespace());
54 let access_control: Vec<proc_macro2::TokenStream> = args
55 .split(')')
56 .filter(|ac| !ac.is_empty())
57 .map(|ac| format!("{ac})")) // Put back on the split char.
58 .map(|ac| format!("{ac}?;")) // Add `?;` syntax.
59 .map(|ac| {
60 ac.parse::<proc_macro2::TokenStream>().map_err(|_| {
61 syn::Error::new(
62 proc_macro2::Span::call_site(),
63 format!("`#[access_control]` argument `{ac} is not valid Rust syntax"),
64 )
65 .into_compile_error()
66 })
67 })
68 .collect::<Result<Vec<_>, _>>()
69 .unwrap_or_else(|err| vec![err]);
70
71 let item_fn = parse_macro_input!(input as syn::ItemFn);
72
73 let fn_attrs = item_fn.attrs;
74 let fn_vis = item_fn.vis;
75 let fn_sig = item_fn.sig;
76 let fn_block = item_fn.block;
77
78 let fn_stmts = fn_block.stmts;
79
80 proc_macro::TokenStream::from(quote! {
81 #(#fn_attrs)*
82 #fn_vis #fn_sig {
83
84 #(#access_control)*
85
86 #(#fn_stmts)*
87 }
88 })
89}