Skip to main content

miniextendr_api/
altrep.rs

1//! Core ALTREP types and registration traits.
2//!
3//! ## Architecture
4//!
5//! - **FFI**: Raw setters/types in `crate::sys::altrep`
6//! - **Traits**: Safe traits in [`crate::altrep_traits`] (`Altrep`, `AltVec`, `AltInteger`, etc.)
7//!   - Required methods: Compiler-enforced by trait definition
8//!   - Optional methods: Gated by HAS_* constants, defaults provided
9//! - **Bridge**: Generic `extern "C-unwind"` trampolines in [`crate::altrep_bridge`]
10//! - **High-level data traits**: [`crate::altrep_data`] (`AltrepLen` +
11//!   `Alt*Data`) — implement with `&self` methods instead of raw SEXP.
12//! - **SEXP wrapper**: [`crate::altrep_sexp`] — `!Send + !Sync` wrapper that
13//!   prevents an ALTREP SEXP from crossing thread boundaries before
14//!   materialization.
15//! - **Derive**: `#[derive(AltrepInteger)]` / `AltrepReal` / `AltrepLogical`
16//!   / `AltrepRaw` / `AltrepString` / `AltrepComplex` / `AltrepList` on a
17//!   struct emits everything below: `Altrep`, `AltVec`, the family-specific
18//!   trait, `AltrepLen`, `Alt*Data`, an `impl RegisterAltrep`, and the
19//!   `R_make_alt*` registration. See the `altrep_derive` module in the
20//!   `miniextendr-macros` crate for the attribute reference and validation
21//!   rules.
22//!
23//! ## Two code paths
24//!
25//! 1. **Field-based derive** (default) — annotate fields with
26//!    `#[altrep(len = "field", elt = "field", class = "Name")]` and the
27//!    derive handles `length`/`elt`/registration.
28//! 2. **Manual** — `#[altrep(manual)]` skips `AltrepLen` / `Alt*Data` so you
29//!    hand-roll those traits (custom `elt`, `no_na`, `sum`, …); the
30//!    `impl_alt*_from_data!` registration is still emitted.
31//!
32//! Both paths use [`Altrep::GUARD`](crate::altrep_traits::Altrep::GUARD) for
33//! native reads. Allocating bridges always retain RUnwind protection;
34//! guard modes are documented on [`crate::altrep_traits`].
35//!
36//! ## Threading
37//!
38//! ALTREP callbacks run on R's main thread; the trampolines bridge from C
39//! straight back into safe Rust there, with panic / longjmp handling per the
40//! chosen guard mode.
41
42use crate::sys::altrep::{
43    R_altrep_class_t, R_make_altcomplex_class, R_make_altinteger_class, R_make_altlist_class,
44    R_make_altlogical_class, R_make_altraw_class, R_make_altreal_class, R_make_altstring_class,
45};
46use std::cell::RefCell;
47use std::ffi::CStr;
48
49/// Base type for ALTREP vectors.
50#[derive(#[automatically_derived]impl ::core::fmt::Debug for RBase {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Int Real Logical Raw String List Complex",
            match self {
                RBase::Int => 0usize,
                RBase::Real => 4usize,
                RBase::Logical => 9usize,
                RBase::Raw => 17usize,
                RBase::String => 21usize,
                RBase::List => 28usize,
                RBase::Complex => 33usize,
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RBase {
}
#[automatically_derived]impl ::core::clone::Clone for RBase {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for RBase { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for RBase { }
#[automatically_derived]impl ::core::cmp::PartialEq for RBase {
    #[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 RBase { }Eq)]
51pub enum RBase {
52    /// Integer vectors (`INTSXP`).
53    Int,
54    /// Double vectors (`REALSXP`).
55    Real,
56    /// Logical vectors (`LGLSXP`).
57    Logical,
58    /// Raw byte vectors (`RAWSXP`).
59    Raw,
60    /// Character vectors (`STRSXP`).
61    String,
62    /// Generic list vectors (`VECSXP`).
63    List,
64    /// Complex vectors (`CPLXSXP`).
65    Complex,
66}
67
68impl RBase {
69    /// The [`SEXPTYPE`](crate::SEXPTYPE) an ALTREP vector of this base
70    /// presents to R.
71    pub const fn sexptype(self) -> crate::SEXPTYPE {
72        match self {
73            RBase::Int => crate::SEXPTYPE::INTSXP,
74            RBase::Real => crate::SEXPTYPE::REALSXP,
75            RBase::Logical => crate::SEXPTYPE::LGLSXP,
76            RBase::Raw => crate::SEXPTYPE::RAWSXP,
77            RBase::String => crate::SEXPTYPE::STRSXP,
78            RBase::List => crate::SEXPTYPE::VECSXP,
79            RBase::Complex => crate::SEXPTYPE::CPLXSXP,
80        }
81    }
82}
83
84/// Trait implemented by ALTREP classes via `#[miniextendr]`.
85///
86/// This trait is automatically implemented when using the proc-macro with
87/// ALTREP attributes (class, pkg, base).
88pub trait AltrepClass {
89    /// The class name (null-terminated C string).
90    const CLASS_NAME: &'static std::ffi::CStr;
91    /// The base R type (Int, Real, Logical, etc.).
92    const BASE: RBase;
93}
94
95/// Registration trait: implemented per type by the macro on struct items.
96///
97/// The `get_or_init_class` method returns the ALTREP class handle, initializing
98/// it on first call and returning the cached handle on subsequent calls.
99///
100/// This trait combines class creation and method installation into a single
101/// `get_or_init_class` call that caches the result.
102pub trait RegisterAltrep {
103    /// Get the ALTREP class handle, initializing it if this is the first call.
104    ///
105    /// The implementation should:
106    /// 1. Create the class handle via `R_make_alt*` (or via `InferBase::make_class`)
107    /// 2. Install methods via `install_*` functions from `altrep_bridge`
108    /// 3. Cache the result in a static `OnceLock`
109    fn get_or_init_class() -> R_altrep_class_t;
110}
111
112// region: Runtime dispatch helper for class creation
113
114#[doc =
r" Records every ALTREP class name registered during `package_init()`."]
#[doc = r""]
#[doc =
r" After all registrations complete, [`assert_altrep_class_uniqueness`]"]
#[doc = r" checks for duplicates. Only R's main thread makes classes:"]
#[doc =
r" `package_init()` registers them there, and a class made on first use"]
#[doc =
r" is made by a conversion to R, which runs there too (`[T; N]` arrays"]
#[doc = r" enter it through `with_r_thread`)."]
const REGISTERED_CLASS_NAMES: ::std::thread::LocalKey<RefCell<Vec<String>>> =
    {
        const __RUST_STD_INTERNAL_INIT: RefCell<Vec<String>> =
            { RefCell::new(Vec::new()) };
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<Vec<String>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::EagerStorage<RefCell<Vec<String>>>
                                        =
                                        ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL: RefCell<Vec<String>> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };thread_local! {
115    /// Records every ALTREP class name registered during `package_init()`.
116    ///
117    /// After all registrations complete, [`assert_altrep_class_uniqueness`]
118    /// checks for duplicates. Only R's main thread makes classes:
119    /// `package_init()` registers them there, and a class made on first use
120    /// is made by a conversion to R, which runs there too (`[T; N]` arrays
121    /// enter it through `with_r_thread`).
122    static REGISTERED_CLASS_NAMES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
123}
124
125/// Validate that an ALTREP class handle was successfully created.
126///
127/// Panics with a descriptive message if the class handle is null, indicating
128/// that `R_make_alt*_class()` failed during registration.
129///
130/// Also records the class name for later duplicate detection via
131/// [`assert_altrep_class_uniqueness`].
132///
133/// # Arguments
134/// * `cls` - The class handle returned by `R_make_alt*_class()`
135/// * `class_name` - The name of the ALTREP class (for diagnostics)
136/// * `base` - The base R type (for diagnostics)
137pub fn validate_altrep_class(
138    cls: R_altrep_class_t,
139    class_name: &CStr,
140    base: RBase,
141) -> R_altrep_class_t {
142    if cls.ptr.is_null_ptr() {
143        {
    ::core::panicking::panic_fmt(format_args!("ALTREP class registration failed: R_make_alt{1:?}_class() returned NULL for class {0:?}",
            class_name, base));
};panic!(
144            "ALTREP class registration failed: R_make_alt{base:?}_class() returned NULL \
145             for class {:?}",
146            class_name
147        );
148    }
149    // Record the name for duplicate detection at the end of package_init().
150    REGISTERED_CLASS_NAMES
151        .with_borrow_mut(|names| names.push(class_name.to_string_lossy().into_owned()));
152    cls
153}
154
155/// Assert that all registered ALTREP class names are unique.
156///
157/// Must be called after all ALTREP registrations (builtin, arrow, user-defined)
158/// have completed in `package_init()`. Panics with a clear message if any
159/// duplicate class name is found.
160pub fn assert_altrep_class_uniqueness() {
161    let duplicate = REGISTERED_CLASS_NAMES.with_borrow(|names| {
162        // Sort so that equal names are adjacent.
163        let mut sorted: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
164        sorted.sort_unstable();
165        sorted
166            .windows(2)
167            .find(|window| window[0] == window[1])
168            .map(|window| window[0].to_owned())
169    });
170    if let Some(name) = duplicate {
171        {
    ::core::panicking::panic_fmt(format_args!("miniextendr: duplicate ALTREP class name \"{0}\" — each ALTREP type must have a unique class name within the package",
            name));
};panic!(
172            "miniextendr: duplicate ALTREP class name \"{name}\" \
173             — each ALTREP type must have a unique class name within the package"
174        );
175    }
176}
177
178/// Create an ALTREP class handle based on the runtime base type.
179///
180/// Validates the returned handle and panics if registration fails.
181///
182/// # Safety
183/// Must be called during R initialization (after `set_altrep_dll_info`).
184pub unsafe fn make_class_by_base(
185    class_name: *const ::core::ffi::c_char,
186    pkg_name: *const ::core::ffi::c_char,
187    base: RBase,
188) -> R_altrep_class_t {
189    let dll = crate::altrep_dll_info();
190    let cls = unsafe {
191        match base {
192            RBase::Int => R_make_altinteger_class(class_name, pkg_name, dll),
193            RBase::Real => R_make_altreal_class(class_name, pkg_name, dll),
194            RBase::Logical => R_make_altlogical_class(class_name, pkg_name, dll),
195            RBase::Raw => R_make_altraw_class(class_name, pkg_name, dll),
196            RBase::String => R_make_altstring_class(class_name, pkg_name, dll),
197            RBase::List => R_make_altlist_class(class_name, pkg_name, dll),
198            RBase::Complex => R_make_altcomplex_class(class_name, pkg_name, dll),
199        }
200    };
201    // SAFETY: class_name was passed to R, so it's still a valid C string
202    let name_cstr = unsafe { CStr::from_ptr(class_name) };
203    validate_altrep_class(cls, name_cstr, base)
204}
205// endregion