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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use crate::*;
use std::os::raw;

///////////////////////////////////////////////////////////////
/// The following impls wrap specific Rinternals.h functions.
///
pub trait Rinternals: Types + Conversions {
    /// Return true if this is the null object.
    fn is_null(&self) -> bool {
        unsafe { Rf_isNull(self.get()) != 0 }
    }

    /// Return true if this is a symbol.
    fn is_symbol(&self) -> bool {
        unsafe { Rf_isSymbol(self.get()) != 0 }
    }

    /// Return true if this is a boolean (logical) vector
    fn is_logical(&self) -> bool {
        unsafe { Rf_isLogical(self.get()) != 0 }
    }

    /// Return true if this is a real (f64) vector.
    fn is_real(&self) -> bool {
        unsafe { Rf_isReal(self.get()) != 0 }
    }

    /// Return true if this is a complex vector.
    fn is_complex(&self) -> bool {
        unsafe { Rf_isComplex(self.get()) != 0 }
    }

    /// Return true if this is an expression.
    fn is_expressions(&self) -> bool {
        unsafe { Rf_isExpression(self.get()) != 0 }
    }

    /// Return true if this is an environment.
    fn is_environment(&self) -> bool {
        unsafe { Rf_isEnvironment(self.get()) != 0 }
    }

    /// Return true if this is an environment.
    fn is_promise(&self) -> bool {
        self.sexptype() == PROMSXP
    }

    /// Return true if this is a string.
    fn is_string(&self) -> bool {
        unsafe { Rf_isString(self.get()) != 0 }
    }

    /// Return true if this is an object (ie. has a class attribute).
    fn is_object(&self) -> bool {
        unsafe { Rf_isObject(self.get()) != 0 }
    }

    /// Return true if this is a S4 object.
    fn is_s4(&self) -> bool {
        unsafe { Rf_isS4(self.get()) != 0 }
    }

    /// Return true if this is an expression.
    fn is_external_pointer(&self) -> bool {
        self.rtype() == Rtype::ExternalPtr
    }

    /// Get the source ref.
    fn get_current_srcref(val: i32) -> Robj {
        unsafe { Robj::from_sexp(R_GetCurrentSrcref(val as raw::c_int)) }
    }

    /// Get the source filename.
    fn get_src_filename(&self) -> Robj {
        unsafe { Robj::from_sexp(R_GetSrcFilename(self.get())) }
    }

    /// Convert to a string vector.
    fn as_character_vector(&self) -> Robj {
        unsafe { Robj::from_sexp(Rf_asChar(self.get())) }
    }

    /// Convert to vectors of many kinds.
    fn coerce_vector(&self, sexptype: u32) -> Robj {
        single_threaded(|| unsafe {
            Robj::from_sexp(Rf_coerceVector(self.get(), sexptype as SEXPTYPE))
        })
    }

