git.delta.rocks / unique-network / refs/commits / 1602901e39d7

difftreelog

source

crates/evm-coder/procedural/src/solidity_interface.rs33.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, token_stream};24use quote::{quote, ToTokens, format_ident};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_const(&self) -> proc_macro2::TokenStream {729		let screaming_name = &self.screaming_name;730		let screaming_name_signature = format_ident!("{}_SIGNATURE", &self.screaming_name);731		let selector_str = &self.selector_str;732		let custom_signature = self.expand_custom_signature();733		quote! {734			const #screaming_name_signature: ::evm_coder::custom_signature::FunctionSignature = #custom_signature;735			#[doc = #selector_str]736			const #screaming_name: ::evm_coder::types::bytes4 = {737				let a = ::evm_coder::sha3_const::Keccak256::new()738				.update_with_size(&Self::#screaming_name_signature.data, Self::#screaming_name_signature.len)739				.finalize();740				[a[0], a[1], a[2], a[3]]741			};742		}743	}744745	fn expand_interface_id(&self) -> proc_macro2::TokenStream {746		let screaming_name = &self.screaming_name;747		quote! {748			interface_id ^= u32::from_be_bytes(Self::#screaming_name);749		}750	}751752	fn expand_parse(&self) -> proc_macro2::TokenStream {753		let pascal_name = &self.pascal_name;754		let screaming_name = &self.screaming_name;755		if self.has_normal_args {756			let parsers = self757				.args758				.iter()759				.filter(|a| !a.is_special())760				.map(|a| a.expand_parse());761			quote! {762				Self::#screaming_name => return Ok(Some(Self::#pascal_name {763					#(764						#parsers,765					)*766				}))767			}768		} else {769			quote! { Self::#screaming_name => return Ok(Some(Self::#pascal_name)) }770		}771	}772773	fn expand_variant_call(&self, call_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {774		let pascal_name = &self.pascal_name;775		let name = &self.name;776777		let matcher = if self.has_normal_args {778			let names = self779				.args780				.iter()781				.filter(|a| !a.is_special())782				.map(|a| &a.name);783784			quote! {{785				#(786					#names,787				)*788			}}789		} else {790			quote! {}791		};792793		let receiver = match self.mutability {794			Mutability::Mutable | Mutability::View => quote! {self.},795			Mutability::Pure => quote! {Self::},796		};797		let args = self.args.iter().map(|a| a.expand_call_arg());798799		quote! {800			#call_name::#pascal_name #matcher => {801				let result = #receiver #name(802					#(803						#args,804					)*805				)?;806				(&result).to_result()807			}808		}809	}810811	fn expand_variant_weight(&self) -> proc_macro2::TokenStream {812		let pascal_name = &self.pascal_name;813		if let Some(weight) = &self.weight {814			let matcher = if self.has_normal_args {815				let names = self816					.args817					.iter()818					.filter(|a| !a.is_special())819					.map(|a| &a.name);820821				quote! {{822					#(823						#names,824					)*825				}}826			} else {827				quote! {}828			};829			quote! {830				Self::#pascal_name #matcher => (#weight).into()831			}832		} else {833			let matcher = if self.has_normal_args {834				quote! {{..}}835			} else {836				quote! {}837			};838			quote! {839				Self::#pascal_name #matcher => ().into()840			}841		}842	}843844	fn expand_type(845		ty: &AbiType,846		token_stream: &mut proc_macro2::TokenStream,847		read_signature: bool,848	) {849		match ty {850			AbiType::Plain(ref ident) => {851				let plain_token = if read_signature {852					quote! {853						(<#ident>::SIGNATURE)854					}855				} else {856					quote! {857						#ident858					}859				};860861				token_stream.extend(plain_token);862			}863864			AbiType::Tuple(ref tuple_type) => {865				let mut tuple_types = proc_macro2::TokenStream::new();866				let mut is_first = true;867868				for ty in tuple_type {869					if is_first {870						is_first = false871					} else {872						tuple_types.extend(quote!(,));873					}874					Self::expand_type(ty, &mut tuple_types, false);875				}876				tuple_types = if read_signature {877					quote! { (<(#tuple_types)>::SIGNATURE) }878				} else {879					quote! { (#tuple_types) }880				};881				token_stream.extend(tuple_types);882			}883884			AbiType::Vec(ref vec_type) => {885				let mut vec_token = proc_macro2::TokenStream::new();886				Self::expand_type(vec_type.as_ref(), &mut vec_token, false);887				vec_token = if read_signature {888					quote! { (<Vec<#vec_token>>::SIGNATURE) }889				} else {890					quote! { <Vec<#vec_token>> }891				};892				token_stream.extend(vec_token);893			}894895			AbiType::Array(_, _) => todo!("Array eth signature"),896		};897	}898899	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {900		let mut token_stream = TokenStream::new();901902		let mut is_first = true;903		for arg in &self.args {904			if arg.is_special() {905				continue;906			}907908			if is_first {909				is_first = false;910			} else {911				token_stream.extend(quote!(,));912			}913			Self::expand_type(&arg.ty, &mut token_stream, true);914		}915916		if !is_first {917			token_stream.extend(quote!(,));918		}919920		let func_name = self.camel_name.clone();921		let func_name = quote!(SignaturePreferences {922			open_name: Some(SignatureUnit::new(#func_name)),923			open_delimiter: Some(SignatureUnit::new("(")),924			param_delimiter: Some(SignatureUnit::new(",")),925			close_delimiter: Some(SignatureUnit::new(")")),926			close_name: None,927		});928		quote!({ ::evm_coder::make_signature!(new fn(#func_name), #token_stream) })929	}930931	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {932		let camel_name = &self.camel_name;933		let mutability = match self.mutability {934			Mutability::Mutable => quote! {SolidityMutability::Mutable},935			Mutability::View => quote! { SolidityMutability::View },936			Mutability::Pure => quote! {SolidityMutability::Pure},937		};938		let result = &self.result;939940		let args = self941			.args942			.iter()943			.filter(|a| !a.is_special())944			.map(MethodArg::expand_solidity_argument);945		let docs = &self.docs;946		let selector_str = &self.selector_str;947		let screaming_name = &self.screaming_name;948		let hide = self.hide;949		let custom_signature = self.expand_custom_signature();950		let custom_signature = quote!(951			{952				const cs: FunctionSignature = #custom_signature;953				cs954			}955		);956		// println!("!!!!! {}", custom_signature);957		let is_payable = self.has_value_args;958		let out = quote! {959			SolidityFunction {960				docs: &[#(#docs),*],961				selector_str: #selector_str,962				hide: #hide,963				selector: u32::from_be_bytes(Self::#screaming_name),964				custom_signature: #custom_signature,965				name: #camel_name,966				mutability: #mutability,967				is_payable: #is_payable,968				args: (969					#(970						#args,971					)*972				),973				result: <UnnamedArgument<#result>>::default(),974			}975		};976		// println!("@@@ {}", out);977		out978	}979}980981fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {982	if gen.params.is_empty() {983		return quote! {};984	}985	let params = gen.params.iter().map(|p| match p {986		syn::GenericParam::Type(id) => {987			let v = &id.ident;988			quote! {#v}989		}990		syn::GenericParam::Lifetime(lt) => {991			let v = &lt.lifetime;992			quote! {#v}993		}994		syn::GenericParam::Const(c) => {995			let i = &c.ident;996			quote! {#i}997		}998	});999	quote! { #(#params),* }1000}1001fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {1002	if gen.params.is_empty() {1003		return quote! {};1004	}1005	let list = generics_list(gen);1006	quote! { <#list> }1007}1008fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {1009	let list = generics_list(gen);1010	if gen.params.len() == 1 {1011		quote! {#list}1012	} else {1013		quote! { (#list) }1014	}1015}10161017pub struct SolidityInterface {1018	generics: Generics,1019	name: Box<syn::Type>,1020	info: InterfaceInfo,1021	methods: Vec<Method>,1022	docs: Vec<String>,1023}1024impl SolidityInterface {1025	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {1026		let mut methods = Vec::new();10271028		for item in &value.items {1029			if let ImplItem::Method(method) = item {1030				methods.push(Method::try_from(method)?)1031			}1032		}1033		let mut docs = vec![];1034		for attr in &value.attrs {1035			let ident = parse_ident_from_path(&attr.path, false)?;1036			if ident == "doc" {1037				let args = attr.parse_meta().unwrap();1038				let value = match args {1039					Meta::NameValue(MetaNameValue {1040						lit: Lit::Str(str), ..1041					}) => str.value(),1042					_ => unreachable!(),1043				};1044				docs.push(value);1045			}1046		}1047		Ok(Self {1048			generics: value.generics.clone(),1049			name: value.self_ty.clone(),1050			info,1051			methods,1052			docs,1053		})1054	}1055	pub fn expand(self) -> proc_macro2::TokenStream {1056		let name = self.name;10571058		let solidity_name = self.info.name.to_string();1059		let call_name = pascal_ident_to_call(&self.info.name);1060		let generics = self.generics;1061		let gen_ref = generics_reference(&generics);1062		let gen_data = generics_data(&generics);1063		let gen_where = &generics.where_clause;10641065		let call_sub = self1066			.info1067			.inline_is1068			.01069			.iter()1070			.chain(self.info.is.0.iter())1071			.map(|c| Is::expand_call_def(c, &gen_ref));1072		let call_parse = self1073			.info1074			.inline_is1075			.01076			.iter()1077			.chain(self.info.is.0.iter())1078			.map(|is| Is::expand_parse(is, &gen_ref));1079		let call_variants = self1080			.info1081			.inline_is1082			.01083			.iter()1084			.chain(self.info.is.0.iter())1085			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));1086		let weight_variants = self1087			.info1088			.inline_is1089			.01090			.iter()1091			.chain(self.info.is.0.iter())1092			.map(Is::expand_variant_weight);10931094		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);1095		let supports_interface = self1096			.info1097			.is1098			.01099			.iter()1100			.map(|is| Is::expand_supports_interface(is, &gen_ref));11011102		let calls = self.methods.iter().map(Method::expand_call_def);1103		let consts = self.methods.iter().map(Method::expand_const);1104		let interface_id = self.methods.iter().map(Method::expand_interface_id);1105		let parsers = self.methods.iter().map(Method::expand_parse);1106		let call_variants_this = self1107			.methods1108			.iter()1109			.map(|m| Method::expand_variant_call(m, &call_name));1110		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1111		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);11121113		// TODO: Inline inline_is1114		let solidity_is = self1115			.info1116			.is1117			.01118			.iter()1119			.chain(self.info.inline_is.0.iter())1120			.map(|is| is.name.to_string());1121		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1122		let solidity_generators = self1123			.info1124			.is1125			.01126			.iter()1127			.chain(self.info.inline_is.0.iter())1128			.map(|is| Is::expand_generator(is, &gen_ref));1129		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);11301131		let docs = &self.docs;11321133		if let Some(expect_selector) = &self.info.expect_selector {1134			if !self.info.inline_is.0.is_empty() {1135				return syn::Error::new(1136					name.span(),1137					"expect_selector is not compatible with inline_is",1138				)1139				.to_compile_error();1140			}1141			let selector = self1142				.methods1143				.iter()1144				.map(|m| m.selector)1145				.fold(0, |a, b| a ^ b);11461147			if *expect_selector != selector {1148				let mut methods = String::new();1149				for meth in self.methods.iter() {1150					write!(methods, "\n- {}", meth.selector_str).expect("write to string");1151				}1152				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();1153			}1154		}1155		// let methods = self.methods.iter().map(Method::solidity_def);11561157		quote! {1158			#[derive(Debug)]1159			#(#[doc = #docs])*1160			pub enum #call_name #gen_ref {1161				/// Inherited method1162				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1163				#(1164					#calls,1165				)*1166				#(1167					#call_sub,1168				)*1169			}1170			impl #gen_ref #call_name #gen_ref {1171				#(1172					#consts1173				)*1174				/// Return this call ERC165 selector1175				pub fn interface_id() -> ::evm_coder::types::bytes4 {1176					let mut interface_id = 0;1177					#(#interface_id)*1178					#(#inline_interface_id)*1179					u32::to_be_bytes(interface_id)1180				}1181				/// Generate solidity definitions for methods described in this interface1182				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1183					use evm_coder::solidity::*;1184					use core::fmt::Write;1185					let interface = SolidityInterface {1186						docs: &[#(#docs),*],1187						name: #solidity_name,1188						selector: Self::interface_id(),1189						is: &["Dummy", "ERC165", #(1190							#solidity_is,1191						)* #(1192							#solidity_events_is,1193						)* ],1194						functions: (#(1195							#solidity_functions,1196						)*),1197					};11981199					let mut out = ::evm_coder::types::string::new();1200					if #solidity_name.starts_with("Inline") {1201						out.push_str("/// @dev inlined interface\n");1202					}1203					let _ = interface.format(is_impl, &mut out, tc);1204					tc.collect(out);1205					#(1206						#solidity_event_generators1207					)*1208					#(1209						#solidity_generators1210					)*1211					if is_impl {1212						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());1213					} else {1214						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());1215					}1216				}1217			}1218			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1219				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1220					use ::evm_coder::abi::AbiRead;1221					match method_id {1222						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1223							::evm_coder::ERC165Call::parse(method_id, reader)?1224							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1225						),1226						#(1227							#parsers,1228						)*1229						_ => {},1230					}1231					#(1232						#call_parse1233					)else*1234					return Ok(None);1235				}1236			}1237			impl #generics #call_name #gen_ref1238			#gen_where1239			{1240				/// Is this contract implements specified ERC165 selector1241				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1242					interface_id != u32::to_be_bytes(0xffffff) && (1243						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1244						interface_id == Self::interface_id()1245						#(1246							|| #supports_interface1247						)*1248					)1249				}1250			}1251			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1252			#gen_where1253			{1254				#[allow(unused_variables)]1255				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1256					match self {1257						#(1258							#weight_variants,1259						)*1260						// TODO: It should be very cheap, but not free1261						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1262						#(1263							#weight_variants_this,1264						)*1265					}1266				}1267			}1268			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1269			#gen_where1270			{1271				#[allow(unreachable_code)] // In case of no inner calls1272				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1273					use ::evm_coder::abi::AbiWrite;1274					match c.call {1275						#(1276							#call_variants,1277						)*1278						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1279							let mut writer = ::evm_coder::abi::AbiWriter::default();1280							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1281							return Ok(writer.into());1282						}1283						_ => {},1284					}1285					let mut writer = ::evm_coder::abi::AbiWriter::default();1286					match c.call {1287						#(1288							#call_variants_this,1289						)*1290						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1291					}1292				}1293			}1294		}1295	}1296}