From 6490874fd97fe9916d85e1de9363699ec6d3b4c1 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 15:19:09 -0700 Subject: [PATCH 01/18] Record pallet indices in CallMetadata --- .../support/procedural/src/construct_runtime/expand/call.rs | 5 ++++- frame/support/src/traits/metadata.rs | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index f847bc6dbfbdd..1efa171a4aac0 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -29,6 +29,7 @@ pub fn expand_outer_dispatch( let mut variant_patterns = Vec::new(); let mut query_call_part_macros = Vec::new(); let mut pallet_names = Vec::new(); + let mut pallet_indices = Vec::new(); let pallets_with_call = pallet_decls.iter().filter(|decl| decl.exists_part("Call")); @@ -42,6 +43,7 @@ pub fn expand_outer_dispatch( ); variant_patterns.push(quote!(Call::#name(call))); pallet_names.push(name); + pallet_indices.push(index); query_call_part_macros.push(quote! { #path::__substrate_call_check::is_call_part_defined!(#name); }); @@ -74,7 +76,8 @@ pub fn expand_outer_dispatch( #variant_patterns => { let function_name = call.get_call_name(); let pallet_name = stringify!(#pallet_names); - #scrate::dispatch::CallMetadata { function_name, pallet_name } + let index = #pallet_indices; + #scrate::dispatch::CallMetadata { function_name, pallet_name, index } } )* } diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index e877f29e0a137..31995d1dca244 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -48,6 +48,8 @@ pub struct CallMetadata { pub function_name: &'static str, /// Name of the pallet to which the function belongs. pub pallet_name: &'static str, + /// Index of the pallet specified in `construct_runtime`. + pub index: u8, } /// Gets the function name of the Call. From edb7f2ee36c17a5af85e33727ec0c0dee7f9ca46 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 18:23:37 -0700 Subject: [PATCH 02/18] Resurrect PalletVersion infrastructure and rename as CrateVersion --- .../src/construct_runtime/expand/call.rs | 16 ++++- frame/support/procedural/src/crate_version.rs | 64 +++++++++++++++++++ frame/support/procedural/src/lib.rs | 8 +++ .../src/pallet/expand/pallet_struct.rs | 11 ++++ frame/support/src/dispatch.rs | 9 +++ frame/support/src/lib.rs | 15 +++++ frame/support/src/traits.rs | 4 +- frame/support/src/traits/metadata.rs | 38 ++++++++++- 8 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 frame/support/procedural/src/crate_version.rs diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index 1efa171a4aac0..853981b1422f6 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -30,6 +30,7 @@ pub fn expand_outer_dispatch( let mut query_call_part_macros = Vec::new(); let mut pallet_names = Vec::new(); let mut pallet_indices = Vec::new(); + let mut pallet_structs = Vec::new(); let pallets_with_call = pallet_decls.iter().filter(|decl| decl.exists_part("Call")); @@ -37,6 +38,10 @@ pub fn expand_outer_dispatch( let name = &pallet_declaration.name; let path = &pallet_declaration.path; let index = pallet_declaration.index; + let pallet_struct = match pallet_declaration.instance.as_ref() { + Some(inst) => quote!(#path::Pallet::<#inst>), + None => quote!(#path::Pallet), + }; variant_defs.extend( quote!(#[codec(index = #index)] #name( #scrate::dispatch::CallableCallFor<#name, #runtime> ),), @@ -44,6 +49,7 @@ pub fn expand_outer_dispatch( variant_patterns.push(quote!(Call::#name(call))); pallet_names.push(name); pallet_indices.push(index); + pallet_structs.push(pallet_struct); query_call_part_macros.push(quote! { #path::__substrate_call_check::is_call_part_defined!(#name); }); @@ -77,7 +83,15 @@ pub fn expand_outer_dispatch( let function_name = call.get_call_name(); let pallet_name = stringify!(#pallet_names); let index = #pallet_indices; - #scrate::dispatch::CallMetadata { function_name, pallet_name, index } + let crate_version = < + #pallet_structs as #scrate::traits::GetCrateVersion + >::crate_version(); + #scrate::dispatch::CallMetadata { + function_name, + pallet_name, + index, + crate_version, + } } )* } diff --git a/frame/support/procedural/src/crate_version.rs b/frame/support/procedural/src/crate_version.rs new file mode 100644 index 0000000000000..fc9ae9ff4c449 --- /dev/null +++ b/frame/support/procedural/src/crate_version.rs @@ -0,0 +1,64 @@ +// This file is part of Substrate. + +// Copyright (C) 2020-2021 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. + +//! Implementation of macros related to pallet versioning. + +use frame_support_procedural_tools::generate_crate_access_2018; +use proc_macro2::{Span, TokenStream}; +use std::{env, str::FromStr}; +use syn::{Error, Result}; + +/// Get the version from the given version environment variable. +/// +/// The version is parsed into the requested destination type. +fn get_version(version_env: &str) -> std::result::Result { + let version = env::var(version_env) + .unwrap_or_else(|_| panic!("`{}` is always set by cargo; qed", version_env)); + + T::from_str(&version).map_err(drop) +} + +/// Create an error that will be shown by rustc at the call site of the macro. +fn create_error(message: &str) -> Error { + Error::new(Span::call_site(), message) +} + +/// Implementation of the `crate_to_crate_version!` macro. +pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(create_error("No arguments expected!")) + } + + let major_version = get_version::("CARGO_PKG_VERSION_MAJOR") + .map_err(|_| create_error("Major version needs to fit into `u16`"))?; + + let minor_version = get_version::("CARGO_PKG_VERSION_MINOR") + .map_err(|_| create_error("Minor version needs to fit into `u8`"))?; + + let patch_version = get_version::("CARGO_PKG_VERSION_PATCH") + .map_err(|_| create_error("Patch version needs to fit into `u8`"))?; + + let crate_ = generate_crate_access_2018("frame-support")?; + + Ok(quote::quote! { + #crate_::traits::CrateVersion { + major: #major_version, + minor: #minor_version, + patch: #patch_version, + } + }) +} diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index a8ac022c35c6b..5a69aa8033b4f 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -26,6 +26,7 @@ mod default_no_bound; mod dummy_part_checker; mod key_prefix; mod pallet; +mod crate_version; mod partial_eq_no_bound; mod storage; mod transactional; @@ -462,6 +463,13 @@ pub fn require_transactional(attr: TokenStream, input: TokenStream) -> TokenStre .unwrap_or_else(|e| e.to_compile_error().into()) } +#[proc_macro] +pub fn crate_to_crate_version(input: TokenStream) -> TokenStream { + crate_version::crate_to_crate_version(input) + .unwrap_or_else(|e| e.to_compile_error()) + .into() +} + /// The number of module instances supported by the runtime, starting at index 1, /// and up to `NUMBER_OF_INSTANCE`. pub(crate) const NUMBER_OF_INSTANCE: u8 = 16; diff --git a/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/frame/support/procedural/src/pallet/expand/pallet_struct.rs index 40fc39b161f15..401bfe5e935a8 100644 --- a/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -19,6 +19,7 @@ use crate::pallet::{expand::merge_where_clauses, parse::helper::get_doc_literals /// /// * Add derive trait on Pallet +/// * Implement GetCrateVersion on Pallet /// * Implement GetStorageVersion on Pallet /// * Implement OnGenesis on Pallet /// * Implement ModuleErrorMetadata on Pallet @@ -168,6 +169,16 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { #[allow(dead_code)] pub type Module<#type_decl_gen> = #pallet_ident<#type_use_gen>; + // Implement `GetCrateVersion` for `Pallet` + impl<#type_impl_gen> #frame_support::traits::GetCrateVersion + for #pallet_ident<#type_use_gen> + #config_where_clause + { + fn crate_version() -> #frame_support::traits::CrateVersion { + #frame_support::crate_to_crate_version!() + } + } + // Implement `GetStorageVersion` for `Pallet` impl<#type_impl_gen> #frame_support::traits::GetStorageVersion for #pallet_ident<#type_use_gen> diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index a4644cebeeb55..294794dcf6ab1 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2168,6 +2168,15 @@ macro_rules! decl_module { } } + // Implement `GetCrateVersion` for `Module` + impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::GetCrateVersion + for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* + { + fn crate_version() -> $crate::traits::CrateVersion { + $crate::crate_to_crate_version!() + } + } + // Implement `OnGenesis` for `Module` impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::OnGenesis for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 105b2328f2325..0966a65cbddac 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -666,6 +666,21 @@ pub use frame_support_procedural::DefaultNoBound; /// ``` pub use frame_support_procedural::require_transactional; +/// Convert the current crate version into a [`CrateVersion`](crate::traits::CrateVersion). +/// +/// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and +/// `CARGO_PKG_VERSION_PATCH` environment variables to fetch the crate version. +/// This means that the [`CrateVersion`](crate::traits::CrateVersion) +/// object will correspond to the version of the crate the macro is called in! +/// +/// # Example +/// +/// ``` +/// # use frame_support::{traits::CrateVersion, crate_to_crate_version}; +/// const Version: CrateVersion = crate_to_crate_version!(); +/// ``` +pub use frame_support_procedural::crate_to_crate_version; + /// Return Err of the expression: `return Err($expression);`. /// /// Used as `fail!(expression)`. diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index efb5559ed0622..4f27afeee64a0 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -62,8 +62,8 @@ pub use randomness::Randomness; mod metadata; pub use metadata::{ - CallMetadata, GetCallMetadata, GetCallName, GetStorageVersion, PalletInfo, PalletInfoAccess, - StorageVersion, STORAGE_VERSION_STORAGE_KEY_POSTFIX, + CallMetadata, CrateVersion, GetCallMetadata, GetCallName, GetCrateVersion, GetStorageVersion, + PalletInfo, PalletInfoAccess, StorageVersion, STORAGE_VERSION_STORAGE_KEY_POSTFIX, }; mod hooks; diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index 31995d1dca244..8824d20827c44 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -48,8 +48,10 @@ pub struct CallMetadata { pub function_name: &'static str, /// Name of the pallet to which the function belongs. pub pallet_name: &'static str, - /// Index of the pallet specified in `construct_runtime`. + /// Index of the containing pallet specified in `construct_runtime`. pub index: u8, + /// Version of the crate containing the pallet to which the function belongs. + pub crate_version: CrateVersion, } /// Gets the function name of the Call. @@ -70,6 +72,40 @@ pub trait GetCallMetadata { fn get_call_metadata(&self) -> CallMetadata; } +/// The version of a crate. +#[derive(RuntimeDebug, Eq, PartialEq, Encode, Decode, Ord, Clone, Copy, Default)] +pub struct CrateVersion { + /// The major version of the crate. + pub major: u16, + /// The minor version of the crate. + pub minor: u8, + /// The patch version of the crate. + pub patch: u8, +} + +impl CrateVersion { + pub const fn new(major: u16, minor: u8, patch: u8) -> Self { + Self { major, minor, patch } + } +} + +impl sp_std::cmp::PartialOrd for CrateVersion { + fn partial_cmp(&self, other: &Self) -> Option { + let res = self + .major + .cmp(&other.major) + .then_with(|| self.minor.cmp(&other.minor).then_with(|| self.patch.cmp(&other.patch))); + + Some(res) + } +} + +/// Provides information about the version of a crate. +pub trait GetCrateVersion { + /// Returns the current version of the crate. + fn crate_version() -> CrateVersion; +} + /// The storage key postfix that is used to store the [`StorageVersion`] per pallet. /// /// The full storage key is built by using: From e9d8acc786d64f425f81916b42a9f162bd61af94 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 18:27:00 -0700 Subject: [PATCH 03/18] cargo fmt --- frame/support/procedural/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index 5a69aa8033b4f..c379e6940a305 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -21,12 +21,12 @@ mod clone_no_bound; mod construct_runtime; +mod crate_version; mod debug_no_bound; mod default_no_bound; mod dummy_part_checker; mod key_prefix; mod pallet; -mod crate_version; mod partial_eq_no_bound; mod storage; mod transactional; From c57286b9fe199f12484a9892975784e12e50d6c2 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 18:55:15 -0700 Subject: [PATCH 04/18] Add missing runtime generics to pallet struct --- frame/support/procedural/src/construct_runtime/expand/call.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index 853981b1422f6..3d632ba67c336 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -39,8 +39,8 @@ pub fn expand_outer_dispatch( let path = &pallet_declaration.path; let index = pallet_declaration.index; let pallet_struct = match pallet_declaration.instance.as_ref() { - Some(inst) => quote!(#path::Pallet::<#inst>), - None => quote!(#path::Pallet), + Some(inst) => quote!(#path::Pallet::<#runtime, #inst>), + None => quote!(#path::Pallet<#runtime>), }; variant_defs.extend( From 46b0b6e77101a1e7f232dacd7fcc1574fcd6abc8 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 19:14:47 -0700 Subject: [PATCH 05/18] Fix path to instance --- frame/support/procedural/src/construct_runtime/expand/call.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index 3d632ba67c336..b73fbde18930f 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -39,7 +39,7 @@ pub fn expand_outer_dispatch( let path = &pallet_declaration.path; let index = pallet_declaration.index; let pallet_struct = match pallet_declaration.instance.as_ref() { - Some(inst) => quote!(#path::Pallet::<#runtime, #inst>), + Some(inst) => quote!(#path::Pallet::<#runtime, #path::#inst>), None => quote!(#path::Pallet<#runtime>), }; From c24eccfb93510163c7f4871bf06fc65ad44495bc Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 19:28:22 -0700 Subject: [PATCH 06/18] Fix test --- frame/support/test/tests/construct_runtime.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 5ddcb89a7dca2..fc5d65c064583 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -21,7 +21,7 @@ #![recursion_limit = "128"] -use frame_support::traits::PalletInfo as _; +use frame_support::traits::{CrateVersion, PalletInfo as _}; use sp_core::{sr25519, H256}; use sp_runtime::{ generic, @@ -545,7 +545,16 @@ fn call_metadata() { use frame_support::dispatch::{CallMetadata, GetCallMetadata}; let call = Call::Module3(module3::Call::::aux_4()); let metadata = call.get_call_metadata(); - let expected = CallMetadata { function_name: "aux_4".into(), pallet_name: "Module3".into() }; + let expected = CallMetadata { + function_name: "aux_4".into(), + pallet_name: "Module3".into(), + index: 35, + crate_version: CrateVersion { + major: 3, + minor: 0, + patch: 0, + }, + }; assert_eq!(metadata, expected); } From 748eb2d12adcb3216bb8020d1c1eeb37858a553c Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 20:10:51 -0700 Subject: [PATCH 07/18] Fix UI test expectations --- frame/support/test/tests/construct_runtime.rs | 6 +----- .../tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index fc5d65c064583..72aeebdcaa645 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -549,11 +549,7 @@ fn call_metadata() { function_name: "aux_4".into(), pallet_name: "Module3".into(), index: 35, - crate_version: CrateVersion { - major: 3, - minor: 0, - patch: 0, - }, + crate_version: CrateVersion { major: 3, minor: 0, patch: 0 }, }; assert_eq!(metadata, expected); } diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index 6c92423c6a7fe..cc9343f38e305 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -4,6 +4,6 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied 10 | #[pallet::generate_storage_info] | ^^^^^^^^^^^^^^^^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | - = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` + = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `NMapKey` = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` = note: required by `storage_info` From 08beeb803e0616238d2ff1c080758f09494e0d1c Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 3 Sep 2021 22:07:55 -0700 Subject: [PATCH 08/18] Fix UI test expectations --- .../test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index cc9343f38e305..545520124bfee 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -5,5 +5,5 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied | ^^^^^^^^^^^^^^^^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `NMapKey` - = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` + = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, NMapKey, u32>` = note: required by `storage_info` From 4a338ab62346e7ee58a921f4265ddb5c8bca166a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 4 Sep 2021 15:42:56 -0700 Subject: [PATCH 09/18] Move crate_version function to PalletInfoAccess --- .../src/construct_runtime/expand/call.rs | 19 +------------ .../procedural/src/construct_runtime/mod.rs | 28 ++++++++++++++++--- .../src/pallet/expand/pallet_struct.rs | 15 +++------- frame/support/src/dispatch.rs | 25 +++++++++-------- frame/support/src/lib.rs | 4 +++ frame/support/src/traits.rs | 4 +-- frame/support/src/traits/metadata.rs | 14 +++------- frame/support/test/src/lib.rs | 3 ++ frame/support/test/tests/construct_runtime.rs | 20 +++++++++---- test-utils/runtime/src/lib.rs | 21 +++++++++++++- 10 files changed, 90 insertions(+), 63 deletions(-) diff --git a/frame/support/procedural/src/construct_runtime/expand/call.rs b/frame/support/procedural/src/construct_runtime/expand/call.rs index b73fbde18930f..f847bc6dbfbdd 100644 --- a/frame/support/procedural/src/construct_runtime/expand/call.rs +++ b/frame/support/procedural/src/construct_runtime/expand/call.rs @@ -29,8 +29,6 @@ pub fn expand_outer_dispatch( let mut variant_patterns = Vec::new(); let mut query_call_part_macros = Vec::new(); let mut pallet_names = Vec::new(); - let mut pallet_indices = Vec::new(); - let mut pallet_structs = Vec::new(); let pallets_with_call = pallet_decls.iter().filter(|decl| decl.exists_part("Call")); @@ -38,18 +36,12 @@ pub fn expand_outer_dispatch( let name = &pallet_declaration.name; let path = &pallet_declaration.path; let index = pallet_declaration.index; - let pallet_struct = match pallet_declaration.instance.as_ref() { - Some(inst) => quote!(#path::Pallet::<#runtime, #path::#inst>), - None => quote!(#path::Pallet<#runtime>), - }; variant_defs.extend( quote!(#[codec(index = #index)] #name( #scrate::dispatch::CallableCallFor<#name, #runtime> ),), ); variant_patterns.push(quote!(Call::#name(call))); pallet_names.push(name); - pallet_indices.push(index); - pallet_structs.push(pallet_struct); query_call_part_macros.push(quote! { #path::__substrate_call_check::is_call_part_defined!(#name); }); @@ -82,16 +74,7 @@ pub fn expand_outer_dispatch( #variant_patterns => { let function_name = call.get_call_name(); let pallet_name = stringify!(#pallet_names); - let index = #pallet_indices; - let crate_version = < - #pallet_structs as #scrate::traits::GetCrateVersion - >::crate_version(); - #scrate::dispatch::CallMetadata { - function_name, - pallet_name, - index, - crate_version, - } + #scrate::dispatch::CallMetadata { function_name, pallet_name } } )* } diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 402cb5458851d..fbc6f6fde8df0 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -132,7 +132,7 @@ fn construct_runtime_parsed(definition: RuntimeDefinition) -> Result( } fn decl_pallet_runtime_setup( + runtime: &Ident, pallet_declarations: &[Pallet], scrate: &TokenStream2, ) -> TokenStream2 { - let names = pallet_declarations.iter().map(|d| &d.name); - let names2 = pallet_declarations.iter().map(|d| &d.name); + let names = pallet_declarations.iter().map(|d| &d.name).collect::>(); let name_strings = pallet_declarations.iter().map(|d| d.name.to_string()); let indices = pallet_declarations.iter().map(|pallet| pallet.index as usize); + let pallet_structs = pallet_declarations.iter().map(|pallet| { + let path = &pallet.path; + match pallet.instance.as_ref() { + Some(inst) => quote!(#path::Pallet<#runtime, #path::#inst>), + None => quote!(#path::Pallet<#runtime>), + } + }); quote!( /// Provides an implementation of `PalletInfo` to provide information @@ -261,13 +268,26 @@ fn decl_pallet_runtime_setup( fn name() -> Option<&'static str> { let type_id = #scrate::sp_std::any::TypeId::of::

(); #( - if type_id == #scrate::sp_std::any::TypeId::of::<#names2>() { + if type_id == #scrate::sp_std::any::TypeId::of::<#names>() { return Some(#name_strings) } )* None } + + fn crate_version() -> Option<#scrate::traits::CrateVersion> { + let type_id = #scrate::sp_std::any::TypeId::of::

(); + #( + if type_id == #scrate::sp_std::any::TypeId::of::<#names>() { + return Some( + <#pallet_structs as #scrate::traits::PalletInfoAccess>::crate_version() + ) + } + )* + + None + } } ) } diff --git a/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/frame/support/procedural/src/pallet/expand/pallet_struct.rs index 401bfe5e935a8..dc549547fdb42 100644 --- a/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -19,7 +19,6 @@ use crate::pallet::{expand::merge_where_clauses, parse::helper::get_doc_literals /// /// * Add derive trait on Pallet -/// * Implement GetCrateVersion on Pallet /// * Implement GetStorageVersion on Pallet /// * Implement OnGenesis on Pallet /// * Implement ModuleErrorMetadata on Pallet @@ -169,16 +168,6 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { #[allow(dead_code)] pub type Module<#type_decl_gen> = #pallet_ident<#type_use_gen>; - // Implement `GetCrateVersion` for `Pallet` - impl<#type_impl_gen> #frame_support::traits::GetCrateVersion - for #pallet_ident<#type_use_gen> - #config_where_clause - { - fn crate_version() -> #frame_support::traits::CrateVersion { - #frame_support::crate_to_crate_version!() - } - } - // Implement `GetStorageVersion` for `Pallet` impl<#type_impl_gen> #frame_support::traits::GetStorageVersion for #pallet_ident<#type_use_gen> @@ -224,6 +213,10 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { .expect("Pallet is part of the runtime because pallet `Config` trait is \ implemented by the runtime") } + + fn crate_version() -> #frame_support::traits::CrateVersion { + #frame_support::crate_to_crate_version!() + } } #storage_info diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 294794dcf6ab1..203c9fb93010a 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2140,6 +2140,10 @@ macro_rules! decl_module { .expect("Pallet is part of the runtime because pallet `Config` trait is \ implemented by the runtime") } + + fn crate_version() -> $crate::traits::CrateVersion { + $crate::crate_to_crate_version!() + } } // Implement GetCallName for the Call. @@ -2168,15 +2172,6 @@ macro_rules! decl_module { } } - // Implement `GetCrateVersion` for `Module` - impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::GetCrateVersion - for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* - { - fn crate_version() -> $crate::traits::CrateVersion { - $crate::crate_to_crate_version!() - } - } - // Implement `OnGenesis` for `Module` impl<$trait_instance: $trait_name $(, $instance: $instantiable)?> $crate::traits::OnGenesis for $mod_type<$trait_instance $(, $instance)?> where $( $other_where_bounds )* @@ -2607,8 +2602,8 @@ mod tests { use super::*; use crate::{ traits::{ - Get, GetCallName, IntegrityTest, OnFinalize, OnIdle, OnInitialize, OnRuntimeUpgrade, - PalletInfo, + CrateVersion, Get, GetCallName, IntegrityTest, OnFinalize, OnIdle, OnInitialize, + OnRuntimeUpgrade, PalletInfo, }, weights::{DispatchClass, DispatchInfo, Pays, RuntimeDbWeight}, }; @@ -2770,6 +2765,14 @@ mod tests { return Some("Test") } + None + } + fn crate_version() -> Option { + let type_id = sp_std::any::TypeId::of::

(); + if type_id == sp_std::any::TypeId::of::() { + return Some(frame_support::crate_to_crate_version!()) + } + None } } diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 0966a65cbddac..5ead86e747e4f 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -798,6 +798,7 @@ pub mod tests { DecodeDifferent, DefaultByteGetter, StorageEntryMetadata, StorageEntryModifier, StorageEntryType, StorageHasher, StorageMetadata, }; + use frame_support::traits::CrateVersion; use sp_io::TestExternalities; use sp_std::{marker::PhantomData, result}; @@ -811,6 +812,9 @@ pub mod tests { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } + fn crate_version() -> Option { + unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + } } pub trait Config: 'static { diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 4f27afeee64a0..121bdd5596dc7 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -62,8 +62,8 @@ pub use randomness::Randomness; mod metadata; pub use metadata::{ - CallMetadata, CrateVersion, GetCallMetadata, GetCallName, GetCrateVersion, GetStorageVersion, - PalletInfo, PalletInfoAccess, StorageVersion, STORAGE_VERSION_STORAGE_KEY_POSTFIX, + CallMetadata, CrateVersion, GetCallMetadata, GetCallName, GetStorageVersion, PalletInfo, + PalletInfoAccess, StorageVersion, STORAGE_VERSION_STORAGE_KEY_POSTFIX, }; mod hooks; diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index 8824d20827c44..1121c27800687 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -29,6 +29,8 @@ pub trait PalletInfo { fn index() -> Option; /// Convert the given pallet `P` into its name as configured in the runtime. fn name() -> Option<&'static str>; + /// Convert the given pallet `P` into its containing crate version. + fn crate_version() -> Option; } /// Provides information about the pallet setup in the runtime. @@ -39,6 +41,8 @@ pub trait PalletInfoAccess { fn index() -> usize; /// Name of the pallet as configured in the runtime. fn name() -> &'static str; + /// Version of the crate containing the pallet. + fn crate_version() -> CrateVersion; } /// The function and pallet name of the Call. @@ -48,10 +52,6 @@ pub struct CallMetadata { pub function_name: &'static str, /// Name of the pallet to which the function belongs. pub pallet_name: &'static str, - /// Index of the containing pallet specified in `construct_runtime`. - pub index: u8, - /// Version of the crate containing the pallet to which the function belongs. - pub crate_version: CrateVersion, } /// Gets the function name of the Call. @@ -100,12 +100,6 @@ impl sp_std::cmp::PartialOrd for CrateVersion { } } -/// Provides information about the version of a crate. -pub trait GetCrateVersion { - /// Returns the current version of the crate. - fn crate_version() -> CrateVersion; -} - /// The storage key postfix that is used to store the [`StorageVersion`] per pallet. /// /// The full storage key is built by using: diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index 78317a1a2f907..f058bf5fc5356 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -49,6 +49,9 @@ impl frame_support::traits::PalletInfo for PanicPalletInfo { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } + fn crate_version() -> Option { + unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + } } /// Provides an implementation of [`frame_support::traits::Randomness`] that should only be used in diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 72aeebdcaa645..4089214d69e17 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -545,12 +545,7 @@ fn call_metadata() { use frame_support::dispatch::{CallMetadata, GetCallMetadata}; let call = Call::Module3(module3::Call::::aux_4()); let metadata = call.get_call_metadata(); - let expected = CallMetadata { - function_name: "aux_4".into(), - pallet_name: "Module3".into(), - index: 35, - crate_version: CrateVersion { major: 3, minor: 0, patch: 0 }, - }; + let expected = CallMetadata { function_name: "aux_4".into(), pallet_name: "Module3".into() }; assert_eq!(metadata, expected); } @@ -953,40 +948,53 @@ fn test_metadata() { fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 30); assert_eq!(PalletInfo::name::().unwrap(), "System"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 31); assert_eq!(PalletInfo::name::().unwrap(), "Module1_1"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 32); assert_eq!(PalletInfo::name::().unwrap(), "Module2"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 33); assert_eq!(PalletInfo::name::().unwrap(), "Module1_2"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 34); assert_eq!(PalletInfo::name::().unwrap(), "NestedModule3"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 35); assert_eq!(PalletInfo::name::().unwrap(), "Module3"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 6); assert_eq!(PalletInfo::name::().unwrap(), "Module1_3"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 3); assert_eq!(PalletInfo::name::().unwrap(), "Module1_4"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 4); assert_eq!(PalletInfo::name::().unwrap(), "Module1_5"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 1); assert_eq!(PalletInfo::name::().unwrap(), "Module1_6"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 2); assert_eq!(PalletInfo::name::().unwrap(), "Module1_7"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 12); assert_eq!(PalletInfo::name::().unwrap(), "Module1_8"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 13); assert_eq!(PalletInfo::name::().unwrap(), "Module1_9"); + assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index bdb8724120813..fd6cf99d50690 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -35,7 +35,11 @@ use sp_trie::{ use trie_db::{Trie, TrieMut}; use cfg_if::cfg_if; -use frame_support::{parameter_types, traits::KeyOwnerProofSystem, weights::RuntimeDbWeight}; +use frame_support::{ + parameter_types, + traits::{CrateVersion, KeyOwnerProofSystem}, + weights::RuntimeDbWeight, +}; use frame_system::limits::{BlockLength, BlockWeights}; use sp_api::{decl_runtime_apis, impl_runtime_apis}; pub use sp_core::hash::H256; @@ -519,6 +523,21 @@ impl frame_support::traits::PalletInfo for Runtime { return Some("Babe") } + None + } + fn crate_version() -> Option { + use frame_support::traits::PalletInfoAccess as _; + let type_id = sp_std::any::TypeId::of::

