stylus-proc 0.10.5

Procedural macros for stylus-sdk
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright 2022-2026, Offchain Labs, Inc.
// For licensing, see https://github.com/OffchainLabs/stylus-sdk-rs/blob/main/licenses/COPYRIGHT.md

use cfg_if::cfg_if;
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use proc_macro_error::emit_error;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, parse_quote, spanned::Spanned};
use types::{
    FnArgExtension, FnExtension, FnKind, InterfaceExtension, PublicFn, PublicFnArg, PublicImpl,
    PublicTrait,
};

use crate::{
    types::Purity,
    utils::{
        attrs::{check_attr_is_empty, consume_attr, consume_flag},
        get_generics,
    },
};

mod attrs;
mod types;

cfg_if! {
    if #[cfg(feature = "export-abi")] {
        mod export_abi;
        type Extension = export_abi::InterfaceAbi;
    } else {
        type Extension = ();
    }
}

const STYLUS_PUBLIC_TAG_CHECK_FN_NAME: &str =
    "__stylus_trait_and_impl_must_be_tagged_with_public_macro";

/// Implementation of the [`#[public]`][crate::public] macro.
///
/// This implementation performs the following steps:
/// - Parse the input as [`syn::ItemImpl`]
/// - Generate AST items within a [`PublicImpl`]
/// - Expand those AST items into tokens for output
pub fn public(attr: TokenStream, input: TokenStream) -> TokenStream {
    check_attr_is_empty(attr);

    let mut output = proc_macro2::TokenStream::new();

    let item = parse_macro_input!(input as syn::Item);
    match item {
        syn::Item::Impl(mut item_impl) => {
            let public_impl = PublicImpl::<Extension>::from(&mut item_impl);
            add_stylus_public_tag_check_fn_definition(&mut item_impl);
            output.extend(quote! {
                #[cfg(not(feature = "contract-client-gen"))]
                #[allow(dead_code)]
            });
            output.extend(item_impl.into_token_stream());
            public_impl.to_tokens(&mut output);
        }
        syn::Item::Trait(mut item_trait) => {
            let public_trait = PublicTrait::from(&mut item_trait);
            add_stylus_public_tag_check_fn_declaration(&mut item_trait);
            output.extend(quote! {
                #[cfg(not(feature = "contract-client-gen"))]
                #[allow(dead_code)]
            });
            output.extend(item_trait.into_token_stream());
            public_trait.to_tokens(&mut output);
        }
        _ => {
            emit_error!(item.span(), "expected impl or trait");
        }
    }
    output.into()
}

fn add_stylus_public_tag_check_fn_declaration(item_trait: &mut syn::ItemTrait) {
    let fn_name = syn::Ident::new(STYLUS_PUBLIC_TAG_CHECK_FN_NAME, item_trait.span());
    let item: syn::TraitItem = parse_quote! {
        fn #fn_name(&self);
    };
    item_trait.items.push(item);
}

fn add_stylus_public_tag_check_fn_definition(item_impl: &mut syn::ItemImpl) {
    let fn_name = syn::Ident::new(STYLUS_PUBLIC_TAG_CHECK_FN_NAME, item_impl.span());
    let item: syn::ImplItem = parse_quote! {
        fn #fn_name(&self) {
        }
    };
    item_impl.items.push(item);
}

impl From<&mut syn::ItemTrait> for PublicTrait {
    fn from(node: &mut syn::ItemTrait) -> Self {
        let ident = node.ident.clone();

        let funcs = node
            .items
            .iter_mut()
            .filter_map(|item| match item {
                syn::TraitItem::Fn(func) => Some(PublicFn::from(func)),
                syn::TraitItem::Const(_) => {
                    emit_error!(item, "unsupported trait item");
                    None
                }
                _ => {
                    // allow other item types
                    None
                }
            })
            .collect();

        let (generic_params, where_clause) = get_generics(&node.generics);

        // Extract associated types
        let mut associated_types = Vec::new();
        for item in &node.items {
            if let syn::TraitItem::Type(type_item) = item {
                associated_types.push((type_item.ident.clone(), type_item.bounds.clone()));
            }
        }

        Self {
            ident,
            generic_params,
            where_clause,
            funcs,
            associated_types,
        }
    }
}

