From 496bbac0eb4e9262d6f49d2bef5ab913686a9d44 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 4 Sep 2023 11:11:39 +0530 Subject: [PATCH 01/48] Moves from older repo --- .../bin/node-template/runtime/src/lib.rs | 23 +- substrate/bin/node/runtime/src/lib.rs | 31 +- .../procedural/src/construct_runtime/mod.rs | 14 +- .../procedural/src/construct_runtime/parse.rs | 8 +- .../src/construct_runtime_v2/expand/mod.rs | 289 ++++++++++++++++++ .../src/construct_runtime_v2/mod.rs | 30 ++ .../src/construct_runtime_v2/parse/helper.rs | 37 +++ .../src/construct_runtime_v2/parse/mod.rs | 144 +++++++++ .../src/construct_runtime_v2/parse/pallet.rs | 176 +++++++++++ .../construct_runtime_v2/parse/pallet_decl.rs | 72 +++++ .../src/construct_runtime_v2/parse/pallets.rs | 117 +++++++ .../parse/runtime_struct.rs | 35 +++ .../parse/runtime_types.rs | 70 +++++ substrate/frame/support/procedural/src/lib.rs | 6 + .../src/pallet/expand/tt_default_parts.rs | 72 +++++ .../support/procedural/src/pallet/mod.rs | 2 +- substrate/frame/support/src/lib.rs | 2 +- 17 files changed, 1098 insertions(+), 30 deletions(-) create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs create mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 216be9588bca..e447a4e28e60 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -279,8 +279,23 @@ impl pallet_template::Config for Runtime { } // Create the runtime by composing the FRAME pallets that were previously configured. -construct_runtime!( - pub struct Runtime { +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId + )] + pub struct Pallets { System: frame_system, Timestamp: pallet_timestamp, Aura: pallet_aura, @@ -289,9 +304,11 @@ construct_runtime!( TransactionPayment: pallet_transaction_payment, Sudo: pallet_sudo, // Include the custom logic from the pallet-template in the runtime. + #[frame::pallet_index(8)] + #[frame::disable_call] TemplateModule: pallet_template, } -); +} /// The address format for describing accounts. pub type Address = sp_runtime::MultiAddress; diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 4f34e4ecd812..03ac51eb34a3 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -28,7 +28,6 @@ use frame_election_provider_support::{ onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight, }; use frame_support::{ - construct_runtime, dispatch::DispatchClass, instances::{Instance1, Instance2}, ord_parameter_types, @@ -2009,9 +2008,13 @@ impl pallet_broker::Config for Runtime { type PriceAdapter = pallet_broker::Linear; } -construct_runtime!( - pub struct Runtime - { +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + pub struct Pallets { System: frame_system, Utility: pallet_utility, Babe: pallet_babe, @@ -2028,10 +2031,10 @@ construct_runtime!( Staking: pallet_staking, Session: pallet_session, Democracy: pallet_democracy, - Council: pallet_collective::, - TechnicalCommittee: pallet_collective::, + Council: pallet_collective, + TechnicalCommittee: pallet_collective, Elections: pallet_elections_phragmen, - TechnicalMembership: pallet_membership::, + TechnicalMembership: pallet_membership, Grandpa: pallet_grandpa, Treasury: pallet_treasury, AssetRate: pallet_asset_rate, @@ -2040,7 +2043,7 @@ construct_runtime!( ImOnline: pallet_im_online, AuthorityDiscovery: pallet_authority_discovery, Offences: pallet_offences, - Historical: pallet_session_historical::{Pallet}, + Historical: pallet_session_historical + Pallet, RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, Identity: pallet_identity, Society: pallet_society, @@ -2053,8 +2056,8 @@ construct_runtime!( Multisig: pallet_multisig, Bounties: pallet_bounties, Tips: pallet_tips, - Assets: pallet_assets::, - PoolAssets: pallet_assets::, + Assets: pallet_assets, + PoolAssets: pallet_assets, Mmr: pallet_mmr, Lottery: pallet_lottery, Nis: pallet_nis, @@ -2064,7 +2067,7 @@ construct_runtime!( Salary: pallet_salary, CoreFellowship: pallet_core_fellowship, TransactionStorage: pallet_transaction_storage, - VoterList: pallet_bags_list::, + VoterList: pallet_bags_list, StateTrieMigration: pallet_state_trie_migration, ChildBounties: pallet_child_bounties, Referenda: pallet_referenda, @@ -2072,10 +2075,10 @@ construct_runtime!( RootTesting: pallet_root_testing, ConvictionVoting: pallet_conviction_voting, Whitelist: pallet_whitelist, - AllianceMotion: pallet_collective::, + AllianceMotion: pallet_collective, Alliance: pallet_alliance, NominationPools: pallet_nomination_pools, - RankedPolls: pallet_referenda::, + RankedPolls: pallet_referenda, RankedCollective: pallet_ranked_collective, AssetConversion: pallet_asset_conversion, FastUnstake: pallet_fast_unstake, @@ -2086,7 +2089,7 @@ construct_runtime!( Statement: pallet_statement, Broker: pallet_broker, } -); +} /// The address format for describing accounts. pub type Address = sp_runtime::MultiAddress; diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index f42dd837e3a9..162596b9c71c 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -208,8 +208,8 @@ //! This macro returns the ` :: expanded { Error }` list of additional parts we would like to //! expose. -mod expand; -mod parse; +pub mod expand; +pub mod parse; use cfg_expr::Predicate; use frame_support_procedural_tools::{ @@ -496,7 +496,7 @@ fn construct_runtime_final_expansion( Ok(res) } -fn decl_all_pallets<'a>( +pub fn decl_all_pallets<'a>( runtime: &'a Ident, pallet_declarations: impl Iterator, features: &HashSet<&str>, @@ -660,7 +660,7 @@ fn decl_all_pallets<'a>( ) } -fn decl_pallet_runtime_setup( +pub fn decl_pallet_runtime_setup( runtime: &Ident, pallet_declarations: &[Pallet], scrate: &TokenStream2, @@ -752,7 +752,7 @@ fn decl_pallet_runtime_setup( ) } -fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { +pub fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { quote!( #[cfg(test)] mod __construct_runtime_integrity_test { @@ -767,7 +767,7 @@ fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { ) } -fn decl_static_assertions( +pub fn decl_static_assertions( runtime: &Ident, pallet_decls: &[Pallet], scrate: &TokenStream2, @@ -798,7 +798,7 @@ fn decl_static_assertions( } } -fn check_pallet_number(input: TokenStream2, pallet_num: usize) -> Result<()> { +pub fn check_pallet_number(input: TokenStream2, pallet_num: usize) -> Result<()> { let max_pallet_num = { if cfg!(feature = "tuples-96") { 96 diff --git a/substrate/frame/support/procedural/src/construct_runtime/parse.rs b/substrate/frame/support/procedural/src/construct_runtime/parse.rs index 9b08e1646975..b407b897e410 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/parse.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/parse.rs @@ -446,7 +446,7 @@ impl Parse for PalletPartKeyword { impl PalletPartKeyword { /// Returns the name of `Self`. - fn name(&self) -> &'static str { + pub fn name(&self) -> &'static str { match self { Self::Pallet(_) => "Pallet", Self::Call(_) => "Call", @@ -465,12 +465,12 @@ impl PalletPartKeyword { } /// Returns `true` if this pallet part is allowed to have generic arguments. - fn allows_generic(&self) -> bool { + pub fn allows_generic(&self) -> bool { Self::all_generic_arg().iter().any(|n| *n == self.name()) } /// Returns the names of all pallet parts that allow to have a generic argument. - fn all_generic_arg() -> &'static [&'static str] { + pub fn all_generic_arg() -> &'static [&'static str] { &["Event", "Error", "Origin", "Config"] } } @@ -552,7 +552,7 @@ fn remove_kind( /// The declaration of a part without its generics #[derive(Debug, Clone)] pub struct PalletPartNoGeneric { - keyword: PalletPartKeyword, + pub keyword: PalletPartKeyword, } impl Parse for PalletPartNoGeneric { diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs new file mode 100644 index 000000000000..e11bd71407a0 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -0,0 +1,289 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::construct_runtime_v2::{ + parse::pallets::{ + AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, + }, + Def, +}; +use cfg_expr::Predicate; +use frame_support_procedural_tools::{ + generate_crate_access, generate_crate_access_2018, generate_hidden_includes, +}; +use proc_macro2::TokenStream as TokenStream2; +use quote::quote; +use std::collections::HashSet; +use syn::{Ident, Result}; + +use crate::construct_runtime::{check_pallet_number, expand}; + +use crate::construct_runtime::{ + decl_all_pallets, decl_integrity_test, decl_pallet_runtime_setup, decl_static_assertions, +}; + +use super::parse::runtime_types::RuntimeType; + +/// The fixed name of the system pallet. +const SYSTEM_PALLET_NAME: &str = "System"; + +pub fn expand(def: Def) -> proc_macro2::TokenStream { + let input = def.input; + + let res = match def.pallets { + AllPalletsDeclaration::Implicit(ref decl) => + check_pallet_number(input.clone(), decl.pallet_count) + .and_then(|_| construct_runtime_implicit_to_explicit(input.into(), decl.clone())), + AllPalletsDeclaration::Explicit(ref decl) => check_pallet_number(input, decl.pallets.len()) + .and_then(|_| { + construct_runtime_final_expansion( + def.runtime_struct.ident.clone(), + decl.clone(), + def.runtime_types.clone(), + ) + }), + }; + + let res = res.unwrap_or_else(|e| e.to_compile_error()); + + let res = expander::Expander::new("construct_runtime") + .dry(std::env::var("FRAME_EXPAND").is_err()) + .verbose(true) + .write_to_out_dir(res) + .expect("Does not fail because of IO in OUT_DIR; qed"); + + res.into() +} + +fn construct_runtime_implicit_to_explicit( + input: TokenStream2, + definition: ImplicitAllPalletsDeclaration, +) -> Result { + let frame_support = generate_crate_access_2018("frame-support")?; + let mut expansion = quote::quote!( + #[frame_support::construct_runtime_v2] + #input + ); + for pallet in definition.pallet_decls.iter() { + let pallet_path = &pallet.path; + let pallet_name = &pallet.name; + let pallet_instance = pallet.instance.as_ref().map(|instance| quote::quote!(<#instance>)); + expansion = quote::quote!( + #frame_support::__private::tt_call! { + macro = [{ #pallet_path::tt_default_parts_v2 }] + frame_support = [{ #frame_support }] + ~~> #frame_support::match_and_insert! { + target = [{ #expansion }] + pattern = [{ #pallet_name: #pallet_path #pallet_instance }] + } + } + ); + } + + Ok(expansion) +} + +fn construct_runtime_final_expansion( + name: Ident, + definition: ExplicitAllPalletsDeclaration, + runtime_types: Vec, +) -> Result { + let ExplicitAllPalletsDeclaration { pallets, name: pallets_name } = definition; + + let system_pallet = + pallets.iter().find(|decl| decl.name == SYSTEM_PALLET_NAME).ok_or_else(|| { + syn::Error::new( + pallets_name.span(), + "`System` pallet declaration is missing. \ + Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", + ) + })?; + if !system_pallet.cfg_pattern.is_empty() { + return Err(syn::Error::new( + system_pallet.name.span(), + "`System` pallet declaration is feature gated, please remove any `#[cfg]` attributes", + )) + } + + let features = pallets + .iter() + .filter_map(|decl| { + (!decl.cfg_pattern.is_empty()).then(|| { + decl.cfg_pattern.iter().flat_map(|attr| { + attr.predicates().filter_map(|pred| match pred { + Predicate::Feature(feat) => Some(feat), + Predicate::Test => Some("test"), + _ => None, + }) + }) + }) + }) + .flatten() + .collect::>(); + + let hidden_crate_name = "construct_runtime"; + let scrate = generate_crate_access(hidden_crate_name, "frame-support"); + let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support"); + + let frame_system = generate_crate_access_2018("frame-system")?; + let block = quote!(<#name as #frame_system::Config>::Block); + let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); + + let mut dispatch = quote!(); + let mut outer_event = quote!(); + let mut outer_error = quote!(); + let mut outer_origin = quote!(); + let mut freeze_reason = quote!(); + let mut hold_reason = quote!(); + let mut slash_reason = quote!(); + let mut lock_id = quote!(); + + for runtime_type in runtime_types.iter() { + match runtime_type { + RuntimeType::RuntimeCall(_) => { + dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate); + }, + RuntimeType::RuntimeEvent(_) => { + outer_event = expand::expand_outer_enum( + &name, + &pallets, + &scrate, + expand::OuterEnumType::Event, + )?; + }, + RuntimeType::RuntimeError(_) => { + outer_error = expand::expand_outer_enum( + &name, + &pallets, + &scrate, + expand::OuterEnumType::Error, + )?; + }, + RuntimeType::RuntimeOrigin(_) => { + outer_origin = + expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?; + }, + RuntimeType::RuntimeFreezeReason(_) => { + freeze_reason = expand::expand_outer_freeze_reason(&pallets, &scrate); + }, + RuntimeType::RuntimeHoldReason(_) => { + hold_reason = expand::expand_outer_hold_reason(&pallets, &scrate); + }, + RuntimeType::RuntimeSlashReason(_) => { + slash_reason = expand::expand_outer_slash_reason(&pallets, &scrate); + }, + RuntimeType::RuntimeLockId(_) => { + lock_id = expand::expand_outer_lock_id(&pallets, &scrate); + }, + } + } + + let all_pallets = decl_all_pallets(&name, pallets.iter(), &features); + let pallet_to_index = decl_pallet_runtime_setup(&name, &pallets, &scrate); + + let metadata = expand::expand_runtime_metadata( + &name, + &pallets, + &scrate, + &unchecked_extrinsic, + &system_pallet.path, + ); + let outer_config = expand::expand_outer_config(&name, &pallets, &scrate); + let inherent = + expand::expand_outer_inherent(&name, &block, &unchecked_extrinsic, &pallets, &scrate); + let validate_unsigned = expand::expand_outer_validate_unsigned(&name, &pallets, &scrate); + let integrity_test = decl_integrity_test(&scrate); + let static_assertions = decl_static_assertions(&name, &pallets, &scrate); + + let res = quote!( + #scrate_decl + + // Prevent UncheckedExtrinsic to print unused warning. + const _: () = { + #[allow(unused)] + type __hidden_use_of_unchecked_extrinsic = #unchecked_extrinsic; + }; + + #[derive( + Clone, Copy, PartialEq, Eq, #scrate::sp_runtime::RuntimeDebug, + #scrate::__private::scale_info::TypeInfo + )] + pub struct #name; + impl #scrate::sp_runtime::traits::GetRuntimeBlockType for #name { + type RuntimeBlock = #block; + } + + // Each runtime must expose the `runtime_metadata()` to fetch the runtime API metadata. + // The function is implemented by calling `impl_runtime_apis!`. + // + // However, the `construct_runtime!` may be called without calling `impl_runtime_apis!`. + // Rely on the `Deref` trait to differentiate between a runtime that implements + // APIs (by macro impl_runtime_apis!) and a runtime that is simply created (by macro construct_runtime!). + // + // Both `InternalConstructRuntime` and `InternalImplRuntimeApis` expose a `runtime_metadata()` function. + // `InternalConstructRuntime` is implemented by the `construct_runtime!` for Runtime references (`& Runtime`), + // while `InternalImplRuntimeApis` is implemented by the `impl_runtime_apis!` for Runtime (`Runtime`). + // + // Therefore, the `Deref` trait will resolve the `runtime_metadata` from `impl_runtime_apis!` + // when both macros are called; and will resolve an empty `runtime_metadata` when only the `construct_runtime!` + // is called. + + #[doc(hidden)] + trait InternalConstructRuntime { + #[inline(always)] + fn runtime_metadata(&self) -> #scrate::__private::sp_std::vec::Vec<#scrate::__private::metadata_ir::RuntimeApiMetadataIR> { + Default::default() + } + } + #[doc(hidden)] + impl InternalConstructRuntime for &#name {} + + #outer_event + + #outer_error + + #outer_origin + + #all_pallets + + #pallet_to_index + + #dispatch + + #metadata + + #outer_config + + #inherent + + #validate_unsigned + + #freeze_reason + + #hold_reason + + #lock_id + + #slash_reason + + #integrity_test + + #static_assertions + ); + + Ok(res) +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs new file mode 100644 index 000000000000..c24de0458bf8 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs @@ -0,0 +1,30 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use parse::Def; +use proc_macro::TokenStream; + +mod expand; +mod parse; + +pub fn construct_runtime(_attrs: TokenStream, tokens: TokenStream) -> TokenStream { + let item = syn::parse_macro_input!(tokens as syn::ItemMod); + match parse::Def::try_from(item) { + Ok(def) => expand::expand(def).into(), + Err(e) => e.to_compile_error().into(), + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs new file mode 100644 index 000000000000..b442370d3a68 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs @@ -0,0 +1,37 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::pallet::parse::helper::MutItemAttrs; +use quote::ToTokens; + +pub(crate) fn take_first_item_runtime_attr( + item: &mut impl MutItemAttrs, +) -> syn::Result> +where + Attr: syn::parse::Parse, +{ + let attrs = if let Some(attrs) = item.mut_item_attrs() { attrs } else { return Ok(None) }; + + if let Some(index) = attrs.iter().position(|attr| { + attr.path().segments.first().map_or(false, |segment| segment.ident == "frame") + }) { + let runtime_attr = attrs.remove(index); + Ok(Some(syn::parse2(runtime_attr.into_token_stream())?)) + } else { + Ok(None) + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs new file mode 100644 index 000000000000..af871b1d5601 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs @@ -0,0 +1,144 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod helper; +pub mod pallet; +pub mod pallet_decl; +pub mod pallets; +pub mod runtime_struct; +pub mod runtime_types; + +use proc_macro2::TokenStream as TokenStream2; +use quote::ToTokens; +use syn::{spanned::Spanned, Token}; + +use frame_support_procedural_tools::syn_ext as ext; +use runtime_types::RuntimeType; + +mod keyword { + syn::custom_keyword!(frame); + syn::custom_keyword!(runtime); + syn::custom_keyword!(pallets); + syn::custom_keyword!(derive); +} + +enum RuntimeAttr { + Runtime(proc_macro2::Span), + Pallets(proc_macro2::Span), + Derive(proc_macro2::Span, Vec), +} + +impl RuntimeAttr { + fn span(&self) -> proc_macro2::Span { + match self { + Self::Runtime(span) => *span, + Self::Pallets(span) => *span, + Self::Derive(span, _) => *span, + } + } +} + +impl syn::parse::Parse for RuntimeAttr { + fn parse(input: syn::parse::ParseStream) -> syn::Result { + input.parse::()?; + let content; + syn::bracketed!(content in input); + content.parse::()?; + content.parse::()?; + + let lookahead = content.lookahead1(); + if lookahead.peek(keyword::runtime) { + Ok(RuntimeAttr::Runtime(content.parse::()?.span())) + } else if lookahead.peek(keyword::pallets) { + Ok(RuntimeAttr::Pallets(content.parse::()?.span())) + } else if lookahead.peek(keyword::derive) { + let _ = content.parse::(); + let derive_content; + syn::parenthesized!(derive_content in content); + let runtime_types = + derive_content.parse::>()?; + let runtime_types = runtime_types.inner.into_iter().collect(); + Ok(RuntimeAttr::Derive(derive_content.span(), runtime_types)) + } else { + Err(lookahead.error()) + } + } +} + +pub struct Def { + pub input: TokenStream2, + pub item: syn::ItemMod, + pub runtime_struct: runtime_struct::RuntimeStructDef, + pub pallets: pallets::AllPalletsDeclaration, + pub runtime_types: Vec, +} + +impl Def { + pub fn try_from(mut item: syn::ItemMod) -> syn::Result { + let input: TokenStream2 = item.to_token_stream().into(); + let item_span = item.span(); + let items = &mut item + .content + .as_mut() + .ok_or_else(|| { + let msg = "Invalid runtime definition, expected mod to be inlined."; + syn::Error::new(item_span, msg) + })? + .1; + + let mut runtime_struct = None; + let mut pallets = None; + let mut runtime_types = None; + + for item in items.iter_mut() { + while let Some(runtime_attr) = + helper::take_first_item_runtime_attr::(item)? + { + match runtime_attr { + RuntimeAttr::Runtime(span) if runtime_struct.is_none() => { + let p = runtime_struct::RuntimeStructDef::try_from(span, item)?; + runtime_struct = Some(p); + }, + RuntimeAttr::Pallets(span) if pallets.is_none() => { + let p = pallets::AllPalletsDeclaration::try_from(span, item)?; + pallets = Some(p); + }, + RuntimeAttr::Derive(_, types) if runtime_types.is_none() => { + runtime_types = Some(types); + }, + attr => { + let msg = "Invalid duplicated attribute"; + return Err(syn::Error::new(attr.span(), msg)) + }, + } + } + } + + let def = Def { + input, + item, + runtime_struct: runtime_struct + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::runtime]`"))?, + pallets: pallets + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::pallets]`"))?, + runtime_types: runtime_types + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::runtime_types]`"))?, + }; + + Ok(def) + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs new file mode 100644 index 000000000000..27522578c7fb --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -0,0 +1,176 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; +use quote::ToTokens; +use syn::{punctuated::Punctuated, spanned::Spanned, token, Error}; + +mod keyword { + syn::custom_keyword!(frame); + syn::custom_keyword!(pallet_index); + syn::custom_keyword!(disable_call); +} + +enum PalletAttr { + PalletIndex(proc_macro2::Span, u8), + DisableCall(proc_macro2::Span), +} + +impl PalletAttr { + fn span(&self) -> proc_macro2::Span { + match self { + Self::PalletIndex(span, _) => *span, + Self::DisableCall(span) => *span, + } + } +} + +impl syn::parse::Parse for PalletAttr { + fn parse(input: syn::parse::ParseStream) -> syn::Result { + input.parse::()?; + let content; + syn::bracketed!(content in input); + content.parse::()?; + content.parse::()?; + + let lookahead = content.lookahead1(); + if lookahead.peek(keyword::pallet_index) { + let _ = content.parse::(); + let pallet_index_content; + syn::parenthesized!(pallet_index_content in content); + let pallet_index = pallet_index_content.parse::()?; + if !pallet_index.suffix().is_empty() { + let msg = "Number literal must not have a suffix"; + return Err(syn::Error::new(pallet_index.span(), msg)) + } + Ok(PalletAttr::PalletIndex(pallet_index.span(), pallet_index.base10_parse()?)) + } else if lookahead.peek(keyword::disable_call) { + Ok(PalletAttr::DisableCall(content.parse::()?.span())) + } else { + Err(lookahead.error()) + } + } +} + +fn take_first_item_pallet_attr(item: &mut syn::Field) -> syn::Result> +where + Attr: syn::parse::Parse, +{ + let attrs = &mut item.attrs; + + if let Some(index) = attrs.iter().position(|attr| { + attr.path().segments.first().map_or(false, |segment| segment.ident == "frame") + }) { + let runtime_attr = attrs.remove(index); + Ok(Some(syn::parse2(runtime_attr.into_token_stream())?)) + } else { + Ok(None) + } +} + +impl Pallet { + pub fn try_from( + attr_span: proc_macro2::Span, + index: u8, + item: &mut syn::Field, + bounds: &Punctuated, + ) -> syn::Result { + let name = item + .ident + .clone() + .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a named field"))?; + + let mut pallet_index = index; + let mut disable_call = false; + + while let Some(pallet_attr) = take_first_item_pallet_attr::(item)? { + match pallet_attr { + PalletAttr::PalletIndex(_, index) => pallet_index = index, + PalletAttr::DisableCall(_) => disable_call = true, + } + } + + let mut pallet_path = None; + let mut pallet_parts = vec![]; + + for (index, bound) in bounds.into_iter().enumerate() { + if let syn::TypeParamBound::Trait(syn::TraitBound { path, .. }) = bound { + if index == 0 { + pallet_path = Some(PalletPath { inner: path.clone() }); + } else { + let pallet_part = syn::parse2::(bound.into_token_stream())?; + pallet_parts.push(pallet_part); + } + } else { + return Err(Error::new( + attr_span, + "Invalid pallet declaration, expected a path or a trait object", + )) + }; + } + + let mut path = pallet_path.ok_or(Error::new( + attr_span, + "Invalid pallet declaration, expected a path or a trait object", + ))?; + + let mut instance = None; + // Todo: revisit this + if let Some(segment) = path.inner.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) + { + if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { + args, + .. + }) = segment.arguments.clone() + { + if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { + instance = Some(syn::Ident::new( + &arg_path.to_token_stream().to_string(), + arg_path.span(), + )); + segment.arguments = syn::PathArguments::None; + } + } + } + + if disable_call { + pallet_parts = + pallet_parts + .into_iter() + .filter(|part| { + if let PalletPartKeyword::Call(_) = part.keyword { + false + } else { + true + } + }) + .collect(); + } + + let cfg_pattern = vec![]; + + Ok(Pallet { + is_expanded: true, + name, + index: pallet_index, + path, + instance, + cfg_pattern, + pallet_parts, + }) + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs new file mode 100644 index 000000000000..4245a7b40e8b --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs @@ -0,0 +1,72 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use quote::ToTokens; +use syn::{spanned::Spanned, Attribute, Error, Ident}; + +/// The declaration of a pallet. +#[derive(Debug, Clone)] +pub struct PalletDeclaration { + /// The name of the pallet, e.g.`System` in `System: frame_system`. + pub name: Ident, + /// Optional attributes tagged right above a pallet declaration. + pub attrs: Vec, + /// Optional fixed index, e.g. `MyPallet ... = 3,`. + pub index: Option, + /// The path of the pallet, e.g. `frame_system` in `System: frame_system`. + pub path: syn::Path, + /// The instance of the pallet, e.g. `Instance1` in `Council: pallet_collective::`. + pub instance: Option, +} + +impl PalletDeclaration { + pub fn try_from( + attr_span: proc_macro2::Span, + index: usize, + item: &mut syn::Field, + path: &syn::TypePath, + ) -> syn::Result { + let name = item + .ident + .clone() + .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a named field"))?; + + let mut path = path.path.clone(); + + let mut instance = None; + // Todo: revisit this + if let Some(segment) = path.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) { + if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { + args, + .. + }) = segment.arguments.clone() + { + if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { + instance = Some(syn::Ident::new( + &arg_path.to_token_stream().to_string(), + arg_path.span(), + )); + segment.arguments = syn::PathArguments::None; + } + } + } + + let index = Some(index as u8); + + Ok(Self { name, path, instance, index, attrs: item.attrs.clone() }) + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs new file mode 100644 index 000000000000..19e27a6567d7 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs @@ -0,0 +1,117 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{ + construct_runtime::parse::Pallet, construct_runtime_v2::parse::pallet_decl::PalletDeclaration, +}; +use std::collections::{HashMap, HashSet}; +use syn::{spanned::Spanned, Ident}; + +#[derive(Debug, Clone)] +pub enum AllPalletsDeclaration { + Implicit(ImplicitAllPalletsDeclaration), + Explicit(ExplicitAllPalletsDeclaration), +} + +/// Declaration of a runtime with some pallet with implicit declaration of parts. +#[derive(Debug, Clone)] +pub struct ImplicitAllPalletsDeclaration { + pub name: Ident, + pub pallet_decls: Vec, + pub pallet_count: usize, +} + +/// Declaration of a runtime with all pallet having explicit declaration of parts. +#[derive(Debug, Clone)] +pub struct ExplicitAllPalletsDeclaration { + pub name: Ident, + pub pallets: Vec, +} + +impl AllPalletsDeclaration { + pub fn try_from(attr_span: proc_macro2::Span, item: &mut syn::Item) -> syn::Result { + let item = if let syn::Item::Struct(item) = item { + item + } else { + let msg = "Invalid frame::pallets, expected struct definition"; + return Err(syn::Error::new(item.span(), msg)) + }; + + let name = item.ident.clone(); + + let mut indices = HashMap::new(); + let mut names = HashMap::new(); + + let mut last_index: Option = None; + + let mut pallet_decls = vec![]; + let mut pallets = vec![]; + + for (index, item) in item.fields.iter_mut().enumerate() { + match item.ty.clone() { + syn::Type::Path(ref path) => { + let pallet_decl = PalletDeclaration::try_from(attr_span, index, item, path)?; + pallet_decls.push(pallet_decl); + }, + syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { + let current_index = match last_index { + Some(index) => index.checked_add(1).ok_or_else(|| { + let msg = "Pallet index doesn't fit into u8, index is 256"; + syn::Error::new(name.span(), msg) + }), + None => Ok(0), + }?; + let pallet = Pallet::try_from(attr_span, current_index, item, &bounds)?; + + if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { + let msg = format!( + "Pallet indices are conflicting: Both pallets {} and {} are at index {}", + used_pallet, pallet.name, pallet.index, + ); + let mut err = syn::Error::new(used_pallet.span(), &msg); + err.combine(syn::Error::new(pallet.name.span(), msg)); + return Err(err) + } + + if let Some(used_pallet) = names.insert(pallet.name.clone(), pallet.name.span()) + { + let msg = "Two pallets with the same name!"; + + let mut err = syn::Error::new(used_pallet, &msg); + err.combine(syn::Error::new(pallet.name.span(), &msg)); + return Err(err) + } + + last_index = Some(pallet.index); + pallets.push(pallet); + }, + _ => continue, + } + } + + let decl_count = pallet_decls.len(); + if decl_count > 0 { + Ok(AllPalletsDeclaration::Implicit(ImplicitAllPalletsDeclaration { + name, + pallet_decls, + pallet_count: decl_count.saturating_add(pallets.len()), + })) + } else { + Ok(AllPalletsDeclaration::Explicit(ExplicitAllPalletsDeclaration { name, pallets })) + } + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs new file mode 100644 index 000000000000..edc2d79eb593 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs @@ -0,0 +1,35 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use syn::spanned::Spanned; +pub struct RuntimeStructDef { + pub ident: syn::Ident, + pub attr_span: proc_macro2::Span, +} + +impl RuntimeStructDef { + pub fn try_from(attr_span: proc_macro2::Span, item: &mut syn::Item) -> syn::Result { + let item = if let syn::Item::Struct(item) = item { + item + } else { + let msg = "Invalid frame::runtime, expected struct definition"; + return Err(syn::Error::new(item.span(), msg)) + }; + + Ok(Self { ident: item.ident.clone(), attr_span }) + } +} diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs new file mode 100644 index 000000000000..a645ade54a40 --- /dev/null +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs @@ -0,0 +1,70 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use syn::{ + parse::{Parse, ParseStream}, + Result, +}; + +mod keyword { + syn::custom_keyword!(RuntimeCall); + syn::custom_keyword!(RuntimeEvent); + syn::custom_keyword!(RuntimeError); + syn::custom_keyword!(RuntimeOrigin); + syn::custom_keyword!(RuntimeFreezeReason); + syn::custom_keyword!(RuntimeHoldReason); + syn::custom_keyword!(RuntimeSlashReason); + syn::custom_keyword!(RuntimeLockId); +} + +#[derive(Debug, Clone, PartialEq)] +pub enum RuntimeType { + RuntimeCall(keyword::RuntimeCall), + RuntimeEvent(keyword::RuntimeEvent), + RuntimeError(keyword::RuntimeError), + RuntimeOrigin(keyword::RuntimeOrigin), + RuntimeFreezeReason(keyword::RuntimeFreezeReason), + RuntimeHoldReason(keyword::RuntimeHoldReason), + RuntimeSlashReason(keyword::RuntimeSlashReason), + RuntimeLockId(keyword::RuntimeLockId), +} + +impl Parse for RuntimeType { + fn parse(input: ParseStream) -> Result { + let lookahead = input.lookahead1(); + + if lookahead.peek(keyword::RuntimeCall) { + Ok(Self::RuntimeCall(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeEvent) { + Ok(Self::RuntimeEvent(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeError) { + Ok(Self::RuntimeError(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeOrigin) { + Ok(Self::RuntimeOrigin(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeFreezeReason) { + Ok(Self::RuntimeFreezeReason(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeHoldReason) { + Ok(Self::RuntimeHoldReason(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeSlashReason) { + Ok(Self::RuntimeSlashReason(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeLockId) { + Ok(Self::RuntimeLockId(input.parse()?)) + } else { + Err(lookahead.error()) + } + } +} diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 9957cf1cff85..35054b0dcc48 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -21,6 +21,7 @@ mod benchmark; mod construct_runtime; +mod construct_runtime_v2; mod crate_version; mod derive_impl; mod dummy_part_checker; @@ -1688,3 +1689,8 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { } .into() } + +#[proc_macro_attribute] +pub fn construct_runtime_v2(attr: TokenStream, item: TokenStream) -> TokenStream { + construct_runtime_v2::construct_runtime(attr, item) +} diff --git a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs index 86db56c776df..a778b49f3ce1 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs @@ -28,6 +28,8 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { syn::Ident::new(&format!("__tt_default_parts_{}", count), def.item.span()); let extra_parts_unique_id = syn::Ident::new(&format!("__tt_extra_parts_{}", count), def.item.span()); + let default_parts_unique_id_v2 = + syn::Ident::new(&format!("__tt_default_parts_v2_{}", count), def.item.span()); let call_part = def.call.as_ref().map(|_| quote::quote!(Call,)); @@ -79,6 +81,56 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { .any(|c| matches!(c.composite_keyword, CompositeKeyword::SlashReason(_))) .then_some(quote::quote!(SlashReason,)); + let call_part_v2 = def.call.as_ref().map(|_| quote::quote!(+ Call)); + + let storage_part_v2 = (!def.storages.is_empty()).then(|| quote::quote!(+ Storage)); + + let event_part_v2 = def.event.as_ref().map(|event| { + let gen = event.gen_kind.is_generic().then(|| quote::quote!()); + quote::quote!(+ Event #gen) + }); + + let error_part_v2 = def.error.as_ref().map(|_| quote::quote!(+ Error)); + + let origin_part_v2 = def.origin.as_ref().map(|origin| { + let gen = origin.is_generic.then(|| quote::quote!()); + quote::quote!(+ Origin #gen) + }); + + let config_part_v2 = def.genesis_config.as_ref().map(|genesis_config| { + let gen = genesis_config.gen_kind.is_generic().then(|| quote::quote!()); + quote::quote!(+ Config #gen) + }); + + let inherent_part_v2 = def.inherent.as_ref().map(|_| quote::quote!(+ Inherent)); + + let validate_unsigned_part_v2 = + def.validate_unsigned.as_ref().map(|_| quote::quote!(+ ValidateUnsigned)); + + let freeze_reason_part_v2 = def + .composites + .iter() + .any(|c| matches!(c.composite_keyword, CompositeKeyword::FreezeReason(_))) + .then_some(quote::quote!(+ FreezeReason)); + + let hold_reason_part_v2 = def + .composites + .iter() + .any(|c| matches!(c.composite_keyword, CompositeKeyword::HoldReason(_))) + .then_some(quote::quote!(+ HoldReason)); + + let lock_id_part_v2 = def + .composites + .iter() + .any(|c| matches!(c.composite_keyword, CompositeKeyword::LockId(_))) + .then_some(quote::quote!(+ LockId)); + + let slash_reason_part_v2 = def + .composites + .iter() + .any(|c| matches!(c.composite_keyword, CompositeKeyword::SlashReason(_))) + .then_some(quote::quote!(+ SlashReason)); + quote::quote!( // This macro follows the conventions as laid out by the `tt-call` crate. It does not // accept any arguments and simply returns the pallet parts, separated by commas, then @@ -138,5 +190,25 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { } pub use #extra_parts_unique_id as tt_extra_parts; + + #[macro_export] + #[doc(hidden)] + macro_rules! #default_parts_unique_id_v2 { + { + $caller:tt + frame_support = [{ $($frame_support:ident)::* }] + } => { + $($frame_support)*::__private::tt_return! { + $caller + tokens = [{ + + Pallet #call_part_v2 #storage_part_v2 #event_part_v2 #error_part_v2 #origin_part_v2 #config_part_v2 + #inherent_part_v2 #validate_unsigned_part_v2 #freeze_reason_part_v2 + #hold_reason_part_v2 #lock_id_part_v2 #slash_reason_part_v2 + }] + } + }; + } + + pub use #default_parts_unique_id_v2 as tt_default_parts_v2; ) } diff --git a/substrate/frame/support/procedural/src/pallet/mod.rs b/substrate/frame/support/procedural/src/pallet/mod.rs index 3618711051d7..42d8272fb23e 100644 --- a/substrate/frame/support/procedural/src/pallet/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/mod.rs @@ -26,7 +26,7 @@ //! to user defined types. And also crate new types and implement block. mod expand; -mod parse; +pub(crate) mod parse; pub use parse::{composite::keyword::CompositeKeyword, Def}; use syn::spanned::Spanned; diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index a7106780e021..3f317462f07a 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -491,7 +491,7 @@ pub fn debug(data: &impl sp_std::fmt::Debug) { #[doc(inline)] pub use frame_support_procedural::{ - construct_runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, + construct_runtime, construct_runtime_v2, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, }; #[doc(hidden)] From cec8668f8ca9db5f4a7d08f6686f8c4256e1e5e4 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 5 Sep 2023 10:48:44 +0530 Subject: [PATCH 02/48] Adds disable_unsigned --- .../src/construct_runtime_v2/parse/pallet.rs | 42 +++++++++---------- .../src/construct_runtime_v2/parse/pallets.rs | 2 +- substrate/frame/support/src/lib.rs | 3 +- 3 files changed, 23 insertions(+), 24 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index 27522578c7fb..4c4c16df2484 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -23,20 +23,13 @@ mod keyword { syn::custom_keyword!(frame); syn::custom_keyword!(pallet_index); syn::custom_keyword!(disable_call); + syn::custom_keyword!(disable_unsigned); } enum PalletAttr { PalletIndex(proc_macro2::Span, u8), DisableCall(proc_macro2::Span), -} - -impl PalletAttr { - fn span(&self) -> proc_macro2::Span { - match self { - Self::PalletIndex(span, _) => *span, - Self::DisableCall(span) => *span, - } - } + DisableUnsigned(proc_macro2::Span), } impl syn::parse::Parse for PalletAttr { @@ -60,6 +53,8 @@ impl syn::parse::Parse for PalletAttr { Ok(PalletAttr::PalletIndex(pallet_index.span(), pallet_index.base10_parse()?)) } else if lookahead.peek(keyword::disable_call) { Ok(PalletAttr::DisableCall(content.parse::()?.span())) + } else if lookahead.peek(keyword::disable_unsigned) { + Ok(PalletAttr::DisableUnsigned(content.parse::()?.span())) } else { Err(lookahead.error()) } @@ -96,11 +91,13 @@ impl Pallet { let mut pallet_index = index; let mut disable_call = false; + let mut disable_unsigned = false; while let Some(pallet_attr) = take_first_item_pallet_attr::(item)? { match pallet_attr { PalletAttr::PalletIndex(_, index) => pallet_index = index, PalletAttr::DisableCall(_) => disable_call = true, + PalletAttr::DisableUnsigned(_) => disable_unsigned = true, } } @@ -147,19 +144,20 @@ impl Pallet { } } - if disable_call { - pallet_parts = - pallet_parts - .into_iter() - .filter(|part| { - if let PalletPartKeyword::Call(_) = part.keyword { - false - } else { - true - } - }) - .collect(); - } + pallet_parts = pallet_parts + .into_iter() + .filter(|part| { + if let (true, &PalletPartKeyword::Call(_)) = (disable_call, &part.keyword) { + false + } else if let (true, &PalletPartKeyword::ValidateUnsigned(_)) = + (disable_unsigned, &part.keyword) + { + false + } else { + true + } + }) + .collect(); let cfg_pattern = vec![]; diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs index 19e27a6567d7..da82d54adcf8 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs @@ -18,7 +18,7 @@ use crate::{ construct_runtime::parse::Pallet, construct_runtime_v2::parse::pallet_decl::PalletDeclaration, }; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use syn::{spanned::Spanned, Ident}; #[derive(Debug, Clone)] diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 3f317462f07a..b22fe047a2d0 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -491,7 +491,8 @@ pub fn debug(data: &impl sp_std::fmt::Debug) { #[doc(inline)] pub use frame_support_procedural::{ - construct_runtime, construct_runtime_v2, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, + construct_runtime, construct_runtime_v2, match_and_insert, transactional, PalletError, + RuntimeDebugNoBound, }; #[doc(hidden)] From 73327a1f356abcc88c5777d3c84d7c981fae8a2c Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 5 Sep 2023 11:02:54 +0530 Subject: [PATCH 03/48] Fixes kitchensink build --- substrate/bin/node/runtime/src/lib.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 03ac51eb34a3..311e353cd506 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2014,6 +2014,16 @@ mod runtime { pub struct Runtime; #[frame::pallets] + #[frame::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId + )] pub struct Pallets { System: frame_system, Utility: pallet_utility, From 99a43cfee25ee8d0118aa5a875b86057107dfdbd Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 6 Sep 2023 11:23:03 +0530 Subject: [PATCH 04/48] Makes pallet_index mandatory --- .../bin/node-template/runtime/src/lib.rs | 10 ++- substrate/bin/node/runtime/src/lib.rs | 71 +++++++++++++++++++ .../src/construct_runtime_v2/parse/pallet.rs | 8 ++- .../construct_runtime_v2/parse/pallet_decl.rs | 7 +- .../src/construct_runtime_v2/parse/pallets.rs | 16 +---- 5 files changed, 88 insertions(+), 24 deletions(-) diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index e447a4e28e60..a99dc195e0b8 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -296,16 +296,22 @@ mod runtime { RuntimeLockId )] pub struct Pallets { + #[frame::pallet_index(0)] System: frame_system, + #[frame::pallet_index(1)] Timestamp: pallet_timestamp, + #[frame::pallet_index(2)] Aura: pallet_aura, + #[frame::pallet_index(3)] Grandpa: pallet_grandpa, + #[frame::pallet_index(4)] Balances: pallet_balances, + #[frame::pallet_index(5)] TransactionPayment: pallet_transaction_payment, + #[frame::pallet_index(6)] Sudo: pallet_sudo, // Include the custom logic from the pallet-template in the runtime. - #[frame::pallet_index(8)] - #[frame::disable_call] + #[frame::pallet_index(7)] TemplateModule: pallet_template, } } diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 311e353cd506..76d8a30709f9 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2025,78 +2025,149 @@ mod runtime { RuntimeLockId )] pub struct Pallets { + #[frame::pallet_index(0)] System: frame_system, + #[frame::pallet_index(1)] Utility: pallet_utility, + #[frame::pallet_index(2)] Babe: pallet_babe, + #[frame::pallet_index(3)] Timestamp: pallet_timestamp, // Authorship must be before session in order to note author in the correct session and era // for im-online and staking. + #[frame::pallet_index(4)] Authorship: pallet_authorship, + #[frame::pallet_index(5)] Indices: pallet_indices, + #[frame::pallet_index(6)] Balances: pallet_balances, + #[frame::pallet_index(7)] TransactionPayment: pallet_transaction_payment, + #[frame::pallet_index(8)] AssetTxPayment: pallet_asset_tx_payment, + #[frame::pallet_index(9)] AssetConversionTxPayment: pallet_asset_conversion_tx_payment, + #[frame::pallet_index(10)] ElectionProviderMultiPhase: pallet_election_provider_multi_phase, + #[frame::pallet_index(11)] Staking: pallet_staking, + #[frame::pallet_index(12)] Session: pallet_session, + #[frame::pallet_index(13)] Democracy: pallet_democracy, + #[frame::pallet_index(14)] Council: pallet_collective, + #[frame::pallet_index(15)] TechnicalCommittee: pallet_collective, + #[frame::pallet_index(16)] Elections: pallet_elections_phragmen, + #[frame::pallet_index(17)] TechnicalMembership: pallet_membership, + #[frame::pallet_index(18)] Grandpa: pallet_grandpa, + #[frame::pallet_index(19)] Treasury: pallet_treasury, + #[frame::pallet_index(20)] AssetRate: pallet_asset_rate, + #[frame::pallet_index(21)] Contracts: pallet_contracts, + #[frame::pallet_index(22)] Sudo: pallet_sudo, + #[frame::pallet_index(23)] ImOnline: pallet_im_online, + #[frame::pallet_index(24)] AuthorityDiscovery: pallet_authority_discovery, + #[frame::pallet_index(25)] Offences: pallet_offences, + #[frame::pallet_index(26)] Historical: pallet_session_historical + Pallet, + #[frame::pallet_index(27)] RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, + #[frame::pallet_index(28)] Identity: pallet_identity, + #[frame::pallet_index(29)] Society: pallet_society, + #[frame::pallet_index(30)] Recovery: pallet_recovery, + #[frame::pallet_index(31)] Vesting: pallet_vesting, + #[frame::pallet_index(32)] Scheduler: pallet_scheduler, + #[frame::pallet_index(33)] Glutton: pallet_glutton, + #[frame::pallet_index(34)] Preimage: pallet_preimage, + #[frame::pallet_index(35)] Proxy: pallet_proxy, + #[frame::pallet_index(36)] Multisig: pallet_multisig, + #[frame::pallet_index(37)] Bounties: pallet_bounties, + #[frame::pallet_index(38)] Tips: pallet_tips, + #[frame::pallet_index(39)] Assets: pallet_assets, + #[frame::pallet_index(40)] PoolAssets: pallet_assets, + #[frame::pallet_index(41)] Mmr: pallet_mmr, + #[frame::pallet_index(42)] Lottery: pallet_lottery, + #[frame::pallet_index(43)] Nis: pallet_nis, + #[frame::pallet_index(44)] Uniques: pallet_uniques, + #[frame::pallet_index(45)] Nfts: pallet_nfts, + #[frame::pallet_index(46)] NftFractionalization: pallet_nft_fractionalization, + #[frame::pallet_index(47)] Salary: pallet_salary, + #[frame::pallet_index(48)] CoreFellowship: pallet_core_fellowship, + #[frame::pallet_index(49)] TransactionStorage: pallet_transaction_storage, + #[frame::pallet_index(50)] VoterList: pallet_bags_list, + #[frame::pallet_index(51)] StateTrieMigration: pallet_state_trie_migration, + #[frame::pallet_index(52)] ChildBounties: pallet_child_bounties, + #[frame::pallet_index(53)] Referenda: pallet_referenda, + #[frame::pallet_index(54)] Remark: pallet_remark, + #[frame::pallet_index(55)] RootTesting: pallet_root_testing, + #[frame::pallet_index(56)] ConvictionVoting: pallet_conviction_voting, + #[frame::pallet_index(57)] Whitelist: pallet_whitelist, + #[frame::pallet_index(58)] AllianceMotion: pallet_collective, + #[frame::pallet_index(59)] Alliance: pallet_alliance, + #[frame::pallet_index(60)] NominationPools: pallet_nomination_pools, + #[frame::pallet_index(61)] RankedPolls: pallet_referenda, + #[frame::pallet_index(62)] RankedCollective: pallet_ranked_collective, + #[frame::pallet_index(63)] AssetConversion: pallet_asset_conversion, + #[frame::pallet_index(64)] FastUnstake: pallet_fast_unstake, + #[frame::pallet_index(65)] MessageQueue: pallet_message_queue, + #[frame::pallet_index(66)] Pov: frame_benchmarking_pallet_pov, + #[frame::pallet_index(67)] TxPause: pallet_tx_pause, + #[frame::pallet_index(68)] SafeMode: pallet_safe_mode, + #[frame::pallet_index(69)] Statement: pallet_statement, + #[frame::pallet_index(70)] Broker: pallet_broker, } } diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index 4c4c16df2484..4920c4bfd57b 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -80,7 +80,6 @@ where impl Pallet { pub fn try_from( attr_span: proc_macro2::Span, - index: u8, item: &mut syn::Field, bounds: &Punctuated, ) -> syn::Result { @@ -89,18 +88,21 @@ impl Pallet { .clone() .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a named field"))?; - let mut pallet_index = index; + let mut pallet_index: Option = None; let mut disable_call = false; let mut disable_unsigned = false; while let Some(pallet_attr) = take_first_item_pallet_attr::(item)? { match pallet_attr { - PalletAttr::PalletIndex(_, index) => pallet_index = index, + PalletAttr::PalletIndex(_, index) => pallet_index = Some(index), PalletAttr::DisableCall(_) => disable_call = true, PalletAttr::DisableUnsigned(_) => disable_unsigned = true, } } + let pallet_index = pallet_index + .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a pallet index"))?; + let mut pallet_path = None; let mut pallet_parts = vec![]; diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs index 4245a7b40e8b..3745e82c9019 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs @@ -25,8 +25,6 @@ pub struct PalletDeclaration { pub name: Ident, /// Optional attributes tagged right above a pallet declaration. pub attrs: Vec, - /// Optional fixed index, e.g. `MyPallet ... = 3,`. - pub index: Option, /// The path of the pallet, e.g. `frame_system` in `System: frame_system`. pub path: syn::Path, /// The instance of the pallet, e.g. `Instance1` in `Council: pallet_collective::`. @@ -36,7 +34,6 @@ pub struct PalletDeclaration { impl PalletDeclaration { pub fn try_from( attr_span: proc_macro2::Span, - index: usize, item: &mut syn::Field, path: &syn::TypePath, ) -> syn::Result { @@ -65,8 +62,6 @@ impl PalletDeclaration { } } - let index = Some(index as u8); - - Ok(Self { name, path, instance, index, attrs: item.attrs.clone() }) + Ok(Self { name, path, instance, attrs: item.attrs.clone() }) } } diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs index da82d54adcf8..b4a6b2c1f1af 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs @@ -56,26 +56,17 @@ impl AllPalletsDeclaration { let mut indices = HashMap::new(); let mut names = HashMap::new(); - let mut last_index: Option = None; - let mut pallet_decls = vec![]; let mut pallets = vec![]; - for (index, item) in item.fields.iter_mut().enumerate() { + for item in item.fields.iter_mut() { match item.ty.clone() { syn::Type::Path(ref path) => { - let pallet_decl = PalletDeclaration::try_from(attr_span, index, item, path)?; + let pallet_decl = PalletDeclaration::try_from(attr_span, item, path)?; pallet_decls.push(pallet_decl); }, syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { - let current_index = match last_index { - Some(index) => index.checked_add(1).ok_or_else(|| { - let msg = "Pallet index doesn't fit into u8, index is 256"; - syn::Error::new(name.span(), msg) - }), - None => Ok(0), - }?; - let pallet = Pallet::try_from(attr_span, current_index, item, &bounds)?; + let pallet = Pallet::try_from(attr_span, item, &bounds)?; if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { let msg = format!( @@ -96,7 +87,6 @@ impl AllPalletsDeclaration { return Err(err) } - last_index = Some(pallet.index); pallets.push(pallet); }, _ => continue, From 1467f0a11207ab135d2c2021b8c138cee7925c4f Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 6 Sep 2023 13:39:12 +0530 Subject: [PATCH 05/48] Adds UI Test --- .../src/construct_runtime_v2/parse/mod.rs | 2 +- .../test/tests/construct_runtime_v2_ui.rs | 36 +++++++++++++++++++ .../construct_runtime_v2_ui/pass/basic.rs | 23 ++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs index af871b1d5601..d72210b60a98 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs @@ -136,7 +136,7 @@ impl Def { pallets: pallets .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::pallets]`"))?, runtime_types: runtime_types - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::runtime_types]`"))?, + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::derive]`"))?, }; Ok(def) diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui.rs new file mode 100644 index 000000000000..1de0c9874d1c --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui.rs @@ -0,0 +1,36 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[rustversion::attr(not(stable), ignore)] +#[cfg(not(feature = "disable-ui-tests"))] +#[test] +fn ui() { + // Only run the ui tests when `RUN_UI_TESTS` is set. + if std::env::var("RUN_UI_TESTS").is_err() { + return + } + + // As trybuild is using `cargo check`, we don't need the real WASM binaries. + std::env::set_var("SKIP_WASM_BUILD", "1"); + + // Deny all warnings since we emit warnings as part of a Runtime's UI. + std::env::set_var("RUSTFLAGS", "--deny warnings"); + + let t = trybuild::TestCases::new(); + t.compile_fail("tests/construct_runtime_v2_ui/*.rs"); + t.pass("tests/construct_runtime_v2_ui/pass/*.rs"); +} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs new file mode 100644 index 000000000000..c3e2c15ec632 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs @@ -0,0 +1,23 @@ +use frame_support::derive_impl; + +pub type Block = frame_system::mocking::MockBlock; + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type Block = Block; +} + +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeError)] + pub struct Pallets { + #[frame::pallet_index(0)] + System: frame_system + } +} + +fn main() {} From 65688525463342a6fc347d793d22223889baafaf Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 11 Sep 2023 12:27:27 +0530 Subject: [PATCH 06/48] Adds UI Tests --- .../src/construct_runtime_v2/expand/mod.rs | 2 +- .../src/construct_runtime_v2/parse/pallet.rs | 2 +- .../src/construct_runtime_v2/parse/pallets.rs | 6 +++--- .../can_only_be_attached_to_mod.rs | 4 ++++ .../can_only_be_attached_to_mod.stderr | 5 +++++ .../construct_runtime_v2_ui/missing_pallet_index.rs | 13 +++++++++++++ .../missing_pallet_index.stderr | 5 +++++ .../construct_runtime_v2_ui/missing_pallets.rs | 7 +++++++ .../construct_runtime_v2_ui/missing_pallets.stderr | 5 +++++ .../construct_runtime_v2_ui/missing_runtime.rs | 4 ++++ .../construct_runtime_v2_ui/missing_runtime.stderr | 5 +++++ .../missing_runtime_types_derive.rs | 10 ++++++++++ .../missing_runtime_types_derive.stderr | 5 +++++ .../missing_system_pallet.rs | 11 +++++++++++ .../missing_system_pallet.stderr | 5 +++++ .../tests/construct_runtime_v2_ui/pallets_struct.rs | 10 ++++++++++ .../construct_runtime_v2_ui/pallets_struct.stderr | 5 +++++ .../tests/construct_runtime_v2_ui/runtime_struct.rs | 7 +++++++ .../construct_runtime_v2_ui/runtime_struct.stderr | 5 +++++ 19 files changed, 111 insertions(+), 5 deletions(-) create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index e11bd71407a0..c0c8aa04c49b 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -109,7 +109,7 @@ fn construct_runtime_final_expansion( syn::Error::new( pallets_name.span(), "`System` pallet declaration is missing. \ - Please add this line: `System: frame_system::{Pallet, Call, Storage, Config, Event},`", + Please add this line: `System: frame_system,`", ) })?; if !system_pallet.cfg_pattern.is_empty() { diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index 4920c4bfd57b..bd4ceea32016 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -101,7 +101,7 @@ impl Pallet { } let pallet_index = pallet_index - .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a pallet index"))?; + .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a #[frame::pallet_index]"))?; let mut pallet_path = None; let mut pallet_parts = vec![]; diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs index b4a6b2c1f1af..9dd7262e9767 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs @@ -48,7 +48,7 @@ impl AllPalletsDeclaration { item } else { let msg = "Invalid frame::pallets, expected struct definition"; - return Err(syn::Error::new(item.span(), msg)) + return Err(syn::Error::new(attr_span, msg)) }; let name = item.ident.clone(); @@ -62,11 +62,11 @@ impl AllPalletsDeclaration { for item in item.fields.iter_mut() { match item.ty.clone() { syn::Type::Path(ref path) => { - let pallet_decl = PalletDeclaration::try_from(attr_span, item, path)?; + let pallet_decl = PalletDeclaration::try_from(item.span(), item, path)?; pallet_decls.push(pallet_decl); }, syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { - let pallet = Pallet::try_from(attr_span, item, &bounds)?; + let pallet = Pallet::try_from(item.span(), item, &bounds)?; if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { let msg = format!( diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs new file mode 100644 index 000000000000..646ba1b9f4a6 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs @@ -0,0 +1,4 @@ +#[frame_support::construct_runtime_v2] +fn construct_runtime() {} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr new file mode 100644 index 000000000000..4f4b0e17792b --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr @@ -0,0 +1,5 @@ +error: expected `mod` + --> tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs:2:1 + | +2 | fn construct_runtime() {} + | ^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs new file mode 100644 index 000000000000..bab325faf43f --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs @@ -0,0 +1,13 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall)] + pub struct Pallets { + System: frame_system + } +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr new file mode 100644 index 000000000000..f877cfb03430 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr @@ -0,0 +1,5 @@ +error: Invalid pallet declaration, expected a #[frame::pallet_index] + --> tests/construct_runtime_v2_ui/missing_pallet_index.rs:9:9 + | +9 | System: frame_system + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs new file mode 100644 index 000000000000..86bb7d50cf0b --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs @@ -0,0 +1,7 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr new file mode 100644 index 000000000000..bc61579c972d --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr @@ -0,0 +1,5 @@ +error: Missing `#[frame::pallets]` + --> tests/construct_runtime_v2_ui/missing_pallets.rs:2:1 + | +2 | mod runtime { + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs new file mode 100644 index 000000000000..8132df8ff55f --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs @@ -0,0 +1,4 @@ +#[frame_support::construct_runtime_v2] +mod runtime {} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr new file mode 100644 index 000000000000..55906910480e --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr @@ -0,0 +1,5 @@ +error: Missing `#[frame::runtime]` + --> tests/construct_runtime_v2_ui/missing_runtime.rs:2:1 + | +2 | mod runtime {} + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs new file mode 100644 index 000000000000..aae6ad563221 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs @@ -0,0 +1,10 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + pub struct Pallets {} +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr new file mode 100644 index 000000000000..5e5a3a951d37 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr @@ -0,0 +1,5 @@ +error: Missing `#[frame::derive]` + --> tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs:2:1 + | +2 | mod runtime { + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs new file mode 100644 index 000000000000..b5701a372a2d --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs @@ -0,0 +1,11 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall)] + pub struct Pallets {} +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr new file mode 100644 index 000000000000..e0f5253ae0ee --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr @@ -0,0 +1,5 @@ +error: `System` pallet declaration is missing. Please add this line: `System: frame_system,` + --> tests/construct_runtime_v2_ui/missing_system_pallet.rs:8:16 + | +8 | pub struct Pallets {} + | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs new file mode 100644 index 000000000000..389ee9c56004 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs @@ -0,0 +1,10 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + pub enum Pallets {} +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr new file mode 100644 index 000000000000..d318cb963c09 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr @@ -0,0 +1,5 @@ +error: Invalid frame::pallets, expected struct definition + --> tests/construct_runtime_v2_ui/pallets_struct.rs:6:14 + | +6 | #[frame::pallets] + | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs new file mode 100644 index 000000000000..3bb29ede894a --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs @@ -0,0 +1,7 @@ +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub enum Runtime {} +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr new file mode 100644 index 000000000000..0515cff029f9 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr @@ -0,0 +1,5 @@ +error: Invalid frame::runtime, expected struct definition + --> tests/construct_runtime_v2_ui/runtime_struct.rs:4:5 + | +4 | pub enum Runtime {} + | ^^^ From 2a70549343523a2c22be41bafd7a969065cf6499 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 11 Sep 2023 13:32:28 +0530 Subject: [PATCH 07/48] Minor CI fixes --- .../src/construct_runtime_v2/parse/pallet.rs | 6 ++++-- .../can_only_be_attached_to_mod.rs | 17 +++++++++++++++++ .../can_only_be_attached_to_mod.stderr | 8 ++++---- .../missing_pallet_index.rs | 17 +++++++++++++++++ .../missing_pallet_index.stderr | 8 ++++---- .../construct_runtime_v2_ui/missing_pallets.rs | 17 +++++++++++++++++ .../missing_pallets.stderr | 8 ++++---- .../construct_runtime_v2_ui/missing_runtime.rs | 17 +++++++++++++++++ .../missing_runtime.stderr | 8 ++++---- .../missing_runtime_types_derive.rs | 17 +++++++++++++++++ .../missing_runtime_types_derive.stderr | 8 ++++---- .../missing_system_pallet.rs | 17 +++++++++++++++++ .../missing_system_pallet.stderr | 8 ++++---- .../construct_runtime_v2_ui/pallets_struct.rs | 17 +++++++++++++++++ .../pallets_struct.stderr | 8 ++++---- .../tests/construct_runtime_v2_ui/pass/basic.rs | 17 +++++++++++++++++ .../construct_runtime_v2_ui/runtime_struct.rs | 17 +++++++++++++++++ .../runtime_struct.stderr | 8 ++++---- 18 files changed, 189 insertions(+), 34 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index bd4ceea32016..03fd035d19d7 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -100,8 +100,10 @@ impl Pallet { } } - let pallet_index = pallet_index - .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a #[frame::pallet_index]"))?; + let pallet_index = pallet_index.ok_or(Error::new( + attr_span, + "Invalid pallet declaration, expected a #[frame::pallet_index]", + ))?; let mut pallet_path = None; let mut pallet_parts = vec![]; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs index 646ba1b9f4a6..49e69beffdd2 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] fn construct_runtime() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr index 4f4b0e17792b..2763747b97f9 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr @@ -1,5 +1,5 @@ error: expected `mod` - --> tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs:2:1 - | -2 | fn construct_runtime() {} - | ^^ + --> tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs:19:1 + | +19 | fn construct_runtime() {} + | ^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs index bab325faf43f..532bddc9a508 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr index f877cfb03430..797ae25f3e3d 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr @@ -1,5 +1,5 @@ error: Invalid pallet declaration, expected a #[frame::pallet_index] - --> tests/construct_runtime_v2_ui/missing_pallet_index.rs:9:9 - | -9 | System: frame_system - | ^^^^^^ + --> tests/construct_runtime_v2_ui/missing_pallet_index.rs:26:9 + | +26 | System: frame_system + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs index 86bb7d50cf0b..1db0813fa8e4 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr index bc61579c972d..f4ff0977c03e 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr @@ -1,5 +1,5 @@ error: Missing `#[frame::pallets]` - --> tests/construct_runtime_v2_ui/missing_pallets.rs:2:1 - | -2 | mod runtime { - | ^^^ + --> tests/construct_runtime_v2_ui/missing_pallets.rs:19:1 + | +19 | mod runtime { + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs index 8132df8ff55f..f7a05c28fac1 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr index 55906910480e..992087eaf857 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr @@ -1,5 +1,5 @@ error: Missing `#[frame::runtime]` - --> tests/construct_runtime_v2_ui/missing_runtime.rs:2:1 - | -2 | mod runtime {} - | ^^^ + --> tests/construct_runtime_v2_ui/missing_runtime.rs:19:1 + | +19 | mod runtime {} + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs index aae6ad563221..53b02d911c96 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr index 5e5a3a951d37..eb0138825e5a 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr @@ -1,5 +1,5 @@ error: Missing `#[frame::derive]` - --> tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs:2:1 - | -2 | mod runtime { - | ^^^ + --> tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs:19:1 + | +19 | mod runtime { + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs index b5701a372a2d..7f4016bc3435 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr index e0f5253ae0ee..76ed324fab7a 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr @@ -1,5 +1,5 @@ error: `System` pallet declaration is missing. Please add this line: `System: frame_system,` - --> tests/construct_runtime_v2_ui/missing_system_pallet.rs:8:16 - | -8 | pub struct Pallets {} - | ^^^^^^^ + --> tests/construct_runtime_v2_ui/missing_system_pallet.rs:25:16 + | +25 | pub struct Pallets {} + | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs index 389ee9c56004..80666ba55978 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr index d318cb963c09..fb73417e0577 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr @@ -1,5 +1,5 @@ error: Invalid frame::pallets, expected struct definition - --> tests/construct_runtime_v2_ui/pallets_struct.rs:6:14 - | -6 | #[frame::pallets] - | ^^^^^^^ + --> tests/construct_runtime_v2_ui/pallets_struct.rs:23:14 + | +23 | #[frame::pallets] + | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs index c3e2c15ec632..c1fce3e7c4c1 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + use frame_support::derive_impl; pub type Block = frame_system::mocking::MockBlock; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs index 3bb29ede894a..72d9fc93bfd8 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs @@ -1,3 +1,20 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + #[frame_support::construct_runtime_v2] mod runtime { #[frame::runtime] diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr index 0515cff029f9..10bcf8cf4fd5 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr @@ -1,5 +1,5 @@ error: Invalid frame::runtime, expected struct definition - --> tests/construct_runtime_v2_ui/runtime_struct.rs:4:5 - | -4 | pub enum Runtime {} - | ^^^ + --> tests/construct_runtime_v2_ui/runtime_struct.rs:21:5 + | +21 | pub enum Runtime {} + | ^^^ From 9beb3ba65197e9f97cc6646697edd2c4985a2a38 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 12 Sep 2023 11:36:09 +0530 Subject: [PATCH 08/48] Adds more UI tests --- .../src/construct_runtime_v2/parse/pallets.rs | 20 +++++---- .../conflicting_pallet_index.rs | 45 +++++++++++++++++++ .../conflicting_pallet_index.stderr | 11 +++++ .../conflicting_pallet_name.rs | 45 +++++++++++++++++++ .../conflicting_pallet_name.stderr | 11 +++++ .../invalid_pallet_index.rs | 31 +++++++++++++ .../invalid_pallet_index.stderr | 5 +++ .../invalid_runtime_type_derive.rs | 28 ++++++++++++ .../invalid_runtime_type_derive.stderr | 5 +++ 9 files changed, 192 insertions(+), 9 deletions(-) create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs create mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs index 9dd7262e9767..f704b304a0ce 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs @@ -63,6 +63,17 @@ impl AllPalletsDeclaration { match item.ty.clone() { syn::Type::Path(ref path) => { let pallet_decl = PalletDeclaration::try_from(item.span(), item, path)?; + + if let Some(used_pallet) = + names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) + { + let msg = "Two pallets with the same name!"; + + let mut err = syn::Error::new(used_pallet, &msg); + err.combine(syn::Error::new(pallet_decl.name.span(), &msg)); + return Err(err) + } + pallet_decls.push(pallet_decl); }, syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { @@ -78,15 +89,6 @@ impl AllPalletsDeclaration { return Err(err) } - if let Some(used_pallet) = names.insert(pallet.name.clone(), pallet.name.span()) - { - let msg = "Two pallets with the same name!"; - - let mut err = syn::Error::new(used_pallet, &msg); - err.combine(syn::Error::new(pallet.name.span(), &msg)); - return Err(err) - } - pallets.push(pallet); }, _ => continue, diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs new file mode 100644 index 000000000000..4dc2b3ed2b6d --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs @@ -0,0 +1,45 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[frame_support::pallet] +mod pallet { + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::call] + impl Pallet {} +} + +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall)] + pub struct Pallets { + #[frame::pallet_index(0)] + System: frame_system, + #[frame::pallet_index(0)] + Pallet: pallet, + } +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr new file mode 100644 index 000000000000..215b67ca981c --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr @@ -0,0 +1,11 @@ +error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 + --> tests/construct_runtime_v2_ui/conflicting_pallet_index.rs:39:9 + | +39 | System: frame_system, + | ^^^^^^ + +error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 + --> tests/construct_runtime_v2_ui/conflicting_pallet_index.rs:41:9 + | +41 | Pallet: pallet, + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs new file mode 100644 index 000000000000..a92e3c0b1fa4 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs @@ -0,0 +1,45 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[frame_support::pallet] +mod pallet { + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::call] + impl Pallet {} +} + +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall)] + pub struct Pallets { + #[frame::pallet_index(0)] + System: frame_system, + #[frame::pallet_index(1)] + System: pallet, + } +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr new file mode 100644 index 000000000000..346ccf263750 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr @@ -0,0 +1,11 @@ +error: Two pallets with the same name! + --> tests/construct_runtime_v2_ui/conflicting_pallet_name.rs:39:9 + | +39 | System: frame_system, + | ^^^^^^ + +error: Two pallets with the same name! + --> tests/construct_runtime_v2_ui/conflicting_pallet_name.rs:41:9 + | +41 | System: pallet, + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs new file mode 100644 index 000000000000..847dd00a82e5 --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs @@ -0,0 +1,31 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeCall)] + pub struct Pallets { + #[frame::pallet_index("0")] + System: frame_system + } +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr new file mode 100644 index 000000000000..2ac048e1834f --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr @@ -0,0 +1,5 @@ +error: expected integer literal + --> tests/construct_runtime_v2_ui/invalid_pallet_index.rs:26:31 + | +26 | #[frame::pallet_index("0")] + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs new file mode 100644 index 000000000000..c5c9ba491e8c --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs @@ -0,0 +1,28 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive(RuntimeInfo)] + pub struct Pallets {} +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr new file mode 100644 index 000000000000..eceef731815f --- /dev/null +++ b/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr @@ -0,0 +1,5 @@ +error: expected one of: `RuntimeCall`, `RuntimeEvent`, `RuntimeError`, `RuntimeOrigin`, `RuntimeFreezeReason`, `RuntimeHoldReason`, `RuntimeSlashReason`, `RuntimeLockId` + --> tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs:24:21 + | +24 | #[frame::derive(RuntimeInfo)] + | ^^^^^^^^^^^ From 88fa35a20caed1351b8d288ad63de3a6182003f9 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 12 Sep 2023 11:49:51 +0530 Subject: [PATCH 09/48] Adds some docs --- substrate/frame/support/procedural/src/lib.rs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 35054b0dcc48..ebbd9373d82a 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1690,6 +1690,62 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { .into() } +/// Construct a runtime, with the given name and the given pallets. +/// +/// # Example: +/// +/// ```ignore +/// #[frame_support::construct_runtime_v2] +/// mod runtime { +/// // The main runtime +/// #[frame::runtime] +/// pub struct Runtime; +/// +/// #[frame::pallets] +/// // Runtime Types to be generated +/// #[frame::derive( +/// RuntimeCall, +/// RuntimeEvent, +/// RuntimeError, +/// RuntimeOrigin, +/// RuntimeFreezeReason, +/// RuntimeHoldReason, +/// RuntimeSlashReason, +/// RuntimeLockId +/// )] +/// pub struct Pallets { +/// #[frame::pallet_index(0)] +/// System: frame_system, +/// #[frame::pallet_index(1)] +/// Test: path::to::test, +/// +/// // Pallet with instance. +/// #[frame::pallet_index(2)] +/// Test2_Instance1: test2, +/// +/// // Pallet with calls disabled. +/// #[frame::pallet_index(3)] +/// #[frame::disable_call] +/// Test3: test3, +/// +/// // Pallet with unsigned extrinsics disabled. +/// #[frame::pallet_index(4)] +/// #[frame::disable_unsigned] +/// Test4: test4, +/// } +/// } +/// ``` +/// +/// # Note +/// +/// The population of the genesis storage depends on the order of pallets. So, if one of your +/// pallets depends on another pallet, the pallet that is depended upon needs to come before +/// the pallet depending on it. +/// +/// # Type definitions +/// +/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System = +/// frame_system::Pallet` #[proc_macro_attribute] pub fn construct_runtime_v2(attr: TokenStream, item: TokenStream) -> TokenStream { construct_runtime_v2::construct_runtime(attr, item) From 8ab5c66c167e73a846b1a9e5202d268407f7dc6a Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Sep 2023 11:13:12 +0530 Subject: [PATCH 10/48] Updates tests for construct_runtime_v2 --- .../support/test/tests/construct_runtime.rs | 144 ++++++++++++++---- 1 file changed, 115 insertions(+), 29 deletions(-) diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/construct_runtime.rs index 9ad51ad530eb..a94f4c75bd67 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime.rs @@ -31,7 +31,7 @@ use sp_api::RuntimeVersion; use sp_core::{sr25519, ConstU64}; use sp_runtime::{ generic, - traits::{BlakeTwo256, Verify}, + traits::{BlakeTwo256, ValidateUnsigned, Verify}, DispatchError, ModuleError, }; @@ -176,6 +176,17 @@ mod nested { impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + fn validate_unsigned( + _source: TransactionSource, + _call: &Self::Call, + ) -> TransactionValidity { + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + } + } } } @@ -247,6 +258,20 @@ pub mod module3 { impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } + + #[pallet::storage] + pub type Storage = StorageValue<_, u32>; + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + fn validate_unsigned( + _source: TransactionSource, + _call: &Self::Call, + ) -> TransactionValidity { + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + } + } } pub type BlockNumber = u64; @@ -256,24 +281,54 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -frame_support::construct_runtime!( - pub struct Runtime - { - System: frame_system::{Pallet, Call, Event, Origin} = 30, - Module1_1: module1::::{Pallet, Call, Storage, Event, Origin}, - Module2: module2::{Pallet, Call, Storage, Event, Origin}, - Module1_2: module1::::{Pallet, Call, Storage, Event, Origin}, - NestedModule3: nested::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module3: self::module3::{Pallet, Call, Config, Storage, Event, Origin}, - Module1_3: module1::::{Pallet, Storage, Event } = 6, - Module1_4: module1::::{Pallet, Call, Event } = 3, - Module1_5: module1::::{Pallet, Event}, - Module1_6: module1::::{Pallet, Call, Storage, Event, Origin} = 1, - Module1_7: module1::::{Pallet, Call, Storage, Event, Origin}, - Module1_8: module1::::{Pallet, Call, Storage, Event, Origin} = 12, - Module1_9: module1::::{Pallet, Call, Storage, Event, Origin}, +#[frame_support::construct_runtime_v2] +mod runtime { + #[frame::runtime] + pub struct Runtime; + + #[frame::pallets] + #[frame::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId + )] + pub struct Pallets { + #[frame::pallet_index(30)] + System: frame_system + Pallet + Call + Event + Origin, + #[frame::pallet_index(31)] + Module1_1: module1, + #[frame::pallet_index(32)] + Module2: module2, + #[frame::pallet_index(33)] + Module1_2: module1, + #[frame::pallet_index(34)] + NestedModule3: nested::module3, + #[frame::pallet_index(35)] + #[frame::disable_unsigned] + Module3: self::module3, + #[frame::pallet_index(6)] + #[frame::disable_call] + Module1_3: module1, + #[frame::pallet_index(3)] + Module1_4: module1, + #[frame::pallet_index(4)] + #[frame::disable_call] + Module1_5: module1, + #[frame::pallet_index(1)] + Module1_6: module1, + #[frame::pallet_index(2)] + Module1_7: module1, + #[frame::pallet_index(12)] + Module1_8: module1, + #[frame::pallet_index(13)] + Module1_9: module1, } -); +} #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { @@ -636,9 +691,13 @@ fn call_subtype_conversion() { #[test] fn test_metadata() { - use frame_metadata::{v14::*, *}; + use frame_metadata::{ + v14::{StorageEntryType::Plain, *}, + *, + }; use scale_info::meta_type; use sp_core::Encode; + use sp_metadata_ir::StorageEntryModifierIR::Optional; fn maybe_docs(doc: Vec<&'static str>) -> Vec<&'static str> { if cfg!(feature = "no-metadata-docs") { @@ -703,7 +762,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_1", - storage: Some(PalletStorageMetadata { prefix: "Module1_1", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -712,7 +771,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module2", - storage: Some(PalletStorageMetadata { prefix: "Module2", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -721,7 +780,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_2", - storage: Some(PalletStorageMetadata { prefix: "Module1_2", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -730,7 +789,7 @@ fn test_metadata() { }, PalletMetadata { name: "NestedModule3", - storage: Some(PalletStorageMetadata { prefix: "NestedModule3", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -739,7 +798,18 @@ fn test_metadata() { }, PalletMetadata { name: "Module3", - storage: Some(PalletStorageMetadata { prefix: "Module3", entries: vec![] }), + storage: Some(PalletStorageMetadata { + prefix: "Module3", + entries: vec![ + StorageEntryMetadata { + name: "Storage", + modifier: Optional.into(), + ty: Plain(meta_type::().into()), + default: vec![0], + docs: vec![], + }, + ] + }), calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -748,7 +818,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_3", - storage: Some(PalletStorageMetadata { prefix: "Module1_3", entries: vec![] }), + storage: None, calls: None, event: Some(meta_type::>().into()), constants: vec![], @@ -775,7 +845,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_6", - storage: Some(PalletStorageMetadata { prefix: "Module1_6", entries: vec![] }), + storage:None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -784,7 +854,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_7", - storage: Some(PalletStorageMetadata { prefix: "Module1_7", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -793,7 +863,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_8", - storage: Some(PalletStorageMetadata { prefix: "Module1_8", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -802,7 +872,7 @@ fn test_metadata() { }, PalletMetadata { name: "Module1_9", - storage: Some(PalletStorageMetadata { prefix: "Module1_9", entries: vec![] }), + storage: None, calls: Some(meta_type::>().into()), event: Some(meta_type::>().into()), constants: vec![], @@ -895,3 +965,19 @@ fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert!(PalletInfo::crate_version::().is_some()); } + +#[test] +fn test_validate_unsigned() { + use frame_support::pallet_prelude::*; + + let call = RuntimeCall::NestedModule3(nested::module3::Call::fail {}); + let validity = Runtime::validate_unsigned(TransactionSource::Local, &call).unwrap_err(); + assert_eq!(validity, TransactionValidityError::Invalid(InvalidTransaction::Call)); + + let call = RuntimeCall::Module3(module3::Call::fail {}); + let validity = Runtime::validate_unsigned(TransactionSource::Local, &call).unwrap_err(); + assert_eq!( + validity, + TransactionValidityError::Unknown(UnknownTransaction::NoUnsignedValidator) + ); +} From 977a553a42c650a5c8017422756a18f7b928904b Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Sep 2023 11:26:12 +0530 Subject: [PATCH 11/48] Adds docs --- .../src/construct_runtime_v2/mod.rs | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs index c24de0458bf8..0bb157c11388 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs @@ -15,6 +15,191 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! Implementation of `construct_runtime_v2`. +//! +//! `construct_runtime_v2` implementation is recursive and can generate code which will call itself +//! in order to get all the pallet parts for each pallet. +//! +//! Pallets can define their parts: +//! - Implicitly: `System: frame_system` +//! - Explicitly: `System: frame_system + Pallet + Call` +//! +//! The `construct_runtime_v2` transitions from the implicit definition to the explicit one. +//! From the explicit state, Substrate expands the pallets with additional information +//! that is to be included in the runtime metadata. +//! +//! Pallets must provide the `tt_default_parts_v2` macro for these transitions. +//! These are automatically implemented by the `#[pallet::pallet]` macro. +//! +//! This macro also generates the following enums for ease of decoding if the respective type +//! is defined inside `#[frame::derive]`: +//! - `enum RuntimeCall`: This type contains the information needed to decode extrinsics. +//! - `enum RuntimeEvent`: This type contains the information needed to decode events. +//! - `enum RuntimeError`: While this cannot be used directly to decode `sp_runtime::DispatchError` +//! from the chain, it contains the information needed to decode the +//! `sp_runtime::DispatchError::Module`. +//! +//! # State Transitions +//! +//! ```ignore +//! +----------+ +//! | Implicit | +//! +----------+ +//! | +//! v +//! +----------+ +//! | Explicit | +//! +----------+ +//! ``` +//! +//! The `construct_runtime_v2` macro transforms the implicit declaration of each pallet +//! `System: frame_system` to an explicit one `System: frame_system + Pallet + Call` using the +//! `tt_default_parts_v2` macro. +//! +//! The `tt_default_parts_v2` macro exposes a plus separated list of pallet parts. For example, the +//! `Event` part is exposed only if the pallet implements an event via `#[pallet::event]` macro. +//! The tokens generated by this macro are `+ Pallet + Call` for our example. +//! +//! The `match_and_insert` macro takes in 3 arguments: +//! - target: This is the `TokenStream` that contains the `construct_runtime_v2` macro. +//! - pattern: The pattern to match against in the target stream. +//! - tokens: The tokens to added after the pattern match. +//! +//! The `construct_runtime_v2` macro uses the `tt_call` to get the default pallet parts via +//! the `tt_default_parts_v2` macro defined by each pallet. The pallet parts are then returned as +//! input to the `match_and_replace` macro. +//! The `match_and_replace` then will modify the the `construct_runtime_v2` to expand the implicit +//! definition to the explicit one. +//! +//! For example, +//! +//! ```ignore +//! #[frame::construct_runtime_v2] +//! mod runtime { +//! //... +//! { +//! #[frame::pallet_index(0)] +//! System: frame_system, // Implicit definition of parts +//! #[frame::pallet_index(1)] +//! Balances: pallet_balances, // Implicit definition of parts +//! } +//! } +//! ``` +//! This call has some implicit pallet parts, thus it will expand to: +//! ```ignore +//! frame_support::__private::tt_call! { +//! macro = [{ pallet_balances::tt_default_parts_v2 }] +//! ~~> frame_support::match_and_insert! { +//! target = [{ +//! frame_support::__private::tt_call! { +//! macro = [{ frame_system::tt_default_parts_v2 }] +//! ~~> frame_support::match_and_insert! { +//! target = [{ +//! #[frame::construct_runtime_v2] +//! mod runtime { +//! //... +//! { +//! #[frame::pallet_index(0)] +//! System: frame_system, +//! #[frame::pallet_index(1)] +//! Balances: pallet_balances, +//! } +//! } +//! }] +//! pattern = [{ System: frame_system }] +//! } +//! } +//! }] +//! pattern = [{ Balances: pallet_balances }] +//! } +//! } +//! ``` +//! `tt_default_parts_v2` must be defined. It returns the pallet parts inside some tokens, and +//! then `tt_call` will pipe the returned pallet parts into the input of `match_and_insert`. +//! Thus `match_and_insert` will initially receive the following inputs: +//! ```ignore +//! frame_support::match_and_insert! { +//! target = [{ +//! frame_support::match_and_insert! { +//! target = [{ +//! #[frame::construct_runtime_v2] +//! mod runtime { +//! //... +//! { +//! #[frame::pallet_index(0)] +//! System: frame_system, +//! #[frame::pallet_index(1)] +//! Balances: pallet_balances, +//! } +//! } +//! }] +//! pattern = [{ System: frame_system }] +//! tokens = [{ ::{Pallet, Call} }] +//! } +//! }] +//! pattern = [{ Balances: pallet_balances }] +//! tokens = [{ ::{Pallet, Call} }] +//! } +//! ``` +//! After dealing with `pallet_balances`, the inner `match_and_insert` will expand to: +//! ```ignore +//! frame_support::match_and_insert! { +//! target = [{ +//! #[frame::construct_runtime_v2] +//! mod runtime { +//! //... +//! { +//! #[frame::pallet_index(0)] +//! System: frame_system, // Implicit definition of parts +//! #[frame::pallet_index(1)] +//! Balances: pallet_balances + Pallet + Call, // Explicit definition of parts +//! } +//! } +//! }] +//! pattern = [{ System: frame_system }] +//! tokens = [{ ::{Pallet, Call} }] +//! } +//! ``` +//! +//! Which will then finally expand to the following: +//! ```ignore +//! #[frame::construct_runtime_v2] +//! mod runtime { +//! //... +//! { +//! #[frame::pallet_index(0)] +//! System: frame_system + Pallet + Call, +//! #[frame::pallet_index(1)] +//! Balances: pallet_balances + Pallet + Call, +//! } +//! } +//! ``` +//! +//! This call has no implicit pallet parts, thus it will expand to the runtime construction: +//! ```ignore +//! pub struct Runtime { ... } +//! pub struct Call { ... } +//! impl Call ... +//! pub enum Origin { ... } +//! ... +//! ``` +//! +//! Visualizing the entire flow of `construct_runtime!`, it would look like the following: +//! +//! ```ignore +//! +----------------------+ +---------------------+ +-------------------+ +//! | | | (defined in pallet) | | | +//! | construct_runtime_v2 | --> | tt_default_parts! | --> | match_and_insert! | +//! | w/ no pallet parts | | | | | +//! +----------------------+ +---------------------+ +-------------------+ +//! +//! +----------------------+ +//! | | +//! --> | construct_runtime_v2 | +//! | w/ pallet parts | +//! +----------------------+ +//! ``` + pub use parse::Def; use proc_macro::TokenStream; From df4fc3dc70b33d57eac41d8789799e30e228a539 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Sep 2023 11:42:54 +0530 Subject: [PATCH 12/48] Minor update in doc --- .../procedural/src/construct_runtime_v2/expand/mod.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index c0c8aa04c49b..c0ba3445fd32 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -230,17 +230,17 @@ fn construct_runtime_final_expansion( // Each runtime must expose the `runtime_metadata()` to fetch the runtime API metadata. // The function is implemented by calling `impl_runtime_apis!`. // - // However, the `construct_runtime!` may be called without calling `impl_runtime_apis!`. + // However, the `construct_runtime_v2` may be used without calling `impl_runtime_apis!`. // Rely on the `Deref` trait to differentiate between a runtime that implements - // APIs (by macro impl_runtime_apis!) and a runtime that is simply created (by macro construct_runtime!). + // APIs (by macro impl_runtime_apis!) and a runtime that is simply created (by macro construct_runtime_v2). // // Both `InternalConstructRuntime` and `InternalImplRuntimeApis` expose a `runtime_metadata()` function. - // `InternalConstructRuntime` is implemented by the `construct_runtime!` for Runtime references (`& Runtime`), + // `InternalConstructRuntime` is implemented by the `construct_runtime_v2` for Runtime references (`& Runtime`), // while `InternalImplRuntimeApis` is implemented by the `impl_runtime_apis!` for Runtime (`Runtime`). // // Therefore, the `Deref` trait will resolve the `runtime_metadata` from `impl_runtime_apis!` - // when both macros are called; and will resolve an empty `runtime_metadata` when only the `construct_runtime!` - // is called. + // when both macros are called; and will resolve an empty `runtime_metadata` when only the `construct_runtime_v2` + // is used. #[doc(hidden)] trait InternalConstructRuntime { From 88fa6628c7d255864ae9bad813fa72eba9b5a3ee Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Sep 2023 11:49:11 +0530 Subject: [PATCH 13/48] Minor updates --- .../procedural/src/construct_runtime/mod.rs | 14 +++++++------- .../procedural/src/construct_runtime/parse.rs | 8 ++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 162596b9c71c..d0f64801d915 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -208,8 +208,8 @@ //! This macro returns the ` :: expanded { Error }` list of additional parts we would like to //! expose. -pub mod expand; -pub mod parse; +pub(crate) mod expand; +pub(crate) mod parse; use cfg_expr::Predicate; use frame_support_procedural_tools::{ @@ -496,7 +496,7 @@ fn construct_runtime_final_expansion( Ok(res) } -pub fn decl_all_pallets<'a>( +pub(crate) fn decl_all_pallets<'a>( runtime: &'a Ident, pallet_declarations: impl Iterator, features: &HashSet<&str>, @@ -660,7 +660,7 @@ pub fn decl_all_pallets<'a>( ) } -pub fn decl_pallet_runtime_setup( +pub(crate) fn decl_pallet_runtime_setup( runtime: &Ident, pallet_declarations: &[Pallet], scrate: &TokenStream2, @@ -752,7 +752,7 @@ pub fn decl_pallet_runtime_setup( ) } -pub fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { +pub(crate) fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { quote!( #[cfg(test)] mod __construct_runtime_integrity_test { @@ -767,7 +767,7 @@ pub fn decl_integrity_test(scrate: &TokenStream2) -> TokenStream2 { ) } -pub fn decl_static_assertions( +pub(crate) fn decl_static_assertions( runtime: &Ident, pallet_decls: &[Pallet], scrate: &TokenStream2, @@ -798,7 +798,7 @@ pub fn decl_static_assertions( } } -pub fn check_pallet_number(input: TokenStream2, pallet_num: usize) -> Result<()> { +pub(crate) fn check_pallet_number(input: TokenStream2, pallet_num: usize) -> Result<()> { let max_pallet_num = { if cfg!(feature = "tuples-96") { 96 diff --git a/substrate/frame/support/procedural/src/construct_runtime/parse.rs b/substrate/frame/support/procedural/src/construct_runtime/parse.rs index b407b897e410..9b08e1646975 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/parse.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/parse.rs @@ -446,7 +446,7 @@ impl Parse for PalletPartKeyword { impl PalletPartKeyword { /// Returns the name of `Self`. - pub fn name(&self) -> &'static str { + fn name(&self) -> &'static str { match self { Self::Pallet(_) => "Pallet", Self::Call(_) => "Call", @@ -465,12 +465,12 @@ impl PalletPartKeyword { } /// Returns `true` if this pallet part is allowed to have generic arguments. - pub fn allows_generic(&self) -> bool { + fn allows_generic(&self) -> bool { Self::all_generic_arg().iter().any(|n| *n == self.name()) } /// Returns the names of all pallet parts that allow to have a generic argument. - pub fn all_generic_arg() -> &'static [&'static str] { + fn all_generic_arg() -> &'static [&'static str] { &["Event", "Error", "Origin", "Config"] } } @@ -552,7 +552,7 @@ fn remove_kind( /// The declaration of a part without its generics #[derive(Debug, Clone)] pub struct PalletPartNoGeneric { - pub keyword: PalletPartKeyword, + keyword: PalletPartKeyword, } impl Parse for PalletPartNoGeneric { From a3d9319dc405d47e345fb27a5d724e9081ada084 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Fri, 15 Sep 2023 15:29:58 +0530 Subject: [PATCH 14/48] Removes Todo --- .../src/construct_runtime_v2/parse/pallet.rs | 16 ++++++---------- .../construct_runtime_v2/parse/pallet_decl.rs | 16 ++++++---------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index 03fd035d19d7..f3c96caf7963 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -17,7 +17,7 @@ use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; use quote::ToTokens; -use syn::{punctuated::Punctuated, spanned::Spanned, token, Error}; +use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; mod keyword { syn::custom_keyword!(frame); @@ -130,20 +130,16 @@ impl Pallet { ))?; let mut instance = None; - // Todo: revisit this if let Some(segment) = path.inner.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) { - if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { - args, - .. + if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { + args, .. }) = segment.arguments.clone() { if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { - instance = Some(syn::Ident::new( - &arg_path.to_token_stream().to_string(), - arg_path.span(), - )); - segment.arguments = syn::PathArguments::None; + instance = + Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span())); + segment.arguments = PathArguments::None; } } } diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs index 3745e82c9019..5ab08dea2fec 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs @@ -16,7 +16,7 @@ // limitations under the License. use quote::ToTokens; -use syn::{spanned::Spanned, Attribute, Error, Ident}; +use syn::{spanned::Spanned, Attribute, Error, Ident, PathArguments}; /// The declaration of a pallet. #[derive(Debug, Clone)] @@ -45,19 +45,15 @@ impl PalletDeclaration { let mut path = path.path.clone(); let mut instance = None; - // Todo: revisit this if let Some(segment) = path.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) { - if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { - args, - .. + if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { + args, .. }) = segment.arguments.clone() { if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { - instance = Some(syn::Ident::new( - &arg_path.to_token_stream().to_string(), - arg_path.span(), - )); - segment.arguments = syn::PathArguments::None; + instance = + Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span())); + segment.arguments = PathArguments::None; } } } From e2ab4f64c458b9aa3618ab1e986d465ad7c9dd8f Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 18 Sep 2023 11:34:40 +0530 Subject: [PATCH 15/48] Addresses review comments --- .../src/construct_runtime_v2/expand/mod.rs | 37 ++++++++++--------- .../src/construct_runtime_v2/parse/pallet.rs | 10 +++-- .../parse/runtime_types.rs | 18 +++++---- 3 files changed, 35 insertions(+), 30 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index c0ba3445fd32..3f87c5ee5905 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -143,51 +143,52 @@ fn construct_runtime_final_expansion( let block = quote!(<#name as #frame_system::Config>::Block); let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); - let mut dispatch = quote!(); - let mut outer_event = quote!(); - let mut outer_error = quote!(); - let mut outer_origin = quote!(); - let mut freeze_reason = quote!(); - let mut hold_reason = quote!(); - let mut slash_reason = quote!(); - let mut lock_id = quote!(); + let mut dispatch = None; + let mut outer_event = None; + let mut outer_error = None; + let mut outer_origin = None; + let mut freeze_reason = None; + let mut hold_reason = None; + let mut slash_reason = None; + let mut lock_id = None; for runtime_type in runtime_types.iter() { match runtime_type { RuntimeType::RuntimeCall(_) => { - dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate); + dispatch = + Some(expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate)); }, RuntimeType::RuntimeEvent(_) => { - outer_event = expand::expand_outer_enum( + outer_event = Some(expand::expand_outer_enum( &name, &pallets, &scrate, expand::OuterEnumType::Event, - )?; + )?); }, RuntimeType::RuntimeError(_) => { - outer_error = expand::expand_outer_enum( + outer_error = Some(expand::expand_outer_enum( &name, &pallets, &scrate, expand::OuterEnumType::Error, - )?; + )?); }, RuntimeType::RuntimeOrigin(_) => { outer_origin = - expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?; + Some(expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?); }, RuntimeType::RuntimeFreezeReason(_) => { - freeze_reason = expand::expand_outer_freeze_reason(&pallets, &scrate); + freeze_reason = Some(expand::expand_outer_freeze_reason(&pallets, &scrate)); }, RuntimeType::RuntimeHoldReason(_) => { - hold_reason = expand::expand_outer_hold_reason(&pallets, &scrate); + hold_reason = Some(expand::expand_outer_hold_reason(&pallets, &scrate)); }, RuntimeType::RuntimeSlashReason(_) => { - slash_reason = expand::expand_outer_slash_reason(&pallets, &scrate); + slash_reason = Some(expand::expand_outer_slash_reason(&pallets, &scrate)); }, RuntimeType::RuntimeLockId(_) => { - lock_id = expand::expand_outer_lock_id(&pallets, &scrate); + lock_id = Some(expand::expand_outer_lock_id(&pallets, &scrate)); }, } } diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index f3c96caf7963..37407b516eff 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -20,10 +20,12 @@ use quote::ToTokens; use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; mod keyword { - syn::custom_keyword!(frame); - syn::custom_keyword!(pallet_index); - syn::custom_keyword!(disable_call); - syn::custom_keyword!(disable_unsigned); + use syn::custom_keyword; + + custom_keyword!(frame); + custom_keyword!(pallet_index); + custom_keyword!(disable_call); + custom_keyword!(disable_unsigned); } enum PalletAttr { diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs index a645ade54a40..de0e582dd550 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs @@ -21,14 +21,16 @@ use syn::{ }; mod keyword { - syn::custom_keyword!(RuntimeCall); - syn::custom_keyword!(RuntimeEvent); - syn::custom_keyword!(RuntimeError); - syn::custom_keyword!(RuntimeOrigin); - syn::custom_keyword!(RuntimeFreezeReason); - syn::custom_keyword!(RuntimeHoldReason); - syn::custom_keyword!(RuntimeSlashReason); - syn::custom_keyword!(RuntimeLockId); + use syn::custom_keyword; + + custom_keyword!(RuntimeCall); + custom_keyword!(RuntimeEvent); + custom_keyword!(RuntimeError); + custom_keyword!(RuntimeOrigin); + custom_keyword!(RuntimeFreezeReason); + custom_keyword!(RuntimeHoldReason); + custom_keyword!(RuntimeSlashReason); + custom_keyword!(RuntimeLockId); } #[derive(Debug, Clone, PartialEq)] From d1cd1a9c7a2be96346d9be57f30c21f046425545 Mon Sep 17 00:00:00 2001 From: gupnik <17176722+gupnik@users.noreply.github.com> Date: Tue, 19 Sep 2023 12:01:13 +0530 Subject: [PATCH 16/48] Update substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs Co-authored-by: Francisco Aguirre --- .../frame/support/procedural/src/construct_runtime_v2/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs index 0bb157c11388..57045a386225 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs @@ -68,7 +68,7 @@ //! The `construct_runtime_v2` macro uses the `tt_call` to get the default pallet parts via //! the `tt_default_parts_v2` macro defined by each pallet. The pallet parts are then returned as //! input to the `match_and_replace` macro. -//! The `match_and_replace` then will modify the the `construct_runtime_v2` to expand the implicit +//! The `match_and_replace` then will modify the `construct_runtime_v2` to expand the implicit //! definition to the explicit one. //! //! For example, From 2df5888a17446e834b0d53e9c9528e17b254fc6b Mon Sep 17 00:00:00 2001 From: gupnik <17176722+gupnik@users.noreply.github.com> Date: Tue, 19 Sep 2023 12:02:57 +0530 Subject: [PATCH 17/48] Update substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs Co-authored-by: Francisco Aguirre --- .../support/procedural/src/construct_runtime_v2/expand/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index 3f87c5ee5905..1c09d130fbd2 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -41,7 +41,7 @@ use super::parse::runtime_types::RuntimeType; /// The fixed name of the system pallet. const SYSTEM_PALLET_NAME: &str = "System"; -pub fn expand(def: Def) -> proc_macro2::TokenStream { +pub fn expand(def: Def) -> TokenStream2 { let input = def.input; let res = match def.pallets { From 51f1a708ef4da4ce343523a5db264c7a19adb203 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 19 Sep 2023 12:05:48 +0530 Subject: [PATCH 18/48] Addresses review comment --- .../src/construct_runtime_v2/expand/mod.rs | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index 1c09d130fbd2..f3bad514f7ab 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -15,11 +15,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::construct_runtime_v2::{ - parse::pallets::{ - AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, +use super::parse::runtime_types::RuntimeType; +use crate::{ + construct_runtime::{ + check_pallet_number, decl_all_pallets, decl_integrity_test, decl_pallet_runtime_setup, + decl_static_assertions, expand, + }, + construct_runtime_v2::{ + parse::pallets::{ + AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, + }, + Def, }, - Def, }; use cfg_expr::Predicate; use frame_support_procedural_tools::{ @@ -30,14 +37,6 @@ use quote::quote; use std::collections::HashSet; use syn::{Ident, Result}; -use crate::construct_runtime::{check_pallet_number, expand}; - -use crate::construct_runtime::{ - decl_all_pallets, decl_integrity_test, decl_pallet_runtime_setup, decl_static_assertions, -}; - -use super::parse::runtime_types::RuntimeType; - /// The fixed name of the system pallet. const SYSTEM_PALLET_NAME: &str = "System"; From 996fefeae740dc58b802439dbe0d7d507e743944 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 25 Sep 2023 09:53:53 +0530 Subject: [PATCH 19/48] Uses type alias for pallets --- .../bin/node-template/runtime/src/lib.rs | 51 ++++--- .../src/construct_runtime_v2/expand/mod.rs | 4 +- .../src/construct_runtime_v2/parse/helper.rs | 2 +- .../src/construct_runtime_v2/parse/mod.rs | 130 +++++++++++++++--- .../src/construct_runtime_v2/parse/pallet.rs | 52 ++----- .../construct_runtime_v2/parse/pallet_decl.rs | 11 +- .../src/construct_runtime_v2/parse/pallets.rs | 109 --------------- .../procedural/src/pallet/parse/helper.rs | 6 + 8 files changed, 164 insertions(+), 201 deletions(-) delete mode 100644 substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index a99dc195e0b8..0c69da7cc6bc 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -281,11 +281,11 @@ impl pallet_template::Config for Runtime { // Create the runtime by composing the FRAME pallets that were previously configured. #[frame_support::construct_runtime_v2] mod runtime { - #[frame::runtime] + #[runtime::runtime] pub struct Runtime; - #[frame::pallets] - #[frame::derive( + #[runtime::pallets] + #[runtime::derive( RuntimeCall, RuntimeEvent, RuntimeError, @@ -295,25 +295,32 @@ mod runtime { RuntimeSlashReason, RuntimeLockId )] - pub struct Pallets { - #[frame::pallet_index(0)] - System: frame_system, - #[frame::pallet_index(1)] - Timestamp: pallet_timestamp, - #[frame::pallet_index(2)] - Aura: pallet_aura, - #[frame::pallet_index(3)] - Grandpa: pallet_grandpa, - #[frame::pallet_index(4)] - Balances: pallet_balances, - #[frame::pallet_index(5)] - TransactionPayment: pallet_transaction_payment, - #[frame::pallet_index(6)] - Sudo: pallet_sudo, - // Include the custom logic from the pallet-template in the runtime. - #[frame::pallet_index(7)] - TemplateModule: pallet_template, - } + pub struct AllPallets; + + #[runtime::pallet_index(0)] + pub type System = frame_system; + + #[runtime::pallet_index(1)] + pub type Timestamp = pallet_timestamp; + + #[runtime::pallet_index(2)] + pub type Aura = pallet_aura; + + #[runtime::pallet_index(3)] + pub type Grandpa = pallet_grandpa; + + #[runtime::pallet_index(4)] + pub type Balances = pallet_balances; + + #[runtime::pallet_index(5)] + pub type TransactionPayment = pallet_transaction_payment; + + #[runtime::pallet_index(6)] + pub type Sudo = pallet_sudo; + + // Include the custom logic from the pallet-template in the runtime. + #[runtime::pallet_index(7)] + pub type TemplateModule = pallet_template; } /// The address format for describing accounts. diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs index f3bad514f7ab..399775863c9d 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs @@ -22,7 +22,7 @@ use crate::{ decl_static_assertions, expand, }, construct_runtime_v2::{ - parse::pallets::{ + parse::{ AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, }, Def, @@ -87,7 +87,7 @@ fn construct_runtime_implicit_to_explicit( frame_support = [{ #frame_support }] ~~> #frame_support::match_and_insert! { target = [{ #expansion }] - pattern = [{ #pallet_name: #pallet_path #pallet_instance }] + pattern = [{ #pallet_name = #pallet_path #pallet_instance }] } } ); diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs index b442370d3a68..f05395f9b7ab 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs @@ -27,7 +27,7 @@ where let attrs = if let Some(attrs) = item.mut_item_attrs() { attrs } else { return Ok(None) }; if let Some(index) = attrs.iter().position(|attr| { - attr.path().segments.first().map_or(false, |segment| segment.ident == "frame") + attr.path().segments.first().map_or(false, |segment| segment.ident == "runtime") }) { let runtime_attr = attrs.remove(index); Ok(Some(syn::parse2(runtime_attr.into_token_stream())?)) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs index d72210b60a98..0416cde66f82 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs @@ -18,28 +18,33 @@ pub mod helper; pub mod pallet; pub mod pallet_decl; -pub mod pallets; pub mod runtime_struct; pub mod runtime_types; +use crate::construct_runtime::parse::Pallet; +use pallet_decl::PalletDeclaration; use proc_macro2::TokenStream as TokenStream2; use quote::ToTokens; -use syn::{spanned::Spanned, Token}; +use std::collections::HashMap; +use syn::{spanned::Spanned, Ident, Token}; use frame_support_procedural_tools::syn_ext as ext; use runtime_types::RuntimeType; mod keyword { - syn::custom_keyword!(frame); - syn::custom_keyword!(runtime); - syn::custom_keyword!(pallets); - syn::custom_keyword!(derive); + use syn::custom_keyword; + + custom_keyword!(runtime); + custom_keyword!(pallets); + custom_keyword!(derive); + custom_keyword!(pallet_index); } enum RuntimeAttr { Runtime(proc_macro2::Span), Pallets(proc_macro2::Span), Derive(proc_macro2::Span, Vec), + PalletIndex(proc_macro2::Span, u8), } impl RuntimeAttr { @@ -48,6 +53,7 @@ impl RuntimeAttr { Self::Runtime(span) => *span, Self::Pallets(span) => *span, Self::Derive(span, _) => *span, + Self::PalletIndex(span, _) => *span, } } } @@ -57,7 +63,7 @@ impl syn::parse::Parse for RuntimeAttr { input.parse::()?; let content; syn::bracketed!(content in input); - content.parse::()?; + content.parse::()?; content.parse::()?; let lookahead = content.lookahead1(); @@ -73,17 +79,48 @@ impl syn::parse::Parse for RuntimeAttr { derive_content.parse::>()?; let runtime_types = runtime_types.inner.into_iter().collect(); Ok(RuntimeAttr::Derive(derive_content.span(), runtime_types)) + } else if lookahead.peek(keyword::pallet_index) { + let _ = content.parse::(); + let pallet_index_content; + syn::parenthesized!(pallet_index_content in content); + let pallet_index = pallet_index_content.parse::()?; + if !pallet_index.suffix().is_empty() { + let msg = "Number literal must not have a suffix"; + return Err(syn::Error::new(pallet_index.span(), msg)) + } + Ok(RuntimeAttr::PalletIndex(pallet_index.span(), pallet_index.base10_parse()?)) } else { Err(lookahead.error()) } } } +#[derive(Debug, Clone)] +pub enum AllPalletsDeclaration { + Implicit(ImplicitAllPalletsDeclaration), + Explicit(ExplicitAllPalletsDeclaration), +} + +/// Declaration of a runtime with some pallet with implicit declaration of parts. +#[derive(Debug, Clone)] +pub struct ImplicitAllPalletsDeclaration { + pub name: Ident, + pub pallet_decls: Vec, + pub pallet_count: usize, +} + +/// Declaration of a runtime with all pallet having explicit declaration of parts. +#[derive(Debug, Clone)] +pub struct ExplicitAllPalletsDeclaration { + pub name: Ident, + pub pallets: Vec, +} + pub struct Def { pub input: TokenStream2, pub item: syn::ItemMod, pub runtime_struct: runtime_struct::RuntimeStructDef, - pub pallets: pallets::AllPalletsDeclaration, + pub pallets: AllPalletsDeclaration, pub runtime_types: Vec, } @@ -101,9 +138,14 @@ impl Def { .1; let mut runtime_struct = None; - let mut pallets = None; let mut runtime_types = None; + let mut indices = HashMap::new(); + let mut names = HashMap::new(); + + let mut pallet_decls = vec![]; + let mut pallets = vec![]; + for item in items.iter_mut() { while let Some(runtime_attr) = helper::take_first_item_runtime_attr::(item)? @@ -113,13 +155,58 @@ impl Def { let p = runtime_struct::RuntimeStructDef::try_from(span, item)?; runtime_struct = Some(p); }, - RuntimeAttr::Pallets(span) if pallets.is_none() => { - let p = pallets::AllPalletsDeclaration::try_from(span, item)?; - pallets = Some(p); + RuntimeAttr::Pallets(_span) => { + //Todo: Parse pallets struct }, RuntimeAttr::Derive(_, types) if runtime_types.is_none() => { runtime_types = Some(types); }, + RuntimeAttr::PalletIndex(span, pallet_index) => { + let item = if let syn::Item::Type(item) = item { + item + } else { + let msg = "Invalid runtime::pallet_index, expected type definition"; + return Err(syn::Error::new(span, msg)) + }; + + match *item.ty.clone() { + syn::Type::Path(ref path) => { + let pallet_decl = + PalletDeclaration::try_from(item.span(), item, path)?; + + if let Some(used_pallet) = + names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) + { + let msg = "Two pallets with the same name!"; + + let mut err = syn::Error::new(used_pallet, &msg); + err.combine(syn::Error::new(pallet_decl.name.span(), &msg)); + return Err(err) + } + + pallet_decls.push(pallet_decl); + }, + syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { + let pallet = + Pallet::try_from(item.span(), item, pallet_index, &bounds)?; + + if let Some(used_pallet) = + indices.insert(pallet.index, pallet.name.clone()) + { + let msg = format!( + "Pallet indices are conflicting: Both pallets {} and {} are at index {}", + used_pallet, pallet.name, pallet.index, + ); + let mut err = syn::Error::new(used_pallet.span(), &msg); + err.combine(syn::Error::new(pallet.name.span(), msg)); + return Err(err) + } + + pallets.push(pallet); + }, + _ => continue, + } + }, attr => { let msg = "Invalid duplicated attribute"; return Err(syn::Error::new(attr.span(), msg)) @@ -128,15 +215,26 @@ impl Def { } } + let name = item.ident.clone(); + let decl_count = pallet_decls.len(); + let pallets = if decl_count > 0 { + AllPalletsDeclaration::Implicit(ImplicitAllPalletsDeclaration { + name, + pallet_decls, + pallet_count: decl_count.saturating_add(pallets.len()), + }) + } else { + AllPalletsDeclaration::Explicit(ExplicitAllPalletsDeclaration { name, pallets }) + }; + let def = Def { input, item, runtime_struct: runtime_struct - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::runtime]`"))?, - pallets: pallets - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::pallets]`"))?, + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[runtime::runtime]`"))?, + pallets, runtime_types: runtime_types - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[frame::derive]`"))?, + .ok_or_else(|| syn::Error::new(item_span, "Missing `#[runtime::derive]`"))?, }; Ok(def) diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs index 37407b516eff..0dec4e49d862 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs @@ -15,6 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use super::helper; use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; use quote::ToTokens; use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; @@ -22,14 +23,12 @@ use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArg mod keyword { use syn::custom_keyword; - custom_keyword!(frame); - custom_keyword!(pallet_index); + custom_keyword!(runtime); custom_keyword!(disable_call); custom_keyword!(disable_unsigned); } enum PalletAttr { - PalletIndex(proc_macro2::Span, u8), DisableCall(proc_macro2::Span), DisableUnsigned(proc_macro2::Span), } @@ -39,21 +38,11 @@ impl syn::parse::Parse for PalletAttr { input.parse::()?; let content; syn::bracketed!(content in input); - content.parse::()?; + content.parse::()?; content.parse::()?; let lookahead = content.lookahead1(); - if lookahead.peek(keyword::pallet_index) { - let _ = content.parse::(); - let pallet_index_content; - syn::parenthesized!(pallet_index_content in content); - let pallet_index = pallet_index_content.parse::()?; - if !pallet_index.suffix().is_empty() { - let msg = "Number literal must not have a suffix"; - return Err(syn::Error::new(pallet_index.span(), msg)) - } - Ok(PalletAttr::PalletIndex(pallet_index.span(), pallet_index.base10_parse()?)) - } else if lookahead.peek(keyword::disable_call) { + if lookahead.peek(keyword::disable_call) { Ok(PalletAttr::DisableCall(content.parse::()?.span())) } else if lookahead.peek(keyword::disable_unsigned) { Ok(PalletAttr::DisableUnsigned(content.parse::()?.span())) @@ -63,50 +52,25 @@ impl syn::parse::Parse for PalletAttr { } } -fn take_first_item_pallet_attr(item: &mut syn::Field) -> syn::Result> -where - Attr: syn::parse::Parse, -{ - let attrs = &mut item.attrs; - - if let Some(index) = attrs.iter().position(|attr| { - attr.path().segments.first().map_or(false, |segment| segment.ident == "frame") - }) { - let runtime_attr = attrs.remove(index); - Ok(Some(syn::parse2(runtime_attr.into_token_stream())?)) - } else { - Ok(None) - } -} - impl Pallet { pub fn try_from( attr_span: proc_macro2::Span, - item: &mut syn::Field, + item: &mut syn::ItemType, + pallet_index: u8, bounds: &Punctuated, ) -> syn::Result { - let name = item - .ident - .clone() - .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a named field"))?; + let name = item.ident.clone(); - let mut pallet_index: Option = None; let mut disable_call = false; let mut disable_unsigned = false; - while let Some(pallet_attr) = take_first_item_pallet_attr::(item)? { + while let Some(pallet_attr) = helper::take_first_item_runtime_attr::(item)? { match pallet_attr { - PalletAttr::PalletIndex(_, index) => pallet_index = Some(index), PalletAttr::DisableCall(_) => disable_call = true, PalletAttr::DisableUnsigned(_) => disable_unsigned = true, } } - let pallet_index = pallet_index.ok_or(Error::new( - attr_span, - "Invalid pallet declaration, expected a #[frame::pallet_index]", - ))?; - let mut pallet_path = None; let mut pallet_parts = vec![]; diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs index 5ab08dea2fec..5d571996ad07 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs @@ -16,7 +16,7 @@ // limitations under the License. use quote::ToTokens; -use syn::{spanned::Spanned, Attribute, Error, Ident, PathArguments}; +use syn::{spanned::Spanned, Attribute, Ident, PathArguments}; /// The declaration of a pallet. #[derive(Debug, Clone)] @@ -33,14 +33,11 @@ pub struct PalletDeclaration { impl PalletDeclaration { pub fn try_from( - attr_span: proc_macro2::Span, - item: &mut syn::Field, + _attr_span: proc_macro2::Span, + item: &mut syn::ItemType, path: &syn::TypePath, ) -> syn::Result { - let name = item - .ident - .clone() - .ok_or(Error::new(attr_span, "Invalid pallet declaration, expected a named field"))?; + let name = item.ident.clone(); let mut path = path.path.clone(); diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs deleted file mode 100644 index f704b304a0ce..000000000000 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallets.rs +++ /dev/null @@ -1,109 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{ - construct_runtime::parse::Pallet, construct_runtime_v2::parse::pallet_decl::PalletDeclaration, -}; -use std::collections::HashMap; -use syn::{spanned::Spanned, Ident}; - -#[derive(Debug, Clone)] -pub enum AllPalletsDeclaration { - Implicit(ImplicitAllPalletsDeclaration), - Explicit(ExplicitAllPalletsDeclaration), -} - -/// Declaration of a runtime with some pallet with implicit declaration of parts. -#[derive(Debug, Clone)] -pub struct ImplicitAllPalletsDeclaration { - pub name: Ident, - pub pallet_decls: Vec, - pub pallet_count: usize, -} - -/// Declaration of a runtime with all pallet having explicit declaration of parts. -#[derive(Debug, Clone)] -pub struct ExplicitAllPalletsDeclaration { - pub name: Ident, - pub pallets: Vec, -} - -impl AllPalletsDeclaration { - pub fn try_from(attr_span: proc_macro2::Span, item: &mut syn::Item) -> syn::Result { - let item = if let syn::Item::Struct(item) = item { - item - } else { - let msg = "Invalid frame::pallets, expected struct definition"; - return Err(syn::Error::new(attr_span, msg)) - }; - - let name = item.ident.clone(); - - let mut indices = HashMap::new(); - let mut names = HashMap::new(); - - let mut pallet_decls = vec![]; - let mut pallets = vec![]; - - for item in item.fields.iter_mut() { - match item.ty.clone() { - syn::Type::Path(ref path) => { - let pallet_decl = PalletDeclaration::try_from(item.span(), item, path)?; - - if let Some(used_pallet) = - names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) - { - let msg = "Two pallets with the same name!"; - - let mut err = syn::Error::new(used_pallet, &msg); - err.combine(syn::Error::new(pallet_decl.name.span(), &msg)); - return Err(err) - } - - pallet_decls.push(pallet_decl); - }, - syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { - let pallet = Pallet::try_from(item.span(), item, &bounds)?; - - if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { - let msg = format!( - "Pallet indices are conflicting: Both pallets {} and {} are at index {}", - used_pallet, pallet.name, pallet.index, - ); - let mut err = syn::Error::new(used_pallet.span(), &msg); - err.combine(syn::Error::new(pallet.name.span(), msg)); - return Err(err) - } - - pallets.push(pallet); - }, - _ => continue, - } - } - - let decl_count = pallet_decls.len(); - if decl_count > 0 { - Ok(AllPalletsDeclaration::Implicit(ImplicitAllPalletsDeclaration { - name, - pallet_decls, - pallet_count: decl_count.saturating_add(pallets.len()), - })) - } else { - Ok(AllPalletsDeclaration::Explicit(ExplicitAllPalletsDeclaration { name, pallets })) - } - } -} diff --git a/substrate/frame/support/procedural/src/pallet/parse/helper.rs b/substrate/frame/support/procedural/src/pallet/parse/helper.rs index 1e6e83d7eeba..46ffcec031a9 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/helper.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/helper.rs @@ -147,6 +147,12 @@ impl MutItemAttrs for syn::ImplItemFn { } } +impl MutItemAttrs for syn::ItemType { + fn mut_item_attrs(&mut self) -> Option<&mut Vec> { + Some(&mut self.attrs) + } +} + /// Parse for `()` struct Unit; impl syn::parse::Parse for Unit { From 0498dc4fe3f01482bbe586b677d6803141bce4e9 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 15:35:55 +0530 Subject: [PATCH 20/48] Updates as per latest syntax --- substrate/bin/node-template/runtime/src/lib.rs | 5 +---- .../procedural/src/construct_runtime_v2/parse/mod.rs | 8 -------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 63bc0d14ac52..310805346613 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -283,9 +283,6 @@ impl pallet_template::Config for Runtime { #[frame_support::construct_runtime_v2] mod runtime { #[runtime::runtime] - pub struct Runtime; - - #[runtime::pallets] #[runtime::derive( RuntimeCall, RuntimeEvent, @@ -296,7 +293,7 @@ mod runtime { RuntimeSlashReason, RuntimeLockId )] - pub struct AllPallets; + pub struct Runtime; #[runtime::pallet_index(0)] pub type System = frame_system; diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs index 0416cde66f82..68c389f8776d 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs @@ -35,14 +35,12 @@ mod keyword { use syn::custom_keyword; custom_keyword!(runtime); - custom_keyword!(pallets); custom_keyword!(derive); custom_keyword!(pallet_index); } enum RuntimeAttr { Runtime(proc_macro2::Span), - Pallets(proc_macro2::Span), Derive(proc_macro2::Span, Vec), PalletIndex(proc_macro2::Span, u8), } @@ -51,7 +49,6 @@ impl RuntimeAttr { fn span(&self) -> proc_macro2::Span { match self { Self::Runtime(span) => *span, - Self::Pallets(span) => *span, Self::Derive(span, _) => *span, Self::PalletIndex(span, _) => *span, } @@ -69,8 +66,6 @@ impl syn::parse::Parse for RuntimeAttr { let lookahead = content.lookahead1(); if lookahead.peek(keyword::runtime) { Ok(RuntimeAttr::Runtime(content.parse::()?.span())) - } else if lookahead.peek(keyword::pallets) { - Ok(RuntimeAttr::Pallets(content.parse::()?.span())) } else if lookahead.peek(keyword::derive) { let _ = content.parse::(); let derive_content; @@ -155,9 +150,6 @@ impl Def { let p = runtime_struct::RuntimeStructDef::try_from(span, item)?; runtime_struct = Some(p); }, - RuntimeAttr::Pallets(_span) => { - //Todo: Parse pallets struct - }, RuntimeAttr::Derive(_, types) if runtime_types.is_none() => { runtime_types = Some(types); }, From 502fda434a2a1afbb7dbe25b6b2cf32a62be8458 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 15:40:56 +0530 Subject: [PATCH 21/48] Renames construct_runtime_v2 to runtime --- .../bin/node-template/runtime/src/lib.rs | 2 +- substrate/bin/node/runtime/src/lib.rs | 2 +- substrate/frame/support/procedural/src/lib.rs | 8 ++--- .../expand/mod.rs | 12 ++++---- .../{construct_runtime_v2 => runtime}/mod.rs | 30 +++++++++---------- .../parse/helper.rs | 0 .../parse/mod.rs | 0 .../parse/pallet.rs | 0 .../parse/pallet_decl.rs | 0 .../parse/runtime_struct.rs | 0 .../parse/runtime_types.rs | 0 substrate/frame/support/src/lib.rs | 2 +- .../support/test/tests/construct_runtime.rs | 2 +- .../can_only_be_attached_to_mod.stderr | 5 ---- .../missing_runtime_types_derive.stderr | 5 ---- ...nstruct_runtime_v2_ui.rs => runtime_ui.rs} | 4 +-- .../can_only_be_attached_to_mod.rs | 2 +- .../can_only_be_attached_to_mod.stderr | 5 ++++ .../conflicting_pallet_index.rs | 2 +- .../conflicting_pallet_index.stderr | 4 +-- .../conflicting_pallet_name.rs | 2 +- .../conflicting_pallet_name.stderr | 4 +-- .../invalid_pallet_index.rs | 2 +- .../invalid_pallet_index.stderr | 2 +- .../invalid_runtime_type_derive.rs | 2 +- .../invalid_runtime_type_derive.stderr | 2 +- .../missing_pallet_index.rs | 2 +- .../missing_pallet_index.stderr | 2 +- .../missing_pallets.rs | 2 +- .../missing_pallets.stderr | 2 +- .../missing_runtime.rs | 2 +- .../missing_runtime.stderr | 2 +- .../missing_runtime_types_derive.rs | 2 +- .../missing_runtime_types_derive.stderr | 5 ++++ .../missing_system_pallet.rs | 2 +- .../missing_system_pallet.stderr | 2 +- .../pallets_struct.rs | 2 +- .../pallets_struct.stderr | 2 +- .../pass/basic.rs | 2 +- .../runtime_struct.rs | 2 +- .../runtime_struct.stderr | 2 +- 41 files changed, 66 insertions(+), 66 deletions(-) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/expand/mod.rs (95%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/mod.rs (87%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/helper.rs (100%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/mod.rs (100%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/pallet.rs (100%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/pallet_decl.rs (100%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/runtime_struct.rs (100%) rename substrate/frame/support/procedural/src/{construct_runtime_v2 => runtime}/parse/runtime_types.rs (100%) delete mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr delete mode 100644 substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr rename substrate/frame/support/test/tests/{construct_runtime_v2_ui.rs => runtime_ui.rs} (91%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/can_only_be_attached_to_mod.rs (94%) create mode 100644 substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.stderr rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/conflicting_pallet_index.rs (96%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/conflicting_pallet_index.stderr (67%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/conflicting_pallet_name.rs (96%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/conflicting_pallet_name.stderr (58%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/invalid_pallet_index.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/invalid_pallet_index.stderr (63%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/invalid_runtime_type_derive.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/invalid_runtime_type_derive.stderr (77%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_pallet_index.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_pallet_index.stderr (66%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_pallets.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_pallets.stderr (53%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_runtime.rs (94%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_runtime.stderr (53%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_runtime_types_derive.rs (95%) create mode 100644 substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_system_pallet.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/missing_system_pallet.stderr (70%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/pallets_struct.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/pallets_struct.stderr (65%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/pass/basic.rs (96%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/runtime_struct.rs (95%) rename substrate/frame/support/test/tests/{construct_runtime_v2_ui => runtime_ui}/runtime_struct.stderr (64%) diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 310805346613..a86c29c4e802 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -280,7 +280,7 @@ impl pallet_template::Config for Runtime { } // Create the runtime by composing the FRAME pallets that were previously configured. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[runtime::runtime] #[runtime::derive( diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 99041bcdb7ac..bfd192556081 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2051,7 +2051,7 @@ impl pallet_mixnet::Config for Runtime { type MinMixnodes = ConstU32<7>; // Low to allow small testing networks } -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 9f3d3319856d..ca1fcb84524c 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -21,7 +21,7 @@ mod benchmark; mod construct_runtime; -mod construct_runtime_v2; +mod runtime; mod crate_version; mod derive_impl; mod dummy_part_checker; @@ -1660,7 +1660,7 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// # Example: /// /// ```ignore -/// #[frame_support::construct_runtime_v2] +/// #[frame_support::runtime] /// mod runtime { /// // The main runtime /// #[frame::runtime] @@ -1712,6 +1712,6 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System = /// frame_system::Pallet` #[proc_macro_attribute] -pub fn construct_runtime_v2(attr: TokenStream, item: TokenStream) -> TokenStream { - construct_runtime_v2::construct_runtime(attr, item) +pub fn runtime(attr: TokenStream, item: TokenStream) -> TokenStream { + runtime::runtime(attr, item) } diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs similarity index 95% rename from substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs rename to substrate/frame/support/procedural/src/runtime/expand/mod.rs index 399775863c9d..ed19a31a5520 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -21,7 +21,7 @@ use crate::{ check_pallet_number, decl_all_pallets, decl_integrity_test, decl_pallet_runtime_setup, decl_static_assertions, expand, }, - construct_runtime_v2::{ + runtime::{ parse::{ AllPalletsDeclaration, ExplicitAllPalletsDeclaration, ImplicitAllPalletsDeclaration, }, @@ -74,7 +74,7 @@ fn construct_runtime_implicit_to_explicit( ) -> Result { let frame_support = generate_crate_access_2018("frame-support")?; let mut expansion = quote::quote!( - #[frame_support::construct_runtime_v2] + #[frame_support::runtime] #input ); for pallet in definition.pallet_decls.iter() { @@ -230,16 +230,16 @@ fn construct_runtime_final_expansion( // Each runtime must expose the `runtime_metadata()` to fetch the runtime API metadata. // The function is implemented by calling `impl_runtime_apis!`. // - // However, the `construct_runtime_v2` may be used without calling `impl_runtime_apis!`. + // However, the `runtime` may be used without calling `impl_runtime_apis!`. // Rely on the `Deref` trait to differentiate between a runtime that implements - // APIs (by macro impl_runtime_apis!) and a runtime that is simply created (by macro construct_runtime_v2). + // APIs (by macro impl_runtime_apis!) and a runtime that is simply created (by macro runtime). // // Both `InternalConstructRuntime` and `InternalImplRuntimeApis` expose a `runtime_metadata()` function. - // `InternalConstructRuntime` is implemented by the `construct_runtime_v2` for Runtime references (`& Runtime`), + // `InternalConstructRuntime` is implemented by the `runtime` for Runtime references (`& Runtime`), // while `InternalImplRuntimeApis` is implemented by the `impl_runtime_apis!` for Runtime (`Runtime`). // // Therefore, the `Deref` trait will resolve the `runtime_metadata` from `impl_runtime_apis!` - // when both macros are called; and will resolve an empty `runtime_metadata` when only the `construct_runtime_v2` + // when both macros are called; and will resolve an empty `runtime_metadata` when only the `runtime` // is used. #[doc(hidden)] diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs similarity index 87% rename from substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs rename to substrate/frame/support/procedural/src/runtime/mod.rs index 57045a386225..0322cf7fa903 100644 --- a/substrate/frame/support/procedural/src/construct_runtime_v2/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -15,16 +15,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Implementation of `construct_runtime_v2`. +//! Implementation of `runtime`. //! -//! `construct_runtime_v2` implementation is recursive and can generate code which will call itself +//! `runtime` implementation is recursive and can generate code which will call itself //! in order to get all the pallet parts for each pallet. //! //! Pallets can define their parts: //! - Implicitly: `System: frame_system` //! - Explicitly: `System: frame_system + Pallet + Call` //! -//! The `construct_runtime_v2` transitions from the implicit definition to the explicit one. +//! The `runtime` transitions from the implicit definition to the explicit one. //! From the explicit state, Substrate expands the pallets with additional information //! that is to be included in the runtime metadata. //! @@ -52,7 +52,7 @@ //! +----------+ //! ``` //! -//! The `construct_runtime_v2` macro transforms the implicit declaration of each pallet +//! The `runtime` macro transforms the implicit declaration of each pallet //! `System: frame_system` to an explicit one `System: frame_system + Pallet + Call` using the //! `tt_default_parts_v2` macro. //! @@ -61,20 +61,20 @@ //! The tokens generated by this macro are `+ Pallet + Call` for our example. //! //! The `match_and_insert` macro takes in 3 arguments: -//! - target: This is the `TokenStream` that contains the `construct_runtime_v2` macro. +//! - target: This is the `TokenStream` that contains the `runtime` macro. //! - pattern: The pattern to match against in the target stream. //! - tokens: The tokens to added after the pattern match. //! -//! The `construct_runtime_v2` macro uses the `tt_call` to get the default pallet parts via +//! The `runtime` macro uses the `tt_call` to get the default pallet parts via //! the `tt_default_parts_v2` macro defined by each pallet. The pallet parts are then returned as //! input to the `match_and_replace` macro. -//! The `match_and_replace` then will modify the `construct_runtime_v2` to expand the implicit +//! The `match_and_replace` then will modify the `runtime` to expand the implicit //! definition to the explicit one. //! //! For example, //! //! ```ignore -//! #[frame::construct_runtime_v2] +//! #[frame::runtime] //! mod runtime { //! //... //! { @@ -95,7 +95,7 @@ //! macro = [{ frame_system::tt_default_parts_v2 }] //! ~~> frame_support::match_and_insert! { //! target = [{ -//! #[frame::construct_runtime_v2] +//! #[frame::runtime] //! mod runtime { //! //... //! { @@ -122,7 +122,7 @@ //! target = [{ //! frame_support::match_and_insert! { //! target = [{ -//! #[frame::construct_runtime_v2] +//! #[frame::runtime] //! mod runtime { //! //... //! { @@ -145,7 +145,7 @@ //! ```ignore //! frame_support::match_and_insert! { //! target = [{ -//! #[frame::construct_runtime_v2] +//! #[frame::runtime] //! mod runtime { //! //... //! { @@ -163,7 +163,7 @@ //! //! Which will then finally expand to the following: //! ```ignore -//! #[frame::construct_runtime_v2] +//! #[frame::runtime] //! mod runtime { //! //... //! { @@ -189,13 +189,13 @@ //! ```ignore //! +----------------------+ +---------------------+ +-------------------+ //! | | | (defined in pallet) | | | -//! | construct_runtime_v2 | --> | tt_default_parts! | --> | match_and_insert! | +//! | runtime | --> | tt_default_parts! | --> | match_and_insert! | //! | w/ no pallet parts | | | | | //! +----------------------+ +---------------------+ +-------------------+ //! //! +----------------------+ //! | | -//! --> | construct_runtime_v2 | +//! --> | runtime | //! | w/ pallet parts | //! +----------------------+ //! ``` @@ -206,7 +206,7 @@ use proc_macro::TokenStream; mod expand; mod parse; -pub fn construct_runtime(_attrs: TokenStream, tokens: TokenStream) -> TokenStream { +pub fn runtime(_attrs: TokenStream, tokens: TokenStream) -> TokenStream { let item = syn::parse_macro_input!(tokens as syn::ItemMod); match parse::Def::try_from(item) { Ok(def) => expand::expand(def).into(), diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs b/substrate/frame/support/procedural/src/runtime/parse/helper.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/helper.rs rename to substrate/frame/support/procedural/src/runtime/parse/helper.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/mod.rs rename to substrate/frame/support/procedural/src/runtime/parse/mod.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet.rs rename to substrate/frame/support/procedural/src/runtime/parse/pallet.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/pallet_decl.rs rename to substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs b/substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_struct.rs rename to substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs diff --git a/substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs b/substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs similarity index 100% rename from substrate/frame/support/procedural/src/construct_runtime_v2/parse/runtime_types.rs rename to substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index a210544bd35f..a8b09a56420f 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -491,7 +491,7 @@ pub fn debug(data: &impl sp_std::fmt::Debug) { #[doc(inline)] pub use frame_support_procedural::{ - construct_runtime, construct_runtime_v2, match_and_insert, transactional, PalletError, + construct_runtime, runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, }; diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/construct_runtime.rs index a94f4c75bd67..fd58748f7602 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime.rs @@ -281,7 +281,7 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr deleted file mode 100644 index 2763747b97f9..000000000000 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected `mod` - --> tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs:19:1 - | -19 | fn construct_runtime() {} - | ^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr deleted file mode 100644 index eb0138825e5a..000000000000 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Missing `#[frame::derive]` - --> tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs:19:1 - | -19 | mod runtime { - | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui.rs b/substrate/frame/support/test/tests/runtime_ui.rs similarity index 91% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui.rs rename to substrate/frame/support/test/tests/runtime_ui.rs index 1de0c9874d1c..dbe150f38ed6 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui.rs +++ b/substrate/frame/support/test/tests/runtime_ui.rs @@ -31,6 +31,6 @@ fn ui() { std::env::set_var("RUSTFLAGS", "--deny warnings"); let t = trybuild::TestCases::new(); - t.compile_fail("tests/construct_runtime_v2_ui/*.rs"); - t.pass("tests/construct_runtime_v2_ui/pass/*.rs"); + t.compile_fail("tests/runtime_ui/*.rs"); + t.pass("tests/runtime_ui/pass/*.rs"); } diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs b/substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.rs similarity index 94% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs rename to substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.rs index 49e69beffdd2..eb5868090418 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/can_only_be_attached_to_mod.rs +++ b/substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] fn construct_runtime() {} fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.stderr b/substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.stderr new file mode 100644 index 000000000000..7c2f0d1f1699 --- /dev/null +++ b/substrate/frame/support/test/tests/runtime_ui/can_only_be_attached_to_mod.stderr @@ -0,0 +1,5 @@ +error: expected `mod` + --> tests/runtime_ui/can_only_be_attached_to_mod.rs:19:1 + | +19 | fn construct_runtime() {} + | ^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs similarity index 96% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs rename to substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs index 4dc2b3ed2b6d..a314a18dea4b 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.rs +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs @@ -27,7 +27,7 @@ mod pallet { impl Pallet {} } -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr similarity index 67% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr rename to substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr index 215b67ca981c..f0d308a090c4 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_index.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr @@ -1,11 +1,11 @@ error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 - --> tests/construct_runtime_v2_ui/conflicting_pallet_index.rs:39:9 + --> tests/runtime_ui/conflicting_pallet_index.rs:39:9 | 39 | System: frame_system, | ^^^^^^ error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 - --> tests/construct_runtime_v2_ui/conflicting_pallet_index.rs:41:9 + --> tests/runtime_ui/conflicting_pallet_index.rs:41:9 | 41 | Pallet: pallet, | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs similarity index 96% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs rename to substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs index a92e3c0b1fa4..63c75d82c6d5 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.rs +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs @@ -27,7 +27,7 @@ mod pallet { impl Pallet {} } -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr similarity index 58% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr rename to substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr index 346ccf263750..8b831acd33ab 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/conflicting_pallet_name.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr @@ -1,11 +1,11 @@ error: Two pallets with the same name! - --> tests/construct_runtime_v2_ui/conflicting_pallet_name.rs:39:9 + --> tests/runtime_ui/conflicting_pallet_name.rs:39:9 | 39 | System: frame_system, | ^^^^^^ error: Two pallets with the same name! - --> tests/construct_runtime_v2_ui/conflicting_pallet_name.rs:41:9 + --> tests/runtime_ui/conflicting_pallet_name.rs:41:9 | 41 | System: pallet, | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs rename to substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs index 847dd00a82e5..e5aff9de21de 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.rs +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr similarity index 63% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr rename to substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr index 2ac048e1834f..bd140d0491fc 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_pallet_index.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr @@ -1,5 +1,5 @@ error: expected integer literal - --> tests/construct_runtime_v2_ui/invalid_pallet_index.rs:26:31 + --> tests/runtime_ui/invalid_pallet_index.rs:26:31 | 26 | #[frame::pallet_index("0")] | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs rename to substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs index c5c9ba491e8c..901f9fd84d94 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr similarity index 77% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr rename to substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr index eceef731815f..99512fb51e43 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/invalid_runtime_type_derive.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr @@ -1,5 +1,5 @@ error: expected one of: `RuntimeCall`, `RuntimeEvent`, `RuntimeError`, `RuntimeOrigin`, `RuntimeFreezeReason`, `RuntimeHoldReason`, `RuntimeSlashReason`, `RuntimeLockId` - --> tests/construct_runtime_v2_ui/invalid_runtime_type_derive.rs:24:21 + --> tests/runtime_ui/invalid_runtime_type_derive.rs:24:21 | 24 | #[frame::derive(RuntimeInfo)] | ^^^^^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs rename to substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs index 532bddc9a508..3e89acb2a7c3 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr similarity index 66% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr rename to substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr index 797ae25f3e3d..b6599bc4ae6e 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallet_index.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr @@ -1,5 +1,5 @@ error: Invalid pallet declaration, expected a #[frame::pallet_index] - --> tests/construct_runtime_v2_ui/missing_pallet_index.rs:26:9 + --> tests/runtime_ui/missing_pallet_index.rs:26:9 | 26 | System: frame_system | ^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs rename to substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs index 1db0813fa8e4..3ee621c9729b 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr similarity index 53% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr rename to substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr index f4ff0977c03e..491f0791aedf 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_pallets.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr @@ -1,5 +1,5 @@ error: Missing `#[frame::pallets]` - --> tests/construct_runtime_v2_ui/missing_pallets.rs:19:1 + --> tests/runtime_ui/missing_pallets.rs:19:1 | 19 | mod runtime { | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.rs similarity index 94% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs rename to substrate/frame/support/test/tests/runtime_ui/missing_runtime.rs index f7a05c28fac1..c5febbe52876 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime {} fn main() {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr similarity index 53% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr rename to substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr index 992087eaf857..1f7840abbc49 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr @@ -1,5 +1,5 @@ error: Missing `#[frame::runtime]` - --> tests/construct_runtime_v2_ui/missing_runtime.rs:19:1 + --> tests/runtime_ui/missing_runtime.rs:19:1 | 19 | mod runtime {} | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs rename to substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs index 53b02d911c96..659299c67b40 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_runtime_types_derive.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr new file mode 100644 index 000000000000..1817ac458e46 --- /dev/null +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr @@ -0,0 +1,5 @@ +error: Missing `#[frame::derive]` + --> tests/runtime_ui/missing_runtime_types_derive.rs:19:1 + | +19 | mod runtime { + | ^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs rename to substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs index 7f4016bc3435..f6e707e968dc 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr similarity index 70% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr rename to substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr index 76ed324fab7a..c55d31a7f017 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/missing_system_pallet.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr @@ -1,5 +1,5 @@ error: `System` pallet declaration is missing. Please add this line: `System: frame_system,` - --> tests/construct_runtime_v2_ui/missing_system_pallet.rs:25:16 + --> tests/runtime_ui/missing_system_pallet.rs:25:16 | 25 | pub struct Pallets {} | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs rename to substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs index 80666ba55978..3cd79481816e 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.rs +++ b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr similarity index 65% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr rename to substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr index fb73417e0577..c6c64f218b4a 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pallets_struct.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr @@ -1,5 +1,5 @@ error: Invalid frame::pallets, expected struct definition - --> tests/construct_runtime_v2_ui/pallets_struct.rs:23:14 + --> tests/runtime_ui/pallets_struct.rs:23:14 | 23 | #[frame::pallets] | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs similarity index 96% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs rename to substrate/frame/support/test/tests/runtime_ui/pass/basic.rs index c1fce3e7c4c1..a6d014e2d932 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/pass/basic.rs +++ b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs @@ -24,7 +24,7 @@ impl frame_system::Config for Runtime { type Block = Block; } -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs similarity index 95% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs rename to substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs index 72d9fc93bfd8..673e308abcc3 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.rs +++ b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::construct_runtime_v2] +#[frame_support::runtime] mod runtime { #[frame::runtime] pub enum Runtime {} diff --git a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr similarity index 64% rename from substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr rename to substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr index 10bcf8cf4fd5..73453312e382 100644 --- a/substrate/frame/support/test/tests/construct_runtime_v2_ui/runtime_struct.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr @@ -1,5 +1,5 @@ error: Invalid frame::runtime, expected struct definition - --> tests/construct_runtime_v2_ui/runtime_struct.rs:21:5 + --> tests/runtime_ui/runtime_struct.rs:21:5 | 21 | pub enum Runtime {} | ^^^ From e8b5371aedad6c291cf83bf8d9362d1d90504cb6 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 15:52:31 +0530 Subject: [PATCH 22/48] Fixes kitchensink build --- substrate/bin/node/runtime/src/lib.rs | 373 +++++++++++++++----------- 1 file changed, 221 insertions(+), 152 deletions(-) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index bfd192556081..562786cf1d7f 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2053,11 +2053,8 @@ impl pallet_mixnet::Config for Runtime { #[frame_support::runtime] mod runtime { - #[frame::runtime] - pub struct Runtime; - - #[frame::pallets] - #[frame::derive( + #[runtime::runtime] + #[runtime::derive( RuntimeCall, RuntimeEvent, RuntimeError, @@ -2067,153 +2064,225 @@ mod runtime { RuntimeSlashReason, RuntimeLockId )] - pub struct Pallets { - #[frame::pallet_index(0)] - System: frame_system, - #[frame::pallet_index(1)] - Utility: pallet_utility, - #[frame::pallet_index(2)] - Babe: pallet_babe, - #[frame::pallet_index(3)] - Timestamp: pallet_timestamp, - // Authorship must be before session in order to note author in the correct session and era - // for im-online and staking. - #[frame::pallet_index(4)] - Authorship: pallet_authorship, - #[frame::pallet_index(5)] - Indices: pallet_indices, - #[frame::pallet_index(6)] - Balances: pallet_balances, - #[frame::pallet_index(7)] - TransactionPayment: pallet_transaction_payment, - #[frame::pallet_index(8)] - AssetTxPayment: pallet_asset_tx_payment, - #[frame::pallet_index(9)] - AssetConversionTxPayment: pallet_asset_conversion_tx_payment, - #[frame::pallet_index(10)] - ElectionProviderMultiPhase: pallet_election_provider_multi_phase, - #[frame::pallet_index(11)] - Staking: pallet_staking, - #[frame::pallet_index(12)] - Session: pallet_session, - #[frame::pallet_index(13)] - Democracy: pallet_democracy, - #[frame::pallet_index(14)] - Council: pallet_collective, - #[frame::pallet_index(15)] - TechnicalCommittee: pallet_collective, - #[frame::pallet_index(16)] - Elections: pallet_elections_phragmen, - #[frame::pallet_index(17)] - TechnicalMembership: pallet_membership, - #[frame::pallet_index(18)] - Grandpa: pallet_grandpa, - #[frame::pallet_index(19)] - Treasury: pallet_treasury, - #[frame::pallet_index(20)] - AssetRate: pallet_asset_rate, - #[frame::pallet_index(21)] - Contracts: pallet_contracts, - #[frame::pallet_index(22)] - Sudo: pallet_sudo, - #[frame::pallet_index(23)] - ImOnline: pallet_im_online, - #[frame::pallet_index(24)] - AuthorityDiscovery: pallet_authority_discovery, - #[frame::pallet_index(25)] - Offences: pallet_offences, - #[frame::pallet_index(26)] - Historical: pallet_session_historical + Pallet, - #[frame::pallet_index(27)] - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, - #[frame::pallet_index(28)] - Identity: pallet_identity, - #[frame::pallet_index(29)] - Society: pallet_society, - #[frame::pallet_index(30)] - Recovery: pallet_recovery, - #[frame::pallet_index(31)] - Vesting: pallet_vesting, - #[frame::pallet_index(32)] - Scheduler: pallet_scheduler, - #[frame::pallet_index(33)] - Glutton: pallet_glutton, - #[frame::pallet_index(34)] - Preimage: pallet_preimage, - #[frame::pallet_index(35)] - Proxy: pallet_proxy, - #[frame::pallet_index(36)] - Multisig: pallet_multisig, - #[frame::pallet_index(37)] - Bounties: pallet_bounties, - #[frame::pallet_index(38)] - Tips: pallet_tips, - #[frame::pallet_index(39)] - Assets: pallet_assets, - #[frame::pallet_index(40)] - PoolAssets: pallet_assets, - #[frame::pallet_index(41)] - Mmr: pallet_mmr, - #[frame::pallet_index(42)] - Lottery: pallet_lottery, - #[frame::pallet_index(43)] - Nis: pallet_nis, - #[frame::pallet_index(44)] - Uniques: pallet_uniques, - #[frame::pallet_index(45)] - Nfts: pallet_nfts, - #[frame::pallet_index(46)] - NftFractionalization: pallet_nft_fractionalization, - #[frame::pallet_index(47)] - Salary: pallet_salary, - #[frame::pallet_index(48)] - CoreFellowship: pallet_core_fellowship, - #[frame::pallet_index(49)] - TransactionStorage: pallet_transaction_storage, - #[frame::pallet_index(50)] - VoterList: pallet_bags_list, - #[frame::pallet_index(51)] - StateTrieMigration: pallet_state_trie_migration, - #[frame::pallet_index(52)] - ChildBounties: pallet_child_bounties, - #[frame::pallet_index(53)] - Referenda: pallet_referenda, - #[frame::pallet_index(54)] - Remark: pallet_remark, - #[frame::pallet_index(55)] - RootTesting: pallet_root_testing, - #[frame::pallet_index(56)] - ConvictionVoting: pallet_conviction_voting, - #[frame::pallet_index(57)] - Whitelist: pallet_whitelist, - #[frame::pallet_index(58)] - AllianceMotion: pallet_collective, - #[frame::pallet_index(59)] - Alliance: pallet_alliance, - #[frame::pallet_index(60)] - NominationPools: pallet_nomination_pools, - #[frame::pallet_index(61)] - RankedPolls: pallet_referenda, - #[frame::pallet_index(62)] - RankedCollective: pallet_ranked_collective, - #[frame::pallet_index(63)] - AssetConversion: pallet_asset_conversion, - #[frame::pallet_index(64)] - FastUnstake: pallet_fast_unstake, - #[frame::pallet_index(65)] - MessageQueue: pallet_message_queue, - #[frame::pallet_index(66)] - Pov: frame_benchmarking_pallet_pov, - #[frame::pallet_index(67)] - TxPause: pallet_tx_pause, - #[frame::pallet_index(68)] - SafeMode: pallet_safe_mode, - #[frame::pallet_index(69)] - Statement: pallet_statement, - #[frame::pallet_index(70)] - Broker: pallet_broker, - Mixnet: pallet_mixnet, - } + pub struct Runtime; + + #[runtime::pallet_index(0)] + pub type System = frame_system; + + #[runtime::pallet_index(1)] + pub type Utility= pallet_utility; + + #[runtime::pallet_index(2)] + pub type Babe = pallet_babe; + + #[runtime::pallet_index(3)] + pub type Timestamp = pallet_timestamp; + + // Authorship must be before session in order to note author in the correct session and era + // for im-online and staking. + #[runtime::pallet_index(4)] + pub type Authorship = pallet_authorship; + + #[runtime::pallet_index(5)] + pub type Indices = pallet_indices; + + #[runtime::pallet_index(6)] + pub type Balances = pallet_balances; + + #[runtime::pallet_index(7)] + pub type TransactionPayment = pallet_transaction_payment; + + #[runtime::pallet_index(8)] + pub type AssetTxPayment = pallet_asset_tx_payment; + + #[runtime::pallet_index(9)] + pub type AssetConversionTxPayment = pallet_asset_conversion_tx_payment; + + #[runtime::pallet_index(10)] + pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase; + + #[runtime::pallet_index(11)] + pub type Staking = pallet_staking; + + #[runtime::pallet_index(12)] + pub type Session = pallet_session; + + #[runtime::pallet_index(13)] + pub type Democracy = pallet_democracy; + + #[runtime::pallet_index(14)] + pub type Council = pallet_collective; + + #[runtime::pallet_index(15)] + pub type TechnicalCommittee = pallet_collective; + + #[runtime::pallet_index(16)] + pub type Elections = pallet_elections_phragmen; + + #[runtime::pallet_index(17)] + pub type TechnicalMembership = pallet_membership; + + #[runtime::pallet_index(18)] + pub type Grandpa = pallet_grandpa; + + #[runtime::pallet_index(19)] + pub type Treasury = pallet_treasury; + + #[runtime::pallet_index(20)] + pub type AssetRate = pallet_asset_rate; + + #[runtime::pallet_index(21)] + pub type Contracts = pallet_contracts; + + #[runtime::pallet_index(22)] + pub type Sudo = pallet_sudo; + + #[runtime::pallet_index(23)] + pub type ImOnline = pallet_im_online; + + #[runtime::pallet_index(24)] + pub type AuthorityDiscovery = pallet_authority_discovery; + + #[runtime::pallet_index(25)] + pub type Offences = pallet_offences; + + #[runtime::pallet_index(26)] + pub type Historical = pallet_session_historical + Pallet; + + #[runtime::pallet_index(27)] + pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip; + + #[runtime::pallet_index(28)] + pub type Identity = pallet_identity; + + #[runtime::pallet_index(29)] + pub type Society = pallet_society; + + #[runtime::pallet_index(30)] + pub type Recovery = pallet_recovery; + + #[runtime::pallet_index(31)] + pub type Vesting = pallet_vesting; + + #[runtime::pallet_index(32)] + pub type Scheduler = pallet_scheduler; + + #[runtime::pallet_index(33)] + pub type Glutton = pallet_glutton; + + #[runtime::pallet_index(34)] + pub type Preimage = pallet_preimage; + + #[runtime::pallet_index(35)] + pub type Proxy = pallet_proxy; + + #[runtime::pallet_index(36)] + pub type Multisig = pallet_multisig; + + #[runtime::pallet_index(37)] + pub type Bounties = pallet_bounties; + + #[runtime::pallet_index(38)] + pub type Tips = pallet_tips; + + #[runtime::pallet_index(39)] + pub type Assets = pallet_assets; + + #[runtime::pallet_index(40)] + pub type PoolAssets = pallet_assets; + + #[runtime::pallet_index(41)] + pub type Mmr = pallet_mmr; + + #[runtime::pallet_index(42)] + pub type Lottery = pallet_lottery; + + #[runtime::pallet_index(43)] + pub type Nis = pallet_nis; + + #[runtime::pallet_index(44)] + pub type Uniques = pallet_uniques; + + #[runtime::pallet_index(45)] + pub type Nfts = pallet_nfts; + + #[runtime::pallet_index(46)] + pub type NftFractionalization = pallet_nft_fractionalization; + + #[runtime::pallet_index(47)] + pub type Salary = pallet_salary; + + #[runtime::pallet_index(48)] + pub type CoreFellowship = pallet_core_fellowship; + + #[runtime::pallet_index(49)] + pub type TransactionStorage = pallet_transaction_storage; + + #[runtime::pallet_index(50)] + pub type VoterList = pallet_bags_list; + + #[runtime::pallet_index(51)] + pub type StateTrieMigration = pallet_state_trie_migration; + + #[runtime::pallet_index(52)] + pub type ChildBounties = pallet_child_bounties; + + #[runtime::pallet_index(53)] + pub type Referenda = pallet_referenda; + + #[runtime::pallet_index(54)] + pub type Remark = pallet_remark; + + #[runtime::pallet_index(55)] + pub type RootTesting = pallet_root_testing; + + #[runtime::pallet_index(56)] + pub type ConvictionVoting = pallet_conviction_voting; + + #[runtime::pallet_index(57)] + pub type Whitelist = pallet_whitelist; + + #[runtime::pallet_index(58)] + pub type AllianceMotion = pallet_collective; + + #[runtime::pallet_index(59)] + pub type Alliance = pallet_alliance; + + #[runtime::pallet_index(60)] + pub type NominationPools = pallet_nomination_pools; + + #[runtime::pallet_index(61)] + pub type RankedPolls = pallet_referenda; + + #[runtime::pallet_index(62)] + pub type RankedCollective = pallet_ranked_collective; + + #[runtime::pallet_index(63)] + pub type AssetConversion = pallet_asset_conversion; + + #[runtime::pallet_index(64)] + pub type FastUnstake = pallet_fast_unstake; + + #[runtime::pallet_index(65)] + pub type MessageQueue = pallet_message_queue; + + #[runtime::pallet_index(66)] + pub type Pov = frame_benchmarking_pallet_pov; + + #[runtime::pallet_index(67)] + pub type TxPause = pallet_tx_pause; + + #[runtime::pallet_index(68)] + pub type SafeMode = pallet_safe_mode; + + #[runtime::pallet_index(69)] + pub type Statement = pallet_statement; + + #[runtime::pallet_index(70)] + pub type Broker = pallet_broker; + + #[runtime::pallet_index(71)] + pub type Mixnet = pallet_mixnet; } /// The address format for describing accounts. From dcc0b604faa0632eccc335b293f9f87c3b76aa09 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 16:15:24 +0530 Subject: [PATCH 23/48] Updates tests and docs --- substrate/frame/support/procedural/src/lib.rs | 48 ++++++----- .../procedural/src/runtime/expand/mod.rs | 2 +- .../support/procedural/src/runtime/mod.rs | 60 +++++++------- .../support/test/tests/construct_runtime.rs | 81 ++++++++++--------- .../runtime_ui/conflicting_pallet_index.rs | 16 ++-- .../conflicting_pallet_index.stderr | 12 +-- .../runtime_ui/conflicting_pallet_name.rs | 16 ++-- .../runtime_ui/conflicting_pallet_name.stderr | 12 +-- .../tests/runtime_ui/invalid_pallet_index.rs | 11 +-- .../runtime_ui/invalid_pallet_index.stderr | 6 +- .../runtime_ui/invalid_runtime_type_derive.rs | 7 +- .../invalid_runtime_type_derive.stderr | 6 +- .../tests/runtime_ui/missing_pallet_index.rs | 30 ------- .../runtime_ui/missing_pallet_index.stderr | 5 -- .../test/tests/runtime_ui/missing_pallets.rs | 24 ------ .../tests/runtime_ui/missing_pallets.stderr | 5 -- .../tests/runtime_ui/missing_runtime.stderr | 2 +- .../missing_runtime_types_derive.rs | 5 +- .../missing_runtime_types_derive.stderr | 2 +- .../tests/runtime_ui/missing_system_pallet.rs | 7 +- .../runtime_ui/missing_system_pallet.stderr | 8 +- .../test/tests/runtime_ui/pallets_struct.rs | 27 ------- .../tests/runtime_ui/pallets_struct.stderr | 5 -- .../test/tests/runtime_ui/pass/basic.rs | 11 +-- .../test/tests/runtime_ui/runtime_struct.rs | 2 +- 25 files changed, 151 insertions(+), 259 deletions(-) delete mode 100644 substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs delete mode 100644 substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr delete mode 100644 substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs delete mode 100644 substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr delete mode 100644 substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs delete mode 100644 substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index ca1fcb84524c..cec036a5d182 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1663,12 +1663,9 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// #[frame_support::runtime] /// mod runtime { /// // The main runtime -/// #[frame::runtime] -/// pub struct Runtime; -/// -/// #[frame::pallets] +/// #[runtime::runtime] /// // Runtime Types to be generated -/// #[frame::derive( +/// #[runtime::derive( /// RuntimeCall, /// RuntimeEvent, /// RuntimeError, @@ -1678,26 +1675,27 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// RuntimeSlashReason, /// RuntimeLockId /// )] -/// pub struct Pallets { -/// #[frame::pallet_index(0)] -/// System: frame_system, -/// #[frame::pallet_index(1)] -/// Test: path::to::test, -/// -/// // Pallet with instance. -/// #[frame::pallet_index(2)] -/// Test2_Instance1: test2, -/// -/// // Pallet with calls disabled. -/// #[frame::pallet_index(3)] -/// #[frame::disable_call] -/// Test3: test3, -/// -/// // Pallet with unsigned extrinsics disabled. -/// #[frame::pallet_index(4)] -/// #[frame::disable_unsigned] -/// Test4: test4, -/// } +/// pub struct Runtime; +/// +/// #[runtime::pallet_index(0)] +/// pub type System = frame_system; +/// +/// #[runtime::pallet_index(1)] +/// pub type Test = path::to::test; +/// +/// // Pallet with instance. +/// #[runtime::pallet_index(2)] +/// pub type Test2_Instance1 = test2; +/// +/// // Pallet with calls disabled. +/// #[runtime::pallet_index(3)] +/// #[runtime::disable_call] +/// pub type Test3 = test3; +/// +/// // Pallet with unsigned extrinsics disabled. +/// #[runtime::pallet_index(4)] +/// #[runtime::disable_unsigned] +/// pub type Test4 = test4; /// } /// ``` /// diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index ed19a31a5520..f88fd5af44d7 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -108,7 +108,7 @@ fn construct_runtime_final_expansion( syn::Error::new( pallets_name.span(), "`System` pallet declaration is missing. \ - Please add this line: `System: frame_system,`", + Please add this line: `pub type System = frame_system;`", ) })?; if !system_pallet.cfg_pattern.is_empty() { diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index 0322cf7fa903..60ac2f78e0e8 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -77,12 +77,12 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! { -//! #[frame::pallet_index(0)] -//! System: frame_system, // Implicit definition of parts -//! #[frame::pallet_index(1)] -//! Balances: pallet_balances, // Implicit definition of parts -//! } +//! +//! #[runtime::pallet_index(0)] +//! pub type System = frame_system; // Implicit definition of parts +//! +//! #[runtime::pallet_index(1)] +//! pub type Balances = pallet_balances; // Implicit definition of parts //! } //! ``` //! This call has some implicit pallet parts, thus it will expand to: @@ -98,12 +98,12 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! { -//! #[frame::pallet_index(0)] -//! System: frame_system, -//! #[frame::pallet_index(1)] -//! Balances: pallet_balances, -//! } +//! +//! #[runtime::pallet_index(0)] +//! pub type System = frame_system; +//! +//! #[runtime::pallet_index(1)] +//! pub type Balances = pallet_balances; //! } //! }] //! pattern = [{ System: frame_system }] @@ -125,12 +125,12 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! { -//! #[frame::pallet_index(0)] -//! System: frame_system, -//! #[frame::pallet_index(1)] -//! Balances: pallet_balances, -//! } +//! +//! #[runtime::pallet_index(0)] +//! pub type System = frame_system; +//! +//! #[runtime::pallet_index(1)] +//! pub type Balances = pallet_balances; //! } //! }] //! pattern = [{ System: frame_system }] @@ -148,12 +148,12 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! { -//! #[frame::pallet_index(0)] -//! System: frame_system, // Implicit definition of parts -//! #[frame::pallet_index(1)] -//! Balances: pallet_balances + Pallet + Call, // Explicit definition of parts -//! } +//! +//! #[runtime::pallet_index(0)] +//! pub type System = frame_system; // Implicit definition of parts +//! +//! #[runtime::pallet_index(1)] +//! pub type Balances = pallet_balances + Pallet + Call; // Explicit definition of parts //! } //! }] //! pattern = [{ System: frame_system }] @@ -166,12 +166,12 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! { -//! #[frame::pallet_index(0)] -//! System: frame_system + Pallet + Call, -//! #[frame::pallet_index(1)] -//! Balances: pallet_balances + Pallet + Call, -//! } +//! +//! #[runtime::pallet_index(0)] +//! pub type System = frame_system + Pallet + Call; +//! +//! #[runtime::pallet_index(1)] +//! pub type Balances = pallet_balances + Pallet + Call; //! } //! ``` //! diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/construct_runtime.rs index fd58748f7602..a6342c1b2d17 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime.rs @@ -283,11 +283,8 @@ pub type Block = generic::Block; #[frame_support::runtime] mod runtime { - #[frame::runtime] - pub struct Runtime; - - #[frame::pallets] - #[frame::derive( + #[runtime::runtime] + #[runtime::derive( RuntimeCall, RuntimeEvent, RuntimeError, @@ -297,37 +294,49 @@ mod runtime { RuntimeSlashReason, RuntimeLockId )] - pub struct Pallets { - #[frame::pallet_index(30)] - System: frame_system + Pallet + Call + Event + Origin, - #[frame::pallet_index(31)] - Module1_1: module1, - #[frame::pallet_index(32)] - Module2: module2, - #[frame::pallet_index(33)] - Module1_2: module1, - #[frame::pallet_index(34)] - NestedModule3: nested::module3, - #[frame::pallet_index(35)] - #[frame::disable_unsigned] - Module3: self::module3, - #[frame::pallet_index(6)] - #[frame::disable_call] - Module1_3: module1, - #[frame::pallet_index(3)] - Module1_4: module1, - #[frame::pallet_index(4)] - #[frame::disable_call] - Module1_5: module1, - #[frame::pallet_index(1)] - Module1_6: module1, - #[frame::pallet_index(2)] - Module1_7: module1, - #[frame::pallet_index(12)] - Module1_8: module1, - #[frame::pallet_index(13)] - Module1_9: module1, - } + pub struct Runtime; + + #[runtime::pallet_index(30)] + pub type System = frame_system + Pallet + Call + Event + Origin; + + #[runtime::pallet_index(31)] + pub type Module1_1 = module1; + + #[runtime::pallet_index(32)] + pub type Module2 = module2; + + #[runtime::pallet_index(33)] + pub type Module1_2 = module1; + + #[runtime::pallet_index(34)] + pub type NestedModule3 = nested::module3; + + #[runtime::pallet_index(35)] + #[frame::disable_unsigned] + pub type Module3 = self::module3; + + #[runtime::pallet_index(6)] + #[frame::disable_call] + pub type Module1_3 = module1; + + #[runtime::pallet_index(3)] + pub type Module1_4 = module1; + + #[runtime::pallet_index(4)] + #[frame::disable_call] + pub type Module1_5 = module1; + + #[runtime::pallet_index(1)] + pub type Module1_6 = module1; + + #[runtime::pallet_index(2)] + pub type Module1_7 = module1; + + #[runtime::pallet_index(12)] + pub type Module1_8 = module1; + + #[runtime::pallet_index(13)] + pub type Module1_9 = module1; } #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] diff --git a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs index a314a18dea4b..648812b52c4f 100644 --- a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.rs @@ -29,17 +29,15 @@ mod pallet { #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeCall)] pub struct Runtime; - #[frame::pallets] - #[frame::derive(RuntimeCall)] - pub struct Pallets { - #[frame::pallet_index(0)] - System: frame_system, - #[frame::pallet_index(0)] - Pallet: pallet, - } + #[runtime::pallet_index(0)] + pub type System = frame_system; + + #[runtime::pallet_index(0)] + pub type Pallet = pallet; } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr index f0d308a090c4..8963c5d3f265 100644 --- a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_index.stderr @@ -1,11 +1,11 @@ error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 - --> tests/runtime_ui/conflicting_pallet_index.rs:39:9 + --> tests/runtime_ui/conflicting_pallet_index.rs:37:14 | -39 | System: frame_system, - | ^^^^^^ +37 | pub type System = frame_system; + | ^^^^^^ error: Pallet indices are conflicting: Both pallets System and Pallet are at index 0 - --> tests/runtime_ui/conflicting_pallet_index.rs:41:9 + --> tests/runtime_ui/conflicting_pallet_index.rs:40:14 | -41 | Pallet: pallet, - | ^^^^^^ +40 | pub type Pallet = pallet; + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs index 63c75d82c6d5..c68f9a8082b4 100644 --- a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.rs @@ -29,17 +29,15 @@ mod pallet { #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeCall)] pub struct Runtime; - #[frame::pallets] - #[frame::derive(RuntimeCall)] - pub struct Pallets { - #[frame::pallet_index(0)] - System: frame_system, - #[frame::pallet_index(1)] - System: pallet, - } + #[runtime::pallet_index(0)] + pub type System = frame_system; + + #[runtime::pallet_index(1)] + pub type System = pallet; } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr index 8b831acd33ab..c250c24e3e70 100644 --- a/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/conflicting_pallet_name.stderr @@ -1,11 +1,11 @@ error: Two pallets with the same name! - --> tests/runtime_ui/conflicting_pallet_name.rs:39:9 + --> tests/runtime_ui/conflicting_pallet_name.rs:37:14 | -39 | System: frame_system, - | ^^^^^^ +37 | pub type System = frame_system; + | ^^^^^^ error: Two pallets with the same name! - --> tests/runtime_ui/conflicting_pallet_name.rs:41:9 + --> tests/runtime_ui/conflicting_pallet_name.rs:40:14 | -41 | System: pallet, - | ^^^^^^ +40 | pub type System = pallet; + | ^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs index e5aff9de21de..de89bb60224f 100644 --- a/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.rs @@ -17,15 +17,12 @@ #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeCall)] pub struct Runtime; - #[frame::pallets] - #[frame::derive(RuntimeCall)] - pub struct Pallets { - #[frame::pallet_index("0")] - System: frame_system - } + #[runtime::pallet_index("0")] + pub type System = frame_system; } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr index bd140d0491fc..1fbd086ddbe7 100644 --- a/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_pallet_index.stderr @@ -1,5 +1,5 @@ error: expected integer literal - --> tests/runtime_ui/invalid_pallet_index.rs:26:31 + --> tests/runtime_ui/invalid_pallet_index.rs:24:29 | -26 | #[frame::pallet_index("0")] - | ^^^ +24 | #[runtime::pallet_index("0")] + | ^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs index 901f9fd84d94..89ba2f23bb1a 100644 --- a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.rs @@ -17,12 +17,9 @@ #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeInfo)] pub struct Runtime; - - #[frame::pallets] - #[frame::derive(RuntimeInfo)] - pub struct Pallets {} } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr index 99512fb51e43..2a71b75986a2 100644 --- a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr @@ -1,5 +1,5 @@ error: expected one of: `RuntimeCall`, `RuntimeEvent`, `RuntimeError`, `RuntimeOrigin`, `RuntimeFreezeReason`, `RuntimeHoldReason`, `RuntimeSlashReason`, `RuntimeLockId` - --> tests/runtime_ui/invalid_runtime_type_derive.rs:24:21 + --> tests/runtime_ui/invalid_runtime_type_derive.rs:21:23 | -24 | #[frame::derive(RuntimeInfo)] - | ^^^^^^^^^^^ +21 | #[runtime::derive(RuntimeInfo)] + | ^^^^^^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs deleted file mode 100644 index 3e89acb2a7c3..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.rs +++ /dev/null @@ -1,30 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[frame_support::runtime] -mod runtime { - #[frame::runtime] - pub struct Runtime; - - #[frame::pallets] - #[frame::derive(RuntimeCall)] - pub struct Pallets { - System: frame_system - } -} - -fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr deleted file mode 100644 index b6599bc4ae6e..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/missing_pallet_index.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Invalid pallet declaration, expected a #[frame::pallet_index] - --> tests/runtime_ui/missing_pallet_index.rs:26:9 - | -26 | System: frame_system - | ^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs deleted file mode 100644 index 3ee621c9729b..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/missing_pallets.rs +++ /dev/null @@ -1,24 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[frame_support::runtime] -mod runtime { - #[frame::runtime] - pub struct Runtime; -} - -fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr deleted file mode 100644 index 491f0791aedf..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/missing_pallets.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Missing `#[frame::pallets]` - --> tests/runtime_ui/missing_pallets.rs:19:1 - | -19 | mod runtime { - | ^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr index 1f7840abbc49..689a3d7e5af1 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr @@ -1,4 +1,4 @@ -error: Missing `#[frame::runtime]` +error: Missing `#[runtime::runtime]` --> tests/runtime_ui/missing_runtime.rs:19:1 | 19 | mod runtime {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs index 659299c67b40..c3fb0fd454f0 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.rs @@ -17,11 +17,8 @@ #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] pub struct Runtime; - - #[frame::pallets] - pub struct Pallets {} } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr index 1817ac458e46..f136af36cf8c 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr @@ -1,4 +1,4 @@ -error: Missing `#[frame::derive]` +error: Missing `#[runtime::derive]` --> tests/runtime_ui/missing_runtime_types_derive.rs:19:1 | 19 | mod runtime { diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs index f6e707e968dc..f9a15fcf992a 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs +++ b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.rs @@ -17,12 +17,9 @@ #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeCall)] pub struct Runtime; - - #[frame::pallets] - #[frame::derive(RuntimeCall)] - pub struct Pallets {} } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr index c55d31a7f017..dc3ac4cd5d56 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_system_pallet.stderr @@ -1,5 +1,5 @@ -error: `System` pallet declaration is missing. Please add this line: `System: frame_system,` - --> tests/runtime_ui/missing_system_pallet.rs:25:16 +error: `System` pallet declaration is missing. Please add this line: `pub type System = frame_system;` + --> tests/runtime_ui/missing_system_pallet.rs:19:5 | -25 | pub struct Pallets {} - | ^^^^^^^ +19 | mod runtime { + | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs deleted file mode 100644 index 3cd79481816e..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/pallets_struct.rs +++ /dev/null @@ -1,27 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#[frame_support::runtime] -mod runtime { - #[frame::runtime] - pub struct Runtime; - - #[frame::pallets] - pub enum Pallets {} -} - -fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr b/substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr deleted file mode 100644 index c6c64f218b4a..000000000000 --- a/substrate/frame/support/test/tests/runtime_ui/pallets_struct.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Invalid frame::pallets, expected struct definition - --> tests/runtime_ui/pallets_struct.rs:23:14 - | -23 | #[frame::pallets] - | ^^^^^^^ diff --git a/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs index a6d014e2d932..b84ff72f95fc 100644 --- a/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs +++ b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs @@ -26,15 +26,12 @@ impl frame_system::Config for Runtime { #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] + #[runtime::derive(RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeError)] pub struct Runtime; - #[frame::pallets] - #[frame::derive(RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeError)] - pub struct Pallets { - #[frame::pallet_index(0)] - System: frame_system - } + #[runtime::pallet_index(0)] + pub type System = frame_system; } fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs index 673e308abcc3..bfa2fb75f04b 100644 --- a/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs +++ b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.rs @@ -17,7 +17,7 @@ #[frame_support::runtime] mod runtime { - #[frame::runtime] + #[runtime::runtime] pub enum Runtime {} } From 8a4b13c123a91dde5bb766fbdca59e88f70debdc Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 16:16:06 +0530 Subject: [PATCH 24/48] fmt --- substrate/bin/node/runtime/src/lib.rs | 2 +- substrate/frame/support/procedural/src/lib.rs | 4 ++-- .../support/procedural/src/runtime/mod.rs | 18 +++++++++--------- substrate/frame/support/src/lib.rs | 3 +-- 4 files changed, 13 insertions(+), 14 deletions(-) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 562786cf1d7f..1d56c9b10090 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2070,7 +2070,7 @@ mod runtime { pub type System = frame_system; #[runtime::pallet_index(1)] - pub type Utility= pallet_utility; + pub type Utility = pallet_utility; #[runtime::pallet_index(2)] pub type Babe = pallet_babe; diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index cec036a5d182..071580b9a8d9 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -21,7 +21,6 @@ mod benchmark; mod construct_runtime; -mod runtime; mod crate_version; mod derive_impl; mod dummy_part_checker; @@ -30,6 +29,7 @@ mod match_and_insert; mod no_bound; mod pallet; mod pallet_error; +mod runtime; mod storage_alias; mod transactional; mod tt_macro; @@ -1676,7 +1676,7 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// RuntimeLockId /// )] /// pub struct Runtime; -/// +/// /// #[runtime::pallet_index(0)] /// pub type System = frame_system; /// diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index 60ac2f78e0e8..f7d9071122f4 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -77,10 +77,10 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! +//! //! #[runtime::pallet_index(0)] //! pub type System = frame_system; // Implicit definition of parts -//! +//! //! #[runtime::pallet_index(1)] //! pub type Balances = pallet_balances; // Implicit definition of parts //! } @@ -98,7 +98,7 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! +//! //! #[runtime::pallet_index(0)] //! pub type System = frame_system; //! @@ -125,10 +125,10 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! +//! //! #[runtime::pallet_index(0)] //! pub type System = frame_system; -//! +//! //! #[runtime::pallet_index(1)] //! pub type Balances = pallet_balances; //! } @@ -148,10 +148,10 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! +//! //! #[runtime::pallet_index(0)] //! pub type System = frame_system; // Implicit definition of parts -//! +//! //! #[runtime::pallet_index(1)] //! pub type Balances = pallet_balances + Pallet + Call; // Explicit definition of parts //! } @@ -166,10 +166,10 @@ //! #[frame::runtime] //! mod runtime { //! //... -//! +//! //! #[runtime::pallet_index(0)] //! pub type System = frame_system + Pallet + Call; -//! +//! //! #[runtime::pallet_index(1)] //! pub type Balances = pallet_balances + Pallet + Call; //! } diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index a8b09a56420f..4c1cc8a5fbc8 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -491,8 +491,7 @@ pub fn debug(data: &impl sp_std::fmt::Debug) { #[doc(inline)] pub use frame_support_procedural::{ - construct_runtime, runtime, match_and_insert, transactional, PalletError, - RuntimeDebugNoBound, + construct_runtime, match_and_insert, runtime, transactional, PalletError, RuntimeDebugNoBound, }; #[doc(hidden)] From 1e44e9bdf50fc58a05447ce5fc420a7cb3f5ef9c Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 16:18:05 +0530 Subject: [PATCH 25/48] Minor fix --- substrate/frame/support/test/tests/construct_runtime.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/construct_runtime.rs index a6342c1b2d17..f1de4b971dd2 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime.rs @@ -312,18 +312,18 @@ mod runtime { pub type NestedModule3 = nested::module3; #[runtime::pallet_index(35)] - #[frame::disable_unsigned] + #[runtime::disable_unsigned] pub type Module3 = self::module3; #[runtime::pallet_index(6)] - #[frame::disable_call] + #[runtime::disable_call] pub type Module1_3 = module1; #[runtime::pallet_index(3)] pub type Module1_4 = module1; #[runtime::pallet_index(4)] - #[frame::disable_call] + #[runtime::disable_call] pub type Module1_5 = module1; #[runtime::pallet_index(1)] From 6660575eac63878f057fe9a028cb3180d3b1297f Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <> Date: Thu, 12 Oct 2023 16:19:56 +0530 Subject: [PATCH 26/48] Minor fixes --- .../frame/support/procedural/src/runtime/mod.rs | 12 ++++++------ .../procedural/src/runtime/parse/runtime_struct.rs | 2 +- .../test/tests/runtime_ui/runtime_struct.stderr | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index f7d9071122f4..ac9e99397c88 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -32,7 +32,7 @@ //! These are automatically implemented by the `#[pallet::pallet]` macro. //! //! This macro also generates the following enums for ease of decoding if the respective type -//! is defined inside `#[frame::derive]`: +//! is defined inside `#[runtime::derive]`: //! - `enum RuntimeCall`: This type contains the information needed to decode extrinsics. //! - `enum RuntimeEvent`: This type contains the information needed to decode events. //! - `enum RuntimeError`: While this cannot be used directly to decode `sp_runtime::DispatchError` @@ -74,7 +74,7 @@ //! For example, //! //! ```ignore -//! #[frame::runtime] +//! #[frame_support::runtime] //! mod runtime { //! //... //! @@ -95,7 +95,7 @@ //! macro = [{ frame_system::tt_default_parts_v2 }] //! ~~> frame_support::match_and_insert! { //! target = [{ -//! #[frame::runtime] +//! #[frame_support::runtime] //! mod runtime { //! //... //! @@ -122,7 +122,7 @@ //! target = [{ //! frame_support::match_and_insert! { //! target = [{ -//! #[frame::runtime] +//! #[frame_support::runtime] //! mod runtime { //! //... //! @@ -145,7 +145,7 @@ //! ```ignore //! frame_support::match_and_insert! { //! target = [{ -//! #[frame::runtime] +//! #[frame_support::runtime] //! mod runtime { //! //... //! @@ -163,7 +163,7 @@ //! //! Which will then finally expand to the following: //! ```ignore -//! #[frame::runtime] +//! #[frame_support::runtime] //! mod runtime { //! //... //! diff --git a/substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs b/substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs index edc2d79eb593..8fa746ee8072 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/runtime_struct.rs @@ -26,7 +26,7 @@ impl RuntimeStructDef { let item = if let syn::Item::Struct(item) = item { item } else { - let msg = "Invalid frame::runtime, expected struct definition"; + let msg = "Invalid runtime::runtime, expected struct definition"; return Err(syn::Error::new(item.span(), msg)) }; diff --git a/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr index 73453312e382..04192bcf7f19 100644 --- a/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/runtime_struct.stderr @@ -1,4 +1,4 @@ -error: Invalid frame::runtime, expected struct definition +error: Invalid runtime::runtime, expected struct definition --> tests/runtime_ui/runtime_struct.rs:21:5 | 21 | pub enum Runtime {} From 985faefae9995a083db319cecbfa0b357560fd88 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Sat, 3 Feb 2024 10:48:43 +0530 Subject: [PATCH 27/48] Adds missing pallets in v2 --- substrate/bin/node/runtime/src/lib.rs | 73 +++++++++++++++------------ 1 file changed, 42 insertions(+), 31 deletions(-) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 085554efc79b..64859a3d8f64 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2182,7 +2182,7 @@ mod runtime { pub type Offences = pallet_offences; #[runtime::pallet_index(26)] - pub type Historical = pallet_session_historical + Pallet; + pub type Historical = pallet_session_historical; #[runtime::pallet_index(27)] pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip; @@ -2227,97 +2227,108 @@ mod runtime { pub type PoolAssets = pallet_assets; #[runtime::pallet_index(41)] - pub type Mmr = pallet_mmr; + pub type Beefy = pallet_beefy; + // MMR leaf construction must be after session in order to have a leaf's next_auth_set + // refer to block. See issue polkadot-fellows/runtimes#160 for details. #[runtime::pallet_index(42)] - pub type Lottery = pallet_lottery; + pub type Mmr = pallet_mmr; #[runtime::pallet_index(43)] - pub type Nis = pallet_nis; + pub type MmrLeaf = pallet_beefy_mmr; #[runtime::pallet_index(44)] - pub type Uniques = pallet_uniques; + pub type Lottery = pallet_lottery; #[runtime::pallet_index(45)] - pub type Nfts = pallet_nfts; + pub type Nis = pallet_nis; #[runtime::pallet_index(46)] - pub type NftFractionalization = pallet_nft_fractionalization; + pub type Uniques = pallet_uniques; #[runtime::pallet_index(47)] - pub type Salary = pallet_salary; + pub type Nfts = pallet_nfts; #[runtime::pallet_index(48)] - pub type CoreFellowship = pallet_core_fellowship; + pub type NftFractionalization = pallet_nft_fractionalization; #[runtime::pallet_index(49)] - pub type TransactionStorage = pallet_transaction_storage; + pub type Salary = pallet_salary; #[runtime::pallet_index(50)] - pub type VoterList = pallet_bags_list; + pub type CoreFellowship = pallet_core_fellowship; #[runtime::pallet_index(51)] - pub type StateTrieMigration = pallet_state_trie_migration; + pub type TransactionStorage = pallet_transaction_storage; #[runtime::pallet_index(52)] - pub type ChildBounties = pallet_child_bounties; + pub type VoterList = pallet_bags_list; #[runtime::pallet_index(53)] - pub type Referenda = pallet_referenda; + pub type StateTrieMigration = pallet_state_trie_migration; #[runtime::pallet_index(54)] - pub type Remark = pallet_remark; + pub type ChildBounties = pallet_child_bounties; #[runtime::pallet_index(55)] - pub type RootTesting = pallet_root_testing; + pub type Referenda = pallet_referenda; #[runtime::pallet_index(56)] - pub type ConvictionVoting = pallet_conviction_voting; + pub type Remark = pallet_remark; #[runtime::pallet_index(57)] - pub type Whitelist = pallet_whitelist; + pub type RootTesting = pallet_root_testing; #[runtime::pallet_index(58)] - pub type AllianceMotion = pallet_collective; + pub type ConvictionVoting = pallet_conviction_voting; #[runtime::pallet_index(59)] - pub type Alliance = pallet_alliance; + pub type Whitelist = pallet_whitelist; #[runtime::pallet_index(60)] - pub type NominationPools = pallet_nomination_pools; + pub type AllianceMotion = pallet_collective; #[runtime::pallet_index(61)] - pub type RankedPolls = pallet_referenda; + pub type Alliance = pallet_alliance; #[runtime::pallet_index(62)] - pub type RankedCollective = pallet_ranked_collective; + pub type NominationPools = pallet_nomination_pools; #[runtime::pallet_index(63)] - pub type AssetConversion = pallet_asset_conversion; + pub type RankedPolls = pallet_referenda; #[runtime::pallet_index(64)] - pub type FastUnstake = pallet_fast_unstake; + pub type RankedCollective = pallet_ranked_collective; #[runtime::pallet_index(65)] - pub type MessageQueue = pallet_message_queue; + pub type AssetConversion = pallet_asset_conversion; #[runtime::pallet_index(66)] - pub type Pov = frame_benchmarking_pallet_pov; + pub type FastUnstake = pallet_fast_unstake; #[runtime::pallet_index(67)] - pub type TxPause = pallet_tx_pause; + pub type MessageQueue = pallet_message_queue; #[runtime::pallet_index(68)] - pub type SafeMode = pallet_safe_mode; + pub type Pov = frame_benchmarking_pallet_pov; #[runtime::pallet_index(69)] - pub type Statement = pallet_statement; + pub type TxPause = pallet_tx_pause; #[runtime::pallet_index(70)] - pub type Broker = pallet_broker; + pub type SafeMode = pallet_safe_mode; #[runtime::pallet_index(71)] + pub type Statement = pallet_statement; + + #[runtime::pallet_index(72)] + pub type Broker = pallet_broker; + + #[runtime::pallet_index(73)] pub type Mixnet = pallet_mixnet; + + #[runtime::pallet_index(74)] + pub type SkipFeelessPayment = pallet_skip_feeless_payment; } /// The address format for describing accounts. From 5be682d8dc33fd9e370e31936d2dc59fff440efb Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Thu, 8 Feb 2024 10:37:48 +0530 Subject: [PATCH 28/48] Fixes build and adds RuntimeTask support --- substrate/bin/node-template/runtime/src/lib.rs | 3 ++- substrate/bin/node/runtime/src/lib.rs | 3 ++- .../support/procedural/src/runtime/expand/mod.rs | 12 +++++++++--- .../procedural/src/runtime/parse/runtime_types.rs | 4 ++++ 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 7e9ada83a370..c0b05e1240ba 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -267,7 +267,8 @@ mod runtime { RuntimeFreezeReason, RuntimeHoldReason, RuntimeSlashReason, - RuntimeLockId + RuntimeLockId, + RuntimeTask, )] pub struct Runtime; diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 64859a3d8f64..140ab0c0d873 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2097,7 +2097,8 @@ mod runtime { RuntimeFreezeReason, RuntimeHoldReason, RuntimeSlashReason, - RuntimeLockId + RuntimeLockId, + RuntimeTask, )] pub struct Runtime; diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index f88fd5af44d7..0184d0be0651 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -30,7 +30,7 @@ use crate::{ }; use cfg_expr::Predicate; use frame_support_procedural_tools::{ - generate_crate_access, generate_crate_access_2018, generate_hidden_includes, + generate_access_from_frame_or_crate, generate_crate_access, generate_hidden_includes, }; use proc_macro2::TokenStream as TokenStream2; use quote::quote; @@ -72,7 +72,7 @@ fn construct_runtime_implicit_to_explicit( input: TokenStream2, definition: ImplicitAllPalletsDeclaration, ) -> Result { - let frame_support = generate_crate_access_2018("frame-support")?; + let frame_support = generate_access_from_frame_or_crate("frame-support")?; let mut expansion = quote::quote!( #[frame_support::runtime] #input @@ -138,7 +138,7 @@ fn construct_runtime_final_expansion( let scrate = generate_crate_access(hidden_crate_name, "frame-support"); let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support"); - let frame_system = generate_crate_access_2018("frame-system")?; + let frame_system = generate_access_from_frame_or_crate("frame-system")?; let block = quote!(<#name as #frame_system::Config>::Block); let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); @@ -150,6 +150,7 @@ fn construct_runtime_final_expansion( let mut hold_reason = None; let mut slash_reason = None; let mut lock_id = None; + let mut task = None; for runtime_type in runtime_types.iter() { match runtime_type { @@ -189,6 +190,9 @@ fn construct_runtime_final_expansion( RuntimeType::RuntimeLockId(_) => { lock_id = Some(expand::expand_outer_lock_id(&pallets, &scrate)); }, + RuntimeType::RuntimeTask(_) => { + task = Some(expand::expand_outer_task(&name, &pallets, &scrate)); + }, } } @@ -264,6 +268,8 @@ fn construct_runtime_final_expansion( #dispatch + #task + #metadata #outer_config diff --git a/substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs b/substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs index de0e582dd550..a4480e2a1fd3 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/runtime_types.rs @@ -31,6 +31,7 @@ mod keyword { custom_keyword!(RuntimeHoldReason); custom_keyword!(RuntimeSlashReason); custom_keyword!(RuntimeLockId); + custom_keyword!(RuntimeTask); } #[derive(Debug, Clone, PartialEq)] @@ -43,6 +44,7 @@ pub enum RuntimeType { RuntimeHoldReason(keyword::RuntimeHoldReason), RuntimeSlashReason(keyword::RuntimeSlashReason), RuntimeLockId(keyword::RuntimeLockId), + RuntimeTask(keyword::RuntimeTask), } impl Parse for RuntimeType { @@ -65,6 +67,8 @@ impl Parse for RuntimeType { Ok(Self::RuntimeSlashReason(input.parse()?)) } else if lookahead.peek(keyword::RuntimeLockId) { Ok(Self::RuntimeLockId(input.parse()?)) + } else if lookahead.peek(keyword::RuntimeTask) { + Ok(Self::RuntimeTask(input.parse()?)) } else { Err(lookahead.error()) } From aba35c6ac4e47dee8d8de3377baa536325024cdd Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Thu, 8 Feb 2024 11:16:25 +0530 Subject: [PATCH 29/48] Fixes test --- .../procedural/src/runtime/parse/mod.rs | 103 +++++++++++------- .../procedural/src/runtime/parse/pallet.rs | 47 +------- .../src/runtime/parse/pallet_decl.rs | 2 +- .../support/test/tests/construct_runtime.rs | 3 +- 4 files changed, 68 insertions(+), 87 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs index 68c389f8776d..65ab546206d2 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/mod.rs @@ -37,12 +37,16 @@ mod keyword { custom_keyword!(runtime); custom_keyword!(derive); custom_keyword!(pallet_index); + custom_keyword!(disable_call); + custom_keyword!(disable_unsigned); } enum RuntimeAttr { Runtime(proc_macro2::Span), Derive(proc_macro2::Span, Vec), PalletIndex(proc_macro2::Span, u8), + DisableCall(proc_macro2::Span), + DisableUnsigned(proc_macro2::Span), } impl RuntimeAttr { @@ -51,6 +55,8 @@ impl RuntimeAttr { Self::Runtime(span) => *span, Self::Derive(span, _) => *span, Self::PalletIndex(span, _) => *span, + Self::DisableCall(span) => *span, + Self::DisableUnsigned(span) => *span, } } } @@ -84,6 +90,10 @@ impl syn::parse::Parse for RuntimeAttr { return Err(syn::Error::new(pallet_index.span(), msg)) } Ok(RuntimeAttr::PalletIndex(pallet_index.span(), pallet_index.base10_parse()?)) + } else if lookahead.peek(keyword::disable_call) { + Ok(RuntimeAttr::DisableCall(content.parse::()?.span())) + } else if lookahead.peek(keyword::disable_unsigned) { + Ok(RuntimeAttr::DisableUnsigned(content.parse::()?.span())) } else { Err(lookahead.error()) } @@ -142,6 +152,12 @@ impl Def { let mut pallets = vec![]; for item in items.iter_mut() { + let mut pallet_item = None; + let mut pallet_index = 0; + + let mut disable_call = false; + let mut disable_unsigned = false; + while let Some(runtime_attr) = helper::take_first_item_runtime_attr::(item)? { @@ -153,58 +169,63 @@ impl Def { RuntimeAttr::Derive(_, types) if runtime_types.is_none() => { runtime_types = Some(types); }, - RuntimeAttr::PalletIndex(span, pallet_index) => { - let item = if let syn::Item::Type(item) = item { - item + RuntimeAttr::PalletIndex(span, index) => { + pallet_index = index; + pallet_item = if let syn::Item::Type(item) = item { + Some(item.clone()) } else { let msg = "Invalid runtime::pallet_index, expected type definition"; return Err(syn::Error::new(span, msg)) }; - - match *item.ty.clone() { - syn::Type::Path(ref path) => { - let pallet_decl = - PalletDeclaration::try_from(item.span(), item, path)?; - - if let Some(used_pallet) = - names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) - { - let msg = "Two pallets with the same name!"; - - let mut err = syn::Error::new(used_pallet, &msg); - err.combine(syn::Error::new(pallet_decl.name.span(), &msg)); - return Err(err) - } - - pallet_decls.push(pallet_decl); - }, - syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { - let pallet = - Pallet::try_from(item.span(), item, pallet_index, &bounds)?; - - if let Some(used_pallet) = - indices.insert(pallet.index, pallet.name.clone()) - { - let msg = format!( - "Pallet indices are conflicting: Both pallets {} and {} are at index {}", - used_pallet, pallet.name, pallet.index, - ); - let mut err = syn::Error::new(used_pallet.span(), &msg); - err.combine(syn::Error::new(pallet.name.span(), msg)); - return Err(err) - } - - pallets.push(pallet); - }, - _ => continue, - } }, + RuntimeAttr::DisableCall(_) => disable_call = true, + RuntimeAttr::DisableUnsigned(_) => disable_unsigned = true, attr => { let msg = "Invalid duplicated attribute"; return Err(syn::Error::new(attr.span(), msg)) }, } } + + if let Some(pallet_item) = pallet_item { + match *pallet_item.ty.clone() { + syn::Type::Path(ref path) => { + let pallet_decl = + PalletDeclaration::try_from(item.span(), &pallet_item, path)?; + + if let Some(used_pallet) = + names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) + { + let msg = "Two pallets with the same name!"; + + let mut err = syn::Error::new(used_pallet, &msg); + err.combine(syn::Error::new(pallet_decl.name.span(), &msg)); + return Err(err) + } + + pallet_decls.push(pallet_decl); + }, + syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { + let pallet = + Pallet::try_from(item.span(), &pallet_item, pallet_index, disable_call, disable_unsigned, &bounds)?; + + if let Some(used_pallet) = + indices.insert(pallet.index, pallet.name.clone()) + { + let msg = format!( + "Pallet indices are conflicting: Both pallets {} and {} are at index {}", + used_pallet, pallet.name, pallet.index, + ); + let mut err = syn::Error::new(used_pallet.span(), &msg); + err.combine(syn::Error::new(pallet.name.span(), msg)); + return Err(err) + } + + pallets.push(pallet); + }, + _ => continue, + } + } } let name = item.ident.clone(); diff --git a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs index 0dec4e49d862..d2f1857fb2b4 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs @@ -15,62 +15,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::helper; use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; use quote::ToTokens; use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; -mod keyword { - use syn::custom_keyword; - - custom_keyword!(runtime); - custom_keyword!(disable_call); - custom_keyword!(disable_unsigned); -} - -enum PalletAttr { - DisableCall(proc_macro2::Span), - DisableUnsigned(proc_macro2::Span), -} - -impl syn::parse::Parse for PalletAttr { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - input.parse::()?; - let content; - syn::bracketed!(content in input); - content.parse::()?; - content.parse::()?; - - let lookahead = content.lookahead1(); - if lookahead.peek(keyword::disable_call) { - Ok(PalletAttr::DisableCall(content.parse::()?.span())) - } else if lookahead.peek(keyword::disable_unsigned) { - Ok(PalletAttr::DisableUnsigned(content.parse::()?.span())) - } else { - Err(lookahead.error()) - } - } -} - impl Pallet { pub fn try_from( attr_span: proc_macro2::Span, - item: &mut syn::ItemType, + item: &syn::ItemType, pallet_index: u8, + disable_call: bool, + disable_unsigned: bool, bounds: &Punctuated, ) -> syn::Result { let name = item.ident.clone(); - let mut disable_call = false; - let mut disable_unsigned = false; - - while let Some(pallet_attr) = helper::take_first_item_runtime_attr::(item)? { - match pallet_attr { - PalletAttr::DisableCall(_) => disable_call = true, - PalletAttr::DisableUnsigned(_) => disable_unsigned = true, - } - } - let mut pallet_path = None; let mut pallet_parts = vec![]; diff --git a/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs index 5d571996ad07..437a163cfbc4 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs @@ -34,7 +34,7 @@ pub struct PalletDeclaration { impl PalletDeclaration { pub fn try_from( _attr_span: proc_macro2::Span, - item: &mut syn::ItemType, + item: &syn::ItemType, path: &syn::TypePath, ) -> syn::Result { let name = item.ident.clone(); diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/construct_runtime.rs index 24fc7edb8bf8..322ffad3562e 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/construct_runtime.rs @@ -292,7 +292,8 @@ mod runtime { RuntimeFreezeReason, RuntimeHoldReason, RuntimeSlashReason, - RuntimeLockId + RuntimeLockId, + RuntimeTask, )] pub struct Runtime; From 7733d61d36612a76b9b33cfc7ef7231aa14b1f3e Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Thu, 8 Feb 2024 11:19:58 +0530 Subject: [PATCH 30/48] Adds task to tt_default_parts_v2 --- .../support/procedural/src/pallet/expand/tt_default_parts.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs index 0b00e7b59a2b..99364aaa96cd 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs @@ -85,6 +85,8 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { let call_part_v2 = def.call.as_ref().map(|_| quote::quote!(+ Call)); + let task_part_v2 = def.task_enum.as_ref().map(|_| quote::quote!(+ Task)); + let storage_part_v2 = (!def.storages.is_empty()).then(|| quote::quote!(+ Storage)); let event_part_v2 = def.event.as_ref().map(|event| { @@ -202,7 +204,7 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { $caller tokens = [{ + Pallet #call_part_v2 #storage_part_v2 #event_part_v2 #error_part_v2 #origin_part_v2 #config_part_v2 - #inherent_part_v2 #validate_unsigned_part_v2 #freeze_reason_part_v2 + #inherent_part_v2 #validate_unsigned_part_v2 #freeze_reason_part_v2 #task_part_v2 #hold_reason_part_v2 #lock_id_part_v2 #slash_reason_part_v2 }] } From 0774bcac52e185cbc0461fff9c8da58cde37bb41 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Thu, 8 Feb 2024 11:40:55 +0530 Subject: [PATCH 31/48] Adds TaskExample in v2 --- substrate/bin/node/runtime/src/lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 3663ac8faf38..67f9cc5ef917 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2328,9 +2328,12 @@ mod runtime { pub type Broker = pallet_broker; #[runtime::pallet_index(73)] - pub type Mixnet = pallet_mixnet; + pub type TasksExample = pallet_example_tasks; #[runtime::pallet_index(74)] + pub type Mixnet = pallet_mixnet; + + #[runtime::pallet_index(75)] pub type SkipFeelessPayment = pallet_skip_feeless_payment; } From 2c17eda2607ca982a970a0c7278142db8299f72a Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Fri, 9 Feb 2024 10:19:35 +0530 Subject: [PATCH 32/48] Fixes UI Tests --- .../test/tests/runtime_ui/invalid_runtime_type_derive.stderr | 2 +- substrate/frame/support/test/tests/runtime_ui/pass/basic.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr index 2a71b75986a2..0b128c3dd457 100644 --- a/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_runtime_type_derive.stderr @@ -1,4 +1,4 @@ -error: expected one of: `RuntimeCall`, `RuntimeEvent`, `RuntimeError`, `RuntimeOrigin`, `RuntimeFreezeReason`, `RuntimeHoldReason`, `RuntimeSlashReason`, `RuntimeLockId` +error: expected one of: `RuntimeCall`, `RuntimeEvent`, `RuntimeError`, `RuntimeOrigin`, `RuntimeFreezeReason`, `RuntimeHoldReason`, `RuntimeSlashReason`, `RuntimeLockId`, `RuntimeTask` --> tests/runtime_ui/invalid_runtime_type_derive.rs:21:23 | 21 | #[runtime::derive(RuntimeInfo)] diff --git a/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs index b84ff72f95fc..514f15018015 100644 --- a/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs +++ b/substrate/frame/support/test/tests/runtime_ui/pass/basic.rs @@ -27,7 +27,7 @@ impl frame_system::Config for Runtime { #[frame_support::runtime] mod runtime { #[runtime::runtime] - #[runtime::derive(RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeError)] + #[runtime::derive(RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeError, RuntimeTask)] pub struct Runtime; #[runtime::pallet_index(0)] From 19db6d7d8b4204e8024aa0db5527da554d264344 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 12 Feb 2024 08:59:10 +0530 Subject: [PATCH 33/48] Updates docs --- substrate/bin/node/runtime/src/lib.rs | 1 + substrate/frame/support/procedural/src/lib.rs | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 1d9aabadf335..30a553f898ad 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2128,6 +2128,7 @@ impl Default for RuntimeParameters { )) } } + pub struct DynamicParametersManagerOrigin; impl EnsureOriginWithArg for DynamicParametersManagerOrigin { type Success = (); diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index e348b88dcea0..30377104542b 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1708,7 +1708,8 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// RuntimeFreezeReason, /// RuntimeHoldReason, /// RuntimeSlashReason, -/// RuntimeLockId +/// RuntimeLockId, +/// RuntimeTask, /// )] /// pub struct Runtime; /// From 69a49a46b65128972886a504a6aee9a6d69e47be Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 12 Feb 2024 09:00:16 +0530 Subject: [PATCH 34/48] Adds legacy_ordering --- .../procedural/src/runtime/expand/mod.rs | 21 +++++++++++++---- .../support/procedural/src/runtime/mod.rs | 23 +++++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index 0184d0be0651..56751b60f42d 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -40,19 +40,20 @@ use syn::{Ident, Result}; /// The fixed name of the system pallet. const SYSTEM_PALLET_NAME: &str = "System"; -pub fn expand(def: Def) -> TokenStream2 { +pub fn expand(def: Def, legacy_ordering: bool) -> TokenStream2 { let input = def.input; let res = match def.pallets { AllPalletsDeclaration::Implicit(ref decl) => check_pallet_number(input.clone(), decl.pallet_count) - .and_then(|_| construct_runtime_implicit_to_explicit(input.into(), decl.clone())), + .and_then(|_| construct_runtime_implicit_to_explicit(input.into(), decl.clone(), legacy_ordering)), AllPalletsDeclaration::Explicit(ref decl) => check_pallet_number(input, decl.pallets.len()) .and_then(|_| { construct_runtime_final_expansion( def.runtime_struct.ident.clone(), decl.clone(), def.runtime_types.clone(), + legacy_ordering, ) }), }; @@ -71,10 +72,16 @@ pub fn expand(def: Def) -> TokenStream2 { fn construct_runtime_implicit_to_explicit( input: TokenStream2, definition: ImplicitAllPalletsDeclaration, + legacy_ordering: bool, ) -> Result { let frame_support = generate_access_from_frame_or_crate("frame-support")?; + let attr = if legacy_ordering { + quote!((legacy_ordering)) + } else { + quote!() + }; let mut expansion = quote::quote!( - #[frame_support::runtime] + #[frame_support::runtime #attr] #input ); for pallet in definition.pallet_decls.iter() { @@ -100,8 +107,14 @@ fn construct_runtime_final_expansion( name: Ident, definition: ExplicitAllPalletsDeclaration, runtime_types: Vec, + legacy_ordering: bool, ) -> Result { - let ExplicitAllPalletsDeclaration { pallets, name: pallets_name } = definition; + let ExplicitAllPalletsDeclaration { mut pallets, name: pallets_name } = definition; + + if !legacy_ordering { + // Ensure that order of hooks is based on the pallet index + pallets.sort_by_key(|p| p.index); + } let system_pallet = pallets.iter().find(|decl| decl.name == SYSTEM_PALLET_NAME).ok_or_else(|| { diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index ac9e99397c88..e24bca1b4abe 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -202,14 +202,33 @@ pub use parse::Def; use proc_macro::TokenStream; +use syn::spanned::Spanned; mod expand; mod parse; -pub fn runtime(_attrs: TokenStream, tokens: TokenStream) -> TokenStream { +mod keyword { + syn::custom_keyword!(legacy_ordering); +} + +pub fn runtime(attr: TokenStream, tokens: TokenStream) -> TokenStream { + let mut legacy_ordering = false; + if !attr.is_empty() { + if let Ok(_) = syn::parse::(attr.clone()) { + legacy_ordering = true; + } else { + let msg = "Invalid runtime macro call: unexpected attribute. Macro call must be \ + bare, such as `#[frame_support::runtime]` or `#[runtime]`, or must specify the \ + `legacy_ordering` attribute, such as `#[frame_support::runtime(legacy_ordering)]` or \ + #[runtime(legacy_ordering)]."; + let span = proc_macro2::TokenStream::from(attr).span(); + return syn::Error::new(span, msg).to_compile_error().into() + } + } + let item = syn::parse_macro_input!(tokens as syn::ItemMod); match parse::Def::try_from(item) { - Ok(def) => expand::expand(def).into(), + Ok(def) => expand::expand(def, legacy_ordering).into(), Err(e) => e.to_compile_error().into(), } } From dd1df58e3f89fe389e9158600096a0aacb53fdec Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 13 Feb 2024 10:40:32 +0530 Subject: [PATCH 35/48] Adds UI Test for legacy_ordering --- .../tests/runtime_ui/invalid_attribute.rs | 23 +++++++++++++++++++ .../tests/runtime_ui/invalid_attribute.stderr | 5 ++++ 2 files changed, 28 insertions(+) create mode 100644 substrate/frame/support/test/tests/runtime_ui/invalid_attribute.rs create mode 100644 substrate/frame/support/test/tests/runtime_ui/invalid_attribute.stderr diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.rs b/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.rs new file mode 100644 index 000000000000..5df2491cb24b --- /dev/null +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.rs @@ -0,0 +1,23 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[frame_support::runtime(dummy)] +mod runtime { + +} + +fn main() {} diff --git a/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.stderr b/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.stderr new file mode 100644 index 000000000000..e13552413c00 --- /dev/null +++ b/substrate/frame/support/test/tests/runtime_ui/invalid_attribute.stderr @@ -0,0 +1,5 @@ +error: Invalid runtime macro call: unexpected attribute. Macro call must be bare, such as `#[frame_support::runtime]` or `#[runtime]`, or must specify the `legacy_ordering` attribute, such as `#[frame_support::runtime(legacy_ordering)]` or #[runtime(legacy_ordering)]. + --> tests/runtime_ui/invalid_attribute.rs:18:26 + | +18 | #[frame_support::runtime(dummy)] + | ^^^^^ From c3c0be3a16e5d81b779d665c90c7e9af327c8615 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 13 Feb 2024 10:43:10 +0530 Subject: [PATCH 36/48] Fixes UT --- .../{construct_runtime.rs => runtime.rs} | 150 +-- .../test/tests/runtime_legacy_ordering.rs | 994 ++++++++++++++++++ 2 files changed, 1069 insertions(+), 75 deletions(-) rename substrate/frame/support/test/tests/{construct_runtime.rs => runtime.rs} (99%) create mode 100644 substrate/frame/support/test/tests/runtime_legacy_ordering.rs diff --git a/substrate/frame/support/test/tests/construct_runtime.rs b/substrate/frame/support/test/tests/runtime.rs similarity index 99% rename from substrate/frame/support/test/tests/construct_runtime.rs rename to substrate/frame/support/test/tests/runtime.rs index 322ffad3562e..e2ca125ff51a 100644 --- a/substrate/frame/support/test/tests/construct_runtime.rs +++ b/substrate/frame/support/test/tests/runtime.rs @@ -21,19 +21,19 @@ #![recursion_limit = "128"] -use codec::MaxEncodedLen; -use frame_support::{ +pub use codec::MaxEncodedLen; +pub use frame_support::{ derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, }; -use frame_system::limits::{BlockLength, BlockWeights}; -use scale_info::TypeInfo; -use sp_core::{sr25519, ConstU64}; -use sp_runtime::{ +pub use frame_system::limits::{BlockLength, BlockWeights}; +pub use scale_info::TypeInfo; +pub use sp_core::{sr25519, ConstU64}; +pub use sp_runtime::{ generic, traits::{BlakeTwo256, ValidateUnsigned, Verify}, DispatchError, ModuleError, }; -use sp_version::RuntimeVersion; +pub use sp_version::RuntimeVersion; parameter_types! { pub static IntegrityTestExec: u32 = 0; @@ -670,17 +670,17 @@ fn get_module_names() { let module_names = RuntimeCall::get_module_names(); assert_eq!( [ + "Module1_6", + "Module1_7", + "Module1_4", + "Module1_8", + "Module1_9", "System", "Module1_1", "Module2", "Module1_2", "NestedModule3", "Module3", - "Module1_4", - "Module1_6", - "Module1_7", - "Module1_8", - "Module1_9", ], module_names ); @@ -718,6 +718,69 @@ fn test_metadata() { } let pallets = vec![ + PalletMetadata { + name: "Module1_6", + storage:None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 1, + }, + PalletMetadata { + name: "Module1_7", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 2, + }, + PalletMetadata { + name: "Module1_4", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 3, + }, + PalletMetadata { + name: "Module1_5", + storage: None, + calls: None, + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 4, + }, + PalletMetadata { + name: "Module1_3", + storage: None, + calls: None, + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 6, + }, + PalletMetadata { + name: "Module1_8", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 12, + }, + PalletMetadata { + name: "Module1_9", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 13, + }, PalletMetadata { name: "System", storage: None, @@ -826,69 +889,6 @@ fn test_metadata() { error: Some(meta_type::>().into()), index: 35, }, - PalletMetadata { - name: "Module1_3", - storage: None, - calls: None, - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 6, - }, - PalletMetadata { - name: "Module1_4", - storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 3, - }, - PalletMetadata { - name: "Module1_5", - storage: None, - calls: None, - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 4, - }, - PalletMetadata { - name: "Module1_6", - storage:None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 1, - }, - PalletMetadata { - name: "Module1_7", - storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 2, - }, - PalletMetadata { - name: "Module1_8", - storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 12, - }, - PalletMetadata { - name: "Module1_9", - storage: None, - calls: Some(meta_type::>().into()), - event: Some(meta_type::>().into()), - constants: vec![], - error: Some(meta_type::>().into()), - index: 13, - }, ]; let extrinsic = ExtrinsicMetadata { diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs new file mode 100644 index 000000000000..2d7b20da2ced --- /dev/null +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -0,0 +1,994 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! General tests for construct_runtime macro, test for: +//! * error declared with decl_error works +//! * integrity test is generated + +#![recursion_limit = "128"] + +pub use codec::MaxEncodedLen; +pub use frame_support::{ + derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, +}; +pub use frame_system::limits::{BlockLength, BlockWeights}; +pub use scale_info::TypeInfo; +pub use sp_core::{sr25519, ConstU64}; +pub use sp_runtime::{ + generic, + traits::{BlakeTwo256, ValidateUnsigned, Verify}, + DispatchError, ModuleError, +}; +pub use sp_version::RuntimeVersion; + +parameter_types! { + pub static IntegrityTestExec: u32 = 0; +} + +#[frame_support::pallet(dev_mode)] +mod module1 { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } + + #[pallet::call] + impl, I: 'static> Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + } + + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + #[scale_info(skip_type_params(I))] + pub struct Origin(pub PhantomData<(T, I)>); + + #[pallet::event] + pub enum Event, I: 'static = ()> { + A(::AccountId), + } + + #[pallet::error] + pub enum Error { + Something, + } +} + +#[frame_support::pallet(dev_mode)] +mod module2 { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn integrity_test() { + IntegrityTestExec::mutate(|i| *i += 1); + } + } + + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + } + + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin; + + #[pallet::event] + pub enum Event { + A, + } + + #[pallet::error] + pub enum Error { + Something, + } +} + +mod nested { + use super::*; + + #[frame_support::pallet(dev_mode)] + pub mod module3 { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn integrity_test() { + IntegrityTestExec::mutate(|i| *i += 1); + } + } + + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + } + + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin; + + #[pallet::event] + pub enum Event { + A, + } + + #[pallet::error] + pub enum Error { + Something, + } + + #[pallet::genesis_config] + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } + + #[pallet::genesis_build] + impl BuildGenesisConfig for GenesisConfig { + fn build(&self) {} + } + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + fn validate_unsigned( + _source: TransactionSource, + _call: &Self::Call, + ) -> TransactionValidity { + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + } + } + } +} + +#[frame_support::pallet(dev_mode)] +pub mod module3 { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + } + + #[pallet::call] + impl Pallet { + pub fn fail(_origin: OriginFor) -> DispatchResult { + Err(Error::::Something.into()) + } + pub fn aux_1(_origin: OriginFor, #[pallet::compact] _data: u32) -> DispatchResult { + unreachable!() + } + pub fn aux_2( + _origin: OriginFor, + _data: i32, + #[pallet::compact] _data2: u32, + ) -> DispatchResult { + unreachable!() + } + #[pallet::weight(0)] + pub fn aux_3(_origin: OriginFor, _data: i32, _data2: String) -> DispatchResult { + unreachable!() + } + #[pallet::weight(3)] + pub fn aux_4(_origin: OriginFor) -> DispatchResult { + unreachable!() + } + #[pallet::weight((5, DispatchClass::Operational))] + pub fn operational(_origin: OriginFor) -> DispatchResult { + unreachable!() + } + } + + #[pallet::origin] + #[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)] + pub struct Origin(pub PhantomData); + + #[pallet::event] + pub enum Event { + A, + } + + #[pallet::error] + pub enum Error { + Something, + } + + #[pallet::genesis_config] + #[derive(frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + pub _config: sp_std::marker::PhantomData, + } + + #[pallet::genesis_build] + impl BuildGenesisConfig for GenesisConfig { + fn build(&self) {} + } + + #[pallet::storage] + pub type Storage = StorageValue<_, u32>; + + #[pallet::validate_unsigned] + impl ValidateUnsigned for Pallet { + type Call = Call; + fn validate_unsigned( + _source: TransactionSource, + _call: &Self::Call, + ) -> TransactionValidity { + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + } + } +} + +pub type BlockNumber = u64; +pub type Signature = sr25519::Signature; +pub type AccountId = ::Signer; +pub type Header = generic::Header; +pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; +pub type Block = generic::Block; + + +#[frame_support::runtime(legacy_ordering)] +mod runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask, + )] + pub struct Runtime; + + #[runtime::pallet_index(30)] + pub type System = frame_system + Pallet + Call + Event + Origin; + + #[runtime::pallet_index(31)] + pub type Module1_1 = module1; + + #[runtime::pallet_index(32)] + pub type Module2 = module2; + + #[runtime::pallet_index(33)] + pub type Module1_2 = module1; + + #[runtime::pallet_index(34)] + pub type NestedModule3 = nested::module3; + + #[runtime::pallet_index(35)] + #[runtime::disable_unsigned] + pub type Module3 = self::module3; + + #[runtime::pallet_index(6)] + #[runtime::disable_call] + pub type Module1_3 = module1; + + #[runtime::pallet_index(3)] + pub type Module1_4 = module1; + + #[runtime::pallet_index(4)] + #[runtime::disable_call] + pub type Module1_5 = module1; + + #[runtime::pallet_index(1)] + pub type Module1_6 = module1; + + #[runtime::pallet_index(2)] + pub type Module1_7 = module1; + + #[runtime::pallet_index(12)] + pub type Module1_8 = module1; + + #[runtime::pallet_index(13)] + pub type Module1_9 = module1; +} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type AccountId = AccountId; + type Lookup = sp_runtime::traits::IdentityLookup; + type BaseCallFilter = frame_support::traits::Everything; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type PalletInfo = PalletInfo; + type OnSetCode = (); + type Block = Block; + type BlockHashCount = ConstU64<10>; +} + +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module1::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module2::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl nested::module3::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} +impl module3::Config for Runtime { + type RuntimeEvent = RuntimeEvent; +} + +fn test_pub() -> AccountId { + AccountId::from_raw([0; 32]) +} + +#[test] +fn check_modules_error_type() { + sp_io::TestExternalities::default().execute_with(|| { + assert_eq!( + Module1_1::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 31, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module2::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 32, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_2::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 33, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + NestedModule3::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 34, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_3::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 6, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_4::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 3, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_5::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 4, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_6::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 1, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_7::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 2, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_8::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 12, + error: [0; 4], + message: Some("Something") + })), + ); + assert_eq!( + Module1_9::fail(frame_system::Origin::::Root.into()), + Err(DispatchError::Module(ModuleError { + index: 13, + error: [0; 4], + message: Some("Something") + })), + ); + }) +} + +#[test] +fn integrity_test_works() { + __construct_runtime_integrity_test::runtime_integrity_tests(); + assert_eq!(IntegrityTestExec::get(), 2); +} + +#[test] +fn origin_codec() { + use codec::Encode; + + let origin = OriginCaller::system(frame_system::RawOrigin::None); + assert_eq!(origin.encode()[0], 30); + + let origin = OriginCaller::Module1_1(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 31); + + let origin = OriginCaller::Module2(module2::Origin); + assert_eq!(origin.encode()[0], 32); + + let origin = OriginCaller::Module1_2(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 33); + + let origin = OriginCaller::NestedModule3(nested::module3::Origin); + assert_eq!(origin.encode()[0], 34); + + let origin = OriginCaller::Module3(module3::Origin(Default::default())); + assert_eq!(origin.encode()[0], 35); + + let origin = OriginCaller::Module1_6(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 1); + + let origin = OriginCaller::Module1_7(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 2); + + let origin = OriginCaller::Module1_8(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 12); + + let origin = OriginCaller::Module1_9(module1::Origin(Default::default())); + assert_eq!(origin.encode()[0], 13); +} + +#[test] +fn event_codec() { + use codec::Encode; + + let event = + frame_system::Event::::ExtrinsicSuccess { dispatch_info: Default::default() }; + assert_eq!(RuntimeEvent::from(event).encode()[0], 30); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 31); + + let event = module2::Event::A; + assert_eq!(RuntimeEvent::from(event).encode()[0], 32); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 33); + + let event = nested::module3::Event::A; + assert_eq!(RuntimeEvent::from(event).encode()[0], 34); + + let event = module3::Event::A; + assert_eq!(RuntimeEvent::from(event).encode()[0], 35); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 4); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 1); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 2); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 12); + + let event = module1::Event::::A(test_pub()); + assert_eq!(RuntimeEvent::from(event).encode()[0], 13); +} + +#[test] +fn call_codec() { + use codec::Encode; + assert_eq!(RuntimeCall::System(frame_system::Call::remark { remark: vec![1] }).encode()[0], 30); + assert_eq!(RuntimeCall::Module1_1(module1::Call::fail {}).encode()[0], 31); + assert_eq!(RuntimeCall::Module2(module2::Call::fail {}).encode()[0], 32); + assert_eq!(RuntimeCall::Module1_2(module1::Call::fail {}).encode()[0], 33); + assert_eq!(RuntimeCall::NestedModule3(nested::module3::Call::fail {}).encode()[0], 34); + assert_eq!(RuntimeCall::Module3(module3::Call::fail {}).encode()[0], 35); + assert_eq!(RuntimeCall::Module1_4(module1::Call::fail {}).encode()[0], 3); + assert_eq!(RuntimeCall::Module1_6(module1::Call::fail {}).encode()[0], 1); + assert_eq!(RuntimeCall::Module1_7(module1::Call::fail {}).encode()[0], 2); + assert_eq!(RuntimeCall::Module1_8(module1::Call::fail {}).encode()[0], 12); + assert_eq!(RuntimeCall::Module1_9(module1::Call::fail {}).encode()[0], 13); +} + +#[test] +fn call_compact_attr() { + use codec::Encode; + let call: module3::Call = module3::Call::aux_1 { data: 1 }; + let encoded = call.encode(); + assert_eq!(2, encoded.len()); + assert_eq!(vec![1, 4], encoded); + + let call: module3::Call = module3::Call::aux_2 { data: 1, data2: 2 }; + let encoded = call.encode(); + assert_eq!(6, encoded.len()); + assert_eq!(vec![2, 1, 0, 0, 0, 8], encoded); +} + +#[test] +fn call_encode_is_correct_and_decode_works() { + use codec::{Decode, Encode}; + let call: module3::Call = module3::Call::fail {}; + let encoded = call.encode(); + assert_eq!(vec![0], encoded); + let decoded = module3::Call::::decode(&mut &encoded[..]).unwrap(); + assert_eq!(decoded, call); + + let call: module3::Call = module3::Call::aux_3 { data: 32, data2: "hello".into() }; + let encoded = call.encode(); + assert_eq!(vec![3, 32, 0, 0, 0, 20, 104, 101, 108, 108, 111], encoded); + let decoded = module3::Call::::decode(&mut &encoded[..]).unwrap(); + assert_eq!(decoded, call); +} + +#[test] +fn call_weight_should_attach_to_call_enum() { + use frame_support::{ + dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, + weights::Weight, + }; + // operational. + assert_eq!( + module3::Call::::operational {}.get_dispatch_info(), + DispatchInfo { + weight: Weight::from_parts(5, 0), + class: DispatchClass::Operational, + pays_fee: Pays::Yes + }, + ); + // custom basic + assert_eq!( + module3::Call::::aux_4 {}.get_dispatch_info(), + DispatchInfo { + weight: Weight::from_parts(3, 0), + class: DispatchClass::Normal, + pays_fee: Pays::Yes + }, + ); +} + +#[test] +fn call_name() { + use frame_support::traits::GetCallName; + let name = module3::Call::::aux_4 {}.get_call_name(); + assert_eq!("aux_4", name); +} + +#[test] +fn call_metadata() { + use frame_support::traits::{CallMetadata, GetCallMetadata}; + let call = RuntimeCall::Module3(module3::Call::::aux_4 {}); + let metadata = call.get_call_metadata(); + let expected = CallMetadata { function_name: "aux_4".into(), pallet_name: "Module3".into() }; + assert_eq!(metadata, expected); +} + +#[test] +fn get_call_names() { + use frame_support::traits::GetCallName; + let call_names = module3::Call::::get_call_names(); + assert_eq!(["fail", "aux_1", "aux_2", "aux_3", "aux_4", "operational"], call_names); +} + +#[test] +fn get_module_names() { + use frame_support::traits::GetCallMetadata; + let module_names = RuntimeCall::get_module_names(); + assert_eq!( + [ + "System", + "Module1_1", + "Module2", + "Module1_2", + "NestedModule3", + "Module3", + "Module1_4", + "Module1_6", + "Module1_7", + "Module1_8", + "Module1_9", + ], + module_names + ); +} + +#[test] +fn call_subtype_conversion() { + use frame_support::{dispatch::CallableCallFor, traits::IsSubType}; + let call = RuntimeCall::Module3(module3::Call::::fail {}); + let subcall: Option<&CallableCallFor> = call.is_sub_type(); + let subcall_none: Option<&CallableCallFor> = call.is_sub_type(); + assert_eq!(Some(&module3::Call::::fail {}), subcall); + assert_eq!(None, subcall_none); + + let from = RuntimeCall::from(subcall.unwrap().clone()); + assert_eq!(from, call); +} + +#[test] +fn test_metadata() { + use frame_metadata::{ + v14::{StorageEntryType::Plain, *}, + *, + }; + use scale_info::meta_type; + use sp_core::Encode; + use sp_metadata_ir::StorageEntryModifierIR::Optional; + + fn maybe_docs(doc: Vec<&'static str>) -> Vec<&'static str> { + if cfg!(feature = "no-metadata-docs") { + vec![] + } else { + doc + } + } + + let pallets = vec![ + PalletMetadata { + name: "System", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![ + PalletConstantMetadata { + name: "BlockWeights", + ty: meta_type::(), + value: BlockWeights::default().encode(), + docs: maybe_docs(vec![" Block & extrinsics weights: base values and limits."]), + }, + PalletConstantMetadata { + name: "BlockLength", + ty: meta_type::(), + value: BlockLength::default().encode(), + docs: maybe_docs(vec![" The maximum length of a block (in bytes)."]), + }, + PalletConstantMetadata { + name: "BlockHashCount", + ty: meta_type::(), + value: 10u64.encode(), + docs: maybe_docs(vec![" Maximum number of block number to block hash mappings to keep (oldest pruned first)."]), + }, + PalletConstantMetadata { + name: "DbWeight", + ty: meta_type::(), + value: RuntimeDbWeight::default().encode(), + docs: maybe_docs(vec![" The weight of runtime database operations the runtime can invoke.",]), + }, + PalletConstantMetadata { + name: "Version", + ty: meta_type::(), + value: RuntimeVersion::default().encode(), + docs: maybe_docs(vec![ " Get the chain's current version."]), + }, + PalletConstantMetadata { + name: "SS58Prefix", + ty: meta_type::(), + value: 0u16.encode(), + docs: maybe_docs(vec![ + " The designated SS58 prefix of this chain.", + "", + " This replaces the \"ss58Format\" property declared in the chain spec. Reason is", + " that the runtime should know about the prefix in order to make use of it as", + " an identifier of the chain.", + ]), + }, + ], + error: Some(meta_type::>().into()), + index: 30, + }, + PalletMetadata { + name: "Module1_1", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 31, + }, + PalletMetadata { + name: "Module2", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 32, + }, + PalletMetadata { + name: "Module1_2", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 33, + }, + PalletMetadata { + name: "NestedModule3", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 34, + }, + PalletMetadata { + name: "Module3", + storage: Some(PalletStorageMetadata { + prefix: "Module3", + entries: vec![ + StorageEntryMetadata { + name: "Storage", + modifier: Optional.into(), + ty: Plain(meta_type::().into()), + default: vec![0], + docs: vec![], + }, + ] + }), + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 35, + }, + PalletMetadata { + name: "Module1_3", + storage: None, + calls: None, + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 6, + }, + PalletMetadata { + name: "Module1_4", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 3, + }, + PalletMetadata { + name: "Module1_5", + storage: None, + calls: None, + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 4, + }, + PalletMetadata { + name: "Module1_6", + storage:None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 1, + }, + PalletMetadata { + name: "Module1_7", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 2, + }, + PalletMetadata { + name: "Module1_8", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 12, + }, + PalletMetadata { + name: "Module1_9", + storage: None, + calls: Some(meta_type::>().into()), + event: Some(meta_type::>().into()), + constants: vec![], + error: Some(meta_type::>().into()), + index: 13, + }, + ]; + + let extrinsic = ExtrinsicMetadata { + ty: meta_type::(), + version: 4, + signed_extensions: vec![SignedExtensionMetadata { + identifier: "UnitSignedExtension", + ty: meta_type::<()>(), + additional_signed: meta_type::<()>(), + }], + }; + + let expected_metadata: RuntimeMetadataPrefixed = + RuntimeMetadataLastVersion::new(pallets, extrinsic, meta_type::()).into(); + let actual_metadata = Runtime::metadata(); + + pretty_assertions::assert_eq!(actual_metadata, expected_metadata); +} + +#[test] +fn pallet_in_runtime_is_correct() { + assert_eq!(PalletInfo::index::().unwrap(), 30); + assert_eq!(PalletInfo::name::().unwrap(), "System"); + assert_eq!(PalletInfo::module_name::().unwrap(), "frame_system"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 31); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_1"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 32); + assert_eq!(PalletInfo::name::().unwrap(), "Module2"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module2"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 33); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_2"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 34); + assert_eq!(PalletInfo::name::().unwrap(), "NestedModule3"); + assert_eq!(PalletInfo::module_name::().unwrap(), "nested::module3"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 35); + assert_eq!(PalletInfo::name::().unwrap(), "Module3"); + assert_eq!(PalletInfo::module_name::().unwrap(), "self::module3"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 6); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_3"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 3); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_4"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 4); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_5"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 1); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_6"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 2); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_7"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 12); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_8"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); + + assert_eq!(PalletInfo::index::().unwrap(), 13); + assert_eq!(PalletInfo::name::().unwrap(), "Module1_9"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); + assert!(PalletInfo::crate_version::().is_some()); +} + +#[test] +fn test_validate_unsigned() { + use frame_support::pallet_prelude::*; + + let call = RuntimeCall::NestedModule3(nested::module3::Call::fail {}); + let validity = Runtime::validate_unsigned(TransactionSource::Local, &call).unwrap_err(); + assert_eq!(validity, TransactionValidityError::Invalid(InvalidTransaction::Call)); + + let call = RuntimeCall::Module3(module3::Call::fail {}); + let validity = Runtime::validate_unsigned(TransactionSource::Local, &call).unwrap_err(); + assert_eq!( + validity, + TransactionValidityError::Unknown(UnknownTransaction::NoUnsignedValidator) + ); +} From a8fd2282480ce124eb4a5a88183698a0d38a9496 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 13 Feb 2024 10:44:51 +0530 Subject: [PATCH 37/48] Updates docs --- substrate/frame/support/procedural/src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 30377104542b..e6205cd50312 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1734,6 +1734,12 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// pub type Test4 = test4; /// } /// ``` +/// +/// # Legacy Ordering +/// +/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to +/// ensure that the order of hooks is same as the order of pallets (and not based on the +/// pallet_index). This is to support legacy runtimes and should be avoided for new ones. /// /// # Note /// From 2f8b62cae7ef43a14468563c2c17ae28024f12c6 Mon Sep 17 00:00:00 2001 From: command-bot <> Date: Tue, 13 Feb 2024 05:17:02 +0000 Subject: [PATCH 38/48] ".git/.scripts/commands/fmt/fmt.sh" --- substrate/bin/node-template/runtime/src/lib.rs | 2 +- substrate/bin/node/runtime/src/lib.rs | 2 +- substrate/frame/support/procedural/src/lib.rs | 10 +++++----- .../support/procedural/src/runtime/expand/mod.rs | 11 ++++------- .../support/procedural/src/runtime/parse/mod.rs | 13 +++++++++---- substrate/frame/support/test/tests/runtime.rs | 2 +- .../support/test/tests/runtime_legacy_ordering.rs | 3 +-- 7 files changed, 22 insertions(+), 21 deletions(-) diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index c0b05e1240ba..f8b1f3dc463d 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -268,7 +268,7 @@ mod runtime { RuntimeHoldReason, RuntimeSlashReason, RuntimeLockId, - RuntimeTask, + RuntimeTask )] pub struct Runtime; diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 30a553f898ad..4740b0e3cc30 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -2174,7 +2174,7 @@ mod runtime { RuntimeHoldReason, RuntimeSlashReason, RuntimeLockId, - RuntimeTask, + RuntimeTask )] pub struct Runtime; diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index e6205cd50312..b876086b0321 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1709,7 +1709,7 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// RuntimeHoldReason, /// RuntimeSlashReason, /// RuntimeLockId, -/// RuntimeTask, +/// RuntimeTask, /// )] /// pub struct Runtime; /// @@ -1734,11 +1734,11 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// pub type Test4 = test4; /// } /// ``` -/// +/// /// # Legacy Ordering -/// -/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to -/// ensure that the order of hooks is same as the order of pallets (and not based on the +/// +/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to +/// ensure that the order of hooks is same as the order of pallets (and not based on the /// pallet_index). This is to support legacy runtimes and should be avoided for new ones. /// /// # Note diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index 56751b60f42d..8151baa70c4a 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -45,8 +45,9 @@ pub fn expand(def: Def, legacy_ordering: bool) -> TokenStream2 { let res = match def.pallets { AllPalletsDeclaration::Implicit(ref decl) => - check_pallet_number(input.clone(), decl.pallet_count) - .and_then(|_| construct_runtime_implicit_to_explicit(input.into(), decl.clone(), legacy_ordering)), + check_pallet_number(input.clone(), decl.pallet_count).and_then(|_| { + construct_runtime_implicit_to_explicit(input.into(), decl.clone(), legacy_ordering) + }), AllPalletsDeclaration::Explicit(ref decl) => check_pallet_number(input, decl.pallets.len()) .and_then(|_| { construct_runtime_final_expansion( @@ -75,11 +76,7 @@ fn construct_runtime_implicit_to_explicit( legacy_ordering: bool, ) -> Result { let frame_support = generate_access_from_frame_or_crate("frame-support")?; - let attr = if legacy_ordering { - quote!((legacy_ordering)) - } else { - quote!() - }; + let attr = if legacy_ordering { quote!((legacy_ordering)) } else { quote!() }; let mut expansion = quote::quote!( #[frame_support::runtime #attr] #input diff --git a/substrate/frame/support/procedural/src/runtime/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs index 65ab546206d2..4bfb8eecb9ad 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/mod.rs @@ -206,11 +206,16 @@ impl Def { pallet_decls.push(pallet_decl); }, syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) => { - let pallet = - Pallet::try_from(item.span(), &pallet_item, pallet_index, disable_call, disable_unsigned, &bounds)?; + let pallet = Pallet::try_from( + item.span(), + &pallet_item, + pallet_index, + disable_call, + disable_unsigned, + &bounds, + )?; - if let Some(used_pallet) = - indices.insert(pallet.index, pallet.name.clone()) + if let Some(used_pallet) = indices.insert(pallet.index, pallet.name.clone()) { let msg = format!( "Pallet indices are conflicting: Both pallets {} and {} are at index {}", diff --git a/substrate/frame/support/test/tests/runtime.rs b/substrate/frame/support/test/tests/runtime.rs index e2ca125ff51a..aebf4782dc5b 100644 --- a/substrate/frame/support/test/tests/runtime.rs +++ b/substrate/frame/support/test/tests/runtime.rs @@ -293,7 +293,7 @@ mod runtime { RuntimeHoldReason, RuntimeSlashReason, RuntimeLockId, - RuntimeTask, + RuntimeTask )] pub struct Runtime; diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs index 2d7b20da2ced..188692001e7d 100644 --- a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -281,7 +281,6 @@ pub type Header = generic::Header; pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; pub type Block = generic::Block; - #[frame_support::runtime(legacy_ordering)] mod runtime { #[runtime::runtime] @@ -294,7 +293,7 @@ mod runtime { RuntimeHoldReason, RuntimeSlashReason, RuntimeLockId, - RuntimeTask, + RuntimeTask )] pub struct Runtime; From c779b744e07e8d3722a21c484b5292d18d4080c4 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 13 Feb 2024 10:52:57 +0530 Subject: [PATCH 39/48] Adds PrDoc --- prdoc/pr_1378.prdoc | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 prdoc/pr_1378.prdoc diff --git a/prdoc/pr_1378.prdoc b/prdoc/pr_1378.prdoc new file mode 100644 index 000000000000..ccbdeb2f00c9 --- /dev/null +++ b/prdoc/pr_1378.prdoc @@ -0,0 +1,27 @@ +title: Construct Runtime V2 - An outer macro approach to define the runtime + +doc: + - audience: Runtime Dev + description: | + Introduces `#[frame_support::runtime]` that can be attached to a mod to define a runtime. The items + in this mod can be attached to the following attributes to define the key components of the runtime. + 1. `#[runtime::runtime]` attached to a struct defines the main runtime + 2. `#[runtime::derive]` attached to this struct defines the types generated by the runtime + 3. `#[runtime::pallet_index]` must be attached to a pallet to define its index + 4. `#[runtime::disable_call]` can be optionally attached to a pallet to disable its calls + 5. `#[runtime::disable_unsigned]` can be optionally attached to a pallet to disable unsigned calls + 6. A pallet instance can be defined as `TemplateModule: pallet_template` + An optional attribute can be defined as `#[frame_support::runtime(legacy_ordering)]` to ensure that + the order of hooks is same as the order of pallets (and not based on the pallet_index). This is to support + legacy runtimes and should be avoided for new ones. + +migrations: + db: [] + + runtime: [] + +crates: + - name: frame-support + - name: frame-support-procedural + +host_functions: [] From 1aac057cf4d3bb8db4e4f035174ff4086e1d22bb Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 13 Feb 2024 10:56:06 +0530 Subject: [PATCH 40/48] Minor fix --- substrate/frame/support/test/tests/runtime.rs | 14 +++++++------- .../support/test/tests/runtime_legacy_ordering.rs | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/substrate/frame/support/test/tests/runtime.rs b/substrate/frame/support/test/tests/runtime.rs index aebf4782dc5b..4365702e7243 100644 --- a/substrate/frame/support/test/tests/runtime.rs +++ b/substrate/frame/support/test/tests/runtime.rs @@ -21,19 +21,19 @@ #![recursion_limit = "128"] -pub use codec::MaxEncodedLen; -pub use frame_support::{ +use codec::MaxEncodedLen; +use frame_support::{ derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, }; -pub use frame_system::limits::{BlockLength, BlockWeights}; -pub use scale_info::TypeInfo; -pub use sp_core::{sr25519, ConstU64}; -pub use sp_runtime::{ +use frame_system::limits::{BlockLength, BlockWeights}; +use scale_info::TypeInfo; +use sp_core::{sr25519, ConstU64}; +use sp_runtime::{ generic, traits::{BlakeTwo256, ValidateUnsigned, Verify}, DispatchError, ModuleError, }; -pub use sp_version::RuntimeVersion; +use sp_version::RuntimeVersion; parameter_types! { pub static IntegrityTestExec: u32 = 0; diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs index 188692001e7d..3c2e75cf25de 100644 --- a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -21,19 +21,19 @@ #![recursion_limit = "128"] -pub use codec::MaxEncodedLen; -pub use frame_support::{ +use codec::MaxEncodedLen; +use frame_support::{ derive_impl, parameter_types, traits::PalletInfo as _, weights::RuntimeDbWeight, }; -pub use frame_system::limits::{BlockLength, BlockWeights}; -pub use scale_info::TypeInfo; -pub use sp_core::{sr25519, ConstU64}; -pub use sp_runtime::{ +use frame_system::limits::{BlockLength, BlockWeights}; +use scale_info::TypeInfo; +use sp_core::{sr25519, ConstU64}; +use sp_runtime::{ generic, traits::{BlakeTwo256, ValidateUnsigned, Verify}, DispatchError, ModuleError, }; -pub use sp_version::RuntimeVersion; +use sp_version::RuntimeVersion; parameter_types! { pub static IntegrityTestExec: u32 = 0; From d150a5bcd3f969c9f4c89933a45aca8253c6301f Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 14 Feb 2024 10:16:56 +0530 Subject: [PATCH 41/48] Updates docs --- .../support/procedural/src/runtime/mod.rs | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index e24bca1b4abe..1d4242cd122e 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -21,8 +21,8 @@ //! in order to get all the pallet parts for each pallet. //! //! Pallets can define their parts: -//! - Implicitly: `System: frame_system` -//! - Explicitly: `System: frame_system + Pallet + Call` +//! - Implicitly: `pub type System = frame_system;` +//! - Explicitly: `pub type System = frame_system + Pallet + Call;` //! //! The `runtime` transitions from the implicit definition to the explicit one. //! From the explicit state, Substrate expands the pallets with additional information @@ -106,11 +106,11 @@ //! pub type Balances = pallet_balances; //! } //! }] -//! pattern = [{ System: frame_system }] +//! pattern = [{ System = frame_system }] //! } //! } //! }] -//! pattern = [{ Balances: pallet_balances }] +//! pattern = [{ Balances = pallet_balances }] //! } //! } //! ``` @@ -133,12 +133,12 @@ //! pub type Balances = pallet_balances; //! } //! }] -//! pattern = [{ System: frame_system }] -//! tokens = [{ ::{Pallet, Call} }] +//! pattern = [{ System = frame_system }] +//! tokens = [{ ::{+ Pallet + Call} }] //! } //! }] -//! pattern = [{ Balances: pallet_balances }] -//! tokens = [{ ::{Pallet, Call} }] +//! pattern = [{ Balances = pallet_balances }] +//! tokens = [{ ::{+ Pallet + Call} }] //! } //! ``` //! After dealing with `pallet_balances`, the inner `match_and_insert` will expand to: @@ -156,8 +156,8 @@ //! pub type Balances = pallet_balances + Pallet + Call; // Explicit definition of parts //! } //! }] -//! pattern = [{ System: frame_system }] -//! tokens = [{ ::{Pallet, Call} }] +//! pattern = [{ System = frame_system }] +//! tokens = [{ ::{+ Pallet + Call} }] //! } //! ``` //! @@ -184,18 +184,18 @@ //! ... //! ``` //! -//! Visualizing the entire flow of `construct_runtime!`, it would look like the following: +//! Visualizing the entire flow of `#[frame_support::runtime]`, it would look like the following: //! //! ```ignore -//! +----------------------+ +---------------------+ +-------------------+ -//! | | | (defined in pallet) | | | -//! | runtime | --> | tt_default_parts! | --> | match_and_insert! | -//! | w/ no pallet parts | | | | | -//! +----------------------+ +---------------------+ +-------------------+ +//! +----------------------+ +------------------------+ +-------------------+ +//! | | | (defined in pallet) | | | +//! | runtime | --> | tt_default_parts_v2! | --> | match_and_insert! | +//! | w/ no pallet parts | | | | | +//! +----------------------+ +------------------------+ +-------------------+ //! //! +----------------------+ //! | | -//! --> | runtime | +//! --> | runtime | //! | w/ pallet parts | //! +----------------------+ //! ``` From 7ad4fc7243fac178d5662ca99a18746ae8508bf0 Mon Sep 17 00:00:00 2001 From: gupnik Date: Wed, 14 Feb 2024 13:54:12 +0100 Subject: [PATCH 42/48] Update prdoc/pr_1378.prdoc Co-authored-by: Francisco Aguirre --- prdoc/pr_1378.prdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prdoc/pr_1378.prdoc b/prdoc/pr_1378.prdoc index ccbdeb2f00c9..6533dcb66303 100644 --- a/prdoc/pr_1378.prdoc +++ b/prdoc/pr_1378.prdoc @@ -6,7 +6,7 @@ doc: Introduces `#[frame_support::runtime]` that can be attached to a mod to define a runtime. The items in this mod can be attached to the following attributes to define the key components of the runtime. 1. `#[runtime::runtime]` attached to a struct defines the main runtime - 2. `#[runtime::derive]` attached to this struct defines the types generated by the runtime + 2. `#[runtime::derive]` attached to the runtime struct defines the types generated by the runtime 3. `#[runtime::pallet_index]` must be attached to a pallet to define its index 4. `#[runtime::disable_call]` can be optionally attached to a pallet to disable its calls 5. `#[runtime::disable_unsigned]` can be optionally attached to a pallet to disable unsigned calls From d22e45bc39b0fe37b3aa350561cdc5c9c1f23eb8 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 19 Feb 2024 16:42:47 +0530 Subject: [PATCH 43/48] Addresses review comments --- .../frame/support/procedural/src/runtime/parse/mod.rs | 8 ++++++-- .../support/test/tests/runtime_ui/missing_runtime.stderr | 2 +- .../tests/runtime_ui/missing_runtime_types_derive.stderr | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs index 4bfb8eecb9ad..23e4c7be4787 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/mod.rs @@ -249,10 +249,14 @@ impl Def { input, item, runtime_struct: runtime_struct - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[runtime::runtime]`"))?, + .ok_or_else(|| syn::Error::new(item_span, + "Missing Runtime. Please add a struct inside the module and annotate it with `#[runtime::runtime]`" + ))?, pallets, runtime_types: runtime_types - .ok_or_else(|| syn::Error::new(item_span, "Missing `#[runtime::derive]`"))?, + .ok_or_else(|| syn::Error::new(item_span, + "Missing Runtime Types. Please annotate the runtime struct with `#[runtime::derive]`" + ))?, }; Ok(def) diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr index 689a3d7e5af1..9790c5dbc1a9 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime.stderr @@ -1,4 +1,4 @@ -error: Missing `#[runtime::runtime]` +error: Missing Runtime. Please add a struct inside the module and annotate it with `#[runtime::runtime]` --> tests/runtime_ui/missing_runtime.rs:19:1 | 19 | mod runtime {} diff --git a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr index f136af36cf8c..1a8deebe5497 100644 --- a/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr +++ b/substrate/frame/support/test/tests/runtime_ui/missing_runtime_types_derive.stderr @@ -1,4 +1,4 @@ -error: Missing `#[runtime::derive]` +error: Missing Runtime Types. Please annotate the runtime struct with `#[runtime::derive]` --> tests/runtime_ui/missing_runtime_types_derive.rs:19:1 | 19 | mod runtime { From 0aeb0f355d8bd18103852e1a58d31a1c94434f13 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 19 Feb 2024 20:50:25 +0530 Subject: [PATCH 44/48] Fmt --- .../support/procedural/src/runtime/parse/mod.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs index 23e4c7be4787..893cb4726e2b 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/mod.rs @@ -248,15 +248,17 @@ impl Def { let def = Def { input, item, - runtime_struct: runtime_struct - .ok_or_else(|| syn::Error::new(item_span, + runtime_struct: runtime_struct.ok_or_else(|| { + syn::Error::new(item_span, "Missing Runtime. Please add a struct inside the module and annotate it with `#[runtime::runtime]`" - ))?, + ) + })?, pallets, - runtime_types: runtime_types - .ok_or_else(|| syn::Error::new(item_span, + runtime_types: runtime_types.ok_or_else(|| { + syn::Error::new(item_span, "Missing Runtime Types. Please annotate the runtime struct with `#[runtime::derive]`" - ))?, + ) + })?, }; Ok(def) From 761cedbe33bff7944e160d6401765c3f3a428b93 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Tue, 27 Feb 2024 16:53:33 +0530 Subject: [PATCH 45/48] Incorporates changes for improved error reporting --- .../procedural/src/runtime/expand/mod.rs | 43 +++++++++++++------ 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index 8151baa70c4a..93c88fce94b7 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -43,24 +43,39 @@ const SYSTEM_PALLET_NAME: &str = "System"; pub fn expand(def: Def, legacy_ordering: bool) -> TokenStream2 { let input = def.input; - let res = match def.pallets { - AllPalletsDeclaration::Implicit(ref decl) => - check_pallet_number(input.clone(), decl.pallet_count).and_then(|_| { - construct_runtime_implicit_to_explicit(input.into(), decl.clone(), legacy_ordering) - }), - AllPalletsDeclaration::Explicit(ref decl) => check_pallet_number(input, decl.pallets.len()) - .and_then(|_| { - construct_runtime_final_expansion( - def.runtime_struct.ident.clone(), - decl.clone(), - def.runtime_types.clone(), - legacy_ordering, - ) - }), + let (check_pallet_number_res, res) = match def.pallets { + AllPalletsDeclaration::Implicit(ref decl) => ( + check_pallet_number(input.clone(), decl.pallet_count), + construct_runtime_implicit_to_explicit(input.into(), decl.clone(), legacy_ordering), + ), + AllPalletsDeclaration::Explicit(ref decl) => ( + check_pallet_number(input, decl.pallets.len()), + construct_runtime_final_expansion( + def.runtime_struct.ident.clone(), + decl.clone(), + def.runtime_types.clone(), + legacy_ordering, + ), + ), }; let res = res.unwrap_or_else(|e| e.to_compile_error()); + // We want to provide better error messages to the user and thus, handle the error here + // separately. If there is an error, we print the error and still generate all of the code to + // get in overall less errors for the user. + let res = if let Err(error) = check_pallet_number_res { + let error = error.to_compile_error(); + + quote! { + #error + + #res + } + } else { + res + }; + let res = expander::Expander::new("construct_runtime") .dry(std::env::var("FRAME_EXPAND").is_err()) .verbose(true) From 97a4425510a1d01e279c9640dca7bc51a4a407ba Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Mon, 11 Mar 2024 14:01:19 +0530 Subject: [PATCH 46/48] Minor fix --- substrate/frame/support/test/tests/runtime_legacy_ordering.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs index 3c2e75cf25de..38875517018c 100644 --- a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -895,7 +895,7 @@ fn test_metadata() { ty: meta_type::(), version: 4, signed_extensions: vec![SignedExtensionMetadata { - identifier: "UnitSignedExtension", + identifier: "UnitTransactionExtension", ty: meta_type::<()>(), additional_signed: meta_type::<()>(), }], From 29c2259bda0f43bcfd424e348c803bd6b19bf556 Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Mar 2024 11:46:33 +0530 Subject: [PATCH 47/48] Feature gates under experimental --- substrate/bin/node/runtime/Cargo.toml | 2 +- substrate/frame/support/Cargo.toml | 4 +++- substrate/frame/support/procedural/Cargo.toml | 1 + substrate/frame/support/procedural/src/lib.rs | 1 + substrate/frame/support/src/lib.rs | 5 ++++- substrate/frame/support/test/Cargo.toml | 2 +- templates/solochain/runtime/Cargo.toml | 2 +- 7 files changed, 12 insertions(+), 5 deletions(-) diff --git a/substrate/bin/node/runtime/Cargo.toml b/substrate/bin/node/runtime/Cargo.toml index bdef42474d09..09c8fb4ed3d4 100644 --- a/substrate/bin/node/runtime/Cargo.toml +++ b/substrate/bin/node/runtime/Cargo.toml @@ -58,7 +58,7 @@ sp-io = { path = "../../../primitives/io", default-features = false } frame-executive = { path = "../../../frame/executive", default-features = false } frame-benchmarking = { path = "../../../frame/benchmarking", default-features = false } frame-benchmarking-pallet-pov = { path = "../../../frame/benchmarking/pov", default-features = false } -frame-support = { path = "../../../frame/support", default-features = false, features = ["tuples-96"] } +frame-support = { path = "../../../frame/support", default-features = false, features = ["experimental", "tuples-96"] } frame-system = { path = "../../../frame/system", default-features = false } frame-system-benchmarking = { path = "../../../frame/system/benchmarking", default-features = false, optional = true } frame-election-provider-support = { path = "../../../frame/election-provider-support", default-features = false } diff --git a/substrate/frame/support/Cargo.toml b/substrate/frame/support/Cargo.toml index 113af41751ed..be60068f1220 100644 --- a/substrate/frame/support/Cargo.toml +++ b/substrate/frame/support/Cargo.toml @@ -109,7 +109,9 @@ try-runtime = [ "sp-debug-derive/force-debug", "sp-runtime/try-runtime", ] -experimental = [] +experimental = [ + "frame-support-procedural/experimental", +] # By default some types have documentation, `no-metadata-docs` allows to reduce the documentation # in the metadata. no-metadata-docs = [ diff --git a/substrate/frame/support/procedural/Cargo.toml b/substrate/frame/support/procedural/Cargo.toml index 859475038020..dd0688f2ad06 100644 --- a/substrate/frame/support/procedural/Cargo.toml +++ b/substrate/frame/support/procedural/Cargo.toml @@ -38,6 +38,7 @@ regex = "1" default = ["std"] std = ["sp-crypto-hashing/std"] no-metadata-docs = [] +experimental = [] # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of # pallets in a runtime grows. Does increase the compile time! tuples-96 = [] diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index 725dab9dc842..d09b9b31b614 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -1292,6 +1292,7 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { /// /// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System = /// frame_system::Pallet` +#[cfg(feature = "experimental")] #[proc_macro_attribute] pub fn runtime(attr: TokenStream, item: TokenStream) -> TokenStream { runtime::runtime(attr, item) diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 7b709905b2c5..0b2d89e12565 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -507,9 +507,12 @@ pub fn debug(data: &impl sp_std::fmt::Debug) { #[doc(inline)] pub use frame_support_procedural::{ - construct_runtime, match_and_insert, runtime, transactional, PalletError, RuntimeDebugNoBound, + construct_runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, }; +#[cfg(feature = "experimental")] +pub use frame_support_procedural::runtime; + #[doc(hidden)] pub use frame_support_procedural::{__create_tt_macro, __generate_dummy_part_checker}; diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index ae2c56a531fd..2f12cc00ed9e 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -24,7 +24,7 @@ sp-api = { path = "../../../primitives/api", default-features = false } sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false } sp-io = { path = "../../../primitives/io", default-features = false } sp-state-machine = { path = "../../../primitives/state-machine", optional = true } -frame-support = { path = "..", default-features = false } +frame-support = { path = "..", default-features = false, features = ["experimental"] } frame-benchmarking = { path = "../../benchmarking", default-features = false } sp-runtime = { path = "../../../primitives/runtime", default-features = false } sp-core = { path = "../../../primitives/core", default-features = false } diff --git a/templates/solochain/runtime/Cargo.toml b/templates/solochain/runtime/Cargo.toml index 4f22e7ff6a3b..706ea863d0f1 100644 --- a/templates/solochain/runtime/Cargo.toml +++ b/templates/solochain/runtime/Cargo.toml @@ -25,7 +25,7 @@ scale-info = { version = "2.10.0", default-features = false, features = [ ] } # frame -frame-support = { path = "../../../substrate/frame/support", default-features = false } +frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["experimental"] } frame-system = { path = "../../../substrate/frame/system", default-features = false } frame-try-runtime = { path = "../../../substrate/frame/try-runtime", default-features = false, optional = true } frame-executive = { path = "../../../substrate/frame/executive", default-features = false } From d71dbbcf2bd25188ee7f44ecec695c50eb2acc2b Mon Sep 17 00:00:00 2001 From: Nikhil Gupta <17176722+gupnik@users.noreply.github.com> Date: Wed, 13 Mar 2024 11:56:40 +0530 Subject: [PATCH 48/48] Minor fix --- substrate/frame/support/procedural/src/runtime/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/substrate/frame/support/procedural/src/runtime/mod.rs b/substrate/frame/support/procedural/src/runtime/mod.rs index 1d4242cd122e..aaae579eb086 100644 --- a/substrate/frame/support/procedural/src/runtime/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/mod.rs @@ -200,6 +200,8 @@ //! +----------------------+ //! ``` +#![cfg(feature = "experimental")] + pub use parse::Def; use proc_macro::TokenStream; use syn::spanned::Spanned;