(); + if type_id == sp_std::any::TypeId::of::>() { + return Some(system::Pallet::::crate_version()) + } + if type_id == sp_std::any::TypeId::of::>() { + return Some(pallet_timestamp::Pallet::::crate_version()) + } + if type_id == sp_std::any::TypeId::of::>() { + return Some(pallet_babe::Pallet::::crate_version()) + } + None } } From 7778c580dff33401e4477a41ee5d6f88d8dd56fc Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 4 Sep 2021 16:23:50 -0700 Subject: [PATCH 10/18] Update UI test expectations --- .../test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index 545520124bfee..6c92423c6a7fe 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -4,6 +4,6 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied 10 | #[pallet::generate_storage_info] | ^^^^^^^^^^^^^^^^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | - = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `NMapKey` - = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, NMapKey, u32>` + = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` + = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` = note: required by `storage_info` From cd4c2b922a31c1854e90f9898cd6f3aa24b1a8b3 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 7 Sep 2021 02:52:21 -0700 Subject: [PATCH 11/18] Add crate_name method to PalletInfo --- .../procedural/src/construct_runtime/mod.rs | 16 ++++++++- frame/support/procedural/src/crate_name.rs | 36 +++++++++++++++++++ frame/support/procedural/src/crate_version.rs | 20 +++-------- frame/support/procedural/src/lib.rs | 20 ++++++++++- .../src/pallet/expand/pallet_struct.rs | 4 +++ frame/support/src/dispatch.rs | 12 +++++++ frame/support/src/lib.rs | 17 +++++++++ frame/support/src/traits/metadata.rs | 4 +++ frame/support/test/src/lib.rs | 3 ++ frame/support/test/tests/construct_runtime.rs | 13 +++++++ test-utils/runtime/src/lib.rs | 15 ++++++++ 11 files changed, 143 insertions(+), 17 deletions(-) create mode 100644 frame/support/procedural/src/crate_name.rs diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index fbc6f6fde8df0..21744b82a120f 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -246,7 +246,8 @@ fn decl_pallet_runtime_setup( Some(inst) => quote!(#path::Pallet<#runtime, #path::#inst>), None => quote!(#path::Pallet<#runtime>), } - }); + }) + .collect::>(); quote!( /// Provides an implementation of `PalletInfo` to provide information @@ -276,6 +277,19 @@ fn decl_pallet_runtime_setup( None } + fn crate_name() -> Option<&'static str> { + let type_id = #scrate::sp_std::any::TypeId::of::

