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 4 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
62 changes: 3 additions & 59 deletions substrate/frame/support/procedural/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1188,67 +1188,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`.
#[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
27 changes: 24 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,42 @@ impl Pallet {
"Invalid pallet declaration, expected a path or a trait object",
))?;

let mut pallet_segment = None;
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: 115 additions & 5 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,125 @@ 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 {
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" {
runtime_param = Some(ident.clone());
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;
}
}
}
}

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(),
};
}

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 }));
}
61 changes: 61 additions & 0 deletions substrate/frame/support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,67 @@ 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:
///
/// ```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>`
pub use frame_support_procedural::runtime;

#[doc(hidden)]
Expand Down
12 changes: 6 additions & 6 deletions templates/minimal/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,27 +99,27 @@ mod runtime {

/// Mandatory system pallet that should always be included in a FRAME runtime.
#[runtime::pallet_index(0)]
pub type System = frame_system;
pub type System = frame_system::Pallet<Runtime>;

/// Provides a way for consensus systems to set and check the onchain time.
#[runtime::pallet_index(1)]
pub type Timestamp = pallet_timestamp;
pub type Timestamp = pallet_timestamp::Pallet<Runtime>;

/// Provides the ability to keep track of balances.
#[runtime::pallet_index(2)]
pub type Balances = pallet_balances;
pub type Balances = pallet_balances::Pallet<Runtime>;

/// Provides a way to execute privileged functions.
#[runtime::pallet_index(3)]
pub type Sudo = pallet_sudo;
pub type Sudo = pallet_sudo::Pallet<Runtime>;

/// Provides the ability to charge for extrinsic execution.
#[runtime::pallet_index(4)]
pub type TransactionPayment = pallet_transaction_payment;
pub type TransactionPayment = pallet_transaction_payment::Pallet<Runtime>;

/// A minimal pallet template.
#[runtime::pallet_index(5)]
pub type Template = pallet_minimal_template;
pub type Template = pallet_minimal_template::Pallet<Runtime>;
}

parameter_types! {
Expand Down
Loading