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
//! DSL syntax tokens.

#[cfg(feature = "idl")]
use crate::idl::{IdlAccount, IdlAccountItem, IdlAccounts};
use anyhow::Result;
#[cfg(feature = "idl")]
use heck::MixedCase;
use quote::quote;
use std::collections::HashMap;

pub mod codegen;
#[cfg(feature = "hash")]
pub mod hash;
#[cfg(not(feature = "hash"))]
pub(crate) mod hash;
#[cfg(feature = "idl")]
pub mod idl;
pub mod parser;

#[derive(Debug)]
pub struct Program {
    pub state: Option<State>,
    pub ixs: Vec<Ix>,
    pub name: syn::Ident,
    pub program_mod: syn::ItemMod,
}

// State struct singleton.
#[derive(Debug)]
pub struct State {
    pub name: String,
    pub strct: syn::ItemStruct,
    pub ctor_and_anchor: Option<(syn::ImplItemMethod, syn::Ident)>,
    pub impl_block_and_methods: Option<(syn::ItemImpl, Vec<StateIx>)>,
    pub interfaces: Option<Vec<StateInterface>>,
}

#[derive(Debug)]
pub struct StateIx {
    pub raw_method: syn::ImplItemMethod,
    pub ident: syn::Ident,
    pub args: Vec<IxArg>,
    pub anchor_ident: syn::Ident,
    // True if there exists a &self on the method.
    pub has_receiver: bool,
}

#[derive(Debug)]
pub struct StateInterface {
    pub trait_name: String,
    pub methods: Vec<StateIx>,
}

#[derive(Debug)]
pub struct Ix {
    pub raw_method: syn::ItemFn,
    pub ident: syn::Ident,
    pub args: Vec<IxArg>,
    // The ident for the struct deriving Accounts.
    pub anchor_ident: syn::Ident,
}

#[derive(Debug)]
pub struct IxArg {
    pub name: proc_macro2::Ident,
    pub raw_arg: syn::PatType,
}

#[derive(Debug)]
pub struct AccountsStruct {
    // Name of the accounts struct.
    pub ident: syn::Ident,
    // Generics + lifetimes on the accounts struct.
    pub generics: syn::Generics,
    // Fields on the accounts struct.
    pub fields: Vec<AccountField>,
}

impl AccountsStruct {
    pub fn new(strct: syn::ItemStruct, fields: Vec<AccountField>) -> Self {
        let ident = strct.ident.clone();
        let generics = strct.generics.clone();
        Self {
            ident,
            generics,
            fields,
        }
    }

    // Returns all program owned accounts in the Accounts struct.
    //
    // `global_accs` is given to "link" account types that are embedded
    // in each other.
    pub fn account_tys(
        &self,
        global_accs: &HashMap<String, AccountsStruct>,
    ) -> Result<Vec<String>> {
        let mut tys = vec![];
        for f in &self.fields {
            match f {
                AccountField::Field(f) => {
                    if let Ty::ProgramAccount(pty) = &f.ty {
                        tys.push(pty.account_ident.to_string());
                    }
                }
                AccountField::AccountsStruct(comp_f) => {
                    let accs = global_accs.get(&comp_f.symbol).ok_or(anyhow::format_err!(
                        "Invalid account type: {}",
                        comp_f.symbol
                    ))?;
                    tys.extend(accs.account_tys(global_accs)?);
                }
            }
        }
        Ok(tys)
    }

    #[cfg(feature = "idl")]
    pub fn idl_accounts(
        &self,
        global_accs: &HashMap<String, AccountsStruct>,
    ) -> Vec<IdlAccountItem> {
        self.fields
            .iter()
            .map(|acc: &AccountField| match acc {
                AccountField::AccountsStruct(comp_f) => {
                    let accs_strct = global_accs
                        .get(&comp_f.symbol)
                        .expect("Could not reslve Accounts symbol");
                    let accounts = accs_strct.idl_accounts(global_accs);
                    IdlAccountItem::IdlAccounts(IdlAccounts {
                        name: comp_f.ident.to_string().to_mixed_case(),
                        accounts,
                    })
                }
                AccountField::Field(acc) => IdlAccountItem::IdlAccount(IdlAccount {
                    name: acc.ident.to_string().to_mixed_case(),
                    is_mut: acc.is_mut,
                    is_signer: acc.is_signer,
                }),
            })
            .collect::<Vec<_>>()
    }
}

