Skip to main content

miniextendr_macros/miniextendr_impl_trait/
method_context.rs

1//! Shared per-method context for trait-impl R wrapper generation.
2//!
3//! Parallels `r_class_formatter::MethodContext` (used by the 6 inherent-impl
4//! class generators) so the 5 trait generators (env/s3/s4/s7/r6) build
5//! `.Call()` invocations and method preludes the same way instead of each
6//! hand-rolling its own version. See
7//! `audit/2026-07-03-dogfooding-macros-codegen.md` finding #1: the trait path
8//! previously shared nothing above `DotCallBuilder`, which caused a
9//! substring-corruption bug in the receiver-ptr extraction (S4/S7/R6) and a
10//! silent 3-of-6-step prelude omission (missing `precondition_checks` /
11//! `match_arg_prelude`) relative to inherent methods.
12
13use super::{TraitMethod, trait_method_body_lines};
14use crate::miniextendr_impl::ClassSystem;
15
16/// How the trait wrappers of `class_system` name the class of `type_ident`:
17/// its R name, which a `class = "..."` rename on the type's impl block sets,
18/// resolved when the wrappers are written (#2266,
19/// [`class_ref_for`](crate::r_class_formatter::class_ref_for)). Used for every
20/// R object the trait impl attaches to or wraps in (S3 method suffixes and
21/// registrations, the `Class$Trait` namespace, the S4 method signature, the S7
22/// class object, a `Self` return). Rust-side names (C symbols, the S7 and S4
23/// flat member names) and the `@rdname` page keep the Rust identifier.
24pub(super) fn class_ref(class_system: ClassSystem, type_ident: &syn::Ident) -> String {
25    crate::r_class_formatter::class_ref_for(class_system, &type_ident.to_string())
26}
27
28/// The trait namespace environment, `Class$Trait`, of Env, S3, R6 and vctrs
29/// classes; its members are [`trait_namespace_target`]s.
30pub(super) fn trait_namespace_env(
31    class_system: ClassSystem,
32    type_ident: &syn::Ident,
33    trait_name: &syn::Ident,
34) -> String {
35    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}",
                class_ref(class_system, type_ident), trait_name))
    })format!("{}${trait_name}", class_ref(class_system, type_ident))
36}
37
38/// R-visible assignment target for a trait member (method or const) placed in
39/// the per-class trait namespace — the single owner of the namespace-shape
40/// policy the 5 generators previously hand-rolled independently (audit
41/// `2026-07-03-dogfooding-macros-codegen.md` finding #1; #1141). `member` is
42/// the R-facing method/const name.
43///
44/// Policy:
45/// - **Env / S3 / R6 / Vctrs**: `Type$Trait$member` — class-scoped, so it is
46///   collision-free by construction. This is what fixes #1115: two R6 impls of
47///   one trait on *different* types now emit `TypeA$Trait$m` / `TypeB$Trait$m`
48///   rather than a shared, unqualified `r6_trait_Trait_m` that aborted
49///   wrapper-gen via the duplicate-definition guard. `Type` is the class's R
50///   name ([`trait_namespace_env`]).
51/// - **S4**: flat `Type_Trait_member` standalone name. S4 objects intercept
52///   `$<-`, so `Type$Trait$member` cannot be assigned onto them; the class
53///   component in the flat name keeps it collision-free.
54/// - **S7**: `env_var$member`, where `env_var` = [`trait_namespace_env_var`]
55///   (`.Type__Trait`) is a local env attached to `Type` via `attr()` at the end
56///   of the generator. S7 objects also intercept `$<-`, and `$` too, so users
57///   reach the member as [`s7_trait_member_access`]'s
58///   `attr(Type, "Trait")$member`.
59pub(super) fn trait_namespace_target(
60    class_system: ClassSystem,
61    type_ident: &syn::Ident,
62    trait_name: &syn::Ident,
63    member: &str,
64) -> String {
65    match class_system {
66        ClassSystem::Env | ClassSystem::S3 | ClassSystem::R6 | ClassSystem::Vctrs => {
67            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}",
                trait_namespace_env(class_system, type_ident, trait_name),
                member))
    })format!(
68                "{}${member}",
69                trait_namespace_env(class_system, type_ident, trait_name)
70            )
71        }
72        ClassSystem::S4 => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}_{1}_{2}", type_ident,
                trait_name, member))
    })format!("{type_ident}_{trait_name}_{member}"),
