Skip to main content

miniextendr_macros/miniextendr_impl/
s3_class.rs

1//! S3-class R wrapper generator.
2//!
3//! Generates **lightweight, single-dispatch** S3 generics with
4//! `<generic>.<class>` methods. Method dispatch is driven by the `class()`
5//! attribute vector — first match wins — so inheritance is "string-prefix"
6//! based and cheap. No formal slot validation, no multi-dispatch (vctrs-style
7//! double-dispatch is supported via `#[miniextendr(s3(generic = "...", class = "..."))]` for
8//! `vec_ptype2.a.b` patterns). Pick S3 for tidyverse interop and for
9//! extending existing base generics (`print`, `format`, `summary`); use S4/S7
10//! when you need validation or formal hierarchies.
11
12use super::ParsedImpl;
13
14/// Generates the R wrapper of an S3-style class, in the parts the wrapper
15/// writer merges per type ([`super::ClassWrapper`], #1776).
16///
17/// Produces the following R code:
18/// - Constructor: `new_<class>(...)` function that calls the Rust constructor
19///   and wraps the result with `structure(.val, class = "<class>")`; none for
20///   a class without a constructor (see [`no_constructor_head`])
21/// - S3 generics: for each instance method, a `UseMethod()` generic is created
22///   (unless overriding an existing generic via `#[miniextendr(generic = "...")]`)
23/// - S3 methods: `<generic>.<class>` functions dispatching to the Rust `.Call()` wrapper,
24///   with the ExternalPtr extracted from `x`
25/// - Static methods: regular functions named `<class>_<method>(...)`
26/// - Class environment: `ClassName <- new.env(parent = emptyenv())` for `Class$new()`
27///   syntax and trait namespaces (see [`class_env`])
28///
29/// Custom double-dispatch patterns (e.g., `vec_ptype2.a.b`) are supported via
30/// `#[miniextendr(generic = "...", class = "...")]` attributes.
31///
32/// The constructor and the field methods are the head; the S3 methods and the
33/// static methods are the members. With a constructor, the tail is the class
34/// environment and its `$new` binding; without one, the class environment is
35/// the env part, which the wrapper writer keeps only when a trait impl writes
36/// into it (#2264, #2289).
37pub fn generate_s3_class(parsed_impl: &ParsedImpl) -> super::ClassWrapper {
38    use crate::r_class_formatter::{
39        ClassDocBuilder, MethodDocBuilder, ParsedImplExt, emit_s3_generic_guard,
40        should_export_from_tags,
41    };
42
43    let class_name = parsed_impl.class_name();
44    let type_ident = &parsed_impl.type_ident;
45    // S3 convention: lowercase constructor name
46    let ctor_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("new_{0}",
                class_name.to_lowercase()))
    })format!("new_{}", class_name.to_lowercase());
