Skip to main content

miniextendr_macros/miniextendr_impl/
env_class.rs

1//! Env-class R wrapper generator.
2//!
3//! Generates an R environment (`new.env(parent = emptyenv())`) that serves as
4//! the class namespace, with `obj$method()` dispatched through an `$.ClassName`
5//! S3 method. This is the **fastest** of the six class systems and has **no R
6//! package dependencies**, but provides no formal class machinery: no
7//! inheritance, no multi-dispatch, no slot validation. Pick env for simple
8//! ExternalPtr-backed APIs; reach for R6/S3/S4/S7 when you need dispatch or
9//! formal class semantics.
10
11use super::ParsedImpl;
12
13/// Generates the R wrapper of an environment-based class, in the parts the
14/// wrapper writer merges per type ([`super::ClassWrapper`], #1776).
15///
16/// Produces an R environment object (`new.env(parent = emptyenv())`) that serves as a
17/// class namespace, with methods attached as `ClassName$method_name`. This pattern
18/// supports both inherent methods and trait namespace dispatch via `$`/`[[`.
19///
20/// The generated code includes:
21/// - Class environment: `ClassName <- new.env(parent = emptyenv())`
22/// - Constructor: `ClassName$new(...)` that calls the Rust `new` function, sets
23///   `class(self) <- "ClassName"`, and returns the ExternalPtr as `self`
24/// - Instance methods: `ClassName$method(...)` whose bodies read a free `self`,
25///   which `$` dispatch binds in a fresh environment over the method's own
26/// - Static methods: `ClassName$method(...)` that call Rust directly
27/// - `$.ClassName` S3 method: dispatches `obj$method(...)` by looking up the method
28///   in the class environment, binding `.mx_self` for instance methods, and supporting
29///   trait namespace environments (nested envs with `.__mx_instance__` attributes),
30///   through the package's shared `.miniextendr_env_method` helper
31/// - `[[.ClassName`: the same lookup, with `exact` (ignored) and a `...` that
32///   refuses every argument (#2174)
33/// - With `env(r_data_accessors)`: a field branch at the top of `$.ClassName`
34///   (a `#[r_data]` field wins over a method of the same name),
35///   `.DollarNames.ClassName` (the fields, then the methods; #1885), and,
36///   unless the getters-only `r_data_accessors = "get"`, `$<-.ClassName` with
37///   its `[[<-.ClassName` alias (`field_syntax.rs`, #1848), which refuses
38///   every field under `r_data_accessors = "read_only"` (#2268)
39///
40/// Roxygen2 documentation is generated for the class, each method, and the
41/// dispatch methods, with appropriate `@export`/`@keywords internal`/`@noRd` tags.
42///
43/// The class environment and constructor are the head; the instance and
44/// static methods are the members; the dispatch methods are the tail.
45pub fn generate_env_class(parsed_impl: &ParsedImpl) -> super::ClassWrapper {
46    use crate::r_class_formatter::{
47        ClassDocBuilder, MethodDocBuilder, ParsedImplExt, should_export_from_tags,
48    };
49
50    let class_name = parsed_impl.class_name();
51    let type_ident = &parsed_impl.type_ident;
52    // Check if class has @noRd - if so, skip method documentation. A plain
53    // `noexport` (without `internal`) is folded in too — it must suppress Rd
54    // contribution entirely, matching `ClassDocBuilder::build`'s `suppress_rd` gate.
55    let class_has_no_rd = crate::roxygen::has_roxygen_tag(&parsed_impl.doc_tags, "noRd")
56        || (parsed_impl.noexport && !parsed_impl.internal);
57
58    let mut w = super::ClassWrapper::default();
59    let mut lines = Vec::new();
60
61    // Class environment documentation and definition
62    let class_docs = ClassDocBuilder::new(&class_name, type_ident, &parsed_impl.doc_tags, "")
63        .with_export_control(parsed_impl.internal, parsed_impl.noexport);
64    lines.extend(class_docs.build());
65    w.class_docs = class_docs.docs();
66    w.mark_class_doc_lines(&mut lines, parsed_impl);
67    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} <- new.env(parent = emptyenv())",
                class_name))
    })format!("{} <- new.env(parent = emptyenv())", class_name));
