This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
mod.rs
620 lines (557 loc) · 19.7 KB
/
mod.rs
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
// This file is part of Substrate.
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implementation of `construct_runtime`.
//!
//! `construct_runtime` implementation is recursive and can generate code which will call itself in
//! order to get all the pallet parts for each pallet.
//!
//! Pallets define their parts (`Call`, `Storage`, ..) either explicitly with the syntax
//! `::{Call, ...}` or implicitly.
//!
//! In case a pallet defines its parts implicitly, then the pallet must provide the
//! `tt_default_parts` macro. `construct_rutime` will generate some code which utilizes `tt_call`
//! to call the `tt_default_parts` macro of the pallet. `tt_default_parts` will then return the
//! default pallet parts as input tokens to the `match_and_replace` macro, which ultimately
//! generates a call to `construct_runtime` again, this time with all the pallet parts explicitly
//! defined.
//!
//! E.g.
//! ```ignore
//! construct_runtime!(
//! //...
//! {
//! System: frame_system = 0, // Implicit definition of parts
//! Balances: pallet_balances = 1, // Implicit definition of parts
//! }
//! );
//! ```
//! This call has some implicit pallet parts, thus it will expand to:
//! ```ignore
//! frame_support::tt_call! {
//! macro = [{ pallet_balances::tt_default_parts }]
//! ~~> frame_support::match_and_insert! {
//! target = [{
//! frame_support::tt_call! {
//! macro = [{ frame_system::tt_default_parts }]
//! ~~> frame_support::match_and_insert! {
//! target = [{
//! construct_runtime!(
//! //...
//! {
//! System: frame_system = 0,
//! Balances: pallet_balances = 1,
//! }
//! );
//! }]
//! pattern = [{ System: frame_system }]
//! }
//! }
//! }]
//! pattern = [{ Balances: pallet_balances }]
//! }
//! }
//! ```
//! `tt_default_parts` must be defined. It returns the pallet parts inside some tokens, and
//! then `tt_call` will pipe the returned pallet parts into the input of `match_and_insert`.
//! Thus `match_and_insert` will initially receive the following inputs:
//! ```ignore
//! frame_support::match_and_insert! {
//! target = [{
//! frame_support::match_and_insert! {
//! target = [{
//! construct_runtime!(
//! //...
//! {
//! System: frame_system = 0,
//! Balances: pallet_balances = 1,
//! }
//! )
//! }]
//! pattern = [{ System: frame_system }]
//! tokens = [{ ::{Pallet, Call} }]
//! }
//! }]
//! pattern = [{ Balances: pallet_balances }]
//! tokens = [{ ::{Pallet, Call} }]
//! }
//! ```
//! After dealing with `pallet_balances`, the inner `match_and_insert` will expand to:
//! ```ignore
//! frame_support::match_and_insert! {
//! target = [{
//! construct_runtime!(
//! //...
//! {
//! System: frame_system = 0, // Implicit definition of parts
//! Balances: pallet_balances::{Pallet, Call} = 1, // Explicit definition of parts
//! }
//! )
//! }]
//! pattern = [{ System: frame_system }]
//! tokens = [{ ::{Pallet, Call} }]
//! }
//! ```
//! Which will then finally expand to the following:
//! ```ignore
//! construct_runtime!(
//! //...
//! {
//! System: frame_system::{Pallet, Call},
//! Balances: pallet_balances::{Pallet, Call},
//! }
//! )
//! ```
//! This call has no implicit pallet parts, thus it will expand to the runtime construction:
//! ```ignore
//! pub struct Runtime { ... }
//! pub struct Call { ... }
//! impl Call ...
//! pub enum Origin { ... }
//! ...
//! ```
//!
//! Visualizing the entire flow of `construct_runtime!`, it would look like the following:
//!
//! ```ignore
//! +--------------------+ +---------------------+ +-------------------+
//! | | | (defined in pallet) | | |
//! | construct_runtime! | --> | tt_default_parts! | --> | match_and_insert! |
//! | w/ no pallet parts | | | | |
//! +--------------------+ +---------------------+ +-------------------+
//!
//! +--------------------+
//! | |
//! --> | construct_runtime! |
//! | w/ pallet parts |
//! +--------------------+
//! ```
mod expand;
mod parse;
use cfg_expr::Predicate;
use frame_support_procedural_tools::{
generate_crate_access, generate_crate_access_2018, generate_hidden_includes,
};
use itertools::Itertools;
use parse::{
ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration,
WhereSection,
};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::{
collections::{HashMap, HashSet},
str::FromStr,
};
use syn::{Ident, Result};
/// The fixed name of the system pallet.
const SYSTEM_PALLET_NAME: &str = "System";
/// Implementation of `construct_runtime` macro. Either expand to some code which will call
/// `construct_runtime` again, or expand to the final runtime definition.
pub fn construct_runtime(input: TokenStream) -> TokenStream {
let input_copy = input.clone();
let definition = syn::parse_macro_input!(input as RuntimeDeclaration);
let res = match definition {
RuntimeDeclaration::Implicit(implicit_def) =>
construct_runtime_intermediary_expansion(input_copy.into(), implicit_def),
RuntimeDeclaration::Explicit(explicit_decl) =>
construct_runtime_final_expansion(explicit_decl),
};
res.unwrap_or_else(|e| e.to_compile_error()).into()
}
/// When some pallet have implicit parts definition then the macro will expand into a macro call to
/// `construct_runtime_args` of each pallets, see root documentation.
fn construct_runtime_intermediary_expansion(
input: TokenStream2,
definition: ImplicitRuntimeDeclaration,
) -> Result<TokenStream2> {
let frame_support = generate_crate_access_2018("frame-support")?;
let mut expansion = quote::quote!(
#frame_support::construct_runtime! { #input }
);
for pallet in definition.pallets.iter().filter(|pallet| pallet.pallet_parts.is_none()) {
let pallet_path = &pallet.path;
let pallet_name = &pallet.name;
let pallet_instance = pallet.instance.as_ref().map(|instance| quote::quote!(::<#instance>));
expansion = quote::quote!(
#frame_support::tt_call! {
macro = [{ #pallet_path::tt_default_parts }]
frame_support = [{ #frame_support }]
~~> #frame_support::match_and_insert! {
target = [{ #expansion }]
pattern = [{ #pallet_name: #pallet_path #pallet_instance }]
}
}
);
}
Ok(expansion)
}
/// All pallets have explicit definition of parts, this will expand to the runtime declaration.
fn construct_runtime_final_expansion(
definition: ExplicitRuntimeDeclaration,
) -> Result<TokenStream2> {
let ExplicitRuntimeDeclaration {
name,
where_section: WhereSection { block, node_block, unchecked_extrinsic },
pallets,
pallets_token,
} = definition;
let system_pallet =
pallets.iter().find(|decl| decl.name == SYSTEM_PALLET_NAME).ok_or_else(|| {
syn::Error::new(
pallets_token.span,
"`System` pallet declaration is missing. \
Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event<T>},`",
)
})?;
if !system_pallet.cfg_pattern.is_empty() {
return Err(syn::Error::new(
system_pallet.name.span(),
"`System` pallet declaration is feature gated, please remove any `#[cfg]` attributes",
))
}
let features = pallets
.iter()
.filter_map(|decl| {
(!decl.cfg_pattern.is_empty()).then(|| {
decl.cfg_pattern.iter().flat_map(|attr| {
attr.predicates().filter_map(|pred| match pred {
Predicate::Feature(feat) => Some(feat),
Predicate::Test => Some("test"),
_ => None,
})
})
})
})
.flatten()
.collect::<HashSet<_>>();
let hidden_crate_name = "construct_runtime";
let scrate = generate_crate_access(hidden_crate_name, "frame-support");
let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support");
let outer_event = expand::expand_outer_event(&name, &pallets, &scrate)?;
let outer_origin = expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?;
let all_pallets = decl_all_pallets(&name, pallets.iter(), &features);
let pallet_to_index = decl_pallet_runtime_setup(&name, &pallets, &scrate);
let dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate);
let metadata = expand::expand_runtime_metadata(&name, &pallets, &scrate, &unchecked_extrinsic);
let outer_config = expand::expand_outer_config(&name, &pallets, &scrate);
let inherent =
expand::expand_outer_inherent(&name, &block, &unchecked_extrinsic, &pallets, &scrate);
let validate_unsigned = expand::expand_outer_validate_unsigned(&name, &pallets, &scrate);
let integrity_test = decl_integrity_test(&scrate);
let static_assertions = decl_static_assertions(&name, &pallets, &scrate);
let res = quote!(
#scrate_decl
// Prevent UncheckedExtrinsic to print unused warning.
const _: () = {
#[allow(unused)]
type __hidden_use_of_unchecked_extrinsic = #unchecked_extrinsic;
};
#[derive(
Clone, Copy, PartialEq, Eq, #scrate::sp_runtime::RuntimeDebug,
#scrate::scale_info::TypeInfo
)]
pub struct #name;
impl #scrate::sp_runtime::traits::GetNodeBlockType for #name {
type NodeBlock = #node_block;
}
impl #scrate::sp_runtime::traits::GetRuntimeBlockType for #name {
type RuntimeBlock = #block;
}
#outer_event
#outer_origin
#all_pallets
#pallet_to_index
#dispatch
#metadata
#outer_config
#inherent
#validate_unsigned
#integrity_test
#static_assertions
);
Ok(res)
}
fn decl_all_pallets<'a>(
runtime: &'a Ident,
pallet_declarations: impl Iterator<Item = &'a Pallet>,
features: &HashSet<&str>,
) -> TokenStream2 {
let mut types = TokenStream2::new();
let mut names_by_feature = features
.iter()
.powerset()
.map(|feat| (feat, Vec::new()))
.collect::<HashMap<_, _>>();
for pallet_declaration in pallet_declarations {
let type_name = &pallet_declaration.name;
let pallet = &pallet_declaration.path;
let mut generics = vec![quote!(#runtime)];
generics.extend(pallet_declaration.instance.iter().map(|name| quote!(#pallet::#name)));
let mut attrs = Vec::new();
for cfg in &pallet_declaration.cfg_pattern {
let feat = format!("#[cfg({})]\n", cfg.original());
attrs.extend(TokenStream2::from_str(&feat).expect("was parsed successfully; qed"));
}
let type_decl = quote!(
#(#attrs)*
pub type #type_name = #pallet::Pallet <#(#generics),*>;
);
types.extend(type_decl);
if pallet_declaration.cfg_pattern.is_empty() {
for names in names_by_feature.values_mut() {
names.push(&pallet_declaration.name);
}
} else {
for (feature_set, names) in &mut names_by_feature {
// Rust tidbit: if we have multiple `#[cfg]` feature on the same item, then the
// predicates listed in all `#[cfg]` attributes are effectively joined by `and()`,
// meaning that all of them must match in order to activate the item
let is_feature_active = pallet_declaration.cfg_pattern.iter().all(|expr| {
expr.eval(|pred| match pred {
Predicate::Feature(f) => feature_set.contains(&f),
Predicate::Test => feature_set.contains(&&"test"),
_ => false,
})
});
if is_feature_active {
names.push(&pallet_declaration.name);
}
}
}
}
let all_pallets_without_system = names_by_feature.iter().map(|(feature_set, names)| {
let mut feature_set = feature_set.iter().collect::<HashSet<_>>();
let test_cfg = feature_set.remove(&&&"test").then_some(quote!(test)).into_iter();
let feature_set = feature_set.into_iter();
let attr = quote!(#[cfg(all( #(#test_cfg),* #(feature = #feature_set),* ))]);
let names = names.iter().filter(|n| **n != SYSTEM_PALLET_NAME);
quote! {
#attr
/// All pallets included in the runtime as a nested tuple of types.
/// Excludes the System pallet.
pub type AllPalletsWithoutSystem = ( #(#names,)* );
}
});
let all_pallets_with_system = names_by_feature.iter().map(|(feature_set, names)| {
let mut feature_set = feature_set.iter().collect::<HashSet<_>>();
let test_cfg = feature_set.remove(&&&"test").then_some(quote!(test)).into_iter();
let feature_set = feature_set.into_iter();
let attr = quote!(#[cfg(all( #(#test_cfg),* #(feature = #feature_set),* ))]);
quote! {
#attr
/// All pallets included in the runtime as a nested tuple of types.
pub type AllPalletsWithSystem = ( #(#names,)* );
}
});
let all_pallets_without_system_reversed =
names_by_feature.iter().map(|(feature_set, names)| {
let mut feature_set = feature_set.iter().collect::<HashSet<_>>();
let test_cfg = feature_set.remove(&&&"test").then_some(quote!(test)).into_iter();
let feature_set = feature_set.into_iter();
let attr = quote!(#[cfg(all( #(#test_cfg),* #(feature = #feature_set),* ))]);
let names = names.iter().filter(|n| **n != SYSTEM_PALLET_NAME).rev();
quote! {
#attr
/// All pallets included in the runtime as a nested tuple of types in reversed order.
/// Excludes the System pallet.
#[deprecated(note = "Using reverse pallet orders is deprecated. use only \
`AllPalletWithSystem or AllPalletsWithoutSystem`")]
pub type AllPalletsWithoutSystemReversed = ( #(#names,)* );
}
});
let all_pallets_with_system_reversed = names_by_feature.iter().map(|(feature_set, names)| {
let mut feature_set = feature_set.iter().collect::<HashSet<_>>();
let test_cfg = feature_set.remove(&&&"test").then_some(quote!(test)).into_iter();
let feature_set = feature_set.into_iter();
let attr = quote!(#[cfg(all( #(#test_cfg),* #(feature = #feature_set),* ))]);
let names = names.iter().rev();
quote! {
#attr
/// All pallets included in the runtime as a nested tuple of types in reversed order.
#[deprecated(note = "Using reverse pallet orders is deprecated. use only \
`AllPalletWithSystem or AllPalletsWithoutSystem`")]
pub type AllPalletsWithSystemReversed = ( #(#names,)* );
}
});
let system_pallet =
match names_by_feature[&Vec::new()].iter().find(|n| **n == SYSTEM_PALLET_NAME) {
Some(name) => name,
None =>
return syn::Error::new(
proc_macro2::Span::call_site(),
"`System` pallet declaration is missing. \
Please add this line: `System: frame_system,`",
)
.into_compile_error(),
};
let all_pallets_reversed_with_system_first =
names_by_feature.iter().map(|(feature_set, names)| {
let mut feature_set = feature_set.iter().collect::<HashSet<_>>();
let test_cfg = feature_set.remove(&&&"test").then_some(quote!(test)).into_iter();
let feature_set = feature_set.into_iter();
let attr = quote!(#[cfg(all( #(#test_cfg),* #(feature = #feature_set),* ))]);
let names = std::iter::once(system_pallet)
.chain(names.iter().rev().filter(|n| **n != SYSTEM_PALLET_NAME));
quote! {
#attr
/// All pallets included in the runtime as a nested tuple of types in reversed order.
/// With the system pallet first.
#[deprecated(note = "Using reverse pallet orders is deprecated. use only \
`AllPalletWithSystem or AllPalletsWithoutSystem`")]
pub type AllPalletsReversedWithSystemFirst = ( #(#names,)* );
}
});
quote!(
#types
/// All pallets included in the runtime as a nested tuple of types.
#[deprecated(note = "The type definition has changed from representing all pallets \
excluding system, in reversed order to become the representation of all pallets \
including system pallet in regular order. For this reason it is encouraged to use \
explicitly one of `AllPalletsWithSystem`, `AllPalletsWithoutSystem`, \
`AllPalletsWithSystemReversed`, `AllPalletsWithoutSystemReversed`. \
Note that the type `frame_executive::Executive` expects one of `AllPalletsWithSystem` \
, `AllPalletsWithSystemReversed`, `AllPalletsReversedWithSystemFirst`. More details in \
https://github.com/paritytech/substrate/pull/10043")]
pub type AllPallets = AllPalletsWithSystem;
#( #all_pallets_with_system )*
#( #all_pallets_without_system )*
#( #all_pallets_with_system_reversed )*
#( #all_pallets_without_system_reversed )*
#( #all_pallets_reversed_with_system_first )*
)
}
fn decl_pallet_runtime_setup(
runtime: &Ident,
pallet_declarations: &[Pallet],
scrate: &TokenStream2,
) -> TokenStream2 {
let names = pallet_declarations.iter().map(|d| &d.name).collect::<Vec<_>>();
let name_strings = pallet_declarations.iter().map(|d| d.name.to_string());
let module_names = pallet_declarations.iter().map(|d| d.path.module_name());
let indices = pallet_declarations.iter().map(|pallet| pallet.index as usize);
let pallet_structs = pallet_declarations
.iter()
.map(|pallet| {
let path = &pallet.path;
match pallet.instance.as_ref() {
Some(inst) => quote!(#path::Pallet<#runtime, #path::#inst>),
None => quote!(#path::Pallet<#runtime>),
}
})
.collect::<Vec<_>>();
let pallet_attrs = pallet_declarations
.iter()
.map(|pallet| {
pallet.cfg_pattern.iter().fold(TokenStream2::new(), |acc, pattern| {
let attr = TokenStream2::from_str(&format!("#[cfg({})]", pattern.original()))
.expect("was successfully parsed before; qed");
quote! {
#acc
#attr
}
})
})
.collect::<Vec<_>>();
quote!(
/// Provides an implementation of `PalletInfo` to provide information
/// about the pallet setup in the runtime.
pub struct PalletInfo;
impl #scrate::traits::PalletInfo for PalletInfo {
fn index<P: 'static>() -> Option<usize> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
#pallet_attrs
if type_id == #scrate::sp_std::any::TypeId::of::<#names>() {
return Some(#indices)
}
)*
None
}
fn name<P: 'static>() -> Option<&'static str> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
#pallet_attrs
if type_id == #scrate::sp_std::any::TypeId::of::<#names>() {
return Some(#name_strings)
}
)*
None
}
fn module_name<P: 'static>() -> Option<&'static str> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
#pallet_attrs
if type_id == #scrate::sp_std::any::TypeId::of::<#names>() {
return Some(#module_names)
}
)*
None
}
fn crate_version<P: 'static>() -> Option<#scrate::traits::CrateVersion> {
let type_id = #scrate::sp_std::any::TypeId::of::<P>();
#(
#pallet_attrs
if type_id == #scrate::sp_std::any::TypeId::of::<#names>() {
return Some(
<#pallet_structs as #scrate::traits::PalletInfoAccess>::crate_version()
)
}
)*
None
}
}
)
}
fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 {
quote!(
#[cfg(test)]
mod __construct_runtime_integrity_test {
use super::*;
#[test]
pub fn runtime_integrity_tests() {
<AllPalletsWithSystem as #scrate::traits::IntegrityTest>::integrity_test();
}
}
)
}
fn decl_static_assertions(
runtime: &Ident,
pallet_decls: &[Pallet],
scrate: &TokenStream2,
) -> TokenStream2 {
let error_encoded_size_check = pallet_decls.iter().map(|decl| {
let path = &decl.path;
let assert_message = format!(
"The maximum encoded size of the error type in the `{}` pallet exceeds \
`MAX_MODULE_ERROR_ENCODED_SIZE`",
decl.name,
);
quote! {
#scrate::tt_call! {
macro = [{ #path::tt_error_token }]
frame_support = [{ #scrate }]
~~> #scrate::assert_error_encoded_size! {
path = [{ #path }]
runtime = [{ #runtime }]
assert_message = [{ #assert_message }]
}
}
}
});
quote! {
#(#error_encoded_size_check)*
}
}