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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use super::helper;
use frame_support_procedural_tools::get_doc_literals;
use quote::ToTokens;
use std::collections::HashMap;
use syn::spanned::Spanned;
mod keyword {
syn::custom_keyword!(Error);
syn::custom_keyword!(pallet);
syn::custom_keyword!(getter);
syn::custom_keyword!(storage_prefix);
syn::custom_keyword!(unbounded);
syn::custom_keyword!(OptionQuery);
syn::custom_keyword!(ValueQuery);
}
pub enum PalletStorageAttr {
Getter(syn::Ident, proc_macro2::Span),
StorageName(syn::LitStr, proc_macro2::Span),
Unbounded(proc_macro2::Span),
}
impl PalletStorageAttr {
fn attr_span(&self) -> proc_macro2::Span {
match self {
Self::Getter(_, span) | Self::StorageName(_, span) | Self::Unbounded(span) => *span,
}
}
}
impl syn::parse::Parse for PalletStorageAttr {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
input.parse::<syn::Token![#]>()?;
let attr_span = input.span();
let content;
syn::bracketed!(content in input);
content.parse::<keyword::pallet>()?;
content.parse::<syn::Token![::]>()?;
let lookahead = content.lookahead1();
if lookahead.peek(keyword::getter) {
content.parse::<keyword::getter>()?;
let generate_content;
syn::parenthesized!(generate_content in content);
generate_content.parse::<syn::Token![fn]>()?;
Ok(Self::Getter(generate_content.parse::<syn::Ident>()?, attr_span))
} else if lookahead.peek(keyword::storage_prefix) {
content.parse::<keyword::storage_prefix>()?;
content.parse::<syn::Token![=]>()?;
let renamed_prefix = content.parse::<syn::LitStr>()?;
syn::parse_str::<syn::Ident>(&renamed_prefix.value()).map_err(|_| {
let msg = format!("`{}` is not a valid identifier", renamed_prefix.value());
syn::Error::new(renamed_prefix.span(), msg)
})?;
Ok(Self::StorageName(renamed_prefix, attr_span))
} else if lookahead.peek(keyword::unbounded) {
content.parse::<keyword::unbounded>()?;
Ok(Self::Unbounded(attr_span))
} else {
Err(lookahead.error())
}
}
}
struct PalletStorageAttrInfo {
getter: Option<syn::Ident>,
rename_as: Option<syn::LitStr>,
unbounded: bool,
}
impl PalletStorageAttrInfo {
fn from_attrs(attrs: Vec<PalletStorageAttr>) -> syn::Result<Self> {
let mut getter = None;
let mut rename_as = None;
let mut unbounded = false;
for attr in attrs {
match attr {
PalletStorageAttr::Getter(ident, ..) if getter.is_none() => getter = Some(ident),
PalletStorageAttr::StorageName(name, ..) if rename_as.is_none() =>
rename_as = Some(name),
PalletStorageAttr::Unbounded(..) if !unbounded => unbounded = true,
attr =>
return Err(syn::Error::new(
attr.attr_span(),
"Invalid attribute: Duplicate attribute",
)),
}
}
Ok(PalletStorageAttrInfo { getter, rename_as, unbounded })
}
}
pub enum Metadata {
Value { value: syn::Type },
Map { value: syn::Type, key: syn::Type },
CountedMap { value: syn::Type, key: syn::Type },
DoubleMap { value: syn::Type, key1: syn::Type, key2: syn::Type },
NMap { keys: Vec<syn::Type>, keygen: syn::Type, value: syn::Type },
}
pub enum QueryKind {
OptionQuery,
ValueQuery,
}
pub struct StorageDef {
pub index: usize,
pub vis: syn::Visibility,
pub ident: syn::Ident,
pub metadata: Metadata,
pub docs: Vec<syn::Lit>,
pub instances: Vec<helper::InstanceUsage>,
pub getter: Option<syn::Ident>,
pub rename_as: Option<syn::LitStr>,
pub query_kind: Option<QueryKind>,
pub where_clause: Option<syn::WhereClause>,
pub attr_span: proc_macro2::Span,
pub cfg_attrs: Vec<syn::Attribute>,
pub named_generics: Option<StorageGenerics>,
pub unbounded: bool,
}
#[derive(Clone)]
pub enum StorageGenerics {
DoubleMap {
hasher1: syn::Type,
key1: syn::Type,
hasher2: syn::Type,
key2: syn::Type,
value: syn::Type,
query_kind: Option<syn::Type>,
on_empty: Option<syn::Type>,
max_values: Option<syn::Type>,
},
Map {
hasher: syn::Type,
key: syn::Type,
value: syn::Type,
query_kind: Option<syn::Type>,
on_empty: Option<syn::Type>,
max_values: Option<syn::Type>,
},
CountedMap {
hasher: syn::Type,
key: syn::Type,
value: syn::Type,
query_kind: Option<syn::Type>,
on_empty: Option<syn::Type>,
max_values: Option<syn::Type>,
},
Value {
value: syn::Type,
query_kind: Option<syn::Type>,
on_empty: Option<syn::Type>,
},
NMap {
keygen: syn::Type,
value: syn::Type,
query_kind: Option<syn::Type>,
on_empty: Option<syn::Type>,
max_values: Option<syn::Type>,
},
}
impl StorageGenerics {
fn metadata(&self) -> syn::Result<Metadata> {
let res = match self.clone() {
Self::DoubleMap { value, key1, key2, .. } => Metadata::DoubleMap { value, key1, key2 },
Self::Map { value, key, .. } => Metadata::Map { value, key },
Self::CountedMap { value, key, .. } => Metadata::CountedMap { value, key },
Self::Value { value, .. } => Metadata::Value { value },
Self::NMap { keygen, value, .. } =>
Metadata::NMap { keys: collect_keys(&keygen)?, keygen, value },
};
Ok(res)
}
fn query_kind(&self) -> Option<syn::Type> {
match &self {
Self::DoubleMap { query_kind, .. } |
Self::Map { query_kind, .. } |
Self::CountedMap { query_kind, .. } |
Self::Value { query_kind, .. } |
Self::NMap { query_kind, .. } => query_kind.clone(),
}
}
}
enum StorageKind {
Value,
Map,
CountedMap,
DoubleMap,
NMap,
}
fn check_generics(
map: &HashMap<String, syn::Binding>,
mandatory_generics: &[&str],
optional_generics: &[&str],
storage_type_name: &str,
args_span: proc_macro2::Span,
) -> syn::Result<()> {
let mut errors = vec![];
let expectation = {
let mut e = format!(
"`{}` expect generics {}and optional generics {}",
storage_type_name,
mandatory_generics
.iter()
.map(|name| format!("`{}`, ", name))
.collect::<String>(),
&optional_generics.iter().map(|name| format!("`{}`, ", name)).collect::<String>(),
);
e.pop();
e.pop();
e.push_str(".");
e
};
for (gen_name, gen_binding) in map {
if !mandatory_generics.contains(&gen_name.as_str()) &&
!optional_generics.contains(&gen_name.as_str())
{
let msg = format!(
"Invalid pallet::storage, Unexpected generic `{}` for `{}`. {}",
gen_name, storage_type_name, expectation,
);
errors.push(syn::Error::new(gen_binding.span(), msg));
}
}
for mandatory_generic in mandatory_generics {
if !map.contains_key(&mandatory_generic.to_string()) {
let msg = format!(
"Invalid pallet::storage, cannot find `{}` generic, required for `{}`.",
mandatory_generic, storage_type_name
);
errors.push(syn::Error::new(args_span, msg));
}
}
let mut errors = errors.drain(..);
if let Some(mut error) = errors.next() {
for other_error in errors {
error.combine(other_error);
}
Err(error)
} else {
Ok(())
}
}
fn process_named_generics(
storage: &StorageKind,
args_span: proc_macro2::Span,
args: &[syn::Binding],
) -> syn::Result<(Option<StorageGenerics>, Metadata, Option<syn::Type>)> {
let mut parsed = HashMap::<String, syn::Binding>::new();
for arg in args {
if let Some(other) = parsed.get(&arg.ident.to_string()) {
let msg = "Invalid pallet::storage, Duplicated named generic";
let mut err = syn::Error::new(arg.ident.span(), msg);
err.combine(syn::Error::new(other.ident.span(), msg));
return Err(err)
}
parsed.insert(arg.ident.to_string(), arg.clone());
}
let generics = match storage {
StorageKind::Value => {
check_generics(
&parsed,
&["Value"],
&["QueryKind", "OnEmpty"],
"StorageValue",
args_span,
)?;
StorageGenerics::Value {
value: parsed
.remove("Value")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
query_kind: parsed.remove("QueryKind").map(|binding| binding.ty),
on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty),
}
},
StorageKind::Map => {
check_generics(
&parsed,
&["Hasher", "Key", "Value"],
&["QueryKind", "OnEmpty", "MaxValues"],
"StorageMap",
args_span,
)?;
StorageGenerics::Map {
hasher: parsed
.remove("Hasher")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
key: parsed
.remove("Key")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
value: parsed
.remove("Value")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
query_kind: parsed.remove("QueryKind").map(|binding| binding.ty),
on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty),
max_values: parsed.remove("MaxValues").map(|binding| binding.ty),
}
},
StorageKind::CountedMap => {
check_generics(
&parsed,
&["Hasher", "Key", "Value"],
&["QueryKind", "OnEmpty", "MaxValues"],
"CountedStorageMap",
args_span,
)?;
StorageGenerics::CountedMap {
hasher: parsed
.remove("Hasher")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
key: parsed
.remove("Key")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
value: parsed
.remove("Value")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
query_kind: parsed.remove("QueryKind").map(|binding| binding.ty),
on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty),
max_values: parsed.remove("MaxValues").map(|binding| binding.ty),
}
},
StorageKind::DoubleMap => {
check_generics(
&parsed,
&["Hasher1", "Key1", "Hasher2", "Key2", "Value"],
&["QueryKind", "OnEmpty", "MaxValues"],
"StorageDoubleMap",
args_span,
)?;
StorageGenerics::DoubleMap {
hasher1: parsed
.remove("Hasher1")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
key1: parsed
.remove("Key1")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
hasher2: parsed
.remove("Hasher2")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
key2: parsed
.remove("Key2")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
value: parsed
.remove("Value")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
query_kind: parsed.remove("QueryKind").map(|binding| binding.ty),
on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty),
max_values: parsed.remove("MaxValues").map(|binding| binding.ty),
}
},
StorageKind::NMap => {
check_generics(
&parsed,
&["Key", "Value"],
&["QueryKind", "OnEmpty", "MaxValues"],
"StorageNMap",
args_span,
)?;
StorageGenerics::NMap {
keygen: parsed
.remove("Key")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
value: parsed
.remove("Value")
.map(|binding| binding.ty)
.expect("checked above as mandatory generic"),
query_kind: parsed.remove("QueryKind").map(|binding| binding.ty),
on_empty: parsed.remove("OnEmpty").map(|binding| binding.ty),
max_values: parsed.remove("MaxValues").map(|binding| binding.ty),
}
},
};
let metadata = generics.metadata()?;
let query_kind = generics.query_kind();
Ok((Some(generics), metadata, query_kind))
}
fn process_unnamed_generics(
storage: &StorageKind,
args_span: proc_macro2::Span,
args: &[syn::Type],
) -> syn::Result<(Option<StorageGenerics>, Metadata, Option<syn::Type>)> {
let retrieve_arg = |arg_pos| {
args.get(arg_pos).cloned().ok_or_else(|| {
let msg = format!(
"Invalid pallet::storage, unexpected number of generic argument, \
expect at least {} args, found {}.",
arg_pos + 1,
args.len(),
);
syn::Error::new(args_span, msg)
})
};
let prefix_arg = retrieve_arg(0)?;
syn::parse2::<syn::Token![_]>(prefix_arg.to_token_stream()).map_err(|e| {
let msg = "Invalid pallet::storage, for unnamed generic arguments the type \
first generic argument must be `_`, the argument is then replaced by macro.";
let mut err = syn::Error::new(prefix_arg.span(), msg);
err.combine(e);
err
})?;
let res = match storage {
StorageKind::Value =>
(None, Metadata::Value { value: retrieve_arg(1)? }, retrieve_arg(2).ok()),
StorageKind::Map => (
None,
Metadata::Map { key: retrieve_arg(2)?, value: retrieve_arg(3)? },
retrieve_arg(4).ok(),
),
StorageKind::CountedMap => (
None,
Metadata::CountedMap { key: retrieve_arg(2)?, value: retrieve_arg(3)? },
retrieve_arg(4).ok(),
),
StorageKind::DoubleMap => (
None,
Metadata::DoubleMap {
key1: retrieve_arg(2)?,
key2: retrieve_arg(4)?,
value: retrieve_arg(5)?,
},
retrieve_arg(6).ok(),
),
StorageKind::NMap => {
let keygen = retrieve_arg(1)?;
let keys = collect_keys(&keygen)?;
(None, Metadata::NMap { keys, keygen, value: retrieve_arg(2)? }, retrieve_arg(3).ok())
},
};
Ok(res)
}
fn process_generics(
segment: &syn::PathSegment,
) -> syn::Result<(Option<StorageGenerics>, Metadata, Option<syn::Type>)> {
let storage_kind = match &*segment.ident.to_string() {
"StorageValue" => StorageKind::Value,
"StorageMap" => StorageKind::Map,
"CountedStorageMap" => StorageKind::CountedMap,
"StorageDoubleMap" => StorageKind::DoubleMap,
"StorageNMap" => StorageKind::NMap,
found => {
let msg = format!(
"Invalid pallet::storage, expected ident: `StorageValue` or \
`StorageMap` or `StorageDoubleMap` or `StorageNMap` in order to expand metadata, \
found `{}`.",
found,
);
return Err(syn::Error::new(segment.ident.span(), msg))
},
};
let args_span = segment.arguments.span();
let args = match &segment.arguments {
syn::PathArguments::AngleBracketed(args) if args.args.len() != 0 => args,
_ => {
let msg = "Invalid pallet::storage, invalid number of generic generic arguments, \
expect more that 0 generic arguments.";
return Err(syn::Error::new(segment.span(), msg))
},
};
if args.args.iter().all(|gen| matches!(gen, syn::GenericArgument::Type(_))) {
let args = args
.args
.iter()
.map(|gen| match gen {
syn::GenericArgument::Type(gen) => gen.clone(),
_ => unreachable!("It is asserted above that all generics are types"),
})
.collect::<Vec<_>>();
process_unnamed_generics(&storage_kind, args_span, &args)
} else if args.args.iter().all(|gen| matches!(gen, syn::GenericArgument::Binding(_))) {
let args = args
.args
.iter()
.map(|gen| match gen {
syn::GenericArgument::Binding(gen) => gen.clone(),
_ => unreachable!("It is asserted above that all generics are bindings"),
})
.collect::<Vec<_>>();
process_named_generics(&storage_kind, args_span, &args)
} else {
let msg = "Invalid pallet::storage, invalid generic declaration for storage. Expect only \
type generics or binding generics, e.g. `<Name1 = Gen1, Name2 = Gen2, ..>` or \
`<Gen1, Gen2, ..>`.";
Err(syn::Error::new(segment.span(), msg))
}
}
fn collect_keys(keygen: &syn::Type) -> syn::Result<Vec<syn::Type>> {
if let syn::Type::Tuple(tup) = keygen {
tup.elems.iter().map(extract_key).collect::<syn::Result<Vec<_>>>()
} else {
Ok(vec![extract_key(keygen)?])
}
}
fn extract_key(ty: &syn::Type) -> syn::Result<syn::Type> {
let typ = if let syn::Type::Path(typ) = ty {
typ
} else {
let msg = "Invalid pallet::storage, expected type path";
return Err(syn::Error::new(ty.span(), msg))
};
let key_struct = typ.path.segments.last().ok_or_else(|| {
let msg = "Invalid pallet::storage, expected type path with at least one segment";
syn::Error::new(typ.path.span(), msg)
})?;
if key_struct.ident != "Key" && key_struct.ident != "NMapKey" {
let msg = "Invalid pallet::storage, expected Key or NMapKey struct";
return Err(syn::Error::new(key_struct.ident.span(), msg))
}
let ty_params = if let syn::PathArguments::AngleBracketed(args) = &key_struct.arguments {
args
} else {
let msg = "Invalid pallet::storage, expected angle bracketed arguments";
return Err(syn::Error::new(key_struct.arguments.span(), msg))
};
if ty_params.args.len() != 2 {
let msg = format!(
"Invalid pallet::storage, unexpected number of generic arguments \
for Key struct, expected 2 args, found {}",
ty_params.args.len()
);
return Err(syn::Error::new(ty_params.span(), msg))
}
let key = match &ty_params.args[1] {
syn::GenericArgument::Type(key_ty) => key_ty.clone(),
_ => {
let msg = "Invalid pallet::storage, expected type";
return Err(syn::Error::new(ty_params.args[1].span(), msg))
},
};
Ok(key)
}
impl StorageDef {
pub fn prefix(&self) -> String {
self.rename_as
.as_ref()
.map(syn::LitStr::value)
.unwrap_or(self.ident.to_string())
}
pub fn prefix_span(&self) -> proc_macro2::Span {
self.rename_as.as_ref().map(syn::LitStr::span).unwrap_or(self.ident.span())
}
pub fn try_from(
attr_span: proc_macro2::Span,
index: usize,
item: &mut syn::Item,
) -> syn::Result<Self> {
let item = if let syn::Item::Type(item) = item {
item
} else {
return Err(syn::Error::new(item.span(), "Invalid pallet::storage, expect item type."))
};
let attrs: Vec<PalletStorageAttr> = helper::take_item_pallet_attrs(&mut item.attrs)?;
let PalletStorageAttrInfo { getter, rename_as, unbounded } =
PalletStorageAttrInfo::from_attrs(attrs)?;
let cfg_attrs = helper::get_item_cfg_attrs(&item.attrs);
let mut instances = vec![];
instances.push(helper::check_type_def_gen(&item.generics, item.ident.span())?);
let where_clause = item.generics.where_clause.clone();
let docs = get_doc_literals(&item.attrs);
let typ = if let syn::Type::Path(typ) = &*item.ty {
typ
} else {
let msg = "Invalid pallet::storage, expected type path";
return Err(syn::Error::new(item.ty.span(), msg))
};
if typ.path.segments.len() != 1 {
let msg = "Invalid pallet::storage, expected type path with one segment";
return Err(syn::Error::new(item.ty.span(), msg))
}
let (named_generics, metadata, query_kind) = process_generics(&typ.path.segments[0])?;
let query_kind = query_kind
.map(|query_kind| match query_kind {
syn::Type::Path(path)
if path.path.segments.last().map_or(false, |s| s.ident == "OptionQuery") =>
Some(QueryKind::OptionQuery),
syn::Type::Path(path)
if path.path.segments.last().map_or(false, |s| s.ident == "ValueQuery") =>
Some(QueryKind::ValueQuery),
_ => None,
})
.unwrap_or(Some(QueryKind::OptionQuery));
if query_kind.is_none() && getter.is_some() {
let msg = "Invalid pallet::storage, cannot generate getter because QueryKind is not \
identifiable. QueryKind must be `OptionQuery`, `ValueQuery`, or default one to be \
identifiable.";
return Err(syn::Error::new(getter.unwrap().span(), msg))
}
Ok(StorageDef {
attr_span,
index,
vis: item.vis.clone(),
ident: item.ident.clone(),
instances,
metadata,
docs,
getter,
rename_as,
query_kind,
where_clause,
cfg_attrs,
named_generics,
unbounded,
})
}
}