git.delta.rocks / unique-network / refs/commits / 15e4512df81d

difftreelog

source

crates/evm-coder/procedural/src/solidity_interface.rs31.9 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, 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.signature, Self::#screaming_name_signature.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_custom_signature(&self) -> proc_macro2::TokenStream {845		let mut custom_signature = TokenStream::new();846847		self.args848			.iter()849			.filter_map(|a| {850				if a.is_special() {851					return None;852				};853854				match a.ty {855					AbiType::Plain(ref ident) => Some(ident),856					_ => None,857				}858			})859			.for_each(|ident| {860				custom_signature.extend(quote! {861					(<#ident>::SIGNATURE, <#ident>::SIGNATURE_LEN)862				});863			});864865		let func_name = self.camel_name.clone();866		let func_name = quote!(FunctionName::new(#func_name));867		custom_signature =868			quote!({ ::evm_coder::make_signature!(new fn(& #func_name),#custom_signature) });869870		// println!("!!!!! {}", custom_signature);871872		custom_signature873	}874875	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {876		let camel_name = &self.camel_name;877		let mutability = match self.mutability {878			Mutability::Mutable => quote! {SolidityMutability::Mutable},879			Mutability::View => quote! { SolidityMutability::View },880			Mutability::Pure => quote! {SolidityMutability::Pure},881		};882		let result = &self.result;883884		let args = self885			.args886			.iter()887			.filter(|a| !a.is_special())888			.map(MethodArg::expand_solidity_argument);889		let docs = &self.docs;890		let selector_str = &self.selector_str;891		let screaming_name = &self.screaming_name;892		let hide = self.hide;893		let custom_signature = self.expand_custom_signature();894		let custom_signature = quote!(895			{896				const cs: FunctionSignature = #custom_signature;897				cs898			}899		);900		// println!("!!!!! {}", custom_signature);901		let is_payable = self.has_value_args;902		let out = quote! {903			SolidityFunction {904				docs: &[#(#docs),*],905				selector_str: #selector_str,906				hide: #hide,907				selector: u32::from_be_bytes(Self::#screaming_name),908				custom_signature: #custom_signature,909				name: #camel_name,910				mutability: #mutability,911				is_payable: #is_payable,912				args: (913					#(914						#args,915					)*916				),917				result: <UnnamedArgument<#result>>::default(),918			}919		};920		// println!("@@@ {}", out);921		out922	}923}924925fn generics_list(gen: &Generics) -> proc_macro2::TokenStream {926	if gen.params.is_empty() {927		return quote! {};928	}929	let params = gen.params.iter().map(|p| match p {930		syn::GenericParam::Type(id) => {931			let v = &id.ident;932			quote! {#v}933		}934		syn::GenericParam::Lifetime(lt) => {935			let v = &lt.lifetime;936			quote! {#v}937		}938		syn::GenericParam::Const(c) => {939			let i = &c.ident;940			quote! {#i}941		}942	});943	quote! { #(#params),* }944}945fn generics_reference(gen: &Generics) -> proc_macro2::TokenStream {946	if gen.params.is_empty() {947		return quote! {};948	}949	let list = generics_list(gen);950	quote! { <#list> }951}952fn generics_data(gen: &Generics) -> proc_macro2::TokenStream {953	let list = generics_list(gen);954	if gen.params.len() == 1 {955		quote! {#list}956	} else {957		quote! { (#list) }958	}959}960961pub struct SolidityInterface {962	generics: Generics,963	name: Box<syn::Type>,964	info: InterfaceInfo,965	methods: Vec<Method>,966	docs: Vec<String>,967}968impl SolidityInterface {969	pub fn try_from(info: InterfaceInfo, value: &ItemImpl) -> syn::Result<Self> {970		let mut methods = Vec::new();971972		for item in &value.items {973			if let ImplItem::Method(method) = item {974				methods.push(Method::try_from(method)?)975			}976		}977		let mut docs = vec![];978		for attr in &value.attrs {979			let ident = parse_ident_from_path(&attr.path, false)?;980			if ident == "doc" {981				let args = attr.parse_meta().unwrap();982				let value = match args {983					Meta::NameValue(MetaNameValue {984						lit: Lit::Str(str), ..985					}) => str.value(),986					_ => unreachable!(),987				};988				docs.push(value);989			}990		}991		Ok(Self {992			generics: value.generics.clone(),993			name: value.self_ty.clone(),994			info,995			methods,996			docs,997		})998	}999	pub fn expand(self) -> proc_macro2::TokenStream {1000		let name = self.name;10011002		let solidity_name = self.info.name.to_string();1003		let call_name = pascal_ident_to_call(&self.info.name);1004		let generics = self.generics;1005		let gen_ref = generics_reference(&generics);1006		let gen_data = generics_data(&generics);1007		let gen_where = &generics.where_clause;10081009		let call_sub = self1010			.info1011			.inline_is1012			.01013			.iter()1014			.chain(self.info.is.0.iter())1015			.map(|c| Is::expand_call_def(c, &gen_ref));1016		let call_parse = self1017			.info1018			.inline_is1019			.01020			.iter()1021			.chain(self.info.is.0.iter())1022			.map(|is| Is::expand_parse(is, &gen_ref));1023		let call_variants = self1024			.info1025			.inline_is1026			.01027			.iter()1028			.chain(self.info.is.0.iter())1029			.map(|c| Is::expand_variant_call(c, &call_name, &gen_ref));1030		let weight_variants = self1031			.info1032			.inline_is1033			.01034			.iter()1035			.chain(self.info.is.0.iter())1036			.map(Is::expand_variant_weight);10371038		let inline_interface_id = self.info.inline_is.0.iter().map(Is::expand_interface_id);1039		let supports_interface = self1040			.info1041			.is1042			.01043			.iter()1044			.map(|is| Is::expand_supports_interface(is, &gen_ref));10451046		let calls = self.methods.iter().map(Method::expand_call_def);1047		let consts = self.methods.iter().map(Method::expand_const);1048		let interface_id = self.methods.iter().map(Method::expand_interface_id);1049		let parsers = self.methods.iter().map(Method::expand_parse);1050		let call_variants_this = self1051			.methods1052			.iter()1053			.map(|m| Method::expand_variant_call(m, &call_name));1054		let weight_variants_this = self.methods.iter().map(Method::expand_variant_weight);1055		let solidity_functions = self.methods.iter().map(Method::expand_solidity_function);10561057		// TODO: Inline inline_is1058		let solidity_is = self1059			.info1060			.is1061			.01062			.iter()1063			.chain(self.info.inline_is.0.iter())1064			.map(|is| is.name.to_string());1065		let solidity_events_is = self.info.events.0.iter().map(|is| is.name.to_string());1066		let solidity_generators = self1067			.info1068			.is1069			.01070			.iter()1071			.chain(self.info.inline_is.0.iter())1072			.map(|is| Is::expand_generator(is, &gen_ref));1073		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);10741075		let docs = &self.docs;10761077		if let Some(expect_selector) = &self.info.expect_selector {1078			if !self.info.inline_is.0.is_empty() {1079				return syn::Error::new(1080					name.span(),1081					"expect_selector is not compatible with inline_is",1082				)1083				.to_compile_error();1084			}1085			let selector = self1086				.methods1087				.iter()1088				.map(|m| m.selector)1089				.fold(0, |a, b| a ^ b);10901091			if *expect_selector != selector {1092				let mut methods = String::new();1093				for meth in self.methods.iter() {1094					write!(methods, "\n- {}", meth.selector_str).expect("write to string");1095				}1096				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();1097			}1098		}1099		// let methods = self.methods.iter().map(Method::solidity_def);11001101		quote! {1102			#[derive(Debug)]1103			#(#[doc = #docs])*1104			pub enum #call_name #gen_ref {1105				/// Inherited method1106				ERC165Call(::evm_coder::ERC165Call, ::core::marker::PhantomData<#gen_data>),1107				#(1108					#calls,1109				)*1110				#(1111					#call_sub,1112				)*1113			}1114			impl #gen_ref #call_name #gen_ref {1115				#(1116					#consts1117				)*1118				/// Return this call ERC165 selector1119				pub fn interface_id() -> ::evm_coder::types::bytes4 {1120					let mut interface_id = 0;1121					#(#interface_id)*1122					#(#inline_interface_id)*1123					u32::to_be_bytes(interface_id)1124				}1125				/// Generate solidity definitions for methods described in this interface1126				pub fn generate_solidity_interface(tc: &evm_coder::solidity::TypeCollector, is_impl: bool) {1127					use evm_coder::solidity::*;1128					use core::fmt::Write;1129					let interface = SolidityInterface {1130						docs: &[#(#docs),*],1131						name: #solidity_name,1132						selector: Self::interface_id(),1133						is: &["Dummy", "ERC165", #(1134							#solidity_is,1135						)* #(1136							#solidity_events_is,1137						)* ],1138						functions: (#(1139							#solidity_functions,1140						)*),1141					};11421143					let mut out = ::evm_coder::types::string::new();1144					if #solidity_name.starts_with("Inline") {1145						out.push_str("/// @dev inlined interface\n");1146					}1147					let _ = interface.format(is_impl, &mut out, tc);1148					tc.collect(out);1149					#(1150						#solidity_event_generators1151					)*1152					#(1153						#solidity_generators1154					)*1155					if is_impl {1156						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());1157					} else {1158						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());1159					}1160				}1161			}1162			impl #gen_ref ::evm_coder::Call for #call_name #gen_ref {1163				fn parse(method_id: ::evm_coder::types::bytes4, reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Option<Self>> {1164					use ::evm_coder::abi::AbiRead;1165					match method_id {1166						::evm_coder::ERC165Call::INTERFACE_ID => return Ok(1167							::evm_coder::ERC165Call::parse(method_id, reader)?1168							.map(|c| Self::ERC165Call(c, ::core::marker::PhantomData))1169						),1170						#(1171							#parsers,1172						)*1173						_ => {},1174					}1175					#(1176						#call_parse1177					)else*1178					return Ok(None);1179				}1180			}1181			impl #generics #call_name #gen_ref1182			#gen_where1183			{1184				/// Is this contract implements specified ERC165 selector1185				pub fn supports_interface(this: &#name, interface_id: ::evm_coder::types::bytes4) -> bool {1186					interface_id != u32::to_be_bytes(0xffffff) && (1187						interface_id == ::evm_coder::ERC165Call::INTERFACE_ID ||1188						interface_id == Self::interface_id()1189						#(1190							|| #supports_interface1191						)*1192					)1193				}1194			}1195			impl #generics ::evm_coder::Weighted for #call_name #gen_ref1196			#gen_where1197			{1198				#[allow(unused_variables)]1199				fn weight(&self) -> ::evm_coder::execution::DispatchInfo {1200					match self {1201						#(1202							#weight_variants,1203						)*1204						// TODO: It should be very cheap, but not free1205						Self::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {..}, _) => ::frame_support::weights::Weight::from_ref_time(100).into(),1206						#(1207							#weight_variants_this,1208						)*1209					}1210				}1211			}1212			impl #generics ::evm_coder::Callable<#call_name #gen_ref> for #name1213			#gen_where1214			{1215				#[allow(unreachable_code)] // In case of no inner calls1216				fn call(&mut self, c: Msg<#call_name #gen_ref>) -> ::evm_coder::execution::ResultWithPostInfo<::evm_coder::abi::AbiWriter> {1217					use ::evm_coder::abi::AbiWrite;1218					match c.call {1219						#(1220							#call_variants,1221						)*1222						#call_name::ERC165Call(::evm_coder::ERC165Call::SupportsInterface {interface_id}, _) => {1223							let mut writer = ::evm_coder::abi::AbiWriter::default();1224							writer.bool(&<#call_name #gen_ref>::supports_interface(self, interface_id));1225							return Ok(writer.into());1226						}1227						_ => {},1228					}1229					let mut writer = ::evm_coder::abi::AbiWriter::default();1230					match c.call {1231						#(1232							#call_variants_this,1233						)*1234						_ => Err(::evm_coder::execution::Error::from("method is not available").into()),1235					}1236				}1237			}1238		}1239	}1240}