1use crate::gc_protect::ProtectScope;
4use crate::{R_xlen_t, SEXP, SEXPTYPE, SexpExt};
5
6#[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 Either(&'static [Option<NativeBorrow>; 2]),
28 ChoiceOr(&'static Option<NativeBorrow>),
32}
33
34impl NativeBorrow {
35 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 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 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 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 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 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 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 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 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 #[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 #[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 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#[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#[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#[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
322unsafe 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
369fn 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#[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#[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 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 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;