logo
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
/// Macros for use within the Artichoke VM.
///
/// This module contains macros for working with interpreters and Ruby values.
/// This module should be included first in `lib.rs` with the `#[macro_use]`
/// attribute, which makes all macros available for all modules in this crate.
///
/// Macros that relate to manipulating the underlying mruby VM are exported.

/// Log a fatal error to stderr and suppress all errors.
///
/// This macro accepts a format string and arguments similar to [`write!`].
macro_rules! emit_fatal_warning {
    ($($arg:tt)+) => {{
        use ::std::io::Write;

        // Something bad, terrible, and unexpected has happened.
        //
        // Suppress errors from logging to stderr because this function may being
        // called when there are foreign C frames in the stack and panics are
        // either undefined behavior or will result in an abort.
        //
        // Ensure the returned error is dropped so we don't leave anything on
        // the stack in the event of a foreign unwind.
        let maybe_err = ::std::write!(::std::io::stderr(), "fatal[artichoke-backend]: ");
        drop(maybe_err);
        let maybe_err = ::std::writeln!(::std::io::stderr(), $($arg)+);
        drop(maybe_err);
    }};
}

/// Extract an [`Artichoke`] instance from the userdata on a [`sys::mrb_state`].
///
/// If there is an error when extracting the Rust wrapper around the
/// interpreter, return `nil` or a user-provided default.
///
/// This macro calls `unsafe` functions.
///
/// [`Artichoke`]: crate::Artichoke
/// [`sys::mrb_state`]: crate::sys::mrb_state
#[macro_export]
macro_rules! unwrap_interpreter {
    ($mrb:expr, to => $to:ident, or_else = ()) => {
        let mut interp = if let Ok(interp) = $crate::ffi::from_user_data($mrb) {
            interp
        } else {
            return;
        };
        let mut arena = if let Ok(arena) =
            $crate::gc::MrbGarbageCollection::create_arena_savepoint(&mut interp)
        {
            arena
        } else {
            return;
        };
        #[allow(unused_mut)]
        let mut $to = $crate::Guard::new(arena.interp());
    };
    ($mrb:expr, to => $to:ident, or_else = $default:expr) => {
        let mut interp = if let Ok(interp) = $crate::ffi::from_user_data($mrb) {
            interp
        } else {
            return $default;
        };
        let mut arena = if let Ok(arena) =
            $crate::gc::MrbGarbageCollection::create_arena_savepoint(&mut interp)
        {
            arena
        } else {
            return $default;
        };
        #[allow(unused_mut)]
        let mut $to = $crate::Guard::new(arena.interp());
    };
    ($mrb:expr, to => $to:ident) => {
        unwrap_interpreter!($mrb, to => $to, or_else = $crate::sys::mrb_sys_nil_value())
    };
}

#[doc(hidden)]
pub mod argspec {
    use std::ffi::CStr;

    pub const NONE: &CStr = qed::const_cstr_from_str!("\0");
    pub const REQ1: &CStr = qed::const_cstr_from_str!("o\0");
    pub const OPT1: &CStr = qed::const_cstr_from_str!("|o\0");
    pub const REQ1_OPT1: &CStr = qed::const_cstr_from_str!("o|o\0");
    pub const REQ1_OPT2: &CStr = qed::const_cstr_from_str!("o|oo\0");
    pub const REQ1_REQBLOCK: &CStr = qed::const_cstr_from_str!("o&\0");
    pub const REQ1_REQBLOCK_OPT1: &CStr = qed::const_cstr_from_str!("o&|o?\0");
    pub const REQ2: &CStr = qed::const_cstr_from_str!("oo\0");
    pub const OPT2: &CStr = qed::const_cstr_from_str!("|oo\0");
    pub const OPT2_OPTBLOCK: &CStr = qed::const_cstr_from_str!("&|o?o?\0");
    pub const REQ2_OPT1: &CStr = qed::const_cstr_from_str!("oo|o\0");
    pub const REST: &CStr = qed::const_cstr_from_str!("*\0");
}

