Skip to main content

miniextendr_macros/
naming.rs

1//! Naming helpers for the static symbols the `#[miniextendr]` attribute emits.
2//!
3//! These formatters live in one place so the attribute macro and any later
4//! consumer (e.g. a registration-chasing linter) can compute the exact same
5//! identifiers from a source `syn::Ident`.
6
7use syn::ext::IdentExt;
8
9// region: raw identifiers
10//
11// Rust keywords are ordinary R names (`type`, `where`, `match`, `mod`, ...),
12// so users spell them as raw identifiers: `fn r#match(r#where: &str)`. The
13// `r#` prefix is Rust surface syntax only — `Display` for `syn::Ident` keeps it
14// (`"r#where"`), which is neither a valid R name, nor a valid C symbol
15// fragment, nor accepted by `syn::Ident::new` / `format_ident!`. Every place
16// that turns a user identifier into a *name* (R formals, R function/method
17// names, list/data-frame column names, C symbols, HashMap keys, synthesized
18// Rust bindings) must go through `ident_name` / `unraw` instead of
19// `to_string()` / direct interpolation. Token positions (`quote! { #ident }`)
20// keep the raw ident — `r#where` is what the Rust side needs.
21
22/// The user's identifier as a plain name: `r#where` → `"where"`, `x` → `"x"`.
23pub(crate) fn ident_name(ident: &syn::Ident) -> String {
24    ident.unraw().to_string()
25}
26
27/// The user's identifier without its `r#` prefix, for `format_ident!` /
28/// `quote!` interpolation into *synthesized* identifiers (`__storage_where`).
29/// Not for emitting the identifier itself — `where` is not a valid binding.
30pub(crate) fn unraw(ident: &syn::Ident) -> syn::Ident {
31    ident.unraw()
32}
33
34/// A *name* (a column / list-element name, from a user field or a `rename`)
35/// as a Rust identifier for a generated struct field or binding. Keywords come
36/// back raw so `type` emits `r#type` instead of an unparsable token stream.
37pub(crate) fn name_ident(name: &str) -> syn::Ident {
38    syn::parse_str::<syn::Ident>(name)
39        .unwrap_or_else(|_| syn::Ident::new_raw(name, proc_macro2::Span::call_site()))
40}
41// endregion
42
43/// Local repr(C) type for a concrete trait vtable. Only the static beside it
44/// is exported to C; this type reproduces the declaration's supplied layout.
45pub(crate) fn vtable_layout_ident(trait_name: &syn::Ident, type_name: &str) -> syn::Ident {
46    let table = vtable_static_ident(trait_name, type_name);
47    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("{0}_Layout", table))
            }), ::quote::__private::Option::None)quote::format_ident!("{table}_Layout")
48}
49
50/// Identifier for the registration entry holding the R wrapper source.
51///
52/// Returns `R_WRAPPER_{rust_ident}`, preserving case.
53pub(crate) fn r_wrapper_const_ident_for(rust_ident: &syn::Ident) -> syn::Ident {
54    let name = unraw(rust_ident);
55    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("R_WRAPPER_{0}", name))
            }), ::quote::__private::Option::None)quote::format_ident!("R_WRAPPER_{name}")
