extendr_api/wrapper/
promise.rs

1use super::*;
2
3/// Wrapper for creating promises (PROMSXP).
4#[derive(PartialEq, Clone)]
5pub struct Promise {
6    pub(crate) robj: Robj,
7}
8
9impl Promise {
10    /// Make a Promise from parts.
11    /// ```
12    /// use extendr_api::prelude::*;
13    /// test! {
14    ///     let promise = Promise::from_parts(r!(1), global_env())?;
15    ///     assert!(promise.value().is_unbound_value());
16    ///     assert_eq!(promise.eval_promise()?, r!(1));
17    ///     assert_eq!(promise.value(), r!(1));
18    /// }
19    /// ```
20    #[cfg(feature = "non-api")]
21    pub fn from_parts(code: Robj, environment: Environment) -> Result<Self> {
22        single_threaded(|| unsafe {
23            let sexp = extendr_ffi::Rf_allocSExp(SEXPTYPE::PROMSXP);
24            let robj = Robj::from_sexp(sexp);
25            extendr_ffi::SET_PRCODE(sexp, code.get());
26            extendr_ffi::SET_PRENV(sexp, environment.robj.get());
27            extendr_ffi::SET_PRVALUE(sexp, extendr_ffi::R_UnboundValue);
28            Ok(Promise { robj })
29        })
30    }
31
32    #[cfg(feature = "non-api")]
33    /// Get the code to be executed from the promise.
34    pub fn code(&self) -> Robj {
35        unsafe {
36            let sexp = self.robj.get();
37            Robj::from_sexp(extendr_ffi::PRCODE(sexp))
38        }
39    }
40
41    #[cfg(feature = "non-api")]
42    /// Get the environment for the execution from the promise.
43    pub fn environment(&self) -> Environment {
44        unsafe {
45            let sexp = self.robj.get();
46            Robj::from_sexp(extendr_ffi::PRENV(sexp))
47                .try_into()
48                .unwrap()
49        }
50    }
51
52    #[cfg(feature = "non-api")]
53    /// Get the value of the promise, once executed.
54    pub fn value(&self) -> Robj {
55        unsafe {
56            let sexp = self.robj.get();
57            Robj::from_sexp(extendr_ffi::PRVALUE(sexp))
58        }
59    }
60
61    #[cfg(feature = "non-api")]
62    /// Get the seen flag (avoids recursion).
63    pub fn seen(&self) -> i32 {
64        unsafe {
65            let sexp = self.robj.get();
66            extendr_ffi::PRSEEN(sexp)
67        }
68    }
69
70    #[cfg(feature = "non-api")]
71    /// If this promise has not been evaluated, evaluate it, otherwise return the value.
72    /// ```
73    /// use extendr_api::prelude::*;
74    /// test! {
75    ///    let iris_promise = global_env().find_var(sym!(iris)).unwrap();
76    ///    let iris_dataframe = iris_promise.as_promise().unwrap().eval().unwrap();
77    ///    assert_eq!(iris_dataframe.is_frame(), true);
78    /// }
79    /// ```
80    pub fn eval(&self) -> Result<Robj> {
81        assert!(self.is_promise());
82        if !self.value().is_unbound_value() {
83            Ok(self.value())
84        } else {
85            self.robj.eval()
86        }
87    }
88}
89
90impl std::fmt::Debug for Promise {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        let mut result = f.debug_struct("Promise");
93
94        #[cfg(feature = "non-api")]
95        {
96            let result = result.field("code", &self.code());
97            let result = result.field("environment", &self.environment());
98        }
99        result.finish()
100    }
101}