Skip to main content

miniextendr_api/
registry.rs

1//! Automatic registration for miniextendr.
2//!
3//! Every `#[miniextendr]` item self-registers at link time. `package_init()`
4//! (generated by `miniextendr_init!`) calls [`miniextendr_register_routines`]
5//! during `R_init_*` to finalize registration with R. Users never interact
6//! with this module.
7
8use crate::abi::{mx_erased, mx_tag};
9use crate::sys::{DllInfo, R_CallMethodDef};
10#[cfg(not(target_arch = "wasm32"))]
11use linkme::distributed_slice;
12use std::os::raw::c_void;
13
14// region: Distributed Slices
15//
16// `linkme::distributed_slice` does not compile for `wasm32-*` targets — the
17// proc macro hits a `compile_error!` arm in `linkme-impl/src/declaration.rs`.
18// On wasm32 we keep the same public surface for the three runtime-critical
19// slices (MX_CALL_DEFS / MX_ALTREP_REGISTRATIONS / MX_TRAIT_DISPATCH) but
20// back them with a `OnceLock` populated from the user crate's
21// `wasm_registry.rs` snapshot at `R_init_*` time (see
22// `install_wasm_runtime_slices` below). The host-only slices (MX_R_WRAPPERS,
23// MX_MATCH_ARG_*, MX_CLASS_NAMES, MX_CLASS_BLOCKS, MX_S7_SIDECAR_PROPS, ...) are
24// only consumed by the wrapper-gen pass — that pass is itself
25// native-only, so the slices, their consumers, and the `wasm_registry_writer`
26// module are all `cfg(not(target_arch = "wasm32"))`-gated.
27
28/// R `.Call` method registrations (function + method C wrappers).
29///
30/// Each `#[miniextendr]` function or method emits an entry here.
31#[cfg(not(target_arch = "wasm32"))]
32#[doc = " R `.Call` method registrations (function + method C wrappers)."]
#[doc = ""]
#[doc = " Each `#[miniextendr]` function or method emits an entry here."]
pub static MX_CALL_DEFS: ::linkme::DistributedSlice<[R_CallMethodDef]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_CALL_DEFS"]
            static LINKME_START:
                [<[R_CallMethodDef] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_CALL_DEFS"]
            static LINKME_STOP:
                [<[R_CallMethodDef] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_CALL_DEFS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_CALL_DEFS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_CALL_DEFS")]
        static mut LINKME_PLEASE:
            [<[R_CallMethodDef] as ::linkme::__private36::Slice>::Element; 0]
            =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_CALL_DEFS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_CALL_DEFS",
                (&raw const LINKME_START).cast::<<[R_CallMethodDef] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[R_CallMethodDef] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_CALL_DEFS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = concat! ("linkme_MX_CALL_DEFS", $key)]
            # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeAFud52Jy,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_CALL_DEFS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_CALL_DEFS", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_CALL_DEFS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_CALL_DEFS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeAFud52Jy,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_CALL_DEFS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_CALL_DEFS"] # !
            [linkme_bsd_section = "linkme_MX_CALL_DEFS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_CALL_DEFS as MX_CALL_DEFS;#[distributed_slice]
33pub static MX_CALL_DEFS: [R_CallMethodDef];
34
35/// R wrapper code fragments with priority for ordering. **Host-only.**
36///
37/// Each `#[miniextendr]` function, impl block, or trait impl emits an entry.
38/// Priorities ensure correct evaluation order when R sources the wrapper file
39/// (sidecar helpers must be defined before class definitions that reference them).
40#[cfg(not(target_arch = "wasm32"))]
41#[doc =
" R wrapper code fragments with priority for ordering. **Host-only.**"]
#[doc = ""]
#[doc =
" Each `#[miniextendr]` function, impl block, or trait impl emits an entry."]
#[doc =
" Priorities ensure correct evaluation order when R sources the wrapper file"]
#[doc =
" (sidecar helpers must be defined before class definitions that reference them)."]
pub static MX_R_WRAPPERS: ::linkme::DistributedSlice<[RWrapperEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_R_WRAPPERS"]
            static LINKME_START:
                [<[RWrapperEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_R_WRAPPERS"]
            static LINKME_STOP:
                [<[RWrapperEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_R_WRAPPERS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_R_WRAPPERS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_R_WRAPPERS")]
        static mut LINKME_PLEASE:
            [<[RWrapperEntry] as ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_R_WRAPPERS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_R_WRAPPERS",
                (&raw const LINKME_START).cast::<<[RWrapperEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[RWrapperEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_R_WRAPPERS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat! ("linkme_MX_R_WRAPPERS", $key)] #
            !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeA6xXjXOK,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_R_WRAPPERS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_R_WRAPPERS", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_R_WRAPPERS", $key)]
            $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_R_WRAPPERS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeA6xXjXOK,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_R_WRAPPERS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_R_WRAPPERS"] # !
            [linkme_bsd_section = "linkme_MX_R_WRAPPERS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_R_WRAPPERS as MX_R_WRAPPERS;#[distributed_slice]
42pub static MX_R_WRAPPERS: [RWrapperEntry];
43
44/// ALTREP class registration entries, called once at package init.
45///
46/// Each ALTREP struct or trait impl emits an entry pairing the registration
47/// function pointer with its `#[no_mangle]` symbol name. The fn is declared
48/// `pub extern "C"` with `#[unsafe(no_mangle)]`, making it externally
49/// addressable from a separate compilation unit (e.g. the WASM snapshot
50/// codegen path). The fn pointer is not `unsafe` — R-thread invariants are a
51/// module-level contract, not encoded in the type (same convention as the
52/// `extern "C-unwind" fn` entries in `MX_CALL_DEFS`). The `symbol` string is
53/// consumed by the host-time WASM snapshot writer to emit
54/// `extern "C-unwind" { fn <symbol>(); }` declarations in `wasm_registry.rs`.
55#[cfg(not(target_arch = "wasm32"))]
56#[doc = " ALTREP class registration entries, called once at package init."]
#[doc = ""]
#[doc =
" Each ALTREP struct or trait impl emits an entry pairing the registration"]
#[doc =
" function pointer with its `#[no_mangle]` symbol name. The fn is declared"]
#[doc =
" `pub extern \"C\"` with `#[unsafe(no_mangle)]`, making it externally"]
#[doc =
" addressable from a separate compilation unit (e.g. the WASM snapshot"]
#[doc =
" codegen path). The fn pointer is not `unsafe` — R-thread invariants are a"]
#[doc =
" module-level contract, not encoded in the type (same convention as the"]
#[doc =
" `extern \"C-unwind\" fn` entries in `MX_CALL_DEFS`). The `symbol` string is"]
#[doc = " consumed by the host-time WASM snapshot writer to emit"]
#[doc =
" `extern \"C-unwind\" { fn <symbol>(); }` declarations in `wasm_registry.rs`."]
pub static MX_ALTREP_REGISTRATIONS:
    ::linkme::DistributedSlice<[AltrepRegistration]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_ALTREP_REGISTRATIONS"]
            static LINKME_START:
                [<[AltrepRegistration] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_ALTREP_REGISTRATIONS"]
            static LINKME_STOP:
                [<[AltrepRegistration] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_ALTREP_REGISTRATIONS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_ALTREP_REGISTRATIONS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_ALTREP_REGISTRATIONS")]
        static mut LINKME_PLEASE:
            [<[AltrepRegistration] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_ALTREP_REGISTRATIONS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_ALTREP_REGISTRATIONS",
                (&raw const LINKME_START).cast::<<[AltrepRegistration] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[AltrepRegistration] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_ALTREP_REGISTRATIONS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_ALTREP_REGISTRATIONS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeJFQYUnae,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_ALTREP_REGISTRATIONS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_ALTREP_REGISTRATIONS", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_ALTREP_REGISTRATIONS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_ALTREP_REGISTRATIONS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeJFQYUnae,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_ALTREP_REGISTRATIONS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_ALTREP_REGISTRATIONS"] #
            ! [linkme_bsd_section = "linkme_MX_ALTREP_REGISTRATIONS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_ALTREP_REGISTRATIONS as MX_ALTREP_REGISTRATIONS;#[distributed_slice]
57pub static MX_ALTREP_REGISTRATIONS: [AltrepRegistration];
58
59/// Trait dispatch entries for [`universal_query`].
60///
61/// Each `#[miniextendr] impl Trait for Type` emits an entry mapping
62/// `(concrete_tag, trait_tag)` to the trait's vtable pointer.
63#[cfg(not(target_arch = "wasm32"))]
64#[doc = " Trait dispatch entries for [`universal_query`]."]
#[doc = ""]
#[doc = " Each `#[miniextendr] impl Trait for Type` emits an entry mapping"]
#[doc = " `(concrete_tag, trait_tag)` to the trait\'s vtable pointer."]
pub static MX_TRAIT_DISPATCH: ::linkme::DistributedSlice<[TraitDispatchEntry]>
    =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_TRAIT_DISPATCH"]
            static LINKME_START:
                [<[TraitDispatchEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_TRAIT_DISPATCH"]
            static LINKME_STOP:
                [<[TraitDispatchEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_TRAIT_DISPATCH"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_TRAIT_DISPATCH"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_TRAIT_DISPATCH")]
        static mut LINKME_PLEASE:
            [<[TraitDispatchEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_TRAIT_DISPATCH")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_TRAIT_DISPATCH",
                (&raw const LINKME_START).cast::<<[TraitDispatchEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[TraitDispatchEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_TRAIT_DISPATCH {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_TRAIT_DISPATCH", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmehjtiMuFn,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_TRAIT_DISPATCH$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_TRAIT_DISPATCH", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_TRAIT_DISPATCH", $key)]
            $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_TRAIT_DISPATCH"] # !
            [linkme_macho_section =
            "__DATA,__linkmehjtiMuFn,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_TRAIT_DISPATCH$b"] # !
            [linkme_illumos_section = "set_linkme_MX_TRAIT_DISPATCH"] # !
            [linkme_bsd_section = "linkme_MX_TRAIT_DISPATCH"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_TRAIT_DISPATCH as MX_TRAIT_DISPATCH;#[distributed_slice]
65pub static MX_TRAIT_DISPATCH: [TraitDispatchEntry];
66
67/// Match-arg choices entries for R wrapper post-processing. **Host-only.**
68///
69/// Each `#[miniextendr]` function with `match_arg` params emits an entry.
70/// During `write_r_wrappers_to_file`, the placeholder in the R formal default
71/// is replaced with the actual choices from the enum's `MatchArg::CHOICES`.
72#[cfg(not(target_arch = "wasm32"))]
73#[doc =
" Match-arg choices entries for R wrapper post-processing. **Host-only.**"]
#[doc = ""]
#[doc =
" Each `#[miniextendr]` function with `match_arg` params emits an entry."]
#[doc =
" During `write_r_wrappers_to_file`, the placeholder in the R formal default"]
#[doc =
" is replaced with the actual choices from the enum\'s `MatchArg::CHOICES`."]
pub static MX_MATCH_ARG_CHOICES:
    ::linkme::DistributedSlice<[MatchArgChoicesEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_MATCH_ARG_CHOICES"]
            static LINKME_START:
                [<[MatchArgChoicesEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_MATCH_ARG_CHOICES"]
            static LINKME_STOP:
                [<[MatchArgChoicesEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_MATCH_ARG_CHOICES"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_MATCH_ARG_CHOICES"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_MATCH_ARG_CHOICES")]
        static mut LINKME_PLEASE:
            [<[MatchArgChoicesEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_MATCH_ARG_CHOICES")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_MATCH_ARG_CHOICES",
                (&raw const LINKME_START).cast::<<[MatchArgChoicesEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[MatchArgChoicesEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_MATCH_ARG_CHOICES {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_MATCH_ARG_CHOICES", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmefIX4YxkR,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_MATCH_ARG_CHOICES$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_MATCH_ARG_CHOICES", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_MATCH_ARG_CHOICES", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_MATCH_ARG_CHOICES"] # !
            [linkme_macho_section =
            "__DATA,__linkmefIX4YxkR,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_MATCH_ARG_CHOICES$b"] # !
            [linkme_illumos_section = "set_linkme_MX_MATCH_ARG_CHOICES"] # !
            [linkme_bsd_section = "linkme_MX_MATCH_ARG_CHOICES"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_MATCH_ARG_CHOICES as MX_MATCH_ARG_CHOICES;#[distributed_slice]
74pub static MX_MATCH_ARG_CHOICES: [MatchArgChoicesEntry];
75
76/// Match-arg `@param` doc entries for R wrapper post-processing. **Host-only.**
77///
78/// Each `#[miniextendr]` function with `match_arg` params that has no
79/// user-written `@param` doc emits an entry here. During
80/// `write_r_wrappers_to_file`, the placeholder in the `@param` roxygen tag
81/// is replaced with e.g. `One of "Fast", "Safe", "Debug".`
82#[cfg(not(target_arch = "wasm32"))]
83#[doc =
" Match-arg `@param` doc entries for R wrapper post-processing. **Host-only.**"]
#[doc = ""]
#[doc = " Each `#[miniextendr]` function with `match_arg` params that has no"]
#[doc = " user-written `@param` doc emits an entry here. During"]
#[doc =
" `write_r_wrappers_to_file`, the placeholder in the `@param` roxygen tag"]
#[doc = " is replaced with e.g. `One of \"Fast\", \"Safe\", \"Debug\".`"]
pub static MX_MATCH_ARG_PARAM_DOCS:
    ::linkme::DistributedSlice<[MatchArgParamDocEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_MATCH_ARG_PARAM_DOCS"]
            static LINKME_START:
                [<[MatchArgParamDocEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_MATCH_ARG_PARAM_DOCS"]
            static LINKME_STOP:
                [<[MatchArgParamDocEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_MATCH_ARG_PARAM_DOCS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_MATCH_ARG_PARAM_DOCS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_MATCH_ARG_PARAM_DOCS")]
        static mut LINKME_PLEASE:
            [<[MatchArgParamDocEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_MATCH_ARG_PARAM_DOCS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_MATCH_ARG_PARAM_DOCS",
                (&raw const LINKME_START).cast::<<[MatchArgParamDocEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[MatchArgParamDocEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_MATCH_ARG_PARAM_DOCS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_MATCH_ARG_PARAM_DOCS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeV0zVCfXB,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_MATCH_ARG_PARAM_DOCS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_MATCH_ARG_PARAM_DOCS", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_MATCH_ARG_PARAM_DOCS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_MATCH_ARG_PARAM_DOCS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeV0zVCfXB,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_MATCH_ARG_PARAM_DOCS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_MATCH_ARG_PARAM_DOCS"] #
            ! [linkme_bsd_section = "linkme_MX_MATCH_ARG_PARAM_DOCS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_MATCH_ARG_PARAM_DOCS as MX_MATCH_ARG_PARAM_DOCS;#[distributed_slice]
84pub static MX_MATCH_ARG_PARAM_DOCS: [MatchArgParamDocEntry];
85
86/// Class name entries mapping Rust type names to R-visible class names. **Host-only.**
87///
88/// Each `#[miniextendr]` impl block emits an entry. During
89/// `write_r_wrappers_to_file`, the `.__MX_CLASS_REF_*<RustName>__`
90/// placeholders other expansions write where they name the class (see
91/// `resolve_class_refs`) are replaced with the registered R class name
92/// (which may differ when `class = "Override"` is set on the impl block).
93/// Package load reads it too: [`call_defs`] leaves out the sidecar setters
94/// of a type whose entry has [`ClassNameEntry::read_only_fields`] (#2292).
95#[cfg(not(target_arch = "wasm32"))]
96#[doc =
" Class name entries mapping Rust type names to R-visible class names. **Host-only.**"]
#[doc = ""]
#[doc = " Each `#[miniextendr]` impl block emits an entry. During"]
#[doc = " `write_r_wrappers_to_file`, the `.__MX_CLASS_REF_*<RustName>__`"]
#[doc = " placeholders other expansions write where they name the class (see"]
#[doc =
" `resolve_class_refs`) are replaced with the registered R class name"]
#[doc =
" (which may differ when `class = \"Override\"` is set on the impl block)."]
#[doc =
" Package load reads it too: [`call_defs`] leaves out the sidecar setters"]
#[doc =
" of a type whose entry has [`ClassNameEntry::read_only_fields`] (#2292)."]
pub static MX_CLASS_NAMES: ::linkme::DistributedSlice<[ClassNameEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_CLASS_NAMES"]
            static LINKME_START:
                [<[ClassNameEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_CLASS_NAMES"]
            static LINKME_STOP:
                [<[ClassNameEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_CLASS_NAMES"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_CLASS_NAMES"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_CLASS_NAMES")]
        static mut LINKME_PLEASE:
            [<[ClassNameEntry] as ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_CLASS_NAMES")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_CLASS_NAMES",
                (&raw const LINKME_START).cast::<<[ClassNameEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[ClassNameEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_CLASS_NAMES {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat! ("linkme_MX_CLASS_NAMES", $key)] #
            !
            [linkme_macho_section = concat!
            ("__DATA,__linkmejXEM0NMl,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_CLASS_NAMES$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_CLASS_NAMES", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_CLASS_NAMES", $key)]
            $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_CLASS_NAMES"] # !
            [linkme_macho_section =
            "__DATA,__linkmejXEM0NMl,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_CLASS_NAMES$b"] # !
            [linkme_illumos_section = "set_linkme_MX_CLASS_NAMES"] # !
            [linkme_bsd_section = "linkme_MX_CLASS_NAMES"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_CLASS_NAMES as MX_CLASS_NAMES;#[distributed_slice]
97pub static MX_CLASS_NAMES: [ClassNameEntry];
98
99/// The R class parts of every `#[miniextendr(env|r6|s3|s4|s7|vctrs)]` impl
100/// block. **Host-only.**
101///
102/// [`collect_r_wrappers`] merges the blocks of each Rust type into one class
103/// fragment: the class is defined once and every block's members attach to it
104/// (#1776).
105#[cfg(not(target_arch = "wasm32"))]
106#[doc =
" The R class parts of every `#[miniextendr(env|r6|s3|s4|s7|vctrs)]` impl"]
#[doc = " block. **Host-only.**"]
#[doc = ""]
#[doc =
" [`collect_r_wrappers`] merges the blocks of each Rust type into one class"]
#[doc =
" fragment: the class is defined once and every block\'s members attach to it"]
#[doc = " (#1776)."]
pub static MX_CLASS_BLOCKS: ::linkme::DistributedSlice<[ClassBlockEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_CLASS_BLOCKS"]
            static LINKME_START:
                [<[ClassBlockEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_CLASS_BLOCKS"]
            static LINKME_STOP:
                [<[ClassBlockEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_CLASS_BLOCKS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_CLASS_BLOCKS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_CLASS_BLOCKS")]
        static mut LINKME_PLEASE:
            [<[ClassBlockEntry] as ::linkme::__private36::Slice>::Element; 0]
            =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_CLASS_BLOCKS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_CLASS_BLOCKS",
                (&raw const LINKME_START).cast::<<[ClassBlockEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[ClassBlockEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_CLASS_BLOCKS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat! ("linkme_MX_CLASS_BLOCKS", $key)]
            # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeCAA1ohRR,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_CLASS_BLOCKS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_CLASS_BLOCKS", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_CLASS_BLOCKS", $key)]
            $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_CLASS_BLOCKS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeCAA1ohRR,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_CLASS_BLOCKS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_CLASS_BLOCKS"] # !
            [linkme_bsd_section = "linkme_MX_CLASS_BLOCKS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_CLASS_BLOCKS as MX_CLASS_BLOCKS;#[distributed_slice]
107pub static MX_CLASS_BLOCKS: [ClassBlockEntry];
108
109/// The types whose class environment a trait impl writes into: one entry
110/// per `#[miniextendr] impl Trait for Type` whose wrappers bind the
111/// `Class$Trait` namespace. **Host-only.** [`collect_r_wrappers`] keeps a
112/// class's [`env`](ClassBlockEntry::env) part only for a type with an entry
113/// here (#2264, #2289).
114#[cfg(not(target_arch = "wasm32"))]
115#[doc =
" The types whose class environment a trait impl writes into: one entry"]
#[doc = " per `#[miniextendr] impl Trait for Type` whose wrappers bind the"]
#[doc =
" `Class$Trait` namespace. **Host-only.** [`collect_r_wrappers`] keeps a"]
#[doc =
" class\'s [`env`](ClassBlockEntry::env) part only for a type with an entry"]
#[doc = " here (#2264, #2289)."]
pub static MX_TRAIT_NAMESPACES:
    ::linkme::DistributedSlice<[TraitNamespaceEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_TRAIT_NAMESPACES"]
            static LINKME_START:
                [<[TraitNamespaceEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_TRAIT_NAMESPACES"]
            static LINKME_STOP:
                [<[TraitNamespaceEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_TRAIT_NAMESPACES"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_TRAIT_NAMESPACES"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_TRAIT_NAMESPACES")]
        static mut LINKME_PLEASE:
            [<[TraitNamespaceEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_TRAIT_NAMESPACES")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_TRAIT_NAMESPACES",
                (&raw const LINKME_START).cast::<<[TraitNamespaceEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[TraitNamespaceEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_TRAIT_NAMESPACES {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_TRAIT_NAMESPACES", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmelk5seaGz,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_TRAIT_NAMESPACES$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_TRAIT_NAMESPACES", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_TRAIT_NAMESPACES", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_TRAIT_NAMESPACES"] # !
            [linkme_macho_section =
            "__DATA,__linkmelk5seaGz,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_TRAIT_NAMESPACES$b"] # !
            [linkme_illumos_section = "set_linkme_MX_TRAIT_NAMESPACES"] # !
            [linkme_bsd_section = "linkme_MX_TRAIT_NAMESPACES"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_TRAIT_NAMESPACES as MX_TRAIT_NAMESPACES;#[distributed_slice]
116pub static MX_TRAIT_NAMESPACES: [TraitNamespaceEntry];
117
118/// S7 sidecar property documentation entries. **Host-only.**
119///
120/// Each `#[derive(ExternalPtr)] #[externalptr(s7)]` struct with `#[r_data]` fields
121/// emits one entry per public field. During `write_r_wrappers_to_file`, the
122/// `.__MX_S7_SIDECAR_PROP_DOCS_<TypeName>__` placeholder in the S7 class wrapper
123/// is replaced with the formatted `#' @prop {field} {doc}` roxygen lines.
124#[cfg(not(target_arch = "wasm32"))]
125#[doc = " S7 sidecar property documentation entries. **Host-only.**"]
#[doc = ""]
#[doc =
" Each `#[derive(ExternalPtr)] #[externalptr(s7)]` struct with `#[r_data]` fields"]
#[doc =
" emits one entry per public field. During `write_r_wrappers_to_file`, the"]
#[doc =
" `.__MX_S7_SIDECAR_PROP_DOCS_<TypeName>__` placeholder in the S7 class wrapper"]
#[doc =
" is replaced with the formatted `#\' @prop {field} {doc}` roxygen lines."]
pub static MX_S7_SIDECAR_PROPS: ::linkme::DistributedSlice<[SidecarPropEntry]>
    =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_S7_SIDECAR_PROPS"]
            static LINKME_START:
                [<[SidecarPropEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_S7_SIDECAR_PROPS"]
            static LINKME_STOP:
                [<[SidecarPropEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_S7_SIDECAR_PROPS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_S7_SIDECAR_PROPS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_S7_SIDECAR_PROPS")]
        static mut LINKME_PLEASE:
            [<[SidecarPropEntry] as ::linkme::__private36::Slice>::Element; 0]
            =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_S7_SIDECAR_PROPS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_S7_SIDECAR_PROPS",
                (&raw const LINKME_START).cast::<<[SidecarPropEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[SidecarPropEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_S7_SIDECAR_PROPS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_S7_SIDECAR_PROPS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmef0iLUGpd,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_S7_SIDECAR_PROPS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_S7_SIDECAR_PROPS", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_S7_SIDECAR_PROPS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_S7_SIDECAR_PROPS"] # !
            [linkme_macho_section =
            "__DATA,__linkmef0iLUGpd,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_S7_SIDECAR_PROPS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_S7_SIDECAR_PROPS"] # !
            [linkme_bsd_section = "linkme_MX_S7_SIDECAR_PROPS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_S7_SIDECAR_PROPS as MX_S7_SIDECAR_PROPS;#[distributed_slice]
126pub static MX_S7_SIDECAR_PROPS: [SidecarPropEntry];
127
128/// The standalone sidecar accessors of each `#[derive(ExternalPtr)]` type
129/// with public `#[r_data]` fields. **Host-only.** [`collect_r_wrappers`]
130/// writes each as exported or internal, from the type's
131/// [`ClassNameEntry::field_syntax`] (#1900).
132#[cfg(not(target_arch = "wasm32"))]
133#[doc =
" The standalone sidecar accessors of each `#[derive(ExternalPtr)]` type"]
#[doc =
" with public `#[r_data]` fields. **Host-only.** [`collect_r_wrappers`]"]
#[doc = " writes each as exported or internal, from the type\'s"]
#[doc = " [`ClassNameEntry::field_syntax`] (#1900)."]
pub static MX_SIDECAR_ACCESSORS:
    ::linkme::DistributedSlice<[SidecarAccessorsEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_SIDECAR_ACCESSORS"]
            static LINKME_START:
                [<[SidecarAccessorsEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_SIDECAR_ACCESSORS"]
            static LINKME_STOP:
                [<[SidecarAccessorsEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_SIDECAR_ACCESSORS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_SIDECAR_ACCESSORS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_SIDECAR_ACCESSORS")]
        static mut LINKME_PLEASE:
            [<[SidecarAccessorsEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_SIDECAR_ACCESSORS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_SIDECAR_ACCESSORS",
                (&raw const LINKME_START).cast::<<[SidecarAccessorsEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[SidecarAccessorsEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_SIDECAR_ACCESSORS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_SIDECAR_ACCESSORS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkme7m9xCfja,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_SIDECAR_ACCESSORS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_SIDECAR_ACCESSORS", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_SIDECAR_ACCESSORS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_SIDECAR_ACCESSORS"] # !
            [linkme_macho_section =
            "__DATA,__linkme7m9xCfja,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_SIDECAR_ACCESSORS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_SIDECAR_ACCESSORS"] # !
            [linkme_bsd_section = "linkme_MX_SIDECAR_ACCESSORS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_SIDECAR_ACCESSORS as MX_SIDECAR_ACCESSORS;#[distributed_slice]
134pub static MX_SIDECAR_ACCESSORS: [SidecarAccessorsEntry];
135
136/// The `.Call` registrations of the sidecar setters `#[derive(ExternalPtr)]`
137/// generates, one per public `#[r_data]` field R can write, each with its
138/// type. **Host-only.** [`call_defs`] registers a type's setters unless a
139/// [`ClassNameEntry`] of the type makes its fields read-only
140/// (`r_data_accessors = "read_only"`, #2292); the wasm snapshot is written
141/// from the same list.
142#[cfg(not(target_arch = "wasm32"))]
143#[doc =
" The `.Call` registrations of the sidecar setters `#[derive(ExternalPtr)]`"]
#[doc =
" generates, one per public `#[r_data]` field R can write, each with its"]
#[doc =
" type. **Host-only.** [`call_defs`] registers a type\'s setters unless a"]
#[doc = " [`ClassNameEntry`] of the type makes its fields read-only"]
#[doc =
" (`r_data_accessors = \"read_only\"`, #2292); the wasm snapshot is written"]
#[doc = " from the same list."]
pub static MX_SIDECAR_SETTERS:
    ::linkme::DistributedSlice<[SidecarSetterEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_SIDECAR_SETTERS"]
            static LINKME_START:
                [<[SidecarSetterEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_SIDECAR_SETTERS"]
            static LINKME_STOP:
                [<[SidecarSetterEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_SIDECAR_SETTERS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_SIDECAR_SETTERS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_SIDECAR_SETTERS")]
        static mut LINKME_PLEASE:
            [<[SidecarSetterEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_SIDECAR_SETTERS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_SIDECAR_SETTERS",
                (&raw const LINKME_START).cast::<<[SidecarSetterEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[SidecarSetterEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_SIDECAR_SETTERS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_SIDECAR_SETTERS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeBNKAGdoy,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_SIDECAR_SETTERS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_SIDECAR_SETTERS", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_SIDECAR_SETTERS", $key)]
            $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_SIDECAR_SETTERS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeBNKAGdoy,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_SIDECAR_SETTERS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_SIDECAR_SETTERS"] # !
            [linkme_bsd_section = "linkme_MX_SIDECAR_SETTERS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_SIDECAR_SETTERS as MX_SIDECAR_SETTERS;#[distributed_slice]
144pub static MX_SIDECAR_SETTERS: [SidecarSetterEntry];
145
146/// The `all.equal()` methods `#[derive(AllEqual)]` generates (#2149).
147/// **Host-only.** [`collect_r_wrappers`] names and registers each for the
148/// type's R class, which the type's impl block gives in its
149/// [`ClassNameEntry`]: the derive sits on the struct, a separate expansion.
150#[cfg(not(target_arch = "wasm32"))]
151#[doc = " The `all.equal()` methods `#[derive(AllEqual)]` generates (#2149)."]
#[doc =
" **Host-only.** [`collect_r_wrappers`] names and registers each for the"]
#[doc = " type\'s R class, which the type\'s impl block gives in its"]
#[doc =
" [`ClassNameEntry`]: the derive sits on the struct, a separate expansion."]
pub static MX_ALL_EQUAL: ::linkme::DistributedSlice<[AllEqualEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_ALL_EQUAL"]
            static LINKME_START:
                [<[AllEqualEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_ALL_EQUAL"]
            static LINKME_STOP:
                [<[AllEqualEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_ALL_EQUAL"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_ALL_EQUAL"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_ALL_EQUAL")]
        static mut LINKME_PLEASE:
            [<[AllEqualEntry] as ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_ALL_EQUAL")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_ALL_EQUAL",
                (&raw const LINKME_START).cast::<<[AllEqualEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[AllEqualEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_ALL_EQUAL {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = concat! ("linkme_MX_ALL_EQUAL", $key)]
            # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeHq940RQF,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_ALL_EQUAL$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_ALL_EQUAL", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_ALL_EQUAL", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_ALL_EQUAL"] # !
            [linkme_macho_section =
            "__DATA,__linkmeHq940RQF,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_ALL_EQUAL$b"] # !
            [linkme_illumos_section = "set_linkme_MX_ALL_EQUAL"] # !
            [linkme_bsd_section = "linkme_MX_ALL_EQUAL"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_ALL_EQUAL as MX_ALL_EQUAL;#[distributed_slice]
152pub static MX_ALL_EQUAL: [AllEqualEntry];
153
154/// The `pkg::name` items of every `reexport!` (#1910). **Host-only.**
155/// [`collect_r_wrappers`] writes roxygen2's re-export block for each
156/// `pkg::name` once, however many items name it, and
157/// [`write_r_wrappers_to_file`] refuses a name re-exported from two packages
158/// or bound by the package's own wrappers or hand-written R files
159/// (`reexport_conflicts`).
160#[cfg(not(target_arch = "wasm32"))]
161#[doc = " The `pkg::name` items of every `reexport!` (#1910). **Host-only.**"]
#[doc = " [`collect_r_wrappers`] writes roxygen2\'s re-export block for each"]
#[doc = " `pkg::name` once, however many items name it, and"]
#[doc =
" [`write_r_wrappers_to_file`] refuses a name re-exported from two packages"]
#[doc = " or bound by the package\'s own wrappers or hand-written R files"]
#[doc = " (`reexport_conflicts`)."]
pub static MX_REEXPORTS: ::linkme::DistributedSlice<[ReexportEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_REEXPORTS"]
            static LINKME_START:
                [<[ReexportEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_REEXPORTS"]
            static LINKME_STOP:
                [<[ReexportEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_REEXPORTS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_REEXPORTS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_REEXPORTS")]
        static mut LINKME_PLEASE:
            [<[ReexportEntry] as ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_REEXPORTS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_REEXPORTS",
                (&raw const LINKME_START).cast::<<[ReexportEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[ReexportEntry] as
                    ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_REEXPORTS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = concat! ("linkme_MX_REEXPORTS", $key)]
            # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmeZ89u477l,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_REEXPORTS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_REEXPORTS", $key)] # !
            [linkme_bsd_section = concat! ("linkme_MX_REEXPORTS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_REEXPORTS"] # !
            [linkme_macho_section =
            "__DATA,__linkmeZ89u477l,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_REEXPORTS$b"] # !
            [linkme_illumos_section = "set_linkme_MX_REEXPORTS"] # !
            [linkme_bsd_section = "linkme_MX_REEXPORTS"] $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_REEXPORTS as MX_REEXPORTS;#[distributed_slice]
162pub static MX_REEXPORTS: [ReexportEntry];
163
164/// The package crate's `conversion_error_class`. **Host-only.**
165///
166/// `miniextendr_init!` emits one entry, with the classes it reads from the
167/// crate's `[package.metadata.miniextendr]` (empty when unset). During
168/// `write_r_wrappers_to_file` it becomes `.miniextendr_conversion_error_class`,
169/// the classes `.miniextendr_arg_error` gives every R-side argument error, so
170/// they match the ones the macro emits into the Rust conversion arms (#1591).
171#[cfg(not(target_arch = "wasm32"))]
172#[doc = " The package crate\'s `conversion_error_class`. **Host-only.**"]
#[doc = ""]
#[doc =
" `miniextendr_init!` emits one entry, with the classes it reads from the"]
#[doc =
" crate\'s `[package.metadata.miniextendr]` (empty when unset). During"]
#[doc =
" `write_r_wrappers_to_file` it becomes `.miniextendr_conversion_error_class`,"]
#[doc =
" the classes `.miniextendr_arg_error` gives every R-side argument error, so"]
#[doc =
" they match the ones the macro emits into the Rust conversion arms (#1591)."]
pub static MX_CONVERSION_ERROR_CLASS:
    ::linkme::DistributedSlice<[ConversionErrorClassEntry]> =
    {
        unsafe extern "Rust" {
            #[link_name = "__start_linkme_MX_CONVERSION_ERROR_CLASS"]
            static LINKME_START:
                [<[ConversionErrorClassEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__stop_linkme_MX_CONVERSION_ERROR_CLASS"]
            static LINKME_STOP:
                [<[ConversionErrorClassEntry] as
                ::linkme::__private36::Slice>::Element; 0];
            #[link_name = "__start_linkm2_MX_CONVERSION_ERROR_CLASS"]
            static DUPCHECK_START: ();
            #[link_name = "__stop_linkm2_MX_CONVERSION_ERROR_CLASS"]
            static DUPCHECK_STOP: ();
        }
        #[used]
        #[unsafe(link_section = "linkme_MX_CONVERSION_ERROR_CLASS")]
        static mut LINKME_PLEASE:
            [<[ConversionErrorClassEntry] as
            ::linkme::__private36::Slice>::Element; 0] =
            [];
        #[used]
        #[unsafe(link_section = "linkm2_MX_CONVERSION_ERROR_CLASS")]
        static DUPCHECK: ::linkme::__private36::isize = 1;
        unsafe {
            ::linkme::DistributedSlice::private_new("MX_CONVERSION_ERROR_CLASS",
                (&raw const LINKME_START).cast::<<[ConversionErrorClassEntry]
                    as ::linkme::__private36::Slice>::Element>(),
                (&raw const LINKME_STOP).cast::<<[ConversionErrorClassEntry]
                    as ::linkme::__private36::Slice>::Element>(),
                (&raw const DUPCHECK_START).cast::<::linkme::__private36::isize>(),
                (&raw const DUPCHECK_STOP).cast::<::linkme::__private36::isize>())
        }
    };
#[doc(hidden)]
#[macro_export]
macro_rules! _linkme_macro_MX_CONVERSION_ERROR_CLASS {
    (# ! [linkme_macro = $macro : path] # ! [linkme_sort_key = $key : tt]
    $item : item) =>
    {
        $macro !
        {
            # !
            [linkme_linux_section = concat!
            ("linkme_MX_CONVERSION_ERROR_CLASS", $key)] # !
            [linkme_macho_section = concat!
            ("__DATA,__linkmesGGwUYY5,regular,no_dead_strip", $key)] # !
            [linkme_windows_section = concat!
            (".linkme_MX_CONVERSION_ERROR_CLASS$b", $key)] # !
            [linkme_illumos_section = concat!
            ("set_linkme_MX_CONVERSION_ERROR_CLASS", $key)] # !
            [linkme_bsd_section = concat!
            ("linkme_MX_CONVERSION_ERROR_CLASS", $key)] $item
        }
    }; (# ! [linkme_macro = $macro : path] $item : item) =>
    {
        $macro !
        {
            # ! [linkme_linux_section = "linkme_MX_CONVERSION_ERROR_CLASS"] #
            !
            [linkme_macho_section =
            "__DATA,__linkmesGGwUYY5,regular,no_dead_strip"] # !
            [linkme_windows_section = ".linkme_MX_CONVERSION_ERROR_CLASS$b"] #
            !
            [linkme_illumos_section = "set_linkme_MX_CONVERSION_ERROR_CLASS"]
            # ! [linkme_bsd_section = "linkme_MX_CONVERSION_ERROR_CLASS"]
            $item
        }
    };
    (# ! [linkme_linux_section = $linux_section : expr] # !
    [linkme_macho_section = $macho_section : expr] # !
    [linkme_windows_section = $windows_section : expr] # !
    [linkme_illumos_section = $illumos_section : expr] # !
    [linkme_bsd_section = $bsd_section : expr] $item : item) =>
    {
        #[used]
        #[cfg_attr(any(target_os = "none", target_os = "linux", target_os =
        "android", target_os = "fuchsia", target_os = "psp"), unsafe
        (link_section = $linux_section))]
        #[cfg_attr(any(target_os = "macos", target_os = "ios", target_os =
        "tvos"), unsafe (link_section = $macho_section))]
        #[cfg_attr(any(target_os = "uefi", target_os = "windows"), unsafe
        (link_section = $windows_section))]
        #[cfg_attr(target_os = "illumos", unsafe
        (link_section = $illumos_section))]
        #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), unsafe
        (link_section = $bsd_section))] $item
    };
}
#[doc(hidden)]
pub use _linkme_macro_MX_CONVERSION_ERROR_CLASS as MX_CONVERSION_ERROR_CLASS;#[distributed_slice]
173pub static MX_CONVERSION_ERROR_CLASS: [ConversionErrorClassEntry];
174
175// endregion
176
177// region: Runtime slice access (cfg-uniform)
178
179/// The `.Call` routines the package registers with R.
180///
181/// Native: [`MX_CALL_DEFS`] and the [`MX_SIDECAR_SETTERS`] of every type
182/// whose fields R can write (#2292). The wasm snapshot is written from this
183/// list. wasm32: that snapshot, read from a `OnceLock` populated by
184/// `install_wasm_runtime_slices`.
185pub fn call_defs() -> Vec<R_CallMethodDef> {
186    #[cfg(not(target_arch = "wasm32"))]
187    {
188        registered_call_defs(&MX_CALL_DEFS, &MX_SIDECAR_SETTERS, &MX_CLASS_NAMES)
189    }
190    #[cfg(target_arch = "wasm32")]
191    {
192        wasm_runtime::call_defs().to_vec()
193    }
194}
195
196/// `call_defs` and the setters of `setters` whose type keeps its fields
197/// writable from R: a type with an impl block that makes them read-only
198/// (`r_data_accessors = "read_only"`, [`read_only_fields`]) keeps its setter
199/// functions in the binary, unregistered (#2292). `package_init` turns off
200/// dynamic symbol lookup, so R can't reach a routine left out here.
201#[cfg(not(target_arch = "wasm32"))]
202fn registered_call_defs(
203    call_defs: &[R_CallMethodDef],
204    setters: &[SidecarSetterEntry],
205    classes: &[ClassNameEntry],
206) -> Vec<R_CallMethodDef> {
207    let mut defs = call_defs.to_vec();
208    defs.extend(
209        setters
210            .iter()
211            .filter(|setter| !read_only_fields(classes, setter.rust_type))
212            .map(|setter| setter.def),
213    );
214    defs
215}
216
217/// Whether an impl block of `rust_type` makes its fields read-only from R
218/// (`r_data_accessors = "read_only"`, #2268). Its standalone setters are
219/// then not written ([`sidecar_accessor_fragments`]) and its setter
220/// routines not registered ([`registered_call_defs`], #2292).
221#[cfg(not(target_arch = "wasm32"))]
222fn read_only_fields(classes: &[ClassNameEntry], rust_type: &str) -> bool {
223    classes
224        .iter()
225        .any(|class| class.rust_type == rust_type && class.read_only_fields)
226}
227
228#[inline]
229pub(crate) fn altrep_regs() -> &'static [AltrepRegistration] {
230    #[cfg(not(target_arch = "wasm32"))]
231    {
232        &MX_ALTREP_REGISTRATIONS
233    }
234    #[cfg(target_arch = "wasm32")]
235    {
236        wasm_runtime::altrep_regs()
237    }
238}
239
240#[inline]
241pub(crate) fn trait_dispatch() -> &'static [TraitDispatchEntry] {
242    #[cfg(not(target_arch = "wasm32"))]
243    {
244        &MX_TRAIT_DISPATCH
245    }
246    #[cfg(target_arch = "wasm32")]
247    {
248        wasm_runtime::trait_dispatch()
249    }
250}
251
252/// The package crate's `conversion_error_class` (empty when it sets none).
253///
254/// Native: the [`MX_CONVERSION_ERROR_CLASS`] entry `miniextendr_init!`
255/// registers (a package has one). wasm32: the copy the `wasm_registry.rs`
256/// snapshot carries, installed by `install_wasm_runtime_slices`.
257#[inline]
258pub(crate) fn conversion_error_class() -> &'static [&'static str] {
259    #[cfg(not(target_arch = "wasm32"))]
260    {
261        MX_CONVERSION_ERROR_CLASS
262            .first()
263            .map_or(&[][..], |entry| entry.classes)
264    }
265    #[cfg(target_arch = "wasm32")]
266    {
267        wasm_runtime::conversion_error_class()
268    }
269}
270
271#[cfg(target_arch = "wasm32")]
272mod wasm_runtime {
273    use super::{AltrepRegistration, R_CallMethodDef, TraitDispatchEntry};
274    use std::sync::OnceLock;
275
276    static CALL_DEFS: OnceLock<&'static [R_CallMethodDef]> = OnceLock::new();
277    static ALTREP_REGS: OnceLock<&'static [AltrepRegistration]> = OnceLock::new();
278    static TRAIT_DISPATCH: OnceLock<&'static [TraitDispatchEntry]> = OnceLock::new();
279    static CONVERSION_ERROR_CLASS: OnceLock<&'static [&'static str]> = OnceLock::new();
280
281    pub(super) fn install(
282        c: &'static [R_CallMethodDef],
283        a: &'static [AltrepRegistration],
284        t: &'static [TraitDispatchEntry],
285        k: &'static [&'static str],
286    ) {
287        // Double-install is a programmer error but not memory-unsafe — silently
288        // ignore so a second `R_init_*` (e.g. dyn.unload + dyn.load) doesn't
289        // panic. The first install wins.
290        let _ = CALL_DEFS.set(c);
291        let _ = ALTREP_REGS.set(a);
292        let _ = TRAIT_DISPATCH.set(t);
293        let _ = CONVERSION_ERROR_CLASS.set(k);
294    }
295
296    pub(super) fn call_defs() -> &'static [R_CallMethodDef] {
297        CALL_DEFS.get().copied().unwrap_or(&[])
298    }
299    pub(super) fn altrep_regs() -> &'static [AltrepRegistration] {
300        ALTREP_REGS.get().copied().unwrap_or(&[])
301    }
302    pub(super) fn trait_dispatch() -> &'static [TraitDispatchEntry] {
303        TRAIT_DISPATCH.get().copied().unwrap_or(&[])
304    }
305    pub(super) fn conversion_error_class() -> &'static [&'static str] {
306        CONVERSION_ERROR_CLASS.get().copied().unwrap_or(&[])
307    }
308}
309
310/// Install the runtime-critical slice data on `wasm32-*`.
311///
312/// Called from the user crate's `R_init_<pkg>` (generated by
313/// `miniextendr_init!`) before `package_init` runs. The slices are typically
314/// the `MX_*_WASM` constants emitted into `<crate>/src/rust/<crate>/src/wasm_registry.rs`
315/// by [`crate::wasm_registry_writer::write_wasm_registry_to_file`].
316/// `conversion_error_class` is the crate's `conversion_error_class` from the
317/// same snapshot, which the raising guards give an `arg_error!` (#1768).
318///
319/// Calling more than once is harmless — the first install wins (the assumption
320/// being all calls supply the same data; second-install is treated as a
321/// re-init from `dyn.unload` + `dyn.load`).
322#[cfg(target_arch = "wasm32")]
323pub fn install_wasm_runtime_slices(
324    call_defs: &'static [R_CallMethodDef],
325    altrep_regs: &'static [AltrepRegistration],
326    trait_dispatch: &'static [TraitDispatchEntry],
327    conversion_error_class: &'static [&'static str],
328) {
329    wasm_runtime::install(
330        call_defs,
331        altrep_regs,
332        trait_dispatch,
333        conversion_error_class,
334    );
335}
336
337// endregion
338
339// region: Entry Types
340
341/// Ordering priority for R wrapper code fragments.
342///
343/// Variant declaration order = output order. The order matters because
344/// R evaluates the wrapper file top-to-bottom, so dependencies must come first:
345/// sidecar accessors before class definitions, classes before functions, etc.
346#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RWrapperPriority {
}
#[automatically_derived]impl ::core::clone::Clone for RWrapperPriority {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RWrapperPriority { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    RWrapperPriority {
}
#[automatically_derived]impl ::core::cmp::PartialEq for RWrapperPriority {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for RWrapperPriority { }Eq, #[automatically_derived]impl ::core::cmp::PartialOrd for RWrapperPriority {
    #[inline]
    fn partial_cmp(&self, other: &Self)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]impl ::core::cmp::Ord for RWrapperPriority {
    #[inline]
    fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
            &::core::intrinsics::discriminant_value(other))
    }
}Ord)]
347pub enum RWrapperPriority {
348    /// `#[r_data]` getters/setters — must come before class definitions.
349    Sidecar,
350    /// Class definitions (impl blocks: env/R6/S3/S4/S7).
351    Class,
352    /// Standalone `#[miniextendr]` functions.
353    Function,
354    /// Trait impl wrappers (`impl Trait for Type`).
355    TraitImpl,
356    /// Vctrs S3 method wrappers (`#[derive(Vctrs)]`).
357    Vctrs,
358    /// The re-export blocks of `reexport!` (#1910). They bind nothing, so
359    /// their place is free; last keeps them together.
360    Reexport,
361}
362
363/// R wrapper code with priority for ordering.
364pub struct RWrapperEntry {
365    /// Ordering priority (lower = earlier in output file).
366    pub priority: RWrapperPriority,
367    /// R source code fragment.
368    pub content: &'static str,
369    /// Source file path (from `file!()`). Used to derive a default `@rdname`
370    /// for standalone functions that don't have an explicit one, so that all
371    /// functions from the same source file share a single .Rd page.
372    pub source_file: &'static str,
373    /// Line the generating item starts on in `source_file`. Together with the
374    /// file it fixes the emission order within a priority group at source
375    /// order, so the blocks merged onto a shared `.Rd` page read as written
376    /// rather than in link order (#1476).
377    pub source_line: u32,
378}
379
380// SAFETY: All fields are immutable and valid for 'static lifetime.
381unsafe impl Sync for RWrapperEntry {}
382
383/// The package crate's `conversion_error_class`, registered by
384/// `miniextendr_init!` in [`MX_CONVERSION_ERROR_CLASS`].
385pub struct ConversionErrorClassEntry {
386    /// The classes, most specific first; empty when the crate sets none.
387    pub classes: &'static [&'static str],
388}
389
390/// Entry for replacing match_arg placeholder defaults with actual choices.
391pub struct MatchArgChoicesEntry {
392    /// Placeholder string in the R formal default, e.g. `".__MX_MATCH_ARG_CHOICES_mode__"`.
393    pub placeholder: &'static str,
394    /// The parameter type's `MatchArg::CHOICES`, unescaped.
395    pub choices: &'static [&'static str],
396    /// User-supplied `default = "..."` value (unquoted, e.g. `"zstd"`), or `""`
397    /// if the user did not supply one. When non-empty, the write-time pass
398    /// moves this choice to the front of the formal ([`match_arg_formal`]),
399    /// so `.miniextendr_match_arg()` picks it for `NULL` and for the omitted
400    /// argument.
401    pub preferred_default: &'static str,
402    /// Placeholder for the trailing `aliases =` (and `listed =`) arguments
403    /// of the parameter's `.miniextendr_match_arg` /
404    /// `.miniextendr_match_arg_several` call, e.g.
405    /// `".__MX_MATCH_ARG_ALIASES_run_mode__"`. The writer replaces `, ` and
406    /// it with [`match_arg_aliases_arg`]: nothing for a type without aliases.
407    pub aliases_placeholder: &'static str,
408    /// The parameter type's `MatchArg::ALIASES`, unescaped.
409    pub aliases: &'static [crate::match_arg::MatchArgAlias],
410}
411
412/// Entry for replacing match_arg `@param` doc placeholders with human-readable
413/// choice descriptions.
414pub struct MatchArgParamDocEntry {
415    /// Placeholder string in the `@param` roxygen tag, e.g.
416    /// `".__MX_MATCH_ARG_PARAM_DOC_match_arg_set_mode_mode__"`.
417    pub placeholder: &'static str,
418    /// `true` for `several_ok` params (emits "One or more of …");
419    /// `false` for plain `match_arg` (emits "One of …").
420    pub several_ok: bool,
421    /// Text after the rendered choice list, before the closing period:
422    /// `""` for a plain param, `", or NULL for no choice"` for an `Option<T>`
423    /// one (#1473), an omission note for `Missing<T>` (#1551). Composed by
424    /// the macro from the parameter type.
425    pub suffix: &'static str,
426    /// Function that returns the choices as a comma-separated quoted string,
427    /// e.g. `"\"Fast\", \"Safe\", \"Debug\""`.
428    pub choices_str: fn() -> String,
429}
430
431// SAFETY: function pointer, bools, and &'static str are Send+Sync.
432unsafe impl Sync for MatchArgParamDocEntry {}
433
434/// Entry mapping a Rust type name to its R-visible class name and class system.
435///
436/// Emitted by every `#[miniextendr(env|r6|s3|s4|s7|vctrs)]` impl block.
437/// Used by the resolver in `write_r_wrappers_to_file` to replace
438/// `.__MX_CLASS_REF_*<RustName>__` placeholders with the actual R class name.
439pub struct ClassNameEntry {
440    /// Rust type identifier, e.g. `"S7Shape"`.
441    pub rust_type: &'static str,
442    /// R-visible class name. Equals `rust_type` unless `class = "Override"` was
443    /// set on the impl block, in which case it is the override string.
444    pub r_class_name: &'static str,
445    /// Class system tag: `"env"` | `"r6"` | `"s3"` | `"s4"` | `"s7"` | `"vctrs"`.
446    pub class_system: &'static str,
447    /// The impl block gives the class `$` / `[[` field syntax for the type's
448    /// `#[r_data]` fields (`s3(r_data_accessors)`, `s4(...)`, `env(...)`).
449    /// The type's standalone `Type_get_f()` / `Type_set_f()` are then
450    /// written without an export or a page ([`SidecarAccessorsEntry`],
451    /// #1900).
452    pub field_syntax: bool,
453    /// The field syntax is the read-only form, `r_data_accessors =
454    /// "read_only"` (#2268): every field is read-only from R, so the
455    /// standalone setters are not written either
456    /// ([`SidecarAccessorsEntry::internal_read_only`]), and the setter
457    /// routines are not registered ([`MX_SIDECAR_SETTERS`], #2292).
458    pub read_only_fields: bool,
459}
460
461// SAFETY: &'static str fields and bools — immutable and valid for program lifetime.
462unsafe impl Sync for ClassNameEntry {}
463
464/// The line of [`ClassBlockEntry::head`] where the class's roxygen block
465/// takes the [`ClassBlockEntry::class_doc_lines`] of every impl block of the
466/// type. Spelled the same as `miniextendr_macros`'s `CLASS_DOC_LINES_MARKER`.
467pub const CLASS_DOC_LINES_MARKER: &str = ".__MX_CLASS_DOC_LINES__";
468
469/// The line of [`ClassBlockEntry::head`] where the class's roxygen block
470/// takes the [`ClassBlockEntry::class_docs`] of every impl block of the
471/// type, the defining block's first. Spelled the same as
472/// `miniextendr_macros`'s `CLASS_DOCS_MARKER`.
473pub const CLASS_DOCS_MARKER: &str = ".__MX_CLASS_DOCS__";
474
475/// Opens a class's roxygen block, in [`ClassBlockEntry::head`], that only
476/// carries the impl docs: the block of an S3 or vctrs class without a
477/// constructor that the package names and builds itself (`class = "..."`).
478/// The writer writes the block, up to its closing `NULL`, only when the
479/// type's [`class_docs`](ClassBlockEntry::class_docs) or
480/// [`class_doc_lines`](ClassBlockEntry::class_doc_lines) say something beyond
481/// the page and export tags, so a readers-only impl adds no page (#1918), or
482/// when it writes the class environment ([`ClassBlockEntry::env`]), whose
483/// block goes on the class's page (#2289).
484/// Spelled the same as `miniextendr_macros`'s `CLASS_DOCS_ONLY_MARKER`.
485pub const CLASS_DOCS_ONLY_MARKER: &str = ".__MX_CLASS_DOCS_ONLY__";
486
487/// Opens a generated line of a class's roxygen block, in
488/// [`ClassBlockEntry::head`] or [`ClassBlockEntry::class_doc_lines`], that a
489/// doc tag on another impl block of the type replaces: `@title`, `@name`,
490/// `@rdname`, `@export`, a constructor's `@param` or an R6 `@field`. The
491/// writer drops the line when another block's
492/// [`class_docs`](ClassBlockEntry::class_docs) have the tag (for `@param` and
493/// `@field`, for the same name), and otherwise writes it without the prefix.
494/// Spelled the same as `miniextendr_macros`'s `CLASS_DEFAULT_PREFIX`.
495pub const CLASS_DEFAULT_PREFIX: &str = ".__MX_CLASS_DEFAULT__";
496
497/// Generated member page/parameter/prose defaults. The class assembler resolves
498/// these against the defining impl's topic, preserving explicit member tags.
499/// Spelled the same as the proc-macro's `CLASS_MEMBER_DEFAULT_PREFIX`.
500pub const CLASS_MEMBER_DEFAULT_PREFIX: &str = ".__MX_CLASS_MEMBER_DEFAULT__";
501
502/// One `#[miniextendr]` impl block's share of its Rust type's R class (#1776).
503///
504/// A type's methods may be split over several impl blocks. Each block
505/// registers its R wrapper in parts, and [`collect_r_wrappers`] writes one
506/// class per type: the defining block's [`head`](Self::head), every block's
507/// [`members`](Self::members) in source order, then the defining block's
508/// [`env`](Self::env) when something lands in it and its
509/// [`tail`](Self::tail). The defining block is the one with a
510/// [`defines`](Self::defines) entry (at most one block may have any), else
511/// the first in source order. The class's roxygen block has the
512/// [`class_docs`](Self::class_docs) of every block, the defining block's
513/// first. Every part is R source, framed by the newline the macro's raw
514/// string literal adds at each end.
515pub struct ClassBlockEntry {
516    /// Rust type identifier as written in the impl, e.g. `"Counter"`.
517    pub rust_type: &'static str,
518    /// The type's `core::any::type_name`, which tells apart two types that
519    /// share an identifier. The blocks of one type are merged by it.
520    pub type_path: fn() -> &'static str,
521    /// R-visible class name (`class = "..."`, else the type's identifier).
522    pub r_class_name: &'static str,
523    /// Source file of the impl block (`file!()`).
524    pub source_file: &'static str,
525    /// Line of the impl's type in `source_file`.
526    pub source_line: u32,
527    /// Column of the impl's type, for the `# Generated from` header.
528    pub source_column: u32,
529    /// The class-level settings, rendered: class system and its options,
530    /// `class = "..."`, `internal` / `noexport`, and the `@noRd` /
531    /// `@keywords internal` tags. They shape every block's members, so all
532    /// blocks of a type must have the same.
533    pub settings: &'static str,
534    /// The Rust name of the block's class constructor, `""` when it has
535    /// none: the method marked `#[miniextendr(<system>(constructor))]`, else a
536    /// receiver-less `new` returning `Self`, else
537    /// ([`constructor_inferred`](Self::constructor_inferred)) the block's one
538    /// [candidate](Self::constructor_candidates).
539    pub constructor: &'static str,
540    /// Whether [`constructor`](Self::constructor) was inferred: the block
541    /// declares none and has one candidate. The type's constructor is then
542    /// decided across its impl blocks when [`collect_r_wrappers`] merges them.
543    pub constructor_inferred: bool,
544    /// The Rust names of the block's receiver-less methods returning `Self`
545    /// other than a declared constructor: the methods that could be the
546    /// constructor of a type that declares none.
547    pub constructor_candidates: &'static [&'static str],
548    /// The block as it reads when another impl block of the type declares
549    /// the constructor: present when the block infers one, which there stays
550    /// a static method.
551    pub demoted: Option<&'static ClassBlockEntry>,
552    /// What this block has that only the defining block may: `"a
553    /// constructor"` (or `` "the inferred constructor `name`" ``), `"S7
554    /// properties"`, `"the field fallback"` (`s3(r_data_accessors, fallback
555    /// = ...)`, whose `.Call` entry the block emits and whose field methods
556    /// call it).
557    pub defines: &'static [&'static str],
558    /// The class definition as this block would write it: the class's
559    /// roxygen block (with the [`CLASS_DOCS_MARKER`] and
560    /// [`CLASS_DOC_LINES_MARKER`] lines, and [`CLASS_DEFAULT_PREFIX`]
561    /// lines), the class object, the constructor, and the class-level
562    /// helpers.
563    pub head: &'static str,
564    /// The block's doc comment as roxygen lines (with the constructor's for
565    /// S3 and vctrs, whose class block is the constructor's). The class's
566    /// roxygen block has every block's, the defining block's first; a tag
567    /// repeated exactly is written once, and two blocks giving the class
568    /// different `@title`s, or a page other than the defining block's
569    /// (`@name`, `@rdname`), are refused.
570    pub class_docs: &'static str,
571    /// Roxygen lines this block's members add to the class's roxygen block,
572    /// such as an R6 active binding's `@field` or a lifecycle import.
573    pub class_doc_lines: &'static str,
574    /// The block's members: its methods, static methods and coercions.
575    pub members: &'static str,
576    /// Names the members bind in the class's own namespaces (`$name` of an
577    /// env class or of an R6 generator, R6 members, S4 and S7 method
578    /// registrations), for the check that two blocks don't bind the same one.
579    /// Top-level functions are left to the duplicate-definition scan of the
580    /// written file.
581    pub member_names: &'static [&'static str],
582    /// The class environment, `Class <- new.env(...)` with its roxygen
583    /// block, when only the trait namespaces `Class$Trait` can land in it:
584    /// an S3 class without a constructor, and a vctrs class. Empty for the
585    /// other class systems; an S3 class with a constructor has its
586    /// environment, which holds `Class$new()`, in the [`tail`](Self::tail).
587    /// Written after the members, before the tail, only when a trait impl
588    /// writes into it ([`MX_TRAIT_NAMESPACES`]), so a class exports no empty
589    /// environment (#2264, #2289).
590    pub env: &'static str,
591    /// What follows every block's members, such as R6's `$lock()`.
592    pub tail: &'static str,
593}
594
595// SAFETY: &'static str fields, a fn pointer, integers and a reference to
596// another such entry — immutable and valid for program lifetime.
597unsafe impl Sync for ClassBlockEntry {}
598
599/// A trait impl that writes into its type's class environment: the
600/// `Class$Trait` namespace an Env, S3, vctrs or R6 trait impl binds for its
601/// static methods and consts (and an Env or R6 one for its instance methods
602/// too). Registered in [`MX_TRAIT_NAMESPACES`] by
603/// `#[miniextendr] impl Trait for Type`, a separate expansion from the
604/// type's impl blocks, which can't see it: the wrapper writer keeps the
605/// type's [`ClassBlockEntry::env`] for it (#2264, #2289).
606pub struct TraitNamespaceEntry {
607    /// The implementing type's `core::any::type_name`, matched against
608    /// [`ClassBlockEntry::type_path`].
609    pub type_path: fn() -> &'static str,
610}
611
612/// Implemented by `#[miniextendr]` for each type with an impl block that
613/// declares its class constructor (`#[miniextendr(<system>(constructor))]`,
614/// or a receiver-less `new` returning `Self`). `Block` is a type private to that
615/// impl block, so two such blocks don't conflict here; the wrapper writer
616/// refuses them ([`merge_class_blocks`]).
617///
618/// An impl block with several methods that could be the constructor and
619/// none declared requires it ([`require_class_constructor`]): the type then
620/// compiles only when another of its impl blocks declares the constructor.
621#[doc(hidden)]
622#[diagnostic::on_unimplemented(
623    message = "`{Self}` has several methods that could be its constructor, and none is declared",
624    label = "this method returns `Self` and takes no receiver, like another method of `{Self}`",
625    note = "mark the constructor with the class system's `constructor` option, e.g. \
626            `#[miniextendr(r6(constructor))]`, or name it `new`; the other methods stay static \
627            factory methods"
628)]
629pub trait ClassConstructor<Block> {}
630
631/// Compiles only when `T` has an impl block that declares its class
632/// constructor ([`ClassConstructor`]). Never called.
633#[doc(hidden)]
634pub const fn require_class_constructor<T: ?Sized + ClassConstructor<Block>, Block>() {}
635
636/// The standalone R accessors `#[derive(ExternalPtr)]` generates for a
637/// type's public `#[r_data]` fields, `Type_get_f(x)` / `Type_set_f(x,
638/// value)`, in three renderings: exported on a "Type Sidecar Accessors" page,
639/// internal (`@noRd`, no export), or internal without the setters.
640/// [`collect_r_wrappers`] writes an internal one for a type whose class has
641/// field syntax ([`ClassNameEntry::field_syntax`]): the class's `$` / `[[`
642/// are its R interface to the fields there, and the setters would write in
643/// place through every copy (#1900); the one without setters when that
644/// syntax is read-only ([`ClassNameEntry::read_only_fields`], #2268). The
645/// derive can't see the impl's option, so it emits all three. The internal
646/// renderings also carry the field helpers that those methods call. Written
647/// with the sidecar fragments.
648pub struct SidecarAccessorsEntry {
649    /// Rust type identifier, matched against [`ClassNameEntry::rust_type`].
650    pub rust_type: &'static str,
651    /// The page and the exported accessors.
652    pub exported: &'static str,
653    /// The same accessors with `@noRd` and no export, plus field-syntax helpers.
654    pub internal: &'static str,
655    /// [`Self::internal`] without the setters.
656    pub internal_read_only: &'static str,
657    /// Source file of the derive (`file!()`), for the fragment order.
658    pub source_file: &'static str,
659    /// Line of the derived type in `source_file`.
660    pub source_line: u32,
661}
662
663// SAFETY: &'static str fields and a u32 — immutable and valid for program lifetime.
664unsafe impl Sync for SidecarAccessorsEntry {}
665
666/// The `.Call` registration of one sidecar setter,
667/// `C_<crate>__mx_rdata_set_<Type>_<field>` ([`MX_SIDECAR_SETTERS`]). The
668/// derive can't see the impl's `r_data_accessors = "read_only"`, a separate
669/// expansion, so it registers the setter with its type, and [`call_defs`]
670/// leaves it out for a type whose fields are read-only (#2292).
671pub struct SidecarSetterEntry {
672    /// Rust type identifier, matched against [`ClassNameEntry::rust_type`].
673    pub rust_type: &'static str,
674    /// The setter's registration.
675    pub def: R_CallMethodDef,
676}
677
678/// The `all.equal()` method `#[derive(AllEqual)]` generates for a type
679/// (#2149), without the parts that depend on the type's R class: its name,
680/// its title and its registration, which [`collect_r_wrappers`] adds.
681pub struct AllEqualEntry {
682    /// Rust type identifier, matched against [`ClassNameEntry::rust_type`].
683    pub rust_type: &'static str,
684    /// The method, `function(target, current, ...) { ... }`.
685    pub method: &'static str,
686    /// The roxygen lines of the method's page after its title: the
687    /// description, the arguments and the value.
688    pub docs: &'static str,
689    /// Source file of the derive (`file!()`).
690    pub source_file: &'static str,
691    /// Line of the derived type in `source_file`.
692    pub source_line: u32,
693    /// Column of the derived type, for the `# Generated from` header.
694    pub source_column: u32,
695}
696
697// SAFETY: &'static str fields and integers — immutable and valid for program lifetime.
698unsafe impl Sync for AllEqualEntry {}
699
700/// One `pkg::name` item of a `reexport!` invocation (#1910): `name`, an
701/// export of the R package `package`, which this package exports too.
702/// The macro has checked both names.
703pub struct ReexportEntry {
704    /// The R package the name comes from, e.g. `"generics"`.
705    pub package: &'static str,
706    /// The re-exported name as R spells it, unquoted, e.g. `"tidy"` or
707    /// `"%>%"`.
708    pub name: &'static str,
709    /// Source file of the invocation (`file!()`).
710    pub source_file: &'static str,
711    /// Line of the item in `source_file`.
712    pub source_line: u32,
713    /// Column of the item, for the `# Generated from` header.
714    pub source_column: u32,
715}
716
717/// Build the `rust_type → ClassNameEntry` lookup used by every placeholder
718/// resolver in `write_r_wrappers_to_file`.
719///
720/// Each `#[miniextendr]` impl block of a type registers a `ClassNameEntry`
721/// (#1242, #1776) — the class name is a property of the *type*, so identical
722/// duplicates collapse here. *Conflicting* registrations (same `rust_type`,
723/// different `r_class_name` or `class_system` — e.g. two blocks with
724/// disagreeing `class = "..."` overrides) panic: silently keeping
725/// whichever entry linkme ordered last would resolve `.__MX_CLASS_REF_*__`
726/// placeholders nondeterministically. `field_syntax` may differ between the
727/// blocks ([`sidecar_accessor_fragments`] reads every entry). Distinct Rust
728/// types must also have distinct R class names: otherwise their class bindings
729/// and generated methods overwrite each other when the package loads (#1677).
730///
731/// Host-only like `MX_CLASS_NAMES` itself — the consumers all live in the
732/// wrapper-writing path, which never runs on wasm32.
733#[cfg(not(target_arch = "wasm32"))]
734fn build_class_name_index<'a>(
735    entries: impl IntoIterator<Item = &'a ClassNameEntry>,
736) -> std::collections::HashMap<&'a str, &'a ClassNameEntry> {
737    use std::collections::hash_map::Entry;
738    let mut index = std::collections::HashMap::new();
739    let mut r_class_names = std::collections::HashMap::new();
740    for e in entries {
741        match index.entry(e.rust_type) {
742            Entry::Vacant(slot) => {
743                slot.insert(e);
744            }
745            Entry::Occupied(slot) => {
746                let prev = *slot.get();
747                if prev.r_class_name != e.r_class_name || prev.class_system != e.class_system {
748                    {
    ::core::panicking::panic_fmt(format_args!("conflicting class registrations for Rust type `{0}`: `{1}` ({2}) vs `{3}` ({4}). Multiple #[miniextendr] impl blocks on one type must agree on the class system and any `class = \"...\"` override.",
            e.rust_type, prev.r_class_name, prev.class_system, e.r_class_name,
            e.class_system));
};panic!(
749                        "conflicting class registrations for Rust type `{}`: \
750                         `{}` ({}) vs `{}` ({}). Multiple #[miniextendr] impl blocks \
751                         on one type must agree on the class system and any \
752                         `class = \"...\"` override.",
753                        e.rust_type,
754                        prev.r_class_name,
755                        prev.class_system,
756                        e.r_class_name,
757                        e.class_system,
758                    );
759                }
760            }
761        }
762        if let Some(prev) = r_class_names.insert(e.r_class_name, e) {
763            if !(prev.rust_type == e.rust_type) {
    {
        ::core::panicking::panic_fmt(format_args!("R class `{0}` is registered for both Rust type `{1}` ({2}) and `{3}` ({4}). Distinct Rust types must use distinct R class names; change one `class = \"...\"` override to avoid overwriting its class and methods.",
                e.r_class_name, prev.rust_type, prev.class_system,
                e.rust_type, e.class_system));
    }
};assert!(
764                prev.rust_type == e.rust_type,
765                "R class `{}` is registered for both Rust type `{}` ({}) and `{}` ({}). \
766                 Distinct Rust types must use distinct R class names; change one \
767                 `class = \"...\"` override to avoid overwriting its class and methods.",
768                e.r_class_name,
769                prev.rust_type,
770                prev.class_system,
771                e.rust_type,
772                e.class_system,
773            );
774        }
775    }
776    index
777}
778
779/// Entry documenting a sidecar (`#[r_data]`) property on an S7 ExternalPtr type.
780///
781/// Emitted by `#[derive(ExternalPtr)] #[externalptr(s7)]` for each public `#[r_data]`
782/// field. Used by `write_r_wrappers_to_file` to substitute the
783/// `.__MX_S7_SIDECAR_PROP_DOCS_<TypeName>__` placeholder with `#' @prop` lines.
784pub struct SidecarPropEntry {
785    /// Rust type name, e.g. `"SidecarS7"`.
786    pub rust_type: &'static str,
787    /// Field name, e.g. `"prop_int"`.
788    pub field_name: &'static str,
789    /// Documentation string for this property.
790    /// Defaults to `"(undocumented sidecar property)"` when no `prop_doc` was supplied.
791    pub prop_doc: &'static str,
792    /// Whether the property has no setter (a `Computed` or
793    /// `#[r_data(read_only)]` field, #2268): the derive then emits no
794    /// `<Class>_set_<field>()`.
795    pub read_only: bool,
796}
797
798// SAFETY: All fields are &'static str — immutable and valid for program lifetime.
799unsafe impl Sync for SidecarPropEntry {}
800
801/// Trait dispatch entry mapping (concrete_tag, trait_tag) → vtable.
802#[repr(C)]
803pub struct TraitDispatchEntry {
804    /// Tag identifying the concrete type.
805    pub concrete_tag: mx_tag,
806    /// Tag identifying the trait interface.
807    pub trait_tag: mx_tag,
808    /// Pointer to the trait's vtable (cast from `&'static SomeVTable`).
809    pub vtable: *const c_void,
810    /// Symbol name of the `#[no_mangle]` vtable static
811    /// (e.g. `"__VTABLE_mypkg_Counter_FOR_MyType"`). Consumed by the host-time WASM
812    /// snapshot writer to emit `extern "C" { static <symbol>: u8; }`
813    /// declarations in `wasm_registry.rs`.
814    pub vtable_symbol: &'static str,
815}
816
817// SAFETY: vtable points to a static vtable valid for program lifetime.
818// Tags are Copy values. All fields are safe to read from any thread.
819unsafe impl Sync for TraitDispatchEntry {}
820unsafe impl Send for TraitDispatchEntry {}
821
822/// ALTREP class registration entry: fn pointer + `#[no_mangle]` symbol name.
823///
824/// See [`MX_ALTREP_REGISTRATIONS`] for context.
825#[repr(C)]
826pub struct AltrepRegistration {
827    /// Registration function called inside the package-init unwind boundary.
828    pub register: extern "C-unwind" fn(),
829    /// Symbol name of `register` (e.g. `"__mx_altrep_reg_MyType"`). Consumed by
830    /// the host-time WASM snapshot writer to emit `extern "C-unwind" { fn <symbol>(); }`
831    /// declarations in `wasm_registry.rs`.
832    pub symbol: &'static str,
833}
834
835// SAFETY: register is a static fn pointer; symbol is a `'static` string.
836unsafe impl Sync for AltrepRegistration {}
837unsafe impl Send for AltrepRegistration {}
838// endregion
839
840// region: Universal Query
841
842/// Universal query function for trait dispatch.
843///
844/// Scans [`MX_TRAIT_DISPATCH`] for a matching `(concrete_tag, trait_tag)` pair.
845/// Returns the vtable pointer, or null if the trait is not implemented.
846///
847/// This replaces per-type query functions — a single function handles all types
848/// by reading from the global dispatch table.
849///
850/// # Safety
851///
852/// - `ptr` must point to a valid `mx_erased` with a valid base vtable.
853/// - Must be called on R's main thread.
854pub unsafe extern "C" fn universal_query(ptr: *mut mx_erased, trait_tag: mx_tag) -> *const c_void {
855    let concrete_tag = unsafe { (*(*ptr).base).concrete_tag };
856    for entry in trait_dispatch().iter() {
857        if entry.concrete_tag == concrete_tag && entry.trait_tag == trait_tag {
858            return entry.vtable;
859        }
860    }
861    std::ptr::null()
862}
863// endregion
864
865// region: Initialization
866
867/// Register all `#[miniextendr]` routines and ALTREP classes with R.
868///
869/// Called from `package_init()` during `R_init_*` (via `miniextendr_init!`).
870/// Everything else is automatic.
871///
872/// # Safety
873///
874/// Must be called from R's main thread during `R_init_*`.
875/// `dll` must be a valid pointer provided by R.
876#[unsafe(no_mangle)]
877pub unsafe extern "C-unwind" fn miniextendr_register_routines(dll: *mut DllInfo) {
878    // 1. Register ALTREP classes (skip during wrapper generation)
879    //
880    // During wrapper-gen, the installed shared object is loaded temporarily via
881    // dyn.load() then unloaded via dyn.unload(). ALTREP class registration creates
882    // R-global entries with method pointers into the loaded code. After dyn.unload(),
883    // those pointers become dangling. When R later loads the installed package and
884    // re-registers, it may still have the stale entries, leading to heap corruption
885    // (e.g., "malloc(): unsorted double linked list corrupted" on Linux).
886    // Shares the single read-site with package_init (see init::WRAPPER_GEN_ENV) so
887    // the env-var name cannot drift between the two consumers.
888    let wrapper_gen = crate::init::wrapper_gen_mode();
889    if !wrapper_gen {
890        // All ALTREP classes — both user-defined (#[miniextendr] structs) and
891        // builtins (Vec, Box, Range, Cow, Arrow) — register via linkme
892        // MX_ALTREP_REGISTRATIONS. Each call site emits a
893        // `#[distributed_slice(MX_ALTREP_REGISTRATIONS)]` entry, so a single
894        // iteration here covers everything. No hand-enumerated builtin list needed.
895        for reg in altrep_regs().iter() {
896            (reg.register)();
897        }
898
899        // Verify no two ALTREP types registered the same class name.
900        // Duplicates cause silent overwrites in R — the wrong type gets
901        // reconstructed on readRDS, leading to memory corruption.
902        crate::altrep::assert_altrep_class_uniqueness();
903    }
904
905    // 2. Build call method defs with null sentinel
906    let mut call_defs: Vec<R_CallMethodDef> = self::call_defs();
907    // Always register the wrapper-gen entry points so they're visible
908    // via getNativeSymbolInfo even when R_forceSymbols(TRUE) is set. wasm32
909    // doesn't run wrapper-gen (it's host-only), so these are gated off there.
910    // SAFETY: DL_FUNC is Option<extern "C-unwind" fn() -> *mut c_void> — R's
911    // standard erased function pointer. The actual signature (SEXP -> SEXP) is
912    // ABI-compatible; R dispatches based on numArgs.
913    #[cfg(not(target_arch = "wasm32"))]
914    {
915        call_defs.push(R_CallMethodDef {
916            name: c"miniextendr_write_wrappers".as_ptr(),
917            fun: unsafe {
918                std::mem::transmute::<
919                    *const (),
920                    Option<unsafe extern "C-unwind" fn() -> *mut c_void>,
921                >(miniextendr_write_wrappers as *const ())
922            },
923            numArgs: 1,
924        });
925        call_defs.push(R_CallMethodDef {
926            name: c"miniextendr_write_wasm_registry".as_ptr(),
927            fun: unsafe {
928                std::mem::transmute::<
929                    *const (),
930                    Option<unsafe extern "C-unwind" fn() -> *mut c_void>,
931                >(miniextendr_write_wasm_registry as *const ())
932            },
933            numArgs: 1,
934        });
935    }
936    call_defs.push(R_CallMethodDef {
937        name: std::ptr::null(),
938        fun: None,
939        numArgs: 0,
940    });
941
942    // 3. Register routines
943    // R copies every entry into the DLL's own table (`R_addCallRoutine`
944    // strdups the name and stores the function pointer), so `call_defs` is
945    // freed on return. Leaking it showed up as ~114 KB "definitely lost" per
946    // load under Valgrind.
947    unsafe {
948        crate::sys::R_registerRoutines_unchecked(
949            dll,
950            std::ptr::null(),
951            call_defs.as_ptr(),
952            std::ptr::null(),
953            std::ptr::null(),
954        );
955    }
956}
957
958/// The standalone sidecar accessors as sidecar fragments: each type's
959/// internal rendering when one of its impl blocks gives its class field
960/// syntax (#1900), without the setters when that syntax is read-only
961/// (#2268), else the exported one.
962#[cfg(not(target_arch = "wasm32"))]
963fn sidecar_accessor_fragments(
964    accessors: &[SidecarAccessorsEntry],
965    classes: &[ClassNameEntry],
966) -> Vec<WrapperFragment> {
967    accessors
968        .iter()
969        .map(|entry| {
970            let content = if read_only_fields(classes, entry.rust_type) {
971                entry.internal_read_only
972            } else if classes
973                .iter()
974                .any(|class| class.rust_type == entry.rust_type && class.field_syntax)
975            {
976                entry.internal
977            } else {
978                entry.exported
979            };
980            WrapperFragment {
981                priority: RWrapperPriority::Sidecar,
982                content: std::borrow::Cow::Borrowed(content),
983                source_file: entry.source_file,
984                source_line: entry.source_line,
985            }
986        })
987        .collect()
988}
989
990/// The `all.equal()` methods of `#[derive(AllEqual)]` as fragments (#2149):
991/// each named `all.equal.<Class>` for the R class of the type's
992/// [`ClassNameEntry`], on its own page, and registered with
993/// `S3method(all.equal, <Class>)`, which an env, R6, S3 or S4 object
994/// dispatches on (S4 through R's S3 dispatch on the S4 class, which also
995/// reaches callers of `base::all.equal()` such as testthat, where an S4
996/// method would not). An S7 object's class attribute is `pkg::Class`, so an
997/// S7 class also registers the method with `S7::method(all.equal, Class)`,
998/// followed by the unbinding every such replacement call on a base generic
999/// needs (see `miniextendr_macros`'s `s7_base_operator_unbind`).
1000///
1001/// The fragments are written with the trait impls, after every class
1002/// definition, which the S7 registration names.
1003///
1004/// Every problem is collected into one message: a type no impl block gives
1005/// an R class, and a vctrs class, whose objects are R vectors with no pointer
1006/// to the Rust value.
1007#[cfg(not(target_arch = "wasm32"))]
1008fn all_equal_fragments(
1009    entries: &[AllEqualEntry],
1010    classes: &[ClassNameEntry],
1011) -> Result<Vec<WrapperFragment>, String> {
1012    let index = build_class_name_index(classes);
1013    let mut errors = Vec::new();
1014    let mut fragments = Vec::new();
1015    for entry in entries {
1016        let derive = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`#[derive(AllEqual)]` on `{0}` ({1}:{2})",
                entry.rust_type, entry.source_file, entry.source_line))
    })format!(
1017            "`#[derive(AllEqual)]` on `{}` ({}:{})",
1018            entry.rust_type, entry.source_file, entry.source_line
1019        );
1020        match index.get(entry.rust_type) {
1021            None => errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: no `#[miniextendr(env | r6 | s3 | s4 | s7)]` impl block gives the type an R class, so there is no class to give the `all.equal()` method",
                derive))
    })format!(
1022                "{derive}: no `#[miniextendr(env | r6 | s3 | s4 | s7)]` impl block gives the \
1023                 type an R class, so there is no class to give the `all.equal()` method"
1024            )),
1025            Some(class) if class.class_system == "vctrs" => errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: the objects of a vctrs class are R vectors, not pointers to the Rust value, and `all.equal()` already compares them",
                derive))
    })format!(
1026                "{derive}: the objects of a vctrs class are R vectors, not pointers to the Rust \
1027                 value, and `all.equal()` already compares them"
1028            )),
1029            Some(class) => fragments.push(WrapperFragment {
1030                priority: RWrapperPriority::TraitImpl,
1031                source_file: entry.source_file,
1032                source_line: entry.source_line,
1033                content: std::borrow::Cow::Owned(all_equal_method(entry, class)),
1034            }),
1035        }
1036    }
1037    if errors.is_empty() {
1038        Ok(fragments)
1039    } else {
1040        Err(errors.join("\n"))
1041    }
1042}
1043
1044/// The text of one `#[derive(AllEqual)]` method: see [`all_equal_fragments`].
1045#[cfg(not(target_arch = "wasm32"))]
1046fn all_equal_method(entry: &AllEqualEntry, class: &ClassNameEntry) -> String {
1047    let class_name = class.r_class_name;
1048    let method = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("all.equal.{0}", class_name))
    })format!("all.equal.{class_name}");
1049    // `all.equal.` makes the name start with a letter; a class name with
1050    // other characters than R's name characters needs backticks.
1051    let symbol = if class_name
1052        .bytes()
1053        .all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'_')
1054    {
1055        method.clone()
1056    } else {
1057        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", method))
    })format!("`{method}`")
1058    };
1059    let mut out = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated from Rust derive `AllEqual` on `{0}` ({1}:{2}:{3})\n#\' Compare two `{6}` objects\n#\'\n{4}\n#\' @method all.equal {6}\n#\' @export\n{7} <- {5}",
                entry.rust_type, entry.source_file, entry.source_line,
                entry.source_column, entry.docs.trim_matches('\n'),
                entry.method.trim_matches('\n'), class_name, symbol))
    })format!(
1060        "# Generated from Rust derive `AllEqual` on `{}` ({}:{}:{})\n\
1061         #' Compare two `{class_name}` objects\n\
1062         #'\n\
1063         {}\n\
1064         #' @method all.equal {class_name}\n\
1065         #' @export\n\
1066         {symbol} <- {}",
1067        entry.rust_type,
1068        entry.source_file,
1069        entry.source_line,
1070        entry.source_column,
1071        entry.docs.trim_matches('\n'),
1072        entry.method.trim_matches('\n'),
1073    );
1074    if class.class_system == "s7" {
1075        out.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\nS7::method(all.equal, {0}) <- {1}\nbase::rm(list = \"all.equal\")",
                class_name, symbol))
    })format!(
1076            "\nS7::method(all.equal, {class_name}) <- {symbol}\nbase::rm(list = \"all.equal\")"
1077        ));
1078    }
1079    out
1080}
1081
1082// region: re-exports (#1910)
1083
1084/// The re-exports of every `reexport!` as one fragment, `None` without any:
1085/// for each `pkg::name`, roxygen2's re-export block
1086///
1087/// ```r
1088/// # Generated from Rust `reexport!` of `generics::tidy` (fits.rs:3:11)
1089/// #' @importFrom generics tidy
1090/// #' @export
1091/// generics::tidy
1092/// ```
1093///
1094/// from which roxygen2 writes `importFrom(generics,tidy)` and `export(tidy)`
1095/// to `NAMESPACE` and an alias to `man/reexports.Rd`. A `pkg::name` that
1096/// several items name is written once, its header listing their sites. The
1097/// blocks are sorted by package, then name.
1098///
1099/// A name re-exported from two packages gets a block for each here;
1100/// [`reexport_conflicts`] refuses it with the other problems once the file
1101/// is assembled.
1102#[cfg(not(target_arch = "wasm32"))]
1103fn reexport_fragment(entries: &[ReexportEntry]) -> Option<WrapperFragment> {
1104    let mut by_item: std::collections::BTreeMap<(&str, &str), Vec<&ReexportEntry>> =
1105        std::collections::BTreeMap::new();
1106    for entry in entries {
1107        by_item
1108            .entry((entry.package, entry.name))
1109            .or_default()
1110            .push(entry);
1111    }
1112    let first = *by_item.values().next()?.first()?;
1113    let blocks: Vec<String> = by_item
1114        .iter()
1115        .map(|((package, name), sites)| {
1116            let object = if is_syntactic_r_name(name) {
1117                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::{1}", package, name))
    })format!("{package}::{name}")
1118            } else {
1119                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}::`{1}`", package, name))
    })format!("{package}::`{name}`")
1120            };
1121            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated from Rust `reexport!` of `{2}::{3}` {0}\n#\' @importFrom {2} {1}\n#\' @export\n{4}",
                reexport_sites(sites), r_namespace_name(name), package, name,
                object))
    })format!(
1122                "# Generated from Rust `reexport!` of `{package}::{name}` {}\n\
1123                 #' @importFrom {package} {}\n\
1124                 #' @export\n\
1125                 {object}",
1126                reexport_sites(sites),
1127                r_namespace_name(name),
1128            )
1129        })
1130        .collect();
1131    Some(WrapperFragment {
1132        priority: RWrapperPriority::Reexport,
1133        source_file: first.source_file,
1134        source_line: first.source_line,
1135        content: std::borrow::Cow::Owned(blocks.join("\n\n")),
1136    })
1137}
1138
1139/// The sites of `entries`, `(file.rs:line:column)` each, in source order.
1140#[cfg(not(target_arch = "wasm32"))]
1141fn reexport_sites(entries: &[&ReexportEntry]) -> String {
1142    let mut sites: Vec<(&str, u32, u32)> = entries
1143        .iter()
1144        .map(|entry| (entry.source_file, entry.source_line, entry.source_column))
1145        .collect();
1146    sites.sort_unstable();
1147    sites.dedup();
1148    sites
1149        .iter()
1150        .map(|(file, line, column)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("({0}:{1}:{2})", file, line,
                column))
    })format!("({file}:{line}:{column})"))