56}
57
58/// The binder of a conditional bound, `for<'__mx_cond> FieldTy: Trait`.
59///
60/// A where clause on a concrete type that does not hold is an error where the
61/// impl is written (E0277). Behind a higher-ranked binder the same bound is
62/// checked where the impl is used, so the impl just does not apply to that
63/// type. Derives use it for impls that exist only when the user's field types
64/// allow them, such as a companion's `Debug`. The name stays clear of user
65/// lifetimes, which a binder must not shadow (E0496).
66pub(crate) fn conditional_bound_lifetime() -> syn::Lifetime {
67    syn::Lifetime::new("'__mx_cond", proc_macro2::Span::call_site())
68}
69
70/// The C wrapper's receiver slot, shared with method extraction and return
71/// handling. Its mixed-site span keeps a user parameter named `self_sexp`
72/// from replacing the original R handle after conversion.
73pub(crate) fn self_sexp_ident() -> syn::Ident {
74    syn::Ident::new("self_sexp", proc_macro2::Span::mixed_site())
75}
76
77/// The C wrapper's call slot, declared by `CWrapperContext` with `quote!`.
78/// A reference inside a `quote_spanned!` template would take the user type's
79/// span instead. That only resolves while the macro's call site is the
80/// user's, not when the wrapper is generated inside a `macro_rules!`
81/// expansion, as a trait impl's is (#1489). So references interpolate this.
82pub(crate) fn call_slot_ident() -> syn::Ident {
83    syn::Ident::new("__miniextendr_call", proc_macro2::Span::call_site())
84}
85
86/// The error a failed argument conversion binds, for the same reason as
87/// [`call_slot_ident`]: the binding and the expressions that read it are
88/// built in different templates.
89pub(crate) fn conversion_error_ident() -> syn::Ident {
90    syn::Ident::new("e", proc_macro2::Span::call_site())
91}
92
93/// A private export name for a trait's metadata macro. The public macro is
94/// re-exported beside the trait under the trait's own name, in Rust's separate
95/// macro namespace, so imports carry both. An expansion-local suffix prevents
96/// same-named traits in different modules from colliding at the crate root.
97/// This name never enters the trait tag or any C/wasm registration symbol.
98pub(crate) fn trait_metadata_macro_ident(trait_name: &syn::Ident) -> syn::Ident {
99    use std::sync::atomic::{AtomicUsize, Ordering};
100    static NEXT: AtomicUsize = AtomicUsize::new(0);
101    let suffix = NEXT.fetch_add(1, Ordering::Relaxed);
102    let name = unraw(trait_name);
103    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__mx_trait_metadata_{0}_{1}",
                        name, suffix))
            }), ::quote::__private::Option::None)quote::format_ident!("__mx_trait_metadata_{name}_{suffix}")
104}
105
106// region: crate-prefixed C symbol naming (#1273)
107//
108// Every `#[miniextendr]`-emitted `#[no_mangle]` C symbol is prefixed with the
109// consuming crate's name so that two packages loaded into the same webR
110// session (which share one GOT under Emscripten's SIDE_MODULE model) can't
111// have the first-loaded package's definition of a name silently win for a
112// later package's identically-named export. Native `dyn.load` with
113// `RTLD_LOCAL` was never affected — this is purely a wasm cross-package
114// hygiene fix — but the prefix is applied unconditionally on every target so
115// there's a single code path and no target-dependent symbol shape.
116//
117// Registration name and linker symbol name are kept identical everywhere
118// (the invariant the wasm snapshot writer,
119// `miniextendr-api/src/wasm_registry_writer.rs`, depends on to reconstruct
120// `extern "C" { fn <name>(...); }` blocks from `R_CallMethodDef.name`) — so
121// every formatter below produces the *one* string used for both the
122// `#[no_mangle]` fn/static definition and its registration entry.
123
124/// The consuming crate's name, used as the prefix for every macro-emitted
125/// `#[no_mangle]` C symbol.
126///
127/// Reads `CARGO_CRATE_NAME`, which cargo sets (with hyphens already
128/// normalized to underscores) for the rustc invocation that expands this
129/// proc macro — the same precedent `miniextendr_init!()` relies on
130/// (`lib.rs`, `miniextendr_init` fn). Real macro expansion (i.e. compiling a
131/// downstream crate through cargo) always has this set.
132///
133/// Falls back to `CARGO_PKG_NAME` (normalized the same way, since it is
134/// *not* auto-normalized) for the one context where `CARGO_CRATE_NAME` is
135/// absent: this crate's own unit/insta tests call codegen functions directly
136/// at test *runtime* rather than through real macro expansion, and cargo
137/// does not forward `CARGO_CRATE_NAME` to a test binary's process
138/// environment (verified empirically — only `CARGO_PKG_*` vars are). Falls
139/// back further to the literal `"crate"` if even that is absent (e.g. a
140/// direct `rustc` invocation bypassing cargo entirely).
141pub(crate) fn crate_prefix() -> String {
142    std::env::var("CARGO_CRATE_NAME").unwrap_or_else(|_| {
143        std::env::var("CARGO_PKG_NAME")
144            .map(|n| n.replace('-', "_"))
145            .unwrap_or_else(|_| "crate".to_string())
146    })
147}
148
149/// `C_<crate>_<fn>` — bare-fn C wrapper identifier (internal-wrapper arm
150/// only; `extern`/`#[export_name]` fns pass through untouched and own their
151/// own cross-package uniqueness).
152pub(crate) fn bare_fn_c_wrapper_ident(rust_ident: &syn::Ident) -> syn::Ident {
153    let prefix = crate_prefix();
154    let rust_ident = unraw(rust_ident);
155    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("C_{0}_{1}", prefix,
                        rust_ident))
            }), ::quote::__private::Option::None)quote::format_ident!("C_{prefix}_{rust_ident}")
