cel_runtime/list_traits.rs
1//! Builds and borrows heterogeneous lists without erasing their field types.
2//!
3//! ```
4//! use cel_runtime::{IntoTupleList, List, TypeIdIterator};
5//! let list = (String::from("first"), 7u8).into_tuple_list();
6//! assert_eq!(list.head(), "first");
7//! assert_eq!(*list.tail().head(), 7);
8//! assert_eq!(list.len(), 2);
9//! assert!(!list.is_empty());
10//! assert_eq!(list.reverse().reverse().append(()).len(), 2);
11//! assert_eq!(TypeIdIterator::<(String, (u8, ()))>::default().count(), 2);
12//! ```
13
14use std::any::TypeId;
15
16/// Represents a finite heterogeneous list with source-ordered heads and tails.
17///
18/// The `List` trait provides a type-safe way to work with lists where each node
19/// contains a value (head) and the remainder of the list (tail). This trait
20/// is implemented for both empty lists and non-empty lists.
21///
22/// Empty lists have length zero; each nonempty list has one more field than
23/// its tail. Borrowed heads and tails remain part of the caller-owned list.
24///
25/// # Examples
26/// See the [module tutorial](self).
27pub trait List {
28 /// The type returned by [`List::empty()`].
29 type Empty: EmptyList;
30 /// Returns a new empty list that can be used to create a list with the same characteristics.
31 ///
32 /// # Examples
33 /// See [`List`].
34 fn empty() -> Self::Empty;
35
36 /// The type of head.
37 type Head: 'static;
38 /// Returns a reference to the head.
39 ///
40 /// - Precondition: The list is nonempty.
41 ///
42 /// # Examples
43 /// See [`List`].
44 fn head(&self) -> &Self::Head;
45
46 /// The type of the rest of the list.
47 type Tail: List;
48 /// Returns a reference to the rest of the list.
49 ///
50 /// - Precondition: The list is nonempty.
51 ///
52 /// # Examples
53 /// See [`List`].
54 fn tail(&self) -> &Self::Tail;
55
56 /// Returns true if the list is empty.
57 ///
58 /// # Examples
59 /// See [`List`].
60 fn is_empty(&self) -> bool {
61 self.len() == 0
62 }
63
64 /// The length of the list, computed at compile time.
65 const LENGTH: usize = Self::Tail::LENGTH + 1;
66 /// Returns the length of the list.
67 ///
68 /// # Examples
69 /// See [`List`].
70 fn len(&self) -> usize {
71 Self::LENGTH
72 }
73
74 /// The type of the list after pushing a new value.
75 type Push<U: 'static>: List;
76 /// Pushes a new value onto the front of the list, returning a new list.
77 ///
78 /// # Examples
79 /// ```
80 /// use cel_runtime::List;
81 /// assert_eq!(().push("first").push(7u8), (7, ("first", ())));
82 /// ```
83 fn push<U: 'static>(self, item: U) -> Self::Push<U>;
84
85 // ---
86
87 /// The style of `List` appended to `Self`
88 type Append<U: List>: List;
89
90 /// Moves `other` after this list's source-ordered fields.
91 ///
92 /// - Complexity: O(n) field moves for n fields in this list.
93 ///
94 /// # Examples
95 ///
96 /// ```rust
97 /// use cel_runtime::*;
98 ///
99 /// assert_eq!(
100 /// (1, (2, (3, ()))).append((4, (5, (6, ())))),
101 /// (1, (2, (3, (4, (5, (6, ()))))))
102 /// );
103 /// ```
104 fn append<U: List>(self, other: U) -> Self::Append<U>;
105
106 /// The resulting list when reversing `Self` onto `U`.
107 type ReverseOnto<U: List>: List;
108 /// Moves this list's reversed fields before `other`.
109 ///
110 /// - Complexity: O(n) field moves for n fields in this list.
111 ///
112 /// # Examples
113 /// See [`List::reverse`].
114 fn reverse_onto<U: List>(self, other: U) -> Self::ReverseOnto<U>;
115
116 /// Moves this list's fields into opposite source order.
117 ///
118 /// - Complexity: O(n) field moves for n fields.
119 ///
120 /// # Examples
121 /// See [`List`].
122 fn reverse(self) -> Self::ReverseOnto<Self::Empty>
123 where
124 Self: Sized,
125 {
126 self.reverse_onto(Self::empty())
127 }
128}
129
130/// Convenience alias for reversing a `List` onto its empty counterpart.
131///
132/// # Examples
133/// ```
134/// use cel_runtime::{List, ReverseList};
135/// let reversed: ReverseList<(u8, (String, ()))> = (7u8, (String::from("first"), ())).reverse();
136/// assert_eq!(reversed.head(), "first");
137/// ```
138pub type ReverseList<T> = <T as List>::ReverseOnto<<T as List>::Empty>;
139
140// Iterate a list (not recurse) to implement equal against an iterator.
141/// Property generator for iterating over type-level lists.
142///
143/// # Examples
144/// See [`ListTypeIterator`], which uses `TypeId` as its property generator.
145pub trait ListTypeProperty {
146 /// The per-element property type produced during iteration.
147 type Output;
148 /// Computes the property for the current list head in `R`.
149 ///
150 /// # Examples
151 /// See [`ListTypeIterator`].
152 fn property<R: List>() -> Self::Output;
153}
154
155impl ListTypeProperty for TypeId {
156 type Output = Self;
157 /// Returns the current logical head's runtime type identity.
158 fn property<R: List>() -> Self::Output {
159 TypeId::of::<R::Head>()
160 }
161}
162
163/// Iterator over type-level `List` values producing properties via `P`.
164///
165/// Iteration visits each logical head once and remains exhausted after its tail.
166///
167/// # Examples
168/// ```
169/// use cel_runtime::{ListTypeIterator, TypeIdIterator};
170/// use std::any::TypeId;
171/// let mut iter = ListTypeIterator::<(u8, (String, ())), TypeId>::new();
172/// assert_eq!(iter.next(), Some(TypeId::of::<u8>()));
173/// assert_eq!(iter.next(), Some(TypeId::of::<String>()));
174/// assert_eq!(iter.next(), None);
175/// assert_eq!(TypeIdIterator::<()>::default().next(), None);
176/// ```
177pub struct ListTypeIterator<T: List, P: ListTypeProperty> {
178 /// Dispatches the next logical node, or the persistent empty-tail sentinel.
179 pub(crate) advance: fn(&mut Self) -> Option<P::Output>,
180}
181
182/// Advance function provider used by [`ListTypeIterator`].
183///
184/// Implementations advance to the next tail before returning a head property,
185/// and return `None` at an empty tail.
186///
187/// # Examples
188/// See [`ListTypeIterator`].
189pub trait ListTypeIteratorAdvance<P: ListTypeProperty>: List + Sized {
190 /// Advances the iterator and returns the next property, or `None` at exhaustion.
191 ///
192 /// - Complexity: The property generator's complexity for a nonempty head.
193 ///
194 /// # Examples
195 /// See [`ListTypeIterator`].
196 fn advancer<R: List>(iter: &mut ListTypeIterator<R, P>) -> Option<P::Output>;
197}
198
199impl<T: ListTypeIteratorAdvance<P> + 'static, P: ListTypeProperty> ListTypeIterator<T, P> {
200 /// Constructs an iterator positioned at the first logical head of `T`.
201 ///
202 /// # Examples
203 /// See [`ListTypeIterator`].
204 #[must_use]
205 pub fn new() -> Self {
206 ListTypeIterator {
207 advance: T::advancer::<T>,
208 }
209 }
210}
211
212impl<T: ListTypeIteratorAdvance<P> + 'static, P: ListTypeProperty> Default
213 for ListTypeIterator<T, P>
214{
215 /// Constructs an iterator positioned at the first logical head.
216 fn default() -> Self {
217 Self::new()
218 }
219}
220
221impl<T: ListTypeIteratorAdvance<P> + 'static, P: ListTypeProperty> Iterator
222 for ListTypeIterator<T, P>
223{
224 type Item = P::Output;
225 /// Returns the next source-ordered property, or `None` after exhaustion.
226 ///
227 /// - Complexity: The property generator's complexity.
228 fn next(&mut self) -> Option<Self::Item> {
229 (self.advance)(self)
230 }
231}
232
233/// Iterator that yields the [`TypeId`] of each head in the `List`.
234///
235/// # Examples
236/// See [`ListTypeIterator`].
237pub type TypeIdIterator<T> = ListTypeIterator<T, TypeId>;
238
239/// Marker type representing the head of an empty list.
240///
241/// No empty-list operation constructs or borrows a head value.
242///
243/// # Examples
244/// ```
245/// use cel_runtime::{List, Undefined};
246/// fn empty_head_type(_: Option<&<() as List>::Head>) {}
247/// empty_head_type(None::<&Undefined>);
248/// ```
249pub struct Undefined;
250
251/// Trait implemented by empty lists to support list construction.
252///
253/// # Examples
254/// ```
255/// use cel_runtime::{EmptyList, List};
256/// let list = <()>::root_empty().push_first(String::from("owned"));
257/// assert_eq!(list.head(), "owned");
258/// ```
259pub trait EmptyList {
260 /// The result of pushing the first element onto an empty list.
261 type PushFirst<U: 'static>: List;
262 /// Moves the first element into a singleton list.
263 ///
264 /// # Examples
265 /// See [`EmptyList`].
266 fn push_first<U: 'static>(self, item: U) -> Self::PushFirst<U>;
267
268 /// The canonical empty list type for this family.
269 type RootEmpty: EmptyList;
270 /// Returns a new canonical empty list.
271 ///
272 /// # Examples
273 /// See [`EmptyList`].
274 fn root_empty() -> Self::RootEmpty;
275}
276
277/// A blanket implementation for EmptyList.
278impl<T: EmptyList> List for T {
279 type Empty = T::RootEmpty;
280 /// Constructs this family's canonical empty root.
281 fn empty() -> Self::Empty {
282 T::root_empty()
283 }
284
285 type Head = Undefined;
286 /// Borrows a logical head.
287 ///
288 /// - Precondition: The list is nonempty.
289 fn head(&self) -> &Self::Head {
290 debug_assert!(!self.is_empty());
291 unreachable!("EmptyList has no head")
292 }
293
294 type Tail = T; // Satisfy the List trait
295 /// Borrows the remaining logical fields.
296 ///
297 /// - Precondition: The list is nonempty.
298 fn tail(&self) -> &Self::Tail {
299 debug_assert!(!self.is_empty());
300 unreachable!("EmptyList has no tail")
301 }
302
303 type Push<U: 'static> = T::PushFirst<U>;
304 /// Moves the first logical field into this empty list.
305 fn push<U>(self, item: U) -> Self::Push<U> {
306 self.push_first(item)
307 }
308
309 const LENGTH: usize = 0;
310
311 type Append<U: List> = U;
312 /// Returns `other` because this list contributes no logical fields.
313 fn append<U: List>(self, other: U) -> Self::Append<U> {
314 other
315 }
316
317 type ReverseOnto<U: List> = U;
318 /// Returns `other` because reversing the empty list adds no fields.
319 fn reverse_onto<U: List>(self, other: U) -> Self::ReverseOnto<U> {
320 other
321 }
322}
323
324/// Indexing for lists using typenum-based indices and ranges.
325///
326/// The index type establishes that the selected field or range exists.
327///
328/// # Examples
329/// ```
330/// use cel_runtime::{IntoTupleList, ListIndex};
331/// let list = ("first", 7u8).into_tuple_list();
332/// assert_eq!(*list.index(typenum::U1::new()), 7);
333/// ```
334pub trait ListIndex<Idx: ?Sized> {
335 /// The output reference type when indexing with `Idx`.
336 type Output;
337 /// Borrows the element or sublist selected by `index`.
338 ///
339 /// - Complexity: Representation-dependent; recursive suffix traversal takes
340 /// O(i) steps for source index i.
341 ///
342 /// # Examples
343 /// See [`ListIndex`].
344 fn index(&self, index: Idx) -> &Self::Output;
345}
346
347/// Names the field or sublist type selected by index `N` in list `L`.
348///
349/// # Examples
350/// ```
351/// use cel_runtime::Item;
352/// let first: Item<(String, (u8, ())), typenum::U0> = String::from("owned");
353/// assert_eq!(first, "owned");
354/// ```
355pub type Item<L, N> = <L as ListIndex<N>>::Output;
356
357/// Converts to a type-level `List` without consuming the source.
358///
359/// # Examples
360/// A converter retains its source ownership and states whether its fields are
361/// borrowed or independently copied; see [`IntoList`] for the consuming bridge.
362pub trait ToList {
363 /// The resulting `List` type using `T` as the empty list type family.
364 type ToList<T: EmptyList>: List;
365 /// Converts to a `List` using `T` as the empty list type family.
366 ///
367 /// - Complexity: The converter's field borrowing or copying costs.
368 ///
369 /// # Examples
370 /// See [`ToList`].
371 fn to_list<T: EmptyList>(&self) -> Self::ToList<T>;
372}
373
374/// Moves source fields into a type-level `List`.
375///
376/// # Examples
377/// ```
378/// use cel_runtime::{IntoList, List};
379/// let list = (String::from("first"), 7u8).into_list::<()>();
380/// assert_eq!(list.head(), "first");
381/// ```
382pub trait IntoList {
383 /// The resulting `List` type using `T` as the empty list type family.
384 type Output<T: EmptyList>: List;
385 /// Moves fields into a `List` using `T` as the empty list type family.
386 ///
387 /// - Complexity: O(n) field moves for the native tuple bridges, without allocation.
388 ///
389 /// # Examples
390 /// See [`IntoList`].
391 fn into_list<T: EmptyList>(self) -> Self::Output<T>;
392}
393
394impl IntoList for () {
395 type Output<T: EmptyList> = <T as List>::Empty;
396 /// Constructs the requested family's empty root.
397 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
398 T::empty()
399 }
400}
401
402impl<A: 'static> IntoList for (A,) {
403 type Output<T: EmptyList> = <<T as List>::Empty as List>::Push<A>;
404 /// Moves the singleton source field into the requested list family.
405 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
406 ().into_list::<T>().push(self.0)
407 }
408}
409
410impl<A: 'static, B: 'static> IntoList for (A, B) {
411 type Output<T: EmptyList> = <<(B,) as IntoList>::Output<T> as List>::Push<A>;
412 /// Moves both source fields into the requested list family without cloning.
413 ///
414 /// - Complexity: O(n) field moves for n tuple fields.
415 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
416 (self.1,).into_list::<T>().push(self.0)
417 }
418}
419
420impl<A: 'static, B: 'static, C: 'static> IntoList for (A, B, C) {
421 type Output<T: EmptyList> = <<(B, C) as IntoList>::Output<T> as List>::Push<A>;
422 /// Moves source fields into the requested list family without cloning.
423 ///
424 /// - Complexity: O(n) field moves for n tuple fields.
425 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
426 (self.1, self.2).into_list::<T>().push(self.0)
427 }
428}
429impl<A: 'static, B: 'static, C: 'static, D: 'static> IntoList for (A, B, C, D) {
430 type Output<T: EmptyList> = <<(B, C, D) as IntoList>::Output<T> as List>::Push<A>;
431 /// Moves source fields into the requested list family without cloning.
432 ///
433 /// - Complexity: O(n) field moves for n tuple fields.
434 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
435 (self.1, self.2, self.3).into_list::<T>().push(self.0)
436 }
437}
438
439impl<A: 'static, B: 'static, C: 'static, D: 'static, E: 'static> IntoList for (A, B, C, D, E) {
440 type Output<T: EmptyList> = <<(B, C, D, E) as IntoList>::Output<T> as List>::Push<A>;
441 /// Moves source fields into the requested list family without cloning.
442 ///
443 /// - Complexity: O(n) field moves for n tuple fields.
444 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
445 (self.1, self.2, self.3, self.4)
446 .into_list::<T>()
447 .push(self.0)
448 }
449}
450
451impl<A: 'static, B: 'static, C: 'static, D: 'static, E: 'static, F: 'static> IntoList
452 for (A, B, C, D, E, F)
453{
454 type Output<T: EmptyList> = <<(B, C, D, E, F) as IntoList>::Output<T> as List>::Push<A>;
455 /// Moves source fields into the requested list family without cloning.
456 ///
457 /// - Complexity: O(n) field moves for n tuple fields.
458 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
459 (self.1, self.2, self.3, self.4, self.5)
460 .into_list::<T>()
461 .push(self.0)
462 }
463}
464
465impl<A: 'static, B: 'static, C: 'static, D: 'static, E: 'static, F: 'static, G: 'static> IntoList
466 for (A, B, C, D, E, F, G)
467{
468 type Output<T: EmptyList> = <<(B, C, D, E, F, G) as IntoList>::Output<T> as List>::Push<A>;
469 /// Moves source fields into the requested list family without cloning.
470 ///
471 /// - Complexity: O(n) field moves for n tuple fields.
472 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
473 (self.1, self.2, self.3, self.4, self.5, self.6)
474 .into_list::<T>()
475 .push(self.0)
476 }
477}
478
479impl<A: 'static, B: 'static, C: 'static, D: 'static, E: 'static, F: 'static, G: 'static, H: 'static>
480 IntoList for (A, B, C, D, E, F, G, H)
481{
482 type Output<T: EmptyList> = <<(B, C, D, E, F, G, H) as IntoList>::Output<T> as List>::Push<A>;
483 /// Moves source fields into the requested list family without cloning.
484 ///
485 /// - Complexity: O(n) field moves for n tuple fields.
486 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
487 (self.1, self.2, self.3, self.4, self.5, self.6, self.7)
488 .into_list::<T>()
489 .push(self.0)
490 }
491}
492
493impl<
494 A: 'static,
495 B: 'static,
496 C: 'static,
497 D: 'static,
498 E: 'static,
499 F: 'static,
500 G: 'static,
501 H: 'static,
502 I: 'static,
503> IntoList for (A, B, C, D, E, F, G, H, I)
504{
505 type Output<T: EmptyList> =
506 <<(B, C, D, E, F, G, H, I) as IntoList>::Output<T> as List>::Push<A>;
507 /// Moves source fields into the requested list family without cloning.
508 ///
509 /// - Complexity: O(n) field moves for n tuple fields.
510 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
511 (
512 self.1, self.2, self.3, self.4, self.5, self.6, self.7, self.8,
513 )
514 .into_list::<T>()
515 .push(self.0)
516 }
517}
518
519impl<
520 A: 'static,
521 B: 'static,
522 C: 'static,
523 D: 'static,
524 E: 'static,
525 F: 'static,
526 G: 'static,
527 H: 'static,
528 I: 'static,
529 J: 'static,
530> IntoList for (A, B, C, D, E, F, G, H, I, J)
531{
532 type Output<T: EmptyList> =
533 <<(B, C, D, E, F, G, H, I, J) as IntoList>::Output<T> as List>::Push<A>;
534 /// Moves source fields into the requested list family without cloning.
535 ///
536 /// - Complexity: O(n) field moves for n tuple fields.
537 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
538 (
539 self.1, self.2, self.3, self.4, self.5, self.6, self.7, self.8, self.9,
540 )
541 .into_list::<T>()
542 .push(self.0)
543 }
544}
545
546impl<
547 A: 'static,
548 B: 'static,
549 C: 'static,
550 D: 'static,
551 E: 'static,
552 F: 'static,
553 G: 'static,
554 H: 'static,
555 I: 'static,
556 J: 'static,
557 K: 'static,
558> IntoList for (A, B, C, D, E, F, G, H, I, J, K)
559{
560 type Output<T: EmptyList> =
561 <<(B, C, D, E, F, G, H, I, J, K) as IntoList>::Output<T> as List>::Push<A>;
562 /// Moves source fields into the requested list family without cloning.
563 ///
564 /// - Complexity: O(n) field moves for n tuple fields.
565 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
566 (
567 self.1, self.2, self.3, self.4, self.5, self.6, self.7, self.8, self.9, self.10,
568 )
569 .into_list::<T>()
570 .push(self.0)
571 }
572}
573
574impl<
575 A: 'static,
576 B: 'static,
577 C: 'static,
578 D: 'static,
579 E: 'static,
580 F: 'static,
581 G: 'static,
582 H: 'static,
583 I: 'static,
584 J: 'static,
585 K: 'static,
586 L: 'static,
587> IntoList for (A, B, C, D, E, F, G, H, I, J, K, L)
588{
589 type Output<T: EmptyList> =
590 <<(B, C, D, E, F, G, H, I, J, K, L) as IntoList>::Output<T> as List>::Push<A>;
591 /// Moves source fields into the requested list family without cloning.
592 ///
593 /// - Complexity: O(n) field moves for n tuple fields.
594 fn into_list<T: EmptyList>(self) -> Self::Output<T> {
595 (
596 self.1, self.2, self.3, self.4, self.5, self.6, self.7, self.8, self.9, self.10,
597 self.11,
598 )
599 .into_list::<T>()
600 .push(self.0)
601 }
602}