73        ClassSystem::S7 => {
74            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}${1}",
                trait_namespace_env_var(type_ident, trait_name), member))
    })format!(
75                "{}${member}",
76                trait_namespace_env_var(type_ident, trait_name)
77            )
78        }
79    }
80}
81
82/// [`trait_namespace_target`] in R code position (the left of `<-`, the
83/// argument of `attr()`). A non-syntactic member (an operator `r_name`, #1475)
84/// is backtick-quoted: `Type$Trait$`[[``, or `` `Type_Trait_[[` `` for S4.
85/// Roxygen `@name` keeps the bare [`trait_namespace_target`] spelling.
86pub(super) fn trait_namespace_symbol(
87    class_system: ClassSystem,
88    type_ident: &syn::Ident,
89    trait_name: &syn::Ident,
90    member: &str,
91) -> String {
92    match class_system {
93        ClassSystem::S4 => crate::naming::r_def_name(&trait_namespace_target(
94            class_system,
95            type_ident,
96            trait_name,
97            member,
98        )),
99        _ => trait_namespace_target(
100            class_system,
101            type_ident,
102            trait_name,
103            &crate::naming::r_def_name(member),
104        ),
105    }
106}
107
108/// The local environment variable S7 trait wrappers assign members into before
109/// attaching it to the class object via `attr()`. One owner so
110/// [`trait_namespace_target`]'s S7 arm and the generator's `new.env` / `attr()`
111/// lines can't drift apart.
112pub(super) fn trait_namespace_env_var(type_ident: &syn::Ident, trait_name: &syn::Ident) -> String {
113    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".{0}__{1}", type_ident,
                trait_name))
    })format!(".{type_ident}__{trait_name}")