68    lines.push(String::new());
69
70    // Constructor
71    if let Some(ctx) = parsed_impl.constructor_context() {
72        w.member_names.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}$new`", class_name))
    })format!("`{class_name}$new`"));
73        lines.push(ctx.source_comment(type_ident));
74        // Skip method documentation if class has @noRd
75        if !class_has_no_rd {
76            let choice_docs = ctx.choice_param_docs();
77            let method_doc =
78                MethodDocBuilder::new(&class_name, "new", type_ident, &ctx.method.doc_tags)
79                    .with_source_method(&ctx.method.ident)
80                    .with_name_prefix("$")
81                    .with_params_as_details()
82                    .with_r_params(&ctx.params)
83                    .with_choice_param_docs(&choice_docs);
84            lines.extend(method_doc.build());
85        }
86        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}$new <- function({1}) {{",
                class_name, ctx.params))
    })format!("{}$new <- function({}) {{", class_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("  self <- .val".to_string());
97        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  class(self) <- \"{0}\"",
                class_name))
    })format!("  class(self) <- \"{}\"", class_name));
98        lines.push("  self".to_string());
99        lines.push("}".to_string());
100        lines.push(String::new());
101    }
102    w.head = std::mem::take(&mut lines);
103
104    // Instance methods
105    for ctx in parsed_impl.instance_method_contexts() {
106        let method_name = ctx.method.r_method_name();
107        w.member_names.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}${1}`", class_name,
                method_name))
    })format!("`{class_name}${method_name}`"));
108        lines.push(ctx.source_comment(type_ident));
109        // Skip method documentation if class has @noRd
110        if !class_has_no_rd {
111            let choice_docs = ctx.choice_param_docs();
112            let method_doc =
113                MethodDocBuilder::new(&class_name, &method_name, type_ident, &ctx.method.doc_tags)
114                    .with_source_method(&ctx.method.ident)
115                    .with_name_prefix("$")
116                    .with_params_as_details()
117                    .with_r_params(&ctx.params)
118                    .with_choice_param_docs(&choice_docs);
119            lines.extend(method_doc.build());
120        }
121
122        // `$` takes an R symbol: quote operator names (#1475).
123        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1} <- function({2}) {{",
                class_name, crate::naming::r_def_name(&method_name),
                ctx.params))
    })format!(
124            "{}${} <- function({}) {{",
125            class_name,
126            crate::naming::r_def_name(&method_name),
127            ctx.params
128        ));
129
130        let what = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}", class_name, method_name))
    })format!("{}${}", class_name, method_name);
131        ctx.emit_method_prelude(&mut lines, "  ", &what, &ctx.params);
132
133        let call = ctx.instance_call(".mx_self");
134        let strategy = crate::ReturnStrategy::for_method(ctx.method);
135        let return_builder = crate::MethodReturnBuilder::new(call)
136            .with_strategy(strategy)
137            .with_invisible(ctx.method.is_invisible())
138            .with_chain_var(".mx_self".to_string())
139            .with_class_name(class_name.clone())
140            .with_return_class_from_method(ctx.method, &type_ident.to_string());
141        lines.extend(return_builder.build());
142
143        lines.push("}".to_string());
144        lines.push(String::new());
145    }
146
147    // Static methods
148    for ctx in parsed_impl.static_method_contexts() {
149        let method_name = ctx.method.r_method_name();
150        w.member_names.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}${1}`", class_name,
                method_name))
    })format!("`{class_name}${method_name}`"));
151        lines.push(ctx.source_comment(type_ident));
152        // Skip method documentation if class has @noRd
153        if !class_has_no_rd {
154            let choice_docs = ctx.choice_param_docs();
155            // The constructor's arguments are details of `$new`; its alias
156            // doesn't repeat them.
157            let doc_tags = parsed_impl.static_doc_tags(
158                ctx.method,
159                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}()", class_name,
                method_name))
    })format!("{class_name}${method_name}()"),
160                &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}$new()", class_name))
    })format!("{class_name}$new()"),
161                false,
162            );
163            let method_doc =
164                MethodDocBuilder::new(&class_name, &method_name, type_ident, &doc_tags)
165                    .with_source_method(&ctx.method.ident)
166                    .with_name_prefix("$")
167                    .with_params_as_details()
168                    .with_r_params(&ctx.params)
169                    .with_choice_param_docs(&choice_docs);
170            lines.extend(method_doc.build());
171        }
172
173        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1} <- function({2}) {{",
                class_name, crate::naming::r_def_name(&method_name),
                ctx.params))
    })format!(
174            "{}${} <- function({}) {{",
175            class_name,
176            crate::naming::r_def_name(&method_name),
177            ctx.params
178        ));
179
180        let what = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}", class_name, method_name))
    })format!("{}${}", class_name, method_name);
181        ctx.emit_method_prelude(&mut lines, "  ", &what, &ctx.params);
182
183        let strategy = crate::ReturnStrategy::for_method(ctx.method);
184        let return_builder = crate::MethodReturnBuilder::new(ctx.static_call())
185            .with_strategy(strategy)
186            .with_invisible(ctx.method.is_invisible())
187            .with_class_name(class_name.clone())
188            .with_return_class_from_method(ctx.method, &type_ident.to_string());
189        lines.extend(return_builder.build());
190
191        lines.push("}".to_string());
192        lines.push(String::new());
193    }
194    w.members = std::mem::take(&mut lines);
195
196    // $ dispatch - export as S3 methods
197    // Handles both functions (inherent methods) and environments (trait namespaces)
198    let should_export = should_export_from_tags(
199        &parsed_impl.doc_tags,
200        parsed_impl.noexport || parsed_impl.internal,
201    );
202
203    // Generate roxygen tags for dispatch methods.
204    // roxygen2 8.0.0+ enforces that any `generic.class`-named function carry
205    // @export or @exportS3Method (@noRd alone doesn't satisfy the check). We
206    // always emit @export so roxygen2 emits a properly-quoted
207    // `S3method("$", Class)` / `S3method("[[", Class)` (bare @exportS3Method
208    // skips the operator-name quoting and produces invalid NAMESPACE entries).
209    // For internal/noexport classes the @rdname target is dropped so the
210    // helpers don't bleed into the user-visible Rd page.
211    // `env(r_data_accessors)` (#1848): `$` / `[[` read a field before the
212    // method lookup, and `$<-` / `[[<-` write one.
213    let fields = parsed_impl.r_data_accessors.enabled();
214    if fields {
215        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Field syntax for the `#[r_data]` fields of {0} (`env(r_data_accessors)`).",
                type_ident))
    })format!(
216            "# Field syntax for the `#[r_data]` fields of {type_ident} (`env(r_data_accessors)`)."
217        ));
218        lines.push(super::field_syntax::env_load_check(parsed_impl));
219        lines.push(String::new());
220    }
221    if class_has_no_rd {
222        lines.push("#' @noRd".to_string());
223        lines.push("#' @export".to_string());
224    } else if !should_export {
225        lines.push("#' @export".to_string());
226    } else {
227        // The class's topic: the impl's own `@rdname`, else the class page.
228        lines.extend(super::field_syntax::page_lines(
229            parsed_impl,
230            &[
231                ("self", "The object instance."),
232                (
233                    "name",
234                    if fields {
235                        super::field_syntax::env_name_param(parsed_impl)
236                    } else {
237                        "Method name for dispatch."
238                    },
239                ),
240            ],
241        ));
242        lines.push("#' @export".to_string());
243    }
244    // The lookup `$` and `[[` share. `[[` is its own function, not an alias
245    // of `$`, so that each method's frame names its own generic for
246    // `.miniextendr_frame_call`.
247    let mut lookup = Vec::new();
248    if fields {
249        lookup.extend(super::field_syntax::env_field_branch(parsed_impl));
250    }
251    let method_lookup = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".miniextendr_env_method(self, name, {0})",
                class_name))
    })format!(".miniextendr_env_method(self, name, {class_name})");
