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
use crate::parser;
use crate::parser::docs;
use crate::parser::program::ctx_accounts_ident;
use crate::{IxArg, State, StateInterface, StateIx};
use syn::parse::{Error as ParseError, Result as ParseResult};
use syn::spanned::Spanned;
// Name of the attribute denoting a state struct.
const STATE_STRUCT_ATTRIBUTE: &str = "state";
// Reserved keyword for the constructor method.
const CTOR_METHOD_NAME: &str = "new";
// Parse the state from the program mod definition.
pub fn parse(program_mod: &syn::ItemMod) -> ParseResult<Option<State>> {
let mod_content = &program_mod
.content
.as_ref()
.ok_or_else(|| ParseError::new(program_mod.span(), "program content not provided"))?
.1;
// Parse `struct` marked with the `#[state]` attribute.
let strct: Option<(&syn::ItemStruct, bool)> = mod_content
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item_strct) => {
let attrs = &item_strct.attrs;
if attrs.is_empty() {
return None;
}
let attr_label = attrs[0].path.get_ident().map(|i| i.to_string());
if attr_label != Some(STATE_STRUCT_ATTRIBUTE.to_string()) {
return None;
}
let is_zero_copy = parser::tts_to_string(&attrs[0].tokens) == "(zero_copy)";
Some((item_strct, is_zero_copy))
}
_ => None,
})
.next();
// Parse `impl` block for the state struct.
let impl_block: Option<syn::ItemImpl> = match strct {
None => None,
Some((strct, _)) => mod_content
.iter()
.filter_map(|item| match item {
syn::Item::Impl(item_impl) => {
let impl_ty_str = parser::tts_to_string(&item_impl.self_ty);
let strct_name = strct.ident.to_string();
if item_impl.trait_.is_some() {
return None;
}
if strct_name != impl_ty_str {
return None;
}
Some(item_impl.clone())
}
_ => None,
})
.next(),
};
// Parse ctor and the generic type in `Context<MY-TYPE>`.
let ctor_and_anchor: Option<(syn::ImplItemMethod, syn::Ident)> = impl_block
.as_ref()
.map(|impl_block| {
let r: Option<ParseResult<_>> = impl_block
.items
.iter()
.filter_map(|item: &syn::ImplItem| match item {
syn::ImplItem::Method(m) => match m.sig.ident == CTOR_METHOD_NAME {
false => None,
true => Some(m),
},
_ => None,
})
.map(|m: &syn::ImplItemMethod| {
let (_, is_zero_copy) = strct
.as_ref()
.expect("impl_block exists therefore the struct exists");
let ctx_arg = {
if *is_zero_copy {
// Second param is context.
let mut iter = m.sig.inputs.iter();
match iter.next() {
None => {
return Err(ParseError::new(
m.sig.span(),
"first parameter must be &mut self",
))
}
Some(arg) => match arg {
syn::FnArg::Receiver(r) => {
if r.mutability.is_none() {
return Err(ParseError::new(
m.sig.span(),
"first parameter must be &mut self",
));
}
}
syn::FnArg::Typed(_) => {
return Err(ParseError::new(
m.sig.span(),
"first parameter must be &mut self",
))
}
},
};
match iter.next() {
None => {
return Err(ParseError::new(
m.sig.span(),
"second parameter must be the Context",
))
}
Some(ctx_arg) => match ctx_arg {
syn::FnArg::Receiver(_) => {
return Err(ParseError::new(
ctx_arg.span(),
"second parameter must be the Context",
))
}
syn::FnArg::Typed(arg) => arg,
},
}
} else {
match m.sig.inputs.first() {
None => {
return Err(ParseError::new(
m.sig.span(),
"first parameter must be the Context",
))
}
Some(ctx_arg) => match ctx_arg {
syn::FnArg::Receiver(_) => {
return Err(ParseError::new(
ctx_arg.span(),
"second parameter must be the Context",
))
}
syn::FnArg::Typed(arg) => arg,
},
}
}
};
Ok((m.clone(), ctx_accounts_ident(ctx_arg)?))
})
.next();
r.transpose()
})
.transpose()?
.unwrap_or(None);
// Parse all methods in the above `impl` block.
let methods: Option<Vec<StateIx>> = impl_block
.as_ref()
.map(|impl_block| {
impl_block
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Method(m) => match m.sig.ident != CTOR_METHOD_NAME {
false => None,
true => Some(m),
},
_ => None,
})
.map(|m: &syn::ImplItemMethod| {
let mut args = m
.sig
.inputs
.iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(arg) => Some(arg),
})
.map(|raw_arg| {
let docs = docs::parse(&raw_arg.attrs);
let ident = match &*raw_arg.pat {
syn::Pat::Ident(ident) => &ident.ident,
_ => {
return Err(ParseError::new(
raw_arg.pat.span(),
"unexpected type argument",
))
}
};
Ok(IxArg {
name: ident.clone(),
docs,
raw_arg: raw_arg.clone(),
})
})
.collect::<ParseResult<Vec<IxArg>>>()?;
// Remove the Anchor accounts argument
let anchor = args.remove(0);
let anchor_ident = ctx_accounts_ident(&anchor.raw_arg)?;
Ok(StateIx {
raw_method: m.clone(),
ident: m.sig.ident.clone(),
args,
anchor_ident,
has_receiver: true,
})
})
.collect::<ParseResult<Vec<_>>>()
})
.transpose()?;
// Parse all trait implementations for the above `#[state]` struct.
let trait_impls: Option<Vec<StateInterface>> = strct
.map(|_strct| {
mod_content
.iter()
.filter_map(|item| match item {
syn::Item::Impl(item_impl) => match &item_impl.trait_ {
None => None,
Some((_, path, _)) => {
let trait_name = path
.segments
.iter()
.next()
.expect("Must have one segment in a path")
.ident
.clone()
.to_string();
Some((item_impl, trait_name))
}
},
_ => None,
})
.map(|(item_impl, trait_name)| {
let methods = item_impl
.items
.iter()
.filter_map(|item: &syn::ImplItem| match item {
syn::ImplItem::Method(m) => Some(m),
_ => None,
})
.map(|m: &syn::ImplItemMethod| {
match m.sig.inputs.first() {
None => Err(ParseError::new(
m.sig.inputs.span(),
"state methods must have a self argument",
)),
Some(_arg) => {
let mut has_receiver = false;
let mut args = m
.sig
.inputs
.iter()
.filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => {
has_receiver = true;
None
}
syn::FnArg::Typed(arg) => Some(arg),
})
.map(|raw_arg| {
let docs = docs::parse(&raw_arg.attrs);
let ident = match &*raw_arg.pat {
syn::Pat::Ident(ident) => &ident.ident,
_ => panic!("invalid syntax"),
};
IxArg {
name: ident.clone(),
docs,
raw_arg: raw_arg.clone(),
}
})
.collect::<Vec<IxArg>>();
// Remove the Anchor accounts argument
let anchor = args.remove(0);
let anchor_ident = ctx_accounts_ident(&anchor.raw_arg)?;
Ok(StateIx {
raw_method: m.clone(),
ident: m.sig.ident.clone(),
args,
anchor_ident,
has_receiver,
})
}
}
})
.collect::<ParseResult<Vec<StateIx>>>()?;
Ok(StateInterface {
trait_name,
methods,
})
})
.collect::<ParseResult<Vec<StateInterface>>>()
})
.transpose()?;
Ok(strct.map(|(strct, is_zero_copy)| {
// Chop off the `#[state]` attribute. It's just a marker.
//
// TODO: instead of mutating the syntax, we should just implement
// a macro that does nothing.
let mut strct = strct.clone();
strct.attrs = vec![];
State {
name: strct.ident.to_string(),
strct,
interfaces: trait_impls,
impl_block_and_methods: impl_block.map(|impl_block| (impl_block, methods.unwrap())),
ctor_and_anchor,
is_zero_copy,
}
}))
}