Skip to main content

miniextendr_macros/
r_wrapper_builder.rs

1//! Shared utilities for building R wrapper code.
2//!
3//! This module provides builders for constructing R function signatures and call arguments
4//! consistently across both standalone functions and impl methods.
5//!
6//! ## Key Components
7//!
8//! - [`RArgumentBuilder`]: Builds R formals and `.Call()` arguments from Rust signatures
9//! - [`DotCallBuilder`]: Formats `.Call()` invocations with proper argument handling
10//! - [`RoxygenBuilder`]: Generates roxygen2 documentation tags
11//!
12//! ## Usage
13//!
14//! ```ignore
15//! // Build R function signature
16//! let formals = build_r_formals_from_sig(&method.sig, &r_formals, &defaults);
17//! let call_args = build_r_call_args_from_sig(&method.sig, &r_formals, absent_formals);
18//!
19//! // Build .Call() invocation
20//! let call = DotCallBuilder::new("C_MyType__method")
21//!     .with_self("self")
22//!     .with_args(&["x", "y"])
23//!     .build();
24//!
25//! // Build roxygen tags
26//! let tags = RoxygenBuilder::new("MyType")
27//!     .name("method")
28//!     .rdname("MyType")
29//!     .export()
30//!     .build();
31//! ```
32
33/// Normalizes a Rust argument name (its [`crate::naming::ident_name`], no
34/// `r#`) for R.
35///
36/// - Leading `_` → stripped (Rust convention for unused params)
37/// - Leading `__` → stripped
38/// - Otherwise → unchanged
39///
40/// # Examples
41/// - `_x` → `x`
42/// - `_to` → `to`
43/// - `__field` → `field`
44/// - `value` → `value`
45///
46/// Note: We strip underscores rather than prefixing "unused" because R callers
47/// (like vctrs) may use named arguments that must match the original name.
48///
49/// This is the R formal of a parameter without a declared `formal = ".."`
50/// only: R-facing names come from [`Formals::of`], which applies it.
51pub fn normalize_r_arg_string(name: &str) -> String {
52    let normalized = name.trim_start_matches('_');
53    if normalized.is_empty() {
54        "arg".to_string()
55    } else {
56        normalized.to_string()
57    }
58}
59
60/// The R formal of each parameter of one signature (#1842).
61///
62/// A parameter declared with `formal = "conf.int"` (a standalone function's
63/// per-parameter option, a method's `formal(conf_int = "conf.int")`) has that
64/// formal; every other one has [`normalize_r_arg_string`] of its Rust name.
65/// [`Formals::of`] is the one place that rule lives: every site that writes a
66/// parameter's name into R text (the formals, the `.Call()` arguments, the
67/// argument checks and their errors, `e$param` of a conversion error, the
68/// `@param` lines) asks it. Maps keyed by Rust name (the per-parameter
69/// options) stay keyed by Rust name, and so do the `match_arg` placeholders,
70/// which the wrapper writer replaces before R reads them.
71///
72/// A declared formal may hold a `.`, which no Rust identifier can, so it is
73/// only ever a string: never an identifier, and never part of one.
74#[derive(#[automatically_derived]impl ::core::clone::Clone for Formals {
    #[inline]
    fn clone(&self) -> Self {
        Formals { declared: ::core::clone::Clone::clone(&self.declared) }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Formals {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "Formals declared", &&self.declared)
    }
}Debug, #[automatically_derived]impl ::core::default::Default for Formals {
    #[inline]
    fn default() -> Self {
        Formals { declared: ::core::default::Default::default() }
    }
}Default)]
75pub(crate) struct Formals {
76    /// The declared formals, keyed by Rust parameter name
77    /// ([`crate::naming::ident_name`]), each with the literal that declared
78    /// it (where its errors point).
79    declared: std::collections::HashMap<String, syn::LitStr>,
80}
81
82impl Formals {
83    /// The formals the per-parameter options of one signature declare.
84    pub(crate) fn from_param_attrs(
85        per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
86    ) -> Self {
87        Self {
88            declared: per_param
89                .iter()
90                .filter_map(|(name, attrs)| Some((name.clone(), attrs.formal.clone()?)))
91                .collect(),
92        }
93    }
94
95    /// The R formal of the parameter whose Rust name is `rust_name`: its
96    /// declared formal, else the name without leading underscores.
97    pub(crate) fn of(&self, rust_name: &str) -> String {
98        match self.declared.get(rust_name) {
99            Some(formal) => formal.value(),
100            None => normalize_r_arg_string(rust_name),
101        }
102    }
103
104    /// [`Self::of`] the parameter `ident` (`r#` dropped).
105    pub(crate) fn of_ident(&self, ident: &syn::Ident) -> String {
106        self.of(&crate::naming::ident_name(ident))
107    }
108
109    /// The literal that declared the formal of `rust_name`, if one did.
110    pub(crate) fn declared(&self, rust_name: &str) -> Option<&syn::LitStr> {
111        self.declared.get(rust_name)
112    }
113
114    /// `map` with each key, a Rust parameter name, replaced by that
115    /// parameter's R formal: for maps keyed by Rust name (a function's
116    /// `default = ".."`, a method's `defaults(p = "..")`) that feed a builder
117    /// keyed by R formal.
118    pub(crate) fn rekey<V>(
119        &self,
120        map: impl IntoIterator<Item = (String, V)>,
121    ) -> std::collections::HashMap<String, V> {
122        map.into_iter()
123            .map(|(rust_name, value)| (self.of(&rust_name), value))
124            .collect()
125    }
126}
127
128/// The R names a declared formal must not take, beyond R's own syntax rules:
129/// the names the generated wrapper binds or reads in the function's frame
130/// (#1842). Another dotted name is the framework's only when it starts with
131/// one of [`FRAMEWORK_FORMAL_PREFIXES`].
132const FRAMEWORK_FORMALS: &[(&str, &str)] = &[
133    (
134        ".call",
135        "is the call the generated wrapper passes to `.Call()`",
136    ),
137    (
138        ".val",
139        "is where the generated wrapper keeps the result of `.Call()`",
140    ),
141    (
142        ".ptr",
143        "is the pointer argument of a generated class constructor",
144    ),
145    (
146        ".Generic",
147        "is bound by R's S3 dispatch in a method's frame",
148    ),
149    (".Class", "is bound by R's S3 dispatch in a method's frame"),
150    (".Method", "is bound by R's S3 dispatch in a method's frame"),
151    (".Group", "is bound by R's S3 dispatch in a method's frame"),
152    (
153        ".GenericCallEnv",
154        "is bound by R's S3 dispatch in a method's frame",
155    ),
156    (
157        ".GenericDefEnv",
158        "is bound by R's S3 dispatch in a method's frame",
159    ),
160];
161
162/// Prefixes of the R names the framework generates (locals such as
163/// `.mx_call` and `.mx_self`, the wrappers preamble's `.miniextendr_*`
164/// helpers, the `.rdata_*` helpers `#[derive(ExternalPtr)]` writes for a
165/// sidecar, the write-time `.__MX_*` placeholders): a declared formal starting
166/// with one is refused.
167const FRAMEWORK_FORMAL_PREFIXES: &[&str] = &[".mx_", ".miniextendr_", ".rdata_", ".__MX_"];
168
169/// Why `formal` can't be a declared formal, or `None` when it can: it must be
170/// a syntactic R name ([`crate::naming::is_syntactic_r_name`]: letters,
171/// digits, `.` and `_`, not starting with a digit, `_` or `.` and a digit, and
172/// not a reserved word), not `...` or `..1` (R's dots), and none of the names
173/// the generated wrapper binds itself ([`FRAMEWORK_FORMALS`],
174/// [`FRAMEWORK_FORMAL_PREFIXES`]).
175pub(crate) fn declared_formal_problem(formal: &str) -> Option<String> {
176    if formal.is_empty() {
177        return Some("is empty".to_string());
178    }
179    if formal.starts_with("..") {
180        return Some(
181            "is R's `...` or one of its elements (`..1`, `..2`, ...), not an argument name"
182                .to_string(),
183        );
184    }
185    if crate::naming::is_r_reserved_word(formal) {
186        return Some("is an R reserved word".to_string());
187    }
188    if !crate::naming::is_syntactic_r_name(formal) {
189        return Some(
190            "is not a syntactic R name: it must start with a letter, or with a `.` that is not \
191             followed by a digit, and hold only ASCII letters, digits, `.` and `_`"
192                .to_string(),
193        );
194    }
195    if let Some((_, role)) = FRAMEWORK_FORMALS.iter().find(|(name, _)| *name == formal) {
196        return Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, so the generated wrapper can\'t take it",
                role))
    })format!("{role}, so the generated wrapper can't take it"));
