solana_sdk_macro/
lib.rs

1//! Convenience macro to declare a static public key and functions to interact with it
2//!
3//! Input: a single literal base58 string representation of a program's id
4
5extern crate proc_macro;
6
7use {
8    proc_macro::TokenStream,
9    proc_macro2::Span,
10    quote::{quote, ToTokens},
11    syn::{
12        bracketed,
13        parse::{Parse, ParseStream, Result},
14        parse_macro_input,
15        punctuated::Punctuated,
16        token::Bracket,
17        Expr, Ident, LitByte, LitStr, Token,
18    },
19};
20
21fn parse_id(
22    input: ParseStream,
23    pubkey_type: proc_macro2::TokenStream,
24) -> Result<proc_macro2::TokenStream> {
25    let id = if input.peek(syn::LitStr) {
26        let id_literal: LitStr = input.parse()?;
27        parse_pubkey(&id_literal, &pubkey_type)?
28    } else {
29        let expr: Expr = input.parse()?;
30        quote! { #expr }
31    };
32
33    if !input.is_empty() {
34        let stream: proc_macro2::TokenStream = input.parse()?;
35        return Err(syn::Error::new_spanned(stream, "unexpected token"));
36    }
37    Ok(id)
38}
39
40fn id_to_tokens(
41    id: &proc_macro2::TokenStream,
42    pubkey_type: proc_macro2::TokenStream,
43    tokens: &mut proc_macro2::TokenStream,
44) {
45    tokens.extend(quote! {
46        /// The const program ID.
47        pub const ID: #pubkey_type = #id;
48
49        /// Returns `true` if given pubkey is the program ID.
50        // TODO make this const once `derive_const` makes it out of nightly
51        // and we can `derive_const(PartialEq)` on `Pubkey`.
52        pub fn check_id(id: &#pubkey_type) -> bool {
53            id == &ID
54        }
55
56        /// Returns the program ID.
57        pub const fn id() -> #pubkey_type {
58            ID
59        }
60
61        #[cfg(test)]
62        #[test]
63        fn test_id() {
64            assert!(check_id(&id()));
65        }
66    });
67}
68
69fn deprecated_id_to_tokens(
70    id: &proc_macro2::TokenStream,
71    pubkey_type: proc_macro2::TokenStream,
72    tokens: &mut proc_macro2::TokenStream,
73) {
74    tokens.extend(quote! {
75        /// The static program ID.
76        pub static ID: #pubkey_type = #id;
77
78        /// Returns `true` if given pubkey is the program ID.
79        #[deprecated()]
80        pub fn check_id(id: &#pubkey_type) -> bool {
81            id == &ID
82        }
83
84        /// Returns the program ID.
85        #[deprecated()]
86        pub fn id() -> #pubkey_type {
87            ID
88        }
89
90        #[cfg(test)]
91        #[test]
92        #[allow(deprecated)]
93        fn test_id() {
94            assert!(check_id(&id()));
95        }
96    });
97}
98
99struct SdkPubkey(proc_macro2::TokenStream);
100
101impl Parse for SdkPubkey {
102    fn parse(input: ParseStream) -> Result<Self> {
103        parse_id(input, quote! { ::solana_sdk::pubkey::Pubkey }).map(Self)
104    }
105}
106
107impl ToTokens for SdkPubkey {
108    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
109        let id = &self.0;
110        tokens.extend(quote! {#id})
111    }
112}
113
114struct ProgramSdkPubkey(proc_macro2::TokenStream);
115
116impl Parse for ProgramSdkPubkey {
117    fn parse(input: ParseStream) -> Result<Self> {
118        parse_id(input, quote! { ::solana_program::pubkey::Pubkey }).map(Self)
119    }
120}
121
122impl ToTokens for ProgramSdkPubkey {
123    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
124        let id = &self.0;
125        tokens.extend(quote! {#id})
126    }
127}
128
129struct Id(proc_macro2::TokenStream);
130
131impl Parse for Id {
132    fn parse(input: ParseStream) -> Result<Self> {
133        parse_id(input, quote! { ::solana_sdk::pubkey::Pubkey }).map(Self)
134    }
135}
136
137impl ToTokens for Id {
138    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
139        id_to_tokens(&self.0, quote! { ::solana_sdk::pubkey::Pubkey }, tokens)
140    }
141}
142
143struct IdDeprecated(proc_macro2::TokenStream);
144
145impl Parse for IdDeprecated {
146    fn parse(input: ParseStream) -> Result<Self> {
147        parse_id(input, quote! { ::solana_sdk::pubkey::Pubkey }).map(Self)
148    }
149}
150
151impl ToTokens for IdDeprecated {
152    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
153        deprecated_id_to_tokens(&self.0, quote! { ::solana_sdk::pubkey::Pubkey }, tokens)
154    }
155}
156
157struct ProgramSdkId(proc_macro2::TokenStream);
158impl Parse for ProgramSdkId {
159    fn parse(input: ParseStream) -> Result<Self> {
160        parse_id(input, quote! { ::solana_program::pubkey::Pubkey }).map(Self)
161    }
162}
163
164impl ToTokens for ProgramSdkId {
165    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
166        id_to_tokens(&self.0, quote! { ::solana_program::pubkey::Pubkey }, tokens)
167    }
168}
169
170struct ProgramSdkIdDeprecated(proc_macro2::TokenStream);
171impl Parse for ProgramSdkIdDeprecated {
172    fn parse(input: ParseStream) -> Result<Self> {
173        parse_id(input, quote! { ::solana_program::pubkey::Pubkey }).map(Self)
174    }
175}
176
177impl ToTokens for ProgramSdkIdDeprecated {
178    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
179        deprecated_id_to_tokens(&self.0, quote! { ::solana_program::pubkey::Pubkey }, tokens)
180    }
181}
182
183#[deprecated(since = "2.1.0", note = "Use `solana_pubkey::pubkey` instead")]
184#[proc_macro]
185pub fn pubkey(input: TokenStream) -> TokenStream {
186    let id = parse_macro_input!(input as SdkPubkey);
187    TokenStream::from(quote! {#id})
188}
189
190#[deprecated(since = "2.1.0", note = "Use `solana_pubkey::pubkey!` instead")]
191#[proc_macro]
192pub fn program_pubkey(input: TokenStream) -> TokenStream {
193    let id = parse_macro_input!(input as ProgramSdkPubkey);
194    TokenStream::from(quote! {#id})
195}
196
197#[proc_macro]
198pub fn declare_id(input: TokenStream) -> TokenStream {
199    let id = parse_macro_input!(input as Id);
200    TokenStream::from(quote! {#id})
201}
202
203#[proc_macro]
204pub fn declare_deprecated_id(input: TokenStream) -> TokenStream {
205    let id = parse_macro_input!(input as IdDeprecated);
206    TokenStream::from(quote! {#id})
207}
208
209#[deprecated(since = "2.1.0", note = "Use `solana_pubkey::declare_id` instead")]
210#[proc_macro]
211pub fn program_declare_id(input: TokenStream) -> TokenStream {
212    let id = parse_macro_input!(input as ProgramSdkId);
213    TokenStream::from(quote! {#id})
214}
215
216#[deprecated(
217    since = "2.1.0",
218    note = "Use `solana_pubkey::declare_deprecated_id` instead"
219)]
220#[proc_macro]
221pub fn program_declare_deprecated_id(input: TokenStream) -> TokenStream {
222    let id = parse_macro_input!(input as ProgramSdkIdDeprecated);
223    TokenStream::from(quote! {#id})
224}
225
226fn parse_pubkey(
227    id_literal: &LitStr,
228    pubkey_type: &proc_macro2::TokenStream,
229) -> Result<proc_macro2::TokenStream> {
230    let id_vec = bs58::decode(id_literal.value())
231        .into_vec()
232        .map_err(|_| syn::Error::new_spanned(id_literal, "failed to decode base58 string"))?;
233    let id_array = <[u8; 32]>::try_from(<&[u8]>::clone(&&id_vec[..])).map_err(|_| {
234        syn::Error::new_spanned(
235            id_literal,
236            format!("pubkey array is not 32 bytes long: len={}", id_vec.len()),
237        )
238    })?;
239    let bytes = id_array.iter().map(|b| LitByte::new(*b, Span::call_site()));
240    Ok(quote! {
241        #pubkey_type::new_from_array(
242            [#(#bytes,)*]
243        )
244    })
245}
246
247struct Pubkeys {
248    method: Ident,
249    num: usize,
250    pubkeys: proc_macro2::TokenStream,
251}
252impl Parse for Pubkeys {
253    fn parse(input: ParseStream) -> Result<Self> {
254        let pubkey_type = quote! {
255            ::solana_sdk::pubkey::Pubkey
256        };
257
258        let method = input.parse()?;
259        let _comma: Token![,] = input.parse()?;
260        let (num, pubkeys) = if input.peek(syn::LitStr) {
261            let id_literal: LitStr = input.parse()?;
262            (1, parse_pubkey(&id_literal, &pubkey_type)?)
263        } else if input.peek(Bracket) {
264            let pubkey_strings;
265            bracketed!(pubkey_strings in input);
266            let punctuated: Punctuated<LitStr, Token![,]> =
267                Punctuated::parse_terminated(&pubkey_strings)?;
268            let mut pubkeys: Punctuated<proc_macro2::TokenStream, Token![,]> = Punctuated::new();
269            for string in punctuated.iter() {
270                pubkeys.push(parse_pubkey(string, &pubkey_type)?);
271            }
272            (pubkeys.len(), quote! {#pubkeys})
273        } else {
274            let stream: proc_macro2::TokenStream = input.parse()?;
275            return Err(syn::Error::new_spanned(stream, "unexpected token"));
276        };
277
278        Ok(Pubkeys {
279            method,
280            num,
281            pubkeys,
282        })
283    }
284}
285
286impl ToTokens for Pubkeys {
287    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
288        let Pubkeys {
289            method,
290            num,
291            pubkeys,
292        } = self;
293
294        let pubkey_type = quote! {
295            ::solana_sdk::pubkey::Pubkey
296        };
297        if *num == 1 {
298            tokens.extend(quote! {
299                pub fn #method() -> #pubkey_type {
300                    #pubkeys
301                }
302            });
303        } else {
304            tokens.extend(quote! {
305                pub fn #method() -> ::std::vec::Vec<#pubkey_type> {
306                    vec![#pubkeys]
307                }
308            });
309        }
310    }
311}
312
313#[proc_macro]
314pub fn pubkeys(input: TokenStream) -> TokenStream {
315    let pubkeys = parse_macro_input!(input as Pubkeys);
316    TokenStream::from(quote! {#pubkeys})
317}
318
319// Sets padding in structures to zero explicitly.
320// Otherwise padding could be inconsistent across the network and lead to divergence / consensus failures.
321#[proc_macro_derive(CloneZeroed)]
322pub fn derive_clone_zeroed(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
323    match parse_macro_input!(input as syn::Item) {
324        syn::Item::Struct(item_struct) => {
325            let clone_statements = match item_struct.fields {
326                syn::Fields::Named(ref fields) => fields.named.iter().map(|f| {
327                    let name = &f.ident;
328                    quote! {
329                        core::ptr::addr_of_mut!((*ptr).#name).write(self.#name);
330                    }
331                }),
332                _ => unimplemented!(),
333            };
334            let name = &item_struct.ident;
335            quote! {
336                impl Clone for #name {
337                    // Clippy lint `incorrect_clone_impl_on_copy_type` requires that clone
338                    // implementations on `Copy` types are simply wrappers of `Copy`.
339                    // This is not the case here, and intentionally so because we want to
340                    // guarantee zeroed padding.
341                    fn clone(&self) -> Self {
342                        let mut value = core::mem::MaybeUninit::<Self>::uninit();
343                        unsafe {
344                            core::ptr::write_bytes(&mut value, 0, 1);
345                            let ptr = value.as_mut_ptr();
346                            #(#clone_statements)*
347                            value.assume_init()
348                        }
349                    }
350                }
351            }
352        }
353        _ => unimplemented!(),
354    }
355    .into()
356}