/// Extract [`sys::mrb_value`]s from a [`sys::mrb_state`] to adapt a C
/// entry point to a Rust implementation of a Ruby function.
///
/// This macro exists because the mruby VM [does not validate argspecs] attached
/// to native functions.
///
/// This macro calls `unsafe` functions.
///
/// [`sys::mrb_value`]: crate::sys::mrb_value
/// [`sys::mrb_state`]: crate::sys::mrb_state
/// [does not validate argspecs]: https://github.com/mruby/mruby/issues/4688
#[macro_export]
macro_rules! mrb_get_args {
    ($mrb:expr, none) => {{
        $crate::sys::mrb_get_args($mrb, $crate::macros::argspec::NONE.as_ptr());
    }};
    ($mrb:expr, required = 1) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args($mrb, $crate::macros::argspec::REQ1.as_ptr(), req1.as_mut_ptr());
        match argc {
            1 => req1.assume_init(),
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, optional = 1) => {{
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args($mrb, $crate::macros::argspec::OPT1.as_ptr(), opt1.as_mut_ptr());
        match argc {
            1 => {
                let opt1 = opt1.assume_init();
                Some(opt1)
            }
            0 => None,
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, required = 1, optional = 1) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ1_OPT1.as_ptr(),
            req1.as_mut_ptr(),
            opt1.as_mut_ptr(),
        );
        match argc {
            2 => {
                let req1 = req1.assume_init();
                let opt1 = opt1.assume_init();
                (req1, Some(opt1))
            }
            1 => {
                let req1 = req1.assume_init();
                (req1, None)
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, required = 1, optional = 2) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ1_OPT2.as_ptr(),
            req1.as_mut_ptr(),
            opt1.as_mut_ptr(),
            opt2.as_mut_ptr(),
        );
        match argc {
            3 => {
                let req1 = req1.assume_init();
                let opt1 = opt1.assume_init();
                let opt2 = opt2.assume_init();
                (req1, Some(opt1), Some(opt2))
            }
            2 => {
                let req1 = req1.assume_init();
                let opt1 = opt1.assume_init();
                (req1, Some(opt1), None)
            }
            1 => {
                let req1 = req1.assume_init();
                (req1, None, None)
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, required = 1, &block) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ1_REQBLOCK.as_ptr(),
            req1.as_mut_ptr(),
            block.as_mut_ptr(),
        );
        match argc {
            2 | 1 => {
                let req1 = req1.assume_init();
                let block = block.assume_init();
                (req1, $crate::block::Block::new(block))
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, required = 1, optional = 1, &block) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut has_opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
        let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ1_REQBLOCK_OPT1.as_ptr(),
            req1.as_mut_ptr(),
            block.as_mut_ptr(),
            opt1.as_mut_ptr(),
            has_opt1.as_mut_ptr(),
        );
        let has_opt1 = has_opt1.assume_init() != 0;
        match argc {
            3 => {
                let req1 = req1.assume_init();
                let opt1 = opt1.assume_init();
                let block = block.assume_init();
                (req1, Some(opt1), $crate::block::Block::new(block))
            }
            2 => {
                let req1 = req1.assume_init();
                let opt1 = if has_opt1 { Some(opt1.assume_init()) } else { None };
                let block = block.assume_init();
                (req1, opt1, $crate::block::Block::new(block))
            }
            1 => {
                let req1 = req1.assume_init();
                let block = block.assume_init();
                (req1, None, $crate::block::Block::new(block))
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, required = 2) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut req2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ2.as_ptr(),
            req1.as_mut_ptr(),
            req2.as_mut_ptr(),
        );
        match argc {
            2 => {
                let req1 = req1.assume_init();
                let req2 = req2.assume_init();
                (req1, req2)
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, optional = 2) => {{
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::OPT2.as_ptr(),
            opt1.as_mut_ptr(),
            opt2.as_mut_ptr(),
        );
        match argc {
            2 => {
                let opt1 = opt1.assume_init();
                let opt2 = opt2.assume_init();
                (Some(opt1), Some(opt2))
            }
            1 => {
                let opt1 = opt1.assume_init();
                (Some(opt1), None)
            }
            0 => (None, None),
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, optional = 2, &block) => {{
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut has_opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
        let mut opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut has_opt2 = std::mem::MaybeUninit::<$crate::sys::mrb_bool>::uninit();
        let mut block = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::OPT2_OPTBLOCK.as_ptr(),
            block.as_mut_ptr(),
            opt1.as_mut_ptr(),
            has_opt1.as_mut_ptr(),
            opt2.as_mut_ptr(),
            has_opt2.as_mut_ptr(),
        );
        let has_opt1 = has_opt1.assume_init() != 0;
        let has_opt2 = has_opt2.assume_init() != 0;
        let opt1 = if has_opt1 { Some(opt1.assume_init()) } else { None };
        let opt2 = if has_opt2 { Some(opt2.assume_init()) } else { None };
        let block = block.assume_init();
        (opt1, opt2, $crate::block::Block::new(block))
    }};
    ($mrb:expr, required = 2, optional = 1) => {{
        let mut req1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut req2 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let mut opt1 = std::mem::MaybeUninit::<$crate::sys::mrb_value>::uninit();
        let argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REQ2_OPT1.as_ptr(),
            req1.as_mut_ptr(),
            req2.as_mut_ptr(),
            opt1.as_mut_ptr(),
        );
        match argc {
            3 => {
                let req1 = req1.assume_init();
                let req2 = req2.assume_init();
                let opt1 = opt1.assume_init();
                (req1, req2, Some(opt1))
            }
            2 => {
                let req1 = req1.assume_init();
                let req2 = req2.assume_init();
                (req1, req2, None)
            }
            _ => unreachable!("mrb_get_args should have raised"),
        }
    }};
    ($mrb:expr, *args) => {{
        let mut args = std::mem::MaybeUninit::<*const $crate::sys::mrb_value>::uninit();
        let mut count = std::mem::MaybeUninit::<usize>::uninit();
        let _argc = $crate::sys::mrb_get_args(
            $mrb,
            $crate::macros::argspec::REST.as_ptr(),
            args.as_mut_ptr(),
            count.as_mut_ptr(),
        );
        std::slice::from_raw_parts(args.assume_init(), count.assume_init())
    }};
}