git.delta.rocks / unique-network / refs/commits / 00d3414d19d7

difftreelog

feat add implementations of AbiRead & AbiWrite with macto AbiCoder

Trubnikov Sergey2022-11-14parent: #3d5704a.patch.diff
in: master

3 files changed

modifiedcrates/evm-coder/procedural/src/abi_derive.rsdiffbeforeafterboth
before · crates/evm-coder/procedural/src/abi_derive.rs
1use quote::quote;23pub(crate) fn impl_abi_macro(ast: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {4	// dbg!(ast);5	let name = &ast.ident;6	let can_be_plcaed_in_vec = impl_can_be_placed_in_vec(name);7	let abi_type = impl_abi_type(ast)?;8	// println!("{}", abi_type);9	Ok(quote! {10		#can_be_plcaed_in_vec11		#abi_type12	})13}1415fn impl_can_be_placed_in_vec(ident: &syn::Ident) -> proc_macro2::TokenStream {16	quote! {17		impl ::evm_coder::abi::sealed::CanBePlacedInVec for #ident {}18	}19}2021fn map_field_to_type<'a>(field: &'a syn::Field) -> &'a syn::Type {22	&field.ty23}2425fn impl_abi_type(ast: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {26	let name = &ast.ident;27	let (fields, params_count) = match &ast.data {28		syn::Data::Struct(ds) => match ds.fields {29			syn::Fields::Named(ref fields) => Ok((30				fields.named.iter().map(map_field_to_type),31				fields.named.len(),32			)),33			syn::Fields::Unnamed(ref fields) => Ok((34				fields.unnamed.iter().map(map_field_to_type),35				fields.unnamed.len(),36			)),37			syn::Fields::Unit => Err(syn::Error::new(name.span(), "Unit structs not supported")),38		},39		syn::Data::Enum(_) => Err(syn::Error::new(name.span(), "Enums not supported")),40		syn::Data::Union(_) => Err(syn::Error::new(name.span(), "Unions not supported")),41	}?;4243	let mut params_signature = {44		let fields = fields.clone();45		quote!(46			#(nameof(<#fields as ::evm_coder::abi::AbiType>::SIGNATURE) fixed(","))*47		)48	};4950	if params_count == 0 {51		return Err(syn::Error::new(name.span(), "Empty structs not supported"));52	};5354	params_signature.extend(quote!(shift_left(1)));5556	let fields_for_dynamic = fields.clone();5758	Ok(quote! {59		impl ::evm_coder::abi::AbiType for #name {60			const SIGNATURE: ::evm_coder::custom_signature::SignatureUnit = ::evm_coder::make_signature!(61				new fixed("(")62				#params_signature63				fixed(")")64			);65			fn is_dynamic() -> bool {66				false67				#(68					|| <#fields_for_dynamic as ::evm_coder::abi::AbiType>::is_dynamic()69				)*70			}71			fn size() -> usize {72				0 #(+ <#fields as ::evm_coder::abi::AbiType>::size())*73			}74		}75	})76}
after · crates/evm-coder/procedural/src/abi_derive.rs
1use quote::quote;23pub(crate) fn impl_abi_macro(ast: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {4	// dbg!(ast);5	let name = &ast.ident;6	let (is_named_fields, field_names, field_types, params_count) = match &ast.data {7		syn::Data::Struct(ds) => match ds.fields {8			syn::Fields::Named(ref fields) => Ok((9				true,10				fields.named.iter().enumerate().map(map_field_to_name),11				fields.named.iter().map(map_field_to_type),12				fields.named.len(),13			)),14			syn::Fields::Unnamed(ref fields) => Ok((15				false,16				fields.unnamed.iter().enumerate().map(map_field_to_name),17				fields.unnamed.iter().map(map_field_to_type),18				fields.unnamed.len(),19			)),20			syn::Fields::Unit => Err(syn::Error::new(name.span(), "Unit structs not supported")),21		},22		syn::Data::Enum(_) => Err(syn::Error::new(name.span(), "Enums not supported")),23		syn::Data::Union(_) => Err(syn::Error::new(name.span(), "Unions not supported")),24	}?;2526	if params_count == 0 {27		return Err(syn::Error::new(name.span(), "Empty structs not supported"));28	};2930	let can_be_plcaed_in_vec = impl_can_be_placed_in_vec(name);31	let abi_type = impl_abi_type(name, field_types.clone());32	let abi_read = impl_abi_read(name, is_named_fields, field_names.clone(), field_types);33	let abi_write = impl_abi_write(name, is_named_fields, params_count, field_names);34	println!("{}", abi_write);35	Ok(quote! {36		#can_be_plcaed_in_vec37		#abi_type38		#abi_read39		#abi_write40	})41}4243fn impl_can_be_placed_in_vec(ident: &syn::Ident) -> proc_macro2::TokenStream {44	quote! {45		impl ::evm_coder::abi::sealed::CanBePlacedInVec for #ident {}46	}47}4849fn map_field_to_name(field: (usize, &syn::Field)) -> syn::Ident {50	match field.1.ident.as_ref() {51		Some(name) => name.clone(),52		None => {53			let mut name = "field".to_string();54			name.push_str(field.0.to_string().as_str());55			syn::Ident::new(name.as_str(), proc_macro2::Span::call_site())56		}57	}58}5960fn map_field_to_type<'a>(field: &'a syn::Field) -> &'a syn::Type {61	&field.ty62}6364fn impl_abi_type<'a>(65	name: &syn::Ident,66	field_types: impl Iterator<Item = &'a syn::Type> + Clone,67) -> proc_macro2::TokenStream {68	let mut params_signature = {69		let types = field_types.clone();70		quote!(71			#(nameof(<#types as ::evm_coder::abi::AbiType>::SIGNATURE) fixed(","))*72		)73	};7475	params_signature.extend(quote!(shift_left(1)));7677	let fields_for_dynamic = field_types.clone();7879	quote! {80		impl ::evm_coder::abi::AbiType for #name {81			const SIGNATURE: ::evm_coder::custom_signature::SignatureUnit = ::evm_coder::make_signature!(82				new fixed("(")83				#params_signature84				fixed(")")85			);86			fn is_dynamic() -> bool {87				false88				#(89					|| <#fields_for_dynamic as ::evm_coder::abi::AbiType>::is_dynamic()90				)*91			}92			fn size() -> usize {93				0 #(+ <#field_types as ::evm_coder::abi::AbiType>::size())*94			}95		}96	}97}9899fn impl_abi_read<'a>(100	name: &syn::Ident,101	is_named_fields: bool,102	field_names: impl Iterator<Item = proc_macro2::Ident> + Clone,103	field_types: impl Iterator<Item = &'a syn::Type> + Clone,104) -> proc_macro2::TokenStream {105	let field_names1 = field_names.clone();106107	let struct_constructor = if is_named_fields {108		quote!(Ok(Self { #(#field_names1),* }))109	} else {110		quote!(Ok(Self ( #(#field_names1),* )))111	};112	quote!(113		impl ::evm_coder::abi::AbiRead for #name {114			fn abi_read(reader: &mut ::evm_coder::abi::AbiReader) -> ::evm_coder::execution::Result<Self> {115				let size = if !<Self as ::evm_coder::abi::AbiType>::is_dynamic() {116					Some(<Self as ::evm_coder::abi::AbiType>::size())117				} else {118					None119				};120				let mut subresult = reader.subresult(size)?;121				#(122					let #field_names = <#field_types as ::evm_coder::abi::AbiRead>::abi_read(&mut subresult)?;123				)*124125				#struct_constructor126			}127		}128	)129}130131fn impl_abi_write<'a>(132	name: &syn::Ident,133	is_named_fields: bool,134	params_count: usize,135	field_names: impl Iterator<Item = proc_macro2::Ident> + Clone,136) -> proc_macro2::TokenStream {137	let abi_write = if is_named_fields {138		quote!(139			#(140				self.#field_names.abi_write(writer);141			)*142		)143	} else {144		let field_names = (0..params_count)145			.into_iter()146			.map(proc_macro2::Literal::usize_unsuffixed);147		quote!(148			#(149				self.#field_names.abi_write(writer);150			)*151		)152	};153	quote!(154		impl ::evm_coder::abi::AbiWrite for #name {155			fn abi_write(&self, writer: &mut ::evm_coder::abi::AbiWriter) {156				#abi_write157			}158		}159	)160}
modifiedcrates/evm-coder/src/abi/mod.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/abi/mod.rs
+++ b/crates/evm-coder/src/abi/mod.rs
@@ -186,7 +186,7 @@
 
 	/// Slice recursive buffer, advance one word for buffer offset
 	/// If `size` is [`None`] then [`Self::offset`] and [`Self::subresult_offset`] evals from [`Self::buf`].
-	fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
+	pub fn subresult(&mut self, size: Option<usize>) -> Result<AbiReader<'i>> {
 		let subresult_offset = self.subresult_offset;
 		let offset = if let Some(size) = size {
 			self.offset += size;
modifiedcrates/evm-coder/tests/abi_derive_generation.rsdiffbeforeafterboth
--- a/crates/evm-coder/tests/abi_derive_generation.rs
+++ b/crates/evm-coder/tests/abi_derive_generation.rs
@@ -405,3 +405,8 @@
 		<TupleStruct3DerivedMixedParam as AbiType>::size()
 	);
 }
+
+// #[test]
+// fn impl_abi_read() {
+// 	TypeStruct1SimpleParam::
+// }