Skip to main content

miniextendr_macros/miniextendr_impl_trait/
r_wrappers.rs

1//! R wrapper generation for trait methods across all class systems.
2//!
3//! Each class system (Env, S3, S4, S7, R6, Vctrs) has its own generator that
4//! produces R code strings for instance methods, static methods, and associated
5//! constants. The top-level [`generate_trait_r_wrapper`] dispatches to the
6//! appropriate generator and applies post-processing for export/documentation control.
7
8use super::method_context::{
9    TraitMethodContext, class_ref, s7_trait_member_access, trait_namespace_env,
10    trait_namespace_env_var, trait_namespace_target,
11};
12use super::{TraitConst, TraitMethod};
13use crate::miniextendr_impl::ClassSystem;
14use crate::r_class_formatter::emit_s3_generic_guard;
15
16/// Options controlling export visibility and documentation for trait R wrapper generation.
17pub(super) struct TraitWrapperOpts {
18    /// Which R class system to generate wrappers for (env, r6, s3, s4, s7, vctrs).
19    pub(super) class_system: ClassSystem,
20    /// Whether the impl block has `@noRd`, suppressing roxygen documentation output.
21    /// For S3/vctrs, method registration tags are preserved even when this is true.
22    pub(super) class_has_no_rd: bool,
23    /// Whether `#[miniextendr(internal)]` is set, adding `@keywords internal` and
24    /// suppressing `@export`/`@exportMethod`.
25    pub(super) internal: bool,
26    /// Whether `#[miniextendr(noexport)]` is set, suppressing `@export`/`@exportMethod`
27    /// without adding `@keywords internal`.
28    pub(super) noexport: bool,
29    /// The impl block's `preconditions` / `no_preconditions`
30    /// (`ImplAttrs::preconditions`), as on an inherent impl.
31    pub(super) impl_preconditions: Option<bool>,
32}
33
34/// Whether the trait wrappers of `class_system` for `methods` and `consts`
35/// bind the `Class$Trait` namespace in the class's own object
36/// ([`trait_namespace_env`]): Env always, R6 for any member, S3 and vctrs for
37/// a static method or a const; S4 and S7 keep theirs elsewhere. The trait
38/// impl then registers a `TraitNamespaceEntry`, so the wrapper writer keeps
39/// the S3 or vctrs class environment it writes into (#2264, #2289).
40pub(super) fn binds_trait_namespace(
41    class_system: ClassSystem,
42    methods: &[TraitMethod],
43    consts: &[TraitConst],
44) -> bool {
45    match class_system {
46        ClassSystem::Env => true,
47        ClassSystem::R6 => !methods.is_empty() || !consts.is_empty(),
48        ClassSystem::S3 | ClassSystem::Vctrs => {
49            methods.iter().any(|m| !m.has_self) || !consts.is_empty()
50        }
51        ClassSystem::S4 | ClassSystem::S7 => false,
52    }
53}
54
55/// Generate R wrapper code for trait methods and consts, dispatching by class system.
56///
57/// Calls the appropriate class-system-specific generator (env, s3, s4, s7, r6),
58/// then applies post-processing for `@noRd`, `internal`, and `noexport` options:
59///
60/// - `class_has_no_rd`: Strips roxygen blocks (for S3/vctrs, keeps `@method`/`@export` tags)
61/// - `internal`: Replaces `@export`/`@exportMethod` with `@keywords internal`
62/// - `noexport`: Removes `@export`/`@exportMethod` entirely
63///
64/// Returns the complete R wrapper code as a string ready for embedding in a `const`.
65pub(super) fn generate_trait_r_wrapper(
66    type_ident: &syn::Ident,
67    trait_name: &syn::Ident,
68    methods: &[TraitMethod],
69    consts: &[TraitConst],
70    opts: TraitWrapperOpts,
71) -> syn::Result<String> {
72    let TraitWrapperOpts {
73        class_system,
74        class_has_no_rd,
75        internal,
76        noexport,
77        impl_preconditions,
78    } = opts;
79    reject_unsupported_describe_in(methods, class_system)?;
80    check_trait_method_formals(methods, class_system)?;
81    let generate = match class_system {
82        ClassSystem::Env => generate_trait_env_r_wrapper,
83        // vctrs uses S3 under the hood, so use the S3 trait wrapper
84        ClassSystem::S3 | ClassSystem::Vctrs => generate_trait_s3_r_wrapper,
85        ClassSystem::S4 => generate_trait_s4_r_wrapper,
86        ClassSystem::S7 => generate_trait_s7_r_wrapper,
87        ClassSystem::R6 => generate_trait_r6_r_wrapper,
88    };
89    let result = generate(type_ident, trait_name, methods, consts, impl_preconditions);
90
91    // When the impl block has @noRd, suppress documentation generation. A plain
92    // `noexport` (without `internal`) is folded into the same gate — it must
93    // produce no Rd contribution at all (no alias, no usage entry, nothing on a
94    // shared page), same as `@noRd`. `internal` wins if both flags are set on
95    // the same impl block (mirrors the standalone-fn precedent, where `internal`
96    // + `noexport` together is a compile error). See #431 for the inherent-impl
97    // S3 generator's analogous `should_register_s3method = !noexport` rule.
98    let suppress_all_rd = class_has_no_rd || (noexport && !internal);
99    if suppress_all_rd {
100        if #[allow(non_exhaustive_omitted_patterns)] match class_system {
    ClassSystem::S3 | ClassSystem::Vctrs => true,
    _ => false,
}matches!(class_system, ClassSystem::S3 | ClassSystem::Vctrs) {
101            // A user-written `@noRd` still preserves S3 dispatch registration
102            // (`@method`/`@export`) so `S3method()` lands in NAMESPACE — the
103            // class stays undocumented but dispatchable. A `noexport`-driven
104            // suppression (no explicit `@noRd`) additionally drops `@export`:
105            // `noexport` means zero observable trace, not "documented nowhere
106            // but still dispatchable".
107            let keep_export = class_has_no_rd;
108            let mut filtered = Vec::new();
109            let mut roxygen_block: Vec<&str> = Vec::new();
110
111            let flush_block = |block: &mut Vec<&str>, out: &mut Vec<String>| {
112                if block.iter().any(|line| line.contains("@method ")) {
113                    out.push("#' @noRd".to_string());
114                    for &line in block.iter() {
115                        if line.contains("@method ")
116                            || line.contains("@param ")
117                            || (keep_export && line.contains("@export"))
118                        {
119                            out.push(line.to_string());
120                        }
121                    }
122                }
123                block.clear();
124            };
125
126            for line in result.lines() {
127                if line.starts_with("#'") {
128                    roxygen_block.push(line);
129                    continue;
130                }
131
132                if !roxygen_block.is_empty() {
133                    flush_block(&mut roxygen_block, &mut filtered);
134                }
135                filtered.push(line.to_string());
136            }
137
138            if !roxygen_block.is_empty() {
139                flush_block(&mut roxygen_block, &mut filtered);
140            }
141
142            Ok(filtered.join("\n"))
143        } else {
144            Ok(result
145                .lines()
146                .filter(|line| !line.starts_with("#'"))
147                .collect::<Vec<_>>()
148                .join("\n"))
149        }
150    } else if internal {
151        // internal → documented, but @export/@exportMethod becomes @keywords
152        // internal. The bare `@export` of an S3 method block (one with
153        // `@method`) stays: it is the `S3method()` registration, which an
154        // inherent `internal` S3 impl keeps too, and without it a method on
155        // another package's generic (`summary`) dispatches only from inside
156        // the namespace.
157        let has_export = result.lines().any(|line| line.contains("@export"));
158        let lines: Vec<&str> = result.lines().collect();
159        let mut processed: Vec<String> = Vec::with_capacity(lines.len());
160        let mut start = 0;
161        while start < lines.len() {
162            let roxygen = lines[start].starts_with("#'");
163            let end = lines[start..]
164                .iter()
165                .position(|line| line.starts_with("#'") != roxygen)
166                .map_or(lines.len(), |len| start + len);
167            let block = &lines[start..end];
168            let registers_s3 = roxygen && block.iter().any(|line| line.contains("@method "));
169            for &line in block {
170                if line.contains("@export") && !(registers_s3 && line.trim_end() == "#' @export") {
171                    processed.push("#' @keywords internal".to_string());
172                } else {
173                    processed.push(line.to_string());
174                }
175            }
176            start = end;
177        }
178        // For class systems without @export (e.g., Env), insert @keywords internal
179        // before the first roxygen tag if no @export line was found to replace.
180        if !has_export && let Some(pos) = processed.iter().position(|l| l.starts_with("#'")) {
181            processed.insert(pos, "#' @keywords internal".to_string());
182        }
183        Ok(processed.join("\n"))
184    } else {
185        Ok(result)
186    }
187}
188
189// region: author page tags (#1438, #1590)
190
191/// The author tags of a trait-impl method that its own wrapper block
192/// forwards besides the `@param` lines: the tags that decide the method's
193/// page and where its arguments are documented. `@describeIn` / `@rdname`
194/// route the block, `@name` names its topic, `@order` sorts it, and
195/// `@inheritParams` / `@inherit` / `@inheritDotParams` fill its arguments.
196/// Env trait methods and the namespace statics of S3, vctrs and S7 forward
197/// every other tag but `@title` and a bare `@export` too
198/// ([`forwarded_body_tag`]); S4 statics get `@param` lines
199/// ([`param_doc_tags`]).
200const PAGE_TAGS: &[&str] = &[
201    "describeIn",
202    "rdname",
203    "name",
204    "order",
205    "inheritParams",
206    "inherit",
207    "inheritDotParams",
208];
209
210/// Whether the body of a block without `\usage` (an env trait method, a
211/// `Type$Trait$method` static of S3 and vctrs, an `attr(Type, "Trait")$method`
212/// static of S7) forwards the author tag
213/// `tag`: every tag but the [`PAGE_TAGS`], which [`own_block_page_lines`]
214/// forwards, `@title`, which the structural split-page title owns, and a bare
215/// `@export`, which would export the member itself
216/// ([`forwarded_member_tag`](crate::roxygen::forwarded_member_tag)). The
217/// `@param` lines become items of the block's `\describe{}` list.
218fn forwarded_body_tag(tag: &str) -> bool {
219    crate::roxygen::forwarded_member_tag(tag)
220        && crate::roxygen::roxygen_tag_name(tag)
221            .is_none_or(|name| name != "title" && !PAGE_TAGS.contains(&name))
222}
223
224/// The documentation body of a block without `\usage` (see
225/// [`forwarded_body_tag`]), documented like an env inherent method: the
226/// forwarded author tags, then one `\describe{}` list with the author's
227/// `@param` items and the choice text of the parameters they leave
228/// undocumented ([`describe_params_lines`](crate::r_class_formatter::describe_params_lines)).
229/// `label` is the block's topic name, used in the list's lead-in. Empty for a
230/// method with no doc comment and no choice parameter.
231fn namespace_member_body_lines(
232    ctx: &TraitMethodContext<'_>,
233    type_str: &str,
234    label: &str,
235) -> Vec<String> {
236    let choice_docs = ctx.choice_param_docs();
237    crate::r_class_formatter::describe_params_lines(
238        &ctx.method.doc_tags,
239        forwarded_body_tag,
240        &ctx.params,
241        type_str,
242        Some(&choice_docs),
243        label,
244    )
245}
246
247/// The `@param` tags of a block that documents the method's arguments in a
248/// `\usage` (an S3 / vctrs instance method, an S4 static): the author's
249/// `@param` lines, then one per formal of `ctx.params` they leave
250/// undocumented, with its choice text for a choice parameter and
251/// `(undocumented)` otherwise. A method whose arguments another block
252/// documents (an author topic, `@inheritParams`) gets no generated tag
253/// (#1590).
254fn param_doc_tags(ctx: &TraitMethodContext<'_>, type_str: &str) -> Vec<String> {
255    let method = ctx.method;
256    let mut tags: Vec<String> = param_tags(method).cloned().collect();
257    if params_documented_elsewhere(method, type_str) {
258        return tags;
259    }
260    let choice_docs = ctx.choice_param_docs();
261    for formal in crate::roxygen::split_r_formals(&ctx.params) {
262        let pname = crate::roxygen::formal_name(formal);
263        if pname == "..." || crate::roxygen::param_documented(&method.doc_tags, pname) {
264            continue;
265        }
266        let body = choice_docs
267            .get(pname)
268            .map_or("(undocumented)", String::as_str);
269        tags.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@param {0} {1}", pname, body))
    })format!("@param {pname} {body}"));