1151        .collect::<Vec<_>>()
1152        .join(" ")
1153}
1154
1155/// Refuse the re-exports of `entries` that can't be written, all in one
1156/// message: a name re-exported from two packages (a package exports one
1157/// object under a name), and a name the package also binds at top level or
1158/// exports, in `content`, the assembled wrappers, or in `hand_written`, its
1159/// hand-written R files (#2205). The package's own binding would hide the
1160/// imported one inside its namespace, so `export(name)` would export it
1161/// instead; an export alone repeats the one the re-export writes.
1162///
1163/// A hand-written file is read by [`wrapper_names`] too, so the scan sees
1164/// what that sees in generated text; every name is the file's.
1165#[cfg(not(target_arch = "wasm32"))]
1166fn reexport_conflicts(
1167    content: &str,
1168    hand_written: &[HandWrittenFile],
1169    entries: &[ReexportEntry],
1170) -> Result<(), String> {
1171    use std::collections::BTreeMap;
1172    use std::rc::Rc;
1173    let mut by_name: BTreeMap<&str, BTreeMap<&str, Vec<&ReexportEntry>>> = BTreeMap::new();
1174    for entry in entries {
1175        by_name
1176            .entry(entry.name)
1177            .or_default()
1178            .entry(entry.package)
1179            .or_default()
1180            .push(entry);
1181    }
1182    if by_name.is_empty() {
1183        return Ok(());
1184    }
1185    let reexports = |name: &str, packages: &BTreeMap<&str, Vec<&ReexportEntry>>| {
1186        packages
1187            .iter()
1188            .map(|(package, sites)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{1}::{2}` {0}",
                reexport_sites(sites), package, name))
    })format!("`{package}::{name}` {}", reexport_sites(sites)))
1189            .collect::<Vec<_>>()
1190            .join(", ")
1191    };
1192
1193    let mut errors = Vec::new();
1194    for (name, packages) in &by_name {
1195        if packages.len() > 1 {
1196            errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`reexport!` re-exports `{2}` from {0} packages: {1}. A package exports one object under a name; re-export it from one of them.",
                packages.len(), reexports(name, packages), name))
    })format!(
1197                "`reexport!` re-exports `{name}` from {} packages: {}. A package exports one \
1198                 object under a name; re-export it from one of them.",
1199                packages.len(),
1200                reexports(name, packages),
1201            ));
1202        }
1203    }
1204
1205    // Each fragment or hand-written file that binds or exports a re-exported
1206    // name, once, by its binding when it both binds and exports it.
1207    struct Use {
1208        kind: &'static str,
1209        producer: Rc<str>,
1210        /// `producer` is a hand-written file.
1211        in_file: bool,
1212    }
1213    let mut own: BTreeMap<&str, Vec<Use>> = BTreeMap::new();
1214    let generated = wrapper_names(content).into_iter().map(|name| (name, false));
1215    let files = hand_written.iter().flat_map(|file| {
1216        let producer: Rc<str> = Rc::from(file.name.as_str());
1217        // A `# Generated from` comment in the file doesn't change whose the
1218        // names are.
1219        wrapper_names(&file.text).into_iter().map(move |name| {
1220            let producer = producer.clone();
1221            (WrapperName { producer, ..name }, true)
1222        })
1223    });
1224    for (
1225        WrapperName {
1226            name,
1227            kind,
1228            producer,
1229        },
1230        in_file,
1231    ) in generated.chain(files)
1232    {
1233        if !by_name.contains_key(name) {
1234            continue;
1235        }
1236        let uses = own.entry(name).or_default();
1237        match uses.iter_mut().find(|used| used.producer == producer) {
1238            Some(used) if used.kind == "export" => used.kind = kind,
1239            Some(_) => {}
1240            None => uses.push(Use {
1241                kind,
1242                producer,
1243                in_file,
1244            }),
1245        }
1246    }
1247    for (name, uses) in own {
1248        let what = uses
1249            .iter()
1250            .map(|used| {
1251                let (kind, producer) = (used.kind, &used.producer);
1252                let from = if used.in_file { "in" } else { "from" };
1253                if kind == "export" {
1254                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("an export {0} {1}", from,
                producer))
    })format!("an export {from} {producer}")
1255                } else {
1256                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("a {0} {1} {2}", kind, from,
                producer))
    })format!("a {kind} {from} {producer}")