47    let class_doc_tags = &parsed_impl.doc_tags;
48    // A plain `noexport` (without `internal`) is folded into the @noRd gate too —
49    // it must suppress Rd contribution entirely, matching `ClassDocBuilder::build`'s
50    // `suppress_rd` gate. `@method`/`@export` tags stay preserved for S3 dispatch
51    // registration by the existing @noRd-handling branches below.
52    let class_has_no_rd = crate::roxygen::has_roxygen_tag(class_doc_tags, "noRd")
53        || (parsed_impl.noexport && !parsed_impl.internal);
54    // Generic export (NAMESPACE `export(generic_name)`): suppressed by
55    // @noRd / internal / noexport. An internal class doesn't pollute the
56    // package's user-facing surface with a bare generic.
57    let should_export =
58        should_export_from_tags(class_doc_tags, parsed_impl.noexport || parsed_impl.internal);
59    // Method @export (NAMESPACE `S3method(generic, Class)`): only suppressed
60    // by `noexport`. `internal` should keep S3method registration so dispatch
61    // still works for instances of the class — without it, callers (including
62    // the package's own tests) couldn't dispatch on the type at all. See #431.
63    let should_register_s3method = !parsed_impl.noexport;
64
65    let mut w = super::ClassWrapper::default();
66    let mut lines = Vec::new();
67    // The class block is the constructor's; a block without one still
68    // documents the class with its impl docs.
69    crate::roxygen::push_roxygen_tags(&mut w.class_docs, class_doc_tags);
70
71    // Constructor with combined class and constructor documentation
72    if let Some(ctx) = parsed_impl.constructor_context() {
73        w.member_names.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}$new`", class_name))
    })format!("`{class_name}$new`"));
74        lines.push(ctx.source_comment(type_ident));
75        let mut ctor_doc_tags = Vec::new();
76        ctor_doc_tags.extend(class_doc_tags.iter().cloned());
77        ctor_doc_tags.extend(ctx.method.doc_tags.iter().cloned());
78        let ctor_choice_docs = ctx.choice_param_docs();
79
80        let class_docs = ClassDocBuilder::new(&class_name, type_ident, &ctor_doc_tags, "S3")
81            .with_ctor_params(&ctx.params, &ctor_choice_docs)
82            .with_export_control(parsed_impl.internal, parsed_impl.noexport);
83        lines.extend(class_docs.build());
84        w.class_docs = class_docs.docs();
85        w.mark_class_doc_lines(&mut lines, parsed_impl);
86        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctor_name, ctx.params))
    })format!("{} <- function({}) {{", ctor_name, ctx.params));
87        for check in ctx.precondition_checks() {
88            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", check))
    })format!("  {}", check));
89        }
90        // Inject match.arg validation for match_arg/choices params
91        for line in ctx.match_arg_prelude() {
92            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", line))
    })format!("  {}", line));
93        }
94        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .val <- {0}", ctx.static_call()))
    })format!("  .val <- {}", ctx.static_call()));
95        lines.extend(crate::method_return_builder::condition_check_lines("  "));
96        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  structure(.val, class = \"{0}\")",
                class_name))
    })format!("  structure(.val, class = \"{}\")", class_name));
97        lines.push("}".to_string());
98        lines.push(String::new());
99    } else {
100        no_constructor_head(parsed_impl, &mut w, &mut lines, "S3", None);
101    }
102
103    // The field methods of `s3(r_data_accessors)` (`$` / `[[` / `names` /
104    // `as.list` / `.DollarNames`, and the setters; #1848, #1890, #1885),
105    // ahead of the instance methods: on a shared page roxygen2 keeps the last
106    // `@param` of a name, so a method's own text for `name` or `value` wins.
107    // They are documented whenever the class is: `internal` keeps the class
108    // out of the exports, and its page (`\keyword{internal}`) still documents
109    // the registered methods, as for S4 (#1918).
110    if parsed_impl.r_data_accessors.enabled() {
111        lines.extend(super::field_syntax::s3_field_methods(
112            parsed_impl,
113            !class_has_no_rd,
114            should_register_s3method,
115        ));
116    }
117    w.head = std::mem::take(&mut lines);
118
119    // Instance methods as S3 generics + methods. Their conditions report the
120    // generic's call, resolved from the method frame on a raise (#1851).
121    for ctx in parsed_impl.instance_method_contexts() {
122        let ctx = ctx.with_call_attribution(crate::r_wrapper_builder::CallAttribution::Generic);
123        lines.push(ctx.source_comment(type_ident));
124        let qualified_generic = ctx.generic_name();
125        let (generic_package, generic_name) = crate::naming::split_generic(&qualified_generic);
126        // Use custom class suffix if provided (for double-dispatch patterns like vec_ptype2.a.b)
127        let method_class_suffix = ctx
128            .class_suffix()
129            .map(|s| s.to_string())
130            .unwrap_or_else(|| class_name.clone());
131        let s3_method_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", generic_name,
                method_class_suffix))
    })format!("{}.{}", generic_name, method_class_suffix);
132        // `@export` on the method gives `S3method(generic, Class)`. A method on
133        // `pkg::generic` registers through `@exportS3Method pkg::generic Class`
134        // instead: R applies `S3method(pkg::generic, Class)` once `pkg`'s
135        // namespace loads, so `pkg` may stay in Suggests (#2154).
136        let registration = match generic_package {
137            Some(package) => {
138                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportS3Method {0}::{1} {2}",
                package, generic_name, method_class_suffix))
    })format!("#' @exportS3Method {package}::{generic_name} {method_class_suffix}")
139            }
140            None => "#' @export".to_string(),
141        };
142        let receiver = ctx.method.method_attrs.receiver.as_deref().unwrap_or("x");
143        let full_params = ctx.s3_method_formals(); // x, params, ... (`value` last for `*<-`)
144
145        // Only create the S3 generic if no generic/class override was provided
146        // (custom class suffix implies using an existing generic)
147        if !ctx.has_generic_override() && !ctx.has_class_override() {
148            // Create the S3 generic (only for custom generics, not base R overrides)
149            if class_has_no_rd {
150                lines.push("#' @noRd".to_string());
151            } else {
152                // The generic block is named after the S3 method (`generic.Class`,
153                // class-qualified so classes sharing a generic don't collide on
154                // `\alias{generic}`). That is the same alias the method block
155                // below produces, so both must land on the same page: a
156                // method-level `@rdname` or `@describeIn` moves the generic block
157                // along with the method, otherwise R CMD check reports the alias
158                // as duplicated across the class page and the method's page.
159                let method_tags = &ctx.method.doc_tags;
160                let joined = crate::roxygen::joins_author_topic(method_tags, Some(&class_name));
161                if !joined {
162                    // roxygen2 keeps the first `@title` on a page. On the class
163                    // page that is the class block's, so this one is inert; on a
164                    // split page it would beat the method's structural title.
165                    // The author's topic describes the method itself, so the
166                    // structural description would only add a stray paragraph.
167                    lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title S3 generic for `{0}`",
                generic_name))
    })format!(
168                        "#' @title S3 generic for `{}`",
169                        generic_name
170                    )));
171                    lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @description S3 generic for `{0}`",
                generic_name))
    })format!(
172                        "#' @description S3 generic for `{}`",
173                        generic_name
174                    )));
175                }
176                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}.{1}", generic_name,
                class_name))
    })format!("#' @name {}.{}", generic_name, class_name));
177                super::push_member_rdname(&mut lines, method_tags, &class_name);
178                if !joined {
179                    // On the author's topic its own block documents `x` and
180                    // `...`; a generated line would replace that text (#1590).
181                    lines.push(super::member_default("#' @param x An object".to_string()));
182                    lines.push(super::member_default(
183                        "#' @param ... Additional arguments passed to methods".to_string(),
184                    ));
185                }
186                crate::roxygen::push_order_after_topic_blocks(&mut lines, method_tags, &class_name);
187                lines.extend(crate::roxygen::method_source_tag(
188                    type_ident,
189                    &ctx.method.ident,
190                ));
191                if should_export {
192                    // Explicit name on @export: the generic is wrapped in
193                    // `if (!exists(...))`, which roxygen2 can't introspect, and the
194                    // @name tag above is the class-qualified form (to dedupe aliases
195                    // when several classes share a generic). Without an explicit
196                    // target on @export, roxygen2 attaches the export to the next
197                    // parseable function (the S3 method), producing a bogus
198                    // `export(generic.Class)` instead of `export(generic)`.
199                    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @export {0}", generic_name))
    })format!("#' @export {}", generic_name));
200                }
201            }
202            lines.push(emit_s3_generic_guard(generic_name));
203            lines.push(String::new());
204        }
205
206        // Then create the S3 method
207        if class_has_no_rd {
208            // @noRd class: minimal roxygen — just @method (+ @export for NAMESPACE
209            // dispatch registration, gated by `should_register_s3method` so a
210            // `noexport`-driven suppression — folded into `class_has_no_rd` above —
211            // also drops S3 dispatch, not just Rd docs; a plain user `@noRd` with
212            // no `noexport` attr still registers dispatch as before, since
213            // `should_register_s3method` is `true` whenever `noexport` isn't set).
214            // @export on S3 methods produces S3method() in NAMESPACE (not export()).
215            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", generic_name,
                method_class_suffix))
    })format!("#' @method {generic_name} {method_class_suffix}"));
216            if should_register_s3method {
217                lines.push(registration);
218            }
219        } else {
220            let mx_doc = ctx.choice_param_docs();
221            let method_doc =
222                MethodDocBuilder::new(&class_name, generic_name, type_ident, &ctx.method.doc_tags)
223                    .with_source_method(&ctx.method.ident)
224                    .with_r_params(&ctx.params)
225                    .with_choice_param_docs(&mx_doc)
226                    .with_r_name(s3_method_name.clone());
227            lines.extend(method_doc.build());
228            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", generic_name,
                method_class_suffix))
    })format!("#' @method {generic_name} {method_class_suffix}"));
229            // roxygen2 can't parse generic blocks wrapped in if (!exists(...)),
230            // so @param x/@param ... must also appear on the method block. On
231            // an author topic (method-level `@rdname` / `@describeIn`) the
232            // topic's own block documents them instead: roxygen2 keeps the
233            // later `@param` of a name, and this block sorts last (#1590).
234            if !crate::roxygen::joins_author_topic(&ctx.method.doc_tags, Some(&class_name)) {
235                lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} An object.",
                receiver))
    })format!(
236                    "#' @param {receiver} An object."
237                )));
238                if !ctx.method.method_attrs.no_dispatch_dots || ctx.method.has_dots {
239                    lines.push(super::member_default(
240                        "#' @param ... Additional arguments.".to_string(),
241                    ));
242                }
243            }
244            if should_register_s3method {
245                lines.push(registration);
246            }
247        }
248        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!(
249            "{} <- function({}) {{",
250            crate::naming::r_def_name(&s3_method_name),
251            full_params
252        ));
253
254        ctx.emit_method_prelude(&mut lines, "  ", &s3_method_name, &full_params);
255
256        let call = ctx.instance_call(receiver);
257        let strategy = crate::ReturnStrategy::for_method(ctx.method);
258        let return_builder = crate::MethodReturnBuilder::new(call)
259            .with_raise_default(ctx.call_attribution.raise_default())
260            .with_strategy(strategy)
261            .with_invisible(ctx.method.is_invisible())
262            .with_class_name(class_name.clone())
263            .with_return_class_from_method(ctx.method, &type_ident.to_string())
264            .with_chain_var(receiver.to_string());
265        lines.extend(return_builder.build_s3_body());
266
267        lines.push("}".to_string());
268        lines.push(String::new());
269    }
270
271    // Static methods as regular functions
272    for ctx in parsed_impl.static_method_contexts() {
273        lines.push(ctx.source_comment(type_ident));
274        // Static methods get a prefix to avoid naming conflicts
275        let method_name = ctx.method.r_method_name();
276        let fn_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}",
                class_name.to_lowercase(), method_name))
    })format!("{}_{}", class_name.to_lowercase(), method_name);
277
278        let mx_doc = ctx.choice_param_docs();
279        let doc_tags = parsed_impl.static_doc_tags(
280            ctx.method,
281            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}()", fn_name))
    })format!("{fn_name}()"),
282            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}()", ctor_name))
    })format!("{ctor_name}()"),
283            true,
284        );
285        let method_doc = MethodDocBuilder::new(&class_name, &method_name, type_ident, &doc_tags)
286            .with_source_method(&ctx.method.ident)
287            .with_r_params(&ctx.params)
288            .with_choice_param_docs(&mx_doc)
289            .with_r_name(fn_name.clone())
290            .with_class_no_rd(class_has_no_rd);
291        lines.extend(method_doc.build());
292        // Export static methods so users can call them
293        if !class_has_no_rd {
294            lines.push("#' @export".to_string());
295        }
296
297        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                crate::naming::r_def_name(&fn_name), ctx.params))
    })format!(
298            "{} <- function({}) {{",
299            crate::naming::r_def_name(&fn_name),
300            ctx.params
301        ));
302
303        ctx.emit_method_prelude(&mut lines, "  ", &fn_name, &ctx.params);
304
305        let strategy = crate::ReturnStrategy::for_method(ctx.method);
306        let return_builder = crate::MethodReturnBuilder::new(ctx.static_call())
307            .with_strategy(strategy)
308            .with_invisible(ctx.method.is_invisible())
309            .with_class_name(class_name.clone())
310            .with_return_class_from_method(ctx.method, &type_ident.to_string());
311        lines.extend(return_builder.build_s3_body());
312
313        lines.push("}".to_string());
314        lines.push(String::new());
315    }
316    w.members = std::mem::take(&mut lines);
317
318    // The class environment holds `Class$new()` and the trait namespaces
319    // (`Class$Trait`, for a trait's static methods and consts; static methods
320    // of the impl are plain functions). With a constructor it is the tail,
321    // with the `$new` binding. Without one, only a trait namespace can land
322    // in it, which is known only when the wrappers are written, where the
323    // trait impls register: it is the env part, kept for a trait namespace
324    // (#2264, #2289). A readers-only impl of a class the package names and
325    // builds itself then binds no same-named constructor a second time
326    // (#1918).
327    let env = class_env(parsed_impl, class_has_no_rd, should_export);
328    if parsed_impl.constructor_context().is_some() {
329        w.tail = env;
330        w.tail.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}$new <- {1}", class_name,
                ctor_name))
    })format!("{}$new <- {}", class_name, ctor_name));
331        w.tail.push(String::new());
332    } else {
333        w.env = env;
334    }
335    w
336}
337
338/// The class environment of an S3 or vctrs class, `Class <- new.env(...)`
339/// with its roxygen block: `@noRd` for a class without a page
340/// (`class_has_no_rd`), else on the class's topic (the impl's `@rdname` when
341/// it names one, after the topic's own block, #1900) and exported when the
342/// class is (`should_export`). It holds S3's `Class$new()` and the trait
343/// namespaces `Class$Trait` of both systems.
344pub(super) fn class_env(
345    parsed_impl: &ParsedImpl,
346    class_has_no_rd: bool,
347    should_export: bool,
348) -> Vec<String> {
349    let class_name = parsed_impl.class_name();
350    let binding = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                class_name))
    })format!("{class_name} <- new.env(parent = emptyenv())");
351    let block = if class_has_no_rd {
352        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @noRd\n{0}", binding))
    })format!("#' @noRd\n{binding}")
353    } else {
354        let topic = super::field_syntax::topic(parsed_impl);
355        let order = if topic == class_name {
356            String::new()
357        } else {
358            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}\n",
                crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS))
    })format!("#' {}\n", crate::roxygen::ORDER_AFTER_TOPIC_BLOCKS)
359        };
360        let export_line = if should_export { "#' @export\n" } else { "" };
361        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}\n{1}{2}{3}", topic,
                order, export_line, binding))
    })format!("#' @rdname {topic}\n{order}{export_line}{binding}")
362    };
363    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [block, String::new()]))vec![block, String::new()]
364}
365
366/// The S3 class as one string: [`generate_s3_class`], rendered.
367#[cfg(test)]
368pub fn generate_s3_r_wrapper(parsed_impl: &ParsedImpl) -> String {
369    generate_s3_class(parsed_impl).render()
370}
371
372/// The head of an S3 or vctrs class without a constructor: `kind` is the
373/// class system in its title, `imports` its roxygen imports. Neither gets a
374/// `new_<class>()`: a package that builds its objects in R may write its own
375/// (#2069).
376///
377/// - A class named as its Rust type has its class block on `NULL`, without
378///   an `@export` of the class name: the class environment ([`class_env`])
379///   exports it when a trait impl writes into it (#2264, #2289).
380/// - A class the package names and builds itself (`class = "..."`) may name
381///   its own constructor like the class (#1918). Its roxygen block only
382///   carries the impl docs ([`super::docs_only_class_block`]), and the writer
383///   drops the block when they say nothing, unless the class environment is
384///   kept for a trait impl and needs the page.
385pub(super) fn no_constructor_head(
386    parsed_impl: &ParsedImpl,
387    w: &mut super::ClassWrapper,
388    lines: &mut Vec<String>,
389    kind: &'static str,
390    imports: Option<&str>,
391) {
392    let class_name = parsed_impl.class_name();
393    let type_ident = &parsed_impl.type_ident;
394    if *type_ident != class_name {
395        if let Some(imports) = imports {
396            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", imports))
    })format!("#' {imports}"));
397            lines.push("NULL".to_string());
398            lines.push(String::new());
399        }
400        lines.extend(super::docs_only_class_block(parsed_impl, kind));
401        w.mark_class_doc_lines(lines, parsed_impl);
402        lines.push(String::new());
403        return;
404    }
405    let mut class_docs = crate::r_class_formatter::ClassDocBuilder::new(
406        &class_name,
407        type_ident,
408        &parsed_impl.doc_tags,
409        kind,
410    )
411    .with_export_control(parsed_impl.internal, parsed_impl.noexport);
412    if let Some(imports) = imports {
413        class_docs = class_docs.with_imports(imports);
414    }
415    let export = super::class_default("#' @export");
416    lines.extend(
417        class_docs
418            .build()
419            .into_iter()
420            .filter(|line| *line != export),
421    );
422    w.class_docs = class_docs.docs();
423    lines.push("NULL".to_string());
424    w.mark_class_doc_lines(lines, parsed_impl);
425    lines.push(String::new());
426}