Skip to main content

miniextendr_macros/miniextendr_impl/
vctrs_class.rs

1//! Vctrs class R wrapper generator.
2//!
3//! Generates an S3 class that **integrates with the tidyverse `vctrs`
4//! package**: emits a `new_<class>` wrapper around `vctrs::new_vctr` /
5//! `new_rcrd` / `new_list_of` (selected via `VctrsKind`), plus the standard
6//! `vec_ptype2` / `vec_cast` self-coercion methods so the type composes
7//! cleanly inside `tibble`, `dplyr`, and `tidyr`. Pick vctrs when your Rust
8//! type is "a vector of X" and you want first-class tibble columns; use
9//! plain S3/S7 for scalar-like objects.
10
11use super::{ParsedImpl, VctrsKind};
12
13/// The roxygen imports of a vctrs class's roxygen block.
14const VCTRS_IMPORTS: &str =
15    "@importFrom vctrs new_vctr new_rcrd new_list_of vec_ptype2 vec_cast vec_ptype_abbr";
16
17/// Generates the R wrapper of a vctrs-compatible S3 class, in the parts the
18/// wrapper writer merges per type ([`super::ClassWrapper`], #1776).
19///
20/// This is used when an `impl` block is annotated with `#[miniextendr(vctrs)]`.
21/// Unlike the `#[derive(Vctrs)]` macro (which generates standalone S3 methods from
22/// struct attributes), this generator produces class wrappers from `impl` block methods.
23///
24/// Produces the following R code:
25/// - Constructor: `new_<class>(...)` that calls the Rust `new` constructor, then wraps
26///   the result with `vctrs::new_vctr()`, `vctrs::new_rcrd()`, or `vctrs::new_list_of()`
27///   depending on the `VctrsKind`
28/// - `vec_ptype_abbr.<class>`: compact abbreviation for printing (if `abbr` is specified)
29/// - `vec_ptype2.<class>.<class>`: self-coercion prototype (returns empty typed vector)
30/// - `vec_cast.<class>.<class>`: identity cast (returns `x` unchanged)
31/// - Static methods: regular functions named `<class>_<method>(...)`, or
32///   `<protocol>.<class>` S3 methods with `#[miniextendr(vctrs(<protocol>))]`
33///   (instance methods are refused, MXL120)
34///
35/// Roxygen2 documentation and `@importFrom vctrs ...` tags are generated automatically.
36/// A class-level `@noRd` (or a plain `noexport` without `internal`) suppresses the Rd
37/// contribution of every block — self-coercion methods and static method docs
38/// all collapse to `@noRd` (#1180), like the other five
39/// class-system generators. S3 `S3method()` dispatch registration (`@method` +
40/// `@export`) is kept unconditionally: vctrs generics dispatch from the vctrs
41/// namespace, so an unregistered method would leave even a gated class non-functional
42/// (and roxygen2 warns on any recognized-but-unregistered S3 method).
43///
44/// The constructor, `vec_ptype_abbr` and the self-coercion methods are the
45/// head; the static methods and protocol methods are the members. The class
46/// environment (`Class <- new.env(...)`, [`super::s3_class::class_env`]) is
47/// the env part: only a trait impl's static methods and consts land in it
48/// (`Class$Trait`), and the wrapper writer keeps it only for one (#2289).
49pub fn generate_vctrs_class(parsed_impl: &ParsedImpl) -> super::ClassWrapper {
50    use crate::r_class_formatter::{
51        ClassDocBuilder, MethodDocBuilder, ParsedImplExt, should_export_from_tags,
52    };
53
54    let class_name = parsed_impl.class_name();
55    let type_ident = &parsed_impl.type_ident;
56    let class_doc_tags = &parsed_impl.doc_tags;
57    let vctrs_attrs = &parsed_impl.vctrs_attrs;
58    let should_export =
59        should_export_from_tags(class_doc_tags, parsed_impl.noexport || parsed_impl.internal);
60    // Check if the class has @noRd — if so, skip method documentation (#1180). A
61    // plain `noexport` (without `internal`) is folded into the gate too: it must
62    // suppress Rd contribution entirely (audit A10 semantics), matching the other
63    // five class generators. `internal` keeps full docs (the constructor's
64    // ClassDocBuilder adds `@keywords internal`); `should_export` (above) gates
65    // the export()-shaped surface (static helpers) and is always false when
66    // this gate is true.
67    //
68    // S3-method-shaped emissions (`vec_ptype_abbr`/`vec_ptype2`/`vec_cast`,
69    // protocol overrides) keep their `@method` + `@export`
70    // pair unconditionally: with `@method`, `@export` produces an `S3method()`
71    // dispatch registration in NAMESPACE — not an `export()` — and both
72    // roxygen2 (`warn_missing_s3_exports`) and vctrs itself (generics dispatch
73    // from the vctrs namespace) require registered methods. A gated class stays
74    // hidden (no Rd page, no `export()` entries) but remains a functioning vctr.
75    let class_has_no_rd = crate::roxygen::has_roxygen_tag(class_doc_tags, "noRd")
76        || (parsed_impl.noexport && !parsed_impl.internal);
77
78    // Constructor name follows vctrs convention: new_<class>
79    let ctor_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("new_{0}",
                class_name.to_lowercase()))
    })format!("new_{}", class_name.to_lowercase());
