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

use spinoso_exception::TypeError;

use crate::core::{ClassRegistry, Convert, ConvertMut, TryConvert, TryConvertMut, Value as _};
use crate::error::{Error, RubyException};
use crate::sys;
use crate::types::{Ruby, Rust};
use crate::value::Value;
use crate::Artichoke;

mod array;
mod boolean;
mod boxing;
mod bytes;
mod conv;
mod fixnum;
mod float;
mod float_to_int;
mod hash;
mod implicit;
mod maybe_to_int;
mod nilable;
mod string;

pub use boxing::{BoxUnboxVmValue, HeapAllocated, HeapAllocatedData, Immediate, UnboxedValueGuard};
pub use conv::{
    check_string_type, check_to_a, check_to_ary, check_to_int, check_to_str, convert_type, to_a, to_ary, to_i, to_int,
    to_str, ConvertOnError,
};
pub use float_to_int::float_to_int;
pub use implicit::{
    implicitly_convert_to_int, implicitly_convert_to_nilable_string, implicitly_convert_to_spinoso_string,
    implicitly_convert_to_string,
};
pub use maybe_to_int::{maybe_to_int, MaybeToInt};

/// 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 = Error;

    /// 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 = Error;

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

impl From<UnboxRubyError> for Error {
    fn from(exception: UnboxRubyError) -> Self {
        let err: Box<dyn RubyException> = Box::new(exception);
        Self::from(err)
    }
}

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

impl From<BoxIntoRubyError> for Error {
    fn from(exception: BoxIntoRubyError) -> Self {
        let err: Box<dyn RubyException> = Box::new(exception);
        Self::from(err)
    }
}