Skip to main content

miniextendr_macros/
r_class_formatter.rs

1//! Shared utilities for R class wrapper generation.
2//!
3//! This module provides abstractions to reduce duplication across the 5 class system
4//! generators (Env, R6, S3, S4, S7). Each class system has different R idioms but shares
5//! common patterns:
6//!
7//! - Class-level roxygen documentation
8//! - Constructor generation
9//! - Instance method iteration with `.Call()` building
10//! - Static method handling
11//! - Return strategy application
12//!
13//! ## Architecture
14//!
15//! ```text
16//! ParsedImpl
17//!     │
18//!     ├─▶ ClassDocBuilder  → roxygen header lines (#' @title, @name, etc.)
19//!     │
20//!     └─▶ MethodContext[]  → pre-computed method data for each method
21//!             │
22//!             └─▶ ClassFormatter::format_constructor()
23//!             └─▶ ClassFormatter::format_instance_method()
24//!             └─▶ ClassFormatter::format_static_method()
25//! ```
26
27use crate::miniextendr_impl::{
28    CLASS_DOCS_MARKER, ClassSystem, ParsedImpl, ParsedMethod, class_default,
29};
30
31/// Determine whether a class or method should be `@export`-ed.
32///
33/// Returns `true` unless the doc tags include `@noRd` or `@keywords internal`,
34/// or the `noexport` flag is set (which should incorporate both the `noexport`
35/// attribute and the `internal` attribute from the impl block).
36///
37/// Call sites should pass `parsed_impl.noexport || parsed_impl.internal` as
38/// `noexport` so the `internal` attribute is correctly folded in.
39pub(crate) fn should_export_from_tags(tags: &[String], noexport: bool) -> bool {
40    let has_no_rd = crate::roxygen::has_roxygen_tag(tags, "noRd");
41    let has_internal = crate::roxygen::has_roxygen_tag(tags, "keywords internal");
42    !has_no_rd && !has_internal && !noexport
43}
44
45/// Emit the conditional S3 generic guard for a given generic name.
46///
47/// Returns an R code string (to be pushed onto a `lines: Vec<String>` with
48/// `lines.push(emit_s3_generic_guard(name))`) that creates the generic when
49/// it doesn't already exist as a function, and — mirroring the S7 classifier
50/// (#1114, `s7_class.rs:880-935`) — shadows any existing binding that
51/// `UseMethod` dispatch would never consult:
52///
53/// ```r
54/// if (!base::exists("name", mode = "function")) {
55///   name <- function(x, ...) UseMethod("name")
56/// } else if (local({ .mx_gen <- base::get("name", mode = "function"); !(is.primitive(.mx_gen) || isTRUE(utils::isS3stdGeneric(.mx_gen)) || methods::isGeneric("name") || inherits(.mx_gen, "S7_generic")) })) {
57///   .mx_shadow_default <- local({
58///     .mx_masked <- base::get("name", mode = "function")
59///     function(x, ...) .mx_masked(x, ...)
60///   })
61///   name <- function(x, ...) UseMethod("name")
62///   base::registerS3method("name", "default", .mx_shadow_default, envir = base::environment())
63///   base::rm(.mx_shadow_default)
64/// }
65/// # else: existing usable generic (primitive/S3/S4/S7) — reuse as-is.
66/// ```
67///
68/// `name` resolving to a **plain non-generic closure** (`var`, `get`, `row`,
69/// `col`, `diag`, `reshape`, …) is the #1248 bug: a bare `exists()` check
70/// sees the name is bound and never installs the `UseMethod` dispatcher, so
71/// the generated `name.Class` method is registered but silently never fires.
72/// The classifier shadows such bindings with a package-local generic and
73/// delegates the `default` method back to the masked closure, so ordinary
74/// (non-dispatching) calls like `var(1:10)` keep working. S3 generic formals
75/// are always `function(x, ...)`, so the delegation works positionally even
76/// when the masked closure's first argument has a different name (e.g.
77/// `reshape`'s is `data`) — S3 doesn't need S7's `dispatch_args`-mirroring
78/// `fallback_sig` machinery.
79///
80/// The delegating default method is registered via `base::registerS3method()`
81/// so it lives ONLY in the namespace's S3 methods table
82/// (`.__S3MethodsTable__.`), never as a `name.default` namespace binding:
83///
84/// - a literal `name.default` binding trips roxygen2's dynamic S3 scan
85///   (`warn_missing_s3_exports` walks the loaded namespace's bindings and
86///   flags any method-shaped function not covered by an
87///   `@export`/`@exportS3Method` block);
88/// - a static NAMESPACE `S3method(name, default)` directive would break
89///   package load whenever the shadow branch doesn't fire (e.g. for a real
90///   generic like `print`, where no `name.default` of ours exists — and we
91///   must never touch `print.default`).
92///
93/// Ordering inside the branch is load-bearing: `.mx_shadow_default` captures
94/// the masked closure BEFORE `name` is rebound (once `name` is the generic,
95/// `base::get("name")` would find our own generic → infinite recursion; the
96/// assignment inside `local()` forces the value now — a function *argument*
97/// would stay an unforced promise). The generic is bound at the branch top
98/// level (not inside `local()`) so its closure environment is the package
99/// namespace — `registerS3method` resolves the generic via
100/// `get(genname, envir)`, takes `environment(genfun)` as the defining env,
101/// and registers into THAT env's `.__S3MethodsTable__.`; the generic's env
102/// must be the namespace for the table to be the namespace's.
103/// `registerS3method` is called AFTER the generic is bound so it finds our
104/// generic (not the masked closure, whose home namespace would otherwise
105/// receive the registration). `base::rm` then drops the helper so the
106/// namespace ends with zero helper bindings.
107///
108/// The classifier condition is wrapped in `local({...})` so `.mx_gen` doesn't
109/// leak into the package namespace (the braced `else if` in the mirrored S7
110/// pattern evaluates at source time in the namespace env — see the
111/// corresponding fix at `s7_class.rs:902`, #1261 item 1).
112///
113/// Everything is `base::`-qualified (`exists`/`get`/`registerS3method`/
114/// `environment`/`rm`): once we define a shadow generic named e.g. `get`, a
115/// bare `get(...)` in a later generic's classifier would route through our
116/// own generic instead of the real `base::get`.
117///
118/// Use this for S3/vctrs class generators and trait-ABI wrappers. Do **not**
119/// use for S7 generics — those use `S7::new_generic()` / `S7::new_external_generic()`.
120pub(crate) fn emit_s3_generic_guard(name: &str) -> String {
121    // The assignment target must be an R symbol; operator generics such as
122    // `%custom%` need backticks there, while the string literals keep the bare
123    // name (#1475).
124    let symbol = crate::naming::r_def_name(name);
125    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (!base::exists(\"{0}\", mode = \"function\")) {{\n  {1} <- function(x, ...) UseMethod(\"{0}\")\n}} else if (local({{ .mx_gen <- base::get(\"{0}\", mode = \"function\"); !(is.primitive(.mx_gen) || isTRUE(utils::isS3stdGeneric(.mx_gen)) || methods::isGeneric(\"{0}\") || inherits(.mx_gen, \"S7_generic\")) }})) {{\n  # `{0}` is a plain closure that UseMethod dispatch will never consult.\n  # Shadow it with a package-local generic. The default method delegating to\n  # the masked closure is registered via registerS3method() so it lives ONLY\n  # in the namespace\'s S3 methods table: a literal `{0}.default` binding\n  # would trip roxygen2\'s dynamic S3 scan (warn_missing_s3_exports), and a\n  # static NAMESPACE S3method({0}, default) would break package load\n  # whenever this branch does not fire.\n  .mx_shadow_default <- local({{\n    .mx_masked <- base::get(\"{0}\", mode = \"function\")\n    function(x, ...) .mx_masked(x, ...)\n  }})\n  {1} <- function(x, ...) UseMethod(\"{0}\")\n  base::registerS3method(\"{0}\", \"default\", .mx_shadow_default, envir = base::environment())\n  base::rm(.mx_shadow_default)\n}}\n# else: existing usable generic (primitive/S3/S4/S7) — reuse as-is.",
                name, symbol))
    })format!(
126        "if (!base::exists(\"{name}\", mode = \"function\")) {{\n  {symbol} <- function(x, ...) UseMethod(\"{name}\")\n}} else if (local({{ .mx_gen <- base::get(\"{name}\", mode = \"function\"); !(is.primitive(.mx_gen) || isTRUE(utils::isS3stdGeneric(.mx_gen)) || methods::isGeneric(\"{name}\") || inherits(.mx_gen, \"S7_generic\")) }})) {{\n  # `{name}` is a plain closure that UseMethod dispatch will never consult.\n  # Shadow it with a package-local generic. The default method delegating to\n  # the masked closure is registered via registerS3method() so it lives ONLY\n  # in the namespace's S3 methods table: a literal `{name}.default` binding\n  # would trip roxygen2's dynamic S3 scan (warn_missing_s3_exports), and a\n  # static NAMESPACE S3method({name}, default) would break package load\n  # whenever this branch does not fire.\n  .mx_shadow_default <- local({{\n    .mx_masked <- base::get(\"{name}\", mode = \"function\")\n    function(x, ...) .mx_masked(x, ...)\n  }})\n  {symbol} <- function(x, ...) UseMethod(\"{name}\")\n  base::registerS3method(\"{name}\", \"default\", .mx_shadow_default, envir = base::environment())\n  base::rm(.mx_shadow_default)\n}}\n# else: existing usable generic (primitive/S3/S4/S7) — reuse as-is."
127    )
128}
129
130/// Check whether `s` is a bare R identifier (only `[A-Za-z_][A-Za-z0-9_]*`).
131pub(crate) fn is_bare_identifier(s: &str) -> bool {
132    let mut chars = s.chars();
133    match chars.next() {
134        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
135        _ => return false,
136    }
137    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
138}
139
140/// Return a `.__MX_CLASS_REF_<name>__` placeholder (for bare identifiers) so the
141/// resolver can look up the actual R class name at wrapper write time, or `name`
142/// verbatim (for namespaced / non-identifier strings).
143pub(crate) fn class_ref_or_verbatim(name: &str) -> String {
144    if is_bare_identifier(name) {
145        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".__MX_CLASS_REF_{0}__", name))
    })format!(".__MX_CLASS_REF_{name}__")