270    }
271    tags
272}
273
274/// The `@param` lines of the method's doc comment.
275fn param_tags(method: &TraitMethod) -> impl Iterator<Item = &String> {
276    method
277        .doc_tags
278        .iter()
279        .filter(|tag| crate::roxygen::roxygen_tag_name(tag) == Some("param"))
280}
281
282/// The page a trait method's own block lands on, and with it the companion
283/// block that must share it (the S3 generic block, named after the method):
284/// the `@describeIn` destination, the method-level `@rdname`, else the type's
285/// shared page. Generics of S4 / S7 and consts always use the type page.
286fn method_page<'a>(method: &'a TraitMethod, type_str: &'a str) -> &'a str {
287    crate::roxygen::method_page(&method.doc_tags, type_str)
288}
289
290/// Whether the method's page is an author topic other than the type page
291/// (`@describeIn`, or an `@rdname` naming another page). The topic's own
292/// block documents that page, so the method's blocks sort after it
293/// (`@order NaN`) and leave the structural `@param` lines (`x`, `...`,
294/// `self`) and generated prose to it.
295fn joins_author_topic(method: &TraitMethod, type_str: &str) -> bool {
296    crate::roxygen::joins_author_topic(&method.doc_tags, Some(type_str))
297}
298
299/// Whether the method's arguments are documented by another block: it joins
300/// an author topic, or inherits them (`@inheritParams`, `@inherit`). The
301/// generated `(undocumented)` fillers are left out then.
302fn params_documented_elsewhere(method: &TraitMethod, type_str: &str) -> bool {
303    crate::roxygen::params_documented_elsewhere(&method.doc_tags, Some(type_str))
304}
305
306/// Whether the method-level `@describeIn` lists the method's own block in
307/// its destination's "Functions" section.
308fn describes_in(method: &TraitMethod) -> bool {
309    crate::roxygen::describe_in_topic(&method.doc_tags).is_some()
310}
311
312/// The page lines of a trait method's own wrapper block, as `MethodDocBuilder`
313/// writes an inherent method's (#1590):
314///
315/// - the author's [`PAGE_TAGS`], verbatim;
316/// - without an author `@describeIn`: `@name default_name` unless the author
317///   named the topic (blocks roxygen2 cannot name from their object need
318///   one), `@rdname <Type>` unless the author picked the page, and, on a page
319///   the author's `@rdname` splits off, `@title split_title` (roxygen2 skips
320///   a page without a title). With `@describeIn` roxygen2 takes the page from
321///   the destination and rejects `@name` / `@rdname` next to it, so neither
322///   is generated;
323/// - `@order NaN` on an author topic the author did not order
324///   (`roxygen::orders_after_topic_blocks`).
325fn own_block_page_lines(
326    method: &TraitMethod,
327    type_str: &str,
328    default_name: Option<&str>,
329    split_title: Option<&str>,
330) -> Vec<String> {
331    let tags = &method.doc_tags;
332    let mut lines = Vec::new();
333    if !describes_in(method) {
334        let has = |tag: &str| crate::roxygen::has_roxygen_tag(tags, tag);
335        if has("rdname")
336            && let Some(title) = split_title
337        {
338            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", title))
    })format!("#' @title {title}"));
339        }
340        if !has("name")
341            && let Some(name) = default_name
342        {
343            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", name))
    })format!("#' @name {name}"));
344        }
345        if !has("rdname") {
346            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", type_str))
    })format!("#' @rdname {type_str}"));
347        }
348    }
349    let page_tags: Vec<String> = tags
350        .iter()
351        .filter(|tag| {
352            crate::roxygen::roxygen_tag_name(tag).is_some_and(|name| PAGE_TAGS.contains(&name))
353        })
354        .cloned()
355        .collect();
356    crate::roxygen::push_roxygen_tags(&mut lines, &page_tags);
357    crate::roxygen::push_order_after_topic_blocks(&mut lines, tags, type_str);
358    lines
359}
360
361/// Push the method's `@param` lines, each continuation line with its own
362/// `#' ` lead.
363fn push_param_tags(lines: &mut Vec<String>, method: &TraitMethod) {
364    let params: Vec<String> = param_tags(method).cloned().collect();
365    crate::roxygen::push_roxygen_tags(lines, &params);
366}
367
368/// Check the R formals of every trait method
369/// ([`check_r_formals`](crate::r_wrapper_builder::check_r_formals)). Every
370/// dispatching class system defaults an instance method's receiver to `x`.
371/// S3/S4 existing-generic overrides can select another receiver. S7
372/// shortcuts and Env/R6 trait methods use the injected receiver
373/// `.mx_self`, which cannot be spelled by a Rust parameter.
374fn check_trait_method_formals(
375    methods: &[TraitMethod],
376    class_system: ClassSystem,
377) -> syn::Result<()> {
378    let system = match class_system {
379        ClassSystem::Env => "Env-class",
380        ClassSystem::R6 => "R6",
381        ClassSystem::S3 => "S3",
382        ClassSystem::S4 => "S4",
383        ClassSystem::S7 => "S7",
384        ClassSystem::Vctrs => "vctrs",
385    };
386    for method in methods {
387        if (method.generic.is_some() || method.receiver.is_some() || method.no_dispatch_dots)
388            && (!method.has_self || !#[allow(non_exhaustive_omitted_patterns)] match class_system {
    ClassSystem::S3 | ClassSystem::S4 => true,
    _ => false,
}matches!(class_system, ClassSystem::S3 | ClassSystem::S4))
389        {
390            return Err(syn::Error::new_spanned(
391                &method.sig,
392                "`generic`, `receiver` and `no_dots` apply only to S3/S4 instance methods",
393            ));
394        }
395        if (method.receiver.is_some() || method.no_dispatch_dots) && method.generic.is_none() {
396            return Err(syn::Error::new_spanned(
397                &method.sig,
398                "`receiver` and `no_dots` require an explicit S3/S4 `generic = \"...\"`",
399            ));
400        }
401        let mut reserved = Vec::new();
402        if method.has_self && !#[allow(non_exhaustive_omitted_patterns)] match class_system {
    ClassSystem::Env | ClassSystem::R6 => true,
    _ => false,
}matches!(class_system, ClassSystem::Env | ClassSystem::R6) {
403            reserved.push((
404                method.receiver.as_deref().unwrap_or("x").to_string(),
405                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is the receiver of the generated {0} trait method",
                system))
    })format!("is the receiver of the generated {system} trait method"),
