alloy-sol-macro 0.4.0

Solidity to Rust procedural macro
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! [`ItemContract`] expansion.

use super::{ty, ExpCtxt};
use crate::{attr, utils::ExprArray};
use ast::{Item, ItemContract, ItemError, ItemEvent, ItemFunction, SolIdent};
use heck::ToSnakeCase;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote};
use syn::{ext::IdentExt, parse_quote, Attribute, Result};

/// Expands an [`ItemContract`]:
///
/// ```ignore (pseudo-code)
/// pub mod #name {
///     pub enum #{name}Calls {
///         ...
///    }
///
///     pub enum #{name}Errors {
///         ...
///    }
/// }
/// ```
pub(super) fn expand(cx: &ExpCtxt<'_>, contract: &ItemContract) -> Result<TokenStream> {
    let ItemContract {
        attrs, name, body, ..
    } = contract;

    let (sol_attrs, attrs) = attr::SolAttrs::parse(attrs)?;
    let extra_methods = sol_attrs
        .extra_methods
        .or(cx.attrs.extra_methods)
        .unwrap_or(false);

    let bytecode = sol_attrs.bytecode.map(|lit| {
        let name = Ident::new("BYTECODE", lit.span());
        quote! {
            /// The creation / init code of the contract.
            pub static #name: ::alloy_sol_types::private::Bytes = ::alloy_sol_types::private::bytes!(#lit);
        }
    });
    let deployed_bytecode = sol_attrs.deployed_bytecode.map(|lit| {
        let name = Ident::new("DEPLOYED_BYTECODE", lit.span());
        quote! {
            /// The runtime bytecode of the contract.
            pub static #name: ::alloy_sol_types::private::Bytes = ::alloy_sol_types::private::bytes!(#lit);
        }
    });

    let mut functions = Vec::with_capacity(contract.body.len());
    let mut errors = Vec::with_capacity(contract.body.len());
    let mut events = Vec::with_capacity(contract.body.len());

    let mut item_tokens = TokenStream::new();
    let d_attrs: Vec<Attribute> = attr::derives(&attrs).cloned().collect();
    for item in body {
        match item {
            Item::Function(function) if function.name.is_some() => functions.push(function),
            Item::Error(error) => errors.push(error),
            Item::Event(event) => events.push(event),
            _ => {}
        }
        if !d_attrs.is_empty() {
            item_tokens.extend(quote!(#(#d_attrs)*));
        }
        item_tokens.extend(cx.expand_item(item)?);
    }

    let functions_enum = (!functions.is_empty()).then(|| {
        let mut attrs = d_attrs.clone();
        let doc_str = format!("Container for all the [`{name}`](self) function calls.");
        attrs.push(parse_quote!(#[doc = #doc_str]));
        CallLikeExpander::from_functions(cx, name, functions).expand(attrs, extra_methods)
    });

    let errors_enum = (!errors.is_empty()).then(|| {
        let mut attrs = d_attrs.clone();
        let doc_str = format!("Container for all the [`{name}`](self) custom errors.");
        attrs.push(parse_quote!(#[doc = #doc_str]));
        CallLikeExpander::from_errors(cx, name, errors).expand(attrs, extra_methods)
    });

    let events_enum = (!events.is_empty()).then(|| {
        let mut attrs = d_attrs;
        let doc_str = format!("Container for all the [`{name}`](self) events.");
        attrs.push(parse_quote!(#[doc = #doc_str]));
        CallLikeExpander::from_events(cx, name, events).expand_event(attrs, extra_methods)
    });

    let mod_attrs = attr::docs(&attrs);
    let mod_docs = (!attr::has_docs(&attrs))
        .then(|| attr::mk_doc("Module containing a contract's types and functions."));
    let tokens = quote! {
        #mod_docs
        #(#mod_attrs)*
        #[allow(non_camel_case_types, non_snake_case, clippy::style)]
        pub mod #name {
            use super::*;

            #bytecode
            #deployed_bytecode

            #item_tokens

            #functions_enum
            #errors_enum
            #events_enum
        }
    };
    Ok(tokens)
}

// note that item impls generated here do not need to be wrapped in an anonymous
// constant (`const _: () = { ... };`) because they are in one already

/// Expands a `SolInterface` enum:
///
/// ```ignore (pseudo-code)
/// #name = #{contract_name}Calls | #{contract_name}Errors | #{contract_name}Events;
///
/// pub enum #name {
///    #(#variants(#types),)*
/// }
///
/// impl SolInterface for #name {
///     ...
/// }
///
/// impl #name {
///     pub const SELECTORS: &'static [[u8; _]] = &[...];
/// }
///
/// #if extra_methods
/// #(
///     impl From<#types> for #name { ... }
///     impl TryFrom<#name> for #types { ... }
/// )*
///
/// impl #name {
///     #(
///         pub fn #is_variant,#as_variant,#as_variant_mut(...) -> ... { ... }
///     )*
/// }
/// #endif
/// ```
struct CallLikeExpander<'a> {
    cx: &'a ExpCtxt<'a>,
    name: Ident,
    variants: Vec<Ident>,
    min_data_len: usize,
    trait_: Ident,
    data: CallLikeExpanderData,
}

enum CallLikeExpanderData {
    Function {
        selectors: Vec<ExprArray<u8, 4>>,
        types: Vec<Ident>,
    },
    Error {
        selectors: Vec<ExprArray<u8, 4>>,
    },
    Event {
        selectors: Vec<ExprArray<u8, 32>>,
    },
}

impl<'a> CallLikeExpander<'a> {
    fn from_functions(
        cx: &'a ExpCtxt<'a>,
        contract_name: &SolIdent,
        functions: Vec<&ItemFunction>,
    ) -> Self {
        let variants: Vec<_> = functions
            .iter()
            .map(|&f| cx.overloaded_name(f.into()).0)
            .collect();

        let types: Vec<_> = variants.iter().map(|name| cx.raw_call_name(name)).collect();

        let mut selectors: Vec<_> = functions.iter().map(|f| cx.function_selector(f)).collect();
        selectors.sort_unstable_by_key(|a| a.array);

        Self {
            cx,
            name: format_ident!("{contract_name}Calls"),
            variants,
            min_data_len: functions
                .iter()
                .map(|function| ty::params_base_data_size(cx, &function.arguments))
                .min()
                .unwrap(),
            trait_: Ident::new("SolCall", Span::call_site()),
            data: CallLikeExpanderData::Function { selectors, types },
        }
    }

    fn from_errors(cx: &'a ExpCtxt<'a>, contract_name: &SolIdent, errors: Vec<&ItemError>) -> Self {
        let mut selectors: Vec<_> = errors.iter().map(|e| cx.error_selector(e)).collect();
        selectors.sort_unstable_by_key(|a| a.array);

        Self {
            cx,
            name: format_ident!("{contract_name}Errors"),
            variants: errors.iter().map(|error| error.name.0.clone()).collect(),
            min_data_len: errors
                .iter()
                .map(|error| ty::params_base_data_size(cx, &error.parameters))
                .min()
                .unwrap(),
            trait_: Ident::new("SolError", Span::call_site()),
            data: CallLikeExpanderData::Error { selectors },
        }
    }

    fn from_events(cx: &'a ExpCtxt<'a>, contract_name: &SolIdent, events: Vec<&ItemEvent>) -> Self {
        let variants: Vec<_> = events
            .iter()
            .map(|&event| cx.overloaded_name(event.into()).0)
            .collect();

        let mut selectors: Vec<_> = events.iter().map(|e| cx.event_selector(e)).collect();
        selectors.sort_unstable_by_key(|a| a.array);

        Self {
            cx,
            name: format_ident!("{contract_name}Events"),
            variants,
            min_data_len: events
                .iter()
                .map(|event| ty::params_base_data_size(cx, &event.params()))
                .min()
                .unwrap(),
            trait_: Ident::new("SolEvent", Span::call_site()),
            data: CallLikeExpanderData::Event { selectors },
        }
    }

    /// Type name overrides. Currently only functions support because of the
    /// `Call` suffix.
    fn types(&self) -> &[Ident] {
        match &self.data {
            CallLikeExpanderData::Function { types, .. } => types,
            _ => &self.variants,
        }
    }

    fn expand(self, attrs: Vec<Attribute>, extra_methods: bool) -> TokenStream {
        let Self {
            name,
            variants,
            min_data_len,
            trait_,
            ..
        } = &self;
        let types = self.types();

        assert_eq!(variants.len(), types.len());
        let name_s = name.to_string();
        let count = variants.len();
        let def = self.generate_enum(attrs, extra_methods);
        quote! {
            #def

            #[automatically_derived]
            impl ::alloy_sol_types::SolInterface for #name {
                const NAME: &'static str = #name_s;
                const MIN_DATA_LENGTH: usize = #min_data_len;
                const COUNT: usize = #count;

                #[inline]
                fn selector(&self) -> [u8; 4] {
                    match self {#(
                        Self::#variants(_) => <#types as ::alloy_sol_types::#trait_>::SELECTOR,
                    )*}
                }

                #[inline]
                fn selector_at(i: usize) -> Option<[u8; 4]> {
                    Self::SELECTORS.get(i).copied()
                }

                #[inline]
                fn valid_selector(selector: [u8; 4]) -> bool {
                    ::core::matches!(selector, #(<#types as ::alloy_sol_types::#trait_>::SELECTOR)|*)
                }

                #[inline]
                fn abi_decode_raw(
                    selector: [u8; 4],
                    data: &[u8],
                    validate: bool
                )-> ::alloy_sol_types::Result<Self> {
                    match selector {
                        #(<#types as ::alloy_sol_types::#trait_>::SELECTOR => {
                            <#types as ::alloy_sol_types::#trait_>::abi_decode_raw(data, validate)
                                .map(Self::#variants)
                        })*
                        s => ::core::result::Result::Err(::alloy_sol_types::Error::unknown_selector(
                            Self::NAME,
                            s,
                        )),
                    }
                }

                #[inline]
                fn abi_encoded_size(&self) -> usize {
                    match self {#(
                        Self::#variants(inner) =>
                            <#types as ::alloy_sol_types::#trait_>::abi_encoded_size(inner),
                    )*}
                }

                #[inline]
                fn abi_encode_raw(&self, out: &mut ::alloy_sol_types::private::Vec<u8>) {
                    match self {#(
                        Self::#variants(inner) =>
                            <#types as ::alloy_sol_types::#trait_>::abi_encode_raw(inner, out),
                    )*}
                }
            }
        }
    }

    fn expand_event(self, attrs: Vec<Attribute>, extra_methods: bool) -> TokenStream {
        // TODO: SolInterface for events
        self.generate_enum(attrs, extra_methods)
    }

    fn generate_enum(&self, mut attrs: Vec<Attribute>, extra_methods: bool) -> TokenStream {
        let Self {
            name,
            variants,
            data,
            ..
        } = self;
        let (selectors, selector_type) = match data {
            CallLikeExpanderData::Function { selectors, .. }
            | CallLikeExpanderData::Error { selectors } => {
                (quote!(#(#selectors,)*), quote!([u8; 4]))
            }
            CallLikeExpanderData::Event { selectors } => {
                (quote!(#(#selectors,)*), quote!([u8; 32]))
            }
        };

        let types = self.types();
        self.cx.type_derives(
            &mut attrs,
            types.iter().cloned().map(ast::Type::custom),
            false,
        );
        let tokens = quote! {
            #(#attrs)*
            pub enum #name {
                #(#variants(#types),)*
            }

            #[automatically_derived]
            impl #name {
                /// All the selectors of this enum.
                ///
                /// Note that the selectors might not be in the same order as the
                /// variants, as they are sorted instead of ordered by definition.
                pub const SELECTORS: &'static [#selector_type] = &[#selectors];
            }
        };

        if extra_methods {
            let conversions = variants
                .iter()
                .zip(types)
                .map(|(v, t)| generate_variant_conversions(name, v, t));
            let methods = variants.iter().zip(types).map(generate_variant_methods);
            quote! {
                #tokens

                #(#conversions)*

                #[automatically_derived]
                impl #name {
                    #(#methods)*
                }
            }
        } else {
            tokens
        }
    }
}

fn generate_variant_conversions(name: &Ident, variant: &Ident, ty: &Ident) -> TokenStream {
    quote! {
        #[automatically_derived]
        impl ::core::convert::From<#ty> for #name {
            #[inline]
            fn from(value: #ty) -> Self {
                Self::#variant(value)
            }
        }

        #[automatically_derived]
        impl ::core::convert::TryFrom<#name> for #ty {
            type Error = #name;

            #[inline]
            fn try_from(value: #name) -> ::core::result::Result<Self, #name> {
                match value {
                    #name::#variant(value) => ::core::result::Result::Ok(value),
                    _ => ::core::result::Result::Err(value),
                }
            }
        }
    }
}

fn generate_variant_methods((variant, ty): (&Ident, &Ident)) -> TokenStream {
    let name = variant.unraw();
    let name_snake = snakify(&name.to_string());

    let is_variant = format_ident!("is_{name_snake}");
    let is_variant_doc = format!("Returns `true` if `self` matches [`{name}`](Self::{name}).");

    let as_variant = format_ident!("as_{name_snake}");
    let as_variant_doc = format!(
        "Returns an immutable reference to the inner [`{ty}`] if `self` matches [`{name}`](Self::{name})."
    );

    let as_variant_mut = format_ident!("as_{name_snake}_mut");
    let as_variant_mut_doc = format!(
        "Returns a mutable reference to the inner [`{ty}`] if `self` matches [`{name}`](Self::{name})."
    );

    quote! {
        #[doc = #is_variant_doc]
        #[inline]
        pub const fn #is_variant(&self) -> bool {
            ::core::matches!(self, Self::#variant(_))
        }

        #[doc = #as_variant_doc]
        #[inline]
        pub const fn #as_variant(&self) -> ::core::option::Option<&#ty> {
            match self {
                Self::#variant(inner) => ::core::option::Option::Some(inner),
                _ => ::core::option::Option::None,
            }
        }

        #[doc = #as_variant_mut_doc]
        #[inline]
        pub fn #as_variant_mut(&mut self) -> ::core::option::Option<&mut #ty> {
            match self {
                Self::#variant(inner) => ::core::option::Option::Some(inner),
                _ => ::core::option::Option::None,
            }
        }
    }
}

/// `heck` doesn't treat numbers as new words, and discards leading underscores.
fn snakify(s: &str) -> String {
    let leading_n = s.chars().take_while(|c| *c == '_').count();
    let (leading, s) = s.split_at(leading_n);
    let mut output: Vec<char> = leading.chars().chain(s.to_snake_case().chars()).collect();

    let mut num_starts = vec![];
    for (pos, c) in output.iter().enumerate() {
        if pos != 0
            && c.is_ascii_digit()
            && !output[pos - 1].is_ascii_digit()
            && !output[pos - 1].is_ascii_punctuation()
        {
            num_starts.push(pos);
        }
    }
    // need to do in reverse, because after inserting, all chars after the point of
    // insertion are off
    for i in num_starts.into_iter().rev() {
        output.insert(i, '_');
    }
    output.into_iter().collect()
}