git.delta.rocks / unique-network / refs/commits / fe70dfc798ca

difftreelog

source

crates/evm-coder/procedural/src/solidity_interface.rs27.4 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![allow(dead_code)]1819// NOTE: In order to understand this Rust macro better, first read this chapter20// about Procedural Macros in Rust book:21// https://doc.rust-lang.org/reference/procedural-macros.html2223use proc_macro2::TokenStream;24use quote::{quote, format_ident};25use inflector::cases;26use syn::{27	Expr, FnArg, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta, MetaNameValue,28	PatType, ReturnType, Type,29	spanned::Spanned,30	parse::{Parse, ParseStream},31	parenthesized, Token, LitInt, LitStr,32};3334use crate::{35	parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment, parse_result_ok,36	pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,37	snake_ident_to_screaming,38};3940struct Is {41	name: Ident,42	pascal_call_name: Ident,43	snake_call_name: Ident,44	via: Option<(Type, Ident)>,45	condition: Option<Expr>,46}47impl Is {48	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {49		let name = &self.name;50		let pascal_call_name = &self.pascal_call_name;51		quote! {52			#name(#pascal_call_name #gen_ref)53		}54	}5556	fn expand_interface_id(&self) -> proc_macro2::TokenStream {57		let pascal_call_name = &self.pascal_call_name;58		quote! {59			interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());60		}61	}6263	fn expand_supports_interface(64		&self,65		generics: &proc_macro2::TokenStream,66	) -> proc_macro2::TokenStream {67		let pascal_call_name = &self.pascal_call_name;68		let condition = self.condition.as_ref().map(|condition| {69			quote! {70				(#condition) &&71			}72		});73		quote! {74			#condition <#pascal_call_name #generics>::supports_interface(this, interface_id)75		}76	}7778	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {79		let name = &self.name;80		quote! {81			Self::#name(call) => call.weight()82		}83	}8485	fn expand_variant_call(86		&self,87		call_name: &proc_macro2::Ident,88		generics: &proc_macro2::TokenStream,89	) -> proc_macro2::TokenStream {90		let name = &self.name;91		let pascal_call_name = &self.pascal_call_name;92		let via_typ = self93			.via94			.as_ref()95			.map(|(t, _)| quote! {#t})96			.unwrap_or_else(|| quote! {Self});97		let via_map = self98			.via99			.as_ref()100			.map(|(_, i)| quote! {.#i()})101			.unwrap_or_default();102		let condition = self.condition.as_ref().map(|condition| {103			quote! {104				if ({let this = &self; (#condition)})105			}106		});107		quote! {108			#call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {109				call,110				caller: c.caller,111				value: c.value,112			})113		}114	}115116	fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {117		let name = &self.name;118		let pascal_call_name = &self.pascal_call_name;119		quote! {120			if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {121				return Ok(Some(Self::#name(parsed_call)))122			}123		}124	}125126	fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {127		let pascal_call_name = &self.pascal_call_name;128		quote! {129			<#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);130		}131	}132133	fn expand_event_generator(&self) -> proc_macro2::TokenStream {134		let name = &self.name;135		quote! {136			#name::generate_solidity_interface(tc, is_impl);137		}138	}139}140141#[derive(Default)]142struct IsList(Vec<Is>);143impl Parse for IsList {144	fn parse(input: ParseStream) -> syn::Result<Self> {145		let mut out = vec![];146		loop {147			if input.is_empty() {148				break;149			}150			let name = input.parse::<Ident>()?;151			let lookahead = input.lookahead1();152153			let mut condition: Option<Expr> = None;154			let mut via: Option<(Type, Ident)> = None;155156			if lookahead.peek(syn::token::Paren) {157				let contents;158				parenthesized!(contents in input);159				let input = contents;160161				while !input.is_empty() {162					let lookahead = input.lookahead1();163					if lookahead.peek(Token![if]) {164						input.parse::<Token![if]>()?;165						let contents;166						parenthesized!(contents in input);167						let contents = contents.parse::<Expr>()?;168169						if condition.replace(contents).is_some() {170							return Err(syn::Error::new(input.span(), "condition is already set"));171						}172					} else if lookahead.peek(kw::via) {173						input.parse::<kw::via>()?;174						let contents;175						parenthesized!(contents in input);176177						let method = contents.parse::<Ident>()?;178						contents.parse::<kw::returns>()?;179						let ty = contents.parse::<Type>()?;180181						if via.replace((ty, method)).is_some() {182							return Err(syn::Error::new(input.span(), "via is already set"));183						}184					} else {185						return Err(lookahead.error());186					}187188					if input.peek(Token![,]) {189						input.parse::<Token![,]>()?;190					} else if !input.is_empty() {191						return Err(syn::Error::new(input.span(), "expected end"));192					}193				}194			} else if lookahead.peek(Token![,]) || input.is_empty() {195				// Pass196			} else {197				return Err(lookahead.error());198			};199			out.push(Is {200				pascal_call_name: pascal_ident_to_call(&name),201				snake_call_name: pascal_ident_to_snake_call(&name),202				name,203				via,204				condition,205			});206			if input.peek(Token![,]) {207				input.parse::<Token![,]>()?;208				continue;209			} else {210				break;211			}212		}213		Ok(Self(out))214	}215}216217pub struct InterfaceInfo {218	name: Ident,219	is: IsList,220	inline_is: IsList,221	events: IsList,222	expect_selector: Option<u32>,223}224impl Parse for InterfaceInfo {225	fn parse(input: ParseStream) -> syn::Result<Self> {226		let mut name = None;227		let mut is = None;228		let mut inline_is = None;229		let mut events = None;230		let mut expect_selector = None;231		// TODO: create proc-macro to optimize proc-macro boilerplate? :D232		loop {233			let lookahead = input.lookahead1();234			if lookahead.peek(kw::name) {235				let k = input.parse::<kw::name>()?;236				input.parse::<Token![=]>()?;237				if name.replace(input.parse::<Ident>()?).is_some() {238					return Err(syn::Error::new(k.span(), "name is already set"));239				}240			} else if lookahead.peek(kw::is) {241				let k = input.parse::<kw::is>()?;242				let contents;243				parenthesized!(contents in input);244				if is.replace(contents.parse::<IsList>()?).is_some() {245					return Err(syn::Error::new(k.span(), "is is already set"));246				}247			} else if lookahead.peek(kw::inline_is) {248				let k = input.parse::<kw::inline_is>()?;249				let contents;250				parenthesized!(contents in input);251				if inline_is.replace(contents.parse::<IsList>()?).is_some() {252					return Err(syn::Error::new(k.span(), "inline_is is already set"));253				}254			} else if lookahead.peek(kw::events) {255				let k = input.parse::<kw::events>()?;256				let contents;257				parenthesized!(contents in input);258				if events.replace(contents.parse::<IsList>()?).is_some() {259					return Err(syn::Error::new(k.span(), "events is already set"));260				}261			} else if lookahead.peek(kw::expect_selector) {262				let k = input.parse::<kw::expect_selector>()?;263				input.parse::<Token![=]>()?;264				let value = input.parse::<LitInt>()?;265				if expect_selector266					.replace(value.base10_parse::<u32>()?)267					.is_some()268				{269					return Err(syn::Error::new(k.span(), "expect_selector is already set"));270				}271			} else if input.is_empty() {272				break;273			} else {274				return Err(lookahead.error());275			}276			if input.peek(Token![,]) {277				input.parse::<Token![,]>()?;278			} else {279				break;280			}281		}282		Ok(Self {283			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,284			is: is.unwrap_or_default(),285			inline_is: inline_is.unwrap_or_default(),286			events: events.unwrap_or_default(),287			expect_selector,288		})289	}290}291292struct MethodInfo {293	rename_selector: Option<String>,294	hide: bool,295}296impl Parse for MethodInfo {297	fn parse(input: ParseStream) -> syn::Result<Self> {298		let mut rename_selector = None;299		let mut hide = false;300		while !input.is_empty() {301			let lookahead = input.lookahead1();302			if lookahead.peek(kw::rename_selector) {303				let k = input.parse::<kw::rename_selector>()?;304				input.parse::<Token![=]>()?;305				if rename_selector306					.replace(input.parse::<LitStr>()?.value())307					.is_some()308				{309					return Err(syn::Error::new(k.span(), "rename_selector is already set"));310				}311			} else if lookahead.peek(kw::hide) {312				input.parse::<kw::hide>()?;313				hide = true;314			} else {315				return Err(lookahead.error());316			}317318			if input.peek(Token![,]) {319				input.parse::<Token![,]>()?;320			} else if !input.is_empty() {321				return Err(syn::Error::new(input.span(), "expected end"));322			}323		}324		Ok(Self {325			rename_selector,326			hide,327		})328	}329}330331trait AbiType {332	fn plain(&self) -> syn::Result<&Ident>;333	fn is_value(&self) -> bool;334	fn is_caller(&self) -> bool;335	fn is_special(&self) -> bool;336}337338impl AbiType for Type {339	fn plain(&self) -> syn::Result<&Ident> {340		let path = parse_path(self)?;341		let segment = parse_path_segment(path)?;342		if !segment.arguments.is_empty() {343			return Err(syn::Error::new(self.span(), "Not plain type"));344		}345		Ok(&segment.ident)346	}347348	fn is_value(&self) -> bool {349		if let Ok(ident) = self.plain() {350			return ident == "value";351		}352		false353	}354355	fn is_caller(&self) -> bool {356		if let Ok(ident) = self.plain() {357			return ident == "caller";358		}359		false360	}361362	fn is_special(&self) -> bool {363		self.is_caller() || self.is_value()364	}365}366367#[derive(Debug)]368struct MethodArg {369	name: Ident,370	camel_name: String,371	ty: Type,372}373impl MethodArg {374	fn try_from(value: &PatType) -> syn::Result<Self> {375		let name = parse_ident_from_pat(&value.pat)?.clone();376		Ok(Self {377			camel_name: cases::camelcase::to_camel_case(&name.to_string()),378			name,379			ty: value.ty.as_ref().clone(),380		})381	}382	fn is_value(&self) -> bool {383		self.ty.is_value()384	}385	fn is_caller(&self) -> bool {386		self.ty.is_caller()387	}388	fn is_special(&self) -> bool {389		self.ty.is_special()390	}391392	fn expand_call_def(&self) -> proc_macro2::TokenStream {393		assert!(!self.is_special());394		let name = &self.name;395		let ty = &self.ty;396397		quote! {398			#name: #ty399		}400	}401402	fn expand_parse(&self) -> proc_macro2::TokenStream {403		assert!(!self.is_special());404		let name = &self.name;405		let ty = &self.ty;406		quote! {407			#name: <#ty>::abi_read(reader)?408		}409	}410411	fn expand_call_arg(&self) -> proc_macro2::TokenStream {412		if self.is_value() {413			quote! {414				c.value.clone()415			}416		} else if self.is_caller() {417			quote! {418				c.caller.clone()419			}420		} else {421			let name = &self.name;422			quote! {423				#name424			}425		}426	}427428	fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {429		let camel_name = &self.camel_name.to_string();430		let ty = &self.ty;431		quote! {432			<NamedArgument<#ty>>::new(#camel_name)433		}434	}435}436437#[derive(PartialEq)]438enum Mutability {439	Mutable,440	View,441	Pure,442}443444/// Group all keywords for this macro. Usage example:445/// #[solidity_interface(name = "B", inline_is(A))]446mod kw {447	syn::custom_keyword!(weight);448449	syn::custom_keyword!(via);450	syn::custom_keyword!(returns);451	syn::custom_keyword!(name);452	syn::custom_keyword!(is);453	syn::custom_keyword!(inline_is);454	syn::custom_keyword!(events);455	syn::custom_keyword!(expect_selector);456457	syn::custom_keyword!(rename_selector);458	syn::custom_keyword!(hide);459}460461/// Rust methods are parsed into this structure when Solidity code is generated462struct Method {463	name: Ident,464	camel_name: String,465	pascal_name: Ident,466	screaming_name: Ident,467	hide: bool,468	args: Vec<MethodArg>,469	has_normal_args: bool,470	has_value_args: bool,471	mutability: Mutability,472	result: Type,473	weight: Option<Expr>,474	docs: Vec<String>,475}476impl Method {477	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {478		let mut info = MethodInfo {479			rename_selector: None,480			hide: false,481		};482		let mut docs = Vec::new();483		let mut weight = None;484		for attr in &value.attrs {485			let ident = parse_ident_from_path(&attr.path, false)?;486			if ident == "solidity" {487				info = attr.parse_args::<MethodInfo>()?;488			} else if ident == "doc" {489				let args = attr.parse_meta().unwrap();490				let value = match args {491					Meta::NameValue(MetaNameValue {492						lit: Lit::Str(str), ..493					}) => str.value(),494					_ => unreachable!(),495				};496				docs.push(value);497			} else if ident == "weight" {498				weight = Some(attr.parse_args::<Expr>()?);499			}500		}501		let ident = &value.sig.ident;502		let ident_str = ident.to_string();503		if !cases::snakecase::is_snake_case(&ident_str) {504			return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));505		}506507		let mut mutability = Mutability::Pure;508509		if let Some(FnArg::Receiver(receiver)) = value510			.sig511			.inputs512			.iter()513			.find(|arg| matches!(arg, FnArg::Receiver(_)))514		{515			if receiver.reference.is_none() {516				return Err(syn::Error::new(517					receiver.span(),518					"receiver should be by ref",519				));520			}521			if receiver.mutability.is_some() {522				mutability = Mutability::Mutable;523			} else {524				mutability = Mutability::View;525			}526		}527		let mut args = Vec::new();528		for typ in value529			.sig530			.inputs531			.iter()532			.filter(|arg| matches!(arg, FnArg::Typed(_)))533		{534			let typ = match typ {535				FnArg::Typed(typ) => typ,536				_ => unreachable!(),537			};538			args.push(MethodArg::try_from(typ)?);539		}540541		if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {542			return Err(syn::Error::new(543				args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),544				"payable function should be mutable",545			));546		}547548		let result = match &value.sig.output {549			ReturnType::Type(_, ty) => ty,550			_ => return Err(syn::Error::new(value.sig.output.span(), "interface method should return Result<value>\nif there is no value to return - specify void (which is alias to unit)")),551		};552		let result = parse_result_ok(result)?;553554		let camel_name = info555			.rename_selector556			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));557		let has_normal_args = args.iter().filter(|arg| !arg.is_special()).count() != 0;558		let has_value_args = args.iter().any(|a| a.is_value());559560		Ok(Self {561			name: ident.clone(),562			camel_name,563			pascal_name: snake_ident_to_pascal(ident),564			screaming_name: snake_ident_to_screaming(ident),565			hide: info.hide,566			args,567			has_normal_args,568			has_value_args,569			mutability,570			result: result.clone(),571			weight,572			docs,573		})574	}575	fn expand_call_def(&self) -> proc_macro2::TokenStream {576		let defs = self577			.args578			.iter()579			.filter(|a| !a.is_special())580			.map(|a| a.expand_call_def());581		let pascal_name = &self.pascal_name;582		let docs = &self.docs;583584		if self.has_normal_args {585			quote! {586				#(#[doc = #docs])*587				#[allow(missing_docs)]588				#pascal_name {589					#(590						#defs,591					)*592				}593			}594		} else {595			quote! {#pascal_name}596		}597	}598599	fn expand_const(&self) -> proc_macro2::TokenStream {600		let screaming_name = &self.screaming_name;601		let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);602		let custom_signature = self.expand_custom_signature();603		quote! {604			const #screaming_name_signature: ::evm_coder::custom_signature::SignatureUnit = #custom_signature;605			const #screaming_name: ::evm_coder::types::bytes4 = {606				let mut sum = ::evm_coder::sha3_const::Keccak256::new();607				let mut pos = 0;608				while pos < Self::#screaming_name_signature.len {609					sum = sum.update(&[Self::#screaming_name_signature.data[pos]; 1]);610					pos += 1;611				}612				let a = sum.finalize();613				[a[0], a[1], a[2], a[3]]614			};615		}616	}617618	fn expand_interface_id(&self) -> proc_macro2::TokenStream {619		let screaming_name = &self.screaming_name;620		quote! {621			interface_id ^= u32::from_be_bytes(Self::#screaming_name);622		}623	}624625	fn expand_parse(&self) -> proc_macro2::TokenStream {626		let pascal_name = &self.pascal_name;627		let screaming_name = &self.screaming_name;628		if self.has_normal_args {629			let parsers = self630				.args631				.iter()632				.filter(|a| !a.is_special())633				.map(|a| a.expand_parse());634			quote! {635				Self::#screaming_name => return Ok(Some(Self::#pascal_name {636					#(637						#parsers,638					)*639				}))640			}641		} else {642			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }643		}644	}645646	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {647		let pascal_name = &self.pascal_name;648		let name = &self.name;649650		let matcher = if self.has_normal_args {651			let names = self652				.args653				.iter()654				.filter(|a| !a.is_special())655				.map(|a| &a.name);656657			quote! {{658				#(659					#names,660				)*661			}}662		} else {663			quote! {}664		};665666		let receiver = match self.mutability {667			Mutability::Mutable | Mutability::View => quote! {self.},668			Mutability::Pure => quote! {Self::},669		};670		let args = self.args.iter().map(|a| a.expand_call_arg());671672		quote! {673			#call_name::#pascal_name #matcher => {674				let result = #receiver #name(675					#(676						#args,677					)*678				)?;679				(&result).to_result()680			}681		}682	}683684	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {685		let pascal_name = &self.pascal_name;686		if let Some(weight) = &self.weight {687			let matcher = if self.has_normal_args {688				let names = self689					.args690					.iter()691					.filter(|a| !a.is_special())692					.map(|a| &a.name);693694				quote! {{695					#(696						#names,697					)*698				}}699			} else {700				quote! {}701			};702			quote! {703				Self::#pascal_name #matcher => (#weight).into()704			}705		} else {706			let matcher = if self.has_normal_args {707				quote! {{..}}708			} else {709				quote! {}710			};711			quote! {712				Self::#pascal_name #matcher => ().into()713			}714		}715	}716717	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {718		let mut args = TokenStream::new();719720		let mut has_params = false;721		for arg in self.args.iter().filter(|a| !a.is_special()) {722			has_params = true;723			let ty = &arg.ty;724			args.extend(quote! {nameof(<#ty>::SIGNATURE)});725			args.extend(quote! {fixed(",")})726		}727728		// Remove trailing comma729		if has_params {730			args.extend(quote! {shift_left(1)})731		}732733		let func_name = self.camel_name.clone();734		quote! { ::evm_coder::make_signature!(new fixed(#func_name) fixed("(") #args fixed(")")) }735	}736737	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {738		let camel_name = &self.camel_name;739		let mutability = match self.mutability {740			Mutability::Mutable => quote! {SolidityMutability::Mutable},741			Mutability::View => quote! { SolidityMutability::View },742			Mutability::Pure => quote! {SolidityMutability::Pure},743		};744		let result = &self.result;745746		let args = self747			.args748			.iter()749			.filter(|a| !a.is_special())750			.map(MethodArg::expand_solidity_argument);751		let docs = &self.docs;752		let screaming_name = &self.screaming_name;753		let hide = self.hide;754		let custom_signature = self.expand_custom_signature();755		let is_payable = self.has_value_args;756757		quote! {758			SolidityFunction {759				docs: &[#(#docs),*],760				hide: #hide,761				selector: u32::from_be_bytes(Self::#screaming_name),762				custom_signature: #custom_signature,763				name: #camel_name,764				mutability: #mutability,765				is_payable: #is_payable,766				args: (767					#(768						#args,769					)*770				),771				result: <UnnamedArgument<#result>>::default(),772			}773		}774	}775}776777fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {778	if gen.params.is_empty() {779		return quote! {};780	}781	let params = gen.params.iter().map(|p| match p {782		syn::GenericParam::Type(id) => {783			let v = &id.ident;784			quote! {#v}785		}786		syn::GenericParam::Lifetime(lt) => {787			let v = &lt.lifetime;788			quote! {#v}789		}790		syn::GenericParam::Const(c) => {791			let i = &c.ident;792			quote! {#i}793		}794	});795	quote! { #(#params),* }796}797fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {798	if gen.params.is_empty() {799		return quote! {};800	}801	let list = generics_list(gen);802	quote! { <#list> }803}804fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {805	let list = generics_list(gen);806	if gen.params.len() == 1 {807		quote! {#list}808	} else {809		quote! { (#list) }810	}811}812813pub struct SolidityInterface {814	generics: Generics,815	name: Box<syn::Type>,816	info: InterfaceInfo,817	methods: Vec<Method>,818	docs: Vec<String>,819}820impl SolidityInterface {821	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {822		let mut methods = Vec::new();823824		for item in &value.items {825			if let ImplItem::Method(method) = item {826				methods.push(Method::try_from(method)?)827			}828		}829		let mut docs = vec![];830		for attr in &value.attrs {831			let ident = parse_ident_from_path(&attr.path, false)?;832			if ident == "doc" {833				let args = attr.parse_meta().unwrap();834				let value = match args {835					Meta::NameValue(MetaNameValue {836						lit: Lit::Str(str), ..837					}) => str.value(),838					_ => unreachable!(),839				};840				docs.push(value);841			}842		}843		Ok(Self {844			generics: value.generics.clone(),845			name: value.self_ty.clone(),846			info,847			methods,848			docs,849		})850	}851	pub fn expand(self) -> proc_macro2::TokenStream {852		let name = self.name;853854		let solidity_name = self.info.name.to_string();855		let call_name = pascal_ident_to_call(&self.info.name);856		let generics = self.generics;857		let gen_ref = generics_reference(&generics);858		let gen_data = generics_data(&generics);859		let gen_where = &generics.where_clause;860861		let call_sub = self862			.info863			.inline_is864			.0865			.iter()866			.chain(self.info.is.0.iter())867			.map(|c| Is::expand_call_def(c, &gen_ref));868		let call_parse = self869			.info870			.inline_is871			.0872			.iter()873			.chain(self.info.is.0.iter())874			.map(|is| Is::expand_parse(is, &gen_ref));875		let call_variants = self876			.info877			.inline_is878			.0879			.iter()880			.chain(self.info.is.0.iter())881			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));882		let weight_variants = self883			.info884			.inline_is885			.0886			.iter()887			.chain(self.info.is.0.iter())888			.map(Is::expand_variant_weight);889890		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);891		let supports_interface = self892			.info893			.is894			.0895			.iter()896			.map(|is| Is::expand_supports_interface(is, &gen_ref));897898		let calls = self.methods.iter().map(Method::expand_call_def);899		let consts = self.methods.iter().map(Method::expand_const);900		let interface_id = self.methods.iter().map(Method::expand_interface_id);901		let parsers = self.methods.iter().map(Method::expand_parse);902		let call_variants_this = self903			.methods904			.iter()905			.map(|m| Method::expand_variant_call(m, &call_name));906		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);907		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);908909		// TODO: Inline inline_is910		let solidity_is = self911			.info912			.is913			.0914			.iter()915			.chain(self.info.inline_is.0.iter())916			.map(|is| is.name.to_string());917		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());918		let solidity_generators = self919			.info920			.is921			.0922			.iter()923			.chain(self.info.inline_is.0.iter())924			.map(|is| Is::expand_generator(is, &gen_ref));925		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);926927		let docs = &self.docs;928929		quote! {930			#[derive(Debug)]931			#(#[doc = #docs])*932			pub enum #call_name #gen_ref {933				/// Inherited method934				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),935				#(936					#calls,937				)*938				#(939					#call_sub,940				)*941			}942			impl #gen_ref #call_name #gen_ref {943				#(944					#consts945				)*946				/// Return this call ERC165 selector947				pub fn interface_id() -> ::evm_coder::types::bytes4 {948					let mut interface_id = 0;949					#(#interface_id)*950					#(#inline_interface_id)*951					u32::to_be_bytes(interface_id)952				}953				/// Generate solidity definitions for methods described in this interface954				#[cfg(feature = "stubgen")]955				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {956					use evm_coder::solidity::*;957					use core::fmt::Write;958					let interface = SolidityInterface {959						docs: &[#(#docs),*],960						name: #solidity_name,961						selector: Self::interface_id(),962						is: &["Dummy", "ERC165", #(963							#solidity_is,964						)* #(965							#solidity_events_is,966						)* ],967						functions: (#(968							#solidity_functions,969						)*),970					};971972					let mut out = ::evm_coder::types::string::new();973					if #solidity_name.starts_with("Inline") {974						out.push_str("/// @dev inlined interface\n");975					}976					let _ = interface.format(is_impl, &mut out, tc);977					tc.collect(out);978					#(979						#solidity_event_generators980					)*981					#(982						#solidity_generators983					)*984					if is_impl {985						tc.collect("/// @dev common stubs holder\ncontract Dummy {\n\tuint8 dummy;\n\tstring stub_error = \"this contract is implemented in native\";\n}\ncontract ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool) {\n\t\trequire(false, stub_error);\n\t\tinterfaceID;\n\t\treturn true;\n\t}\n}\n".into());986					} else {987						tc.collect("/// @dev common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());988					}989				}990			}991			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {992				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {993					use ::evm_coder::abi::AbiRead;994					match method_id {995						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(996							::evm_coder::ERC165Call::parse(method_id, reader)?997							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))998						),999						#(1000							#parsers,1001						)*1002						_ => {},1003					}1004					#(1005						#call_parse1006					)else*1007					return Ok(None);1008				}1009			}1010			impl #generics #call_name #gen_ref1011			#gen_where1012			{1013				/// Is this contract implements specified ERC165 selector1014				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1015					interface_id != u32::to_be_bytes(0xffffff) && (1016						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1017						interface_id == Self::interface_id()1018						#(1019							|| #supports_interface1020						)*1021					)1022				}1023			}1024			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1025			#gen_where1026			{1027				#[allow(unused_variables)]1028				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1029					match self {1030						#(1031							#weight_variants,1032						)*1033						// TODO: It should be very cheap, but not free1034						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1035						#(1036							#weight_variants_this,1037						)*1038					}1039				}1040			}1041			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1042			#gen_where1043			{1044				#[allow(unreachable_code)] // In case of no inner calls1045				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1046					use ::evm_coder::abi::AbiWrite;1047					match c.call {1048						#(1049							#call_variants,1050						)*1051						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1052							let mut writer = ::evm_coder::abi::AbiWriter::default();1053							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1054							return Ok(writer.into());1055						}1056						_ => {},1057					}1058					let mut writer = ::evm_coder::abi::AbiWriter::default();1059					match c.call {1060						#(1061							#call_variants_this,1062						)*1063						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1064					}1065				}1066			}1067		}1068	}1069}