referrerpolicy=no-referrer-when-downgrade

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