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

difftreelog

refactor(evm-coder)! manual macro parsing

Yaroslav Bolyukin2022-07-12parent: #34aa637.patch.diff
in: master
We have plans to allow evm-coder to generate Callables for externally defined contracts, however our current attribute parsing was limiting code maintanability, rework was needed before starting to implement new features

BREAKING CHANGE: solidity_interface definitions may now look slightly different, for example interface names now should be identifiers, not strings

8 files changed

modifiedcrates/evm-coder-macros/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder-macros/Cargo.toml
+++ b/crates/evm-coder-macros/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "evm-coder-macros"
-version = "0.1.0"
+version = "0.2.0"
 license = "GPLv3"
 edition = "2021"
 
@@ -8,10 +8,9 @@
 proc-macro = true
 
 [dependencies]
-sha3 = "0.9.1"
+sha3 = "0.10.1"
 quote = "1.0"
 proc-macro2 = "1.0"
 syn = { version = "1.0", features = ["full"] }
 hex = "0.4.3"
 Inflector = "0.11.4"
-darling = "0.13.0"
modifiedcrates/evm-coder-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/evm-coder-macros/src/lib.rs
+++ b/crates/evm-coder-macros/src/lib.rs
@@ -16,14 +16,13 @@
 
 #![allow(dead_code)]
 
-use darling::FromMeta;
 use inflector::cases;
 use proc_macro::TokenStream;
 use quote::quote;
 use sha3::{Digest, Keccak256};
 use syn::{
-	AttributeArgs, DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,
-	PathSegment, Type, parse_macro_input, spanned::Spanned,
+	DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,
+	PathSegment, Type, parse_macro_input, spanned::Spanned, Attribute, parse::Parse,
 };
 
 mod solidity_interface;