80
81    let mut w = super::ClassWrapper::default();
82    let mut lines = Vec::new();
83    // The class block is the constructor's; a block without one still
84    // documents the class with its impl docs.
85    crate::roxygen::push_roxygen_tags(&mut w.class_docs, class_doc_tags);
86
87    // Constructor with combined class and constructor documentation
88    if let Some(ctx) = parsed_impl.constructor_context() {
89        lines.push(ctx.source_comment(type_ident));
90        let mut ctor_doc_tags = Vec::new();
91        ctor_doc_tags.extend(class_doc_tags.iter().cloned());
92        ctor_doc_tags.extend(ctx.method.doc_tags.iter().cloned());
93        let ctor_choice_docs = ctx.choice_param_docs();
94
95        let class_docs = ClassDocBuilder::new(&class_name, type_ident, &ctor_doc_tags, "vctrs S3")
96            .with_ctor_params(&ctx.params, &ctor_choice_docs)
97            .with_imports(VCTRS_IMPORTS)
98            .with_export_control(parsed_impl.internal, parsed_impl.noexport);
99        lines.extend(class_docs.build());
100        w.class_docs = class_docs.docs();
101        w.mark_class_doc_lines(&mut lines, parsed_impl);
102
103        // Generate constructor body based on vctrs kind
104        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                ctor_name, ctx.params))
    })format!("{} <- function({}) {{", ctor_name, ctx.params));
105        for check in ctx.precondition_checks() {
106            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", check))
    })format!("  {}", check));
107        }
108        // Inject match.arg validation for match_arg/choices params
109        for line in ctx.match_arg_prelude() {
110            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", line))
    })format!("  {}", line));
111        }
112        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  .val <- {0}", ctx.static_call()))
    })format!("  .val <- {}", ctx.static_call()));
113        lines.extend(crate::method_return_builder::condition_check_lines("  "));
114        lines.push("  data <- .val".to_string());
115
116        match vctrs_attrs.kind {
117            VctrsKind::Vctr => {
118                // Build new_vctr call with optional inherit_base_type
119                let inherit_arg = match vctrs_attrs.inherit_base_type {
120                    Some(true) => ", inherit_base_type = TRUE",
121                    Some(false) => ", inherit_base_type = FALSE",
122                    None => "",
123                };
124                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  vctrs::new_vctr(data, class = \"{0}\"{1})",
                class_name, inherit_arg))
    })format!(
125                    "  vctrs::new_vctr(data, class = \"{}\"{})",
126                    class_name, inherit_arg
127                ));
128            }
129            VctrsKind::Rcrd => {
130                // Record type - data should be a list
131                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  vctrs::new_rcrd(data, class = \"{0}\")",
                class_name))
    })format!(
132                    "  vctrs::new_rcrd(data, class = \"{}\")",
133                    class_name
134                ));
135            }
136            VctrsKind::ListOf => {
137                // list_of - needs ptype
138                let ptype_arg = vctrs_attrs
139                    .ptype
140                    .as_ref()
141                    .map(|p| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", ptype = {0}", p))
    })format!(", ptype = {}", p))
142                    .unwrap_or_default();
143                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  vctrs::new_list_of(data, class = \"{0}\"{1})",
                class_name, ptype_arg))
    })format!(
144                    "  vctrs::new_list_of(data, class = \"{}\"{})",
145                    class_name, ptype_arg
146                ));
147            }
148        }
149        lines.push("}".to_string());
150        lines.push(String::new());
151    } else {
152        super::s3_class::no_constructor_head(
153            parsed_impl,
154            &mut w,
155            &mut lines,
156            "vctrs S3",
157            Some(VCTRS_IMPORTS),
158        );
159    }
160
161    // vec_ptype_abbr for compact printing (if abbr is specified)
162    if let Some(abbr) = &vctrs_attrs.abbr {
163        if class_has_no_rd {
164            // Gated class (@noRd / plain noexport): no Rd contribution — keep
165            // only the @method + @export S3method() registration pair.
166            lines.push("#' @noRd".to_string());
167        } else {
168            lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", class_name))
    })format!("#' @rdname {}", class_name)));