406            ));
407        }
408        crate::r_wrapper_builder::check_r_formals(
409            &method.sig.inputs,
410            &Default::default(),
411            &reserved,
412        )?;
413    }
414    Ok(())
415}
416
417/// Reject a method-level `@describeIn` that roxygen2 cannot honour on the
418/// trait wrapper (#1590), the rule `ParsedImpl::reject_unsupported_describe_in`
419/// applies to inherent methods.
420///
421/// roxygen2 lists a `@describeIn` block in its destination's "Functions"
422/// section through the R object the block documents. The trait wrappers give
423/// the method's own block such an object for S3 and vctrs instance methods
424/// (the S3 method `generic.Type`), S4 instance methods (the block sits on
425/// `methods::setMethod()`, an S4 method object), S4 static methods (the
426/// plain function `Type_Trait_method`) and S7 instance methods (the
427/// fast-path shortcut `Type_method`). Every other method is a
428/// `Type$Trait$method` (or `.Type__Trait$method`) namespace member, whose
429/// block roxygen2 drops ("Block must have a @name"), and an S7 instance
430/// method with `s7(no_shortcut)` has no block of its own. There the tag is a
431/// compile error pointing at `@rdname`, reported for every such method at
432/// once.
433///
434/// The set is wider than the inherent one on S4 instance methods: an
435/// inherent S4 method's block sits on the `if (!exists(...))` generic guard,
436/// a trait method's on its own `setMethod()` call.
437fn reject_unsupported_describe_in(
438    methods: &[TraitMethod],
439    class_system: ClassSystem,
440) -> syn::Result<()> {
441    let system = match class_system {
442        ClassSystem::S3 => "S3",
443        ClassSystem::Vctrs => "vctrs",
444        ClassSystem::S4 => "S4",
445        ClassSystem::S7 => "S7",
446        ClassSystem::Env => "Env",
447        ClassSystem::R6 => "R6",
448    };
449    let mut errors: Option<syn::Error> = None;
450    for method in methods.iter().filter(|m| describes_in(m)) {
451        let supported = match class_system {
452            ClassSystem::S3 | ClassSystem::Vctrs => method.has_self,
453            ClassSystem::S4 => true,
454            ClassSystem::S7 => method.has_self && !method.no_shortcut,
455            ClassSystem::Env | ClassSystem::R6 => false,
456        };
457        if supported {
458            continue;
459        }
460        let (kind, qualifier) = if !method.has_self {
461            ("static method", "")
462        } else if #[allow(non_exhaustive_omitted_patterns)] match class_system {
    ClassSystem::S7 => true,
    _ => false,
}matches!(class_system, ClassSystem::S7) {
463            ("instance method", " without a fast-path shortcut")
464        } else {
465            ("instance method", "")
466        };
467        let error = syn::Error::new_spanned(
468            &method.ident,
469            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`@describeIn` is not supported on the {1} trait {2} `{0}`{3}: its R wrapper is not an R function roxygen2 can list in the destination\'s \"Functions\" section, so roxygen2 would drop the block. Use `@rdname <topic>` to document it on that page instead. On trait impls `@describeIn` works on S3, vctrs and S4 instance methods, on S4 static methods, and on S7 instance methods with a fast-path shortcut.",
                method.ident, system, kind, qualifier))
    })format!(
470                "`@describeIn` is not supported on the {system} trait {kind} `{}`{qualifier}: \
471                 its R wrapper is not an R function roxygen2 can list in the destination's \
472                 \"Functions\" section, so roxygen2 would drop the block. Use `@rdname <topic>` \
473                 to document it on that page instead. On trait impls `@describeIn` works on \
474                 S3, vctrs and S4 instance methods, on S4 static methods, and on S7 instance \
475                 methods with a fast-path shortcut.",
476                method.ident,
477            ),
478        );
479        match errors.as_mut() {
480            Some(all) => all.combine(error),
481            None => errors = Some(error),
482        }
483    }
484    errors.map_or(Ok(()), Err)
485}
486
487// endregion
488
489/// Generate Env-style R wrapper code for trait methods.
490///
491/// Env-class trait methods use a namespace hierarchy: `Type$Trait$method(.mx_self, ...)`.
492/// Instance methods take `.mx_self` as the first parameter (the self object) and are
493/// stamped with `.__mx_instance__` attribute for `$` dispatch detection.
494/// Void instance methods return the receiver for pipe-friendly chaining
495/// (invisibly only when marked `Invisible<..>`, #1213).
496///
497/// Static methods and constants also live under `Type$Trait$name`. A method
498/// has no `\usage`, so its block is documented like an env inherent method's
499/// ([`namespace_member_body_lines`]).
500fn generate_trait_env_r_wrapper(
501    type_ident: &syn::Ident,
502    trait_name: &syn::Ident,
503    methods: &[TraitMethod],
504    consts: &[TraitConst],
505    impl_preconditions: Option<bool>,
506) -> String {
507    use crate::r_wrapper_builder::{DotCallBuilder, RoxygenBuilder};
508
509    let mut lines = Vec::new();
510    let type_str = type_ident.to_string();
511
512    // Header comment
513    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Trait methods and consts for {0} implementing {1}",
                type_ident, trait_name))
    })format!(
514        "# Trait methods and consts for {} implementing {}",
515        type_ident, trait_name
516    ));
517    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated by #[miniextendr] impl {0} for {1}",
                trait_name, type_ident))
    })format!(
518        "# Generated by #[miniextendr] impl {} for {}",
519        trait_name, type_ident
520    ));
521    lines.push(String::new());
522
523    // Create trait namespace environment
524    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                trait_namespace_env(ClassSystem::Env, type_ident,
                    trait_name)))
    })format!(
525        "{} <- new.env(parent = emptyenv())",
526        trait_namespace_env(ClassSystem::Env, type_ident, trait_name)
527    ));
528    lines.push(String::new());
529
530    for method in methods {
531        let r_name = method.r_method_name();
532        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
533            .with_impl_preconditions(impl_preconditions);
534
535        // Trait-namespace assignment target (`Type$Trait$method`), owned by
536        // `trait_namespace_target` — see #1141. `symbol` is its R-code form.
537        let target = ctx.namespace_target(ClassSystem::Env);
538        let symbol = ctx.namespace_symbol(ClassSystem::Env);
539
540        // Roxygen: the body (prose, the `\describe{}` argument list), then
541        // the page lines, the order `MethodDocBuilder` gives an env inherent
542        // method.
543        lines.extend(namespace_member_body_lines(&ctx, &type_str, &target));
544        lines.extend(own_block_page_lines(
545            method,
546            &type_str,
547            Some(&target),
548            Some(&target),
549        ));
550
551        // Build .Call() invocation — C name uses Rust ident, R name uses r_name
552        let (full_params, call) = if method.has_self {
553            let fp = if ctx.params.is_empty() {
554                ".mx_self".to_string()
555            } else {
556                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".mx_self, {0}", ctx.params))
    })format!(".mx_self, {}", ctx.params)
557            };
558            (fp, ctx.instance_call(".mx_self"))
559        } else {
560            (ctx.params.clone(), ctx.static_call())
561        };
562
563        // Generate method wrapper (R-facing name)
564        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{", symbol,
                full_params))
    })format!("{symbol} <- function({full_params}) {{"));
565        ctx.emit_method_prelude(&mut lines, "  ", &r_name);
566        lines.extend(ctx.method_body_lines(&call, ClassSystem::Env));
567        if method.has_self {
568            finish_instance_body(&mut lines, method, ".mx_self");
569        }
570        lines.push("}".to_string());
571
572        // Stamp instance methods with attribute for $ dispatch detection
573        if method.has_self {
574            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("attr({0}, \".__mx_instance__\") <- TRUE",
                symbol))
    })format!("attr({symbol}, \".__mx_instance__\") <- TRUE"));