197    }
198    FRAMEWORK_FORMAL_PREFIXES
199        .iter()
200        .find(|prefix| formal.starts_with(*prefix))
201        .map(|prefix| {
202            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("starts with `{0}`, a prefix of the names the framework generates, so the generated wrapper can\'t take it",
                prefix))
    })format!(
203                "starts with `{prefix}`, a prefix of the names the framework generates, so \
204                 the generated wrapper can't take it"
205            )
206        })
207}
208
209/// Check the R formals a signature produces, before any wrapper is generated.
210///
211/// Each parameter becomes its formal ([`Formals::of`]: the declared
212/// `formal = ".."`, else [`normalize_r_arg_string`] of its name); the `&Dots`
213/// parameter becomes `...`, wherever it sits, and is skipped. A formal must be
214/// an R name (not a reserved word such as `if` or `in`, not starting with a
215/// digit; a declared one must pass [`declared_formal_problem`]), distinct
216/// from the others (`x` and `_x` both become `x`), and not one of the
217/// `reserved` names the generated wrapper binds itself (a method's receiver,
218/// R6's `self` and `private`), each paired with what it is. Any of these would
219/// break the wrapper: a parse error in the wrappers file, or a parameter that
220/// hides the object the method works on.
221///
222/// Every case is a compile error rather than a rename: callers pass arguments
223/// by name, so the R formal has to stay the parameter's own name unless the
224/// author declares another. An error points at the declaring literal for a
225/// declared formal, else at the parameter. Every problem of the signature is
226/// reported, in one combined error.
227pub(crate) fn check_r_formals(
228    inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
229    formals: &Formals,
230    reserved: &[(String, String)],
231) -> syn::Result<()> {
232    let mut errors: Option<syn::Error> = None;
233    let mut push = |error: syn::Error| match errors.as_mut() {
234        Some(all) => all.combine(error),
235        None => errors = Some(error),
236    };
237    let mut seen: std::collections::HashMap<String, &syn::Ident> = std::collections::HashMap::new();
238    for (formal, ident) in r_formal_names(inputs, formals) {
239        let declared = formals.declared(&crate::naming::ident_name(ident));
240        let problem = if let Some(lit) = declared {
241            declared_formal_problem(&formal).map(|problem| (lit.span(), problem))
242        } else if crate::naming::is_r_reserved_word(&formal) {
243            Some((
244                ident.span(),
245                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is an R reserved word, so the generated R wrapper would not parse. Rename the parameter (for example `{0}_`)",
                formal))
    })format!(
246                    "is an R reserved word, so the generated R wrapper would not parse. \
247                     Rename the parameter (for example `{formal}_`)"
248                ),
249            ))
250        } else if formal.starts_with(|c: char| c.is_ascii_digit()) {
251            Some((
252                ident.span(),
253                "starts with a digit, so the generated R wrapper would not parse. \
254                 Rename the parameter so that, without its leading underscores, it \
255                 starts with a letter"
256                    .to_string(),
257            ))
258        } else {
259            None
260        };
261        let problem = problem.or_else(|| {
262            reserved
263                .iter()
264                .find(|(name, _)| *name == formal)
265                .map(|(_, role)| {
266                    let fix = if declared.is_some() {
267                        "Declare another formal"
268                    } else {
269                        "Rename the parameter"
270                    };
271                    (
272                        declared.map_or(ident.span(), syn::LitStr::span),
273                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}. {1}", role, fix))
    })format!("{role}. {fix}"),
274                    )
275                })
276        });
277        if let Some((span, problem)) = problem {
278            let becomes = if declared.is_some() {
279                "is declared as"
280            } else {
281                "becomes"
282            };
283            push(syn::Error::new(
284                span,
285                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parameter `{0}` {1} the R argument `{2}`, which {3}.",
                ident, becomes, formal, problem))
    })format!(
286                    "parameter `{ident}` {becomes} the R argument `{formal}`, which {problem}."
287                ),
288            ));
289            continue;
290        }
291        if let Some(first) = seen.insert(formal.clone(), ident) {
292            let span = declared.map_or(ident.span(), syn::LitStr::span);
293            let how = if declared.is_some()
294                || formals
295                    .declared(&crate::naming::ident_name(first))
296                    .is_some()
297            {
298                "a declared `formal` names the R argument"
299            } else {
300                "the R name drops leading underscores"
301            };
302            push(syn::Error::new(
303                span,
304                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parameters `{0}` and `{1}` both become the R argument `{2}` ({3}), and R rejects a repeated argument name. Rename one of them.",
                first, ident, formal, how))
    })format!(
305                    "parameters `{first}` and `{ident}` both become the R argument `{formal}` \
306                     ({how}), and R rejects a repeated argument name. Rename one of them."
307                ),
308            ));
309        }
310    }
311    errors.map_or(Ok(()), Err)
312}
313
314/// The R formal each parameter of a signature becomes, with the parameter's
315/// ident: [`Formals::of`] its name. The `&Dots` / `LazyDots` parameter becomes
316/// `...` wherever it sits and is skipped, as are receivers, non-ident patterns
317/// and an `NArgs` parameter, which is no formal (#1860).
318///
319/// [`check_r_formals`] checks these names, and the shadowing pass
320/// ([`formal_names`](crate::r_shadowing::formal_names)) qualifies the calls
321/// they would shadow, so the two agree on what each formal is named.
322pub(crate) fn r_formal_names<'a>(
323    inputs: &'a syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
324    formals: &'a Formals,
325) -> impl Iterator<Item = (String, &'a syn::Ident)> {
326    let dots_index = crate::miniextendr_fn::dots_index(inputs);
327    inputs.iter().enumerate().filter_map(move |(idx, input)| {
328        let syn::FnArg::Typed(pat_type) = input else {
329            return None;
330        };
331        if Some(idx) == dots_index || crate::type_inspect::is_nargs_marker(&pat_type.ty) {
332            return None;
333        }
334        let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
335            return None;
336        };
337        let ident = &pat_ident.ident;
338        Some((formals.of_ident(ident), ident))
339    })
340}
341
342/// Split a comma-separated choices list (as given to `choices(param = "a, b, c")`)
343/// into individual trimmed entries. Surrounding double-quotes are tolerated so
344/// users can spell the list either way: `"a, b"` or `"\"a\", \"b\""`.
345///
346/// Shared by the inherent-impl (`miniextendr_impl.rs`) and trait-impl
347/// (`miniextendr_impl_trait/vtable.rs`) `choices(...)` attribute parsers so the
348/// two independently-maintained parsers can't drift on quoting/whitespace rules.
349pub(crate) fn split_choice_list(raw: &str) -> Vec<String> {
350    raw.split(',')
351        .map(|s| s.trim().trim_matches('"').to_string())
352        .filter(|s| !s.is_empty())
353        .collect()
354}
355
356/// Builder for R function formal parameters and call arguments.
357///
358/// Handles:
359/// - R formals: the declared `formal = ".."` (#1842), else the Rust name
360///   without leading underscores (`_x` → `x`)
361/// - Unit type defaults (`()` → `= NULL`)
362/// - Dots: the `&Dots` parameter is `...` in the formals and `list(...)` in
363///   the call arguments, at its own position in the signature; a `LazyDots`
364///   parameter is `...` too, and `environment()` in the call arguments, which
365///   passes the dots unforced (#1892)
366/// - The argument count: an `NArgs` parameter is no formal and `nargs()` in
367///   the call arguments, at its own position (#1860)
368/// - Consistent formatting across function and method wrappers
369pub struct RArgumentBuilder<'a> {
370    /// The function's input parameters from the parsed Rust signature.
371    inputs: &'a syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
372    /// Position of the `&Dots` / `LazyDots` parameter in `inputs` (receiver
373    /// included, the way both build loops count). Its Rust name never reaches
374    /// R: the formal is always plain `...`.
375    dots_index: Option<usize>,
376    /// Which `...` type it is: what the call arguments pass at its position.
377    dots_kind: Option<crate::miniextendr_fn::DotsKind>,
378    /// If true, skip the first parameter (used for `self`/`&self` in method wrappers,
379    /// since the self argument is handled separately by [`DotCallBuilder::with_self`]).
380    skip_first: bool,
381    /// Parameter default values from `#[miniextendr(default = "...")]` attributes.
382    /// Keys are R formals ([`Formals::of`]), values are R expressions emitted
383    /// verbatim (e.g., `"1L"`, `"c(1, 2, 3)"`, `"NULL"`).
384    defaults: std::collections::HashMap<String, String>,
385    /// The R formals of the single-choice `Missing<..>` parameters that read
386    /// a value `identical()` to their formal as omitted (#2152), whose
387    /// prelude binds [`absent_flag`] (see
388    /// [`crate::miniextendr_fn::ParamAttrs::reads_formal_as_absent`]).
389    absent_formals: std::collections::HashSet<String>,
390    /// The R formal of each parameter (#1842).
391    formals: Formals,
392}
393
394impl<'a> RArgumentBuilder<'a> {
395    /// Create a new builder for the given function inputs.
396    pub fn new(inputs: &'a syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>) -> Self {
397        let dots_index = crate::miniextendr_fn::dots_index(inputs);
398        let dots_kind = dots_index.and_then(|idx| match &inputs[idx] {
399            syn::FnArg::Typed(pt) => crate::miniextendr_fn::dots_kind(pt.ty.as_ref()),
400            syn::FnArg::Receiver(_) => None,
401        });
402        Self {
403            inputs,
404            dots_index,
405            dots_kind,
406            skip_first: false,
407            defaults: std::collections::HashMap::new(),
408            absent_formals: std::collections::HashSet::new(),
409            formals: Formals::default(),
410        }
411    }
412
413    /// Name each parameter by its R formal (#1842): the declared
414    /// `formal = ".."`, else the normalized Rust name (the default). The
415    /// keys of [`Self::with_defaults`] and [`Self::with_absent_formals`] are
416    /// these formals.
417    pub fn with_formals(mut self, formals: Formals) -> Self {
418        self.formals = formals;
419        self
420    }
421
422    /// Add the `Missing<..>` choice parameters that read a value `identical()`
423    /// to their formal as omitted (#2152), by R formal (see
424    /// [`crate::miniextendr_fn::absent_formals_by_r_name`]). Their call
425    /// arguments read the [`absent_flag`] that the wrapper's prelude binds
426    /// ([`CallAttribution::match_arg_lines`]), so pass them only for a body
427    /// that runs the prelude.
428    pub fn with_absent_formals(
429        mut self,
430        absent_formals: std::collections::HashSet<String>,
431    ) -> Self {
432        self.absent_formals = absent_formals;
433        self
434    }
435
436    /// Add parameter defaults from `#[miniextendr(default = "...")]` attributes.
437    ///
438    /// Keys are R formals (see [`Self::with_formals`]; without a declared
439    /// formal, the Rust name without leading underscores), values are R
440    /// expression strings emitted verbatim into formals.
441    pub fn with_defaults(mut self, defaults: std::collections::HashMap<String, String>) -> Self {
442        self.defaults = defaults;
443        self
444    }
445
446    /// Skip the first parameter (for instance methods with `self`).
447    pub fn skip_first(mut self) -> Self {
448        self.skip_first = true;
449        self
450    }
451
452    /// Build R formal parameters string (for function signature).
453    ///
454    /// # Returns
455    /// Comma-separated parameter list, e.g., `"x, y = NULL, ..."`
456    ///
457    /// This method handles R-style defaults (like `1L`, `c(1,2,3)`) that aren't
458    /// valid Rust syntax by outputting them directly as strings.
459    pub fn build_formals(&self) -> String {
460        let mut formals = Vec::new();
461
462        for (idx, input) in self.inputs.iter().enumerate() {
463            // Skip first if requested (for self in methods)
464            if self.skip_first && idx == 0 {
465                continue;
466            }
467
468            let pat_type = match input {
469                syn::FnArg::Typed(pt) => pt,
470                syn::FnArg::Receiver(_) => continue, // Skip self receivers
471            };
472
473            // The dots, at their own position. In R, `...` takes no name or
474            // default, so the Rust binding never shows: the formal is `...`.
475            if Some(idx) == self.dots_index {
476                formals.push("...".to_string());
477                continue;
478            }
479
480            // The argument count (#1860) is no formal: the call arguments pass
481            // `nargs()` in its place.
482            if crate::type_inspect::is_nargs_marker(&pat_type.ty) {
483                continue;
484            }
485
486            // The parameter's R formal (#1842)
487            let formal = match pat_type.pat.as_ref() {
488                syn::Pat::Ident(pat_ident) => self.formals.of_ident(&pat_ident.ident),
489                _ => continue,
490            };
491
492            // Check for user-specified default value
493            if let Some(default_val) = self.defaults.get(&formal) {
494                // User provided default via #[miniextendr(default = "...")]
495                // Output directly as string - supports R-style defaults like "1L", "c(1,2,3)"
496                formals.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = {1}", formal, default_val))
    })format!("{} = {}", formal, default_val));
497                continue;
498            }
499
500            // Add default for unit types
501            match pat_type.ty.as_ref() {
502                syn::Type::Tuple(t) if t.elems.is_empty() => {
503                    formals.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = NULL", formal))
    })format!("{} = NULL", formal));