1257                }
1258            })
1259            .collect::<Vec<_>>()
1260            .join(", ");
1261        let binders = || uses.iter().filter(|used| used.kind != "export");
1262        let (does, why) = if binders().next().is_some() {
1263            let files = binders()
1264                .filter(|used| used.in_file)
1265                .map(|used| &*used.producer)
1266                .collect::<Vec<_>>()
1267                .join(", ");
1268            let rename = if files.is_empty() {
1269                "rename the package's binding (`r_name = \"...\"`, `class = \"...\"`)".to_string()
1270            } else if binders().any(|used| !used.in_file) {
1271                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rename the package\'s binding (`r_name = \"...\"`, `class = \"...\"`) and the one in {0}",
                files))
    })format!(
1272                    "rename the package's binding (`r_name = \"...\"`, `class = \"...\"`) and \
1273                     the one in {files}"
1274                )
1275            } else {
1276                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rename the package\'s `{0}` in {1}",
                name, files))
    })format!("rename the package's `{name}` in {files}")
1277            };
1278            (
1279                "binds",
1280                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("The package\'s own `{0}` would hide the imported one in its namespace, so `export({0})` would export it instead. Remove the re-export, or {1}.",
                name, rename))
    })format!(
1281                    "The package's own `{name}` would hide the imported one in its namespace, \
1282                     so `export({name})` would export it instead. Remove the re-export, or \
1283                     {rename}."
1284                ),
1285            )
1286        } else {
1287            (
1288                "exports",
1289                "`reexport!` writes the export itself; drop the other one.".to_string(),
1290            )
1291        };
1292        errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`reexport!` re-exports {0}, and the package also {1} `{2}` ({3}). {4}",
                reexports(name, &by_name[name]), does, name, what, why))
    })format!(
1293            "`reexport!` re-exports {}, and the package also {does} `{name}` ({what}). {why}",
1294            reexports(name, &by_name[name]),
1295        ));
1296    }
1297
1298    if errors.is_empty() {
1299        Ok(())
1300    } else {
1301        Err(errors
1302            .iter()
1303            .map(|error| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: {0}", error))
    })format!("miniextendr: {error}"))
1304            .collect::<Vec<_>>()
1305            .join("\n"))
1306    }
1307}
1308
1309/// A hand-written R file of the package, as [`reexport_conflicts`] reads it.
1310#[cfg(not(target_arch = "wasm32"))]
1311struct HandWrittenFile {
1312    /// The file as messages name it, `R/tidy.R`.
1313    name: String,
1314    text: String,
1315}
1316
1317/// The package's hand-written R files: the code files of `r_dir`, its `R/`
1318/// directory, that R installs (extension `.R`, `.r`, `.S`, `.s` or `.q`, and
1319/// a name starting with a letter or digit), in name order. The file named
1320/// like `wrappers`, the file being written, is left out by name, since a
1321/// release tarball's install writes into a temporary copy of it. The OS
1322/// subdirectories `R/unix/` and `R/windows/` are not read. A file's text is
1323/// read lossily: R also accepts Latin-1 sources.
1324#[cfg(not(target_arch = "wasm32"))]
1325fn hand_written_r_files(
1326    r_dir: &std::path::Path,
1327    wrappers: &std::path::Path,
1328) -> Vec<HandWrittenFile> {
1329    let failed = |e: std::io::Error| -> ! { {
    ::core::panicking::panic_fmt(format_args!("failed to read {0}: {1}",
            r_dir.display(), e));
}panic!("failed to read {}: {e}", r_dir.display()) };
1330    let mut files: Vec<HandWrittenFile> = std::fs::read_dir(r_dir)
1331        .unwrap_or_else(|e| failed(e))
1332        .filter_map(|entry| {
1333            let path = entry.unwrap_or_else(|e| failed(e)).path();
1334            let name = path.file_name()?.to_str()?;
1335            let code = name.starts_with(|c: char| c.is_ascii_alphanumeric())
1336                && name
1337                    .rsplit_once('.')
1338                    .is_some_and(|(_, ext)| ["R", "r", "S", "s", "q"].contains(&ext));
1339            let written = wrappers.file_name() == Some(std::ffi::OsStr::new(name));
1340            if !code || written || !path.is_file() {
1341                return None;
1342            }
1343            let bytes = std::fs::read(&path)
1344                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("failed to read {0}: {1}",
            path.display(), e));
}panic!("failed to read {}: {e}", path.display()));
1345            Some(HandWrittenFile {
1346                name: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("R/{0}", name))
    })format!("R/{name}"),
1347                text: String::from_utf8_lossy(&bytes).into_owned(),
1348            })
1349        })
1350        .collect();
1351    files.sort_unstable_by(|a, b| a.name.cmp(&b.name));
1352    files
1353}
1354
1355// endregion
1356
1357// region: impl blocks merged per type (#1776)
1358
1359/// A wrapper fragment to write: an [`RWrapperEntry`]'s text, or a fragment
1360/// assembled at write time (a class merged from its impl blocks, a type's
1361/// sidecar accessors).
1362#[cfg(not(target_arch = "wasm32"))]
1363struct WrapperFragment {
1364    priority: RWrapperPriority,
1365    source_file: &'static str,
1366    source_line: u32,
1367    content: std::borrow::Cow<'static, str>,
1368}
1369
1370#[cfg(not(target_arch = "wasm32"))]
1371impl From<&RWrapperEntry> for WrapperFragment {
1372    fn from(entry: &RWrapperEntry) -> Self {
1373        WrapperFragment {
1374            priority: entry.priority,
1375            source_file: entry.source_file,
1376            source_line: entry.source_line,
1377            content: std::borrow::Cow::Borrowed(entry.content),
1378        }
1379    }
1380}
1381
1382/// A [`ClassBlockEntry`] part without the newline its raw string literal
1383/// adds at each end.
1384#[cfg(not(target_arch = "wasm32"))]
1385fn class_part(part: &str) -> &str {
1386    let part = part.strip_prefix('\n').unwrap_or(part);
1387    part.strip_suffix('\n').unwrap_or(part)
1388}
1389
1390/// How a merge error names an impl block: `` `impl Counter` (lib.rs:12) ``.
1391#[cfg(not(target_arch = "wasm32"))]
1392fn class_block_name(block: &ClassBlockEntry) -> String {
1393    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`impl {0}` ({1}:{2})",
                block.rust_type, block.source_file, block.source_line))
    })format!(
1394        "`impl {}` ({}:{})",
1395        block.rust_type, block.source_file, block.source_line
1396    )
1397}
1398
1399/// Merge the impl blocks of each Rust type into one class fragment (#1776).
1400///
1401/// Blocks are grouped by [`ClassBlockEntry::type_path`] and taken in source
1402/// order. A type's fragment is the defining block's head, with the
1403/// `class_docs` of every block (the defining block's first) at its
1404/// [`CLASS_DOCS_MARKER`] line and the `class_doc_lines` of every block at its
1405/// [`CLASS_DOC_LINES_MARKER`] line, then each block's members, then the
1406/// defining block's env and tail. The env is written only when a trait impl
1407/// writes into it (an entry of `trait_namespaces` for the type, #2264,
1408/// #2289), and then a docs-only class block ([`CLASS_DOCS_ONLY_MARKER`]) is
1409/// written too, as the env's page. A tag repeated exactly is written once, and a
1410/// generated [`CLASS_DEFAULT_PREFIX`] line gives way to the same tag on
1411/// another block. A `# Generated from Rust impl` header precedes each
1412/// part whose block differs from the previous part's, so the
1413/// duplicate-definition scan of the written file
1414/// ([`detect_duplicate_wrapper_defs`]) names the block a definition comes from.
1415///
1416/// Every problem is collected into one message:
1417///
1418/// - two Rust types claim one R class name: their class objects and methods
1419///   would overwrite each other when the package loads (#1677);
1420/// - the blocks of a type disagree on the class settings
1421///   ([`ClassBlockEntry::settings`]), which shape every block's members;
1422/// - two blocks of a type each have something only the defining block may
1423///   have ([`ClassBlockEntry::defines`]);
1424/// - the doc comments of a type's blocks give the class two titles, or a
1425///   page other than the defining block's ([`class_doc_conflicts`]);
1426/// - two blocks of a type bind the same member name
1427///   ([`ClassBlockEntry::member_names`]), the later replacing the earlier;
1428/// - a type without a declared constructor has several methods that could be
1429///   one ([`resolve_class_constructor`], which first picks each block's
1430///   rendering).
1431#[cfg(not(target_arch = "wasm32"))]
1432fn merge_class_blocks(
1433    blocks: &[ClassBlockEntry],
1434    trait_namespaces: &[TraitNamespaceEntry],
1435) -> Result<Vec<WrapperFragment>, String> {
1436    use std::collections::{HashMap, HashSet};
1437
1438    let mut ordered: Vec<&ClassBlockEntry> = blocks.iter().collect();
1439    ordered.sort_by_key(|b| (b.source_file, b.source_line, b.source_column));
1440
1441    // The blocks of each type, in source order; types in order of their first block.
1442    let mut types: Vec<(&'static str, Vec<&ClassBlockEntry>)> = Vec::new();
1443    let mut type_index: HashMap<&'static str, usize> = HashMap::new();
1444    for block in ordered {
1445        let path = (block.type_path)();
1446        let i = *type_index.entry(path).or_insert_with(|| {
1447            types.push((path, Vec::new()));
1448            types.len() - 1
1449        });
1450        types[i].1.push(block);
1451    }
1452
1453    let mut errors: Vec<String> = Vec::new();
1454
1455    // One Rust type per R class name.
1456    let mut class_owner: HashMap<&'static str, (&'static str, &ClassBlockEntry)> = HashMap::new();
1457    for (path, type_blocks) in &types {
1458        for block in type_blocks {
1459            match class_owner.get(block.r_class_name) {
1460                Some(&(owner, first)) if owner != *path => {
1461                    errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: R class `{0}` is claimed by two Rust types, `{3}` ({1}) and `{4}` ({2}). Their class objects and methods would overwrite each other when the package loads; give one a distinct `class = \"...\"`.",
                block.r_class_name, class_block_name(first),
                class_block_name(block), owner, path))
    })format!(
1462                        "miniextendr: R class `{}` is claimed by two Rust types, `{owner}` \
1463                         ({}) and `{path}` ({}). Their class objects and methods would \
1464                         overwrite each other when the package loads; give one a distinct \
1465                         `class = \"...\"`.",
1466                        block.r_class_name,
1467                        class_block_name(first),
1468                        class_block_name(block),
1469                    ));
1470                }
1471                Some(_) => {}
1472                None => {
1473                    class_owner.insert(block.r_class_name, (path, block));
1474                }
1475            }
1476        }
1477    }
1478
1479    // The types a trait impl writes `Class$Trait` into.
1480    let namespaced: HashSet<&'static str> =
1481        trait_namespaces.iter().map(|e| (e.type_path)()).collect();
1482
1483    let mut fragments = Vec::with_capacity(types.len());
1484    for (path, type_blocks) in &types {
1485        let type_blocks = match resolve_class_constructor(type_blocks) {
1486            Ok(blocks) => blocks,
1487            Err(error) => {
1488                errors.push(error);
1489                continue;
1490            }
1491        };
1492        let first = type_blocks[0];
1493        let type_errors = errors.len();
1494
1495        for block in &type_blocks[1..] {
1496            if block.settings != first.settings {
1497                errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: the impl blocks of `{0}` disagree on the class settings: `{1}` on {2}, `{3}` on {4}. The blocks are merged into one class, and these settings shape every block\'s methods: spell the same class system and options, `class = \"...\"`, `internal` / `noexport` and `@noRd` / `@keywords internal` on each block (#1776).",
                first.rust_type, first.settings, class_block_name(first),
                block.settings, class_block_name(block)))
    })format!(
1498                    "miniextendr: the impl blocks of `{}` disagree on the class settings: \
1499                     `{}` on {}, `{}` on {}. The blocks are merged into one class, and \
1500                     these settings shape every block's methods: spell the same class \
1501                     system and options, `class = \"...\"`, `internal` / `noexport` and \
1502                     `@noRd` / `@keywords internal` on each block (#1776).",
1503                    first.rust_type,
1504                    first.settings,
1505                    class_block_name(first),
1506                    block.settings,
1507                    class_block_name(block),
1508                ));
1509            }
1510        }
1511
1512        let defining: Vec<&ClassBlockEntry> = type_blocks
1513            .iter()
1514            .copied()
1515            .filter(|b| !b.defines.is_empty())
1516            .collect();
1517        if let [a, b, ..] = defining.as_slice() {
1518            errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: two impl blocks of `{0}` each define the class: {1} has {2}, {3} has {4}. A type\'s impl blocks merge into one class, and only one of them may have a constructor or S7 properties: move what {5} has into {6} (#1776).",
                first.rust_type, class_block_name(a), a.defines.join(" and "),
                class_block_name(b), b.defines.join(" and "),
                class_block_name(b), class_block_name(a)))
    })format!(
1519                "miniextendr: two impl blocks of `{}` each define the class: {} has {}, \
1520                 {} has {}. A type's impl blocks merge into one class, and only one of \
1521                 them may have a constructor or S7 properties: move what {} has into \
1522                 {} (#1776).",
1523                first.rust_type,
1524                class_block_name(a),
1525                a.defines.join(" and "),
1526                class_block_name(b),
1527                b.defines.join(" and "),
1528                class_block_name(b),
1529                class_block_name(a),
1530            ));
1531        }
1532
1533        let definer = defining.first().copied().unwrap_or(first);
1534        errors.extend(class_doc_conflicts(definer, &type_blocks));
1535
1536        let mut members: HashMap<&str, &ClassBlockEntry> = HashMap::new();
1537        for &block in &type_blocks {
1538            for &name in block.member_names {
1539                match members.get(name) {
1540                    Some(&previous) if !std::ptr::eq(previous, block) => {
1541                        errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: two impl blocks of `{0}` define {3}: {1} and {2}. The later definition would replace the earlier one when the package loads; rename one with `#[miniextendr(r_name = \"...\")]` (#1776).",
                first.rust_type, class_block_name(previous),
                class_block_name(block), name))
    })format!(
1542                            "miniextendr: two impl blocks of `{}` define {name}: {} and {}. \
1543                             The later definition would replace the earlier one when the \
1544                             package loads; rename one with \
1545                             `#[miniextendr(r_name = \"...\")]` (#1776).",
1546                            first.rust_type,
1547                            class_block_name(previous),
1548                            class_block_name(block),
1549                        ));
1550                    }
1551                    Some(_) => {}
1552                    None => {
1553                        members.insert(name, block);
1554                    }
1555                }
1556            }
1557        }
1558
1559        if errors.len() > type_errors {
1560            continue;
1561        }
1562        let keep_env = namespaced.contains(path);
1563        fragments.push(WrapperFragment {
1564            priority: RWrapperPriority::Class,
1565            source_file: first.source_file,
1566            source_line: first.source_line,
1567            content: std::borrow::Cow::Owned(merged_class_content(definer, &type_blocks, keep_env)),
1568        });
1569    }
1570
1571    if errors.is_empty() {
1572        Ok(fragments)
1573    } else {
1574        Err(errors.join("\n"))
1575    }
1576}
1577
1578/// One roxygen tag of a class's docs: its `#'` lines, the first opening the
1579/// tag (`#' @name ...`), or the lines before the first tag. `default` marks a
1580/// generated line ([`CLASS_DEFAULT_PREFIX`], stripped from `lines`).
1581#[cfg(not(target_arch = "wasm32"))]
1582#[derive(#[automatically_derived]impl<'a> ::core::clone::Clone for DocTag<'a> {
    #[inline]
    fn clone(&self) -> Self {
        DocTag {
            default: ::core::clone::Clone::clone(&self.default),
            lines: ::core::clone::Clone::clone(&self.lines),
        }
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::StructuralPartialEq for
    DocTag<'a> {
}
#[automatically_derived]impl<'a> ::core::cmp::PartialEq for DocTag<'a> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.default == other.default && self.lines == other.lines
    }
}PartialEq)]
1583struct DocTag<'a> {
1584    default: bool,
1585    lines: Vec<&'a str>,
1586}
1587
1588#[cfg(not(target_arch = "wasm32"))]
1589impl<'a> DocTag<'a> {
1590    /// The tags of `text`, a run of roxygen lines: a tag runs from its
1591    /// `#' @tag` line to the next one, as roxygen2 reads it.
1592    fn parse(text: &'a str) -> Vec<Self> {
1593        let mut tags: Vec<Self> = Vec::new();
1594        for line in text.lines() {
1595            let (default, line) = match line.strip_prefix(CLASS_DEFAULT_PREFIX) {
1596                Some(line) => (true, line),
1597                None => (false, line),
1598            };
1599            match tags.last_mut() {
1600                Some(tag) if !default && !line.starts_with("#' @") => tag.lines.push(line),
1601                _ => tags.push(Self {
1602                    default,
1603                    lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [line]))vec![line],
1604                }),
1605            }
1606        }
1607        tags
1608    }
1609
1610    /// A head's generated default line, as a one-line tag; `None` for
1611    /// any other line.
1612    fn default_line(line: &'a str) -> Option<Self> {
1613        line.strip_prefix(CLASS_DEFAULT_PREFIX).map(|line| Self {
1614            default: true,
1615            lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [line]))vec![line],
1616        })
1617    }
1618
1619    /// The tag's name (`title` for `#' @title ...`), or `""` before the
1620    /// first tag.
1621    fn name(&self) -> &'a str {
1622        self.lines[0]
1623            .strip_prefix("#' @")
1624            .and_then(|rest| rest.split_whitespace().next())
1625            .unwrap_or("")
1626    }
1627
1628    /// The tag's text after its name, continuation lines included.
1629    fn value(&self) -> String {
1630        let first = self.lines[0]
1631            .strip_prefix("#' @")
1632            .map_or("", |rest| rest.trim_start()[self.name().len()..].trim());
1633        let rest = self.lines[1..]
1634            .iter()
1635            .map(|line| line.strip_prefix("#'").unwrap_or(line).trim());
1636        std::iter::once(first)
1637            .chain(rest)
1638            .collect::<Vec<_>>()
1639            .join("\n")
1640            .trim()
1641            .to_string()
1642    }
1643
1644    /// Whether this tag replaces the generated `default` (a tag of the same
1645    /// name; for `@param` and `@field`, naming the same argument or field,
1646    /// and `@inheritParams` for any `@param`).
1647    fn replaces(&self, default: &DocTag<'_>) -> bool {
1648        match default.name() {
1649            name @ ("param" | "field") => {
1650                let value = default.value();
1651                let arg = value.split_whitespace().next().unwrap_or("");
1652                (self.name() == name
1653                    && self
1654                        .value()
1655                        .split_whitespace()
1656                        .next()
1657                        .is_some_and(|names| names.split(',').any(|n| n.trim() == arg)))
1658                    || (name == "param" && self.name() == "inheritParams")
1659            }
1660            name => self.name() == name,
1661        }
1662    }
1663}
1664
1665/// Every block's [`class_docs`](ClassBlockEntry::class_docs) as tags, the
1666/// defining block's first, then the others' in source order.
1667#[cfg(not(target_arch = "wasm32"))]
1668fn block_docs<'a>(
1669    definer: &'a ClassBlockEntry,
1670    blocks: &[&'a ClassBlockEntry],
1671) -> Vec<(&'a ClassBlockEntry, Vec<DocTag<'a>>)> {
1672    let others = blocks
1673        .iter()
1674        .copied()
1675        .filter(|b| !std::ptr::eq(*b, definer));
1676    std::iter::once(definer)
1677        .chain(others)
1678        .map(|b| (b, DocTag::parse(class_part(b.class_docs))))
1679        .collect()
1680}
1681
1682/// The problems the doc comments of a type's impl blocks make for its merged
1683/// roxygen block (#1776): every block's doc tags are written, so two
1684/// different `@title`s give the class two titles (roxygen2 silently keeps
1685/// the first), and a `@name` or `@rdname` other than the defining block's
1686/// would move the class block to a page the defining block's generated
1687/// documentation was not written for.
1688#[cfg(not(target_arch = "wasm32"))]
1689fn class_doc_conflicts(definer: &ClassBlockEntry, blocks: &[&ClassBlockEntry]) -> Vec<String> {
1690    let mut errors = Vec::new();
1691    let docs = block_docs(definer, blocks);
1692    let tag_value =
1693        |tags: &[DocTag<'_>], name: &str| tags.iter().find(|t| t.name() == name).map(|t| t.value());
1694
1695    let mut title: Option<(&ClassBlockEntry, String)> = None;
1696    for (block, tags) in &docs {
1697        let Some(value) = tag_value(tags, "title") else {
1698            continue;
1699        };
1700        match &title {
1701            None => title = Some((block, value)),
1702            Some((first, first_value)) if *first_value != value => {
1703                errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: the impl blocks of `{0}` give the class two titles: {1} has `@title {3}`, {2} has `@title {4}`. A type\'s impl blocks merge into one class with one help page: keep one `@title` (#1776).",
                definer.rust_type, class_block_name(first),
                class_block_name(block), first_value, value))
    })format!(
1704                    "miniextendr: the impl blocks of `{}` give the class two titles: {} \
1705                     has `@title {first_value}`, {} has `@title {value}`. A type's impl \
1706                     blocks merge into one class with one help page: keep one `@title` \
1707                     (#1776).",
1708                    definer.rust_type,
1709                    class_block_name(first),
1710                    class_block_name(block),
1711                ));
1712                break;
1713            }
1714            Some(_) => {}
1715        }
1716    }
1717
1718    // The page the defining block documents the class on: its own tag, else
1719    // the generated default.
1720    let head_defaults: Vec<DocTag<'_>> = class_part(definer.head)
1721        .lines()
1722        .filter_map(DocTag::default_line)
1723        .collect();
1724    for name in ["name", "rdname"] {
1725        let page = tag_value(&docs[0].1, name).or_else(|| tag_value(&head_defaults, name));
1726        for (block, tags) in &docs[1..] {
1727            let Some(value) = tag_value(tags, name) else {
1728                continue;
1729            };
1730            if page.as_ref() == Some(&value) {
1731                continue;
1732            }
1733            let page = match &page {
1734                Some(page) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`@{0} {1}`", name, page))
    })format!("`@{name} {page}`"),
1735                None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `@{0}`", name))
    })format!("no `@{name}`"),
