Make Get<T> const friendly + Clean the runtime files a bit. (#6132)

* Make Get const friendly

* Better doc

* Grumble

* Better doc

* Clean runtime files more
This commit is contained in:
Kian Paimani
2020-05-27 14:40:07 +02:00
committed by GitHub
parent bba5d7d5da
commit 8279ba96df
11 changed files with 103 additions and 35 deletions
+51 -4
View File
@@ -84,27 +84,62 @@ pub use sp_runtime::{self, ConsensusEngineId, print, traits::Printable};
#[derive(Debug)]
pub enum Never {}
/// Macro for easily creating a new implementation of the `Get` trait. Use similarly to
/// how you would declare a `const`:
/// Macro for easily creating a new implementation of the `Get` trait. If `const` token is used, the
/// rhs of the expression must be `const`-only, and get is implemented as `const`:
///
/// ```no_compile
/// ```
/// # use frame_support::traits::Get;
/// # use frame_support::parameter_types;
/// // This function cannot be used in a const context.
/// fn non_const_expression() -> u64 { 99 }
///
/// const FIXED_VALUE: u64 = 10;
/// parameter_types! {
/// pub const Argument: u64 = 42;
/// pub const Argument: u64 = 42 + FIXED_VALUE;
/// pub OtherArgument: u64 = non_const_expression();
/// }
///
/// trait Config {
/// type Parameter: Get<u64>;
/// type OtherParameter: Get<u64>;
/// }
///
/// struct Runtime;
/// impl Config for Runtime {
/// type Parameter = Argument;
/// type OtherParameter = OtherArgument;
/// }
/// ```
///
/// Invalid example:
///
/// ```compile_fail
/// # use frame_support::traits::Get;
/// # use frame_support::parameter_types;
/// // This function cannot be used in a const context.
/// fn non_const_expression() -> u64 { 99 }
///
/// parameter_types! {
/// pub const Argument: u64 = non_const_expression();
/// }
/// ```
#[macro_export]
macro_rules! parameter_types {
(
$( #[ $attr:meta ] )*
$vis:vis const $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
$crate::parameter_types!{IMPL_CONST $name , $type , $value}
$crate::parameter_types!{ $( $rest )* }
);
(
$( #[ $attr:meta ] )*
$vis:vis $name:ident: $type:ty = $value:expr;
$( $rest:tt )*
) => (
$( #[ $attr ] )*
$vis struct $name;
@@ -112,6 +147,18 @@ macro_rules! parameter_types {
$crate::parameter_types!{ $( $rest )* }
);
() => ();
(IMPL_CONST $name:ident , $type:ty , $value:expr) => {
impl $name {
pub const fn get() -> $type {
$value
}
}
impl<I: From<$type>> $crate::traits::Get<I> for $name {
fn get() -> I {
I::from($value)
}
}
};
(IMPL $name:ident , $type:ty , $value:expr) => {
impl $name {
pub fn get() -> $type {