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

use crate::class_registry::ClassRegistry;
use crate::core::{Convert, ConvertMut, TryConvert, TryConvertMut};
use crate::exception::{Exception, RubyException};
use crate::extn::core::exception::TypeError;
use crate::sys;
use crate::types::{Ruby, Rust};
use crate::value::Value;
use crate::Artichoke;

mod array;
mod boolean;
mod boxing;
mod bytes;
mod fixnum;
mod float;
mod hash;
mod nilable;
mod string;

pub use boxing::{BoxUnboxVmValue, HeapAllocatedData, Immediate, UnboxedValueGuard};

/// Provide a fallible converter for types that implement an infallible
/// conversion.
impl<T, U> TryConvert<T, U> for Artichoke
where
    Artichoke: Convert<T, U>,
{
    // TODO: this should be the never type.
    // https://github.com/rust-lang/rust/issues/35121
    type Error = Exception;

    /// Blanket implementation that always succeeds by delegating to
    /// [`Convert::convert`].
    #[inline]
    fn try_convert(&self, value: T) -> Result<U, Self::Error> {
        Ok(Convert::convert(self, value))
    }
}

/// Provide a mutable fallible converter for types that implement an infallible
/// conversion.
impl<T, U> TryConvertMut<T, U> for Artichoke
where
    Artichoke: ConvertMut<T, U>,
{
    // TODO: this should be the never type.
    // https://github.com/rust-lang/rust/issues/35121
    type Error = Exception;

    /// Blanket implementation that always succeeds by delegating to
    /// [`Convert::convert`].
    #[inline]
    fn try_convert_mut(&mut self, value: T) -> Result<U, Self::Error> {
        Ok(ConvertMut::convert_mut(self, value))
    }
}

/// Failed to convert from boxed Ruby value to a Rust type.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct UnboxRubyError {
    pub from: Ruby,
    pub into: Rust,
}

impl UnboxRubyError {
    #[must_use]
    #[inline]
    pub fn new(value: &Value, into: Rust) -> Self {
        Self {
            from: value.ruby_type(),
            into,
        }
    }
}

impl fmt::Display for UnboxRubyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to convert from {} to {}", self.from, self.into)
    }
}

impl error::Error for UnboxRubyError {}

impl RubyException for UnboxRubyError {
    fn message(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(b"Failed to convert from Ruby value to Rust type")
    }

    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.to_string());
        let value = interp
            .new_instance::<TypeError>(&[message])
            .ok()
            .flatten()?;
        Some(value.inner())
    }
}

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

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

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

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

/// Failed to convert from Rust type to a boxed Ruby value.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BoxIntoRubyError {
    pub from: Rust,
    pub into: Ruby,
}

impl BoxIntoRubyError {
    #[must_use]
    #[inline]
    pub fn new(from: Rust, into: Ruby) -> Self {
        Self { from, into }
    }
}

impl fmt::Display for BoxIntoRubyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed to convert from {} to {}", self.from, self.into)
    }
}

impl error::Error for BoxIntoRubyError {}

impl RubyException for BoxIntoRubyError {
    fn message(&self) -> Cow<'_, [u8]> {
        Cow::Borrowed(b"Failed to convert from Rust type to Ruby value")
    }

    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.to_string());
        let value = interp
            .new_instance::<TypeError>(&[message])
            .ok()
            .flatten()?;
        Some(value.inner())
    }
}

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

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

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

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