1736            };
1737            errors.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: the impl blocks of `{0}` put the class on two help pages: {1}, which defines the class, has {4}, and {2} has `@{5} {6}`. The block that defines the class decides its page: move `@{5} {6}` into {3}, or remove it (#1776).",
                definer.rust_type, class_block_name(definer),
                class_block_name(block), class_block_name(definer), page,
                name, value))
    })format!(
1738                "miniextendr: the impl blocks of `{}` put the class on two help pages: {}, \
1739                 which defines the class, has {page}, and {} has `@{name} {value}`. The \
1740                 block that defines the class decides its page: move `@{name} {value}` \
1741                 into {}, or remove it (#1776).",
1742                definer.rust_type,
1743                class_block_name(definer),
1744                class_block_name(block),
1745                class_block_name(definer),
1746            ));
1747        }
1748    }
1749    errors
1750}
1751
1752/// Decide a type's class constructor across its impl blocks: the blocks to
1753/// merge, each in the rendering that agrees with the decision.
1754///
1755/// - A block that declares the constructor
1756///   (`#[miniextendr(<system>(constructor))]`, or a receiver-less `new`
1757///   returning `Self`) has it. A block that would
1758///   infer one takes its [`demoted`](ClassBlockEntry::demoted) rendering,
1759///   where that method is a static method. Two declaring blocks are refused
1760///   with the other two-definer cases ([`merge_class_blocks`]).
1761/// - Without one, the type's one
1762///   [candidate](ClassBlockEntry::constructor_candidates) is its constructor,
1763///   whichever block has it. Several candidates are an error naming each
1764///   with its block (the compiler already refuses several in one block).
1765#[cfg(not(target_arch = "wasm32"))]
1766fn resolve_class_constructor<'a>(
1767    blocks: &[&'a ClassBlockEntry],
1768) -> Result<Vec<&'a ClassBlockEntry>, String> {
1769    let declared = blocks
1770        .iter()
1771        .any(|b| !b.constructor.is_empty() && !b.constructor_inferred);
1772    if declared {
1773        return Ok(blocks
1774            .iter()
1775            .map(|&b| match b.demoted {
1776                Some(demoted) if b.constructor_inferred => demoted,
1777                _ => b,
1778            })
1779            .collect());
1780    }
1781    let candidates: usize = blocks.iter().map(|b| b.constructor_candidates.len()).sum();
1782    if candidates > 1 {
1783        let listed: Vec<String> = blocks
1784            .iter()
1785            .filter(|b| !b.constructor_candidates.is_empty())
1786            .map(|b| {
1787                let names: Vec<String> = b
1788                    .constructor_candidates
1789                    .iter()
1790                    .map(|name| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", name))
    })format!("`{name}`"))
1791                    .collect();
1792                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} in {1}", names.join(", "),
                class_block_name(b)))
    })format!("{} in {}", names.join(", "), class_block_name(b))
1793            })
1794            .collect();
1795        // The class system is the first word of the settings, `r6(...)`.
1796        let settings = blocks[0].settings;
1797        let system = &settings[..settings
1798            .find(|c: char| !c.is_ascii_alphanumeric())
1799            .unwrap_or(settings.len())];
1800        return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: `{0}` has several methods that could be its constructor, and none is declared: {1}. Mark the constructor with `#[miniextendr({2}(constructor))]` (or name it `new`); the others stay static factory methods.",
                blocks[0].rust_type, listed.join("; "), system))
    })format!(
1801            "miniextendr: `{}` has several methods that could be its constructor, and none \
1802             is declared: {}. Mark the constructor with `#[miniextendr({system}(constructor))]` \
1803             (or name it `new`); the others stay static factory methods.",
1804            blocks[0].rust_type,
1805            listed.join("; "),
1806        ));
1807    }
1808    Ok(blocks.to_vec())
1809}
1810
1811/// Resolve each member's generated page after the defining impl is known.
1812/// A default page follows that impl's `@rdname`; explicit member pages do not.
1813/// On an inherited author topic, its block supplies the title and parameter
1814/// docs, so generated prose/parameters are removed and the member sorts last.
1815#[cfg(not(target_arch = "wasm32"))]
1816fn resolve_class_member_docs(content: &str, class: &str, topic: &str) -> String {
1817    fn unmark(line: &str) -> &str {
1818        line.strip_prefix(CLASS_MEMBER_DEFAULT_PREFIX)
1819            .unwrap_or(line)
1820    }
1821    let mut lines = content.split('\n').peekable();
1822    let mut result = Vec::new();
1823    while let Some(line) = lines.next() {
1824        if !unmark(line).trim_start().starts_with("#'") {
1825            result.push(line.to_owned());
1826            continue;
1827        }
1828        let mut block = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [line]))vec![line];
1829        while lines
1830            .peek()
1831            .is_some_and(|line| unmark(line).trim_start().starts_with("#'"))
1832        {
1833            block.push(lines.next().unwrap());
1834        }
1835        let default_page = block.iter().any(|line| {
1836            line.strip_prefix(CLASS_MEMBER_DEFAULT_PREFIX)
1837                .is_some_and(|line| line.starts_with("#' @rdname "))
1838        });
1839        let page = if default_page {
1840            Some(topic)
1841        } else {
1842            block
1843                .iter()
1844                .find_map(|line| line.strip_prefix("#' @rdname "))
1845        };
1846        let joined = page.is_some_and(|page| page != class)
1847            || block.iter().any(|line| line.starts_with("#' @describeIn "));
1848        let has_order = block
1849            .iter()
1850            .any(|line| unmark(line).starts_with("#' @order "));
1851        let no_rd = block.iter().any(|line| unmark(line).trim() == "#' @noRd");
1852        for line in block {
1853            match line.strip_prefix(CLASS_MEMBER_DEFAULT_PREFIX) {
1854                Some(default) if joined => {
1855                    if default.starts_with("#' @rdname ") {
1856                        result.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rdname {0}", topic))
    })format!("#' @rdname {topic}"));
1857                    }
1858                }
1859                Some(default) => result.push(default.to_owned()),
1860                None => result.push(line.to_owned()),
1861            }
1862        }
1863        if joined && !has_order && !no_rd && default_page {
1864            result.push("#' @order NaN".to_owned());
1865        }
1866    }
1867    result.join("\n")
1868}
1869
1870/// The text of a type's merged class: see [`merge_class_blocks`], which
1871/// decides `keep_env`.
1872#[cfg(not(target_arch = "wasm32"))]
1873fn merged_class_content(
1874    definer: &ClassBlockEntry,
1875    blocks: &[&ClassBlockEntry],
1876    keep_env: bool,
1877) -> String {
1878    let block_docs = block_docs(definer, blocks);
1879    // A default of `owner` gives way to the same tag on another block; its
1880    // own docs were seen when it was generated.
1881    let replaced = |owner: &ClassBlockEntry, default: &DocTag<'_>| {
1882        block_docs.iter().any(|(block, tags)| {
1883            !std::ptr::eq(*block, owner) && tags.iter().any(|t| t.replaces(default))
1884        })
1885    };
1886    let mut class_docs: Vec<DocTag<'_>> = Vec::new();
1887    for tag in block_docs.iter().flat_map(|(_, tags)| tags) {
1888        if !class_docs.contains(tag) {
1889            class_docs.push(tag.clone());
1890        }
1891    }
1892    let mut class_doc_lines: Vec<DocTag<'_>> = Vec::new();
1893    for block in blocks {
1894        for mut tag in DocTag::parse(class_part(block.class_doc_lines)) {
1895            if tag.default && replaced(block, &tag) {
1896                continue;
1897            }
1898            tag.default = false;
1899            if !class_doc_lines.contains(&tag) {
1900                class_doc_lines.push(tag);
1901            }
1902        }
1903    }
1904    // A docs-only block (`CLASS_DOCS_ONLY_MARKER`) is written when the docs
1905    // say something beyond the page and export tags, or when the class
1906    // environment is written: its block goes on the class's page (#2289).
1907    let says_something = keep_env
1908        || !class_doc_lines.is_empty()
1909        || class_docs.iter().any(|t| {
1910            !#[allow(non_exhaustive_omitted_patterns)] match t.name() {
    "rdname" | "noRd" | "keywords" | "order" | "export" => true,
    _ => false,
}matches!(
1911                t.name(),
1912                "rdname" | "noRd" | "keywords" | "order" | "export"
1913            )
1914        });
1915    let mut skipping = false;
1916    // `split`, not `lines`: a blank last line separates the head from the
1917    // members.
1918    let mut head_lines: Vec<&str> = Vec::new();
1919    for line in class_part(definer.head).split('\n') {
1920        if skipping {
1921            skipping = line != "NULL";
1922            continue;
1923        }
1924        if line == CLASS_DOCS_ONLY_MARKER {
1925            skipping = !says_something;
1926        } else if line == CLASS_DOCS_MARKER {
1927            head_lines.extend(class_docs.iter().flat_map(|t| t.lines.iter().copied()));
1928        } else if line == CLASS_DOC_LINES_MARKER {
1929            head_lines.extend(class_doc_lines.iter().flat_map(|t| t.lines.iter().copied()));
1930        } else if let Some(tag) = DocTag::default_line(line) {
1931            if !replaced(definer, &tag) {
1932                head_lines.push(tag.lines[0]);
1933            }
1934        } else {
1935            head_lines.push(line);
1936        }
1937    }
1938    let head = head_lines.join("\n");
1939
1940    let mut parts: Vec<(&ClassBlockEntry, &str)> = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(definer, &head)]))vec![(definer, &head)];
1941    parts.extend(blocks.iter().map(|&b| (b, class_part(b.members))));
1942    if keep_env {
1943        parts.push((definer, class_part(definer.env)));
1944    }
1945    parts.push((definer, class_part(definer.tail)));
1946
1947    let mut content = String::new();
1948    let mut previous: Option<&ClassBlockEntry> = None;
1949    for (block, text) in parts {
1950        // A blank part would only open a header with nothing under it.
1951        if text.trim().is_empty() {
1952            continue;
1953        }
1954        if previous.is_some_and(|p| std::ptr::eq(p, block)) {
1955            content.push('\n');
1956            content.push_str(text);
1957            continue;
1958        }
1959        if previous.is_some() {
1960            content.truncate(content.trim_end_matches('\n').len());
1961            content.push_str("\n\n");
1962        }
1963        content.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Generated from Rust impl `{0}` ({1}:{2}:{3})\n",
                block.rust_type, block.source_file, block.source_line,
                block.source_column))
    })format!(
1964            "# Generated from Rust impl `{}` ({}:{}:{})\n",
1965            block.rust_type, block.source_file, block.source_line, block.source_column
1966        ));
1967        content.push_str(text.trim_start_matches('\n'));
1968        previous = Some(block);
1969    }
1970    let topic = block_docs[0]
1971        .1
1972        .iter()
1973        .find(|tag| tag.name() == "rdname")
1974        .map(|tag| tag.value())
1975        .unwrap_or_else(|| definer.r_class_name.to_owned());
1976    resolve_class_member_docs(&content, definer.r_class_name, &topic)
1977}
1978
1979// endregion
1980
1981/// Collect all R wrapper entries, sorted and deduplicated.
1982///
1983/// Each type's impl blocks are first merged into one class fragment
1984/// (`merge_class_blocks`, #1776); a conflict between them panics with every
1985/// problem found. The `reexport!` blocks are one more fragment
1986/// (`reexport_fragment`). Entries are then ordered by `sort_wrapper_entries`: priority
1987/// first, then source file, then source line. Within each priority group, S7
1988/// class definitions are additionally topologically sorted so parents are
1989/// defined before children (S7 `parent = X` requires X to exist).
1990///
1991/// Host-only — wasm32 doesn't run wrapper-gen.
1992#[cfg(not(target_arch = "wasm32"))]
1993pub fn collect_r_wrappers() -> Vec<std::borrow::Cow<'static, str>> {
1994    let classes = merge_class_blocks(&MX_CLASS_BLOCKS, &MX_TRAIT_NAMESPACES)
1995        .unwrap_or_else(|msg| { ::core::panicking::panic_fmt(format_args!("{0}", msg)); }panic!("{msg}"));
1996    let mut entries: Vec<WrapperFragment> = MX_R_WRAPPERS
1997        .iter()
1998        .map(WrapperFragment::from)
1999        .chain(classes)
2000        .chain(sidecar_accessor_fragments(
2001            &MX_SIDECAR_ACCESSORS,
2002            &MX_CLASS_NAMES,
2003        ))
2004        .chain(
2005            all_equal_fragments(&MX_ALL_EQUAL, &MX_CLASS_NAMES)
2006                .unwrap_or_else(|msg| { ::core::panicking::panic_fmt(format_args!("{0}", msg)); }panic!("{msg}")),
2007        )
2008        .chain(reexport_fragment(&MX_REEXPORTS))
2009        .collect();
2010    sort_wrapper_entries(&mut entries);
2011
2012    let mut seen = std::collections::HashSet::<String>::new();
2013    let mut fragments: Vec<(
2014        RWrapperPriority,
2015        &'static str,
2016        std::borrow::Cow<'static, str>,
2017    )> = Vec::with_capacity(entries.len());
2018    for entry in entries {
2019        let trimmed = match entry.content {
2020            std::borrow::Cow::Borrowed(content) => std::borrow::Cow::Borrowed(content.trim()),
2021            std::borrow::Cow::Owned(content) => std::borrow::Cow::Owned(content.trim().to_string()),
2022        };
2023        if !trimmed.is_empty() && seen.insert(trimmed.to_string()) {
2024            fragments.push((entry.priority, entry.source_file, trimmed));
2025        }
2026    }
2027
2028    // Standalone functions: the default `@title`, the generated `@param`
2029    // fillers and the `@order` of blocks on an author topic are decided
2030    // together, per page.
2031    let standalone: Vec<StandaloneFragment<'_>> = fragments
2032        .iter()
2033        .filter(|(priority, _, _)| *priority == RWrapperPriority::Function)
2034        .map(|(_, source_file, content)| StandaloneFragment {
2035            content,
2036            stem: source_file_stem(source_file),
2037        })
2038        .collect();
2039    let mut resolved = resolve_standalone_pages(&standalone).into_iter();
2040
2041    let mut result: Vec<std::borrow::Cow<'static, str>> = fragments
2042        .into_iter()
2043        .map(|(priority, _, content)| {
2044            if priority == RWrapperPriority::Function {
2045                std::borrow::Cow::Owned(
2046                    resolved
2047                        .next()
2048                        .expect("one resolved fragment per standalone function"),
2049                )
2050            } else {
2051                content
2052            }
2053        })
2054        .collect();
2055
2056    // Topological sort for S7 inheritance ordering
2057    sort_s7_classes(&mut result);
2058
2059    result
2060}
2061
2062// region: standalone-function pages (#1590)
2063
2064/// Prefix of a generated `@param` line in a standalone function's fragment,
2065/// after the `#' ` roxygen lead. Spelled the same as
2066/// `miniextendr_macros::roxygen::PARAM_FILLER_MARKER`, which emits it.
2067#[cfg(not(target_arch = "wasm32"))]
2068const PARAM_FILLER_MARKER: &str = ".__MX_PARAM_FILLER__ ";
2069
2070/// The `@order` line for a block on an author topic. Spelled the same as
2071/// `miniextendr_macros::roxygen::ORDER_AFTER_TOPIC_BLOCKS`, which documents
2072/// why `NaN` sorts the block after the topic's own block.
2073#[cfg(not(target_arch = "wasm32"))]
2074const ORDER_AFTER_TOPIC_BLOCKS: &str = "#' @order NaN";
2075
2076/// A standalone function's wrapper fragment and the stem of its source file
2077/// (`None` for `lib.rs` / `mod.rs`, see [`source_file_stem`]).
2078///
2079/// The stem is the topic an explicit `@rdname <stem>` names to group the
2080/// file's functions on one page (#1289): such a block is on its own file's
2081/// page, not joining a topic defined elsewhere, so it keeps its generated
2082/// `@param` lines where no function on the page documents the argument.
2083#[cfg(not(target_arch = "wasm32"))]
2084struct StandaloneFragment<'a> {
2085    content: &'a str,
2086    stem: Option<String>,
2087}
2088
2089/// Where a standalone function's block lands, read from its own tags.
2090#[cfg(not(target_arch = "wasm32"))]
2091struct StandalonePage {
2092    /// The `.Rd` topic, `None` for an `@noRd` block.
2093    page: Option<String>,
2094    /// The block joins a topic defined elsewhere: `@describeIn`, or an
2095    /// `@rdname` naming neither its file's stem page nor the block's own
2096    /// `@name` / function name.
2097    joined: bool,
2098    /// The `@title` to inject: the function name, for a roxygen block that
2099    /// documents its own page and has no `@title` (roxygen2 renders no page
2100    /// without one).
2101    title: Option<String>,
2102}
2103
2104#[cfg(not(target_arch = "wasm32"))]
2105fn standalone_page(fragment: &StandaloneFragment<'_>) -> StandalonePage {
2106    let content = fragment.content;
2107    let stem = fragment.stem.as_deref();
2108    if has_no_rd_tag(content) {
2109        return StandalonePage {
2110            page: None,
2111            joined: false,
2112            title: None,
2113        };
2114    }
2115    let rdname = roxygen_tag_value(content, "rdname");
2116    let describe_in = roxygen_tag_value(content, "describeIn");
2117    let own_name = roxygen_tag_value(content, "name");
2118    let fn_name = content.lines().find_map(parse_top_level_fn_def_name);
2119    let own_page =
2120        |topic: &str| Some(topic) == stem || Some(topic) == own_name || Some(topic) == fn_name;
2121    let joined = describe_in.is_some() || rdname.is_some_and(|topic| !own_page(topic));
2122    let page = describe_in
2123        .or(rdname)
2124        .or(own_name)
2125        .or(fn_name)
2126        .map(str::to_string);
2127    let is_roxygen_block = content.lines().any(|l| l.trim_start().starts_with("#'"));
2128    let has_title = content.lines().any(|l| l.trim().starts_with("#' @title "));
2129    let title = fn_name
2130        .filter(|_| is_roxygen_block && !has_title && !has_page_assignment_tag(content))
2131        .map(str::to_string);
2132    StandalonePage {
2133        page,
2134        joined,
2135        title,
2136    }
2137}
2138
2139/// Resolve the standalone functions' fragments, in emission order (#1590):
2140///
2141/// - give a roxygen block that picks no page itself (see
2142///   [`has_page_assignment_tag`]) and has no `@title` the function name as
2143///   its title. Such a block documents the function's own page, as in
2144///   roxygen2; grouping functions on one page is opt-in through an explicit
2145///   `@rdname` (#1289);
2146/// - resolve each generated `@param` filler (marked with
2147///   [`PARAM_FILLER_MARKER`] by the macro): keep it, unmarked, when the block
2148///   stays on its own page or its file's stem page (`@rdname <file stem>`)
2149///   and no other block of that page documents the argument; drop it when
2150///   the block joins a topic defined elsewhere (that topic's block documents
2151///   the arguments) or another function on the page documents the argument
2152///   (roxygen2 keeps the later of two `@param` lines for a name, so a filler
2153///   would replace the real text);
2154/// - give a block that joins a topic defined elsewhere `@order NaN`
2155///   ([`ORDER_AFTER_TOPIC_BLOCKS`]), so the topic's own block names and
2156///   titles the merged page whatever the R file order (an author `@order`
2157///   is kept).
2158///
2159/// Only the wrapper file is visible here: an R-file block that joins a
2160/// file-stem page does not count as documenting its arguments. Reading the
2161/// package's `R/*.R` blocks would tie the generated wrappers to R sources the
2162/// build does not track: they are regenerated only when the shared library is
2163/// relinked, so they would not follow an R-file edit.
2164#[cfg(not(target_arch = "wasm32"))]
2165fn resolve_standalone_pages(fragments: &[StandaloneFragment<'_>]) -> Vec<String> {
2166    use std::collections::{HashMap, HashSet};
2167
2168    let pages: Vec<StandalonePage> = fragments.iter().map(standalone_page).collect();
2169
2170    // Arguments each page documents for real (the author's `@param` lines).
2171    let mut documented: HashMap<&str, HashSet<&str>> = HashMap::new();
2172    for (fragment, page) in fragments.iter().zip(&pages) {
2173        let Some(topic) = page.page.as_deref() else {
2174            continue;
2175        };
2176        let names = documented.entry(topic).or_default();
2177        for line in fragment.content.lines() {
2178            if let Some(rest) = line.trim().strip_prefix("#' @param ")
2179                && let Some(token) = rest.split_whitespace().next()
2180            {
2181                names.extend(token.split(',').map(str::trim));
2182            }
2183        }
2184    }
2185
2186    let filler_prefix = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", PARAM_FILLER_MARKER))
    })format!("#' {PARAM_FILLER_MARKER}");
2187    fragments
2188        .iter()
2189        .zip(&pages)
2190        .map(|(fragment, page)| {
2191            let mut kept = Vec::new();
2192            for line in fragment.content.lines() {
2193                let Some(param) = line.trim().strip_prefix(filler_prefix.as_str()) else {
2194                    kept.push(line.to_string());
2195                    continue;
2196                };
2197                let name = param
2198                    .strip_prefix("@param ")
2199                    .and_then(|rest| rest.split_whitespace().next());
2200                let documented_on_page = page
2201                    .page
2202                    .as_deref()
2203                    .zip(name)
2204                    .is_some_and(|(topic, name)| documented[topic].contains(name));
2205                if page.page.is_some() && !page.joined && !documented_on_page {
2206                    kept.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0}", param))
    })format!("#' {param}"));
2207                }
2208            }
2209            let mut content = kept.join("\n");
2210            if page.joined && !content.lines().any(|l| l.trim().starts_with("#' @order ")) {
2211                content = insert_roxygen_line(&content, ORDER_AFTER_TOPIC_BLOCKS);
2212            }
2213            match page.title.as_deref() {
2214                Some(title) => insert_roxygen_line(&content, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @title {0}", title))
    })format!("#' @title {title}")),
2215                None => content,
2216            }
2217        })
2218        .collect()
2219}
2220
2221/// The value of a fragment's first `#' @<tag> <value>` line (its first word).
2222#[cfg(not(target_arch = "wasm32"))]
2223fn roxygen_tag_value<'a>(content: &'a str, tag: &str) -> Option<&'a str> {
2224    content.lines().find_map(|line| {
2225        let rest = line.trim().strip_prefix("#' @")?.strip_prefix(tag)?;
2226        if rest.starts_with(char::is_whitespace) {
2227            rest.split_whitespace().next()
2228        } else {
2229            None
2230        }
2231    })
2232}
2233
2234/// Insert a roxygen line into a fragment at a tag boundary: before the first
2235/// `@export` / `@keywords` / `@source` line, else after the last roxygen line.
2236#[cfg(not(target_arch = "wasm32"))]
2237fn insert_roxygen_line(content: &str, new_line: &str) -> String {
2238    let lines: Vec<&str> = content.lines().collect();
2239    let at = lines
2240        .iter()
2241        .position(|l| {
2242            let t = l.trim();
2243            t.starts_with("#' @export")
2244                || t.starts_with("#' @keywords")
2245                || t.starts_with("#' @source")
2246        })
2247        .or_else(|| {
2248            lines
2249                .iter()
2250                .rposition(|l| l.trim().starts_with("#'"))
2251                .map(|i| i + 1)
2252        })
2253        .unwrap_or(0);
2254    let mut result = lines;
2255    result.insert(at, new_line);
2256    result.join("\n")
2257}
2258
2259// endregion
2260
2261/// Order wrapper entries for emission: by priority (the load-order
2262/// dependencies between sidecar accessors, classes, functions, trait impls and
2263/// vctrs methods), then by source file, then by the line the item starts on.
2264///
2265/// Within one source file that is source order, so the `@description`
2266/// paragraphs and `\usage` entries roxygen merges onto a shared `@rdname` /
2267/// `@describeIn` page appear in the order the Rust file defines them, not in
2268/// link order (#1476). The sort is stable, so entries generated at the same
2269/// file and line (a `macro_rules!` expansion) keep their registration order.
2270#[cfg(not(target_arch = "wasm32"))]
2271fn sort_wrapper_entries(entries: &mut [WrapperFragment]) {
2272    entries.sort_by_key(|e| (e.priority, e.source_file, e.source_line));
2273}
2274
2275#[cfg(not(target_arch = "wasm32"))]
2276/// Check if an R wrapper fragment already assigns itself to a documentation
2277/// page: `@rdname <topic>`, `@describeIn <topic> <desc>`, or `@name <topic>`.
2278///
2279/// A fragment without one documents the function's own page, and only such a
2280/// fragment gets the default `@title` (the function name) when it has none
2281/// (#1289).
2282fn has_page_assignment_tag(content: &str) -> bool {
2283    content.lines().any(|line| {
2284        let trimmed = line.trim();
2285        trimmed.starts_with("#' @rdname ")
2286            || trimmed.starts_with("#' @describeIn ")
2287            || trimmed.starts_with("#' @name ")
2288    })
2289}
2290
2291#[cfg(not(target_arch = "wasm32"))]
2292/// Check if an R wrapper fragment has `@noRd`.
2293fn has_no_rd_tag(content: &str) -> bool {
2294    content.lines().any(|line| {
2295        let trimmed = line.trim();
2296        trimmed == "#' @noRd"
2297    })
2298}
2299
2300#[cfg(not(target_arch = "wasm32"))]
2301/// The stem of a standalone function's source file: the topic an explicit
2302/// `@rdname` names to group the file's functions on one page (see
2303/// [`StandaloneFragment`]). `None` for `lib.rs` / `mod.rs`, whose stems name
2304/// no page of their own.
2305///
2306/// `"src/rust/zero_copy_tests.rs"` → `Some("zero_copy_tests")`
2307/// `"lib.rs"` → `None`
2308fn source_file_stem(path: &str) -> Option<String> {
2309    let file_name = path.rsplit(['/', '\\']).next()?;
2310    let stem = file_name.strip_suffix(".rs").unwrap_or(file_name);
2311    if stem.is_empty() || stem == "lib" || stem == "mod" {
2312        return None;
2313    }
2314    Some(stem.to_string())
2315}
2316
2317#[cfg(not(target_arch = "wasm32"))]
2318/// Sort S7 class definitions so parents come before children.
2319///
2320/// Detects `S7::new_class()` calls, extracts `parent = ClassName` relationships,
2321/// and performs topological sort. Non-S7 entries keep their relative order.
2322fn sort_s7_classes(entries: &mut [std::borrow::Cow<'static, str>]) {
2323    use std::collections::HashMap;
2324
2325    // Parse S7 class definitions: find (index, name, parent)
2326    let mut s7_info: Vec<(usize, String, Option<String>)> = Vec::new();
2327
2328    for (i, entry) in entries.iter().enumerate() {
2329        if let Some(nc_pos) = entry.find("S7::new_class(") {
2330            // Extract class name: "NAME <- S7::new_class("
2331            let before = entry[..nc_pos].trim_end();
2332            let name = before
2333                .strip_suffix("<-")
2334                .or_else(|| before.rsplit_once("<-").map(|(_, r)| r))
2335                .map(|s| s.trim())
2336                .and_then(|s| s.split_whitespace().last());
2337
2338            let Some(name) = name else { continue };
2339
2340            // Extract parent: "parent = ParentName,"
2341            let after = &entry[nc_pos..];
2342            let parent = after.find("parent = ").and_then(|p| {
2343                let rest = &after[p + "parent = ".len()..];
2344                let end = rest.find([',', ')', '\n']).unwrap_or(rest.len());
2345                let p = rest[..end].trim();
2346                if p.is_empty() {
2347                    None
2348                } else {
2349                    Some(p.to_string())
2350                }
2351            });
2352
2353            s7_info.push((i, name.to_string(), parent));
2354        }
2355    }
2356
2357    if s7_info.len() <= 1 {
2358        return;
2359    }
2360
2361    // Build name → position-in-s7_info map.
2362    // Also map placeholder .__MX_CLASS_REF_<Name>__ to the same position, since
2363    // the placeholder carries the Rust type name which equals the R class name
2364    // (before any `class = "Override"` resolution — good enough for ordering).
2365    let mut name_to_pos: HashMap<String, usize> = HashMap::new();
2366    for (pos, (_, name, _)) in s7_info.iter().enumerate() {
2367        name_to_pos.insert(name.clone(), pos);
2368        // Also register the placeholder form so a child class that references
2369        // `parent = .__MX_CLASS_REF_ParentName__` can still be sorted correctly.
2370        name_to_pos.insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".__MX_CLASS_REF_{0}__", name))
    })format!(".__MX_CLASS_REF_{name}__"), pos);
