FRAME: inherited call weight syntax (#13932)

* First approach on pallet::call_weight

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Use attr on pallet::call instead

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Ui tests

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Rename to weight(prefix = ...))

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Simplify to #[pallet::call(weight(T))]

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Add stray token error

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Cleanup

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Migrate remaining pallets

Using script from https://github.com/ggwpez/substrate-scripts/blob/e1b5ea5b5b4018867f3e869fce6f448b4ba9d71f/frame-code-migration/src/call_weight.rs

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Try to add some docs

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Revert "Migrate remaining pallets"

Lets do this as a follow-up, I dont want to bloat this small MR.

This reverts commit 331d4b42d72de1dacaed714d69166fa1bc9c92dd.

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Renames

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Review fixes

Co-authored-by: Sam Johnson <sam@durosoft.com>

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Test weights

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update UI tests

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update frame/support/procedural/src/pallet/parse/mod.rs

Co-authored-by: Muharem Ismailov <ismailov.m.h@gmail.com>

* Remove old code

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

* Update docs

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>

---------

Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
Co-authored-by: parity-processbot <>
Co-authored-by: Muharem Ismailov <ismailov.m.h@gmail.com>
This commit is contained in:
Oliver Tale-Yazdi
2023-04-27 16:08:08 +02:00
committed by GitHub
parent 6e5141fc23
commit b5201fa0ec
30 changed files with 698 additions and 92 deletions
@@ -15,7 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use super::helper;
use super::{helper, InheritedCallWeightAttr};
use frame_support_procedural_tools::get_doc_literals;
use quote::ToTokens;
use std::collections::HashMap;
@@ -46,6 +46,23 @@ pub struct CallDef {
pub attr_span: proc_macro2::Span,
/// Docs, specified on the impl Block.
pub docs: Vec<syn::Expr>,
/// The optional `weight` attribute on the `pallet::call`.
pub inherited_call_weight: Option<InheritedCallWeightAttr>,
}
/// The weight of a call.
#[derive(Clone)]
pub enum CallWeightDef {
/// Explicitly set on the call itself with `#[pallet::weight(…)]`. This value is used.
Immediate(syn::Expr),
/// The default value that should be set for dev-mode pallets. Usually zero.
DevModeDefault,
/// Inherits whatever value is configured on the pallet level.
///
/// The concrete value is not known at this point.
Inherited,
}
/// Definition of dispatchable typically: `#[weight...] fn foo(origin .., param1: ...) -> ..`
@@ -55,8 +72,8 @@ pub struct CallVariantDef {
pub name: syn::Ident,
/// Information on args: `(is_compact, name, type)`
pub args: Vec<(bool, syn::Ident, Box<syn::Type>)>,
/// Weight formula.
pub weight: syn::Expr,
/// Weight for the call.
pub weight: CallWeightDef,
/// Call index of the dispatchable.
pub call_index: u8,
/// Whether an explicit call index was specified.
@@ -151,6 +168,7 @@ impl CallDef {
index: usize,
item: &mut syn::Item,
dev_mode: bool,
inherited_call_weight: Option<InheritedCallWeightAttr>,
) -> syn::Result<Self> {
let item_impl = if let syn::Item::Impl(item) = item {
item
@@ -228,17 +246,23 @@ impl CallDef {
weight_attrs.push(FunctionAttr::Weight(empty_weight));
}
if weight_attrs.len() != 1 {
let msg = if weight_attrs.is_empty() {
"Invalid pallet::call, requires weight attribute i.e. `#[pallet::weight($expr)]`"
} else {
"Invalid pallet::call, too many weight attributes given"
};
return Err(syn::Error::new(method.sig.span(), msg))
}
let weight = match weight_attrs.pop().unwrap() {
FunctionAttr::Weight(w) => w,
_ => unreachable!("checked during creation of the let binding"),
let weight = match weight_attrs.len() {
0 if inherited_call_weight.is_some() => CallWeightDef::Inherited,
0 if dev_mode => CallWeightDef::DevModeDefault,
0 => return Err(syn::Error::new(
method.sig.span(),
"A pallet::call requires either a concrete `#[pallet::weight($expr)]` or an
inherited weight from the `#[pallet:call(weight($type))]` attribute, but
none were given.",
)),
1 => match weight_attrs.pop().unwrap() {
FunctionAttr::Weight(w) => CallWeightDef::Immediate(w),
_ => unreachable!("checked during creation of the let binding"),
},
_ => {
let msg = "Invalid pallet::call, too many weight attributes given";
return Err(syn::Error::new(method.sig.span(), msg))
},
};
if call_idx_attrs.len() > 1 {
@@ -321,6 +345,7 @@ impl CallDef {
methods,
where_clause: item_impl.generics.where_clause.clone(),
docs: get_doc_literals(&item_impl.attrs),
inherited_call_weight,
})
}
}
@@ -110,8 +110,8 @@ impl Def {
let m = hooks::HooksDef::try_from(span, index, item)?;
hooks = Some(m);
},
Some(PalletAttr::RuntimeCall(span)) if call.is_none() =>
call = Some(call::CallDef::try_from(span, index, item, dev_mode)?),
Some(PalletAttr::RuntimeCall(cw, span)) if call.is_none() =>
call = Some(call::CallDef::try_from(span, index, item, dev_mode, cw)?),
Some(PalletAttr::Error(span)) if error.is_none() =>
error = Some(error::ErrorDef::try_from(span, index, item)?),
Some(PalletAttr::RuntimeEvent(span)) if event.is_none() =>
@@ -402,6 +402,7 @@ impl GenericKind {
mod keyword {
syn::custom_keyword!(origin);
syn::custom_keyword!(call);
syn::custom_keyword!(weight);
syn::custom_keyword!(event);
syn::custom_keyword!(config);
syn::custom_keyword!(hooks);
@@ -425,7 +426,44 @@ enum PalletAttr {
Config(proc_macro2::Span),
Pallet(proc_macro2::Span),
Hooks(proc_macro2::Span),
RuntimeCall(proc_macro2::Span),
/// A `#[pallet::call]` with optional attributes to specialize the behaviour.
///
/// # Attributes
///
/// Each attribute `attr` can take the form of `#[pallet::call(attr = …)]` or
/// `#[pallet::call(attr(…))]`. The possible attributes are:
///
/// ## `weight`
///
/// Can be used to reduce the repetitive weight annotation in the trivial case. It accepts one
/// argument that is expected to be an implementation of the `WeightInfo` or something that
/// behaves syntactically equivalent. This allows to annotate a `WeightInfo` for all the calls.
/// Now each call does not need to specify its own `#[pallet::weight]` but can instead use the
/// one from the `#[pallet::call]` definition. So instead of having to write it on each call:
///
/// ```ignore
/// #[pallet::call]
/// impl<T: Config> Pallet<T> {
/// #[pallet::weight(T::WeightInfo::create())]
/// pub fn create(
/// ```
/// you can now omit it on the call itself, if the name of the weigh function matches the call:
///
/// ```ignore
/// #[pallet::call(weight = <T as crate::Config>::WeightInfo)]
/// impl<T: Config> Pallet<T> {
/// pub fn create(
/// ```
///
/// It is possible to use this syntax together with instantiated pallets by using `Config<I>`
/// instead.
///
/// ### Dev Mode
///
/// Normally the `dev_mode` sets all weights of calls without a `#[pallet::weight]` annotation
/// to zero. Now when there is a `weight` attribute on the `#[pallet::call]`, then that is used
/// instead of the zero weight. So to say: it works together with `dev_mode`.
RuntimeCall(Option<InheritedCallWeightAttr>, proc_macro2::Span),
Error(proc_macro2::Span),
RuntimeEvent(proc_macro2::Span),
RuntimeOrigin(proc_macro2::Span),
@@ -445,7 +483,7 @@ impl PalletAttr {
Self::Config(span) => *span,
Self::Pallet(span) => *span,
Self::Hooks(span) => *span,
Self::RuntimeCall(span) => *span,
Self::RuntimeCall(_, span) => *span,
Self::Error(span) => *span,
Self::RuntimeEvent(span) => *span,
Self::RuntimeOrigin(span) => *span,
@@ -477,7 +515,12 @@ impl syn::parse::Parse for PalletAttr {
} else if lookahead.peek(keyword::hooks) {
Ok(PalletAttr::Hooks(content.parse::<keyword::hooks>()?.span()))
} else if lookahead.peek(keyword::call) {
Ok(PalletAttr::RuntimeCall(content.parse::<keyword::call>()?.span()))
let span = content.parse::<keyword::call>().expect("peeked").span();
let attr = match content.is_empty() {
true => None,
false => Some(InheritedCallWeightAttr::parse(&content)?),
};
Ok(PalletAttr::RuntimeCall(attr, span))
} else if lookahead.peek(keyword::error) {
Ok(PalletAttr::Error(content.parse::<keyword::error>()?.span()))
} else if lookahead.peek(keyword::event) {
@@ -505,3 +548,33 @@ impl syn::parse::Parse for PalletAttr {
}
}
}
/// The optional weight annotation on a `#[pallet::call]` like `#[pallet::call(weight($type))]`.
#[derive(Clone)]
pub struct InheritedCallWeightAttr {
pub typename: syn::Type,
pub span: proc_macro2::Span,
}
impl syn::parse::Parse for InheritedCallWeightAttr {
// Parses `(weight($type))` or `(weight = $type)`.
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let content;
syn::parenthesized!(content in input);
content.parse::<keyword::weight>()?;
let lookahead = content.lookahead1();
let buffer = if lookahead.peek(syn::token::Paren) {
let inner;
syn::parenthesized!(inner in content);
inner
} else if lookahead.peek(syn::Token![=]) {
content.parse::<syn::Token![=]>().expect("peeked");
content
} else {
return Err(lookahead.error())
};
Ok(Self { typename: buffer.parse()?, span: input.span() })
}
}
@@ -61,8 +61,8 @@ pub enum PalletStructAttr {
impl PalletStructAttr {
fn span(&self) -> proc_macro2::Span {
match self {
Self::GenerateStore { span, .. } => *span,
Self::WithoutStorageInfoTrait(span) => *span,
Self::GenerateStore { span, .. } |
Self::WithoutStorageInfoTrait(span) |
Self::StorageVersion { span, .. } => *span,
}
}