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
use std::ffi::CString;
use savvy_ffi::{R_GlobalEnv, R_NilValue, Rboolean_TRUE, SEXP};
// Note: Since `unwind_protect()` can only return an SEXP, we need some sentinel
// value to indicate either success or failure. Any SEXP can be used here as
// long as it's (1) not a value that Rf_eval() possibly returns, and (2) not a
// non-API. A null pointer is invalid as an SEXP, but that's why it fits for
// this usage.
const THE_SENTINEL_VALUE: SEXP = std::ptr::null_mut() as SEXP;
use crate::{Sexp, savvy_err};
use super::utils::str_to_symsxp;
/// An environment.
pub struct EnvironmentSexp(pub SEXP);
impl EnvironmentSexp {
/// Returns the raw SEXP.
#[inline]
pub fn inner(&self) -> savvy_ffi::SEXP {
self.0
}
/// Returns the SEXP bound to a variable of the specified name in the
/// specified environment.
///
/// The absense of an object with the specified name is represented as
/// `None`. `Some(NilSexp)` means there's a variable whose value is `NULL`.
///
/// # Protection
///
/// The result `Sexp` is unprotected. In most of the cases, you don't need
/// to worry about this because existing in an environment means it won't be
/// GC-ed as long as the environment exists (it's possible the correspondig
/// variable gets explicitly removed, but it should be rare). However, if
/// the environment is a temporary one (e.g. an exectuion environment of a
/// function call), it's your responsibility to protect the object. In other
/// words, you should never use this if you don't understand how R's
/// protection mechanism works.
pub fn get<T: AsRef<str>>(&self, name: T) -> crate::error::Result<Option<crate::Sexp>> {
let sym = str_to_symsxp(name)?.ok_or(savvy_err!("name must not be empty"))?;
// Note: since this SEXP already belongs to an environment, this doesn't
// need protection.
let sexp = unsafe {
crate::unwind_protect(|| {
if savvy_ffi::R_existsVarInFrame(self.0, sym) == Rboolean_TRUE {
// TODO: replace this with R_getVar() when savvy drop supports on R <4.5
savvy_ffi::Rf_eval(sym, self.0)
} else {
// In this case, THE_SENTINEL_VALUE indicates a failure
THE_SENTINEL_VALUE
}
})?
};
if sexp == THE_SENTINEL_VALUE {
Ok(None)
} else {
Ok(Some(Sexp(sexp)))
}
}
/// Returns `true` the specified environment contains the specified
/// variable.
pub fn contains<T: AsRef<str>>(&self, name: T) -> crate::error::Result<bool> {
let sym = str_to_symsxp(name)?.ok_or(savvy_err!("name must not be empty"))?;
let res = unsafe {
crate::unwind_protect(|| {
if savvy_ffi::R_existsVarInFrame(self.0, sym) == Rboolean_TRUE {
// In this case, THE_SENTINEL_VALUE indicates a success
THE_SENTINEL_VALUE
} else {
R_NilValue
}
})? == THE_SENTINEL_VALUE
};
Ok(res)
}
/// Bind the SEXP to the specified environment as the specified name.
pub fn set<T: AsRef<str>>(&self, name: T, value: Sexp) -> crate::error::Result<()> {
let name_cstr = CString::new(name.as_ref())?;
unsafe {
crate::unwind_protect(|| {
savvy_ffi::Rf_defineVar(savvy_ffi::Rf_install(name_cstr.as_ptr()), value.0, self.0);
R_NilValue
})?
};
Ok(())
}
/// Return the global env.
pub fn global_env() -> Self {
Self(unsafe { R_GlobalEnv })
}
}
// conversions from/to EnvironmentSexp ***************
impl TryFrom<Sexp> for EnvironmentSexp {
type Error = crate::error::Error;
fn try_from(value: Sexp) -> crate::error::Result<Self> {
value.assert_environment()?;
Ok(Self(value.0))
}
}
impl From<EnvironmentSexp> for Sexp {
fn from(value: EnvironmentSexp) -> Self {
Self(value.inner())
}
}
impl From<EnvironmentSexp> for crate::error::Result<Sexp> {
fn from(value: EnvironmentSexp) -> Self {
Ok(<Sexp>::from(value))
}
}