504                }
505                _ => {
506                    formals.push(formal);
507                }
508            }
509        }
510
511        formals.join(", ")
512    }
513
514    /// Build R call arguments string (for `.Call()` invocation).
515    ///
516    /// # Returns
517    /// Comma-separated argument list, e.g., `"x, y, list(...)"` (or
518    /// `"x, y, environment()"` for a `LazyDots` parameter)
519    pub fn build_call_args(&self) -> String {
520        self.build_call_args_vec().join(", ")
521    }
522
523    /// Build R call arguments as a `Vec<String>`.
524    ///
525    /// Each element is a single argument expression. A `&Dots` parameter
526    /// becomes `"list(...)"`, which captures the variadic args as an R list for
527    /// the `.Call()` interface; a `LazyDots` parameter becomes
528    /// `"environment()"`, the wrapper's own frame, whose `...` binding holds
529    /// the dots unforced (#1892).
530    pub fn build_call_args_vec(&self) -> Vec<String> {
531        let mut call_args = Vec::new();
532
533        for (idx, input) in self.inputs.iter().enumerate() {
534            // Skip first if requested (for self in methods)
535            if self.skip_first && idx == 0 {
536                continue;
537            }
538
539            let syn::FnArg::Typed(pat_type) = input else {
540                continue;
541            };
542
543            // The dots, at their own position: the formal is plain `...`, so
544            // the argument is `list(...)` for `&Dots` and `environment()` for
545            // `LazyDots` (#1892). `.Call()` evaluates its arguments in the
546            // wrapper's frame, so `environment()` is that frame, and nothing in
547            // `...` is forced on the way in.
548            if Some(idx) == self.dots_index {
549                let kind = self
550                    .dots_kind
551                    .unwrap_or(crate::miniextendr_fn::DotsKind::Forced);
552                call_args.push(kind.r_call_arg().to_string());
553                continue;
554            }
555
556            // The argument count (#1860): the wrapper's own `nargs()`, which
557            // the C wrapper converts like any argument. `.Call()` evaluates
558            // its arguments in the wrapper's frame, so `nargs()` counts the
559            // wrapper's call as typed.
560            if crate::type_inspect::is_nargs_marker(&pat_type.ty) {
561                call_args.push("nargs()".to_string());
562                continue;
563            }
564
565            // The parameter's R formal (#1842)
566            let formal = match pat_type.pat.as_ref() {
567                syn::Pat::Ident(pat_ident) => self.formals.of_ident(&pat_ident.ident),
568                _ => continue,
569            };
570
571            // `Quoted` / `Quosure` (also under `Missing<..>`, #1835): the
572            // argument unevaluated, behind the same missing-argument sentinel
573            // as `Missing<T>`. Neither branch forces it. A `default` on
574            // `Missing<..>` only writes the formal: `missing()` is `TRUE` for
575            // an omitted argument with a default, so the default is never
576            // evaluated.
577            if let Some(param) = crate::type_inspect::unevaluated_param(pat_type.ty.as_ref()) {
578                call_args.push(param.kind.r_call_arg(&formal));
579                continue;
580            }
581
582            // `Missing<T>`: forward true missingness as the `R_MissingArg`
583            // sentinel, produced *at the argument position*. A binding holding
584            // the sentinel errors on symbol lookup ("argument is missing, with
585            // no default"), so the former `if (missing(x)) x <- quote(expr=)`
586            // prelude broke every truly-missing call. A `default` on it
587            // (#2161) only writes the formal: `missing()` is `TRUE` for an
588            // omitted argument with a default, so the default is never
589            // evaluated, and a supplied value, the default's own included, is
590            // `Present`. A single-choice parameter also forwards the
591            // sentinel for a value `identical()` to its formal (#2152): the
592            // default shown in the usage line means the same as leaving it
593            // out. Its prelude compared the argument once, before matching it,
594            // and kept the answer in `absent_flag(p)`; comparing here, after
595            // the match, would read every match of a one-choice list as the
596            // formal (#2182).
597            if is_missing_type(pat_type.ty.as_ref()) {
598                let p = formal;
599                call_args.push(if self.absent_formals.contains(&p) {
600                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if ({0}) quote(expr=) else {1}",
                absent_flag(&p), p))
    })format!("if ({}) quote(expr=) else {p}", absent_flag(&p))
601                } else {
602                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (missing({0})) quote(expr=) else {0}",
                p))
    })format!("if (missing({p})) quote(expr=) else {p}")
