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`.
67use syn::ext::IdentExt;
89// 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.
2122/// The user's identifier as a plain name: `r#where` → `"where"`, `x` → `"x"`.
23pub(crate) fn ident_name(ident: &syn::Ident) -> String {
24ident.unraw().to_string()
25}
2627/// 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 {
31ident.unraw()
32}
3334/// 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
4243/// 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 {
46let 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}
4950/// 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 {
54let 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}
5758/// 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}
6970/// 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}
7677/// 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}
8586/// 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}
9293/// 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 {
99use std::sync::atomic::{AtomicUsize, Ordering};
100static NEXT: AtomicUsize = AtomicUsize::new(0);
101let suffix = NEXT.fetch_add(1, Ordering::Relaxed);
102let 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}
105106// 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.
123124/// 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}
148149/// `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 {
153let prefix = crate_prefix();
154let 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}
157158/// `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 {
163let prefix = crate_prefix();
164let 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}
167168/// `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 {
177let prefix = crate_prefix();
178let 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}
181182/// 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 {
189match ::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}
194195/// `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 {
197let 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}
200201/// `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 {
203let 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}
206207/// `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 {
210let 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}
213214/// `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 {
217let 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}
220221/// `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 {
225let 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}
228229/// `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 {
232let 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}
235236/// 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.
241Fields,
242/// `.rdata_get_<Type>(x, name)`: the field's getter `.Call()`.
243Get,
244/// `.rdata_set_<Type>(x, name, value)`: the field's setter `.Call()`.
245Set,
246/// `.rdata_no_field_<Type>(name, env, cls)`: the `miniextendr_no_field`
247 /// error, naming the R class `cls` the method serves.
248NoField,
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.
254ReadOnly,
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.
258ErrorClass,
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`].
262EveryRead,
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.
267Live,
268}
269270/// `.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 {
274let 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}
286287/// `__mx_altrep_reg_<crate>_<Ident>` — ALTREP class registration fn.
288pub(crate) fn altrep_reg_fn_ident(ident: &syn::Ident) -> syn::Ident {
289let 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}
292293/// `__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 {
302let prefix = crate_prefix();
303let span = ident.span();
304let file = span.file();
305let file = file.rsplit(['/', '\\']).next().unwrap_or(&file);
306let start = span.start();
307let site = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}:{0}:{1}", start.line,
start.column, file))
})format!("{file}:{}:{}", start.line, start.column);
308let hash = site.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
309 (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
310 });
311let 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}
314315/// `__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 {
320let prefix = crate_prefix();
321let 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}
324325/// Trait tag, shared by the declaration and both impl expansion paths.
326pub(crate) fn trait_tag_ident(trait_name: &syn::Ident) -> syn::Ident {
327let 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}
330331/// 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 {
333let 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}
336337/// 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 {
342let trait_name = unraw(trait_name);
343let 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}
346347/// 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 {
349let 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}
352353/// 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 {
355let 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}
358359/// `__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 {
365let prefix = crate_prefix();
366let 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
370371/// 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 {
377let mut out = String::new();
378for (i, c) in s.char_indices() {
379if c.is_uppercase() && i > 0 {
380 out.push('_');
381 }
382 out.extend(c.to_lowercase());
383 }
384out385}
386387/// Convert a PascalCase string to kebab-case (`InProgress` → `in-progress`).
388pub(crate) fn to_kebab_case(s: &str) -> String {
389to_snake_case(s).replace('_', "-")
390}
391392/// 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 {
397match rename_all {
398Some("snake_case") => to_snake_case(name),
399Some("kebab-case") => to_kebab_case(name),
400Some("lower") => name.to_lowercase(),
401Some("upper") => name.to_uppercase(),
402_ => name.to_string(),
403 }
404}
405406// region: R definition names
407408/// 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];
430431/// Whether `name` is one of R's reserved words (`if`, `in`, `TRUE`, `NA`, ...).
432pub(crate) fn is_r_reserved_word(name: &str) -> bool {
433R_RESERVED_WORDS.contains(&name)
434}
435436/// 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 {
441let mut chars = name.chars();
442match chars.next() {
443Some(c) if c.is_ascii_alphabetic() => {}
444Some('.') => {
445if chars.next().is_some_and(|c| c.is_ascii_digit()) {
446return false;
447 }
448 }
449_ => return false,
450 }
451name.chars()
452 .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
453 && !is_r_reserved_word(name)
454}
455456/// 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 {
460let bytes = name.as_bytes();
461bytes.len() >= 2
462&& bytes[0].is_ascii_alphabetic()
463 && bytes[bytes.len() - 1] != b'.'
464&& bytes465 .iter()
466 .all(|b| b.is_ascii_alphanumeric() || *b == b'.')
467}
468469/// 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 {
482if is_syntactic_r_name(name) {
483name.to_string()
484 } else {
485::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
name.replace('\\', "\\\\").replace('`', "\\`")))
})format!("`{}`", name.replace('\\', "\\\\").replace('`', "\\`"))486 }
487}
488489/// 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 {
501if is_syntactic_r_name(name) {
502name.to_string()
503 } else {
504::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"",
name.replace('\\', "\\\\").replace('"', "\\\"")))
})format!("\"{}\"", name.replace('\\', "\\\\").replace('"', "\\\""))505 }
506}
507508/// 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 {
520use std::fmt::Writeas _;
521let mut out = String::with_capacity(s.len());
522for c in s.chars() {
523match 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 => {
531let _ = out.write_fmt(format_args!("\\u{{{0:x}}}", u32::from(c)))write!(out, "\\u{{{:x}}}", u32::from(c));
532 }
533 c => {
534let _ = out.write_fmt(format_args!("\\U{{{0:x}}}", u32::from(c)))write!(out, "\\U{{{:x}}}", u32::from(c));
535 }
536 }
537 }
538out539}
540541// endregion
542543// region: package-qualified generics (#2154)
544545/// 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) {
550match generic.split_once("::") {
551Some((package, name)) => (Some(package), name),
552None => (None, generic),
553 }
554}
555556/// 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> {
561let generic = value.value();
562let error = |message: String| Err(syn::Error::new(value.span(), message));
563if generic.contains(":::") {
564return 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 }
569let Some((package, name)) = generic.split_once("::") else {
570return Ok(generic);
571 };
572if name.contains("::") {
573return 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 }
577if name.is_empty() {
578return 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 }
580if !is_r_package_name(package) {
581return 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 }
587Ok(generic)
588}
589590// endregion
591592/// 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> {
594let name = value.value();
595if !is_syntactic_r_name(&name) || !crate::r_class_formatter::is_bare_identifier(&name) {
596return Err(syn::Error::new(
597value.span(),
598"receiver must start with a letter and contain only letters, digits and underscores",
599 ));
600 }
601Ok(name)
602}
603604#[cfg(test)]
605mod tests;