146    } else {
147        name.to_string()
148    }
149}
150
151/// The R name of the class that `system` wraps a value in, for the Rust type
152/// `name`, in an expansion other than the class's own impl block (a
153/// `WrapAs*` return, a trait impl): a write-time placeholder the wrappers
154/// writer resolves through `MX_CLASS_NAMES`, so a `class = "..."` rename
155/// applies there too (#2265, #2266). The class system stays the caller's;
156/// only the name comes from the registry.
157///
158/// A type with no impl block keeps its Rust name. Where any string is a class
159/// (S3, Env, vctrs) that is quiet, `.__MX_CLASS_REF_OR_BARE_<name>__`; where
160/// the named class object must exist (R6, S7, S4) the writer warns,
161/// `.__MX_CLASS_REF_<name>__` ([`class_ref_or_verbatim`]). `Self`, which the
162/// caller substitutes with the implementing class, and names that are not
163/// bare identifiers pass through.
164pub(crate) fn class_ref_for(system: ClassSystem, name: &str) -> String {
165    if name == "Self" || !is_bare_identifier(name) {
166        return name.to_string();
167    }
168    match system {
169        ClassSystem::R6 | ClassSystem::S7 | ClassSystem::S4 => class_ref_or_verbatim(name),
170        ClassSystem::S3 | ClassSystem::Env | ClassSystem::Vctrs => {
171            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".__MX_CLASS_REF_OR_BARE_{0}__",
                name))
    })format!(".__MX_CLASS_REF_OR_BARE_{name}__")
172        }
173    }
174}
175
176pub(crate) use crate::match_arg_keys::{
177    choices_placeholder as match_arg_placeholder,
178    param_doc_placeholder as match_arg_param_doc_placeholder,
179};
180
181/// Build the R-formal → auto-generated `@param` text map for a method's
182/// choice params: the write-time placeholder for a `match_arg` param (the
183/// wrapper writer renders it from the enum's `MatchArg::CHOICES`, #210), the
184/// literal `One of "a", "b".` line for a `choices(...)` param
185/// ([`ParamAttrs::literal_choices_doc`](crate::miniextendr_fn::ParamAttrs::literal_choices_doc),
186/// the same text a standalone function gets). Pass to
187/// `MethodDocBuilder::with_choice_param_docs` in each class generator.
188///
189/// Takes the per-param attribute map directly (rather than `&ParsedMethod`) so
190/// it's shared by both the inherent-impl (`MethodContext`) and trait-impl
191/// (`TraitMethodContext`, `miniextendr_impl_trait/method_context.rs`) paths.
192pub(crate) fn choice_param_doc_map(
193    c_ident: &str,
194    per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
195) -> std::collections::HashMap<String, String> {
196    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
197    let mut out = std::collections::HashMap::new();
198    for (rust_name, attrs) in per_param {
199        let doc = if attrs.match_arg {
200            match_arg_param_doc_placeholder(c_ident, &crate::match_arg_keys::param_key(rust_name))
201        } else if let Some(doc) = attrs.literal_choices_doc() {
202            doc
203        } else {
204            continue;
205        };
206        out.insert(formals.of(rust_name), doc);
207    }
208    out
209}
210
211/// Build R prelude lines that validate `match_arg` / `choices` / `several_ok`
212/// parameters before the `.Call()`.
213///
214/// Returns an empty vector when the method declares none. Every form is one
215/// statement from `CallAttribution::match_arg_statement` with the method's
216/// own attribution: the strict scalar helper (`NULL` and the formal default
217/// select the first choice, a factor is read as its labels), the `Option<T>`
218/// form that skips it for `NULL` (#1473), and the strict `several_ok` helper
219/// (every element must match, `NULL` selects all; #1472). An `Either` layer,
220/// over a scalar or a `several_ok` list (#1612), guards either helper with
221/// `is.character(x) || is.factor(x)`, so everything else reaches the `R`
222/// arm; `Missing` adds `!missing(x)` (#1551), and for a single choice
223/// `!.mx_absent_x`, a flag bound on the line before
224/// (`.mx_absent_x <- missing(x) || identical(x, <choices>)`, #2152, #2182;
225/// `CallAttribution::match_arg_lines`), which the `.Call()` argument reads
226/// too. The body that calls the method's `.Call()` must run these lines. For
227/// `match_arg` the
228/// choice list is the write-time placeholder (`c_ident` keys it, the same one
229/// `effective_r_defaults` puts in the formal); for `choices(...)` it is the
230/// literal.
231///
232/// The `match_arg` statements come first, then the `choices(...)` ones, each
233/// group in signature order (`inputs`), as in a standalone function's wrapper.
234///
235/// Shared by `MethodContext::match_arg_prelude` (inherent impls) and
236/// `TraitMethodContext::match_arg_prelude` (trait impls) — see
237/// `audit/2026-07-03-dogfooding-macros-codegen.md` finding #1 (trait methods
238/// previously had no match_arg support at all).
239pub(crate) fn build_match_arg_prelude(
240    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
241    per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
242    c_ident: &str,
243    attribution: crate::r_wrapper_builder::CallAttribution,
244) -> Vec<String> {
245    use crate::miniextendr_fn::per_param_in_signature_order;
246    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
247    let mut lines = Vec::new();
248
249    for (rust_name, attrs) in per_param_in_signature_order(inputs, per_param) {
250        if !attrs.match_arg {
251            continue;
252        }
253        let key = crate::match_arg_keys::param_key(rust_name);
254        let placeholder = match_arg_placeholder(c_ident, &key);
255        let aliases = crate::match_arg_keys::aliases_placeholder(c_ident, &key);
256        lines.extend(attribution.match_arg_lines(
257            &formals.of(rust_name),
258            &placeholder,
259            Some(&aliases),
260            attrs,
261        ));
262    }
263
264    for (rust_name, attrs) in per_param_in_signature_order(inputs, per_param) {
265        let Some(choices) = attrs.choices.as_ref() else {
266            continue;
267        };
268        let r_name = formals.of(rust_name);
269        let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", c))
    })format!("\"{c}\"")).collect();