2371    }
2372
2373    // Topological sort: repeatedly emit classes whose parent is already placed
2374    let n = s7_info.len();
2375    let mut order: Vec<usize> = Vec::with_capacity(n);
2376    let mut placed = ::alloc::vec::from_elem_global(false, n)vec![false; n];
2377
2378    for _ in 0..n {
2379        for (pos, (_, _, parent)) in s7_info.iter().enumerate() {
2380            if placed[pos] {
2381                continue;
2382            }
2383            let ready = match parent {
2384                None => true,
2385                Some(pname) => match name_to_pos.get(pname.as_str()) {
2386                    None => true, // external parent
2387                    Some(&pp) => placed[pp],
2388                },
2389            };
2390            if ready {
2391                order.push(pos);
2392                placed[pos] = true;
2393            }
2394        }
2395    }
2396
2397    // Fallback: add any remaining (cycles) in original order
2398    for (pos, &is_placed) in placed.iter().enumerate().take(n) {
2399        if !is_placed {
2400            order.push(pos);
2401        }
2402    }
2403
2404    // Apply: place sorted S7 entries back at their original indices
2405    let s7_indices: Vec<usize> = s7_info.iter().map(|(i, _, _)| *i).collect();
2406    let original: Vec<std::borrow::Cow<'static, str>> =
2407        s7_indices.iter().map(|&i| entries[i].clone()).collect();
2408
2409    for (slot, &src) in order.iter().enumerate() {
2410        entries[s7_indices[slot]] = original[src].clone();
2411    }
2412}
2413// endregion
2414
2415/// The R formal of a `match_arg` parameter, `c("a", "b")`, that the wrappers
2416/// writer splices in place of its placeholder: `choices` (the type's
2417/// `MatchArg::CHOICES`), each quoted and escaped for an R string literal
2418/// ([`escape_r_string`](crate::match_arg::escape_r_string)).
2419///
2420/// With a `default = "..."` (`preferred`: the literal's text without its
2421/// quotes, so escaped as R source is), that choice comes first and the others
2422/// keep their order ([`crate::match_arg::default_first`], the order
2423/// [`crate::match_arg::match_arg_param_with_default`] matches against,
2424/// #1767). An empty `preferred` keeps the declaration order.
2425///
2426/// A `preferred` that names no choice panics with the placeholder: the
2427/// wrappers writer is the only caller, so the panic surfaces as a load-time
2428/// error in the host R session rather than a broken wrapper.
2429#[cfg(not(target_arch = "wasm32"))]
2430#[doc(hidden)]
2431pub fn match_arg_formal(choices: &[&str], preferred: &str, placeholder: &str) -> String {
2432    use crate::match_arg::{default_first, escape_r_string};
2433    let formal = if preferred.is_empty() {
2434        choices.to_vec()
2435    } else {
2436        default_first(choices, |choice| escape_r_string(choice) == preferred).unwrap_or_else(|| {
2437            {
    ::core::panicking::panic_fmt(format_args!("miniextendr: preferred default `{0}` for placeholder `{1}` does not match any choice in {2:?}",
            preferred, placeholder, choices));
}panic!(
2438                "miniextendr: preferred default `{preferred}` for placeholder `{placeholder}` \
2439                 does not match any choice in {choices:?}"
2440            )
2441        })
2442    };
2443    let quoted: Vec<String> = formal
2444        .iter()
2445        .map(|choice| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", escape_r_string(choice)))
    })format!("\"{}\"", escape_r_string(choice)))
2446        .collect();
2447    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "))
2448}
2449
2450/// The trailing arguments a `match_arg` parameter's check passes to
2451/// `.miniextendr_match_arg` / `.miniextendr_match_arg_several` for the
2452/// type's `MatchArg::ALIASES` (#1843), which the wrappers writer splices in
2453/// place of `, <placeholder>`: `, aliases = base::c("grey" = "gray")`, each
2454/// alias and choice escaped for an R string literal. For a type without
2455/// aliases it is empty, so that wrapper keeps the text it had before aliases
2456/// existed. `base::c` is spelled out because the argument is written after
2457/// the shadowing pass, which would otherwise qualify it for a parameter
2458/// named `c`.
2459///
2460/// When an alias is listed, `, listed = " (or \"grey\" for \"gray\")"`
2461/// follows: the clause the check's message appends after the choices,
2462/// rendered here by the same function as the Rust side's messages
2463/// (`match_arg::listed_aliases_clause`), so the two word it alike (#2148). A
2464/// type whose aliases are all unlisted passes no `listed`, and its check
2465/// words its message as without aliases.
2466///
2467/// Aliases a hand-written impl got wrong (empty, `"NA"`, a choice, repeated,
2468/// a prefix of another choice, or naming no choice; the rules
2469/// `#[derive(MatchArg)]` enforces at compile time) panic with the
2470/// placeholder, as [`match_arg_formal`] does for a bad default.
2471#[cfg(not(target_arch = "wasm32"))]
2472#[doc(hidden)]
2473pub fn match_arg_aliases_arg(
2474    choices: &[&str],
2475    aliases: &[crate::match_arg::MatchArgAlias],
2476    placeholder: &str,
2477) -> String {
2478    use crate::match_arg::{alias_problems, escape_r_string, listed_aliases_clause, r_quote};
2479    if aliases.is_empty() {
2480        return String::new();
2481    }
2482    let problems = alias_problems(choices, aliases);
2483    if !problems.is_empty() {
2484        {
    ::core::panicking::panic_fmt(format_args!("miniextendr: the `MatchArg::ALIASES` behind placeholder `{1}` can\'t be used (choices {2:?}): {0}",
            problems.join("; "), placeholder, choices));
};panic!(
2485            "miniextendr: the `MatchArg::ALIASES` behind placeholder `{placeholder}` \
2486             can't be used (choices {choices:?}): {}",
2487            problems.join("; ")
2488        );
2489    }
2490    let pairs: Vec<String> = aliases
2491        .iter()
2492        .map(|alias| {
2493            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\" = \"{1}\"",
                escape_r_string(alias.alias), escape_r_string(alias.choice)))
    })format!(
2494                "\"{}\" = \"{}\"",
2495                escape_r_string(alias.alias),
2496                escape_r_string(alias.choice)
2497            )
2498        })
2499        .collect();
2500    let mut arg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", aliases = base::c({0})",
                pairs.join(", ")))
    })format!(", aliases = base::c({})", pairs.join(", "));
2501    let listed = listed_aliases_clause(choices, aliases, r_quote);
2502    if !listed.is_empty() {
2503        arg.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", listed = \"{0}\"",
                escape_r_string(&listed)))
    })format!(", listed = \"{}\"", escape_r_string(&listed)));
2504    }
2505    arg
2506}
2507
2508/// `content` with one `match_arg` parameter's placeholders resolved from its
2509/// [`MatchArgChoicesEntry`]: every choices placeholder (the formal and the
2510/// check) by [`match_arg_formal`], and the check's `, <aliases placeholder>`
2511/// by [`match_arg_aliases_arg`], which is empty for a type without aliases.
2512#[cfg(not(target_arch = "wasm32"))]
2513fn splice_match_arg_entry(content: &str, entry: &MatchArgChoicesEntry) -> String {
2514    let formal = match_arg_formal(entry.choices, entry.preferred_default, entry.placeholder);
2515    let aliases = match_arg_aliases_arg(entry.choices, entry.aliases, entry.aliases_placeholder);
2516    content
2517        .replace(entry.placeholder, &formal)
2518        .replace(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(", {0}", entry.aliases_placeholder))
    })format!(", {}", entry.aliases_placeholder), &aliases)
2519}
2520
2521// region: R Wrapper File Generation
2522
2523// region: Generic doc marker resolution
2524
2525/// Parse the payload of a `.__MX_GENERIC_DOC__(...)` marker line.
2526///
2527/// Returns `(kind, generic_name, class_name, export, dispatch, no_dots)` on success.
2528/// The marker format (emitted by proc-macros) is:
2529/// ```text
2530/// .__MX_GENERIC_DOC__(kind="S7", generic="get_value", class="MyClass",
2531///                     export=true, dispatch="x", no_dots=false)
2532/// ```
2533/// S4 markers omit `dispatch` and `no_dots` (always `"x"` / `false`).
2534#[cfg(not(target_arch = "wasm32"))]
2535fn parse_generic_doc_marker(marker: &str) -> Option<(String, String, String, bool, String, bool)> {
2536    // Strip prefix and trailing ')'
2537    let inner = marker
2538        .strip_prefix(".__MX_GENERIC_DOC__(")?
2539        .strip_suffix(')')?;
2540
2541    let mut kind = String::new();
2542    let mut generic = String::new();
2543    let mut class = String::new();
2544    let mut export = false;
2545    let mut dispatch = "x".to_string();
2546    let mut no_dots = false;
2547
2548    for part in inner.split(", ") {
2549        let part = part.trim();
2550        if let Some(val) = part.strip_prefix("kind=") {
2551            kind = val.trim_matches('"').to_string();
2552        } else if let Some(val) = part.strip_prefix("generic=") {
2553            generic = val.trim_matches('"').to_string();
2554        } else if let Some(val) = part.strip_prefix("class=") {
2555            class = val.trim_matches('"').to_string();
2556        } else if let Some(val) = part.strip_prefix("export=") {
2557            export = val == "true";
2558        } else if let Some(val) = part.strip_prefix("dispatch=") {
2559            dispatch = val.trim_matches('"').to_string();
2560        } else if let Some(val) = part.strip_prefix("no_dots=") {
2561            no_dots = val == "true";
2562        }
2563    }
2564
2565    if kind.is_empty() || generic.is_empty() || class.is_empty() {
2566        return None;
2567    }
2568
2569    Some((kind, generic, class, export, dispatch, no_dots))
2570}
2571
2572/// Whether `name` is a syntactic R name (letters, digits, `.` and `_`; starts
2573/// with a letter or a `.` not followed by a digit; not a reserved word).
2574///
2575/// Mirrors `is_syntactic_r_name` in `miniextendr-macros`' `naming` module,
2576/// which decides how the class generators spell the same names.
2577#[cfg(not(target_arch = "wasm32"))]
2578fn is_syntactic_r_name(name: &str) -> bool {
2579    const RESERVED: &[&str] = &[
2580        "if",
2581        "else",
2582        "repeat",
2583        "while",
2584        "function",
2585        "for",
2586        "next",
2587        "break",
2588        "TRUE",
2589        "FALSE",
2590        "NULL",
2591        "Inf",
2592        "NaN",
2593        "NA",
2594        "NA_integer_",
2595        "NA_real_",
2596        "NA_character_",
2597        "NA_complex_",
2598        "in",
2599    ];
2600    let mut chars = name.chars();
2601    match chars.next() {
2602        Some(c) if c.is_ascii_alphabetic() => {}
2603        Some('.') => {
2604            if chars.next().is_some_and(|c| c.is_ascii_digit()) {
2605                return false;
2606            }
2607        }
2608        _ => return false,
2609    }
2610    name.chars()
2611        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
2612        && !RESERVED.contains(&name)
2613}
2614
2615/// The argument of a raw `export(...)` NAMESPACE directive: bare for a
2616/// syntactic name, a double-quoted string for an operator such as `[[`
2617/// (`export([[)` does not parse). Must match `r_namespace_name` in
2618/// `miniextendr-macros`' `naming` module, which writes the method blocks'
2619/// directive for the same generic; roxygen2 only merges identical lines.
2620#[cfg(not(target_arch = "wasm32"))]
2621fn r_namespace_name(name: &str) -> String {
2622    if is_syntactic_r_name(name) {
2623        name.to_string()
2624    } else {
2625        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                name.replace('\\', "\\\\").replace('"', "\\\"")))
    })format!("\"{}\"", name.replace('\\', "\\\\").replace('"', "\\\""))
2626    }
2627}
2628
2629/// Synthesise a standalone roxygen doc block for a generic.
2630///
2631/// Produces a block with:
2632/// - `@title` / `@description` describing the generic
2633/// - `@param` lines for each dispatch argument (plus `...` unless no_dots)
2634/// - `@name <generic>` — yields the bare `\alias{<generic>}` that `?generic` resolves
2635/// - `@export` or `@rawNamespace export(<generic>)` as appropriate
2636/// - `NULL` anchor
2637///
2638/// The method blocks emitted by the class generators keep their qualified
2639/// `@name Class-generic` so there is no duplicate-alias regression.
2640#[cfg(not(target_arch = "wasm32"))]
2641fn synthesise_generic_doc_block(
2642    kind: &str,
2643    generic: &str,
2644    classes: &[String],
2645    export: bool,
2646    dispatch: &str,
2647    no_dots: bool,
2648) -> String {
2649    let mut lines: Vec<String> = Vec::new();
2650
2651    // An operator generic (`[[`, `%op%`) is not called as `name()`.
2652    let display = if is_syntactic_r_name(generic) {
2653        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}()`", generic))
    })format!("`{generic}()`")
2654    } else {
2655        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", generic))
    })format!("`{generic}`")
2656    };
2657
2658    // Title
2659    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' The {0} generic", display))
    })format!("#' The {display} generic"));
2660    lines.push("#'".to_string());
2661
2662    // Description
2663    let kind_phrase = if kind == "S4" {
2664        "an S4 generic"
2665    } else {
2666        "an S7 generic"
2667    };
2668    lines.push("#' @description".to_string());
2669    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' {0} is {1} generated by miniextendr. Methods in this",
                display, kind_phrase))
    })format!(
2670        "#' {display} is {kind_phrase} generated by miniextendr. Methods in this"
2671    ));
2672    lines.push("#' package are available for:".to_string());
2673    lines.push("#' \\itemize{".to_string());
2674    for cls in classes {
2675        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\'   \\item \\code{{\\link{{{0}}}}}",
                cls))
    })format!("#'   \\item \\code{{\\link{{{cls}}}}}"));
2676    }
2677    lines.push("#' }".to_string());
2678
2679    // @param lines for dispatch formals
2680    let dispatch_args: Vec<&str> = dispatch.split(',').map(|s| s.trim()).collect();
2681    for arg in &dispatch_args {
2682        lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} An object.", arg))
    })format!("#' @param {arg} An object."));
2683    }
2684    if !no_dots {
2685        lines.push("#' @param ... Passed on to methods.".to_string());
2686    }
2687
2688    // Bare @name — this is what produces the bare \\alias{<generic>} in Rd
2689    lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @name {0}", generic))
    })format!("#' @name {generic}"));
2690
2691    // Export directive
2692    if export {
2693        if kind == "S4" {
2694            // S4 generics use @exportMethod (matches the method blocks)
2695            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @exportMethod {0}", generic))
    })format!("#' @exportMethod {generic}"));
2696        } else {
2697            // S7 generics use @rawNamespace export(...) (matches the method blocks,
2698            // including the quoting of operator names).
2699            lines.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @rawNamespace export({0})",
                r_namespace_name(generic)))
    })format!(
2700                "#' @rawNamespace export({})",
2701                r_namespace_name(generic)
2702            ));
2703        }
2704    }
2705
2706    lines.push("NULL".to_string());
2707
2708    lines.join("\n")
2709}
2710
2711/// Scan `content` for `.__MX_GENERIC_DOC__(...)` marker lines, group by
2712/// generic name, replace the first marker per generic with a synthesised
2713/// standalone doc block, and delete all remaining markers.
2714///
2715/// This is the write-time counterpart to the proc-macro marker emission in
2716/// `s7_class.rs` and `s4_class.rs`.
2717#[cfg(not(target_arch = "wasm32"))]
2718fn resolve_generic_doc_markers(content: String) -> String {
2719    use std::collections::HashMap;
2720
2721    const MARKER_PREFIX: &str = ".__MX_GENERIC_DOC__(";
2722
2723    // First pass: collect all (generic, kind, classes[], export, dispatch, no_dots) grouped
2724    // by generic name.  Preserve insertion order (first class encountered wins for kind/export).
2725    let mut by_generic: HashMap<String, (String, Vec<String>, bool, String, bool)> = HashMap::new();
2726    let mut generic_order: Vec<String> = Vec::new(); // tracks first-seen order
2727
2728    for line in content.lines() {
2729        let trimmed = line.trim();
2730        if !trimmed.starts_with(MARKER_PREFIX) {
2731            continue;
2732        }
2733        if let Some((kind, generic, class, export, dispatch, no_dots)) =
2734            parse_generic_doc_marker(trimmed)
2735        {
2736            let entry = by_generic.entry(generic.clone()).or_insert_with(|| {
2737                generic_order.push(generic.clone());
2738                (kind, Vec::new(), export, dispatch, no_dots)
2739            });
2740            entry.1.push(class);
2741        }
2742    }
2743
2744    if by_generic.is_empty() {
2745        return content;
2746    }
2747
2748    // Second pass: walk the content line by line.  For each generic, the first
2749    // marker line is replaced by the synthesised doc block; subsequent markers
2750    // for the same generic are dropped entirely.
2751    let mut first_seen: std::collections::HashSet<String> = std::collections::HashSet::new();
2752    let mut result = String::with_capacity(content.len() + 512 * by_generic.len());
2753
2754    for line in content.lines() {
2755        let trimmed = line.trim();
2756        if trimmed.starts_with(MARKER_PREFIX) {
2757            if let Some((_kind, generic, _class, _export, _dispatch, _no_dots)) =
2758                parse_generic_doc_marker(trimmed)
2759            {
2760                if first_seen.insert(generic.clone()) {
2761                    // First occurrence: replace with synthesised block
2762                    if let Some((kind, classes, export, dispatch, no_dots)) =
2763                        by_generic.get(&generic)
2764                    {
2765                        let block = synthesise_generic_doc_block(
2766                            kind, &generic, classes, *export, dispatch, *no_dots,
2767                        );
2768                        result.push_str(&block);
2769                        result.push('\n');
2770                    }
2771                }
2772                // Subsequent occurrences: drop the line entirely (no push)
2773                continue;
2774            }
2775        }
2776        result.push_str(line);
2777        result.push('\n');
2778    }
2779
2780    // Trim trailing newlines added by the line-by-line loop and restore the
2781    // original termination (content typically ends with \n).
2782    result
2783}
2784
2785// endregion
2786
2787// region: Inherited param marker resolution
2788
2789/// Parse a `.__MX_INHERITED_PARAM__(...)` marker line.
2790///
2791/// The marker format is:
2792/// ```text
2793/// .__MX_INHERITED_PARAM__(class="R6Dog", parent="R6Animal", method="speak", param="times")
2794/// ```
2795/// Returns `(class, parent, method, param)` on success.
2796#[cfg(not(target_arch = "wasm32"))]
2797fn parse_inherited_param_marker(marker: &str) -> Option<(String, String, String, String)> {
2798    let inner = marker
2799        .strip_prefix(".__MX_INHERITED_PARAM__(")?
2800        .strip_suffix(')')?;
2801
2802    let mut class = String::new();
2803    let mut parent = String::new();
2804    let mut method = String::new();
2805    let mut param = String::new();
2806
2807    for part in inner.split(", ") {
2808        let part = part.trim();
2809        if let Some(val) = part.strip_prefix("class=") {
2810            class = val.trim_matches('"').to_string();
2811        } else if let Some(val) = part.strip_prefix("parent=") {
2812            parent = val.trim_matches('"').to_string();
2813        } else if let Some(val) = part.strip_prefix("method=") {
2814            method = val.trim_matches('"').to_string();
2815        } else if let Some(val) = part.strip_prefix("param=") {
2816            param = val.trim_matches('"').to_string();
2817        }
2818    }
2819
2820    if class.is_empty() || parent.is_empty() || method.is_empty() || param.is_empty() {
2821        return None;
2822    }
2823
2824    Some((class, parent, method, param))
2825}
2826
2827/// Resolve `.__MX_INHERITED_PARAM__(...)` markers.
2828///
2829/// For each marker, checks whether the parent class is in-package and has
2830/// `@param <param>` documented for either:
2831/// - The same method name (in any of its method doc blocks), or
2832/// - The class-level `@param` (emitted in the class header).
2833///
2834/// If the parent is documented → delete the marker line (roxygen2 8.0.0 inherits
2835/// the parent method's `@param` into the subclass method).
2836///
2837/// If the parent is cross-package or the param is not documented there → replace
2838/// with `#' @param {param} (no documentation available)` to preserve the zero-warning
2839/// guarantee on rendered Rd.
2840///
2841/// Cross-package parents: markers are always replaced with the fallback text because
2842/// we cannot inspect foreign packages' wrapper content at write time.
2843#[cfg(not(target_arch = "wasm32"))]
2844fn resolve_inherited_param_markers(content: String) -> String {
2845    use std::collections::{HashMap, HashSet};
2846
2847    const MARKER_PREFIX: &str = ".__MX_INHERITED_PARAM__(";
2848
2849    // Check if the marker is present at all (fast path).
2850    if !content.contains(MARKER_PREFIX) {
2851        return content;
2852    }
2853
2854    // Build an index of in-package class param documentation:
2855    //   class_name → Set<param_name>
2856    // We scan the content for:
2857    //   1. Class-level @param tags: lines like `#' @param <name> ...` appearing
2858    //      between `#' @name <ClassName>` and the R6Class(...) definition.
2859    //   2. Method-level @param tags for a specific method: lines like
2860    //      `    #' @param <name> ...` inside the method's doc block.
2861    //
2862    // Strategy: build a map of (class_name, method_name_or_class) → Set<param_name>
2863    // where method_name_or_class = "" means class-level.
2864    let mut class_method_params: HashMap<(String, String), HashSet<String>> = HashMap::new();
2865
2866    // We need to scan the wrapper content to find documented params.
2867    // Simple heuristic: find `#' @name ClassName` then collect `#' @param` lines
2868    // until the next non-doc line (the R6Class definition).
2869    let lines: Vec<&str> = content.lines().collect();
2870    let mut i = 0;
2871    while i < lines.len() {
2872        let line = lines[i].trim();
2873        // Class-level: `#' @name ClassName` followed by class-level @param lines
2874        if let Some(rest) = line.strip_prefix("#' @name ") {
2875            let class_name = rest.trim().to_string();
2876            // Scan forward for @param lines in the class header (until non-doc)
2877            let mut j = i + 1;
2878            while j < lines.len() {
2879                let next = lines[j].trim();
2880                if next.starts_with("#'") {
2881                    if let Some(param_rest) = next.strip_prefix("#' @param ") {
2882                        if let Some(param_name) = param_rest.split_whitespace().next() {
2883                            class_method_params
2884                                .entry((class_name.clone(), String::new()))
2885                                .or_default()
2886                                .insert(param_name.to_string());
2887                        }
2888                    }
2889                    j += 1;
2890                } else {
2891                    break;
2892                }
2893            }
2894        }
2895        // Method-level: `    #' @description Method \`method_name\`.` or source comment
2896        // Simpler: look for `    #' @param` lines at method indent — attribute to the
2897        // nearest preceding `#' @rdname ClassName` (method blocks carry this).
2898        // Actually, method-level @param inside an R6 class block are indented with 4 spaces.
2899        // We track the current class context from the most recent R6Class definition.
2900        i += 1;
2901    }
2902
2903    // Walk the content to track current R6 class + method context, and also
2904    // build method-level param maps. We do a second pass specifically for method params.
2905    let mut current_class: Option<String> = None;
2906    let mut current_method: Option<String> = None;
2907    i = 0;
2908    while i < lines.len() {
2909        let raw = lines[i];
2910        let trimmed = raw.trim();
2911        // Detect R6Class definition: `ClassName <- R6::R6Class("ClassName",`
2912        if trimmed.contains("R6::R6Class(\"") {
2913            if let Some(start) = trimmed.find("R6::R6Class(\"") {
2914                let rest = &trimmed[start + "R6::R6Class(\"".len()..];
2915                if let Some(end) = rest.find('"') {
2916                    current_class = Some(rest[..end].to_string());
2917                    current_method = None;
2918                }
2919            }
2920        }
2921        // Detect method source comment: `    # ClassName::method_name (file:line)`
2922        if let Some(ref cls) = current_class.clone() {
2923            let prefix = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# {0}::", cls))
    })format!("# {}::", cls);
2924            if trimmed.starts_with(&prefix) {
2925                let rest = &trimmed[prefix.len()..];
2926                let method_name = rest.split_whitespace().next().unwrap_or("").to_string();
2927                if !method_name.is_empty() {
2928                    current_method = Some(method_name);
2929                }
2930            }
2931            // Detect indented method @param: `    #' @param name ...`
2932            if let Some(ref method) = current_method.clone() {
2933                if let Some(rest) = raw.strip_prefix("    #' @param ") {
2934                    if let Some(param_name) = rest.split_whitespace().next() {
2935                        class_method_params
2936                            .entry((cls.clone(), method.clone()))
2937                            .or_default()
2938                            .insert(param_name.to_string());
2939                    }
2940                }
2941            }
2942        }
2943        i += 1;
2944    }
2945
2946    // Second pass: resolve markers.
2947    let mut result = String::with_capacity(content.len());
2948    for line in content.lines() {
2949        let trimmed = line.trim();
2950        // Marker format: `    #' .__MX_INHERITED_PARAM__(class="...", parent="...", method="...", param="...")`
2951        let inner = trimmed.strip_prefix("#' ").unwrap_or(trimmed);
2952        if inner.starts_with(MARKER_PREFIX) {
2953            if let Some((_class, parent, method, param)) = parse_inherited_param_marker(inner) {
2954                // Check if parent is in-package and has the param documented:
2955                // Either at method level (parent, method) or class level (parent, "").
2956                let parent_method_key = (parent.clone(), method.clone());
2957                let parent_class_key = (parent.clone(), String::new());
2958                let documented_in_method = class_method_params
2959                    .get(&parent_method_key)
2960                    .map(|s| s.contains(&param))
2961                    .unwrap_or(false);
2962                let documented_at_class = class_method_params
2963                    .get(&parent_class_key)
2964                    .map(|s| s.contains(&param))
2965                    .unwrap_or(false);
2966
2967                if documented_in_method || documented_at_class {
2968                    // Parent is documented in-package → drop this line entirely.
2969                    // roxygen2 8.0.0 inherits the parent method's @param.
2970                    continue;
2971                } else {
2972                    // Parent not found or param not documented → keep fallback.
2973                    // Reconstruct indentation from the original line.
2974                    let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
2975                    result.push_str(&indent);
2976                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @param {0} (no documentation available)",
                param))
    })format!("#' @param {} (no documentation available)", param));
2977                    result.push('\n');
2978                    continue;
2979                }
2980            }
2981        }
2982        result.push_str(line);
2983        result.push('\n');
2984    }
2985
2986    result
2987}
2988
2989// endregion
2990
2991// region: cross-class return wrapper resolvers
2992
2993/// Scan `content` for `<prefix><RustName>__(<expr>)` markers and replace each
2994/// with whatever `emit` pushes for the resolved class entry (or `None` when
2995/// `RustName` is not registered).
2996///
2997/// Shared scan loop behind [`resolve_scalar_return_wrappers`] and
2998/// [`resolve_list_return_wrappers`]. The two marker families use
2999/// non-overlapping prefixes (`.__MX_WRAP_RETURN_` vs `.__MX_WRAP_LIST_RETURN_`)
3000/// so each resolver only ever consumes its own markers — the scalar resolver
3001/// rewrites *unrecognized* names of its own prefix to the bare expression, so
3002/// a shared prefix would destroy list markers before the list pass ran (#1284).
3003///
3004/// Malformed markers (missing `__(` or the closing `)`) are emitted as-is and
3005/// scanning stops, matching the other placeholder resolvers in this file.
3006#[cfg(not(target_arch = "wasm32"))]
3007fn resolve_wrap_return_markers(
3008    content: &str,
3009    prefix: &str,
3010    class_index: &std::collections::HashMap<&str, &ClassNameEntry>,
3011    emit: impl Fn(&mut String, Option<&ClassNameEntry>, &str),
3012) -> String {
3013    const ARG_OPEN: &str = "__(";
3014    const ARG_CLOSE: char = ')';
3015
3016    let mut result = String::with_capacity(content.len());
3017    let mut remaining = content;
3018    while let Some(start) = remaining.find(prefix) {
3019        result.push_str(&remaining[..start]);
3020        let rest_from_prefix = &remaining[start..];
3021        let marker_body = &rest_from_prefix[prefix.len()..];
3022        let Some(name_end) = marker_body.find(ARG_OPEN) else {
3023            // Malformed placeholder (no opening `__(`) — emit as-is and stop scanning.
3024            result.push_str(prefix);
3025            remaining = marker_body;
3026            break;
3027        };
3028        let rust_name = &marker_body[..name_end];
3029        let after_open = &marker_body[name_end + ARG_OPEN.len()..];
3030        let Some(expr_end) = after_open.find(ARG_CLOSE) else {
3031            // Malformed placeholder (no closing `)`) — emit as-is and stop scanning.
3032            result.push_str(prefix);
3033            remaining = marker_body;
3034            break;
3035        };
3036        let expr = &after_open[..expr_end];
3037        remaining = &after_open[expr_end + ARG_CLOSE.len_utf8()..];
3038        emit(&mut result, class_index.get(rust_name).copied(), expr);
3039    }
3040    result.push_str(remaining);
3041    result
3042}
3043
3044/// What a `.__MX_CLASS_REF_*` placeholder writes when its Rust type has no
3045/// [`ClassNameEntry`], and which registered classes it accepts.
3046#[cfg(not(target_arch = "wasm32"))]
3047#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ClassRefForm {
}
#[automatically_derived]impl ::core::clone::Clone for ClassRefForm {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ClassRefForm { }Copy)]
3048enum ClassRefForm {
3049    /// `.__MX_CLASS_REF_<RustName>__`: the bare Rust name, with a warning.
3050    /// For a class object that must exist: R6 `inherit =`, an S7 parent, an
3051    /// S7 conversion, and the R6 / S7 / S4 class of a `WrapAs*` return or a
3052    /// trait impl.
3053    Loud,
3054    /// `.__MX_CLASS_REF_OR_BARE_<RustName>__`: the bare Rust name, quietly.
3055    /// For a name any string can be: the S3 / Env / vctrs class of a
3056    /// `WrapAs*` return or a trait impl (#2265, #2266).
3057    OrBare,
3058    /// `.__MX_CLASS_REF_OR_ANY_<RustName>__`: `S7::class_any`, also for a
3059    /// registered class that is not S7. For an S7 property class constraint
3060    /// (#203: a getter returning `SEXP`, `PathBuf`, or an R6/S3/S4 type
3061    /// shouldn't break load-time with "object '…' not found"; the property
3062    /// falls back to the permissive class_any it had pre-#154).
3063    OrAny,
3064}
3065
3066/// Replace every `.__MX_CLASS_REF_*<RustName>__` placeholder in `content`
3067/// with the R class name `class_index` registers for `<RustName>` (the
3068/// `class = "..."` override, else the Rust name), or the [`ClassRefForm`]'s
3069/// fallback when none does.
3070///
3071/// A linear scan for the sentinel prefix, without a regex dependency.
3072#[cfg(not(target_arch = "wasm32"))]
3073fn resolve_class_refs(
3074    content: &str,
3075    class_index: &std::collections::HashMap<&str, &ClassNameEntry>,
3076) -> String {
3077    const PREFIX: &str = ".__MX_CLASS_REF_";
3078    const SUFFIX: &str = "__";
3079    // Both start with `PREFIX`, so they are told apart after it matches.
3080    const OR_ANY_PREFIX: &str = ".__MX_CLASS_REF_OR_ANY_";
3081    const OR_BARE_PREFIX: &str = ".__MX_CLASS_REF_OR_BARE_";
3082
3083    let mut result = String::with_capacity(content.len());
3084    let mut remaining = content;
3085    while let Some(start) = remaining.find(PREFIX) {
3086        result.push_str(&remaining[..start]);
3087        let rest_from_prefix = &remaining[start..];
3088        let (form, header_len) = if rest_from_prefix.starts_with(OR_ANY_PREFIX) {
3089            (ClassRefForm::OrAny, OR_ANY_PREFIX.len())
3090        } else if rest_from_prefix.starts_with(OR_BARE_PREFIX) {
3091            (ClassRefForm::OrBare, OR_BARE_PREFIX.len())
3092        } else {
3093            (ClassRefForm::Loud, PREFIX.len())
3094        };
3095        remaining = &rest_from_prefix[header_len..];
3096        let Some(end) = remaining.find(SUFFIX) else {
3097            // Malformed placeholder (no closing __): emit as-is and stop scanning.
3098            result.push_str(&rest_from_prefix[..header_len]);
3099            break;
3100        };
3101        let rust_name = &remaining[..end];
3102        remaining = &remaining[end + SUFFIX.len()..];
3103        match (class_index.get(rust_name), form) {
3104            // An S7 property takes an S7 class only: S7 can't use an R6 /
3105            // S3 / S4 / Env / vctrs class as a constraint.
3106            (Some(entry), ClassRefForm::OrAny) if entry.class_system != "s7" => {
3107                result.push_str("S7::class_any");
3108            }
3109            (Some(entry), _) => result.push_str(entry.r_class_name),
3110            (None, ClassRefForm::OrAny) => result.push_str("S7::class_any"),
3111            (None, ClassRefForm::OrBare) => result.push_str(rust_name),
3112            (None, ClassRefForm::Loud) => {
3113                {
    ::std::io::_eprint(format_args!("miniextendr: unresolved class reference `{0}` in R wrapper — is the class defined in a reachable crate?\n",
            rust_name));
};eprintln!(
3114                    "miniextendr: unresolved class reference `{rust_name}` \
3115                     in R wrapper — is the class defined in a reachable crate?"
3116                );
3117                result.push_str(rust_name);
3118            }
3119        }
3120    }
3121    result.push_str(remaining);
3122    result
3123}
3124
3125/// Resolve scalar `.__MX_WRAP_RETURN_<RustName>__(<expr>)` placeholders
3126/// emitted by class-method wrappers whose Rust return type may name a
3127/// different ExternalPtr-backed class.
3128///
3129/// Unlike `CLASS_REF`, an unresolved return wrapper is a quiet no-op (the bare
3130/// `<expr>`): the syntactic macro-time heuristic intentionally allows false
3131/// positives, and write time is where we know whether `<RustName>` is
3132/// registered in this package.
3133#[cfg(not(target_arch = "wasm32"))]
3134fn resolve_scalar_return_wrappers(
3135    content: &str,
3136    class_index: &std::collections::HashMap<&str, &ClassNameEntry>,
3137) -> String {
3138    resolve_wrap_return_markers(
3139        content,
3140        ".__MX_WRAP_RETURN_",
3141        class_index,
3142        |result, entry, expr| match entry {
3143            Some(entry) => match entry.class_system {
3144                "r6" => {
3145                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}$new(.ptr = {1})",
                entry.r_class_name, expr))
    })format!("{}$new(.ptr = {})", entry.r_class_name, expr));
