Skip to main content

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