270        let choices_expr = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "));
271        lines.extend(attribution.match_arg_lines(&r_name, &choices_expr, None, attrs));
272    }
273
274    lines
275}
276
277/// The R formals of the parameters that are validated by R's `match.arg()`
278/// and therefore don't need type-check preconditions generated for them.
279/// Shared by `MethodContext` and `TraitMethodContext`.
280pub(crate) fn match_arg_skip_set(
281    per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
282) -> std::collections::HashSet<String> {
283    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
284    per_param
285        .iter()
286        .filter(|(_, attrs)| attrs.match_arg || attrs.choices.is_some())
287        .map(|(rust_name, _)| formals.of(rust_name))
288        .collect()
289}
290
291/// Build the R-side precondition guard lines for a parameter list, given
292/// its per-param map (match_arg/choices skips, `inherits` / `not_inherits` /
293/// `no_na` checks, each parameter's own `preconditions` decision), whether
294/// `coerce` is active
295/// for the whole method, and the method's and impl block's `preconditions` /
296/// `no_preconditions` (`method_level`, `impl_level`). Each parameter keeps
297/// its type-derived checks as `crate::r_preconditions::resolve_type_checks`
298/// decides, under the crate default and the `no-preconditions-default`
299/// feature; the named checks stay either way.
300///
301/// Neither impl methods nor trait methods carry a per-param `coerce` flag
302/// (only function-wide `coerce`, see `ParsedMethod::per_param` docs), so
303/// `coerce_params` is always empty here. `call` is the call every failing
304/// guard is attributed to (`PreconditionOutput::guards`): `None` for the
305/// method's own frame, `environment()` for an S3 method (#1851). Shared by
306/// `MethodContext::precondition_checks`,
307/// `TraitMethodContext::precondition_checks` and the R6 active-binding
308/// setter.
309pub(crate) fn build_method_precondition_checks(
310    inputs: &syn::punctuated::Punctuated<syn::FnArg, ::syn::token::Commasyn::Token![,]>,
311    per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
312    coerce_all: bool,
313    method_level: Option<bool>,
314    impl_level: Option<bool>,
315    call: Option<&str>,
316) -> Vec<String> {
317    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
318    let opts = crate::r_preconditions::PreconditionOptions {
319        coerce_all,
320        coerce_params: std::collections::HashSet::new(),
321        explicit: crate::miniextendr_fn::explicit_checks_by_r_name(per_param),
322        unchecked: crate::r_preconditions::unchecked_params(
323            inputs,
324            &formals,
325            |name| per_param.get(name).and_then(|a| a.preconditions),
326            method_level,
327            impl_level,
328            crate::crate_config::preconditions_default(),
329        ),
330        formals,
331    };
332    crate::r_preconditions::build_precondition_checks(inputs, &match_arg_skip_set(per_param), &opts)
333        .guards(call)
334}
335
336/// Effective R-formal defaults for a method.
337///
338/// Layers defaults in priority order:
339/// 1. `#[miniextendr(match_arg)]` → ALWAYS a write-time placeholder that the
340///    wrapper writer resolves to `c("a", "b", ...)`. Any user-
341///    supplied `default = "X"` is consumed elsewhere (rotates X to the front
342///    of the choice list at write time) rather than overriding the formal.
343/// 2. `#[miniextendr(choices("a", "b", ...))]` → `c("a", "b", ...)` formal default.
344/// 3. User-provided `#[miniextendr(defaults(param = "..."))]` for non-match_arg
345///    params.
346///
347/// The `Option<T>` form of a choice parameter gets `NULL` instead (#1473),
348/// and a `no_default(p)` one no default at all (#1828; see
349/// [`ParamAttrs::choice_formal`](crate::miniextendr_fn::ParamAttrs::choice_formal)).
350/// A choice formal is documentation: the prelude
351/// ([`build_match_arg_prelude`]) passes the choice list to the helpers, which
352/// never read it off the formal (#1552). Shared by `MethodContext::new`
353/// (inherent impls) and `TraitMethodContext::new` (trait impls,
354/// `miniextendr_impl_trait/method_context.rs`).
355///
356/// `param_defaults` is keyed by Rust name, as `defaults(p = "...")` names
357/// the parameter; the result is keyed by R formal (#1842), as
358/// [`RArgumentBuilder::with_defaults`](crate::r_wrapper_builder::RArgumentBuilder::with_defaults)
359/// reads it.
360pub(crate) fn effective_r_defaults(
361    param_defaults: &std::collections::HashMap<String, String>,
362    per_param: &std::collections::HashMap<String, crate::miniextendr_fn::ParamAttrs>,
363    c_ident: &str,
364) -> std::collections::HashMap<String, String> {
365    let formals = crate::r_wrapper_builder::Formals::from_param_attrs(per_param);
366    let mut defaults = formals.rekey(param_defaults.clone());
367    // match_arg → unconditionally splice the placeholder (overriding any user
368    // default, which is captured separately for write-time rotation).
369    for (rust_name, attrs) in per_param {
370        if !attrs.match_arg {
371            continue;
372        }
373        let key = crate::match_arg_keys::param_key(rust_name);
374        // `Option<T>` (#1473): the formal is NULL (no choice); `no_default`
375        // (#1828, refused with `defaults(p = ...)`): none. The prelude spells
376        // the choices out through the placeholder either way.
377        if let Some(default) = attrs.choice_formal(&match_arg_placeholder(c_ident, &key)) {
378            defaults.insert(formals.of(rust_name), default);
379        }
380    }
381    // choices(...) → c("a", "b", ...) formal (NULL for the `Option<T>` form,
382    // none under `no_default`). Lower priority than user defaults (kept for
383    // back-compat on non-match_arg params).
384    for (rust_name, attrs) in per_param {
385        let Some(choices) = attrs.choices.as_ref() else {
386            continue;
387        };
388        let quoted: Vec<String> = choices.iter().map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", c))
    })format!("\"{c}\"")).collect();