252    if fields {
253        lookup.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  obj <- {0}", method_lookup))
    })format!("  obj <- {method_lookup}"));
254        lookup.push("  if (is.null(obj)) {".to_string());
255        lookup.extend(super::field_syntax::env_unknown_name_check(parsed_impl));
256        lookup.push("  }".to_string());
257        lookup.push("  obj".to_string());
258    } else {
259        lookup.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("  {0}", method_lookup))
    })format!("  {method_lookup}"));
260    }
261    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`$.{0}` <- function(self, name) {{",
                class_name))
    })format!("`$.{}` <- function(self, name) {{", class_name));
262    lines.extend(lookup.iter().cloned());
263    lines.push("}".to_string());
264    // `[[` takes `exact`, as a list's does, and ignores it: names match
265    // exactly. Nothing reads its `...`, so every argument there is refused
266    // (#2174).
267    if class_has_no_rd {
268        lines.push("#' @noRd".to_string());
269        lines.push("#' @export".to_string());
270    } else if !should_export {
271        lines.push("#' @export".to_string());
272    } else {
273        lines.extend(super::field_syntax::page_lines(
274            parsed_impl,
275            &[
276                ("...", "Refused: `[[` takes one name."),
277                ("exact", "Ignored: names match exactly."),
278            ],
279        ));
280        lines.push("#' @export".to_string());
281    }
282    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`[[.{1}` <- function({0}) {{",
                super::field_syntax::ENV_SUBSET_FORMALS, class_name))
    })format!(
283        "`[[.{class_name}` <- function({}) {{",
284        super::field_syntax::ENV_SUBSET_FORMALS
285    ));
286    lines.push(super::field_syntax::env_subset_dots_check(parsed_impl));
287    lines.extend(lookup);
288    lines.push("}".to_string());
289    if fields {
290        lines.extend(super::field_syntax::env_dollar_names(
291            parsed_impl,
292            !class_has_no_rd && should_export,
293        ));
294    }
295    if fields && parsed_impl.r_data_accessors.writers() {
296        lines.extend(super::field_syntax::env_replacement_methods(
297            parsed_impl,
298            !class_has_no_rd && should_export,
299        ));
300    }
301
302    w.tail = lines;
303    w
304}
305
306/// The env class as one string: [`generate_env_class`], rendered.
307#[cfg(test)]
308pub fn generate_env_r_wrapper(parsed_impl: &ParsedImpl) -> String {
309    generate_env_class(parsed_impl).render()
310}