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
use super::*;
/// Wrapper for creating promises (PROMSXP).
#[derive(PartialEq, Clone)]
pub struct Promise {
pub(crate) robj: Robj,
}
impl Promise {
/// Make a Promise from parts.
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let promise = Promise::from_parts(r!(1), global_env())?;
/// assert_eq!(promise.eval_promise()?, r!(1));
/// assert_eq!(promise.value(), r!(1));
/// }
/// ```
#[cfg(feature = "non-api")]
pub fn from_parts(code: Robj, environment: Environment) -> Result<Self> {
single_threaded(|| unsafe {
let sexp = extendr_ffi::Rf_allocSExp(SEXPTYPE::PROMSXP);
let robj = Robj::from_sexp(sexp);
extendr_ffi::SET_PRCODE(sexp, code.get());
extendr_ffi::SET_PRENV(sexp, environment.robj.get());
#[cfg(not(r_4_5))]
extendr_ffi::SET_PRVALUE(sexp, extendr_ffi::R_UnboundValue);
Ok(Promise { robj })
})
}
#[cfg(feature = "non-api")]
/// Get the code to be executed from the promise.
pub fn code(&self) -> Robj {
unsafe {
let sexp = self.robj.get();
Robj::from_sexp(extendr_ffi::PRCODE(sexp))
}
}
#[cfg(feature = "non-api")]
/// Get the environment for the execution from the promise.
pub fn environment(&self) -> Environment {
unsafe {
let sexp = self.robj.get();
Robj::from_sexp(extendr_ffi::PRENV(sexp))
.try_into()
.unwrap()
}
}
#[cfg(feature = "non-api")]
/// Get the value of the promise, once executed.
pub fn value(&self) -> Robj {
unsafe {
let sexp = self.robj.get();
Robj::from_sexp(extendr_ffi::PRVALUE(sexp))
}
}
#[cfg(feature = "non-api")]
/// Get the seen flag (avoids recursion).
pub fn seen(&self) -> i32 {
unsafe {
let sexp = self.robj.get();
extendr_ffi::PRSEEN(sexp)
}
}
#[cfg(feature = "non-api")]
/// If this promise has not been evaluated, evaluate it, otherwise return the value.
/// ```
/// use extendr_api::prelude::*;
/// test! {
/// let iris_promise = global_env().find_var(sym!(iris)).unwrap();
/// let iris_dataframe = iris_promise.as_promise().unwrap().eval().unwrap();
/// assert_eq!(iris_dataframe.is_frame(), true);
/// }
/// ```
pub fn eval(&self) -> Result<Robj> {
assert!(self.is_promise());
#[cfg(not(r_4_5))]
if !self.value().is_unbound_value() {
return Ok(self.value());
}
self.robj.eval()
}
}
impl std::fmt::Debug for Promise {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut result = f.debug_struct("Promise");
#[cfg(feature = "non-api")]
{
let result = result.field("code", &self.code());
let _result = result.field("environment", &self.environment());
}
result.finish()
}
}