(); + #( + if type_id == #scrate::sp_std::any::TypeId::of::<#names>() { + return Some( + <#pallet_structs as #scrate::traits::PalletInfoAccess>::crate_name() + ) + } + )* + + None + } + fn crate_version() -> Option<#scrate::traits::CrateVersion> { let type_id = #scrate::sp_std::any::TypeId::of::

(); #( diff --git a/frame/support/procedural/src/crate_name.rs b/frame/support/procedural/src/crate_name.rs new file mode 100644 index 0000000000000..0543b4bb655de --- /dev/null +++ b/frame/support/procedural/src/crate_name.rs @@ -0,0 +1,36 @@ +// This file is part of Substrate. + +// Copyright (C) 2021 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. + +//! Implementation of macros related to crate naming. + +use proc_macro2::{Span, TokenStream}; +use syn::{Error, Result}; +use super::get_cargo_env_var; + +/// Implementation of the `crate_to_crate_name!` macro. +pub fn crate_to_crate_name(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(Error::new(Span::call_site(), "No arguments expected!")) + } + + let crate_name = get_cargo_env_var::("CARGO_PKG_NAME") + .map_err(|_| Error::new(Span::call_site(), "Major version needs to fit into `u16`"))? + .replace("-", "_"); + + Ok(quote::quote!(#crate_name)) +} + diff --git a/frame/support/procedural/src/crate_version.rs b/frame/support/procedural/src/crate_version.rs index fc9ae9ff4c449..7fcdbfc2b8dfe 100644 --- a/frame/support/procedural/src/crate_version.rs +++ b/frame/support/procedural/src/crate_version.rs @@ -15,22 +15,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Implementation of macros related to pallet versioning. +//! Implementation of macros related to crate versioning. use frame_support_procedural_tools::generate_crate_access_2018; use proc_macro2::{Span, TokenStream}; -use std::{env, str::FromStr}; use syn::{Error, Result}; - -/// Get the version from the given version environment variable. -/// -/// The version is parsed into the requested destination type. -fn get_version(version_env: &str) -> std::result::Result { - let version = env::var(version_env) - .unwrap_or_else(|_| panic!("`{}` is always set by cargo; qed", version_env)); - - T::from_str(&version).map_err(drop) -} +use super::get_cargo_env_var; /// Create an error that will be shown by rustc at the call site of the macro. fn create_error(message: &str) -> Error { @@ -43,13 +33,13 @@ pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result("CARGO_PKG_VERSION_MAJOR") + let major_version = get_cargo_env_var::("CARGO_PKG_VERSION_MAJOR") .map_err(|_| create_error("Major version needs to fit into `u16`"))?; - let minor_version = get_version::("CARGO_PKG_VERSION_MINOR") + let minor_version = get_cargo_env_var::("CARGO_PKG_VERSION_MINOR") .map_err(|_| create_error("Minor version needs to fit into `u8`"))?; - let patch_version = get_version::("CARGO_PKG_VERSION_PATCH") + let patch_version = get_cargo_env_var::("CARGO_PKG_VERSION_PATCH") .map_err(|_| create_error("Patch version needs to fit into `u8`"))?; let crate_ = generate_crate_access_2018("frame-support")?; diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index c379e6940a305..cf47cf2b80dc4 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -21,6 +21,7 @@ mod clone_no_bound; mod construct_runtime; +mod crate_name; mod crate_version; mod debug_no_bound; mod default_no_bound; @@ -32,7 +33,7 @@ mod storage; mod transactional; use proc_macro::TokenStream; -use std::cell::RefCell; +use std::{cell::RefCell, str::FromStr}; pub(crate) use storage::INHERENT_INSTANCE_NAME; thread_local! { @@ -53,6 +54,16 @@ impl Counter { } } +/// Get the value from the given environment variable set by cargo. +/// +/// The value is parsed into the requested destination type. +fn get_cargo_env_var(version_env: &str) -> std::result::Result { + let version = std::env::var(version_env) + .unwrap_or_else(|_| panic!("`{}` is always set by cargo; qed", version_env)); + + T::from_str(&version).map_err(drop) +} + /// Declares strongly-typed wrappers around codec-compatible types in storage. /// /// ## Example @@ -470,6 +481,13 @@ pub fn crate_to_crate_version(input: TokenStream) -> TokenStream { .into() } +#[proc_macro] +pub fn crate_to_crate_name(input: TokenStream) -> TokenStream { + crate_name::crate_to_crate_name(input) + .unwrap_or_else(|e| e.to_compile_error()) + .into() +} + /// The number of module instances supported by the runtime, starting at index 1, /// and up to `NUMBER_OF_INSTANCE`. pub(crate) const NUMBER_OF_INSTANCE: u8 = 16; diff --git a/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/frame/support/procedural/src/pallet/expand/pallet_struct.rs index dc549547fdb42..e4ee15433dcf7 100644 --- a/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -214,6 +214,10 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { implemented by the runtime") } + fn crate_name() -> &'static str { + #frame_support::crate_to_crate_name!() + } + fn crate_version() -> #frame_support::traits::CrateVersion { #frame_support::crate_to_crate_version!() } diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 203c9fb93010a..9ef513ae015a0 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2141,6 +2141,10 @@ macro_rules! decl_module { implemented by the runtime") } + fn crate_name() -> &'static str { + $crate::crate_to_crate_name!() + } + fn crate_version() -> $crate::traits::CrateVersion { $crate::crate_to_crate_version!() } @@ -2767,6 +2771,14 @@ mod tests { None } + fn crate_name() -> Option<&'static str> { + let type_id = sp_std::any::TypeId::of::

