test_fuzz_macro/
lib.rs

1#![deny(clippy::unwrap_used)]
2
3use darling::{ast::NestedMeta, FromMeta};
4use itertools::MultiUnzip;
5use proc_macro::TokenStream;
6use proc_macro2::{Literal, Span, TokenStream as TokenStream2};
7use quote::{quote, ToTokens};
8use std::{
9    collections::{BTreeMap, BTreeSet},
10    env::var,
11    str::FromStr,
12    sync::{
13        atomic::{AtomicU32, Ordering},
14        LazyLock,
15    },
16};
17use syn::{
18    parse::Parser, parse2, parse_macro_input, parse_quote, parse_str, punctuated::Punctuated,
19    token, Attribute, Block, Expr, Field, FieldValue, File, FnArg, GenericArgument, GenericParam,
20    Generics, Ident, ImplItem, ImplItemFn, ItemFn, ItemImpl, ItemMod, LifetimeParam, PatType, Path,
21    PathArguments, PathSegment, Receiver, ReturnType, Signature, Stmt, Type, TypeParam, TypePath,
22    TypeReference, TypeSlice, Visibility, WhereClause, WherePredicate,
23};
24
25mod ord_type;
26use ord_type::OrdType;
27
28mod pat_utils;
29
30mod type_utils;
31
32type Attrs = Vec<Attribute>;
33
34type Conversions = BTreeMap<OrdType, (Type, bool)>;
35
36static CARGO_CRATE_NAME: LazyLock<String> =
37    LazyLock::new(|| var("CARGO_CRATE_NAME").expect("Could not get `CARGO_CRATE_NAME`"));
38
39#[derive(FromMeta)]
40struct TestFuzzImplOpts {}
41
42#[proc_macro_attribute]
43pub fn test_fuzz_impl(args: TokenStream, item: TokenStream) -> TokenStream {
44    let attr_args =
45        NestedMeta::parse_meta_list(args.into()).expect("Could not parse attribute args");
46    let _ =
47        TestFuzzImplOpts::from_list(&attr_args).expect("Could not parse `test_fuzz_impl` options");
48
49    let item = parse_macro_input!(item as ItemImpl);
50    let ItemImpl {
51        attrs,
52        defaultness,
53        unsafety,
54        impl_token,
55        generics,
56        trait_,
57        self_ty,
58        brace_token: _,
59        items,
60    } = item;
61
62    let (_, _, where_clause) = generics.split_for_impl();
63
64    // smoelius: Without the next line, you get:
65    //   the trait `quote::ToTokens` is not implemented for `(std::option::Option<syn::token::Bang>,
66    // syn::Path, syn::token::For)`
67    let (trait_path, trait_) = trait_.map_or((None, None), |(bang, path, for_)| {
68        (Some(path.clone()), Some(quote! { #bang #path #for_ }))
69    });
70
71    let (impl_items, modules) = map_impl_items(&generics, trait_path.as_ref(), &self_ty, &items);
72
73    let result = quote! {
74        #(#attrs)* #defaultness #unsafety #impl_token #generics #trait_ #self_ty #where_clause {
75            #(#impl_items)*
76        }
77
78        #(#modules)*
79    };
80    log(&result.to_token_stream());
81    result.into()
82}
83
84fn map_impl_items(
85    generics: &Generics,
86    trait_path: Option<&Path>,
87    self_ty: &Type,
88    items: &[ImplItem],
89) -> (Vec<ImplItem>, Vec<ItemMod>) {
90    let impl_items_modules = items
91        .iter()
92        .map(map_impl_item(generics, trait_path, self_ty));
93
94    let (impl_items, modules): (Vec<_>, Vec<_>) = impl_items_modules.unzip();
95
96    let modules = modules.into_iter().flatten().collect();
97
98    (impl_items, modules)
99}
100
101fn map_impl_item<'a>(
102    generics: &'a Generics,
103    trait_path: Option<&'a Path>,
104    self_ty: &'a Type,
105) -> impl Fn(&ImplItem) -> (ImplItem, Option<ItemMod>) + 'a {
106    let generics = generics.clone();
107    let self_ty = self_ty.clone();
108    move |impl_item| {
109        if let ImplItem::Fn(impl_item_fn) = &impl_item {
110            map_impl_item_fn(&generics, trait_path, &self_ty, impl_item_fn)
111        } else {
112            (impl_item.clone(), None)
113        }
114    }
115}
116
117// smoelius: This function is slightly misnamed. The mapped item could actually be an associated
118// function. I am keeping this name to be consistent with `ImplItem::Method`.
119// smoelius: In `syn` 2.0, `ImplItem::Method` was renamed to `ImplItem::Fn`:
120// https://github.com/dtolnay/syn/releases/tag/2.0.0
121fn map_impl_item_fn(
122    generics: &Generics,
123    trait_path: Option<&Path>,
124    self_ty: &Type,
125    impl_item_fn: &ImplItemFn,
126) -> (ImplItem, Option<ItemMod>) {
127    let ImplItemFn {
128        attrs,
129        vis,
130        defaultness,
131        sig,
132        block,
133    } = &impl_item_fn;
134
135    let mut attrs = attrs.clone();
136
137    attrs.iter().position(is_test_fuzz).map_or_else(
138        || (parse_quote!( #impl_item_fn ), None),
139        |i| {
140            let attr = attrs.remove(i);
141            let opts = opts_from_attr(&attr);
142            let (method, module) = map_method_or_fn(
143                &generics.clone(),
144                trait_path,
145                Some(self_ty),
146                &opts,
147                &attrs,
148                vis,
149                defaultness.as_ref(),
150                sig,
151                block,
152            );
153            (parse_quote!( #method ), Some(module))
154        },
155    )
156}
157
158#[allow(clippy::struct_excessive_bools)]
159#[derive(Clone, Debug, Default, FromMeta)]
160struct TestFuzzOpts {
161    #[darling(default)]
162    bounds: Option<String>,
163    #[darling(multiple)]
164    convert: Vec<String>,
165    #[darling(default)]
166    enable_in_production: bool,
167    #[darling(default)]
168    execute_with: Option<String>,
169    #[darling(default)]
170    generic_args: Option<String>,
171    #[darling(default)]
172    impl_generic_args: Option<String>,
173    #[darling(default)]
174    no_auto_generate: bool,
175    #[darling(default)]
176    only_generic_args: bool,
177    #[darling(default)]
178    rename: Option<Ident>,
179}
180
181#[proc_macro_attribute]
182pub fn test_fuzz(args: TokenStream, item: TokenStream) -> TokenStream {
183    let attr_args =
184        NestedMeta::parse_meta_list(args.into()).expect("Could not parse attribute args");
185    let opts = TestFuzzOpts::from_list(&attr_args).expect("Could not parse `test_fuzz` options");
186
187    let item = parse_macro_input!(item as ItemFn);
188    let ItemFn {
189        attrs,
190        vis,
191        sig,
192        block,
193    } = &item;
194    let (item, module) = map_method_or_fn(
195        &Generics::default(),
196        None,
197        None,
198        &opts,
199        attrs,
200        vis,
201        None,
202        sig,
203        block,
204    );
205    let result = quote! {
206        #item
207        #module
208    };
209    log(&result.to_token_stream());
210    result.into()
211}
212
213#[allow(
214    clippy::ptr_arg,
215    clippy::too_many_arguments,
216    clippy::too_many_lines,
217    clippy::trivially_copy_pass_by_ref
218)]
219#[cfg_attr(dylint_lib = "supplementary", allow(commented_out_code))]
220fn map_method_or_fn(
221    generics: &Generics,
222    trait_path: Option<&Path>,
223    self_ty: Option<&Type>,
224    opts: &TestFuzzOpts,
225    attrs: &Vec<Attribute>,
226    vis: &Visibility,
227    defaultness: Option<&token::Default>,
228    sig: &Signature,
229    block: &Block,
230) -> (TokenStream2, ItemMod) {
231    let mut sig = sig.clone();
232    let stmts = &block.stmts;
233
234    let mut conversions = Conversions::new();
235    opts.convert.iter().for_each(|s| {
236        let tokens = TokenStream::from_str(s).expect("Could not tokenize string");
237        let args = Parser::parse(Punctuated::<Type, token::Comma>::parse_terminated, tokens)
238            .expect("Could not parse `convert` argument");
239        assert!(args.len() == 2, "Could not parse `convert` argument");
240        let mut iter = args.into_iter();
241        let key = iter.next().expect("Should have two `convert` arguments");
242        let value = iter.next().expect("Should have two `convert` arguments");
243        conversions.insert(OrdType(key), (value, false));
244    });
245
246    let opts_impl_generic_args = opts
247        .impl_generic_args
248        .as_deref()
249        .map(parse_generic_arguments);
250
251    let opts_generic_args = opts.generic_args.as_deref().map(parse_generic_arguments);
252
253    // smoelius: Error early.
254    #[cfg(fuzzing)]
255    if !opts.only_generic_args {
256        if is_generic(generics) && opts_impl_generic_args.is_none() {
257            panic!(
258                "`{}` appears in a generic impl but `impl_generic_args` was not specified",
259                sig.ident.to_string(),
260            );
261        }
262
263        if is_generic(&sig.generics) && opts_generic_args.is_none() {
264            panic!(
265                "`{}` is generic but `generic_args` was not specified",
266                sig.ident.to_string(),
267            );
268        }
269    }
270
271    let mut attrs = attrs.clone();
272    let maybe_use_cast_checks = if cfg!(feature = "__cast_checks") {
273        attrs.push(parse_quote! {
274            #[test_fuzz::cast_checks::enable]
275        });
276        quote! {
277            use test_fuzz::cast_checks;
278        }
279    } else {
280        quote! {}
281    };
282
283    let impl_ty_idents = type_idents(generics);
284    let ty_idents = type_idents(&sig.generics);
285    let combined_type_idents = [impl_ty_idents.clone(), ty_idents.clone()].concat();
286
287    let impl_ty_names: Vec<Expr> = impl_ty_idents
288        .iter()
289        .map(|ident| parse_quote! { std::any::type_name::< #ident >() })
290        .collect();
291    let ty_names: Vec<Expr> = ty_idents
292        .iter()
293        .map(|ident| parse_quote! { std::any::type_name::< #ident >() })
294        .collect();
295
296    let combined_generics = combine_generics(generics, &sig.generics);
297    let combined_generics_deserializable = restrict_to_deserialize(&combined_generics);
298
299    let (impl_generics, ty_generics, where_clause) = combined_generics.split_for_impl();
300    let (impl_generics_deserializable, _, _) = combined_generics_deserializable.split_for_impl();
301
302    let args_where_clause: Option<WhereClause> = opts.bounds.as_ref().map(|bounds| {
303        let tokens = TokenStream::from_str(bounds).expect("Could not tokenize string");
304        let where_predicates = Parser::parse(
305            Punctuated::<WherePredicate, token::Comma>::parse_terminated,
306            tokens,
307        )
308        .expect("Could not parse type bounds");
309        parse_quote! {
310            where #where_predicates
311        }
312    });
313
314    // smoelius: "Constraints don’t count as 'using' a type parameter," as explained by Daniel Keep
315    // here: https://users.rust-lang.org/t/error-parameter-t-is-never-used-e0392-but-i-use-it/5673
316    // So, for each type parameter `T`, add a `PhantomData<T>` member to `Args` to ensure that `T`
317    // is used. See also: https://github.com/rust-lang/rust/issues/23246
318    let (phantom_idents, phantom_tys): (Vec<_>, Vec<_>) =
319        type_generic_phantom_idents_and_types(&combined_generics)
320            .into_iter()
321            .unzip();
322    let phantoms: Vec<FieldValue> = phantom_idents
323        .iter()
324        .map(|ident| {
325            parse_quote! { #ident: std::marker::PhantomData }
326        })
327        .collect();
328
329    let impl_generic_args = opts_impl_generic_args.as_ref().map(args_as_turbofish);
330    let generic_args = opts_generic_args.as_ref().map(args_as_turbofish);
331    let combined_generic_args_base = combine_options(
332        opts_impl_generic_args.clone(),
333        opts_generic_args,
334        |mut left, right| {
335            left.extend(right);
336            left
337        },
338    );
339    let combined_generic_args = combined_generic_args_base.as_ref().map(args_as_turbofish);
340    // smoelius: The macro generates code like this:
341    //  struct Ret(<Args as HasRetTy>::RetTy);
342    // If `Args` has lifetime parameters, this code won't compile. Insert `'static` for each
343    // parameter that is not filled.
344    let combined_generic_args_with_dummy_lifetimes = {
345        let mut args = combined_generic_args_base.unwrap_or_default();
346        let n_lifetime_params = combined_generics.lifetimes().count();
347        let n_lifetime_args = args
348            .iter()
349            .filter(|arg| matches!(arg, GenericArgument::Lifetime(..)))
350            .count();
351        #[allow(clippy::cast_possible_wrap)]
352        let n_missing_lifetime_args =
353            usize::try_from(n_lifetime_params as isize - n_lifetime_args as isize)
354                .expect("n_lifetime_params < n_lifetime_args");
355        let dummy_lifetime = GenericArgument::Lifetime(parse_quote! { 'static });
356        args.extend(std::iter::repeat_n(dummy_lifetime, n_missing_lifetime_args));
357        args_as_turbofish(&args)
358    };
359
360    let self_ty_base = self_ty.and_then(type_utils::type_base);
361
362    let (mut arg_attrs, mut arg_idents, mut arg_tys, fmt_args, mut ser_args, de_args) = {
363        let mut candidates = BTreeSet::new();
364        let result = map_args(
365            &mut conversions,
366            &mut candidates,
367            trait_path,
368            self_ty,
369            sig.inputs.iter_mut(),
370        );
371        for (from, (to, used)) in conversions {
372            assert!(
373                used,
374                r#"Conversion "{}" -> "{}" does not apply to the following candidates: {:#?}"#,
375                from,
376                OrdType(to),
377                candidates
378            );
379        }
380        result
381    };
382    arg_attrs.extend(phantom_idents.iter().map(|_| Attrs::new()));
383    arg_idents.extend_from_slice(&phantom_idents);
384    arg_tys.extend_from_slice(&phantom_tys);
385    ser_args.extend_from_slice(&phantoms);
386    assert_eq!(arg_attrs.len(), arg_idents.len());
387    assert_eq!(arg_attrs.len(), arg_tys.len());
388    let attr_pub_arg_ident_tys: Vec<Field> = arg_attrs
389        .iter()
390        .zip(arg_idents.iter())
391        .zip(arg_tys.iter())
392        .map(|((attrs, ident), ty)| {
393            parse_quote! {
394                #(#attrs)*
395                pub #ident: #ty
396            }
397        })
398        .collect();
399    let pub_arg_ident_tys: Vec<Field> = arg_idents
400        .iter()
401        .zip(arg_tys.iter())
402        .map(|(ident, ty)| {
403            parse_quote! {
404                pub #ident: #ty
405            }
406        })
407        .collect();
408    let autos: Vec<Expr> = arg_tys
409        .iter()
410        .map(|ty| {
411            parse_quote! {
412                test_fuzz::runtime::auto!( #ty ).collect::<Vec<_>>()
413            }
414        })
415        .collect();
416    let args_from_autos = args_from_autos(&arg_idents, &autos);
417    let ret_ty = match &sig.output {
418        ReturnType::Type(_, ty) => self_ty.as_ref().map_or(*ty.clone(), |self_ty| {
419            type_utils::expand_self(trait_path, self_ty, ty)
420        }),
421        ReturnType::Default => parse_quote! { () },
422    };
423
424    let target_ident = &sig.ident;
425    let mod_ident = mod_ident(opts, self_ty_base, target_ident);
426
427    // smoelius: This is a hack. When `only_generic_args` is specified, the user should not have
428    // to also specify trait bounds. But `Args` is used to get the module path at runtime via
429    // `type_name`. So when `only_generic_args` is specified, `Args` gets an empty declaration.
430    let empty_generics = Generics {
431        lt_token: None,
432        params: parse_quote! {},
433        gt_token: None,
434        where_clause: None,
435    };
436    let (_, empty_ty_generics, _) = empty_generics.split_for_impl();
437    let (ty_generics_as_turbofish, struct_args) = if opts.only_generic_args {
438        (
439            empty_ty_generics.as_turbofish(),
440            quote! {
441                pub(super) struct Args;
442            },
443        )
444    } else {
445        (
446            ty_generics.as_turbofish(),
447            quote! {
448                pub(super) struct Args #ty_generics #args_where_clause {
449                    #(#pub_arg_ident_tys),*
450                }
451            },
452        )
453    };
454
455    let write_generic_args = quote! {
456        let impl_generic_args = [
457            #(#impl_ty_names),*
458        ];
459        let generic_args = [
460            #(#ty_names),*
461        ];
462        test_fuzz::runtime::write_impl_generic_args::< #mod_ident :: Args #ty_generics_as_turbofish>(&impl_generic_args);
463        test_fuzz::runtime::write_generic_args::< #mod_ident :: Args #ty_generics_as_turbofish>(&generic_args);
464    };
465    let write_args = if opts.only_generic_args {
466        quote! {}
467    } else {
468        quote! {
469            #mod_ident :: write_args::< #(#combined_type_idents),* >(#mod_ident :: Args {
470                #(#ser_args),*
471            });
472        }
473    };
474    let write_generic_args_and_args = quote! {
475        #[cfg(test)]
476        if !test_fuzz::runtime::test_fuzz_enabled() {
477            #write_generic_args
478            #write_args
479        }
480    };
481    let (in_production_write_generic_args_and_args, mod_attr) = if opts.enable_in_production {
482        (
483            quote! {
484                #[cfg(not(test))]
485                if test_fuzz::runtime::write_enabled() {
486                    #write_generic_args
487                    #write_args
488                }
489            },
490            quote! {},
491        )
492    } else {
493        (
494            quote! {},
495            quote! {
496                #[cfg(test)]
497            },
498        )
499    };
500    let auto_generate = if opts.no_auto_generate {
501        quote! {}
502    } else {
503        quote! {
504            #[test]
505            fn auto_generate() {
506                Args #combined_generic_args :: auto_generate();
507            }
508        }
509    };
510    let input_args = {
511        #[cfg(feature = "__persistent")]
512        quote! {}
513        #[cfg(not(feature = "__persistent"))]
514        quote! {
515            let mut args = UsingReader::<_>::read_args #combined_generic_args (std::io::stdin());
516        }
517    };
518    let output_args = {
519        #[cfg(feature = "__persistent")]
520        quote! {}
521        #[cfg(not(feature = "__persistent"))]
522        quote! {
523            args.as_ref().map(|x| {
524                if test_fuzz::runtime::pretty_print_enabled() {
525                    eprint!("{:#?}", x);
526                } else {
527                    eprint!("{:?}", x);
528                };
529            });
530            eprintln!();
531        }
532    };
533    let args_ret_ty: Type = parse_quote! {
534        <Args #combined_generic_args_with_dummy_lifetimes as HasRetTy>::RetTy
535    };
536    let call: Expr = if let Some(self_ty) = self_ty {
537        let opts_impl_generic_args = opts_impl_generic_args.unwrap_or_default();
538        let map = generic_params_map(generics, &opts_impl_generic_args);
539        let self_ty_with_generic_args =
540            type_utils::type_as_turbofish(&type_utils::map_type_generic_params(&map, self_ty));
541        let qualified_self = if let Some(trait_path) = trait_path {
542            let trait_path_with_generic_args = type_utils::path_as_turbofish(
543                &type_utils::map_path_generic_params(&map, trait_path),
544            );
545            quote! {
546                < #self_ty_with_generic_args as #trait_path_with_generic_args >
547            }
548        } else {
549            self_ty_with_generic_args
550        };
551        parse_quote! {
552            #qualified_self :: #target_ident #generic_args (
553                #(#de_args),*
554            )
555        }
556    } else {
557        parse_quote! {
558            super :: #target_ident #generic_args (
559                #(#de_args),*
560            )
561        }
562    };
563    let call_in_environment = if let Some(s) = &opts.execute_with {
564        let execute_with: Expr = parse_str(s).expect("Could not parse `execute_with` argument");
565        parse_quote! {
566            #execute_with (|| #call)
567        }
568    } else {
569        call
570    };
571    let call_in_environment_with_deserialized_arguments = {
572        #[cfg(feature = "__persistent")]
573        quote! {
574            test_fuzz::afl::fuzz!(|data: &[u8]| {
575                let mut args = UsingReader::<_>::read_args #combined_generic_args (data);
576                let ret: Option< #args_ret_ty > = args.map(|mut args|
577                    #call_in_environment
578                );
579            });
580        }
581        #[cfg(not(feature = "__persistent"))]
582        quote! {
583            let ret: Option< #args_ret_ty > = args.map(|mut args|
584                #call_in_environment
585            );
586        }
587    };
588    let output_ret = {
589        #[cfg(feature = "__persistent")]
590        quote! {
591            // smoelius: Suppress unused variable warning.
592            let _: Option< #args_ret_ty > = None;
593        }
594        #[cfg(not(feature = "__persistent"))]
595        quote! {
596            struct Ret( #args_ret_ty );
597            impl std::fmt::Debug for Ret {
598                fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599                    use test_fuzz::runtime::TryDebugFallback;
600                    let mut debug_tuple = fmt.debug_tuple("Ret");
601                    test_fuzz::runtime::TryDebug(&self.0).apply(&mut |value| {
602                        debug_tuple.field(value);
603                    });
604                    debug_tuple.finish()
605                }
606            }
607            let ret = ret.map(Ret);
608            ret.map(|x| {
609                if test_fuzz::runtime::pretty_print_enabled() {
610                    eprint!("{:#?}", x);
611                } else {
612                    eprint!("{:?}", x);
613                };
614            });
615            eprintln!();
616        }
617    };
618    let mod_items = if opts.only_generic_args {
619        quote! {}
620    } else {
621        quote! {
622            // smoelius: It is tempting to want to put all of these functions under `impl Args`.
623            // But `write_args` and `read args` impose different bounds on their arguments. So
624            // I don't think that idea would work.
625            pub(super) fn write_args #impl_generics (Args { #(#arg_idents),* }: Args #ty_generics_as_turbofish) #where_clause {
626                #[derive(serde::Serialize)]
627                struct Args #ty_generics #args_where_clause {
628                    #(#attr_pub_arg_ident_tys),*
629                }
630                let args = Args {
631                    #(#arg_idents),*
632                };
633                test_fuzz::runtime::write_args(&args);
634            }
635
636            struct UsingReader<R>(R);
637
638            impl<R: std::io::Read> UsingReader<R> {
639                pub fn read_args #impl_generics_deserializable (reader: R) -> Option<Args #ty_generics_as_turbofish> #where_clause {
640                    #[derive(serde::Deserialize)]
641                    struct Args #ty_generics #args_where_clause {
642                        #(#attr_pub_arg_ident_tys),*
643                    }
644                    let args = test_fuzz::runtime::read_args::<Args #ty_generics_as_turbofish, _>(reader);
645                    args.map(|Args { #(#arg_idents),* }| #mod_ident :: Args {
646                        #(#arg_idents),*
647                    })
648                }
649            }
650
651            impl #impl_generics std::fmt::Debug for Args #ty_generics #where_clause {
652                fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
653                    use test_fuzz::runtime::TryDebugFallback;
654                    let mut debug_struct = fmt.debug_struct("Args");
655                    #(#fmt_args)*
656                    debug_struct.finish()
657                }
658            }
659
660            // smoelius: Inherent associated types are unstable:
661            // https://github.com/rust-lang/rust/issues/8995
662            trait HasRetTy {
663                type RetTy;
664            }
665
666            impl #impl_generics HasRetTy for Args #ty_generics #where_clause {
667                type RetTy = #ret_ty;
668            }
669        }
670    };
671    // smoelius: The `Args`' implementation and the `auto_generate` test won't compile without
672    // generic args.
673    //   Also, cargo-test-fuzz finds targets by looking for tests that end with `_fuzz__::entry`. So
674    // create such a test regardless. If say `only_generic_args` was specified, then give the
675    // test an empty body.
676    let (generic_args_dependent_mod_items, entry_stmts) = if opts.only_generic_args
677        || (generics.type_params().next().is_some() && impl_generic_args.is_none())
678        || (sig.generics.type_params().next().is_some() && generic_args.is_none())
679    {
680        (quote! {}, quote! {})
681    } else {
682        (
683            quote! {
684                impl #impl_generics Args #ty_generics #where_clause {
685                    // smoelius: `#autos` could refer to type parameters. Expanding it in a method
686                    // definition like this ensures such type parameters resolve.
687                    fn auto_generate() {
688                        if !test_fuzz::runtime::test_fuzz_enabled() {
689                            let autos = ( #(#autos,)* );
690                            for args in #args_from_autos {
691                                write_args(args);
692                            }
693                        }
694                    }
695
696                    fn entry() {
697                        test_fuzz::runtime::warn_if_test_fuzz_not_enabled();
698
699                        // smoelius: Do not set the panic hook when replaying. Leave cargo test's
700                        // panic hook in place.
701                        if test_fuzz::runtime::test_fuzz_enabled() {
702                            if test_fuzz::runtime::display_enabled()
703                                || test_fuzz::runtime::replay_enabled()
704                            {
705                                #input_args
706                                if test_fuzz::runtime::display_enabled() {
707                                    #output_args
708                                }
709                                if test_fuzz::runtime::replay_enabled() {
710                                    #call_in_environment_with_deserialized_arguments
711                                    #output_ret
712                                }
713                            } else {
714                                std::panic::set_hook(std::boxed::Box::new(|_| std::process::abort()));
715                                #input_args
716                                #call_in_environment_with_deserialized_arguments
717                                let _ = std::panic::take_hook();
718                            }
719                        }
720                    }
721                }
722
723                #auto_generate
724            },
725            quote! {
726                Args #combined_generic_args :: entry();
727            },
728        )
729    };
730    (
731        parse_quote! {
732            #(#attrs)* #vis #defaultness #sig {
733                #maybe_use_cast_checks
734
735                #write_generic_args_and_args
736
737                #in_production_write_generic_args_and_args
738
739                #(#stmts)*
740            }
741        },
742        parse_quote! {
743            #mod_attr
744            mod #mod_ident {
745                use super::*;
746
747                #struct_args
748
749                #mod_items
750
751                #generic_args_dependent_mod_items
752
753                #[test]
754                fn entry() {
755                    #entry_stmts
756                }
757            }
758        },
759    )
760}
761
762fn generic_params_map<'a, 'b>(
763    generics: &'a Generics,
764    impl_generic_args: &'b Punctuated<GenericArgument, token::Comma>,
765) -> BTreeMap<&'a Ident, &'b GenericArgument> {
766    let n = generics
767        .params
768        .len()
769        .checked_sub(impl_generic_args.len())
770        .unwrap_or_else(|| {
771            panic!(
772                "{:?} is shorter than {:?}",
773                generics.params, impl_generic_args
774            );
775        });
776    generics
777        .params
778        .iter()
779        .skip(n)
780        .zip(impl_generic_args)
781        .filter_map(|(key, value)| {
782            if let GenericParam::Type(TypeParam { ident, .. }) = key {
783                Some((ident, value))
784            } else {
785                None
786            }
787        })
788        .collect()
789}
790
791#[allow(clippy::type_complexity)]
792fn map_args<'a, I>(
793    conversions: &mut Conversions,
794    candidates: &mut BTreeSet<OrdType>,
795    trait_path: Option<&Path>,
796    self_ty: Option<&Type>,
797    inputs: I,
798) -> (
799    Vec<Attrs>,
800    Vec<Ident>,
801    Vec<Type>,
802    Vec<Stmt>,
803    Vec<FieldValue>,
804    Vec<Expr>,
805)
806where
807    I: Iterator<Item = &'a mut FnArg>,
808{
809    let (attrs, ident, ty, fmt, ser, de): (Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>) = inputs
810        .map(map_arg(conversions, candidates, trait_path, self_ty))
811        .multiunzip();
812
813    (attrs, ident, ty, fmt, ser, de)
814}
815
816fn map_arg<'a>(
817    conversions: &'a mut Conversions,
818    candidates: &'a mut BTreeSet<OrdType>,
819    trait_path: Option<&'a Path>,
820    self_ty: Option<&'a Type>,
821) -> impl FnMut(&mut FnArg) -> (Attrs, Ident, Type, Stmt, FieldValue, Expr) + 'a {
822    move |arg| {
823        let (fn_arg_attrs, ident, expr, ty, fmt) = match arg {
824            FnArg::Receiver(Receiver {
825                attrs,
826                reference,
827                mutability,
828                ..
829            }) => {
830                let ident = anonymous_ident();
831                let expr = parse_quote! { self };
832                let reference = reference
833                    .as_ref()
834                    .map(|(and, lifetime)| quote! { #and #lifetime });
835                let ty = parse_quote! { #reference #mutability #self_ty };
836                let fmt = parse_quote! {
837                    test_fuzz::runtime::TryDebug(&self.#ident).apply(&mut |value| {
838                        debug_struct.field("self", value);
839                    });
840                };
841                (attrs, ident, expr, ty, fmt)
842            }
843            FnArg::Typed(PatType { attrs, pat, ty, .. }) => {
844                let ident = match *pat_utils::pat_idents(pat).as_slice() {
845                    [] => anonymous_ident(),
846                    [ident] => ident.clone(),
847                    _ => panic!("Unexpected pattern: {}", pat.to_token_stream()),
848                };
849                let expr = parse_quote! { #ident };
850                let ty = self_ty.as_ref().map_or(*ty.clone(), |self_ty| {
851                    type_utils::expand_self(trait_path, self_ty, ty)
852                });
853                let name = ident.to_string();
854                let fmt = parse_quote! {
855                    test_fuzz::runtime::TryDebug(&self.#ident).apply(&mut |value| {
856                        debug_struct.field(#name, value);
857                    });
858                };
859                (attrs, ident, expr, ty, fmt)
860            }
861        };
862        let attrs = std::mem::take(fn_arg_attrs);
863        let (ty, ser, de) = if attrs.is_empty() {
864            map_typed_arg(conversions, candidates, &ident, &expr, &ty)
865        } else {
866            (
867                parse_quote! { #ty },
868                parse_quote! { #ident: <#ty as std::clone::Clone>::clone( & #expr ) },
869                parse_quote! { args.#ident },
870            )
871        };
872        (attrs, ident, ty, fmt, ser, de)
873    }
874}
875
876fn map_typed_arg(
877    conversions: &mut Conversions,
878    candidates: &mut BTreeSet<OrdType>,
879    ident: &Ident,
880    expr: &Expr,
881    ty: &Type,
882) -> (Type, FieldValue, Expr) {
883    candidates.insert(OrdType(ty.clone()));
884    if let Some((arg_ty, used)) = conversions.get_mut(&OrdType(ty.clone())) {
885        *used = true;
886        return (
887            parse_quote! { #arg_ty },
888            parse_quote! { #ident: <#arg_ty as test_fuzz::FromRef::<#ty>>::from_ref( & #expr ) },
889            parse_quote! { <_ as test_fuzz::Into::<_>>::into(args.#ident) },
890        );
891    }
892    match &ty {
893        Type::Path(path) => map_path_arg(conversions, candidates, ident, expr, path),
894        Type::Reference(ty) => map_ref_arg(conversions, candidates, ident, expr, ty),
895        _ => (
896            parse_quote! { #ty },
897            parse_quote! { #ident: #expr.clone() },
898            parse_quote! { args.#ident },
899        ),
900    }
901}
902
903fn map_path_arg(
904    _conversions: &mut Conversions,
905    _candidates: &mut BTreeSet<OrdType>,
906    ident: &Ident,
907    expr: &Expr,
908    path: &TypePath,
909) -> (Type, FieldValue, Expr) {
910    (
911        parse_quote! { #path },
912        parse_quote! { #ident: #expr.clone() },
913        parse_quote! { args.#ident },
914    )
915}
916
917fn map_ref_arg(
918    conversions: &mut Conversions,
919    candidates: &mut BTreeSet<OrdType>,
920    ident: &Ident,
921    expr: &Expr,
922    ty: &TypeReference,
923) -> (Type, FieldValue, Expr) {
924    let (maybe_mut, mutability) = if ty.mutability.is_some() {
925        ("mut_", quote! { mut })
926    } else {
927        ("", quote! {})
928    };
929    let ty = &*ty.elem;
930    match ty {
931        Type::Path(path) => {
932            if type_utils::match_type_path(path, &["str"]) == Some(PathArguments::None) {
933                let as_maybe_mut_str = Ident::new(&format!("as_{maybe_mut}str"), Span::call_site());
934                (
935                    parse_quote! { String },
936                    parse_quote! { #ident: #expr.to_owned() },
937                    parse_quote! { args.#ident.#as_maybe_mut_str() },
938                )
939            } else {
940                let expr = parse_quote! { (*#expr) };
941                let (ty, ser, de) = map_path_arg(conversions, candidates, ident, &expr, path);
942                (ty, ser, parse_quote! { & #mutability #de })
943            }
944        }
945        Type::Slice(TypeSlice { elem, .. }) => {
946            let as_maybe_mut_slice = Ident::new(&format!("as_{maybe_mut}slice"), Span::call_site());
947            (
948                parse_quote! { Vec<#elem> },
949                parse_quote! { #ident: #expr.to_vec() },
950                parse_quote! { args.#ident.#as_maybe_mut_slice() },
951            )
952        }
953        _ => {
954            let expr = parse_quote! { (*#expr) };
955            let (ty, ser, de) = map_typed_arg(conversions, candidates, ident, &expr, ty);
956            (ty, ser, parse_quote! { & #mutability #de })
957        }
958    }
959}
960
961fn opts_from_attr(attr: &Attribute) -> TestFuzzOpts {
962    attr.parse_args::<TokenStream2>()
963        .map_or(TestFuzzOpts::default(), |tokens| {
964            let attr_args =
965                NestedMeta::parse_meta_list(tokens).expect("Could not parse attribute args");
966            TestFuzzOpts::from_list(&attr_args).expect("Could not parse `test_fuzz` options")
967        })
968}
969
970fn is_test_fuzz(attr: &Attribute) -> bool {
971    attr.path()
972        .segments
973        .iter()
974        .all(|PathSegment { ident, .. }| ident == "test_fuzz")
975}
976
977fn parse_generic_arguments(s: &str) -> Punctuated<GenericArgument, token::Comma> {
978    let tokens = TokenStream::from_str(s).expect("Could not tokenize string");
979    Parser::parse(
980        Punctuated::<GenericArgument, token::Comma>::parse_terminated,
981        tokens,
982    )
983    .expect("Could not parse generic arguments")
984}
985
986#[cfg(fuzzing)]
987fn is_generic(generics: &Generics) -> bool {
988    generics
989        .params
990        .iter()
991        .filter(|param| !matches!(param, GenericParam::Lifetime(_)))
992        .next()
993        .is_some()
994}
995
996fn type_idents(generics: &Generics) -> Vec<Ident> {
997    generics
998        .params
999        .iter()
1000        .filter_map(|param| {
1001            if let GenericParam::Type(ty_param) = param {
1002                Some(ty_param.ident.clone())
1003            } else {
1004                None
1005            }
1006        })
1007        .collect()
1008}
1009
1010fn combine_generics(left: &Generics, right: &Generics) -> Generics {
1011    let mut generics = left.clone();
1012    generics.params.extend(right.params.clone());
1013    generics.where_clause = combine_options(
1014        generics.where_clause,
1015        right.where_clause.clone(),
1016        |mut left, right| {
1017            left.predicates.extend(right.predicates);
1018            left
1019        },
1020    );
1021    generics
1022}
1023
1024// smoelius: Is there a better name for this operation? The closest thing I've found is the `<|>`
1025// operation in Haskell's `Alternative` class (thanks, @incertia):
1026// https://en.wikibooks.org/wiki/Haskell/Alternative_and_MonadPlus
1027// ... (<|>) is a binary function which combines two computations.
1028//                                      ^^^^^^^^
1029
1030fn combine_options<T, F>(x: Option<T>, y: Option<T>, f: F) -> Option<T>
1031where
1032    F: FnOnce(T, T) -> T,
1033{
1034    match (x, y) {
1035        (Some(x), Some(y)) => Some(f(x, y)),
1036        (x, None) => x,
1037        (None, y) => y,
1038    }
1039}
1040
1041fn restrict_to_deserialize(generics: &Generics) -> Generics {
1042    let mut generics = generics.clone();
1043    generics.params.iter_mut().for_each(|param| {
1044        if let GenericParam::Type(ty_param) = param {
1045            ty_param
1046                .bounds
1047                .push(parse_quote! { serde::de::DeserializeOwned });
1048        }
1049    });
1050    generics
1051}
1052
1053fn type_generic_phantom_idents_and_types(generics: &Generics) -> Vec<(Ident, Type)> {
1054    generics
1055        .params
1056        .iter()
1057        .filter_map(|param| match param {
1058            GenericParam::Type(TypeParam { ident, .. }) => Some((
1059                anonymous_ident(),
1060                parse_quote! { std::marker::PhantomData< #ident > },
1061            )),
1062            GenericParam::Lifetime(LifetimeParam { lifetime, .. }) => Some((
1063                anonymous_ident(),
1064                parse_quote! { std::marker::PhantomData< & #lifetime () > },
1065            )),
1066            GenericParam::Const(_) => None,
1067        })
1068        .collect()
1069}
1070
1071fn args_as_turbofish(args: &Punctuated<GenericArgument, token::Comma>) -> TokenStream2 {
1072    quote! {
1073        ::<#args>
1074    }
1075}
1076
1077// smoelius: The current strategy for combining auto-generated values is a kind of "round robin."
1078// The strategy ensures that each auto-generated value gets into at least one `Args` value.
1079// smoelius: One problem with the current approach is that it increments `Args` fields in lockstep.
1080// So for any two fields with the same number of values, if value x appears alongside value y, then
1081// whenever x appears, it appears alongside y (and vice versa).
1082fn args_from_autos(idents: &[Ident], autos: &[Expr]) -> Expr {
1083    assert_eq!(idents.len(), autos.len());
1084    let lens: Vec<Expr> = (0..autos.len())
1085        .map(|i| {
1086            let i = Literal::usize_unsuffixed(i);
1087            parse_quote! {
1088                autos.#i.len()
1089            }
1090        })
1091        .collect();
1092    let args: Vec<FieldValue> = (0..autos.len())
1093        .map(|i| {
1094            let ident = &idents[i];
1095            let i = Literal::usize_unsuffixed(i);
1096            parse_quote! {
1097                #ident: autos.#i[(i + #i) % lens[#i]].clone()
1098            }
1099        })
1100        .collect();
1101    parse_quote! {{
1102        let lens = [ #(#lens),* ];
1103        let max = if lens.iter().copied().min().unwrap_or(1) > 0 {
1104            lens.iter().copied().max().unwrap_or(1)
1105        } else {
1106            0
1107        };
1108        (0..max).map(move |i|
1109            Args { #(#args),* }
1110        )
1111    }}
1112}
1113
1114#[allow(unused_variables)]
1115fn mod_ident(opts: &TestFuzzOpts, self_ty_base: Option<&Ident>, target_ident: &Ident) -> Ident {
1116    let mut s = String::new();
1117    if let Some(name) = &opts.rename {
1118        s.push_str(&name.to_string());
1119    } else {
1120        if let Some(ident) = self_ty_base {
1121            s.push_str(&<str as heck::ToSnakeCase>::to_snake_case(
1122                &ident.to_string(),
1123            ));
1124            s.push('_');
1125        }
1126        s.push_str(&target_ident.to_string());
1127    }
1128    s.push_str("_fuzz__");
1129    Ident::new(&s, Span::call_site())
1130}
1131
1132static INDEX: AtomicU32 = AtomicU32::new(0);
1133
1134fn anonymous_ident() -> Ident {
1135    let index = INDEX.fetch_add(1, Ordering::SeqCst);
1136    Ident::new(&format!("_{index}"), Span::call_site())
1137}
1138
1139fn log(tokens: &TokenStream2) {
1140    if log_enabled() {
1141        let syntax_tree: File = parse2(tokens.clone()).expect("Could not parse tokens");
1142        let formatted = prettyplease::unparse(&syntax_tree);
1143        print!("{formatted}");
1144    }
1145}
1146
1147fn log_enabled() -> bool {
1148    option_env!("TEST_FUZZ_LOG").map_or(false, |value| value == "1" || value == *CARGO_CRATE_NAME)
1149}