@@ -254,8 +253,7 @@
 /// ```
 #[proc_macro_attribute]
 pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {
-	let args = parse_macro_input!(args as AttributeArgs);
-	let args = solidity_interface::InterfaceInfo::from_list(&args).unwrap();
+	let args = parse_macro_input!(args as solidity_interface::InterfaceInfo);
 
 	let input: ItemImpl = match syn::parse(stream) {
 		Ok(t) => t,
modifiedcrates/evm-coder-macros/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder-macros/src/solidity_interface.rs
+++ b/crates/evm-coder-macros/src/solidity_interface.rs
@@ -16,14 +16,15 @@
 
 #![allow(dead_code)]
 
-use quote::quote;
-use darling::{FromMeta, ToTokens};
+use quote::{quote, ToTokens};
 use inflector::cases;
 use std::fmt::Write;
 use syn::{
 	Expr, FnArg, GenericArgument, Generics, Ident, ImplItem, ImplItemMethod, ItemImpl, Lit, Meta,
-	MetaNameValue, NestedMeta, PatType, Path, PathArguments, ReturnType, Type, spanned::Spanned,
-	parse_str,
+	MetaNameValue, PatType, PathArguments, ReturnType, Type,
+	spanned::Spanned,
+	parse::{Parse, ParseStream},
+	parenthesized, Token, LitInt, LitStr,
 };
 
 use crate::{
@@ -39,19 +40,6 @@
 	via: Option<(Type, Ident)>,
 }
 impl Is {
-	fn new_via(path: &Path, via: Option<(Type, Ident)>) -> syn::Result<Self> {
-		let name = parse_ident_from_path(path, false)?.clone();
-		Ok(Self {
-			pascal_call_name: pascal_ident_to_call(&name),
-			snake_call_name: pascal_ident_to_snake_call(&name),
-			name,
-			via,
-		})
-	}
-	fn new(path: &Path) -> syn::Result<Self> {
-		Self::new_via(path, None)
-	}
-
 	fn expand_call_def(&self, gen_ref: &proc_macro2::TokenStream) -> proc_macro2::TokenStream {
 		let name = &self.name;
 		let pascal_call_name = &self.pascal_call_name;
@@ -137,73 +125,141 @@
 
 #[derive(Default)]
 struct IsList(Vec<Is>);
-impl FromMeta for IsList {
-	fn from_list(items: &[NestedMeta]) -> darling::Result<Self> {
-		let mut out = Vec::new();
-		for item in items {
-			match item {
-				NestedMeta::Meta(Meta::Path(path)) => out.push(Is::new(path)?),
-				// TODO: replace meta parsing with manual
-				NestedMeta::Meta(Meta::List(list))
-					if list.path.is_ident("via") && list.nested.len() == 3 =>
-				{
-					let mut data = list.nested.iter();
-					let typ = match data.next().expect("len == 3") {
-						NestedMeta::Lit(Lit::Str(s)) => {
-							let v = s.value();
-							let typ: Type = parse_str(&v)?;
-							typ
-						}
-						_ => {
-							return Err(syn::Error::new(
-								item.span(),
-								"via typ should be type in string",
-							)
-							.into())
-						}
-					};
-					let via = match data.next().expect("len == 3") {
-						NestedMeta::Meta(Meta::Path(path)) => path
-							.get_ident()
-							.ok_or_else(|| syn::Error::new(item.span(), "via should be ident"))?,
-						_ => return Err(syn::Error::new(item.span(), "via should be ident").into()),
-					};
-					let path = match data.next().expect("len == 3") {
-						NestedMeta::Meta(Meta::Path(path)) => path,
-						_ => return Err(syn::Error::new(item.span(), "path should be path").into()),
-					};
-
-					out.push(Is::new_via(path, Some((typ, via.clone())))?)
-				}
-				_ => {
-					return Err(syn::Error::new(
-						item.span(),
-						"expected either Name or via(\"Type\", getter, Name)",
-					)
-					.into())
-				}
+impl Parse for IsList {
+	fn parse(input: ParseStream) -> syn::Result<Self> {
+		let mut out = vec![];
+		loop {
+			if input.is_empty() {
+				break;
+			}
+			let name = input.parse::<Ident>()?;
+			let lookahead = input.lookahead1();
+			let via = if lookahead.peek(syn::token::Paren) {
+				let contents;
+				parenthesized!(contents in input);
+				let method = contents.parse::<Ident>()?;
+				contents.parse::<Token![,]>()?;
+				let ty = contents.parse::<Type>()?;
+				Some((ty, method))
+			} else if lookahead.peek(Token![,]) {
+				None
+			} else if input.is_empty() {
+				None
+			} else {
+				return Err(lookahead.error());
+			};
+			out.push(Is {
+				pascal_call_name: pascal_ident_to_call(&name),
+				snake_call_name: pascal_ident_to_snake_call(&name),
+				name,
+				via,
+			});
+			if input.peek(Token![,]) {
+				input.parse::<Token![,]>()?;
+				continue;
+			} else {
+				break;
 			}
 		}
 		Ok(Self(out))
 	}
 }
 
-#[derive(FromMeta)]
 pub struct InterfaceInfo {
 	name: Ident,
-	#[darling(default)]
 	is: IsList,
-	#[darling(default)]
 	inline_is: IsList,
-	#[darling(default)]
 	events: IsList,
+	expect_selector: Option<u32>,
 }
+impl Parse for InterfaceInfo {
+	fn parse(input: ParseStream) -> syn::Result<Self> {
+		let mut name = None;
+		let mut is = None;
+		let mut inline_is = None;
+		let mut events = None;
+		let mut expect_selector = None;
+		// TODO: create proc-macro to optimize proc-macro boilerplate? :D
+		loop {
+			let lookahead = input.lookahead1();
+			if lookahead.peek(kw::name) {
+				let k = input.parse::<kw::name>()?;
+				input.parse::<Token![=]>()?;
+				if name.replace(input.parse::<Ident>()?).is_some() {
+					return Err(syn::Error::new(k.span(), "name is already set"));
+				}
+			} else if lookahead.peek(kw::is) {
+				let k = input.parse::<kw::is>()?;
+				let contents;
+				parenthesized!(contents in input);
+				if is.replace(contents.parse::<IsList>()?).is_some() {
+					return Err(syn::Error::new(k.span(), "is is already set"));
+				}
+			} else if lookahead.peek(kw::inline_is) {
+				let k = input.parse::<kw::inline_is>()?;
+				let contents;
+				parenthesized!(contents in input);
+				if inline_is.replace(contents.parse::<IsList>()?).is_some() {
+					return Err(syn::Error::new(k.span(), "inline_is is already set"));
+				}
+			} else if lookahead.peek(kw::events) {
+				let k = input.parse::<kw::events>()?;
+				let contents;
+				parenthesized!(contents in input);
+				if events.replace(contents.parse::<IsList>()?).is_some() {
+					return Err(syn::Error::new(k.span(), "events is already set"));
+				}
+			} else if lookahead.peek(kw::expect_selector) {
+				let k = input.parse::<kw::expect_selector>()?;
+				input.parse::<Token![=]>()?;
+				let value = input.parse::<LitInt>()?;
+				if expect_selector
+					.replace(value.base10_parse::<u32>()?)
+					.is_some()
+				{
+					return Err(syn::Error::new(k.span(), "expect_selector is already set"));
+				}
+			} else if input.is_empty() {
+				break;
+			} else {
+				return Err(lookahead.error());
+			}
+			if input.peek(Token![,]) {
+				input.parse::<Token![,]>()?;
+			} else {
+				break;
+			}
+		}
+		Ok(Self {
+			name: name.ok_or_else(|| syn::Error::new(input.span(), "missing name"))?,
+			is: is.unwrap_or_default(),
+			inline_is: inline_is.unwrap_or_default(),
+			events: events.unwrap_or_default(),
+			expect_selector,
+		})
+	}
+}
 
-#[derive(FromMeta)]
 struct MethodInfo {
-	#[darling(default)]
 	rename_selector: Option<String>,
 }
+impl Parse for MethodInfo {
+	fn parse(input: ParseStream) -> syn::Result<Self> {
+		let mut rename_selector = None;
+		let lookahead = input.lookahead1();
+		if lookahead.peek(kw::rename_selector) {
+			let k = input.parse::<kw::rename_selector>()?;
+			input.parse::<Token![=]>()?;
+			if rename_selector
+				.replace(input.parse::<LitStr>()?.value())
+				.is_some()
+			{
+				return Err(syn::Error::new(k.span(), "rename_selector is already set"));
+			}
+		}
+		Ok(Self { rename_selector })
+	}
+}
 
 enum AbiType {
 	// type
@@ -258,7 +314,7 @@
 							"expected only one generic for vec",
 						));
 					}
-					let arg = args.first().unwrap();
+					let arg = args.first().expect("first arg");
 
 					let ty = match arg {
 						GenericArgument::Type(ty) => ty,
@@ -429,23 +485,17 @@
 	Pure,
 }
 
-pub struct WeightAttr(syn::Expr);
-
-mod keyword {
+mod kw {
 	syn::custom_keyword!(weight);
-}
 
-impl syn::parse::Parse for WeightAttr {
-	fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
-		input.parse::<syn::Token![#]>()?;
-		let content;
-		syn::bracketed!(content in input);
-		content.parse::<keyword::weight>()?;
+	syn::custom_keyword!(via);
+	syn::custom_keyword!(name);
+	syn::custom_keyword!(is);
+	syn::custom_keyword!(inline_is);
+	syn::custom_keyword!(events);
+	syn::custom_keyword!(expect_selector);
 
-		let weight_content;
-		syn::parenthesized!(weight_content in content);
-		Ok(WeightAttr(weight_content.parse::<syn::Expr>()?))
-	}
+	syn::custom_keyword!(rename_selector);
 }
 
 struct Method {
@@ -472,8 +522,7 @@
 		for attr in &value.attrs {
 			let ident = parse_ident_from_path(&attr.path, false)?;
 			if ident == "solidity" {
-				let args = attr.parse_meta().unwrap();
-				info = MethodInfo::from_meta(&args).unwrap();
+				info = attr.parse_args::<MethodInfo>()?;
 			} else if ident == "doc" {
 				let args = attr.parse_meta().unwrap();
 				let value = match args {
@@ -484,7 +533,7 @@
 				};
 				docs.push(value);
 			} else if ident == "weight" {
-				weight = Some(syn::parse2::<WeightAttr>(attr.to_token_stream())?.0);
+				weight = Some(attr.parse_args::<Expr>()?);
 			}
 		}
 		let ident = &value.sig.ident;
@@ -869,6 +918,28 @@
 			.map(|is| Is::expand_generator(is, &gen_ref));
 		let solidity_event_generators = self.info.events.0.iter().map(Is::expand_event_generator);
 
+		if let Some(expect_selector) = &self.info.expect_selector {
+			if !self.info.inline_is.0.is_empty() {
+				return syn::Error::new(
+					name.span(),
+					"expect_selector is not compatible with inline_is",
+				)
+				.to_compile_error();
+			}
+			let selector = self
+				.methods
+				.iter()
+				.map(|m| m.selector)
+				.fold(0, |a, b| a ^ b);
+
+			if *expect_selector != selector {
+				let mut methods = String::new();
+				for meth in self.methods.iter() {
+					write!(methods, "\n- {}", meth.selector_str).expect("write to string");
+				}
+				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();
+			}
+		}
 		// let methods = self.methods.iter().map(Method::solidity_def);
 
 		quote! {
@@ -917,9 +988,9 @@
 						)*),
 					};
 					if is_impl {
-						tc.collect("// 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());
+						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());
 					} else {
-						tc.collect("// Common stubs holder\ninterface Dummy {\n}\ninterface ERC165 is Dummy {\n\tfunction supportsInterface(bytes4 interfaceID) external view returns (bool);\n}\n".into());
+						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());
 					}
 					#(
 						#solidity_generators
@@ -930,9 +1001,9 @@
 
 					let mut out = string::new();
 					// In solidity interface usage (is) should be preceeded by interface definition
-					// This comment helps to sort it in a set
+					// HACK: this comment helps to sort it in a set
 					if #solidity_name.starts_with("Inline") {
-						out.push_str("// Inline\n");
+						out.push_str("/// @dev inlined interface\n");
 					}
 					let _ = interface.format(is_impl, &mut out, tc);
 					tc.collect(out);
modifiedcrates/evm-coder-macros/src/to_log.rsdiffbeforeafterboth
--- a/crates/evm-coder-macros/src/to_log.rs
+++ b/crates/evm-coder-macros/src/to_log.rs
@@ -207,7 +207,7 @@
 						)*),
 					};
 					let mut out = string::new();
-					out.push_str("// Inline\n");
+					out.push_str("/// @dev inlined interface\n");
 					let _ = interface.format(is_impl, &mut out, tc);
 					tc.collect(out);
 				}
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
before · crates/evm-coder/src/solidity.rs
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#[cfg(not(feature = "std"))]18use alloc::{19	string::String,20	vec::Vec,21	collections::{BTreeSet, BTreeMap},22	format,23};24#[cfg(feature = "std")]25use std::collections::{BTreeSet, BTreeMap};26use core::{27	fmt::{self, Write},28	marker::PhantomData,29	cell::{Cell, RefCell},30};31use impl_trait_for_tuples::impl_for_tuples;32use crate::types::*;3334#[derive(Default)]35pub struct TypeCollector {36	structs: RefCell<BTreeSet<string>>,37	anonymous: RefCell<BTreeMap<Vec<string>, usize>>,38	id: Cell<usize>,39}40impl TypeCollector {41	pub fn new() -> Self {42		Self::default()43	}44	pub fn collect(&self, item: string) {45		self.structs.borrow_mut().insert(item);46	}47	pub fn next_id(&self) -> usize {48		let v = self.id.get();49		self.id.set(v + 1);50		v51	}52	pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {53		let names = T::names(self);54		if let Some(id) = self.anonymous.borrow().get(&names).cloned() {55			return format!("Tuple{}", id);56		}57		let id = self.next_id();58		let mut str = String::new();59		writeln!(str, "// Anonymous struct").unwrap();60		writeln!(str, "struct Tuple{} {{", id).unwrap();61		for (i, name) in names.iter().enumerate() {62			writeln!(str, "\t{} field_{};", name, i).unwrap();63		}64		writeln!(str, "}}").unwrap();65		self.collect(str);66		self.anonymous.borrow_mut().insert(names, id);67		format!("Tuple{}", id)68	}69	pub fn finish(self) -> BTreeSet<string> {70		self.structs.into_inner()71	}72}7374pub trait SolidityTypeName: 'static {75	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;76	fn is_simple() -> bool;77	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;78	fn is_void() -> bool {79		false80	}81}82macro_rules! solidity_type_name {83    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {84        $(85            impl SolidityTypeName for $ty {86                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {87                    write!(writer, $name)88                }89				fn is_simple() -> bool {90					$simple91				}92				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {93					write!(writer, $default)94				}95            }96        )*97    };98}99100solidity_type_name! {101	uint8 => "uint8" true = "0",102	uint32 => "uint32" true = "0",103	uint64 => "uint64" true = "0",104	uint128 => "uint128" true = "0",105	uint256 => "uint256" true = "0",106	bytes4 => "bytes4" true = "bytes4(0)",107	address => "address" true = "0x0000000000000000000000000000000000000000",108	string => "string" false = "\"\"",109	bytes => "bytes" false = "hex\"\"",110	bool => "bool" true = "false",111}112impl SolidityTypeName for void {113	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {114		Ok(())115	}116	fn is_simple() -> bool {117		true118	}119	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {120		Ok(())121	}122	fn is_void() -> bool {123		true124	}125}126127mod sealed {128	pub trait CanBePlacedInVec {}129}130131impl sealed::CanBePlacedInVec for uint256 {}132impl sealed::CanBePlacedInVec for string {}133impl sealed::CanBePlacedInVec for address {}134135impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {136	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {137		T::solidity_name(writer, tc)?;138		write!(writer, "[]")139	}140	fn is_simple() -> bool {141		false142	}143	fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {144		write!(writer, "[]")145	}146}147148pub trait SolidityTupleType {149	fn names(tc: &TypeCollector) -> Vec<String>;150	fn len() -> usize;151}152153macro_rules! count {154    () => (0usize);155    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));156}157158macro_rules! impl_tuples {159	($($ident:ident)+) => {160		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}161		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {162			fn names(tc: &TypeCollector) -> Vec<string> {163				let mut collected = Vec::with_capacity(Self::len());164				$({165					let mut out = string::new();166					$ident::solidity_name(&mut out, tc).expect("no fmt error");167					collected.push(out);168				})*;169				collected170			}171172			fn len() -> usize {173				count!($($ident)*)174			}175		}176		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {177			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {178				write!(writer, "{}", tc.collect_tuple::<Self>())179			}180			fn is_simple() -> bool {181				false182			}183			#[allow(unused_assignments)]184			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {185				write!(writer, "{}(", tc.collect_tuple::<Self>())?;186				let mut first = true;187				$(188					if !first {189						write!(writer, ",")?;190					} else {191						first = false;192					}193					<$ident>::solidity_default(writer, tc)?;194				)*195				write!(writer, ")")196			}197		}198	};199}200201impl_tuples! {A}202impl_tuples! {A B}203impl_tuples! {A B C}204impl_tuples! {A B C D}205impl_tuples! {A B C D E}206impl_tuples! {A B C D E F}207impl_tuples! {A B C D E F G}208impl_tuples! {A B C D E F G H}209impl_tuples! {A B C D E F G H I}210impl_tuples! {A B C D E F G H I J}211212pub trait SolidityArguments {213	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;214	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;215	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;216	fn is_empty(&self) -> bool {217		self.len() == 0218	}219	fn len(&self) -> usize;220}221222#[derive(Default)]223pub struct UnnamedArgument<T>(PhantomData<*const T>);224225impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {226	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {227		if !T::is_void() {228			T::solidity_name(writer, tc)?;229			if !T::is_simple() {230				write!(writer, " memory")?;231			}232			Ok(())233		} else {234			Ok(())235		}236	}237	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {238		Ok(())239	}240	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241		T::solidity_default(writer, tc)242	}243	fn len(&self) -> usize {244		if T::is_void() {245			0246		} else {247			1248		}249	}250}251252pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);253254impl<T> NamedArgument<T> {255	pub fn new(name: &'static str) -> Self {256		Self(name, Default::default())257	}258}259260impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {261	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {262		if !T::is_void() {263			T::solidity_name(writer, tc)?;264			if !T::is_simple() {265				write!(writer, " memory")?;266			}267			write!(writer, " {}", self.0)268		} else {269			Ok(())270		}271	}272	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {273		writeln!(writer, "\t\t{};", self.0)274	}275	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276		T::solidity_default(writer, tc)277	}278	fn len(&self) -> usize {279		if T::is_void() {280			0281		} else {282			1283		}284	}285}286287pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);288289impl<T> SolidityEventArgument<T> {290	pub fn new(indexed: bool, name: &'static str) -> Self {291		Self(indexed, name, Default::default())292	}293}294295impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {296	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {297		if !T::is_void() {298			T::solidity_name(writer, tc)?;299			if self.0 {300				write!(writer, " indexed")?;301			}302			write!(writer, " {}", self.1)303		} else {304			Ok(())305		}306	}307	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {308		writeln!(writer, "\t\t{};", self.1)309	}310	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311		T::solidity_default(writer, tc)312	}313	fn len(&self) -> usize {314		if T::is_void() {315			0316		} else {317			1318		}319	}320}321322impl SolidityArguments for () {323	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {324		Ok(())325	}326	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {327		Ok(())328	}329	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {330		Ok(())331	}332	fn len(&self) -> usize {333		0334	}335}336337#[impl_for_tuples(1, 12)]338impl SolidityArguments for Tuple {339	for_tuples!( where #( Tuple: SolidityArguments ),* );340341	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {342		let mut first = true;343		for_tuples!( #(344            if !Tuple.is_empty() {345                if !first {346                    write!(writer, ", ")?;347                }348                first = false;349                Tuple.solidity_name(writer, tc)?;350            }351        )* );352		Ok(())353	}354	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {355		for_tuples!( #(356            Tuple.solidity_get(writer)?;357        )* );358		Ok(())359	}360	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {361		if self.is_empty() {362			Ok(())363		} else if self.len() == 1 {364			for_tuples!( #(365				Tuple.solidity_default(writer, tc)?;366			)* );367			Ok(())368		} else {369			write!(writer, "(")?;370			let mut first = true;371			for_tuples!( #(372				if !Tuple.is_empty() {373					if !first {374						write!(writer, ", ")?;375					}376					first = false;377					Tuple.solidity_default(writer, tc)?;378				}379			)* );380			write!(writer, ")")?;381			Ok(())382		}383	}384	fn len(&self) -> usize {385		for_tuples!( #( Tuple.len() )+* )386	}387}388389pub trait SolidityFunctions {390	fn solidity_name(391		&self,392		is_impl: bool,393		writer: &mut impl fmt::Write,394		tc: &TypeCollector,395	) -> fmt::Result;396}397398pub enum SolidityMutability {399	Pure,400	View,401	Mutable,402}403pub struct SolidityFunction<A, R> {404	pub docs: &'static [&'static str],405	pub selector: &'static str,406	pub name: &'static str,407	pub args: A,408	pub result: R,409	pub mutability: SolidityMutability,410}411impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {412	fn solidity_name(413		&self,414		is_impl: bool,415		writer: &mut impl fmt::Write,416		tc: &TypeCollector,417	) -> fmt::Result {418		for doc in self.docs {419			writeln!(writer, "\t//{}", doc)?;420		}421		if !self.docs.is_empty() {422			writeln!(writer, "\t//")?;423		}424		writeln!(writer, "\t// Selector: {}", self.selector)?;425		write!(writer, "\tfunction {}(", self.name)?;426		self.args.solidity_name(writer, tc)?;427		write!(writer, ")")?;428		if is_impl {429			write!(writer, " public")?;430		} else {431			write!(writer, " external")?;432		}433		match &self.mutability {434			SolidityMutability::Pure => write!(writer, " pure")?,435			SolidityMutability::View => write!(writer, " view")?,436			SolidityMutability::Mutable => {}437		}438		if !self.result.is_empty() {439			write!(writer, " returns (")?;440			self.result.solidity_name(writer, tc)?;441			write!(writer, ")")?;442		}443		if is_impl {444			writeln!(writer, " {{")?;445			writeln!(writer, "\t\trequire(false, stub_error);")?;446			self.args.solidity_get(writer)?;447			match &self.mutability {448				SolidityMutability::Pure => {}449				SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,450				SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,451			}452			if !self.result.is_empty() {453				write!(writer, "\t\treturn ")?;454				self.result.solidity_default(writer, tc)?;455				writeln!(writer, ";")?;456			}457			writeln!(writer, "\t}}")?;458		} else {459			writeln!(writer, ";")?;460		}461		Ok(())462	}463}464465#[impl_for_tuples(0, 24)]466impl SolidityFunctions for Tuple {467	for_tuples!( where #( Tuple: SolidityFunctions ),* );468469	fn solidity_name(470		&self,471		is_impl: bool,472		writer: &mut impl fmt::Write,473		tc: &TypeCollector,474	) -> fmt::Result {475		let mut first = false;476		for_tuples!( #(477            Tuple.solidity_name(is_impl, writer, tc)?;478        )* );479		Ok(())480	}481}482483pub struct SolidityInterface<F: SolidityFunctions> {484	pub selector: bytes4,485	pub name: &'static str,486	pub is: &'static [&'static str],487	pub functions: F,488}489490impl<F: SolidityFunctions> SolidityInterface<F> {491	pub fn format(492		&self,493		is_impl: bool,494		out: &mut impl fmt::Write,495		tc: &TypeCollector,496	) -> fmt::Result {497		const ZERO_BYTES: [u8; 4] = [0; 4];498		if self.selector != ZERO_BYTES {499			writeln!(500				out,501				"// Selector: {:0>8x}",502				u32::from_be_bytes(self.selector)503			)?;504		}505		if is_impl {506			write!(out, "contract ")?;507		} else {508			write!(out, "interface ")?;509		}510		write!(out, "{}", self.name)?;511		if !self.is.is_empty() {512			write!(out, " is")?;513			for (i, n) in self.is.iter().enumerate() {514				if i != 0 {515					write!(out, ",")?;516				}517				write!(out, " {}", n)?;518			}519		}520		writeln!(out, " {{")?;521		self.functions.solidity_name(is_impl, out, tc)?;522		writeln!(out, "}}")?;523		Ok(())524	}525}526527pub struct SolidityEvent<A> {528	pub name: &'static str,529	pub args: A,530}531532impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {533	fn solidity_name(534		&self,535		_is_impl: bool,536		writer: &mut impl fmt::Write,537		tc: &TypeCollector,538	) -> fmt::Result {539		write!(writer, "\tevent {}(", self.name)?;540		self.args.solidity_name(writer, tc)?;541		writeln!(writer, ");")542	}543}
after · crates/evm-coder/src/solidity.rs
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#[cfg(not(feature = "std"))]18use alloc::{19	string::String,20	vec::Vec,21	collections::{BTreeSet, BTreeMap},22	format,23};24#[cfg(feature = "std")]25use std::collections::{BTreeSet, BTreeMap};26use core::{27	fmt::{self, Write},28	marker::PhantomData,29	cell::{Cell, RefCell},30};31use impl_trait_for_tuples::impl_for_tuples;32use crate::types::*;3334#[derive(Default)]35pub struct TypeCollector {36	structs: RefCell<BTreeSet<string>>,37	anonymous: RefCell<BTreeMap<Vec<string>, usize>>,38	id: Cell<usize>,39}40impl TypeCollector {41	pub fn new() -> Self {42		Self::default()43	}44	pub fn collect(&self, item: string) {45		self.structs.borrow_mut().insert(item);46	}47	pub fn next_id(&self) -> usize {48		let v = self.id.get();49		self.id.set(v + 1);50		v51	}52	pub fn collect_tuple<T: SolidityTupleType>(&self) -> String {53		let names = T::names(self);54		if let Some(id) = self.anonymous.borrow().get(&names).cloned() {55			return format!("Tuple{}", id);56		}57		let id = self.next_id();58		let mut str = String::new();59		writeln!(str, "/// @dev anonymous struct").unwrap();60		writeln!(str, "struct Tuple{} {{", id).unwrap();61		for (i, name) in names.iter().enumerate() {62			writeln!(str, "\t{} field_{};", name, i).unwrap();63		}64		writeln!(str, "}}").unwrap();65		self.collect(str);66		self.anonymous.borrow_mut().insert(names, id);67		format!("Tuple{}", id)68	}69	pub fn finish(self) -> BTreeSet<string> {70		self.structs.into_inner()71	}72}7374pub trait SolidityTypeName: 'static {75	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;76	fn is_simple() -> bool;77	fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;78	fn is_void() -> bool {79		false80	}81}82macro_rules! solidity_type_name {83    ($($ty:ty => $name:literal $simple:literal = $default:literal),* $(,)?) => {84        $(85            impl SolidityTypeName for $ty {86                fn solidity_name(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {87                    write!(writer, $name)88                }89				fn is_simple() -> bool {90					$simple91				}92				fn solidity_default(writer: &mut impl core::fmt::Write, _tc: &TypeCollector) -> core::fmt::Result {93					write!(writer, $default)94				}95            }96        )*97    };98}99100solidity_type_name! {101	uint8 => "uint8" true = "0",102	uint32 => "uint32" true = "0",103	uint64 => "uint64" true = "0",104	uint128 => "uint128" true = "0",105	uint256 => "uint256" true = "0",106	bytes4 => "bytes4" true = "bytes4(0)",107	address => "address" true = "0x0000000000000000000000000000000000000000",108	string => "string" false = "\"\"",109	bytes => "bytes" false = "hex\"\"",110	bool => "bool" true = "false",111}112impl SolidityTypeName for void {113	fn solidity_name(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {114		Ok(())115	}116	fn is_simple() -> bool {117		true118	}119	fn solidity_default(_writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {120		Ok(())121	}122	fn is_void() -> bool {123		true124	}125}126127mod sealed {128	pub trait CanBePlacedInVec {}129}130131impl sealed::CanBePlacedInVec for uint256 {}132impl sealed::CanBePlacedInVec for string {}133impl sealed::CanBePlacedInVec for address {}134135impl<T: SolidityTypeName + sealed::CanBePlacedInVec> SolidityTypeName for Vec<T> {136	fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {137		T::solidity_name(writer, tc)?;138		write!(writer, "[]")139	}140	fn is_simple() -> bool {141		false142	}143	fn solidity_default(writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {144		write!(writer, "[]")145	}146}147148pub trait SolidityTupleType {149	fn names(tc: &TypeCollector) -> Vec<String>;150	fn len() -> usize;151}152153macro_rules! count {154    () => (0usize);155    ( $x:tt $($xs:tt)* ) => (1usize + count!($($xs)*));156}157158macro_rules! impl_tuples {159	($($ident:ident)+) => {160		impl<$($ident),+> sealed::CanBePlacedInVec for ($($ident,)+) {}161		impl<$($ident: SolidityTypeName + 'static),+> SolidityTupleType for ($($ident,)+) {162			fn names(tc: &TypeCollector) -> Vec<string> {163				let mut collected = Vec::with_capacity(Self::len());164				$({165					let mut out = string::new();166					$ident::solidity_name(&mut out, tc).expect("no fmt error");167					collected.push(out);168				})*;169				collected170			}171172			fn len() -> usize {173				count!($($ident)*)174			}175		}176		impl<$($ident: SolidityTypeName + 'static),+> SolidityTypeName for ($($ident,)+) {177			fn solidity_name(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {178				write!(writer, "{}", tc.collect_tuple::<Self>())179			}180			fn is_simple() -> bool {181				false182			}183			#[allow(unused_assignments)]184			fn solidity_default(writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {185				write!(writer, "{}(", tc.collect_tuple::<Self>())?;186				let mut first = true;187				$(188					if !first {189						write!(writer, ",")?;190					} else {191						first = false;192					}193					<$ident>::solidity_default(writer, tc)?;194				)*195				write!(writer, ")")196			}197		}198	};199}200201impl_tuples! {A}202impl_tuples! {A B}203impl_tuples! {A B C}204impl_tuples! {A B C D}205impl_tuples! {A B C D E}206impl_tuples! {A B C D E F}207impl_tuples! {A B C D E F G}208impl_tuples! {A B C D E F G H}209impl_tuples! {A B C D E F G H I}210impl_tuples! {A B C D E F G H I J}211212pub trait SolidityArguments {213	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;214	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result;215	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result;216	fn is_empty(&self) -> bool {217		self.len() == 0218	}219	fn len(&self) -> usize;220}221222#[derive(Default)]223pub struct UnnamedArgument<T>(PhantomData<*const T>);224225impl<T: SolidityTypeName> SolidityArguments for UnnamedArgument<T> {226	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {227		if !T::is_void() {228			T::solidity_name(writer, tc)?;229			if !T::is_simple() {230				write!(writer, " memory")?;231			}232			Ok(())233		} else {234			Ok(())235		}236	}237	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {238		Ok(())239	}240	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {241		T::solidity_default(writer, tc)242	}243	fn len(&self) -> usize {244		if T::is_void() {245			0246		} else {247			1248		}249	}250}251252pub struct NamedArgument<T>(&'static str, PhantomData<*const T>);253254impl<T> NamedArgument<T> {255	pub fn new(name: &'static str) -> Self {256		Self(name, Default::default())257	}258}259260impl<T: SolidityTypeName> SolidityArguments for NamedArgument<T> {261	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {262		if !T::is_void() {263			T::solidity_name(writer, tc)?;264			if !T::is_simple() {265				write!(writer, " memory")?;266			}267			write!(writer, " {}", self.0)268		} else {269			Ok(())270		}271	}272	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {273		writeln!(writer, "\t\t{};", self.0)274	}275	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {276		T::solidity_default(writer, tc)277	}278	fn len(&self) -> usize {279		if T::is_void() {280			0281		} else {282			1283		}284	}285}286287pub struct SolidityEventArgument<T>(pub bool, &'static str, PhantomData<*const T>);288289impl<T> SolidityEventArgument<T> {290	pub fn new(indexed: bool, name: &'static str) -> Self {291		Self(indexed, name, Default::default())292	}293}294295impl<T: SolidityTypeName> SolidityArguments for SolidityEventArgument<T> {296	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {297		if !T::is_void() {298			T::solidity_name(writer, tc)?;299			if self.0 {300				write!(writer, " indexed")?;301			}302			write!(writer, " {}", self.1)303		} else {304			Ok(())305		}306	}307	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {308		writeln!(writer, "\t\t{};", self.1)309	}310	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {311		T::solidity_default(writer, tc)312	}313	fn len(&self) -> usize {314		if T::is_void() {315			0316		} else {317			1318		}319	}320}321322impl SolidityArguments for () {323	fn solidity_name(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {324		Ok(())325	}326	fn solidity_get(&self, _writer: &mut impl fmt::Write) -> fmt::Result {327		Ok(())328	}329	fn solidity_default(&self, _writer: &mut impl fmt::Write, _tc: &TypeCollector) -> fmt::Result {330		Ok(())331	}332	fn len(&self) -> usize {333		0334	}335}336337#[impl_for_tuples(1, 12)]338impl SolidityArguments for Tuple {339	for_tuples!( where #( Tuple: SolidityArguments ),* );340341	fn solidity_name(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {342		let mut first = true;343		for_tuples!( #(344            if !Tuple.is_empty() {345                if !first {346                    write!(writer, ", ")?;347                }348                first = false;349                Tuple.solidity_name(writer, tc)?;350            }351        )* );352		Ok(())353	}354	fn solidity_get(&self, writer: &mut impl fmt::Write) -> fmt::Result {355		for_tuples!( #(356            Tuple.solidity_get(writer)?;357        )* );358		Ok(())359	}360	fn solidity_default(&self, writer: &mut impl fmt::Write, tc: &TypeCollector) -> fmt::Result {361		if self.is_empty() {362			Ok(())363		} else if self.len() == 1 {364			for_tuples!( #(365				Tuple.solidity_default(writer, tc)?;366			)* );367			Ok(())368		} else {369			write!(writer, "(")?;370			let mut first = true;371			for_tuples!( #(372				if !Tuple.is_empty() {373					if !first {374						write!(writer, ", ")?;375					}376					first = false;377					Tuple.solidity_default(writer, tc)?;378				}379			)* );380			write!(writer, ")")?;381			Ok(())382		}383	}384	fn len(&self) -> usize {385		for_tuples!( #( Tuple.len() )+* )386	}387}388389pub trait SolidityFunctions {390	fn solidity_name(391		&self,392		is_impl: bool,393		writer: &mut impl fmt::Write,394		tc: &TypeCollector,395	) -> fmt::Result;396}397398pub enum SolidityMutability {399	Pure,400	View,401	Mutable,402}403pub struct SolidityFunction<A, R> {404	pub docs: &'static [&'static str],405	pub selector: &'static str,406	pub name: &'static str,407	pub args: A,408	pub result: R,409	pub mutability: SolidityMutability,410}411impl<A: SolidityArguments, R: SolidityArguments> SolidityFunctions for SolidityFunction<A, R> {412	fn solidity_name(413		&self,414		is_impl: bool,415		writer: &mut impl fmt::Write,416		tc: &TypeCollector,417	) -> fmt::Result {418		for doc in self.docs {419			writeln!(writer, "\t///{}", doc)?;420		}421		if !self.docs.is_empty() {422			writeln!(writer, "\t///")?;423		}424		writeln!(writer, "\t/// Selector: {}", self.selector)?;425		write!(writer, "\tfunction {}(", self.name)?;426		self.args.solidity_name(writer, tc)?;427		write!(writer, ")")?;428		if is_impl {429			write!(writer, " public")?;430		} else {431			write!(writer, " external")?;432		}433		match &self.mutability {434			SolidityMutability::Pure => write!(writer, " pure")?,435			SolidityMutability::View => write!(writer, " view")?,436			SolidityMutability::Mutable => {}437		}438		if !self.result.is_empty() {439			write!(writer, " returns (")?;440			self.result.solidity_name(writer, tc)?;441			write!(writer, ")")?;442		}443		if is_impl {444			writeln!(writer, " {{")?;445			writeln!(writer, "\t\trequire(false, stub_error);")?;446			self.args.solidity_get(writer)?;447			match &self.mutability {448				SolidityMutability::Pure => {}449				SolidityMutability::View => writeln!(writer, "\t\tdummy;")?,450				SolidityMutability::Mutable => writeln!(writer, "\t\tdummy = 0;")?,451			}452			if !self.result.is_empty() {453				write!(writer, "\t\treturn ")?;454				self.result.solidity_default(writer, tc)?;455				writeln!(writer, ";")?;456			}457			writeln!(writer, "\t}}")?;458		} else {459			writeln!(writer, ";")?;460		}461		Ok(())462	}463}464465#[impl_for_tuples(0, 24)]466impl SolidityFunctions for Tuple {467	for_tuples!( where #( Tuple: SolidityFunctions ),* );468469	fn solidity_name(470		&self,471		is_impl: bool,472		writer: &mut impl fmt::Write,473		tc: &TypeCollector,474	) -> fmt::Result {475		let mut first = false;476		for_tuples!( #(477            Tuple.solidity_name(is_impl, writer, tc)?;478        )* );479		Ok(())480	}481}482483pub struct SolidityInterface<F: SolidityFunctions> {484	pub selector: bytes4,485	pub name: &'static str,486	pub is: &'static [&'static str],487	pub functions: F,488}489490impl<F: SolidityFunctions> SolidityInterface<F> {491	pub fn format(492		&self,493		is_impl: bool,494		out: &mut impl fmt::Write,495		tc: &TypeCollector,496	) -> fmt::Result {497		const ZERO_BYTES: [u8; 4] = [0; 4];498		if self.selector != ZERO_BYTES {499			writeln!(500				out,501				"/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",502				u32::from_be_bytes(self.selector)503			)?;504		}505		if is_impl {506			write!(out, "contract ")?;507		} else {508			write!(out, "interface ")?;509		}510		write!(out, "{}", self.name)?;511		if !self.is.is_empty() {512			write!(out, " is")?;513			for (i, n) in self.is.iter().enumerate() {514				if i != 0 {515					write!(out, ",")?;516				}517				write!(out, " {}", n)?;518			}519		}520		writeln!(out, " {{")?;521		self.functions.solidity_name(is_impl, out, tc)?;522		writeln!(out, "}}")?;523		Ok(())524	}525}526527pub struct SolidityEvent<A> {528	pub name: &'static str,529	pub args: A,530}531532impl<A: SolidityArguments> SolidityFunctions for SolidityEvent<A> {533	fn solidity_name(534		&self,535		_is_impl: bool,536		writer: &mut impl fmt::Write,537		tc: &TypeCollector,538	) -> fmt::Result {539		write!(writer, "\tevent {}(", self.name)?;540		self.args.solidity_name(writer, tc)?;541		writeln!(writer, ");")542	}543}
modifiedcrates/evm-coder/tests/generics.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/generics.rs
+++ b/crates/evm-coder/tests/generics.rs
@@ -19,14 +19,14 @@
 
 struct Generic<T>(PhantomData<T>);
 