389        if let Some(default) = attrs.choice_formal(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "))) {
390            defaults.entry(formals.of(rust_name)).or_insert(default);
391        }
392    }
393    defaults
394}
395
396/// Pre-computed context for a method, holding all data needed for R wrapper generation.
397///
398/// This struct captures the common computations performed for every method across all
399/// class systems, reducing duplicate code. It pre-formats the C wrapper name, R formal
400/// parameters (with defaults), and R call arguments so each class generator can
401/// focus on its specific formatting logic.
402pub struct MethodContext<'a> {
403    /// Reference to the parsed method metadata.
404    pub method: &'a ParsedMethod,
405    /// The C wrapper identifier string (e.g., `"C_Counter__inc"`), used in `.Call()`.
406    pub c_ident: String,
407    /// R formals string with defaults (e.g., `"value, step = 1L"`), used in
408    /// `function(...)` signatures.
409    pub params: String,
410    /// R call arguments string without defaults (e.g., `"value, step"`), used
411    /// inside `.Call()` expressions.
412    pub args: String,
413    /// The impl block's `preconditions` / `no_preconditions`
414    /// (`ImplAttrs::preconditions`): below the method's own and each
415    /// parameter's, above the crate default (see
416    /// `build_method_precondition_checks`).
417    pub impl_preconditions: Option<bool>,
418    /// The call the method's conditions report (`CallAttribution`): the
419    /// method's own `sys.call()` by default; an S3 method's generator sets
420    /// `CallAttribution::Generic`, the frame resolved to the generic's call
421    /// on a raise (#1851). It decides the `.call` of `instance_call`, the
422    /// call the R-side checks raise with and the raise fallback.
423    pub call_attribution: crate::r_wrapper_builder::CallAttribution,
424}
425
426impl<'a> MethodContext<'a> {
427    /// Create a new MethodContext for a method.
428    ///
429    /// Computes the C wrapper identifier from the method name and type name,
430    /// then formats the R formals and call arguments from the method's
431    /// signature and default values. The
432    /// impl block says nothing about the R-side checks; use
433    /// [`MethodContext::with_impl_preconditions`] to inherit its
434    /// `preconditions` / `no_preconditions`.
435    pub fn new(method: &'a ParsedMethod, type_ident: &syn::Ident) -> Self {
436        let c_ident = method.c_wrapper_ident(type_ident).to_string();
437        let effective_defaults = effective_r_defaults(
438            &method.param_defaults,
439            &method.method_attrs.per_param,
440            &c_ident,
441        );
442        let arg_builder = crate::r_wrapper_builder::RArgumentBuilder::new(&method.sig.inputs)
443            .with_formals(method.formals())
444            .with_defaults(effective_defaults)
445            .with_absent_formals(crate::miniextendr_fn::absent_formals_by_r_name(
446                &method.method_attrs.per_param,
447            ));
448        let params = arg_builder.build_formals();
449        let args = arg_builder.build_call_args();
450        Self {
451            method,
452            c_ident,
453            params,
454            args,
455            impl_preconditions: None,
456            call_attribution: crate::r_wrapper_builder::CallAttribution::Wrapper,
457        }
458    }
459
460    /// For a body that calls the method without its prelude
461    /// ([`Self::match_arg_prelude`]): an `as = "..."` coercion method
462    /// (#1830) or an S7 property getter / setter lambda. [`Self::args`] then
463    /// reads no `.mx_absent_<p>` flag, which only the prelude binds (#2182),
464    /// so a `Missing<..>` choice is forwarded as omitted only when it is.
465    pub fn without_prelude(mut self) -> Self {
466        self.args = crate::r_wrapper_builder::RArgumentBuilder::new(&self.method.sig.inputs)
467            .with_formals(self.method.formals())
468            .build_call_args();
469        self
470    }
471
472    /// Set the `preconditions` decision inherited from the surrounding
473    /// `ImplAttrs`. Returns `self` so callers can chain on top of
474    /// `MethodContext::new`.
475    pub fn with_impl_preconditions(mut self, impl_preconditions: Option<bool>) -> Self {
476        self.impl_preconditions = impl_preconditions;
477        self
478    }
479
480    /// Set the call the method's conditions report (see
481    /// [`MethodContext::call_attribution`]).
482    pub fn with_call_attribution(
483        mut self,
484        call_attribution: crate::r_wrapper_builder::CallAttribution,
485    ) -> Self {
486        self.call_attribution = call_attribution;
487        self
488    }
489
490    /// Build the R-param-name → `@param` text map for this method's
491    /// `match_arg` / `choices` params ([`choice_param_doc_map`]) and its
492    /// `Missing<..>` params with a default
493    /// ([`missing_default_param_docs`](crate::miniextendr_fn::missing_default_param_docs),
494    /// #2161). Pass to `MethodDocBuilder::with_choice_param_docs`.
495    pub fn choice_param_docs(&self) -> std::collections::HashMap<String, String> {
496        let per_param = &self.method.method_attrs.per_param;
497        let mut docs = choice_param_doc_map(&self.c_ident, per_param);
498        docs.extend(crate::miniextendr_fn::missing_default_param_docs(
499            &self.method.sig.inputs,
500            per_param,
501            &self.method.param_defaults,
502            &self.method.formals(),
503        ));
504        docs
505    }
506
507    /// Build R prelude lines that validate `match_arg` / `choices` / `several_ok`
508    /// parameters via `base::match.arg()` before the `.Call()`.
509    ///
510    /// Returns an empty vector when the method declares none. Both `match_arg`
511    /// and `choices(...)` carry their choice list as the formal default
512    /// (`c("a", "b", ...)`), so `base::match.arg(arg)` finds the list by
513    /// itself — no second arg, no C helper lookup. `match_arg` adds a
514    /// factor → character coercion in front of `match.arg`.
515    ///
516    /// Callers should include these lines in the R wrapper body after parameter
517    /// defaulting but before the `.Call()`.
518    pub fn match_arg_prelude(&self) -> Vec<String> {
519        build_match_arg_prelude(
520            &self.method.sig.inputs,
521            &self.method.method_attrs.per_param,
522            &self.c_ident,
523            self.call_attribution,
524        )
525    }
526
527    /// Build the `.Call()` expression for a static/constructor call.
528    pub fn static_call(&self) -> String {
529        crate::r_wrapper_builder::DotCallBuilder::new(&self.c_ident)
530            .with_args_str(&self.args)
531            .build()
532    }
533
534    /// Build the `.Call()` expression for an instance method with `self` as ptr.
535    ///
536    /// The `self_expr` is typically "self", "private$.ptr", "x", "x@ptr", or "x@.ptr".
537    /// The `.call` is the context's [`MethodContext::call_attribution`].
538    pub fn instance_call(&self, self_expr: &str) -> String {
539        crate::r_wrapper_builder::DotCallBuilder::new(&self.c_ident)
540            .with_call_attribution(self.call_attribution)
541            .with_self(self_expr)
542            .with_args_str(&self.args)
543            .build()
544    }
545
546    /// Like [`instance_call`](Self::instance_call) but passes `.call = NULL`.
547    ///
548    /// Use for lambda dispatch sites (S7 property getter/setter) where
549    /// `sys.call()` names the S7 dispatch frame, not the user's call.
550    pub fn instance_call_null_attr(&self, self_expr: &str) -> String {
551        crate::r_wrapper_builder::DotCallBuilder::new(&self.c_ident)
552            .null_call_attribution()
553            .with_self(self_expr)
554            .with_args_str(&self.args)
555            .build()
556    }
557
558    /// Full R formals of a `<generic>.<Class>` S3 method: `"x, <params>, ..."`,
559    /// except that for a replacement generic (a name ending in `<-`, such as
560    /// `[[<-` or `names<-`) the dispatch `...` goes before the last formal,
561    /// `"x, i, ..., value"`. `R CMD check` (`tools::checkReplaceFuns()`)
562    /// requires a replacement method's last formal to be `value`, and the
563    /// impl-block check (`check_s3_replacement_methods`) makes sure it is
564    /// (#1853). A method that takes `&Dots` keeps its own order.
565    pub fn s3_method_formals(&self) -> String {
566        let receiver = self.method.method_attrs.receiver.as_deref().unwrap_or("x");
567        let dots = !self.method.method_attrs.no_dispatch_dots;
568        if !dots || self.method.has_dots || !self.generic_name().ends_with("<-") {
569            return self.instance_formals_with_receiver(receiver, dots);
570        }
571        let mut formals = crate::roxygen::split_r_formals(&self.params);
572        formals.retain(|formal| !formal.is_empty());
573        let last = formals.pop();
574        let mut out = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [receiver]))vec![receiver];
575        out.extend(formals);
576        out.push("...");
577        out.extend(last);
578        out.join(", ")
579    }
580
581    /// Build instance formals with a custom receiver name (default is `x`).
582    ///
583    /// Used by S3/S4 generic overrides and the S7 per-class shortcut.
584    pub fn instance_formals_with_receiver(&self, receiver: &str, include_dots: bool) -> String {
585        instance_formals(
586            &self.params,
587            receiver,
588            include_dots && !self.method.has_dots,
589        )
590    }
591
592    /// Get the generic name (uses override if present).
593    pub fn generic_name(&self) -> String {
594        // Explicit `generic = ".."` wins; otherwise the R-facing method name
595        // (`r_name` / `postfix` / Rust ident) doubles as the generic, so a
596        // renamed S3/S7 instance method dispatches under its R name.
597        self.method
598            .method_attrs
599            .generic
600            .clone()
601            .unwrap_or_else(|| self.method.r_method_name())
602    }
603
604    /// Generate a source location comment for this method.
605    ///
606    /// Returns a string like `# Type::method (lib.rs:114:12)`. The position
607    /// carries the file name ([`crate::source_position`]) so the wrapper
608    /// writer's position-only comparison covers it: a bare `(114:12)` would
609    /// rewrite the wrappers whenever a line above the impl block moved.
610    pub fn source_comment(&self, type_ident: &syn::Ident) -> String {
611        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# {0}::{1} {2}", type_ident,
                self.method.ident,
                crate::source_position(self.method.ident.span())))
    })format!(
612            "# {}::{} {}",
613            type_ident,
614            self.method.ident,
615            crate::source_position(self.method.ident.span()),
616        )
617    }
618
619    /// Check if this method uses a generic override (for existing generics like print).
620    pub fn has_generic_override(&self) -> bool {
621        self.method.method_attrs.generic.is_some()
622    }
623
624    /// Get custom class suffix if specified.
625    ///
626    /// This allows double-dispatch patterns like `vec_ptype2.my_class.my_class`
627    /// by specifying `#[miniextendr(s3(generic = "vec_ptype2", class = "my_class.my_class"))]`.
628    pub fn class_suffix(&self) -> Option<&str> {
629        self.method.method_attrs.class.as_deref()
630    }
631
632    /// Check if this method uses a custom class suffix.
633    pub fn has_class_override(&self) -> bool {
634        self.method.method_attrs.class.is_some()
635    }
636
637    /// Build the R-side precondition guard lines for this method's parameters.
638    ///
639    /// Returns static checks for known types. Custom types not in the static table
640    /// are identified as fallback params but no R-side precheck is generated for them.
641    ///
642    /// Skips `self`/receiver parameters automatically (they are `FnArg::Receiver`) and
643    /// any parameter validated by `base::match.arg()` (via `match_arg` / `choices`) —
644    /// those already have a stronger runtime guarantee than an `is.character()` check.
645    ///
646    /// Each parameter keeps or drops its type-derived checks as its own
647    /// spelling, the method's, the impl block's, the crate default and the
648    /// feature decide ([`build_method_precondition_checks`]); the
649    /// per-parameter `inherits(...)` / `not_inherits(...)` / `no_na(...)`
650    /// checks stay.
651    pub fn precondition_checks(&self) -> Vec<String> {
652        // A coerced integer-element vector reads via `&[i32]` (INTSXP-only), so
653        // its precondition tightens to `is.integer` (#616). Impl methods carry
654        // coerce at method level (`method_attrs.coerce`, equivalent to
655        // `coerce_all`); there is no per-param coerce on the impl path (see
656        // ParsedMethod::per_param docs).
657        build_method_precondition_checks(
658            &self.method.sig.inputs,
659            &self.method.method_attrs.per_param,
660            self.method.method_attrs.coerce,
661            self.method.method_attrs.preconditions,
662            self.impl_preconditions,
663            self.call_attribution.r_check_call(),
664        )
665    }
666
667    /// Emit the 7-step method prelude into `lines`, each line prefixed with `indent`.
668    ///
669    /// The prelude is the standardised sequence that appears at the top of every
670    /// generated R method body, in order:
671    ///
672    /// 1. `r_entry` — user code injected before any checks
673    /// 2. `r_on_exit` — `on.exit(...)` cleanup
674    /// 3. `lifecycle_prelude` — deprecation/superseded banner (class-system-specific label)
675    /// 4. the `...` check of `dots = empty | forward(..)` (#2157,
676    ///    [`DotsPolicy::r_check`](crate::dots_policy::DotsPolicy::r_check)),
677    ///    which reads the wrapper's `formals` (the R formals list of the
678    ///    `function()` the prelude opens) and is skipped when they have no `...`
679    /// 5. `precondition_checks` — one `isTRUE()` guard per check on typed params
680    /// 6. `match_arg_prelude` — `base::match.arg(param)` validation
681    /// 7. `r_post_checks` — user code after all checks, before `.Call()`
682    ///
683    /// (`Missing<T>` forwarding is not a prelude step: it lives inline in the
684    /// `.Call()` args — see `build_call_args_vec` — because a binding of the
685    /// missing sentinel errors on lookup.)
686    ///
687    /// `what` is the human-readable method label passed to `lifecycle_prelude`
688    /// (e.g., `"Type.method"` for S3/S4, `"Type$method"` for Env/R6/S7).
689    /// `indent` is the per-line prefix (e.g., `"  "` for 2-space, `"      "` for 6-space).
690    pub fn emit_method_prelude(
691        &self,
692        lines: &mut Vec<String>,
693        indent: &str,
694        what: &str,
695        formals: &str,
696    ) {
697        let m = self.method;
698        if let Some(ref entry) = m.method_attrs.r_entry {
699            for line in entry.lines() {
700                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{}{}", indent, line));
701            }
702        }
703        if let Some(ref on_exit) = m.method_attrs.r_on_exit {
704            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent,
                on_exit.to_r_code()))
    })format!("{}{}", indent, on_exit.to_r_code()));
