git.delta.rocks / unique-network / refs/commits / 460ecccc2904

difftreelog

source

crates/evm-coder/procedural/src/lib.rs6.4 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)]1819use inflector::cases;20use proc_macro::TokenStream;21use quote::quote;22use sha3::{Digest, Keccak256};23use syn::{24	DeriveInput, GenericArgument, Ident, ItemImpl, Pat, Path, PathArguments, PathSegment, Type,25	parse_macro_input, spanned::Spanned,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/// See documentation for this proc-macro reexported in `evm-coder` crate203#[proc_macro_attribute]204pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {205	let args = parse_macro_input!(args as solidity_interface::InterfaceInfo);206207	let input: ItemImpl = match syn::parse(stream) {208		Ok(t) => t,209		Err(e) => return e.to_compile_error().into(),210	};211212	let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {213		Ok(v) => v.expand(),214		Err(e) => e.to_compile_error(),215	};216217	(quote! {218		#input219220		#expanded221	})222	.into()223}224225#[proc_macro_attribute]226pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {227	stream228}229#[proc_macro_attribute]230pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {231	stream232}233234/// See documentation for this proc-macro reexported in `evm-coder` crate235#[proc_macro_derive(ToLog, attributes(indexed))]236pub fn to_log(value: TokenStream) -> TokenStream {237	let input = parse_macro_input!(value as DeriveInput);238239	match to_log::Events::try_from(&input) {240		Ok(e) => e.expand(),241		Err(e) => e.to_compile_error(),242	}243	.into()244}