156}
157
158/// `C_<crate>_<Type>__<method>` — impl-method C wrapper identifier.
159pub(crate) fn impl_method_c_wrapper_ident(
160    type_ident: &syn::Ident,
161    method_ident: &syn::Ident,
162) -> syn::Ident {
163    let prefix = crate_prefix();
164    let method_ident = unraw(method_ident);
165    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("C_{0}_{1}__{2}", prefix,
                        type_ident, method_ident))
            }), ::quote::__private::Option::None)quote::format_ident!("C_{prefix}_{type_ident}__{method_ident}")
166}
167
168/// `C_<crate>_<Type>__<Trait>__<member>` as a `String` — shared by
169/// `TraitMethod` and `TraitConst`, and by both the ident and string forms
170/// each needs, so the format string can't drift across the four call sites
171/// that used to duplicate it.
172pub(crate) fn trait_member_c_wrapper_string(
173    type_ident: &syn::Ident,
174    trait_name: &syn::Ident,
175    member_ident: &syn::Ident,
176) -> String {
177    let prefix = crate_prefix();
178    let member_ident = unraw(member_ident);
179    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}_{1}__{2}__{3}", prefix,
                type_ident, trait_name, member_ident))
    })format!("C_{prefix}_{type_ident}__{trait_name}__{member_ident}")
180}
181
182/// Same as [`trait_member_c_wrapper_string`], as a `syn::Ident` for Rust
183/// token generation.
184pub(crate) fn trait_member_c_wrapper_ident(
185    type_ident: &syn::Ident,
186    trait_name: &syn::Ident,
187    member_ident: &syn::Ident,
188) -> syn::Ident {
189    match ::quote::__private::IdentFragmentAdapter(&trait_member_c_wrapper_string(type_ident,
                trait_name, member_ident)) {
    arg =>
        ::quote::__private::mk_ident(&::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("{0}", arg))
                    }), ::quote::__private::Option::None.or(arg.span())),
}quote::format_ident!(
190        "{}",
191        trait_member_c_wrapper_string(type_ident, trait_name, member_ident)
192    )
193}
194
195/// `C_<crate>__mx_rdata_get_<Type>_<field>` — sidecar field getter C symbol.
196pub(crate) fn sidecar_getter_c_name(type_name: &str, field_name: &str) -> String {
197    let prefix = crate_prefix();
198    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_rdata_get_{1}_{2}",
                prefix, type_name, field_name))
    })format!("C_{prefix}__mx_rdata_get_{type_name}_{field_name}")
199}
200
201/// `C_<crate>__mx_rdata_set_<Type>_<field>` — sidecar field setter C symbol.
202pub(crate) fn sidecar_setter_c_name(type_name: &str, field_name: &str) -> String {
203    let prefix = crate_prefix();
204    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_rdata_set_{1}_{2}",
                prefix, type_name, field_name))
    })format!("C_{prefix}__mx_rdata_set_{type_name}_{field_name}")
205}
206
207/// `C_<crate>__mx_all_equal_<Type>` — the field reader of the `all.equal()`
208/// method of `#[derive(AllEqual)]` (#2149).
209pub(crate) fn all_equal_c_name(type_name: &str) -> String {
210    let prefix = crate_prefix();
211    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_all_equal_{1}", prefix,
                type_name))
    })format!("C_{prefix}__mx_all_equal_{type_name}")