3146                }
3147                "s7" => {
3148                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}(.ptr = {1})",
                entry.r_class_name, expr))
    })format!("{}(.ptr = {})", entry.r_class_name, expr));
3149                }
3150                "s4" => {
3151                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("methods::new(\"{0}\", ptr = {1})",
                entry.r_class_name, expr))
    })format!(
3152                        "methods::new(\"{}\", ptr = {})",
3153                        entry.r_class_name, expr
3154                    ));
3155                }
3156                _ => {
3157                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("structure({0}, class = \"{1}\")",
                expr, entry.r_class_name))
    })format!(
3158                        "structure({}, class = \"{}\")",
3159                        expr, entry.r_class_name
3160                    ));
3161                }
3162            },
3163            None => result.push_str(expr),
3164        },
3165    )
3166}
3167
3168/// Resolve list-shaped `.__MX_WRAP_LIST_RETURN_<RustName>__(<expr>)`
3169/// placeholders emitted for `Vec<Class>`-returning class methods (#1284).
3170///
3171/// `<expr>` is a bare R list of external pointers (the `IntoRVecElement`
3172/// conversion emitted by `#[derive(ExternalPtr)]`); each element gets the same
3173/// per-element wrap the scalar resolver applies, via `lapply`. Unregistered
3174/// element types fall back to the bare list, mirroring the scalar fallback.
3175#[cfg(not(target_arch = "wasm32"))]
3176fn resolve_list_return_wrappers(
3177    content: &str,
3178    class_index: &std::collections::HashMap<&str, &ClassNameEntry>,
3179) -> String {
3180    resolve_wrap_return_markers(
3181        content,
3182        ".__MX_WRAP_LIST_RETURN_",
3183        class_index,
3184        |result, entry, expr| match entry {
3185            Some(entry) => match entry.class_system {
3186                "r6" => {
3187                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lapply({0}, function(.el) {1}$new(.ptr = .el))",
                expr, entry.r_class_name))
    })format!(
3188                        "lapply({}, function(.el) {}$new(.ptr = .el))",
3189                        expr, entry.r_class_name
3190                    ));
3191                }
3192                "s7" => {
3193                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lapply({0}, function(.el) {1}(.ptr = .el))",
                expr, entry.r_class_name))
    })format!(
3194                        "lapply({}, function(.el) {}(.ptr = .el))",
3195                        expr, entry.r_class_name
3196                    ));
3197                }
3198                "s4" => {
3199                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lapply({0}, function(.el) methods::new(\"{1}\", ptr = .el))",
                expr, entry.r_class_name))
    })format!(
3200                        "lapply({}, function(.el) methods::new(\"{}\", ptr = .el))",
3201                        expr, entry.r_class_name
3202                    ));
3203                }
3204                _ => {
3205                    result.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lapply({0}, function(.el) structure(.el, class = \"{1}\"))",
                expr, entry.r_class_name))
    })format!(
3206                        "lapply({}, function(.el) structure(.el, class = \"{}\"))",
3207                        expr, entry.r_class_name
3208                    ));
3209                }
3210            },
3211            None => result.push_str(expr),
3212        },
3213    )
3214}
3215
3216// endregion
3217
3218/// R source of the `.miniextendr_caller_call` helper, with its comment
3219/// block, as written into the wrappers preamble by
3220/// [`write_r_wrappers_to_file`]: the call a `call = caller` wrapper reports
3221/// (#1450, #1548, #1552), including the frame or call a hand-written helper
3222/// passed as the wrapper's `.call` formal (#1613), and the frame or call a
3223/// `call_arg` wrapper was passed (`own = TRUE`, #1834).
3224#[cfg(not(target_arch = "wasm32"))]
3225const CALLER_CALL_HELPER: &str = r#"# Internal helper: the call a wrapper with a `.call` formal attributes its
3226# conditions to, as written. A `#[miniextendr(noexport, call = caller)]`
3227# wrapper calls it as its first statement, `.mx_call <- .miniextendr_caller_call(.call)`,
3228# with its trailing `.call = NULL` formal (an S3 method has none and calls it
3229# without an argument). A `#[miniextendr(call_arg)]` wrapper binds
3230# `.mx_call <- if (is.null(.call)) sys.call() else .miniextendr_caller_call(.call, own = TRUE)`,
3231# so it calls the helper only for a `.call` that isn't NULL. The calling chain
3232# is [caller's caller] <- [caller] <- [wrapper] <- [this helper]:
3233# `sys.parent(1L)` is the wrapper's frame, `sys.parent(2L)` its caller's.
3234# `call` is what the wrapper's caller passed as `.call`:
3235# - an environment: a hand-written helper between the public function and the
3236#   wrapper passes its caller's frame (`call = parent.frame()` in the helper's
3237#   formals), or a function composing the wrapper its own (`environment()`).
3238#   The result is the call of the closure owning that frame.
3239#   `match(TRUE, ...)` takes the oldest frame with that environment, the
3240#   closure's own, ahead of a later `eval()` over it. An environment that is no
3241#   closure's live frame (`globalenv()`) counts as NULL.
3242# - a call object: used as is.
3243# - NULL, the default: under `own = TRUE`, the wrapper's own call, without
3244#   `.call`. Otherwise, when the wrapper's caller is a closure, that caller's
3245#   call; else (top level, or an `eval()` frame such as a testthat block,
3246#   `source()` or `local()`, whose frame function is not a closure and whose
3247#   call names `eval`) the wrapper's own call, without `.call`.
3248# - anything else: an argument error on `.call` against the wrapper's own call,
3249#   which also catches a positional argument too many.
3250.miniextendr_caller_call <- function(call = NULL, own = FALSE) {
3251  wrapper <- sys.parent(1L)
3252  if (is.environment(call)) {
3253    frames <- sys.frames()
3254    i <- match(TRUE, vapply(frames, identical, NA, call))
3255    if (!is.na(i) && typeof(sys.function(i)) == "closure") return(sys.call(i))
3256  } else if (is.call(call)) {
3257    return(call)
3258  } else if (!is.null(call)) {
3259    .miniextendr_arg_error(".call", "must be NULL, an environment or a call", sys.call(wrapper))
3260  }
3261  if (!own) {
3262    parent <- sys.parent(2L)
3263    if (parent > 0L && typeof(sys.function(parent)) == "closure") return(sys.call(parent))
3264  }
3265  call <- sys.call(wrapper)
3266  call$.call <- NULL
3267  call
3268}
3269"#;
3270
3271/// R source of `.miniextendr_frame_call` as a bare `function(env)`
3272/// expression: the call a generated S3 method's conditions report, resolved
3273/// from the method's frame (#1851).
3274///
3275/// A generated S3 method passes `environment()` as its `.call` and as the
3276/// raise fallback (`CallAttribution::Generic` in the macros), so the success
3277/// path pays no more than for `sys.call()`, and the frame becomes a call only
3278/// when a condition is raised. [`write_r_wrappers_to_file`] binds the
3279/// expression under that name in the preamble ([`FRAME_CALL_HELPER`]) for the
3280/// package's raise helper, the R-side checks (`.miniextendr_arg_error`) and a
3281/// method with a `Call` parameter, which resolves it up front;
3282/// [`RAISE_CONDITION_HELPER_FN`] inlines it, because that copy of the raise
3283/// helper signals deferred conditions from the base namespace, where the
3284/// preamble's binding is not visible.
3285///
3286/// The frame is looked up among the live frames (`sys.frames()`), newest
3287/// first, so the helper works from the method itself, from the raise helper
3288/// the method calls, and from the deferred-condition path, which R runs from
3289/// C while the method's `.Call()` is still on the stack (a `.Call` context
3290/// is not a function frame, so the frame numbers line up). `.Generic` is
3291/// bound in the frame of a method R dispatched (`UseMethod()`, an internal
3292/// generic such as `[[`, `NextMethod()`, a group generic such as `Ops`) and
3293/// not in a method called by name, so a direct call keeps the method's name.
3294/// For a replacement generic R's call is
3295/// `` `$<-.cls`(`*tmp*`, name, value = <value>) ``: the result is the
3296/// assignment as written, `x$name <- value`, which never deparses the value.
3297/// `rbind()` and `cbind()` dispatch from C (`do_bind`) without binding
3298/// `.Generic`, and call the method as `rbind(deparse.level, ...)`; when the
3299/// method's caller is base's `rbind` / `cbind` closure, the result is that
3300/// closure's call, the user's `rbind(x, y)` (#2162).
3301/// No comment inside: the text is inlined into another function. A macro,
3302/// not a `const`, because `concat!` takes literals only.
3303macro_rules! frame_call_helper_fn {
3304    () => {
3305        r#"function(env) {
3306  frames <- sys.frames()
3307  i <- length(frames)
3308  while (i > 0L && !identical(frames[[i]], env)) i <- i - 1L
3309  if (i == 0L) return(NULL)
3310  call <- sys.call(i)
3311  generic <- env[[".Generic"]]
3312  if (is.null(generic) && length(call) == 3L && identical(call[[2L]], quote(deparse.level)) && identical(call[[3L]], quote(...))) {
3313    bind <- if (identical(call[[1L]], quote(rbind))) base::rbind else if (identical(call[[1L]], quote(cbind))) base::cbind
3314    p <- sys.parents()[[i]]
3315    if (!is.null(bind) && p > 0L && identical(sys.function(p), bind)) {
3316      user <- sys.call(p)
3317      user[[1L]] <- call[[1L]]
3318      return(user)
3319    }
3320  }
3321  if (!is.character(generic) || length(generic) != 1L) return(call)
3322  if (length(call) > 1L && identical(call[[2L]], quote(`*tmp*`))) {
3323    call[[2L]] <- as.name(names(formals(sys.function(i)))[[1L]])
3324  }
3325  if (!endsWith(generic, "<-")) {
3326    call[[1L]] <- as.name(generic)
3327    return(call)
3328  }
3329  call$value <- NULL
3330  call[[1L]] <- as.name(substr(generic, 1L, nchar(generic) - 2L))
3331  call("<-", call, quote(value))
3332}"#
3333    };
3334}
3335
3336/// The preamble's `.miniextendr_frame_call` binding of
3337/// [`frame_call_helper_fn!`], with its comment block, as written by
3338/// [`write_r_wrappers_to_file`].
3339#[cfg(not(target_arch = "wasm32"))]
3340const FRAME_CALL_HELPER: &str = "# Internal helper: the call a generated S3 method\'s conditions report, from\n# the method\'s frame (`environment()`, which the method passes as `.call`).\n# Under R\'s dispatch the method\'s own call names the method,\n# `summary.cls(x, a = 1)`, and `.Generic` is bound in its frame; the result\n# names the generic the user called instead: `summary(x, a = 1)`, `x[i]`,\n# `x + 1` for an `Ops` method. For a replacement generic (`$<-`, `[[<-`, `[<-`,\n# `names<-`, ...), which R calls as `` `$<-.cls`(`*tmp*`, name, value = <v>) ``,\n# the result is the assignment as written, `x$name <- value`, with the\n# method\'s first formal as the receiver and the symbol `value` in place of the\n# value, so a large value is never deparsed into the call. `rbind()` and\n# `cbind()` dispatch from C and call the method as `rbind(deparse.level, ...)`;\n# the result is the user\'s call to base\'s `rbind` / `cbind` instead. A method\n# called directly by name has no `.Generic` and keeps its own call. The frame is\n# looked up among the live frames, so the helper serves the method\'s own\n# checks, the raise helper and the conditions deferred while the method\'s\n# `.Call()` runs; a frame that is no longer live gives NULL.\n.miniextendr_frame_call <- function(env) {\n  frames <- sys.frames()\n  i <- length(frames)\n  while (i > 0L && !identical(frames[[i]], env)) i <- i - 1L\n  if (i == 0L) return(NULL)\n  call <- sys.call(i)\n  generic <- env[[\".Generic\"]]\n  if (is.null(generic) && length(call) == 3L && identical(call[[2L]], quote(deparse.level)) && identical(call[[3L]], quote(...))) {\n    bind <- if (identical(call[[1L]], quote(rbind))) base::rbind else if (identical(call[[1L]], quote(cbind))) base::cbind\n    p <- sys.parents()[[i]]\n    if (!is.null(bind) && p > 0L && identical(sys.function(p), bind)) {\n      user <- sys.call(p)\n      user[[1L]] <- call[[1L]]\n      return(user)\n    }\n  }\n  if (!is.character(generic) || length(generic) != 1L) return(call)\n  if (length(call) > 1L && identical(call[[2L]], quote(`*tmp*`))) {\n    call[[2L]] <- as.name(names(formals(sys.function(i)))[[1L]])\n  }\n  if (!endsWith(generic, \"<-\")) {\n    call[[1L]] <- as.name(generic)\n    return(call)\n  }\n  call$value <- NULL\n  call[[1L]] <- as.name(substr(generic, 1L, nchar(generic) - 2L))\n  call(\"<-\", call, quote(value))\n}\n"concat!(
3341    r#"# Internal helper: the call a generated S3 method's conditions report, from
3342# the method's frame (`environment()`, which the method passes as `.call`).
3343# Under R's dispatch the method's own call names the method,
3344# `summary.cls(x, a = 1)`, and `.Generic` is bound in its frame; the result
3345# names the generic the user called instead: `summary(x, a = 1)`, `x[i]`,
3346# `x + 1` for an `Ops` method. For a replacement generic (`$<-`, `[[<-`, `[<-`,
3347# `names<-`, ...), which R calls as `` `$<-.cls`(`*tmp*`, name, value = <v>) ``,
3348# the result is the assignment as written, `x$name <- value`, with the
3349# method's first formal as the receiver and the symbol `value` in place of the
3350# value, so a large value is never deparsed into the call. `rbind()` and
3351# `cbind()` dispatch from C and call the method as `rbind(deparse.level, ...)`;
3352# the result is the user's call to base's `rbind` / `cbind` instead. A method
3353# called directly by name has no `.Generic` and keeps its own call. The frame is
3354# looked up among the live frames, so the helper serves the method's own
3355# checks, the raise helper and the conditions deferred while the method's
3356# `.Call()` runs; a frame that is no longer live gives NULL.
3357.miniextendr_frame_call <- "#,
3358    frame_call_helper_fn!(),
3359    "\n"
3360);
3361
3362/// R source of the `.miniextendr_field_at` helper, with its comment block,
3363/// as written into the wrappers preamble by [`write_r_wrappers_to_file`]: the
3364/// field a position picks in the generated `[[.Class` of an S3 class with
3365/// `s3(r_data_accessors)`, on the bare classed pointer (#1891). The method
3366/// checks for `NA` first (a list's `[[NA]]` is `NULL`, a character vector's
3367/// is `NA`). A position is truncated and a logical is taken, as by a list's
3368/// `[[`; every position that picks no field (past the last one, `0`, a
3369/// negative one) raises `subscriptOutOfBoundsError` with the type's
3370/// field-error classes in front (`class`, the derive's
3371/// `.rdata_error_class_<Type>`, #1899), on the generic's call. Also
3372/// `.miniextendr_field_index_error`, the same method's refusal of an index
3373/// that is neither one name nor one position (#1920), and under
3374/// `lookup = "strict"` of a non-whole number, a logical or `NA` (#1921).
3375#[cfg(not(target_arch = "wasm32"))]
3376const FIELD_AT_HELPER: &str = r#"# Internal helper: the field a position picks on a bare classed pointer, as
3377# `[[` picks a list element: `2.9` is the second field, `TRUE` the first. A
3378# position that picks no field (past the last one, `0`, a negative one)
3379# raises `subscriptOutOfBoundsError`, with the type's own classes (`class`)
3380# in front, reporting the generic's call, `x[[9]]`, resolved from the
3381# method's frame (`env`).
3382.miniextendr_field_at <- function(fields, i, env, class = NULL) {
3383  k <- trunc(i)
3384  if (k < 1 || k > length(fields)) stop(errorCondition("subscript out of bounds", class = c(class, "subscriptOutOfBoundsError"), call = .miniextendr_frame_call(env)))
3385  fields[[k]]
3386}
3387
3388# Internal helper: refuses a `[[` index on a bare classed pointer that is
3389# neither one field name nor one position (`x[[1:2]]`, `x[[list(1)]]`, and
3390# under strict lookup `x[[TRUE]]`, `x[[NA]]` or `x[[1.5]]` too), where R's
3391# `[[.default` would report itself. The type's own classes (`class`) go in
3392# front of R's `notSubsettableError`; the call is the generic's, `x[[1:2]]`,
3393# resolved from the method's frame (`env`). `cls` is the R class.
3394.miniextendr_field_index_error <- function(cls, env, class = NULL, strict = FALSE) {
3395  stop(errorCondition(sprintf("`[[` on a `%s` object takes one field name or one %sposition", cls, if (strict) "whole-number " else ""), class = c(class, "notSubsettableError"), call = .miniextendr_frame_call(env)))
3396}
3397"#;
3398
3399/// R source blocks for the argument-check helpers of the wrappers preamble,
3400/// `.miniextendr_arg_error`, `.miniextendr_match_arg_several` and
3401/// `.miniextendr_match_arg`, with their comment blocks, as written by
3402/// [`write_r_wrappers_to_file`] (they read `.miniextendr_conversion_error_class`,
3403/// bound after them, and `.miniextendr_frame_call`, bound before).
3404/// Each block is emitted only when needed; this ordered array lets the
3405/// equivalence tests evaluate the same source as the wrapper writer.
3406///
3407/// `.miniextendr_match_arg`'s messages are the ones
3408/// [`crate::match_arg::match_arg_param`] and the generated conversion of a
3409/// `match_arg` type word in Rust (#1767): all take their words from
3410/// `match_arg::match_arg_wording!`, and the API tests
3411/// (`miniextendr-api/tests/match_arg_param.rs`) evaluate this source and
3412/// compare them on every input class (#1741).
3413///
3414/// History, kept here because the R comments ship in every package and cite
3415/// no PR numbers (#1832): `.miniextendr_arg_error` is #1591, the `call`
3416/// argument a `call = caller` wrapper passes is #1548, the frame an S3 method
3417/// passes there and the `NULL` of `call = none` are #1851, the strict
3418/// `several_ok` match is #1472, reading a factor as its labels is #1552, the
3419/// `aliases` argument ([`match_arg_aliases_arg`]) is #1843, and the `listed`
3420/// argument, the clause naming the listed aliases, is #2148.
3421#[cfg(not(target_arch = "wasm32"))]
3422#[doc(hidden)]
3423pub const ARG_CHECK_HELPERS: [&str; 3] =
3424    [ARG_ERROR_HELPER, MATCH_ARG_SEVERAL_HELPER, MATCH_ARG_HELPER];
3425
3426#[cfg(not(target_arch = "wasm32"))]
3427const ARG_ERROR_HELPER: &str = r#"# Internal helper: raise an argument error from an R-side check: a
3428# type / length precondition, `no_na`, `inherits`, or a `match_arg` /
3429# `choices` value. The condition is the one a failed Rust conversion raises:
3430# the crate's `conversion_error_class` (`.miniextendr_conversion_error_class`,
3431# at the end of this preamble), then `rust_error`, with
3432# `kind = "conversion"` and `e$param`, so one handler catches an argument
3433# error whichever side finds it. The message is `'<param>' <what>`, or the
3434# author's own `message` (`inherits(..., message = )` / `no_na(message = )`),
3435# used as given. `call` defaults to the wrapper's own call, as `stopifnot()`
3436# reported it; a `call = caller` wrapper passes `.mx_call`, by name
3437# next to a named `message`; an S3 method passes its frame, resolved here to
3438# the generic's call (`.miniextendr_frame_call`); a `call = none` wrapper
3439# passes NULL. Only a failing check calls this: the passing path is one
3440# `isTRUE()` test per check.
3441.miniextendr_arg_error <- function(param, what, call = sys.call(-1L), message = sprintf("'%s' %s", param, what)) {
3442  if (is.environment(call)) call <- .miniextendr_frame_call(call)
3443  stop(structure(
3444    list(message = message, call = call, kind = "conversion", param = param),
3445    class = c(.miniextendr_conversion_error_class, "rust_error", "simpleError", "error", "condition")
3446  ))
3447}
3448"#;
3449
3450/// The check of `#[miniextendr(dots = empty | empty(allow = ..) | forward(allow
3451/// = ..))]` (#2157): a wrapper with such an attribute calls it as
3452/// `if (...length()) .miniextendr_check_dots(...names(), ...length(),
3453/// <formals>, allow = .., forward = TRUE, class = .., call = ..)`, the
3454/// statement `miniextendr-macros`' `dots_policy::DotsPolicy::r_check` writes
3455/// (`forward = TRUE` for `forward` only). The `[[`, `as.list()` and `[[<-`
3456/// field methods of `s3(r_data_accessors)` and an env class's `[[` make the
3457/// `empty` check on a bare pointer (#2174). It builds its own condition, an
3458/// argument error with two more fields, and depends only on the helpers every
3459/// preamble has.
3460#[cfg(not(target_arch = "wasm32"))]
3461const DOTS_CHECK_HELPER: &str = r#"# Internal helper: refuse the arguments in a wrapper's `...` that its
3462# `dots = empty | empty(allow = ...) | forward(allow = ...)` attribute does not
3463# take, or that a generated field method or env class `[[` (`empty`) gets.
3464# The wrapper calls it only when `...length()` is nonzero, with
3465# `...names()` and `...length()`, so no argument is forced. Every name outside
3466# `allow` is refused. An unnamed argument stands for an allowed name given by
3467# position: under `forward` (`forward = TRUE`) it passes, since the function
3468# the dots go on to matches it by position itself; under `empty` nothing reads
3469# it, so only the count matters, and the unnamed arguments past the number of
3470# allowed names not given by name are refused. All of them go in one
3471# condition: `argument` holds each one (`..<i>` for an unnamed one, its
3472# position in `...`) and `suggestion` the formal or allowed name each one most
3473# likely meant, or NA. That is the one name it is a prefix of, else the first
3474# one closest by edit distance (a swap of two neighbours counts as one edit),
3475# at most a third of its length in edits but at least one, and fewer than its
3476# length. The condition is an argument error (`kind = "conversion"`,
3477# `param = "..."`) classed `miniextendr_error_unused_argument` after the
3478# attribute's own `class`, then the crate's conversion classes; a class in
3479# both keeps only its first place. `call` is the wrapper's call by default; a
3480# `call = caller` wrapper passes `.mx_call`, an S3 method its frame (resolved
3481# to the generic's call), a `call = none` wrapper NULL.
3482.miniextendr_check_dots <- function(names, n, formals, allow = character(), forward = FALSE, class = character(), call = sys.call(-1L)) {
3483  if (is.null(names)) names <- character(n)
3484  names[is.na(names)] <- ""
3485  unnamed <- !nzchar(names)
3486  bad <- !unnamed & !(names %in% allow)
3487  if (!forward) bad <- bad | (unnamed & cumsum(unnamed) > length(setdiff(allow, names)))
3488  bad <- which(bad)
3489  if (!length(bad)) return(invisible())
3490  if (is.environment(call)) call <- .miniextendr_frame_call(call)
3491  candidates <- c(formals, allow)
3492  distance <- function(a, b) {
3493    a <- strsplit(a, "", fixed = TRUE)[[1L]]
3494    b <- strsplit(b, "", fixed = TRUE)[[1L]]
3495    d <- matrix(0L, length(a) + 1L, length(b) + 1L)
3496    d[, 1L] <- seq.int(0L, length(a))
3497    d[1L, ] <- seq.int(0L, length(b))
3498    for (i in seq_along(a)) for (j in seq_along(b)) {
3499      d[i + 1L, j + 1L] <- min(d[i, j + 1L] + 1L, d[i + 1L, j] + 1L, d[i, j] + (a[[i]] != b[[j]]))
3500      if (i > 1L && j > 1L && a[[i]] == b[[j - 1L]] && a[[i - 1L]] == b[[j]]) {
3501        d[i + 1L, j + 1L] <- min(d[i + 1L, j + 1L], d[i - 1L, j - 1L] + 1L)
3502      }
3503    }
3504    d[[length(a) + 1L, length(b) + 1L]]
3505  }
3506  suggest <- function(name) {
3507    if (!nzchar(name) || !length(candidates)) return(NA_character_)
3508    prefixed <- candidates[startsWith(candidates, name)]
3509    if (length(prefixed) == 1L) return(prefixed)
3510    edits <- vapply(candidates, distance, 0L, b = name, USE.NAMES = FALSE)
3511    best <- which(edits == min(edits) & edits <= max(1L, nchar(name) %/% 3L) & edits < nchar(name))
3512    if (length(best)) candidates[[best[[1L]]]] else NA_character_
3513  }
3514  unnamed <- !nzchar(names[bad])
3515  argument <- ifelse(unnamed, paste0("..", bad), names[bad])
3516  suggestion <- vapply(names[bad], suggest, "", USE.NAMES = FALSE)
3517  what <- sprintf("'%s'%s", argument, ifelse(unnamed, " (unnamed)", ""))
3518  hint <- !is.na(suggestion)
3519  what[hint] <- sprintf("%s (did you mean '%s'?)", what[hint], suggestion[hint])
3520  message <- sprintf("unused argument%s %s", if (length(bad) > 1L) "s" else "", paste(what, collapse = ", "))
3521  stop(structure(
3522    list(message = message, call = call, kind = "conversion", param = "...", argument = argument, suggestion = suggestion),
3523    class = unique(c(class, "miniextendr_error_unused_argument", .miniextendr_conversion_error_class, "rust_error", "simpleError", "error", "condition"))
3524  ))
3525}
3526"#;
3527
3528#[cfg(not(target_arch = "wasm32"))]
3529const MATCH_ARG_SEVERAL_HELPER: &str = "# Internal helper: strict `match.arg(several.ok = TRUE)` for `several_ok` params.\n# Base R keeps only the elements that match as long as one of them does, so a\n# misspelled entry silently shortens the selection and the per-element check on\n# the Rust side never sees it. Here every element has to match a choice\n# (exactly or as a unique prefix), the first that does not is reported with its\n# position, and `NULL` selects every choice, like an omitted argument does. A\n# factor is read as its labels. `aliases`, a named character vector\n# (`c(grey = \"gray\")`), maps each element typed exactly as an alias to its\n# choice first; a prefix of an alias is not one. `listed` is the text the\n# message names the listed aliases with after the choices\n# (` (or \"grey\" for \"gray\")`, empty when none is listed). The error is an\n# argument error (`.miniextendr_arg_error`) attributed to `call`: by default\n# the wrapper\'s own call, not this helper; a `call = caller` wrapper passes\n# its caller\'s matched call. An `NA` that matches no choice, or a\n# non-character value holding `NA`, is refused as `must not be NA`, the\n# wording of a `no_na` parameter.\n.miniextendr_match_arg_several <- function(arg, choices, arg_name, call = sys.call(-1L), aliases = NULL, listed = \"\") {\n  if (is.null(arg)) return(choices)\n  if (is.factor(arg)) arg <- as.character(arg)\n  if (!is.character(arg)) .miniextendr_arg_error(arg_name, if (is.atomic(arg) && anyNA(arg)) \"must not be NA\" else \"must be NULL or a character vector\", call)\n  if (length(arg) == 0L) .miniextendr_arg_error(arg_name, \"must be of length >= 1\", call)\n  if (!is.null(aliases)) {\n    a <- match(arg, names(aliases))\n    arg[!is.na(a)] <- aliases[a[!is.na(a)]]\n  }\n  i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)\n  bad <- which(is.na(i) | i == 0L)\n  if (anyNA(arg[bad])) .miniextendr_arg_error(arg_name, \"must not be NA\", call)\n  if (length(bad)) {\n    .miniextendr_arg_error(arg_name, sprintf(\"element %d (\\\"%s\\\") should be one of %s%s\", bad[[1L]], arg[[bad[[1L]]]], paste(dQuote(choices, FALSE), collapse = \", \"), listed), call)\n  }\n  choices[i]\n}\n"concat!(
3530    r#"# Internal helper: strict `match.arg(several.ok = TRUE)` for `several_ok` params.
3531# Base R keeps only the elements that match as long as one of them does, so a
3532# misspelled entry silently shortens the selection and the per-element check on
3533# the Rust side never sees it. Here every element has to match a choice
3534# (exactly or as a unique prefix), the first that does not is reported with its
3535# position, and `NULL` selects every choice, like an omitted argument does. A
3536# factor is read as its labels. `aliases`, a named character vector
3537# (`c(grey = "gray")`), maps each element typed exactly as an alias to its
3538# choice first; a prefix of an alias is not one. `listed` is the text the
3539# message names the listed aliases with after the choices
3540# (` (or "grey" for "gray")`, empty when none is listed). The error is an
3541# argument error (`.miniextendr_arg_error`) attributed to `call`: by default
3542# the wrapper's own call, not this helper; a `call = caller` wrapper passes
3543# its caller's matched call. An `NA` that matches no choice, or a
3544# non-character value holding `NA`, is refused as `must not be NA`, the
3545# wording of a `no_na` parameter.
3546.miniextendr_match_arg_several <- function(arg, choices, arg_name, call = sys.call(-1L), aliases = NULL, listed = "") {
3547  if (is.null(arg)) return(choices)
3548  if (is.factor(arg)) arg <- as.character(arg)
3549  if (!is.character(arg)) .miniextendr_arg_error(arg_name, if (is.atomic(arg) && anyNA(arg)) ""#,
3550    crate::match_arg::match_arg_wording!(is_na),
3551    r#"" else ""#,
3552    crate::match_arg::match_arg_wording!(not_character),
3553    r#"", call)
3554  if (length(arg) == 0L) .miniextendr_arg_error(arg_name, "must be of length >= 1", call)
3555  if (!is.null(aliases)) {
3556    a <- match(arg, names(aliases))
3557    arg[!is.na(a)] <- aliases[a[!is.na(a)]]
3558  }
3559  i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)
3560  bad <- which(is.na(i) | i == 0L)
3561  if (anyNA(arg[bad])) .miniextendr_arg_error(arg_name, ""#,
3562    crate::match_arg::match_arg_wording!(is_na),
3563    r#"", call)
3564  if (length(bad)) {
3565    .miniextendr_arg_error(arg_name, sprintf("element %d (\"%s\") "#,
3566    crate::match_arg::match_arg_wording!(not_a_choice),
3567    r#" %s%s", bad[[1L]], arg[[bad[[1L]]]], paste(dQuote(choices, FALSE), collapse = ", "), listed), call)
3568  }
3569  choices[i]
3570}
3571"#
3572);
3573
3574#[cfg(not(target_arch = "wasm32"))]
3575const MATCH_ARG_HELPER: &str = "# Internal helper: scalar `match.arg()` for `match_arg` / `choices` params.\n# `base::match.arg()` says `\'arg\'` in its messages and reports its own frame;\n# this names the argument and raises an argument error\n# (`.miniextendr_arg_error`) attributed to `call`: by default the wrapper\'s own\n# call, for a `call = caller` wrapper its caller\'s matched call.\n# Semantics follow `match.arg(arg, choices)`: `NULL` and the full choice vector\n# (the formal default) select the first choice; otherwise exactly one string\n# that matches a choice exactly or as a unique prefix. A factor is read as its\n# labels. `aliases`, a named character vector (`c(grey = \"gray\")`), maps a\n# string typed exactly as an alias to its choice; a prefix of an alias is not\n# one. `listed` is the text the message names the listed aliases with after\n# the choices (` (or \"grey\" for \"gray\")`, empty when none is listed). `NA`\n# is matched as the string \"NA\", as `pmatch()` does; when that matches no\n# choice, it is refused as `must not be NA`, the wording of a `no_na`\n# parameter, whatever the value\'s length or type (a value of several elements\n# holding such an `NA` is refused for the `NA`, not its length). The Rust side\'s\n# `match_arg_param()` gives a body the same results and messages for a choice\n# argument it matches itself.\n.miniextendr_match_arg <- function(arg, choices, arg_name, call = sys.call(-1L), aliases = NULL, listed = \"\") {\n  if (is.null(arg)) return(choices[[1L]])\n  if (is.factor(arg)) arg <- as.character(arg)\n  if (!is.character(arg)) .miniextendr_arg_error(arg_name, if (is.atomic(arg) && anyNA(arg)) \"must not be NA\" else \"must be NULL or a character vector\", call)\n  if (identical(arg, choices)) return(arg[[1L]])\n  if (length(arg) != 1L) .miniextendr_arg_error(arg_name, if (anyNA(arg) && !pmatch(NA_character_, choices, nomatch = 0L)) \"must not be NA\" else \"must be of length 1\", call)\n  if (!is.null(aliases) && !is.na(a <- match(arg, names(aliases)))) return(aliases[[a]])\n  i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)\n  if (is.na(i) || i == 0L) {\n    if (is.na(arg)) .miniextendr_arg_error(arg_name, \"must not be NA\", call)\n    .miniextendr_arg_error(arg_name, sprintf(\"should be one of %s%s\", paste(dQuote(choices, FALSE), collapse = \", \"), listed), call)\n  }\n  choices[[i]]\n}\n"concat!(
3576    r#"# Internal helper: scalar `match.arg()` for `match_arg` / `choices` params.
3577# `base::match.arg()` says `'arg'` in its messages and reports its own frame;
3578# this names the argument and raises an argument error
3579# (`.miniextendr_arg_error`) attributed to `call`: by default the wrapper's own
3580# call, for a `call = caller` wrapper its caller's matched call.
3581# Semantics follow `match.arg(arg, choices)`: `NULL` and the full choice vector
3582# (the formal default) select the first choice; otherwise exactly one string
3583# that matches a choice exactly or as a unique prefix. A factor is read as its
3584# labels. `aliases`, a named character vector (`c(grey = "gray")`), maps a
3585# string typed exactly as an alias to its choice; a prefix of an alias is not
3586# one. `listed` is the text the message names the listed aliases with after
3587# the choices (` (or "grey" for "gray")`, empty when none is listed). `NA`
3588# is matched as the string "NA", as `pmatch()` does; when that matches no
3589# choice, it is refused as `must not be NA`, the wording of a `no_na`
3590# parameter, whatever the value's length or type (a value of several elements
3591# holding such an `NA` is refused for the `NA`, not its length). The Rust side's
3592# `match_arg_param()` gives a body the same results and messages for a choice
3593# argument it matches itself.
3594.miniextendr_match_arg <- function(arg, choices, arg_name, call = sys.call(-1L), aliases = NULL, listed = "") {
3595  if (is.null(arg)) return(choices[[1L]])
3596  if (is.factor(arg)) arg <- as.character(arg)
3597  if (!is.character(arg)) .miniextendr_arg_error(arg_name, if (is.atomic(arg) && anyNA(arg)) ""#,
3598    crate::match_arg::match_arg_wording!(is_na),
3599    r#"" else ""#,
3600    crate::match_arg::match_arg_wording!(not_character),
3601    r#"", call)
3602  if (identical(arg, choices)) return(arg[[1L]])
3603  if (length(arg) != 1L) .miniextendr_arg_error(arg_name, if (anyNA(arg) && !pmatch(NA_character_, choices, nomatch = 0L)) ""#,
3604    crate::match_arg::match_arg_wording!(is_na),
3605    r#"" else ""#,
3606    crate::match_arg::match_arg_wording!(not_scalar),
3607    r#"", call)
3608  if (!is.null(aliases) && !is.na(a <- match(arg, names(aliases)))) return(aliases[[a]])
3609  i <- pmatch(arg, choices, nomatch = 0L, duplicates.ok = TRUE)
3610  if (is.na(i) || i == 0L) {
3611    if (is.na(arg)) .miniextendr_arg_error(arg_name, ""#,
3612    crate::match_arg::match_arg_wording!(is_na),
3613    r#"", call)
3614    .miniextendr_arg_error(arg_name, sprintf(""#,
3615    crate::match_arg::match_arg_wording!(not_a_choice),
3616    r#" %s%s", paste(dQuote(choices, FALSE), collapse = ", "), listed), call)
3617  }
3618  choices[[i]]
3619}
3620"#
3621);
3622
3623/// One condition-transport body for the package and standalone Rust helpers.
3624/// The resolver is a package binding or a self-contained function expression.
3625macro_rules! raise_condition_helper_fn {
3626    ($resolver:expr) => {
3627        concat!(
3628            r#"function(.val, .call_default) {
3629  # The condition object for one tagged value `.v`.
3630  .cond <- function(.v) {
3631    .msg <- .v$error
3632    # `.v$call` is the call the Rust side captured, NULL to use the wrapper's
3633    # call, or FALSE for a condition raised without one (`call = none`, R's
3634    # `call. = FALSE`), which is signalled with `call = NULL`.
3635    .call <- if (isFALSE(.v$call)) NULL else if (is.null(.v$call)) .call_default else .v$call
3636    # A generated S3 method passes its frame instead of a call, so that the
3637    # generic's call (`summary(x)` for `summary.cls(x)`, the assignment for a
3638    # replacement method) is built only now, when a condition is raised. The
3639    # resolver recovers the generic's call from that method frame.
3640    if (is.environment(.call)) .call <- "#,
3641            $resolver,
3642            r#"(.call)
3643    .class <- .v$class
3644    # `arg_error!` writes the class ".miniextendr_conversion_error_class"
3645    # where the crate's `conversion_error_class` belongs: only the generated R
3646    # knows those classes, bound under that name at the end of the wrappers
3647    # preamble, so they replace it here. The copy of this helper that signals
3648    # deferred conditions lives in the base namespace, where the name is
3649    # unbound and the marker is dropped. A class the condition already has
3650    # (a package's `field_error` class shared with its conversion classes)
3651    # keeps only its first place.
3652    .at <- match(".miniextendr_conversion_error_class", .class)
3653    if (!is.na(.at)) {
3654      .class <- unique(append(.class[-.at], get0(".miniextendr_conversion_error_class", ifnotfound = NULL), after = .at - 1L))
3655    }
3656    # `.v$data` is an optional named list of structured fields (from the
3657    # macros' `data = ...` form). When present, splice its named elements into
3658    # the condition object alongside message/call/kind so handlers can read
3659    # `e$<name>`. `utils::modifyList` keeps the base fields and appends the
3660    # data fields; a malformed (non-list / unnamed) payload is ignored.
3661    # `keep.null = TRUE`: a field the Rust side set to `RValue::Null` is a
3662    # present field whose value is NULL, and must stay in `names(e)`; the
3663    # default would silently drop it (found downstream via a
3664    # `RConditionData::data()` returning an explicit NULL entry).
3665    .data <- .v$data
3666    # A cause the Rust side attached (`RCondition::with_parent`) travels as
3667    # the tagged value `.mx_parent` and becomes the condition object
3668    # `e$parent`, as `rlang::abort(parent = )` chains conditions. It is not
3669    # signalled, and its classes stay out of this condition's.
3670    if (is.list(.data) && !is.null(.data[[".mx_parent", exact = TRUE]])) {
3671      .parent <- .cond(.data[[".mx_parent", exact = TRUE]])
3672      .data[[".mx_parent"]] <- NULL
3673      .data[["parent"]] <- .parent
3674    }
3675    # The failed elements of a container's conversion (a tuple's fields, the
3676    # rows of a `Vec` of tuples) travel as `.mx_errors`, entries
3677    # `list(index, condition)` whose condition is a tagged value; they become
3678    # `e$errors`, each condition built like `e$parent` and not signalled.
3679    if (is.list(.data) && !is.null(.data[[".mx_errors", exact = TRUE]])) {
3680      .errors <- lapply(.data[[".mx_errors", exact = TRUE]], function(.e) {
3681        list(index = .e$index, condition = .cond(.e$condition))
3682      })
3683      .data[[".mx_errors"]] <- NULL
3684      .data[["errors"]] <- .errors
3685    }
3686    .cond_fields <- function(base) {
3687      if (is.null(.data) || !is.list(.data) || is.null(names(.data))) {
3688        base
3689      } else {
3690        utils::modifyList(base, .data, keep.null = TRUE)
3691      }
3692    }
3693    switch(.v$kind,
3694      warning = structure(.cond_fields(list(message = .msg, call = .call, kind = "warning")),
3695        class = c(.class, "rust_warning", "simpleWarning", "warning", "condition")),
3696      message = structure(.cond_fields(list(message = paste0(.msg, "\n"), call = NULL, kind = "message")),
3697        class = c(.class, "rust_message", "simpleMessage", "message", "condition")),
3698      condition = structure(.cond_fields(list(message = .msg, call = .call, kind = "condition")),
3699        class = c(.class, "rust_condition", "simpleCondition", "condition")),
3700      panic = structure(list(message = .msg, call = .call, kind = "panic"),
3701        class = c("rust_error", "simpleError", "error", "condition")),
3702      # error / result_err / none_err / conversion / other: an error whose class
3703      # vector and data (if any) come from the Rust side, e.g. a
3704      # `Result<T, E: RConditionData>`.
3705      structure(.cond_fields(list(message = .msg, call = .call, kind = .v$kind)),
3706        class = c(.class, "rust_error", "simpleError", "error", "condition")))
3707  }
3708  .c <- .cond(.val)
3709  switch(.val$kind,
3710    warning = warning(.c),
3711    message = message(.c),
3712    condition = signalCondition(.c),
3713    stop(.c)
3714  )
3715  invisible(NULL)
3716}"#
3717        )
3718    };
3719}
3720
3721/// R source of the `.miniextendr_raise_condition` helper as a bare
3722/// `function(.val, .call_default)` expression.
3723///
3724/// [`crate::deferred_condition`] evaluates this self-contained expression
3725/// once (in the base namespace) to signal queued conditions from Rust without
3726/// depending on any package namespace. [`write_r_wrappers_to_file`] renders
3727/// the same template with the preamble's `.miniextendr_frame_call` binding as
3728/// the resolver instead of a second inline copy. Keeping one source
3729/// guarantees identical class layering and `data` splicing.
3730///
3731/// The helper dispatches on `.val$kind` (see [`crate::error_value::kind`]) and
3732/// re-raises the tagged Rust condition value as the matching R condition:
3733/// `stop()` for the error kinds, `warning()` / `message()` /
3734/// `signalCondition()` for the non-fatal ones (returning `invisible(NULL)`).
3735/// The marker class it replaces is the one `arg_error!` writes (#1740). A
3736/// frame in the call slot or as the default (a generated S3 method passes
3737/// `environment()`, #1851) is resolved to the generic's call with an inline
3738/// copy of [`frame_call_helper_fn!`], since the base-namespace copy of this
3739/// helper cannot see the preamble's `.miniextendr_frame_call`.
3740pub(crate) const RAISE_CONDITION_HELPER_FN: &str =
3741    "function(.val, .call_default) {\n  # The condition object for one tagged value `.v`.\n  .cond <- function(.v) {\n    .msg <- .v$error\n    # `.v$call` is the call the Rust side captured, NULL to use the wrapper\'s\n    # call, or FALSE for a condition raised without one (`call = none`, R\'s\n    # `call. = FALSE`), which is signalled with `call = NULL`.\n    .call <- if (isFALSE(.v$call)) NULL else if (is.null(.v$call)) .call_default else .v$call\n    # A generated S3 method passes its frame instead of a call, so that the\n    # generic\'s call (`summary(x)` for `summary.cls(x)`, the assignment for a\n    # replacement method) is built only now, when a condition is raised. The\n    # resolver recovers the generic\'s call from that method frame.\n    if (is.environment(.call)) .call <- (function(env) {\n  frames <- sys.frames()\n  i <- length(frames)\n  while (i > 0L && !identical(frames[[i]], env)) i <- i - 1L\n  if (i == 0L) return(NULL)\n  call <- sys.call(i)\n  generic <- env[[\".Generic\"]]\n  if (is.null(generic) && length(call) == 3L && identical(call[[2L]], quote(deparse.level)) && identical(call[[3L]], quote(...))) {\n    bind <- if (identical(call[[1L]], quote(rbind))) base::rbind else if (identical(call[[1L]], quote(cbind))) base::cbind\n    p <- sys.parents()[[i]]\n    if (!is.null(bind) && p > 0L && identical(sys.function(p), bind)) {\n      user <- sys.call(p)\n      user[[1L]] <- call[[1L]]\n      return(user)\n    }\n  }\n  if (!is.character(generic) || length(generic) != 1L) return(call)\n  if (length(call) > 1L && identical(call[[2L]], quote(`*tmp*`))) {\n    call[[2L]] <- as.name(names(formals(sys.function(i)))[[1L]])\n  }\n  if (!endsWith(generic, \"<-\")) {\n    call[[1L]] <- as.name(generic)\n    return(call)\n  }\n  call$value <- NULL\n  call[[1L]] <- as.name(substr(generic, 1L, nchar(generic) - 2L))\n  call(\"<-\", call, quote(value))\n})(.call)\n    .class <- .v$class\n    # `arg_error!` writes the class \".miniextendr_conversion_error_class\"\n    # where the crate\'s `conversion_error_class` belongs: only the generated R\n    # knows those classes, bound under that name at the end of the wrappers\n    # preamble, so they replace it here. The copy of this helper that signals\n    # deferred conditions lives in the base namespace, where the name is\n    # unbound and the marker is dropped. A class the condition already has\n    # (a package\'s `field_error` class shared with its conversion classes)\n    # keeps only its first place.\n    .at <- match(\".miniextendr_conversion_error_class\", .class)\n    if (!is.na(.at)) {\n      .class <- unique(append(.class[-.at], get0(\".miniextendr_conversion_error_class\", ifnotfound = NULL), after = .at - 1L))\n    }\n    # `.v$data` is an optional named list of structured fields (from the\n    # macros\' `data = ...` form). When present, splice its named elements into\n    # the condition object alongside message/call/kind so handlers can read\n    # `e$<name>`. `utils::modifyList` keeps the base fields and appends the\n    # data fields; a malformed (non-list / unnamed) payload is ignored.\n    # `keep.null = TRUE`: a field the Rust side set to `RValue::Null` is a\n    # present field whose value is NULL, and must stay in `names(e)`; the\n    # default would silently drop it (found downstream via a\n    # `RConditionData::data()` returning an explicit NULL entry).\n    .data <- .v$data\n    # A cause the Rust side attached (`RCondition::with_parent`) travels as\n    # the tagged value `.mx_parent` and becomes the condition object\n    # `e$parent`, as `rlang::abort(parent = )` chains conditions. It is not\n    # signalled, and its classes stay out of this condition\'s.\n    if (is.list(.data) && !is.null(.data[[\".mx_parent\", exact = TRUE]])) {\n      .parent <- .cond(.data[[\".mx_parent\", exact = TRUE]])\n      .data[[\".mx_parent\"]] <- NULL\n      .data[[\"parent\"]] <- .parent\n    }\n    # The failed elements of a container\'s conversion (a tuple\'s fields, the\n    # rows of a `Vec` of tuples) travel as `.mx_errors`, entries\n    # `list(index, condition)` whose condition is a tagged value; they become\n    # `e$errors`, each condition built like `e$parent` and not signalled.\n    if (is.list(.data) && !is.null(.data[[\".mx_errors\", exact = TRUE]])) {\n      .errors <- lapply(.data[[\".mx_errors\", exact = TRUE]], function(.e) {\n        list(index = .e$index, condition = .cond(.e$condition))\n      })\n      .data[[\".mx_errors\"]] <- NULL\n      .data[[\"errors\"]] <- .errors\n    }\n    .cond_fields <- function(base) {\n      if (is.null(.data) || !is.list(.data) || is.null(names(.data))) {\n        base\n      } else {\n        utils::modifyList(base, .data, keep.null = TRUE)\n      }\n    }\n    switch(.v$kind,\n      warning = structure(.cond_fields(list(message = .msg, call = .call, kind = \"warning\")),\n        class = c(.class, \"rust_warning\", \"simpleWarning\", \"warning\", \"condition\")),\n      message = structure(.cond_fields(list(message = paste0(.msg, \"\\n\"), call = NULL, kind = \"message\")),\n        class = c(.class, \"rust_message\", \"simpleMessage\", \"message\", \"condition\")),\n      condition = structure(.cond_fields(list(message = .msg, call = .call, kind = \"condition\")),\n        class = c(.class, \"rust_condition\", \"simpleCondition\", \"condition\")),\n      panic = structure(list(message = .msg, call = .call, kind = \"panic\"),\n        class = c(\"rust_error\", \"simpleError\", \"error\", \"condition\")),\n      # error / result_err / none_err / conversion / other: an error whose class\n      # vector and data (if any) come from the Rust side, e.g. a\n      # `Result<T, E: RConditionData>`.\n      structure(.cond_fields(list(message = .msg, call = .call, kind = .v$kind)),\n        class = c(.class, \"rust_error\", \"simpleError\", \"error\", \"condition\")))\n  }\n  .c <- .cond(.val)\n  switch(.val$kind,\n    warning = warning(.c),\n    message = message(.c),\n    condition = signalCondition(.c),\n    stop(.c)\n  )\n  invisible(NULL)\n}"raise_condition_helper_fn!(concat!("(", frame_call_helper_fn!(), ")"));
3742
3743/// The package preamble already binds the resolver; reuse it there.
3744#[cfg(not(target_arch = "wasm32"))]
3745const WRAPPER_RAISE_CONDITION_HELPER_FN: &str =
3746    "function(.val, .call_default) {\n  # The condition object for one tagged value `.v`.\n  .cond <- function(.v) {\n    .msg <- .v$error\n    # `.v$call` is the call the Rust side captured, NULL to use the wrapper\'s\n    # call, or FALSE for a condition raised without one (`call = none`, R\'s\n    # `call. = FALSE`), which is signalled with `call = NULL`.\n    .call <- if (isFALSE(.v$call)) NULL else if (is.null(.v$call)) .call_default else .v$call\n    # A generated S3 method passes its frame instead of a call, so that the\n    # generic\'s call (`summary(x)` for `summary.cls(x)`, the assignment for a\n    # replacement method) is built only now, when a condition is raised. The\n    # resolver recovers the generic\'s call from that method frame.\n    if (is.environment(.call)) .call <- .miniextendr_frame_call(.call)\n    .class <- .v$class\n    # `arg_error!` writes the class \".miniextendr_conversion_error_class\"\n    # where the crate\'s `conversion_error_class` belongs: only the generated R\n    # knows those classes, bound under that name at the end of the wrappers\n    # preamble, so they replace it here. The copy of this helper that signals\n    # deferred conditions lives in the base namespace, where the name is\n    # unbound and the marker is dropped. A class the condition already has\n    # (a package\'s `field_error` class shared with its conversion classes)\n    # keeps only its first place.\n    .at <- match(\".miniextendr_conversion_error_class\", .class)\n    if (!is.na(.at)) {\n      .class <- unique(append(.class[-.at], get0(\".miniextendr_conversion_error_class\", ifnotfound = NULL), after = .at - 1L))\n    }\n    # `.v$data` is an optional named list of structured fields (from the\n    # macros\' `data = ...` form). When present, splice its named elements into\n    # the condition object alongside message/call/kind so handlers can read\n    # `e$<name>`. `utils::modifyList` keeps the base fields and appends the\n    # data fields; a malformed (non-list / unnamed) payload is ignored.\n    # `keep.null = TRUE`: a field the Rust side set to `RValue::Null` is a\n    # present field whose value is NULL, and must stay in `names(e)`; the\n    # default would silently drop it (found downstream via a\n    # `RConditionData::data()` returning an explicit NULL entry).\n    .data <- .v$data\n    # A cause the Rust side attached (`RCondition::with_parent`) travels as\n    # the tagged value `.mx_parent` and becomes the condition object\n    # `e$parent`, as `rlang::abort(parent = )` chains conditions. It is not\n    # signalled, and its classes stay out of this condition\'s.\n    if (is.list(.data) && !is.null(.data[[\".mx_parent\", exact = TRUE]])) {\n      .parent <- .cond(.data[[\".mx_parent\", exact = TRUE]])\n      .data[[\".mx_parent\"]] <- NULL\n      .data[[\"parent\"]] <- .parent\n    }\n    # The failed elements of a container\'s conversion (a tuple\'s fields, the\n    # rows of a `Vec` of tuples) travel as `.mx_errors`, entries\n    # `list(index, condition)` whose condition is a tagged value; they become\n    # `e$errors`, each condition built like `e$parent` and not signalled.\n    if (is.list(.data) && !is.null(.data[[\".mx_errors\", exact = TRUE]])) {\n      .errors <- lapply(.data[[\".mx_errors\", exact = TRUE]], function(.e) {\n        list(index = .e$index, condition = .cond(.e$condition))\n      })\n      .data[[\".mx_errors\"]] <- NULL\n      .data[[\"errors\"]] <- .errors\n    }\n    .cond_fields <- function(base) {\n      if (is.null(.data) || !is.list(.data) || is.null(names(.data))) {\n        base\n      } else {\n        utils::modifyList(base, .data, keep.null = TRUE)\n      }\n    }\n    switch(.v$kind,\n      warning = structure(.cond_fields(list(message = .msg, call = .call, kind = \"warning\")),\n        class = c(.class, \"rust_warning\", \"simpleWarning\", \"warning\", \"condition\")),\n      message = structure(.cond_fields(list(message = paste0(.msg, \"\\n\"), call = NULL, kind = \"message\")),\n        class = c(.class, \"rust_message\", \"simpleMessage\", \"message\", \"condition\")),\n      condition = structure(.cond_fields(list(message = .msg, call = .call, kind = \"condition\")),\n        class = c(.class, \"rust_condition\", \"simpleCondition\", \"condition\")),\n      panic = structure(list(message = .msg, call = .call, kind = \"panic\"),\n        class = c(\"rust_error\", \"simpleError\", \"error\", \"condition\")),\n      # error / result_err / none_err / conversion / other: an error whose class\n      # vector and data (if any) come from the Rust side, e.g. a\n      # `Result<T, E: RConditionData>`.\n      structure(.cond_fields(list(message = .msg, call = .call, kind = .v$kind)),\n        class = c(.class, \"rust_error\", \"simpleError\", \"error\", \"condition\")))\n  }\n  .c <- .cond(.val)\n  switch(.val$kind,\n    warning = warning(.c),\n    message = message(.c),\n    condition = signalCondition(.c),\n    stop(.c)\n  )\n  invisible(NULL)\n}"raise_condition_helper_fn!(".miniextendr_frame_call");
3747
3748/// Shared method lookup for environment classes. Each returned closure gets
3749/// its own receiver-binding frame. An inherent method keeps its original
3750/// enclosure behind that frame, so native symbols and author-supplied R code
3751/// never resolve through the lookup helper's locals (#1677). Field lookup and
3752/// its condition call stay in the S3 method. Flat trait lookup must find a
3753/// unique method; inherent methods and explicit trait namespaces take priority.
3754#[cfg(not(target_arch = "wasm32"))]
3755const ENV_METHOD_HELPER: &str = r#"# Internal helper: bind an environment class's methods to one receiver.
3756# The class's `$` / `[[` methods handle fields before calling this lookup.
3757.miniextendr_env_method <- function(self, name, methods) {
3758  obj <- methods[[name]]
3759  if (is.environment(obj)) {
3760    bound <- new.env(parent = emptyenv())
3761    for (method_name in names(obj)) {
3762      method <- obj[[method_name]]
3763      if (is.function(method)) {
3764        if (isTRUE(attr(method, ".__mx_instance__"))) {
3765          local({
3766            m <- method
3767            bound[[method_name]] <<- function(...) m(self, ...)
3768          })
3769        } else {
3770          bound[[method_name]] <- method
3771        }
3772      }
3773    }
3774    bound
3775  } else if (is.null(obj)) {
3776    matches <- list()
3777    for (ns_name in names(methods)) {
3778      ns <- methods[[ns_name]]
3779      if (is.environment(ns) && exists(name, envir = ns, inherits = FALSE)) {
3780        method <- ns[[name]]
3781        if (is.function(method)) matches[[ns_name]] <- method
3782      }
3783    }
3784    if (!length(matches)) return(NULL)
3785    if (length(matches) > 1L) {
3786      traits <- sort(names(matches))
3787      stop(errorCondition(
3788        sprintf("Method '%s' is provided by multiple traits (%s). Use obj$Trait to select a trait explicitly.", name, paste(traits, collapse = ", ")),
3789        class = "miniextendr_ambiguous_method", method = name, traits = traits,
3790        call = .miniextendr_frame_call(parent.frame())
3791      ))
3792    }
3793    m <- matches[[1L]]
3794    if (isTRUE(attr(m, ".__mx_instance__"))) {
3795      s <- self
3796      function(...) m(s, ...)
3797    } else {
3798      m
3799    }
3800  } else {
3801    environment(obj) <- list2env(list(.mx_self = self), parent = environment(obj))
3802    obj
3803  }
3804}
3805"#;
3806
3807/// The `.miniextendr_conversion_error_class` binding that closes the wrappers
3808/// preamble: the classes `.miniextendr_arg_error` puts on every R-side
3809/// argument error, from the [`MX_CONVERSION_ERROR_CLASS`] entry that
3810/// `miniextendr_init!` registers for the package crate (#1591).
3811///
3812/// The Rust conversion arms carry the same classes, emitted by the macro from
3813/// the same `[package.metadata.miniextendr]` key, so the two paths agree for
3814/// every item of that crate. A package has one `miniextendr_init!`, hence one
3815/// entry; with none (or a crate that sets no class) the binding is `NULL`.
3816#[cfg(not(target_arch = "wasm32"))]
3817fn conversion_error_class_binding() -> String {
3818    format_conversion_error_class_binding(conversion_error_class())
3819}
3820
3821/// [`conversion_error_class_binding`] for an explicit class list.
3822#[cfg(not(target_arch = "wasm32"))]
3823fn format_conversion_error_class_binding(classes: &[&str]) -> String {
3824    let value = if classes.is_empty() {
3825        "NULL".to_string()
3826    } else {
3827        let quoted: Vec<String> = classes
3828            .iter()
3829            .map(|c| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"",
                c.replace('\\', "\\\\").replace('"', "\\\"")))
    })format!("\"{}\"", c.replace('\\', "\\\\").replace('"', "\\\"")))
3830            .collect();
3831        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("c({0})", quoted.join(", ")))
    })format!("c({})", quoted.join(", "))
3832    };
3833    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("# Internal: the crate\'s `conversion_error_class` ([package.metadata.miniextendr]),\n# the classes of every argument error ahead of `rust_error`; NULL when unset.\n.miniextendr_conversion_error_class <- {0}",
                value))
    })format!(
3834        "# Internal: the crate's `conversion_error_class` ([package.metadata.miniextendr]),\n\
3835         # the classes of every argument error ahead of `rust_error`; NULL when unset.\n\
3836         .miniextendr_conversion_error_class <- {value}"
3837    )
3838}
3839
3840/// The comment block that opens the wrappers preamble, ahead of the
3841/// `.miniextendr_raise_condition` binding, as written by
3842/// [`write_r_wrappers_to_file`].
3843#[cfg(not(target_arch = "wasm32"))]
3844const WRAPPERS_PREAMBLE_HEADER: &str =
3845    "# This file is generated by the miniextendr proc-macro during package build.
3846# Any manual changes will be overwritten.
3847#
3848# To regenerate: rebuild the package (R CMD INSTALL or devtools::install).
3849# nolint start
3850# nocov start
3851
3852# Internal helper: re-raise a tagged Rust error/condition value as an R condition.
3853# Generated wrappers call this whenever `.Call()` returns a `rust_condition_value`.
3854# `.call_default` is the wrapper's `sys.call()` (or its `.mx_call`, the
3855# caller's call as written, for `#[miniextendr(noexport, call = caller)]` entry
3856# points, which honours a `.call` a helper passed on; an S3 method's frame,
3857# `environment()`, resolved to the generic's call here; NULL for a
3858# `call = none` wrapper), used as the fallback when the Rust panic payload
3859# didn't carry a captured call (e.g. lambda contexts that pass `.call = NULL`
3860# to `.Call`). For error/panic kinds `stop()` longjmps; for
3861# warning/message/condition the helper signals and returns invisible(NULL),
3862# which the wrapper's surrounding `return(...)` propagates as its result.
3863";
3864
3865/// Emit an optional preamble helper only when a collected fragment names it.
3866///
3867/// A name in a roxygen comment also keeps its helper, which is harmless.
3868/// The one dependency between optional helpers is explicit:
3869/// `.miniextendr_caller_call` raises through `.miniextendr_arg_error`. The
3870/// helpers every preamble has (condition transport, the frame resolver, the
3871/// conversion-error class) are written unconditionally.
3872#[cfg(not(target_arch = "wasm32"))]
3873fn append_used_wrapper_helpers(content: &mut String, fragments: &[std::borrow::Cow<'_, str>]) {
3874    let uses = |name: &str| fragments.iter().any(|fragment| fragment.contains(name));
3875    let caller = uses(".miniextendr_caller_call");
3876    // Generated calls have no space before '('; include it to distinguish
3877    // the scalar matcher from the several-choice matcher's name.
3878    let scalar = uses(".miniextendr_match_arg(");
3879    let several = uses(".miniextendr_match_arg_several(");
3880    for (needed, helper) in [
3881        (caller, CALLER_CALL_HELPER),
3882        (
3883            uses(".miniextendr_field_at") || uses(".miniextendr_field_index_error"),
3884            FIELD_AT_HELPER,
3885        ),
3886        (uses(".miniextendr_env_method"), ENV_METHOD_HELPER),
3887        (uses(".miniextendr_check_dots("), DOTS_CHECK_HELPER),
3888        (
3889            caller || scalar || several || uses(".miniextendr_arg_error"),
3890            ARG_ERROR_HELPER,
3891        ),
3892        (several, MATCH_ARG_SEVERAL_HELPER),
3893        (scalar, MATCH_ARG_HELPER),
3894    ] {
3895        if needed {
3896            content.push_str(helper);
3897            content.push('\n');
3898        }
3899    }
3900}
3901
3902/// Write all R wrapper entries to a file.
3903///
3904/// Called from [`miniextendr_write_wrappers`] (via `dyn.load`/`.Call` of the
3905/// installed shared object). All distributed_slice entries from `#[miniextendr]`
3906/// items are available because stub.c force-loads the whole user crate.
3907///
3908/// `r_dir` is the package's `R/` directory. With it, the `reexport!` names
3909/// are also checked against the package's hand-written R files (the code
3910/// files R installs from `R/`); without it, only against the wrappers.
3911///
3912/// Host-only — wasm32 doesn't run wrapper-gen.
3913#[cfg(not(target_arch = "wasm32"))]
3914pub fn write_r_wrappers_to_file(path: &str, r_dir: Option<&str>) {
3915    // Build the new content in memory; `wrappers_file_content` prepends the
3916    // header (marker line + version/fingerprint line) once the body is final.
3917    let mut content = String::from(WRAPPERS_PREAMBLE_HEADER);
3918    content.push_str(".miniextendr_raise_condition <- ");
3919    content.push_str(WRAPPER_RAISE_CONDITION_HELPER_FN);
3920    content.push_str("\n\n");
3921    content.push_str(FRAME_CALL_HELPER);
3922    content.push('\n');
3923    let fragments = collect_r_wrappers();
3924    append_used_wrapper_helpers(&mut content, &fragments);
3925    content.push_str(&conversion_error_class_binding());
3926    content.push_str("\n\n");
3927
3928    for fragment in fragments {
3929        content.push_str(fragment.as_ref());
3930        content.push_str("\n\n");
3931    }
3932
3933    content.push_str("# nocov end\n# nolint end\n");
3934
3935    // Replace match_arg choices placeholders with actual enum choices.
3936    // If the entry has a `preferred_default`, that choice comes first —
3937    // `.miniextendr_match_arg()` returns `arg[1]` when arg is the formal
3938    // default, so the position-0 element becomes the effective default. The
3939    // check's aliases placeholder becomes its `aliases =` argument, or
3940    // nothing (#1843).
3941    for entry in MX_MATCH_ARG_CHOICES.iter() {
3942        content = splice_match_arg_entry(&content, entry);
3943    }
3944
3945    // Replace match_arg @param doc placeholders with human-readable choice descriptions
3946    for entry in MX_MATCH_ARG_PARAM_DOCS.iter() {
3947        let choices = (entry.choices_str)();
3948        let prefix = if entry.several_ok {
3949            "One or more of"
3950        } else {
3951            "One of"
3952        };
3953        let replacement = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1} {2}{0}.", entry.suffix, prefix,
                choices))
    })format!("{prefix} {choices}{}.", entry.suffix);
