extendr_api/wrapper/
wrapper_macros.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
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
339
340
341
342
343
344
345
346
347
348
use super::*;
use crate as extendr_api;

pub(crate) fn make_symbol(name: &str) -> SEXP {
    let name = CString::new(name).unwrap();
    unsafe { libR_sys::Rf_install(name.as_ptr()) }
}

pub(crate) fn make_vector<T>(sexptype: SEXPTYPE, values: T) -> Robj
where
    T: IntoIterator,
    T::IntoIter: ExactSizeIterator,
    T::Item: Into<Robj>,
{
    single_threaded(|| unsafe {
        let values = values.into_iter();
        let mut res = Robj::alloc_vector(sexptype, values.len());
        let sexp = res.get_mut();
        for (i, val) in values.enumerate() {
            SET_VECTOR_ELT(sexp, i as R_xlen_t, val.into().get());
        }
        res
    })
}

macro_rules! make_conversions {
    ($typename: ident, $errname: ident, $isfunc: ident, $errstr: expr) => {
        impl From<$typename> for Robj {
            /// Make an robj from a wrapper.
            fn from(val: $typename) -> Self {
                val.robj
            }
        }

        // We can convert a reference to any wrapper to a Robj by cloning the robj pointer
        impl From<&$typename> for Robj {
            /// Make an robj from a wrapper.
            fn from(val: &$typename) -> Self {
                val.robj.to_owned()
            }
        }

        impl TryFrom<&Robj> for $typename {
            type Error = crate::Error;

            /// Make a wrapper from a robj if it matches.
            fn try_from(robj: &Robj) -> Result<Self> {
                if robj.$isfunc() {
                    Ok($typename { robj: robj.clone() })
                } else {
                    Err(Error::$errname(robj.clone()))
                }
            }
        }

        impl TryFrom<Robj> for $typename {
            type Error = crate::Error;

            /// Make a wrapper from a robj if it matches.
            fn try_from(robj: Robj) -> Result<Self> {
                <$typename>::try_from(&robj)
            }
        }

        make_getsexp!($typename, impl);
    };
}

macro_rules! make_getsexp {
    ($typename: ty, $($impl : tt)*) => {
        $($impl)* GetSexp for $typename {
            unsafe fn get(&self) -> SEXP {
                self.robj.get()
            }

            unsafe fn get_mut(&mut self) -> SEXP {
                self.robj.get_mut()
            }

            fn as_robj(&self) -> &Robj {
                &self.robj
            }

            fn as_robj_mut(&mut self) -> &mut Robj {
                &mut self.robj
            }
        }

        // These traits all derive from GetSexp

        /// len() and is_empty()
        $($impl)* Length for $typename {}

        /// rtype() and rany()
        $($impl)* Types for $typename {}

        /// as_*()
        $($impl)* Conversions for $typename {}

        /// find_var() etc.
        $($impl)* Rinternals for $typename {}

        /// as_typed_slice_raw() etc.
        $($impl)* Slices for $typename {}

        /// dollar() etc.
        $($impl)* Operators for $typename {}
    };
}

make_conversions!(Pairlist, ExpectedPairlist, is_pairlist, "Not a pairlist");

make_conversions!(
    Function,
    ExpectedFunction,
    is_function,
    "Not a function or primitive."
);

make_conversions!(Raw, ExpectedRaw, is_raw, "Not a raw object");

make_conversions!(Rstr, ExpectedRstr, is_char, "Not a character object");

make_conversions!(
    Environment,
    ExpectedEnvironment,
    is_environment,
    "Not an Environment"
);

make_conversions!(List, ExpectedList, is_list, "Not a List");

make_conversions!(
    Expressions,
    ExpectedExpression,
    is_expressions,
    "Not an Expression"
);

make_conversions!(
    Language,
    ExpectedLanguage,
    is_language,
    "Not a Language object"
);

make_conversions!(Symbol, ExpectedSymbol, is_symbol, "Not a Symbol object");

make_conversions!(
    Primitive,
    ExpectedPrimitive,
    is_primitive,
    "Not a Primitive object"
);

make_conversions!(Promise, ExpectedPromise, is_promise, "Not a Promise object");

make_conversions!(Altrep, ExpectedAltrep, is_altrep, "Not an Altrep type");

make_conversions!(S4, ExpectedS4, is_s4, "Not a S4 type");

make_conversions!(Integers, ExpectedInteger, is_integer, "Not an integer type");
make_conversions!(Logicals, ExpectedLogical, is_logical, "Not a logical type");
make_conversions!(Doubles, ExpectedReal, is_real, "Not a floating point type");
make_conversions!(
    Complexes,
    ExpectedComplex,
    is_complex,
    "Not a complex number or vector"
);
// make_conversions!(Function, ExpectedFunction, is_function, "Not a function");

make_conversions!(Strings, ExpectedString, is_string, "Not a string vector");

make_getsexp!(Dataframe<T>, impl<T>);

// impl Deref for Integers {
//     type Target = [Rint];