575        }
576
577        lines.push(String::new());
578    }
579
580    // Generate const wrappers
581    for trait_const in consts {
582        let const_name = &trait_const.ident;
583        let const_str = const_name.to_string();
584        let target = trait_namespace_target(ClassSystem::Env, type_ident, trait_name, &const_str);
585
586        // Build roxygen tags
587        let roxygen = RoxygenBuilder::new()
588            .name(target.clone())
589            .rdname(&type_str)
590            .build();
591        lines.extend(roxygen);
592
593        // Build .Call() invocation
594        let c_ident = trait_const.c_wrapper_ident_string(type_ident, trait_name);
595        let call = DotCallBuilder::new(&c_ident).build();
596
597        // Generate const wrapper
598        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function() {{", target))
    })format!("{target} <- function() {{"));
599        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", call))
    })format!("  {}", call));
600        lines.push("}".to_string());
601        lines.push(String::new());
602    }
603
604    lines.join("\n")
605}
606
607/// Generate S3-style R wrapper code (generic + method.Type).
608///
609/// For `impl Counter for SimpleCounter`, generates:
610/// - S3 generic `value(x, ...)` (if not already defined)
611/// - S3 method `value.SimpleCounter <- function(x, ...) { .Call(...) }`
612/// - S7 method registration if the generic is an S7 generic
613///
614/// Static methods and constants use `Type$Trait$name` namespace (env-style).
615/// Void instance methods return the receiver `x` for pipe-friendly chaining
616/// (invisibly only when marked `Invisible<..>`, #1213).
617///
618/// Also used for `ClassSystem::Vctrs` since vctrs uses S3 under the hood.
619fn generate_trait_s3_r_wrapper(
620    type_ident: &syn::Ident,
621    trait_name: &syn::Ident,
622    methods: &[TraitMethod],
623    consts: &[TraitConst],
624    impl_preconditions: Option<bool>,
625) -> String {
626    use crate::r_wrapper_builder::{DotCallBuilder, RoxygenBuilder};
627
628    let mut lines = Vec::new();
629    let type_str = type_ident.to_string();
630    // The S3 class the methods dispatch on: the class's R name (#2266). The
631    // page (`type_str`) keeps the Rust name.
632    let class_str = class_ref(ClassSystem::S3, type_ident);
633
634    // Header comment
635    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# S3 trait methods for {0} implementing {1}",
                type_ident, trait_name))
    })format!(
636        "# S3 trait methods for {} implementing {}",
637        type_ident, trait_name
638    ));
639    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated by #[miniextendr(s3)] impl {0} for {1}",
                trait_name, type_ident))
    })format!(
640        "# Generated by #[miniextendr(s3)] impl {} for {}",
641        trait_name, type_ident
642    ));
643    lines.push(String::new());
644
645    // Separate instance methods (S3 dispatch) from static methods (namespace access)
646    let instance_methods: Vec<_> = methods.iter().filter(|m| m.has_self).collect();
647    let static_methods: Vec<_> = methods.iter().filter(|m| !m.has_self).collect();
648
649    // Generate S3 generics + methods for instance methods. Their conditions
650    // report the generic's call, resolved from the method frame on a raise
651    // (#1851).
652    for method in &instance_methods {
653        let qualified_generic = method
654            .generic
655            .clone()
656            .unwrap_or_else(|| method.r_method_name());
657        let (generic_package, generic_name) = crate::naming::split_generic(&qualified_generic);
658        let receiver = method.receiver.as_deref().unwrap_or("x");
659        let s3_method_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", generic_name, class_str))
    })format!("{generic_name}.{class_str}");
660        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
661            .with_impl_preconditions(impl_preconditions)
662            .with_call_attribution(crate::r_wrapper_builder::CallAttribution::Generic);
663
664        if method.generic.is_none() {
665            // S3 generic roxygen (only create if doesn't exist). The type-qualified
666            // @name avoids duplicate aliases across types, but it is also the S3
667            // method's own name, so the generic block must follow a method-level
668            // `@rdname` / `@describeIn` onto the method's page or R CMD check
669            // reports the alias as duplicated across two pages. The `@title` is
670            // inert on the type page (the type block's title comes first) and
671            // would beat the method's structural title on a split page, so it is
672            // only emitted when the block stays on the type page. The prose is a
673            // `@description`: a bare line here continues the tag before it
674            // (`@rdname` is single-line and roxygen2 skips the page; #1552
675            // surfaced this once `@source` stopped absorbing it).
676            let tags = &method.doc_tags;
677            let generic_roxygen = RoxygenBuilder::new();
678            let generic_roxygen =
679                if crate::roxygen::has_roxygen_tag(tags, "rdname") || describes_in(method) {
680                    generic_roxygen
681                } else {
682                    generic_roxygen.title(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S3 generic for `{0}`",
                generic_name))
    })format!("S3 generic for `{}`", generic_name))
683                };
684            let generic_roxygen = generic_roxygen
685                .name(&s3_method_name)
686                .rdname(method_page(method, &type_str));
687            // On an author topic its own block describes the method and documents
688            // `x` and `...` (#1590); the structural lines would only compete.
689            let generic_roxygen = if joins_author_topic(method, &type_str) {
690                generic_roxygen
691            } else {
692                generic_roxygen
693                    .description(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S3 generic for `{0}`",
                generic_name))
    })format!("S3 generic for `{}`", generic_name))
694                    .custom("@param x An object")
695                    .custom("@param ... Additional arguments passed to methods")
696            };
697            let generic_roxygen = if crate::roxygen::orders_after_topic_blocks(tags, &type_str) {
698                generic_roxygen.custom(crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS)
699            } else {
700                generic_roxygen
701            };
702            let generic_roxygen = generic_roxygen
703                .source(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `impl {0} for {1}`",
                trait_name, type_ident))
    })format!(
704                    "Generated by miniextendr from `impl {} for {}`",
705                    trait_name, type_ident
706                ))
707                // Explicit target: roxygen2 can't see the generic inside the
708                // `if (!exists(...))` guard and would attach a bare `@export` to
709                // the next function, exporting the method `generic.Type` as a plain
710                // function and leaving the generic unexported (see s3_class.rs).
711                .custom(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@export {0}", generic_name))
    })format!("@export {}", generic_name))
712                .build();
713            lines.extend(generic_roxygen);
714
715            // S3 generic definition
716            lines.push(emit_s3_generic_guard(generic_name));
717            lines.push(String::new());
718        }
719
720        // S3 method: generic.class
721        let full_params = crate::r_class_formatter::instance_formals(
722            &ctx.params,
723            receiver,
724            !method.no_dispatch_dots,
725        );
726
727        // S3 method roxygen: the method's own @param tags, then a filler for
728        // every other formal in its `\usage` (`x` and `...` are documented by
729        // the generic block above), like an inherent S3 method's
730        // `MethodDocBuilder`: choice text for a `choices(...)` param,
731        // `(undocumented)` otherwise. A method whose arguments another block
732        // documents (an author topic, `@inheritParams`) gets no filler
733        // (#1590). roxygen2 names the block from the S3 method object, so it
734        // needs no generated `@name`.
735        lines.extend(own_block_page_lines(
736            method,
737            &type_str,
738            None,
739            Some(&s3_method_name),
740        ));
741        // A method on `pkg::generic` registers through `@exportS3Method`, so
742        // `pkg` may stay in Suggests (#2154).
743        let mut method_roxygen = match generic_package {
744            Some(package) => RoxygenBuilder::new().custom(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@exportS3Method {0}::{1} {2}",
                package, generic_name, class_str))
    })format!(
745                "@exportS3Method {package}::{generic_name} {class_str}"
746            )),
747            None => RoxygenBuilder::new().export(),
748        }
749        .method(generic_name, &class_str);
750        if method.generic.is_some() && !joins_author_topic(method, &type_str) {
751            method_roxygen = method_roxygen.custom(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@param {0} An object", receiver))
    })format!("@param {receiver} An object"));
