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 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
117fn 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_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 #[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 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 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 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 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 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 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 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 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 if test_fuzz::runtime::test_fuzz_enabled() {
700 if test_fuzz::runtime::display_enabled()
701 || test_fuzz::runtime::replay_enabled()
702 {
703 #input_args
704 if test_fuzz::runtime::display_enabled() {
705 #output_args
706 }
707 if test_fuzz::runtime::replay_enabled() {
708 #call_in_environment_with_deserialized_arguments
709 #output_ret
710 }
711 } else {
712 std::panic::set_hook(std::boxed::Box::new(|_| std::process::abort()));
713 #input_args
714 #call_in_environment_with_deserialized_arguments
715 let _ = std::panic::take_hook();
716 }
717 }
718 }
719 }
720
721 #auto_generate
722 },
723 quote! {
724 Args #combined_generic_args :: entry();
725 },
726 )
727 };
728 (
729 parse_quote! {
730 #(#attrs)* #vis #defaultness #sig {
731 #maybe_use_cast_checks
732
733 #write_generic_args_and_args
734
735 #in_production_write_generic_args_and_args
736
737 #(#stmts)*
738 }
739 },
740 parse_quote! {
741 #mod_attr
742 mod #mod_ident {
743 use super::*;
744
745 #struct_args
746
747 #mod_items
748
749 #generic_args_dependent_mod_items
750
751 #[test]
752 fn entry() {
753 #entry_stmts
754 }
755 }
756 },
757 )
758}
759
760fn generic_params_map<'a, 'b>(
761 generics: &'a Generics,
762 impl_generic_args: &'b Punctuated<GenericArgument, token::Comma>,
763) -> BTreeMap<&'a Ident, &'b GenericArgument> {
764 let n = generics
765 .params
766 .len()
767 .checked_sub(impl_generic_args.len())
768 .unwrap_or_else(|| {
769 panic!(
770 "{:?} is shorter than {:?}",
771 generics.params, impl_generic_args
772 );
773 });
774 generics
775 .params
776 .iter()
777 .skip(n)
778 .zip(impl_generic_args)
779 .filter_map(|(key, value)| {
780 if let GenericParam::Type(TypeParam { ident, .. }) = key {
781 Some((ident, value))
782 } else {
783 None
784 }
785 })
786 .collect()
787}
788
789#[allow(clippy::type_complexity)]
790fn map_args<'a, I>(
791 conversions: &mut Conversions,
792 candidates: &mut BTreeSet<OrdType>,
793 trait_path: Option<&Path>,
794 self_ty: Option<&Type>,
795 inputs: I,
796) -> (
797 Vec<Attrs>,
798 Vec<Ident>,
799 Vec<Type>,
800 Vec<Stmt>,
801 Vec<FieldValue>,
802 Vec<Expr>,
803)
804where
805 I: Iterator<Item = &'a mut FnArg>,
806{
807 let (attrs, ident, ty, fmt, ser, de): (Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>, Vec<_>) = inputs
808 .map(map_arg(conversions, candidates, trait_path, self_ty))
809 .multiunzip();
810
811 (attrs, ident, ty, fmt, ser, de)
812}
813
814fn map_arg<'a>(
815 conversions: &'a mut Conversions,
816 candidates: &'a mut BTreeSet<OrdType>,
817 trait_path: Option<&'a Path>,
818 self_ty: Option<&'a Type>,
819) -> impl FnMut(&mut FnArg) -> (Attrs, Ident, Type, Stmt, FieldValue, Expr) + 'a {
820 move |arg| {
821 let (fn_arg_attrs, ident, expr, ty, fmt) = match arg {
822 FnArg::Receiver(Receiver {
823 attrs,
824 reference,
825 mutability,
826 ..
827 }) => {
828 let ident = anonymous_ident();
829 let expr = parse_quote! { self };
830 let reference = reference
831 .as_ref()
832 .map(|(and, lifetime)| quote! { #and #lifetime });
833 let ty = parse_quote! { #reference #mutability #self_ty };
834 let fmt = parse_quote! {
835 test_fuzz::runtime::TryDebug(&self.#ident).apply(&mut |value| {
836 debug_struct.field("self", value);
837 });
838 };
839 (attrs, ident, expr, ty, fmt)
840 }
841 FnArg::Typed(PatType { attrs, pat, ty, .. }) => {
842 let ident = match *pat_utils::pat_idents(pat).as_slice() {
843 [] => anonymous_ident(),
844 [ident] => ident.clone(),
845 _ => panic!("Unexpected pattern: {}", pat.to_token_stream()),
846 };
847 let expr = parse_quote! { #ident };
848 let ty = self_ty.as_ref().map_or(*ty.clone(), |self_ty| {
849 type_utils::expand_self(trait_path, self_ty, ty)
850 });
851 let name = ident.to_string();
852 let fmt = parse_quote! {
853 test_fuzz::runtime::TryDebug(&self.#ident).apply(&mut |value| {
854 debug_struct.field(#name, value);
855 });
856 };
857 (attrs, ident, expr, ty, fmt)
858 }
859 };
860 let attrs = std::mem::take(fn_arg_attrs);
861 let (ty, ser, de) = if attrs.is_empty() {
862 map_typed_arg(conversions, candidates, &ident, &expr, &ty)
863 } else {
864 (
865 parse_quote! { #ty },
866 parse_quote! { #ident: <#ty as std::clone::Clone>::clone( & #expr ) },
867 parse_quote! { args.#ident },
868 )
869 };
870 (attrs, ident, ty, fmt, ser, de)
871 }
872}
873
874fn map_typed_arg(
875 conversions: &mut Conversions,
876 candidates: &mut BTreeSet<OrdType>,
877 ident: &Ident,
878 expr: &Expr,
879 ty: &Type,
880) -> (Type, FieldValue, Expr) {
881 candidates.insert(OrdType(ty.clone()));
882 if let Some((arg_ty, used)) = conversions.get_mut(&OrdType(ty.clone())) {
883 *used = true;
884 return (
885 parse_quote! { #arg_ty },
886 parse_quote! { #ident: <#arg_ty as test_fuzz::FromRef::<#ty>>::from_ref( & #expr ) },
887 parse_quote! { <_ as test_fuzz::Into::<_>>::into(args.#ident) },
888 );
889 }
890 match &ty {
891 Type::Path(path) => map_path_arg(conversions, candidates, ident, expr, path),
892 Type::Reference(ty) => map_ref_arg(conversions, candidates, ident, expr, ty),
893 _ => (
894 parse_quote! { #ty },
895 parse_quote! { #ident: #expr.clone() },
896 parse_quote! { args.#ident },
897 ),
898 }
899}
900
901fn map_path_arg(
902 _conversions: &mut Conversions,
903 _candidates: &mut BTreeSet<OrdType>,
904 ident: &Ident,
905 expr: &Expr,
906 path: &TypePath,
907) -> (Type, FieldValue, Expr) {
908 (
909 parse_quote! { #path },
910 parse_quote! { #ident: #expr.clone() },
911 parse_quote! { args.#ident },
912 )
913}
914
915fn map_ref_arg(
916 conversions: &mut Conversions,
917 candidates: &mut BTreeSet<OrdType>,
918 ident: &Ident,
919 expr: &Expr,
920 ty: &TypeReference,
921) -> (Type, FieldValue, Expr) {
922 let (maybe_mut, mutability) = if ty.mutability.is_some() {
923 ("mut_", quote! { mut })
924 } else {
925 ("", quote! {})
926 };
927 let ty = &*ty.elem;
928 match ty {
929 Type::Path(path) => {
930 if type_utils::match_type_path(path, &["str"]) == Some(PathArguments::None) {
931 let as_maybe_mut_str = Ident::new(&format!("as_{maybe_mut}str"), Span::call_site());
932 (
933 parse_quote! { String },
934 parse_quote! { #ident: #expr.to_owned() },
935 parse_quote! { args.#ident.#as_maybe_mut_str() },
936 )
937 } else {
938 let expr = parse_quote! { (*#expr) };
939 let (ty, ser, de) = map_path_arg(conversions, candidates, ident, &expr, path);
940 (ty, ser, parse_quote! { & #mutability #de })
941 }
942 }
943 Type::Slice(TypeSlice { elem, .. }) => {
944 let as_maybe_mut_slice = Ident::new(&format!("as_{maybe_mut}slice"), Span::call_site());
945 (
946 parse_quote! { Vec<#elem> },
947 parse_quote! { #ident: #expr.to_vec() },
948 parse_quote! { args.#ident.#as_maybe_mut_slice() },
949 )
950 }
951 _ => {
952 let expr = parse_quote! { (*#expr) };
953 let (ty, ser, de) = map_typed_arg(conversions, candidates, ident, &expr, ty);
954 (ty, ser, parse_quote! { & #mutability #de })
955 }
956 }
957}
958
959fn opts_from_attr(attr: &Attribute) -> TestFuzzOpts {
960 attr.parse_args::<TokenStream2>()
961 .map_or(TestFuzzOpts::default(), |tokens| {
962 let attr_args =
963 NestedMeta::parse_meta_list(tokens).expect("Could not parse attribute args");
964 TestFuzzOpts::from_list(&attr_args).expect("Could not parse `test_fuzz` options")
965 })
966}
967
968fn is_test_fuzz(attr: &Attribute) -> bool {
969 attr.path()
970 .segments
971 .iter()
972 .all(|PathSegment { ident, .. }| ident == "test_fuzz")
973}
974
975fn parse_generic_arguments(s: &str) -> Punctuated<GenericArgument, token::Comma> {
976 let tokens = TokenStream::from_str(s).expect("Could not tokenize string");
977 Parser::parse(
978 Punctuated::<GenericArgument, token::Comma>::parse_terminated,
979 tokens,
980 )
981 .expect("Could not parse generic arguments")
982}
983
984#[cfg(fuzzing)]
985fn is_generic(generics: &Generics) -> bool {
986 generics
987 .params
988 .iter()
989 .filter(|param| !matches!(param, GenericParam::Lifetime(_)))
990 .next()
991 .is_some()
992}
993
994fn type_idents(generics: &Generics) -> Vec<Ident> {
995 generics
996 .params
997 .iter()
998 .filter_map(|param| {
999 if let GenericParam::Type(ty_param) = param {
1000 Some(ty_param.ident.clone())
1001 } else {
1002 None
1003 }
1004 })
1005 .collect()
1006}
1007
1008fn combine_generics(left: &Generics, right: &Generics) -> Generics {
1009 let mut generics = left.clone();
1010 generics.params.extend(right.params.clone());
1011 generics.where_clause = combine_options(
1012 generics.where_clause,
1013 right.where_clause.clone(),
1014 |mut left, right| {
1015 left.predicates.extend(right.predicates);
1016 left
1017 },
1018 );
1019 generics
1020}
1021
1022fn combine_options<T, F>(x: Option<T>, y: Option<T>, f: F) -> Option<T>
1029where
1030 F: FnOnce(T, T) -> T,
1031{
1032 match (x, y) {
1033 (Some(x), Some(y)) => Some(f(x, y)),
1034 (x, None) => x,
1035 (None, y) => y,
1036 }
1037}
1038
1039fn restrict_to_deserialize(generics: &Generics) -> Generics {
1040 let mut generics = generics.clone();
1041 generics.params.iter_mut().for_each(|param| {
1042 if let GenericParam::Type(ty_param) = param {
1043 ty_param
1044 .bounds
1045 .push(parse_quote! { serde::de::DeserializeOwned });
1046 }
1047 });
1048 generics
1049}
1050
1051fn type_generic_phantom_idents_and_types(generics: &Generics) -> Vec<(Ident, Type)> {
1052 generics
1053 .params
1054 .iter()
1055 .filter_map(|param| match param {
1056 GenericParam::Type(TypeParam { ident, .. }) => Some((
1057 anonymous_ident(),
1058 parse_quote! { std::marker::PhantomData< #ident > },
1059 )),
1060 GenericParam::Lifetime(LifetimeParam { lifetime, .. }) => Some((
1061 anonymous_ident(),
1062 parse_quote! { std::marker::PhantomData< & #lifetime () > },
1063 )),
1064 GenericParam::Const(_) => None,
1065 })
1066 .collect()
1067}
1068
1069fn args_as_turbofish(args: &Punctuated<GenericArgument, token::Comma>) -> TokenStream2 {
1070 quote! {
1071 ::<#args>
1072 }
1073}
1074
1075fn args_from_autos(idents: &[Ident], autos: &[Expr]) -> Expr {
1081 assert_eq!(idents.len(), autos.len());
1082 let lens: Vec<Expr> = (0..autos.len())
1083 .map(|i| {
1084 let i = Literal::usize_unsuffixed(i);
1085 parse_quote! {
1086 autos.#i.len()
1087 }
1088 })
1089 .collect();
1090 let args: Vec<FieldValue> = (0..autos.len())
1091 .map(|i| {
1092 let ident = &idents[i];
1093 let i = Literal::usize_unsuffixed(i);
1094 parse_quote! {
1095 #ident: autos.#i[(i + #i) % lens[#i]].clone()
1096 }
1097 })
1098 .collect();
1099 parse_quote! {{
1100 let lens = [ #(#lens),* ];
1101 let max = if lens.iter().copied().min().unwrap_or(1) > 0 {
1102 lens.iter().copied().max().unwrap_or(1)
1103 } else {
1104 0
1105 };
1106 (0..max).map(move |i|
1107 Args { #(#args),* }
1108 )
1109 }}
1110}
1111
1112#[allow(unused_variables)]
1113fn mod_ident(opts: &TestFuzzOpts, self_ty_base: Option<&Ident>, target_ident: &Ident) -> Ident {
1114 let mut s = String::new();
1115 if let Some(name) = &opts.rename {
1116 s.push_str(&name.to_string());
1117 } else {
1118 if let Some(ident) = self_ty_base {
1119 s.push_str(&<str as heck::ToSnakeCase>::to_snake_case(
1120 &ident.to_string(),
1121 ));
1122 s.push('_');
1123 }
1124 s.push_str(&target_ident.to_string());
1125 }
1126 s.push_str("_fuzz__");
1127 Ident::new(&s, Span::call_site())
1128}
1129
1130static INDEX: AtomicU32 = AtomicU32::new(0);
1131
1132fn anonymous_ident() -> Ident {
1133 let index = INDEX.fetch_add(1, Ordering::SeqCst);
1134 Ident::new(&format!("_{index}"), Span::call_site())
1135}
1136
1137fn log(tokens: &TokenStream2) {
1138 if log_enabled() {
1139 let syntax_tree: File = parse2(tokens.clone()).expect("Could not parse tokens");
1140 let formatted = prettyplease::unparse(&syntax_tree);
1141 print!("{formatted}");
1142 }
1143}
1144
1145fn log_enabled() -> bool {
1146 option_env!("TEST_FUZZ_LOG").map_or(false, |value| value == "1" || value == *CARGO_CRATE_NAME)
1147}