#[derive(Debug)]
pub enum AccountField {
    // Use a `String` instead of the `AccountsStruct` because all
    // accounts structs aren't visible to a single derive macro.
    //
    // When we need the global context, we fill in the String with the
    // appropriate values. See, `account_tys` as an example.
    AccountsStruct(CompositeField), // Composite
    Field(Field),                   // Primitive
}

#[derive(Debug)]
pub struct CompositeField {
    pub ident: syn::Ident,
    pub symbol: String,
    pub constraints: Vec<Constraint>,
    pub raw_field: syn::Field,
}

// An account in the accounts struct.
#[derive(Debug)]
pub struct Field {
    pub ident: syn::Ident,
    pub ty: Ty,
    pub constraints: Vec<Constraint>,
    pub is_mut: bool,
    pub is_signer: bool,
    pub is_init: bool,
}

impl Field {
    pub fn typed_ident(&self) -> proc_macro2::TokenStream {
        let name = &self.ident;

        let ty = match &self.ty {
            Ty::AccountInfo => quote! { AccountInfo },
            Ty::ProgramState(ty) => {
                let account = &ty.account_ident;
                quote! {
                    ProgramState<#account>
                }
            }
            Ty::ProgramAccount(ty) => {
                let account = &ty.account_ident;
                quote! {
                    ProgramAccount<#account>
                }
            }
            Ty::CpiAccount(ty) => {
                let account = &ty.account_ident;
                quote! {
                    CpiAccount<#account>
                }
            }
            Ty::Sysvar(ty) => {
                let account = match ty {
                    SysvarTy::Clock => quote! {Clock},
                    SysvarTy::Rent => quote! {Rent},
                    SysvarTy::EpochSchedule => quote! {EpochSchedule},
                    SysvarTy::Fees => quote! {Fees},
                    SysvarTy::RecentBlockHashes => quote! {RecentBlockHashes},
                    SysvarTy::SlotHashes => quote! {SlotHashes},
                    SysvarTy::SlotHistory => quote! {SlotHistory},
                    SysvarTy::StakeHistory => quote! {StakeHistory},
                    SysvarTy::Instructions => quote! {Instructions},
                    SysvarTy::Rewards => quote! {Rewards},
                };
                quote! {
                    Sysvar<#account>
                }
            }
        };

        quote! {
            #name: #ty
        }
    }
}

// A type of an account field.
#[derive(Debug, PartialEq)]
pub enum Ty {
    AccountInfo,
    ProgramState(ProgramStateTy),
    ProgramAccount(ProgramAccountTy),
    CpiAccount(CpiAccountTy),
    Sysvar(SysvarTy),
}

#[derive(Debug, PartialEq)]
pub enum SysvarTy {
    Clock,
    Rent,
    EpochSchedule,
    Fees,
    RecentBlockHashes,
    SlotHashes,
    SlotHistory,
    StakeHistory,
    Instructions,
    Rewards,
}

#[derive(Debug, PartialEq)]
pub struct ProgramStateTy {
    pub account_ident: syn::Ident,
}

#[derive(Debug, PartialEq)]
pub struct ProgramAccountTy {
    // The struct type of the account.
    pub account_ident: syn::Ident,
}

#[derive(Debug, PartialEq)]
pub struct CpiAccountTy {
    // The struct type of the account.
    pub account_ident: syn::Ident,
}

// An access control constraint for an account.
#[derive(Debug)]
pub enum Constraint {
    Signer(ConstraintSigner),
    BelongsTo(ConstraintBelongsTo),
    Literal(ConstraintLiteral),
    Owner(ConstraintOwner),
    RentExempt(ConstraintRentExempt),
    Seeds(ConstraintSeeds),
}

#[derive(Debug)]
pub struct ConstraintBelongsTo {
    pub join_target: proc_macro2::Ident,
}

#[derive(Debug)]
pub struct ConstraintSigner {}

#[derive(Debug)]
pub struct ConstraintLiteral {
    pub tokens: proc_macro2::TokenStream,
}

#[derive(Debug)]
pub enum ConstraintOwner {
    Program,
    Skip,
}

#[derive(Debug)]
pub enum ConstraintRentExempt {
    Enforce,
    Skip,
}

#[derive(Debug)]
pub struct ConstraintSeeds {
    pub seeds: proc_macro2::Group,
}

#[derive(Debug)]
pub struct Error {
    pub name: String,
    pub raw_enum: syn::ItemEnum,
    pub ident: syn::Ident,
    pub codes: Vec<ErrorCode>,
}

#[derive(Debug)]
pub struct ErrorCode {
    pub id: u32,
    pub ident: syn::Ident,
    pub msg: Option<String>,
}