212}
213
214/// `C_<crate>__mx_rdata_live_<Type>` — the liveness check of a type with
215/// `#[externalptr(restored(refuse = "every_read"))]` (#1901).
216pub(crate) fn sidecar_live_c_name(type_name: &str) -> String {
217    let prefix = crate_prefix();
218    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_rdata_live_{1}", prefix,
                type_name))
    })format!("C_{prefix}__mx_rdata_live_{type_name}")
219}
220
221/// `C_<crate>__mx_rdata_fallback_<Type>` — the field fallback of an S3, S4
222/// or env class with `r_data_accessors` (`fallback = "Self::f"`, #2150),
223/// which the impl block that has it emits.
224pub(crate) fn sidecar_fallback_c_name(type_name: &str) -> String {
225    let prefix = crate_prefix();
226    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_rdata_fallback_{1}",
                prefix, type_name))
    })format!("C_{prefix}__mx_rdata_fallback_{type_name}")
227}
228
229/// `C_<crate>__mx_rdata_names_<Type>` — the names the field fallback
230/// answers, for `.DollarNames()` (`fallback_names = "Self::g"`, #2150).
231pub(crate) fn sidecar_fallback_names_c_name(type_name: &str) -> String {
232    let prefix = crate_prefix();
233    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("C_{0}__mx_rdata_names_{1}", prefix,
                type_name))
    })format!("C_{prefix}__mx_rdata_names_{type_name}")
234}
235
236/// The R helpers `#[derive(ExternalPtr)]` emits for a type's sidecar fields
237/// and the `$` / `[[` field methods of `r_data_accessors` call (#1848).
238#[derive(#[automatically_derived]impl ::core::fmt::Debug for RDataHelper {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Fields Get Set NoField ReadOnly ErrorClass EveryRead Live",
            match self {
                RDataHelper::Fields => 0usize,
                RDataHelper::Get => 7usize,
                RDataHelper::Set => 11usize,
                RDataHelper::NoField => 15usize,
                RDataHelper::ReadOnly => 23usize,
                RDataHelper::ErrorClass => 32usize,
                RDataHelper::EveryRead => 43usize,
                RDataHelper::Live => 53usize,
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RDataHelper {
}
#[automatically_derived]impl ::core::clone::Clone for RDataHelper {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RDataHelper { }Copy)]
239pub(crate) enum RDataHelper {
240    /// `.rdata_fields_<Type>`: the field names, a character vector.
241    Fields,
242    /// `.rdata_get_<Type>(x, name)`: the field's getter `.Call()`.
243    Get,
244    /// `.rdata_set_<Type>(x, name, value)`: the field's setter `.Call()`.
245    Set,
246    /// `.rdata_no_field_<Type>(name, env, cls)`: the `miniextendr_no_field`
247    /// error, naming the R class `cls` the method serves.
248    NoField,
249    /// `.rdata_read_only_<Type>(name, x, env, why)`: the
250    /// `miniextendr_read_only_field` error of a write to a field R can't
251    /// write, a `Computed` or `#[r_data(read_only)]` one or any under
252    /// `r_data_accessors = "read_only"` (#2268), naming the R class of `x`
253    /// and with `field_error(read_only_hint = ...)` after it.
254    ReadOnly,
255    /// `.rdata_error_class_<Type>`: the classes the field methods put in
256    /// front of their own errors, `#[externalptr(field_error(class = ...))]`
257    /// (#1899); `NULL` without them.
258    ErrorClass,
259    /// `.rdata_every_read_<Type>`: `TRUE` for a type with
260    /// `restored(refuse = "every_read")` (#1901), else `FALSE`; it gates the
261    /// field methods' calls of [`RDataHelper::Live`].
262    EveryRead,
263    /// `.rdata_live_<Type>(x, raise)`: the liveness check of a type with
264    /// `restored(refuse = "every_read")` (#1901). Other types get a stub that
265    /// is never called (gated by [`RDataHelper::EveryRead`]), so a binding
266    /// the methods call is always a function, as `R CMD check` expects.
267    Live,
268}
269
270/// `.rdata_<helper>_<Type>`: the R name of a sidecar field helper, named by
271/// the Rust type (not an impl's `class = "..."`), since the derive only knows
272/// the type.
273pub(crate) fn rdata_helper_name(helper: RDataHelper, type_name: &str) -> String {
274    let helper = match helper {
275        RDataHelper::Fields => "fields",
276        RDataHelper::Get => "get",
277        RDataHelper::Set => "set",
278        RDataHelper::NoField => "no_field",
279        RDataHelper::ReadOnly => "read_only",
280        RDataHelper::ErrorClass => "error_class",
281        RDataHelper::EveryRead => "every_read",
282        RDataHelper::Live => "live",
283    };
284    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".rdata_{0}_{1}", helper,
                type_name))
    })format!(".rdata_{helper}_{type_name}")
