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
use std::borrow::Cow;
use std::convert::TryFrom;
use std::error;
use std::fmt;

use crate::class_registry::ClassRegistry;
use crate::core::{ConvertMut, Value as _};
use crate::error::{Error, RubyException};
use crate::exception_handler;
use crate::extn::core::exception::{Fatal, TypeError};
use crate::sys::{self, protect};
use crate::types::{self, Ruby};
use crate::value::Value;
use crate::Artichoke;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoBlockGiven(Ruby);

impl fmt::Display for NoBlockGiven {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("no block given")
    }
}

impl error::Error for NoBlockGiven {}

impl RubyException for NoBlockGiven {
    fn message(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(b"no block given")
    }

    fn name(&self) -> Cow<'_, str> {
        "TypeError".into()
    }

    fn vm_backtrace(&self, interp: &mut Artichoke) -> Option<Vec<Vec<u8>>> {
        let _ = interp;
        None
    }

    fn as_mrb_value(&self, interp: &mut Artichoke) -> Option<sys::mrb_value> {
        let message = interp.convert_mut(self.message());
        let value = interp.new_instance::<TypeError>(&[message]).ok().flatten()?;
        Some(value.inner())
    }
}

impl From<NoBlockGiven> for Error {
    fn from(exception: NoBlockGiven) -> Self {
        Self::from(Box::<dyn RubyException>::from(exception))
    }
}

impl From<Box<NoBlockGiven>> for Error {
    fn from(exception: Box<NoBlockGiven>) -> Self {
        Self::from(Box::<dyn RubyException>::from(exception))
    }
}

impl From<NoBlockGiven> for Box<dyn RubyException> {
    fn from(exception: NoBlockGiven) -> Box<dyn RubyException> {
        Box::new(exception)
    }
}

impl From<Box<NoBlockGiven>> for Box<dyn RubyException> {
    fn from(exception: Box<NoBlockGiven>) -> Box<dyn RubyException> {
        exception
    }
}

impl From<Value> for NoBlockGiven {
    fn from(value: Value) -> Self {
        Self(value.ruby_type())
    }
}

impl From<sys::mrb_value> for NoBlockGiven {
    fn from(value: sys::mrb_value) -> Self {
        Self(types::ruby_from_mrb_value(value))
    }
}

impl From<Ruby> for NoBlockGiven {
    fn from(ruby_type: Ruby) -> Self {
        Self(ruby_type)
    }
}

impl Default for NoBlockGiven {
    fn default() -> Self {
        Self::new()
    }
}

impl NoBlockGiven {
    /// Construce a new, empty no block given error.
    ///
    /// The inner Ruby type is `nil`.
    #[must_use]
    pub const fn new() -> Self {
        Self(Ruby::Nil)
    }

    /// Return the [`Ruby`] type of the object given instead of a block.
    #[must_use]
    pub const fn ruby_type(self) -> Ruby {
        self.0
    }
}

#[derive(Default, Debug, Clone, Copy)]
pub struct Block(sys::mrb_value);

impl From<sys::mrb_value> for Option<Block> {
    fn from(value: sys::mrb_value) -> Self {
        if let Ruby::Nil = types::ruby_from_mrb_value(value) {
            None
        } else {
            Some(Block(value))
        }
    }
}

impl TryFrom<sys::mrb_value> for Block {
    type Error = NoBlockGiven;

    fn try_from(value: sys::mrb_value) -> Result<Self, Self::Error> {
        if let Some(block) = value.into() {
            Ok(block)
        } else {
            Err(NoBlockGiven::from(value))
        }
    }
}

impl Block {
    /// Construct a `Block` from a Ruby value.
    #[must_use]
    pub fn new(block: sys::mrb_value) -> Option<Self> {
        if let Ruby::Nil = types::ruby_from_mrb_value(block) {
            None
        } else {
            Some(Self(block))
        }
    }

    /// Construct a `Block` from a Ruby value.
    ///
    /// # Safety
    ///
    /// The block must not be `nil`.
    #[must_use]
    pub const unsafe fn new_unchecked(block: sys::mrb_value) -> Self {
        Self(block)
    }

    #[inline]
    #[must_use]
    pub const fn inner(&self) -> sys::mrb_value {
        self.0
    }

    pub fn yield_arg(&self, interp: &mut Artichoke, arg: &Value) -> Result<Value, Error> {
        let result = unsafe { interp.with_ffi_boundary(|mrb| protect::block_yield(mrb, self.inner(), arg.inner()))? };
        match result {
            Ok(value) => {
                let value = interp.protect(Value::from(value));
                if value.is_unreachable() {
                    // Unreachable values are internal to the mruby interpreter
                    // and interacting with them via the C API is unspecified
                    // and may result in a segfault.
                    //
                    // See: https://github.com/mruby/mruby/issues/4460
                    Err(Fatal::from("Unreachable Ruby value").into())
                } else {
                    Ok(value)
                }
            }
            Err(exception) => {
                let exception = interp.protect(Value::from(exception));
                Err(exception_handler::last_error(interp, exception)?)
            }
        }
    }
}