shank-parse-macro 2.0.0

Internal proc-macro implementation for shank-parse — generates Rust client code from Shank/Anchor IDL JSON files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::idl::*;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::{format_ident, quote};
use std::collections::HashMap;

pub fn generate(idl: &Idl, program_id_bytes: Option<[u8; 32]>) -> TokenStream {
    let mod_name = format_ident!("{}", idl.name);

    // Map every named (defined-able) type to the submodule it is generated into,
    // so cross-module references can be emitted as `super::<mod>::<Name>` paths.
    let module_of = build_module_map(idl);

    // Program ID constant (directly in the program module, not in a submodule)
    let id_token = program_id_bytes
        .map(|b| gen_program_id(&b))
        .unwrap_or_default();

    // types submodule: every entry from the IDL `types` section. Field-less
    // enums become "domain" enums (with `from_u8` / `to_u8`); enums with data
    // variants and all structs are emitted as borsh types. Everything derives
    // borsh and gets an inherent `try_from_slice`.
    let mut types_tokens = TokenStream::new();
    for ty in &idl.types {
        if ty.ty.kind == "enum" {
            if ty.ty.variants.iter().all(|v| v.fields.is_empty()) {
                types_tokens.extend(gen_domain_enum(ty));
            } else {
                types_tokens.extend(gen_data_enum(ty, &module_of));
            }
        } else {
            types_tokens.extend(gen_data_struct(ty, &module_of));
        }
    }

    // accounts submodule: account structs
    let accounts_tokens: TokenStream = idl
        .accounts
        .iter()
        .map(|a| gen_account(a, &module_of))
        .collect();

    // instructions submodule: instruction builder functions + their Accounts
    // structs (argument types live in the `types` submodule).
    let mut instructions_tokens = TokenStream::new();
    for ix in &idl.instructions {
        instructions_tokens.extend(gen_instruction(ix, &module_of));
    }

    // errors submodule: error code constants
    let errors_tokens: TokenStream = idl.errors.iter().map(gen_error).collect();

    // Only emit submodules that have content
    let types_mod = wrap_mod("types", types_tokens);
    let accounts_mod = wrap_mod("accounts", accounts_tokens);
    let instructions_mod = wrap_mod("instructions", instructions_tokens);
    let errors_mod = wrap_mod("errors", errors_tokens);

    quote! {
        pub mod #mod_name {
            #id_token
            #types_mod
            #accounts_mod
            #instructions_mod
            #errors_mod
        }
    }
}

fn wrap_mod(name: &str, tokens: TokenStream) -> TokenStream {
    if tokens.is_empty() {
        return quote! {};
    }
    let ident = format_ident!("{}", name);
    quote! { pub mod #ident { #tokens } }
}

/// name -> submodule it is generated into. Accounts live in `accounts`,
/// everything from the IDL `types` section lives in `types`.
fn build_module_map(idl: &Idl) -> HashMap<&str, &'static str> {
    let mut map: HashMap<&str, &'static str> = HashMap::new();
    for a in &idl.accounts {
        map.insert(a.name.as_str(), "accounts");
    }
    for t in &idl.types {
        map.insert(t.name.as_str(), "types");
    }
    map
}

fn gen_program_id(bytes: &[u8; 32]) -> TokenStream {
    let byte_literals: Vec<Literal> = bytes.iter().map(|b| Literal::u8_unsuffixed(*b)).collect();
    quote! {
        #[allow(dead_code)]
        pub const ID: ::shank_parse::__private::Pubkey =
            ::shank_parse::__private::Pubkey::new_from_array([#(#byte_literals),*]);
    }
}

/// `#[derive(...)]` line shared by every borsh-(de)serializable generated type.
/// borsh is reached through the `shank_parse` re-export, so the consuming crate
/// does not need its own borsh dependency.
fn borsh_derive() -> TokenStream {
    quote! {
        #[derive(
            Debug,
            Clone,
            PartialEq,
            ::shank_parse::__private::borsh::BorshSerialize,
            ::shank_parse::__private::borsh::BorshDeserialize,
        )]
        #[borsh(crate = "::shank_parse::__private::borsh")]
        #[allow(dead_code)]
    }
}

