git.delta.rocks / unique-network / refs/commits / 507b779dd4fb

difftreelog

source

crates/evm-coder/procedural/src/lib.rs6.6 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 abi_derive;29mod 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 one 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/// See documentation for this proc-macro reexported in `evm-coder` crate204#[proc_macro_attribute]205pub fn solidity_interface(args: TokenStream, stream: TokenStream) -> TokenStream {206	let args = parse_macro_input!(args as solidity_interface::InterfaceInfo);207208	let input: ItemImpl = match syn::parse(stream) {209		Ok(t) => t,210		Err(e) => return e.to_compile_error().into(),211	};212213	let expanded = match solidity_interface::SolidityInterface::try_from(args, &input) {214		Ok(v) => v.expand(),215		Err(e) => e.to_compile_error(),216	};217218	(quote! {219		#input220221		#expanded222	})223	.into()224}225226#[proc_macro_attribute]227pub fn solidity(_args: TokenStream, stream: TokenStream) -> TokenStream {228	stream229}230#[proc_macro_attribute]231pub fn weight(_args: TokenStream, stream: TokenStream) -> TokenStream {232	stream233}234235/// See documentation for this proc-macro reexported in `evm-coder` crate236#[proc_macro_derive(ToLog, attributes(indexed))]237pub fn to_log(value: TokenStream) -> TokenStream {238	let input = parse_macro_input!(value as DeriveInput);239240	match to_log::Events::try_from(&input) {241		Ok(e) => e.expand(),242		Err(e) => e.to_compile_error(),243	}244	.into()245}246247#[proc_macro_derive(AbiCoder)]248pub fn abi_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {249	let ast = syn::parse(input).unwrap();250	let ts = match abi_derive::impl_abi_macro(&ast) {251		Ok(e) => e,252		Err(e) => e.to_compile_error(),253	};254	ts.into()255}