705        }
706        if let Some(prelude) = m.lifecycle_prelude(what) {
707            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, prelude))
    })format!("{}{}", indent, prelude));
708        }
709        if let Some(check) = m
710            .method_attrs
711            .dots_policy
712            .as_ref()
713            .and_then(|policy| policy.r_check(formals, self.call_attribution.r_check_call()))
714        {
715            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, check))
    })format!("{}{}", indent, check));
716        }
717        for check in self.precondition_checks() {
718            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, check))
    })format!("{}{}", indent, check));
719        }
720        for line in self.match_arg_prelude() {
721            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{}{}", indent, line));
722        }
723        if let Some(ref post) = m.method_attrs.r_post_checks {
724            for line in post.lines() {
725                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{}{}", indent, line));
726            }
727        }
728    }
729}
730
731// region: generated parameter docs
732
733/// The formals of `r_params` that `doc_tags` leaves undocumented, each with
734/// its choice text from `choice_docs` (the write-time placeholder of a
735/// `match_arg` parameter, the literal line of a `choices(...)` one), or
736/// `None` for a formal that has none. Skips `.mx_self`, `.ptr` and `...`, and
737/// yields nothing when the tags take the arguments from another topic
738/// (`roxygen::params_documented_elsewhere` against `page`, #1590). The class
739/// page default a builder appends is not in `doc_tags`, and an author
740/// `@rdname` naming `page` is the same page, so neither suppresses them.
741///
742/// Splits on top-level commas only: a naive `split(", ")` shreds a
743/// `mode = c("fast", "slow")` default into a bogus `"slow")` formal.
744fn generated_params<'p, 'd>(
745    r_params: &'p str,
746    doc_tags: &[String],
747    page: &str,
748    choice_docs: Option<&'d std::collections::HashMap<String, String>>,
749) -> Vec<(&'p str, Option<&'d str>)> {
750    if crate::roxygen::params_documented_elsewhere(doc_tags, Some(page)) {
751        return Vec::new();
752    }
753    crate::roxygen::split_r_formals(r_params)
754        .into_iter()
755        .map(crate::roxygen::formal_name)
756        .filter(|name| !#[allow(non_exhaustive_omitted_patterns)] match *name {
    ".ptr" | "..." | ".mx_self" => true,
    _ => false,
}matches!(*name, ".ptr" | "..." | ".mx_self"))
757        .filter(|name| !crate::roxygen::param_documented(doc_tags, name))
758        .map(|name| {
759            let choice = choice_docs
760                .and_then(|docs| docs.get(name))
761                .map(String::as_str);
762            (name, choice)
763        })
764        .collect()
765}
766
767/// Push one `#' @param name text` line per [`generated_params`] entry: the
768/// choice text for a choice parameter, `(undocumented)` otherwise (so
769/// `R CMD check` codoc sees every formal in `\usage` documented).
770fn push_param_filler(
771    lines: &mut Vec<String>,
772    r_params: &str,
773    doc_tags: &[String],
774    page: &str,
775    choice_docs: Option<&std::collections::HashMap<String, String>>,
776) {
777    for (name, choice) in generated_params(r_params, doc_tags, page, choice_docs) {
778        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {1} {0}",
                choice.unwrap_or("(undocumented)"), name))
    })format!(
779            "#' @param {name} {}",
780            choice.unwrap_or("(undocumented)")
781        ));
782    }
783}
784
785/// The documentation body of a method block that has no `\usage` (env
786/// methods): the author tags `forward` accepts, verbatim, then one
787/// `\describe{}` list with the author's `@param` items followed by the
788/// choice items of [`generated_params`]. A formal without choice text gets no
789/// item (nothing in `\usage` asks for one), and no `@param` line is emitted:
790/// with no usage entry to match, roxygen2 would write an `\arguments` entry
791/// that `R CMD check` reports as "Documented arguments not in \usage".
792///
793/// After a forwarded `@description` / `@details`, the list continues that
794/// section after a blank line; after `@examples` / `@examplesIf`, whose code
795/// block a blank line does not end, it opens a `@details`. Otherwise
796/// `@description Arguments of \code{<label>()}:` and a blank line open it:
797/// roxygen2 runs a tag's text up to the next tag, so after any other tag
798/// (`@return`, `@seealso`, `@title`, ...) the list would land in that tag's
799/// section, and an untagged list would be the block's intro paragraph, i.e.
800/// its title, which roxygen2 drops on the class page the block merges into.
801///
802/// `doc_tags` is the full tag list, so a page tag that `forward` rejects
803/// still sends the arguments elsewhere. Emits nothing when there is neither a
804/// forwarded tag nor an item.
805pub(crate) fn describe_params_lines(
806    doc_tags: &[String],
807    forward: impl Fn(&str) -> bool,
808    r_params: &str,
809    page: &str,
810    choice_docs: Option<&std::collections::HashMap<String, String>>,
811    label: &str,
812) -> Vec<String> {
813    let (param_tags, other_tags): (Vec<&str>, Vec<&str>) = doc_tags
814        .iter()
815        .map(String::as_str)
816        .filter(|tag| forward(tag))
817        .partition(|tag| tag.trim_start().starts_with("@param "));
818    let item = |name: &str, desc: &str| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  \\item{{\\code{{{0}}}}}{{{1}}}",
                name, desc))
    })format!("  \\item{{\\code{{{name}}}}}{{{desc}}}");
819    let mut items: Vec<String> = param_tags
820        .iter()
821        .filter_map(|tag| {
822            let rest = tag.trim_start().strip_prefix("@param ")?;
823            let (name, desc) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
824            Some(item(name, desc))
825        })
826        .collect();
827    items.extend(
828        generated_params(r_params, doc_tags, page, choice_docs)
829            .into_iter()
830            .filter_map(|(name, choice)| Some(item(name, choice?))),
831    );
832
833    let mut lines = Vec::new();
834    crate::roxygen::push_roxygen_tags_str(&mut lines, &other_tags);
835    if items.is_empty() {
836        return lines;
837    }
838    match other_tags
839        .last()
840        .and_then(|tag| crate::roxygen::roxygen_tag_name(tag))
841    {
842        Some("description" | "details") => lines.push("#'".to_string()),
843        Some("examples" | "examplesIf") => lines.push("#' @details".to_string()),
844        _ => {
845            // `%` starts an Rd comment and `\` an escape, also inside `\code{}`.
846            let label = label.replace('\\', "\\\\").replace('%', "\\%");
847            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @description Arguments of \\code{{{0}()}}:",
                label))
    })format!("#' @description Arguments of \\code{{{label}()}}:"));