/// Generate a field-less ("domain") enum. It derives borsh (a field-less enum
/// serializes as a single u8 variant tag) and gets `from_u8` / `to_u8` helpers
/// plus the shared `try_from_slice`.
fn gen_domain_enum(ty: &IdlTypeDef) -> TokenStream {
    let name = format_ident!("{}", ty.name);
    let derive = borsh_derive();

    let variants: Vec<Ident> = ty
        .ty
        .variants
        .iter()
        .map(|v| format_ident!("{}", v.name))
        .collect();

    let from_u8_arms: Vec<TokenStream> = ty
        .ty
        .variants
        .iter()
        .enumerate()
        .map(|(i, v)| {
            let disc = Literal::u8_unsuffixed(i as u8);
            let vname = format_ident!("{}", v.name);
            quote! { #disc => Some(Self::#vname), }
        })
        .collect();

    let to_u8_arms: Vec<TokenStream> = ty
        .ty
        .variants
        .iter()
        .enumerate()
        .map(|(i, v)| {
            let disc = Literal::u8_unsuffixed(i as u8);
            let vname = format_ident!("{}", v.name);
            quote! { Self::#vname => #disc, }
        })
        .collect();

    let try_from_slice = gen_try_from_slice_impl(&name);

    quote! {
        #derive
        pub enum #name {
            #(#variants,)*
        }

        impl #name {
            #[allow(dead_code)]
            pub fn from_u8(v: u8) -> Option<Self> {
                match v {
                    #(#from_u8_arms)*
                    _ => None,
                }
            }

            #[allow(dead_code)]
            pub fn to_u8(&self) -> u8 {
                match self {
                    #(#to_u8_arms)*
                }
            }
        }

        #try_from_slice
    }
}

/// Generate an enum with data-carrying variants. Each variant's `defined`
/// fields become a tuple variant; field-less variants stay unit. Borsh tags the
/// variant with its declaration-order index as a leading u8.
fn gen_data_enum(ty: &IdlTypeDef, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    let name = format_ident!("{}", ty.name);
    let derive = borsh_derive();

    let variants = ty.ty.variants.iter().map(|v| {
        let vname = format_ident!("{}", v.name);
        if v.fields.is_empty() {
            quote! { #vname }
        } else {
            let types = v.fields.iter().map(|f| defined_path(&f.defined, module_of));
            quote! { #vname(#(#types),*) }
        }
    });

    let try_from_slice = gen_try_from_slice_impl(&name);

    quote! {
        #derive
        pub enum #name {
            #(#variants,)*
        }

        #try_from_slice
    }
}

/// Generate an error constant: `pub const NOT_ADMIN: u32 = 0;`
fn gen_error(err: &IdlError) -> TokenStream {
    let snake = to_snake_case(&err.name);
    let const_name = format_ident!("{}", snake.to_uppercase());
    let code = Literal::u32_unsuffixed(err.code);
    quote! {
        #[allow(dead_code)]
        pub const #const_name: u32 = #code;
    }
}

/// A data struct from the IDL `types` section. Derives borsh and gets the
/// shared `try_from_slice`.
fn gen_data_struct(ty: &IdlTypeDef, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    let name = format_ident!("{}", ty.name);
    let derive = borsh_derive();
    let fields = gen_struct_fields(&ty.ty.fields, module_of);
    let try_from_slice = gen_try_from_slice_impl(&name);

    quote! {
        #derive
        pub struct #name {
            #(#fields,)*
        }

        #try_from_slice
    }
}

fn gen_account(acc: &IdlTypeDef, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    let name = format_ident!("{}", acc.name);
    let derive = borsh_derive();
    let fields = gen_struct_fields(&acc.ty.fields, module_of);

    quote! {
        #derive
        pub struct #name {
            #(#fields,)*
        }

        impl #name {
            /// Deserialize this account from raw account data. Trailing bytes
            /// (e.g. zero padding) after the struct are ignored.
            #[allow(dead_code)]
            pub fn from_account_data(data: &[u8]) -> ::std::io::Result<Self> {
                let mut buf: &[u8] = data;
                <Self as ::shank_parse::__private::borsh::BorshDeserialize>::deserialize_reader(
                    &mut buf,
                )
            }
        }
    }
}

