referrerpolicy=no-referrer-when-downgrade

frame_support_procedural/pallet/expand/
config.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use crate::pallet::{parse::GenericKind, Def};
19use proc_macro2::TokenStream;
20use quote::quote;
21use syn::{parse_quote, Item};
22
23///
24/// * Generate default rust doc
25pub fn expand_config(def: &mut Def) -> TokenStream {
26	let config = &def.config;
27	let config_item = {
28		let item = &mut def.item.content.as_mut().expect("Checked by def parser").1[config.index];
29		if let Item::Trait(item) = item {
30			item
31		} else {
32			unreachable!("Checked by config parser")
33		}
34	};
35
36	config_item.attrs.insert(
37		0,
38		parse_quote!(
39			#[doc = r"
40Configuration trait of this pallet.
41
42The main purpose of this trait is to act as an interface between this pallet and the runtime in
43which it is embedded in. A type, function, or constant in this trait is essentially left to be
44configured by the runtime that includes this pallet.
45
46Consequently, a runtime that wants to include this pallet must implement this trait."
47			]
48		),
49	);
50	config_item.attrs.retain(|attr| !attr.path().is_ident("deprecated"));
51
52	// insert `frame_system::Config` supertrait with `RuntimeEvent: From<Event<Self>>` if neither
53	// associated type nor type bound is defined.
54	if let Some(event) = &def.event {
55		if !def.is_frame_system {
56			let frame_system = &def.frame_system;
57
58			// can't use `type_use_gen()` since it returns `T`, not `Self`
59			let event_use_gen = match event.gen_kind {
60				GenericKind::None => quote!(),
61				GenericKind::Config => quote::quote_spanned! {event.attr_span => Self},
62				GenericKind::ConfigAndInstance =>
63					quote::quote_spanned! {event.attr_span => Self, I},
64			};
65
66			let supertrait_with_event_bound = syn::parse2::<syn::TypeParamBound>(
67				quote! { #frame_system::Config<RuntimeEvent: From<Event<#event_use_gen>>> },
68			)
69			.expect("Parsing super trait doesn't fail; qed");
70
71			config_item.supertraits.push(supertrait_with_event_bound.into());
72		}
73	}
74
75	// we only emit `DefaultConfig` if there are trait items, so an empty `DefaultConfig` is
76	// impossible consequently.
77	match &config.default_sub_trait {
78		Some(default_sub_trait) if default_sub_trait.items.len() > 0 => {
79			let trait_items = &default_sub_trait
80				.items
81				.iter()
82				.map(|item| {
83					if item.1 {
84						if let syn::TraitItem::Type(item) = item.0.clone() {
85							let mut item = item.clone();
86							item.bounds.clear();
87							syn::TraitItem::Type(item)
88						} else {
89							item.0.clone()
90						}
91					} else {
92						item.0.clone()
93					}
94				})
95				.collect::<Vec<_>>();
96
97			let type_param_bounds = if default_sub_trait.has_system {
98				let system = &def.frame_system;
99				quote::quote!(: #system::DefaultConfig)
100			} else {
101				quote::quote!()
102			};
103
104			quote!(
105				/// Based on [`Config`]. Auto-generated by
106				/// [`#[pallet::config(with_default)]`](`frame_support::pallet_macros::config`).
107				/// Can be used in tandem with
108				/// [`#[register_default_config]`](`frame_support::register_default_config`) and
109				/// [`#[derive_impl]`](`frame_support::derive_impl`) to derive test config traits
110				/// based on existing pallet config traits in a safe and developer-friendly way.
111				///
112				/// See [here](`frame_support::pallet_macros::config`) for more information and caveats about
113				/// the auto-generated `DefaultConfig` trait and how it is generated.
114				pub trait DefaultConfig #type_param_bounds {
115					#(#trait_items)*
116				}
117			)
118		},
119		_ => quote!(),
120	}
121}
122
123/// Generate the metadata for the associated types of the config trait.
124///
125/// Implements the `pallet_associated_types_metadata` function for the pallet.
126pub fn expand_config_metadata(def: &Def) -> proc_macro2::TokenStream {
127	let frame_support = &def.frame_support;
128	let type_impl_gen = &def.type_impl_generics(proc_macro2::Span::call_site());
129	let type_use_gen = &def.type_use_generics(proc_macro2::Span::call_site());
130	let pallet_ident = &def.pallet_struct.pallet;
131	let trait_use_gen = &def.trait_use_generics(proc_macro2::Span::call_site());
132
133	let mut where_clauses = vec![&def.config.where_clause];
134	where_clauses.extend(def.extra_constants.iter().map(|d| &d.where_clause));
135	let completed_where_clause = super::merge_where_clauses(&where_clauses);
136
137	let types = def.config.associated_types_metadata.iter().map(|metadata| {
138		let ident = &metadata.ident;
139		let span = ident.span();
140		let ident_str = ident.to_string();
141		let cfgs = &metadata.cfg;
142
143		let no_docs = vec![];
144		let doc = if cfg!(feature = "no-metadata-docs") { &no_docs } else { &metadata.doc };
145
146		quote::quote_spanned!(span => {
147			#( #cfgs ) *
148			#frame_support::__private::metadata_ir::PalletAssociatedTypeMetadataIR {
149				name: #ident_str,
150				ty: #frame_support::__private::scale_info::meta_type::<
151						<T as Config #trait_use_gen>::#ident
152					>(),
153				docs: #frame_support::__private::vec![ #( #doc ),* ],
154			}
155		})
156	});
157
158	quote::quote!(
159		impl<#type_impl_gen> #pallet_ident<#type_use_gen> #completed_where_clause {
160
161			#[doc(hidden)]
162			pub fn pallet_associated_types_metadata()
163				-> #frame_support::__private::vec::Vec<#frame_support::__private::metadata_ir::PalletAssociatedTypeMetadataIR>
164			{
165				#frame_support::__private::vec![ #( #types ),* ]
166			}
167		}
168	)
169}