(); + if type_id == sp_std::any::TypeId::of::() { + return Some(frame_support::crate_to_crate_name!()) + } + + None + } fn crate_version() -> Option { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 5ead86e747e4f..778cdfd0ad52d 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -666,6 +666,20 @@ pub use frame_support_procedural::DefaultNoBound; /// ``` pub use frame_support_procedural::require_transactional; +/// Return the name of the current crate. +/// +/// It uses the `CARGO_PKG_NAME` environment variable to fetch the crate name. +/// This means that the returned string will correspond to the version of the crate the macro is +/// called in! +/// +/// # Example +/// +/// ``` +/// # use frame_support::crate_to_crate_name; +/// const Name: &'static str = crate_to_crate_name!(); +/// ``` +pub use frame_support_procedural::crate_to_crate_name; + /// Convert the current crate version into a [`CrateVersion`](crate::traits::CrateVersion). /// /// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and @@ -812,6 +826,9 @@ pub mod tests { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } + fn crate_name() -> Option<&'static str> { + unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + } fn crate_version() -> Option { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index 1121c27800687..54fe415b16e53 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -29,6 +29,8 @@ pub trait PalletInfo { fn index() -> Option; /// Convert the given pallet `P` into its name as configured in the runtime. fn name() -> Option<&'static str>; + /// Convert the given pallet `P` into its containing crate name. + fn crate_name() -> Option<&'static str>; /// Convert the given pallet `P` into its containing crate version. fn crate_version() -> Option; } @@ -41,6 +43,8 @@ pub trait PalletInfoAccess { fn index() -> usize; /// Name of the pallet as configured in the runtime. fn name() -> &'static str; + /// Name of the crate containing the pallet. + fn crate_name() -> &'static str; /// Version of the crate containing the pallet. fn crate_version() -> CrateVersion; } diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index f058bf5fc5356..a39659fe01278 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -49,6 +49,9 @@ impl frame_support::traits::PalletInfo for PanicPalletInfo { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } + fn crate_name() -> Option<&'static str> { + unimplemented!("PanicPalletInfo mustn't be triggered by tests"); + } fn crate_version() -> Option { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 4089214d69e17..73b16a1e8df6f 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -948,53 +948,66 @@ fn test_metadata() { fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 30); assert_eq!(PalletInfo::name::().unwrap(), "System"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 31); assert_eq!(PalletInfo::name::().unwrap(), "Module1_1"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 32); assert_eq!(PalletInfo::name::().unwrap(), "Module2"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 33); assert_eq!(PalletInfo::name::().unwrap(), "Module1_2"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 34); assert_eq!(PalletInfo::name::().unwrap(), "NestedModule3"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 35); assert_eq!(PalletInfo::name::().unwrap(), "Module3"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 6); assert_eq!(PalletInfo::name::().unwrap(), "Module1_3"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 3); assert_eq!(PalletInfo::name::().unwrap(), "Module1_4"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 4); assert_eq!(PalletInfo::name::().unwrap(), "Module1_5"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 1); assert_eq!(PalletInfo::name::().unwrap(), "Module1_6"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 2); assert_eq!(PalletInfo::name::().unwrap(), "Module1_7"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 12); assert_eq!(PalletInfo::name::().unwrap(), "Module1_8"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 13); assert_eq!(PalletInfo::name::().unwrap(), "Module1_9"); + assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index fd6cf99d50690..b9f13fea0e729 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -525,6 +525,21 @@ impl frame_support::traits::PalletInfo for Runtime { None } + fn crate_name() -> Option<&'static str> { + use frame_support::traits::PalletInfoAccess as _; + let type_id = sp_std::any::TypeId::of::

(); + if type_id == sp_std::any::TypeId::of::>() { + return Some(system::Pallet::::crate_name()) + } + if type_id == sp_std::any::TypeId::of::>() { + return Some(pallet_timestamp::Pallet::::crate_name()) + } + if type_id == sp_std::any::TypeId::of::>() { + return Some(pallet_babe::Pallet::::crate_name()) + } + + None + } fn crate_version() -> Option { use frame_support::traits::PalletInfoAccess as _; let type_id = sp_std::any::TypeId::of::

(); From b2bf2760abc1d22cbff80301c2a5550a90efdf3e Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 7 Sep 2021 15:42:22 -0700 Subject: [PATCH 12/18] Convert path to module name instead of exposing crate name --- .../procedural/src/construct_runtime/mod.rs | 7 ++-- .../procedural/src/construct_runtime/parse.rs | 12 +++++++ frame/support/procedural/src/crate_name.rs | 36 ------------------- frame/support/procedural/src/lib.rs | 8 ----- .../src/pallet/expand/pallet_struct.rs | 8 +++-- frame/support/src/dispatch.rs | 12 ++++--- frame/support/src/lib.rs | 16 +-------- frame/support/src/traits/metadata.rs | 15 ++++---- frame/support/test/src/lib.rs | 2 +- frame/support/test/tests/construct_runtime.rs | 26 +++++++------- test-utils/runtime/src/lib.rs | 8 ++--- 11 files changed, 56 insertions(+), 94 deletions(-) delete mode 100644 frame/support/procedural/src/crate_name.rs diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 21744b82a120f..3616ed3046302 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -239,6 +239,7 @@ fn decl_pallet_runtime_setup( ) -> TokenStream2 { let names = pallet_declarations.iter().map(|d| &d.name).collect::>(); let name_strings = pallet_declarations.iter().map(|d| d.name.to_string()); + let module_names = pallet_declarations.iter().map(|d| d.path.module_name()); let indices = pallet_declarations.iter().map(|pallet| pallet.index as usize); let pallet_structs = pallet_declarations.iter().map(|pallet| { let path = &pallet.path; @@ -277,13 +278,11 @@ fn decl_pallet_runtime_setup( None } - fn crate_name() -> Option<&'static str> { + fn module_name() -> Option<&'static str> { let type_id = #scrate::sp_std::any::TypeId::of::

(); #( if type_id == #scrate::sp_std::any::TypeId::of::<#names>() { - return Some( - <#pallet_structs as #scrate::traits::PalletInfoAccess>::crate_name() - ) + return Some(#module_names) } )* diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index 6f2fd82e73f4b..7e6796a129b37 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -188,6 +188,18 @@ pub struct PalletPath { pub inner: Path, } +impl PalletPath { + pub fn module_name(&self) -> String { + self.inner.segments.iter().fold(String::new(), |mut acc, segment| { + if !acc.is_empty() { + acc.push('_'); + } + acc.push_str(&segment.ident.to_string()); + acc + }) + } +} + impl Parse for PalletPath { fn parse(input: ParseStream) -> Result { let mut lookahead = input.lookahead1(); diff --git a/frame/support/procedural/src/crate_name.rs b/frame/support/procedural/src/crate_name.rs deleted file mode 100644 index 0543b4bb655de..0000000000000 --- a/frame/support/procedural/src/crate_name.rs +++ /dev/null @@ -1,36 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) 2021 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. - -//! Implementation of macros related to crate naming. - -use proc_macro2::{Span, TokenStream}; -use syn::{Error, Result}; -use super::get_cargo_env_var; - -/// Implementation of the `crate_to_crate_name!` macro. -pub fn crate_to_crate_name(input: proc_macro::TokenStream) -> Result { - if !input.is_empty() { - return Err(Error::new(Span::call_site(), "No arguments expected!")) - } - - let crate_name = get_cargo_env_var::("CARGO_PKG_NAME") - .map_err(|_| Error::new(Span::call_site(), "Major version needs to fit into `u16`"))? - .replace("-", "_"); - - Ok(quote::quote!(#crate_name)) -} - diff --git a/frame/support/procedural/src/lib.rs b/frame/support/procedural/src/lib.rs index cf47cf2b80dc4..6987fc49b9a8c 100644 --- a/frame/support/procedural/src/lib.rs +++ b/frame/support/procedural/src/lib.rs @@ -21,7 +21,6 @@ mod clone_no_bound; mod construct_runtime; -mod crate_name; mod crate_version; mod debug_no_bound; mod default_no_bound; @@ -481,13 +480,6 @@ pub fn crate_to_crate_version(input: TokenStream) -> TokenStream { .into() } -#[proc_macro] -pub fn crate_to_crate_name(input: TokenStream) -> TokenStream { - crate_name::crate_to_crate_name(input) - .unwrap_or_else(|e| e.to_compile_error()) - .into() -} - /// The number of module instances supported by the runtime, starting at index 1, /// and up to `NUMBER_OF_INSTANCE`. pub(crate) const NUMBER_OF_INSTANCE: u8 = 16; diff --git a/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/frame/support/procedural/src/pallet/expand/pallet_struct.rs index e4ee15433dcf7..113d2b80351d8 100644 --- a/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -214,8 +214,12 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { implemented by the runtime") } - fn crate_name() -> &'static str { - #frame_support::crate_to_crate_name!() + fn module_name() -> &'static str { + < + ::PalletInfo as #frame_support::traits::PalletInfo + >::module_name::() + .expect("Pallet is part of the runtime because pallet `Config` trait is \ + implemented by the runtime") } fn crate_version() -> #frame_support::traits::CrateVersion { diff --git a/frame/support/src/dispatch.rs b/frame/support/src/dispatch.rs index 9ef513ae015a0..444c2323e778b 100644 --- a/frame/support/src/dispatch.rs +++ b/frame/support/src/dispatch.rs @@ -2141,8 +2141,12 @@ macro_rules! decl_module { implemented by the runtime") } - fn crate_name() -> &'static str { - $crate::crate_to_crate_name!() + fn module_name() -> &'static str { + < + <$trait_instance as $system::Config>::PalletInfo as $crate::traits::PalletInfo + >::module_name::() + .expect("Pallet is part of the runtime because pallet `Config` trait is \ + implemented by the runtime") } fn crate_version() -> $crate::traits::CrateVersion { @@ -2771,10 +2775,10 @@ mod tests { None } - fn crate_name() -> Option<&'static str> { + fn module_name() -> Option<&'static str> { let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::() { - return Some(frame_support::crate_to_crate_name!()) + return Some("tests") } None diff --git a/frame/support/src/lib.rs b/frame/support/src/lib.rs index 778cdfd0ad52d..b334b4c338b09 100644 --- a/frame/support/src/lib.rs +++ b/frame/support/src/lib.rs @@ -666,20 +666,6 @@ pub use frame_support_procedural::DefaultNoBound; /// ``` pub use frame_support_procedural::require_transactional; -/// Return the name of the current crate. -/// -/// It uses the `CARGO_PKG_NAME` environment variable to fetch the crate name. -/// This means that the returned string will correspond to the version of the crate the macro is -/// called in! -/// -/// # Example -/// -/// ``` -/// # use frame_support::crate_to_crate_name; -/// const Name: &'static str = crate_to_crate_name!(); -/// ``` -pub use frame_support_procedural::crate_to_crate_name; - /// Convert the current crate version into a [`CrateVersion`](crate::traits::CrateVersion). /// /// It uses the `CARGO_PKG_VERSION_MAJOR`, `CARGO_PKG_VERSION_MINOR` and @@ -826,7 +812,7 @@ pub mod tests { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } - fn crate_name() -> Option<&'static str> { + fn module_name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } fn crate_version() -> Option { diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index 54fe415b16e53..ad99961bc11b5 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -20,7 +20,7 @@ use codec::{Decode, Encode}; use sp_runtime::RuntimeDebug; -/// Provides information about the pallet setup in the runtime. +/// Provides information about the pallet itself and its setup in the runtime. /// /// An implementor should be able to provide information about each pallet that /// is configured in `construct_runtime!`. @@ -29,22 +29,23 @@ pub trait PalletInfo { fn index() -> Option; /// Convert the given pallet `P` into its name as configured in the runtime. fn name() -> Option<&'static str>; - /// Convert the given pallet `P` into its containing crate name. - fn crate_name() -> Option<&'static str>; + /// Convert the given pallet `P` into its Rust module name. + fn module_name() -> Option<&'static str>; /// Convert the given pallet `P` into its containing crate version. fn crate_version() -> Option; } -/// Provides information about the pallet setup in the runtime. +/// Provides information about the pallet itself and its setup in the runtime. /// -/// Access the information provided by [`PalletInfo`] for a specific pallet. +/// Declare some information and access the information provided by [`PalletInfo`] for a specific +/// pallet. pub trait PalletInfoAccess { /// Index of the pallet as configured in the runtime. fn index() -> usize; /// Name of the pallet as configured in the runtime. fn name() -> &'static str; - /// Name of the crate containing the pallet. - fn crate_name() -> &'static str; + /// Name of the Rust module containing the pallet. + fn module_name() -> &'static str; /// Version of the crate containing the pallet. fn crate_version() -> CrateVersion; } diff --git a/frame/support/test/src/lib.rs b/frame/support/test/src/lib.rs index a39659fe01278..b5483f4b423b3 100644 --- a/frame/support/test/src/lib.rs +++ b/frame/support/test/src/lib.rs @@ -49,7 +49,7 @@ impl frame_support::traits::PalletInfo for PanicPalletInfo { fn name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } - fn crate_name() -> Option<&'static str> { + fn module_name() -> Option<&'static str> { unimplemented!("PanicPalletInfo mustn't be triggered by tests"); } fn crate_version() -> Option { diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 73b16a1e8df6f..287a270ecff73 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -948,66 +948,66 @@ fn test_metadata() { fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 30); assert_eq!(PalletInfo::name::().unwrap(), "System"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "system"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 31); assert_eq!(PalletInfo::name::().unwrap(), "Module1_1"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 32); assert_eq!(PalletInfo::name::().unwrap(), "Module2"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module2"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 33); assert_eq!(PalletInfo::name::().unwrap(), "Module1_2"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 34); assert_eq!(PalletInfo::name::().unwrap(), "NestedModule3"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "nested_module3"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 35); assert_eq!(PalletInfo::name::().unwrap(), "Module3"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "self_module3"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 6); assert_eq!(PalletInfo::name::().unwrap(), "Module1_3"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 3); assert_eq!(PalletInfo::name::().unwrap(), "Module1_4"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 4); assert_eq!(PalletInfo::name::().unwrap(), "Module1_5"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 1); assert_eq!(PalletInfo::name::().unwrap(), "Module1_6"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 2); assert_eq!(PalletInfo::name::().unwrap(), "Module1_7"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 12); assert_eq!(PalletInfo::name::().unwrap(), "Module1_8"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 13); assert_eq!(PalletInfo::name::().unwrap(), "Module1_9"); - assert_eq!(PalletInfo::crate_name::().unwrap(), "frame_support_test"); + assert_eq!(PalletInfo::module_name::().unwrap(), "module1"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); } diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index b9f13fea0e729..9eb8d4df7913a 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -525,17 +525,17 @@ impl frame_support::traits::PalletInfo for Runtime { None } - fn crate_name() -> Option<&'static str> { + fn module_name() -> Option<&'static str> { use frame_support::traits::PalletInfoAccess as _; let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::>() { - return Some(system::Pallet::::crate_name()) + return Some("system") } if type_id == sp_std::any::TypeId::of::>() { - return Some(pallet_timestamp::Pallet::::crate_name()) + return Some("pallet_timestamp") } if type_id == sp_std::any::TypeId::of::>() { - return Some(pallet_babe::Pallet::::crate_name()) + return Some("pallet_babe") } None From 41dacef98b1ef1a17d6d40806fa94241a46f6241 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 7 Sep 2021 15:46:18 -0700 Subject: [PATCH 13/18] cargo fmt --- .../procedural/src/construct_runtime/mod.rs | 18 ++++++++++-------- frame/support/procedural/src/crate_version.rs | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/frame/support/procedural/src/construct_runtime/mod.rs b/frame/support/procedural/src/construct_runtime/mod.rs index 3616ed3046302..38f5de9ac2473 100644 --- a/frame/support/procedural/src/construct_runtime/mod.rs +++ b/frame/support/procedural/src/construct_runtime/mod.rs @@ -241,14 +241,16 @@ fn decl_pallet_runtime_setup( let name_strings = pallet_declarations.iter().map(|d| d.name.to_string()); let module_names = pallet_declarations.iter().map(|d| d.path.module_name()); let indices = pallet_declarations.iter().map(|pallet| pallet.index as usize); - let pallet_structs = pallet_declarations.iter().map(|pallet| { - let path = &pallet.path; - match pallet.instance.as_ref() { - Some(inst) => quote!(#path::Pallet<#runtime, #path::#inst>), - None => quote!(#path::Pallet<#runtime>), - } - }) - .collect::>(); + let pallet_structs = pallet_declarations + .iter() + .map(|pallet| { + let path = &pallet.path; + match pallet.instance.as_ref() { + Some(inst) => quote!(#path::Pallet<#runtime, #path::#inst>), + None => quote!(#path::Pallet<#runtime>), + } + }) + .collect::>(); quote!( /// Provides an implementation of `PalletInfo` to provide information diff --git a/frame/support/procedural/src/crate_version.rs b/frame/support/procedural/src/crate_version.rs index 7fcdbfc2b8dfe..cfa35c6190e15 100644 --- a/frame/support/procedural/src/crate_version.rs +++ b/frame/support/procedural/src/crate_version.rs @@ -17,10 +17,10 @@ //! Implementation of macros related to crate versioning. +use super::get_cargo_env_var; use frame_support_procedural_tools::generate_crate_access_2018; use proc_macro2::{Span, TokenStream}; use syn::{Error, Result}; -use super::get_cargo_env_var; /// Create an error that will be shown by rustc at the call site of the macro. fn create_error(message: &str) -> Error { From e9c3f6c46e2fef0ee43e43bad35ac6d3d5b70322 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 7 Sep 2021 17:35:47 -0700 Subject: [PATCH 14/18] Keep the double colons when constructing the module name --- frame/support/procedural/src/construct_runtime/parse.rs | 2 +- frame/support/test/tests/construct_runtime.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/frame/support/procedural/src/construct_runtime/parse.rs b/frame/support/procedural/src/construct_runtime/parse.rs index 7e6796a129b37..a0ec6dfa5803e 100644 --- a/frame/support/procedural/src/construct_runtime/parse.rs +++ b/frame/support/procedural/src/construct_runtime/parse.rs @@ -192,7 +192,7 @@ impl PalletPath { pub fn module_name(&self) -> String { self.inner.segments.iter().fold(String::new(), |mut acc, segment| { if !acc.is_empty() { - acc.push('_'); + acc.push_str("::"); } acc.push_str(&segment.ident.to_string()); acc diff --git a/frame/support/test/tests/construct_runtime.rs b/frame/support/test/tests/construct_runtime.rs index 287a270ecff73..4f1e1acce35ba 100644 --- a/frame/support/test/tests/construct_runtime.rs +++ b/frame/support/test/tests/construct_runtime.rs @@ -968,12 +968,12 @@ fn pallet_in_runtime_is_correct() { assert_eq!(PalletInfo::index::().unwrap(), 34); assert_eq!(PalletInfo::name::().unwrap(), "NestedModule3"); - assert_eq!(PalletInfo::module_name::().unwrap(), "nested_module3"); + assert_eq!(PalletInfo::module_name::().unwrap(), "nested::module3"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 35); assert_eq!(PalletInfo::name::().unwrap(), "Module3"); - assert_eq!(PalletInfo::module_name::().unwrap(), "self_module3"); + assert_eq!(PalletInfo::module_name::().unwrap(), "self::module3"); assert_eq!(PalletInfo::crate_version::().unwrap(), CrateVersion::new(3, 0, 0)); assert_eq!(PalletInfo::index::().unwrap(), 6); From 3d73ba978670907379e36e2b7e9b8151b27c12dd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 7 Sep 2021 17:37:28 -0700 Subject: [PATCH 15/18] Remove unused import --- test-utils/runtime/src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 9eb8d4df7913a..38abb63693f5e 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -526,7 +526,6 @@ impl frame_support::traits::PalletInfo for Runtime { None } fn module_name() -> Option<&'static str> { - use frame_support::traits::PalletInfoAccess as _; let type_id = sp_std::any::TypeId::of::

(); if type_id == sp_std::any::TypeId::of::>() { return Some("system") From a7ae59623cdcc1c328b00ca67d27525ead694a93 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 8 Sep 2021 17:23:01 -0700 Subject: [PATCH 16/18] Update UI test expectations --- .../test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index 6c92423c6a7fe..545520124bfee 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -4,6 +4,6 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied 10 | #[pallet::generate_storage_info] | ^^^^^^^^^^^^^^^^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | - = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` - = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` + = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `NMapKey` + = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, NMapKey, u32>` = note: required by `storage_info` From 9f02c4b5243d263bf6dffc58cc1e8822f2e12ea6 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 14 Sep 2021 14:10:22 -0700 Subject: [PATCH 17/18] Update frame/support/src/traits/metadata.rs Co-authored-by: Guillaume Thiolliere --- frame/support/src/traits/metadata.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frame/support/src/traits/metadata.rs b/frame/support/src/traits/metadata.rs index ad99961bc11b5..14b7e6d7355e2 100644 --- a/frame/support/src/traits/metadata.rs +++ b/frame/support/src/traits/metadata.rs @@ -29,7 +29,7 @@ pub trait PalletInfo { fn index() -> Option; /// Convert the given pallet `P` into its name as configured in the runtime. fn name() -> Option<&'static str>; - /// Convert the given pallet `P` into its Rust module name. + /// Convert the given pallet `P` into its Rust module name as used in `construct_runtime!`. fn module_name() -> Option<&'static str>; /// Convert the given pallet `P` into its containing crate version. fn crate_version() -> Option; From 9727fb30564b160975a2396347916a2d37ed3040 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 26 Sep 2021 16:58:48 -0700 Subject: [PATCH 18/18] Update UI test expectations --- .../test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index ffbc5aeea6b4f..2b70102fdac24 100644 --- a/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -4,8 +4,8 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied 10 | #[pallet::generate_storage_info] | ^^^^^^^^^^^^^^^^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | - = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `NMapKey` - = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, NMapKey, u32>` + = note: required because of the requirements on the impl of `KeyGeneratorMaxEncodedLen` for `Key` + = note: required because of the requirements on the impl of `StorageInfoTrait` for `frame_support::pallet_prelude::StorageNMap<_GeneratedPrefixForStorageFoo, Key, u32>` note: required by `storage_info` --> $DIR/storage.rs:71:2 |