Skip to main content

miniextendr_api/
quoted.rs

1//! Unevaluated arguments: the [`Quoted`] and [`Quosure`] parameter markers.
2//!
3//! A generated R wrapper forces every argument it hands to `.Call()`, so a
4//! Rust body normally sees values only. A parameter typed `Quoted` or
5//! `Quosure` is passed unevaluated instead: the body receives the argument's
6//! expression and the environment to evaluate it in, and decides what to do
7//! with them. That is what `subset()`-style methods and APIs taking bare
8//! column names (`f(data, TIME)` as well as `f(data, "TIME")`) need.
9//!
10//! | marker | the wrapper passes | needs | `{{ x }}` / `!!x` |
11//! |---|---|---|---|
12//! | [`Quoted`] | `list(substitute(x), parent.frame())` | base R | no |
13//! | [`Quosure`] | `rlang::enquo(x)` | rlang in `Imports` | yes |
14//!
15//! ```ignore
16//! use miniextendr_api::{miniextendr, Quoted, SEXP};
17//!
18//! /// Rows of `data` where `cond` holds; `cond` sees the columns of `data`,
19//! /// then the caller's variables.
20//! #[miniextendr]
21//! pub fn keep_rows(data: SEXP, cond: Quoted) -> Vec<i32> {
22//!     let keep = cond.eval_in(data);
23//!     // ... read the logical vector
24//! #   vec![]
25//! }
26//! ```
27//!
28//! ```r
29//! threshold <- 3
30//! keep_rows(df, value > threshold)
31//! ```
32//!
33//! The wrapper never forces the argument: a `Quoted` / `Quosure` parameter
34//! takes no R-side checks and none of the per-parameter options (`coerce`,
35//! `match_arg`, `choices`, `default`, `no_na`, `inherits`, ...), which are
36//! compile errors on it. A function taking one runs on R's main thread.
37//! It works on free functions, including standalone S3 methods
38//! (`#[miniextendr(s3(generic = "subset", class = "..."))]`): in a method
39//! reached through `UseMethod()`, `parent.frame()` is the generic's caller, as
40//! in base R's `subset.data.frame()`.
41//!
42//! A missing argument is a conversion error naming the parameter
43//! (`argument "cond" is missing, with no default`), like forcing it in R. Take
44//! `Missing<Quoted>` / `Missing<Quosure>` to make the argument optional.
45//!
46//! Evaluation goes through [`crate::expression::eval_with_handlers`]: the
47//! caller's `withCallingHandlers()` / `suppressWarnings()` see what the
48//! expression signals, and an error, or the exit of a `tryCatch()` handler set
49//! up around the call, unwinds through the Rust frames (running their
50//! destructors) and carries on in R as the original condition.
51//!
52//! Both markers borrow from the `.Call()` arguments, which R keeps rooted for
53//! the call; the lifetime keeps them from outliving it. They are `!Send`.
54//!
55//! A `Quosure` can also be read from a quosure found in an R object
56//! ([`Quosure::from_sexp`]), such as one a wrapper wrote into a call with
57//! `c(time = {{ t }})`, or built from an expression and an environment
58//! ([`Quosure::new`], [`Quosure::args`]). It then borrows the root the caller
59//! holds: the SEXP it was read from, or a [`ProtectScope`].
60
61use std::marker::PhantomData;
62
63use crate::expression::RCall;
64use crate::from_r::{SexpError, try_charsxp_to_str};
65use crate::gc_protect::{OwnedProtect, ProtectScope};
66use crate::missing::Missing;
67use crate::{PairListExt, SEXP, SEXPTYPE, SexpExt};
68
69/// The name an argument expression stands for: a symbol's name, or the value
70/// of a length-1 character literal. `None` for anything else, and for `NA`;
71/// an error for a name that is not text (marked as bytes, or not valid UTF-8).
72fn expr_name<'a>(expr: SEXP) -> Result<Option<&'a str>, SexpError> {
73    match expr.type_of() {
74        // Symbols are never collected; their print names live for the session.
75        SEXPTYPE::SYMSXP => {
76            let name = unsafe { try_charsxp_to_str(expr.printname()) }?;
77            Ok((!name.is_empty()).then_some(name))
78        }
79        SEXPTYPE::STRSXP if expr.len() == 1 => {
80            let elt = expr.string_elt(0);
81            if elt.is_na_string() {
82                return Ok(None);
83            }
84            // The CHARSXP is held by `expr`, which the caller keeps rooted.
85            unsafe { try_charsxp_to_str(elt) }.map(Some)
86        }
87        _ => Ok(None),
88    }
89}
90
91// region: Quoted
92
93/// An argument passed unevaluated: its expression and the environment it was
94/// written in, as base R's `substitute(x)` and `parent.frame()` give them.
95///
96/// Take it as a `#[miniextendr]` parameter. The generated wrapper keeps the
97/// parameter as an R formal and passes
98/// `if (missing(x)) quote(expr=) else list(substitute(x), parent.frame())`,
99/// which never forces the argument. See the [module docs](self).
100///
101/// ```ignore
102/// use miniextendr_api::{miniextendr, Quoted, SEXP, SexpError};
103///
104/// #[miniextendr]
105/// pub fn column_name(col: Quoted) -> Result<Option<String>, SexpError> {
106///     Ok(col.as_name()?.map(str::to_owned))   // column_name(TIME), column_name("TIME")
107/// }
108///
109/// #[miniextendr]
110/// pub fn evaluate(expr: Quoted) -> SEXP {
111///     expr.eval()                          // eval(expr, env)
112/// }
113/// ```
114///
115/// `parent.frame()` is the environment of the function that called the
116/// wrapper, which is where the expression was written when the user calls the
117/// wrapper directly or through `UseMethod()`. A wrapper reached through a
118/// function that forwards its own argument (`g <- function(y) f(y)`) receives
119/// `y` and `g`'s frame, as `subset()` does. To resolve forwarding, `{{ x }}`
120/// and `!!x`, take a [`Quosure`].
121pub struct Quoted<'a> {
122    expr: SEXP,
123    env: SEXP,
124    /// Borrows the `.Call()` argument that roots `expr` and `env`.
125    _arg: PhantomData<&'a SEXP>,
126    /// R objects stay on R's main thread.
127    _not_send: PhantomData<*const ()>,
128}
129
130impl<'a> Quoted<'a> {
131    /// Read the argument a generated wrapper passed for a `Quoted` parameter:
132    /// `None` when the argument is missing (`quote(expr=)`). Generated code
133    /// calls this; user code has no reason to.
134    ///
135    /// # Panics
136    ///
137    /// When `arg` is not the wrapper's `list(<expr>, <environment>)`.
138    ///
139    /// # Safety
140    ///
141    /// R's main thread; `arg` stays rooted for `'a`.
142    #[doc(hidden)]
143    pub unsafe fn from_wrapper_arg(arg: &'a SEXP) -> Option<Self> {
144        let arg = *arg;
145        if arg == SEXP::missing_arg() {
146            return None;
147        }
148        if !(arg.type_of() == SEXPTYPE::VECSXP && arg.len() == 2 &&
            arg.vector_elt(1).is_environment()) {
    {
        ::core::panicking::panic_fmt(format_args!("a `Quoted` argument is passed as `list(substitute(x), parent.frame())`, got {0}",
                arg.type_of().type_name()));
    }
};assert!(
149            arg.type_of() == SEXPTYPE::VECSXP
150                && arg.len() == 2
151                && arg.vector_elt(1).is_environment(),
152            "a `Quoted` argument is passed as `list(substitute(x), parent.frame())`, got {}",
153            arg.type_of().type_name(),
154        );
155        Some(Quoted {
156            expr: arg.vector_elt(0),
157            env: arg.vector_elt(1),
158            _arg: PhantomData,
159            _not_send: PhantomData,
160        })
161    }
162
163    /// [`Self::from_wrapper_arg`] for a `Missing<Quoted>` parameter.
164    ///
165    /// # Safety
166    ///
167    /// As [`Self::from_wrapper_arg`].
168    #[doc(hidden)]
169    pub unsafe fn missing_from_wrapper_arg(arg: &'a SEXP) -> Missing<Self> {
170        match unsafe { Self::from_wrapper_arg(arg) } {
171            Some(quoted) => Missing::Present(quoted),
172            None => Missing::Absent,
173        }
174    }
175
176    /// The expression as written: a symbol, a call, or a constant
177    /// (`substitute(x)`).
178    #[inline]
179    pub fn expr(&self) -> SEXP {
180        self.expr
181    }
182
183    /// The environment the expression was written in (`parent.frame()`).
184    #[inline]
185    pub fn env(&self) -> SEXP {
186        self.env
187    }
188
189    /// The name the argument stands for: `TIME` and `"TIME"` both give
190    /// `"TIME"`. `None` for any other expression (a call, a number, `NA`).
191    ///
192    /// # Errors
193    ///
194    /// A name that is not text: a string marked as bytes, or one that is not
195    /// valid UTF-8.
196    #[inline]
197    pub fn as_name(&self) -> Result<Option<&'a str>, SexpError> {
198        expr_name(self.expr)
199    }
200
201    /// Evaluate the expression in its environment, `eval(expr, env)`, keeping
202    /// the caller's condition handlers
203    /// ([`eval_with_handlers`](crate::expression::eval_with_handlers)).
204    ///
205    /// The value is unprotected: protect it before the next allocation.
206    pub fn eval(&self) -> SEXP {
207        // SAFETY: a `Quoted` exists only inside the `#[miniextendr]` call that
208        // received it, on R's main thread; its argument roots both SEXPs.
209        unsafe { crate::expression::eval_with_handlers(self.expr, self.env) }
210    }
211
212    /// Evaluate the expression with `data` as a data mask, like
213    /// `eval(expr, data, env)`: the elements of a list or the columns of a
214    /// data frame are visible by name, ahead of the expression's environment.
215    /// The first of two elements with one name wins, and unnamed elements are
216    /// not visible. An environment is used as is (`env` is not consulted),
217    /// and `NULL` evaluates in the expression's environment.
218    ///
219    /// The value is unprotected: protect it before the next allocation.
220    ///
221    /// # Panics
222    ///
223    /// When `data` is not a list, a data frame, an environment or `NULL`.
224    pub fn eval_in(&self, data: SEXP) -> SEXP {
225        // SAFETY: as in `eval`; `data` is rooted by the caller.
226        unsafe { self.eval_masked(data, crate::expression::eval_with_handlers) }
227    }
228
229    /// [`eval_in`](Self::eval_in) with an R error returned as `Err`, as
230    /// [`try_eval_with_handlers`](crate::expression::try_eval_with_handlers)
231    /// returns it: the caller's handlers still see the expression's warnings
232    /// and messages. The mask and the rules for `data` are `eval_in`'s.
233    ///
234    /// A `subset()` method can explain a column that doesn't exist and leave
235    /// every other error as R raised it
236    /// ([`REvalError::reraise`](crate::expression::REvalError::reraise)):
237    ///
238    /// ```ignore
239    /// let keep = match subset.try_eval_in(table) {
240    ///     Ok(keep) => keep,
241    ///     // `unknown_column` compares the expression's names with the table's.
242    ///     Err(e) if unknown_column(&subset, table) => {
243    ///         rust_error!(class = "pkg_unknown_column", "{e}; the columns are ...")
244    ///     }
245    ///     // SAFETY: inside the `#[miniextendr]` call.
246    ///     Err(e) => unsafe { e.reraise() },
247    /// };
248    /// ```
249    ///
250    /// The value is unprotected: protect it before the next allocation.
251    ///
252    /// # Panics
253    ///
254    /// When `data` is not a list, a data frame, an environment or `NULL`.
255    pub fn try_eval_in(&self, data: SEXP) -> Result<SEXP, crate::expression::REvalError> {
256        // SAFETY: as in `eval`; `data` is rooted by the caller.
257        unsafe { self.eval_masked(data, crate::expression::try_eval_with_handlers) }
258    }
259
260    /// Evaluate the expression with `data` as a mask, as
261    /// [`eval_in`](Self::eval_in) describes, through `eval`.
262    ///
263    /// # Safety
264    ///
265    /// As `eval`'s: R's main thread, inside a miniextendr boundary; `data`
266    /// rooted by the caller.
267    unsafe fn eval_masked<R>(&self, data: SEXP, eval: unsafe fn(SEXP, SEXP) -> R) -> R {
268        unsafe {
269            match data.type_of() {
270                SEXPTYPE::ENVSXP => eval(self.expr, data),
271                SEXPTYPE::NILSXP => eval(self.expr, self.env),
272                SEXPTYPE::VECSXP => {
273                    // Rooted ahead of the evaluation's own protect frame, so an
274                    // R exit leaves the protect stack as this guard expects.
275                    let mask = OwnedProtect::new(data_mask(data, self.env));
276                    eval(self.expr, mask.get())
277                }
278                other => {
    ::core::panicking::panic_fmt(format_args!("`data` must be a list, a data frame, an environment or NULL, not {0}",
            other.type_name()));
}panic!(
279                    "`data` must be a list, a data frame, an environment or NULL, not {}",
280                    other.type_name()
281                ),
282            }
283        }
284    }
285}
286
287/// A new environment enclosed by `enclos` that binds each named element of
288/// the list `data`, as `eval()` builds one for a list `envir`. Bound in
289/// reverse so the first of two same-named elements wins, as in `eval()`.
290///
291/// # Safety
292///
293/// R's main thread, inside a miniextendr boundary; `data` a rooted list,
294/// `enclos` an environment. The result is unprotected.
295unsafe fn data_mask(data: SEXP, enclos: SEXP) -> SEXP {
296    unsafe {
297        let n = data.len();
298        let size = i32::try_from(n).unwrap_or(i32::MAX);
299        let mask = OwnedProtect::new(crate::sys::R_NewEnv(enclos, crate::Rboolean::TRUE, size));
300        let env = crate::expression::REnv::from_sexp(mask.get());
301        let names = data.get_names();
302        if names.type_of() == SEXPTYPE::STRSXP {
303            for i in (0..n).rev() {
304                let i = isize::try_from(i).expect("list index fits in isize");
305                let name = names.string_elt(i);
306                if name.is_na_string() || name.len() == 0 {
307                    continue;
308                }
309                // `names` is held by `data`; the symbol table keeps the symbol.
310                env.define_symbol(SEXP::install_char(name), data.vector_elt(i));
311            }
312        }
313        mask.get()
314    }
315}
316
317// endregion
318
319// region: Quosure
320
321/// Whether `x` is an rlang quosure: a one-sided formula, `~expr`, of class
322/// `quosure`.
323fn is_quosure(x: SEXP) -> bool {
324    x.is_language() && x.inherits_class(c"quosure")
325}
326
327/// The quosure `x` stands for: `x` itself, or, when its expression is a
328/// quosure too (`rlang::new_quosure(<quosure>)`), the innermost one. `None`
329/// when `x` is not a quosure.
330fn innermost_quosure(x: SEXP) -> Option<SEXP> {
331    if !is_quosure(x) {
332        return None;
333    }
334    let mut quo = x;
335    while is_quosure(quo.cdr().car()) {
336        quo = quo.cdr().car();
337    }
338    Some(quo)
339}
340
341/// The function `rlang::new_quosure`, unprotected.
342///
343/// # Panics
344///
345/// When rlang cannot be loaded.
346///
347/// # Safety
348///
349/// R's main thread.
350unsafe fn rlang_new_quosure() -> SEXP {
351    use crate::sys::{R_BaseEnv, Rf_install};
352    unsafe {
353        // `rlang::new_quosure`; `::` takes both names unevaluated.
354        RCall::new("::")
355            .arg(Rf_install(c"rlang".as_ptr()))
356            .arg(Rf_install(c"new_quosure".as_ptr()))
357            .eval(R_BaseEnv)
358            .unwrap_or_else(|e| {
359                {
    ::core::panicking::panic_fmt(format_args!("a `Quosure` of a bare expression is built with `rlang::new_quosure()`, which needs the rlang package: {0}",
            e));
}panic!(
360                    "a `Quosure` of a bare expression is built with `rlang::new_quosure()`, \
361                     which needs the rlang package: {e}"
362                )
363            })
364    }
365}
366
367/// `new_quosure(quote(<expr>), env)`, unprotected.
368///
369/// # Safety
370///
371/// R's main thread; `new_quosure` (from [`rlang_new_quosure`]), `expr` and
372/// `env` rooted, `env` an environment.
373unsafe fn wrap_in_quosure(new_quosure: SEXP, expr: SEXP, env: SEXP) -> SEXP {
374    unsafe {
375        RCall::from_sexp(new_quosure)
376            .quoted_arg(expr)
377            .arg(env)
378            .eval(crate::sys::R_BaseEnv)
379            .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("`rlang::new_quosure()` failed: {0}",
            e));
}panic!("`rlang::new_quosure()` failed: {e}"))
380    }
381}
382
383/// An argument captured as an rlang quosure, `rlang::enquo(x)`: its expression
384/// and environment, with rlang's argument forwarding and injection resolved.
385///
386/// Take it as a `#[miniextendr]` parameter. The generated wrapper keeps the
387/// parameter as an R formal and passes
388/// `if (missing(x)) quote(expr=) else rlang::enquo(x)`, which never forces the
389/// argument. Unlike [`Quoted`], a wrapper reached through
390/// `function(col) f(data, {{ col }})` or called as `f(data, !!sym)` receives
391/// the expression the user wrote, in the user's environment.
392///
393/// **The package must list rlang in `Imports`.** The macro cannot see
394/// `DESCRIPTION`; without rlang the wrapper fails when it is called.
395///
396/// The expression and environment are read from the quosure directly (a
397/// quosure is a one-sided formula, `~expr`, of class `quosure` whose
398/// environment is its `.Environment` attribute), so [`Self::expr`],
399/// [`Self::env`] and [`Self::as_name`] call no R code.
400/// [`Self::eval_tidy`] evaluates through `rlang::eval_tidy()`, which resolves
401/// nested quosures and the `.data` / `.env` pronouns. Hand [`Self::sexp`] to
402/// other quosure-aware R functions (`tidyselect::eval_select()`) with
403/// [`RCall::eval_with_handlers`].
404///
405/// An argument holding several selections, a role map such as
406/// `cols = c(time = TAD, dose = NA)`, reads entry by entry with
407/// [`Self::args`]: each argument of the call as a quosure of its own. A
408/// quosure found in an R object reads with [`Self::from_sexp`], and
409/// [`Self::new`] makes one from an expression and an environment.
410pub struct Quosure<'a> {
411    quo: SEXP,
412    expr: SEXP,
413    env: SEXP,
414    /// Borrows the root that keeps the quosure alive: the `.Call()` argument,
415    /// the SEXP it was read from, or a [`ProtectScope`].
416    _arg: PhantomData<&'a SEXP>,
417    /// R objects stay on R's main thread.
418    _not_send: PhantomData<*const ()>,
419}
420
421impl<'a> Quosure<'a> {
422    /// Read a quosure's expression and environment.
423    ///
424    /// # Safety
425    ///
426    /// R's main thread; `quo` is a quosure, rooted for `'a`.
427    unsafe fn read(quo: SEXP) -> Self {
428        let expr = quo.cdr().car();
429        let env = quo.get_attr(unsafe { crate::sys::Rf_install(c".Environment".as_ptr()) });
430        Quosure {
431            quo,
432            expr,
433            env,
434            _arg: PhantomData,
435            _not_send: PhantomData,
436        }
437    }
438
439    /// Read the argument a generated wrapper passed for a `Quosure` parameter:
440    /// `None` when the argument is missing (`quote(expr=)`, or a quosure of
441    /// the missing argument, which `{{ x }}` gives for a missing `x`).
442    /// Generated code calls this; user code has no reason to.
443    ///
444    /// # Panics
445    ///
446    /// When `arg` is not a quosure.
447    ///
448    /// # Safety
449    ///
450    /// R's main thread; `arg` stays rooted for `'a`.
451    #[doc(hidden)]
452    pub unsafe fn from_wrapper_arg(arg: &'a SEXP) -> Option<Self> {
453        let quo = *arg;
454        if quo == SEXP::missing_arg() {
455            return None;
456        }
457        if !is_quosure(quo) {
    {
        ::core::panicking::panic_fmt(format_args!("a `Quosure` argument is passed as `rlang::enquo(x)`, got {0}",
                quo.type_of().type_name()));
    }
};assert!(
458            is_quosure(quo),
459            "a `Quosure` argument is passed as `rlang::enquo(x)`, got {}",
460            quo.type_of().type_name(),
461        );
462        let quosure = unsafe { Self::read(quo) };
463        (quosure.expr != SEXP::missing_arg()).then_some(quosure)
464    }
465
466    /// [`Self::from_wrapper_arg`] for a `Missing<Quosure>` parameter.
467    ///
468    /// # Safety
469    ///
470    /// As [`Self::from_wrapper_arg`].
471    #[doc(hidden)]
472    pub unsafe fn missing_from_wrapper_arg(arg: &'a SEXP) -> Missing<Self> {
473        match unsafe { Self::from_wrapper_arg(arg) } {
474            Some(quosure) => Missing::Present(quosure),
475            None => Missing::Absent,
476        }
477    }
478
479    /// Read a quosure the caller holds: `None` when `sexp` is not one.
480    ///
481    /// A quosure whose expression is a quosure too, which
482    /// `rlang::new_quosure(<quosure>)` makes, is looked through: the result is
483    /// the innermost one, which is what the outer one evaluates to and what
484    /// `tidyselect::eval_select()` accepts (it refuses the outer one). A
485    /// quosure of the missing argument is read as it is: [`Self::expr`] is
486    /// [`SEXP::missing_arg()`].
487    ///
488    /// ```ignore
489    /// // `call` is the expression of a `Quosure` argument,
490    /// // `c(time = {{ t }})` written by a forwarding wrapper.
491    /// for (name, arg) in call.args() {
492    ///     if let Some(quosure) = unsafe { Quosure::from_sexp(&arg) } {
493    ///         // the quosure `{{ t }}` left in the call, as it is
494    ///     }
495    /// }
496    /// ```
497    ///
498    /// # Safety
499    ///
500    /// R's main thread, inside a miniextendr boundary (a `#[miniextendr]`
501    /// body, a `with_r_unwind_protect` closure; [`Self::eval_tidy`] needs
502    /// one); `sexp` stays rooted for `'a`.
503    pub unsafe fn from_sexp(sexp: &'a SEXP) -> Option<Self> {
504        innermost_quosure(*sexp).map(|quo| unsafe { Self::read(quo) })
505    }
506
507    /// A quosure of `expr` in `env`, rooted by `scope`.
508    ///
509    /// A bare expression is wrapped with `rlang::new_quosure(expr, env)`. A
510    /// quosure is returned as it is, through [`Self::from_sexp`] (`env` is
511    /// not used): wrapping a quosure again makes a formula that
512    /// `tidyselect::eval_select()` refuses. So an argument read from a call
513    /// can go through `new()` whether or not a wrapper wrote a quosure there.
514    /// The missing argument (an empty argument, `c(a = )`) is wrapped too:
515    /// [`Self::expr`] is then [`SEXP::missing_arg()`].
516    ///
517    /// Each call protects one value in `scope`.
518    ///
519    /// # Panics
520    ///
521    /// When `env` is not an environment, or when `expr` is not a quosure and
522    /// rlang cannot be loaded (a package taking a [`Quosure`] lists rlang in
523    /// `Imports`).
524    ///
525    /// # Safety
526    ///
527    /// As [`Self::from_sexp`]; `expr` and `env` are rooted by the caller for
528    /// the call.
529    pub unsafe fn new(expr: SEXP, env: SEXP, scope: &'a ProtectScope) -> Self {
530        if !env.is_environment() {
    {
        ::core::panicking::panic_fmt(format_args!("`Quosure::new()` takes an environment as `env`, not {0}",
                env.type_of().type_name()));
    }
};assert!(
531            env.is_environment(),
532            "`Quosure::new()` takes an environment as `env`, not {}",
533            env.type_of().type_name(),
534        );
535        let quo = match innermost_quosure(expr) {
536            Some(quo) => quo,
537            // The function's guard drops before `scope` protects the quosure,
538            // so the protect stack unwinds in order; nothing allocates between.
539            None => unsafe {
540                let new_quosure = OwnedProtect::new(rlang_new_quosure());
541                wrap_in_quosure(new_quosure.get(), expr, env)
542            },
543        };
544        unsafe { Self::read(scope.protect_raw(quo)) }
545    }
546
547    /// The arguments of the quosure's call, each as a quosure with its name,
548    /// rooted by `scope`; `None` when the expression is not a call.
549    ///
550    /// `c(time = TAD, dose = NA)` gives `(Some("time"), TAD)` and
551    /// `(Some("dose"), NA)`, each in this quosure's environment. An argument
552    /// a wrapper wrote as a quosure (`c(time = {{ t }})`) comes back as it is,
553    /// in its own environment, as [`Self::new`] returns it; any other is
554    /// wrapped in this quosure's environment with `rlang::new_quosure()`. The
555    /// name is `None` for an unnamed argument; the function (`c`) is not one
556    /// of the arguments.
557    ///
558    /// ```ignore
559    /// #[miniextendr]
560    /// pub fn roles(data: SEXP, cols: Quosure) -> Vec<String> {
561    ///     let scope = unsafe { ProtectScope::new() };
562    ///     let Some(args) = cols.args(&scope) else {
563    ///         panic!("`cols` must be a call, `c(role = column, ...)`");
564    ///     };
565    ///     for (role, quosure) in args {
566    ///         // `quosure.expr()` is `NA` / `NULL` as written; hand the others
567    ///         // to `tidyselect::eval_select()`.
568    ///     }
569    /// #   vec![]
570    /// }
571    /// ```
572    ///
573    /// All the quosures are held in one list, which `scope` protects.
574    ///
575    /// # Panics
576    ///
577    /// As [`Self::new`]: when an argument is not a quosure and rlang cannot
578    /// be loaded.
579    pub fn args<'s>(
580        &'s self,
581        scope: &'s ProtectScope,
582    ) -> Option<Vec<(Option<&'s str>, Quosure<'s>)>> {
583        if !self.expr.is_language() {
584            return None;
585        }
586        let args: Vec<(Option<&'s str>, SEXP)> = self.expr.args().collect();
587        // SAFETY: a `Quosure` exists only on R's main thread, rooted for
588        // `'a`: so are its call and the arguments in it. Each quosure is
589        // stored in `held` as it is made, and `held` is protected by `scope`
590        // before the function's guard, which drops first.
591        unsafe {
592            let held = scope.alloc_vecsxp(args.len()).into_raw();
593            let mut new_quosure: Option<OwnedProtect> = None;
594            for (i, &(_, arg)) in args.iter().enumerate() {
595                let quo = match innermost_quosure(arg) {
596                    Some(quo) => quo,
597                    None => {
598                        let new_quosure = new_quosure
599                            .get_or_insert_with(|| OwnedProtect::new(rlang_new_quosure()));
600                        wrap_in_quosure(new_quosure.get(), arg, self.env)
601                    }
602                };
603                held.set_vector_elt(r_index(i), quo);
604            }
605            drop(new_quosure);
606            Some(
607                args.into_iter()
608                    .enumerate()
609                    .map(|(i, (name, _))| (name, Quosure::read(held.vector_elt(r_index(i)))))
610                    .collect(),
611            )
612        }
613    }
614
615    /// The quosure itself, for R functions that take one
616    /// (`rlang::eval_tidy()`, `tidyselect::eval_select()`).
617    #[inline]
618    pub fn sexp(&self) -> SEXP {
619        self.quo
620    }
621
622    /// The quosure's expression (`rlang::quo_get_expr()`).
623    #[inline]
624    pub fn expr(&self) -> SEXP {
625        self.expr
626    }
627
628    /// The quosure's environment (`rlang::quo_get_env()`): the empty
629    /// environment for a constant.
630    #[inline]
631    pub fn env(&self) -> SEXP {
632        self.env
633    }
634
635    /// The name the argument stands for: `TIME`, `"TIME"`, `{{ col }}` with
636    /// `col = TIME` and `!!rlang::sym("TIME")` all give `"TIME"`. A quosure
637    /// nested in the expression is looked through. `None` for any other
638    /// expression.
639    ///
640    /// # Errors
641    ///
642    /// A name that is not text: a string marked as bytes (`!!x` with
643    /// `Encoding(x) == "bytes"`), or one that is not valid UTF-8.
644    pub fn as_name(&self) -> Result<Option<&'a str>, SexpError> {
645        let mut expr = self.expr;
646        while is_quosure(expr) {
647            expr = expr.cdr().car();
648        }
649        expr_name(expr)
650    }
651
652    /// Evaluate the quosure with `data` as a data mask,
653    /// `rlang::eval_tidy(quo, data)`: columns of `data` win over variables of
654    /// the same name in the quosure's environment, and `.data$x` / `.env$x`
655    /// pick one side. `data` may be `NULL`.
656    ///
657    /// Evaluated with
658    /// [`eval_with_handlers`](crate::expression::eval_with_handlers), so the
659    /// caller's handlers see what the expression signals.
660    ///
661    /// The value is unprotected: protect it before the next allocation.
662    pub fn eval_tidy(&self, data: SEXP) -> SEXP {
663        // SAFETY: a `Quosure` exists only inside a miniextendr boundary on
664        // R's main thread (the `#[miniextendr]` call that received it, or
665        // the caller of `from_sexp` / `new`); `data` is rooted by the caller.
666        unsafe { self.eval_tidy_with(data, crate::expression::eval_with_handlers) }
667    }
668
669    /// [`eval_tidy`](Self::eval_tidy) with an R error returned as `Err`, as
670    /// [`try_eval_with_handlers`](crate::expression::try_eval_with_handlers)
671    /// returns it: the caller's handlers still see the quosure's warnings and
672    /// messages. A missing rlang is an `Err` too.
673    ///
674    /// The value is unprotected: protect it before the next allocation.
675    pub fn try_eval_tidy(&self, data: SEXP) -> Result<SEXP, crate::expression::REvalError> {
676        // SAFETY: as in `eval_tidy`.
677        unsafe { self.eval_tidy_with(data, crate::expression::try_eval_with_handlers) }
678    }
679
680    /// `rlang::eval_tidy(quo, data)` evaluated by `eval`.
681    ///
682    /// # Safety
683    ///
684    /// As `eval_tidy`'s: R's main thread, inside a miniextendr boundary;
685    /// `data` rooted by the caller.
686    unsafe fn eval_tidy_with<R>(&self, data: SEXP, eval: unsafe fn(SEXP, SEXP) -> R) -> R {
687        use crate::sys::{R_BaseEnv, Rf_install, Rf_lang2, Rf_lang3};
688        unsafe {
689            let scope = ProtectScope::new();
690            // `rlang::eval_tidy(quote(<quo>), quote(<data>))`; a missing rlang raises
691            // R's own error, through the caller's handlers.
692            let fun = scope.protect_raw(Rf_lang3(
693                Rf_install(c"::".as_ptr()),
694                Rf_install(c"rlang".as_ptr()),
695                Rf_install(c"eval_tidy".as_ptr()),
696            ));
697            // Both arguments pass through `quote()`, so neither the quosure
698            // nor a language `data` is evaluated on the way in.
699            let quote = Rf_install(c"quote".as_ptr());
700            let quoted = scope.protect_raw(Rf_lang2(quote, self.quo));
701            let data = scope.protect_raw(Rf_lang2(quote, data));
702            let call = scope.protect_raw(Rf_lang3(fun, quoted, data));
703            eval(call, R_BaseEnv)
704        }
705    }
706}
707
708/// An R vector index.
709fn r_index(i: usize) -> isize {
710    isize::try_from(i).expect("an R vector index fits in isize")
711}
712
713// endregion
714
715#[cfg(test)]
716mod tests;