603                });
604                continue;
605            }
606
607            call_args.push(formal);
608        }
609
610        call_args
611    }
612}
613
614/// Build R formal parameters from a Rust function signature, with optional defaults.
615///
616/// Automatically skips `self`/`&self` receivers. `Missing<T>` parameters without
617/// user-provided defaults appear as bare formals (no default value); the
618/// `R_MissingArg` sentinel forwarding is emitted inline in the `.Call()` args
619/// (see [`RArgumentBuilder::build_call_args_vec`]).
620///
621/// Returns a comma-separated string of R formals, e.g., `"x, y = NULL, ..."`.
622/// `formals` names each parameter (see [`RArgumentBuilder::with_formals`]),
623/// and `defaults` is keyed by those formals.
624pub(crate) fn build_r_formals_from_sig(
625    sig: &syn::Signature,
626    formals: &Formals,
627    defaults: &std::collections::HashMap<String, String>,
628) -> String {
629    let mut builder = RArgumentBuilder::new(&sig.inputs).with_formals(formals.clone());
630    if #[allow(non_exhaustive_omitted_patterns)] match sig.inputs.first() {
    Some(syn::FnArg::Receiver(_)) => true,
    _ => false,
}matches!(sig.inputs.first(), Some(syn::FnArg::Receiver(_))) {
631        builder = builder.skip_first();
632    }
633    builder = builder.with_defaults(defaults.clone());
634    builder.build_formals()
635}
636
637/// Build R `.Call()` arguments from a Rust function signature.
638///
639/// Automatically skips `self`/`&self` receivers (those are passed separately
640/// via [`DotCallBuilder::with_self`]). `&Dots` becomes `list(...)`, `LazyDots`
641/// `environment()`. `absent_formals` are the choice parameters that read a
642/// value `identical()` to their formal as omitted (see
643/// [`RArgumentBuilder::with_absent_formals`]).
644///
645/// Returns a comma-separated string of R call arguments, e.g., `"x, y, list(...)"`.
646/// `formals` names each parameter, as in [`build_r_formals_from_sig`].
647pub(crate) fn build_r_call_args_from_sig(
648    sig: &syn::Signature,
649    formals: &Formals,
650    absent_formals: std::collections::HashSet<String>,
651) -> String {
652    let mut builder = RArgumentBuilder::new(&sig.inputs)
653        .with_formals(formals.clone())
654        .with_absent_formals(absent_formals);
655    if #[allow(non_exhaustive_omitted_patterns)] match sig.inputs.first() {
    Some(syn::FnArg::Receiver(_)) => true,
    _ => false,
}matches!(sig.inputs.first(), Some(syn::FnArg::Receiver(_))) {
656        builder = builder.skip_first();
657    }
658    builder.build_call_args()
659}
660
661/// The local that holds whether the single-choice `Missing<..>` parameter
662/// with R formal `formal` reads as omitted (#2182): `.mx_absent_<formal>`.
663/// The prelude binds it right before the parameter's check
664/// ([`CallAttribution::match_arg_lines`]), the check is skipped when it is
665/// `TRUE`, and the `.Call()` argument forwards the missing-argument sentinel
666/// for it ([`RArgumentBuilder::with_absent_formals`]). A declared formal can't
667/// start with `.mx_` ([`declared_formal_problem`]) and a Rust name can't start
668/// with `.`, so no formal takes its name.
669pub(crate) fn absent_flag(formal: &str) -> String {
670    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".mx_absent_{0}", formal))
    })format!(".mx_absent_{formal}")