752            if !method.no_dispatch_dots {
753                method_roxygen =
754                    method_roxygen.custom("@param ... Additional arguments passed to methods");
755            }
756        }
757        for tag in param_doc_tags(&ctx, &type_str) {
758            method_roxygen = method_roxygen.custom(tag);
759        }
760        lines.extend(method_roxygen.build());
761
762        // Build .Call() invocation
763        let call = ctx.instance_call(receiver);
764
765        // Always define the S3 method (roxygen expects it for NAMESPACE export)
766        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                crate::naming::r_def_name(&s3_method_name), full_params))
    })format!(
767            "{} <- function({}) {{",
768            crate::naming::r_def_name(&s3_method_name),
769            full_params
770        ));
771        ctx.emit_method_prelude(&mut lines, "  ", generic_name);
772        lines.extend(ctx.method_body_lines(&call, ClassSystem::S3));
773        finish_instance_body(&mut lines, method, receiver);
774        lines.push("}".to_string());
775
776        // Additionally register as S7 method if the generic is S7
777        // This ensures S7 dispatch works when the generic was defined by an S7 class.
778        // A `pkg::generic` belongs to another package, which may not be
779        // installed at build time, so it is registered as an S3 method only.
780        if generic_package.is_none() {
781            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (inherits(get0(\"{0}\", mode = \"function\"), \"S7_generic\")) {{",
                generic_name))
    })format!(
782                "if (inherits(get0(\"{generic_name}\", mode = \"function\"), \"S7_generic\")) {{"
783            ));
784            // Both sides of the registration are R symbols: quote operator names
785            // such as `[` so the emitted line parses (#1475).
786            let generic_symbol = crate::naming::r_def_name(generic_name);
787            let method_symbol = crate::naming::r_def_name(&s3_method_name);
788            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  S7::method({0}, S7::new_S3_class(\"{1}\")) <- {2}",
                generic_symbol, class_str, method_symbol))
    })format!(
789                "  S7::method({generic_symbol}, S7::new_S3_class(\"{class_str}\")) <- {method_symbol}"
790            ));
791            lines.push("}".to_string());
792        }
793        lines.push(String::new());
794    }
795
796    // Create trait namespace for static methods and consts BEFORE assigning to it
797    if binds_trait_namespace(ClassSystem::S3, methods, consts) {
798        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                trait_namespace_env(ClassSystem::S3, type_ident, trait_name)))
    })format!(
799            "{} <- new.env(parent = emptyenv())",
800            trait_namespace_env(ClassSystem::S3, type_ident, trait_name)
801        ));
802        lines.push(String::new());
803    }
804
805    // Generate static methods in Type$Trait$ namespace
806    for method in &static_methods {
807        let r_name = method.r_method_name();
808        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
809            .with_impl_preconditions(impl_preconditions);
810        let target = ctx.namespace_target(ClassSystem::S3);
811
812        // Static method roxygen: the intro line (the block's title), the
813        // body of a block without `\usage`, the page lines.
814        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' Static trait method {0}::{1}()",
                trait_name, r_name))
    })format!(
815            "#' Static trait method {}::{}()",
816            trait_name, r_name
817        ));
818        lines.extend(namespace_member_body_lines(&ctx, &type_str, &target));
819        lines.extend(own_block_page_lines(method, &type_str, Some(&target), None));
820
821        let call = ctx.static_call();
822
823        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctx.namespace_symbol(ClassSystem::S3), ctx.params))
    })format!(
824            "{} <- function({}) {{",
825            ctx.namespace_symbol(ClassSystem::S3),
826            ctx.params
827        ));
828        ctx.emit_method_prelude(&mut lines, "  ", &r_name);
829        lines.extend(ctx.method_body_lines(&call, ClassSystem::S3));
830        lines.push("}".to_string());
831        lines.push(String::new());
832    }
833
834    // Generate const wrappers in Type$Trait$ namespace
835    for trait_const in consts {
836        let const_name = &trait_const.ident;
837        let const_str = const_name.to_string();
838        let target = trait_namespace_target(ClassSystem::S3, type_ident, trait_name, &const_str);
839
840        let roxygen = RoxygenBuilder::new()
841            .name(target.clone())
842            .rdname(&type_str)
843            .build();
844        lines.extend(roxygen);
845
846        let c_ident = trait_const.c_wrapper_ident_string(type_ident, trait_name);
847        let call = DotCallBuilder::new(&c_ident).build();
848
849        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function() {{", target))
    })format!("{target} <- function() {{"));
850        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", call))
    })format!("  {}", call));
851        lines.push("}".to_string());
852        lines.push(String::new());
853    }
854
855    lines.join("\n")
856}
857
858/// Generate S4-style R wrapper code.
859///
860/// For `impl Counter for SimpleCounter`, generates:
861/// - `setOldClass("SimpleCounter")` to register the S3 class for S4 dispatch
862/// - S4 generic `s4_trait_Counter_value(x, ...)` via `setGeneric()`
863/// - S4 method via `setMethod("s4_trait_Counter_value", "SimpleCounter", ...)`
864///
865/// Generic names are prefixed with `s4_trait_{Trait}_` to avoid collisions
866/// with user-defined S4 generics. Static methods and constants are generated
867/// as standalone exported functions: `{Type}_{Trait}_{method}()`.
868fn generate_trait_s4_r_wrapper(
869    type_ident: &syn::Ident,
870    trait_name: &syn::Ident,
871    methods: &[TraitMethod],
872    consts: &[TraitConst],
873    impl_preconditions: Option<bool>,
874) -> String {
875    use crate::r_wrapper_builder::{DotCallBuilder, RoxygenBuilder};
876
877    let mut lines = Vec::new();
878    let type_str = type_ident.to_string();
879
880    // Header comment
881    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# S4 trait methods for {0} implementing {1}",
                type_ident, trait_name))
    })format!(
882        "# S4 trait methods for {} implementing {}",
883        type_ident, trait_name
884    ));
885    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated by #[miniextendr(s4)] impl {0} for {1}",
                trait_name, type_ident))
    })format!(
886        "# Generated by #[miniextendr(s4)] impl {} for {}",
887        trait_name, type_ident
888    ));
889    lines.push(String::new());
890
891    // Separate instance methods from static methods
892    let instance_methods: Vec<_> = methods.iter().filter(|m| m.has_self).collect();
893    let static_methods: Vec<_> = methods.iter().filter(|m| !m.has_self).collect();
894
895    // NOTE: We do NOT call setOldClass here. The inherent impl's class registration
896    // (setClass for S4, or setOldClass for S3/env) takes care of that. Calling
897    // setOldClass here would clobber a proper S4 setClass with slots.
898    //
899    // The import joins the next roxygen block (a blank line does not end
900    // one), the first generic's, which opens with a tag. Only the instance
901    // methods need it: before a static's untagged intro line it would read
902    // that line as a continuation of `@importFrom`.
903    if !instance_methods.is_empty() {
904        lines.push("#' @importFrom methods setGeneric setMethod".to_string());
905        lines.push(String::new());
906    }
907
908    // Generate S4 generics + methods for instance methods
909    for method in &instance_methods {
910        let generic_name = method
911            .generic
912            .clone()
913            .unwrap_or_else(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s4_trait_{0}_{1}", trait_name,
                method.r_method_name()))
    })format!("s4_trait_{}_{}", trait_name, method.r_method_name()));
914        let receiver = method.receiver.as_deref().unwrap_or("x");
915        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
916            .with_impl_preconditions(impl_preconditions);
917
918        // Build full parameter list (x first, then others, then ...)
919        let full_params = crate::r_class_formatter::instance_formals(
920            &ctx.params,
921            receiver,
922            !method.no_dispatch_dots,
923        );
924
925        if method.generic.is_none() {
926            // S4 generic roxygen (include @param tags from method doc comments)
927            // S4 generic names are already type-qualified (s4_trait_TypeName_method)
928            // so @name won't create duplicate aliases across types. The prose is a
929            // `@description`, not a bare line (see the S3 generic above).
930            let mut generic_roxygen = RoxygenBuilder::new()
931                .description(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S4 generic for trait method `{0}::{1}`",
                trait_name, method.r_method_name()))
    })format!(
932                    "S4 generic for trait method `{}::{}`",
933                    trait_name,
934                    method.r_method_name()
935                ))
936                .name(&generic_name)
937                .rdname(&type_str)
938                .source(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `impl {0} for {1}`",
                trait_name, type_ident))
    })format!(
939                    "Generated by miniextendr from `impl {} for {}`",
940                    trait_name, type_ident
941                ))
942                .custom(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("@param x A `{0}` object",
                type_str))
    })format!("@param x A `{}` object", type_str))
943                .custom("@param ... Additional arguments passed to methods");
944            for tag in param_tags(method) {
945                generic_roxygen = generic_roxygen.custom(tag.clone());
946            }
947            lines.extend(generic_roxygen.export().build());
948        }
949        // Define the generic unless it exists; an explicit `generic` may be
950        // another package's. Also ends the `@importFrom` block above.
951        lines.push(crate::miniextendr_impl::s4_class::s4_generic_guard(
952            &generic_name,
953            method.generic.is_some(),
954            receiver,
955        ));
956        lines.push(String::new());
957
958        // S4 method roxygen + definition (include @param tags from method doc
959        // comments). The block sits on `methods::setMethod()`: roxygen2 names
960        // it from the S4 method object, and a split page (#1438) still needs
961        // a structural title or roxygen2 skips it.
962        lines.extend(own_block_page_lines(
963            method,
964            &type_str,
965            None,
966            Some(&generic_name),
967        ));
968        if method.generic.is_some() && !joins_author_topic(method, &type_str) {
969            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} A `{1}` object",
                receiver, type_str))
    })format!("#' @param {receiver} A `{type_str}` object"));
970            if !method.no_dispatch_dots {
971                lines.push("#' @param ... Additional arguments passed to methods".to_string());
972            }
973        }
974        push_param_tags(&mut lines, method);
975        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportMethod {0}",
                generic_name))
    })format!("#' @exportMethod {}", generic_name));