impl ToTokens for PublicTrait {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        tokens.extend(self.contract_client_gen());
        // Emit collision checks for trait definitions too, so that library crates
        // defining a #[public] trait without a corresponding impl still get checked.
        // When both the trait and its impl exist in the same crate, the compiler will
        // evaluate redundant (but harmless) duplicate const assertions; on a collision,
        // the user may see the error reported twice. Deduplication is not feasible because
        // the trait and impl are processed by separate proc-macro invocations that cannot
        // communicate.
        //
        // Skip checks for generic traits: the generic type parameters would not be in
        // scope in the emitted `const _: ()` items. The concrete `impl Trait<...> for S`
        // block will still emit its own collision checks with the resolved types.
        if self.generic_params.is_empty() {
            for check in types::selector_collision_checks(&self.funcs) {
                check.to_tokens(tokens);
            }
        }
    }
}

impl ToTokens for PublicImpl {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        tokens.extend(self.struct_for_export_abi());
        tokens.extend(self.contract_client_gen());
        tokens.extend(self.print_from_args_fn());
        // Skip collision checks for generic impl blocks: the emitted `const` items
        // would reference type parameters that are not in scope at module level.
        if self.generic_params.is_empty() {
            for check in types::selector_collision_checks(&self.funcs) {
                check.to_tokens(tokens);
            }
        }
        self.impl_router().to_tokens(tokens);
        Extension::codegen(self).to_tokens(tokens);
    }
}

impl From<&mut syn::ItemImpl> for PublicImpl {
    fn from(node: &mut syn::ItemImpl) -> Self {
        // parse traits from #[implements(...)] attribute
        let mut implements = Vec::new();
        if let Some(attr) = consume_attr::<attrs::Implements>(&mut node.attrs, "implements") {
            implements.extend(attr.types);
        }
        let funcs = node
            .items
            .iter_mut()
            .filter_map(|item| match item {
                syn::ImplItem::Fn(func) => Some(PublicFn::from(func)),
                syn::ImplItem::Const(_) => {
                    emit_error!(item, "unsupported impl item");
                    None
                }
                _ => {
                    // allow other item types
                    None
                }
            })
            .collect();

        let self_ty = (*node.self_ty).clone();
        let (generic_params, where_clause) = get_generics(&node.generics);
        let trait_ = match &node.trait_ {
            Some((_, trait_, _)) => Some(trait_.clone()),
            _ => None,
        };

        // Extract associated types from the impl items
        let mut associated_types = Vec::new();
        for item in &node.items {
            if let syn::ImplItem::Type(type_item) = item {
                associated_types.push((type_item.ident.clone(), type_item.ty.clone()));
            }
        }

        #[allow(clippy::let_unit_value)]
        let extension = <Extension as InterfaceExtension>::build(node);
        Self {
            self_ty,
            generic_params,
            where_clause,
            trait_,
            implements,
            funcs,
            associated_types,
            extension,
        }
    }
}

impl<E: FnExtension + Default> From<&mut syn::TraitItemFn> for PublicFn<E> {
    fn from(node: &mut syn::TraitItemFn) -> Self {
        // parse attributes
        let payable = consume_flag(&mut node.attrs, "payable");
        let selector_override =
            consume_attr::<attrs::Selector>(&mut node.attrs, "selector").map(|s| s.value.value());
        let fallback = consume_flag(&mut node.attrs, "fallback");
        let receive = consume_flag(&mut node.attrs, "receive");
        let constructor = consume_flag(&mut node.attrs, "constructor");

        let kind = if fallback {
            // Fallback functions may have two signatures, either
            // with input calldata and output bytes, or no input and output.
            FnKind::Fallback {
                with_args: node.sig.inputs.len() > 1,
            }
        } else if receive {
            FnKind::Receive
        } else if constructor {
            FnKind::Constructor
        } else {
            FnKind::Function
        };

        let num_specials = (fallback as i8) + (constructor as i8) + (receive as i8);
        if num_specials > 1 {
            emit_error!(
                node.span(),
                "function can be only one of fallback, receive or constructor"
            );
        }
        if num_specials > 0 && selector_override.is_some() {
            emit_error!(
                node.span(),
                "fallback, receive, and constructor can't have custom selector"
            );
        }

        // name for generated rust, and solidity abi
        let name = node.sig.ident.clone();
        let (sol_name, name_err) = verify_sol_name(&kind, name.to_string(), selector_override);
        if let Some(err) = name_err {
            emit_error!(node.span(), err);
        }
        let sol_name = syn_solidity::SolIdent::new(&sol_name);

        // determine state mutability
        let (inferred_purity, has_self) = Purity::infer(&node.sig);
        let purity = if payable || matches!(kind, FnKind::Receive) {
            Purity::Payable
        } else {
            inferred_purity
        };

        let mut args = node.sig.inputs.iter();
        if inferred_purity > Purity::Pure {
            // skip self or storage argument
            args.next();
        }
        let inputs = match kind {
            FnKind::Function | FnKind::Constructor => args.map(PublicFnArg::from).collect(),
            _ => Vec::new(),
        };
        let input_span = node.sig.inputs.span();

        let output = match &node.sig.output {
            syn::ReturnType::Default => None,
            syn::ReturnType::Type(_, ty) => Some(*ty.clone()),
        };
        let output_span = output
            .as_ref()
            .map(Spanned::span)
            .unwrap_or(node.sig.output.span());

        let extension: E = E::default();
        Self {
            name,
            sol_name,
            purity,
            inferred_purity,
            kind,

            has_self,
            inputs,
            input_span,
            output: node.sig.output.clone(),
            output_span,

            extension,
        }
    }
}

