difftreelog
refactor(evm-coder)! manual macro parsing
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
crates/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"
crates/evm-coder-macros/src/lib.rsdiffbeforeafterboth1// 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)]1819use darling::FromMeta;20use inflector::cases;21use proc_macro::TokenStream;22use quote::quote;23use sha3::{Digest, Keccak256};24use syn::{25 AttributeArgs, DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,26 PathSegment, Type, parse_macro_input, spanned::Spanned,27};2829mod solidity_interface;30mod to_log;3132fn fn_selector_str(input: &str) -> u32 {33 let mut hasher = Keccak256::new();34 hasher.update(input.as_bytes());35 let result = hasher.finalize();3637 let mut selector_bytes = [0; 4];38 selector_bytes.copy_from_slice(&result[0..4]);3940 u32::from_be_bytes(selector_bytes)41}4243/// Returns solidity function selector (first 4 bytes of hash) by its44/// textual representation45///46/// ```ignore47/// use evm_coder_macros::fn_selector;48///49/// assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);50/// ```51#[proc_macro]52pub fn fn_selector(input: TokenStream) -> TokenStream {53 let input = input.to_string().replace(' ', "");54 let selector = fn_selector_str(&input);5556 (quote! {57 #selector58 })59 .into()60}6162fn event_selector_str(input: &str) -> [u8; 32] {63 let mut hasher = Keccak256::new();64 hasher.update(input.as_bytes());65 let result = hasher.finalize();6667 let mut selector_bytes = [0; 32];68 selector_bytes.copy_from_slice(&result[0..32]);69 selector_bytes70}7172/// Returns solidity topic (hash) by its textual representation73///74/// ```ignore75/// use evm_coder_macros::event_topic;76///77/// assert_eq!(78/// format!("{:x}", event_topic!(Transfer(address, address, uint256))),79/// "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",80/// );81/// ```82#[proc_macro]83pub fn event_topic(stream: TokenStream) -> TokenStream {84 let input = stream.to_string().replace(' ', "");85 let selector_bytes = event_selector_str(&input);8687 (quote! {88 ::primitive_types::H256([#(89 #selector_bytes,90 )*])91 })92 .into()93}9495fn parse_path(ty: &Type) -> syn::Result<&Path> {96 match &ty {97 syn::Type::Path(pat) => {98 if let Some(qself) = &pat.qself {99 return Err(syn::Error::new(qself.ty.span(), "no receiver expected"));100 }101 Ok(&pat.path)102 }103 _ => Err(syn::Error::new(ty.span(), "expected ty to be path")),104 }105}106107fn parse_path_segment(path: &Path) -> syn::Result<&PathSegment> {108 if path.segments.len() != 1 {109 return Err(syn::Error::new(110 path.span(),111 "expected path to have only segment",112 ));113 }114 let last_segment = &path.segments.last().unwrap();115 Ok(last_segment)116}117118fn parse_ident_from_pat(pat: &Pat) -> syn::Result<&Ident> {119 match pat {120 Pat::Ident(i) => Ok(&i.ident),121 _ => Err(syn::Error::new(pat.span(), "expected pat ident")),122 }123}124125fn parse_ident_from_segment(segment: &PathSegment, allow_generics: bool) -> syn::Result<&Ident> {126 if segment.arguments != PathArguments::None && !allow_generics {127 return Err(syn::Error::new(128 segment.arguments.span(),129 "unexpected generic type",130 ));131 }132 Ok(&segment.ident)133}134135fn parse_ident_from_path(path: &Path, allow_generics: bool) -> syn::Result<&Ident> {136 let segment = parse_path_segment(path)?;137 parse_ident_from_segment(segment, allow_generics)138}139140fn parse_ident_from_type(ty: &Type, allow_generics: bool) -> syn::Result<&Ident> {141 let path = parse_path(ty)?;142 parse_ident_from_path(path, allow_generics)143}144145// Gets T out of Result<T>146fn parse_result_ok(ty: &Type) -> syn::Result<&Type> {147 let path = parse_path(ty)?;148 let segment = parse_path_segment(path)?;149150 if segment.ident != "Result" {151 return Err(syn::Error::new(152 ty.span(),153 "expected Result as return type (no renamed aliases allowed)",154 ));155 }156 let args = match &segment.arguments {157 PathArguments::AngleBracketed(e) => e,158 _ => {159 return Err(syn::Error::new(160 segment.arguments.span(),161 "missing Result generics",162 ))163 }164 };165166 let args = &args.args;167 let arg = args.first().unwrap();168169 let ty = match arg {170 GenericArgument::Type(ty) => ty,171 _ => {172 return Err(syn::Error::new(173 arg.span(),174 "expected first generic to be type",175 ))176 }177 };178179 Ok(ty)180}181182fn pascal_ident_to_call(ident: &Ident) -> Ident {183 let name = format!("{}Call", ident);184 Ident::new(&name, ident.span())185}186fn snake_ident_to_pascal(ident: &Ident) -> Ident {187 let name = ident.to_string();188 let name = cases::pascalcase::to_pascal_case(&name);189 Ident::new(&name, ident.span())190}191fn snake_ident_to_screaming(ident: &Ident) -> Ident {192 let name = ident.to_string();193 let name = cases::screamingsnakecase::to_screaming_snake_case(&name);194 Ident::new(&name, ident.span())195}196fn pascal_ident_to_snake_call(ident: &Ident) -> Ident {197 let name = ident.to_string();198 let name = cases::snakecase::to_snake_case(&name);199 let name = format!("call_{}", name);200 Ident::new(&name, ident.span())201}202203/// Derives call enum implementing [`evm_coder::Callable`], [`evm_coder::Weighted`]204/// and [`evm_coder::Call`] from impl block205///206/// ## Macro syntax207///208/// `#[solidity_interface(name, is, inline_is, events)]`209/// - *name*: used in generated code, and for Call enum name210/// - *is*: used to provide call inheritance, not found methods will be delegated to all contracts211/// specified in is/inline_is212/// - *inline_is*: same as is, but selectors for passed contracts will be used by derived ERC165213/// implementation214///215/// `#[weight(value)]`216/// Can be added to every method of impl block, used for deriving [`evm_coder::Weighted`], which217/// is used by substrate bridge218/// - *value*: expression, which evaluates to weight required to call this method.219/// This expression can use call arguments to calculate non-constant execution time.220/// This expression should evaluate faster than actual execution does, and may provide worser case221/// than one is called222///223/// `#[solidity_interface(rename_selector)]`224/// - *rename_selector*: by default, selector name will be generated by transforming method name225/// from snake_case to camelCase. Use this option, if other naming convention is required.226/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name227/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`228/// explicitly229///230/// Also, any contract method may have doc comments, which will be automatically added to generated231/// solidity interface definitions232///233/// ## Example234///235/// ```ignore236/// struct SuperContract;237/// struct InlineContract;238/// struct Contract;239///240/// #[derive(ToLog)]241/// enum ContractEvents {242/// Event(#[indexed] uint32),243/// }244///245/// #[solidity_interface(name = "MyContract", is(SuperContract), inline_is(InlineContract))]246/// impl Contract {247/// /// Multiply two numbers248/// #[weight(200 + a + b)]249/// #[solidity_interface(rename_selector = "mul")]250/// fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {251/// Ok(a.checked_mul(b).ok_or("overflow")?)252/// }253/// }254/// ```255#[proc_macro_attribute]256pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {257 let args = parse_macro_input!(args as AttributeArgs);258 let args = solidity_interface::InterfaceInfo::from_list(&args).unwrap();259260 let input: ItemImpl = match syn::parse(stream) {261 Ok(t) => t,262 Err(e) => return e.to_compile_error().into(),263 };264265 let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {266 Ok(v) => v.expand(),267 Err(e) => e.to_compile_error(),268 };269270 (quote! {271 #input272273 #expanded274 })275 .into()276}277278#[proc_macro_attribute]279pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {280 stream281}282#[proc_macro_attribute]283pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {284 stream285}286287/// ## Syntax288///289/// `#[indexed]`290/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data291#[proc_macro_derive(ToLog, attributes(indexed))]292pub fn to_log(value: TokenStream) -> TokenStream {293 let input = parse_macro_input!(value as DeriveInput);294295 match to_log::Events::try_from(&input) {296 Ok(e) => e.expand(),297 Err(e) => e.to_compile_error(),298 }299 .into()300}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)]1819use inflector::cases;20use proc_macro::TokenStream;21use quote::quote;22use sha3::{Digest, Keccak256};23use syn::{24 DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments,25 PathSegment, Type, parse_macro_input, spanned::Spanned, Attribute, parse::Parse,26};2728mod solidity_interface;29mod to_log;3031fn fn_selector_str(input: &str) -> u32 {32 let mut hasher = Keccak256::new();33 hasher.update(input.as_bytes());34 let result = hasher.finalize();3536 let mut selector_bytes = [0; 4];37 selector_bytes.copy_from_slice(&result[0..4]);3839 u32::from_be_bytes(selector_bytes)40}4142/// Returns solidity function selector (first 4 bytes of hash) by its43/// textual representation44///45/// ```ignore46/// use evm_coder_macros::fn_selector;47///48/// assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);49/// ```50#[proc_macro]51pub fn fn_selector(input: TokenStream) -> TokenStream {52 let input = input.to_string().replace(' ', "");53 let selector = fn_selector_str(&input);5455 (quote! {56 #selector57 })58 .into()59}6061fn event_selector_str(input: &str) -> [u8; 32] {62 let mut hasher = Keccak256::new();63 hasher.update(input.as_bytes());64 let result = hasher.finalize();6566 let mut selector_bytes = [0; 32];67 selector_bytes.copy_from_slice(&result[0..32]);68 selector_bytes69}7071/// Returns solidity topic (hash) by its textual representation72///73/// ```ignore74/// use evm_coder_macros::event_topic;75///76/// assert_eq!(77/// format!("{:x}", event_topic!(Transfer(address, address, uint256))),78/// "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",79/// );80/// ```81#[proc_macro]82pub fn event_topic(stream: TokenStream) -> TokenStream {83 let input = stream.to_string().replace(' ', "");84 let selector_bytes = event_selector_str(&input);8586 (quote! {87 ::primitive_types::H256([#(88 #selector_bytes,89 )*])90 })91 .into()92}9394fn parse_path(ty: &Type) -> syn::Result<&Path> {95 match &ty {96 syn::Type::Path(pat) => {97 if let Some(qself) = &pat.qself {98 return Err(syn::Error::new(qself.ty.span(), "no receiver expected"));99 }100 Ok(&pat.path)101 }102 _ => Err(syn::Error::new(ty.span(), "expected ty to be path")),103 }104}105106fn parse_path_segment(path: &Path) -> syn::Result<&PathSegment> {107 if path.segments.len() != 1 {108 return Err(syn::Error::new(109 path.span(),110 "expected path to have only segment",111 ));112 }113 let last_segment = &path.segments.last().unwrap();114 Ok(last_segment)115}116117fn parse_ident_from_pat(pat: &Pat) -> syn::Result<&Ident> {118 match pat {119 Pat::Ident(i) => Ok(&i.ident),120 _ => Err(syn::Error::new(pat.span(), "expected pat ident")),121 }122}123124fn parse_ident_from_segment(segment: &PathSegment, allow_generics: bool) -> syn::Result<&Ident> {125 if segment.arguments != PathArguments::None && !allow_generics {126 return Err(syn::Error::new(127 segment.arguments.span(),128 "unexpected generic type",129 ));130 }131 Ok(&segment.ident)132}133134fn parse_ident_from_path(path: &Path, allow_generics: bool) -> syn::Result<&Ident> {135 let segment = parse_path_segment(path)?;136 parse_ident_from_segment(segment, allow_generics)137}138139fn parse_ident_from_type(ty: &Type, allow_generics: bool) -> syn::Result<&Ident> {140 let path = parse_path(ty)?;141 parse_ident_from_path(path, allow_generics)142}143144// Gets T out of Result<T>145fn parse_result_ok(ty: &Type) -> syn::Result<&Type> {146 let path = parse_path(ty)?;147 let segment = parse_path_segment(path)?;148149 if segment.ident != "Result" {150 return Err(syn::Error::new(151 ty.span(),152 "expected Result as return type (no renamed aliases allowed)",153 ));154 }155 let args = match &segment.arguments {156 PathArguments::AngleBracketed(e) => e,157 _ => {158 return Err(syn::Error::new(159 segment.arguments.span(),160 "missing Result generics",161 ))162 }163 };164165 let args = &args.args;166 let arg = args.first().unwrap();167168 let ty = match arg {169 GenericArgument::Type(ty) => ty,170 _ => {171 return Err(syn::Error::new(172 arg.span(),173 "expected first generic to be type",174 ))175 }176 };177178 Ok(ty)179}180181fn pascal_ident_to_call(ident: &Ident) -> Ident {182 let name = format!("{}Call", ident);183 Ident::new(&name, ident.span())184}185fn snake_ident_to_pascal(ident: &Ident) -> Ident {186 let name = ident.to_string();187 let name = cases::pascalcase::to_pascal_case(&name);188 Ident::new(&name, ident.span())189}190fn snake_ident_to_screaming(ident: &Ident) -> Ident {191 let name = ident.to_string();192 let name = cases::screamingsnakecase::to_screaming_snake_case(&name);193 Ident::new(&name, ident.span())194}195fn pascal_ident_to_snake_call(ident: &Ident) -> Ident {196 let name = ident.to_string();197 let name = cases::snakecase::to_snake_case(&name);198 let name = format!("call_{}", name);199 Ident::new(&name, ident.span())200}201202/// Derives call enum implementing [`evm_coder::Callable`], [`evm_coder::Weighted`]203/// and [`evm_coder::Call`] from impl block204///205/// ## Macro syntax206///207/// `#[solidity_interface(name, is, inline_is, events)]`208/// - *name*: used in generated code, and for Call enum name209/// - *is*: used to provide call inheritance, not found methods will be delegated to all contracts210/// specified in is/inline_is211/// - *inline_is*: same as is, but selectors for passed contracts will be used by derived ERC165212/// implementation213///214/// `#[weight(value)]`215/// Can be added to every method of impl block, used for deriving [`evm_coder::Weighted`], which216/// is used by substrate bridge217/// - *value*: expression, which evaluates to weight required to call this method.218/// This expression can use call arguments to calculate non-constant execution time.219/// This expression should evaluate faster than actual execution does, and may provide worser case220/// than one is called221///222/// `#[solidity_interface(rename_selector)]`223/// - *rename_selector*: by default, selector name will be generated by transforming method name224/// from snake_case to camelCase. Use this option, if other naming convention is required.225/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name226/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`227/// explicitly228///229/// Also, any contract method may have doc comments, which will be automatically added to generated230/// solidity interface definitions231///232/// ## Example233///234/// ```ignore235/// struct SuperContract;236/// struct InlineContract;237/// struct Contract;238///239/// #[derive(ToLog)]240/// enum ContractEvents {241/// Event(#[indexed] uint32),242/// }243///244/// #[solidity_interface(name = "MyContract", is(SuperContract), inline_is(InlineContract))]245/// impl Contract {246/// /// Multiply two numbers247/// #[weight(200 + a + b)]248/// #[solidity_interface(rename_selector = "mul")]249/// fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {250/// Ok(a.checked_mul(b).ok_or("overflow")?)251/// }252/// }253/// ```254#[proc_macro_attribute]255pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {256 let args = parse_macro_input!(args as solidity_interface::InterfaceInfo);257258 let input: ItemImpl = match syn::parse(stream) {259 Ok(t) => t,260 Err(e) => return e.to_compile_error().into(),261 };262263 let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {264 Ok(v) => v.expand(),265 Err(e) => e.to_compile_error(),266 };267268 (quote! {269 #input270271 #expanded272 })273 .into()274}275276#[proc_macro_attribute]277pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {278 stream279}280#[proc_macro_attribute]281pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {282 stream283}284285/// ## Syntax286///287/// `#[indexed]`288/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data289#[proc_macro_derive(ToLog, attributes(indexed))]290pub fn to_log(value: TokenStream) -> TokenStream {291 let input = parse_macro_input!(value as DeriveInput);292293 match to_log::Events::try_from(&input) {294 Ok(e) => e.expand(),295 Err(e) => e.to_compile_error(),296 }297 .into()298}crates/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);
crates/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);
}
crates/evm-coder/src/solidity.rsdiffbeforeafterboth--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -56,7 +56,7 @@
}
let id = self.next_id();
let mut str = String::new();
- writeln!(str, "// Anonymous struct").unwrap();
+ writeln!(str, "/// @dev anonymous struct").unwrap();
writeln!(str, "struct Tuple{} {{", id).unwrap();
for (i, name) in names.iter().enumerate() {
writeln!(str, "\t{} field_{};", name, i).unwrap();
@@ -416,12 +416,12 @@
tc: &TypeCollector,
) -> fmt::Result {
for doc in self.docs {
- writeln!(writer, "\t//{}", doc)?;
+ writeln!(writer, "\t///{}", doc)?;
}
if !self.docs.is_empty() {
- writeln!(writer, "\t//")?;
+ writeln!(writer, "\t///")?;
}
- writeln!(writer, "\t// Selector: {}", self.selector)?;
+ writeln!(writer, "\t/// Selector: {}", self.selector)?;
write!(writer, "\tfunction {}(", self.name)?;
self.args.solidity_name(writer, tc)?;
write!(writer, ")")?;
@@ -498,7 +498,7 @@
if self.selector != ZERO_BYTES {
writeln!(
out,
- "// Selector: {:0>8x}",
+ "/// @dev the ERC-165 identifier for this interface is 0x{:0>8x}",
u32::from_be_bytes(self.selector)
)?;
}
crates/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,
crates/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 {}
crates/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!()