-#[solidity_interface(name = "GenericIs")]
+#[solidity_interface(name = GenericIs)]
 impl<T> Generic<T> {
 	fn test_1(&self) -> Result<uint256> {
 		unreachable!()
 	}
 }
 
-#[solidity_interface(name = "Generic", is(GenericIs))]
+#[solidity_interface(name = Generic, is(GenericIs))]
 impl<T: Into<u32>> Generic<T> {
 	fn test_2(&self) -> Result<uint256> {
 		unreachable!()
@@ -35,7 +35,7 @@
 
 generate_stubgen!(gen_iface, GenericCall<()>, false);
 
-#[solidity_interface(name = "GenericWhere")]
+#[solidity_interface(name = GenericWhere)]
 impl<T> Generic<T>
 where
 	T: core::fmt::Debug,
modifiedcrates/evm-coder/tests/random.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/random.rs
+++ b/crates/evm-coder/tests/random.rs
@@ -21,14 +21,14 @@
 
 struct Impls;
 
-#[solidity_interface(name = "OurInterface")]
+#[solidity_interface(name = OurInterface)]
 impl Impls {
 	fn fn_a(&self, _input: uint256) -> Result<bool> {
 		unreachable!()
 	}
 }
 
-#[solidity_interface(name = "OurInterface1")]
+#[solidity_interface(name = OurInterface1)]
 impl Impls {
 	fn fn_b(&self, _input: uint128) -> Result<uint32> {
 		unreachable!()
@@ -48,7 +48,7 @@
 }
 
 #[solidity_interface(
-	name = "OurInterface2",
+	name = OurInterface2,
 	is(OurInterface),
 	inline_is(OurInterface1),
 	events(OurEvents)
@@ -79,3 +79,9 @@
 		unreachable!()
 	}
 }
+
+#[solidity_interface(
+	name = ValidSelector,
+	expect_selector = 0x00000000,
+)]
+impl Impls {}
modifiedcrates/evm-coder/tests/solidity_generation.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/solidity_generation.rs
+++ b/crates/evm-coder/tests/solidity_generation.rs
@@ -18,7 +18,7 @@
 
 struct ERC20;
 
-#[solidity_interface(name = "ERC20")]
+#[solidity_interface(name = ERC20)]
 impl ERC20 {
 	fn decimals(&self) -> Result<uint8> {
 		unreachable!()