impl<E: FnExtension> From<&mut syn::ImplItemFn> for PublicFn<E> {
    fn from(node: &mut syn::ImplItemFn) -> Self {
        // parse attributes
        let payable = consume_flag(&mut node.attrs, "payable");
        let selector_override =
            consume_attr::<attrs::Selector>(&mut node.attrs, "selector").map(|s| s.value.value());
        let fallback = consume_flag(&mut node.attrs, "fallback");
        let receive = consume_flag(&mut node.attrs, "receive");
        let constructor = consume_flag(&mut node.attrs, "constructor");

        let kind = if fallback {
            // Fallback functions may have two signatures, either
            // with input calldata and output bytes, or no input and output.
            FnKind::Fallback {
                with_args: node.sig.inputs.len() > 1,
            }
        } else if receive {
            FnKind::Receive
        } else if constructor {
            FnKind::Constructor
        } else {
            FnKind::Function
        };

        let num_specials = (fallback as i8) + (constructor as i8) + (receive as i8);
        if num_specials > 1 {
            emit_error!(
                node.span(),
                "function can be only one of fallback, receive or constructor"
            );
        }
        if num_specials > 0 && selector_override.is_some() {
            emit_error!(
                node.span(),
                "fallback, receive, and constructor can't have custom selector"
            );
        }

        // name for generated rust, and solidity abi
        let name = node.sig.ident.clone();
        let (sol_name, name_err) = verify_sol_name(&kind, name.to_string(), selector_override);
        if let Some(err) = name_err {
            emit_error!(node.span(), err);
        }
        let sol_name = syn_solidity::SolIdent::new(&sol_name);

        // determine state mutability
        let (inferred_purity, has_self) = Purity::infer(&node.sig);
        let purity = if payable || matches!(kind, FnKind::Receive) {
            Purity::Payable
        } else {
            inferred_purity
        };

        let mut args = node.sig.inputs.iter();
        if inferred_purity > Purity::Pure {
            // skip self or storage argument
            args.next();
        }
        let inputs = match kind {
            FnKind::Function | FnKind::Constructor => args.map(PublicFnArg::from).collect(),
            _ => Vec::new(),
        };
        let input_span = node.sig.inputs.span();

        let output = match &node.sig.output {
            syn::ReturnType::Default => None,
            syn::ReturnType::Type(_, ty) => Some(*ty.clone()),
        };
        let output_span = output
            .as_ref()
            .map(Spanned::span)
            .unwrap_or(node.sig.output.span());

        let extension = E::build(node);
        Self {
            name,
            sol_name,
            purity,
            inferred_purity,
            kind,

            has_self,
            inputs,
            input_span,
            output: node.sig.output.clone(),
            output_span,

            extension,
        }
    }
}

impl<E: FnArgExtension> From<&syn::FnArg> for PublicFnArg<E> {
    fn from(node: &syn::FnArg) -> Self {
        match node {
            syn::FnArg::Typed(pat_type) => match &*pat_type.pat {
                syn::Pat::Ident(pat_ident) => Self {
                    name: pat_ident.ident.clone(),
                    ty: *pat_type.ty.clone(),
                    extension: E::build(node),
                },
                other => {
                    emit_error!(other, "destructuring patterns are not supported in #[public] functions; use a named parameter instead");
                    // Dummy value so macro expansion can continue and report additional
                    // errors. The already-emitted error will prevent successful compilation.
                    Self {
                        name: syn::Ident::new("_", other.span()),
                        ty: parse_quote! { () },
                        extension: E::build(node),
                    }
                }
            },
            syn::FnArg::Receiver(recv) => {
                emit_error!(
                    recv,
                    "unexpected `self` parameter in #[public] function argument list"
                );
                // Dummy value (see comment above).
                Self {
                    name: syn::Ident::new("_", recv.span()),
                    ty: parse_quote! { () },
                    extension: E::build(node),
                }
            }
        }
    }
}

