referrerpolicy=no-referrer-when-downgrade

frame_support_procedural/pallet/parse/
event.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use super::helper;
19use quote::ToTokens;
20use syn::spanned::Spanned;
21
22/// List of additional token to be used for parsing.
23mod keyword {
24	syn::custom_keyword!(Event);
25	syn::custom_keyword!(pallet);
26	syn::custom_keyword!(generate_deposit);
27	syn::custom_keyword!(deposit_event);
28}
29
30/// Definition for pallet event enum.
31pub struct EventDef {
32	/// The index of event item in pallet module.
33	pub index: usize,
34	/// The keyword Event used (contains span).
35	pub event: keyword::Event,
36	/// A set of usage of instance, must be check for consistency with trait.
37	pub instances: Vec<helper::InstanceUsage>,
38	/// The kind of generic the type `Event` has.
39	pub gen_kind: super::GenericKind,
40	/// Whether the function `deposit_event` must be generated.
41	pub deposit_event: Option<PalletEventDepositAttr>,
42	/// Where clause used in event definition.
43	pub where_clause: Option<syn::WhereClause>,
44	/// The span of the pallet::event attribute.
45	pub attr_span: proc_macro2::Span,
46}
47
48/// Attribute for a pallet's Event.
49///
50/// Syntax is:
51/// * `#[pallet::generate_deposit($vis fn deposit_event)]`
52pub struct PalletEventDepositAttr {
53	pub fn_vis: syn::Visibility,
54	// Span for the keyword deposit_event
55	pub fn_span: proc_macro2::Span,
56	// Span of the attribute
57	pub span: proc_macro2::Span,
58}
59
60impl syn::parse::Parse for PalletEventDepositAttr {
61	fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
62		input.parse::<syn::Token![#]>()?;
63		let content;
64		syn::bracketed!(content in input);
65		content.parse::<keyword::pallet>()?;
66		content.parse::<syn::Token![::]>()?;
67
68		let span = content.parse::<keyword::generate_deposit>()?.span();
69		let generate_content;
70		syn::parenthesized!(generate_content in content);
71		let fn_vis = generate_content.parse::<syn::Visibility>()?;
72		generate_content.parse::<syn::Token![fn]>()?;
73		let fn_span = generate_content.parse::<keyword::deposit_event>()?.span();
74
75		Ok(PalletEventDepositAttr { fn_vis, span, fn_span })
76	}
77}
78
79struct PalletEventAttrInfo {
80	deposit_event: Option<PalletEventDepositAttr>,
81}
82
83impl PalletEventAttrInfo {
84	fn from_attrs(attrs: Vec<PalletEventDepositAttr>) -> syn::Result<Self> {
85		let mut deposit_event = None;
86		for attr in attrs {
87			if deposit_event.is_none() {
88				deposit_event = Some(attr)
89			} else {
90				return Err(syn::Error::new(attr.span, "Duplicate attribute"))
91			}
92		}
93
94		Ok(PalletEventAttrInfo { deposit_event })
95	}
96}
97
98impl EventDef {
99	pub fn try_from(
100		attr_span: proc_macro2::Span,
101		index: usize,
102		item: &mut syn::Item,
103	) -> syn::Result<Self> {
104		let item = if let syn::Item::Enum(item) = item {
105			item
106		} else {
107			return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected enum item"))
108		};
109
110		crate::deprecation::prevent_deprecation_attr_on_outer_enum(&item.attrs)?;
111
112		let event_attrs: Vec<PalletEventDepositAttr> =
113			helper::take_item_pallet_attrs(&mut item.attrs)?;
114		let attr_info = PalletEventAttrInfo::from_attrs(event_attrs)?;
115		let deposit_event = attr_info.deposit_event;
116
117		if !matches!(item.vis, syn::Visibility::Public(_)) {
118			let msg = "Invalid pallet::event, `Event` must be public";
119			return Err(syn::Error::new(item.span(), msg))
120		}
121
122		let where_clause = item.generics.where_clause.clone();
123
124		let mut instances = vec![];
125		// NOTE: Event is not allowed to be only generic on I because it is not supported
126		// by construct_runtime.
127		if let Some(u) = helper::check_type_def_optional_gen(&item.generics, item.ident.span())? {
128			instances.push(u);
129		} else {
130			// construct_runtime only allow non generic event for non instantiable pallet.
131			instances.push(helper::InstanceUsage { has_instance: false, span: item.ident.span() })
132		}
133
134		let has_instance = item.generics.type_params().any(|t| t.ident == "I");
135		let has_config = item.generics.type_params().any(|t| t.ident == "T");
136		let gen_kind = super::GenericKind::from_gens(has_config, has_instance)
137			.expect("Checked by `helper::check_type_def_optional_gen` above");
138
139		let event = syn::parse2::<keyword::Event>(item.ident.to_token_stream())?;
140
141		Ok(EventDef { attr_span, index, instances, deposit_event, event, gen_kind, where_clause })
142	}
143}