848            lines.push("#'".to_string());
849        }
850    }
851    lines.push("#' \\describe{".to_string());
852    // One `#' ` per line, so a wrapped `@param` stays inside the block.
853    let item_refs: Vec<&str> = items.iter().map(String::as_str).collect();
854    crate::roxygen::push_roxygen_tags_str(&mut lines, &item_refs);
855    lines.push("#' }".to_string());
856    lines
857}
858
859// endregion
860
861/// Builder for class-level roxygen documentation header.
862///
863/// Generates the common roxygen tags that appear at the start of each class definition:
864/// - `@title` (unless user provided)
865/// - `@name` (unless user provided)
866/// - `@rdname` (unless user provided)
867/// - User-provided doc tags, as the [`CLASS_DOCS_MARKER`] line: the wrapper
868///   writer puts there the doc tags of every impl block of the type
869///   ([`ClassDocBuilder::docs`])
870/// - `@param` for the constructor formals the tags leave undocumented, when
871///   set (`with_ctor_params`; S3 and vctrs, whose class block is the
872///   constructor's block)
873/// - `@source Generated by miniextendr...`
874/// - Class-system-specific imports
875/// - `@export` (unless user provided, `@noRd`, or internal/noexport flags)
876///
877/// The generated `@title`, `@name`, `@rdname`, `@param` and `@export` lines
878/// are [`class_default`]s, which a tag on another impl block replaces.
879pub struct ClassDocBuilder<'a> {
880    /// The R-visible class name (e.g., `"Counter"`).
881    class_name: &'a str,
882    /// The Rust type identifier, used in the `@source` annotation.
883    type_ident: &'a syn::Ident,
884    /// User-provided roxygen tags extracted from doc comments.
885    doc_tags: &'a [String],
886    /// Human-readable label for the class system (e.g., `"R6"`, `"S3"`), used in
887    /// the auto-generated `@title`. Empty for Env classes, whose title is plain
888    /// `"<Class> Class"`.
889    class_system_label: &'static str,
890    /// Optional `@importFrom` tag for class-system-specific R packages
891    /// (e.g., `"@importFrom R6 R6Class"`).
892    imports: Option<String>,
893    /// When `true`, adds `@keywords internal` and suppresses `@export`.
894    /// Set by `#[miniextendr(internal)]`.
895    attr_internal: bool,
896    /// When `true`, suppresses `@export` but does not add `@keywords internal`.
897    /// Set by `#[miniextendr(noexport)]`.
898    attr_noexport: bool,
899    /// The constructor's R formals and its choice-parameter `@param` text
900    /// ([`choice_param_doc_map`]), for classes whose class block documents
901    /// the constructor (S3, vctrs). See [`ClassDocBuilder::with_ctor_params`].
902    ctor_params: Option<(&'a str, &'a std::collections::HashMap<String, String>)>,
903}
904
905impl<'a> ClassDocBuilder<'a> {
906    /// Create a new ClassDocBuilder with the given class metadata.
907    ///
908    /// By default, `@export` is included unless suppressed by user tags or
909    /// the `with_export_control` method.
910    pub fn new(
911        class_name: &'a str,
912        type_ident: &'a syn::Ident,
913        doc_tags: &'a [String],
914        class_system_label: &'static str,
915    ) -> Self {
916        Self {
917            class_name,
918            type_ident,
919            doc_tags,
920            class_system_label,
921            imports: None,
922            attr_internal: false,
923            attr_noexport: false,
924            ctor_params: None,
925        }
926    }
927
928    /// Document the constructor's formals on the class block: each formal the
929    /// doc tags leave undocumented gets `@param name <choice text>` for a
930    /// choice parameter and `@param name (undocumented)` otherwise, right after
931    /// the doc tags. Nothing under `@noRd` / plain `noexport`, or when the tags
932    /// take the arguments from another topic (`@rdname other`,
933    /// `@inheritParams`). For generators whose class block is the
934    /// constructor's block (S3 `new_<class>()`, vctrs `new_<class>()`).
935    pub fn with_ctor_params(
936        mut self,
937        params: &'a str,
938        choice_docs: &'a std::collections::HashMap<String, String>,
939    ) -> Self {
940        self.ctor_params = Some((params, choice_docs));
941        self
942    }
943
944    /// Set R package imports (e.g., "@importFrom R6 R6Class").
945    pub fn with_imports(mut self, imports: impl Into<String>) -> Self {
946        self.imports = Some(imports.into());
947        self
948    }
949
950    /// Set attribute-level internal/noexport flags from `ParsedImpl`.
951    pub fn with_export_control(mut self, internal: bool, noexport: bool) -> Self {
952        self.attr_internal = internal;
953        self.attr_noexport = noexport;
954        self
955    }
956
957    /// The user-provided doc tags as roxygen lines, for
958    /// [`ClassWrapper::class_docs`](crate::miniextendr_impl::ClassWrapper::class_docs).
959    pub fn docs(&self) -> Vec<String> {
960        let mut lines = Vec::new();
961        crate::roxygen::push_roxygen_tags(&mut lines, self.doc_tags);
962        lines
963    }
964
965    /// The class header as the writer writes a type with one impl block: the
966    /// [`docs`](Self::docs) in place of the marker, every default kept.
967    #[cfg(test)]
968    pub fn render(&self) -> Vec<String> {
969        self.build()
970            .into_iter()
971            .flat_map(|line| {
972                if line == CLASS_DOCS_MARKER {
973                    self.docs()
974                } else {
975                    vec![
976                        line.strip_prefix(crate::miniextendr_impl::CLASS_DEFAULT_PREFIX)
977                            .unwrap_or(&line)
978                            .to_string(),
979                    ]
980                }
981            })
982            .collect()
983    }
984
985    /// Build the roxygen `#' @tag` lines for the class header.
986    ///
987    /// Returns a vector of strings, each a complete roxygen comment line (e.g., `"#' @title ..."`),
988    /// a [`class_default`] or the [`CLASS_DOCS_MARKER`].
989    /// Auto-generates `@title`, `@name`, and `@rdname` if not provided by the user, and
990    /// respects `@noRd` to suppress all documentation output.
991    pub fn build(&self) -> Vec<String> {
992        let has_title = crate::roxygen::has_roxygen_tag(self.doc_tags, "title");
993        let has_name = crate::roxygen::has_roxygen_tag(self.doc_tags, "name");
994        let has_rdname = crate::roxygen::has_roxygen_tag(self.doc_tags, "rdname");
995        let has_export = crate::roxygen::has_roxygen_tag(self.doc_tags, "export");
996        let has_no_rd = crate::roxygen::has_roxygen_tag(self.doc_tags, "noRd");
997        let has_internal = crate::roxygen::has_roxygen_tag(self.doc_tags, "keywords internal");
998        let effective_internal = has_internal || self.attr_internal;
999
1000        // `noexport` (without `internal`) must produce no Rd contribution at all —
1001        // no alias, no usage entry, nothing on a shared page — distinct from
1002        // `internal`, which stays documented under `\keyword{internal}`. Fold a
1003        // plain `noexport` into the same suppression gate as a user-written
1004        // `@noRd`. `internal` wins if both flags are set on the same impl block
1005        // (mirrors the standalone-fn `#[miniextendr(internal)]` precedence, where
1006        // `internal` + `noexport` together is a compile error).
1007        let suppress_rd = has_no_rd || (self.attr_noexport && !effective_internal);
1008
1009        let mut lines = Vec::new();
1010
1011        if suppress_rd && !has_no_rd {
1012            lines.push("#' @noRd".to_string());
1013        }
1014
1015        if !has_title && !suppress_rd {
1016            // Env classes pass an empty label: "Counter Class", not "Counter  Class".
1017            let title = if self.class_system_label.is_empty() {
1018                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} Class", self.class_name))
    })format!("{} Class", self.class_name)
1019            } else {
1020                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1} Class", self.class_name,
                self.class_system_label))
    })format!("{} {} Class", self.class_name, self.class_system_label)
1021            };
1022            lines.push(class_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", title))
    })format!("#' @title {title}")));
1023        }
1024        if !has_name && !suppress_rd {
1025            lines.push(class_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", self.class_name))
    })format!("#' @name {}", self.class_name)));
1026        }
1027        if !has_rdname && !suppress_rd {
1028            lines.push(class_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", self.class_name))
    })format!("#' @rdname {}", self.class_name)));
1029        }
1030        lines.push(CLASS_DOCS_MARKER.to_string());
1031        if !suppress_rd {
1032            if let Some((params, choice_docs)) = self.ctor_params {
1033                let mut filler = Vec::new();
1034                push_param_filler(
1035                    &mut filler,
1036                    params,
1037                    self.doc_tags,
1038                    self.class_name,
1039                    Some(choice_docs),
1040                );
1041                lines.extend(filler.into_iter().map(class_default));
1042            }
1043            // An impl-level `@rdname topic` puts the class block on an author
1044            // topic, whose own block names and titles the page (#1590).
1045            crate::roxygen::push_order_after_topic_blocks(
1046                &mut lines,
1047                self.doc_tags,
1048                self.class_name,
1049            );
1050            lines.extend(crate::roxygen::class_source_tag(self.type_ident));
1051        }
1052        if let Some(ref imports) = self.imports
1053            && !suppress_rd
1054        {
1055            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", imports))
    })format!("#' {}", imports));