/// Returns the Solidity name used for routing and an error string if the name doesn't match the
/// function kind.
fn verify_sol_name(
    kind: &FnKind,
    name: String,
    selector_override: Option<String>,
) -> (String, Option<String>) {
    let name = selector_override.unwrap_or(name.to_case(Case::Camel));
    let name_low = name.to_lowercase();
    let err_kind = if name_low == "receive" && !matches!(kind, FnKind::Receive) {
        Some("receive")
    } else if name_low == "fallback" && !matches!(kind, FnKind::Fallback { .. }) {
        Some("fallback")
    } else if (name_low == "constructor" || name_low == "stylus_constructor")
        && !matches!(kind, FnKind::Constructor)
    {
        Some("constructor")
    } else {
        None
    };
    let err = err_kind.map(|kind_name| {
        format!("{kind_name} function can only be defined using the corresponding attribute")
    });
    (name, err)
}

#[cfg(test)]
mod tests {
    use quote::ToTokens;
    use syn::parse_quote;

    use super::{
        types::{self, FnKind, PublicImpl, PublicTrait},
        verify_sol_name,
    };

    #[test]
    fn test_public_consumes_payable() {
        let mut impl_item = parse_quote! {
            #[derive(Debug)]
            impl Contract {
                #[payable]
                #[other]
                fn func() {}
            }
        };
        let _public = PublicImpl::from(&mut impl_item);
        let syn::ImplItem::Fn(syn::ImplItemFn { attrs, .. }) = &impl_item.items[0] else {
            unreachable!();
        };
        assert_eq!(attrs, &vec![parse_quote! { #[other] }]);
    }

    #[test]
    fn test_public_consumes_constructor() {
        let mut impl_item = parse_quote! {
            #[derive(Debug)]
            impl Contract {
                #[constructor]
                fn func(&mut self, val: U256) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        assert!(matches!(public.funcs[0].kind, FnKind::Constructor));
        let syn::ImplItem::Fn(syn::ImplItemFn { attrs, .. }) = &impl_item.items[0] else {
            unreachable!();
        };
        assert!(attrs.is_empty());
    }

    #[test]
    fn test_verify_sol_name() {
        let cases = vec![
            ("foo", None, "foo", false),
            ("foo_bar", None, "fooBar", false),
            ("foo_baz", Some("fooBar"), "fooBar", false),
            ("foo_baz", Some("fooBAR"), "fooBAR", false),
            ("receive", None, "receive", true),
            ("re_ceive", None, "reCeive", true),
            ("foo", Some("RECEIVE"), "RECEIVE", true),
        ];
        for (name, selector_override, expected_sol_name, has_err) in cases {
            let kind = FnKind::Function;
            let (sol_name, err) =
                verify_sol_name(&kind, name.to_owned(), selector_override.map(String::from));
            assert_eq!(sol_name, expected_sol_name);
            assert_eq!(err.is_some(), has_err);
        }
    }

    #[test]
    fn test_display_label() {
        // When Rust name equals Solidity name, show just the name.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn foo(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        assert_eq!(public.funcs[0].display_label(), "`foo`");

        // When they differ (camelCase conversion), show both.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn foo_bar(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        assert_eq!(
            public.funcs[0].display_label(),
            "`foo_bar` (ABI name `fooBar`)"
        );
    }

    #[test]
    fn test_selector_collision_checks_count() {
        // Zero functions should produce zero checks.
        let checks = types::selector_collision_checks::<()>(&[]);
        assert!(checks.is_empty(), "expected 0 checks with empty input");

        // One function should produce zero checks (no pair to compare).
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn solo(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert!(
            checks.is_empty(),
            "expected 0 checks with a single function"
        );

        // Two functions should produce exactly one pairwise collision check (one pair from two
        // functions).
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn foo_bar(_x: u64) {}
                #[allow(non_snake_case)]
                fn fooBar(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 1, "expected 1 pairwise collision check");

        // Three regular functions should produce 3 pairwise checks.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn alpha(_x: u64) {}
                fn beta(_x: u64) {}
                fn gamma(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 3, "expected 3 pairwise collision checks");

        // Four regular functions should produce 6 pairwise checks (4*3/2).
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn alpha(_x: u64) {}
                fn beta(_x: u64) {}
                fn gamma(_x: u64) {}
                fn delta(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 6, "expected 6 pairwise collision checks");

        // Special functions (fallback, receive, constructor) are excluded.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn alpha(_x: u64) {}
                #[fallback]
                fn my_fallback(&mut self, _args: &[u8]) -> stylus_sdk::ArbResult { Ok(vec![]) }
                #[receive]
                fn my_receive(&mut self) -> Result<(), Vec<u8>> { Ok(()) }
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert!(
            checks.is_empty(),
            "expected 0 checks with only one regular function"
        );

        // Constructor is also excluded.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn alpha(_x: u64) {}
                fn beta(_x: u64) {}
                #[constructor]
                fn my_constructor(&mut self) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(
            checks.len(),
            1,
            "expected 1 check: constructor excluded, 2 regular functions remain"
        );
    }

    #[test]
    fn test_selector_collision_checks_trait() {
        // Collision checks work on PublicTrait the same as PublicImpl.
        let mut trait_item: syn::ItemTrait = parse_quote! {
            trait MyContract {
                fn foo(_x: u64) {}
                fn bar(_x: u64) {}
                fn baz(_x: u64) {}
            }
        };
        let public = PublicTrait::from(&mut trait_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(
            checks.len(),
            3,
            "expected 3 pairwise collision checks for trait"
        );

        // Single-method trait produces no checks.
        let mut trait_item: syn::ItemTrait = parse_quote! {
            trait MyContract {
                fn only_one(_x: u64) {}
            }
        };
        let public = PublicTrait::from(&mut trait_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert!(
            checks.is_empty(),
            "expected 0 checks for single-method trait"
        );
    }

    #[test]
    fn test_selector_collision_checks_content() {
        // Verify that generated checks reference the expected function names and feature gate.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn foo(_x: u64) {}
                fn bar(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 1);
        let tokens = checks[0].to_token_stream().to_string();
        assert!(
            tokens.contains("__SELECTOR_foo"),
            "expected __SELECTOR_foo in generated check"
        );
        assert!(
            tokens.contains("__SELECTOR_bar"),
            "expected __SELECTOR_bar in generated check"
        );
        assert!(
            tokens.contains("contract-client-gen"),
            "expected cfg gate for contract-client-gen"
        );
        assert!(
            tokens.contains("ABI selector collision"),
            "expected collision error message in generated check"
        );
    }

    #[test]
    fn test_selector_collision_checks_content_camel_case() {
        // When Rust names differ from Solidity names, the error message includes ABI names.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn foo_bar(_x: u64) {}
                fn baz_qux(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 1);
        let tokens = checks[0].to_token_stream().to_string();
        // The error message should mention both Rust and ABI names.
        assert!(
            tokens.contains("foo_bar"),
            "expected Rust name foo_bar in error message"
        );
        assert!(
            tokens.contains("fooBar"),
            "expected ABI name fooBar in error message"
        );
        assert!(
            tokens.contains("baz_qux"),
            "expected Rust name baz_qux in error message"
        );
        assert!(
            tokens.contains("bazQux"),
            "expected ABI name bazQux in error message"
        );
    }

    #[test]
    fn test_selector_collision_checks_content_with_selector_override() {
        // When a function uses #[selector(name = "...")], the generated check uses the
        // overridden Solidity name but the Rust name for the const identifier.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                #[selector(name = "customName")]
                fn my_func(_x: u64) {}
                fn other(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 1);
        let tokens = checks[0].to_token_stream().to_string();
        // Const identifier uses Rust name.
        assert!(
            tokens.contains("__SELECTOR_my_func"),
            "expected __SELECTOR_my_func in generated check"
        );
        // Error message includes the override name.
        assert!(
            tokens.contains("customName"),
            "expected overridden ABI name customName in error message"
        );
    }

    #[test]
    fn test_selector_collision_checks_all_pairs_covered() {
        // Verify that each pair in a 3-function set gets its own check with the right names.
        let mut impl_item: syn::ItemImpl = parse_quote! {
            impl Contract {
                fn alpha(_x: u64) {}
                fn beta(_x: u64) {}
                fn gamma(_x: u64) {}
            }
        };
        let public = PublicImpl::from(&mut impl_item);
        let checks = types::selector_collision_checks(&public.funcs);
        assert_eq!(checks.len(), 3);

        let tokens: Vec<String> = checks
            .iter()
            .map(|c| c.to_token_stream().to_string())
            .collect();

        // Check that all three pairs are present: (alpha,beta), (alpha,gamma), (beta,gamma).
        let has_pair = |a: &str, b: &str| {
            tokens.iter().any(|t| {
                t.contains(&format!("__SELECTOR_{a}")) && t.contains(&format!("__SELECTOR_{b}"))
            })
        };
        assert!(has_pair("alpha", "beta"), "missing alpha-beta pair");
        assert!(has_pair("alpha", "gamma"), "missing alpha-gamma pair");
        assert!(has_pair("beta", "gamma"), "missing beta-gamma pair");
    }
}