285}
286
287/// `__mx_altrep_reg_<crate>_<Ident>` — ALTREP class registration fn.
288pub(crate) fn altrep_reg_fn_ident(ident: &syn::Ident) -> syn::Ident {
289    let prefix = crate_prefix();
290    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__mx_altrep_reg_{0}_{1}",
                        prefix, ident))
            }), ::quote::__private::Option::None)quote::format_ident!("__mx_altrep_reg_{prefix}_{ident}")
291}
292
293/// `__mx_snapshot_reg_<crate>_<Ident>_<hash>` — the registration fn of an
294/// `ExternalPtr` type's carrier class (#2186).
295///
296/// Every non-generic `#[derive(ExternalPtr)]` type emits one, and two types
297/// of one crate may share an ident in different modules, so the symbol
298/// carries a hash of where the type is defined: the source file's name (not
299/// its path, which differs between the host build and a webR build of the
300/// same sources), line and column.
301pub(crate) fn snapshot_reg_fn_ident(ident: &syn::Ident) -> syn::Ident {
302    let prefix = crate_prefix();
303    let span = ident.span();
304    let file = span.file();
305    let file = file.rsplit(['/', '\\']).next().unwrap_or(&file);
306    let start = span.start();
307    let site = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{2}:{0}:{1}", start.line,
                start.column, file))
    })format!("{file}:{}:{}", start.line, start.column);
308    let hash = site.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
309        (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
310    });
311    let ident = unraw(ident);
312    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__mx_snapshot_reg_{0}_{1}_{2:016x}",
                        prefix, ident, hash))
            }), ::quote::__private::Option::None)quote::format_ident!("__mx_snapshot_reg_{prefix}_{ident}_{hash:016x}")
313}
314
315/// `__VTABLE_<crate>_<Trait>_FOR_<Type>` — trait-impl vtable static.
316/// Preserve spelling: Rust distinguishes `Counter` from `counter`, as must
317/// both the Rust identifier and the exported linker symbol. `type_name` may
318/// carry the existing generic-argument hash suffix.
319pub(crate) fn vtable_static_ident(trait_name: &syn::Ident, type_name: &str) -> syn::Ident {
320    let prefix = crate_prefix();
321    let trait_name = unraw(trait_name);
322    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__VTABLE_{0}_{1}_FOR_{2}",
                        prefix, trait_name, type_name))
            }), ::quote::__private::Option::None)quote::format_ident!("__VTABLE_{prefix}_{trait_name}_FOR_{type_name}")
323}
324
325/// Trait tag, shared by the declaration and both impl expansion paths.
326pub(crate) fn trait_tag_ident(trait_name: &syn::Ident) -> syn::Ident {
327    let trait_name = unraw(trait_name);
328    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("TAG_{0}", trait_name))
            }), ::quote::__private::Option::None)quote::format_ident!("TAG_{trait_name}")
329}
330
331/// Trait vtable builder, defined beside the trait and called from its impls.
332pub(crate) fn trait_vtable_builder_ident(trait_name: &syn::Ident) -> syn::Ident {
333    let trait_name = unraw(trait_name);
334    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__{0}_build_vtable",
                        trait_name))
            }), ::quote::__private::Option::None)quote::format_ident!("__{trait_name}_build_vtable")
