miniextendr_api/sexp_ext.rs
1//! `SexpExt` — the ergonomic extension trait on `SEXP` — and `PairListExt`,
2//! its pairlist (call) counterpart.
3//!
4//! Provides safe(r) accessors and type checks. This is the actual user-facing
5//! API surface most callers reach for; both are re-exported from
6//! [`crate::prelude`].
7
8use std::marker::PhantomData;
9
10use crate::from_r::{charsxp_to_str_or_panic, try_charsxp_to_str};
11use crate::gc_protect::ProtectScope;
12use crate::sexp_types::{R_xlen_t, RNativeType, Rboolean, Rcomplex, SEXPTYPE};
13use crate::{IsNA, SEXP};
14// Pull in everything raw from sys. Type re-exports (SEXP, SEXPTYPE, etc.)
15// that `sys` itself promotes are identical items, so glob import is safe;
16// we still bring SEXP/SEXPTYPE in via crate root above so the file reads
17// naturally.
18use crate::sys::{
19 ALTREP, CAR, CAR_unchecked, CDR, CDR_unchecked, COMPLEX_ELT, DATAPTR_RO, DATAPTR_RO_unchecked,
20 IDENT_USE_CLOENV, INTEGER_ELT, LOGICAL_ELT, PRINTNAME, R_BaseEnv, R_CHAR, R_CHAR_unchecked,
21 R_ClassSymbol, R_DimNamesSymbol, R_DimSymbol, R_LevelsSymbol, R_NaString, R_NamesSymbol,
22 R_RowNamesSymbol, R_compute_identical, RAW_ELT, REAL_ELT, Rf_asChar, Rf_asInteger,
23 Rf_asLogical, Rf_asReal, Rf_classgets, Rf_coerceVector, Rf_cons, Rf_cons_unchecked,
24 Rf_copyMostAttrib, Rf_copyMostAttrib_unchecked, Rf_dimgets, Rf_dimnamesgets, Rf_duplicate,
25 Rf_eval, Rf_getAttrib, Rf_getAttrib_unchecked, Rf_inherits, Rf_install, Rf_isArray,
26 Rf_isFactor, Rf_isFunction, Rf_isList, Rf_isMatrix, Rf_isObject, Rf_isS4, Rf_lang2, Rf_lcons,
27 Rf_namesgets, Rf_setAttrib, Rf_setAttrib_unchecked, Rf_shallow_duplicate, Rf_xlength,
28 Rf_xlength_unchecked, Rf_xlengthgets, SET_COMPLEX_ELT, SET_INTEGER_ELT, SET_LOGICAL_ELT,
29 SET_RAW_ELT, SET_REAL_ELT, SET_STRING_ELT, SET_STRING_ELT_unchecked, SET_TAG,
30 SET_TAG_unchecked, SET_VECTOR_ELT, SET_VECTOR_ELT_unchecked, SETCAR, SETCAR_unchecked, SETCDR,
31 SETCDR_unchecked, STRING_ELT, STRING_ELT_unchecked, TAG, TYPEOF, VECTOR_ELT,
32 VECTOR_ELT_unchecked,
33};
34
35/// Extension trait for SEXP providing safe(r) accessors and type checking.
36///
37/// This trait provides idiomatic Rust methods for working with SEXPs,
38/// equivalent to R's inline macros and type checking functions.
39pub trait SexpExt {
40 /// Get the type of this SEXP.
41 ///
42 /// Equivalent to `TYPEOF(x)` macro.
43 ///
44 /// # Safety
45 ///
46 /// The SEXP must be valid (not null and not freed).
47 #[must_use]
48 fn type_of(&self) -> SEXPTYPE;
49
50 /// Get the length of this SEXP as `usize`.
51 ///
52 /// # Safety
53 ///
54 /// The SEXP must be valid.
55 #[must_use]
56 fn len(&self) -> usize;
57
58 /// Get the length as `R_xlen_t`.
59 ///
60 /// # Safety
61 ///
62 /// The SEXP must be valid.
63 #[must_use]
64 fn xlength(&self) -> R_xlen_t;
65
66 /// Get the length as `R_xlen_t` without thread checks.
67 ///
68 /// # Safety
69 ///
70 /// Must be called from R's main thread. No debug assertions.
71 #[must_use]
72 unsafe fn xlength_unchecked(&self) -> R_xlen_t;
73
74 /// Get the length without thread checks.
75 ///
76 /// # Safety
77 ///
78 /// Must be called from R's main thread. No debug assertions.
79 #[must_use]
80 unsafe fn len_unchecked(&self) -> usize;
81
82 /// Get a slice view of this SEXP's data.
83 ///
84 /// # Safety
85 ///
86 /// - The SEXP must be valid and of the correct type for `T`
87 /// - The SEXP must be protected from R's garbage collector for the entire
88 /// duration the returned slice is used. This typically means the SEXP must
89 /// be either:
90 /// - An argument to a `.Call` function (protected by R's calling convention)
91 /// - Explicitly protected via `PROTECT`/`UNPROTECT` or `R_PreserveObject`
92 /// - Part of a protected container (e.g., element of a protected list)
93 /// - The returned slice has `'static` lifetime for API convenience, but this
94 /// is a lie - the actual lifetime is tied to the SEXP's protection status.
95 /// Holding the slice after the SEXP is unprotected is undefined behavior.
96 unsafe fn as_slice<T: RNativeType>(&self) -> &'static [T];
97
98 /// Get a slice view without thread checks.
99 ///
100 /// # Safety
101 ///
102 /// - All safety requirements of [`as_slice`](Self::as_slice) apply
103 /// - Additionally, must be called from R's main thread (no debug assertions)
104 unsafe fn as_slice_unchecked<T: RNativeType>(&self) -> &'static [T];
105
106 /// Get a mutable slice view of this SEXP's data.
107 ///
108 /// # Safety
109 ///
110 /// - All safety requirements of [`as_slice`](Self::as_slice) apply.
111 /// - The caller must ensure **exclusive access**: no other `&[T]` or `&mut [T]`
112 /// slices derived from this SEXP may exist simultaneously. Multiple calls to
113 /// `as_mut_slice` on the same SEXP without dropping the previous slice is UB.
114 /// - The SEXP must not be shared (ALTREP or NAMED > 0 objects may alias).
115 unsafe fn as_mut_slice<T: RNativeType>(&self) -> &'static mut [T];
116
117 // Type checking methods (equivalent to R's type check macros)
118
119 /// Check if this SEXP is an integer vector (INTSXP).
120 #[must_use]
121 fn is_integer(&self) -> bool;
122
123 /// Check if this SEXP is a real/numeric vector (REALSXP).
124 #[must_use]
125 fn is_real(&self) -> bool;
126
127 /// Check if this SEXP is a logical vector (LGLSXP).
128 #[must_use]
129 fn is_logical(&self) -> bool;
130
131 /// Check if this SEXP is a character/string vector (STRSXP).
132 #[must_use]
133 fn is_character(&self) -> bool;
134
135 /// Check if this SEXP is a raw vector (RAWSXP).
136 #[must_use]
137 fn is_raw(&self) -> bool;
138
139 /// Check if this SEXP is a complex vector (CPLXSXP).
140 #[must_use]
141 fn is_complex(&self) -> bool;
142
143 /// Check if this SEXP is a list/generic vector (VECSXP).
144 #[must_use]
145 fn is_list(&self) -> bool;
146
147 /// Check if this SEXP is an external pointer (EXTPTRSXP).
148 #[must_use]
149 fn is_external_ptr(&self) -> bool;
150
151 /// Check if this SEXP is an environment (ENVSXP).
152 #[must_use]
153 fn is_environment(&self) -> bool;
154
155 /// Check if this SEXP is a symbol (SYMSXP).
156 #[must_use]
157 fn is_symbol(&self) -> bool;
158
159 /// Check if this SEXP is a language object (LANGSXP).
160 #[must_use]
161 fn is_language(&self) -> bool;
162
163 /// Check if this SEXP is an ALTREP object.
164 ///
165 /// Equivalent to R's `ALTREP(x)` macro.
166 #[must_use]
167 fn is_altrep(&self) -> bool;
168
169 /// Check if this `SEXP` contains any elements.
170 #[must_use]
171 fn is_empty(&self) -> bool;
172
173 /// Check if this SEXP is a factor.
174 ///
175 /// Equivalent to R's `Rf_isFactor(x)`.
176 #[must_use]
177 fn is_factor(&self) -> bool;
178
179 /// Check if this SEXP is a pairlist (LISTSXP or NILSXP).
180 ///
181 /// Equivalent to R's `Rf_isList(x)`.
182 #[must_use]
183 fn is_pair_list(&self) -> bool;
184
185 /// Check if this SEXP is a matrix.
186 ///
187 /// Equivalent to R's `Rf_isMatrix(x)`.
188 #[must_use]
189 fn is_matrix(&self) -> bool;
190
191 /// Check if this SEXP is an array.
192 ///
193 /// Equivalent to R's `Rf_isArray(x)`.
194 #[must_use]
195 fn is_array(&self) -> bool;
196
197 /// Check if this SEXP is a function (closure, builtin, or special).
198 ///
199 /// Equivalent to R's `Rf_isFunction(x)`.
200 #[must_use]
201 fn is_function(&self) -> bool;
202
203 /// Check if this SEXP is an S4 object.
204 ///
205 /// Equivalent to R's `Rf_isS4(x)`.
206 #[must_use]
207 fn is_s4(&self) -> bool;
208
209 /// Check if this SEXP is a data.frame.
210 ///
211 /// Equivalent to R's `Rf_isDataFrame(x)`.
212 #[must_use]
213 fn is_data_frame(&self) -> bool;
214
215 /// Check if this SEXP is a numeric type (integer, logical, or real, excluding factors).
216 ///
217 /// Equivalent to R's `Rf_isNumeric(x)`.
218 #[must_use]
219 fn is_numeric(&self) -> bool;
220
221 /// Check if this SEXP is a number type (numeric or complex).
222 ///
223 /// Equivalent to R's `Rf_isNumber(x)`.
224 #[must_use]
225 fn is_number(&self) -> bool;
226
227 /// Check if this SEXP is an atomic vector.
228 ///
229 /// Returns true for logical, integer, real, complex, character, and raw vectors.
230 #[must_use]
231 fn is_vector_atomic(&self) -> bool;
232
233 /// Check if this SEXP is a vector list (VECSXP or EXPRSXP).
234 #[must_use]
235 fn is_vector_list(&self) -> bool;
236
237 /// Check if this SEXP is a vector (atomic vector or list).
238 #[must_use]
239 fn is_vector(&self) -> bool;
240
241 /// Check if this SEXP is an R "object" (has a class attribute).
242 #[must_use]
243 fn is_object(&self) -> bool;
244
245 // region: Coercion and scalar extraction
246
247 /// Coerce this SEXP to the given type, returning a new SEXP.
248 ///
249 /// The result is guaranteed to have the requested SEXPTYPE.
250 /// Equivalent to R's `Rf_coerceVector(x, target)`.
251 #[must_use]
252 fn coerce(&self, target: SEXPTYPE) -> SEXP;
253
254 /// Extract a scalar logical value.
255 ///
256 /// Returns `None` for `NA`. Coerces non-logical inputs.
257 /// Equivalent to R's `Rf_asLogical(x)`.
258 #[must_use]
259 fn as_logical(&self) -> Option<bool>;
260
261 /// Extract a scalar integer value.
262 ///
263 /// Returns `None` for `NA_integer_`. Coerces non-integer inputs.
264 /// Equivalent to R's `Rf_asInteger(x)`.
265 #[must_use]
266 fn as_integer(&self) -> Option<i32>;
267
268 /// Extract a scalar real value.
269 ///
270 /// Returns `None` for `NA_real_` (NaN). Coerces non-real inputs.
271 /// Equivalent to R's `Rf_asReal(x)`.
272 #[must_use]
273 fn as_real(&self) -> Option<f64>;
274
275 /// Extract a scalar CHARSXP from this SEXP.
276 ///
277 /// The result is guaranteed to be a CHARSXP.
278 /// Equivalent to R's `Rf_asChar(x)`.
279 #[must_use]
280 fn as_char(&self) -> SEXP;
281
282 // endregion
283
284 // region: Attribute access
285
286 /// Get an attribute by symbol.
287 #[must_use]
288 fn get_attr(&self, name: SEXP) -> SEXP;
289
290 /// Get an attribute by symbol, returning `None` for `R_NilValue`.
291 #[must_use]
292 fn get_attr_opt(&self, name: SEXP) -> Option<SEXP> {
293 let attr = self.get_attr(name);
294 if attr.is_nil() { None } else { Some(attr) }
295 }
296
297 /// Set an attribute by symbol.
298 fn set_attr(&self, name: SEXP, val: SEXP);
299
300 /// Get the `names` attribute.
301 #[must_use]
302 fn get_names(&self) -> SEXP;
303
304 /// Set the `names` attribute.
305 fn set_names(&self, names: SEXP);
306
307 /// Get the `class` attribute.
308 #[must_use]
309 fn get_class(&self) -> SEXP;
310
311 /// Set the `class` attribute.
312 fn set_class(&self, class: SEXP);
313
314 /// Get the `dim` attribute.
315 #[must_use]
316 fn get_dim(&self) -> SEXP;
317
318 /// Set the `dim` attribute.
319 fn set_dim(&self, dim: SEXP);
320
321 /// Get the `dimnames` attribute.
322 #[must_use]
323 fn get_dimnames(&self) -> SEXP;
324
325 /// Set the `dimnames` attribute.
326 fn set_dimnames(&self, dimnames: SEXP);
327
328 /// Get the `levels` attribute (factors).
329 #[must_use]
330 fn get_levels(&self) -> SEXP;
331
332 /// Set the `levels` attribute (factors).
333 fn set_levels(&self, levels: SEXP);
334
335 /// Get the `row.names` attribute.
336 #[must_use]
337 fn get_row_names(&self) -> SEXP;
338
339 /// Set the `row.names` attribute.
340 fn set_row_names(&self, row_names: SEXP);
341
342 /// Copy every attribute of `from` except `names`, `dim` and `dimnames` onto
343 /// this object, as R's `Rf_copyMostAttrib(from, self)` does.
344 ///
345 /// The rule is R's, used where a result built from a vector should keep
346 /// its class but not its shape (subsetting, `rbind` of typed parts):
347 ///
348 /// - `class`, `levels`, `tzone`, `units` and every other attribute are
349 /// copied. A copied attribute replaces one of the same name on `self`;
350 /// the rest of `self`'s attributes, its `names` included, stay.
351 /// - The values are shared, not duplicated: `self` and `from` point at the
352 /// same attribute objects.
353 /// - When `from` is an object (it has a `class` attribute), `self` is
354 /// marked as one. An object bit `self` already has stays set.
355 /// - `self`'s S4 bit is set to `from`'s.
356 ///
357 /// The attributes are not checked against `self`'s type: copying
358 /// `factor`'s class and levels onto a double vector gives an object R
359 /// considers malformed. R raises its error when `self` is `NULL`.
360 fn copy_most_attrib(&self, from: SEXP);
361
362 /// Check if this SEXP inherits from a class.
363 ///
364 /// Equivalent to R's `inherits(x, "class_name")`.
365 #[must_use]
366 fn inherits_class(&self, class: &std::ffi::CStr) -> bool;
367
368 /// Check whether this SEXP carries any attributes.
369 ///
370 /// Same answer as `!is.null(attributes(x))` in R. For a pairlist
371 /// (`LISTSXP`), tag names count, because `attributes()` reports them as a
372 /// `names` attribute: `pairlist(a = 1)` has attributes, `pairlist(1)`
373 /// does not. A `CHARSXP` (an element of a character vector) has none:
374 /// R uses its attribute slot for the global string cache, and
375 /// `identical()` skips it too.
376 ///
377 /// The check evaluates `attributes(quote(x))` in the base environment, so
378 /// it allocates a call and, when attributes exist, the list
379 /// `attributes()` returns. R's constant-time test `ANY_ATTRIB` only
380 /// exists from R 4.5.0 and miniextendr supports R 4.4. `ATTRIB` is not
381 /// part of R's API, and `R CMD check` (R >= 4.6) reports packages that
382 /// call it.
383 ///
384 /// To reproduce R's `identical(x, y)`, which compares attributes as well
385 /// as values, use [`is_identical`](Self::is_identical).
386 ///
387 /// ```ignore
388 /// // attributes(c(a = 1)) is list(names = "a")
389 /// assert!(named_vector.has_attributes());
390 /// assert!(!SEXP::scalar_logical(false).has_attributes());
391 /// ```
392 #[must_use]
393 fn has_attributes(&self) -> bool;
394
395 // endregion
396
397 // region: String element access
398
399 /// Get the i-th CHARSXP element from a STRSXP.
400 ///
401 /// Equivalent to R's `STRING_ELT(x, i)`.
402 #[must_use]
403 fn string_elt(&self, i: isize) -> SEXP;
404
405 /// Get the i-th string element as `Option<&str>`.
406 ///
407 /// Returns `None` for `NA_character_`. The element is read with its own
408 /// encoding: a UTF-8 or ASCII string, or a native one in a UTF-8 session,
409 /// borrows from R's internal string cache (CHARSXP global pool) and is
410 /// valid as long as the parent STRSXP is protected from GC. A Latin-1
411 /// string, or a native non-ASCII one in a session whose locale isn't
412 /// UTF-8, is translated with `Rf_translateCharUTF8`, whose buffer lives on
413 /// R's memory stack until the enclosing `.Call` returns; the translation
414 /// allocates, so it can run the GC. The lifetime is tied to `&self` by the borrow checker, but the true
415 /// validity depends on GC protection — do not hold the `&str` across
416 /// allocation boundaries without ensuring the SEXP remains protected.
417 ///
418 /// # Panics
419 ///
420 /// On an element marked as bytes, or one that is not valid UTF-8: it is
421 /// not text. A conversion that returns a `Result` refuses it instead
422 /// (`Vec<String>`, `Vec<Option<String>>`).
423 #[must_use]
424 fn string_elt_str(&self, i: isize) -> Option<&str>;
425
426 /// Set the i-th CHARSXP element of a STRSXP.
427 ///
428 /// Equivalent to R's `SET_STRING_ELT(x, i, v)`.
429 fn set_string_elt(&self, i: isize, charsxp: SEXP);
430
431 /// Check if this CHARSXP is `NA_character_`.
432 #[must_use]
433 fn is_na_string(&self) -> bool;
434
435 // endregion
436
437 // region: List element access
438
439 /// Get the i-th element of a VECSXP (generic vector / list).
440 ///
441 /// Equivalent to R's `VECTOR_ELT(x, i)`.
442 #[must_use]
443 fn vector_elt(&self, i: isize) -> SEXP;
444
445 /// Set the i-th element of a VECSXP.
446 ///
447 /// Equivalent to R's `SET_VECTOR_ELT(x, i, v)`.
448 fn set_vector_elt(&self, i: isize, val: SEXP);
449
450 // endregion
451
452 // region: Typed single-element access
453
454 /// Get the i-th integer element.
455 #[must_use]
456 fn integer_elt(&self, i: isize) -> i32;
457 /// Get the i-th real element.
458 #[must_use]
459 fn real_elt(&self, i: isize) -> f64;
460 /// Get the i-th logical element (raw i32: 0/1/NA_LOGICAL).
461 #[must_use]
462 fn logical_elt(&self, i: isize) -> i32;
463 /// Get the i-th complex element.
464 #[must_use]
465 fn complex_elt(&self, i: isize) -> Rcomplex;
466 /// Get the i-th raw element.
467 #[must_use]
468 fn raw_elt(&self, i: isize) -> u8;
469
470 /// Set the i-th integer element.
471 fn set_integer_elt(&self, i: isize, v: i32);
472 /// Set the i-th real element.
473 fn set_real_elt(&self, i: isize, v: f64);
474 /// Set the i-th logical element (raw i32: 0/1/NA_LOGICAL).
475 fn set_logical_elt(&self, i: isize, v: i32);
476 /// Set the i-th complex element.
477 fn set_complex_elt(&self, i: isize, v: Rcomplex);
478 /// Set the i-th raw element.
479 fn set_raw_elt(&self, i: isize, v: u8);
480
481 // endregion
482
483 // region: Symbol and CHARSXP access
484
485 /// Get the print name (CHARSXP) of a symbol (SYMSXP).
486 ///
487 /// # Safety
488 ///
489 /// The SEXP must be a valid SYMSXP.
490 #[must_use]
491 fn printname(&self) -> SEXP;
492
493 /// Get the C string pointer from a CHARSXP.
494 ///
495 /// The returned pointer is valid as long as the CHARSXP is protected.
496 ///
497 /// # Safety
498 ///
499 /// The SEXP must be a valid CHARSXP.
500 #[must_use]
501 fn r_char(&self) -> *const ::std::os::raw::c_char;
502
503 /// Get a `&str` from a CHARSXP. Returns `None` for `NA_character_`.
504 ///
505 /// Read with the string's own encoding, as
506 /// [`string_elt_str`](Self::string_elt_str) reads an element: a Latin-1
507 /// string, or a native non-ASCII one in a session whose locale isn't
508 /// UTF-8, is translated (into R's memory stack, until the enclosing
509 /// `.Call` returns).
510 ///
511 /// # Panics
512 ///
513 /// On a string marked as bytes, or one that is not valid UTF-8.
514 #[must_use]
515 fn r_char_str(&self) -> Option<&str>;
516
517 // endregion
518
519 // region: Vector resizing
520
521 /// Resize a vector to a new length, returning a (possibly new) SEXP.
522 ///
523 /// If the new length is shorter, elements are truncated.
524 /// If longer, new elements are filled with NA/NULL.
525 /// Equivalent to R's `Rf_xlengthgets(x, newlen)`.
526 #[must_use]
527 fn resize(&self, newlen: R_xlen_t) -> SEXP;
528
529 // endregion
530
531 // region: Duplication
532
533 /// Deep-copy this SEXP. Equivalent to R's `Rf_duplicate(x)`.
534 #[must_use]
535 fn duplicate(&self) -> SEXP;
536
537 /// Shallow-copy this SEXP. Equivalent to R's `Rf_shallow_duplicate(x)`.
538 #[must_use]
539 fn shallow_duplicate(&self) -> SEXP;
540
541 // endregion
542
543 // region: Comparison
544
545 /// Check whether this SEXP is identical to `other` under the defaults of
546 /// R's `identical(x, y)`.
547 ///
548 /// Calls `R_compute_identical(x, y, IDENT_USE_CLOENV)`. Flag 16 is what
549 /// `identical()` passes with its default arguments: `num.eq`,
550 /// `single.NA`, `attrib.as.set`, `ignore.bytecode` and `ignore.srcref`
551 /// are `TRUE`, and `ignore.environment` and `extptr.as.ref` are `FALSE`.
552 /// Attributes take part in the comparison, so `structure(FALSE, foo = 1)`
553 /// is not identical to `FALSE`.
554 ///
555 /// The `==` operator on `SEXP` compares pointers, not values.
556 ///
557 /// ```ignore
558 /// // R's identical(x, FALSE)
559 /// let is_false = x.is_identical(SEXP::scalar_logical(false));
560 /// ```
561 #[must_use]
562 fn is_identical(&self, other: SEXP) -> bool;
563
564 // endregion
565
566 // region: Unchecked variants (bypass thread-check, for perf-critical paths)
567
568 /// Get the i-th CHARSXP from a STRSXP. No thread check.
569 ///
570 /// # Safety
571 /// Must be called from R's main thread.
572 #[must_use]
573 unsafe fn string_elt_unchecked(&self, i: isize) -> SEXP;
574 /// Set the i-th CHARSXP of a STRSXP. No thread check.
575 ///
576 /// # Safety
577 /// Must be called from R's main thread.
578 unsafe fn set_string_elt_unchecked(&self, i: isize, charsxp: SEXP);
579 /// Get the i-th element of a VECSXP. No thread check.
580 ///
581 /// # Safety
582 /// Must be called from R's main thread.
583 #[must_use]
584 unsafe fn vector_elt_unchecked(&self, i: isize) -> SEXP;
585 /// Set the i-th element of a VECSXP. No thread check.
586 ///
587 /// # Safety
588 /// Must be called from R's main thread.
589 unsafe fn set_vector_elt_unchecked(&self, i: isize, val: SEXP);
590 /// Get an attribute by symbol. No thread check.
591 ///
592 /// # Safety
593 /// Must be called from R's main thread.
594 #[must_use]
595 unsafe fn get_attr_unchecked(&self, name: SEXP) -> SEXP;
596 /// Set an attribute by symbol. No thread check.
597 ///
598 /// # Safety
599 /// Must be called from R's main thread.
600 unsafe fn set_attr_unchecked(&self, name: SEXP, val: SEXP);
601 /// Copy every attribute of `from` except `names`, `dim` and `dimnames`
602 /// onto this object, as [`copy_most_attrib`](Self::copy_most_attrib). No
603 /// thread check.
604 ///
605 /// # Safety
606 /// Must be called from R's main thread.
607 unsafe fn copy_most_attrib_unchecked(&self, from: SEXP);
608
609 /// Get C string pointer from a CHARSXP. No thread check.
610 ///
611 /// # Safety
612 /// Must be called from R's main thread. The SEXP must be a valid CHARSXP.
613 #[must_use]
614 unsafe fn r_char_unchecked(&self) -> *const ::std::os::raw::c_char;
615
616 // endregion
617}
618
619impl SexpExt for SEXP {
620 #[inline]
621 fn type_of(&self) -> SEXPTYPE {
622 unsafe { TYPEOF(*self) }
623 }
624
625 #[inline]
626 fn len(&self) -> usize {
627 unsafe { Rf_xlength(*self) as usize }
628 }
629
630 #[inline]
631 fn xlength(&self) -> R_xlen_t {
632 unsafe { Rf_xlength(*self) }
633 }
634
635 #[inline]
636 unsafe fn xlength_unchecked(&self) -> R_xlen_t {
637 unsafe { Rf_xlength_unchecked(*self) }
638 }
639
640 #[inline]
641 unsafe fn len_unchecked(&self) -> usize {
642 unsafe { Rf_xlength_unchecked(*self) as usize }
643 }
644
645 #[inline]
646 unsafe fn as_slice<T: RNativeType>(&self) -> &'static [T] {
647 debug_assert!(
648 self.type_of() == T::SEXP_TYPE,
649 "SEXP type mismatch: expected {:?}, got {:?}",
650 T::SEXP_TYPE,
651 self.type_of()
652 );
653 unsafe { crate::from_r::r_slice(DATAPTR_RO(*self).cast(), self.len()) }
654 }
655
656 #[inline]
657 unsafe fn as_mut_slice<T: RNativeType>(&self) -> &'static mut [T] {
658 debug_assert!(
659 self.type_of() == T::SEXP_TYPE,
660 "SEXP type mismatch: expected {:?}, got {:?}",
661 T::SEXP_TYPE,
662 self.type_of()
663 );
664 unsafe { crate::from_r::r_slice_mut(T::dataptr_mut(*self), self.len()) }
665 }
666
667 #[inline]
668 unsafe fn as_slice_unchecked<T: RNativeType>(&self) -> &'static [T] {
669 debug_assert!(
670 self.type_of() == T::SEXP_TYPE,
671 "SEXP type mismatch: expected {:?}, got {:?}",
672 T::SEXP_TYPE,
673 self.type_of()
674 );
675 unsafe { crate::from_r::r_slice(DATAPTR_RO_unchecked(*self).cast(), self.len_unchecked()) }
676 }
677
678 // Type checking methods
679
680 #[inline]
681 fn is_integer(&self) -> bool {
682 self.type_of() == SEXPTYPE::INTSXP
683 }
684
685 #[inline]
686 fn is_real(&self) -> bool {
687 self.type_of() == SEXPTYPE::REALSXP
688 }
689
690 #[inline]
691 fn is_logical(&self) -> bool {
692 self.type_of() == SEXPTYPE::LGLSXP
693 }
694
695 #[inline]
696 fn is_character(&self) -> bool {
697 self.type_of() == SEXPTYPE::STRSXP
698 }
699
700 #[inline]
701 fn is_raw(&self) -> bool {
702 self.type_of() == SEXPTYPE::RAWSXP
703 }
704
705 #[inline]
706 fn is_complex(&self) -> bool {
707 self.type_of() == SEXPTYPE::CPLXSXP
708 }
709
710 #[inline]
711 fn is_list(&self) -> bool {
712 self.type_of() == SEXPTYPE::VECSXP
713 }
714
715 #[inline]
716 fn is_external_ptr(&self) -> bool {
717 self.type_of() == SEXPTYPE::EXTPTRSXP
718 }
719
720 #[inline]
721 fn is_environment(&self) -> bool {
722 self.type_of() == SEXPTYPE::ENVSXP
723 }
724
725 #[inline]
726 fn is_symbol(&self) -> bool {
727 self.type_of() == SEXPTYPE::SYMSXP
728 }
729
730 #[inline]
731 fn is_language(&self) -> bool {
732 self.type_of() == SEXPTYPE::LANGSXP
733 }
734
735 #[inline]
736 fn is_altrep(&self) -> bool {
737 unsafe { ALTREP(*self) != 0 }
738 }
739
740 #[inline]
741 fn is_empty(&self) -> bool {
742 self.len() == 0
743 }
744
745 #[inline]
746 fn is_factor(&self) -> bool {
747 unsafe { Rf_isFactor(*self) != Rboolean::FALSE }
748 }
749
750 #[inline]
751 fn is_pair_list(&self) -> bool {
752 unsafe { Rf_isList(*self) != Rboolean::FALSE }
753 }
754
755 #[inline]
756 fn is_matrix(&self) -> bool {
757 unsafe { Rf_isMatrix(*self) != Rboolean::FALSE }
758 }
759
760 #[inline]
761 fn is_array(&self) -> bool {
762 unsafe { Rf_isArray(*self) != Rboolean::FALSE }
763 }
764
765 #[inline]
766 fn is_function(&self) -> bool {
767 unsafe { Rf_isFunction(*self) != Rboolean::FALSE }
768 }
769
770 #[inline]
771 fn is_s4(&self) -> bool {
772 unsafe { Rf_isS4(*self) != Rboolean::FALSE }
773 }
774
775 #[inline]
776 fn is_data_frame(&self) -> bool {
777 self.inherits_class(c"data.frame")
778 }
779
780 #[inline]
781 fn is_numeric(&self) -> bool {
782 let typ = self.type_of();
783 (typ == SEXPTYPE::INTSXP || typ == SEXPTYPE::LGLSXP || typ == SEXPTYPE::REALSXP)
784 && !self.is_factor()
785 }
786
787 #[inline]
788 fn is_number(&self) -> bool {
789 self.is_numeric() || self.is_complex()
790 }
791
792 #[inline]
793 fn is_vector_atomic(&self) -> bool {
794 matches!(
795 self.type_of(),
796 SEXPTYPE::LGLSXP
797 | SEXPTYPE::INTSXP
798 | SEXPTYPE::REALSXP
799 | SEXPTYPE::CPLXSXP
800 | SEXPTYPE::STRSXP
801 | SEXPTYPE::RAWSXP
802 )
803 }
804
805 #[inline]
806 fn is_vector_list(&self) -> bool {
807 let typ = self.type_of();
808 typ == SEXPTYPE::VECSXP || typ == SEXPTYPE::EXPRSXP
809 }
810
811 #[inline]
812 fn is_vector(&self) -> bool {
813 self.is_vector_atomic() || self.is_vector_list()
814 }
815
816 #[inline]
817 fn is_object(&self) -> bool {
818 unsafe { Rf_isObject(*self) != Rboolean::FALSE }
819 }
820
821 // region: Coercion and scalar extraction
822
823 #[inline]
824 fn coerce(&self, target: SEXPTYPE) -> SEXP {
825 unsafe { Rf_coerceVector(*self, target) }
826 }
827
828 #[inline]
829 fn as_logical(&self) -> Option<bool> {
830 let v = unsafe { Rf_asLogical(*self) };
831 if v.is_na() { None } else { Some(v != 0) }
832 }
833
834 #[inline]
835 fn as_integer(&self) -> Option<i32> {
836 let v = unsafe { Rf_asInteger(*self) };
837 if v.is_na() { None } else { Some(v) }
838 }
839
840 #[inline]
841 fn as_real(&self) -> Option<f64> {
842 let v = unsafe { Rf_asReal(*self) };
843 // `R_IsNA`: a computed NA is `None` too; any other NaN is a value.
844 if v.is_na() { None } else { Some(v) }
845 }
846
847 #[inline]
848 fn as_char(&self) -> SEXP {
849 unsafe { Rf_asChar(*self) }
850 }
851
852 // endregion
853
854 // region: Attribute access
855
856 #[inline]
857 fn get_attr(&self, name: SEXP) -> SEXP {
858 unsafe { Rf_getAttrib(*self, name) }
859 }
860
861 #[inline]
862 fn set_attr(&self, name: SEXP, val: SEXP) {
863 unsafe {
864 Rf_setAttrib(*self, name, val);
865 }
866 }
867
868 #[inline]
869 fn get_names(&self) -> SEXP {
870 unsafe { Rf_getAttrib(*self, R_NamesSymbol) }
871 }
872
873 #[inline]
874 fn set_names(&self, names: SEXP) {
875 unsafe {
876 Rf_namesgets(*self, names);
877 }
878 }
879
880 #[inline]
881 fn get_class(&self) -> SEXP {
882 unsafe { Rf_getAttrib(*self, R_ClassSymbol) }
883 }
884
885 #[inline]
886 fn set_class(&self, class: SEXP) {
887 unsafe {
888 Rf_classgets(*self, class);
889 }
890 }
891
892 #[inline]
893 fn get_dim(&self) -> SEXP {
894 unsafe { Rf_getAttrib(*self, R_DimSymbol) }
895 }
896
897 #[inline]
898 fn set_dim(&self, dim: SEXP) {
899 unsafe {
900 Rf_dimgets(*self, dim);
901 }
902 }
903
904 #[inline]
905 fn get_dimnames(&self) -> SEXP {
906 unsafe { Rf_getAttrib(*self, R_DimNamesSymbol) }
907 }
908
909 #[inline]
910 fn set_dimnames(&self, dimnames: SEXP) {
911 unsafe {
912 Rf_dimnamesgets(*self, dimnames);
913 }
914 }
915
916 #[inline]
917 fn get_levels(&self) -> SEXP {
918 unsafe { Rf_getAttrib(*self, R_LevelsSymbol) }
919 }
920
921 #[inline]
922 fn set_levels(&self, levels: SEXP) {
923 unsafe {
924 Rf_setAttrib(*self, R_LevelsSymbol, levels);
925 }
926 }
927
928 #[inline]
929 fn get_row_names(&self) -> SEXP {
930 unsafe { Rf_getAttrib(*self, R_RowNamesSymbol) }
931 }
932
933 #[inline]
934 fn set_row_names(&self, row_names: SEXP) {
935 unsafe {
936 Rf_setAttrib(*self, R_RowNamesSymbol, row_names);
937 }
938 }
939
940 #[inline]
941 fn copy_most_attrib(&self, from: SEXP) {
942 unsafe { Rf_copyMostAttrib(from, *self) }
943 }
944
945 #[inline]
946 fn inherits_class(&self, class: &std::ffi::CStr) -> bool {
947 unsafe { Rf_inherits(*self, class.as_ptr()) != Rboolean::FALSE }
948 }
949
950 fn has_attributes(&self) -> bool {
951 // A CHARSXP's ATTRIB slot links the string-cache hash chain;
952 // `attributes()` would walk those CHARSXPs as if they were pairlist
953 // nodes.
954 if self.type_of() == SEXPTYPE::CHARSXP {
955 return false;
956 }
957 // `attributes` is a builtin, so its argument is evaluated: wrap the
958 // value in `quote()` so a symbol, call or promise is passed as is.
959 unsafe {
960 let scope = ProtectScope::new();
961 let quoted = scope.protect_raw(Rf_lang2(Rf_install(c"quote".as_ptr()), *self));
962 let call = scope.protect_raw(Rf_lang2(Rf_install(c"attributes".as_ptr()), quoted));
963 !Rf_eval(call, R_BaseEnv).is_nil()
964 }
965 }
966
967 // endregion
968
969 // region: String element access
970
971 #[inline]
972 fn string_elt(&self, i: isize) -> SEXP {
973 unsafe { STRING_ELT(*self, i) }
974 }
975
976 #[inline]
977 fn string_elt_str(&self, i: isize) -> Option<&str> {
978 let charsxp = self.string_elt(i);
979 if charsxp.is_na_string() {
980 return None;
981 }
982 // SAFETY: a non-NA CHARSXP element of this STRSXP.
983 let text = unsafe { try_charsxp_to_str(charsxp) }.unwrap_or_else(|e| {
984 panic!(
985 "cannot read element {} of a character vector as Rust text: {}",
986 i + 1,
987 e.r_reason(false)
988 )
989 });
990 Some(text)
991 }
992
993 #[inline]
994 fn set_string_elt(&self, i: isize, charsxp: SEXP) {
995 unsafe { SET_STRING_ELT(*self, i, charsxp) }
996 }
997
998 #[inline]
999 fn is_na_string(&self) -> bool {
1000 unsafe { std::ptr::addr_eq(self.0, R_NaString.0) }
1001 }
1002
1003 // endregion
1004
1005 // region: List element access
1006
1007 #[inline]
1008 fn vector_elt(&self, i: isize) -> SEXP {
1009 unsafe { VECTOR_ELT(*self, i) }
1010 }
1011
1012 #[inline]
1013 fn set_vector_elt(&self, i: isize, val: SEXP) {
1014 unsafe {
1015 SET_VECTOR_ELT(*self, i, val);
1016 }
1017 }
1018
1019 // endregion
1020
1021 // region: Typed single-element access
1022
1023 #[inline]
1024 fn integer_elt(&self, i: isize) -> i32 {
1025 unsafe { INTEGER_ELT(*self, i) }
1026 }
1027 #[inline]
1028 fn real_elt(&self, i: isize) -> f64 {
1029 unsafe { REAL_ELT(*self, i) }
1030 }
1031 #[inline]
1032 fn logical_elt(&self, i: isize) -> i32 {
1033 unsafe { LOGICAL_ELT(*self, i) }
1034 }
1035 #[inline]
1036 fn complex_elt(&self, i: isize) -> Rcomplex {
1037 unsafe { COMPLEX_ELT(*self, i) }
1038 }
1039 #[inline]
1040 fn raw_elt(&self, i: isize) -> u8 {
1041 unsafe { RAW_ELT(*self, i) }
1042 }
1043 #[inline]
1044 fn set_integer_elt(&self, i: isize, v: i32) {
1045 unsafe { SET_INTEGER_ELT(*self, i, v) }
1046 }
1047 #[inline]
1048 fn set_real_elt(&self, i: isize, v: f64) {
1049 unsafe { SET_REAL_ELT(*self, i, v) }
1050 }
1051 #[inline]
1052 fn set_logical_elt(&self, i: isize, v: i32) {
1053 unsafe { SET_LOGICAL_ELT(*self, i, v) }
1054 }
1055 #[inline]
1056 fn set_complex_elt(&self, i: isize, v: Rcomplex) {
1057 unsafe { SET_COMPLEX_ELT(*self, i, v) }
1058 }
1059 #[inline]
1060 fn set_raw_elt(&self, i: isize, v: u8) {
1061 unsafe { SET_RAW_ELT(*self, i, v) }
1062 }
1063
1064 // endregion
1065
1066 // region: Symbol and CHARSXP access
1067
1068 #[inline]
1069 fn printname(&self) -> SEXP {
1070 unsafe { PRINTNAME(*self) }
1071 }
1072
1073 #[inline]
1074 fn r_char(&self) -> *const ::std::os::raw::c_char {
1075 unsafe { R_CHAR(*self) }
1076 }
1077
1078 #[inline]
1079 fn r_char_str(&self) -> Option<&str> {
1080 if self.is_na_string() {
1081 return None;
1082 }
1083 // SAFETY: a non-NA CHARSXP (trait contract).
1084 Some(unsafe { charsxp_to_str_or_panic(*self) })
1085 }
1086
1087 // endregion
1088
1089 // region: Vector resizing
1090
1091 #[inline]
1092 fn resize(&self, newlen: R_xlen_t) -> SEXP {
1093 unsafe { Rf_xlengthgets(*self, newlen) }
1094 }
1095
1096 // endregion
1097
1098 // region: Duplication
1099
1100 #[inline]
1101 fn duplicate(&self) -> SEXP {
1102 unsafe { Rf_duplicate(*self) }
1103 }
1104
1105 #[inline]
1106 fn shallow_duplicate(&self) -> SEXP {
1107 unsafe { Rf_shallow_duplicate(*self) }
1108 }
1109
1110 // endregion
1111
1112 // region: Comparison
1113
1114 #[inline]
1115 fn is_identical(&self, other: SEXP) -> bool {
1116 unsafe { R_compute_identical(*self, other, IDENT_USE_CLOENV) != Rboolean::FALSE }
1117 }
1118
1119 // endregion
1120
1121 // region: Unchecked variants
1122
1123 #[inline]
1124 unsafe fn string_elt_unchecked(&self, i: isize) -> SEXP {
1125 unsafe { STRING_ELT_unchecked(*self, i) }
1126 }
1127
1128 #[inline]
1129 unsafe fn set_string_elt_unchecked(&self, i: isize, charsxp: SEXP) {
1130 unsafe { SET_STRING_ELT_unchecked(*self, i, charsxp) }
1131 }
1132
1133 #[inline]
1134 unsafe fn vector_elt_unchecked(&self, i: isize) -> SEXP {
1135 unsafe { VECTOR_ELT_unchecked(*self, i) }
1136 }
1137
1138 #[inline]
1139 unsafe fn set_vector_elt_unchecked(&self, i: isize, val: SEXP) {
1140 unsafe {
1141 SET_VECTOR_ELT_unchecked(*self, i, val);
1142 }
1143 }
1144
1145 #[inline]
1146 unsafe fn get_attr_unchecked(&self, name: SEXP) -> SEXP {
1147 unsafe { Rf_getAttrib_unchecked(*self, name) }
1148 }
1149
1150 #[inline]
1151 unsafe fn set_attr_unchecked(&self, name: SEXP, val: SEXP) {
1152 unsafe {
1153 Rf_setAttrib_unchecked(*self, name, val);
1154 }
1155 }
1156
1157 #[inline]
1158 unsafe fn copy_most_attrib_unchecked(&self, from: SEXP) {
1159 unsafe { Rf_copyMostAttrib_unchecked(from, *self) }
1160 }
1161
1162 #[inline]
1163 unsafe fn r_char_unchecked(&self) -> *const ::std::os::raw::c_char {
1164 unsafe { R_CHAR_unchecked(*self) }
1165 }
1166
1167 // endregion
1168}
1169
1170/// Pairlist (cons cell) operations on a `SEXP`: R's calls (`LANGSXP`) and
1171/// pairlists (`LISTSXP`, such as `formals(f)` or `pairlist(...)`).
1172///
1173/// Each node has three slots: CAR (the value), CDR (the next node, `NULL`
1174/// after the last) and TAG (the name, a symbol, or `NULL` when unnamed). A
1175/// call's first node holds the function, the following nodes its arguments:
1176///
1177/// ```ignore
1178/// use miniextendr_api::{PairListExt, SEXP};
1179///
1180/// // `call` is `c(time = TAD, dose = NA)`, rooted by the caller.
1181/// fn roles(call: SEXP) -> Vec<(Option<String>, SEXP)> {
1182/// call.args().map(|(name, value)| (name.map(str::to_owned), value)).collect()
1183/// }
1184/// ```
1185///
1186/// The values read from a node are reachable from the pairlist, so they stay
1187/// rooted while it does. A pairlist R handed you (a `.Call()` argument, a
1188/// quosure's expression) is shared: change only a node you own, such as one
1189/// of a `shallow_duplicate()` of the call.
1190pub trait PairListExt {
1191 /// A new pairlist node, `CONS(self, cdr)`: this SEXP as its value, `cdr`
1192 /// as the rest. The node is unprotected.
1193 fn cons(self, cdr: SEXP) -> SEXP;
1194
1195 /// A new call node, `LCONS(self, cdr)`: this SEXP (the function) as its
1196 /// value, `cdr` (the arguments) as the rest. The node is unprotected.
1197 fn lcons(self, cdr: SEXP) -> SEXP;
1198
1199 /// The value of this node (`CAR`). On a call, the function.
1200 fn car(&self) -> SEXP;
1201
1202 /// The rest of the pairlist after this node (`CDR`): the next node, or
1203 /// `NULL` after the last. On a call, its arguments.
1204 fn cdr(&self) -> SEXP;
1205
1206 /// The name of this node (`TAG`): a symbol, or `NULL` when it has none.
1207 fn tag(&self) -> SEXP;
1208
1209 /// The arguments of a call, or the elements of a pairlist, as
1210 /// `(name, value)`. The name is `None` for an unnamed one; a repeated
1211 /// name is kept.
1212 ///
1213 /// | `self` | yields |
1214 /// |---|---|
1215 /// | a call, `f(a, b = 2)` | its arguments, `(None, a)` then `(Some("b"), 2)`; the function is not one of them |
1216 /// | a pairlist, `pairlist(a = 1, 2)` | every element, `(Some("a"), 1)` then `(None, 2)` |
1217 /// | `NULL` (the empty pairlist) | nothing |
1218 ///
1219 /// An empty argument, the slot of `f(a = )`, is the missing argument
1220 /// ([`SEXP::missing_arg()`]); a `NULL` argument does not end the walk.
1221 /// The names are the print names of the tags; the borrow of `self` stands
1222 /// for the root that keeps the pairlist alive.
1223 ///
1224 /// # Panics
1225 ///
1226 /// When `self` is not a call, a pairlist or `NULL`.
1227 fn args(&self) -> PairListArgs<'_>;
1228
1229 /// Set the name of this node (`SET_TAG`): a symbol, or `NULL`.
1230 ///
1231 /// Only on a node you own, such as one of a `shallow_duplicate()` of the
1232 /// call, never on a call or pairlist R handed you: R shares them.
1233 fn set_tag(&self, tag: SEXP);
1234
1235 /// Set the value of this node (`SETCAR`); returns `value`.
1236 ///
1237 /// Only on a node you own, such as one of a `shallow_duplicate()` of the
1238 /// call, never on a call or pairlist R handed you: R shares them.
1239 fn set_car(&self, value: SEXP) -> SEXP;
1240
1241 /// Set the rest of the pairlist after this node (`SETCDR`); returns
1242 /// `tail`.
1243 ///
1244 /// Only on a node you own, such as one of a `shallow_duplicate()` of the
1245 /// call, never on a call or pairlist R handed you: R shares them.
1246 fn set_cdr(&self, tail: SEXP) -> SEXP;
1247
1248 /// Create a cons cell (no thread check).
1249 /// # Safety
1250 /// Must be called from R's main thread.
1251 unsafe fn cons_unchecked(self, cdr: SEXP) -> SEXP;
1252
1253 /// Get the CAR (no thread check).
1254 /// # Safety
1255 /// Must be called from R's main thread.
1256 unsafe fn car_unchecked(&self) -> SEXP;
1257
1258 /// Get the CDR (no thread check).
1259 /// # Safety
1260 /// Must be called from R's main thread.
1261 unsafe fn cdr_unchecked(&self) -> SEXP;
1262
1263 /// Set the TAG (no thread check).
1264 /// # Safety
1265 /// Must be called from R's main thread.
1266 unsafe fn set_tag_unchecked(&self, tag: SEXP);
1267
1268 /// Set the CAR (no thread check).
1269 /// # Safety
1270 /// Must be called from R's main thread.
1271 unsafe fn set_car_unchecked(&self, value: SEXP) -> SEXP;
1272
1273 /// Set the CDR (no thread check).
1274 /// # Safety
1275 /// Must be called from R's main thread.
1276 unsafe fn set_cdr_unchecked(&self, tail: SEXP) -> SEXP;
1277}
1278
1279impl PairListExt for SEXP {
1280 #[inline]
1281 fn cons(self, cdr: SEXP) -> SEXP {
1282 unsafe { Rf_cons(self, cdr) }
1283 }
1284
1285 #[inline]
1286 fn lcons(self, cdr: SEXP) -> SEXP {
1287 unsafe { Rf_lcons(self, cdr) }
1288 }
1289
1290 #[inline]
1291 fn car(&self) -> SEXP {
1292 unsafe { CAR(*self) }
1293 }
1294
1295 #[inline]
1296 fn cdr(&self) -> SEXP {
1297 unsafe { CDR(*self) }
1298 }
1299
1300 #[inline]
1301 fn tag(&self) -> SEXP {
1302 unsafe { TAG(*self) }
1303 }
1304
1305 fn args(&self) -> PairListArgs<'_> {
1306 let first = match self.type_of() {
1307 SEXPTYPE::LANGSXP => self.cdr(),
1308 SEXPTYPE::LISTSXP | SEXPTYPE::NILSXP => *self,
1309 other => panic!(
1310 "`args()` reads a call, a pairlist or NULL, not {}",
1311 other.type_name()
1312 ),
1313 };
1314 PairListArgs {
1315 node: first,
1316 _list: PhantomData,
1317 }
1318 }
1319
1320 #[inline]
1321 fn set_tag(&self, tag: SEXP) {
1322 unsafe { SET_TAG(*self, tag) }
1323 }
1324
1325 #[inline]
1326 fn set_car(&self, value: SEXP) -> SEXP {
1327 unsafe { SETCAR(*self, value) }
1328 }
1329
1330 #[inline]
1331 fn set_cdr(&self, tail: SEXP) -> SEXP {
1332 unsafe { SETCDR(*self, tail) }
1333 }
1334
1335 #[inline]
1336 unsafe fn cons_unchecked(self, cdr: SEXP) -> SEXP {
1337 unsafe { Rf_cons_unchecked(self, cdr) }
1338 }
1339
1340 #[inline]
1341 unsafe fn car_unchecked(&self) -> SEXP {
1342 unsafe { CAR_unchecked(*self) }
1343 }
1344
1345 #[inline]
1346 unsafe fn cdr_unchecked(&self) -> SEXP {
1347 unsafe { CDR_unchecked(*self) }
1348 }
1349
1350 #[inline]
1351 unsafe fn set_tag_unchecked(&self, tag: SEXP) {
1352 unsafe { SET_TAG_unchecked(*self, tag) }
1353 }
1354
1355 #[inline]
1356 unsafe fn set_car_unchecked(&self, value: SEXP) -> SEXP {
1357 unsafe { SETCAR_unchecked(*self, value) }
1358 }
1359
1360 #[inline]
1361 unsafe fn set_cdr_unchecked(&self, tail: SEXP) -> SEXP {
1362 unsafe { SETCDR_unchecked(*self, tail) }
1363 }
1364}
1365
1366/// The arguments of a call, or the elements of a pairlist, as
1367/// `(name, value)`: see [`PairListExt::args`].
1368///
1369/// The `'a` borrow stands for the root that keeps the pairlist alive; the
1370/// names borrow it too.
1371pub struct PairListArgs<'a> {
1372 /// The next node to read, `NULL` once every node has been read.
1373 node: SEXP,
1374 /// Borrows the root of the pairlist.
1375 _list: PhantomData<&'a SEXP>,
1376}
1377
1378impl<'a> Iterator for PairListArgs<'a> {
1379 type Item = (Option<&'a str>, SEXP);
1380
1381 fn next(&mut self) -> Option<Self::Item> {
1382 let node = self.node;
1383 if node.is_nil() {
1384 return None;
1385 }
1386 self.node = node.cdr();
1387 let tag = node.tag();
1388 // A tag is a symbol; its print name lives for the session.
1389 let name = if tag.is_symbol() {
1390 let name = unsafe { charsxp_to_str_or_panic(tag.printname()) };
1391 (!name.is_empty()).then_some(name)
1392 } else {
1393 None
1394 };
1395 Some((name, node.car()))
1396 }
1397}
1398
1399impl std::iter::FusedIterator for PairListArgs<'_> {}