proptest/
macros.rs

1//-
2// Copyright 2017, 2018 Jason Lingle
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! Macros for internal use to reduce boilerplate.
11
12// Pervasive internal sugar
13macro_rules! mapfn {
14    ($({#[$allmeta:meta]})* $(#[$meta:meta])* [$($vis:tt)*]
15     fn $name:ident[$($gen:tt)*]($parm:ident: $input:ty) -> $output:ty {
16         $($body:tt)*
17     }) => {
18        $(#[$allmeta])* $(#[$meta])*
19        #[derive(Clone, Copy, Debug)]
20        $($vis)* struct $name;
21        $(#[$allmeta])*
22        impl $($gen)* $crate::strategy::statics::MapFn<$input> for $name {
23            type Output = $output;
24            fn apply(&self, $parm: $input) -> $output {
25                $($body)*
26            }
27        }
28    }
29}
30
31macro_rules! delegate_vt_0 {
32    () => {
33        fn current(&self) -> Self::Value {
34            self.0.current()
35        }
36
37        fn simplify(&mut self) -> bool {
38            self.0.simplify()
39        }
40
41        fn complicate(&mut self) -> bool {
42            self.0.complicate()
43        }
44    };
45}
46
47macro_rules! opaque_strategy_wrapper {
48    ($({#[$allmeta:meta]})*
49     $(#[$smeta:meta])*
50     pub struct $stratname:ident
51     [$($sgen:tt)*][$($swhere:tt)*]
52     ($innerstrat:ty) -> $stratvtty:ty;
53
54     $(#[$vmeta:meta])* pub struct $vtname:ident
55     [$($vgen:tt)*][$($vwhere:tt)*]
56     ($innervt:ty) -> $actualty:ty;
57    ) => {
58        $(#[$allmeta])*
59        $(#[$smeta])*
60        #[must_use = "strategies do nothing unless used"]
61        pub struct $stratname $($sgen)* ($innerstrat)
62            $($swhere)*;
63
64        $(#[$allmeta])*
65        $(#[$vmeta])* pub struct $vtname $($vgen)* ($innervt) $($vwhere)*;
66
67        $(#[$allmeta])*
68        impl $($sgen)* Strategy for $stratname $($sgen)* $($swhere)* {
69            type Tree = $stratvtty;
70            type Value = $actualty;
71            fn new_tree(&self, runner: &mut TestRunner) -> NewTree<Self> {
72                self.0.new_tree(runner).map($vtname)
73            }
74        }
75
76        $(#[$allmeta])*
77        impl $($vgen)* ValueTree for $vtname $($vgen)* $($vwhere)* {
78            type Value = $actualty;
79
80            delegate_vt_0!();
81        }
82    }
83}
84
85// Example: unwrap_or!(result, err => handle_err(err));
86macro_rules! unwrap_or {
87    ($unwrap: expr, $err: ident => $on_err: expr) => {
88        match $unwrap {
89            Ok(ok) => ok,
90            Err($err) => $on_err,
91        }
92    };
93}