anchor_syn/idl/
constant.rs

1use heck::SnakeCase;
2use proc_macro2::TokenStream;
3use quote::{format_ident, quote};
4
5use super::{
6    common::{gen_print_section, get_idl_module_path, get_no_docs},
7    defined::gen_idl_type,
8};
9use crate::parser::docs;
10
11pub fn gen_idl_print_fn_constant(item: &syn::ItemConst) -> TokenStream {
12    let idl = get_idl_module_path();
13    let no_docs = get_no_docs();
14
15    let name = item.ident.to_string();
16    let expr = &item.expr;
17    let fn_name = format_ident!("__anchor_private_print_idl_const_{}", name.to_snake_case());
18
19    let docs = match docs::parse(&item.attrs) {
20        Some(docs) if !no_docs => quote! { vec![#(#docs.into()),*] },
21        _ => quote! { vec![] },
22    };
23
24    let fn_body = match gen_idl_type(&item.ty, &[]) {
25        Ok((ty, _)) => gen_print_section(
26            "const",
27            quote! {
28                #idl::IdlConst {
29                    name: #name.into(),
30                    docs: #docs,
31                    ty: #ty,
32                    value: format!("{:?}", #expr),
33                }
34            },
35        ),
36        _ => quote! {},
37    };
38
39    quote! {
40        #[test]
41        pub fn #fn_name() {
42            #fn_body
43        }
44    }
45}