Skip to main content

miniextendr_api/
missing.rs

1//! Support for R's missing arguments.
2//!
3//! When an R function is called without providing a value for a formal argument,
4//! R passes `SEXP::missing_arg()` as a placeholder. This is different from `NULL` -
5//! a missing argument means "not provided", while `NULL` is an explicit value.
6//!
7//! # Example
8//!
9//! ```ignore
10//! use miniextendr_api::{miniextendr, Missing};
11//!
12//! #[miniextendr]
13//! fn greet(name: Missing<String>) -> String {
14//!     match name.into_option() {
15//!         Some(n) => format!("Hello, {}!", n),
16//!         None => "Hello, stranger!".to_string(),
17//!     }
18//! }
19//! ```
20//!
21//! In R:
22//! ```r
23//! greet("Alice")  # "Hello, Alice!"
24//! greet()         # "Hello, stranger!"
25//! ```
26//!
27//! # Difference from `Option<T>`
28//!
29//! - `Option<T>` treats `NULL` as `None` and any other value as `Some(T)`.
30//! - `Missing<T>` treats `SEXP::missing_arg()` as missing and any other value (including `NULL`) as present.
31//!
32//! Use `Missing<Option<T>>` if you need to distinguish between:
33//! - Missing argument (not passed)
34//! - `NULL` (explicitly passed `NULL`)
35//! - A value (explicitly passed a non-NULL value)
36//!
37//! # How it works: the `quote(expr=)` sentinel
38//!
39//! In regular R functions, you detect missing arguments with `missing()`:
40//!
41//! ```r
42//! my_func <- function(x) {
43//!   if (missing(x)) "not provided" else x
44//! }
45//! my_func()   # "not provided"
46//! my_func(5)  # 5
47//! ```
48//!
49//! However, `.Call()` (the FFI boundary) forces argument evaluation, so an
50//! omitted argument errors before the call even reaches Rust:
51//!
52//! ```r
53//! wrapper <- function(x) .Call(rust_fn, x)
54//! wrapper()  # Error: argument "x" is missing, with no default
55//! ```
56//!
57//! The generated R wrapper tests `missing()` at the argument position of the
58//! `.Call()`:
59//!
60//! ```r
61//! wrapper <- function(x) .Call(rust_fn, if (missing(x)) quote(expr=) else x)
62//! ```
63//!
64//! `quote(expr=)` is an R idiom for the "missing" state: calling `quote()`
65//! without its `expr` argument returns `SEXP::missing_arg()`. The call
66//! proceeds, the sentinel passes through `.Call()`, and `Missing<T>` reads it
67//! as `Missing::Absent`. Only the argument position may hold the sentinel: a
68//! variable bound to it errors on lookup.
69//!
70//! # A default on `Missing<T>`
71//!
72//! `#[miniextendr(default = "...")]` on a `Missing<T>` parameter (or
73//! `defaults(x = "...")` on a method) only writes the formal, so the usage
74//! line shows the value the function stands for when the argument is left
75//! out:
76//!
77//! ```r
78//! wrapper <- function(tol = 1e-8) .Call(rust_fn, if (missing(tol)) quote(expr=) else tol)
79//! ```
80//!
81//! `missing(tol)` is `TRUE` for an omitted argument even when the formal has
82//! a default, so an omitted argument still reaches Rust as `Missing::Absent`
83//! and the default is never evaluated. The Rust code decides what absence
84//! means; the default in the formal documents it.
85//!
86//! A supplied value is always `Missing::Present`, even one `identical()` to
87//! the default: R's `missing(x)` is `FALSE` once the caller supplies `x`, and
88//! a caller who writes `wrapper(tol = 1e-8)` may mean that value. A caller
89//! forwarding its own formal, `function(tol = 1e-8) wrapper(tol)`, hands its
90//! default over as a value too. This differs from a single-choice
91//! `match_arg` / `choices` parameter under `Missing<..>`, whose formal is the
92//! whole choice vector: that vector is never one valid choice, so passing it
93//! whole reads as omitted. Such a choice parameter takes no `default`.
94
95use crate::SEXP;
96use crate::from_r::prepared::{Arms, Prepared};
97use crate::from_r::{SexpError, TryFromSexp};
98
99/// Wrapper type that detects if an R argument was not passed (missing).
100///
101/// This corresponds to R's `missing()` function. When a function parameter
102/// has type `Missing<T>`, it will be `Missing::Absent` if the caller didn't
103/// provide that argument, or `Missing::Present(value)` if they did.
104///
105/// # Example
106///
107/// ```ignore
108/// use miniextendr_api::{miniextendr, Missing};
109///
110/// #[miniextendr]
111/// fn maybe_square(x: Missing<f64>) -> f64 {
112///     match x {
113///         Missing::Present(val) => val * val,
114///         Missing::Absent => 0.0,
115///     }
116/// }
117/// ```
118///
119/// In R:
120/// ```r
121/// maybe_square(5)  # 25
122/// maybe_square()   # 0
123/// ```
124#[derive(#[automatically_derived]impl<T: ::core::fmt::Debug> ::core::fmt::Debug for
    Missing<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Present(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Present", &__self_0),
            Self::Absent => ::core::fmt::Formatter::write_str(f, "Absent"),
        }
    }
}Debug, #[automatically_derived]impl<T: ::core::clone::Clone> ::core::clone::Clone for
    Missing<T> {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            Self::Present(__self_0) =>
                Missing::Present(::core::clone::Clone::clone(__self_0)),
            Self::Absent => Missing::Absent,
        }
    }
}Clone, #[automatically_derived]impl<T: ::core::marker::Copy> ::core::marker::Copy for
    Missing<T> {
}Copy, #[automatically_derived]impl<T: ::core::cmp::PartialEq>
    ::core::marker::StructuralPartialEq for Missing<T> {
}
#[automatically_derived]impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq
    for Missing<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Present(__self_0), Self::Present(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl<T: ::core::cmp::Eq> ::core::cmp::Eq for
    Missing<T> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) { let _: ::core::cmp::AssertParamIsEq<T>; }
}Eq)]
125pub enum Missing<T> {
126    /// The argument was provided.
127    Present(T),
128    /// The argument was not provided (missing in R).
129    Absent,
130}
131
132impl<T> Missing<T> {
133    /// Returns `true` if the argument was provided.
134    #[inline]
135    pub fn is_present(&self) -> bool {
136        #[allow(non_exhaustive_omitted_patterns)] match self {
    Missing::Present(_) => true,
    _ => false,
}matches!(self, Missing::Present(_))
137    }
138
139    /// Returns `true` if the argument was not provided.
140    ///
141    /// Named to match R's `missing()` function.
142    #[inline]
143    pub fn is_missing(&self) -> bool {
144        #[allow(non_exhaustive_omitted_patterns)] match self {
    Missing::Absent => true,
    _ => false,
}matches!(self, Missing::Absent)
145    }
146
147    /// Convert to `Option<T>`, returning `None` if missing.
148    #[inline]
149    pub fn into_option(self) -> Option<T> {
150        match self {
151            Missing::Present(v) => Some(v),
152            Missing::Absent => None,
153        }
154    }
155
156    /// Get a reference to the value if present.
157    #[inline]
158    pub fn as_ref(&self) -> Missing<&T> {
159        match self {
160            Missing::Present(v) => Missing::Present(v),
161            Missing::Absent => Missing::Absent,
162        }
163    }
164
165    /// Get a mutable reference to the value if present.
166    #[inline]
167    pub fn as_mut(&mut self) -> Missing<&mut T> {
168        match self {
169            Missing::Present(v) => Missing::Present(v),
170            Missing::Absent => Missing::Absent,
171        }
172    }
173
174    /// Returns the contained value or a default.
175    #[inline]
176    pub fn unwrap_or(self, default: T) -> T {
177        match self {
178            Missing::Present(v) => v,
179            Missing::Absent => default,
180        }
181    }
182
183    /// Returns the contained value or computes it from a closure.
184    #[inline]
185    pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
186        match self {
187            Missing::Present(v) => v,
188            Missing::Absent => f(),
189        }
190    }
191
192    /// Maps `Missing<T>` to `Missing<U>` by applying a function.
193    #[inline]
194    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Missing<U> {
195        match self {
196            Missing::Present(v) => Missing::Present(f(v)),
197            Missing::Absent => Missing::Absent,
198        }
199    }
200
201    /// Returns the contained value, panicking if absent.
202    ///
203    /// # Panics
204    ///
205    /// Panics if the value is `Absent`.
206    #[inline]
207    pub fn unwrap(self) -> T {
208        match self {
209            Missing::Present(v) => v,
210            Missing::Absent => {
    ::core::panicking::panic_fmt(format_args!("called `Missing::unwrap()` on an `Absent` value"));
}panic!("called `Missing::unwrap()` on an `Absent` value"),
211        }
212    }
213
214    /// Returns the contained value, panicking with a custom message if absent.
215    ///
216    /// # Panics
217    ///
218    /// Panics with the provided message if the value is `Absent`.
219    #[inline]
220    pub fn expect(self, msg: &str) -> T {
221        match self {
222            Missing::Present(v) => v,
223            Missing::Absent => { ::core::panicking::panic_display(&msg); }panic!("{}", msg),
224        }
225    }
226}
227
228impl<T: Default> Missing<T> {
229    /// Returns the contained value or the default for that type.
230    #[inline]
231    pub fn unwrap_or_default(self) -> T {
232        match self {
233            Missing::Present(v) => v,
234            Missing::Absent => T::default(),
235        }
236    }
237}
238
239impl<T> Default for Missing<T> {
240    /// The default is `Absent`.
241    #[inline]
242    fn default() -> Self {
243        Missing::Absent
244    }
245}
246
247impl<T> From<T> for Missing<T> {
248    #[inline]
249    fn from(value: T) -> Self {
250        Missing::Present(value)
251    }
252}
253
254impl<T> From<Option<T>> for Missing<T> {
255    #[inline]
256    fn from(opt: Option<T>) -> Self {
257        match opt {
258            Some(v) => Missing::Present(v),
259            None => Missing::Absent,
260        }
261    }
262}
263
264impl<T> From<Missing<T>> for Option<T> {
265    #[inline]
266    fn from(missing: Missing<T>) -> Self {
267        missing.into_option()
268    }
269}
270
271// region: TryFromSexp implementation
272
273/// Check if a SEXP is the missing argument sentinel.
274#[inline]
275pub fn is_missing_arg(sexp: SEXP) -> bool {
276    std::ptr::addr_eq(sexp.0, SEXP::missing_arg().0)
277}
278
279/// Read an argument that may be the missing-argument sentinel: the sentinel
280/// is `Missing::Absent`, any other value `read`'s result as
281/// `Missing::Present`. For generated code that converts a `Missing<T>`
282/// parameter with its own reader instead of `T`'s `TryFromSexp`: a `coerce`
283/// parameter's coerced helper (#2274), a choice parameter's decoder
284/// ([`match_arg_missing_or`](crate::match_arg_missing_or)).
285#[doc(hidden)]
286#[inline]
287pub fn __mx_missing_or<T, E>(
288    sexp: SEXP,
289    read: impl FnOnce(SEXP) -> Result<T, E>,
290) -> Result<Missing<T>, E> {
291    if is_missing_arg(sexp) {
292        Ok(Missing::Absent)
293    } else {
294        read(sexp).map(Missing::Present)
295    }
296}
297
298impl<T> TryFromSexp for Missing<T>
299where
300    T: TryFromSexp,
301    <T as TryFromSexp>::Error: Into<SexpError>,
302{
303    const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = T::NATIVE_BORROW;
304    const CHARACTER_ONLY: bool = T::CHARACTER_ONLY;
305
306    type Error = SexpError;
307    // An omitted argument passes `no_na`.
308    #[inline]
309    fn __mx_has_na(&self) -> bool {
310        #[allow(non_exhaustive_omitted_patterns)] match self {
    Missing::Present(v) if v.__mx_has_na() => true,
    _ => false,
}matches!(self, Missing::Present(v) if v.__mx_has_na())
311    }
312
313    // A given argument is read by its value's type (an `Either` asks the arm
314    // it converted to).
315    #[inline]
316    fn __mx_input_has_na(&self, input: SEXP) -> bool {
317        #[allow(non_exhaustive_omitted_patterns)] match self {
    Missing::Present(v) if v.__mx_input_has_na(input) => true,
    _ => false,
}matches!(self, Missing::Present(v) if v.__mx_input_has_na(input))
318    }
319
320    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
321        if is_missing_arg(sexp) {
322            Ok(Missing::Absent)
323        } else {
324            T::try_from_sexp(sexp)
325                .map(Missing::Present)
326                .map_err(Into::into)
327        }
328    }
329
330    unsafe fn try_from_sexp_unchecked(sexp: SEXP) -> Result<Self, Self::Error> {
331        if is_missing_arg(sexp) {
332            Ok(Missing::Absent)
333        } else {
334            unsafe { T::try_from_sexp_unchecked(sexp) }
335                .map(Missing::Present)
336                .map_err(Into::into)
337        }
338    }
339
340    // An omitted argument is ready; a given one prepares as `T`, so an
341    // `Either` inside learns its arm (#1504).
342    fn __mx_prepare(sexp: SEXP) -> Prepared<Self> {
343        if is_missing_arg(sexp) {
344            Prepared::Ready(Missing::Absent)
345        } else {
346            T::__mx_prepare(sexp).map(Missing::Present, Into::into)
347        }
348    }
349
350    fn __mx_materialize(sexp: SEXP, arms: Arms) -> Result<Self, Self::Error> {
351        T::__mx_materialize(sexp, arms)
352            .map(Missing::Present)
353            .map_err(Into::into)
354    }
355}
356
357#[cfg(test)]
358mod tests;
359// endregion