976
977        let class_str = class_ref(ClassSystem::S4, type_ident);
978        let signature = if method.receiver.is_some() {
979            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0} = \"{1}\")", receiver,
                class_str))
    })format!("c({receiver} = \"{class_str}\")")
980        } else {
981            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", class_str))
    })format!("\"{class_str}\"")
982        };
983        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("methods::setMethod(\"{0}\", {1}, function({2}) {{",
                generic_name, signature, full_params))
    })format!(
984            "methods::setMethod(\"{generic_name}\", {signature}, function({full_params}) {{"
985        ));
986        // S4 objects store the ExternalPtr in x@ptr — extract it for .Call()
987        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .ptr <- {0}@ptr", receiver))
    })format!("  .ptr <- {receiver}@ptr"));
988        let s4_call = ctx.instance_call(".ptr");
989        ctx.emit_method_prelude(&mut lines, "  ", &method.r_method_name());
990        lines.extend(ctx.method_body_lines(&s4_call, ClassSystem::S4));
991        finish_instance_body(&mut lines, method, receiver);
992        lines.push("})".to_string());
993        lines.push(String::new());
994    }
995
996    // Generate static methods as standalone functions. S4 objects intercept
997    // `$<-`, so these use the flat, class-qualified `Type_Trait_method` name
998    // (owned by `trait_namespace_target`) rather than `Type$Trait$method`.
999    for method in &static_methods {
1000        let r_name = method.r_method_name();
1001        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
1002            .with_impl_preconditions(impl_preconditions);
1003        let fn_name = ctx.namespace_target(ClassSystem::S4);
1004
1005        // Static method roxygen. A `@describeIn` block is listed in its
1006        // destination's "Functions" section, whose own block titles the page,
1007        // so it carries no intro line that could title it instead.
1008        if !describes_in(method) {
1009            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' Static trait method {0}::{1}() for {2}",
                trait_name, r_name, type_str))
    })format!(
1010                "#' Static trait method {}::{}() for {}",
1011                trait_name, r_name, type_str
1012            ));
1013        }
1014        lines.extend(own_block_page_lines(
1015            method,
1016            &type_str,
1017            Some(&fn_name),
1018            None,
1019        ));
1020        // The block documents the plain function `Type_Trait_method`, whose
1021        // `\usage` lists every formal: `R CMD check` codoc needs each one
1022        // documented.
1023        crate::roxygen::push_roxygen_tags(&mut lines, &param_doc_tags(&ctx, &type_str));
1024        lines.push("#' @export".to_string());
1025
1026        let call = ctx.static_call();
1027
1028        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctx.namespace_symbol(ClassSystem::S4), ctx.params))
    })format!(
1029            "{} <- function({}) {{",
1030            ctx.namespace_symbol(ClassSystem::S4),
1031            ctx.params
1032        ));
1033        ctx.emit_method_prelude(&mut lines, "  ", &r_name);
1034        lines.extend(ctx.method_body_lines(&call, ClassSystem::S4));
1035        lines.push("}".to_string());
1036        lines.push(String::new());
1037    }
1038
1039    // Generate const wrappers as standalone functions (flat name, as above)
1040    for trait_const in consts {
1041        let const_name = &trait_const.ident;
1042        let const_str = const_name.to_string();
1043        let fn_name = trait_namespace_target(ClassSystem::S4, type_ident, trait_name, &const_str);
1044
1045        let roxygen = RoxygenBuilder::new()
1046            .name(&fn_name)
1047            .rdname(&type_str)
1048            .export()
1049            .build();
1050        lines.extend(roxygen);
1051
1052        let c_ident = trait_const.c_wrapper_ident_string(type_ident, trait_name);
1053        let call = DotCallBuilder::new(&c_ident).build();
1054
1055        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function() {{", fn_name))
    })format!("{} <- function() {{", fn_name));
1056        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", call))
    })format!("  {}", call));
1057        lines.push("}".to_string());
1058        lines.push(String::new());
1059    }
1060
1061    lines.join("\n")
1062}
1063
1064/// Generate S7-style R wrapper code.
1065///
1066/// For `impl Counter for SimpleCounter`, generates:
1067/// - S7 S3-class wrapper: `.s7_class_SimpleCounter <- S7::new_S3_class("SimpleCounter")`
1068/// - S7 generic: `s7_trait_Counter_value <- S7::new_generic(...)` (if not exists)
1069/// - S7 method registration: `S7::method(s7_trait_Counter_value, .s7_class_SimpleCounter) <- ...`
1070///
1071/// Generic names are prefixed with `s7_trait_{Trait}_` to avoid collisions.
1072/// Static methods and constants live in an env attached to the class object,
1073/// read as `attr(Type, "Trait")$name` ([`s7_trait_member_access`]).
1074fn generate_trait_s7_r_wrapper(
1075    type_ident: &syn::Ident,
1076    trait_name: &syn::Ident,
1077    methods: &[TraitMethod],
1078    consts: &[TraitConst],
1079    impl_preconditions: Option<bool>,
1080) -> String {
1081    use crate::r_wrapper_builder::{DotCallBuilder, RoxygenBuilder};
1082
1083    let mut lines = Vec::new();
1084    let type_str = type_ident.to_string();
1085    let s7_class_var = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".s7_class_{0}", type_str))
    })format!(".s7_class_{}", type_str);
1086
1087    // Header comment
1088    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# S7 trait methods for {0} implementing {1}",
                type_ident, trait_name))
    })format!(
1089        "# S7 trait methods for {} implementing {}",
1090        type_ident, trait_name
1091    ));
1092    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated by #[miniextendr(s7)] impl {0} for {1}",
                trait_name, type_ident))
    })format!(
1093        "# Generated by #[miniextendr(s7)] impl {} for {}",
1094        trait_name, type_ident
1095    ));
1096    lines.push(String::new());
1097
1098    // Use the S7 class object directly for method dispatch.
1099    // new_S3_class("Foo") creates a descriptor for "Foo" but S7 new_class
1100    // creates instances with the namespaced class "pkg::Foo", so new_S3_class
1101    // wouldn't match. Using the class object directly works correctly.
1102    lines.push("#' @importFrom S7 new_generic method S7_dispatch".to_string());
1103    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} <- {0}",
                class_ref(ClassSystem::S7, type_ident), s7_class_var))
    })format!(
1104        "{s7_class_var} <- {}",
1105        class_ref(ClassSystem::S7, type_ident)
1106    ));
1107    lines.push(String::new());
1108
1109    // Separate instance methods from static methods
1110    let instance_methods: Vec<_> = methods.iter().filter(|m| m.has_self).collect();
1111    let static_methods: Vec<_> = methods.iter().filter(|m| !m.has_self).collect();
1112
1113    // Generate S7 generics + methods for instance methods
1114    for method in &instance_methods {
1115        let generic_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("s7_trait_{0}_{1}", trait_name,
                method.r_method_name()))
    })format!("s7_trait_{}_{}", trait_name, method.r_method_name());
1116        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
1117            .with_impl_preconditions(impl_preconditions);
1118
1119        // Build full parameter list (x first, then others, then ...)
1120        let full_params = if ctx.params.is_empty() {
1121            "x, ...".to_string()
1122        } else {
1123            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("x, {0}, ...", ctx.params))
    })format!("x, {}, ...", ctx.params)
