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
//! Interacting with the Ruby VM directly.

use std::{
    error::Error,
    fmt,
    num::NonZeroI32,
    os::raw::c_int,
};
use crate::{
    prelude::*,
    ruby,
};

mod eval;
mod instr_seq;

pub use self::{
    eval::*,
    instr_seq::*,
};

/// Initializes the Ruby VM, returning an error code if it failed.
#[inline]
pub fn init() -> Result<(), InitError> {
    if let Some(code) = NonZeroI32::new(unsafe { ruby::ruby_setup() as i32 }) {
        Err(InitError(code))
    } else {
        Ok(())
    }
}

/// Destructs the Ruby VM, runs its finalization processes, and frees all
/// resources used by it.
///
/// Returns an exit code on error appropriate for passing into
/// [`std::process::exit`](https://doc.rust-lang.org/std/process/fn.exit.html).
///
/// # Safety
///
/// The caller must ensure that no VM resources are being used by other threads
/// or will continue to be used after this function finishes.
///
/// After this function is called, it will no longer be possible to call
/// [`init`](fn.init.html).
#[inline]
pub unsafe fn destroy() -> Result<(), DestroyError> {
    if let Some(code) = NonZeroI32::new(ruby::ruby_cleanup(0) as i32) {
        Err(DestroyError(code))
    } else {
        Ok(())
    }
}

/// Returns Ruby's level of paranoia. This is equivalent to reading `$SAFE`.
#[inline]
pub fn safe_level() -> c_int {
    unsafe { ruby::rb_safe_level() }
}

/// Sets Ruby's level of paranoia. The default value is 0.
///
/// # Safety
///
/// An exception will be raised if `level` is either negative or not supported.
#[inline]
pub unsafe fn set_safe_level(level: c_int) {
    ruby::rb_set_safe_level(level);
}

/// Initializes the load path for `require`-ing gems.
///
/// # Examples
///
/// ```
/// rosy::vm::init().unwrap();
/// rosy::vm::init_load_path();
/// ```
#[inline]
pub fn init_load_path() {
    unsafe { ruby::ruby_init_loadpath() };
}

/// Loads `file` with the current `safe_level`, without checking for exceptions.
///
/// This returns `true` if successful or `false` if already loaded.
///
/// See [`require_with`](fn.require_with.html) for more info.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
///
/// An exception may be raised by the code in `file` or by `file` being invalid.
#[inline]
pub unsafe fn require(file: impl Into<String>) -> bool {
    require_with(file, safe_level())
}

/// Loads `file` with `safe_level`, without checking for exceptions.
///
/// This returns `true` if successful or `false` if already loaded.
///
// Taken from docs on `rb_f_require` in Ruby's source code
/// If the filename does not resolve to an absolute path, it will be searched
/// for in the directories listed in`$LOAD_PATH` (`$:`).
///
/// If the filename has the extension `.rb`, it is loaded as a source file; if
/// the extension is `.so`, `.o`, or `.dll`, or the default shared library
/// extension on the current platform, Ruby loads the shared library as a Ruby
/// extension. Otherwise, Ruby tries adding `.rb`, `.so`, and so on to the name
/// until found. If the file named cannot be found, a `LoadError` will be
/// returned.
///
/// For Ruby extensions the filename given may use any shared library extension.
/// For example, on Linux the socket extension is `socket.so` and `require
/// 'socket.dll'` will load the socket extension.
///
/// The absolute path of the loaded file is added to `$LOADED_FEATURES` (`$"`).
/// A file will not be loaded again if its path already appears in `$"`.  For
/// example, `require 'a'; require './a'` will not load `a.rb` again.
///
/// ```ruby
/// require "my-library.rb"
/// require "db-driver"
/// ```
///
/// Any constants or globals within the loaded source file will be available in
/// the calling program's global namespace. However, local variables will not be
/// propagated to the loading environment.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
///
/// An exception may be raised by the code in `file` or by `file` being invalid.
#[inline]
pub unsafe fn require_with(
    file: impl Into<String>,
    safe_level: c_int,
) -> bool {
    ruby::rb_require_safe(file.into().raw(), safe_level) != 0
}

/// Loads `file` with the current `safe_level`.
///
/// This returns `true` if successful or `false` if already loaded.
///
/// See [`require_with`](fn.require_with.html) for more info.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
#[inline]
pub unsafe fn require_protected(file: impl Into<String>) -> Result<bool> {
    require_with_protected(file, safe_level())
}

/// Loads `file` with `safe_level`.
///
/// This returns `true` if successful or `false` if already loaded.
///
/// See [`require_with`](fn.require_with.html) for more info.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
#[inline]
pub unsafe fn require_with_protected(
    file: impl Into<String>,
    safe_level: c_int,
) -> Result<bool> {
    // monomorphization
    unsafe fn require(file: String, safe: c_int) -> Result<ruby::VALUE> {
        crate::protected_no_panic(|| ruby::rb_require_safe(file.raw(), safe))
    }
    // Convert to `bool` here for inlining
    Ok(require(file.into(), safe_level)? != 0)
}

/// Loads and executes the Ruby program `file`, without checking for exceptions.
///
/// If the filename does not resolve to an absolute path, the file is searched
/// for in the library directories listed in `$:`.
///
/// If `wrap` is `true`, the loaded script will be executed under an anonymous
/// module, protecting the calling program's global namespace. In no
/// circumstance will any local variables in the loaded file be propagated to
/// the loading environment.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
///
/// An exception may be raised by the code in `file` or by `file` being invalid.
#[inline]
pub unsafe fn load(file: impl Into<String>, wrap: bool) {
    ruby::rb_load(file.into().raw(), wrap as c_int)
}

/// Loads and executes the Ruby program `file`.
///
/// See [`load`](fn.load.html) for more info.
///
/// # Safety
///
/// Code executed from `file` may void the type safety of objects accessible
/// from Rust. For example, if one calls `push` on `Array<A>` with an object of
/// type `B`, then the inserted object will be treated as being of type `A`.
#[inline]
pub unsafe fn load_protected(file: impl Into<String>, wrap: bool) -> Result {
    let mut err = 0;
    ruby::rb_load_protect(file.into().raw(), wrap as c_int, &mut err);
    match err {
        0 => Ok(()),
        _ => Err(AnyException::_take_current()),
    }
}

/// Returns the current backtrace.
#[inline]
pub fn backtrace() -> Array<String> {
    unsafe { Array::from_raw(ruby::rb_make_backtrace()) }
}

/// An error indicating that [`init`](fn.init.html) failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct InitError(NonZeroI32);

impl InitError {
    /// Returns the error code given by the VM.
    #[inline]
    pub fn code(self) -> i32 {
        self.0.get()
    }
}

impl fmt::Display for InitError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} (error code {})", self.description(), self.code())
    }
}

impl Error for InitError {
    #[inline]
    fn description(&self) -> &str {
        "Failed to initialize Ruby"
    }
}

/// An error indicating that [`destroy`](fn.destroy.html) failed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DestroyError(NonZeroI32);

impl DestroyError {
    /// Returns the error code given by the VM.
    #[inline]
    pub fn code(self) -> i32 {
        self.0.get()
    }

    /// Exits the process with the returned error code.
    #[inline]
    pub fn exit_process(self) -> ! {
        std::process::exit(self.code())
    }
}

impl fmt::Display for DestroyError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} (error code {})", self.description(), self.code())
    }
}

impl Error for DestroyError {
    #[inline]
    fn description(&self) -> &str {
        "Failed to destroy Ruby"
    }
}