335}
336
337/// Generic shim defined beside a non-generic trait.
338pub(crate) fn trait_method_shim_ident(
339    trait_name: &syn::Ident,
340    method_name: &syn::Ident,
341) -> syn::Ident {
342    let trait_name = unraw(trait_name);
343    let method_name = unraw(method_name);
344    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__{0}_{1}_shim",
                        trait_name, method_name))
            }), ::quote::__private::Option::None)quote::format_ident!("__{trait_name}_{method_name}_shim")
345}
346
347/// Wrapper fragment registered by either trait impl expansion path.
348pub(crate) fn trait_impl_wrappers_ident(type_name: &str, trait_name: &syn::Ident) -> syn::Ident {
349    let trait_name = unraw(trait_name);
350    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("R_WRAPPERS_{0}_{1}_IMPL",
                        type_name, trait_name))
            }), ::quote::__private::Option::None)quote::format_ident!("R_WRAPPERS_{type_name}_{trait_name}_IMPL")
351}
352
353/// Trait dispatch registration; uses the same type suffix as its vtable.
354pub(crate) fn trait_dispatch_ident(trait_name: &syn::Ident, type_name: &str) -> syn::Ident {
355    let trait_name = unraw(trait_name);
356    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__MX_DISPATCH_{0}_FOR_{1}",
                        trait_name, type_name))
            }), ::quote::__private::Option::None)quote::format_ident!("__MX_DISPATCH_{trait_name}_FOR_{type_name}")
357}
358
359/// `__vtshim_<crate>_<Type>__<Trait>__<method>` — trait-impl vtable shim fn.
360pub(crate) fn vtshim_ident(
361    type_ident: &syn::Ident,
362    trait_name: &syn::Ident,
363    method_ident: &syn::Ident,
364) -> syn::Ident {
365    let prefix = crate_prefix();
366    let method_ident = unraw(method_ident);
367    ::quote::__private::mk_ident(&::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("__vtshim_{0}_{1}__{2}__{3}",
                        prefix, type_ident, trait_name, method_ident))
            }), ::quote::__private::Option::None)quote::format_ident!("__vtshim_{prefix}_{type_ident}__{trait_name}__{method_ident}")