1124        };
1125
1126        // S7 generic roxygen
1127        // Note: Don't include method-specific @param tags here since S7 methods
1128        // are assignments and won't appear in \usage, which would cause warnings
1129        // S7 generic names are already type-qualified so @name won't duplicate.
1130        // The prose is a `@description`, not a bare line (see the S3 generic).
1131        let generic_roxygen = RoxygenBuilder::new()
1132            .description(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7 generic for trait method `{0}::{1}`",
                trait_name, method.r_method_name()))
    })format!(
1133                "S7 generic for trait method `{}::{}`",
1134                trait_name,
1135                method.r_method_name()
1136            ))
1137            .name(&generic_name)
1138            .rdname(&type_str)
1139            .source(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `impl {0} for {1}`",
                trait_name, type_ident))
    })format!(
1140                "Generated by miniextendr from `impl {} for {}`",
1141                trait_name, type_ident
1142            ))
1143            .export()
1144            .build();
1145        lines.extend(generic_roxygen);
1146
1147        // S7 generic definition. An operator `r_name` makes the prefixed
1148        // generic non-syntactic (`s7_trait_Ops_[[`), so symbol positions are
1149        // backtick-quoted (#1475); string literals keep the bare name.
1150        let generic_symbol = crate::naming::r_def_name(&generic_name);
1151        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if (!exists(\"{0}\", mode = \"function\")) {{",
                generic_name))
    })format!(
1152            "if (!exists(\"{generic_name}\", mode = \"function\")) {{"
1153        ));
1154        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0} <- S7::new_generic(\"{1}\", \"x\", function(x, ...) S7::S7_dispatch())",
                generic_symbol, generic_name))
    })format!(
1155            "  {generic_symbol} <- S7::new_generic(\"{generic_name}\", \"x\", function(x, ...) S7::S7_dispatch())"
1156        ));
1157        lines.push("}".to_string());
1158        lines.push(String::new());
1159
1160        // S7 method definition
1161        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("S7::method({0}, {1}) <- function({2}) {{",
                generic_symbol, s7_class_var, full_params))
    })format!(
1162            "S7::method({}, {}) <- function({}) {{",
1163            generic_symbol, s7_class_var, full_params
1164        ));
1165        // S7 objects store the ExternalPtr in x@.ptr — extract it for .Call()
1166        lines.push("  .ptr <- x@.ptr".to_string());
1167        let s7_call = ctx.instance_call(".ptr");
1168        ctx.emit_method_prelude(&mut lines, "  ", &method.r_method_name());
1169        lines.extend(ctx.method_body_lines(&s7_call, ClassSystem::S7));
1170        finish_instance_body(&mut lines, method, "x");
1171        lines.push("}".to_string());
1172        lines.push(String::new());
1173
1174        // Per-class fast-path dispatch shortcut (#987).
1175        //
1176        // Mirror the inherent-impl S7 shortcut (#982, see
1177        // `miniextendr_impl::s7_class`): alongside the trait generic, emit a
1178        // plain `<ClassName>_<method>(self, ...)` function that calls `.Call`
1179        // directly, bypassing `S7::S7_dispatch()`. The receiver is `.mx_self`
1180        // here (the generic names it `x`) and wired through `self@.ptr`.
1181        // `s7(no_shortcut)` opts a method out, and an operator `r_name` gets no
1182        // shortcut (see `s7_class::s7_shortcut_name`).
1183        let shortcut_name = if method.no_shortcut {
1184            None
1185        } else {
1186            crate::miniextendr_impl::s7_class::s7_shortcut_name(&type_str, &method.r_method_name())
1187        };
1188        if let Some(shortcut_name) = shortcut_name {
1189            let shortcut_formals = if ctx.params.is_empty() {
1190                ".mx_self, ...".to_string()
1191            } else {
1192                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".mx_self, {0}, ...", ctx.params))
    })format!(".mx_self, {}, ...", ctx.params)
1193            };
1194            let shortcut_call = ctx.instance_call(".mx_self@.ptr");
1195
1196            // Roxygen: shared advisory prose + scaffolding. The shared @rdname
1197            // page (type_str) already carries the method's prose via the generic
1198            // block above, so only document `.mx_self` + each formal here to keep the
1199            // shortcut's \usage fully covered (no "undocumented argument" warning).
1200            //
1201            // A method-level `@rdname` naming another page or a `@describeIn`
1202            // sends the shortcut to a topic whose own block documents its
1203            // arguments (#1590): only the type page needs the structural `.mx_self` /
1204            // `...` lines, and the advisory's description would be a paragraph of
1205            // the topic's description that names no function. Its first line
1206            // stays as the block's title, which a page of the shortcut's own
1207            // (`@rdname` naming a new page) needs.
1208            let joined = joins_author_topic(method, &type_str);
1209            let advisory = crate::miniextendr_impl::s7_class::shortcut_advisory_lines(
1210                &method.r_method_name(),
1211                &type_str,
1212            );
1213            let advisory_len = if joined { 1 } else { advisory.len() };
1214            lines.extend(advisory.into_iter().take(advisory_len));
1215            if !joined {
1216                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param .mx_self A `{0}` object.",
                type_str))
    })format!("#' @param .mx_self A `{}` object.", type_str));
1217            }
1218            push_param_tags(&mut lines, method);
1219            // Auto-document any formal lacking an explicit @param tag. `...` is
1220            // included so roxygen2 covers it (otherwise R CMD check warns about
1221            // an undocumented argument). Split on top-level commas only — a
1222            // naive `split(", ")` breaks a `mode = c("fast", "slow")` default
1223            // into a bogus `"slow")` formal (undocumented-argument warning). A
1224            // method that inherits its arguments (`@inheritParams`) gets no
1225            // filler, which would block the inheritance. A `choices(...)`
1226            // param's filler is its choice text.
1227            let fillers = !params_documented_elsewhere(method, &type_str);
1228            let choice_docs = ctx.choice_param_docs();
1229            for formal in crate::roxygen::split_r_formals(&shortcut_formals) {
1230                let pname = crate::roxygen::formal_name(formal);
1231                if joined || pname == ".mx_self" {
1232                    continue;
1233                }
1234                let documented = crate::roxygen::param_documented(&method.doc_tags, pname);
1235                if documented {
1236                    continue;
1237                }
1238                if pname == "..." {
1239                    lines.push(
1240                        "#' @param ... Additional arguments; ignored by the fast-path shortcut."
1241                            .to_string(),
1242                    );
1243                } else if fillers {
1244                    let body = choice_docs
1245                        .get(pname)
1246                        .map_or("(undocumented)", String::as_str);
1247                    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} {1}", pname, body))
    })format!("#' @param {pname} {body}"));
1248                }
1249            }
1250            lines.extend(own_block_page_lines(
1251                method,
1252                &type_str,
1253                Some(&shortcut_name),
1254                None,
1255            ));
1256            lines.extend(crate::roxygen::source_tag(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Generated by miniextendr from `impl {0} for {1}` (`{2}` shortcut)",
                trait_name, type_ident, method.r_method_name()))
    })format!(
1257                "Generated by miniextendr from `impl {} for {}` (`{}` shortcut)",
1258                trait_name,
1259                type_ident,
1260                method.r_method_name()
1261            )));
1262            lines.push("#' @export".to_string());
1263
1264            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                shortcut_name, shortcut_formals))
    })format!(
1265                "{} <- function({}) {{",
1266                shortcut_name, shortcut_formals
1267            ));
1268            ctx.emit_method_prelude(&mut lines, "  ", &method.r_method_name());
1269            lines.extend(ctx.method_body_lines(&shortcut_call, ClassSystem::S7));
1270            finish_instance_body(&mut lines, method, ".mx_self");
1271            lines.push("}".to_string());
1272            lines.push(String::new());
1273        }
1274    }
1275
1276    // Create trait namespace for static methods and consts.
1277    // For S7 classes, use a local variable + attr() to avoid S7's $<- interception.
1278    let trait_env_var = trait_namespace_env_var(type_ident, trait_name);
1279    if !static_methods.is_empty() || !consts.is_empty() {
1280        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                trait_env_var))
    })format!("{} <- new.env(parent = emptyenv())", trait_env_var));
1281        lines.push(String::new());
1282    }
1283
1284    // Generate static methods in trait namespace. The wrapper is *assigned*
1285    // into the local env (`trait_namespace_target(S7, ..)` = `.Type__Trait$m`),
1286    // but its documented `@name` is the call-site form `attr(Type, "Trait")$m`
1287    // (`s7_trait_member_access`): S7's `$` stops on the class object.
1288    for method in &static_methods {
1289        let r_name = method.r_method_name();
1290        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
1291            .with_impl_preconditions(impl_preconditions);
1292
1293        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' Static trait method {0}::{1}()",
                trait_name, r_name))
    })format!(
1294            "#' Static trait method {}::{}()",
1295            trait_name, r_name
1296        ));
1297        let name = s7_trait_member_access(type_ident, trait_name, &r_name);
1298        lines.extend(namespace_member_body_lines(&ctx, &type_str, &name));
1299        lines.extend(own_block_page_lines(method, &type_str, Some(&name), None));
1300
1301        let call = ctx.static_call();
1302
1303        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctx.namespace_symbol(ClassSystem::S7), ctx.params))
    })format!(
1304            "{} <- function({}) {{",
1305            ctx.namespace_symbol(ClassSystem::S7),
1306            ctx.params
1307        ));
1308        ctx.emit_method_prelude(&mut lines, "  ", &r_name);
1309        lines.extend(ctx.method_body_lines(&call, ClassSystem::S7));
1310        lines.push("}".to_string());
1311        lines.push(String::new());
1312    }
1313
1314    // Generate const wrappers in trait namespace (assigned into `.Type__Trait`,
1315    // documented as `attr(Type, "Trait")$const`, see the static-method note above).
1316    for trait_const in consts {
1317        let const_name = &trait_const.ident;
1318        let const_str = const_name.to_string();
1319
1320        let roxygen = RoxygenBuilder::new()
1321            .name(s7_trait_member_access(type_ident, trait_name, &const_str))
1322            .rdname(&type_str)
1323            .build();
1324        lines.extend(roxygen);
1325
1326        let c_ident = trait_const.c_wrapper_ident_string(type_ident, trait_name);
1327        let call = DotCallBuilder::new(&c_ident).build();
1328
1329        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function() {{",
                trait_namespace_target(ClassSystem::S7, type_ident,
                    trait_name, &const_str)))
    })format!(
1330            "{} <- function() {{",
1331            trait_namespace_target(ClassSystem::S7, type_ident, trait_name, &const_str)
1332        ));
1333        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", call))
    })format!("  {}", call));