169        }
170        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method vec_ptype_abbr {0}",
                class_name))
    })format!("#' @method vec_ptype_abbr {}", class_name));
171        lines.push("#' @export".to_string());
172        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vec_ptype_abbr.{0} <- function(x, ...) \"{1}\"",
                class_name, abbr))
    })format!(
173            "vec_ptype_abbr.{} <- function(x, ...) \"{}\"",
174            class_name, abbr
175        ));
176        lines.push(String::new());
177    }
178
179    // Self-coercion methods (required for vctrs to work properly)
180    // vec_ptype2.<class>.<class> - returns prototype for combining same types
181    if class_has_no_rd {
182        lines.push("#' @noRd".to_string());
183        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method vec_ptype2 {0}.{1}",
                class_name, class_name))
    })format!(
184            "#' @method vec_ptype2 {}.{}",
185            class_name, class_name
186        ));
187    } else {
188        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", class_name))
    })format!("#' @rdname {}", class_name)));
189        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method vec_ptype2 {0}.{1}",
                class_name, class_name))
    })format!(
190            "#' @method vec_ptype2 {}.{}",
191            class_name, class_name
192        ));
193        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param x A {0} vector.",
                class_name))
    })format!(
194            "#' @param x A {} vector.",
195            class_name
196        )));
197        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param y A {0} vector.",
                class_name))
    })format!(
198            "#' @param y A {} vector.",
199            class_name
200        )));
201        lines.push(super::member_default(
202            "#' @param ... Additional arguments (unused).".to_string(),
203        ));
204    }
205    lines.push("#' @export".to_string());
206    match vctrs_attrs.kind {
207        VctrsKind::Vctr => {
208            let base_type = vctrs_attrs
209                .base
210                .as_ref()
211                .map(|b| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}()", b))
    })format!("{}()", b))
212                .unwrap_or_else(|| "double()".to_string());
213            let inherit_arg = match vctrs_attrs.inherit_base_type {
214                Some(true) => ", inherit_base_type = TRUE",
215                Some(false) => ", inherit_base_type = FALSE",
216                None => "",
217            };
218            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vec_ptype2.{0}.{0} <- function(x, y, ...) vctrs::new_vctr({1}, class = \"{0}\"{2})",
                class_name, base_type, inherit_arg))
    })format!(
219                "vec_ptype2.{c}.{c} <- function(x, y, ...) vctrs::new_vctr({base}, class = \"{c}\"{inherit})",
220                c = class_name,
221                base = base_type,
222                inherit = inherit_arg
223            ));
224        }
225        VctrsKind::Rcrd => {
226            // For records, return empty record with same field structure
227            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vec_ptype2.{0}.{0} <- function(x, y, ...) x[0]",
                class_name))
    })format!(
228                "vec_ptype2.{c}.{c} <- function(x, y, ...) x[0]",
229                c = class_name
230            ));
231        }
232        VctrsKind::ListOf => {
233            let ptype_arg = vctrs_attrs
234                .ptype
235                .as_ref()
236                .map(|p| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", ptype = {0}", p))
    })format!(", ptype = {}", p))
237                .unwrap_or_default();
238            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vec_ptype2.{0}.{0} <- function(x, y, ...) vctrs::new_list_of(list(), class = \"{0}\"{1})",
                class_name, ptype_arg))
    })format!(
239                "vec_ptype2.{c}.{c} <- function(x, y, ...) vctrs::new_list_of(list(), class = \"{c}\"{ptype})",
240                c = class_name,
241                ptype = ptype_arg
242            ));
243        }
244    }
245    lines.push(String::new());
246
247    // vec_cast.<class>.<class> - identity cast (no-op for same type)
248    if class_has_no_rd {
249        lines.push("#' @noRd".to_string());
250        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method vec_cast {0}.{1}",
                class_name, class_name))
    })format!("#' @method vec_cast {}.{}", class_name, class_name));
251    } else {
252        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", class_name))
    })format!("#' @rdname {}", class_name)));
253        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method vec_cast {0}.{1}",
                class_name, class_name))
    })format!("#' @method vec_cast {}.{}", class_name, class_name));
