Skip to main content

extendr_api/wrapper/
expr.rs

1use super::*;
2
3#[derive(PartialEq, Clone)]
4pub struct Expressions {
5    pub(crate) robj: Robj,
6}
7
8impl Expressions {
9    /// Wrapper for creating Expressions (EXPRSXP) objects.
10    pub fn new() -> Self {
11        Expressions::from_values([()])
12    }
13
14    /// Wrapper for creating Expressions (EXPRSXP) objects.
15    /// ```
16    /// use extendr_api::prelude::*;
17    /// test! {
18    ///     let expr = r!(Expressions::from_values(&[r!(0), r!(1), r!(2)]));
19    ///     assert_eq!(expr.is_expressions(), true);
20    ///     assert_eq!(expr.len(), 3);
21    /// }
22    /// ```
23    pub fn from_values<V>(values: V) -> Self
24    where
25        V: IntoIterator,
26        V::IntoIter: ExactSizeIterator,
27        V::Item: Into<Robj>,
28    {
29        Self {
30            robj: make_vector(SEXPTYPE::EXPRSXP, values),
31        }
32    }
33
34    /// Return an iterator over the values of this expression list.
35    pub fn values(&self) -> ListIter {
36        ListIter::from_parts(self.robj.clone(), 0, self.robj.len())
37    }
38}
39
40impl std::default::Default for Expressions {
41    fn default() -> Self {
42        Expressions::new()
43    }
44}
45
46impl std::fmt::Debug for Expressions {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        f.debug_struct("Expressions")
49            .field("values", &self.values())
50            .finish()
51    }
52}
53
54impl std::str::FromStr for Expressions {
55    type Err = Error;
56
57    fn from_str(code: &str) -> Result<Expressions> {
58        single_threaded(|| unsafe {
59            use extendr_ffi::{ParseStatus, R_NilValue, R_ParseVector};
60            let mut status = ParseStatus::PARSE_NULL;
61            let status_ptr = (&mut status) as *mut _;
62            let codeobj: Robj = code.into();
63            let parsed = Robj::from_sexp(R_ParseVector(codeobj.get(), -1, status_ptr, R_NilValue));
64            match status {
65                ParseStatus::PARSE_OK => parsed.try_into(),
66                _ => Err(Error::ParseError {
67                    status,
68                    code: code.into(),
69                }),
70            }
71        })
72    }
73}