1334        lines.push("}".to_string());
1335        lines.push(String::new());
1336    }
1337
1338    // Attach the trait env to the S7 class via attr() to bypass S7's $<- interception.
1339    // S7's `$` stops on the class object too, so callers read it back the same way:
1340    // attr(Type, "Trait")$method.
1341    if !static_methods.is_empty() || !consts.is_empty() {
1342        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("attr({0}, \"{1}\") <- {2}",
                class_ref(ClassSystem::S7, type_ident), trait_name,
                trait_env_var))
    })format!(
1343            "attr({}, \"{}\") <- {}",
1344            class_ref(ClassSystem::S7, type_ident),
1345            trait_name,
1346            trait_env_var
1347        ));
1348        lines.push(String::new());
1349    }
1350
1351    lines.join("\n")
1352}
1353
1354/// Generate R6-style R wrapper code.
1355///
1356/// R6 classes are defined monolithically (all methods in `R6Class()`), so trait
1357/// methods cannot be injected into the class definition. Instead, both instance
1358/// and static trait methods live in the class-scoped `Type$Trait$name`
1359/// namespace (env-style) — the R6 generator object is an environment, so
1360/// `Type$Trait <- new.env()` attaches cleanly and `Type$Trait$method(x)`
1361/// resolves at the call site.
1362///
1363/// For `impl Counter for SimpleCounter`, generates:
1364/// - `SimpleCounter$Counter$value(x)`      -- instance method (takes the object)
1365/// - `SimpleCounter$Counter$increment(x)`  -- instance method
1366///
1367/// This class-qualified shape is collision-free by construction: two R6 impls
1368/// of one trait on different types no longer share an unqualified
1369/// `r6_trait_<Trait>_<method>` name (#1115). It also unifies R6 with the Env/S3
1370/// namespace shape (#1141) — R6 instance and static methods previously
1371/// disagreed on shape for no functional reason.
1372fn generate_trait_r6_r_wrapper(
1373    type_ident: &syn::Ident,
1374    trait_name: &syn::Ident,
1375    methods: &[TraitMethod],
1376    consts: &[TraitConst],
1377    impl_preconditions: Option<bool>,
1378) -> String {
1379    use crate::r_wrapper_builder::{DotCallBuilder, RoxygenBuilder};
1380
1381    let mut lines = Vec::new();
1382    let type_str = type_ident.to_string();
1383
1384    // Header comment
1385    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# R6 trait methods for {0} implementing {1}",
                type_ident, trait_name))
    })format!(
1386        "# R6 trait methods for {} implementing {}",
1387        type_ident, trait_name
1388    ));
1389    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated by #[miniextendr(r6)] impl {0} for {1}",
                trait_name, type_ident))
    })format!(
1390        "# Generated by #[miniextendr(r6)] impl {} for {}",
1391        trait_name, type_ident
1392    ));
1393    lines.push("# Note: R6 trait methods live in the Type$Trait$method namespace".to_string());
1394    lines.push(String::new());
1395
1396    // Separate instance methods from static methods
1397    let instance_methods: Vec<_> = methods.iter().filter(|m| m.has_self).collect();
1398    let static_methods: Vec<_> = methods.iter().filter(|m| !m.has_self).collect();
1399
1400    // Create the trait namespace env up front — instance methods now live in it
1401    // too (not just static methods / consts).
1402    if binds_trait_namespace(ClassSystem::R6, methods, consts) {
1403        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                trait_namespace_env(ClassSystem::R6, type_ident, trait_name)))
    })format!(
1404            "{} <- new.env(parent = emptyenv())",
1405            trait_namespace_env(ClassSystem::R6, type_ident, trait_name)
1406        ));
1407        lines.push(String::new());
1408    }
1409
1410    // Generate instance methods in the Type$Trait$ namespace
1411    for method in &instance_methods {
1412        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
1413            .with_impl_preconditions(impl_preconditions);
1414        let target = ctx.namespace_target(ClassSystem::R6);
1415
1416        // The injected receiver cannot collide with a Rust parameter.
1417        let full_params = if ctx.params.is_empty() {
1418            ".mx_self".to_string()
1419        } else {
1420            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".mx_self, {0}", ctx.params))
    })format!(".mx_self, {}", ctx.params)
1421        };
1422
1423        // Namespace-member roxygen — a `$<-` assignment target, so roxygen emits
1424        // no `\usage` and needs no per-formal `@param` docs (#1141; Env puts
1425        // them in a `\describe{}` list of the page's description instead).
1426        // No `@param` lines on purpose, generated or the method's own: roxygen2
1427        // renders a per-method Arguments list on an R6 page only for a member of
1428        // the generator's `public_methods` (`r6_extract_methods`; an explicit
1429        // `@R6method Type$method` tag warns "can't find matching R6 method" for
1430        // anything else), and a trait method is not one. A `@param` here lands
1431        // in a top-level `\arguments` of the class page, detached from any
1432        // usage (so `R CMD check` never flags it) and merged by name with every
1433        // other trait method's parameters, the last block winning.
1434        lines.extend(own_block_page_lines(
1435            method,
1436            &type_str,
1437            Some(&target),
1438            Some(&target),
1439        ));
1440
1441        let call = ctx.instance_call(".ptr");
1442
1443        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctx.namespace_symbol(ClassSystem::R6), full_params))
    })format!(
1444            "{} <- function({full_params}) {{",
1445            ctx.namespace_symbol(ClassSystem::R6)
1446        ));
1447        // R6 objects store the ExternalPtr in private$.ptr — extract it for .Call()
1448        lines.push("  .ptr <- .mx_self$.__enclos_env__$private$.ptr".to_string());
1449        ctx.emit_method_prelude(&mut lines, "  ", &method.r_method_name());
1450        lines.extend(ctx.method_body_lines(&call, ClassSystem::R6));
1451        finish_instance_body(&mut lines, method, ".mx_self");
1452        lines.push("}".to_string());
1453        lines.push(String::new());
1454    }
1455
1456    // Generate static methods in Type$Trait$ namespace
1457    for method in &static_methods {
1458        let r_name = method.r_method_name();
1459        let ctx = TraitMethodContext::new(method, type_ident, trait_name)
1460            .with_impl_preconditions(impl_preconditions);
1461        let target = ctx.namespace_target(ClassSystem::R6);
1462
1463        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' Static trait method {0}::{1}()",
                trait_name, r_name))
    })format!(
1464            "#' Static trait method {}::{}()",
1465            trait_name, r_name
1466        ));
1467        lines.extend(own_block_page_lines(method, &type_str, Some(&target), None));
1468
1469        let call = ctx.static_call();
1470
1471        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctx.namespace_symbol(ClassSystem::R6), ctx.params))
    })format!(
1472            "{} <- function({}) {{",
1473            ctx.namespace_symbol(ClassSystem::R6),
1474            ctx.params
1475        ));
1476        ctx.emit_method_prelude(&mut lines, "  ", &r_name);
1477        lines.extend(ctx.method_body_lines(&call, ClassSystem::R6));
1478        lines.push("}".to_string());
1479        lines.push(String::new());
1480    }
1481
1482    // Generate const wrappers in Type$Trait$ namespace
1483    for trait_const in consts {
1484        let const_name = &trait_const.ident;
1485        let const_str = const_name.to_string();
1486        let target = trait_namespace_target(ClassSystem::R6, type_ident, trait_name, &const_str);
1487
1488        let roxygen = RoxygenBuilder::new()
1489            .name(target.clone())
1490            .rdname(&type_str)
1491            .build();
1492        lines.extend(roxygen);
1493
1494        let c_ident = trait_const.c_wrapper_ident_string(type_ident, trait_name);
1495        let call = DotCallBuilder::new(&c_ident).build();
1496
1497        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function() {{", target))
    })format!("{target} <- function() {{"));
1498        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", call))
    })format!("  {}", call));
1499        lines.push("}".to_string());
1500        lines.push(String::new());
1501    }
1502
1503    lines.join("\n")
1504}
1505
1506/// Close an instance-method body (#1213).
1507///
1508/// A void method hands back its receiver (`x` / `self`) so calls chain under
1509/// the pipe; the receiver is returned visibly, like every other return. A
1510/// method whose declared return is `Invisible<..>` wraps its final expression
1511/// (the receiver, or the converted `.val` / classed value) in `invisible()`.
1512fn finish_instance_body(lines: &mut Vec<String>, method: &super::TraitMethod, receiver: &str) {
1513    if method.returns_unit() {
1514        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", receiver))
    })format!("  {receiver}"));
1515    }
1516    if method.is_invisible()
1517        && let Some(last) = lines.last_mut()
1518    {
1519        let expr = last.trim_start();
1520        let indent = &last[..last.len() - expr.len()];
1521        *last = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}invisible({1})", indent, expr))
    })format!("{indent}invisible({expr})");
1522    }
1523}