671}
672
673// region: Missing<T> detection for automatic defaults
674
675/// Check if a type is `Missing<T>` by examining the last path segment.
676///
677/// `Missing<T>` is the miniextendr wrapper for R's "missing argument" concept,
678/// allowing Rust functions to accept optional arguments that R callers can omit.
679pub(crate) fn is_missing_type(ty: &syn::Type) -> bool {
680    match ty {
681        syn::Type::Path(tp) => tp
682            .path
683            .segments
684            .last()
685            .map(|s| s.ident == "Missing")
686            .unwrap_or(false),
687        _ => false,
688    }
689}
690
691// endregion
692
693// region: DotCallBuilder - .Call() invocation formatting
694
695/// Which frame a generated wrapper hands to `.Call(.., .call = ..)` and uses as
696/// the raise fallback (`.miniextendr_raise_condition(.val, <default>)`).
697#[derive(#[automatically_derived]impl ::core::fmt::Debug for CallAttribution {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Wrapper Caller Argument NoCall Generic GenericEager",
            match self {
                CallAttribution::Wrapper => 0usize,
                CallAttribution::Caller => 8usize,
                CallAttribution::Argument => 15usize,
                CallAttribution::NoCall => 24usize,
                CallAttribution::Generic => 31usize,
                CallAttribution::GenericEager => 39usize,
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CallAttribution {
}
#[automatically_derived]impl ::core::clone::Clone for CallAttribution {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for CallAttribution { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CallAttribution {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CallAttribution {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for CallAttribution { }Eq, #[automatically_derived]impl ::core::default::Default for CallAttribution {
    #[inline]
    fn default() -> Self { Self::Wrapper }
}Default)]
698pub enum CallAttribution {
699    /// `.call = sys.call()`: the wrapper's own call, as written (default).
700    #[default]
701    Wrapper,
702    /// `.call = .mx_call`, where the wrapper body first binds
703    /// `.mx_call <- .miniextendr_caller_call()`: the caller's call as written,
704    /// resolved by the preamble helper in `miniextendr-api/src/registry.rs`
705    /// (one line per wrapper since #1552, four before). The helper looks two
706    /// frames up the calling chain for the wrapper's caller. It falls back to
707    /// the wrapper's own call when there is no parent frame (top level) or the
708    /// parent frame is not a closure: `eval()`'d code such as a testthat block
709    /// or `source()` has the `eval` primitive as its frame function, whose call
710    /// names `eval`. For a `noexport` entry point behind a hand-written R
711    /// function (`#[miniextendr(noexport, call = caller)]`).
712    ///
713    /// A standalone wrapper with this attribution also takes a trailing
714    /// `.call = NULL` formal ([`CallAttribution::formal`], #1613), which the
715    /// prelude hands to the helper: a hand-written helper sitting between the
716    /// public function and the entry point passes its own caller's frame
717    /// (`call = parent.frame()` in the helper's formals, `.call = call` in its
718    /// body), and the condition names the public function. `.call` also takes a
719    /// call object, used as is. S3 methods keep the zero-argument prelude: a
720    /// trailing formal would break generic/method consistency.
721    Caller,
722    /// `.call = .mx_call`, where the wrapper body first binds
723    /// `.mx_call <- if (is.null(.call)) sys.call() else
724    /// .miniextendr_caller_call(.call, own = TRUE)`: the wrapper's own call,
725    /// as for [`CallAttribution::Wrapper`], unless the caller passes another
726    /// as the trailing `.call = NULL` formal (#1834). Selected by
727    /// `#[miniextendr(call_arg)]` on a standalone function, exported or not:
728    /// an R function composing exported functions (applying them through
729    /// `do.call()`, say) passes `.call = environment()` and every condition
730    /// names its own call. The helper resolves a frame or a call as under
731    /// [`CallAttribution::Caller`]; a frame no closure owns gives the
732    /// wrapper's own call. The success path without `.call` costs one
733    /// `is.null()`. Never parsed from `call = ...`: it is `wrapper`
734    /// attribution plus the formal, so a `Call` marker reads the resolved
735    /// call.
736    Argument,
737    /// `.call = FALSE`: no call at all (#1851). Selected by
738    /// `#[miniextendr(call = none)]` on a standalone function (an S3 method
739    /// included) or by the crate default `call_attribution = "none"`, which
740    /// applies to every standalone function. Every condition the wrapper
741    /// raises then has a `NULL` `conditionCall()`, like R's `call. = FALSE`:
742    /// the R-side checks and the `match_arg` helpers are passed `NULL`, the
743    /// slot carries `FALSE`, the marker the raise helper already reads as "no
744    /// call" (what `call = none` on a condition macro writes, see
745    /// `ConditionCall::None`), and the raise fallback is `NULL`. There is no
746    /// marker spelling: a `Call` / `CallerCall` parameter receives the call,
747    /// and this attribution has none, so either one is a compile error with
748    /// it, as is `call_arg` (whose `.call` would have nothing to replace).
749    NoCall,
750    /// `.call = environment()`: the wrapper's own frame, turned into a call
751    /// only when a condition is raised (#1851). The attribution of every
752    /// generated S3 method that would otherwise be `wrapper`: a standalone
753    /// `s3(...)` function, an impl-block or trait `s3` / `vctrs` method
754    /// ([`CallAttribution::for_s3_method`]). The raise helper and
755    /// `.miniextendr_arg_error` resolve the frame with
756    /// `.miniextendr_frame_call` (`miniextendr-api/src/registry.rs`), which
757    /// names the generic the user called when R dispatched the method
758    /// (`.Generic` is bound in the frame: `summary(x, a = 1)` for
759    /// `summary.cls(x, a = 1)`, `x[i]` for `` `[.cls`(x, i) ``) and writes a
760    /// replacement generic's call as the assignment, `x$name <- value`,
761    /// without the value R passed. A direct call of the method keeps the
762    /// method's name. The success path evaluates `environment()` instead of
763    /// `sys.call()`, the same cost; the rewrite runs only on a raise.
764    Generic,
765    /// `.call = .mx_call`, where the wrapper body first binds
766    /// `.mx_call <- .miniextendr_frame_call(environment())`: the
767    /// [`CallAttribution::Generic`] call resolved before the `.Call()`, for an
768    /// S3 method with a `Call` parameter, whose C wrapper binds it from the
769    /// slot and so needs a call object there (#1851). Costs the frame scan on
770    /// every call, so only the marker selects it.
771    GenericEager,
772}
773
774impl CallAttribution {
775    /// The spelling shared by the attribute (`call = wrapper | caller | none`)
776    /// and the crate default (`call_attribution = "wrapper" | "caller" |
777    /// "none"`).
778    pub fn parse_name(name: &str) -> Option<Self> {
779        match name {
780            "wrapper" => Some(CallAttribution::Wrapper),
781            "caller" => Some(CallAttribution::Caller),
782            "none" => Some(CallAttribution::NoCall),
783            _ => None,
784        }
785    }
786
787    /// The attribute spelling of this attribution. [`CallAttribution::Argument`]
788    /// is `wrapper` attribution with the `call_arg` option, and the two S3
789    /// forms are `wrapper` attribution on a dispatched method, so all three
790    /// share `wrapper`'s spelling.
791    pub fn name(self) -> &'static str {
792        match self {
793            CallAttribution::Wrapper
794            | CallAttribution::Argument
795            | CallAttribution::Generic
796            | CallAttribution::GenericEager => "wrapper",
797            CallAttribution::Caller => "caller",
798            CallAttribution::NoCall => "none",
799        }
800    }
801
802    /// The parameter marker type that selects this attribution (#1566): `Call`
803    /// for `wrapper`, `CallerCall` for `caller`. `none` has no marker: a
804    /// marker receives the call, and `none` passes none.
805    pub fn marker_name(self) -> Option<&'static str> {
806        match self {
807            CallAttribution::Wrapper
808            | CallAttribution::Argument
809            | CallAttribution::Generic
810            | CallAttribution::GenericEager => Some("Call"),
811            CallAttribution::Caller => Some("CallerCall"),
812            CallAttribution::NoCall => None,
813        }
814    }
815
816    /// The attribution of a generated S3 method (#1851): `wrapper` becomes
817    /// [`CallAttribution::Generic`], or [`CallAttribution::GenericEager`] when
818    /// the method takes a `Call` parameter (`has_call_marker`), which needs
819    /// the call resolved before the `.Call()`. `caller` and `none` are
820    /// explicit choices and stay; `Argument` never reaches an S3 method
821    /// (`call_arg` is refused on them).
822    pub fn for_s3_method(self, has_call_marker: bool) -> Self {
823        match self {
824            CallAttribution::Wrapper if has_call_marker => CallAttribution::GenericEager,
825            CallAttribution::Wrapper => CallAttribution::Generic,
826            other => other,
827        }
828    }
829
830    /// Resolve a standalone function's attribution from its three spellings
831    /// (#1566), most specific first: the `Call` / `CallerCall` parameter
832    /// marker, the `call = wrapper | caller | none` attribute, the crate's
833    /// `[package.metadata.miniextendr] call_attribution` default and finally
834    /// the framework default, `wrapper`. A crate default of `caller` applies
835    /// to internal entry points (`noexport` / `internal`) only; an exported
836    /// function's caller is arbitrary user code, so it keeps `wrapper`. A
837    /// crate default of `none` applies to every standalone function, like
838    /// `wrapper` (#1851). The explicit spellings are validated before this
839    /// runs (a `caller` marker or attribute on an exported function is a
840    /// compile error, not a fallback). Class and trait methods always use
841    /// `wrapper`, except the R6 / S7 lambda frames
842    /// ([`DotCallBuilder::null_call_attribution`]) and the S3 methods
843    /// ([`CallAttribution::for_s3_method`]).
844    pub fn resolve(
845        marker: Option<Self>,
846        attribute: Option<Self>,
847        crate_default: Option<Self>,
848        internal_entry: bool,
849    ) -> Self {
850        marker.or(attribute).unwrap_or(match crate_default {
851            Some(CallAttribution::Caller) if !internal_entry => CallAttribution::Wrapper,
852            Some(default) => default,
853            None => CallAttribution::Wrapper,
854        })
855    }
856
857    /// Apply the `call_arg` option (#1834) to a resolved attribution:
858    /// `wrapper` becomes [`CallAttribution::Argument`]. The option is
859    /// validated before this runs: it is a compile error with `call = caller`
860    /// or a `CallerCall` parameter (whose wrapper already takes `.call`), on
861    /// an S3 method and on an `extern "C-unwind"` function, and the caller
862    /// leaves the crate default out of [`CallAttribution::resolve`] when it
863    /// is set, so `caller` never reaches here with it.
864    pub fn with_call_arg(self, call_arg: bool) -> Self {
865        match self {
866            CallAttribution::Wrapper if call_arg => CallAttribution::Argument,
867            other => other,
868        }
869    }
870
871    /// The expression the `.Call()` line passes as `.call`: the call as
872    /// written, the frame it is read from on a raise, or `FALSE` for none.
873    pub fn dot_call_expr(self) -> &'static str {
874        match self {
875            CallAttribution::Wrapper => "sys.call()",
876            CallAttribution::Caller | CallAttribution::Argument | CallAttribution::GenericEager => {
877                ".mx_call"
878            }
879            CallAttribution::NoCall => "FALSE",
880            CallAttribution::Generic => "environment()",
881        }
882    }
883
884    /// The `.call = ...` argument for the `.Call()` line.
885    pub fn dot_call_arg(self) -> &'static str {
886        match self {
887            CallAttribution::Wrapper => ".call = sys.call()",
888            CallAttribution::Caller | CallAttribution::Argument | CallAttribution::GenericEager => {
889                ".call = .mx_call"
890            }
891            CallAttribution::NoCall => ".call = FALSE",
892            CallAttribution::Generic => ".call = environment()",
893        }
894    }
895
896    /// The fallback call handed to `.miniextendr_raise_condition`: the same
897    /// value as the slot, except that `none` passes `NULL` (the helper reads
898    /// `FALSE` in the slot as "no call" and would read it here too; `NULL` is
899    /// the plainer spelling).
900    pub fn raise_default(self) -> &'static str {
901        match self {
902            CallAttribution::Caller | CallAttribution::Argument | CallAttribution::GenericEager => {
903                ".mx_call"
904            }
905            CallAttribution::Wrapper => "sys.call()",
906            CallAttribution::NoCall => "NULL",
907            CallAttribution::Generic => "environment()",
908        }
909    }
910
911    /// The statement the wrapper body needs before anything else: empty for
912    /// [`CallAttribution::Wrapper`], [`CallAttribution::NoCall`] and
913    /// [`CallAttribution::Generic`]; the others bind `.mx_call`. It is the
914    /// first part of the wrapper prelude, ahead of the R-side checks
915    /// (preconditions, `match.arg`), so that those checks can attribute their
916    /// failures to the caller too (#1548). `call_formal` says whether the
917    /// wrapper has the `.call` formal ([`CallAttribution::formal`]); the
918    /// helper then resolves whatever the caller passed there (#1613). Under
919    /// [`CallAttribution::Argument`] a `NULL` `.call` is the wrapper's own
920    /// call, read inline so that a call without `.call` costs one `is.null()`
921    /// (#1834); the wrapper always has the formal there, since the option is
922    /// refused on S3 methods. [`CallAttribution::GenericEager`] resolves the
923    /// method frame's call up front (#1851).
924    pub fn prelude(self, call_formal: bool) -> String {
925        match self {
926            CallAttribution::Caller if call_formal => {
927                ".mx_call <- .miniextendr_caller_call(.call)".to_string()
928            }
929            CallAttribution::Caller => ".mx_call <- .miniextendr_caller_call()".to_string(),
930            CallAttribution::Argument => ".mx_call <- if (is.null(.call)) sys.call() else \
931                 .miniextendr_caller_call(.call, own = TRUE)"
932                .to_string(),
933            CallAttribution::GenericEager => {
934                ".mx_call <- .miniextendr_frame_call(environment())".to_string()
935            }
936            CallAttribution::Wrapper | CallAttribution::NoCall | CallAttribution::Generic => {
937                String::new()
938            }
939        }
940    }
941
942    /// The trailing formal a standalone wrapper with this attribution takes:
943    /// `.call = NULL` for [`CallAttribution::Caller`] (#1613), so a
944    /// hand-written helper between the public function and the entry point
945    /// can pass on the call to report, and for [`CallAttribution::Argument`]
946    /// (#1834), so an R function composing exported functions can. `NULL`
947    /// keeps the wrapper's default (the caller's call, or its own); an
948    /// environment names the closure owning that frame (`parent.frame()` from
949    /// a helper, `environment()` from the composing function); a call object
950    /// is used as is. Rust identifiers cannot start with `.`, so the name
951    /// never collides with a parameter. The caller leaves S3 methods out.
952    pub fn formal(self) -> Option<&'static str> {
953        match self {
954            CallAttribution::Caller | CallAttribution::Argument => Some(".call = NULL"),
955            CallAttribution::Wrapper
956            | CallAttribution::NoCall
957            | CallAttribution::Generic
958            | CallAttribution::GenericEager => None,
959        }
960    }
961
962    /// The generated `@param` text for the [`CallAttribution::formal`]. It is
963    /// written as the author's own line would be, not as a filler, so a block
964    /// on a page or an inheritance source no author block documents `.call`
965    /// for still documents it (see `crate::roxygen::push_fn_param_tags`).
966    pub fn param_doc(self) -> Option<&'static str> {
967        match self {
968            CallAttribution::Caller => Some(
969                "The call conditions from this function report: NULL (the default) for \
970                 the calling function's call, a frame such as parent.frame() for the call \
971                 of the function owning that frame, or a call object. Pass it by name.",
972            ),
973            CallAttribution::Argument => Some(
974                "The call conditions from this function report: NULL (the default) for \
975                 this call, a frame such as environment() for the call of the function \
976                 owning that frame, or a call object. Pass it by name.",
977            ),
978            CallAttribution::Wrapper
979            | CallAttribution::NoCall
980            | CallAttribution::Generic
981            | CallAttribution::GenericEager => None,
982        }
983    }
984
985    /// The call an R-side check raised in the wrapper body should carry:
986    /// `.mx_call` when the prelude binds it, `NULL` for `none`, the frame
987    /// (`environment()`, which `.miniextendr_arg_error` resolves) for an S3
988    /// method, otherwise `None` (the check keeps its own attribution, which
989    /// is the wrapper's frame).
990    pub fn r_check_call(self) -> Option<&'static str> {
991        match self {
992            CallAttribution::Caller | CallAttribution::Argument | CallAttribution::GenericEager => {
993                Some(".mx_call")
994            }
995            CallAttribution::NoCall => Some("NULL"),
996            CallAttribution::Generic => Some("environment()"),
997            CallAttribution::Wrapper => None,
998        }
999    }
1000
1001    /// The R statement validating a choice parameter (`match_arg` / `choices`).
1002    /// `choices` is the R expression for the choice list: a literal
1003    /// `c("a", "b")`, or the write-time placeholder for an enum. `attrs` are
1004    /// the parameter's own attributes, which carry `several_ok` and the
1005    /// type's layers.
1006    ///
1007    /// Every form is one call to a preamble helper (`.miniextendr_match_arg`
1008    /// for a scalar, `.miniextendr_match_arg_several` for `several_ok`,
1009    /// #1472), guarded by the layers of the parameter type: `!missing(..)`
1010    /// for `Missing<..>` (#1551), or `!.mx_absent_<p>` ([`absent_flag`]) for
1011    /// a single choice, whose formal reads as omitted too (#2152): the flag
1012    /// [`Self::match_arg_lines`] binds in front of this statement, which the
1013    /// `.Call()` argument reads as well (see
1014    /// [`RArgumentBuilder::with_absent_formals`]); then `!is.null(..)` for `Option<..>`
1015    /// (#1473), with `!(is.logical(..) && length(..) == 1L && is.na(..))`
1016    /// after it, since the Rust decoder reads a plain `NA` as `None` too
1017    /// (#2305, [`crate::r_preconditions::plain_na_check`]), or
1018    /// `is.character(..) || is.factor(..)` for `Either<T, R>` and
1019    /// `Either<Vec<T>, R>` (#1612), which leaves `NULL` out too: Rust reads it
1020    /// as `None` under `Option`, and otherwise converts it to the `R` arm, even
1021    /// for `several_ok`, whose plain form reads `NULL` as every choice. The
1022    /// helpers name the argument in their messages, read a factor as its
1023    /// labels, and attribute the error to the wrapper's own call by default;
1024    /// under [`CallAttribution::Caller`] the statement passes `.mx_call` so the
1025    /// caller is named instead (#1548), and under
1026    /// [`CallAttribution::Argument`] so that the call passed as `.call` is.
1027    /// The list is spelled out because the helpers, unlike
1028    /// `base::match.arg(param)`, do not read it off the formal.
1029    ///
1030    /// `aliases` is the `match_arg` parameter's write-time
1031    /// `match_arg_keys::aliases_placeholder`, written last as `, <placeholder>`:
1032    /// the wrapper writer turns it into the type's `aliases =` argument, or
1033    /// removes it for a type without aliases (#1843). `None` for a literal
1034    /// `choices(...)` list, which has no aliases.
1035    pub fn match_arg_statement(
1036        self,
1037        param: &str,
1038        choices: &str,
1039        aliases: Option<&str>,
1040        attrs: &crate::miniextendr_fn::ParamAttrs,
1041    ) -> String {
1042        let helper = if attrs.several_ok {
1043            ".miniextendr_match_arg_several"
1044        } else {
1045            ".miniextendr_match_arg"
1046        };
1047        let call = match self.r_check_call() {
1048            Some(call) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", call))
    })format!(", {call}"),
