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
extern crate proc_macro;
use quote::quote;
use syn::parse_macro_input;
#[proc_macro_attribute]
pub fn account(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let namespace = args.to_string().replace("\"", "");
let is_zero_copy = match args.into_iter().next() {
None => false,
Some(tt) => match tt {
proc_macro::TokenTree::Literal(_) => false,
_ => namespace == "zero_copy",
},
};
let account_strct = parse_macro_input!(input as syn::ItemStruct);
let account_name = &account_strct.ident;
let discriminator: proc_macro2::TokenStream = {
let discriminator_preimage = {
if is_zero_copy || namespace.is_empty() {
format!("account:{}", account_name.to_string())
} else {
format!("{}:{}", namespace, account_name.to_string())
}
};
let mut discriminator = [0u8; 8];
discriminator.copy_from_slice(
&anchor_syn::hash::hash(discriminator_preimage.as_bytes()).to_bytes()[..8],
);
format!("{:?}", discriminator).parse().unwrap()
};
proc_macro::TokenStream::from({
if is_zero_copy {
quote! {
#[zero_copy]
#account_strct
unsafe impl anchor_lang::__private::bytemuck::Pod for #account_name {}
unsafe impl anchor_lang::__private::bytemuck::Zeroable for #account_name {}
impl anchor_lang::ZeroCopy for #account_name {}
impl anchor_lang::Discriminator for #account_name {
fn discriminator() -> [u8; 8] {
#discriminator
}
}
impl anchor_lang::AccountDeserialize for #account_name {
fn try_deserialize(buf: &mut &[u8]) -> std::result::Result<Self, ProgramError> {
if buf.len() < #discriminator.len() {
return Err(ProgramError::AccountDataTooSmall);
}
let given_disc = &buf[..8];
if &#discriminator != given_disc {
return Err(ProgramError::InvalidInstructionData);
}
Self::try_deserialize_unchecked(buf)
}
fn try_deserialize_unchecked(buf: &mut &[u8]) -> std::result::Result<Self, ProgramError> {
let data: &[u8] = &buf[8..];
let account = anchor_lang::__private::bytemuck::from_bytes(data);
Ok(*account)
}
}
}
} else {
quote! {
#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
#account_strct
impl anchor_lang::AccountSerialize for #account_name {
fn try_serialize<W: std::io::Write>(&self, writer: &mut W) -> std::result::Result<(), ProgramError> {
writer.write_all(&#discriminator).map_err(|_| ProgramError::InvalidAccountData)?;
AnchorSerialize::serialize(
self,
writer
)
.map_err(|_| ProgramError::InvalidAccountData)?;
Ok(())
}
}
impl anchor_lang::AccountDeserialize for #account_name {
fn try_deserialize(buf: &mut &[u8]) -> std::result::Result<Self, ProgramError> {
if buf.len() < #discriminator.len() {
return Err(ProgramError::AccountDataTooSmall);
}
let given_disc = &buf[..8];
if &#discriminator != given_disc {
return Err(ProgramError::InvalidInstructionData);
}
Self::try_deserialize_unchecked(buf)
}
fn try_deserialize_unchecked(buf: &mut &[u8]) -> std::result::Result<Self, ProgramError> {
let mut data: &[u8] = &buf[8..];
AnchorDeserialize::deserialize(&mut data)
.map_err(|_| ProgramError::InvalidAccountData)
}
}
impl anchor_lang::Discriminator for #account_name {
fn discriminator() -> [u8; 8] {
#discriminator
}
}
}
}
})
}
#[proc_macro_attribute]
pub fn associated(
args: proc_macro::TokenStream,
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let mut account_strct = parse_macro_input!(input as syn::ItemStruct);
let account_name = &account_strct.ident;
match &mut account_strct.fields {
syn::Fields::Named(fields) => {
let mut segments = syn::punctuated::Punctuated::new();
segments.push(syn::PathSegment {
ident: syn::Ident::new("u8", proc_macro2::Span::call_site()),
arguments: syn::PathArguments::None,
});
fields.named.push(syn::Field {
attrs: Vec::new(),
vis: syn::Visibility::Inherited,
ident: Some(syn::Ident::new("__nonce", proc_macro2::Span::call_site())),
colon_token: Some(syn::token::Colon {
spans: [proc_macro2::Span::call_site()],
}),
ty: syn::Type::Path(syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments,
},
}),
});
}
_ => panic!("Fields must be named"),
}
let args: proc_macro2::TokenStream = args.into();
proc_macro::TokenStream::from(quote! {
#[anchor_lang::account(#args)]
#[derive(Default)]
#account_strct
impl anchor_lang::Bump for #account_name {
fn seed(&self) -> u8 {
self.__nonce
}
}
})
}
#[proc_macro_derive(ZeroCopyAccessor, attributes(accessor))]
pub fn derive_zero_copy_accessor(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
let account_strct = parse_macro_input!(item as syn::ItemStruct);
let account_name = &account_strct.ident;
let fields = match &account_strct.fields {
syn::Fields::Named(n) => n,
_ => panic!("Fields must be named"),
};
let methods: Vec<proc_macro2::TokenStream> = fields
.named
.iter()
.filter_map(|field: &syn::Field| {
field
.attrs
.iter()
.filter(|attr| {
let name = anchor_syn::parser::tts_to_string(&attr.path);
if name != "accessor" {
return false;
}
return true;
})
.next()
.map(|attr| {
let mut tts = attr.tokens.clone().into_iter();
let g_stream = match tts.next().expect("Must have a token group") {
proc_macro2::TokenTree::Group(g) => g.stream(),
_ => panic!("Invalid syntax"),
};
let accessor_ty = match g_stream.into_iter().next() {
Some(token) => token,
_ => panic!("Missing accessor type"),
};
let field_name = field.ident.as_ref().unwrap();
let get_field: proc_macro2::TokenStream =
format!("get_{}", field_name.to_string()).parse().unwrap();
let set_field: proc_macro2::TokenStream =
format!("set_{}", field_name.to_string()).parse().unwrap();
quote! {
pub fn #get_field(&self) -> #accessor_ty {
anchor_lang::__private::ZeroCopyAccessor::get(&self.#field_name)
}
pub fn #set_field(&mut self, input: &#accessor_ty) {
self.#field_name = anchor_lang::__private::ZeroCopyAccessor::set(input);
}
}
})
})
.collect();
proc_macro::TokenStream::from(quote! {
impl #account_name {
#(#methods)*
}
})
}
#[proc_macro_attribute]
pub fn zero_copy(
_args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let account_strct = parse_macro_input!(item as syn::ItemStruct);
proc_macro::TokenStream::from(quote! {
#[derive(anchor_lang::__private::ZeroCopyAccessor, Copy, Clone)]
#[repr(packed)]
#account_strct
})
}