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	/// event attributes
47	pub attrs: Vec<syn::Attribute>,
48}
49
50/// Attribute for a pallet's Event.
51///
52/// Syntax is:
53/// * `#[pallet::generate_deposit($vis fn deposit_event)]`
54pub struct PalletEventDepositAttr {
55	pub fn_vis: syn::Visibility,
56	// Span for the keyword deposit_event
57	pub fn_span: proc_macro2::Span,
58	// Span of the attribute
59	pub span: proc_macro2::Span,
60}
61
62impl syn::parse::Parse for PalletEventDepositAttr {
63	fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
64		input.parse::<syn::Token![#]>()?;
65		let content;
66		syn::bracketed!(content in input);
67		content.parse::<keyword::pallet>()?;
68		content.parse::<syn::Token![::]>()?;
69
70		let span = content.parse::<keyword::generate_deposit>()?.span();
71		let generate_content;
72		syn::parenthesized!(generate_content in content);
73		let fn_vis = generate_content.parse::<syn::Visibility>()?;
74		generate_content.parse::<syn::Token![fn]>()?;
75		let fn_span = generate_content.parse::<keyword::deposit_event>()?.span();
76
77		Ok(PalletEventDepositAttr { fn_vis, span, fn_span })
78	}
79}
80
81struct PalletEventAttrInfo {
82	deposit_event: Option<PalletEventDepositAttr>,
83}
84
85impl PalletEventAttrInfo {
86	fn from_attrs(attrs: Vec<PalletEventDepositAttr>) -> syn::Result<Self> {
87		let mut deposit_event = None;
88		for attr in attrs {
89			if deposit_event.is_none() {
90				deposit_event = Some(attr)
91			} else {
92				return Err(syn::Error::new(attr.span, "Duplicate attribute"))
93			}
94		}
95
96		Ok(PalletEventAttrInfo { deposit_event })
97	}
98}
99
100impl EventDef {
101	pub fn try_from(
102		attr_span: proc_macro2::Span,
103		index: usize,
104		item: &mut syn::Item,
105	) -> syn::Result<Self> {
106		let item = if let syn::Item::Enum(item) = item {
107			item
108		} else {
109			return Err(syn::Error::new(item.span(), "Invalid pallet::event, expected enum item"))
110		};
111		let attrs = item.attrs.clone();
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 {
142			attr_span,
143			index,
144			instances,
145			deposit_event,
146			event,
147			gen_kind,
148			where_clause,
149			attrs,
150		})
151	}
152}