1049            None => String::new(),
1050        };
1051        let aliases = match aliases {
1052            Some(placeholder) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", placeholder))
    })format!(", {placeholder}"),
1053            None => String::new(),
1054        };
1055        let statement =
1056            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- {1}({0}, {2}, \"{0}\"{3}{4})",
                param, helper, choices, call, aliases))
    })format!("{param} <- {helper}({param}, {choices}, \"{param}\"{call}{aliases})");
1057        let mut guards = Vec::new();
1058        if attrs.omittable {
1059            // The formal itself reads as omitted too (#2152), as the flag
1060            // bound in front of this statement says (`match_arg_lines`).
1061            guards.push(if attrs.reads_formal_as_absent() {
1062                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!{0}", absent_flag(param)))
    })format!("!{}", absent_flag(param))
1063            } else {
1064                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!missing({0})", param))
    })format!("!missing({param})")
1065            });
1066        }
1067        if attrs.either_noun.is_some() {
1068            // Only the forms `match.arg()` reads are choices; everything else
1069            // (NULL included) goes to the `Either`'s `R` arm unchanged.
1070            let reads = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is.character({0}) || is.factor({0})",
                param))
    })format!("is.character({param}) || is.factor({param})");
1071            guards.push(if guards.is_empty() {
1072                reads
1073            } else {
1074                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0})", reads))
    })format!("({reads})")