    /// Convert a pairlist (LISTSXP) to a vector list (VECSXP).
    fn pair_to_vector_list(&self) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_PairToVectorList(self.get())) })
    }

    /// Convert a vector list (VECSXP) to a pair list (LISTSXP)
    fn vector_to_pair_list(&self) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_VectorToPairList(self.get())) })
    }

    /// Convert a factor to a string vector.
    fn as_character_factor(&self) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_asCharacterFactor(self.get())) })
    }

    /// Allocate a matrix object.
    fn alloc_matrix(sexptype: SEXPTYPE, rows: i32, cols: i32) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_allocMatrix(sexptype, rows, cols)) })
    }

    /// Do a deep copy of this object.
    /// Note that clone() only adds a reference.
    fn duplicate(&self) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_duplicate(self.get())) })
    }

    /// Find a function in an environment ignoring other variables.
    ///
    /// This evaulates promises if they are found.
    ///
    /// See also [global_function()].
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let my_fun = base_env().find_function(sym!(ls)).unwrap();
    ///    assert_eq!(my_fun.is_function(), true);
    ///
    ///    // Note: this may crash on some versions of windows which don't support unwinding.
    ///    // assert!(base_env().find_function(sym!(qwertyuiop)).is_none());
    /// }
    /// ```
    fn find_function<K: TryInto<Symbol, Error = Error>>(&self, key: K) -> Result<Robj> {
        let key: Symbol = key.try_into()?;
        if !self.is_environment() {
            return Err(Error::NotFound(key.into()));
        }
        // This may be better:
        // let mut env: Robj = self.into();
        // loop {
        //     if let Some(var) = env.local(&key) {
        //         if let Some(var) = var.eval_promise() {
        //             if var.is_function() {
        //                 break Some(var);
        //             }
        //         }
        //     }
        //     if let Some(parent) = env.parent() {
        //         env = parent;
        //     } else {
        //         break None;
        //     }
        // }
        unsafe {
            let sexp = self.get();
            if let Ok(var) = catch_r_error(|| Rf_findFun(key.get(), sexp)) {
                Ok(Robj::from_sexp(var))
            } else {
                Err(Error::NotFound(key.into()))
            }
        }
    }

    /// Find a variable in an environment.
    ///
    /// See also [global_var()].
    ///
    /// Note that many common variables and functions are contained in promises
    /// which must be evaluated and this function may throw an R error.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let iris_dataframe = global_env()
    ///        .find_var(sym!(iris)).unwrap().eval_promise().unwrap();
    ///    assert_eq!(iris_dataframe.is_frame(), true);
    ///    assert_eq!(iris_dataframe.len(), 5);
    ///
    ///    // Note: this may crash on some versions of windows which don't support unwinding.
    ///    //assert_eq!(global_env().find_var(sym!(imnotasymbol)), None);
    /// }
    /// ```
    fn find_var<K: TryInto<Symbol, Error = Error>>(&self, key: K) -> Result<Robj> {
        let key: Symbol = key.try_into()?;
        if !self.is_environment() {
            return Err(Error::NotFound(key.into()));
        }
        // Alterative:
        // let mut env: Robj = self.into();
        // loop {
        //     if let Some(var) = env.local(&key) {
        //         println!("v1={:?}", var);
        //         if let Some(var) = var.eval_promise() {
        //             println!("v2={:?}", var);
        //             break Some(var);
        //         }
        //     }
        //     if let Some(parent) = env.parent() {
        //         env = parent;
        //     } else {
        //         break None;
        //     }
        // }
        unsafe {
            let sexp = self.get();
            if let Ok(var) = catch_r_error(|| Rf_findVar(key.get(), sexp)) {
                if var != R_UnboundValue {
                    Ok(Robj::from_sexp(var))
                } else {
                    Err(Error::NotFound(key.into()))
                }
            } else {
                Err(Error::NotFound(key.into()))
            }
        }
    }

    /// If this object is a promise, evaluate it, otherwise return the object.
    /// ```
    /// use extendr_api::prelude::*;
    /// test! {
    ///    let iris_promise = global_env().find_var(sym!(iris)).unwrap();
    ///    let iris_dataframe = iris_promise.eval_promise().unwrap();
    ///    assert_eq!(iris_dataframe.is_frame(), true);
    /// }
    /// ```
    fn eval_promise(&self) -> Result<Robj> {
        if self.is_promise() {
            self.as_promise().unwrap().eval()
        } else {
            Ok(self.as_robj().clone())
        }
    }

    /// Number of columns of a matrix
    fn ncols(&self) -> usize {
        unsafe { Rf_ncols(self.get()) as usize }
    }

    /// Number of rows of a matrix
    fn nrows(&self) -> usize {
        unsafe { Rf_nrows(self.get()) as usize }
    }

    /// Internal function used to implement `#[extendr]` impl
    #[doc(hidden)]
    unsafe fn make_external_ptr<T>(p: *mut T, prot: Robj) -> Robj {
        let type_name: Robj = std::any::type_name::<T>().into();
        Robj::from_sexp(single_threaded(|| {
            R_MakeExternalPtr(
                p as *mut ::std::os::raw::c_void,
                type_name.get(),
                prot.get(),
            )
        }))
    }

    /// Internal function used to implement `#[extendr]` impl
    #[doc(hidden)]
    unsafe fn external_ptr_addr<T>(&self) -> *mut T {
        R_ExternalPtrAddr(self.get()) as *mut T
    }

    /// Internal function used to implement `#[extendr]` impl
    #[doc(hidden)]
    unsafe fn external_ptr_tag(&self) -> Robj {
        Robj::from_sexp(R_ExternalPtrTag(self.get()))
    }

    /// Internal function used to implement `#[extendr]` impl
    #[doc(hidden)]
    unsafe fn external_ptr_protected(&self) -> Robj {
        Robj::from_sexp(R_ExternalPtrProtected(self.get()))
    }

    #[doc(hidden)]
    unsafe fn register_c_finalizer(&self, func: R_CFinalizer_t) {
        // Use R_RegisterCFinalizerEx() and set onexit to 1 (TRUE) to invoke the
        // finalizer on a shutdown of the R session as well.
        single_threaded(|| R_RegisterCFinalizerEx(self.get(), func, 1));
    }

    /// Copy a vector and resize it.
    /// See. <https://github.com/hadley/r-internals/blob/master/vectors.md>
    fn xlengthgets(&self, new_len: usize) -> Result<Robj> {
        unsafe {
            if self.is_vector() {
                Ok(single_threaded(|| {
                    Robj::from_sexp(Rf_xlengthgets(self.get(), new_len as R_xlen_t))
                }))
            } else {
                Err(Error::ExpectedVector(self.as_robj().clone()))
            }
        }
    }

    /// Allocated an owned object of a certain type.
    fn alloc_vector(sexptype: u32, len: usize) -> Robj {
        single_threaded(|| unsafe { Robj::from_sexp(Rf_allocVector(sexptype, len as R_xlen_t)) })
    }

    /// Return true if two arrays have identical dims.
    fn conformable(a: &Robj, b: &Robj) -> bool {
        single_threaded(|| unsafe { Rf_conformable(a.get(), b.get()) != 0 })
    }

    /// Return true if this is an array.
    fn is_array(&self) -> bool {
        unsafe { Rf_isArray(self.get()) != 0 }
    }

    /// Return true if this is factor.
    fn is_factor(&self) -> bool {
        unsafe { Rf_isFactor(self.get()) != 0 }
    }

    /// Return true if this is a data frame.
    fn is_frame(&self) -> bool {
        unsafe { Rf_isFrame(self.get()) != 0 }
    }

    /// Return true if this is a function or a primitive (CLOSXP, BUILTINSXP or SPECIALSXP)
    fn is_function(&self) -> bool {
        unsafe { Rf_isFunction(self.get()) != 0 }
    }

    /// Return true if this is an integer vector (INTSXP) but not a factor.
    fn is_integer(&self) -> bool {
        unsafe { Rf_isInteger(self.get()) != 0 }
    }

    /// Return true if this is a language object (LANGSXP).
    fn is_language(&self) -> bool {
        unsafe { Rf_isLanguage(self.get()) != 0 }
    }

    /// Return true if this is NILSXP or LISTSXP.
    fn is_pairlist(&self) -> bool {
        unsafe { Rf_isList(self.get()) != 0 }
    }

    /// Return true if this is a matrix.
    fn is_matrix(&self) -> bool {
        unsafe { Rf_isMatrix(self.get()) != 0 }
    }

    /// Return true if this is NILSXP or VECSXP.
    fn is_list(&self) -> bool {
        unsafe { Rf_isNewList(self.get()) != 0 }
    }

    /// Return true if this is INTSXP, LGLSXP or REALSXP but not a factor.
    fn is_number(&self) -> bool {
        unsafe { Rf_isNumber(self.get()) != 0 }
    }

    /// Return true if this is a primitive function BUILTINSXP, SPECIALSXP.
    fn is_primitive(&self) -> bool {
        unsafe { Rf_isPrimitive(self.get()) != 0 }
    }

    /// Return true if this is a time series vector (see tsp).
    fn is_ts(&self) -> bool {
        unsafe { Rf_isTs(self.get()) != 0 }
    }

    /// Return true if this is a user defined binop.
    fn is_user_binop(&self) -> bool {
        unsafe { Rf_isUserBinop(self.get()) != 0 }
    }

    /// Return true if this is a valid string.
    fn is_valid_string(&self) -> bool {
        unsafe { Rf_isValidString(self.get()) != 0 }
    }

    /// Return true if this is a valid string.
    fn is_valid_string_f(&self) -> bool {
        unsafe { Rf_isValidStringF(self.get()) != 0 }
    }

    /// Return true if this is a vector.
    fn is_vector(&self) -> bool {
        unsafe { Rf_isVector(self.get()) != 0 }
    }

    /// Return true if this is an atomic vector.
    fn is_vector_atomic(&self) -> bool {
        unsafe { Rf_isVectorAtomic(self.get()) != 0 }
    }

    /// Return true if this is a vector list.
    fn is_vector_list(&self) -> bool {
        unsafe { Rf_isVectorList(self.get()) != 0 }
    }

    /// Return true if this is can be made into a vector.
    fn is_vectorizable(&self) -> bool {
        unsafe { Rf_isVectorizable(self.get()) != 0 }
    }

    /// Return true if this is RAWSXP.
    fn is_raw(&self) -> bool {
        self.rtype() == Rtype::Raw
    }

    /// Return true if this is CHARSXP.
    fn is_char(&self) -> bool {
        self.rtype() == Rtype::Rstr
    }

    /// Check an external pointer tag.
    /// This is used to wrap R objects.
    #[doc(hidden)]
    fn check_external_ptr_type<T>(&self) -> bool {
        if self.sexptype() == libR_sys::EXTPTRSXP {
            let tag = unsafe { self.external_ptr_tag() };
            if tag.as_str() == Some(std::any::type_name::<T>()) {
                return true;
            }
        }
        false
    }

    fn is_missing_arg(&self) -> bool {
        unsafe { self.get() == R_MissingArg }
    }

    fn is_unbound_value(&self) -> bool {
        unsafe { self.get() == R_UnboundValue }
    }

    fn is_package_env(&self) -> bool {
        unsafe { R_IsPackageEnv(self.get()) != 0 }
    }

    fn package_env_name(&self) -> Robj {
        unsafe { Robj::from_sexp(R_PackageEnvName(self.get())) }
    }

    fn is_namespace_env(&self) -> bool {
        unsafe { R_IsNamespaceEnv(self.get()) != 0 }
    }

    fn namespace_env_spec(&self) -> Robj {
        unsafe { Robj::from_sexp(R_NamespaceEnvSpec(self.get())) }
    }

    /// Returns `true` if this is an ALTREP object.
    fn is_altrep(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 }
    }

    /// Returns `true` if this is an integer ALTREP object.
    fn is_altinteger(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == INTSXP as i32 }
    }

    /// Returns `true` if this is an real ALTREP object.
    fn is_altreal(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == REALSXP as i32 }
    }

    /// Returns `true` if this is an logical ALTREP object.
    fn is_altlogical(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == LGLSXP as i32 }
    }

    /// Returns `true` if this is a raw ALTREP object.
    fn is_altraw(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == RAWSXP as i32 }
    }

    /// Returns `true` if this is an integer ALTREP object.
    fn is_altstring(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == STRSXP as i32 }
    }

    /// Returns `true` if this is an integer ALTREP object.
    #[cfg(use_r_altlist)]
    fn is_altlist(&self) -> bool {
        unsafe { ALTREP(self.get()) != 0 && TYPEOF(self.get()) == VECSXP as i32 }
    }

    /// Generate a text representation of this object.
    fn deparse(&self) -> Result<String> {
        use crate as extendr_api;
        let strings: Strings = call!("deparse", self.as_robj())?.try_into()?;
        if strings.len() == 1 {
            Ok(String::from(strings.elt(0).as_str()))
        } else {
            Ok(strings
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(""))
        }
    }
}

impl Rinternals for Robj {}