frame_support_procedural/
lib.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
18//! Proc macro of Support code for the runtime.
19
20#![recursion_limit = "512"]
21#![deny(rustdoc::broken_intra_doc_links)]
22
23mod benchmark;
24mod construct_runtime;
25mod crate_version;
26mod deprecation;
27mod derive_impl;
28mod dummy_part_checker;
29mod dynamic_params;
30mod key_prefix;
31mod match_and_insert;
32mod no_bound;
33mod pallet;
34mod pallet_error;
35mod runtime;
36mod storage_alias;
37mod transactional;
38mod tt_macro;
39
40use frame_support_procedural_tools::generate_access_from_frame_or_crate;
41use macro_magic::{import_tokens_attr, import_tokens_attr_verbatim};
42use proc_macro::TokenStream;
43use quote::{quote, ToTokens};
44use std::{cell::RefCell, str::FromStr};
45use syn::{parse_macro_input, Error, ItemImpl, ItemMod, TraitItemType};
46
47pub(crate) const INHERENT_INSTANCE_NAME: &str = "__InherentHiddenInstance";
48
49thread_local! {
50	/// A global counter, can be used to generate a relatively unique identifier.
51	static COUNTER: RefCell<Counter> = RefCell::new(Counter(0));
52}
53
54/// Counter to generate a relatively unique identifier for macros. This is necessary because
55/// declarative macros gets hoisted to the crate root, which shares the namespace with other pallets
56/// containing the very same macros.
57struct Counter(u64);
58
59impl Counter {
60	fn inc(&mut self) -> u64 {
61		let ret = self.0;
62		self.0 += 1;
63		ret
64	}
65}
66
67/// Get the value from the given environment variable set by cargo.
68///
69/// The value is parsed into the requested destination type.
70fn get_cargo_env_var<T: FromStr>(version_env: &str) -> std::result::Result<T, ()> {
71	let version = std::env::var(version_env)
72		.unwrap_or_else(|_| panic!("`{}` is always set by cargo; qed", version_env));
73
74	T::from_str(&version).map_err(drop)
75}
76
77/// Generate the counter_prefix related to the storage.
78/// counter_prefix is used by counted storage map.
79fn counter_prefix(prefix: &str) -> String {
80	format!("CounterFor{}", prefix)
81}
82
83/// Construct a runtime, with the given name and the given pallets.
84///
85/// NOTE: A new version of this macro is available at `frame_support::runtime`. This macro will
86/// soon be deprecated. Please use the new macro instead.
87///
88/// The parameters here are specific types for `Block`, `NodeBlock`, and `UncheckedExtrinsic`
89/// and the pallets that are used by the runtime.
90/// `Block` is the block type that is used in the runtime and `NodeBlock` is the block type
91/// that is used in the node. For instance they can differ in the extrinsics type.
92///
93/// # Example:
94///
95/// ```ignore
96/// construct_runtime!(
97///     pub enum Runtime where
98///         Block = Block,
99///         NodeBlock = node::Block,
100///         UncheckedExtrinsic = UncheckedExtrinsic
101///     {
102///         System: frame_system::{Pallet, Call, Event<T>, Config<T>} = 0,
103///         Test: path::to::test::{Pallet, Call} = 1,
104///
105///         // Pallets with instances.
106///         Test2_Instance1: test2::<Instance1>::{Pallet, Call, Storage, Event<T, I>, Config<T, I>, Origin<T, I>},
107///         Test2_DefaultInstance: test2::{Pallet, Call, Storage, Event<T>, Config<T>, Origin<T>} = 4,
108///
109///         // Pallets declared with `pallet` attribute macro: no need to define the parts
110///         Test3_Instance1: test3::<Instance1>,
111///         Test3_DefaultInstance: test3,
112///
113///         // with `exclude_parts` keyword some part can be excluded.
114///         Test4_Instance1: test4::<Instance1> exclude_parts { Call, Origin },
115///         Test4_DefaultInstance: test4 exclude_parts { Storage },
116///
117///         // with `use_parts` keyword, a subset of the pallet parts can be specified.
118///         Test4_Instance1: test4::<Instance1> use_parts { Pallet, Call},
119///         Test4_DefaultInstance: test4 use_parts { Pallet },
120///     }
121/// )
122/// ```
123///
124/// Each pallet is declared as such:
125/// * `Identifier`: name given to the pallet that uniquely identifies it.
126///
127/// * `:`: colon separator
128///
129/// * `path::to::pallet`: identifiers separated by colons which declare the path to a pallet
130///   definition.
131///
132/// * `::<InstanceN>` optional: specify the instance of the pallet to use. If not specified it will
133///   use the default instance (or the only instance in case of non-instantiable pallets).
134///
135/// * `::{ Part1, Part2<T>, .. }` optional if pallet declared with `frame_support::pallet`: Comma
136///   separated parts declared with their generic. If a pallet is declared with
137///   `frame_support::pallet` macro then the parts can be automatically derived if not explicitly
138///   provided. We provide support for the following module parts in a pallet:
139///
140///   - `Pallet` - Required for all pallets
141///   - `Call` - If the pallet has callable functions
142///   - `Storage` - If the pallet uses storage
143///   - `Event` or `Event<T>` (if the event is generic) - If the pallet emits events
144///   - `Origin` or `Origin<T>` (if the origin is generic) - If the pallet has instantiable origins
145///   - `Config` or `Config<T>` (if the config is generic) - If the pallet builds the genesis
146///     storage with `GenesisConfig`
147///   - `Inherent` - If the pallet provides/can check inherents.
148///   - `ValidateUnsigned` - If the pallet validates unsigned extrinsics.
149///
150///   It is important to list these parts here to export them correctly in the metadata or to make
151/// the pallet usable in the runtime.
152///
153/// * `exclude_parts { Part1, Part2 }` optional: comma separated parts without generics. I.e. one of
154///   `Pallet`, `Call`, `Storage`, `Event`, `Origin`, `Config`, `Inherent`, `ValidateUnsigned`. It
155///   is incompatible with `use_parts`. This specifies the part to exclude. In order to select
156///   subset of the pallet parts.
157///
158///   For example excluding the part `Call` can be useful if the runtime doesn't want to make the
159///   pallet calls available.
160///
161/// * `use_parts { Part1, Part2 }` optional: comma separated parts without generics. I.e. one of
162///   `Pallet`, `Call`, `Storage`, `Event`, `Origin`, `Config`, `Inherent`, `ValidateUnsigned`. It
163///   is incompatible with `exclude_parts`. This specifies the part to use. In order to select a
164///   subset of the pallet parts.
165///
166///   For example not using the part `Call` can be useful if the runtime doesn't want to make the
167///   pallet calls available.
168///
169/// * `= $n` optional: number to define at which index the pallet variants in `OriginCaller`, `Call`
170///   and `Event` are encoded, and to define the ModuleToIndex value.
171///
172///   if `= $n` is not given, then index is resolved in the same way as fieldless enum in Rust
173///   (i.e. incrementally from previous index):
174///   ```nocompile
175///   pallet1 .. = 2,
176///   pallet2 .., // Here pallet2 is given index 3
177///   pallet3 .. = 0,
178///   pallet4 .., // Here pallet4 is given index 1
179///   ```
180///
181/// # Note
182///
183/// The population of the genesis storage depends on the order of pallets. So, if one of your
184/// pallets depends on another pallet, the pallet that is depended upon needs to come before
185/// the pallet depending on it.
186///
187/// # Type definitions
188///
189/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System =
190///   frame_system::Pallet<Runtime>`
191#[proc_macro]
192pub fn construct_runtime(input: TokenStream) -> TokenStream {
193	construct_runtime::construct_runtime(input)
194}
195
196///
197/// ---
198///
199/// Documentation for this macro can be found at `frame_support::pallet`.
200#[proc_macro_attribute]
201pub fn pallet(attr: TokenStream, item: TokenStream) -> TokenStream {
202	pallet::pallet(attr, item)
203}
204
205/// An attribute macro that can be attached to a (non-empty) module declaration. Doing so will
206/// designate that module as a benchmarking module.
207///
208/// See `frame_benchmarking::v2` for more info.
209#[proc_macro_attribute]
210pub fn benchmarks(attr: TokenStream, tokens: TokenStream) -> TokenStream {
211	match benchmark::benchmarks(attr, tokens, false) {
212		Ok(tokens) => tokens,
213		Err(err) => err.to_compile_error().into(),
214	}
215}
216
217/// An attribute macro that can be attached to a (non-empty) module declaration. Doing so will
218/// designate that module as an instance benchmarking module.
219///
220/// See `frame_benchmarking::v2` for more info.
221#[proc_macro_attribute]
222pub fn instance_benchmarks(attr: TokenStream, tokens: TokenStream) -> TokenStream {
223	match benchmark::benchmarks(attr, tokens, true) {
224		Ok(tokens) => tokens,
225		Err(err) => err.to_compile_error().into(),
226	}
227}
228
229/// An attribute macro used to declare a benchmark within a benchmarking module. Must be
230/// attached to a function definition containing an `#[extrinsic_call]` or `#[block]`
231/// attribute.
232///
233/// See `frame_benchmarking::v2` for more info.
234#[proc_macro_attribute]
235pub fn benchmark(_attrs: TokenStream, _tokens: TokenStream) -> TokenStream {
236	quote!(compile_error!(
237		"`#[benchmark]` must be in a module labeled with #[benchmarks] or #[instance_benchmarks]."
238	))
239	.into()
240}
241
242/// An attribute macro used to specify the extrinsic call inside a benchmark function, and also
243/// used as a boundary designating where the benchmark setup code ends, and the benchmark
244/// verification code begins.
245///
246/// See `frame_benchmarking::v2` for more info.
247#[proc_macro_attribute]
248pub fn extrinsic_call(_attrs: TokenStream, _tokens: TokenStream) -> TokenStream {
249	quote!(compile_error!(
250		"`#[extrinsic_call]` must be in a benchmark function definition labeled with `#[benchmark]`."
251	);)
252	.into()
253}
254
255/// An attribute macro used to specify that a block should be the measured portion of the
256/// enclosing benchmark function, This attribute is also used as a boundary designating where
257/// the benchmark setup code ends, and the benchmark verification code begins.
258///
259/// See `frame_benchmarking::v2` for more info.
260#[proc_macro_attribute]
261pub fn block(_attrs: TokenStream, _tokens: TokenStream) -> TokenStream {
262	quote!(compile_error!(
263		"`#[block]` must be in a benchmark function definition labeled with `#[benchmark]`."
264	))
265	.into()
266}
267
268/// Execute the annotated function in a new storage transaction.
269///
270/// The return type of the annotated function must be `Result`. All changes to storage performed
271/// by the annotated function are discarded if it returns `Err`, or committed if `Ok`.
272///
273/// # Example
274///
275/// ```nocompile
276/// #[transactional]
277/// fn value_commits(v: u32) -> result::Result<u32, &'static str> {
278/// 	Value::set(v);
279/// 	Ok(v)
280/// }
281///
282/// #[transactional]
283/// fn value_rollbacks(v: u32) -> result::Result<u32, &'static str> {
284/// 	Value::set(v);
285/// 	Err("nah")
286/// }
287/// ```
288#[proc_macro_attribute]
289pub fn transactional(attr: TokenStream, input: TokenStream) -> TokenStream {
290	transactional::transactional(attr, input).unwrap_or_else(|e| e.to_compile_error().into())
291}
292
293///
294/// ---
295///
296/// Documentation for this macro can be found at `frame_support::require_transactional`.
297#[proc_macro_attribute]
298pub fn require_transactional(attr: TokenStream, input: TokenStream) -> TokenStream {
299	transactional::require_transactional(attr, input)
300		.unwrap_or_else(|e| e.to_compile_error().into())
301}
302
303/// Derive [`Clone`] but do not bound any generic.
304///
305/// Docs at `frame_support::CloneNoBound`.
306#[proc_macro_derive(CloneNoBound)]
307pub fn derive_clone_no_bound(input: TokenStream) -> TokenStream {
308	no_bound::clone::derive_clone_no_bound(input)
309}
310
311/// Derive [`Debug`] but do not bound any generics.
312///
313/// Docs at `frame_support::DebugNoBound`.
314#[proc_macro_derive(DebugNoBound)]
315pub fn derive_debug_no_bound(input: TokenStream) -> TokenStream {
316	no_bound::debug::derive_debug_no_bound(input)
317}
318
319/// Derive [`PartialEq`] but do not bound any generic.
320///
321/// Docs at `frame_support::PartialEqNoBound`.
322#[proc_macro_derive(PartialEqNoBound)]
323pub fn derive_partial_eq_no_bound(input: TokenStream) -> TokenStream {
324	no_bound::partial_eq::derive_partial_eq_no_bound(input)
325}
326
327/// DeriveEq but do no bound any generic.
328///
329/// Docs at `frame_support::EqNoBound`.
330#[proc_macro_derive(EqNoBound)]
331pub fn derive_eq_no_bound(input: TokenStream) -> TokenStream {
332	let input = syn::parse_macro_input!(input as syn::DeriveInput);
333
334	let name = &input.ident;
335	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
336
337	quote::quote_spanned!(name.span() =>
338		#[allow(deprecated)]
339		const _: () = {
340			impl #impl_generics ::core::cmp::Eq for #name #ty_generics #where_clause {}
341		};
342	)
343	.into()
344}
345
346/// Derive [`PartialOrd`] but do not bound any generic. Docs are at
347/// `frame_support::PartialOrdNoBound`.
348#[proc_macro_derive(PartialOrdNoBound)]
349pub fn derive_partial_ord_no_bound(input: TokenStream) -> TokenStream {
350	no_bound::partial_ord::derive_partial_ord_no_bound(input)
351}
352
353/// Derive [`Ord`] but do no bound any generic. Docs are at `frame_support::OrdNoBound`.
354#[proc_macro_derive(OrdNoBound)]
355pub fn derive_ord_no_bound(input: TokenStream) -> TokenStream {
356	no_bound::ord::derive_ord_no_bound(input)
357}
358
359/// derive `Default` but do no bound any generic. Docs are at `frame_support::DefaultNoBound`.
360#[proc_macro_derive(DefaultNoBound, attributes(default))]
361pub fn derive_default_no_bound(input: TokenStream) -> TokenStream {
362	no_bound::default::derive_default_no_bound(input)
363}
364
365/// Macro used internally in FRAME to generate the crate version for a pallet.
366#[proc_macro]
367pub fn crate_to_crate_version(input: TokenStream) -> TokenStream {
368	crate_version::crate_to_crate_version(input)
369		.unwrap_or_else(|e| e.to_compile_error())
370		.into()
371}
372
373/// The number of module instances supported by the runtime, starting at index 1,
374/// and up to `NUMBER_OF_INSTANCE`.
375pub(crate) const NUMBER_OF_INSTANCE: u8 = 16;
376
377/// This macro is meant to be used by frame-support only.
378/// It implements the trait `HasKeyPrefix` and `HasReversibleKeyPrefix` for tuple of `Key`.
379#[proc_macro]
380pub fn impl_key_prefix_for_tuples(input: TokenStream) -> TokenStream {
381	key_prefix::impl_key_prefix_for_tuples(input)
382		.unwrap_or_else(syn::Error::into_compile_error)
383		.into()
384}
385
386/// Internal macro use by frame_support to generate dummy part checker for old pallet declaration
387#[proc_macro]
388pub fn __generate_dummy_part_checker(input: TokenStream) -> TokenStream {
389	dummy_part_checker::generate_dummy_part_checker(input)
390}
391
392/// Macro that inserts some tokens after the first match of some pattern.
393///
394/// # Example:
395///
396/// ```nocompile
397/// match_and_insert!(
398///     target = [{ Some content with { at some point match pattern } other match pattern are ignored }]
399///     pattern = [{ match pattern }] // the match pattern cannot contain any group: `[]`, `()`, `{}`
400/// 								  // can relax this constraint, but will require modifying the match logic in code
401///     tokens = [{ expansion tokens }] // content inside braces can be anything including groups
402/// );
403/// ```
404///
405/// will generate:
406///
407/// ```nocompile
408///     Some content with { at some point match pattern expansion tokens } other match patterns are
409///     ignored
410/// ```
411#[proc_macro]
412pub fn match_and_insert(input: TokenStream) -> TokenStream {
413	match_and_insert::match_and_insert(input)
414}
415
416#[proc_macro_derive(PalletError, attributes(codec))]
417pub fn derive_pallet_error(input: TokenStream) -> TokenStream {
418	pallet_error::derive_pallet_error(input)
419}
420
421/// Internal macro used by `frame_support` to create tt-call-compliant macros
422#[proc_macro]
423pub fn __create_tt_macro(input: TokenStream) -> TokenStream {
424	tt_macro::create_tt_return_macro(input)
425}
426
427///
428/// ---
429///
430/// Documentation for this macro can be found at `frame_support::pallet_macros::storage_alias`.
431#[proc_macro_attribute]
432pub fn storage_alias(attributes: TokenStream, input: TokenStream) -> TokenStream {
433	storage_alias::storage_alias(attributes.into(), input.into())
434		.unwrap_or_else(|r| r.into_compile_error())
435		.into()
436}
437
438/// This attribute can be used to derive a full implementation of a trait based on a local partial
439/// impl and an external impl containing defaults that can be overridden in the local impl.
440///
441/// For a full end-to-end example, see [below](#use-case-auto-derive-test-pallet-config-traits).
442///
443/// # Usage
444///
445/// The attribute should be attached to an impl block (strictly speaking a `syn::ItemImpl`) for
446/// which we want to inject defaults in the event of missing trait items in the block.
447///
448/// The attribute minimally takes a single `default_impl_path` argument, which should be the module
449/// path to an impl registered via [`#[register_default_impl]`](`macro@register_default_impl`) that
450/// contains the default trait items we want to potentially inject, with the general form:
451///
452/// ```ignore
453/// #[derive_impl(default_impl_path)]
454/// impl SomeTrait for SomeStruct {
455///     ...
456/// }
457/// ```
458///
459/// Optionally, a `disambiguation_path` can be specified as follows by providing `as path::here`
460/// after the `default_impl_path`:
461///
462/// ```ignore
463/// #[derive_impl(default_impl_path as disambiguation_path)]
464/// impl SomeTrait for SomeStruct {
465///     ...
466/// }
467/// ```
468///
469/// The `disambiguation_path`, if specified, should be the path to a trait that will be used to
470/// qualify all default entries that are injected into the local impl. For example if your
471/// `default_impl_path` is `some::path::TestTraitImpl` and your `disambiguation_path` is
472/// `another::path::DefaultTrait`, any items injected into the local impl will be qualified as
473/// `<some::path::TestTraitImpl as another::path::DefaultTrait>::specific_trait_item`.
474///
475/// If you omit the `as disambiguation_path` portion, the `disambiguation_path` will internally
476/// default to `A` from the `impl A for B` part of the default impl. This is useful for scenarios
477/// where all of the relevant types are already in scope via `use` statements.
478///
479/// In case the `default_impl_path` is scoped to a different module such as
480/// `some::path::TestTraitImpl`, the same scope is assumed for the `disambiguation_path`, i.e.
481/// `some::A`. This enables the use of `derive_impl` attribute without having to specify the
482/// `disambiguation_path` in most (if not all) uses within FRAME's context.
483///
484/// Conversely, the `default_impl_path` argument is required and cannot be omitted.
485///
486/// Optionally, `no_aggregated_types` can be specified as follows:
487///
488/// ```ignore
489/// #[derive_impl(default_impl_path as disambiguation_path, no_aggregated_types)]
490/// impl SomeTrait for SomeStruct {
491///     ...
492/// }
493/// ```
494///
495/// If specified, this indicates that the aggregated types (as denoted by impl items
496/// attached with [`#[inject_runtime_type]`]) should not be injected with the respective concrete
497/// types. By default, all such types are injected.
498///
499/// You can also make use of `#[pallet::no_default]` on specific items in your default impl that you
500/// want to ensure will not be copied over but that you nonetheless want to use locally in the
501/// context of the foreign impl and the pallet (or context) in which it is defined.
502///
503/// ## Use-Case Example: Auto-Derive Test Pallet Config Traits
504///
505/// The `#[derive_imp(..)]` attribute can be used to derive a test pallet `Config` based on an
506/// existing pallet `Config` that has been marked with
507/// [`#[pallet::config(with_default)]`](`macro@config`) (which under the hood, generates a
508/// `DefaultConfig` trait in the pallet in which the macro was invoked).
509///
510/// In this case, the `#[derive_impl(..)]` attribute should be attached to an `impl` block that
511/// implements a compatible `Config` such as `frame_system::Config` for a test/mock runtime, and
512/// should receive as its first argument the path to a `DefaultConfig` impl that has been registered
513/// via [`#[register_default_impl]`](`macro@register_default_impl`), and as its second argument, the
514/// path to the auto-generated `DefaultConfig` for the existing pallet `Config` we want to base our
515/// test config off of.
516///
517/// The following is what the `basic` example pallet would look like with a default testing config:
518///
519/// ```ignore
520/// #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::pallet::DefaultConfig)]
521/// impl frame_system::Config for Test {
522///     // These are all defined by system as mandatory.
523///     type BaseCallFilter = frame_support::traits::Everything;
524///     type RuntimeEvent = RuntimeEvent;
525///     type RuntimeCall = RuntimeCall;
526///     type RuntimeOrigin = RuntimeOrigin;
527///     type OnSetCode = ();
528///     type PalletInfo = PalletInfo;
529///     type Block = Block;
530///     // We decide to override this one.
531///     type AccountData = pallet_balances::AccountData<u64>;
532/// }
533/// ```
534///
535/// where `TestDefaultConfig` was defined and registered as follows:
536/// ```ignore
537/// pub struct TestDefaultConfig;
538///
539/// #[register_default_impl(TestDefaultConfig)]
540/// impl DefaultConfig for TestDefaultConfig {
541///     type Version = ();
542///     type BlockWeights = ();
543///     type BlockLength = ();
544///     type DbWeight = ();
545///     type Nonce = u64;
546///     type BlockNumber = u64;
547///     type Hash = sp_core::hash::H256;
548///     type Hashing = sp_runtime::traits::BlakeTwo256;
549///     type AccountId = AccountId;
550///     type Lookup = IdentityLookup<AccountId>;
551///     type BlockHashCount = frame_support::traits::ConstU64<10>;
552///     type AccountData = u32;
553///     type OnNewAccount = ();
554///     type OnKilledAccount = ();
555///     type SystemWeightInfo = ();
556///     type SS58Prefix = ();
557///     type MaxConsumers = frame_support::traits::ConstU32<16>;
558/// }
559/// ```
560///
561/// The above call to `derive_impl` would expand to roughly the following:
562/// ```ignore
563/// impl frame_system::Config for Test {
564///     use frame_system::config_preludes::TestDefaultConfig;
565///     use frame_system::pallet::DefaultConfig;
566///
567///     type BaseCallFilter = frame_support::traits::Everything;
568///     type RuntimeEvent = RuntimeEvent;
569///     type RuntimeCall = RuntimeCall;
570///     type RuntimeOrigin = RuntimeOrigin;
571///     type OnSetCode = ();
572///     type PalletInfo = PalletInfo;
573///     type Block = Block;
574///     type AccountData = pallet_balances::AccountData<u64>;
575///     type Version = <TestDefaultConfig as DefaultConfig>::Version;
576///     type BlockWeights = <TestDefaultConfig as DefaultConfig>::BlockWeights;
577///     type BlockLength = <TestDefaultConfig as DefaultConfig>::BlockLength;
578///     type DbWeight = <TestDefaultConfig as DefaultConfig>::DbWeight;
579///     type Nonce = <TestDefaultConfig as DefaultConfig>::Nonce;
580///     type BlockNumber = <TestDefaultConfig as DefaultConfig>::BlockNumber;
581///     type Hash = <TestDefaultConfig as DefaultConfig>::Hash;
582///     type Hashing = <TestDefaultConfig as DefaultConfig>::Hashing;
583///     type AccountId = <TestDefaultConfig as DefaultConfig>::AccountId;
584///     type Lookup = <TestDefaultConfig as DefaultConfig>::Lookup;
585///     type BlockHashCount = <TestDefaultConfig as DefaultConfig>::BlockHashCount;
586///     type OnNewAccount = <TestDefaultConfig as DefaultConfig>::OnNewAccount;
587///     type OnKilledAccount = <TestDefaultConfig as DefaultConfig>::OnKilledAccount;
588///     type SystemWeightInfo = <TestDefaultConfig as DefaultConfig>::SystemWeightInfo;
589///     type SS58Prefix = <TestDefaultConfig as DefaultConfig>::SS58Prefix;
590///     type MaxConsumers = <TestDefaultConfig as DefaultConfig>::MaxConsumers;
591/// }
592/// ```
593///
594/// You can then use the resulting `Test` config in test scenarios.
595///
596/// Note that items that are _not_ present in our local `DefaultConfig` are automatically copied
597/// from the foreign trait (in this case `TestDefaultConfig`) into the local trait impl (in this
598/// case `Test`), unless the trait item in the local trait impl is marked with
599/// [`#[pallet::no_default]`](`macro@no_default`), in which case it cannot be overridden, and any
600/// attempts to do so will result in a compiler error.
601///
602/// See `frame/examples/default-config/tests.rs` for a runnable end-to-end example pallet that makes
603/// use of `derive_impl` to derive its testing config.
604///
605/// See [here](`macro@config`) for more information and caveats about the auto-generated
606/// `DefaultConfig` trait.
607///
608/// ## Optional Conventions
609///
610/// Note that as an optional convention, we encourage creating a `config_preludes` module inside of
611/// your pallet. This is the convention we follow for `frame_system`'s `TestDefaultConfig` which, as
612/// shown above, is located at `frame_system::config_preludes::TestDefaultConfig`. This is just a
613/// suggested convention -- there is nothing in the code that expects modules with these names to be
614/// in place, so there is no imperative to follow this pattern unless desired.
615///
616/// In `config_preludes`, you can place types named like:
617///
618/// * `TestDefaultConfig`
619/// * `ParachainDefaultConfig`
620/// * `SolochainDefaultConfig`
621///
622/// Signifying in which context they can be used.
623///
624/// # Advanced Usage
625///
626/// ## Expansion
627///
628/// The `#[derive_impl(default_impl_path as disambiguation_path)]` attribute will expand to the
629/// local impl, with any extra items from the foreign impl that aren't present in the local impl
630/// also included. In the case of a colliding trait item, the version of the item that exists in the
631/// local impl will be retained. All imported items are qualified by the `disambiguation_path`, as
632/// discussed above.
633///
634/// ## Handling of Unnamed Trait Items
635///
636/// Items that lack a `syn::Ident` for whatever reason are first checked to see if they exist,
637/// verbatim, in the local/destination trait before they are copied over, so you should not need to
638/// worry about collisions between identical unnamed items.
639#[import_tokens_attr_verbatim {
640    format!(
641        "{}::macro_magic",
642        match generate_access_from_frame_or_crate("frame-support") {
643            Ok(path) => Ok(path),
644            Err(_) => generate_access_from_frame_or_crate("polkadot-sdk-frame"),
645        }
646        .expect("Failed to find either `frame-support` or `polkadot-sdk-frame` in `Cargo.toml` dependencies.")
647        .to_token_stream()
648        .to_string()
649    )
650}]
651#[with_custom_parsing(derive_impl::DeriveImplAttrArgs)]
652#[proc_macro_attribute]
653pub fn derive_impl(attrs: TokenStream, input: TokenStream) -> TokenStream {
654	let custom_attrs = parse_macro_input!(__custom_tokens as derive_impl::DeriveImplAttrArgs);
655	derive_impl::derive_impl(
656		__source_path.into(),
657		attrs.into(),
658		input.into(),
659		custom_attrs.disambiguation_path,
660		custom_attrs.no_aggregated_types,
661		custom_attrs.generics,
662	)
663	.unwrap_or_else(|r| r.into_compile_error())
664	.into()
665}
666
667///
668/// ---
669///
670/// Documentation for this macro can be found at `frame_support::pallet_macros::no_default`.
671#[proc_macro_attribute]
672pub fn no_default(_: TokenStream, _: TokenStream) -> TokenStream {
673	pallet_macro_stub()
674}
675
676///
677/// ---
678///
679/// Documentation for this macro can be found at `frame_support::pallet_macros::no_default_bounds`.
680#[proc_macro_attribute]
681pub fn no_default_bounds(_: TokenStream, _: TokenStream) -> TokenStream {
682	pallet_macro_stub()
683}
684
685/// Attach this attribute to an impl statement that you want to use with
686/// [`#[derive_impl(..)]`](`macro@derive_impl`).
687///
688/// You must also provide an identifier/name as the attribute's argument. This is the name you
689/// must provide to [`#[derive_impl(..)]`](`macro@derive_impl`) when you import this impl via
690/// the `default_impl_path` argument. This name should be unique at the crate-level.
691///
692/// ## Example
693///
694/// ```ignore
695/// pub struct ExampleTestDefaultConfig;
696///
697/// #[register_default_impl(ExampleTestDefaultConfig)]
698/// impl DefaultConfig for ExampleTestDefaultConfig {
699/// 	type Version = ();
700/// 	type BlockWeights = ();
701/// 	type BlockLength = ();
702/// 	...
703/// 	type SS58Prefix = ();
704/// 	type MaxConsumers = frame_support::traits::ConstU32<16>;
705/// }
706/// ```
707///
708/// ## Advanced Usage
709///
710/// This macro acts as a thin wrapper around macro_magic's `#[export_tokens]`. See the docs
711/// [here](https://docs.rs/macro_magic/latest/macro_magic/attr.export_tokens.html) for more
712/// info.
713///
714/// There are some caveats when applying a `use` statement to bring a
715/// `#[register_default_impl]` item into scope. If you have a `#[register_default_impl]`
716/// defined in `my_crate::submodule::MyItem`, it is currently not sufficient to do something
717/// like:
718///
719/// ```ignore
720/// use my_crate::submodule::MyItem;
721/// #[derive_impl(MyItem as Whatever)]
722/// ```
723///
724/// This will fail with a mysterious message about `__export_tokens_tt_my_item` not being
725/// defined.
726///
727/// You can, however, do any of the following:
728/// ```ignore
729/// // partial path works
730/// use my_crate::submodule;
731/// #[derive_impl(submodule::MyItem as Whatever)]
732/// ```
733/// ```ignore
734/// // full path works
735/// #[derive_impl(my_crate::submodule::MyItem as Whatever)]
736/// ```
737/// ```ignore
738/// // wild-cards work
739/// use my_crate::submodule::*;
740/// #[derive_impl(MyItem as Whatever)]
741/// ```
742#[proc_macro_attribute]
743pub fn register_default_impl(attrs: TokenStream, tokens: TokenStream) -> TokenStream {
744	// ensure this is a impl statement
745	let item_impl = syn::parse_macro_input!(tokens as ItemImpl);
746
747	// internally wrap macro_magic's `#[export_tokens]` macro
748	match macro_magic::mm_core::export_tokens_internal(
749		attrs,
750		item_impl.to_token_stream(),
751		true,
752		false,
753	) {
754		Ok(tokens) => tokens.into(),
755		Err(err) => err.to_compile_error().into(),
756	}
757}
758
759/// The optional attribute `#[inject_runtime_type]` can be attached to `RuntimeCall`,
760/// `RuntimeEvent`, `RuntimeOrigin` or `PalletInfo` in an impl statement that has
761/// `#[register_default_impl]` attached to indicate that this item is generated by
762/// `construct_runtime`.
763///
764/// Attaching this attribute to such an item ensures that the combined impl generated via
765/// [`#[derive_impl(..)]`](macro@derive_impl) will use the correct type auto-generated by
766/// `construct_runtime!`.
767#[doc = docify::embed!("examples/proc_main/inject_runtime_type.rs", derive_impl_works_with_runtime_type_injection)]
768///
769/// However, if `no_aggregated_types` is specified while using
770/// [`#[derive_impl(..)]`](macro@derive_impl), then these items are attached verbatim to the
771/// combined impl.
772#[doc = docify::embed!("examples/proc_main/inject_runtime_type.rs", derive_impl_works_with_no_aggregated_types)]
773#[proc_macro_attribute]
774pub fn inject_runtime_type(_: TokenStream, tokens: TokenStream) -> TokenStream {
775	let item = tokens.clone();
776	let item = syn::parse_macro_input!(item as TraitItemType);
777	if item.ident != "RuntimeCall" &&
778		item.ident != "RuntimeEvent" &&
779		item.ident != "RuntimeTask" &&
780		item.ident != "RuntimeViewFunction" &&
781		item.ident != "RuntimeOrigin" &&
782		item.ident != "RuntimeHoldReason" &&
783		item.ident != "RuntimeFreezeReason" &&
784		item.ident != "RuntimeParameters" &&
785		item.ident != "PalletInfo"
786	{
787		return syn::Error::new_spanned(
788			item,
789			"`#[inject_runtime_type]` can only be attached to `RuntimeCall`, `RuntimeEvent`, \
790			`RuntimeTask`, `RuntimeViewFunction`, `RuntimeOrigin`, `RuntimeParameters` or `PalletInfo`",
791		)
792		.to_compile_error()
793		.into();
794	}
795	tokens
796}
797
798/// Used internally to decorate pallet attribute macro stubs when they are erroneously used
799/// outside of a pallet module
800fn pallet_macro_stub() -> TokenStream {
801	quote!(compile_error!(
802		"This attribute can only be used from within a pallet module marked with `#[frame_support::pallet]`"
803	))
804	.into()
805}
806
807///
808/// ---
809///
810/// Documentation for this macro can be found at `frame_support::pallet_macros::config`.
811#[proc_macro_attribute]
812pub fn config(_: TokenStream, _: TokenStream) -> TokenStream {
813	pallet_macro_stub()
814}
815
816///
817/// ---
818///
819/// Documentation for this macro can be found at `frame_support::pallet_macros::constant`.
820#[proc_macro_attribute]
821pub fn constant(_: TokenStream, _: TokenStream) -> TokenStream {
822	pallet_macro_stub()
823}
824
825///
826/// ---
827///
828/// Documentation for this macro can be found at `frame_support::pallet_macros::constant_name`.
829#[proc_macro_attribute]
830pub fn constant_name(_: TokenStream, _: TokenStream) -> TokenStream {
831	pallet_macro_stub()
832}
833
834///
835/// ---
836///
837/// Documentation for this macro can be found at
838/// `frame_support::pallet_macros::disable_frame_system_supertrait_check`.
839#[proc_macro_attribute]
840pub fn disable_frame_system_supertrait_check(_: TokenStream, _: TokenStream) -> TokenStream {
841	pallet_macro_stub()
842}
843
844///
845/// ---
846///
847/// Documentation for this macro can be found at `frame_support::pallet_macros::storage_version`.
848#[proc_macro_attribute]
849pub fn storage_version(_: TokenStream, _: TokenStream) -> TokenStream {
850	pallet_macro_stub()
851}
852
853///
854/// ---
855///
856/// Documentation for this macro can be found at `frame_support::pallet_macros::hooks`.
857#[proc_macro_attribute]
858pub fn hooks(_: TokenStream, _: TokenStream) -> TokenStream {
859	pallet_macro_stub()
860}
861
862///
863/// ---
864///
865/// Documentation for this macro can be found at `frame_support::pallet_macros::weight`.
866#[proc_macro_attribute]
867pub fn weight(_: TokenStream, _: TokenStream) -> TokenStream {
868	pallet_macro_stub()
869}
870
871///
872/// ---
873///
874/// Documentation for this macro can be found at `frame_support::pallet_macros::compact`.
875#[proc_macro_attribute]
876pub fn compact(_: TokenStream, _: TokenStream) -> TokenStream {
877	pallet_macro_stub()
878}
879
880///
881/// ---
882///
883/// Documentation for this macro can be found at `frame_support::pallet_macros::call`.
884#[proc_macro_attribute]
885pub fn call(_: TokenStream, _: TokenStream) -> TokenStream {
886	pallet_macro_stub()
887}
888
889/// Each dispatchable may also be annotated with the `#[pallet::call_index($idx)]` attribute,
890/// which explicitly defines the codec index for the dispatchable function in the `Call` enum.
891///
892/// ---
893///
894/// Documentation for this macro can be found at `frame_support::pallet_macros::call_index`.
895#[proc_macro_attribute]
896pub fn call_index(_: TokenStream, _: TokenStream) -> TokenStream {
897	pallet_macro_stub()
898}
899
900///
901/// ---
902///
903/// Documentation for this macro can be found at `frame_support::pallet_macros::feeless_if`.
904#[proc_macro_attribute]
905pub fn feeless_if(_: TokenStream, _: TokenStream) -> TokenStream {
906	pallet_macro_stub()
907}
908
909///
910/// ---
911///
912/// Documentation for this macro can be found at `frame_support::pallet_macros::extra_constants`.
913#[proc_macro_attribute]
914pub fn extra_constants(_: TokenStream, _: TokenStream) -> TokenStream {
915	pallet_macro_stub()
916}
917
918///
919/// ---
920///
921/// Documentation for this macro can be found at `frame_support::pallet_macros::error`.
922#[proc_macro_attribute]
923pub fn error(_: TokenStream, _: TokenStream) -> TokenStream {
924	pallet_macro_stub()
925}
926
927///
928/// ---
929///
930/// Documentation for this macro can be found at `frame_support::pallet_macros::event`.
931#[proc_macro_attribute]
932pub fn event(_: TokenStream, _: TokenStream) -> TokenStream {
933	pallet_macro_stub()
934}
935
936///
937/// ---
938///
939/// Documentation for this macro can be found at `frame_support::pallet_macros::include_metadata`.
940#[proc_macro_attribute]
941pub fn include_metadata(_: TokenStream, _: TokenStream) -> TokenStream {
942	pallet_macro_stub()
943}
944
945///
946/// ---
947///
948/// Documentation for this macro can be found at `frame_support::pallet_macros::generate_deposit`.
949#[proc_macro_attribute]
950pub fn generate_deposit(_: TokenStream, _: TokenStream) -> TokenStream {
951	pallet_macro_stub()
952}
953
954///
955/// ---
956///
957/// Documentation for this macro can be found at `frame_support::pallet_macros::storage`.
958#[proc_macro_attribute]
959pub fn storage(_: TokenStream, _: TokenStream) -> TokenStream {
960	pallet_macro_stub()
961}
962
963///
964/// ---
965///
966/// Documentation for this macro can be found at `frame_support::pallet_macros::getter`.
967#[proc_macro_attribute]
968pub fn getter(_: TokenStream, _: TokenStream) -> TokenStream {
969	pallet_macro_stub()
970}
971
972///
973/// ---
974///
975/// Documentation for this macro can be found at `frame_support::pallet_macros::storage_prefix`.
976#[proc_macro_attribute]
977pub fn storage_prefix(_: TokenStream, _: TokenStream) -> TokenStream {
978	pallet_macro_stub()
979}
980
981///
982/// ---
983///
984/// Documentation for this macro can be found at `frame_support::pallet_macros::unbounded`.
985#[proc_macro_attribute]
986pub fn unbounded(_: TokenStream, _: TokenStream) -> TokenStream {
987	pallet_macro_stub()
988}
989
990///
991/// ---
992///
993/// Documentation for this macro can be found at `frame_support::pallet_macros::whitelist_storage`.
994#[proc_macro_attribute]
995pub fn whitelist_storage(_: TokenStream, _: TokenStream) -> TokenStream {
996	pallet_macro_stub()
997}
998
999///
1000/// ---
1001///
1002/// Documentation for this macro can be found at
1003/// `frame_support::pallet_macros::disable_try_decode_storage`.
1004#[proc_macro_attribute]
1005pub fn disable_try_decode_storage(_: TokenStream, _: TokenStream) -> TokenStream {
1006	pallet_macro_stub()
1007}
1008
1009///
1010/// ---
1011///
1012/// Documentation for this macro can be found at `frame_support::pallet_macros::type_value`.
1013#[proc_macro_attribute]
1014pub fn type_value(_: TokenStream, _: TokenStream) -> TokenStream {
1015	pallet_macro_stub()
1016}
1017
1018///
1019/// ---
1020///
1021/// Documentation for this macro can be found at `frame_support::pallet_macros::genesis_config`.
1022#[proc_macro_attribute]
1023pub fn genesis_config(_: TokenStream, _: TokenStream) -> TokenStream {
1024	pallet_macro_stub()
1025}
1026
1027///
1028/// ---
1029///
1030/// Documentation for this macro can be found at `frame_support::pallet_macros::genesis_build`.
1031#[proc_macro_attribute]
1032pub fn genesis_build(_: TokenStream, _: TokenStream) -> TokenStream {
1033	pallet_macro_stub()
1034}
1035
1036///
1037/// ---
1038///
1039/// Documentation for this macro can be found at `frame_support::pallet_macros::inherent`.
1040#[proc_macro_attribute]
1041pub fn inherent(_: TokenStream, _: TokenStream) -> TokenStream {
1042	pallet_macro_stub()
1043}
1044
1045///
1046/// ---
1047///
1048/// Documentation for this macro can be found at `frame_support::pallet_macros::validate_unsigned`.
1049#[proc_macro_attribute]
1050pub fn validate_unsigned(_: TokenStream, _: TokenStream) -> TokenStream {
1051	pallet_macro_stub()
1052}
1053
1054///
1055/// ---
1056///
1057/// Documentation for this macro can be found at
1058/// `frame_support::pallet_macros::view_functions`.
1059#[proc_macro_attribute]
1060pub fn view_functions(_: TokenStream, _: TokenStream) -> TokenStream {
1061	pallet_macro_stub()
1062}
1063
1064///
1065/// ---
1066///
1067/// Documentation for this macro can be found at `frame_support::pallet_macros::origin`.
1068#[proc_macro_attribute]
1069pub fn origin(_: TokenStream, _: TokenStream) -> TokenStream {
1070	pallet_macro_stub()
1071}
1072
1073///
1074/// ---
1075///
1076/// Documentation for this macro can be found at `frame_support::pallet_macros::composite_enum`.
1077#[proc_macro_attribute]
1078pub fn composite_enum(_: TokenStream, _: TokenStream) -> TokenStream {
1079	pallet_macro_stub()
1080}
1081
1082/// Allows you to define some service work that can be recognized by the off-chain worker.
1083///
1084/// The off-chain worker can then create and submit all such work items at any given time.
1085///
1086/// These work items are defined as instances of the `Task` trait (found at
1087/// `frame_support::traits::Task`). [`pallet:tasks_experimental`](macro@tasks_experimental) when
1088/// attached to an `impl` block inside a pallet, will generate an enum `Task<T>` whose variants
1089/// are mapped to functions inside this `impl` block.
1090///
1091/// Each such function must have the following set of attributes:
1092///
1093/// * [`pallet::task_list`](macro@task_list)
1094/// * [`pallet::task_condition`](macro@task_condition)
1095/// * [`pallet::task_weight`](macro@task_weight)
1096/// * [`pallet::task_index`](macro@task_index)
1097///
1098/// All of such Tasks are then aggregated into a `RuntimeTask` by
1099/// [`construct_runtime`](macro@construct_runtime).
1100///
1101/// Finally, the `RuntimeTask` can then be used by the off-chain worker to create and
1102/// submit such tasks via an extrinsic defined in `frame_system` called `do_task` which accepts
1103/// unsigned transaction from local source.
1104///
1105/// When submitted as unsigned transactions, note that the tasks will be executed in a random order.
1106///
1107/// ## Example
1108#[doc = docify::embed!("examples/proc_main/tasks.rs", tasks_example)]
1109/// Now, this can be executed as follows:
1110#[doc = docify::embed!("examples/proc_main/tasks.rs", tasks_work)]
1111#[proc_macro_attribute]
1112pub fn tasks_experimental(_: TokenStream, _: TokenStream) -> TokenStream {
1113	pallet_macro_stub()
1114}
1115
1116/// Allows defining an iterator over available work items for a task.
1117///
1118/// This attribute is attached to a function inside an `impl` block annotated with
1119/// [`pallet::tasks_experimental`](macro@tasks_experimental).
1120///
1121/// It takes an iterator as input that yields a tuple with same types as the function
1122/// arguments.
1123#[proc_macro_attribute]
1124pub fn task_list(_: TokenStream, _: TokenStream) -> TokenStream {
1125	pallet_macro_stub()
1126}
1127
1128/// Allows defining conditions for a task to run.
1129///
1130/// This attribute is attached to a function inside an `impl` block annotated with
1131/// [`pallet::tasks_experimental`](macro@tasks_experimental) to define the conditions for a
1132/// given work item to be valid.
1133///
1134/// It takes a closure as input, which is then used to define the condition. The closure
1135/// should have the same signature as the function it is attached to, except that it should
1136/// return a `bool` instead.
1137#[proc_macro_attribute]
1138pub fn task_condition(_: TokenStream, _: TokenStream) -> TokenStream {
1139	pallet_macro_stub()
1140}
1141
1142/// Allows defining the weight of a task.
1143///
1144/// This attribute is attached to a function inside an `impl` block annotated with
1145/// [`pallet::tasks_experimental`](macro@tasks_experimental) define the weight of a given work
1146/// item.
1147///
1148/// It takes a closure as input, which should return a `Weight` value.
1149#[proc_macro_attribute]
1150pub fn task_weight(_: TokenStream, _: TokenStream) -> TokenStream {
1151	pallet_macro_stub()
1152}
1153
1154/// Allows defining an index for a task.
1155///
1156/// This attribute is attached to a function inside an `impl` block annotated with
1157/// [`pallet::tasks_experimental`](macro@tasks_experimental) to define the index of a given
1158/// work item.
1159///
1160/// It takes an integer literal as input, which is then used to define the index. This
1161/// index should be unique for each function in the `impl` block.
1162#[proc_macro_attribute]
1163pub fn task_index(_: TokenStream, _: TokenStream) -> TokenStream {
1164	pallet_macro_stub()
1165}
1166
1167///
1168/// ---
1169///
1170/// **Rust-Analyzer users**: See the documentation of the Rust item in
1171/// `frame_support::pallet_macros::pallet_section`.
1172#[proc_macro_attribute]
1173pub fn pallet_section(attr: TokenStream, tokens: TokenStream) -> TokenStream {
1174	let tokens_clone = tokens.clone();
1175	// ensure this can only be attached to a module
1176	let _mod = parse_macro_input!(tokens_clone as ItemMod);
1177
1178	// use macro_magic's export_tokens as the internal implementation otherwise
1179	match macro_magic::mm_core::export_tokens_internal(attr, tokens, false, true) {
1180		Ok(tokens) => tokens.into(),
1181		Err(err) => err.to_compile_error().into(),
1182	}
1183}
1184
1185///
1186/// ---
1187///
1188/// **Rust-Analyzer users**: See the documentation of the Rust item in
1189/// `frame_support::pallet_macros::import_section`.
1190#[import_tokens_attr {
1191    format!(
1192        "{}::macro_magic",
1193        match generate_access_from_frame_or_crate("frame-support") {
1194            Ok(path) => Ok(path),
1195            Err(_) => generate_access_from_frame_or_crate("polkadot-sdk-frame"),
1196        }
1197        .expect("Failed to find either `frame-support` or `polkadot-sdk-frame` in `Cargo.toml` dependencies.")
1198        .to_token_stream()
1199        .to_string()
1200    )
1201}]
1202#[proc_macro_attribute]
1203pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream {
1204	let foreign_mod = parse_macro_input!(attr as ItemMod);
1205	let mut internal_mod = parse_macro_input!(tokens as ItemMod);
1206
1207	// check that internal_mod is a pallet module
1208	if !internal_mod.attrs.iter().any(|attr| {
1209		if let Some(last_seg) = attr.path().segments.last() {
1210			last_seg.ident == "pallet"
1211		} else {
1212			false
1213		}
1214	}) {
1215		return Error::new(
1216			internal_mod.ident.span(),
1217			"`#[import_section]` can only be applied to a valid pallet module",
1218		)
1219		.to_compile_error()
1220		.into();
1221	}
1222
1223	if let Some(ref mut content) = internal_mod.content {
1224		if let Some(foreign_content) = foreign_mod.content {
1225			content.1.extend(foreign_content.1);
1226		}
1227	}
1228
1229	quote! {
1230		#internal_mod
1231	}
1232	.into()
1233}
1234
1235/// Construct a runtime, with the given name and the given pallets.
1236///
1237/// # Example:
1238#[doc = docify::embed!("examples/proc_main/runtime.rs", runtime_macro)]
1239///
1240/// # Supported Attributes:
1241///
1242/// ## Legacy Ordering
1243///
1244/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to
1245/// ensure that the order of hooks is same as the order of pallets (and not based on the
1246/// pallet_index). This is to support legacy runtimes and should be avoided for new ones.
1247///
1248/// # Note
1249///
1250/// The population of the genesis storage depends on the order of pallets. So, if one of your
1251/// pallets depends on another pallet, the pallet that is depended upon needs to come before
1252/// the pallet depending on it.
1253///
1254/// # Type definitions
1255///
1256/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System =
1257///   frame_system::Pallet<Runtime>`
1258#[proc_macro_attribute]
1259pub fn runtime(attr: TokenStream, item: TokenStream) -> TokenStream {
1260	runtime::runtime(attr, item)
1261}
1262
1263/// Mark a module that contains dynamic parameters.
1264///
1265/// See the `pallet_parameters` for a full example.
1266///
1267/// # Arguments
1268///
1269/// The macro accepts two positional arguments, of which the second is optional.
1270///
1271/// ## Aggregated Enum Name
1272///
1273/// This sets the name that the aggregated Key-Value enum will be named after. Common names would be
1274/// `RuntimeParameters`, akin to `RuntimeCall`, `RuntimeOrigin` etc. There is no default value for
1275/// this argument.
1276///
1277/// ## Parameter Storage Backend
1278///
1279/// The second argument provides access to the storage of the parameters. It can either be set on
1280/// on this attribute, or on the inner ones. If set on both, the inner one takes precedence.
1281#[proc_macro_attribute]
1282pub fn dynamic_params(attrs: TokenStream, input: TokenStream) -> TokenStream {
1283	dynamic_params::dynamic_params(attrs.into(), input.into())
1284		.unwrap_or_else(|r| r.into_compile_error())
1285		.into()
1286}
1287
1288/// Define a module inside a [`macro@dynamic_params`] module that contains dynamic parameters.
1289///
1290/// See the `pallet_parameters` for a full example.
1291///
1292/// # Argument
1293///
1294/// This attribute takes one optional argument. The argument can either be put here or on the
1295/// surrounding `#[dynamic_params]` attribute. If set on both, the inner one takes precedence.
1296#[proc_macro_attribute]
1297pub fn dynamic_pallet_params(attrs: TokenStream, input: TokenStream) -> TokenStream {
1298	dynamic_params::dynamic_pallet_params(attrs.into(), input.into())
1299		.unwrap_or_else(|r| r.into_compile_error())
1300		.into()
1301}
1302
1303/// Used internally by [`dynamic_params`].
1304#[doc(hidden)]
1305#[proc_macro_attribute]
1306pub fn dynamic_aggregated_params_internal(attrs: TokenStream, input: TokenStream) -> TokenStream {
1307	dynamic_params::dynamic_aggregated_params_internal(attrs.into(), input.into())
1308		.unwrap_or_else(|r| r.into_compile_error())
1309		.into()
1310}
1311
1312/// Allows to authorize some general transactions with specific dispatchable functions
1313/// (dispatchable functions a.k.a. calls).
1314///
1315/// This attribute allows to specify a special validation logic for a specific call.
1316/// A general transaction with this specific call can then be validated by the given function,
1317/// and if valid then dispatched with the origin `frame_system::Origin::Authorized`.
1318///
1319/// To ensure the origin of the call is the authorization process, the call must check the origin
1320/// with `frame_system::ensure_authorized` function.
1321///
1322/// To enable the authorization process on the extrinsic, the runtime must use
1323/// `frame_system::AuthorizeCall` transaction extension in the transaction extension pipeline.
1324///
1325/// To enable the creation of authorized call from offchain worker. The runtime should implement
1326/// `frame_system::CreateAuthorizedTransaction`. This trait allows to specify which transaction
1327/// extension to use when creating a transaction for an authorized call.
1328///
1329/// # Usage in the pallet
1330///
1331/// ## Example/Overview:
1332///
1333/// ```
1334/// # #[allow(unused)]
1335/// #[frame_support::pallet]
1336/// pub mod pallet {
1337///     use frame_support::pallet_prelude::*;
1338///     use frame_system::pallet_prelude::*;
1339///
1340///     #[pallet::pallet]
1341///     pub struct Pallet<T>(_);
1342///
1343///     #[pallet::config]
1344///     pub trait Config: frame_system::Config {}
1345///
1346///     #[pallet::call]
1347///     impl<T: Config> Pallet<T> {
1348///         #[pallet::weight(Weight::zero())]
1349///         #[pallet::authorize(|_source, foo| if *foo == 42 {
1350///             // The amount to refund, here we refund nothing
1351///             let refund = Weight::zero();
1352///             // The validity, here we accept the call and it provides itself.
1353///             // See `ValidTransaction` for more information.
1354///             let validity = ValidTransaction::with_tag_prefix("my-pallet")
1355///                 .and_provides("some_call")
1356///                 .into();
1357///             Ok((validity, refund))
1358///         } else {
1359///             Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
1360///         })]
1361///         #[pallet::weight_of_authorize(Weight::zero())]
1362///         #[pallet::call_index(0)]
1363///         pub fn some_call(origin: OriginFor<T>, arg: u32) -> DispatchResult {
1364///             ensure_authorized(origin)?;
1365///
1366///             Ok(())
1367///         }
1368///
1369///         #[pallet::weight(Weight::zero())]
1370///         // We can also give the callback as a function
1371///         #[pallet::authorize(Self::authorize_some_other_call)]
1372///         #[pallet::weight_of_authorize(Weight::zero())]
1373///         #[pallet::call_index(1)]
1374///         pub fn some_other_call(origin: OriginFor<T>, arg: u32) -> DispatchResult {
1375///             ensure_authorized(origin)?;
1376///
1377///             Ok(())
1378///         }
1379///     }
1380///
1381///     impl<T: Config> Pallet<T> {
1382///         fn authorize_some_other_call(
1383///             source: TransactionSource,
1384///             foo: &u32
1385///         ) -> TransactionValidityWithRefund {
1386///             if *foo == 42 {
1387///                 let refund = Weight::zero();
1388///                 let validity = ValidTransaction::default();
1389///                 Ok((validity, refund))
1390///             } else {
1391///                 Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
1392///             }
1393///         }
1394///     }
1395///
1396///     #[frame_benchmarking::v2::benchmarks]
1397///     mod benchmarks {
1398///         use super::*;
1399///         use frame_benchmarking::v2::BenchmarkError;
1400///
1401///         #[benchmark]
1402///         fn authorize_some_call() -> Result<(), BenchmarkError> {
1403///             let call = Call::<T>::some_call { arg: 42 };
1404///
1405///             #[block]
1406///             {
1407///                 use frame_support::pallet_prelude::Authorize;
1408///                 call.authorize(TransactionSource::External)
1409///                     .ok_or("Call must give some authorization")??;
1410///             }
1411///
1412///             Ok(())
1413///         }
1414///     }
1415/// }
1416/// ```
1417///
1418/// ## Specification:
1419///
1420/// Authorize process comes with 2 attributes macro on top of the authorized call:
1421///
1422/// * `#[pallet::authorize($authorized_function)]` - defines the function that authorizes the call.
1423///   First argument is the transaction source `TransactionSource` then followed by the same as call
1424///   arguments but by reference `&`. Return type is `TransactionValidityWithRefund`.
1425/// * `#[pallet::weight_of_authorize($weight)]` - defines the value of the weight of the authorize
1426///   function. This attribute is similar to `#[pallet::weight]`:
1427///   * it can be ignore in `dev_mode`
1428///   * it can be automatically infered from weight info. For the call `foo` the function
1429///     `authorize_foo` in the weight info will be used. (weight info needs to be provided in the
1430///     call attribute: `#[pallet::call(weight = T::WeightInfo)]`).
1431///   * it can be a fixed value like `Weight::from_all(0)` (not recommended in production).
1432///
1433///   The weight must be small enough so that nodes don't get DDOS by validating transactions.
1434///
1435/// Then in the call it must be ensured that the origin is the authorization process. This can
1436/// be done using `frame_system::ensure_authorized` function.
1437///
1438/// # The macro expansion
1439///
1440/// From the given "authorize" function and weight, the macro will implement the trait
1441/// `Authorize` on the call.
1442///
1443/// # How to benchmark
1444///
1445/// The authorize function is used as the implementation of the trait
1446/// `Authorize` for the call.
1447/// To benchmark a call variant, use the function
1448/// `Authorize::authorize` on a call value.
1449/// See the example in the first section.
1450#[proc_macro_attribute]
1451pub fn authorize(_: TokenStream, _: TokenStream) -> TokenStream {
1452	pallet_macro_stub()
1453}
1454
1455/// Allows to define the weight of the authorize function.
1456///
1457/// See [`authorize`](macro@authorize) for more information on how authorization works.
1458///
1459/// Defines the value of the weight of the authorize function. This attribute is similar to
1460/// `#[pallet::weight]`:
1461/// * it can be ignore in `dev_mode`
1462/// * it can be automatically infered from weight info. For the call `foo` the function
1463///   `authorize_foo` in the weight info will be used.
1464/// * it can be a fixed value like `Weight::from_all(0)` (not recommended in production).
1465#[proc_macro_attribute]
1466pub fn weight_of_authorize(_: TokenStream, _: TokenStream) -> TokenStream {
1467	pallet_macro_stub()
1468}