368}
369// endregion
370
371/// Convert a PascalCase string to snake_case.
372///
373/// Inserts an underscore before each uppercase letter (except the first),
374/// then lowercases the entire result. For example, `"InProgress"` becomes
375/// `"in_progress"`.
376pub(crate) fn to_snake_case(s: &str) -> String {
377    let mut out = String::new();
378    for (i, c) in s.char_indices() {
379        if c.is_uppercase() && i > 0 {
380            out.push('_');
381        }
382        out.extend(c.to_lowercase());
383    }
384    out
385}
386
387/// Convert a PascalCase string to kebab-case (`InProgress` → `in-progress`).
388pub(crate) fn to_kebab_case(s: &str) -> String {
389    to_snake_case(s).replace('_', "-")
390}
391
392/// Apply a `rename_all` transformation to a variant name.
393///
394/// Supports `"snake_case"`, `"kebab-case"`, `"lower"`, `"upper"`. Returns the
395/// name unchanged if `rename_all` is `None` or unrecognised.
396pub(crate) fn apply_rename_all(name: &str, rename_all: Option<&str>) -> String {
397    match rename_all {
398        Some("snake_case") => to_snake_case(name),
399        Some("kebab-case") => to_kebab_case(name),
400        Some("lower") => name.to_lowercase(),
401        Some("upper") => name.to_uppercase(),
402        _ => name.to_string(),
403    }
404}
405
406// region: R definition names
407
408/// R's reserved words: never usable as a bare name on the left of `<-`.
409const R_RESERVED_WORDS: &[&str] = &[
410    "if",
411    "else",
412    "repeat",
413    "while",
414    "function",
415    "for",
416    "next",
417    "break",
418    "TRUE",
419    "FALSE",
420    "NULL",
421    "Inf",
422    "NaN",
423    "NA",
424    "NA_integer_",
425    "NA_real_",
426    "NA_character_",
427    "NA_complex_",
428    "in",
429];
430
431/// Whether `name` is one of R's reserved words (`if`, `in`, `TRUE`, `NA`, ...).
432pub(crate) fn is_r_reserved_word(name: &str) -> bool {
433    R_RESERVED_WORDS.contains(&name)
434}
435
436/// Whether `name` is a syntactic R name: ASCII letters, digits, `.` and `_`
437/// only; starts with a letter, or with a `.` that is not followed by a digit;
438/// and is not a reserved word. Anything else (`[.foo`, `$.foo`, `==.foo`,
439/// `%in%.foo`) has to be backtick-quoted in source.
440pub(crate) fn is_syntactic_r_name(name: &str) -> bool {
441    let mut chars = name.chars();
442    match chars.next() {
443        Some(c) if c.is_ascii_alphabetic() => {}
444        Some('.') => {
445            if chars.next().is_some_and(|c| c.is_ascii_digit()) {
446                return false;
447            }
448        }
449        _ => return false,
450    }
451    name.chars()
452        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
453        && !is_r_reserved_word(name)
454}
455
456/// R's rule for a package name (Writing R Extensions, "The DESCRIPTION
457/// file"): ASCII letters, digits and `.`, at least two characters, starting
458/// with a letter and not ending in `.`.
459pub(crate) fn is_r_package_name(name: &str) -> bool {
460    let bytes = name.as_bytes();
461    bytes.len() >= 2
462        && bytes[0].is_ascii_alphabetic()
463        && bytes[bytes.len() - 1] != b'.'
464        && bytes
465            .iter()
466            .all(|b| b.is_ascii_alphanumeric() || *b == b'.')
467}
468
469/// The left-hand side of a generated `<name> <- function(...)` definition.
470///
471/// Syntactic names pass through unchanged so the common output stays readable;
472/// a non-syntactic one (an S3 method on `[`, `$`, `==`, ...) is wrapped in
473/// backticks, which R accepts for any name. Without this the wrapper file did
474/// not parse (#1475).
475///
476/// R processes backslash escapes inside backticks as it does in strings, so a
477/// `\` is doubled (first, so the escapes added for backticks stay single) and a
478/// backtick becomes `` \` ``: the name `a\b` is written `` `a\\b` ``.
479/// `miniextendr-api`'s duplicate-definition scan
480/// (`registry::parse_top_level_fn_def_name`) reads this escaped spelling.
481pub(crate) fn r_def_name(name: &str) -> String {
482    if is_syntactic_r_name(name) {
483        name.to_string()
484    } else {
485        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                name.replace('\\', "\\\\").replace('`', "\\`")))
    })format!("`{}`", name.replace('\\', "\\\\").replace('`', "\\`"))
486    }
487}
488
489/// The argument of a raw NAMESPACE directive such as `export(<name>)`.
490///
491/// `@rawNamespace` lines reach NAMESPACE verbatim, so roxygen2 does not quote
492/// them the way it quotes `@export <name>`. Syntactic names stay bare; a
493/// non-syntactic one (an S7 generic on `[[` or `%op%`) becomes a double-quoted
494/// string, the form roxygen2 itself writes, because `export([[)` does not parse.
495/// `miniextendr-api`'s generic-doc pass mirrors this rule
496/// (`registry::r_namespace_name`); the two must stay in step so roxygen2 sees
497/// one directive, not two spellings of it. Only `\` and `"` are escaped, as
498/// the mirror does ([`r_string_escape`] would also escape control and
499/// non-ASCII characters).
500pub(crate) fn r_namespace_name(name: &str) -> String {
501    if is_syntactic_r_name(name) {
502        name.to_string()
503    } else {
504        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                name.replace('\\', "\\\\").replace('"', "\\\"")))
    })format!("\"{}\"", name.replace('\\', "\\\\").replace('"', "\\\""))