//     fn deref(&self) -> &Self::Target {
//         unsafe { self.as_typed_slice_raw() }
//     }
// }

pub trait Conversions: GetSexp {
    /// Convert a symbol object to a Symbol wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let fred = sym!(fred);
    ///     assert_eq!(fred.as_symbol(), Some(Symbol::from_string("fred")));
    /// }
    /// ```
    fn as_symbol(&self) -> Option<Symbol> {
        Symbol::try_from(self.as_robj()).ok()
    }

    /// Convert a `CHARSXP` object to a `Rstr` wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let fred = Rstr::from_string("fred");
    ///     assert_eq!(fred.as_char(), Some(Rstr::from_string("fred")));
    /// }
    /// ```
    fn as_char(&self) -> Option<Rstr> {
        Rstr::try_from(self.as_robj()).ok()
    }

    /// Convert a raw object to a Rstr wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let bytes = r!(Raw::from_bytes(&[1, 2, 3]));
    ///     assert_eq!(bytes.len(), 3);
    ///     assert_eq!(bytes.as_raw(), Some(Raw::from_bytes(&[1, 2, 3])));
    /// }
    /// ```
    fn as_raw(&self) -> Option<Raw> {
        Raw::try_from(self.as_robj()).ok()
    }

    /// Convert a language object to a Language wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let call_to_xyz = r!(Language::from_values(&[r!(Symbol::from_string("xyz")), r!(1), r!(2)]));
    ///     assert_eq!(call_to_xyz.is_language(), true);
    ///     assert_eq!(call_to_xyz.len(), 3);
    /// }
    /// ```
    fn as_language(&self) -> Option<Language> {
        Language::try_from(self.as_robj()).ok()
    }

    /// Convert a pair list object (LISTSXP) to a Pairlist wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let names_and_values = vec![("a", r!(1)), ("b", r!(2)), ("", r!(3))];
    ///     let pairlist = Pairlist::from_pairs(names_and_values);
    ///     let robj = r!(pairlist.clone());
    ///     assert_eq!(robj.as_pairlist().unwrap(), pairlist);
    /// }
    /// ```
    fn as_pairlist(&self) -> Option<Pairlist> {
        Pairlist::try_from(self.as_robj()).ok()
    }

    /// Convert a list object (VECSXP) to a List wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let list = r!(List::from_values(&[r!(0), r!(1), r!(2)]));
    ///     assert_eq!(list.is_list(), true);
    /// }
    /// ```
    fn as_list(&self) -> Option<List> {
        List::try_from(self.as_robj()).ok()
    }

    /// Convert an expression object (EXPRSXP) to a Expr wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let expr = r!(Expressions::from_values(&[r!(0), r!(1), r!(2)]));
    ///     assert_eq!(expr.is_expressions(), true);
    ///     assert_eq!(expr.as_expressions(), Some(Expressions::from_values(vec![r!(0), r!(1), r!(2)])));
    /// }
    /// ```
    fn as_expressions(&self) -> Option<Expressions> {
        Expressions::try_from(self.as_robj()).ok()
    }

    /// Convert an environment object (ENVSXP) to a Env wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let names_and_values = (0..100).map(|i| (format!("n{}", i), i));
    ///     let env = Environment::from_pairs(global_env(), names_and_values);
    ///     let expr = env.clone();
    ///     assert_eq!(expr.len(), 100);
    ///     let env2 = expr.as_environment().unwrap();
    ///     assert_eq!(env2.len(), 100);
    /// }
    /// ```
    fn as_environment(&self) -> Option<Environment> {
        Environment::try_from(self.as_robj()).ok()
    }

    /// Convert a function object (CLOSXP) to a Function wrapper.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///     let func = R!("function(a,b) a + b").unwrap();
    ///     println!("{:?}", func.as_function());
    /// }
    /// ```
    fn as_function(&self) -> Option<Function> {
        Function::try_from(self.as_robj()).ok()
    }

    /// Get a wrapper for a promise.
    fn as_promise(&self) -> Option<Promise> {
        Promise::try_from(self.as_robj()).ok()
    }
}

impl Conversions for Robj {}

pub trait SymPair {
    fn sym_pair(self) -> (Option<Robj>, Robj);
}

impl<S, R> SymPair for (S, R)
where
    S: AsRef<str>,
    R: Into<Robj>,
{
    fn sym_pair(self) -> (Option<Robj>, Robj) {
        let val = self.0.as_ref();
        // "" represents the absense of the name
        let nm = if val.is_empty() {
            None
        } else {
            Some(r!(Symbol::from_string(val)))
        };
        (nm, self.1.into())
    }
}

impl<S, R> SymPair for &(S, R)
where
    S: AsRef<str>,
    R: Into<Robj>,
    R: Clone,
{
    fn sym_pair(self) -> (Option<Robj>, Robj) {
        use crate as extendr_api;
        let val = self.0.as_ref();
        let nm = if val.is_empty() {
            None
        } else {
            Some(r!(Symbol::from_string(val)))
        };
        (nm, self.1.clone().into())
    }
}