114}
115
116/// How R code reaches an S7 trait static or const: `attr(Type, "Trait")$member`,
117/// also the topic alias of its documentation block. The trait namespace is an
118/// attribute of the class object, and `Type$Trait$member` does not reach it:
119/// an S7 class object is a function, and S7's `$` method stops on any S7
120/// object that is not a list or an environment ("Can't get S7 properties with
121/// `$`").
122pub(super) fn s7_trait_member_access(
123    type_ident: &syn::Ident,
124    trait_name: &syn::Ident,
125    member: &str,
126) -> String {
127    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("attr({0}, \"{1}\")${2}",
                class_ref(ClassSystem::S7, type_ident), trait_name, member))
    })format!(
128        "attr({}, \"{trait_name}\")${member}",
129        class_ref(ClassSystem::S7, type_ident)
130    )
131}
132
133/// Pre-computed context for a trait method, mirroring `MethodContext`
134/// (`r_class_formatter.rs`) for inherent-impl methods. Holds the C wrapper
135/// name, R formals (with defaults), and `.Call()` argument string so all 5
136/// trait generators build calls identically.
137pub(super) struct TraitMethodContext<'a> {
138    /// Reference to the parsed trait method metadata.
139    pub(super) method: &'a TraitMethod,
140    /// The implementing type ident (e.g. `Foo`) — used to build the per-class
141    /// trait-namespace assignment target and the Self-return wrapper class.
142    pub(super) type_ident: &'a syn::Ident,
143    /// The trait ident (e.g. `Bar`) — used to build the per-class trait
144    /// namespace assignment target.
145    pub(super) trait_name: &'a syn::Ident,
146    /// The C wrapper identifier string (e.g., `"C_Foo__Bar__value"`), used in `.Call()`.
147    pub(super) c_ident: String,
148    /// R formals string with defaults, used in `function(...)` signatures.
149    pub(super) params: String,
150    /// R call arguments string (without defaults), used inside `.Call()`
151    /// expressions. `Missing<T>` parameters are forwarded as
152    /// `if (missing(p)) quote(expr=) else p` (a single-choice one also
153    /// forwards the sentinel for a value `identical()` to its formal, #2152)
154    /// — see `r_wrapper_builder::RArgumentBuilder::build_call_args_vec`. Before this
155    /// context existed, trait methods built call args via
156    /// `collect_param_idents` instead, which skipped that forwarding entirely.
157    pub(super) args: String,
158    /// The impl block's `preconditions` / `no_preconditions`
159    /// (`ImplAttrs::preconditions`; for an empty-body impl, its decision with
160    /// the crate default and the feature folded in), below the method's own
161    /// and each parameter's.
162    pub(super) impl_preconditions: Option<bool>,
163    /// The call the method's conditions report, as on
164    /// `MethodContext::call_attribution`: the method's own `sys.call()` by
165    /// default, `CallAttribution::Generic` for the S3 generator (#1851).
166    pub(super) call_attribution: crate::r_wrapper_builder::CallAttribution,
167}
168
169impl<'a> TraitMethodContext<'a> {
170    /// Build a context for `method`, which implements `trait_name` for `type_ident`.
171    pub(super) fn new(
172        method: &'a TraitMethod,
173        type_ident: &'a syn::Ident,
174        trait_name: &'a syn::Ident,
175    ) -> Self {
176        let c_ident = method.c_wrapper_ident_string(type_ident, trait_name);
177        // The choice formals (the choice vector, `NULL` for `Option<T>`, none
178        // under `no_default(p)`), as on inherent methods; see
179        // `effective_r_defaults`.
180        let effective_defaults = crate::r_class_formatter::effective_r_defaults(
181            &method.param_defaults,
182            &method.per_param,
183            &c_ident,
184        );
185        // Trait methods declare no formals (#1842): each is the parameter's
186        // Rust name without leading underscores.
187        let formals = crate::r_wrapper_builder::Formals::default();
188        let params = crate::r_wrapper_builder::build_r_formals_from_sig(
189            &method.sig,
190            &formals,
191            &effective_defaults,
192        );
193        let args = crate::r_wrapper_builder::build_r_call_args_from_sig(
194            &method.sig,
195            &formals,
196            crate::miniextendr_fn::absent_formals_by_r_name(&method.per_param),
197        );
198        Self {
199            method,
200            type_ident,
201            trait_name,
202            c_ident,
203            params,
204            args,
205            impl_preconditions: None,
206            call_attribution: crate::r_wrapper_builder::CallAttribution::Wrapper,
207        }
208    }
209
210    /// Set the `preconditions` decision inherited from the impl block; the
211    /// twin of `MethodContext::with_impl_preconditions`.
212    pub(super) fn with_impl_preconditions(mut self, impl_preconditions: Option<bool>) -> Self {
213        self.impl_preconditions = impl_preconditions;
214        self
215    }
216
217    /// Set the call the method's conditions report; the twin of
218    /// `MethodContext::with_call_attribution`.
219    pub(super) fn with_call_attribution(
220        mut self,
221        call_attribution: crate::r_wrapper_builder::CallAttribution,
222    ) -> Self {
223        self.call_attribution = call_attribution;
224        self
225    }
226
227    /// The R-visible assignment target for this method within `class_system`'s
228    /// per-class trait namespace — a thin wrapper over [`trait_namespace_target`]
229    /// using this method's R-facing name. See that function for the policy.
230    pub(super) fn namespace_target(&self, class_system: ClassSystem) -> String {
231        trait_namespace_target(
232            class_system,
233            self.type_ident,
234            self.trait_name,
235            &self.method.r_method_name(),
236        )
237    }
238
239    /// [`Self::namespace_target`] in R code position, via
240    /// [`trait_namespace_symbol`].
241    pub(super) fn namespace_symbol(&self, class_system: ClassSystem) -> String {
242        trait_namespace_symbol(
243            class_system,
244            self.type_ident,
245            self.trait_name,
246            &self.method.r_method_name(),
247        )
248    }
249
250    /// Whether this method re-wraps its return into a classed object — i.e. it
251    /// returns `Self` / `Result<Self, E>` / `Option<Self>`. Mirrors the
252    /// `ReturnStrategy::ReturnSelf` arm of `ReturnStrategy::for_method` on the
253    /// inherent-impl path.
254    pub(super) fn returns_self(&self) -> bool {
255        self.method.returns_self()
256            || self.method.returns_result_self()
257            || self.method.returns_option_self()
258    }
259
260    /// Emit the R body lines for a trait method (2-space indent): capture
261    /// `.Call()` into `.val`, run the tagged-condition guard, then return
262    /// `.val` — or, for `-> Self` factory methods, re-wrap `.val` into a
263    /// classed object via the shared [`crate::MethodReturnBuilder`], exactly
264    /// as the inherent-impl generators do (audit finding #4 / #1141). The
265    /// wrapper class is the implementing type; the wrapping idiom is selected
266    /// per class system (`class(.val) <-` / `structure()` / `methods::new()` /
267    /// `Class(.ptr=)` / `Class$new(.ptr=)`).
268    pub(super) fn method_body_lines(&self, call: &str, class_system: ClassSystem) -> Vec<String> {
269        let raise_default = self.call_attribution.raise_default();
270        if let Some(wrap) = &self.method.return_wrap {
271            return crate::MethodReturnBuilder::new(call.to_owned())
272                .with_raise_default(raise_default)
273                .with_class_name(class_ref(wrap.system(), self.type_ident))
274                .with_explicit_wrap(wrap.clone())
275                .build();
276        }
277        if !self.returns_self() {
278            return trait_method_body_lines(call, "  ", raise_default);
279        }
280        let builder = crate::MethodReturnBuilder::new(call.to_string())
281            .with_raise_default(raise_default)
282            .with_strategy(crate::ReturnStrategy::ReturnSelf)
283            .with_class_name(class_ref(class_system, self.type_ident))
284            .with_nullable(self.method.returns_option_self())
285            .with_indent(2);
286        match class_system {
287            ClassSystem::Env => builder.build(),
288            ClassSystem::S3 | ClassSystem::Vctrs => builder.build_s3_body(),
289            ClassSystem::S4 => builder.build_s4_body(),
290            ClassSystem::S7 => builder.build_s7_body(),
291            ClassSystem::R6 => builder.build_r6_body(),
292        }
293    }
294
295    /// Build the `.Call()` expression for a static (non-receiver) trait method.
296    pub(super) fn static_call(&self) -> String {
297        crate::r_wrapper_builder::DotCallBuilder::new(&self.c_ident)
298            .with_args_str(&self.args)
299            .build()
300    }
301
302    /// Build the `.Call()` expression for an instance trait method, with
303    /// `self_expr` passed directly as the receiver argument (e.g. `".ptr"`,
304    /// `"x"`, `"self@.ptr"`).
305    ///
306    /// This is the structured equivalent of `MethodContext::instance_call` —
307    /// no string surgery. It fixes the substring-corruption bug where S4/S7/R6
308    /// built the call with `self = "x"` and then ran
309    /// `call.replace(", x", ", .ptr")`: `str::replace` rewrites *every* match
310    /// of the substring `", x"`, so a parameter whose R name started with `x`
311    /// (e.g. `x_factor`) was corrupted into `.ptr_factor`, producing a runtime
312    /// "object '.ptr_factor' not found" error. Passing the receiver expression
313    /// directly to `with_self` never touches the other arguments.
314    pub(super) fn instance_call(&self, self_expr: &str) -> String {
315        crate::r_wrapper_builder::DotCallBuilder::new(&self.c_ident)
316            .with_call_attribution(self.call_attribution)
317            .with_self(self_expr)
318            .with_args_str(&self.args)
319            .build()
320    }
321
322    /// R-param-name → auto-generated `@param` text of this method's choice
323    /// params (`One of "a", "b".` for `choices(...)`) and of its `Missing<..>`
324    /// params with a default (#2161). See
325    /// `r_class_formatter::choice_param_doc_map` and
326    /// `miniextendr_fn::missing_default_param_docs`.
327    pub(super) fn choice_param_docs(&self) -> std::collections::HashMap<String, String> {
328        let mut docs =
329            crate::r_class_formatter::choice_param_doc_map(&self.c_ident, &self.method.per_param);
330        docs.extend(crate::miniextendr_fn::missing_default_param_docs(
331            &self.method.sig.inputs,
332            &self.method.per_param,
333            &self.method.param_defaults,
334            &crate::r_wrapper_builder::Formals::default(),
335        ));
336        docs
337    }
338
339    /// Build R prelude lines validating `match_arg`/`choices` params. See
340    /// `r_class_formatter::build_match_arg_prelude`.
341    pub(super) fn match_arg_prelude(&self) -> Vec<String> {
342        crate::r_class_formatter::build_match_arg_prelude(
343            &self.method.sig.inputs,
344            &self.method.per_param,
345            &self.c_ident,
346            self.call_attribution,
347        )
348    }
349
350    /// R-side precondition guards for this method's parameters.
351    /// See `MethodContext::precondition_checks` for the inherent-impl twin.
352    /// Each parameter keeps or drops its type-derived checks as its own
353    /// `preconditions(p)` / `no_preconditions(p)`, the method's, the impl
354    /// block's, the crate default and the feature decide; the per-parameter
355    /// `inherits(...)` / `not_inherits(...)` / `no_na(...)` checks stay.
356    pub(super) fn precondition_checks(&self) -> Vec<String> {
357        crate::r_class_formatter::build_method_precondition_checks(
358            &self.method.sig.inputs,
359            &self.method.per_param,
360            self.method.coerce,
361            self.method.preconditions,
362            self.impl_preconditions,
363            self.call_attribution.r_check_call(),
364        )
365    }
366
367    /// Emit the shared method prelude into `lines`, each line prefixed with
368    /// `indent` — the trait-impl twin of `MethodContext::emit_method_prelude`.
369    /// In order: `r_entry`, `r_on_exit`, `lifecycle_prelude`,
370    /// `precondition_checks`, `match_arg_prelude`, `r_post_checks`.
371    ///
372    /// `Missing<T>` forwarding is not a prelude step here either — it's inline
373    /// in `self.args` (built in `new`), matching the inherent path.
374    ///
375    /// `what` is the human-readable label passed to the lifecycle prelude.
376    /// This mirrors the pre-refactor `trait_method_preamble_lines`, which
377    /// always used the R-facing method name as `what` regardless of class
378    /// system (inherent methods instead use a class-qualified label like
379    /// `"Type.method"` — trait methods keep the simpler unqualified label to
380    /// avoid changing existing lifecycle-warning wording).
381    pub(super) fn emit_method_prelude(&self, lines: &mut Vec<String>, indent: &str, what: &str) {
382        let m = self.method;
383        if let Some(ref entry) = m.r_entry {
384            for line in entry.lines() {
385                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{indent}{line}"));
386            }
387        }
388        if let Some(ref on_exit) = m.r_on_exit {
389            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}{0}", on_exit.to_r_code(),
                indent))
    })format!("{indent}{}", on_exit.to_r_code()));
390        }
391        if let Some(ref spec) = m.lifecycle
392            && let Some(prelude) = spec.r_prelude(what)
393        {
394            for line in prelude.lines() {
395                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{indent}{line}"));
396            }
397        }
398        for check in self.precondition_checks() {
399            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, check))
    })format!("{indent}{check}"));
400        }
401        for line in self.match_arg_prelude() {
402            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{indent}{line}"));
403        }
404        if let Some(ref post) = m.r_post_checks {
405            for line in post.lines() {
406                lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", indent, line))
    })format!("{indent}{line}"));
407            }
408        }
409    }
410}