3954        content = content.replace(entry.placeholder, &replacement);
3955    }
3956
3957    // Replace .__MX_S7_SIDECAR_PROP_DOCS_<TypeName>__ placeholders with @prop lines.
3958    //
3959    // Each S7 class wrapper with `r_data_accessors` embeds one placeholder per type.
3960    // We collect all entries for each type name and emit `#' @prop field doc` lines.
3961    {
3962        use std::collections::HashMap;
3963        // Group entries by rust_type
3964        let mut by_type: HashMap<&'static str, Vec<&SidecarPropEntry>> = HashMap::new();
3965        for entry in MX_S7_SIDECAR_PROPS.iter() {
3966            by_type.entry(entry.rust_type).or_default().push(entry);
3967        }
3968
3969        const SIDECAR_PREFIX: &str = ".__MX_S7_SIDECAR_PROP_DOCS_";
3970        const SIDECAR_SUFFIX: &str = "__";
3971        let mut result = String::with_capacity(content.len());
3972        let mut remaining = content.as_str();
3973        while let Some(start) = remaining.find(SIDECAR_PREFIX) {
3974            result.push_str(&remaining[..start]);
3975            remaining = &remaining[start + SIDECAR_PREFIX.len()..];
3976            if let Some(end) = remaining.find(SIDECAR_SUFFIX) {
3977                let rust_name = &remaining[..end];
3978                remaining = &remaining[end + SIDECAR_SUFFIX.len()..];
3979                // Emit @prop lines for each sidecar field registered for this type
3980                if let Some(entries) = by_type.get(rust_name) {
3981                    let prop_lines: String = entries
3982                        .iter()
3983                        .map(|e| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#\' @prop {0} {1}", e.field_name,
                e.prop_doc))
    })format!("#' @prop {} {}", e.field_name, e.prop_doc))