1056        }
1057        // Inject @keywords internal if attr flag set and not already present
1058        if self.attr_internal && !has_internal && !suppress_rd {
1059            lines.push("#' @keywords internal".to_string());
1060        }
1061        // Don't auto-export if @noRd, @keywords internal, or attr flags are present
1062        if !has_export && !suppress_rd && !effective_internal && !self.attr_noexport {
1063            lines.push(class_default("#' @export"));
1064        }
1065
1066        lines
1067    }
1068}
1069
1070/// Builder for method-level roxygen documentation.
1071///
1072/// Generates roxygen tags for individual methods within a class. Methods share
1073/// the class's `@rdname` so they appear on the same help page. The builder handles
1074/// `@name` formatting (with optional prefix like `$` for `Class$method` style)
1075/// and respects `@noRd` inheritance from the parent class.
1076pub struct MethodDocBuilder<'a> {
1077    /// The R class name (e.g., `"Counter"`).
1078    class_name: &'a str,
1079    /// The Rust method name (e.g., `"inc"`).
1080    method_name: &'a str,
1081    /// The Rust type identifier, used in the `@source` annotation.
1082    type_ident: &'a syn::Ident,
1083    /// User-provided roxygen tags extracted from the method's doc comments.
1084    doc_tags: &'a [String],
1085    /// Optional separator between class name and method name in `@name`
1086    /// (e.g., `"$"` produces `@name Counter$inc`).
1087    name_prefix: Option<&'a str>,
1088    /// Override for the `@name` tag when the R function name differs from the Rust
1089    /// method name (e.g., for standalone S3 methods like `format.my_class`).
1090    r_name_override: Option<String>,
1091    /// When `true`, adds `@export` to the method (used for standalone S3/S4 generics).
1092    /// Defaults to `false` because `Class$method` access does not need separate export.
1093    always_export: bool,
1094    /// Whether the parent class has `@noRd`. When `true`, this method emits only
1095    /// `#' @noRd` and skips all other documentation tags.
1096    class_has_no_rd: bool,
1097    /// When `true`, convert `@param` tags into `\describe{}` blocks instead of
1098    /// roxygen `@param` entries, with the choice text of undocumented choice
1099    /// parameters as extra items ([`describe_params_lines`]).
1100    ///
1101    /// Used for env-class methods where roxygen cannot infer `\usage` from
1102    /// `Class$method <- function()`. Without this, `@param` tags create
1103    /// `\arguments` entries with no matching `\usage`, causing R CMD check
1104    /// warnings ("Documented arguments not in \\usage").
1105    params_as_details: bool,
1106    /// Optional comma-separated R parameter string for auto-generating `@param` tags.
1107    /// When set, any parameter not already documented gets `@param name (undocumented)`
1108    /// (in `params_as_details` mode only a choice parameter gets an item).
1109    r_params: Option<&'a str>,
1110    /// When `true`, filter out `@param` tags from the doc_tags before pushing.
1111    ///
1112    /// Used for S4/S7 instance methods where the method is defined via `setMethod()`
1113    /// or `S7::method()` assignment, which roxygen2 doesn't parse for `\usage` entries.
1114    /// Including `@param` tags would create "Documented arguments not in \\usage" warnings.
1115    suppress_params: bool,
1116    /// Map of R-param-name → auto-generated `@param` text for choice
1117    /// parameters ([`choice_param_doc_map`]).
1118    ///
1119    /// When the auto-generated `@param` line would otherwise say `(undocumented)`,
1120    /// a `match_arg` param emits its placeholder instead, which the wrapper
1121    /// writer replaces with a rendered choice description (#210), and
1122    /// a `choices(...)` param its literal `One of ...` line.
1123    choice_param_docs: Option<&'a std::collections::HashMap<String, String>>,
1124    /// The Rust method named by the `@source Generated by miniextendr from
1125    /// `Type::method`` line ([`with_source_method`](Self::with_source_method)),
1126    /// else `method_name`.
1127    source_method: Option<&'a syn::Ident>,
1128}
1129
1130impl<'a> MethodDocBuilder<'a> {
1131    /// Create a new MethodDocBuilder with default settings.
1132    ///
1133    /// By default, `always_export` is `false` because methods accessed via `Class$method`
1134    /// should not be exported directly -- only the class env and standalone S3 methods
1135    /// need `@export`.
1136    pub fn new(
1137        class_name: &'a str,
1138        method_name: &'a str,
1139        type_ident: &'a syn::Ident,
1140        doc_tags: &'a [String],
1141    ) -> Self {
1142        Self {
1143            class_name,
1144            method_name,
1145            type_ident,
1146            doc_tags,
1147            name_prefix: None,
1148            r_name_override: None,
1149            always_export: false,
1150            class_has_no_rd: false,
1151            params_as_details: false,
1152            r_params: None,
1153            suppress_params: false,
1154            choice_param_docs: None,
1155            source_method: None,
1156        }
1157    }
1158
1159    /// Name `method` in the `@source` provenance line: the Rust method behind
1160    /// an R name that differs from it (a constructor's `new`, an `r_name`, a
1161    /// generic).
1162    pub fn with_source_method(mut self, method: &'a syn::Ident) -> Self {
1163        self.source_method = Some(method);
1164        self
1165    }
1166
1167    /// Supply the R-param-name → `@param` text map of the method's choice
1168    /// params ([`choice_param_doc_map`]). When the auto-generated `@param`
1169    /// line would otherwise say `(undocumented)`, that text is emitted instead
1170    /// (a `match_arg` placeholder is rewritten by the wrapper writer, #210).
1171    pub fn with_choice_param_docs(
1172        mut self,
1173        docs: &'a std::collections::HashMap<String, String>,
1174    ) -> Self {
1175        self.choice_param_docs = Some(docs);
1176        self
1177    }
1178
1179    /// Set a prefix for the @name tag (e.g., "$" for "Class$method").
1180    pub fn with_name_prefix(mut self, prefix: &'a str) -> Self {
1181        self.name_prefix = Some(prefix);
1182        self
1183    }
1184
1185    /// Override the @name tag with a custom R function name.
1186    ///
1187    /// Use this when the R function name differs from the Rust method name
1188    /// (e.g., for standalone S3/S4/S7 static methods like `s3counter_default_counter`).
1189    pub fn with_r_name(mut self, r_name: String) -> Self {
1190        self.r_name_override = Some(r_name);
1191        self
1192    }
1193
1194    /// Set whether the parent class has @noRd.
1195    ///
1196    /// When true, skips @name, @rdname, @source tags and adds @noRd instead.
1197    pub fn with_class_no_rd(mut self, class_has_no_rd: bool) -> Self {
1198        self.class_has_no_rd = class_has_no_rd;
1199        self
1200    }
1201
1202    /// Convert `@param` tags to inline `\describe{}` blocks instead of roxygen `@param`.
1203    ///
1204    /// Used for env-class methods where roxygen can't infer `\usage` from `Class$method <- function()`.
1205    /// Without this, `@param` tags create `\arguments` entries with no matching `\usage`,
1206    /// causing R CMD check warnings ("Documented arguments not in \\usage"). With
1207    /// [`with_r_params`](Self::with_r_params) and
1208    /// [`with_choice_param_docs`](Self::with_choice_param_docs), an undocumented
1209    /// choice parameter gets a list item with its choice text; no parameter
1210    /// gets an `(undocumented)` filler.
1211    pub fn with_params_as_details(mut self) -> Self {
1212        self.params_as_details = true;
1213        self
1214    }
1215
1216    /// Set the method's formal parameter names (comma-separated R params string).
1217    ///
1218    /// When set, auto-generates `@param name (undocumented)` for any parameter
1219    /// not already covered by a user `@param` tag. Skips `.mx_self`, `.ptr`, and
1220    /// `...` parameters. Generates nothing when the method's own tags take the
1221    /// arguments from another topic (`@rdname`, `@describeIn`,
1222    /// `@inheritParams`; see `roxygen::params_documented_elsewhere`).
1223    pub fn with_r_params(mut self, params: &'a str) -> Self {
1224        self.r_params = Some(params);
1225        self
1226    }
1227
1228    /// Suppress `@param` tags from user doc comments.
1229    ///
1230    /// Used for S4/S7 instance methods where the method is defined via `setMethod()`
1231    /// or `S7::method()` assignment, which roxygen2 doesn't parse for `\usage` entries.
1232    pub fn with_suppress_params(mut self) -> Self {
1233        self.suppress_params = true;
1234        self
1235    }
1236
1237    /// Build the roxygen `#' @tag` lines for the method.
1238    ///
1239    /// Returns roxygen comment lines, with generated member defaults marked for
1240    /// the class assembler (`CLASS_MEMBER_DEFAULT_PREFIX`). If the parent
1241    /// class has `@noRd`, returns only `["#' @noRd"]`. Otherwise generates `@name`,
1242    /// `@rdname`, `@source`, and optionally `@export` tags, plus any user-provided tags.
1243    /// A method that joins an author topic (`@rdname other`, `@describeIn other`)
1244    /// gets no `@name` / `@rdname` next to `@describeIn`, and sorts after the
1245    /// topic's own block (`roxygen::ORDER_AFTER_TOPIC_BLOCKS`).
1246    pub fn build(&self) -> Vec<String> {
1247        let mut lines = Vec::new();
1248
1249        // If parent class has @noRd, skip all documentation and just add @noRd
1250        if self.class_has_no_rd {
1251            lines.push("#' @noRd".to_string());
1252            return lines;
1253        }
1254
1255        let r_name = if let Some(ref r_name) = self.r_name_override {
1256            r_name.clone()
1257        } else if let Some(prefix) = self.name_prefix {
1258            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", self.class_name,
                prefix, self.method_name))
    })format!("{}{}{}", self.class_name, prefix, self.method_name)
