rune/modules/
test.rs

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
//! Testing and benchmarking.

use crate as rune;
use crate::alloc::{try_format, Vec};
use crate::ast;
use crate::compile;
use crate::macros::{quote, FormatArgs, MacroContext, TokenStream};
use crate::parse::Parser;
use crate::runtime::Function;
use crate::{Any, ContextError, Module, T};

/// Testing and benchmarking.
#[rune::module(::std::test)]
pub fn module() -> Result<Module, ContextError> {
    let mut m = Module::from_meta(self::module_meta)?.with_unique("std::test");

    m.macro_meta(assert)?;
    m.macro_meta(assert_eq)?;
    m.macro_meta(assert_ne)?;

    m.ty::<Bencher>()?.docs(docstring! {
        /// A type to perform benchmarks.
        ///
        /// This is the type of the argument to any function which is annotated with `#[bench]`
    })?;

    m.function_meta(Bencher::iter)?;
    Ok(m)
}

/// A helper type to capture benchmarks.
#[derive(Default, Any)]
#[rune(module = crate, item = ::std::test)]
pub struct Bencher {
    fns: Vec<Function>,
}

impl Bencher {
    /// Coerce bencher into its underlying functions.
    pub fn into_functions(self) -> Vec<Function> {
        self.fns
    }

    /// Run a benchmark using the given closure.
    #[rune::function(vm_result)]
    fn iter(&mut self, f: Function) {
        self.fns.try_push(f).vm?;
    }
}

/// Assert that the expression provided as an argument is true, or cause a vm
/// panic.
///
/// The second argument can optionally be used to format a panic message.
///
/// This is useful when writing test cases.
///
/// # Examples
///
/// ```rune
/// let value = 42;
///
/// assert!(value == 42, "Value was not what was expected, instead it was {}", value);
/// ```
#[rune::macro_]
pub(crate) fn assert(
    cx: &mut MacroContext<'_, '_, '_>,
    stream: &TokenStream,
) -> compile::Result<TokenStream> {
    use crate as rune;

    let mut p = Parser::from_token_stream(stream, cx.input_span());
    let expr = p.parse::<ast::Expr>()?;

    let message = if p.parse::<Option<T![,]>>()?.is_some() {
        p.parse_all::<Option<FormatArgs>>()?
    } else {
        None
    };

    let output = if let Some(message) = &message {
        let expanded = message.expand(cx)?;

        quote!(if !(#expr) {
            ::std::panic("assertion failed: " + (#expanded));
        })
    } else {
        let message = try_format!("assertion failed: {}", cx.stringify(&expr)?);
        let message = cx.lit(&message)?;

        quote!(if !(#expr) {
            ::std::panic(#message);
        })
    };

    Ok(output.into_token_stream(cx)?)
}

/// Assert that the two arguments provided are equal, or cause a vm panic.
///
/// The third argument can optionally be used to format a panic message.
///
/// # Examples
///
/// ```rune
/// let value = 42;
///
/// assert_eq!(value, 42, "Value was not 42, instead it was {}", value);
/// ```
#[rune::macro_]
pub(crate) fn assert_eq(
    cx: &mut MacroContext<'_, '_, '_>,
    stream: &TokenStream,
) -> compile::Result<TokenStream> {
    use crate as rune;

    let mut p = Parser::from_token_stream(stream, cx.input_span());
    let left = p.parse::<ast::Expr>()?;
    p.parse::<T![,]>()?;
    let right = p.parse::<ast::Expr>()?;

    let message = if p.parse::<Option<T![,]>>()?.is_some() {
        p.parse_all::<Option<FormatArgs>>()?
    } else {
        None
    };

    let output = if let Some(message) = &message {
        let message = message.expand(cx)?;

        quote! {{
            let left = #left;
            let right = #right;

            if !(left == right) {
                let message = #message;
                message += ::std::fmt::format!("\nleft: {:?}", left);
                message += ::std::fmt::format!("\nright: {:?}", right);
                ::std::panic("assertion failed (left == right): " + message);
            }
        }}
    } else {
        let message = cx.lit("assertion failed (left == right):")?;

        quote! {{
            let left = #left;
            let right = #right;

            if !(left == right) {
                let message = ::std::string::String::from(#message);
                message += ::std::fmt::format!("\nleft: {:?}", left);
                message += ::std::fmt::format!("\nright: {:?}", right);
                ::std::panic(message);
            }
        }}
    };

    Ok(output.into_token_stream(cx)?)
}

/// Assert that the two arguments provided are not equal, or cause a vm panic.
///
/// The third argument can optionally be used to format a panic message.
///
/// # Examples
///
/// ```rune
/// let value = 42;
///
/// assert_ne!(value, 10, "Value was 10");
/// ```
#[rune::macro_]
pub(crate) fn assert_ne(
    cx: &mut MacroContext<'_, '_, '_>,
    stream: &TokenStream,
) -> compile::Result<TokenStream> {
    use crate as rune;

    let mut p = Parser::from_token_stream(stream, cx.input_span());
    let left = p.parse::<ast::Expr>()?;
    p.parse::<T![,]>()?;
    let right = p.parse::<ast::Expr>()?;

    let message = if p.parse::<Option<T![,]>>()?.is_some() {
        p.parse_all::<Option<FormatArgs>>()?
    } else {
        None
    };

    let output = if let Some(message) = &message {
        let message = message.expand(cx)?;

        quote! {{
            let left = #left;
            let right = #right;

            if !(left != right) {
                let message = #message;
                message += ::std::fmt::format!("\nleft: {:?}", left);
                message += ::std::fmt::format!("\nright: {:?}", right);
                ::std::panic("assertion failed (left != right): " + message);
            }
        }}
    } else {
        let message = cx.lit("assertion failed (left != right):")?;

        quote! {{
            let left = #left;
            let right = #right;

            if !(left != right) {
                let message = ::std::string::String::from(#message);
                message += ::std::fmt::format!("\nleft: {:?}", left);
                message += ::std::fmt::format!("\nright: {:?}", right);
                ::std::panic(message);
            }
        }}
    };

    Ok(output.into_token_stream(cx)?)
}