1075            });
1076        } else if attrs.optional {
1077            // A choice under `Option` is a scalar one (`classify_choice_param`
1078            // refuses a bare `Option<Vec<T>>`), so it reads a plain `NA` as
1079            // `None` too (#2305).
1080            guards.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!is.null({0})", param))
    })format!("!is.null({param})"));
1081            guards.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("!{0}",
                crate::r_preconditions::plain_na_check(param)))
    })format!(
1082                "!{}",
1083                crate::r_preconditions::plain_na_check(param)
1084            ));
1085        }
1086        if guards.is_empty() {
1087            statement
1088        } else {
1089            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if ({0}) {1}", guards.join(" && "),
                statement))
    })format!("if ({}) {statement}", guards.join(" && "))
1090        }
1091    }
1092
1093    /// The prelude lines of a choice parameter, one element per line: its
1094    /// [`Self::match_arg_statement`], and in front of it, for a single-choice
1095    /// `Missing<..>` parameter
1096    /// ([`crate::miniextendr_fn::ParamAttrs::reads_formal_as_absent`]), the
1097    /// binding of its [`absent_flag`]:
1098    /// `.mx_absent_<p> <- missing(<p>) || identical(<p>, <choices>)`, where
1099    /// `choices` is also the parameter's formal.
1100    ///
1101    /// The argument is compared with its formal once, before the match
1102    /// (#2182). The check skips a flagged value, and the `.Call()` argument
1103    /// forwards the missing-argument sentinel for it
1104    /// ([`RArgumentBuilder::with_absent_formals`]). Comparing again at the
1105    /// `.Call()` would see the matched value, which for a one-choice list is
1106    /// `"Only"`, `identical()` to the formal `c("Only")`, so every match would
1107    /// read as omitted. The binding sits right before the check, after
1108    /// `r_entry` and the other checks, so the argument is forced where the
1109    /// check forces it.
1110    pub fn match_arg_lines(
1111        self,
1112        param: &str,
1113        choices: &str,
1114        aliases: Option<&str>,
1115        attrs: &crate::miniextendr_fn::ParamAttrs,
1116    ) -> Vec<String> {
1117        let mut lines = Vec::new();
1118        if attrs.reads_formal_as_absent() {
1119            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- missing({1}) || identical({1}, {2})",
                absent_flag(param), param, choices))
    })format!(
1120                "{} <- missing({param}) || identical({param}, {choices})",
1121                absent_flag(param)
1122            ));
1123        }
1124        lines.push(self.match_arg_statement(param, choices, aliases, attrs));
1125        lines
1126    }
1127}
1128
1129/// Append a standalone wrapper's [`CallAttribution::formal`] to its joined
1130/// `formals` (#1613). The formal goes last: after `...` and after any formal
1131/// that follows the dots, so positional extras land in the dots and `.call`
1132/// is matched by name only; a wrapper without other formals takes it alone.
1133pub(crate) fn with_call_formal(formals: &str, call_formal: Option<&str>) -> String {
1134    match call_formal {
1135        Some(formal) if formals.is_empty() => formal.to_string(),
1136        Some(formal) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, {1}", formals, formal))
    })format!("{formals}, {formal}"),
1137        None => formals.to_string(),
1138    }
1139}
1140
1141/// Builder for formatting `.Call()` invocations in R wrapper code.
1142///
1143/// Handles the common pattern of `.Call(C_ident, .call = sys.call(), args...)`.
1144///
1145/// # Example
1146///
1147/// ```ignore
1148/// let call = DotCallBuilder::new("C_Counter__increment")
1149///     .with_self("self")
1150///     .build();
1151/// // => ".Call(C_Counter__increment, .call = sys.call(), self)"
1152///
1153/// let call = DotCallBuilder::new("C_Counter__add")
1154///     .with_self("x")
1155///     .with_args(&["n"])
1156///     .build();
1157/// // => ".Call(C_Counter__add, .call = sys.call(), x, n)"
1158/// ```
1159pub struct DotCallBuilder {
1160    /// The C entry point symbol name (e.g., `"C_Counter__increment"`).
1161    /// This is the first argument to `.Call()`.
1162    c_ident: String,
1163    /// Optional self/receiver variable name (e.g., `"self"`, `"x"`).
1164    /// When present, prepended before other arguments in the `.Call()` invocation.
1165    self_var: Option<String>,
1166    /// Additional argument names passed after self (if any) in the `.Call()` invocation.
1167    args: Vec<String>,
1168    /// Expression for the `.call` named argument. `None` means `sys.call()` (the default).
1169    /// Set via [`DotCallBuilder::null_call_attribution`] to emit `.call = NULL` instead.
1170    call_expr: Option<String>,
1171}
1172
1173impl DotCallBuilder {
1174    /// Create a new builder with the C function identifier.
1175    pub fn new(c_ident: impl Into<String>) -> Self {
1176        Self {
1177            c_ident: c_ident.into(),
1178            self_var: None,
1179            args: Vec::new(),
1180            call_expr: None,
1181        }
1182    }
1183
1184    /// Add a self/x parameter (prepended to args).
1185    pub fn with_self(mut self, var: impl Into<String>) -> Self {
1186        self.self_var = Some(var.into());
1187        self
1188    }
1189
1190    /// Add arguments after self (if any).
1191    pub fn with_args(mut self, args: &[impl AsRef<str>]) -> Self {
1192        self.args = args.iter().map(|s| s.as_ref().to_string()).collect();
1193        self
1194    }
1195
1196    /// Add a pre-joined argument string (e.g., `"x, y"`) as a single emit unit.
1197    ///
1198    /// Empty strings are ignored, so callers can pass the result of
1199    /// `build_r_call_args_from_sig` directly without a length check.
1200    pub fn with_args_str(mut self, args: &str) -> Self {
1201        if !args.is_empty() {
1202            self.args.push(args.to_string());
1203        }
1204        self
1205    }
1206
1207    /// Pass `.call = NULL` instead of `.call = sys.call()`: for the R6 / S7
1208    /// lambda frames, which R6 / S7 dispatch calls (R6 finalizer / `deep_clone`, S7
1209    /// property getter / setter / validator), where `sys.call()` names an
1210    /// internal dispatch frame instead of the user's call. Not reachable from
1211    /// any attribute. With `NULL`, the raise helper's fallback (a `NULL`
1212    /// `.val$call` takes `.call_default`, the `sys.call()` in
1213    /// `condition_check_lines`; only a call-less condition's `FALSE` marker
1214    /// gives `NULL`) surfaces the nearest meaningful frame instead.
1215    pub fn null_call_attribution(mut self) -> Self {
1216        self.call_expr = Some("NULL".to_string());
1217        self
1218    }
1219
1220    /// Pass the `.call` of `attribution` ([`CallAttribution::dot_call_expr`]):
1221    /// `environment()` for a generated S3 method
1222    /// ([`CallAttribution::Generic`], #1851), which the raise helper turns into
1223    /// the generic's call when a condition is raised.
1224    pub fn with_call_attribution(mut self, attribution: CallAttribution) -> Self {
1225        self.call_expr = Some(attribution.dot_call_expr().to_string());
1226        self
1227    }
1228
1229    /// Build the `.Call()` string.
1230    pub fn build(&self) -> String {
1231        let call_arg = self.call_expr.as_deref().unwrap_or("sys.call()");
1232
1233        let mut all_args = Vec::new();
1234
1235        if let Some(ref self_var) = self.self_var {
1236            all_args.push(self_var.clone());
1237        }
1238        all_args.extend(self.args.clone());
1239
1240        if all_args.is_empty() {
1241            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, .call = {1})",
                self.c_ident, call_arg))
    })format!(".Call({}, .call = {})", self.c_ident, call_arg)