3984                        .collect::<Vec<_>>()
3985                        .join("\n");
3986                    result.push_str(&prop_lines);
3987                }
3988                // If no entries, the placeholder is simply removed (empty replacement)
3989            } else {
3990                // Malformed placeholder — emit prefix and stop
3991                result.push_str(SIDECAR_PREFIX);
3992                break;
3993            }
3994        }
3995        result.push_str(remaining);
3996        content = result;
3997    }
3998
3999    // Replace the `.__MX_CLASS_REF_*<RustName>__` placeholders with the
4000    // registered R class names ([`resolve_class_refs`]).
4001    {
4002        let class_index = build_class_name_index(MX_CLASS_NAMES.iter());
4003        content = resolve_class_refs(&content, &class_index);
4004    }
4005
4006    // Resolve the cross-class return wrapper placeholders: the scalar
4007    // `.__MX_WRAP_RETURN_<RustName>__(<expr>)` family and the list-shaped
4008    // `.__MX_WRAP_LIST_RETURN_<RustName>__(<expr>)` family (#1284). The
4009    // prefixes are non-overlapping, so pass order does not matter — each
4010    // resolver only consumes its own markers.
4011    {
4012        let class_index = build_class_name_index(MX_CLASS_NAMES.iter());
4013        content = resolve_scalar_return_wrappers(&content, &class_index);
4014        content = resolve_list_return_wrappers(&content, &class_index);
4015    }
4016
4017    // Resolve .__MX_GENERIC_DOC__(...) markers into standalone Rd pages.
4018    //
4019    // Each package-owned S7/S4 generic-creation site emits one marker line:
4020    //   .__MX_GENERIC_DOC__(kind="S7", generic="get_value", class="MyClass",
4021    //                       export=true, dispatch="x", no_dots=false)
4022    //
4023    // This pass:
4024    //   1. Scans all fragments for marker lines.
4025    //   2. Groups markers by generic name.
4026    //   3. Replaces the FIRST marker per generic with a synthesised standalone
4027    //      roxygen block (bare @name <generic> → bare \alias{<generic>}, listing
4028    //      every in-package implementing class).
4029    //   4. Deletes all remaining markers (keeping none in the final file).
4030    //
4031    // Method blocks keep their qualified @name Class-generic so the PR #83
4032    // duplicate-alias fix is not re-introduced.
4033    content = resolve_generic_doc_markers(content);
4034
4035    // Resolve .__MX_INHERITED_PARAM__(...) markers.
4036    //
4037    // Each R6 subclass method param that might be inherited from a parent class
4038    // emits one marker line per undocumented param. The write-time pass:
4039    //   1. Scans the assembled content for method and class-level @param docs.
4040    //   2. For each marker: if the parent class is in-package and has the param
4041    //      documented (at method or class level) → delete the marker line
4042    //      (roxygen2 8.0.0 inherits the parent's @param into the subclass method).
4043    //   3. Otherwise → replace the marker with the fallback placeholder text.
4044    //
4045    // This guarantees zero markers remain in the final wrappers.R and zero
4046    // roxygen2 warnings about undocumented parameters.
4047    content = resolve_inherited_param_markers(content);
4048
4049    // Detect collisions between separately-expanded wrapper definitions (#991).
4050    //
4051    // Repeated top-level function or class/namespace definitions silently
4052    // clobber each other at load time (last write wins), dispatching calls to
4053    // the wrong implementation or replacing the class object altogether.
4054    // The compile-time `check_s7_shortcut_collisions` only sees one impl block;
4055    // collisions that span macro expansions --
4056    // an S7 shortcut vs a `#[derive(ExternalPtr)]` sidecar accessor, or two S7
4057    // impl blocks on the same type -- are only visible here, where every name
4058    // set is assembled. We resolve the sidecar-accessor prefix through
4059    // MX_CLASS_NAMES so a `class = "Override"` is honoured, then scan the final
4060    // content. This runs after all placeholder resolution so names are final.
4061    {
4062        let class_index = build_class_name_index(MX_CLASS_NAMES.iter());
4063        let accessor_producers = sidecar_accessor_names(&MX_S7_SIDECAR_PROPS, &class_index);
4064        if let Err(msg) = detect_duplicate_wrapper_defs(&content, &accessor_producers) {
4065            { ::core::panicking::panic_fmt(format_args!("{0}", msg)); };panic!("{msg}");
4066        }
4067    }
4068
4069    // Refuse the `reexport!` names the package's wrappers or hand-written R
4070    // files bind or export themselves, and a name re-exported from two
4071    // packages (#1910, #2205). Like the scan above, it reads the final names.
4072    // The R files are read only for a package that re-exports.
4073    let hand_written = match r_dir {
4074        Some(r_dir) if !MX_REEXPORTS.is_empty() => {
4075            hand_written_r_files(std::path::Path::new(r_dir), std::path::Path::new(path))
4076        }
4077        _ => Vec::new(),
4078    };
4079    if let Err(msg) = reexport_conflicts(&content, &hand_written, &MX_REEXPORTS) {
4080        { ::core::panicking::panic_fmt(format_args!("{0}", msg)); };panic!("{msg}");
4081    }
4082
4083    let content = wrappers_file_content(&content);
4084
4085    // Only write if content changed (avoids unnecessary NAMESPACE/man regeneration).
4086    //
4087    // "Semantic equality" means equal after stripping source-position suffixes from
4088    // the source-attribution comments emitted by the `#[miniextendr]` proc-macro:
4089    //
4090    //   # Generated from Rust fn `foo` (lib.rs:42:8)
4091    //   # Counter::get (lib.rs:114:12)
4092    //                          ^^^^^^ positional suffix — ignored here
4093    //
4094    // These positions shift whenever any unrelated Rust source above a wrapper is
4095    // edited. The NOTE and the file rewrite should only fire when the actual
4096    // wrapper code, exports, or docstrings change — not when line numbers move.
4097    // So the positions in the file are those of the last write that changed
4098    // something else, and can lag behind the Rust source until the next one.
4099    let existing = std::fs::read_to_string(path).unwrap_or_default();
4100    if wrappers_semantically_equal(&existing, &content) {
4101        return;
4102    }
4103
4104    // Write via a sibling temp file then rename for atomicity.
4105    //
4106    // A plain `std::fs::write` truncates in place; a concurrent reader (e.g. a
4107    // second `R CMD INSTALL` process) can observe a torn file. `rename(2)` is
4108    // atomic on POSIX — the destination is replaced in a single syscall, so
4109    // readers always see either the old or the new content. On Windows, `rename`
4110    // fails when the destination exists, so we remove it first; that window is
4111    // benign (worst case the reader gets "file not found" and retries, which is
4112    // the same outcome as a torn write).
4113    let dest = std::path::Path::new(path);
4114    let tmp = dest.with_extension("tmp");
4115    std::fs::write(&tmp, content.as_bytes())
4116        .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("failed to write {0}: {1}",
            tmp.display(), e));
}panic!("failed to write {}: {e}", tmp.display()));
4117    #[cfg(windows)]
4118    let _ = std::fs::remove_file(dest);
4119    std::fs::rename(&tmp, dest).unwrap_or_else(|e| {
4120        {
    ::core::panicking::panic_fmt(format_args!("failed to rename {0} → {1}: {2}",
            tmp.display(), dest.display(), e));
}panic!(
4121            "failed to rename {} → {}: {e}",
4122            tmp.display(),
4123            dest.display()
4124        )
4125    });
4126
4127    if !existing.is_empty() {
4128        let filename = dest
4129            .file_name()
4130            .and_then(|f| f.to_str())
4131            .unwrap_or("wrappers.R");
4132        { ::std::io::_eprint(format_args!("\n")); };eprintln!();
4133        {
    ::std::io::_eprint(format_args!("NOTE: {0} changed — run devtools::document() to update NAMESPACE.\n",
            filename));
};eprintln!("NOTE: {filename} changed — run devtools::document() to update NAMESPACE.");
4134        { ::std::io::_eprint(format_args!("\n")); };eprintln!();
4135    }
4136}
4137
4138/// First line of the generated wrappers file.
4139#[cfg(not(target_arch = "wasm32"))]
4140const WRAPPERS_FILE_MARKER: &str = "# ---- AUTO-GENERATED FILE - DO NOT EDIT ----";
4141
4142/// The complete wrappers file for a finished `body`: the marker line, a line
4143/// naming the `miniextendr-api` version that generated it and an FNV-1a 64
4144/// digest of the body, then the body (#1552).
4145///
4146/// The digest is taken over [`normalize_source_locs`]`(body)`, the same view
4147/// [`wrappers_semantically_equal`] compares, so a Rust edit that only shifts
4148/// line numbers leaves the header alone and the no-rewrite check keeps
4149/// holding; any change to wrapper code, exports or docstrings changes it.
4150/// It lets a reviewer or a build tool tell two copies of the file apart from
4151/// the first two lines instead of diffing ~40k lines, and identifies the
4152/// generator version when a shipped wrapper is reported against.
4153#[cfg(not(target_arch = "wasm32"))]
4154fn wrappers_file_content(body: &str) -> String {
4155    let digest = crate::abi::fnv1a_64(
4156        normalize_source_locs(body).as_bytes(),
4157        crate::abi::FNV1A_64_OFFSET,
4158    );
4159    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}\n# miniextendr-api {0} | fnv1a-64 of the normalized lines below: {2:016x}\n{3}",
                "0.1.0", WRAPPERS_FILE_MARKER, digest, body))
    })format!(
4160        "{WRAPPERS_FILE_MARKER}\n# miniextendr-api {} | fnv1a-64 of the normalized lines below: {digest:016x}\n{body}",
4161        env!("CARGO_PKG_VERSION"),
4162    )
4163}
4164
4165/// Returns `true` when `a` and `b` are equal after normalising away
4166/// `(<file>.rs:LINE:COL)` positional suffixes in source-attribution comments.
4167///
4168/// The `#[miniextendr]` proc-macro emits comments of the form:
4169/// ```r
4170/// # Generated from Rust fn `foo` (lib.rs:42:8)
4171/// # Counter::get (lib.rs:114:12)
4172/// ```
4173/// The `42:8` part shifts whenever unrelated code above the wrapper is edited,
4174/// producing spurious wrapper-file rewrites and misleading NOTEs. Normalisation
4175/// replaces `(lib.rs:42:8)` → `(lib.rs:_:_)` for the comparison only, so the
4176/// file on disk keeps the positions of its last real rewrite.
4177///
4178/// A match requires `(` + one or more non-`()`/non-newline chars + `.rs:` +
4179/// ASCII digits + `:` + ASCII digits + `)`. Malformed or non-`.rs` patterns
4180/// are left untouched, so a position comment without its file name, like
4181/// `(114:12)`, is compared as written.
4182///
4183/// Host-only: the sole caller is [`write_r_wrappers_to_file`], gated off on
4184/// wasm32 (the wrapper-gen pass doesn't run there).
4185#[cfg(not(target_arch = "wasm32"))]
4186fn wrappers_semantically_equal(a: &str, b: &str) -> bool {
4187    normalize_source_locs(a) == normalize_source_locs(b)
4188}
4189
4190/// Replace every `(<stem>.rs:LINE:COL)` occurrence with `(<stem>.rs:_:_)`.
4191///
4192/// Returns a [`std::borrow::Cow::Borrowed`] slice when no replacements are
4193/// needed (zero-allocation fast path for the common case where the file has
4194/// never been written or is truly unchanged).
4195#[cfg(not(target_arch = "wasm32"))]
4196fn normalize_source_locs(s: &str) -> std::borrow::Cow<'_, str> {
4197    // Fast path: bail early if there is no `.rs:` anywhere in the string.
4198    if !s.contains(".rs:") {
4199        return std::borrow::Cow::Borrowed(s);
4200    }
4201
4202    let bytes = s.as_bytes();
4203    let len = bytes.len();
4204    let mut out = String::with_capacity(len);
4205    let mut pos = 0usize;
4206    let mut any_replaced = false;
4207
4208    while pos < len {
4209        // Look for the next `(`.
4210        let Some(open) = memchr(bytes, pos, b'(') else {
4211            break;
4212        };
4213
4214        // After `(`, scan for `.rs:` without crossing `)` or `(` or a newline.
4215        let inner_start = open + 1;
4216        let Some(dot_rs) = find_substr(bytes, inner_start, b".rs:") else {
4217            // No `.rs:` at all in the rest of the string — copy remainder and stop.
4218            out.push_str(&s[pos..]);
4219            return std::borrow::Cow::Owned(out);
4220        };
4221
4222        // Make sure `.rs:` precedes any closing `)`, `(`, or newline (no nesting).
4223        let intervening = &bytes[inner_start..dot_rs];
4224        if intervening
4225            .iter()
4226            .any(|&b| b == b')' || b == b'(' || b == b'\n')
4227        {
4228            // Guard crossed; copy up to and including `(` and continue after it.
4229            out.push_str(&s[pos..=open]);
4230            pos = open + 1;
4231            continue;
4232        }
4233
4234        // After `.rs:`, consume digits for LINE.
4235        let after_colon1 = dot_rs + 4; // skip `.rs:`
4236        let Some(colon2) = scan_digits(bytes, after_colon1) else {
4237            // Not digits after `.rs:` — not a source-attribution pattern.
4238            out.push_str(&s[pos..=open]);
4239            pos = open + 1;
4240            continue;
4241        };
4242        if colon2 >= len || bytes[colon2] != b':' {
4243            out.push_str(&s[pos..=open]);
4244            pos = open + 1;
4245            continue;
4246        }
4247
4248        // After the second `:`, consume digits for COL.
4249        let after_colon2 = colon2 + 1;
4250        let Some(close_pos) = scan_digits(bytes, after_colon2) else {
4251            out.push_str(&s[pos..=open]);
4252            pos = open + 1;
4253            continue;
4254        };
4255        if close_pos >= len || bytes[close_pos] != b')' {
4256            out.push_str(&s[pos..=open]);
4257            pos = open + 1;
4258            continue;
4259        }
4260
4261        // We have a match: `(stem.rs:LINE:COL)` — emit `(stem.rs:_:_)`.
4262        any_replaced = true;
4263        out.push_str(&s[pos..inner_start]); // text before inner_start (includes `(`)
4264        out.push_str(&s[inner_start..dot_rs + 3]); // `stem.rs` (without the colon)
4265        out.push_str(":_:_)");
4266        pos = close_pos + 1; // skip past the closing `)`
4267    }
4268
4269    if !any_replaced {
4270        return std::borrow::Cow::Borrowed(s);
4271    }
4272
4273    out.push_str(&s[pos..]);
4274    std::borrow::Cow::Owned(out)
4275}
4276
4277/// Find the first occurrence of `needle` in `haystack[from..]`.
4278/// Returns the absolute index in `haystack`, or `None`.
4279#[cfg(not(target_arch = "wasm32"))]
4280#[inline]
4281fn find_substr(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
4282    let window = haystack.get(from..)?;
4283    window
4284        .windows(needle.len())
4285        .position(|w| w == needle)
4286        .map(|rel| from + rel)
4287}
4288
4289/// Find the first byte equal to `needle` in `haystack[from..]`.
4290/// Returns the absolute index, or `None`.
4291#[cfg(not(target_arch = "wasm32"))]
4292#[inline]
4293fn memchr(haystack: &[u8], from: usize, needle: u8) -> Option<usize> {
4294    haystack[from..]
4295        .iter()
4296        .position(|&b| b == needle)
4297        .map(|rel| from + rel)
4298}
4299
4300/// Advance past a run of ASCII digits starting at `haystack[from]`.
4301/// Returns the absolute index of the first non-digit byte, or `None` if
4302/// there are no digits at `from` (empty run is not valid).
4303#[cfg(not(target_arch = "wasm32"))]
4304#[inline]
4305fn scan_digits(haystack: &[u8], from: usize) -> Option<usize> {
4306    let start = haystack.get(from..)?;
4307    let count = start.iter().take_while(|&&b| b.is_ascii_digit()).count();
4308    if count == 0 { None } else { Some(from + count) }
4309}
4310// endregion
4311
4312// region: Duplicate wrapper-definition detection (#991)
4313
4314/// Compute the sidecar accessor function names a `#[derive(ExternalPtr)]` emits
4315/// for each `#[r_data]` field, resolving the R-visible prefix through the
4316/// class-name registry.
4317///
4318/// The derive emits two top-level functions per field,
4319/// `<prefix>_get_<field>` and `<prefix>_set_<field>` (no setter for a
4320/// read-only field, #2268), where `<prefix>` is the
4321/// R-visible class name. That equals the Rust type name unless the impl block
4322/// set `class = "Override"`, in which case `MX_CLASS_NAMES` carries the
4323/// override. We resolve through `class_index` so the names we attribute match
4324/// what actually lands in the wrapper file.
4325///
4326/// Returns a map from accessor function name -> the human-readable producer
4327/// description used in the collision message.
4328#[cfg(not(target_arch = "wasm32"))]
4329fn sidecar_accessor_names(
4330    sidecar_props: &[SidecarPropEntry],
4331    class_index: &std::collections::HashMap<&str, &ClassNameEntry>,
4332) -> std::collections::HashMap<String, String> {
4333    let mut out = std::collections::HashMap::new();
4334    for entry in sidecar_props {
4335        // Resolve the R-visible prefix (honours `class = "Override"`).
4336        let prefix = class_index
4337            .get(entry.rust_type)
4338            .map(|c| c.r_class_name)
4339            .unwrap_or(entry.rust_type);
4340        let producer = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#[derive(ExternalPtr)] sidecar field `{0}` on `{1}`",
                entry.field_name, entry.rust_type))
    })format!(
4341            "#[derive(ExternalPtr)] sidecar field `{}` on `{}`",
4342            entry.field_name, entry.rust_type
4343        );
4344        out.insert(
4345            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}_get_{0}", entry.field_name,
                prefix))
    })format!("{prefix}_get_{}", entry.field_name),
4346            producer.clone(),
4347        );
4348        // A read-only property has no setter accessor (#2268).
4349        if !entry.read_only {
4350            out.insert(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}_set_{0}", entry.field_name,
                prefix))
    })format!("{prefix}_set_{}", entry.field_name), producer);
4351        }
4352    }
4353    out
4354}
4355
4356/// Detect conflicting top-level function and class/namespace definitions in
4357/// the assembled R wrapper text.
4358///
4359/// This is the write-time counterpart to the compile-time
4360/// `check_s7_shortcut_collisions` (in `miniextendr-macros`): it catches name
4361/// collisions that span *separate* macro expansions and are therefore invisible
4362/// to any single proc-macro invocation. The two motivating cases (#991):
4363///
4364/// 1. An S7 fast-path shortcut `<Class>_<method>` colliding with a
4365///    `#[derive(ExternalPtr)]` sidecar accessor `<Class>_get_<field>` /
4366///    `<Class>_set_<field>` -- the sidecar field names live in the
4367///    `MX_S7_SIDECAR_PROPS` slice, which the impl-block macro can't see.
4368/// 2. Two `#[miniextendr(s7)]` impl blocks on the same type each emitting a
4369///    `<Class>_<method>` shortcut -- cross-impl-block, also invisible to a
4370///    single expansion.
4371///
4372/// Without this check the second definition silently clobbers the first
4373/// (last-write-wins in R), so a call dispatches to the wrong implementation.
4374///
4375/// `accessor_producers` maps a known sidecar-accessor name to a description of
4376/// its producing derive; when a duplicate matches one we name the derive in the
4377/// message, otherwise we report the generic "defined more than once" form.
4378///
4379/// Class and namespace bindings (`new.env`, `R6::R6Class`, `S7::new_class`)
4380/// occupy the same namespace as functions. Include them so a free function
4381/// cannot silently replace a class object (#1677). S4's `setClass()` is not a
4382/// binding assignment: its same-named constructor function remains valid.
4383/// Guarded S3/S4/S7 generic declarations may repeat across classes, but must
4384/// not share their binding with an ordinary function or class object (#1677).
4385/// A class object defined twice would replace the first together with the
4386/// methods bound to it. The impl blocks of one Rust type are merged into one
4387/// class before this scan, and two types claiming one class name are refused
4388/// there ([`merge_class_blocks`], #1776), so this is the last line of defence.
4389///
4390/// Every message names both producers, read from the
4391/// `# Generated from Rust …` header that opens each wrapper fragment.
4392///
4393/// Returns `Err(message)` naming the offending binding on the first collision
4394/// found; `Ok(())` when names are unique apart from shared generic declarations.
4395#[cfg(not(target_arch = "wasm32"))]
4396fn detect_duplicate_wrapper_defs(
4397    content: &str,
4398    accessor_producers: &std::collections::HashMap<String, String>,
4399) -> Result<(), String> {
4400    use std::collections::HashMap;
4401
4402    // Binding name -> (kind, producer) of its first definition.
4403    let mut seen: HashMap<&str, (&str, std::rc::Rc<str>)> = HashMap::new();
4404
4405    for WrapperName {
4406        name,
4407        kind,
4408        producer,
4409    } in wrapper_names(content)
4410    {
4411        if kind == "export" {
4412            continue;
4413        }
4414        let Some((previous, first)) = seen.get(name) else {
4415            seen.insert(name, (kind, producer));
4416            continue;
4417        };
4418        let previous = *previous;
4419        if previous == "guarded generic" && kind == "guarded generic" {
4420            // Several classes intentionally dispatch through one generic.
4421            continue;
4422        }
4423        let both = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} from {1}, {2} from {3}",
                previous, first, kind, producer))
    })format!("{previous} from {first}, {kind} from {producer}");
4424        if previous == "guarded generic" || kind == "guarded generic" {
4425            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: wrapper name `{0}` is used by both a guarded generic and another generated binding ({1}). Package load order would replace one binding or prevent method dispatch. Rename the ordinary function with `r_name = \"...\"`, the class with `class = \"...\"`, or choose a distinct generic name.",
                name, both))
    })format!(
4426                "miniextendr: wrapper name `{name}` is used by both a guarded generic \
4427                 and another generated binding ({both}). Package load order would \
4428                 replace one binding or prevent method dispatch. Rename the ordinary \
4429                 function with `r_name = \"...\"`, the class with `class = \"...\"`, \
4430                 or choose a distinct generic name."
4431            ));
4432        }
4433        if previous != "function" && kind != "function" {
4434            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: class `{0}` is defined more than once ({1}). The second definition replaces the first at load time, together with the methods bound to it. Give one of the classes a distinct `class = \"...\"`.",
                name, both))
    })format!(
4435                "miniextendr: class `{name}` is defined more than once ({both}). The \
4436                 second definition replaces the first at load time, together with the \
4437                 methods bound to it. Give one of the classes a distinct \
4438                 `class = \"...\"`."
4439            ));
4440        }
4441        if previous != "function" || kind != "function" {
4442            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: wrapper name `{0}` is defined more than once ({1}). The second definition overwrites the first at load time. Give the class a distinct `class = \"...\"` name or rename the colliding function with `r_name = \"...\"`.",
                name, both))
    })format!(
4443                "miniextendr: wrapper name `{name}` is defined more than once ({both}). \
4444                 The second definition overwrites the first at load time. Give the \
4445                 class a distinct `class = \"...\"` name or rename the colliding \
4446                 function with `r_name = \"...\"`."
4447            ));
4448        }
4449        // Second function definition of this name -> collision.
4450        if let Some(derive) = accessor_producers.get(name) {
4451            return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: wrapper function `{0}` is defined more than once ({1}). One definition comes from {2}; the other from an S7 fast-path shortcut or `#[miniextendr]` function of the same name. The second definition silently overwrites the first at load time. Rename the colliding S7 method (`#[miniextendr(s7(r_name = \"...\"))]`), opt it out of the shortcut (`#[miniextendr(s7(no_shortcut))]`), or rename the sidecar field.",
                name, both, derive))
    })format!(
4452                "miniextendr: wrapper function `{name}` is defined more than once \
4453                 ({both}). One definition comes from {derive}; the other from an S7 \
4454                 fast-path shortcut or `#[miniextendr]` function of the same name. The \
4455                 second definition silently overwrites the first at load time. Rename \
4456                 the colliding S7 method (`#[miniextendr(s7(r_name = \"...\"))]`), opt \
4457                 it out of the shortcut (`#[miniextendr(s7(no_shortcut))]`), or rename \
4458                 the sidecar field."
4459            ));
4460        }
4461        return Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: wrapper function `{0}` is defined more than once in the generated R wrappers ({1}). Two `#[miniextendr]`-generated top-level functions emit the same name and the second silently overwrites the first at load time. Common causes: two `#[miniextendr(s7)]` impl blocks (or an S7 shortcut and another generated function) sharing a `<Class>_<method>` name — rename one (`#[miniextendr(s7(r_name = \"...\"))]`) or opt it out of the shortcut (`#[miniextendr(s7(no_shortcut))]`); or two trait impls whose generated standalone wrapper names are not class-qualified — rename the colliding method (`#[miniextendr(<system>(r_name = \"...\"))]`).",
                name, both))
    })format!(
4462            "miniextendr: wrapper function `{name}` is defined more than once in the \
4463             generated R wrappers ({both}). Two `#[miniextendr]`-generated top-level \
4464             functions emit the same name and the second silently overwrites the first \
4465             at load time. Common causes: two `#[miniextendr(s7)]` impl blocks (or an S7 \
4466             shortcut and another generated function) sharing a `<Class>_<method>` \
4467             name — rename one (`#[miniextendr(s7(r_name = \"...\"))]`) or opt it out \
4468             of the shortcut (`#[miniextendr(s7(no_shortcut))]`); or two trait impls \
4469             whose generated standalone wrapper names are not class-qualified — rename \
4470             the colliding method (`#[miniextendr(<system>(r_name = \"...\"))]`)."
4471        ));
4472    }
4473
4474    Ok(())
4475}
4476
4477/// A name the assembled wrappers bind at top level or export, and the
4478/// fragment that does, as the `# Generated from Rust …` header opening each
4479/// fragment names it.
4480#[cfg(not(target_arch = "wasm32"))]
4481struct WrapperName<'a> {
4482    name: &'a str,
4483    /// `"function"`, `"class/namespace object"` (`new.env`, `R6::R6Class`,
4484    /// `S7::new_class`), `"guarded generic"` ([`parse_guarded_generic`]), or
4485    /// `"export"`: an `@export <name>` target or an
4486    /// `@rawNamespace export(<name>)` argument.
4487    kind: &'static str,
4488    producer: std::rc::Rc<str>,
4489}
4490
4491/// The names of the assembled wrappers `content` in file order: see
4492/// [`WrapperName`]. Read by [`detect_duplicate_wrapper_defs`] and
4493/// [`reexport_conflicts`].
4494#[cfg(not(target_arch = "wasm32"))]
4495fn wrapper_names(content: &str) -> Vec<WrapperName<'_>> {
4496    let mut names = Vec::new();
4497    let mut producer: std::rc::Rc<str> = std::rc::Rc::from("an unattributed wrapper fragment");
4498    let mut lines = content.lines();
4499    while let Some(line) = lines.next() {
4500        if let Some(header) = line.strip_prefix("# Generated from ") {
4501            producer = std::rc::Rc::from(header);
4502            continue;
4503        }
4504        // A sidecar accessor's header gives only a source position
4505        // (`Rust source (lib.rs:4:5)`); the line after it names the field and
4506        // the Rust type.
4507        if let Some(wraps) = line.strip_prefix("# Wraps ") {
4508            let what = wraps.split_once(" via ").map_or(wraps, |(what, _)| what);
4509            let at = producer.strip_prefix("Rust source ").unwrap_or(&producer);
4510            producer = std::rc::Rc::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} {1}", what, at))
    })format!("{what} {at}"));
4511            continue;
4512        }
4513        if let Some(targets) = line.strip_prefix("#' @export ") {
4514            names.extend(targets.split_whitespace().map(|target| WrapperName {
4515                name: unquote_r_name(target),
4516                kind: "export",
4517                producer: producer.clone(),
4518            }));
4519            continue;
4520        }
4521        if let Some(directives) = line.strip_prefix("#' @rawNamespace ") {
4522            names.extend(raw_namespace_exports(directives).map(|name| WrapperName {
4523                name,
4524                kind: "export",
4525                producer: producer.clone(),
4526            }));
4527            continue;
4528        }
4529        let (name, kind) = if let Some(name) = parse_guarded_generic(line, lines.clone()) {
4530            (name, "guarded generic")
4531        } else {
4532            // Method assignments and indented closures are not bare top-level
4533            // bindings. Only the known generic guards above expose nested defs.
4534            let Some((name, rhs)) = parse_top_level_assignment(line) else {
4535                continue;
4536            };
4537            let kind = if rhs.starts_with("function") {
4538                "function"
4539            } else if ["new.env(", "R6::R6Class(", "S7::new_class("]
4540                .iter()
4541                .any(|prefix| rhs.starts_with(prefix))
4542            {
4543                "class/namespace object"
4544            } else {
4545                continue;
4546            };
4547            (name, kind)
4548        };
4549        names.push(WrapperName {
4550            name,
4551            kind,
4552            producer: producer.clone(),
4553        });
4554    }
4555    names
4556}
4557
4558/// The names the `export(...)` directives of an `@rawNamespace` tag's text
4559/// export: `export(a, "[[")` gives `a` and `[[`. `exportPattern(...)`,
4560/// `exportClasses(...)` and the like are not `export(`.
4561#[cfg(not(target_arch = "wasm32"))]
4562fn raw_namespace_exports(directives: &str) -> impl Iterator<Item = &str> {
4563    directives
4564        .match_indices("export(")
4565        .filter(move |(at, _)| {
4566            !directives[..*at]
4567                .chars()
4568                .next_back()
4569                .is_some_and(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
4570        })
4571        .flat_map(move |(at, open)| {
4572            let args = &directives[at + open.len()..];
4573            let args = args.split_once(')').map_or(args, |(args, _)| args);
4574            args.split(',')
4575                .map(|arg| unquote_r_name(arg.trim()))
4576                .filter(|name| !name.is_empty())
4577        })
4578}
4579
4580/// `name` without the double quotes, single quotes or backticks around it.
4581#[cfg(not(target_arch = "wasm32"))]
4582fn unquote_r_name(name: &str) -> &str {
4583    ['"', '\'', '`']
4584        .iter()
4585        .find_map(|quote| {
4586            name.strip_prefix(*quote)
4587                .and_then(|inner| inner.strip_suffix(*quote))
4588        })
4589        .unwrap_or(name)
4590}
4591
4592/// Recognize the generic guards emitted by `r_class_formatter` and the S4/S7
4593/// inherent/trait generators. This is a scan of generated forms, not an R parser:
4594/// the guard must start at column zero and its first statement must create a
4595/// generic. Never scan arbitrary indented assignments inside function bodies.
4596/// Documentation markers cannot stand in for this: `noexport` / `@noRd` classes
4597/// and trait implementations still declare generics without generic-doc markers.
4598#[cfg(not(target_arch = "wasm32"))]
4599fn parse_guarded_generic<'a>(line: &'a str, mut following: std::str::Lines<'a>) -> Option<&'a str> {
4600    if !(line.starts_with("if (!base::exists(\"")
4601        || line.starts_with("if (!exists(\"")
4602        || line.starts_with("if (!base::inherits(base::get0(\""))
4603    {
4604        return None;
4605    }
4606    // S4 emits its complete guard and setGeneric call on one line.
4607    if let Some((_, call)) = line.split_once(")) methods::setGeneric(\"") {
4608        return call.split_once("\", ").map(|(name, _)| name);
4609    }
4610    if !line.ends_with(" {") {
4611        return None;
4612    }
4613    // S3 and S7 put the assignment first in the guarded block, optionally
4614    // preceded by a generated comment. Their shadow-fallback branch need not
4615    // be scanned: it defines the same binding as the first branch.
4616    let body = following.find(|line| {
4617        let line = line.trim();
4618        !line.is_empty() && !line.starts_with('#')
4619    })?;
4620    let (name, rhs) = parse_top_level_assignment(body.strip_prefix("  ")?)?;
4621    // The wrapper's shadowed-formal pass can qualify UseMethod with base::.
4622    let s3 = rhs.strip_prefix("function(x, ...) ").is_some_and(|body| {
4623        body.strip_prefix("base::").unwrap_or(body) == ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("UseMethod(\"{0}\")", name))
    })format!("UseMethod(\"{name}\")")
4624    });
4625    (s3 || rhs.starts_with("S7::new_generic(") || rhs.starts_with("S7::new_external_generic("))
4626        .then_some(name)
4627}
4628
4629/// Parse a top-level `name <- function(...)` definition. Used both by the
4630/// duplicate scan and by standalone-function documentation grouping.
4631#[cfg(not(target_arch = "wasm32"))]
4632fn parse_top_level_fn_def_name(line: &str) -> Option<&str> {
4633    let (name, rhs) = parse_top_level_assignment(line)?;
4634    rhs.starts_with("function").then_some(name)
4635}
4636
4637/// Parse a bare top-level assignment, returning its name and trimmed RHS.
4638///
4639/// Ignore indented closures and targets containing `$`, `[[` or `::`, or a
4640/// call such as `S7::method(...)`. Backtick-quoted names are returned without
4641/// the quotes, with escapes kept as emitted. Find the closing backtick before
4642/// the arrow so replacement names such as `` `[<-.Foo` `` parse correctly.
4643#[cfg(not(target_arch = "wasm32"))]
4644fn parse_top_level_assignment(line: &str) -> Option<(&str, &str)> {
4645    if line.starts_with([' ', '\t']) {
4646        return None;
4647    }
4648    if let Some(quoted) = line.strip_prefix('`') {
4649        let mut escaped = false;
4650        for (index, ch) in quoted.char_indices() {
4651            if escaped {
4652                escaped = false;
4653            } else if ch == '\\' {
4654                escaped = true;
4655            } else if ch == '`' {
4656                let rhs = quoted[index + 1..].trim_start().strip_prefix("<-")?;
4657                return (!quoted[..index].is_empty())
4658                    .then_some((&quoted[..index], rhs.trim_start()));
4659            }
4660        }
4661        return None;
4662    }
4663    let (lhs, rhs) = line.split_once("<-")?;
4664    let name = lhs.trim();
4665    let first = name.chars().next()?;
4666    if !(first.is_ascii_alphabetic() || first == '.') {
4667        return None;
4668    }
4669    name.chars()
4670        .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_')
4671        .then_some((name, rhs.trim_start()))
4672}
4673// endregion
4674
4675// region: C-Callable Entry Points (wrapper generation)
4676//
4677// All wrapper-gen entry points are host-only — wasm32 builds skip
4678// them (the wrapper-gen pass itself doesn't run on wasm32; wrappers and
4679// `wasm_registry.rs` are pre-generated on native and shipped into the
4680// wasm32 install).
4681
4682/// C-callable entry point for R wrapper generation.
4683///
4684/// Called from Makevars via Rscript: loads the installed shared object with
4685/// `dyn.load()`, then `.Call("miniextendr_write_wrappers", c(path, r_dir))` to
4686/// write `R/miniextendr-wrappers.R`. NAMESPACE generation is left to roxygen2
4687/// (`devtools::document()`).
4688///
4689/// The second element, the package's `R/` directory, is optional: without it,
4690/// or when it is `NA` or empty, the hand-written R files are not checked
4691/// ([`write_r_wrappers_to_file`]). It is an element and not a second argument
4692/// so the routine keeps one argument: R refuses a `.Call` whose argument count
4693/// differs from the registered one, and a package's `tools/write-wrappers.R`
4694/// can be older or newer than its `miniextendr-api`.
4695///
4696/// A panic, such as a name collision found while assembling the wrappers, is
4697/// raised as an R error, so the install stops with the message instead of
4698/// aborting R at this non-unwinding boundary.
4699///
4700/// # Safety
4701///
4702/// `path_sexp` must be a valid STRSXP of length >= 1.
4703#[cfg(not(target_arch = "wasm32"))]
4704#[unsafe(no_mangle)]
4705pub unsafe extern "C" fn miniextendr_write_wrappers(path_sexp: crate::SEXP) -> crate::SEXP {
4706    crate::unwind_protect::with_r_unwind_protect_or_raise(
4707        || unsafe {
4708            use crate::{SEXP, SexpExt};
4709
4710            let element = |i: isize| {
4711                let char_sexp = path_sexp.string_elt_unchecked(i);
4712                crate::from_r::try_charsxp_to_str_unchecked(char_sexp)
4713                    .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("invalid path: {0}",
            e.r_reason(false)));
}panic!("invalid path: {}", e.r_reason(false)))
4714            };
4715            let path = element(0);
4716            let r_dir = (path_sexp.len_unchecked() > 1
4717                && !path_sexp.string_elt_unchecked(1).is_na_string())
4718            .then(|| element(1))
4719            .filter(|dir| !dir.is_empty());
4720
4721            write_r_wrappers_to_file(path, r_dir);
4722
4723            SEXP::nil()
4724        },
4725        None,
4726    )
4727}
4728
4729/// C-callable entry point for `wasm_registry.rs` generation.
4730///
4731/// Pairs with [`miniextendr_write_wrappers`]: same loaded object, separate `.Call`,
4732/// independent output path. Host-only; the generated file itself is then
4733/// consumed at compile time by the user crate's wasm32 build via
4734/// `install_wasm_runtime_slices`. A panic is raised as an R error, as in
4735/// [`miniextendr_write_wrappers`].
4736///
4737/// # Safety
4738///
4739/// `path_sexp` must be a valid STRSXP of length >= 1.
4740#[cfg(not(target_arch = "wasm32"))]
4741#[unsafe(no_mangle)]
4742pub unsafe extern "C" fn miniextendr_write_wasm_registry(path_sexp: crate::SEXP) -> crate::SEXP {
4743    crate::unwind_protect::with_r_unwind_protect_or_raise(
4744        || unsafe {
4745            use crate::{SEXP, SexpExt};
4746
4747            let char_sexp = path_sexp.string_elt_unchecked(0);
4748            let path = crate::from_r::try_charsxp_to_str_unchecked(char_sexp)
4749                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("invalid path: {0}",
            e.r_reason(false)));
}panic!("invalid path: {}", e.r_reason(false)));
4750
4751            crate::wasm_registry_writer::write_wasm_registry_to_file(path);
4752
4753            SEXP::nil()
4754        },
4755        None,
4756    )
4757}
4758// endregion
4759
4760// region: Unit tests for class-ref placeholder resolution
4761
4762#[cfg(test)]
4763mod tests;
4764// endregion