From 7102f28a314c31bdf0574bbf948de37da3da3dbc Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 8 Sep 2023 17:54:56 +0200 Subject: [PATCH 01/33] use path instead of ident --- .../src/pallet/expand/genesis_config.rs | 3 +- .../procedural/src/pallet/parse/composite.rs | 2 +- .../procedural/src/pallet/parse/config.rs | 77 ++++++++++++++----- .../procedural/src/pallet/parse/mod.rs | 4 +- .../support/procedural/src/pallet_error.rs | 4 +- .../support/procedural/src/storage_alias.rs | 4 +- .../frame/support/procedural/tools/src/lib.rs | 34 +++++++- 7 files changed, 95 insertions(+), 33 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs index b00f9bcd1a662..31d519ef29293 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -17,6 +17,7 @@ use crate::{pallet::Def, COUNTER}; use frame_support_procedural_tools::get_doc_literals; +use quote::ToTokens; use syn::{spanned::Spanned, Ident}; /// @@ -79,7 +80,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { let genesis_config_item = &mut def.item.content.as_mut().expect("Checked by def parser").1[genesis_config.index]; - let serde_crate = format!("{}::__private::serde", frame_support); + let serde_crate = format!("{}::__private::serde", frame_support.to_token_stream()); match genesis_config_item { syn::Item::Enum(syn::ItemEnum { attrs, .. }) | diff --git a/substrate/frame/support/procedural/src/pallet/parse/composite.rs b/substrate/frame/support/procedural/src/pallet/parse/composite.rs index cb554a116175c..f3072fd8ae6c5 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/composite.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/composite.rs @@ -91,7 +91,7 @@ impl CompositeDef { pub fn try_from( attr_span: proc_macro2::Span, index: usize, - scrate: &proc_macro2::Ident, + scrate: &syn::Path, item: &mut syn::Item, ) -> syn::Result { let item = if let syn::Item::Enum(item) = item { diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index e505f8b04119b..0ed8204724481 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -16,7 +16,7 @@ // limitations under the License. use super::helper; -use frame_support_procedural_tools::get_doc_literals; +use frame_support_procedural_tools::{get_doc_literals, is_using_frame_crate}; use quote::ToTokens; use syn::{spanned::Spanned, token, Token}; @@ -165,24 +165,23 @@ pub struct PalletAttr { typ: PalletAttrType, } -pub struct ConfigBoundParse(syn::Ident); +/// Prase for `$path`, returning the whole path. +pub struct ConfigBoundParse(syn::Path); impl syn::parse::Parse for ConfigBoundParse { fn parse(input: syn::parse::ParseStream) -> syn::Result { - let ident = input.parse::()?; - input.parse::()?; - input.parse::()?; + let config_path = input.parse::()?; if input.peek(syn::token::Lt) { input.parse::()?; } - Ok(Self(ident)) + Ok(Self(config_path)) } } -/// Parse for `IsType<::RuntimeEvent>` and retrieve `$ident` -pub struct IsTypeBoundEventParse(syn::Ident); +/// Parse for `IsType<::RuntimeEvent>` and retrieve `$path` +pub struct IsTypeBoundEventParse(syn::Path); impl syn::parse::Parse for IsTypeBoundEventParse { fn parse(input: syn::parse::ParseStream) -> syn::Result { @@ -191,15 +190,13 @@ impl syn::parse::Parse for IsTypeBoundEventParse { input.parse::()?; input.parse::()?; input.parse::()?; - let ident = input.parse::()?; - input.parse::()?; - input.parse::()?; + let config_path = input.parse::()?; input.parse::]>()?; input.parse::()?; input.parse::()?; input.parse::]>()?; - Ok(Self(ident)) + Ok(Self(config_path)) } } @@ -237,7 +234,7 @@ impl syn::parse::Parse for FromEventParse { /// Check if trait_item is `type RuntimeEvent`, if so checks its bounds are those expected. /// (Event type is reserved type) fn check_event_type( - frame_system: &syn::Ident, + frame_system: &syn::Path, trait_item: &syn::TraitItem, trait_has_instance: bool, ) -> syn::Result { @@ -252,15 +249,28 @@ fn check_event_type( // Check bound contains IsType and From let has_is_type_bound = type_.bounds.iter().any(|s| { - syn::parse2::(s.to_token_stream()) - .map_or(false, |b| b.0 == *frame_system) + syn::parse2::(s.to_token_stream()).map_or(false, |b| { + let mut expected_system_config = if is_using_frame_crate(&frame_system) { + // in this case we know that the only valid frame_system path is one that is + // `frame_system`, as `frame` re-exports it as such. + let fixed_frame_system = + syn::parse2::(quote::quote!(frame_system)) + .expect("is a valid path; qed"); + fixed_frame_system + } else { + frame_system.clone() + }; + expected_system_config + .segments + .push(syn::PathSegment::from(syn::Ident::new("Config", b.0.span()))); + b.0 == expected_system_config + }) }); if !has_is_type_bound { let msg = format!( "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ - bound: `IsType<::RuntimeEvent>`", - frame_system, + bound: `IsType<::RuntimeEvent>`" ); return Err(syn::Error::new(type_.span(), msg)) } @@ -311,7 +321,7 @@ pub fn replace_self_by_t(input: proc_macro2::TokenStream) -> proc_macro2::TokenS impl ConfigDef { pub fn try_from( - frame_system: &syn::Ident, + frame_system: &syn::Path, attr_span: proc_macro2::Span, index: usize, item: &mut syn::Item, @@ -352,8 +362,32 @@ impl ConfigDef { }; let has_frame_system_supertrait = item.supertraits.iter().any(|s| { - syn::parse2::(s.to_token_stream()) - .map_or(false, |b| b.0 == *frame_system) + syn::parse2::(s.to_token_stream()).map_or(false, |b| { + let mut expected_system_config = if is_using_frame_crate(&frame_system) { + // in this case we know that the only valid supertrait is one that is + // `frame_system::Config`, as `frame` re-exports it as such. + let fixed_frame_system = syn::parse2::(quote::quote!(frame_system)) + .expect("is a valid path; qed"); + fixed_frame_system + } else { + // a possible renamed frame-system, which is a direct dependency. + frame_system.clone() + }; + expected_system_config + .segments + .push(syn::PathSegment::from(syn::Ident::new("Config", b.span()))); + // the parse path might be something like `frame_system::Config<...>`, so we + // only compare the idents along the path. + expected_system_config + .segments + .into_iter() + .map(|ps| ps.ident) + .collect::>() == b + .segments + .into_iter() + .map(|ps| ps.ident) + .collect::>() + }) }); let mut has_event_type = false; @@ -461,7 +495,8 @@ impl ConfigDef { (try `pub trait Config: frame_system::Config {{ ...` or \ `pub trait Config: frame_system::Config {{ ...`). \ To disable this check, use `#[pallet::disable_frame_system_supertrait_check]`", - frame_system, found, + frame_system.to_token_stream(), + found, ); return Err(syn::Error::new(item.span(), msg)) } diff --git a/substrate/frame/support/procedural/src/pallet/parse/mod.rs b/substrate/frame/support/procedural/src/pallet/parse/mod.rs index 0f5e5f1136610..590236f09bacd 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/mod.rs @@ -60,8 +60,8 @@ pub struct Def { pub extra_constants: Option, pub composites: Vec, pub type_values: Vec, - pub frame_system: syn::Ident, - pub frame_support: syn::Ident, + pub frame_system: syn::Path, + pub frame_support: syn::Path, pub dev_mode: bool, } diff --git a/substrate/frame/support/procedural/src/pallet_error.rs b/substrate/frame/support/procedural/src/pallet_error.rs index 7fd02240a628a..e3d7257e345f0 100644 --- a/substrate/frame/support/procedural/src/pallet_error.rs +++ b/substrate/frame/support/procedural/src/pallet_error.rs @@ -111,7 +111,7 @@ pub fn derive_pallet_error(input: proc_macro::TokenStream) -> proc_macro::TokenS fn generate_field_types( field: &syn::Field, - scrate: &syn::Ident, + scrate: &syn::Path, ) -> syn::Result> { let attrs = &field.attrs; @@ -143,7 +143,7 @@ fn generate_field_types( fn generate_variant_field_types( variant: &syn::Variant, - scrate: &syn::Ident, + scrate: &syn::Path, ) -> syn::Result>> { let attrs = &variant.attrs; diff --git a/substrate/frame/support/procedural/src/storage_alias.rs b/substrate/frame/support/procedural/src/storage_alias.rs index a3f21806e18b9..18bc1f15a368a 100644 --- a/substrate/frame/support/procedural/src/storage_alias.rs +++ b/substrate/frame/support/procedural/src/storage_alias.rs @@ -199,7 +199,7 @@ impl StorageType { /// Generate the actual type declaration. fn generate_type_declaration( &self, - crate_: &Ident, + crate_: &syn::Path, storage_instance: &StorageInstance, storage_name: &Ident, storage_generics: Option<&SimpleGenerics>, @@ -527,7 +527,7 @@ struct StorageInstance { /// Generate the [`StorageInstance`] for the storage alias. fn generate_storage_instance( - crate_: &Ident, + crate_: &syn::Path, storage_name: &Ident, storage_generics: Option<&SimpleGenerics>, storage_where_clause: Option<&WhereClause>, diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 541accc8ab96a..1fcabcace753d 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -46,24 +46,50 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { } } +/// Check if the output of [`generate_crate_access_2018`] (or generally another path) is using the +/// `frame` crate or not. +pub fn is_using_frame_crate(path: &syn::Path) -> bool { + path.segments.first().map(|s| s.ident == "frame").unwrap_or(false) +} + /// Generate the crate access for the crate using 2018 syntax. /// -/// for `frame-support` output will for example be `frame_support`. -pub fn generate_crate_access_2018(def_crate: &str) -> Result { - match crate_name(def_crate) { +/// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find +/// `` directly. +pub fn generate_crate_access_2018(def_crate: &str) -> Result { + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); + let path = syn::parse_str::(&path)?; + return Ok(path) + } + + let indent = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); Ok(syn::Ident::new(&name, Span::call_site())) }, Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), Err(e) => Err(Error::new(Span::call_site(), e)), - } + }?; + + Ok(syn::Path::from(indent)) } /// Generates the hidden includes that are required to make the macro independent from its scope. pub fn generate_hidden_includes(unique_id: &str, def_crate: &str) -> TokenStream { let mod_name = generate_hidden_includes_mod_name(unique_id); + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); + let path = syn::parse_str::(&path).expect("is a valid path; qed"); + return quote::quote!( + #[doc(hidden)] + mod #mod_name { + pub use #path as hidden_include; + } + ) + } + match crate_name(def_crate) { Ok(FoundCrate::Itself) => quote!(), Ok(FoundCrate::Name(name)) => { From 933fd3f1b21d1474d3a50410376e457e0d4580bd Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 8 Sep 2023 18:06:29 +0200 Subject: [PATCH 02/33] fix clippy --- .../frame/support/procedural/src/pallet/parse/config.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 0ed8204724481..84911fcf8f910 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -268,10 +268,8 @@ fn check_event_type( }); if !has_is_type_bound { - let msg = format!( - "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ - bound: `IsType<::RuntimeEvent>`" - ); + let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ + bound: `IsType<::RuntimeEvent>`".to_string(); return Err(syn::Error::new(type_.span(), msg)) } From dc43fa52e816c1009c674dadec011cac4cd5f1b6 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 15:26:57 +0200 Subject: [PATCH 03/33] add path changes to frame_support --- .../procedural/src/construct_runtime/mod.rs | 6 +++--- .../support/procedural/src/pallet/expand/error.rs | 8 ++++---- .../src/pallet/expand/tt_default_parts.rs | 8 ++++---- .../support/procedural/src/pallet/parse/config.rs | 15 --------------- .../frame/support/procedural/src/tt_macro.rs | 13 ++++--------- 5 files changed, 15 insertions(+), 35 deletions(-) diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index f42dd837e3a95..743136d74ddea 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -282,7 +282,7 @@ fn construct_runtime_implicit_to_explicit( expansion = quote::quote!( #frame_support::__private::tt_call! { macro = [{ #pallet_path::tt_default_parts }] - frame_support = [{ #frame_support }] + your_tt_return = [{ #frame_support::__private::tt_return }] ~~> #frame_support::match_and_insert! { target = [{ #expansion }] pattern = [{ #pallet_name: #pallet_path #pallet_instance }] @@ -318,7 +318,7 @@ fn construct_runtime_explicit_to_explicit_expanded( expansion = quote::quote!( #frame_support::__private::tt_call! { macro = [{ #pallet_path::tt_extra_parts }] - frame_support = [{ #frame_support }] + your_tt_return = [{ #frame_support::__private::tt_return }] ~~> #frame_support::match_and_insert! { target = [{ #expansion }] pattern = [{ #pallet_name: #pallet_path #pallet_instance }] @@ -783,7 +783,7 @@ fn decl_static_assertions( quote! { #scrate::__private::tt_call! { macro = [{ #path::tt_error_token }] - frame_support = [{ #scrate }] + your_tt_return = [{ #scrate::__private::tt_return }] ~~> #scrate::assert_error_encoded_size! { path = [{ #path }] runtime = [{ #runtime }] diff --git a/substrate/frame/support/procedural/src/pallet/expand/error.rs b/substrate/frame/support/procedural/src/pallet/expand/error.rs index d3aa0b762bc52..877489fd6057b 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/error.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/error.rs @@ -42,9 +42,9 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { macro_rules! #error_token_unique_id { { $caller:tt - frame_support = [{ $($frame_support:ident)::* }] + your_tt_return = [{ $my_tt_return:path }] } => { - $($frame_support::)*__private::tt_return! { + $my_tt_return! { $caller } }; @@ -170,9 +170,9 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { macro_rules! #error_token_unique_id { { $caller:tt - frame_support = [{ $($frame_support:ident)::* }] + your_tt_return = [{ $my_tt_return:path }] } => { - $($frame_support::)*__private::tt_return! { + $my_tt_return! { $caller error = [{ #error_ident }] } 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 86db56c776dfe..7621a56b04133 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 @@ -94,9 +94,9 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { macro_rules! #default_parts_unique_id { { $caller:tt - frame_support = [{ $($frame_support:ident)::* }] + your_tt_return = [{ $my_tt_return:path }] } => { - $($frame_support)*::__private::tt_return! { + $my_tt_return! { $caller tokens = [{ expanded::{ @@ -124,9 +124,9 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { macro_rules! #extra_parts_unique_id { { $caller:tt - frame_support = [{ $($frame_support:ident)::* }] + your_tt_return = [{ $my_tt_return:path }] } => { - $($frame_support)*::__private::tt_return! { + $my_tt_return! { $caller tokens = [{ expanded::{ diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 84911fcf8f910..9b014065ab0cb 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -165,21 +165,6 @@ pub struct PalletAttr { typ: PalletAttrType, } -/// Prase for `$path`, returning the whole path. -pub struct ConfigBoundParse(syn::Path); - -impl syn::parse::Parse for ConfigBoundParse { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - let config_path = input.parse::()?; - - if input.peek(syn::token::Lt) { - input.parse::()?; - } - - Ok(Self(config_path)) - } -} - /// Parse for `IsType<::RuntimeEvent>` and retrieve `$path` pub struct IsTypeBoundEventParse(syn::Path); diff --git a/substrate/frame/support/procedural/src/tt_macro.rs b/substrate/frame/support/procedural/src/tt_macro.rs index 01611f5dc4a4d..d3712742189f8 100644 --- a/substrate/frame/support/procedural/src/tt_macro.rs +++ b/substrate/frame/support/procedural/src/tt_macro.rs @@ -18,7 +18,6 @@ //! Implementation of the `create_tt_return_macro` macro use crate::COUNTER; -use frame_support_procedural_tools::generate_crate_access_2018; use proc_macro2::{Ident, TokenStream}; use quote::format_ident; @@ -65,9 +64,9 @@ impl syn::parse::Parse for CreateTtReturnMacroDef { /// macro_rules! my_tt_macro { /// { /// $caller:tt -/// $(frame_support = [{ $($frame_support:ident)::* }])? +/// $(your_tt_return = [{ $my_tt_return:path }])? /// } => { -/// frame_support::__private::tt_return! { +/// $my_tt_return! { /// $caller /// foo = [{ bar }] /// } @@ -78,10 +77,6 @@ pub fn create_tt_return_macro(input: proc_macro::TokenStream) -> proc_macro::Tok let CreateTtReturnMacroDef { name, args } = syn::parse_macro_input!(input as CreateTtReturnMacroDef); - let frame_support = match generate_crate_access_2018("frame-support") { - Ok(i) => i, - Err(e) => return e.into_compile_error().into(), - }; let (keys, values): (Vec<_>, Vec<_>) = args.into_iter().unzip(); let count = COUNTER.with(|counter| counter.borrow_mut().inc()); let unique_name = format_ident!("{}_{}", name, count); @@ -92,9 +87,9 @@ pub fn create_tt_return_macro(input: proc_macro::TokenStream) -> proc_macro::Tok macro_rules! #unique_name { { $caller:tt - $(frame_support = [{ $($frame_support:ident)::* }])? + $(your_tt_return = [{ $my_tt_macro:path }])? } => { - #frame_support::__private::tt_return! { + $my_tt_return! { $caller #( #keys = [{ #values }] From 16668ca6e8297a7a202a347556b821c22f0ef47d Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 16:38:24 +0200 Subject: [PATCH 04/33] add frame conditional --- .../primitives/api/proc-macro/src/utils.rs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index c9389154bbf40..917f7a2b1e5de 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -15,23 +15,25 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::common::API_VERSION_ATTRIBUTE; +use inflector::Inflector; use proc_macro2::{Span, TokenStream}; - +use proc_macro_crate::{crate_name, FoundCrate}; +use quote::{format_ident, quote, ToTokens}; use syn::{ parse_quote, spanned::Spanned, token::And, Attribute, Error, FnArg, GenericArgument, Ident, ImplItem, ItemImpl, Pat, Path, PathArguments, Result, ReturnType, Signature, Type, TypePath, }; -use quote::{format_ident, quote}; - -use proc_macro_crate::{crate_name, FoundCrate}; - -use crate::common::API_VERSION_ATTRIBUTE; - -use inflector::Inflector; - /// Generates the access to the `sc_client` crate. pub fn generate_crate_access() -> TokenStream { + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + // TODO: add test to make sure `frame` always contains `frame::deps::sp_api`. + // TODO: handle error. + let path = format!("{}::deps::{}", name, "sp_api"); + let path = syn::parse_str::(&path).unwrap(); + return path.into_token_stream() + } match crate_name("sp-api") { Ok(FoundCrate::Itself) => quote!(sp_api), Ok(FoundCrate::Name(renamed_name)) => { @@ -261,8 +263,6 @@ pub fn versioned_trait_name(trait_ident: &Ident, version: u64) -> Ident { /// Extract the documentation from the provided attributes. #[cfg(feature = "frame-metadata")] pub fn get_doc_literals(attrs: &[syn::Attribute]) -> Vec { - use quote::ToTokens; - attrs .iter() .filter_map(|attr| { From ebd13e3dc47f83149e95c44c6194c9dc0459a5c0 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 16:47:19 +0200 Subject: [PATCH 05/33] remove references to the frame-crate --- .../procedural/src/pallet/parse/config.rs | 24 +++-------------- .../frame/support/procedural/tools/src/lib.rs | 26 +------------------ .../primitives/api/proc-macro/src/utils.rs | 7 ----- 3 files changed, 4 insertions(+), 53 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 9b014065ab0cb..8688290677485 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -16,7 +16,7 @@ // limitations under the License. use super::helper; -use frame_support_procedural_tools::{get_doc_literals, is_using_frame_crate}; +use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; use syn::{spanned::Spanned, token, Token}; @@ -235,16 +235,7 @@ fn check_event_type( let has_is_type_bound = type_.bounds.iter().any(|s| { syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = if is_using_frame_crate(&frame_system) { - // in this case we know that the only valid frame_system path is one that is - // `frame_system`, as `frame` re-exports it as such. - let fixed_frame_system = - syn::parse2::(quote::quote!(frame_system)) - .expect("is a valid path; qed"); - fixed_frame_system - } else { - frame_system.clone() - }; + let mut expected_system_config = frame_system.clone(); expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", b.0.span()))); @@ -346,16 +337,7 @@ impl ConfigDef { let has_frame_system_supertrait = item.supertraits.iter().any(|s| { syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = if is_using_frame_crate(&frame_system) { - // in this case we know that the only valid supertrait is one that is - // `frame_system::Config`, as `frame` re-exports it as such. - let fixed_frame_system = syn::parse2::(quote::quote!(frame_system)) - .expect("is a valid path; qed"); - fixed_frame_system - } else { - // a possible renamed frame-system, which is a direct dependency. - frame_system.clone() - }; + let mut expected_system_config = frame_system.clone(); expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", b.span()))); diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 1fcabcace753d..05c22d4a181c9 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -46,23 +46,10 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { } } -/// Check if the output of [`generate_crate_access_2018`] (or generally another path) is using the -/// `frame` crate or not. -pub fn is_using_frame_crate(path: &syn::Path) -> bool { - path.segments.first().map(|s| s.ident == "frame").unwrap_or(false) -} - /// Generate the crate access for the crate using 2018 syntax. /// -/// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find -/// `` directly. +/// for `frame-support` output will for example be `frame_support`. pub fn generate_crate_access_2018(def_crate: &str) -> Result { - if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { - let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); - let path = syn::parse_str::(&path)?; - return Ok(path) - } - let indent = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); @@ -79,17 +66,6 @@ pub fn generate_crate_access_2018(def_crate: &str) -> Result { pub fn generate_hidden_includes(unique_id: &str, def_crate: &str) -> TokenStream { let mod_name = generate_hidden_includes_mod_name(unique_id); - if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { - let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); - let path = syn::parse_str::(&path).expect("is a valid path; qed"); - return quote::quote!( - #[doc(hidden)] - mod #mod_name { - pub use #path as hidden_include; - } - ) - } - match crate_name(def_crate) { Ok(FoundCrate::Itself) => quote!(), Ok(FoundCrate::Name(name)) => { diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index 917f7a2b1e5de..283626b318306 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -27,13 +27,6 @@ use syn::{ /// Generates the access to the `sc_client` crate. pub fn generate_crate_access() -> TokenStream { - if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { - // TODO: add test to make sure `frame` always contains `frame::deps::sp_api`. - // TODO: handle error. - let path = format!("{}::deps::{}", name, "sp_api"); - let path = syn::parse_str::(&path).unwrap(); - return path.into_token_stream() - } match crate_name("sp-api") { Ok(FoundCrate::Itself) => quote!(sp_api), Ok(FoundCrate::Name(renamed_name)) => { From 270a6b7d141070f61ccda2a5104e0f701f4dd0f0 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 17:25:25 +0200 Subject: [PATCH 06/33] update fn description --- substrate/frame/support/procedural/tools/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 05c22d4a181c9..5f5492fb76833 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -48,7 +48,7 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { /// Generate the crate access for the crate using 2018 syntax. /// -/// for `frame-support` output will for example be `frame_support`. +/// It tries to find ``. pub fn generate_crate_access_2018(def_crate: &str) -> Result { let indent = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { From 8be65aa168b4180345151f1fb7f3b1f21bbd6819 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 17:28:28 +0200 Subject: [PATCH 07/33] update fn description --- substrate/frame/support/procedural/tools/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 5f5492fb76833..f47ca1d5b5582 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -48,7 +48,7 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { /// Generate the crate access for the crate using 2018 syntax. /// -/// It tries to find ``. +/// It tries to find `` and returns it as a path. pub fn generate_crate_access_2018(def_crate: &str) -> Result { let indent = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { From 850a77eadb8d6a2a785692f301d896549512dec8 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 11 Sep 2023 20:09:19 +0200 Subject: [PATCH 08/33] make benchmarks to use generate_crate_access_2018 --- .../frame/support/procedural/src/benchmark.rs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/substrate/frame/support/procedural/src/benchmark.rs b/substrate/frame/support/procedural/src/benchmark.rs index 6f8f1d155e1e5..6a8cbb50dca2f 100644 --- a/substrate/frame/support/procedural/src/benchmark.rs +++ b/substrate/frame/support/procedural/src/benchmark.rs @@ -419,6 +419,7 @@ pub fn benchmarks( }; let krate = generate_crate_access_2018("frame-benchmarking")?; + let frame_system = generate_crate_access_2018("frame-system")?; // benchmark name variables let benchmark_names_str: Vec = benchmark_names.iter().map(|n| n.to_string()).collect(); @@ -488,7 +489,7 @@ pub fn benchmarks( } #[cfg(any(feature = "runtime-benchmarks", test))] impl<#type_impl_generics> #krate::Benchmarking for Pallet<#type_use_generics> - where T: frame_system::Config, #where_clause + where T: #frame_system::Config, #where_clause { fn benchmarks( extra: bool, @@ -535,7 +536,7 @@ pub fn benchmarks( _ => return Err("Could not find extrinsic.".into()), }; let mut whitelist = whitelist.to_vec(); - let whitelisted_caller_key = as #krate::__private::storage::StorageMap<_, _,>>::hashed_key_for( #krate::whitelisted_caller::() @@ -571,8 +572,8 @@ pub fn benchmarks( >::instance(&selected_benchmark, c, verify)?; // Set the block number to at least 1 so events are deposited. - if #krate::__private::Zero::is_zero(&frame_system::Pallet::::block_number()) { - frame_system::Pallet::::set_block_number(1u32.into()); + if #krate::__private::Zero::is_zero(&#frame_system::Pallet::::block_number()) { + #frame_system::Pallet::::set_block_number(1u32.into()); } // Commit the externalities to the database, flushing the DB cache. @@ -654,7 +655,7 @@ pub fn benchmarks( } #[cfg(test)] - impl<#type_impl_generics> Pallet<#type_use_generics> where T: ::frame_system::Config, #where_clause { + impl<#type_impl_generics> Pallet<#type_use_generics> where T: #frame_system::Config, #where_clause { /// Test a particular benchmark by name. /// /// This isn't called `test_benchmark_by_name` just in case some end-user eventually @@ -723,6 +724,10 @@ fn expand_benchmark( Ok(ident) => ident, Err(err) => return err.to_compile_error().into(), }; + let frame_system = match generate_crate_access_2018("frame-system") { + Ok(path) => path, + Err(err) => return err.to_compile_error().into(), + }; let codec = quote!(#krate::__private::codec); let traits = quote!(#krate::__private::traits); let setup_stmts = benchmark_def.setup_stmts; @@ -762,7 +767,7 @@ fn expand_benchmark( Expr::Cast(t) => { let ty = t.ty.clone(); quote! { - <::RuntimeOrigin as From<#ty>>::from(#origin); + <::RuntimeOrigin as From<#ty>>::from(#origin); } }, _ => quote! { @@ -932,7 +937,7 @@ fn expand_benchmark( } #[cfg(test)] - impl<#type_impl_generics> Pallet<#type_use_generics> where T: ::frame_system::Config, #where_clause { + impl<#type_impl_generics> Pallet<#type_use_generics> where T: #frame_system::Config, #where_clause { #[allow(unused)] fn #test_ident() -> Result<(), #krate::BenchmarkError> { let selected_benchmark = SelectedBenchmark::#name; @@ -951,8 +956,8 @@ fn expand_benchmark( >::instance(&selected_benchmark, &c, true)?; // Set the block number to at least 1 so events are deposited. - if #krate::__private::Zero::is_zero(&frame_system::Pallet::::block_number()) { - frame_system::Pallet::::set_block_number(1u32.into()); + if #krate::__private::Zero::is_zero(&#frame_system::Pallet::::block_number()) { + #frame_system::Pallet::::set_block_number(1u32.into()); } // Run execution + verification From 5ae6e0741fa7a2dad612562ecc83f8fbf19e3e13 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Tue, 12 Sep 2023 09:51:02 +0200 Subject: [PATCH 09/33] undo unrelated changes --- substrate/primitives/api/proc-macro/src/utils.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index 283626b318306..423bd35747d39 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -15,16 +15,21 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::common::API_VERSION_ATTRIBUTE; -use inflector::Inflector; use proc_macro2::{Span, TokenStream}; -use proc_macro_crate::{crate_name, FoundCrate}; -use quote::{format_ident, quote, ToTokens}; + use syn::{ parse_quote, spanned::Spanned, token::And, Attribute, Error, FnArg, GenericArgument, Ident, ImplItem, ItemImpl, Pat, Path, PathArguments, Result, ReturnType, Signature, Type, TypePath, }; +use quote::{format_ident, quote}; + +use proc_macro_crate::{crate_name, FoundCrate}; + +use crate::common::API_VERSION_ATTRIBUTE; + +use inflector::Inflector; + /// Generates the access to the `sc_client` crate. pub fn generate_crate_access() -> TokenStream { match crate_name("sp-api") { @@ -256,6 +261,8 @@ pub fn versioned_trait_name(trait_ident: &Ident, version: u64) -> Ident { /// Extract the documentation from the provided attributes. #[cfg(feature = "frame-metadata")] pub fn get_doc_literals(attrs: &[syn::Attribute]) -> Vec { + use quote::ToTokens; + attrs .iter() .filter_map(|attr| { From 04dc503342e8ee1e06435ca16d93485c1a1cc74f Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Tue, 12 Sep 2023 09:51:47 +0200 Subject: [PATCH 10/33] undo unrelated changes --- substrate/primitives/api/proc-macro/src/utils.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index 423bd35747d39..c9389154bbf40 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -262,7 +262,7 @@ pub fn versioned_trait_name(trait_ident: &Ident, version: u64) -> Ident { #[cfg(feature = "frame-metadata")] pub fn get_doc_literals(attrs: &[syn::Attribute]) -> Vec { use quote::ToTokens; - + attrs .iter() .filter_map(|attr| { From 95444ae8b96de851c70bef7ee04bdceeca78c9ea Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Tue, 12 Sep 2023 16:21:15 +0200 Subject: [PATCH 11/33] update macro description --- .../procedural/src/pallet/expand/tt_default_parts.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) 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 7621a56b04133..c9a776ee24752 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,10 +85,8 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { // wrapped inside of braces and finally prepended with double colons, to the caller inside // of a key named `tokens`. // - // We need to accept a frame_support argument here, because this macro gets expanded on the - // crate that called the `construct_runtime!` macro, and said crate may have renamed - // frame-support, and so we need to pass in the frame-support path that said crate - // recognizes. + // We need to accept a path argument here, because this macro gets expanded on the + // crate that called the `construct_runtime!` macro, and the actual path is unknown. #[macro_export] #[doc(hidden)] macro_rules! #default_parts_unique_id { @@ -112,7 +110,7 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { pub use #default_parts_unique_id as tt_default_parts; - // This macro is similar to the `tt_default_parts!`. It expands the pallets thare are declared + // This macro is similar to the `tt_default_parts!`. It expands the pallets that are declared // explicitly (`System: frame_system::{Pallet, Call}`) with extra parts. // // For example, after expansion an explicit pallet would look like: From 6a773d0db89d718a487faed8674a62a0f08995ca Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Tue, 12 Sep 2023 19:48:01 +0200 Subject: [PATCH 12/33] refactor `generate_crate_access` --- substrate/frame/support/procedural/tools/src/lib.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index f47ca1d5b5582..88496bb6f7b14 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -39,7 +39,11 @@ fn generate_hidden_includes_mod_name(unique_id: &str) -> Ident { /// Generates the access to the `frame-support` crate. pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { if std::env::var("CARGO_PKG_NAME").unwrap() == def_crate { - quote::quote!(frame_support) + let frame_support = match generate_crate_access_2018("frame-support") { + Ok(c) => c, + Err(e) => return e.into_compile_error().into(), + }; + quote::quote!(#frame_support) } else { let mod_name = generate_hidden_includes_mod_name(unique_id); quote::quote!( self::#mod_name::hidden_include ) From bc1755765449ccff24e5a66bb76e073905c6e48b Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Wed, 13 Sep 2023 13:58:50 +0200 Subject: [PATCH 13/33] unhardcode codec import --- substrate/frame/support/procedural/src/key_prefix.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/src/key_prefix.rs b/substrate/frame/support/procedural/src/key_prefix.rs index 6f793d0e37bde..9c6d75e4a0963 100644 --- a/substrate/frame/support/procedural/src/key_prefix.rs +++ b/substrate/frame/support/procedural/src/key_prefix.rs @@ -15,6 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use frame_support_procedural_tools::generate_crate_access_2018; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Result}; @@ -27,6 +28,7 @@ pub fn impl_key_prefix_for_tuples(input: proc_macro::TokenStream) -> Result Result),* > HasReversibleKeyPrefix<( #( #kargs, )* )> for ( #( Key<#hashers, #current_tuple>, )* ) { - fn decode_partial_key(key_material: &[u8]) -> Result { + fn decode_partial_key(key_material: &[u8]) -> Result< + Self::Suffix, + #frame_support::__private::codec::Error, + > { <#suffix_keygen>::decode_final_key(key_material).map(|k| k.0) } } From 6d9887b8aa22b5b8bdf763b23297fe21921de664 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 14 Sep 2023 16:33:17 +0200 Subject: [PATCH 14/33] bring in hypotetical frame crate --- .../procedural/src/pallet/parse/config.rs | 24 ++++++++++++++++--- .../frame/support/procedural/tools/src/lib.rs | 16 ++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 8688290677485..e1af7ca252f04 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -16,7 +16,7 @@ // limitations under the License. use super::helper; -use frame_support_procedural_tools::get_doc_literals; +use frame_support_procedural_tools::{get_doc_literals, is_using_frame_crate}; use quote::ToTokens; use syn::{spanned::Spanned, token, Token}; @@ -235,7 +235,16 @@ fn check_event_type( let has_is_type_bound = type_.bounds.iter().any(|s| { syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = frame_system.clone(); + let mut expected_system_config = if is_using_frame_crate(&frame_system) { + // in this case, we know that the only valid frame_system path is one that + // is `frame_system`, as `frame` re-exports it as such. + let fixed_frame_system = + syn::parse2::(quote::quote!(frame_system)) + .expect("is a valid path; qed"); + fixed_frame_system + } else { + frame_system.clone() + }; expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", b.0.span()))); @@ -337,7 +346,16 @@ impl ConfigDef { let has_frame_system_supertrait = item.supertraits.iter().any(|s| { syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = frame_system.clone(); + let mut expected_system_config = if is_using_frame_crate(&frame_system) { + // in this case, we know that the only valid supertrait is one that + // `frame_system::Config`, as `frame` re-exports it as such. + let fixed_frame_system = syn::parse2::(quote::quote!(frame_system)) + .expect("is a valid path; qed"); + fixed_frame_system + } else { + // a possibly renamed frame-system, which is a direct dependency. + frame_system.clone() + }; expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", b.span()))); diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 88496bb6f7b14..e67ef578e12c4 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -50,10 +50,24 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { } } +/// Check if a path is using the `frame` crate or not. +/// +/// This will usually check the output of [`generate_crate_access_2018`]. +pub fn is_using_frame_crate(path: &syn::Path) -> bool { + path.segments.first().map(|s| s.ident == "frame").unwrap_or(false) +} + /// Generate the crate access for the crate using 2018 syntax. /// -/// It tries to find `` and returns it as a path. +/// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find +/// `` directly. pub fn generate_crate_access_2018(def_crate: &str) -> Result { + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); + let path = syn::parse_str::(&path)?; + return Ok(path) + } + let indent = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); From 35747a1e97d089e05bdf98c4faf8a85148c1f945 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 15 Sep 2023 12:32:38 +0200 Subject: [PATCH 15/33] refactor expected_system_config and add tests --- .../procedural/src/pallet/parse/config.rs | 121 ++++++++++++------ .../support/test/compile_pass/Cargo.toml | 4 +- .../support/test/compile_pass/src/lib.rs | 4 +- 3 files changed, 84 insertions(+), 45 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index e1af7ca252f04..1a25b0e44299d 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -231,25 +231,11 @@ fn check_event_type( no generics nor where_clause"; return Err(syn::Error::new(trait_item.span(), msg)) } - // Check bound contains IsType and From + // Check bound contains IsType and From let has_is_type_bound = type_.bounds.iter().any(|s| { - syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = if is_using_frame_crate(&frame_system) { - // in this case, we know that the only valid frame_system path is one that - // is `frame_system`, as `frame` re-exports it as such. - let fixed_frame_system = - syn::parse2::(quote::quote!(frame_system)) - .expect("is a valid path; qed"); - fixed_frame_system - } else { - frame_system.clone() - }; - expected_system_config - .segments - .push(syn::PathSegment::from(syn::Ident::new("Config", b.0.span()))); - b.0 == expected_system_config - }) + syn::parse2::(s.to_token_stream()) + .map_or(false, |b| has_expected_system_config(b.0, frame_system)) }); if !has_is_type_bound { @@ -288,6 +274,39 @@ fn check_event_type( } } +fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool { + // check if `frame_system` is actually 'frame_system'. + if let None = path.segments.clone().into_iter().find(|s| s.ident == "frame_system") { + return false + } + + let mut expected_system_config = if is_using_frame_crate(&frame_system) { + // in this case, we know that the only valid frame_system path is one that + // is `frame_system`, as `frame` re-exports it as such. + let fixed_frame_system = + syn::parse2::(quote::quote!(frame_system)).expect("is a valid path; qed"); + fixed_frame_system + } else { + // a possibly renamed frame-system, which is a direct dependency. + frame_system.clone() + }; + + expected_system_config + .segments + .push(syn::PathSegment::from(syn::Ident::new("Config", path.span()))); + // the parse path might be something like `frame_system::Config<...>`, so we + // only compare the idents along the path. + expected_system_config + .segments + .into_iter() + .map(|ps| ps.ident) + .collect::>() == path + .segments + .into_iter() + .map(|ps| ps.ident) + .collect::>() +} + /// Replace ident `Self` by `T` pub fn replace_self_by_t(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream { input @@ -346,30 +365,7 @@ impl ConfigDef { let has_frame_system_supertrait = item.supertraits.iter().any(|s| { syn::parse2::(s.to_token_stream()).map_or(false, |b| { - let mut expected_system_config = if is_using_frame_crate(&frame_system) { - // in this case, we know that the only valid supertrait is one that - // `frame_system::Config`, as `frame` re-exports it as such. - let fixed_frame_system = syn::parse2::(quote::quote!(frame_system)) - .expect("is a valid path; qed"); - fixed_frame_system - } else { - // a possibly renamed frame-system, which is a direct dependency. - frame_system.clone() - }; - expected_system_config - .segments - .push(syn::PathSegment::from(syn::Ident::new("Config", b.span()))); - // the parse path might be something like `frame_system::Config<...>`, so we - // only compare the idents along the path. - expected_system_config - .segments - .into_iter() - .map(|ps| ps.ident) - .collect::>() == b - .segments - .into_iter() - .map(|ps| ps.ident) - .collect::>() + has_expected_system_config(b, frame_system) }) }); @@ -495,3 +491,46 @@ impl ConfigDef { }) } } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn has_expected_system_config_works() { + let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); + let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); + assert!(has_expected_system_config(path, &frame_system)); + } + #[test] + fn has_expected_system_config_works_with_generics() { + let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); + let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); + assert!(has_expected_system_config(path, &frame_system)); + } + #[test] + fn has_expected_system_config_works_with_frame() { + let frame_system = + syn::parse2::(quote::quote!(frame::deps::frame_system)).unwrap(); + let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); + assert!(has_expected_system_config(path, &frame_system)); + } + #[test] + fn has_expected_system_config_unexpected_frame_system() { + let frame_system = + syn::parse2::(quote::quote!(framez::deps::frame_system)).unwrap(); + let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } + #[test] + fn has_expected_system_config_unexpected_path() { + let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); + let path = syn::parse2::(quote::quote!(frame_system::ConfigSystem)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } + #[test] + fn has_expected_system_config_not_frame_system() { + let frame_system = syn::parse2::(quote::quote!(something)).unwrap(); + let path = syn::parse2::(quote::quote!(something::Config)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } +} diff --git a/substrate/frame/support/test/compile_pass/Cargo.toml b/substrate/frame/support/test/compile_pass/Cargo.toml index 9c165cd03e866..b1ba8322337e0 100644 --- a/substrate/frame/support/test/compile_pass/Cargo.toml +++ b/substrate/frame/support/test/compile_pass/Cargo.toml @@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } renamed-frame-support = { package = "frame-support", path = "../..", default-features = false} -frame-system = { path = "../../../system", default-features = false} +renamed-frame-system = { package = "frame-system", path = "../../../system", default-features = false} sp-core = { path = "../../../../primitives/core", default-features = false} sp-runtime = { path = "../../../../primitives/runtime", default-features = false} sp-version = { path = "../../../../primitives/version", default-features = false} @@ -24,7 +24,7 @@ sp-version = { path = "../../../../primitives/version", default-features = false default = [ "std" ] std = [ "codec/std", - "frame-system/std", + "renamed-frame-system/std", "renamed-frame-support/std", "scale-info/std", "sp-core/std", diff --git a/substrate/frame/support/test/compile_pass/src/lib.rs b/substrate/frame/support/test/compile_pass/src/lib.rs index bf90d73acb320..a453dd88440b5 100644 --- a/substrate/frame/support/test/compile_pass/src/lib.rs +++ b/substrate/frame/support/test/compile_pass/src/lib.rs @@ -50,7 +50,7 @@ parameter_types! { pub const Version: RuntimeVersion = VERSION; } -impl frame_system::Config for Runtime { +impl renamed_frame_system::Config for Runtime { type BaseCallFilter = Everything; type BlockWeights = (); type BlockLength = (); @@ -82,6 +82,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic Date: Fri, 15 Sep 2023 10:52:56 +0000 Subject: [PATCH 16/33] ".git/.scripts/commands/fmt/fmt.sh" --- .../procedural/src/pallet/parse/config.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 1a25b0e44299d..d77b65ab54b97 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -292,19 +292,16 @@ fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool }; expected_system_config - .segments - .push(syn::PathSegment::from(syn::Ident::new("Config", path.span()))); + .segments + .push(syn::PathSegment::from(syn::Ident::new("Config", path.span()))); // the parse path might be something like `frame_system::Config<...>`, so we // only compare the idents along the path. expected_system_config .segments .into_iter() .map(|ps| ps.ident) - .collect::>() == path - .segments - .into_iter() - .map(|ps| ps.ident) - .collect::>() + .collect::>() == + path.segments.into_iter().map(|ps| ps.ident).collect::>() } /// Replace ident `Self` by `T` @@ -364,9 +361,8 @@ impl ConfigDef { }; let has_frame_system_supertrait = item.supertraits.iter().any(|s| { - syn::parse2::(s.to_token_stream()).map_or(false, |b| { - has_expected_system_config(b, frame_system) - }) + syn::parse2::(s.to_token_stream()) + .map_or(false, |b| has_expected_system_config(b, frame_system)) }); let mut has_event_type = false; From 10bf65ce9267fa5d465090b01dd0b8e33d7fd32f Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 15 Sep 2023 12:55:39 +0200 Subject: [PATCH 17/33] make zepter happy --- substrate/frame/support/test/compile_pass/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/test/compile_pass/Cargo.toml b/substrate/frame/support/test/compile_pass/Cargo.toml index b1ba8322337e0..167aec8a171c7 100644 --- a/substrate/frame/support/test/compile_pass/Cargo.toml +++ b/substrate/frame/support/test/compile_pass/Cargo.toml @@ -24,8 +24,8 @@ sp-version = { path = "../../../../primitives/version", default-features = false default = [ "std" ] std = [ "codec/std", - "renamed-frame-system/std", "renamed-frame-support/std", + "renamed-frame-system/std", "scale-info/std", "sp-core/std", "sp-runtime/std", From 97bfec49836c0aed5d719dd3867527f4057e9008 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 21 Sep 2023 16:59:16 +0200 Subject: [PATCH 18/33] improve comment --- substrate/frame/support/procedural/tools/src/lib.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index e67ef578e12c4..be988ab19a0e8 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -53,6 +53,8 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { /// Check if a path is using the `frame` crate or not. /// /// This will usually check the output of [`generate_crate_access_2018`]. +/// We want to know if whatever the `path` takes us to, is exported from `frame` or not. In that +/// case `path` would start with `frame`, something like `frame::x::y:z`. pub fn is_using_frame_crate(path: &syn::Path) -> bool { path.segments.first().map(|s| s.ident == "frame").unwrap_or(false) } From 6a07bb3bd27815538a040222ae2f1819b9782cc2 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 22 Sep 2023 17:58:31 +0200 Subject: [PATCH 19/33] add event_type_bound_system_config_assoc_type test --- .../procedural/src/pallet/parse/config.rs | 6 ++- .../pallet_ui/event_type_invalid_bound.rs | 3 +- ...ent_type_bound_system_config_assoc_type.rs | 44 +++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 substrate/frame/support/test/tests/pallet_ui/pass/event_type_bound_system_config_assoc_type.rs diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index d77b65ab54b97..142c15410b6d6 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -498,9 +498,11 @@ mod tests { assert!(has_expected_system_config(path, &frame_system)); } #[test] - fn has_expected_system_config_works_with_generics() { + fn has_expected_system_config_works_with_assoc_type() { let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); - let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame_system::Config)) + .unwrap(); assert!(has_expected_system_config(path, &frame_system)); } #[test] diff --git a/substrate/frame/support/test/tests/pallet_ui/event_type_invalid_bound.rs b/substrate/frame/support/test/tests/pallet_ui/event_type_invalid_bound.rs index 665d2a984cf04..34b563ffb6433 100644 --- a/substrate/frame/support/test/tests/pallet_ui/event_type_invalid_bound.rs +++ b/substrate/frame/support/test/tests/pallet_ui/event_type_invalid_bound.rs @@ -41,5 +41,4 @@ mod pallet { } } -fn main() { -} +fn main() {} diff --git a/substrate/frame/support/test/tests/pallet_ui/pass/event_type_bound_system_config_assoc_type.rs b/substrate/frame/support/test/tests/pallet_ui/pass/event_type_bound_system_config_assoc_type.rs new file mode 100644 index 0000000000000..0a70c4a5e68a8 --- /dev/null +++ b/substrate/frame/support/test/tests/pallet_ui/pass/event_type_bound_system_config_assoc_type.rs @@ -0,0 +1,44 @@ +// 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 { + use frame_support::pallet_prelude::{Hooks, IsType}; + use frame_system::pallet_prelude::BlockNumberFor; + + #[pallet::config] + pub trait Config: frame_system::Config { + type Bar: Clone + std::fmt::Debug + Eq; + type RuntimeEvent: IsType<::RuntimeEvent> + From>; + } + + #[pallet::pallet] + pub struct Pallet(core::marker::PhantomData); + + #[pallet::hooks] + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet {} + + #[pallet::event] + pub enum Event { + B { b: T::Bar }, + } +} + +fn main() {} From f303276417bd7fa4eeb4826654b4cc46573284f5 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 2 Oct 2023 10:54:13 +0300 Subject: [PATCH 20/33] implement review suggestions --- substrate/frame/support/procedural/src/benchmark.rs | 10 +++++----- .../support/procedural/src/construct_runtime/mod.rs | 8 ++++---- .../frame/support/procedural/src/crate_version.rs | 4 ++-- .../frame/support/procedural/src/key_prefix.rs | 4 ++-- substrate/frame/support/procedural/src/lib.rs | 10 +++++----- .../support/procedural/src/pallet/parse/config.rs | 2 +- .../support/procedural/src/pallet/parse/mod.rs | 6 +++--- .../frame/support/procedural/src/pallet_error.rs | 4 ++-- .../frame/support/procedural/src/storage_alias.rs | 4 ++-- .../frame/support/procedural/src/transactional.rs | 6 +++--- substrate/frame/support/procedural/tools/src/lib.rs | 13 ++++++------- 11 files changed, 35 insertions(+), 36 deletions(-) diff --git a/substrate/frame/support/procedural/src/benchmark.rs b/substrate/frame/support/procedural/src/benchmark.rs index 6a8cbb50dca2f..1c9d459de83b9 100644 --- a/substrate/frame/support/procedural/src/benchmark.rs +++ b/substrate/frame/support/procedural/src/benchmark.rs @@ -18,7 +18,7 @@ //! Home of the parsing and expansion code for the new pallet benchmarking syntax use derive_syn_parse::Parse; -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use proc_macro::TokenStream; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens}; @@ -418,8 +418,8 @@ pub fn benchmarks( true => quote!(T: Config, I: 'static), }; - let krate = generate_crate_access_2018("frame-benchmarking")?; - let frame_system = generate_crate_access_2018("frame-system")?; + let krate = generate_crate_access_from_frame_or_deps("frame-benchmarking")?; + let frame_system = generate_crate_access_from_frame_or_deps("frame-system")?; // benchmark name variables let benchmark_names_str: Vec = benchmark_names.iter().map(|n| n.to_string()).collect(); @@ -720,11 +720,11 @@ fn expand_benchmark( where_clause: TokenStream2, ) -> TokenStream2 { // set up variables needed during quoting - let krate = match generate_crate_access_2018("frame-benchmarking") { + let krate = match generate_crate_access_from_frame_or_deps("frame-benchmarking") { Ok(ident) => ident, Err(err) => return err.to_compile_error().into(), }; - let frame_system = match generate_crate_access_2018("frame-system") { + let frame_system = match generate_crate_access_from_frame_or_deps("frame-system") { Ok(path) => path, Err(err) => return err.to_compile_error().into(), }; diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 743136d74ddea..7b214c122d4b1 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -213,7 +213,7 @@ mod parse; use cfg_expr::Predicate; use frame_support_procedural_tools::{ - generate_crate_access, generate_crate_access_2018, generate_hidden_includes, + generate_crate_access, generate_crate_access_from_frame_or_deps, generate_hidden_includes, }; use itertools::Itertools; use parse::{ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration}; @@ -271,7 +271,7 @@ fn construct_runtime_implicit_to_explicit( input: TokenStream2, definition: ImplicitRuntimeDeclaration, ) -> Result { - let frame_support = generate_crate_access_2018("frame-support")?; + let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; let mut expansion = quote::quote!( #frame_support::construct_runtime! { #input } ); @@ -307,7 +307,7 @@ fn construct_runtime_explicit_to_explicit_expanded( input: TokenStream2, definition: ExplicitRuntimeDeclaration, ) -> Result { - let frame_support = generate_crate_access_2018("frame-support")?; + let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; let mut expansion = quote::quote!( #frame_support::construct_runtime! { #input } ); @@ -371,7 +371,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_crate_access_from_frame_or_deps("frame-system")?; let block = quote!(<#name as #frame_system::Config>::Block); let unchecked_extrinsic = quote!(<#block as #scrate::sp_runtime::traits::Block>::Extrinsic); diff --git a/substrate/frame/support/procedural/src/crate_version.rs b/substrate/frame/support/procedural/src/crate_version.rs index 3f728abdb0b03..eaaee860b9f08 100644 --- a/substrate/frame/support/procedural/src/crate_version.rs +++ b/substrate/frame/support/procedural/src/crate_version.rs @@ -18,7 +18,7 @@ //! Implementation of macros related to crate versioning. use super::get_cargo_env_var; -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use proc_macro2::{Span, TokenStream}; use syn::{Error, Result}; @@ -42,7 +42,7 @@ pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result("CARGO_PKG_VERSION_PATCH") .map_err(|_| create_error("Patch version needs to fit into `u8`"))?; - let crate_ = generate_crate_access_2018("frame-support")?; + let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; Ok(quote::quote! { #crate_::traits::CrateVersion { diff --git a/substrate/frame/support/procedural/src/key_prefix.rs b/substrate/frame/support/procedural/src/key_prefix.rs index 9c6d75e4a0963..a3f94eb4bbd80 100644 --- a/substrate/frame/support/procedural/src/key_prefix.rs +++ b/substrate/frame/support/procedural/src/key_prefix.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Result}; @@ -28,7 +28,7 @@ pub fn impl_key_prefix_for_tuples(input: proc_macro::TokenStream) -> Result TokenStream #[import_tokens_attr { format!( "{}::macro_magic", - match generate_crate_access_2018("frame-support") { + match generate_crate_access_from_frame_or_deps("frame-support") { Ok(path) => Ok(path), - Err(_) => generate_crate_access_2018("frame"), + Err(_) => generate_crate_access_from_frame_or_deps("frame"), } .expect("Failed to find either `frame-support` or `frame` in `Cargo.toml` dependencies.") .to_token_stream() @@ -1647,9 +1647,9 @@ pub fn pallet_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { #[import_tokens_attr { format!( "{}::macro_magic", - match generate_crate_access_2018("frame-support") { + match generate_crate_access_from_frame_or_deps("frame-support") { Ok(path) => Ok(path), - Err(_) => generate_crate_access_2018("frame"), + Err(_) => generate_crate_access_from_frame_or_deps("frame"), } .expect("Failed to find either `frame-support` or `frame` in `Cargo.toml` dependencies.") .to_token_stream() diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 142c15410b6d6..44a1b1fb74d5e 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -276,7 +276,7 @@ fn check_event_type( fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool { // check if `frame_system` is actually 'frame_system'. - if let None = path.segments.clone().into_iter().find(|s| s.ident == "frame_system") { + if path.segments.iter().all(|s| s.ident != "frame_system") { return false } diff --git a/substrate/frame/support/procedural/src/pallet/parse/mod.rs b/substrate/frame/support/procedural/src/pallet/parse/mod.rs index 590236f09bacd..c1aaf96557032 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/mod.rs @@ -37,7 +37,7 @@ pub mod type_value; pub mod validate_unsigned; use composite::{keyword::CompositeKeyword, CompositeDef}; -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use syn::spanned::Spanned; /// Parsed definition of a pallet. @@ -67,8 +67,8 @@ pub struct Def { impl Def { pub fn try_from(mut item: syn::ItemMod, dev_mode: bool) -> syn::Result { - let frame_system = generate_crate_access_2018("frame-system")?; - let frame_support = generate_crate_access_2018("frame-support")?; + let frame_system = generate_crate_access_from_frame_or_deps("frame-system")?; + let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; let item_span = item.span(); let items = &mut item diff --git a/substrate/frame/support/procedural/src/pallet_error.rs b/substrate/frame/support/procedural/src/pallet_error.rs index e3d7257e345f0..03c8689161841 100644 --- a/substrate/frame/support/procedural/src/pallet_error.rs +++ b/substrate/frame/support/procedural/src/pallet_error.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use quote::ToTokens; // Derive `PalletError` @@ -25,7 +25,7 @@ pub fn derive_pallet_error(input: proc_macro::TokenStream) -> proc_macro::TokenS Err(e) => return e.to_compile_error().into(), }; - let frame_support = match generate_crate_access_2018("frame-support") { + let frame_support = match generate_crate_access_from_frame_or_deps("frame-support") { Ok(c) => c, Err(e) => return e.into_compile_error().into(), }; diff --git a/substrate/frame/support/procedural/src/storage_alias.rs b/substrate/frame/support/procedural/src/storage_alias.rs index 18bc1f15a368a..f163986bc8d75 100644 --- a/substrate/frame/support/procedural/src/storage_alias.rs +++ b/substrate/frame/support/procedural/src/storage_alias.rs @@ -18,7 +18,7 @@ //! Implementation of the `storage_alias` attribute macro. use crate::counter_prefix; -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{ @@ -475,7 +475,7 @@ enum PrefixType { /// Implementation of the `storage_alias` attribute macro. pub fn storage_alias(attributes: TokenStream, input: TokenStream) -> Result { let input = syn::parse2::(input)?; - let crate_ = generate_crate_access_2018("frame-support")?; + let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; let prefix_type = if attributes.is_empty() { PrefixType::Compatibility diff --git a/substrate/frame/support/procedural/src/transactional.rs b/substrate/frame/support/procedural/src/transactional.rs index 23117ffa39c4e..5798969dee29c 100644 --- a/substrate/frame/support/procedural/src/transactional.rs +++ b/substrate/frame/support/procedural/src/transactional.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_2018; +use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; use proc_macro::TokenStream; use quote::quote; use syn::{ItemFn, Result}; @@ -23,7 +23,7 @@ use syn::{ItemFn, Result}; pub fn transactional(_attr: TokenStream, input: TokenStream) -> Result { let ItemFn { attrs, vis, sig, block } = syn::parse(input)?; - let crate_ = generate_crate_access_2018("frame-support")?; + let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; let output = quote! { #(#attrs)* #vis #sig { @@ -45,7 +45,7 @@ pub fn transactional(_attr: TokenStream, input: TokenStream) -> Result Result { let ItemFn { attrs, vis, sig, block } = syn::parse(input)?; - let crate_ = generate_crate_access_2018("frame-support")?; + let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; let output = quote! { #(#attrs)* #vis #sig { diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index be988ab19a0e8..d6e9f349fd9c8 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -39,7 +39,7 @@ fn generate_hidden_includes_mod_name(unique_id: &str) -> Ident { /// Generates the access to the `frame-support` crate. pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { if std::env::var("CARGO_PKG_NAME").unwrap() == def_crate { - let frame_support = match generate_crate_access_2018("frame-support") { + let frame_support = match generate_crate_access_from_frame_or_deps("frame-support") { Ok(c) => c, Err(e) => return e.into_compile_error().into(), }; @@ -52,7 +52,7 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { /// Check if a path is using the `frame` crate or not. /// -/// This will usually check the output of [`generate_crate_access_2018`]. +/// This will usually check the output of [`generate_crate_access_from_frame_or_deps`]. /// We want to know if whatever the `path` takes us to, is exported from `frame` or not. In that /// case `path` would start with `frame`, something like `frame::x::y:z`. pub fn is_using_frame_crate(path: &syn::Path) -> bool { @@ -63,14 +63,13 @@ pub fn is_using_frame_crate(path: &syn::Path) -> bool { /// /// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find /// `` directly. -pub fn generate_crate_access_2018(def_crate: &str) -> Result { +pub fn generate_crate_access_from_frame_or_deps(def_crate: &str) -> Result { if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); - let path = syn::parse_str::(&path)?; - return Ok(path) + return syn::parse_str::(&path) } - let indent = match crate_name(def_crate) { + let ident = match crate_name(def_crate) { Ok(FoundCrate::Itself) => { let name = def_crate.to_string().replace("-", "_"); Ok(syn::Ident::new(&name, Span::call_site())) @@ -79,7 +78,7 @@ pub fn generate_crate_access_2018(def_crate: &str) -> Result { Err(e) => Err(Error::new(Span::call_site(), e)), }?; - Ok(syn::Path::from(indent)) + Ok(syn::Path::from(ident)) } /// Generates the hidden includes that are required to make the macro independent from its scope. From 963be9468d97b943c150e1a0ad636b0ef25aaa7f Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Mon, 2 Oct 2023 15:38:11 +0300 Subject: [PATCH 21/33] implement review suggestions --- .../frame/support/procedural/src/pallet/parse/config.rs | 5 +++++ substrate/frame/support/test/compile_pass/src/lib.rs | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 44a1b1fb74d5e..36bde6bacb1cf 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -497,6 +497,7 @@ mod tests { let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); assert!(has_expected_system_config(path, &frame_system)); } + #[test] fn has_expected_system_config_works_with_assoc_type() { let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); @@ -505,6 +506,7 @@ mod tests { .unwrap(); assert!(has_expected_system_config(path, &frame_system)); } + #[test] fn has_expected_system_config_works_with_frame() { let frame_system = @@ -512,6 +514,7 @@ mod tests { let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); assert!(has_expected_system_config(path, &frame_system)); } + #[test] fn has_expected_system_config_unexpected_frame_system() { let frame_system = @@ -519,12 +522,14 @@ mod tests { let path = syn::parse2::(quote::quote!(frame_system::Config)).unwrap(); assert!(!has_expected_system_config(path, &frame_system)); } + #[test] fn has_expected_system_config_unexpected_path() { let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); let path = syn::parse2::(quote::quote!(frame_system::ConfigSystem)).unwrap(); assert!(!has_expected_system_config(path, &frame_system)); } + #[test] fn has_expected_system_config_not_frame_system() { let frame_system = syn::parse2::(quote::quote!(something)).unwrap(); diff --git a/substrate/frame/support/test/compile_pass/src/lib.rs b/substrate/frame/support/test/compile_pass/src/lib.rs index a453dd88440b5..6ea37fb27e72f 100644 --- a/substrate/frame/support/test/compile_pass/src/lib.rs +++ b/substrate/frame/support/test/compile_pass/src/lib.rs @@ -16,7 +16,8 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Test that `construct_runtime!` also works when `frame-support` is renamed in the `Cargo.toml`. +//! Test that `construct_runtime!` also works when `frame-support` or `frame-system` are renamed in +//! the `Cargo.toml`. #![cfg_attr(not(feature = "std"), no_std)] From 76de90d6f49b85059c0bd6604970db0c48f649c8 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Tue, 3 Oct 2023 11:11:07 +0300 Subject: [PATCH 22/33] add dummy frame crate for testing --- Cargo.lock | 19 +++++++++++++++++++ Cargo.toml | 2 ++ .../frame/support/procedural/tools/src/lib.rs | 1 + 3 files changed, 22 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index a95a7e2561d6e..c0e5a6059808e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5158,6 +5158,14 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" +[[package]] +name = "frame" +version = "4.0.0-dev" +dependencies = [ + "frame-support", + "frame-system", +] + [[package]] name = "frame-benchmarking" version = "4.0.0-dev" @@ -5486,6 +5494,17 @@ dependencies = [ "sp-runtime", ] +[[package]] +name = "frame-support-test-pallet-no-support" +version = "4.0.0-dev" +dependencies = [ + "frame", + "parity-scale-codec", + "scale-info", + "serde", + "sp-runtime", +] + [[package]] name = "frame-system" version = "4.0.0-dev" diff --git a/Cargo.toml b/Cargo.toml index 4db27b98e9078..79cbe867f6722 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -351,6 +351,8 @@ members = [ "substrate/frame/support/test", "substrate/frame/support/test/compile_pass", "substrate/frame/support/test/pallet", + "substrate/frame/support/test/pallet_no_support", + "substrate/frame/support/test/pallet_no_support/frame", "substrate/frame/system", "substrate/frame/system/benchmarking", "substrate/frame/system/rpc/runtime-api", diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index d6e9f349fd9c8..3be70066246ee 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -64,6 +64,7 @@ pub fn is_using_frame_crate(path: &syn::Path) -> bool { /// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find /// `` directly. pub fn generate_crate_access_from_frame_or_deps(def_crate: &str) -> Result { + // TODO: this does not work if the frame crate is renamed. if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); return syn::parse_str::(&path) From 32f2f1ee1f58b141f12ce996aa2d1c469a22f6de Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Wed, 4 Oct 2023 06:19:29 +0300 Subject: [PATCH 23/33] add pallet test example with frame crate --- .../support/test/pallet_no_support/Cargo.toml | 29 +++++++++ .../test/pallet_no_support/frame/Cargo.toml | 23 ++++++++ .../test/pallet_no_support/frame/src/lib.rs | 4 ++ .../support/test/pallet_no_support/src/lib.rs | 59 +++++++++++++++++++ 4 files changed, 115 insertions(+) create mode 100644 substrate/frame/support/test/pallet_no_support/Cargo.toml create mode 100644 substrate/frame/support/test/pallet_no_support/frame/Cargo.toml create mode 100644 substrate/frame/support/test/pallet_no_support/frame/src/lib.rs create mode 100644 substrate/frame/support/test/pallet_no_support/src/lib.rs diff --git a/substrate/frame/support/test/pallet_no_support/Cargo.toml b/substrate/frame/support/test/pallet_no_support/Cargo.toml new file mode 100644 index 0000000000000..b2001bdd4389f --- /dev/null +++ b/substrate/frame/support/test/pallet_no_support/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "frame-support-test-pallet-no-support" +version = "4.0.0-dev" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +publish = false +homepage = "https://substrate.io" +repository.workspace = true + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive"] } +frame = { path = "frame", default-features = false} +sp-runtime = { path = "../../../../primitives/runtime", default-features = false} + +[features] +default = [ "std" ] +std = [ + "codec/std", + "frame/std", + "scale-info/std", + "serde/std", + "sp-runtime/std", +] diff --git a/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml b/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml new file mode 100644 index 0000000000000..b01341b20ce47 --- /dev/null +++ b/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "frame" +version = "4.0.0-dev" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +publish = false +homepage = "https://substrate.io" +repository.workspace = true + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +frame-system = { path = "../../../../system", default-features = false} +frame-support = { path = "../../..", default-features = false} + +[features] +default = [ "std" ] +std = [ + "frame-system/std", + "frame-support/std", +] diff --git a/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs b/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs new file mode 100644 index 0000000000000..124eb9fa74f45 --- /dev/null +++ b/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs @@ -0,0 +1,4 @@ +pub mod deps { + pub use frame_support; + pub use frame_system; +} diff --git a/substrate/frame/support/test/pallet_no_support/src/lib.rs b/substrate/frame/support/test/pallet_no_support/src/lib.rs new file mode 100644 index 0000000000000..b316285ca532c --- /dev/null +++ b/substrate/frame/support/test/pallet_no_support/src/lib.rs @@ -0,0 +1,59 @@ +// 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. + +//! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and +//! `frame_support` are reexported by a `frame` crate. + +// Ensure docs are propagated properly by the macros. +#![warn(missing_docs)] + +pub use pallet::*; + +#[frame::deps::frame_support::pallet] +pub mod pallet { + use frame::deps::{frame_support::pallet_prelude::*, frame_system}; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + // this wouldn't work with frame::deps::frame_system::Config because of + // has_expected_system_config + pub trait Config: frame::deps::frame_system::Config {} + + /// I'm the documentation + #[pallet::storage] + pub type Value = StorageValue<_, u32>; + + #[pallet::genesis_config] + #[derive(frame::deps::frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: core::marker::PhantomData, + } + + #[pallet::genesis_build] + impl BuildGenesisConfig for GenesisConfig { + fn build(&self) {} + } + + #[pallet::error] + pub enum Error { + /// Something failed + Test, + } +} From 877fdc30719ed51948b4743cc27db106ee41e89d Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Wed, 4 Oct 2023 06:26:13 +0300 Subject: [PATCH 24/33] wip --- .../procedural/src/pallet/parse/config.rs | 34 ++++++++++++++----- .../support/test/pallet_no_support/src/lib.rs | 2 -- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 36bde6bacb1cf..7d6f01584461f 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -280,22 +280,38 @@ fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool return false } - let mut expected_system_config = if is_using_frame_crate(&frame_system) { - // in this case, we know that the only valid frame_system path is one that - // is `frame_system`, as `frame` re-exports it as such. - let fixed_frame_system = - syn::parse2::(quote::quote!(frame_system)).expect("is a valid path; qed"); - fixed_frame_system - } else { + // TODO: WIP. Do we need `if is_using_frame_crate` at all? By having it, things this wouldn't work + // ``` + // #[pallet::config] + // pub trait Config: frame::deps::frame_system::Config {} + // ``` + // Instead this would be needed + // ``` + // pub trait Config: frame_system::Config {} + // ``` + // + // On the other hand, with it the test `has_expected_system_config_works_with_frame` does not work. + let mut expected_system_config = + // if is_using_frame_crate(&frame_system) { + // // in this case, we know that the only valid frame_system path is one that + // // is `frame_system`, as `frame` re-exports it as such. + // let fixed_frame_system = + // syn::parse2::(quote::quote!(frame_system)).expect("is a valid path; qed"); + // fixed_frame_system + // } else { // a possibly renamed frame-system, which is a direct dependency. - frame_system.clone() - }; + frame_system.clone(); + // }; expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", path.span()))); // the parse path might be something like `frame_system::Config<...>`, so we // only compare the idents along the path. + println!("path: {}", path.to_token_stream()); + println!("frame_system: {}", frame_system.to_token_stream()); + println!("expected_system_config: {}", expected_system_config.to_token_stream()); + // TODO: end WIP. expected_system_config .segments .into_iter() diff --git a/substrate/frame/support/test/pallet_no_support/src/lib.rs b/substrate/frame/support/test/pallet_no_support/src/lib.rs index b316285ca532c..61dccffa2d4a2 100644 --- a/substrate/frame/support/test/pallet_no_support/src/lib.rs +++ b/substrate/frame/support/test/pallet_no_support/src/lib.rs @@ -31,8 +31,6 @@ pub mod pallet { pub struct Pallet(_); #[pallet::config] - // this wouldn't work with frame::deps::frame_system::Config because of - // has_expected_system_config pub trait Config: frame::deps::frame_system::Config {} /// I'm the documentation From c89c0c7237cc3ce1837391a26c1ccecc2c8f1e86 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Wed, 4 Oct 2023 11:01:01 +0300 Subject: [PATCH 25/33] make dummy pallet work with frame crate --- Cargo.lock | 2 +- Cargo.toml | 4 +- .../procedural/src/pallet/parse/config.rs | 89 +++++++++++++------ .../support/test/pallet_no_support/Cargo.toml | 29 ------ .../test/pallet_no_support/frame/Cargo.toml | 23 ----- .../test/pallet_no_support/frame/src/lib.rs | 4 - .../support/test/pallet_no_support/src/lib.rs | 57 ------------ 7 files changed, 65 insertions(+), 143 deletions(-) delete mode 100644 substrate/frame/support/test/pallet_no_support/Cargo.toml delete mode 100644 substrate/frame/support/test/pallet_no_support/frame/Cargo.toml delete mode 100644 substrate/frame/support/test/pallet_no_support/frame/src/lib.rs delete mode 100644 substrate/frame/support/test/pallet_no_support/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index c0e5a6059808e..cdcb1afe63cc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5495,7 +5495,7 @@ dependencies = [ ] [[package]] -name = "frame-support-test-pallet-no-support" +name = "frame-support-test-pallet-frame-crate" version = "4.0.0-dev" dependencies = [ "frame", diff --git a/Cargo.toml b/Cargo.toml index 79cbe867f6722..cc009e26e870d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -351,8 +351,8 @@ members = [ "substrate/frame/support/test", "substrate/frame/support/test/compile_pass", "substrate/frame/support/test/pallet", - "substrate/frame/support/test/pallet_no_support", - "substrate/frame/support/test/pallet_no_support/frame", + "substrate/frame/support/test/pallet_frame_crate", + "substrate/frame/support/test/pallet_frame_crate/frame", "substrate/frame/system", "substrate/frame/system/benchmarking", "substrate/frame/system/rpc/runtime-api", diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 7d6f01584461f..fbab92db196cb 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -274,44 +274,35 @@ fn check_event_type( } } +/// Check that the path to `frame_system::Config` is valid, this is that the path is just +/// `frame_system::Config` or when using the `frame` crate it is `frame::xyz::frame_system::Config`. fn has_expected_system_config(path: syn::Path, frame_system: &syn::Path) -> bool { - // check if `frame_system` is actually 'frame_system'. + // Check if `frame_system` is actually 'frame_system'. if path.segments.iter().all(|s| s.ident != "frame_system") { return false } - // TODO: WIP. Do we need `if is_using_frame_crate` at all? By having it, things this wouldn't work - // ``` - // #[pallet::config] - // pub trait Config: frame::deps::frame_system::Config {} - // ``` - // Instead this would be needed - // ``` - // pub trait Config: frame_system::Config {} - // ``` - // - // On the other hand, with it the test `has_expected_system_config_works_with_frame` does not work. - let mut expected_system_config = - // if is_using_frame_crate(&frame_system) { - // // in this case, we know that the only valid frame_system path is one that - // // is `frame_system`, as `frame` re-exports it as such. - // let fixed_frame_system = - // syn::parse2::(quote::quote!(frame_system)).expect("is a valid path; qed"); - // fixed_frame_system - // } else { - // a possibly renamed frame-system, which is a direct dependency. - frame_system.clone(); - // }; + let mut expected_system_config = + match (is_using_frame_crate(&path), is_using_frame_crate(&frame_system)) { + (true, false) => + // We can't use the path to `frame_system` from `frame` if `frame_system` is not being + // in scope through `frame`. + return false, + (false, true) => + // We know that the only valid frame_system path is one that is `frame_system`, as + // `frame` re-exports it as such. + syn::parse2::(quote::quote!(frame_system)).expect("is a valid path; qed"), + (_, _) => + // They are either both `frame_system` or both `frame::xyz::frame_system`. + frame_system.clone(), + }; expected_system_config .segments .push(syn::PathSegment::from(syn::Ident::new("Config", path.span()))); + // the parse path might be something like `frame_system::Config<...>`, so we // only compare the idents along the path. - println!("path: {}", path.to_token_stream()); - println!("frame_system: {}", frame_system.to_token_stream()); - println!("expected_system_config: {}", expected_system_config.to_token_stream()); - // TODO: end WIP. expected_system_config .segments .into_iter() @@ -531,6 +522,50 @@ mod tests { assert!(has_expected_system_config(path, &frame_system)); } + #[test] + fn has_expected_system_config_works_with_frame_full_path() { + let frame_system = + syn::parse2::(quote::quote!(frame::deps::frame_system)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame::deps::frame_system::Config)).unwrap(); + assert!(has_expected_system_config(path, &frame_system)); + } + + #[test] + fn has_expected_system_config_works_with_other_frame_full_path() { + let frame_system = + syn::parse2::(quote::quote!(frame::xyz::frame_system)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame::xyz::frame_system::Config)).unwrap(); + assert!(has_expected_system_config(path, &frame_system)); + } + + #[test] + fn has_expected_system_config_does_not_works_with_mixed_frame_full_path() { + let frame_system = + syn::parse2::(quote::quote!(frame::xyz::frame_system)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame::deps::frame_system::Config)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } + + #[test] + fn has_expected_system_config_does_not_works_with_other_mixed_frame_full_path() { + let frame_system = + syn::parse2::(quote::quote!(frame::deps::frame_system)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame::xyz::frame_system::Config)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } + + #[test] + fn has_expected_system_config_does_not_work_with_frame_full_path_if_not_frame_crate() { + let frame_system = syn::parse2::(quote::quote!(frame_system)).unwrap(); + let path = + syn::parse2::(quote::quote!(frame::deps::frame_system::Config)).unwrap(); + assert!(!has_expected_system_config(path, &frame_system)); + } + #[test] fn has_expected_system_config_unexpected_frame_system() { let frame_system = diff --git a/substrate/frame/support/test/pallet_no_support/Cargo.toml b/substrate/frame/support/test/pallet_no_support/Cargo.toml deleted file mode 100644 index b2001bdd4389f..0000000000000 --- a/substrate/frame/support/test/pallet_no_support/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "frame-support-test-pallet-no-support" -version = "4.0.0-dev" -authors.workspace = true -edition.workspace = true -license = "Apache-2.0" -publish = false -homepage = "https://substrate.io" -repository.workspace = true - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.188", default-features = false, features = ["derive"] } -frame = { path = "frame", default-features = false} -sp-runtime = { path = "../../../../primitives/runtime", default-features = false} - -[features] -default = [ "std" ] -std = [ - "codec/std", - "frame/std", - "scale-info/std", - "serde/std", - "sp-runtime/std", -] diff --git a/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml b/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml deleted file mode 100644 index b01341b20ce47..0000000000000 --- a/substrate/frame/support/test/pallet_no_support/frame/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "frame" -version = "4.0.0-dev" -authors.workspace = true -edition.workspace = true -license = "Apache-2.0" -publish = false -homepage = "https://substrate.io" -repository.workspace = true - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -frame-system = { path = "../../../../system", default-features = false} -frame-support = { path = "../../..", default-features = false} - -[features] -default = [ "std" ] -std = [ - "frame-system/std", - "frame-support/std", -] diff --git a/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs b/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs deleted file mode 100644 index 124eb9fa74f45..0000000000000 --- a/substrate/frame/support/test/pallet_no_support/frame/src/lib.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod deps { - pub use frame_support; - pub use frame_system; -} diff --git a/substrate/frame/support/test/pallet_no_support/src/lib.rs b/substrate/frame/support/test/pallet_no_support/src/lib.rs deleted file mode 100644 index 61dccffa2d4a2..0000000000000 --- a/substrate/frame/support/test/pallet_no_support/src/lib.rs +++ /dev/null @@ -1,57 +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. - -//! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and -//! `frame_support` are reexported by a `frame` crate. - -// Ensure docs are propagated properly by the macros. -#![warn(missing_docs)] - -pub use pallet::*; - -#[frame::deps::frame_support::pallet] -pub mod pallet { - use frame::deps::{frame_support::pallet_prelude::*, frame_system}; - - #[pallet::pallet] - pub struct Pallet(_); - - #[pallet::config] - pub trait Config: frame::deps::frame_system::Config {} - - /// I'm the documentation - #[pallet::storage] - pub type Value = StorageValue<_, u32>; - - #[pallet::genesis_config] - #[derive(frame::deps::frame_support::DefaultNoBound)] - pub struct GenesisConfig { - #[serde(skip)] - _config: core::marker::PhantomData, - } - - #[pallet::genesis_build] - impl BuildGenesisConfig for GenesisConfig { - fn build(&self) {} - } - - #[pallet::error] - pub enum Error { - /// Something failed - Test, - } -} From 8184085c52e120a762a2a50b10911ee203eaeecf Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Wed, 4 Oct 2023 12:23:02 +0300 Subject: [PATCH 26/33] add dummy pallet with frame crate --- .../test/pallet_frame_crate/Cargo.toml | 29 +++++++++ .../test/pallet_frame_crate/frame/Cargo.toml | 23 +++++++ .../test/pallet_frame_crate/frame/src/lib.rs | 4 ++ .../test/pallet_frame_crate/src/lib.rs | 61 +++++++++++++++++++ 4 files changed, 117 insertions(+) create mode 100644 substrate/frame/support/test/pallet_frame_crate/Cargo.toml create mode 100644 substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml create mode 100644 substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs create mode 100644 substrate/frame/support/test/pallet_frame_crate/src/lib.rs diff --git a/substrate/frame/support/test/pallet_frame_crate/Cargo.toml b/substrate/frame/support/test/pallet_frame_crate/Cargo.toml new file mode 100644 index 0000000000000..134dd2d81c64b --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "frame-support-test-pallet-frame-crate" +version = "4.0.0-dev" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +publish = false +homepage = "https://substrate.io" +repository.workspace = true + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive"] } +frame = { path = "frame", default-features = false} +sp-runtime = { path = "../../../../primitives/runtime", default-features = false} + +[features] +default = [ "std" ] +std = [ + "codec/std", + "frame/std", + "scale-info/std", + "serde/std", + "sp-runtime/std", +] diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml new file mode 100644 index 0000000000000..b01341b20ce47 --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "frame" +version = "4.0.0-dev" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +publish = false +homepage = "https://substrate.io" +repository.workspace = true + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +frame-system = { path = "../../../../system", default-features = false} +frame-support = { path = "../../..", default-features = false} + +[features] +default = [ "std" ] +std = [ + "frame-system/std", + "frame-support/std", +] diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs new file mode 100644 index 0000000000000..124eb9fa74f45 --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs @@ -0,0 +1,4 @@ +pub mod deps { + pub use frame_support; + pub use frame_system; +} diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs new file mode 100644 index 0000000000000..f6fa77566cde4 --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -0,0 +1,61 @@ +// 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. + +//! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and +//! `frame_support` are reexported by a `frame` crate. + +// Ensure docs are propagated properly by the macros. +#![warn(missing_docs)] + +pub use pallet::*; + +#[frame::deps::frame_support::pallet] +pub mod pallet { + use frame::deps::frame_support::pallet_prelude::*; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + // The only valid syntax here is the following or + // ``` + // pub trait Config: frame_system::Config {} + // ``` + // if `frame_system` is brought into scope. + pub trait Config: frame::deps::frame_system::Config {} + + #[pallet::storage] + pub type Value = StorageValue<_, u32>; + + #[pallet::genesis_config] + #[derive(frame::deps::frame_support::DefaultNoBound)] + pub struct GenesisConfig { + #[serde(skip)] + _config: core::marker::PhantomData, + } + + #[pallet::genesis_build] + impl BuildGenesisConfig for GenesisConfig { + fn build(&self) {} + } + + #[pallet::error] + pub enum Error { + /// Something failed + Test, + } +} From 1ee920b69525929769c9105b67c5a949485b760b Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 6 Oct 2023 08:35:51 +0300 Subject: [PATCH 27/33] add min runtime ui test --- Cargo.lock | 6 ++- Cargo.toml | 2 +- .../frame/support/procedural/tools/src/lib.rs | 12 ++++++ .../test/pallet_frame_crate/Cargo.toml | 8 ++-- .../test/pallet_frame_crate/frame/Cargo.toml | 2 +- .../test/pallet_frame_crate/src/lib.rs | 11 +++-- .../test/pallet_frame_crate/tests/ui.rs | 35 ++++++++++++++++ .../tests/ui/min_runtime.rs | 40 +++++++++++++++++++ 8 files changed, 105 insertions(+), 11 deletions(-) create mode 100644 substrate/frame/support/test/pallet_frame_crate/tests/ui.rs create mode 100644 substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs diff --git a/Cargo.lock b/Cargo.lock index cdcb1afe63cc4..e6242cfe39ec9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5160,7 +5160,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame" -version = "4.0.0-dev" +version = "0.1.0" dependencies = [ "frame-support", "frame-system", @@ -5496,13 +5496,15 @@ dependencies = [ [[package]] name = "frame-support-test-pallet-frame-crate" -version = "4.0.0-dev" +version = "0.1.0" dependencies = [ "frame", "parity-scale-codec", + "rustversion", "scale-info", "serde", "sp-runtime", + "trybuild", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index cc009e26e870d..31c21e2126468 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -351,8 +351,8 @@ members = [ "substrate/frame/support/test", "substrate/frame/support/test/compile_pass", "substrate/frame/support/test/pallet", - "substrate/frame/support/test/pallet_frame_crate", "substrate/frame/support/test/pallet_frame_crate/frame", + "substrate/frame/support/test/pallet_frame_crate", "substrate/frame/system", "substrate/frame/system/benchmarking", "substrate/frame/system/rpc/runtime-api", diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index 3be70066246ee..e9dd1c0d4facd 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -86,6 +86,18 @@ pub fn generate_crate_access_from_frame_or_deps(def_crate: &str) -> Result TokenStream { let mod_name = generate_hidden_includes_mod_name(unique_id); + // TODO: improve this to avoid code duplication with `generate_crate_access_from_frame_or_deps`. + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); + let path = syn::parse_str::(&path).expect("is a valid path; qed"); + return quote::quote!( + #[doc(hidden)] + mod #mod_name { + pub use #path as hidden_include; + } + ) + } + match crate_name(def_crate) { Ok(FoundCrate::Itself) => quote!(), Ok(FoundCrate::Name(name)) => { diff --git a/substrate/frame/support/test/pallet_frame_crate/Cargo.toml b/substrate/frame/support/test/pallet_frame_crate/Cargo.toml index 134dd2d81c64b..80584ada4d8b6 100644 --- a/substrate/frame/support/test/pallet_frame_crate/Cargo.toml +++ b/substrate/frame/support/test/pallet_frame_crate/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "frame-support-test-pallet-frame-crate" -version = "4.0.0-dev" +version = "0.1.0" authors.workspace = true edition.workspace = true license = "Apache-2.0" @@ -13,10 +13,12 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.188", default-features = false, features = ["derive"] } frame = { path = "frame", default-features = false} +rustversion = "1.0.6" +scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } sp-runtime = { path = "../../../../primitives/runtime", default-features = false} +serde = { version = "1.0.188", default-features = false, features = ["derive"] } +trybuild = { version = "1.0.74", features = [ "diff" ] } [features] default = [ "std" ] diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml index b01341b20ce47..f95606a33bd13 100644 --- a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml +++ b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "frame" -version = "4.0.0-dev" +version = "0.1.0" authors.workspace = true edition.workspace = true license = "Apache-2.0" diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs index f6fa77566cde4..f7b7618a1e40b 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -23,9 +23,12 @@ pub use pallet::*; -#[frame::deps::frame_support::pallet] +use frame::deps::{frame_support, frame_system}; + +#[frame_support::pallet] pub mod pallet { - use frame::deps::frame_support::pallet_prelude::*; + use super::*; + use frame_support::pallet_prelude::*; #[pallet::pallet] pub struct Pallet(_); @@ -36,13 +39,13 @@ pub mod pallet { // pub trait Config: frame_system::Config {} // ``` // if `frame_system` is brought into scope. - pub trait Config: frame::deps::frame_system::Config {} + pub trait Config: frame_system::Config {} #[pallet::storage] pub type Value = StorageValue<_, u32>; #[pallet::genesis_config] - #[derive(frame::deps::frame_support::DefaultNoBound)] + #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] _config: core::marker::PhantomData, diff --git a/substrate/frame/support/test/pallet_frame_crate/tests/ui.rs b/substrate/frame/support/test/pallet_frame_crate/tests/ui.rs new file mode 100644 index 0000000000000..37724b59948f2 --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/tests/ui.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. + +#[rustversion::attr(not(stable), ignore)] +#[cfg(not(feature = "disable-ui-tests"))] +#[test] +fn frame_crate_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 Pallet's UI. + std::env::set_var("RUSTFLAGS", "--deny warnings"); + + let t = trybuild::TestCases::new(); + t.pass("tests/ui/*.rs"); +} diff --git a/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs b/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs new file mode 100644 index 0000000000000..cebab26b7fe77 --- /dev/null +++ b/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs @@ -0,0 +1,40 @@ +// 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::deps::{ + frame_support::{construct_runtime, derive_impl}, + frame_system, +}; + +type Block = frame_system::mocking::MockBlock; + +impl frame_support_test_pallet_frame_crate::pallet::Config for Runtime {} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +impl frame_system::Config for Runtime { + type Block = Block; +} + +construct_runtime! { + pub struct Runtime + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: frame_support_test_pallet_frame_crate::pallet::{Pallet, Config}, + } +} + +fn main() {} From 5050625a03a87196c6485498c299af7cab32958a Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 12 Oct 2023 11:17:56 +0200 Subject: [PATCH 28/33] simplify example pallet --- .../support/test/pallet_frame_crate/src/lib.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs index f7b7618a1e40b..bf1c2b4d41999 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -18,11 +18,6 @@ //! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and //! `frame_support` are reexported by a `frame` crate. -// Ensure docs are propagated properly by the macros. -#![warn(missing_docs)] - -pub use pallet::*; - use frame::deps::{frame_support, frame_system}; #[frame_support::pallet] @@ -41,9 +36,6 @@ pub mod pallet { // if `frame_system` is brought into scope. pub trait Config: frame_system::Config {} - #[pallet::storage] - pub type Value = StorageValue<_, u32>; - #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { @@ -55,10 +47,4 @@ pub mod pallet { impl BuildGenesisConfig for GenesisConfig { fn build(&self) {} } - - #[pallet::error] - pub enum Error { - /// Something failed - Test, - } } From 55daf790727e8eb590fd0ea00713fdd91c67707b Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 12 Oct 2023 11:19:37 +0200 Subject: [PATCH 29/33] update comment --- substrate/frame/support/test/pallet_frame_crate/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs index bf1c2b4d41999..b23c6ab667ee5 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -31,9 +31,8 @@ pub mod pallet { #[pallet::config] // The only valid syntax here is the following or // ``` - // pub trait Config: frame_system::Config {} + // pub trait Config: frame::deps::frame_system::Config {} // ``` - // if `frame_system` is brought into scope. pub trait Config: frame_system::Config {} #[pallet::genesis_config] From 43ca2c2add6ce8cc714578de4209e598050dc31e Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 12 Oct 2023 17:22:59 +0200 Subject: [PATCH 30/33] zepter improvement --- .../frame/support/test/pallet_frame_crate/frame/Cargo.toml | 5 +---- substrate/frame/support/test/pallet_frame_crate/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml index f95606a33bd13..d99ac2d2d46ee 100644 --- a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml +++ b/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml @@ -17,7 +17,4 @@ frame-support = { path = "../../..", default-features = false} [features] default = [ "std" ] -std = [ - "frame-system/std", - "frame-support/std", -] +std = [ "frame-support/std", "frame-system/std" ] diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs index b23c6ab667ee5..3c4cfbcba7a8f 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -18,7 +18,7 @@ //! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and //! `frame_support` are reexported by a `frame` crate. -use frame::deps::{frame_support, frame_system}; +// use frame::deps::{frame_support, frame_system}; #[frame_support::pallet] pub mod pallet { From b55615b86a107ccb898ab2611ab587de8549df43 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Thu, 12 Oct 2023 18:24:23 +0200 Subject: [PATCH 31/33] fix broken test --- substrate/frame/support/test/pallet_frame_crate/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs index 3c4cfbcba7a8f..b23c6ab667ee5 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/pallet_frame_crate/src/lib.rs @@ -18,7 +18,7 @@ //! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and //! `frame_support` are reexported by a `frame` crate. -// use frame::deps::{frame_support, frame_system}; +use frame::deps::{frame_support, frame_system}; #[frame_support::pallet] pub mod pallet { From d253b66aae7690049958736016845e9858c33260 Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 13 Oct 2023 16:45:52 +0300 Subject: [PATCH 32/33] update compile test --- Cargo.lock | 6 +-- Cargo.toml | 4 +- .../test/pallet_frame_crate/frame/src/lib.rs | 4 -- .../tests/ui/min_runtime.rs | 40 ------------------- .../Cargo.toml | 8 +--- .../frame/Cargo.toml | 0 .../frame/src/lib.rs} | 20 ++-------- .../src/lib.rs | 30 +++++++++++++- 8 files changed, 35 insertions(+), 77 deletions(-) delete mode 100644 substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs delete mode 100644 substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs rename substrate/frame/support/test/{pallet_frame_crate => stg_frame_crate}/Cargo.toml (65%) rename substrate/frame/support/test/{pallet_frame_crate => stg_frame_crate}/frame/Cargo.toml (100%) rename substrate/frame/support/test/{pallet_frame_crate/tests/ui.rs => stg_frame_crate/frame/src/lib.rs} (55%) rename substrate/frame/support/test/{pallet_frame_crate => stg_frame_crate}/src/lib.rs (64%) diff --git a/Cargo.lock b/Cargo.lock index 1b3ab6c18aa8f..ed5e0a29f71c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5435,16 +5435,12 @@ dependencies = [ ] [[package]] -name = "frame-support-test-pallet-frame-crate" +name = "frame-support-test-stg-frame-crate" version = "0.1.0" dependencies = [ "frame", "parity-scale-codec", - "rustversion", "scale-info", - "serde", - "sp-runtime", - "trybuild", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index afe0edf0ca7e9..9e8ead6cf7c9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -345,8 +345,8 @@ members = [ "substrate/frame/support/test", "substrate/frame/support/test/compile_pass", "substrate/frame/support/test/pallet", - "substrate/frame/support/test/pallet_frame_crate/frame", - "substrate/frame/support/test/pallet_frame_crate", + "substrate/frame/support/test/stg_frame_crate/frame", + "substrate/frame/support/test/stg_frame_crate", "substrate/frame/system", "substrate/frame/system/benchmarking", "substrate/frame/system/rpc/runtime-api", diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs b/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs deleted file mode 100644 index 124eb9fa74f45..0000000000000 --- a/substrate/frame/support/test/pallet_frame_crate/frame/src/lib.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod deps { - pub use frame_support; - pub use frame_system; -} diff --git a/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs b/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs deleted file mode 100644 index cebab26b7fe77..0000000000000 --- a/substrate/frame/support/test/pallet_frame_crate/tests/ui/min_runtime.rs +++ /dev/null @@ -1,40 +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 frame::deps::{ - frame_support::{construct_runtime, derive_impl}, - frame_system, -}; - -type Block = frame_system::mocking::MockBlock; - -impl frame_support_test_pallet_frame_crate::pallet::Config for Runtime {} - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] -impl frame_system::Config for Runtime { - type Block = Block; -} - -construct_runtime! { - pub struct Runtime - { - System: frame_system::{Pallet, Call, Storage, Config, Event}, - Pallet: frame_support_test_pallet_frame_crate::pallet::{Pallet, Config}, - } -} - -fn main() {} diff --git a/substrate/frame/support/test/pallet_frame_crate/Cargo.toml b/substrate/frame/support/test/stg_frame_crate/Cargo.toml similarity index 65% rename from substrate/frame/support/test/pallet_frame_crate/Cargo.toml rename to substrate/frame/support/test/stg_frame_crate/Cargo.toml index 80584ada4d8b6..25c0852c01a42 100644 --- a/substrate/frame/support/test/pallet_frame_crate/Cargo.toml +++ b/substrate/frame/support/test/stg_frame_crate/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "frame-support-test-pallet-frame-crate" +name = "frame-support-test-stg-frame-crate" version = "0.1.0" authors.workspace = true edition.workspace = true @@ -14,11 +14,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } frame = { path = "frame", default-features = false} -rustversion = "1.0.6" scale-info = { version = "2.0.0", default-features = false, features = ["derive"] } -sp-runtime = { path = "../../../../primitives/runtime", default-features = false} -serde = { version = "1.0.188", default-features = false, features = ["derive"] } -trybuild = { version = "1.0.74", features = [ "diff" ] } [features] default = [ "std" ] @@ -26,6 +22,4 @@ std = [ "codec/std", "frame/std", "scale-info/std", - "serde/std", - "sp-runtime/std", ] diff --git a/substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml b/substrate/frame/support/test/stg_frame_crate/frame/Cargo.toml similarity index 100% rename from substrate/frame/support/test/pallet_frame_crate/frame/Cargo.toml rename to substrate/frame/support/test/stg_frame_crate/frame/Cargo.toml diff --git a/substrate/frame/support/test/pallet_frame_crate/tests/ui.rs b/substrate/frame/support/test/stg_frame_crate/frame/src/lib.rs similarity index 55% rename from substrate/frame/support/test/pallet_frame_crate/tests/ui.rs rename to substrate/frame/support/test/stg_frame_crate/frame/src/lib.rs index 37724b59948f2..dba99f1bbe73f 100644 --- a/substrate/frame/support/test/pallet_frame_crate/tests/ui.rs +++ b/substrate/frame/support/test/stg_frame_crate/frame/src/lib.rs @@ -15,21 +15,7 @@ // 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 frame_crate_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 Pallet's UI. - std::env::set_var("RUSTFLAGS", "--deny warnings"); - - let t = trybuild::TestCases::new(); - t.pass("tests/ui/*.rs"); +pub mod deps { + pub use frame_support; + pub use frame_system; } diff --git a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs b/substrate/frame/support/test/stg_frame_crate/src/lib.rs similarity index 64% rename from substrate/frame/support/test/pallet_frame_crate/src/lib.rs rename to substrate/frame/support/test/stg_frame_crate/src/lib.rs index b23c6ab667ee5..501fcf6a70d7a 100644 --- a/substrate/frame/support/test/pallet_frame_crate/src/lib.rs +++ b/substrate/frame/support/test/stg_frame_crate/src/lib.rs @@ -15,8 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! A basic pallet that can be used to test `construct_runtime!` when `frame_system` and -//! `frame_support` are reexported by a `frame` crate. +// ! A basic pallet to test it compiles along with a runtime using it when `frame_system` and +// `frame_support` are reexported by a `frame` crate. use frame::deps::{frame_support, frame_system}; @@ -47,3 +47,29 @@ pub mod pallet { fn build(&self) {} } } + +#[cfg(test)] +// Dummy test to make sure a runtime would compile. +mod tests { + use super::{ + frame_support::{construct_runtime, derive_impl}, + frame_system, pallet, + }; + + type Block = frame_system::mocking::MockBlock; + + impl crate::pallet::Config for Runtime {} + + #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] + impl frame_system::Config for Runtime { + type Block = Block; + } + + construct_runtime! { + pub struct Runtime + { + System: frame_system::{Pallet, Call, Storage, Config, Event}, + Pallet: pallet::{Pallet, Config}, + } + } +} From d2009d3ff705e8f55dd818558990259de3c79afd Mon Sep 17 00:00:00 2001 From: Juan Girini Date: Fri, 13 Oct 2023 17:23:06 +0300 Subject: [PATCH 33/33] fix todo --- .../frame/support/procedural/src/benchmark.rs | 10 +-- .../procedural/src/construct_runtime/mod.rs | 8 +- .../support/procedural/src/crate_version.rs | 4 +- .../support/procedural/src/key_prefix.rs | 4 +- substrate/frame/support/procedural/src/lib.rs | 10 +-- .../procedural/src/pallet/parse/mod.rs | 6 +- .../support/procedural/src/pallet_error.rs | 4 +- .../support/procedural/src/storage_alias.rs | 4 +- .../support/procedural/src/transactional.rs | 6 +- .../frame/support/procedural/tools/src/lib.rs | 82 ++++++++++--------- .../support/test/stg_frame_crate/Cargo.toml | 6 +- 11 files changed, 73 insertions(+), 71 deletions(-) diff --git a/substrate/frame/support/procedural/src/benchmark.rs b/substrate/frame/support/procedural/src/benchmark.rs index 1c9d459de83b9..fb55e8c9f662c 100644 --- a/substrate/frame/support/procedural/src/benchmark.rs +++ b/substrate/frame/support/procedural/src/benchmark.rs @@ -18,7 +18,7 @@ //! Home of the parsing and expansion code for the new pallet benchmarking syntax use derive_syn_parse::Parse; -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro::TokenStream; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens}; @@ -418,8 +418,8 @@ pub fn benchmarks( true => quote!(T: Config, I: 'static), }; - let krate = generate_crate_access_from_frame_or_deps("frame-benchmarking")?; - let frame_system = generate_crate_access_from_frame_or_deps("frame-system")?; + let krate = generate_access_from_frame_or_crate("frame-benchmarking")?; + let frame_system = generate_access_from_frame_or_crate("frame-system")?; // benchmark name variables let benchmark_names_str: Vec = benchmark_names.iter().map(|n| n.to_string()).collect(); @@ -720,11 +720,11 @@ fn expand_benchmark( where_clause: TokenStream2, ) -> TokenStream2 { // set up variables needed during quoting - let krate = match generate_crate_access_from_frame_or_deps("frame-benchmarking") { + let krate = match generate_access_from_frame_or_crate("frame-benchmarking") { Ok(ident) => ident, Err(err) => return err.to_compile_error().into(), }; - let frame_system = match generate_crate_access_from_frame_or_deps("frame-system") { + let frame_system = match generate_access_from_frame_or_crate("frame-system") { Ok(path) => path, Err(err) => return err.to_compile_error().into(), }; diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 9bbf3afc7eb08..ce34694275b38 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -214,7 +214,7 @@ mod parse; use crate::pallet::parse::helper::two128_str; use cfg_expr::Predicate; use frame_support_procedural_tools::{ - generate_crate_access, generate_crate_access_from_frame_or_deps, generate_hidden_includes, + generate_access_from_frame_or_crate, generate_crate_access, generate_hidden_includes, }; use itertools::Itertools; use parse::{ExplicitRuntimeDeclaration, ImplicitRuntimeDeclaration, Pallet, RuntimeDeclaration}; @@ -272,7 +272,7 @@ fn construct_runtime_implicit_to_explicit( input: TokenStream2, definition: ImplicitRuntimeDeclaration, ) -> Result { - let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; + let frame_support = generate_access_from_frame_or_crate("frame-support")?; let mut expansion = quote::quote!( #frame_support::construct_runtime! { #input } ); @@ -308,7 +308,7 @@ fn construct_runtime_explicit_to_explicit_expanded( input: TokenStream2, definition: ExplicitRuntimeDeclaration, ) -> Result { - let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; + let frame_support = generate_access_from_frame_or_crate("frame-support")?; let mut expansion = quote::quote!( #frame_support::construct_runtime! { #input } ); @@ -372,7 +372,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_from_frame_or_deps("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); diff --git a/substrate/frame/support/procedural/src/crate_version.rs b/substrate/frame/support/procedural/src/crate_version.rs index eaaee860b9f08..8c8975a425971 100644 --- a/substrate/frame/support/procedural/src/crate_version.rs +++ b/substrate/frame/support/procedural/src/crate_version.rs @@ -18,7 +18,7 @@ //! Implementation of macros related to crate versioning. use super::get_cargo_env_var; -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::{Span, TokenStream}; use syn::{Error, Result}; @@ -42,7 +42,7 @@ pub fn crate_to_crate_version(input: proc_macro::TokenStream) -> Result("CARGO_PKG_VERSION_PATCH") .map_err(|_| create_error("Patch version needs to fit into `u8`"))?; - let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; + let crate_ = generate_access_from_frame_or_crate("frame-support")?; Ok(quote::quote! { #crate_::traits::CrateVersion { diff --git a/substrate/frame/support/procedural/src/key_prefix.rs b/substrate/frame/support/procedural/src/key_prefix.rs index a3f94eb4bbd80..7f1ab6866d1e8 100644 --- a/substrate/frame/support/procedural/src/key_prefix.rs +++ b/substrate/frame/support/procedural/src/key_prefix.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Result}; @@ -28,7 +28,7 @@ pub fn impl_key_prefix_for_tuples(input: proc_macro::TokenStream) -> Result TokenStream #[import_tokens_attr_verbatim { format!( "{}::macro_magic", - match generate_crate_access_from_frame_or_deps("frame-support") { + match generate_access_from_frame_or_crate("frame-support") { Ok(path) => Ok(path), - Err(_) => generate_crate_access_from_frame_or_deps("frame"), + Err(_) => generate_access_from_frame_or_crate("frame"), } .expect("Failed to find either `frame-support` or `frame` in `Cargo.toml` dependencies.") .to_token_stream() @@ -1612,9 +1612,9 @@ pub fn pallet_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { #[import_tokens_attr { format!( "{}::macro_magic", - match generate_crate_access_from_frame_or_deps("frame-support") { + match generate_access_from_frame_or_crate("frame-support") { Ok(path) => Ok(path), - Err(_) => generate_crate_access_from_frame_or_deps("frame"), + Err(_) => generate_access_from_frame_or_crate("frame"), } .expect("Failed to find either `frame-support` or `frame` in `Cargo.toml` dependencies.") .to_token_stream() diff --git a/substrate/frame/support/procedural/src/pallet/parse/mod.rs b/substrate/frame/support/procedural/src/pallet/parse/mod.rs index c1aaf96557032..83a881751ef30 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/mod.rs @@ -37,7 +37,7 @@ pub mod type_value; pub mod validate_unsigned; use composite::{keyword::CompositeKeyword, CompositeDef}; -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use syn::spanned::Spanned; /// Parsed definition of a pallet. @@ -67,8 +67,8 @@ pub struct Def { impl Def { pub fn try_from(mut item: syn::ItemMod, dev_mode: bool) -> syn::Result { - let frame_system = generate_crate_access_from_frame_or_deps("frame-system")?; - let frame_support = generate_crate_access_from_frame_or_deps("frame-support")?; + let frame_system = generate_access_from_frame_or_crate("frame-system")?; + let frame_support = generate_access_from_frame_or_crate("frame-support")?; let item_span = item.span(); let items = &mut item diff --git a/substrate/frame/support/procedural/src/pallet_error.rs b/substrate/frame/support/procedural/src/pallet_error.rs index 03c8689161841..693a1e9821c97 100644 --- a/substrate/frame/support/procedural/src/pallet_error.rs +++ b/substrate/frame/support/procedural/src/pallet_error.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use quote::ToTokens; // Derive `PalletError` @@ -25,7 +25,7 @@ pub fn derive_pallet_error(input: proc_macro::TokenStream) -> proc_macro::TokenS Err(e) => return e.to_compile_error().into(), }; - let frame_support = match generate_crate_access_from_frame_or_deps("frame-support") { + let frame_support = match generate_access_from_frame_or_crate("frame-support") { Ok(c) => c, Err(e) => return e.into_compile_error().into(), }; diff --git a/substrate/frame/support/procedural/src/storage_alias.rs b/substrate/frame/support/procedural/src/storage_alias.rs index 18eebd38501f7..c0b4089a2748f 100644 --- a/substrate/frame/support/procedural/src/storage_alias.rs +++ b/substrate/frame/support/procedural/src/storage_alias.rs @@ -18,7 +18,7 @@ //! Implementation of the `storage_alias` attribute macro. use crate::{counter_prefix, pallet::parse::helper}; -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::{ @@ -475,7 +475,7 @@ enum PrefixType { /// Implementation of the `storage_alias` attribute macro. pub fn storage_alias(attributes: TokenStream, input: TokenStream) -> Result { let input = syn::parse2::(input)?; - let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; + let crate_ = generate_access_from_frame_or_crate("frame-support")?; let prefix_type = if attributes.is_empty() { PrefixType::Compatibility diff --git a/substrate/frame/support/procedural/src/transactional.rs b/substrate/frame/support/procedural/src/transactional.rs index 5798969dee29c..e9d4f84b797a9 100644 --- a/substrate/frame/support/procedural/src/transactional.rs +++ b/substrate/frame/support/procedural/src/transactional.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support_procedural_tools::generate_crate_access_from_frame_or_deps; +use frame_support_procedural_tools::generate_access_from_frame_or_crate; use proc_macro::TokenStream; use quote::quote; use syn::{ItemFn, Result}; @@ -23,7 +23,7 @@ use syn::{ItemFn, Result}; pub fn transactional(_attr: TokenStream, input: TokenStream) -> Result { let ItemFn { attrs, vis, sig, block } = syn::parse(input)?; - let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; + let crate_ = generate_access_from_frame_or_crate("frame-support")?; let output = quote! { #(#attrs)* #vis #sig { @@ -45,7 +45,7 @@ pub fn transactional(_attr: TokenStream, input: TokenStream) -> Result Result { let ItemFn { attrs, vis, sig, block } = syn::parse(input)?; - let crate_ = generate_crate_access_from_frame_or_deps("frame-support")?; + let crate_ = generate_access_from_frame_or_crate("frame-support")?; let output = quote! { #(#attrs)* #vis #sig { diff --git a/substrate/frame/support/procedural/tools/src/lib.rs b/substrate/frame/support/procedural/tools/src/lib.rs index e9dd1c0d4facd..62c77ef7a99ae 100644 --- a/substrate/frame/support/procedural/tools/src/lib.rs +++ b/substrate/frame/support/procedural/tools/src/lib.rs @@ -39,7 +39,7 @@ fn generate_hidden_includes_mod_name(unique_id: &str) -> Ident { /// Generates the access to the `frame-support` crate. pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { if std::env::var("CARGO_PKG_NAME").unwrap() == def_crate { - let frame_support = match generate_crate_access_from_frame_or_deps("frame-support") { + let frame_support = match generate_access_from_frame_or_crate("frame-support") { Ok(c) => c, Err(e) => return e.into_compile_error().into(), }; @@ -52,7 +52,7 @@ pub fn generate_crate_access(unique_id: &str, def_crate: &str) -> TokenStream { /// Check if a path is using the `frame` crate or not. /// -/// This will usually check the output of [`generate_crate_access_from_frame_or_deps`]. +/// This will usually check the output of [`generate_access_from_frame_or_crate`]. /// We want to know if whatever the `path` takes us to, is exported from `frame` or not. In that /// case `path` would start with `frame`, something like `frame::x::y:z`. pub fn is_using_frame_crate(path: &syn::Path) -> bool { @@ -63,56 +63,62 @@ pub fn is_using_frame_crate(path: &syn::Path) -> bool { /// /// If `frame` is in scope, it will use `frame::deps::`. Else, it will try and find /// `` directly. -pub fn generate_crate_access_from_frame_or_deps(def_crate: &str) -> Result { - // TODO: this does not work if the frame crate is renamed. - if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { - let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); - return syn::parse_str::(&path) +pub fn generate_access_from_frame_or_crate(def_crate: &str) -> Result { + if let Some(path) = get_frame_crate_path(def_crate) { + Ok(path) + } else { + let ident = match crate_name(def_crate) { + Ok(FoundCrate::Itself) => { + let name = def_crate.to_string().replace("-", "_"); + Ok(syn::Ident::new(&name, Span::call_site())) + }, + Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), + Err(e) => Err(Error::new(Span::call_site(), e)), + }?; + + Ok(syn::Path::from(ident)) } - - let ident = match crate_name(def_crate) { - Ok(FoundCrate::Itself) => { - let name = def_crate.to_string().replace("-", "_"); - Ok(syn::Ident::new(&name, Span::call_site())) - }, - Ok(FoundCrate::Name(name)) => Ok(Ident::new(&name, Span::call_site())), - Err(e) => Err(Error::new(Span::call_site(), e)), - }?; - - Ok(syn::Path::from(ident)) } /// Generates the hidden includes that are required to make the macro independent from its scope. pub fn generate_hidden_includes(unique_id: &str, def_crate: &str) -> TokenStream { let mod_name = generate_hidden_includes_mod_name(unique_id); - // TODO: improve this to avoid code duplication with `generate_crate_access_from_frame_or_deps`. - if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { - let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); - let path = syn::parse_str::(&path).expect("is a valid path; qed"); - return quote::quote!( + if let Some(path) = get_frame_crate_path(def_crate) { + quote::quote!( #[doc(hidden)] mod #mod_name { pub use #path as hidden_include; } ) + } else { + match crate_name(def_crate) { + Ok(FoundCrate::Itself) => quote!(), + Ok(FoundCrate::Name(name)) => { + let name = Ident::new(&name, Span::call_site()); + quote::quote!( + #[doc(hidden)] + mod #mod_name { + pub extern crate #name as hidden_include; + } + ) + }, + Err(e) => { + let err = Error::new(Span::call_site(), e).to_compile_error(); + quote!( #err ) + }, + } } +} - match crate_name(def_crate) { - Ok(FoundCrate::Itself) => quote!(), - Ok(FoundCrate::Name(name)) => { - let name = Ident::new(&name, Span::call_site()); - quote::quote!( - #[doc(hidden)] - mod #mod_name { - pub extern crate #name as hidden_include; - } - ) - }, - Err(e) => { - let err = Error::new(Span::call_site(), e).to_compile_error(); - quote!( #err ) - }, +/// Generates the path to the frame crate deps. +fn get_frame_crate_path(def_crate: &str) -> Option { + // This does not work if the frame crate is renamed. + if let Ok(FoundCrate::Name(name)) = crate_name(&"frame") { + let path = format!("{}::deps::{}", name, def_crate.to_string().replace("-", "_")); + Some(syn::parse_str::(&path).expect("is a valid path; qed")) + } else { + None } } diff --git a/substrate/frame/support/test/stg_frame_crate/Cargo.toml b/substrate/frame/support/test/stg_frame_crate/Cargo.toml index 25c0852c01a42..340f08905c32e 100644 --- a/substrate/frame/support/test/stg_frame_crate/Cargo.toml +++ b/substrate/frame/support/test/stg_frame_crate/Cargo.toml @@ -18,8 +18,4 @@ scale-info = { version = "2.0.0", default-features = false, features = ["derive" [features] default = [ "std" ] -std = [ - "codec/std", - "frame/std", - "scale-info/std", -] +std = [ "codec/std", "frame/std", "scale-info/std" ]