Skip to main content

miniextendr_api/
options.rs

1//! Reading R options (`getOption()`) from Rust.
2//!
3//! [`get_option`] reads one option and converts it with [`TryFromSexp`].
4//! A value that doesn't convert is an [`RError`] whose message names the
5//! option, so `?` in a `#[miniextendr]` function returning `Result<_, RError>`
6//! raises it with its classes:
7//!
8//! ```ignore
9//! use miniextendr_api::condition::RError;
10//! use miniextendr_api::{get_option, miniextendr};
11//!
12//! #[miniextendr]
13//! pub fn report_width() -> Result<i32, RError> {
14//!     Ok(get_option::<i32>("mypkg.width")?.unwrap_or(80))
15//! }
16//! ```
17//!
18//! ```r
19//! options(mypkg.width = "wide")
20//! report_width()
21//! #> Error in report_width() :
22//! #>   options("mypkg.width") is invalid: expected integer, got character
23//! ```
24
25use crate::condition::RError;
26use crate::from_r::{SexpError, TryFromSexp};
27use crate::gc_protect::OwnedProtect;
28use crate::sexp::SEXP;
29
30/// The class every [`get_option`] conversion error carries.
31pub const OPTION_ERROR_CLASS: &str = "miniextendr_option_error";
32
33/// Read the R option `name`, as `getOption(name)` does, and convert it to `T`.
34///
35/// `Ok(None)` when the option is unset or set to `NULL` (R does not tell the
36/// two apart). A value that doesn't convert is an error: its message names
37/// `options("name")` and gives the conversion's reason in R terms, its class
38/// is [`OPTION_ERROR_CLASS`] (after the classes of a refusal that carries its
39/// own, such as a `#[try_from_sexp(validate = ...)]` check), and `e$option`
40/// is `name`.
41///
42/// Read into an owned `T` (`String`, `Vec<_>`, ...). A borrowed `T` such as
43/// `&str` points into the option's value, which nothing roots once this
44/// returns: `options(name = NULL)` or a new value lets R free it.
45///
46/// # Panics
47///
48/// Off R's main thread, before reading anything.
49pub fn get_option<T>(name: &str) -> Result<Option<T>, RError>
50where
51    T: TryFromSexp,
52    SexpError: From<T::Error>,
53{
54    if !crate::is_r_main_thread() {
    {
        ::core::panicking::panic_fmt(format_args!("`get_option(\"{0}\")` reads R\'s options on R\'s main thread: call it there, not from a thread the package spawned",
                name));
    }
};assert!(
55        crate::is_r_main_thread(),
56        "`get_option(\"{name}\")` reads R's options on R's main thread: call it there, \
57         not from a thread the package spawned",
58    );
59
60    // Symbols are never collected; `Rf_GetOption1` doesn't allocate.
61    let value = unsafe { crate::sys::Rf_GetOption1(SEXP::symbol(name)) };
62    if value.is_nil() {
63        return Ok(None);
64    }
65
66    // The conversion may run R code that resets the option, after which only
67    // this protection keeps the value alive.
68    // SAFETY: R's main thread (checked above); released when the guard drops.
69    let guard = unsafe { OwnedProtect::new(value) };
70    T::try_from_sexp(guard.get())
71        .map(Some)
72        .map_err(|e| option_error(name, SexpError::from(e)))
73}
74
75/// The error of an option `name` whose value didn't convert: the refusal's
76/// reason in R terms, its classes and fields kept when it carries its own.
77fn option_error(name: &str, err: SexpError) -> RError {
78    let reason = err.r_reason(false);
79    let mut out = RError::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("options(\"{0}\") is invalid: {1}",
                name, reason))
    })format!("options(\"{name}\") is invalid: {reason}"));
80    if let SexpError::Condition(inner) = &err {
81        out = out.class(inner.classes().to_vec());
82        for (field, value) in inner.fields() {
83            out = out.data(field.clone(), value.clone());
84        }
85    }
86    out.class(OPTION_ERROR_CLASS).data("option", name)
87}