Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use real rust type for pallet alias in runtime macro #4769

Merged
merged 21 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions prdoc/pr_4769.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
title: Use real rust type for pallet alias in `runtime` macro

doc:
- audience: Runtime Dev
description: |
This PR adds the ability to use a real rust type for pallet alias in the new `runtime` macro:
```rust
#[runtime::pallet_index(0)]
pub type System = frame_system::Pallet<Runtime>;
```

Please note that the current syntax still continues to be supported.

crates:
- name: frame-support-procedural
bump: patch
- name: frame-support
bump: patch
- name: minimal-template-runtime
bump: patch
65 changes: 6 additions & 59 deletions substrate/frame/support/procedural/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ fn counter_prefix(prefix: &str) -> String {

/// Construct a runtime, with the given name and the given pallets.
///
/// NOTE: A new version of this macro is available at `frame_support::runtime`. This macro will
/// soon be deprecated. Please use the new macro instead.
///
/// The parameters here are specific types for `Block`, `NodeBlock`, and `UncheckedExtrinsic`
/// and the pallets that are used by the runtime.
/// `Block` is the block type that is used in the runtime and `NodeBlock` is the block type
Expand Down Expand Up @@ -1188,67 +1191,11 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream {
.into()
}

/// Construct a runtime, with the given name and the given pallets.
///
/// # Example:
///
/// ```ignore
/// #[frame_support::runtime]
/// mod runtime {
/// // The main runtime
/// #[runtime::runtime]
/// // Runtime Types to be generated
/// #[runtime::derive(
/// RuntimeCall,
/// RuntimeEvent,
/// RuntimeError,
/// RuntimeOrigin,
/// RuntimeFreezeReason,
/// RuntimeHoldReason,
/// RuntimeSlashReason,
/// RuntimeLockId,
/// RuntimeTask,
/// )]
/// pub struct Runtime;
///
/// #[runtime::pallet_index(0)]
/// pub type System = frame_system;
///
/// #[runtime::pallet_index(1)]
/// pub type Test = path::to::test;
///
/// // Pallet with instance.
/// #[runtime::pallet_index(2)]
/// pub type Test2_Instance1 = test2<Instance1>;
///
/// // Pallet with calls disabled.
/// #[runtime::pallet_index(3)]
/// #[runtime::disable_call]
/// pub type Test3 = test3;
///
/// // Pallet with unsigned extrinsics disabled.
/// #[runtime::pallet_index(4)]
/// #[runtime::disable_unsigned]
/// pub type Test4 = test4;
/// }
/// ```
///
/// # Legacy Ordering
///
/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to
/// ensure that the order of hooks is same as the order of pallets (and not based on the
/// pallet_index). This is to support legacy runtimes and should be avoided for new ones.
///
/// # Note
///
/// The population of the genesis storage depends on the order of pallets. So, if one of your
/// pallets depends on another pallet, the pallet that is depended upon needs to come before
/// the pallet depending on it.
///
/// # Type definitions
/// ---
///
/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System =
/// frame_system::Pallet<Runtime>`
/// **Rust-Analyzer users**: See the documentation of the Rust item in
/// `frame_support::runtime`.
muharem marked this conversation as resolved.
Show resolved Hide resolved
#[proc_macro_attribute]
pub fn runtime(attr: TokenStream, item: TokenStream) -> TokenStream {
runtime::runtime(attr, item)
Expand Down
10 changes: 8 additions & 2 deletions substrate/frame/support/procedural/src/runtime/expand/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,20 @@ fn construct_runtime_implicit_to_explicit(
for pallet in definition.pallet_decls.iter() {
let pallet_path = &pallet.path;
let pallet_name = &pallet.name;
let pallet_instance = pallet.instance.as_ref().map(|instance| quote::quote!(<#instance>));
let runtime_param = &pallet.runtime_param;
let pallet_segment_and_instance = match (&pallet.pallet_segment, &pallet.instance) {
(Some(segment), Some(instance)) => quote::quote!(::#segment<#runtime_param, #instance>),
(Some(segment), None) => quote::quote!(::#segment<#runtime_param>),
(None, Some(instance)) => quote::quote!(<#instance>),
(None, None) => quote::quote!(),
};
expansion = quote::quote!(
#frame_support::__private::tt_call! {
macro = [{ #pallet_path::tt_default_parts_v2 }]
your_tt_return = [{ #frame_support::__private::tt_return }]
~~> #frame_support::match_and_insert! {
target = [{ #expansion }]
pattern = [{ #pallet_name = #pallet_path #pallet_instance }]
pattern = [{ #pallet_name = #pallet_path #pallet_segment_and_instance }]
}
}
);
Expand Down
35 changes: 32 additions & 3 deletions substrate/frame/support/procedural/src/runtime/parse/pallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,50 @@ impl Pallet {
"Invalid pallet declaration, expected a path or a trait object",
))?;

let mut pallet_segment = None;
gupnik marked this conversation as resolved.
Show resolved Hide resolved
let mut instance = None;
if let Some(segment) = path.inner.segments.iter_mut().find(|seg| !seg.arguments.is_empty())
{
if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
args, ..
}) = segment.arguments.clone()
{
if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() {
instance =
Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span()));
if segment.ident == "Pallet" {
let mut segment = segment.clone();
segment.arguments = PathArguments::None;
pallet_segment = Some(segment.clone());
}
let mut args_iter = args.iter();
if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) =
args_iter.next()
{
let ident =
Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span());
if segment.ident == "Pallet" {
if let Some(arg_path) = args_iter.next() {
instance = Some(Ident::new(
&arg_path.to_token_stream().to_string(),
arg_path.span(),
));
segment.arguments = PathArguments::None;
}
} else {
instance = Some(ident);
segment.arguments = PathArguments::None;
}
}
}
}

if pallet_segment.is_some() {
path = PalletPath {
inner: syn::Path {
leading_colon: None,
segments: path.inner.segments.first().cloned().into_iter().collect(),
},
};
}

pallet_parts = pallet_parts
.into_iter()
.filter(|part| {
Expand Down
120 changes: 116 additions & 4 deletions substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ pub struct PalletDeclaration {
pub attrs: Vec<Attribute>,
/// The path of the pallet, e.g. `frame_system` in `pub type System = frame_system`.
pub path: syn::Path,
/// The segment of the pallet, e.g. `Pallet` in `pub type System = frame_system::Pallet`.
pub pallet_segment: Option<syn::PathSegment>,
/// The runtime parameter of the pallet, e.g. `Runtime` in
/// `pub type System = frame_system::Pallet<Runtime>`.
pub runtime_param: Option<Ident>,
/// The instance of the pallet, e.g. `Instance1` in `pub type Council =
/// pallet_collective<Instance1>`.
pub instance: Option<Ident>,
Expand All @@ -42,20 +47,127 @@ impl PalletDeclaration {

let mut path = path.path.clone();

let mut pallet_segment = None;
let mut runtime_param = None;
let mut instance = None;
if let Some(segment) = path.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) {
if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
args, ..
}) = segment.arguments.clone()
{
if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() {
instance =
Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span()));
if segment.ident == "Pallet" {
let mut segment = segment.clone();
segment.arguments = PathArguments::None;
pallet_segment = Some(segment.clone());
}
let mut args_iter = args.iter();
if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) =
args_iter.next()
{
let ident =
Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span());
gupnik marked this conversation as resolved.
Show resolved Hide resolved
if segment.ident == "Pallet" {
runtime_param = Some(ident.clone());
gupnik marked this conversation as resolved.
Show resolved Hide resolved
if let Some(arg_path) = args_iter.next() {
instance = Some(Ident::new(
&arg_path.to_token_stream().to_string(),
arg_path.span(),
));
gupnik marked this conversation as resolved.
Show resolved Hide resolved
segment.arguments = PathArguments::None;
gupnik marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
instance = Some(ident);
segment.arguments = PathArguments::None;
}
}
}
}

Ok(Self { name, path, instance, attrs: item.attrs.clone() })
if pallet_segment.is_some() {
path = syn::Path {
leading_colon: None,
segments: path.segments.first().cloned().into_iter().collect(),
gupnik marked this conversation as resolved.
Show resolved Hide resolved
};
}

Ok(Self { name, path, pallet_segment, runtime_param, instance, attrs: item.attrs.clone() })
}
}

#[test]
fn declaration_works() {
use syn::parse_quote;

let decl: PalletDeclaration = PalletDeclaration::try_from(
proc_macro2::Span::call_site(),
&parse_quote! { pub type System = frame_system; },
&parse_quote! { frame_system },
)
.expect("Failed to parse pallet declaration");

assert_eq!(decl.name, "System");
assert_eq!(decl.path, parse_quote! { frame_system });
assert_eq!(decl.pallet_segment, None);
assert_eq!(decl.runtime_param, None);
assert_eq!(decl.instance, None);
}

#[test]
fn declaration_works_with_instance() {
use syn::parse_quote;

let decl: PalletDeclaration = PalletDeclaration::try_from(
proc_macro2::Span::call_site(),
&parse_quote! { pub type System = frame_system<Instance1>; },
&parse_quote! { frame_system<Instance1> },
)
.expect("Failed to parse pallet declaration");

assert_eq!(decl.name, "System");
assert_eq!(decl.path, parse_quote! { frame_system });
assert_eq!(decl.pallet_segment, None);
assert_eq!(decl.runtime_param, None);
assert_eq!(decl.instance, Some(parse_quote! { Instance1 }));
}

#[test]
fn declaration_works_with_pallet() {
use syn::parse_quote;

let decl: PalletDeclaration = PalletDeclaration::try_from(
proc_macro2::Span::call_site(),
&parse_quote! { pub type System = frame_system::Pallet<Runtime>; },
&parse_quote! { frame_system::Pallet<Runtime> },
)
.expect("Failed to parse pallet declaration");

assert_eq!(decl.name, "System");
assert_eq!(decl.path, parse_quote! { frame_system });

let segment: syn::PathSegment =
syn::PathSegment { ident: parse_quote! { Pallet }, arguments: PathArguments::None };
assert_eq!(decl.pallet_segment, Some(segment));
assert_eq!(decl.runtime_param, Some(parse_quote! { Runtime }));
assert_eq!(decl.instance, None);
}

#[test]
fn declaration_works_with_pallet_and_instance() {
use syn::parse_quote;

let decl: PalletDeclaration = PalletDeclaration::try_from(
proc_macro2::Span::call_site(),
&parse_quote! { pub type System = frame_system::Pallet<Runtime, Instance1>; },
&parse_quote! { frame_system::Pallet<Runtime, Instance1> },
)
.expect("Failed to parse pallet declaration");

assert_eq!(decl.name, "System");
assert_eq!(decl.path, parse_quote! { frame_system });

let segment: syn::PathSegment =
syn::PathSegment { ident: parse_quote! { Pallet }, arguments: PathArguments::None };
assert_eq!(decl.pallet_segment, Some(segment));
assert_eq!(decl.runtime_param, Some(parse_quote! { Runtime }));
assert_eq!(decl.instance, Some(parse_quote! { Instance1 }));
}
21 changes: 21 additions & 0 deletions substrate/frame/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,27 @@ pub use frame_support_procedural::{
construct_runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound,
};

/// Construct a runtime, with the given name and the given pallets.
///
/// # Example:
#[doc = docify::embed!("src/tests/runtime.rs", runtime_macro)]
///
/// # Legacy Ordering
gupnik marked this conversation as resolved.
Show resolved Hide resolved
///
/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to
/// ensure that the order of hooks is same as the order of pallets (and not based on the
/// pallet_index). This is to support legacy runtimes and should be avoided for new ones.
///
/// # Note
///
/// The population of the genesis storage depends on the order of pallets. So, if one of your
/// pallets depends on another pallet, the pallet that is depended upon needs to come before
/// the pallet depending on it.
///
/// # Type definitions
///
/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System =
/// frame_system::Pallet<Runtime>`
pub use frame_support_procedural::runtime;

#[doc(hidden)]
Expand Down
26 changes: 20 additions & 6 deletions substrate/frame/support/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage};
pub use self::frame_system::{pallet_prelude::*, Config, Pallet};

mod inject_runtime_type;
mod runtime;
mod storage_alias;
mod tasks;

Expand Down Expand Up @@ -220,12 +221,25 @@ type Header = generic::Header<BlockNumber, BlakeTwo256>;
type UncheckedExtrinsic = generic::UncheckedExtrinsic<u32, RuntimeCall, (), ()>;
type Block = generic::Block<Header, UncheckedExtrinsic>;

crate::construct_runtime!(
pub enum Runtime
{
System: self::frame_system,
}
);
#[crate::runtime]
mod runtime {
#[runtime::runtime]
#[runtime::derive(
RuntimeCall,
RuntimeEvent,
RuntimeError,
RuntimeOrigin,
RuntimeFreezeReason,
RuntimeHoldReason,
RuntimeSlashReason,
RuntimeLockId,
RuntimeTask
)]
pub struct Runtime;

#[runtime::pallet_index(0)]
pub type System = self::frame_system;
}

#[crate::derive_impl(self::frame_system::config_preludes::TestDefaultConfig as self::frame_system::DefaultConfig)]
impl Config for Runtime {
Expand Down
Loading
Loading