505    }
506}
507
508/// Escape `s` for the inside of an R double-quoted string literal. Every
509/// generated R string literal built from user text goes through this (the
510/// precondition requirement text and the author's messages, the class names
511/// in `inherits()`, lifecycle arguments).
512///
513/// Besides `\` and `"`, a newline, carriage return or tab becomes its escape
514/// (a guard stays on one line of the wrappers file), any other control
515/// character and every non-ASCII character a `\u{..}` / `\U{..}` escape: R
516/// code in a package must be ASCII, and R reads these escapes back to the
517/// same UTF-8 text. A NUL cannot be written (R strings cannot hold one);
518/// the attribute parser rejects it in a message.
519pub(crate) fn r_string_escape(s: &str) -> String {
520    use std::fmt::Write as _;
521    let mut out = String::with_capacity(s.len());
522    for c in s.chars() {
523        match c {
524            '\\' => out.push_str("\\\\"),
525            '"' => out.push_str("\\\""),
526            '\n' => out.push_str("\\n"),
527            '\r' => out.push_str("\\r"),
528            '\t' => out.push_str("\\t"),
529            c if c.is_ascii() && !c.is_ascii_control() => out.push(c),
530            c if u32::from(c) <= 0xFFFF => {
531                let _ = out.write_fmt(format_args!("\\u{{{0:x}}}", u32::from(c)))write!(out, "\\u{{{:x}}}", u32::from(c));
532            }
533            c => {
534                let _ = out.write_fmt(format_args!("\\U{{{0:x}}}", u32::from(c)))write!(out, "\\U{{{:x}}}", u32::from(c));
535            }
536        }
537    }
538    out
539}
540
541// endregion
542
543// region: package-qualified generics (#2154)
544
545/// A `generic = "..."` value split into its package and the generic's own
546/// name: `"dplyr::dplyr_reconstruct"` is `(Some("dplyr"), "dplyr_reconstruct")`,
547/// `"print"` is `(None, "print")`. The value must have passed
548/// [`parse_generic`].
549pub(crate) fn split_generic(generic: &str) -> (Option<&str>, &str) {
550    match generic.split_once("::") {
551        Some((package, name)) => (Some(package), name),
552        None => (None, generic),
553    }
554}
555
556/// Parse a `generic = "..."` value. A generic may name its package,
557/// `pkg::generic`, with a valid R package name (ASCII letters, digits and
558/// `.`; at least two characters; starts with a letter; doesn't end in `.`)
559/// and one `::`.
560pub(crate) fn parse_generic(value: &syn::LitStr) -> syn::Result<String> {
561    let generic = value.value();
562    let error = |message: String| Err(syn::Error::new(value.span(), message));
563    if generic.contains(":::") {
564        return error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`: a method registers on an exported generic; name it `pkg::generic`, not `pkg:::generic`",
                generic))
    })format!(
565            "`{generic}`: a method registers on an exported generic; name it `pkg::generic`, \
566             not `pkg:::generic`"
567        ));
568    }
569    let Some((package, name)) = generic.split_once("::") else {
570        return Ok(generic);
571    };
572    if name.contains("::") {
573        return error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`: a generic takes one `pkg::` qualifier",
                generic))
    })format!(
574            "`{generic}`: a generic takes one `pkg::` qualifier"
575        ));
576    }
577    if name.is_empty() {
578        return error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`: no generic name after `{1}::`",
                generic, package))
    })format!("`{generic}`: no generic name after `{package}::`"));
579    }
580    if !is_r_package_name(package) {
581        return error(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`: `{1}` is not an R package name; a package name has only ASCII letters, digits and `.`, at least two characters, starts with a letter and doesn\'t end in `.`",
                generic, package))
    })format!(
582            "`{generic}`: `{package}` is not an R package name; a package name has only ASCII \
583             letters, digits and `.`, at least two characters, starts with a letter and \
584             doesn't end in `.`"
585        ));
586    }
587    Ok(generic)
588}
589
590// endregion
591
592/// Parse a dispatch receiver that is safe to emit as a bare R symbol.
593pub(crate) fn parse_r_receiver(value: &syn::LitStr) -> syn::Result<String> {
594    let name = value.value();
595    if !is_syntactic_r_name(&name) || !crate::r_class_formatter::is_bare_identifier(&name) {
596        return Err(syn::Error::new(
597            value.span(),
598            "receiver must start with a letter and contain only letters, digits and underscores",
599        ));
600    }
601    Ok(name)
602}
603
604#[cfg(test)]
605mod tests;