254        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param x A {0} vector to cast.",
                class_name))
    })format!(
255            "#' @param x A {} vector to cast.",
256            class_name
257        )));
258        lines.push(super::member_default(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param to A {0} prototype.",
                class_name))
    })format!(
259            "#' @param to A {} prototype.",
260            class_name
261        )));
262        lines.push(super::member_default(
263            "#' @param ... Additional arguments (unused).".to_string(),
264        ));
265    }
266    lines.push("#' @export".to_string());
267    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vec_cast.{0}.{0} <- function(x, to, ...) x",
                class_name))
    })format!(
268        "vec_cast.{c}.{c} <- function(x, to, ...) x",
269        c = class_name
270    ));
271    lines.push(String::new());
272    w.head = std::mem::take(&mut lines);
273
274    // No instance methods: `ParsedImpl::parse` refuses every receiver on a
275    // vctrs impl (MXL120), since the R object is the vector, not a pointer.
276
277    // Static methods as regular functions, or as vctrs protocol S3 methods when
278    // `#[miniextendr(vctrs(protocol))]` is set (e.g. `vctrs(format)` → `format.<Class>`).
279    for ctx in parsed_impl.static_method_contexts() {
280        lines.push(ctx.source_comment(type_ident));
281
282        let is_protocol = ctx.method.method_attrs.vctrs_protocol.is_some();
283        let fn_name = if let Some(ref proto) = ctx.method.method_attrs.vctrs_protocol {
284            // vctrs protocol override: emit as `<protocol>.<Class>` S3 method
285            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}", proto, class_name))
    })format!("{}.{}", proto, class_name)
286        } else {
287            let method_name = ctx.method.r_method_name();
288            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}",
                class_name.to_lowercase(), method_name))
    })format!("{}_{}", class_name.to_lowercase(), method_name)
289        };
290        let r_name = fn_name.clone();
291
292        let mx_doc = ctx.choice_param_docs();
293        let method_name = ctx.method.r_method_name();
294        if is_protocol {
295            let proto = ctx.method.method_attrs.vctrs_protocol.as_ref().unwrap();
296            let method_doc =
297                MethodDocBuilder::new(&class_name, &method_name, type_ident, &ctx.method.doc_tags)
298                    .with_source_method(&ctx.method.ident)
299                    .with_r_params(&ctx.params)
300                    .with_choice_param_docs(&mx_doc)
301                    .with_r_name(r_name.clone())
302                    .with_class_no_rd(class_has_no_rd);
303            lines.extend(method_doc.build());
304            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @method {0} {1}", proto,
                class_name))
    })format!("#' @method {} {}", proto, class_name));
305            lines.push("#' @export".to_string());
306        } else {
307            let method_doc =
308                MethodDocBuilder::new(&class_name, &method_name, type_ident, &ctx.method.doc_tags)
309                    .with_source_method(&ctx.method.ident)
310                    .with_r_params(&ctx.params)
311                    .with_choice_param_docs(&mx_doc)
312                    .with_r_name(r_name.clone())
313                    .with_class_no_rd(class_has_no_rd);
314            lines.extend(method_doc.build());
315            // Export the helper so users can call it, as the S3 / S4 / S7
316            // generators do for their static methods; without it the
317            // function was documented on the class page but unreachable.
318            if should_export {
319                lines.push("#' @export".to_string());
320            }
321        }
322
323        // Protocol methods accept `...` so `format(x, nsmall = 2)` and similar
324        // S3 dispatch calls with extra arguments don't error with "unused argument".
325        // The `...` is silently dropped; the underlying Rust function has a fixed signature.
326        let formals = if is_protocol && !ctx.method.has_dots {
327            if ctx.params.is_empty() {
328                "...".to_string()
329            } else {
330                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ...", ctx.params))
    })format!("{}, ...", ctx.params)
331            }
332        } else {
333            ctx.params.to_string()
334        };
335        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- function({1}) {{",
                crate::naming::r_def_name(&fn_name), formals))
    })format!(
336            "{} <- function({}) {{",
337            crate::naming::r_def_name(&fn_name),
338            formals
339        ));
340
341        ctx.emit_method_prelude(&mut lines, "  ", &fn_name, &formals);
342
343        let strategy = crate::ReturnStrategy::for_method(ctx.method);
344        let return_builder = crate::MethodReturnBuilder::new(ctx.static_call())
345            .with_strategy(strategy)
346            .with_invisible(ctx.method.is_invisible())
347            .with_class_name(class_name.clone())
348            .with_return_class_from_method(ctx.method, &type_ident.to_string());
349        lines.extend(return_builder.build_s3_body());
350
351        lines.push("}".to_string());
352        lines.push(String::new());
353    }
354
355    w.members = lines;
356    w.env = super::s3_class::class_env(parsed_impl, class_has_no_rd, should_export);
357    w
358}
359
360/// The vctrs class as one string: [`generate_vctrs_class`], rendered.
361#[cfg(test)]
362pub fn generate_vctrs_r_wrapper(parsed_impl: &ParsedImpl) -> String {
363    generate_vctrs_class(parsed_impl).render()
364}