fn gen_instruction(ix: &IdlInstruction, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    let accounts_struct_name = format_ident!("{}Accounts", ix.name);
    let fn_name = format_ident!("{}", to_snake_case(&ix.name));
    let disc_val = Literal::u8_unsuffixed(ix.discriminant.value);
    let derive = borsh_derive();

    // Accounts struct fields
    let acc_fields = ix.accounts.iter().map(|a| {
        let fname = format_ident!("{}", to_snake_case(&a.name));
        quote! { pub #fname: ::shank_parse::__private::Pubkey }
    });

    // AccountMeta list
    let account_metas = ix.accounts.iter().map(|a| {
        let fname = format_ident!("{}", to_snake_case(&a.name));
        let is_signer = a.is_signer;
        if a.is_mut {
            quote! { ::shank_parse::__private::AccountMeta::new(accounts.#fname, #is_signer) }
        } else {
            quote! { ::shank_parse::__private::AccountMeta::new_readonly(accounts.#fname, #is_signer) }
        }
    });

    // Args: function params + borsh serialization (errors are propagated, never
    // unwrapped/expected).
    let mut arg_params = Vec::new();
    let mut arg_ser = Vec::new();
    for arg in &ix.args {
        let arg_name = format_ident!("{}", to_snake_case(&arg.name));
        let rust_ty = rust_type(&arg.ty, module_of);
        // `defined` args are passed by reference (they are usually structs);
        // everything else is passed by value. `receiver` is always `&T`.
        let (param, receiver) =
            if matches!(arg.ty, IdlType::Complex(IdlTypeComplex::Defined { .. })) {
                (quote! { #arg_name: &#rust_ty }, quote! { #arg_name })
            } else {
                (quote! { #arg_name: #rust_ty }, quote! { &#arg_name })
            };
        arg_params.push(param);
        arg_ser.push(quote! {
            ::shank_parse::__private::borsh::BorshSerialize::serialize(#receiver, &mut data)?;
        });
    }

    quote! {
        #derive
        pub struct #accounts_struct_name {
            #(#acc_fields,)*
        }

        #[allow(dead_code)]
        #[allow(clippy::too_many_arguments)]
        pub fn #fn_name(
            program_id: &::shank_parse::__private::Pubkey,
            accounts: &#accounts_struct_name,
            #(#arg_params,)*
        ) -> ::std::result::Result<::shank_parse::__private::Instruction, ::std::io::Error> {
            let mut data: Vec<u8> = ::std::vec![#disc_val];
            #(#arg_ser)*
            let account_metas = ::std::vec![
                #(#account_metas,)*
            ];
            Ok(::shank_parse::__private::Instruction::new_with_bytes(
                *program_id,
                &data,
                account_metas,
            ))
        }
    }
}

/// Inherent `try_from_slice` decoding a value from a borsh-encoded byte slice.
/// Returns `Result<Self, std::io::Error>` — no panics.
fn gen_try_from_slice_impl(name: &Ident) -> TokenStream {
    quote! {
        impl #name {
            #[allow(dead_code)]
            pub fn try_from_slice(data: &[u8]) -> ::std::io::Result<Self> {
                ::shank_parse::__private::borsh::from_slice(data)
            }
        }
    }
}

// ─── Helper generators ───────────────────────────────────────────────────────

fn gen_struct_fields(
    fields: &[IdlField],
    module_of: &HashMap<&str, &'static str>,
) -> Vec<TokenStream> {
    fields
        .iter()
        .map(|f| {
            let fname = format_ident!("{}", to_snake_case(&f.name));
            let ftype = rust_type(&f.ty, module_of);
            quote! { pub #fname: #ftype }
        })
        .collect()
}

/// Resolve a `defined` type name to a fully-qualified `super::<mod>::<Name>`
/// path. Falls back to a bare ident if the name is unknown.
fn defined_path(name: &str, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    let ident = format_ident!("{}", name);
    match module_of.get(name) {
        Some(module) => {
            let module = format_ident!("{}", module);
            quote! { super::#module::#ident }
        }
        None => quote! { #ident },
    }
}

fn rust_type(ty: &IdlType, module_of: &HashMap<&str, &'static str>) -> TokenStream {
    match ty {
        IdlType::Primitive(p) => {
            let ident = format_ident!("{}", p);
            quote! { #ident }
        }
        IdlType::Complex(IdlTypeComplex::Array { array: (elem, size) }) => {
            let elem_ty = rust_type(elem, module_of);
            let size_lit = Literal::usize_unsuffixed(*size);
            quote! { [#elem_ty; #size_lit] }
        }
        IdlType::Complex(IdlTypeComplex::Defined { defined }) => defined_path(defined, module_of),
        IdlType::Complex(IdlTypeComplex::Option { option }) => {
            let inner = rust_type(option, module_of);
            quote! { Option<#inner> }
        }
    }
}

pub fn to_snake_case(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        for lc in c.to_lowercase() {
            result.push(lc);
        }
    }
    result
}