Skip to main content

miniextendr_api/from_r/
borrow.rs

1//! Native vector borrow metadata and pre-conversion alias checks.
2
3use crate::gc_protect::ProtectScope;
4use crate::{R_xlen_t, SEXP, SEXPTYPE, SexpExt};
5
6/// The native vector storage borrowed by a conversion.
7///
8/// Homogeneous containers add list levels; tuples describe each positional
9/// field separately. Optional NULLs require no extra level. Owned fields have
10/// no descriptor and never participate in alias checks.
11#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for NativeBorrow {
}
#[automatically_derived]impl ::core::clone::Clone for NativeBorrow {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<BorrowShape>;
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for NativeBorrow { }Copy, #[automatically_derived]impl ::core::fmt::Debug for NativeBorrow {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "NativeBorrow shape list_depth", &self.shape, &&self.list_depth)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    NativeBorrow {
}
#[automatically_derived]impl ::core::cmp::PartialEq for NativeBorrow {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.shape == other.shape && self.list_depth == other.list_depth
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for NativeBorrow {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<BorrowShape>;
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq)]
12pub struct NativeBorrow {
13    shape: BorrowShape,
14    list_depth: usize,
15}
16
17#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for BorrowShape {
}
#[automatically_derived]impl ::core::clone::Clone for BorrowShape {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<SEXPTYPE>;
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _:
                ::core::clone::AssertParamIsClone<&'static [Option<NativeBorrow>]>;
        let _:
                ::core::clone::AssertParamIsClone<&'static [Option<NativeBorrow>; 2]>;
        let _:
                ::core::clone::AssertParamIsClone<&'static Option<NativeBorrow>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for BorrowShape { }Copy, #[automatically_derived]impl ::core::fmt::Debug for BorrowShape {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Vector {
                sexptype: __self_0, mutable: __self_1, scalar: __self_2 } =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f,
                    "Vector sexptype mutable scalar", __self_0, __self_1,
                    &__self_2),
            Self::Tuple(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Tuple",
                    &__self_0),
            Self::Either(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Either", &__self_0),
            Self::ChoiceOr(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ChoiceOr", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    BorrowShape {
}
#[automatically_derived]impl ::core::cmp::PartialEq for BorrowShape {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Vector {
                    sexptype: __self_0, mutable: __self_1, scalar: __self_2 },
                    Self::Vector {
                    sexptype: __arg1_0, mutable: __arg1_1, scalar: __arg1_2 })
                    =>
                    __self_1 == __arg1_1 && __self_2 == __arg1_2 &&
                        __self_0 == __arg1_0,
                (Self::Tuple(__self_0), Self::Tuple(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Either(__self_0), Self::Either(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::ChoiceOr(__self_0), Self::ChoiceOr(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for BorrowShape {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<SEXPTYPE>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<&'static [Option<NativeBorrow>]>;
        let _:
                ::core::cmp::AssertParamIsEq<&'static [Option<NativeBorrow>; 2]>;
        let _: ::core::cmp::AssertParamIsEq<&'static Option<NativeBorrow>>;
    }
}Eq)]
18enum BorrowShape {
19    Vector {
20        sexptype: SEXPTYPE,
21        mutable: bool,
22        scalar: bool,
23    },
24    Tuple(&'static [Option<NativeBorrow>]),
25    /// The arms of an `Either`, left first. Which arm borrows depends on which
26    /// conversion succeeds, so the walk takes both (#1504).
27    Either(&'static [Option<NativeBorrow>; 2]),
28    /// A `match_arg` / `choices` `Either<T, R>`: character or factor input is
29    /// the owned choice, any other input converts to `R`. The input's type
30    /// alone decides it.
31    ChoiceOr(&'static Option<NativeBorrow>),
32}
33
34impl NativeBorrow {
35    /// A reference to the only element of a native R vector.
36    pub const fn scalar(sexptype: SEXPTYPE, mutable: bool) -> Self {
37        Self {
38            shape: BorrowShape::Vector {
39                sexptype,
40                mutable,
41                scalar: true,
42            },
43            list_depth: 0,
44        }
45    }
46
47    /// A slice over a native R vector, with empty vectors excluded from conflicts.
48    pub const fn slice(sexptype: SEXPTYPE, mutable: bool) -> Self {
49        Self {
50            shape: BorrowShape::Vector {
51                sexptype,
52                mutable,
53                scalar: false,
54            },
55            list_depth: 0,
56        }
57    }
58
59    /// Borrow metadata for a positional R list with exactly this many fields.
60    /// Returns `None` when every field is owned.
61    pub const fn tuple(fields: &'static [Option<Self>]) -> Option<Self> {
62        let mut index = 0;
63        while index < fields.len() {
64            if fields[index].is_some() {
65                return Some(Self {
66                    shape: BorrowShape::Tuple(fields),
67                    list_depth: 0,
68                });
69            }
70            index += 1;
71        }
72        None
73    }
74
75    /// Borrow metadata for an `Either` whose arms convert with `arms`, left
76    /// first. Returns `None` when neither arm borrows.
77    ///
78    /// The check treats it as the union of the arms, which is sound without
79    /// knowing which arm converts. When that union meets another argument, a
80    /// generated wrapper prepares the argument
81    /// ([`TryFromSexp::__mx_prepare`](crate::from_r::TryFromSexp)) to learn
82    /// the arm its conversion takes, and checks that arm alone.
83    pub const fn either(arms: &'static [Option<Self>; 2]) -> Option<Self> {
84        if arms[0].is_none() && arms[1].is_none() {
85            None
86        } else {
87            Some(Self {
88                shape: BorrowShape::Either(arms),
89                list_depth: 0,
90            })
91        }
92    }
93
94    /// Borrow metadata for a `match_arg` / `choices` parameter of type
95    /// `Either<T, R>`, where `right` is `R`'s: character or factor input goes
96    /// to the owned choice `T`, any other input to `R`. Returns `None` when
97    /// `R` borrows nothing.
98    pub const fn choice_or(right: &'static Option<Self>) -> Option<Self> {
99        if right.is_none() {
100            None
101        } else {
102            Some(Self {
103                shape: BorrowShape::ChoiceOr(right),
104                list_depth: 0,
105            })
106        }
107    }
108
109    /// Whether `borrow` is an `Either` at the argument's top level: the shape
110    /// a generated wrapper prepares to learn which arm converts. An `Either`
111    /// inside a list or tuple is checked against both arms.
112    pub const fn selects(borrow: Option<Self>) -> bool {
113        #[allow(non_exhaustive_omitted_patterns)] match borrow {
    Some(Self { shape: BorrowShape::Either(_), list_depth: 0 }) => true,
    _ => false,
}matches!(
114            borrow,
115            Some(Self {
116                shape: BorrowShape::Either(_),
117                list_depth: 0,
118            })
119        )
120    }
121
122    /// Forward an element conversion through one R list level.
123    pub const fn in_list(borrow: Option<Self>) -> Option<Self> {
124        match borrow {
125            Some(mut borrow) => {
126                borrow.list_depth += 1;
127                Some(borrow)
128            }
129            None => None,
130        }
131    }
132
133    /// The metadata this shape is made of: a tuple's fields, the arms of an
134    /// `Either`, a choice `Either`'s other arm. Empty for a leaf.
135    fn parts(self) -> &'static [Option<Self>] {
136        match self.shape {
137            BorrowShape::Vector { .. } => &[],
138            BorrowShape::Tuple(fields) => fields,
139            BorrowShape::Either(arms) => arms,
140            BorrowShape::ChoiceOr(right) => core::slice::from_ref(right),
141        }
142    }
143
144    /// Whether the check of this metadata takes both arms of an `Either`
145    /// anywhere in it.
146    fn has_either(self) -> bool {
147        #[allow(non_exhaustive_omitted_patterns)] match self.shape {
    BorrowShape::Either(_) => true,
    _ => false,
}matches!(self.shape, BorrowShape::Either(_))
148            || self.parts().iter().flatten().any(|part| part.has_either())
149    }
150
151    /// Whether this and `other` can borrow one R vector, one of them
152    /// mutably. Two vectors, the common pair, are compared here; a shape
153    /// made of parts goes to the out-of-line [`Self::parts_conflict_with`].
154    #[inline]
155    fn conflicts_with(self, other: Self) -> bool {
156        if let (
157            BorrowShape::Vector {
158                sexptype: a,
159                mutable: am,
160                ..
161            },
162            BorrowShape::Vector {
163                sexptype: b,
164                mutable: bm,
165                ..
166            },
167        ) = (self.shape, other.shape)
168        {
169            return (am || bm) && a == b;
170        }
171        self.parts_conflict_with(other)
172    }
173
174    #[inline(never)]
175    fn parts_conflict_with(self, other: Self) -> bool {
176        if let BorrowShape::Vector { .. } = self.shape {
177            other
178                .parts()
179                .iter()
180                .flatten()
181                .any(|b| self.conflicts_with(*b))
182        } else {
183            self.parts()
184                .iter()
185                .flatten()
186                .any(|a| a.conflicts_with(other))
187        }
188    }
189
190    /// Whether one argument can borrow one R vector twice, once mutably. A
191    /// vector at the top level, the common argument, can't.
192    #[inline]
193    fn needs_internal_check(self) -> bool {
194        if self.list_depth == 0 && #[allow(non_exhaustive_omitted_patterns)] match self.shape {
    BorrowShape::Vector { .. } => true,
    _ => false,
}matches!(self.shape, BorrowShape::Vector { .. }) {
195            return false;
196        }
197        self.nested_needs_internal_check()
198    }
199
200    #[inline(never)]
201    fn nested_needs_internal_check(self) -> bool {
202        if self.list_depth > 0 {
203            return self.conflicts_with(self);
204        }
205        match self.shape {
206            BorrowShape::Vector { .. } => false,
207            BorrowShape::Tuple(fields) => needs_check(fields),
208            // One arm converts, so the arms never borrow together.
209            BorrowShape::Either(_) | BorrowShape::ChoiceOr(_) => self
210                .parts()
211                .iter()
212                .flatten()
213                .any(|arm| arm.needs_internal_check()),
214        }
215    }
216
217    fn accepts_length(self, length: R_xlen_t) -> bool {
218        match self.shape {
219            BorrowShape::Vector { scalar: true, .. } => length == 1,
220            BorrowShape::Vector { scalar: false, .. } => length > 0,
221            BorrowShape::Tuple(_) | BorrowShape::Either(_) | BorrowShape::ChoiceOr(_) => false,
222        }
223    }
224}
225
226/// Whether any conversion pair can alias, without inspecting or allocating in R.
227///
228/// Generated wrappers use this to skip the alias check for owned/custom
229/// conversions and shared-only signatures.
230#[doc(hidden)]
231pub fn needs_check(borrows: &[Option<NativeBorrow>]) -> bool {
232    for (i, borrow) in borrows.iter().enumerate() {
233        let Some(a) = borrow else { continue };
234        if a.needs_internal_check() {
235            return true;
236        }
237        if borrows[i + 1..]
238            .iter()
239            .flatten()
240            .any(|b| a.conflicts_with(*b))
241        {
242            return true;
243        }
244    }
245    false
246}
247
248/// Reject every conflicting argument pair before any Rust borrow is constructed.
249///
250/// An `Either` anywhere in the metadata is checked against both arms. A
251/// generated wrapper first calls [`assert_or_select`] and replaces a
252/// prepared argument's metadata with the arm its conversion takes.
253///
254/// # Safety
255///
256/// Run on R's main thread inside an R unwind-protected wrapper. Argument SEXPs
257/// must stay reachable for the whole call. Metadata must describe the actual
258/// conversions of the corresponding arguments.
259#[doc(hidden)]
260pub unsafe fn assert_no_aliases<const N: usize>(
261    args: [(SEXP, &str); N],
262    borrows: [Option<NativeBorrow>; N],
263) {
264    let mut errors = Vec::new();
265    unsafe {
266        for_each_conflict(&args, &borrows, |i, j| {
267            errors.push(message(&args, &borrows, i, j))
268        })
269    };
270    if !errors.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("aliasing native arguments: {0}",
                errors.join("; ")));
    }
};assert!(
271        errors.is_empty(),
272        "aliasing native arguments: {}",
273        errors.join("; ")
274    );
275}
276
277/// The first pass of a generated wrapper's alias check (#1504).
278///
279/// Checks `borrows` as [`assert_no_aliases`] does, taking both arms of every
280/// `Either`. A conflict that involves an argument whose top level is an
281/// `Either` ([`NativeBorrow::selects`]) may vanish once that argument's arm is
282/// known, so it raises nothing and marks the argument instead. Returns the
283/// marked arguments: the wrapper prepares them, replaces their metadata with
284/// what the prepared conversion borrows, and calls [`assert_no_aliases`],
285/// which then reports every conflict that remains. With nothing marked, every
286/// conflict found has already been raised.
287///
288/// # Safety
289///
290/// As for [`assert_no_aliases`].
291#[doc(hidden)]
292pub unsafe fn assert_or_select<const N: usize>(
293    args: [(SEXP, &str); N],
294    borrows: [Option<NativeBorrow>; N],
295) -> [bool; N] {
296    let mut select = [false; N];
297    let mut errors = Vec::new();
298    unsafe {
299        for_each_conflict(&args, &borrows, |i, j| {
300            let (si, sj) = (
301                NativeBorrow::selects(borrows[i]),
302                NativeBorrow::selects(borrows[j]),
303            );
304            if si || sj {
305                select[i] |= si;
306                select[j] |= sj;
307            } else {
308                errors.push(message(&args, &borrows, i, j));
309            }
310        })
311    };
312    if !select.contains(&true) {
313        if !errors.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("aliasing native arguments: {0}",
                errors.join("; ")));
    }
};assert!(
314            errors.is_empty(),
315            "aliasing native arguments: {}",
316            errors.join("; ")
317        );
318    }
319    select
320}
321
322/// Call `found(i, j)` (`i <= j`) for every argument pair whose borrows alias,
323/// an argument with itself included.
324///
325/// # Safety
326///
327/// As for [`assert_no_aliases`].
328unsafe fn for_each_conflict<const N: usize>(
329    args: &[(SEXP, &str); N],
330    borrows: &[Option<NativeBorrow>; N],
331    mut found: impl FnMut(usize, usize),
332) {
333    for i in 0..N {
334        let Some(a) = borrows[i] else { continue };
335        for j in i..N {
336            let Some(b) = borrows[j] else { continue };
337            let same_arg = i == j;
338            if !a.conflicts_with(b) || (same_arg && !a.needs_internal_check()) {
339                continue;
340            }
341            let mut path_a = Vec::new();
342            let mut path_b = Vec::new();
343            let aliases = unsafe {
344                visit_leaves(
345                    args[i].0,
346                    a,
347                    &mut path_a,
348                    &mut |leaf_a, indices_a, borrow_a| {
349                        visit_leaves(
350                            args[j].0,
351                            b,
352                            &mut path_b,
353                            &mut |leaf_b, indices_b, borrow_b| {
354                                (!same_arg || indices_a < indices_b)
355                                    && leaf_a == leaf_b
356                                    && borrow_a.conflicts_with(borrow_b)
357                            },
358                        )
359                    },
360                )
361            };
362            if aliases {
363                found(i, j);
364            }
365        }
366    }
367}
368
369/// The error for a conflict between arguments `i` and `j`.
370fn message<const N: usize>(
371    args: &[(SEXP, &str); N],
372    borrows: &[Option<NativeBorrow>; N],
373    i: usize,
374    j: usize,
375) -> String {
376    let name_a = args[i].1;
377    let name_b = args[j].1;
378    let mut message = if i == j {
379        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parameter `{0}` contains duplicate elements that borrow the same non-empty R vector mutably",
                name_a))
    })format!(
380            "parameter `{name_a}` contains duplicate elements that borrow the same non-empty R vector mutably"
381        )
382    } else {
383        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("parameters `{0}` and `{1}` borrow the same non-empty R object, and at least one borrows it mutably; pass distinct vectors",
                name_a, name_b))
    })format!(
384            "parameters `{name_a}` and `{name_b}` borrow the same non-empty R object, and at least one borrows it mutably; pass distinct vectors"
385        )
386    };
387    if [borrows[i], borrows[j]]
388        .into_iter()
389        .flatten()
390        .any(NativeBorrow::has_either)
391    {
392        message.push_str(
393            " (an `Either` whose arm is not known before conversion is checked against both arms)",
394        );
395    }
396    message
397}
398
399/// Keep each current ALTREP/list element rooted while the other argument is
400/// visited. Protection depth follows type nesting, not the number of elements.
401///
402/// A plain vector, the common argument, is visited here; every other shape
403/// goes to [`visit_nested`], kept out of line so this stays small enough to
404/// inline into the check of a call with plain borrowed vectors.
405#[inline]
406unsafe fn visit_leaves(
407    sexp: SEXP,
408    borrow: NativeBorrow,
409    path: &mut Vec<R_xlen_t>,
410    visit: &mut impl FnMut(SEXP, &[R_xlen_t], NativeBorrow) -> bool,
411) -> bool {
412    if borrow.list_depth == 0
413        && let BorrowShape::Vector { sexptype, .. } = borrow.shape
414    {
415        return sexp.type_of() == sexptype
416            && borrow.accepts_length(sexp.xlength())
417            && visit(sexp, path, borrow);
418    }
419    unsafe { visit_nested(sexp, borrow, path, visit) }
420}
421
422/// [`visit_leaves`] for a list, a tuple or an `Either`.
423#[inline(never)]
424unsafe fn visit_nested(
425    sexp: SEXP,
426    borrow: NativeBorrow,
427    path: &mut Vec<R_xlen_t>,
428    visit: &mut impl FnMut(SEXP, &[R_xlen_t], NativeBorrow) -> bool,
429) -> bool {
430    if borrow.list_depth == 0 {
431        match borrow.shape {
432            BorrowShape::Vector { .. } => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("visit_leaves visits a plain vector")));
}unreachable!("visit_leaves visits a plain vector"),
433            // Whichever arm converts, its leaves are among these.
434            BorrowShape::Either(arms) => {
435                return arms
436                    .iter()
437                    .flatten()
438                    .any(|arm| unsafe { visit_leaves(sexp, *arm, path, visit) });
439            }
440            BorrowShape::ChoiceOr(right) => {
441                if sexp.type_of() == SEXPTYPE::STRSXP || sexp.is_factor() {
442                    return false;
443                }
444                return right
445                    .is_some_and(|right| unsafe { visit_leaves(sexp, right, path, visit) });
446            }
447            BorrowShape::Tuple(_) => {}
448        }
449    }
450    if sexp.type_of() != SEXPTYPE::VECSXP {
451        return false;
452    }
453    let length = sexp.xlength();
454    if borrow.list_depth == 0
455        && let BorrowShape::Tuple(fields) = borrow.shape
456        && usize::try_from(length).ok() != Some(fields.len())
457    {
458        // Conversion will report the shape error before borrowing any field.
459        return false;
460    }
461    for index in 0..length {
462        let child_borrow = if borrow.list_depth > 0 {
463            NativeBorrow {
464                list_depth: borrow.list_depth - 1,
465                ..borrow
466            }
467        } else {
468            let BorrowShape::Tuple(fields) = borrow.shape else {
469                ::core::panicking::unreachable_default_msg()unreachable!()
470            };
471            let Some(field) = fields[usize::try_from(index).unwrap()] else {
472                continue;
473            };
474            field
475        };
476        let scope = unsafe { ProtectScope::new() };
477        let child = unsafe { scope.protect(sexp.vector_elt(index)).get() };
478        path.push(index);
479        let found = unsafe { visit_leaves(child, child_borrow, path, visit) };
480        path.pop();
481        if found {
482            return true;
483        }
484    }
485    false
486}
487
488#[cfg(test)]
489mod tests;