git.delta.rocks / unique-network / refs/commits / 01896baccffe

difftreelog

source

crates/evm-coder/procedural/src/solidity_interface.rs32.2 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, Group};24use quote::{quote, ToTokens};25use inflector::cases;26use std::fmt::Write;27use syn::{28	Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,29	MetaNameValue, PatType, PathArguments, ReturnType, Type,30	spanned::Spanned,31	parse::{Parse, ParseStream},32	parenthesized, Token, LitInt, LitStr,33};3435use crate::{36	fn_selector_str, parse_ident_from_pat, parse_ident_from_path, parse_path, parse_path_segment,37	parse_result_ok, pascal_ident_to_call, pascal_ident_to_snake_call, snake_ident_to_pascal,38	snake_ident_to_screaming,39};4041struct Is {42	name: Ident,43	pascal_call_name: Ident,44	snake_call_name: Ident,45	via: Option<(Type, Ident)>,46	condition: Option<Expr>,47}48impl Is {49	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {50		let name = &self.name;51		let pascal_call_name = &self.pascal_call_name;52		quote! {53			#name(#pascal_call_name #gen_ref)54		}55	}5657	fn expand_interface_id(&self) -> proc_macro2::TokenStream {58		let pascal_call_name = &self.pascal_call_name;59		quote! {60			interface_id ^= u32::from_be_bytes(#pascal_call_name::interface_id());61		}62	}6364	fn expand_supports_interface(65		&self,66		generics: &proc_macro2::TokenStream,67	) -> proc_macro2::TokenStream {68		let pascal_call_name = &self.pascal_call_name;69		let condition = self.condition.as_ref().map(|condition| {70			quote! {71				(#condition) &&72			}73		});74		quote! {75			#condition <#pascal_call_name #generics>::supports_interface(this, interface_id)76		}77	}7879	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {80		let name = &self.name;81		quote! {82			Self::#name(call) => call.weight()83		}84	}8586	fn expand_variant_call(87		&self,88		call_name: &proc_macro2::Ident,89		generics: &proc_macro2::TokenStream,90	) -> proc_macro2::TokenStream {91		let name = &self.name;92		let pascal_call_name = &self.pascal_call_name;93		let via_typ = self94			.via95			.as_ref()96			.map(|(t, _)| quote! {#t})97			.unwrap_or_else(|| quote! {Self});98		let via_map = self99			.via100			.as_ref()101			.map(|(_, i)| quote! {.#i()})102			.unwrap_or_default();103		let condition = self.condition.as_ref().map(|condition| {104			quote! {105				if ({let this = &self; (#condition)})106			}107		});108		quote! {109			#call_name::#name(call) #condition => return <#via_typ as ::evm_coder::Callable<#pascal_call_name #generics>>::call(self #via_map, Msg {110				call,111				caller: c.caller,112				value: c.value,113			})114		}115	}116117	fn expand_parse(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {118		let name = &self.name;119		let pascal_call_name = &self.pascal_call_name;120		quote! {121			if let Some(parsed_call) = <#pascal_call_name #generics>::parse(method_id, reader)? {122				return Ok(Some(Self::#name(parsed_call)))123			}124		}125	}126127	fn expand_generator(&self, generics: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {128		let pascal_call_name = &self.pascal_call_name;129		quote! {130			<#pascal_call_name #generics>::generate_solidity_interface(tc, is_impl);131		}132	}133134	fn expand_event_generator(&self) -> proc_macro2::TokenStream {135		let name = &self.name;136		quote! {137			#name::generate_solidity_interface(tc, is_impl);138		}139	}140}141142#[derive(Default)]143struct IsList(Vec<Is>);144impl Parse for IsList {145	fn parse(input: ParseStream) -> syn::Result<Self> {146		let mut out = vec![];147		loop {148			if input.is_empty() {149				break;150			}151			let name = input.parse::<Ident>()?;152			let lookahead = input.lookahead1();153154			let mut condition: Option<Expr> = None;155			let mut via: Option<(Type, Ident)> = None;156157			if lookahead.peek(syn::token::Paren) {158				let contents;159				parenthesized!(contents in input);160				let input = contents;161162				while !input.is_empty() {163					let lookahead = input.lookahead1();164					if lookahead.peek(Token![if]) {165						input.parse::<Token![if]>()?;166						let contents;167						parenthesized!(contents in input);168						let contents = contents.parse::<Expr>()?;169170						if condition.replace(contents).is_some() {171							return Err(syn::Error::new(input.span(), "condition is already set"));172						}173					} else if lookahead.peek(kw::via) {174						input.parse::<kw::via>()?;175						let contents;176						parenthesized!(contents in input);177178						let method = contents.parse::<Ident>()?;179						contents.parse::<kw::returns>()?;180						let ty = contents.parse::<Type>()?;181182						if via.replace((ty, method)).is_some() {183							return Err(syn::Error::new(input.span(), "via is already set"));184						}185					} else {186						return Err(lookahead.error());187					}188189					if input.peek(Token![,]) {190						input.parse::<Token![,]>()?;191					} else if !input.is_empty() {192						return Err(syn::Error::new(input.span(), "expected end"));193					}194				}195			} else if lookahead.peek(Token![,]) || input.is_empty() {196				// Pass197			} else {198				return Err(lookahead.error());199			};200			out.push(Is {201				pascal_call_name: pascal_ident_to_call(&name),202				snake_call_name: pascal_ident_to_snake_call(&name),203				name,204				via,205				condition,206			});207			if input.peek(Token![,]) {208				input.parse::<Token![,]>()?;209				continue;210			} else {211				break;212			}213		}214		Ok(Self(out))215	}216}217218pub struct InterfaceInfo {219	name: Ident,220	is: IsList,221	inline_is: IsList,222	events: IsList,223	expect_selector: Option<u32>,224}225impl Parse for InterfaceInfo {226	fn parse(input: ParseStream) -> syn::Result<Self> {227		let mut name = None;228		let mut is = None;229		let mut inline_is = None;230		let mut events = None;231		let mut expect_selector = None;232		// TODO: create proc-macro to optimize proc-macro boilerplate? :D233		loop {234			let lookahead = input.lookahead1();235			if lookahead.peek(kw::name) {236				let k = input.parse::<kw::name>()?;237				input.parse::<Token![=]>()?;238				if name.replace(input.parse::<Ident>()?).is_some() {239					return Err(syn::Error::new(k.span(), "name is already set"));240				}241			} else if lookahead.peek(kw::is) {242				let k = input.parse::<kw::is>()?;243				let contents;244				parenthesized!(contents in input);245				if is.replace(contents.parse::<IsList>()?).is_some() {246					return Err(syn::Error::new(k.span(), "is is already set"));247				}248			} else if lookahead.peek(kw::inline_is) {249				let k = input.parse::<kw::inline_is>()?;250				let contents;251				parenthesized!(contents in input);252				if inline_is.replace(contents.parse::<IsList>()?).is_some() {253					return Err(syn::Error::new(k.span(), "inline_is is already set"));254				}255			} else if lookahead.peek(kw::events) {256				let k = input.parse::<kw::events>()?;257				let contents;258				parenthesized!(contents in input);259				if events.replace(contents.parse::<IsList>()?).is_some() {260					return Err(syn::Error::new(k.span(), "events is already set"));261				}262			} else if lookahead.peek(kw::expect_selector) {263				let k = input.parse::<kw::expect_selector>()?;264				input.parse::<Token![=]>()?;265				let value = input.parse::<LitInt>()?;266				if expect_selector267					.replace(value.base10_parse::<u32>()?)268					.is_some()269				{270					return Err(syn::Error::new(k.span(), "expect_selector is already set"));271				}272			} else if input.is_empty() {273				break;274			} else {275				return Err(lookahead.error());276			}277			if input.peek(Token![,]) {278				input.parse::<Token![,]>()?;279			} else {280				break;281			}282		}283		Ok(Self {284			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,285			is: is.unwrap_or_default(),286			inline_is: inline_is.unwrap_or_default(),287			events: events.unwrap_or_default(),288			expect_selector,289		})290	}291}292293struct MethodInfo {294	rename_selector: Option<String>,295	hide: bool,296}297impl Parse for MethodInfo {298	fn parse(input: ParseStream) -> syn::Result<Self> {299		let mut rename_selector = None;300		let mut hide = false;301		while !input.is_empty() {302			let lookahead = input.lookahead1();303			if lookahead.peek(kw::rename_selector) {304				let k = input.parse::<kw::rename_selector>()?;305				input.parse::<Token![=]>()?;306				if rename_selector307					.replace(input.parse::<LitStr>()?.value())308					.is_some()309				{310					return Err(syn::Error::new(k.span(), "rename_selector is already set"));311				}312			} else if lookahead.peek(kw::hide) {313				input.parse::<kw::hide>()?;314				hide = true;315			} else {316				return Err(lookahead.error());317			}318319			if input.peek(Token![,]) {320				input.parse::<Token![,]>()?;321			} else if !input.is_empty() {322				return Err(syn::Error::new(input.span(), "expected end"));323			}324		}325		Ok(Self {326			rename_selector,327			hide,328		})329	}330}331332#[derive(Debug)]333enum AbiType {334	// type335	Plain(Ident),336	// (type1,type2)337	Tuple(Vec<AbiType>),338	// type[]339	Vec(Box<AbiType>),340	// type[20]341	Array(Box<AbiType>, usize),342}343impl AbiType {344	fn try_from(value: &Type) -> syn::Result<Self> {345		let value = Self::try_maybe_special_from(value)?;346		if value.is_special() {347			return Err(syn::Error::new(value.span(), "unexpected special type"));348		}349		Ok(value)350	}351	fn try_maybe_special_from(value: &Type) -> syn::Result<Self> {352		match value {353			Type::Array(arr) => {354				let wrapped = AbiType::try_from(&arr.elem)?;355				match &arr.len {356					Expr::Lit(l) => match &l.lit {357						Lit::Int(i) => {358							let num = i.base10_parse::<usize>()?;359							Ok(AbiType::Array(Box::new(wrapped), num as usize))360						}361						_ => Err(syn::Error::new(arr.len.span(), "should be int literal")),362					},363					_ => Err(syn::Error::new(arr.len.span(), "should be literal")),364				}365			}366			Type::Path(_) => {367				let path = parse_path(value)?;368				let segment = parse_path_segment(path)?;369				if segment.ident == "Vec" {370					let args = match &segment.arguments {371						PathArguments::AngleBracketed(e) => e,372						_ => {373							return Err(syn::Error::new(374								segment.arguments.span(),375								"missing Vec generic",376							))377						}378					};379					let args = &args.args;380					if args.len() != 1 {381						return Err(syn::Error::new(382							args.span(),383							"expected only one generic for vec",384						));385					}386					let arg = args.first().expect("first arg");387388					let ty = match arg {389						GenericArgument::Type(ty) => ty,390						_ => {391							return Err(syn::Error::new(392								arg.span(),393								"expected first generic to be type",394							))395						}396					};397398					let wrapped = AbiType::try_from(ty)?;399					Ok(Self::Vec(Box::new(wrapped)))400				} else {401					if !segment.arguments.is_empty() {402						return Err(syn::Error::new(403							segment.arguments.span(),404							"unexpected generic arguments for non-vec type",405						));406					}407					Ok(Self::Plain(segment.ident.clone()))408				}409			}410			Type::Tuple(t) => {411				let mut out = Vec::with_capacity(t.elems.len());412				for el in t.elems.iter() {413					out.push(AbiType::try_from(el)?)414				}415				Ok(Self::Tuple(out))416			}417			_ => Err(syn::Error::new(418				value.span(),419				"unexpected type, only arrays, plain types and tuples are supported",420			)),421		}422	}423	fn is_value(&self) -> bool {424		matches!(self, Self::Plain(v) if v == "value")425	}426	fn is_caller(&self) -> bool {427		matches!(self, Self::Plain(v) if v == "caller")428	}429	fn is_special(&self) -> bool {430		self.is_caller() || self.is_value()431	}432	fn selector_ty_buf(&self, buf: &mut String) -> std::fmt::Result {433		match self {434			AbiType::Plain(t) => {435				write!(buf, "{}", t)436			}437			AbiType::Tuple(t) => {438				write!(buf, "(")?;439				for (i, t) in t.iter().enumerate() {440					if i != 0 {441						write!(buf, ",")?;442					}443					t.selector_ty_buf(buf)?;444				}445				write!(buf, ")")446			}447			AbiType::Vec(v) => {448				v.selector_ty_buf(buf)?;449				write!(buf, "[]")450			}451			AbiType::Array(v, len) => {452				v.selector_ty_buf(buf)?;453				write!(buf, "[{}]", len)454			}455		}456	}457	fn selector_ty(&self) -> String {458		let mut out = String::new();459		self.selector_ty_buf(&mut out).expect("no fmt error");460		out461	}462}463impl ToTokens for AbiType {464	fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {465		match self {466			AbiType::Plain(t) => tokens.extend(quote! {#t}),467			AbiType::Tuple(t) => {468				tokens.extend(quote! {(469					#(#t),*470				)});471			}472			AbiType::Vec(v) => tokens.extend(quote! {Vec<#v>}),473			AbiType::Array(v, l) => tokens.extend(quote! {[#v; #l]}),474		}475	}476}477478#[derive(Debug)]479struct MethodArg {480	name: Ident,481	camel_name: String,482	ty: AbiType,483}484impl MethodArg {485	fn try_from(value: &PatType) -> syn::Result<Self> {486		let name = parse_ident_from_pat(&value.pat)?.clone();487		Ok(Self {488			camel_name: cases::camelcase::to_camel_case(&name.to_string()),489			name,490			ty: AbiType::try_maybe_special_from(&value.ty)?,491		})492	}493	fn is_value(&self) -> bool {494		self.ty.is_value()495	}496	fn is_caller(&self) -> bool {497		self.ty.is_caller()498	}499	fn is_special(&self) -> bool {500		self.ty.is_special()501	}502	fn selector_ty(&self) -> String {503		assert!(!self.is_special());504		self.ty.selector_ty()505	}506507	fn expand_call_def(&self) -> proc_macro2::TokenStream {508		assert!(!self.is_special());509		let name = &self.name;510		let ty = &self.ty;511512		quote! {513			#name: #ty514		}515	}516517	fn expand_parse(&self) -> proc_macro2::TokenStream {518		assert!(!self.is_special());519		let name = &self.name;520		quote! {521			#name: reader.abi_read()?522		}523	}524525	fn expand_call_arg(&self) -> proc_macro2::TokenStream {526		if self.is_value() {527			quote! {528				c.value.clone()529			}530		} else if self.is_caller() {531			quote! {532				c.caller.clone()533			}534		} else {535			let name = &self.name;536			quote! {537				#name538			}539		}540	}541542	fn expand_solidity_argument(&self) -> proc_macro2::TokenStream {543		let camel_name = &self.camel_name.to_string();544		let ty = &self.ty;545		quote! {546			<NamedArgument<#ty>>::new(#camel_name)547		}548	}549}550551#[derive(PartialEq)]552enum Mutability {553	Mutable,554	View,555	Pure,556}557558/// Group all keywords for this macro. Usage example:559/// #[solidity_interface(name = "B", inline_is(A))]560mod kw {561	syn::custom_keyword!(weight);562563	syn::custom_keyword!(via);564	syn::custom_keyword!(returns);565	syn::custom_keyword!(name);566	syn::custom_keyword!(is);567	syn::custom_keyword!(inline_is);568	syn::custom_keyword!(events);569	syn::custom_keyword!(expect_selector);570571	syn::custom_keyword!(rename_selector);572	syn::custom_keyword!(hide);573}574575/// Rust methods are parsed into this structure when Solidity code is generated576struct Method {577	name: Ident,578	camel_name: String,579	pascal_name: Ident,580	screaming_name: Ident,581	selector_str: String,582	selector: u32,583	hide: bool,584	args: Vec<MethodArg>,585	has_normal_args: bool,586	has_value_args: bool,587	mutability: Mutability,588	result: Type,589	weight: Option<Expr>,590	docs: Vec<String>,591}592impl Method {593	fn try_from(value: &ImplItemMethod) -> syn::Result<Self> {594		let mut info = MethodInfo {595			rename_selector: None,596			hide: false,597		};598		let mut docs = Vec::new();599		let mut weight = None;600		for attr in &value.attrs {601			let ident = parse_ident_from_path(&attr.path, false)?;602			if ident == "solidity" {603				info = attr.parse_args::<MethodInfo>()?;604			} else if ident == "doc" {605				let args = attr.parse_meta().unwrap();606				let value = match args {607					Meta::NameValue(MetaNameValue {608						lit: Lit::Str(str), ..609					}) => str.value(),610					_ => unreachable!(),611				};612				docs.push(value);613			} else if ident == "weight" {614				weight = Some(attr.parse_args::<Expr>()?);615			}616		}617		let ident = &value.sig.ident;618		let ident_str = ident.to_string();619		if !cases::snakecase::is_snake_case(&ident_str) {620			return Err(syn::Error::new(ident.span(), "method name should be snake_cased\nif alternative solidity name needs to be set - use #[solidity] attribute"));621		}622623		let mut mutability = Mutability::Pure;624625		if let Some(FnArg::Receiver(receiver)) = value626			.sig627			.inputs628			.iter()629			.find(|arg| matches!(arg, FnArg::Receiver(_)))630		{631			if receiver.reference.is_none() {632				return Err(syn::Error::new(633					receiver.span(),634					"receiver should be by ref",635				));636			}637			if receiver.mutability.is_some() {638				mutability = Mutability::Mutable;639			} else {640				mutability = Mutability::View;641			}642		}643		let mut args = Vec::new();644		for typ in value645			.sig646			.inputs647			.iter()648			.filter(|arg| matches!(arg, FnArg::Typed(_)))649		{650			let typ = match typ {651				FnArg::Typed(typ) => typ,652				_ => unreachable!(),653			};654			args.push(MethodArg::try_from(typ)?);655		}656657		if mutability != Mutability::Mutable && args.iter().any(|arg| arg.is_value()) {658			return Err(syn::Error::new(659				args.iter().find(|arg| arg.is_value()).unwrap().ty.span(),660				"payable function should be mutable",661			));662		}663664		let result = match &value.sig.output {665			ReturnType::Type(_, ty) => ty,666			_ => 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)")),667		};668		let result = parse_result_ok(result)?;669670		let camel_name = info671			.rename_selector672			.unwrap_or_else(|| cases::camelcase::to_camel_case(&ident.to_string()));673		let mut selector_str = camel_name.clone();674		selector_str.push('(');675		let mut has_normal_args = false;676		for (i, arg) in args.iter().filter(|arg| !arg.is_special()).enumerate() {677			if i != 0 {678				selector_str.push(',');679			}680			write!(selector_str, "{}", arg.selector_ty()).unwrap();681			has_normal_args = true;682		}683		let has_value_args = args.iter().any(|a| a.is_value());684		selector_str.push(')');685		let selector = fn_selector_str(&selector_str);686687		Ok(Self {688			name: ident.clone(),689			camel_name,690			pascal_name: snake_ident_to_pascal(ident),691			screaming_name: snake_ident_to_screaming(ident),692			selector_str,693			selector,694			hide: info.hide,695			args,696			has_normal_args,697			has_value_args,698			mutability,699			result: result.clone(),700			weight,701			docs,702		})703	}704	fn expand_call_def(&self) -> proc_macro2::TokenStream {705		let defs = self706			.args707			.iter()708			.filter(|a| !a.is_special())709			.map(|a| a.expand_call_def());710		let pascal_name = &self.pascal_name;711		let docs = &self.docs;712713		if self.has_normal_args {714			quote! {715				#(#[doc = #docs])*716				#[allow(missing_docs)]717				#pascal_name {718					#(719						#defs,720					)*721				}722			}723		} else {724			quote! {#pascal_name}725		}726	}727728	fn expand_selector(&self) -> proc_macro2::TokenStream {729		let custom_signature = self.expand_custom_signature();730		quote! {731			 {732				let a = ::evm_coder::sha3_const::Keccak256::new()733					.update(#custom_signature.as_bytes())734					.finalize();735				[a[0], a[1], a[2], a[3]]736			}737		}738	}739740	fn expand_const(&self) -> proc_macro2::TokenStream {741		let screaming_name = &self.screaming_name;742		let selector_str = &self.selector_str;743		let selector = &self.expand_selector();744		quote! {745			#[doc = #selector_str]746			const #screaming_name: ::evm_coder::types::bytes4 = #selector;747		}748	}749750	fn expand_interface_id(&self) -> proc_macro2::TokenStream {751		let screaming_name = &self.screaming_name;752		quote! {753			interface_id ^= u32::from_be_bytes(Self::#screaming_name);754		}755	}756757	fn expand_parse(&self) -> proc_macro2::TokenStream {758		let pascal_name = &self.pascal_name;759		let screaming_name = &self.screaming_name;760		if self.has_normal_args {761			let parsers = self762				.args763				.iter()764				.filter(|a| !a.is_special())765				.map(|a| a.expand_parse());766			quote! {767				Self::#screaming_name => return Ok(Some(Self::#pascal_name {768					#(769						#parsers,770					)*771				}))772			}773		} else {774			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }775		}776	}777778	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {779		let pascal_name = &self.pascal_name;780		let name = &self.name;781782		let matcher = if self.has_normal_args {783			let names = self784				.args785				.iter()786				.filter(|a| !a.is_special())787				.map(|a| &a.name);788789			quote! {{790				#(791					#names,792				)*793			}}794		} else {795			quote! {}796		};797798		let receiver = match self.mutability {799			Mutability::Mutable | Mutability::View => quote! {self.},800			Mutability::Pure => quote! {Self::},801		};802		let args = self.args.iter().map(|a| a.expand_call_arg());803804		quote! {805			#call_name::#pascal_name #matcher => {806				let result = #receiver #name(807					#(808						#args,809					)*810				)?;811				(&result).to_result()812			}813		}814	}815816	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {817		let pascal_name = &self.pascal_name;818		if let Some(weight) = &self.weight {819			let matcher = if self.has_normal_args {820				let names = self821					.args822					.iter()823					.filter(|a| !a.is_special())824					.map(|a| &a.name);825826				quote! {{827					#(828						#names,829					)*830				}}831			} else {832				quote! {}833			};834			quote! {835				Self::#pascal_name #matcher => (#weight).into()836			}837		} else {838			let matcher = if self.has_normal_args {839				quote! {{..}}840			} else {841				quote! {}842			};843			quote! {844				Self::#pascal_name #matcher => ().into()845			}846		}847	}848849	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {850		let mut first_comma = true;851		let mut custom_signature = TokenStream::new();852		let mut template = self.camel_name.clone() + "(";853		self.args854			.iter()855			.filter_map(|a| {856				if a.is_special() {857					return None;858				};859860				match a.ty {861					AbiType::Plain(ref ident) => Some(ident),862					_ => None,863				}864			})865			.for_each(|ident| {866				if !first_comma {867					custom_signature.extend(quote!(,));868					template.push(',');869				} else {870					first_comma = false;871				};872				template.push_str("{}");873				let ident_str = ident.to_string();874				match ident_str.as_str() {875					"address" | "uint8" | "uint16" | "uint32" | "uint64" | "uint128"876					| "uint256" | "bytes4" | "topic" | "string" | "bytes" | "void" | "caller"877					| "bool" | "" => {878						custom_signature.extend(quote!(#ident_str));879					}880					_ => {881						custom_signature.extend(quote! {882							#ident::SIGNATURE_STRING883						});884					}885				}886			});887888		template.push(')');889		let mut template = quote!(#template);890		template.extend(quote!(,));891		template.extend(custom_signature);892		let custom_signature_group = Group::new(proc_macro2::Delimiter::Parenthesis, template);893		let mut custom_signature = quote! {894			::evm_coder::const_format::formatcp!895		};896		custom_signature.extend(custom_signature_group.to_token_stream());897898		println!("!!!!! {}", custom_signature);899		custom_signature900	}901902	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {903		let camel_name = &self.camel_name;904		let mutability = match self.mutability {905			Mutability::Mutable => quote! {SolidityMutability::Mutable},906			Mutability::View => quote! { SolidityMutability::View },907			Mutability::Pure => quote! {SolidityMutability::Pure},908		};909		let result = &self.result;910911		let args = self912			.args913			.iter()914			.filter(|a| !a.is_special())915			.map(MethodArg::expand_solidity_argument);916		let docs = &self.docs;917		let selector_str = &self.selector_str;918		let selector = &self.expand_selector();919		let hide = self.hide;920		let custom_signature = self.expand_custom_signature();921		let is_payable = self.has_value_args;922		quote! {923			SolidityFunction {924				docs: &[#(#docs),*],925				selector_str: #selector_str,926				hide: #hide,927				selector: u32::from_be_bytes(#selector),928				custom_signature: #custom_signature,929				name: #camel_name,930				mutability: #mutability,931				is_payable: #is_payable,932				args: (933					#(934						#args,935					)*936				),937				result: <UnnamedArgument<#result>>::default(),938			}939		}940	}941}942943fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {944	if gen.params.is_empty() {945		return quote! {};946	}947	let params = gen.params.iter().map(|p| match p {948		syn::GenericParam::Type(id) => {949			let v = &id.ident;950			quote! {#v}951		}952		syn::GenericParam::Lifetime(lt) => {953			let v = &lt.lifetime;954			quote! {#v}955		}956		syn::GenericParam::Const(c) => {957			let i = &c.ident;958			quote! {#i}959		}960	});961	quote! { #(#params),* }962}963fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {964	if gen.params.is_empty() {965		return quote! {};966	}967	let list = generics_list(gen);968	quote! { <#list> }969}970fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {971	let list = generics_list(gen);972	if gen.params.len() == 1 {973		quote! {#list}974	} else {975		quote! { (#list) }976	}977}978979pub struct SolidityInterface {980	generics: Generics,981	name: Box<syn::Type>,982	info: InterfaceInfo,983	methods: Vec<Method>,984	docs: Vec<String>,985}986impl SolidityInterface {987	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {988		let mut methods = Vec::new();989990		for item in &value.items {991			if let ImplItem::Method(method) = item {992				methods.push(Method::try_from(method)?)993			}994		}995		let mut docs = vec![];996		for attr in &value.attrs {997			let ident = parse_ident_from_path(&attr.path, false)?;998			if ident == "doc" {999				let args = attr.parse_meta().unwrap();1000				let value = match args {1001					Meta::NameValue(MetaNameValue {1002						lit: Lit::Str(str), ..1003					}) => str.value(),1004					_ => unreachable!(),1005				};1006				docs.push(value);1007			}1008		}1009		Ok(Self {1010			generics: value.generics.clone(),1011			name: value.self_ty.clone(),1012			info,1013			methods,1014			docs,1015		})1016	}1017	pub fn expand(self) -> proc_macro2::TokenStream {1018		let name = self.name;10191020		let solidity_name = self.info.name.to_string();1021		let call_name = pascal_ident_to_call(&self.info.name);1022		let generics = self.generics;1023		let gen_ref = generics_reference(&generics);1024		let gen_data = generics_data(&generics);1025		let gen_where = &generics.where_clause;10261027		let call_sub = self1028			.info1029			.inline_is1030			.01031			.iter()1032			.chain(self.info.is.0.iter())1033			.map(|c| Is::expand_call_def(c, &gen_ref));1034		let call_parse = self1035			.info1036			.inline_is1037			.01038			.iter()1039			.chain(self.info.is.0.iter())1040			.map(|is| Is::expand_parse(is, &gen_ref));1041		let call_variants = self1042			.info1043			.inline_is1044			.01045			.iter()1046			.chain(self.info.is.0.iter())1047			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));1048		let weight_variants = self1049			.info1050			.inline_is1051			.01052			.iter()1053			.chain(self.info.is.0.iter())1054			.map(Is::expand_variant_weight);10551056		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);1057		let supports_interface = self1058			.info1059			.is1060			.01061			.iter()1062			.map(|is| Is::expand_supports_interface(is, &gen_ref));10631064		let calls = self.methods.iter().map(Method::expand_call_def);1065		let consts = self.methods.iter().map(Method::expand_const);1066		let interface_id = self.methods.iter().map(Method::expand_interface_id);1067		let parsers = self.methods.iter().map(Method::expand_parse);1068		let call_variants_this = self1069			.methods1070			.iter()1071			.map(|m| Method::expand_variant_call(m, &call_name));1072		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1073		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10741075		// TODO: Inline inline_is1076		let solidity_is = self1077			.info1078			.is1079			.01080			.iter()1081			.chain(self.info.inline_is.0.iter())1082			.map(|is| is.name.to_string());1083		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1084		let solidity_generators = self1085			.info1086			.is1087			.01088			.iter()1089			.chain(self.info.inline_is.0.iter())1090			.map(|is| Is::expand_generator(is, &gen_ref));1091		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10921093		let docs = &self.docs;10941095		if let Some(expect_selector) = &self.info.expect_selector {1096			if !self.info.inline_is.0.is_empty() {1097				return syn::Error::new(1098					name.span(),1099					"expect_selector is not compatible with inline_is",1100				)1101				.to_compile_error();1102			}1103			let selector = self1104				.methods1105				.iter()1106				.map(|m| m.selector)1107				.fold(0, |a, b| a ^ b);11081109			if *expect_selector != selector {1110				let mut methods = String::new();1111				for meth in self.methods.iter() {1112					write!(methods, "\n- {}", meth.selector_str).expect("write to string");1113				}1114				return syn::Error::new(name.span(), format!("expected selector mismatch, expected {expect_selector:0>8x}, but implementation has {selector:0>8x}{methods}")).to_compile_error();1115			}1116		}1117		// let methods = self.methods.iter().map(Method::solidity_def);11181119		quote! {1120			#[derive(Debug)]1121			#(#[doc = #docs])*1122			pub enum #call_name #gen_ref {1123				/// Inherited method1124				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1125				#(1126					#calls,1127				)*1128				#(1129					#call_sub,1130				)*1131			}1132			impl #gen_ref #call_name #gen_ref {1133				#(1134					#consts1135				)*1136				/// Return this call ERC165 selector1137				pub fn interface_id() -> ::evm_coder::types::bytes4 {1138					let mut interface_id = 0;1139					#(#interface_id)*1140					#(#inline_interface_id)*1141					u32::to_be_bytes(interface_id)1142				}1143				/// Generate solidity definitions for methods described in this interface1144				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1145					use evm_coder::solidity::*;1146					use core::fmt::Write;1147					let interface = SolidityInterface {1148						docs: &[#(#docs),*],1149						name: #solidity_name,1150						selector: Self::interface_id(),1151						is: &["Dummy", "ERC165", #(1152							#solidity_is,1153						)* #(1154							#solidity_events_is,1155						)* ],1156						functions: (#(1157							#solidity_functions,1158						)*),1159					};11601161					let mut out = ::evm_coder::types::string::new();1162					if #solidity_name.starts_with("Inline") {1163						out.push_str("/// @dev inlined interface\n");1164					}1165					let _ = interface.format(is_impl, &mut out, tc);1166					tc.collect(out);1167					#(1168						#solidity_event_generators1169					)*1170					#(1171						#solidity_generators1172					)*1173					if is_impl {1174						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());1175					} else {1176						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());1177					}1178				}1179			}1180			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1181				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1182					use ::evm_coder::abi::AbiRead;1183					match method_id {1184						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1185							::evm_coder::ERC165Call::parse(method_id, reader)?1186							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1187						),1188						#(1189							#parsers,1190						)*1191						_ => {},1192					}1193					#(1194						#call_parse1195					)else*1196					return Ok(None);1197				}1198			}1199			impl #generics #call_name #gen_ref1200			#gen_where1201			{1202				/// Is this contract implements specified ERC165 selector1203				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1204					interface_id != u32::to_be_bytes(0xffffff) && (1205						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1206						interface_id == Self::interface_id()1207						#(1208							|| #supports_interface1209						)*1210					)1211				}1212			}1213			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1214			#gen_where1215			{1216				#[allow(unused_variables)]1217				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1218					match self {1219						#(1220							#weight_variants,1221						)*1222						// TODO: It should be very cheap, but not free1223						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1224						#(1225							#weight_variants_this,1226						)*1227					}1228				}1229			}1230			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1231			#gen_where1232			{1233				#[allow(unreachable_code)] // In case of no inner calls1234				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1235					use ::evm_coder::abi::AbiWrite;1236					match c.call {1237						#(1238							#call_variants,1239						)*1240						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1241							let mut writer = ::evm_coder::abi::AbiWriter::default();1242							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1243							return Ok(writer.into());1244						}1245						_ => {},1246					}1247					let mut writer = ::evm_coder::abi::AbiWriter::default();1248					match c.call {1249						#(1250							#call_variants_this,1251						)*1252						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1253					}1254				}1255			}1256		}1257	}1258}