1259        } else {
1260            self.method_name.to_string()
1261        };
1262
1263        if self.params_as_details {
1264            // Env methods: no `\usage`, so the author's `@param` tags and the
1265            // choice text go into a `\describe{}` list (no `@param` filler).
1266            // A bare `@export` would export `Type$method` itself.
1267            lines.extend(describe_params_lines(
1268                self.doc_tags,
1269                crate::roxygen::forwarded_member_tag,
1270                self.r_params.unwrap_or(""),
1271                self.class_name,
1272                self.choice_param_docs,
1273                &r_name,
1274            ));
1275        } else {
1276            if self.suppress_params {
1277                // Filter out @param tags — they would create "Documented arguments
1278                // not in \usage" warnings for S4/S7 methods.
1279                let filtered: Vec<&str> = self
1280                    .doc_tags
1281                    .iter()
1282                    .filter(|t| {
1283                        !t.trim_start()
1284                            .strip_prefix('@')
1285                            .is_some_and(|rest| rest.starts_with("param"))
1286                    })
1287                    .map(|s| s.as_str())
1288                    .collect();
1289                crate::roxygen::push_roxygen_tags_str(&mut lines, &filtered);
1290            } else {
1291                crate::roxygen::push_roxygen_tags(&mut lines, self.doc_tags);
1292            }
1293
1294            // Auto-generate @param for undocumented method parameters, unless
1295            // the method's own tags send it to a topic that documents them
1296            // (`@rdname`, `@describeIn`) or inherit them (`@inheritParams`,
1297            // #1590). Choice params get their choice text (a match_arg
1298            // placeholder is rendered by the wrapper writer, #210).
1299            if let Some(params) = self.r_params {
1300                let mut fillers = Vec::new();
1301                push_param_filler(
1302                    &mut fillers,
1303                    params,
1304                    self.doc_tags,
1305                    self.class_name,
1306                    self.choice_param_docs,
1307                );
1308                lines.extend(
1309                    fillers
1310                        .into_iter()
1311                        .map(crate::miniextendr_impl::member_default),
1312                );
1313            }
1314        }
1315
1316        // A method-level `@describeIn topic ...` lists the method in `topic`'s
1317        // "Functions" section. roxygen2 rejects it next to `@name` or `@rdname`
1318        // ("can not be used with @name") and takes the page from the method's
1319        // object, so the builder pushes neither, and the destination topic
1320        // supplies the title. Only generators whose method block documents an
1321        // R object get here with the tag (`reject_unsupported_describe_in`).
1322        let describe_in = crate::roxygen::describe_in_topic(self.doc_tags).is_some();
1323        if !describe_in && !crate::roxygen::has_roxygen_tag(self.doc_tags, "name") {
1324            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", r_name))
    })format!("#' @name {}", r_name));
1325        }
1326
1327        // A method-level `@rdname` splits the method onto its own page (#1438).
1328        // Method prose is demoted to `@description` (see `roxygen_tags_from_attrs`)
1329        // and the class page normally supplies the `@title`, so the new page
1330        // would have none and roxygen2 would skip it ("no name and/or title").
1331        // Follow the standalone-function convention (`lib.rs`) and use the
1332        // structural R name as the title unless the author wrote one. A
1333        // `@noRd` block renders no page, so it needs no title (#1552).
1334        let has_no_rd = crate::roxygen::has_roxygen_tag(self.doc_tags, "noRd");
1335        if !describe_in {
1336            if crate::roxygen::has_roxygen_tag(self.doc_tags, "rdname") {
1337                if !has_no_rd && !crate::roxygen::has_roxygen_tag(self.doc_tags, "title") {
1338                    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", r_name))
    })format!("#' @title {}", r_name));
1339                }
1340            } else {
1341                lines.push(crate::miniextendr_impl::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", self.class_name))
    })format!(
1342                    "#' @rdname {}",
1343                    self.class_name
1344                )));
1345            }
1346        }
1347        // On an author topic the topic's own block names and titles the page
1348        // (`ORDER_AFTER_TOPIC_BLOCKS`); the structural title above only
1349        // matters for a page no other block defines.
1350        crate::roxygen::push_order_after_topic_blocks(&mut lines, self.doc_tags, self.class_name);
1351
1352        let method = match self.source_method {
1353            Some(ident) => ident.to_string(),
1354            None => self.method_name.to_string(),
1355        };
1356        lines.extend(crate::roxygen::source_tag(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `{0}::{1}`",
                self.type_ident, method))
    })format!(
1357            "Generated by miniextendr from `{}::{}`",
1358            self.type_ident, method
1359        )));
1360
1361        let has_internal = crate::roxygen::has_roxygen_tag(self.doc_tags, "keywords internal");
1362        // Don't auto-export if @noRd or @keywords internal is present
1363        if self.always_export
1364            && !crate::roxygen::has_roxygen_tag(self.doc_tags, "export")
1365            && !has_no_rd
1366            && !has_internal
1367        {
1368            lines.push("#' @export".to_string());
1369        }
1370
1371        lines
1372    }
1373}
1374
1375/// Extension trait for `ParsedImpl` to iterate over methods as [`MethodContext`].
1376///
1377/// Provides convenience methods that wrap `ParsedImpl`'s method iterators,
1378/// automatically constructing a `MethodContext` for each method. This avoids
1379/// repeating the `MethodContext::new(m, type_ident, label)` boilerplate in
1380/// every class system generator.
1381pub trait ParsedImplExt {
1382    /// Create a `MethodContext` for the constructor method, if one exists.
1383    fn constructor_context(&self) -> Option<MethodContext<'_>>;
1384
1385    /// Iterate over all instance methods (public + private + active) as `MethodContext`.
1386    fn instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>>;
1387
1388    /// Iterate over static (non-receiver) methods as `MethodContext`.
1389    fn static_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>>;
1390
1391    /// Iterate over public instance methods as `MethodContext` (for R6 `public` list).
1392    fn public_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>>;
1393
1394    /// Iterate over private instance methods as `MethodContext` (for R6 `private` list).
1395    fn private_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>>;
1396
1397    /// Iterate over active binding methods as `MethodContext` (for R6 `active` list).
1398    fn active_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>>;
1399}
1400
1401impl ParsedImplExt for ParsedImpl {
1402    fn constructor_context(&self) -> Option<MethodContext<'_>> {
1403        let impl_prec = self.preconditions;
1404        self.constructor()
1405            .map(|m| MethodContext::new(m, &self.type_ident).with_impl_preconditions(impl_prec))
1406    }
1407
1408    fn instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>> {
1409        let type_ident = &self.type_ident;
1410        let impl_prec = self.preconditions;
1411        self.instance_methods()
1412            .map(move |m| MethodContext::new(m, type_ident).with_impl_preconditions(impl_prec))
1413    }
1414
1415    fn static_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>> {
1416        let type_ident = &self.type_ident;
1417        let impl_prec = self.preconditions;
1418        self.static_methods()
1419            .map(move |m| MethodContext::new(m, type_ident).with_impl_preconditions(impl_prec))
1420    }
1421
1422    fn public_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>> {
1423        let type_ident = &self.type_ident;
1424        let impl_prec = self.preconditions;
1425        self.public_instance_methods()
1426            .map(move |m| MethodContext::new(m, type_ident).with_impl_preconditions(impl_prec))
1427    }
1428
1429    fn private_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>> {
1430        let type_ident = &self.type_ident;
1431        let impl_prec = self.preconditions;
1432        self.private_instance_methods()
1433            .map(move |m| MethodContext::new(m, type_ident).with_impl_preconditions(impl_prec))
1434    }
1435
1436    fn active_instance_method_contexts(&self) -> impl Iterator<Item = MethodContext<'_>> {
1437        let type_ident = &self.type_ident;
1438        let impl_prec = self.preconditions;
1439        self.active_instance_methods()
1440            .map(move |m| MethodContext::new(m, type_ident).with_impl_preconditions(impl_prec))
1441    }
1442}
1443
1444/// Prefix an instance receiver and append only missing dispatch dots.
1445/// Shared by inherent and trait wrapper contexts; explicit Dots keeps its place.
1446pub(crate) fn instance_formals(params: &str, receiver: &str, include_dots: bool) -> String {
1447    let has_dots = crate::roxygen::split_r_formals(params)
1448        .iter()
1449        .any(|p| p.trim() == "...");
1450    let tail = if include_dots && !has_dots {
1451        ", ..."
1452    } else {
1453        ""
1454    };
1455    if params.is_empty() {
1456        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", receiver, tail))
    })format!("{receiver}{tail}")
1457    } else {
1458        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, {1}{2}", receiver, params,
                tail))
    })format!("{receiver}, {params}{tail}")
1459    }
1460}
1461
1462#[cfg(test)]
1463mod tests;