1242        } else {
1243            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".Call({0}, .call = {1}, {2})",
                self.c_ident, call_arg, all_args.join(", ")))
    })format!(
1244                ".Call({}, .call = {}, {})",
1245                self.c_ident,
1246                call_arg,
1247                all_args.join(", ")
1248            )
1249        }
1250    }
1251}
1252// endregion
1253
1254// region: RoxygenBuilder - roxygen2 documentation tag generation
1255
1256/// Builder for generating roxygen2 documentation tags.
1257///
1258/// Provides a fluent API for building common roxygen tag patterns used
1259/// across all class systems.
1260///
1261/// # Example
1262///
1263/// ```ignore
1264/// let tags = RoxygenBuilder::new()
1265///     .name("Counter$increment")
1266///     .rdname("Counter")
1267///     .export()
1268///     .build();
1269/// // => vec!["#' @name Counter$increment", "#' @rdname Counter", "#' @export"]
1270/// ```
1271pub struct RoxygenBuilder {
1272    /// Value for `@name` tag. Identifies the documented topic (e.g., `"Counter$increment"`).
1273    name: Option<String>,
1274    /// Value for `@rdname` tag. Groups multiple entries onto a single help page
1275    /// (e.g., all methods of `"Counter"` share one Rd file).
1276    rdname: Option<String>,
1277    /// Value for `@title` tag. The one-line title shown in help page headers.
1278    title: Option<String>,
1279    /// Value for `@description` tag. Longer description text below the title.
1280    description: Option<String>,
1281    /// Value for `@source` tag. Typically `"Generated by miniextendr"` provenance info.
1282    source: Option<String>,
1283    /// Whether to emit `@export`. When true, the item is exported from the package NAMESPACE.
1284    export: bool,
1285    /// Value for `@exportMethod` tag. Used for S4 method exports (e.g., `"show"`).
1286    export_method: Option<String>,
1287    /// Values for `@method` tag as `(generic, class)`. Used for S3 method dispatch
1288    /// (e.g., `("print", "Counter")` emits `@method print Counter`).
1289    method: Option<(String, String)>,
1290    /// Additional custom tag lines emitted verbatim (without the `#' ` prefix,
1291    /// which is added during [`build`](Self::build)). Used for tags like
1292    /// `@keywords internal` or `@param` entries.
1293    custom_tags: Vec<String>,
1294}
1295
1296impl RoxygenBuilder {
1297    /// Create a new empty builder.
1298    pub fn new() -> Self {
1299        Self {
1300            name: None,
1301            rdname: None,
1302            title: None,
1303            description: None,
1304            source: None,
1305            export: false,
1306            export_method: None,
1307            method: None,
1308            custom_tags: Vec::new(),
1309        }
1310    }
1311
1312    /// Set the `@name` tag.
1313    pub fn name(mut self, name: impl Into<String>) -> Self {
1314        self.name = Some(name.into());
1315        self
1316    }
1317
1318    /// Set the `@rdname` tag (groups docs into one page).
1319    pub fn rdname(mut self, rdname: impl Into<String>) -> Self {
1320        self.rdname = Some(rdname.into());
1321        self
1322    }
1323
1324    /// Set the `@title` tag.
1325    pub fn title(mut self, title: impl Into<String>) -> Self {
1326        self.title = Some(title.into());
1327        self
1328    }
1329
1330    /// Set the `@description` tag.
1331    #[allow(dead_code)] // Exercised by tests
1332    pub fn description(mut self, desc: impl Into<String>) -> Self {
1333        self.description = Some(desc.into());
1334        self
1335    }
1336
1337    /// Set the `@source` tag (typically "Generated by miniextendr...").
1338    pub fn source(mut self, source: impl Into<String>) -> Self {
1339        self.source = Some(source.into());
1340        self
1341    }
1342
1343    /// Add `@export` tag.
1344    pub fn export(mut self) -> Self {
1345        self.export = true;
1346        self
1347    }
1348
1349    /// Add `@exportMethod` tag (for S4).
1350    #[allow(dead_code)] // Exercised by tests
1351    pub fn export_method(mut self, method: impl Into<String>) -> Self {
1352        self.export_method = Some(method.into());
1353        self
1354    }
1355
1356    /// Add `@method` tag (for S3).
1357    pub fn method(mut self, generic: impl Into<String>, class: impl Into<String>) -> Self {
1358        self.method = Some((generic.into(), class.into()));
1359        self
1360    }
1361
1362    /// Add a custom tag line (without the `#' ` prefix).
1363    pub fn custom(mut self, tag: impl Into<String>) -> Self {
1364        self.custom_tags.push(tag.into());
1365        self
1366    }
1367
1368    /// Build the roxygen tag lines (each prefixed with `#' `).
1369    pub fn build(&self) -> Vec<String> {
1370        let mut lines = Vec::new();
1371
1372        if let Some(ref title) = self.title {
1373            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", title))
    })format!("#' @title {}", title));
1374        }
1375        if let Some(ref desc) = self.description {
1376            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @description {0}", desc))
    })format!("#' @description {}", desc));
1377        }
1378        if let Some(ref name) = self.name {
1379            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", name))
    })format!("#' @name {}", name));
1380        }
1381        if let Some(ref rdname) = self.rdname {
1382            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", rdname))
    })format!("#' @rdname {}", rdname));
1383        }
1384        if let Some(ref source) = self.source {
1385            lines.extend(crate::roxygen::source_tag(source));
1386        }
1387        if let Some((ref generic, ref class)) = self.method {
1388            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", generic,
                class))
    })format!("#' @method {} {}", generic, class));
1389        }
1390        // A tag the author wrapped (`@param`, `@describeIn`, ...) keeps its
1391        // continuation lines, each with its own `#' ` lead.
1392        crate::roxygen::push_roxygen_tags(&mut lines, &self.custom_tags);
1393        if self.export {
1394            lines.push("#' @export".to_string());
1395        }
1396        if let Some(ref method) = self.export_method {
1397            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportMethod {0}", method))
    })format!("#' @exportMethod {}", method));
1398        }
1399
1400        lines
1401    }
1402}
1403
1404/// Creates an empty builder with no tags set.
1405impl Default for RoxygenBuilder {
1406    fn default() -> Self {
1407        Self::new()
1408    }
1409}
1410// endregion
1411
1412// region: RngSeedContract - the stats::simulate() seed contract
1413
1414/// The seed contract of `stats::simulate()`, which
1415/// `#[miniextendr(rng(seed = <param>))]` writes into a standalone wrapper in
1416/// the order `stats:::simulate.lm` uses (#2198).
1417///
1418/// The [`prelude`](Self::prelude) comes after the argument checks, so a
1419/// refused argument changes no RNG state. It creates `.Random.seed` when it is
1420/// missing. With a `NULL` seed it then remembers the state; otherwise it
1421/// registers the restore of the session's state with `on.exit()` and calls
1422/// `set.seed()` with the value as passed, which validates it. The C wrapper's
1423/// `GetRNGstate()` then loads the seeded state, and its `PutRNGstate()` saves
1424/// the state inside `.Call()`, before `on.exit()` puts the session's state
1425/// back, also when the body returns an error or panics.
1426/// [`ATTRIBUTE`](Self::ATTRIBUTE) records the seed in the result, after the
1427/// result's condition check.
1428pub(crate) struct RngSeedContract<'a> {
1429    /// The seed's R formal.
1430    pub formal: &'a str,
1431}
1432
1433impl RngSeedContract<'_> {
1434    /// The statements before `.Call()`, each line after the first prefixed by
1435    /// `indent`.
1436    pub(crate) fn prelude(&self, indent: &str) -> String {
1437        let seed = self.formal;
1438        let lines = [
1439            "if (!exists(\".Random.seed\", envir = globalenv(), inherits = FALSE)) stats::runif(1)"
1440                .to_owned(),
1441            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (is.null({0})) {{", seed))
    })format!("if (is.null({seed})) {{"),
1442            "  .mx_rng_state <- get(\".Random.seed\", envir = globalenv())".to_owned(),
1443            "} else {".to_owned(),
1444            "  .mx_r_seed <- get(\".Random.seed\", envir = globalenv())".to_owned(),
1445            "  on.exit(assign(\".Random.seed\", .mx_r_seed, envir = globalenv()), add = TRUE)"
1446                .to_owned(),
1447            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  set.seed({0})", seed))
    })format!("  set.seed({seed})"),
1448            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .mx_rng_state <- structure({0}, kind = as.list(RNGkind()))",
                seed))
    })format!("  .mx_rng_state <- structure({seed}, kind = as.list(RNGkind()))"),
1449            "}".to_owned(),
1450        ];
1451        lines.join(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\n{0}", indent))
    })format!("\n{indent}"))
1452    }
1453
1454    /// The statement that gives the result `.val` its `seed` attribute. A
1455    /// value that can't carry attributes (`NULL`, an environment, an external
1456    /// pointer, a function) is left as it is; `NULL` is tested on its own,
1457    /// since `is.atomic(NULL)` is `TRUE` before R 4.4.
1458    pub(crate) const ATTRIBUTE: &'static str = "if (!is.null(.val) && (is.atomic(.val) || \
1459         is.list(.val))) attr(.val, \"seed\") <- .mx_rng_state";
1460}
1461// endregion
1462
1463// region: Tests
1464
1465#[cfg(test)]
1466mod tests;
1467// endregion