Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sol-macro): evaluate array sizes #840

Merged
merged 1 commit into from
Jan 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions crates/sol-macro-expander/src/expand/contract.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! [`ItemContract`] expansion.

use super::{anon_name, ty, ExpCtxt};
use super::{anon_name, ExpCtxt};
use crate::utils::ExprArray;
use alloy_sol_macro_input::{docs_str, mk_doc, ContainsSolAttrs};
use ast::{Item, ItemContract, ItemError, ItemEvent, ItemFunction, SolIdent, Spanned};
Expand Down Expand Up @@ -300,7 +300,7 @@ pub(super) fn expand(cx: &mut ExpCtxt<'_>, contract: &ItemContract) -> Result<To
let names1 = c.parameters.names().enumerate().map(anon_name);
let names2 = names1.clone();
let tys = c.parameters.types().map(|ty| {
super::ty::expand_rust_type(ty, &cx.crates)
cx.expand_rust_type(ty)
});
Some((quote!(#(#names1: #tys),*), quote!(#(#names2,)*)))
}).unzip();
Expand Down Expand Up @@ -618,7 +618,7 @@ impl ToExpand<'_> {
types: Some(types),
min_data_len: functions
.iter()
.map(|function| ty::params_base_data_size(cx, &function.parameters))
.map(|function| cx.params_base_data_size(&function.parameters))
.min()
.unwrap(),
trait_: format_ident!("SolCall"),
Expand All @@ -632,7 +632,7 @@ impl ToExpand<'_> {
types: None,
min_data_len: errors
.iter()
.map(|error| ty::params_base_data_size(cx, &error.parameters))
.map(|error| cx.params_base_data_size(&error.parameters))
.min()
.unwrap(),
trait_: format_ident!("SolError"),
Expand All @@ -649,7 +649,7 @@ impl ToExpand<'_> {
types: None,
min_data_len: events
.iter()
.map(|event| ty::params_base_data_size(cx, &event.params()))
.map(|event| cx.params_base_data_size(&event.params()))
.min()
.unwrap(),
trait_: format_ident!("SolEvent"),
Expand Down Expand Up @@ -981,7 +981,7 @@ fn call_builder_method(f: &ItemFunction, cx: &ExpCtxt<'_>) -> TokenStream {
let call_name = cx.call_name(f);
let param_names1 = f.parameters.names().enumerate().map(anon_name);
let param_names2 = param_names1.clone();
let param_tys = f.parameters.types().map(|ty| super::ty::expand_rust_type(ty, &cx.crates));
let param_tys = f.parameters.types().map(|ty| cx.expand_rust_type(ty));
let doc = format!("Creates a new call builder for the [`{name}`] function.");
quote! {
#[doc = #doc]
Expand Down
10 changes: 5 additions & 5 deletions crates/sol-macro-expander/src/expand/event.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! [`ItemEvent`] expansion.

use super::{anon_name, expand_event_tokenize, expand_tuple_types, expand_type, ty, ExpCtxt};
use super::{anon_name, expand_event_tokenize, expand_tuple_types, ExpCtxt};
use alloy_sol_macro_input::{mk_doc, ContainsSolAttrs};
use ast::{EventParameter, ItemEvent, SolIdent, Spanned};
use proc_macro2::TokenStream;
Expand Down Expand Up @@ -79,7 +79,7 @@ pub(super) fn expand(cx: &ExpCtxt<'_>, event: &ItemEvent) -> Result<TokenStream>

let encode_topics_impl = event.parameters.iter().enumerate().filter(|(_, p)| p.is_indexed()).map(|(i, p)| {
let name = anon_name((i, p.name.as_ref()));
let ty = expand_type(&p.ty, &cx.crates);
let ty = cx.expand_type(&p.ty);

if cx.indexed_as_hash(p) {
quote! {
Expand Down Expand Up @@ -242,7 +242,7 @@ fn expand_event_topic_type(param: &EventParameter, cx: &ExpCtxt<'_>) -> TokenStr
if cx.indexed_as_hash(param) {
quote_spanned! {param.ty.span()=> #alloy_sol_types::sol_data::FixedBytes<32> }
} else {
expand_type(&param.ty, &cx.crates)
cx.expand_type(&param.ty)
}
}

Expand All @@ -255,9 +255,9 @@ fn expand_event_topic_field(
let name = anon_name((i, name));
let ty = if cx.indexed_as_hash(param) {
let bytes32 = ast::Type::FixedBytes(name.span(), core::num::NonZeroU16::new(32).unwrap());
ty::expand_rust_type(&bytes32, &cx.crates)
cx.expand_rust_type(&bytes32)
} else {
ty::expand_rust_type(&param.ty, &cx.crates)
cx.expand_rust_type(&param.ty)
};
quote!(#name: #ty)
}
35 changes: 18 additions & 17 deletions crates/sol-macro-expander/src/expand/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
//! Functions which generate Rust code from the Solidity AST.

use crate::{
expand::ty::expand_rust_type,
utils::{self, ExprArray},
};
use crate::utils::{self, ExprArray};
use alloy_sol_macro_input::{ContainsSolAttrs, SolAttrs};
use ast::{
visit_mut, EventParameter, File, Item, ItemError, ItemEvent, ItemFunction, Parameters,
Expand All @@ -25,15 +22,13 @@ use syn::{ext::IdentExt, parse_quote, Attribute, Error, Result};
#[macro_use]
mod macros;

pub mod ty;
pub use ty::expand_type;

mod contract;
mod r#enum;
mod error;
mod event;
mod function;
mod r#struct;
mod ty;
mod udt;
mod var_def;

Expand All @@ -50,6 +45,14 @@ pub fn expand(ast: File) -> Result<TokenStream> {
ExpCtxt::new(&ast).expand()
}

/// Expands a Rust type from a Solidity type.
pub fn expand_type(ty: &Type, crates: &ExternCrates) -> TokenStream {
let dummy_file = File { attrs: Vec::new(), items: Vec::new() };
let mut cx = ExpCtxt::new(&dummy_file);
cx.crates = crates.clone();
cx.expand_type(ty)
}

/// Mapping namespace -> ident -> T
///
/// Keeps namespaced items. Namespace `None` represents global namespace (top-level items).
Expand Down Expand Up @@ -302,8 +305,7 @@ impl ExpCtxt<'_> {
let mut result = Ok(());

let mut selectors = vec![HashMap::new(); 3];
let all_items = std::mem::take(&mut self.all_items);
for (namespace, items) in &all_items.0 {
for (namespace, items) in &self.all_items.clone().0 {
self.with_namespace(namespace.clone(), |this| {
selectors.iter_mut().for_each(|s| s.clear());
for (_, &item) in items {
Expand Down Expand Up @@ -348,7 +350,6 @@ impl ExpCtxt<'_> {
}
})
}
self.all_items = all_items;

result
}
Expand Down Expand Up @@ -691,8 +692,8 @@ impl<'ast> ExpCtxt<'ast> {
let mut derive_others = true;
for ty in types {
let ty = ty.borrow();
derive_default = derive_default && ty::can_derive_default(self, ty);
derive_others = derive_others && ty::can_derive_builtin_traits(self, ty);
derive_default = derive_default && self.can_derive_default(ty);
derive_others = derive_others && self.can_derive_builtin_traits(ty);
}
if derive_default {
derives.push("Default");
Expand Down Expand Up @@ -735,7 +736,7 @@ impl<'ast> ExpCtxt<'ast> {
///
/// These should be added to import lists at the top of anonymous `const _: () = { ... }` blocks,
/// and in case of top-level structs they should be inlined into all `path`s.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct ExternCrates {
/// The path to the `alloy_sol_types` crate.
pub sol_types: syn::Path,
Expand Down Expand Up @@ -773,7 +774,7 @@ fn expand_fields<'a, P>(
) -> impl Iterator<Item = TokenStream> + 'a {
params.iter().enumerate().map(|(i, var)| {
let name = anon_name((i, var.name.as_ref()));
let ty = expand_rust_type(&var.ty, &cx.crates);
let ty = cx.expand_rust_type(&var.ty);
let attrs = &var.attrs;
quote! {
#(#attrs)*
Expand Down Expand Up @@ -852,10 +853,10 @@ fn expand_tuple_types<'a, I: IntoIterator<Item = &'a Type>>(
let mut rust = TokenStream::new();
let comma = Punct::new(',', Spacing::Alone);
for ty in types {
ty::rec_expand_type(ty, &cx.crates, &mut sol);
cx.expand_type_to(ty, &mut sol);
sol.append(comma.clone());

ty::rec_expand_rust_type(ty, &cx.crates, &mut rust);
cx.expand_rust_type_to(ty, &mut rust);
rust.append(comma.clone());
}
let wrap_in_parens =
Expand Down Expand Up @@ -888,7 +889,7 @@ fn tokenize_<'a>(
cx: &'a ExpCtxt<'_>,
) -> TokenStream {
let statements = iter.into_iter().map(|(i, ty, name)| {
let ty = expand_type(ty, &cx.crates);
let ty = cx.expand_type(ty);
let name = name.cloned().unwrap_or_else(|| generate_name(i).into());
quote! {
<#ty as alloy_sol_types::SolType>::tokenize(&self.#name)
Expand Down
6 changes: 3 additions & 3 deletions crates/sol-macro-expander/src/expand/struct.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! [`ItemStruct`] expansion.

use super::{expand_fields, expand_from_into_tuples, expand_tokenize, expand_type, ExpCtxt};
use super::{expand_fields, expand_from_into_tuples, expand_tokenize, ExpCtxt};
use alloy_sol_macro_input::{mk_doc, ContainsSolAttrs};
use ast::{Item, ItemStruct, Spanned, Type};
use proc_macro2::TokenStream;
Expand Down Expand Up @@ -33,7 +33,7 @@ pub(super) fn expand(cx: &ExpCtxt<'_>, s: &ItemStruct) -> Result<TokenStream> {
let docs = sol_attrs.docs.or(cx.attrs.docs).unwrap_or(true);

let (field_types, field_names): (Vec<_>, Vec<_>) =
fields.iter().map(|f| (expand_type(&f.ty, &cx.crates), f.name.as_ref().unwrap())).unzip();
fields.iter().map(|f| (cx.expand_type(&f.ty), f.name.as_ref().unwrap())).unzip();

let eip712_encode_type_fns = expand_encode_type_fns(cx, fields, name);

Expand Down Expand Up @@ -227,7 +227,7 @@ fn expand_encode_type_fns(
}
});
// cannot panic as this field is guaranteed to contain a custom type
let ty = expand_type(&ty.unwrap(), &cx.crates);
let ty = cx.expand_type(&ty.unwrap());

quote! {
components.push(<#ty as alloy_sol_types::SolStruct>::eip712_root_type());
Expand Down
8 changes: 4 additions & 4 deletions crates/sol-macro-expander/src/expand/to_abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ fn ty_to_param(name: Option<String>, ty: &ast::Type, cx: &ExpCtxt<'_>) -> Param

fn ty_abi_string(ty: &ast::Type, cx: &ExpCtxt<'_>) -> String {
let mut suffix = String::new();
rec_ty_abi_string_suffix(ty, &mut suffix);
rec_ty_abi_string_suffix(cx, ty, &mut suffix);

let mut ty = ty.peel_arrays();
if let ast::Type::Custom(name) = ty {
Expand All @@ -151,10 +151,10 @@ fn ty_abi_string(ty: &ast::Type, cx: &ExpCtxt<'_>) -> String {
format!("{}{suffix}", super::ty::TypePrinter::new(cx, ty))
}

fn rec_ty_abi_string_suffix(ty: &ast::Type, s: &mut String) {
fn rec_ty_abi_string_suffix(cx: &ExpCtxt<'_>, ty: &ast::Type, s: &mut String) {
if let ast::Type::Array(array) = ty {
rec_ty_abi_string_suffix(&array.ty, s);
if let Some(size) = array.size() {
rec_ty_abi_string_suffix(cx, &array.ty, s);
if let Some(size) = cx.eval_array_size(array) {
write!(s, "[{size}]").unwrap();
} else {
s.push_str("[]");
Expand Down
Loading
Loading