typex 0.1.1

Runtime reflection: inspection, traversal, equality and mutation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use crate::path::OwnedPath;
use crate::reflect::with_patch_sequence_mut;
use crate::{
  Meta, MetaMut, MoveItemError, Object, ObjectRefMut, PathSegment, ReflectMut, TypeInfo, ValueKind,
};
// Keep public API names in scope for short intra-doc links.
#[allow(unused_imports)]
use crate::{MutationBatch, TypedMapAccessMut};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// Operation in a patch, applied with [`ObjectRefMut::apply`] or staged in a
/// [`MutationBatch`].
///
/// Path segments borrow field and key names for `'a`. Map operations address
/// string-keyed entries; use [`TypedMapAccessMut::key_typed_mut`] for maps
/// with other key types.
///
/// # Example
///
/// Apply a patch directly to a value:
///
/// ```
/// # use typex::{ObjectRefMut, PatchOperation, PathSegment};
/// let mut values = vec![1_u16, 2, 3];
/// let patch = [PatchOperation::set([PathSegment::Item(1)], 7_u16)];
///
/// ObjectRefMut::new(&mut values).apply(patch).unwrap();
/// assert_eq!(values, [1, 7, 3]);
/// ```
///
/// Stage the same patch to undo it later:
///
/// ```
/// # use typex::{MutationBatch, PatchOperation, PathSegment};
/// let mut values = vec![1_u16, 2, 3];
/// let patch = [PatchOperation::set([PathSegment::Item(1)], 7_u16)];
/// let rollback = MutationBatch::from(patch).commit(&mut values).unwrap();
///
/// assert_eq!(values, [1, 7, 3]);
/// rollback.undo(&mut values).unwrap();
/// assert_eq!(values, [1, 2, 3]);
/// ```
#[derive(Debug)]
pub enum PatchOperation<'a> {
  /// Replaces the value at `path`.
  Set {
    /// Path to the value being replaced.
    path: Vec<PathSegment<'a>>,
    /// Replacement value.
    value: Object,
  },
  /// Inserts or replaces a string-keyed map entry.
  InsertKey {
    /// Path to the map.
    path: Vec<PathSegment<'a>>,
    /// Entry key.
    key: String,
    /// Entry value.
    value: Object,
  },
  /// Removes a string-keyed map entry.
  RemoveKey {
    /// Path to the map.
    path: Vec<PathSegment<'a>>,
    /// Entry key.
    key: String,
  },
  /// Inserts an item before an index.
  InsertItem {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Insertion index.
    index: usize,
    /// Item value.
    value: Object,
  },
  /// Appends an item to a sequence.
  PushItem {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Item value.
    value: Object,
  },
  /// Removes an item at an index.
  RemoveItem {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Item index.
    index: usize,
  },
  /// Moves an item within a sequence.
  MoveItem {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Source index.
    from: usize,
    /// Index of the item to move before, or the length to move to the end.
    to: usize,
  },
}

/// One owned operation waiting for a staged commit.
#[derive(Debug)]
pub enum OwnedPatchOperation {
  /// Replaces the value at `path`.
  Set {
    /// Path to the value being replaced.
    path: OwnedPath,
    /// Replacement value.
    value: Object,
  },
  /// Inserts or replaces a string-keyed map entry.
  InsertKey {
    /// Path to the map.
    path: OwnedPath,
    /// Entry key.
    key: String,
    /// Entry value.
    value: Object,
  },
  /// Removes a string-keyed map entry.
  RemoveKey {
    /// Path to the map.
    path: OwnedPath,
    /// Entry key.
    key: String,
  },
  /// Inserts an item before an index.
  InsertItem {
    /// Path to the sequence.
    path: OwnedPath,
    /// Insertion index.
    index: usize,
    /// Item value.
    value: Object,
  },
  /// Appends an item to a sequence.
  PushItem {
    /// Path to the sequence.
    path: OwnedPath,
    /// Item value.
    value: Object,
  },
  /// Removes an item at an index.
  RemoveItem {
    /// Path to the sequence.
    path: OwnedPath,
    /// Item index.
    index: usize,
  },
  /// Moves an item within a sequence.
  MoveItem {
    /// Path to the sequence.
    path: OwnedPath,
    /// Source index.
    from: usize,
    /// Index of the item to move before, or the length to move to the end.
    to: usize,
  },
}

impl OwnedPatchOperation {
  /// Creates a whole-value replacement operation.
  pub fn set<'a>(path: impl IntoIterator<Item = PathSegment<'a>>, value: Object) -> Self {
    Self::Set {
      path: path.into_iter().collect(),
      value,
    }
  }

  /// Creates a map insertion operation.
  pub fn insert_key<'a>(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    key: impl Into<String>,
    value: Object,
  ) -> Self {
    Self::InsertKey {
      path: path.into_iter().collect(),
      key: key.into(),
      value,
    }
  }

  /// Creates a map removal operation.
  pub fn remove_key<'a>(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    key: impl Into<String>,
  ) -> Self {
    Self::RemoveKey {
      path: path.into_iter().collect(),
      key: key.into(),
    }
  }

  /// Creates a sequence insertion operation.
  pub fn insert_item<'a>(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    index: usize,
    value: Object,
  ) -> Self {
    Self::InsertItem {
      path: path.into_iter().collect(),
      index,
      value,
    }
  }

  /// Creates a sequence append operation.
  pub fn push_item<'a>(path: impl IntoIterator<Item = PathSegment<'a>>, value: Object) -> Self {
    Self::PushItem {
      path: path.into_iter().collect(),
      value,
    }
  }

  /// Creates a sequence removal operation.
  pub fn remove_item<'a>(path: impl IntoIterator<Item = PathSegment<'a>>, index: usize) -> Self {
    Self::RemoveItem {
      path: path.into_iter().collect(),
      index,
    }
  }

  /// Creates a sequence move operation.
  pub fn move_item<'a>(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    from: usize,
    to: usize,
  ) -> Self {
    Self::MoveItem {
      path: path.into_iter().collect(),
      from,
      to,
    }
  }
}

impl<'a> From<PatchOperation<'a>> for OwnedPatchOperation {
  fn from(operation: PatchOperation<'a>) -> Self {
    match operation {
      PatchOperation::Set { path, value } => Self::Set {
        path: OwnedPath::from(path.as_slice()),
        value,
      },
      PatchOperation::InsertKey { path, key, value } => Self::InsertKey {
        path: OwnedPath::from(path.as_slice()),
        key,
        value,
      },
      PatchOperation::RemoveKey { path, key } => Self::RemoveKey {
        path: OwnedPath::from(path.as_slice()),
        key,
      },
      PatchOperation::InsertItem { path, index, value } => Self::InsertItem {
        path: OwnedPath::from(path.as_slice()),
        index,
        value,
      },
      PatchOperation::PushItem { path, value } => Self::PushItem {
        path: OwnedPath::from(path.as_slice()),
        value,
      },
      PatchOperation::RemoveItem { path, index } => Self::RemoveItem {
        path: OwnedPath::from(path.as_slice()),
        index,
      },
      PatchOperation::MoveItem { path, from, to } => Self::MoveItem {
        path: OwnedPath::from(path.as_slice()),
        from,
        to,
      },
    }
  }
}

impl<'a> PatchOperation<'a> {
  /// Creates a whole-value replacement operation.
  pub fn set(path: impl IntoIterator<Item = PathSegment<'a>>, value: impl Meta + 'static) -> Self {
    Self::Set {
      path: path.into_iter().collect(),
      value: Object::new(value),
    }
  }

  /// Creates a map insertion operation.
  pub fn insert_key(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    key: impl Into<String>,
    value: impl Meta + 'static,
  ) -> Self {
    Self::InsertKey {
      path: path.into_iter().collect(),
      key: key.into(),
      value: Object::new(value),
    }
  }

  /// Creates a map removal operation.
  pub fn remove_key(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    key: impl Into<String>,
  ) -> Self {
    Self::RemoveKey {
      path: path.into_iter().collect(),
      key: key.into(),
    }
  }

  /// Creates a sequence insertion operation.
  pub fn insert_item(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    index: usize,
    value: impl Meta + 'static,
  ) -> Self {
    Self::InsertItem {
      path: path.into_iter().collect(),
      index,
      value: Object::new(value),
    }
  }

  /// Creates a sequence append operation.
  pub fn push_item(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    value: impl Meta + 'static,
  ) -> Self {
    Self::PushItem {
      path: path.into_iter().collect(),
      value: Object::new(value),
    }
  }

  /// Creates a sequence removal operation.
  pub fn remove_item(path: impl IntoIterator<Item = PathSegment<'a>>, index: usize) -> Self {
    Self::RemoveItem {
      path: path.into_iter().collect(),
      index,
    }
  }

  /// Creates a sequence move operation.
  pub fn move_item(
    path: impl IntoIterator<Item = PathSegment<'a>>,
    from: usize,
    to: usize,
  ) -> Self {
    Self::MoveItem {
      path: path.into_iter().collect(),
      from,
      to,
    }
  }
}

/// Operation kinds used to identify unsupported patch requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatchOperationKind {
  /// Replaces a value at a path.
  Set,
  /// Inserts or replaces a map entry.
  InsertKey,
  /// Removes a map entry.
  RemoveKey,
  /// Inserts a sequence item.
  InsertItem,
  /// Appends an item to a sequence.
  PushItem,
  /// Removes a sequence item.
  RemoveItem,
  /// Moves an item within a sequence.
  MoveItem,
}

impl fmt::Display for PatchOperationKind {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let name = match self {
      Self::Set => "set",
      Self::InsertKey => "insert key",
      Self::RemoveKey => "remove key",
      Self::InsertItem => "insert item",
      Self::PushItem => "push item",
      Self::RemoveItem => "remove item",
      Self::MoveItem => "move item",
    };
    f.write_str(name)
  }
}

/// Failure returned when applying a reflective patch.
/// Paths in failure variants borrow names from the patch operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplyError<'a> {
  /// No value exists at the requested path.
  PathNotFound {
    /// Path that could not be resolved.
    path: Vec<PathSegment<'a>>,
    /// Operation that was requested at the missing path.
    operation: PatchOperationKind,
  },
  /// The patch shape cannot be applied to the target shape.
  ShapeMismatch {
    /// Path of the incompatible value.
    path: Vec<PathSegment<'a>>,
    /// Shape required by the patch.
    expected: ValueKind,
    /// Shape found on the target.
    actual: ValueKind,
  },
  /// The patch value and target value have different concrete types.
  TypeMismatch {
    /// Path of the incompatible value.
    path: Vec<PathSegment<'a>>,
    /// Concrete type required by the patch.
    expected: TypeInfo,
    /// Concrete type found on the target.
    actual: TypeInfo,
  },
  /// An index lies outside the target sequence.
  IndexOutOfBounds {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Operation that received the index.
    operation: PatchOperationKind,
    /// Index that lies outside the sequence.
    index: usize,
    /// Length of the sequence.
    len: usize,
  },
  /// The target does not support the requested operation.
  Unsupported {
    /// Path at which the operation was requested.
    path: Vec<PathSegment<'a>>,
    /// Operation that was not supported.
    operation: PatchOperationKind,
  },
  /// A move failed and could not restore the item at its source index. The
  /// sequence no longer contains the item.
  ItemLost {
    /// Path to the sequence.
    path: Vec<PathSegment<'a>>,
    /// Source index of the lost item.
    index: usize,
  },
}

impl fmt::Display for ApplyError<'_> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::PathNotFound { operation, .. } => {
        write!(
          f,
          "Reflective patch operation {operation} targets a path that does not exist"
        )
      }
      Self::ShapeMismatch {
        expected, actual, ..
      } => {
        write!(
          f,
          "Reflective patch expected {expected:?}, found {actual:?}"
        )
      }
      Self::TypeMismatch {
        expected, actual, ..
      } => write!(
        f,
        "Reflective patch expected {}, found {}",
        expected.name(),
        actual.name()
      ),
      Self::IndexOutOfBounds {
        operation,
        index,
        len,
        ..
      } => write!(
        f,
        "Reflective patch operation {operation} received index {index} for a sequence of length {len}"
      ),
      Self::Unsupported { operation, .. } => {
        write!(f, "Reflective patch operation {operation} is unsupported")
      }
      Self::ItemLost { index, .. } => write!(
        f,
        "Reflective patch could not restore the item moved from index {index}"
      ),
    }
  }
}

#[cfg(feature = "std")]
impl std::error::Error for ApplyError<'_> {}

#[inline]
fn resolve_target<'a, 'p>(
  root: &'a mut dyn MetaMut,
  path: Vec<PathSegment<'p>>,
  operation: PatchOperationKind,
) -> Result<(&'a mut dyn MetaMut, Vec<PathSegment<'p>>), ApplyError<'p>> {
  match ObjectRefMut::path_from(root, &path) {
    Some(target) => Ok((target.inner, path)),
    None => Err(ApplyError::PathNotFound { path, operation }),
  }
}

/// Returns the structural kind of `target` for an error report.
///
/// Kept out of line so that the error paths add no code to the successful
/// path of each operation.
#[inline(never)]
pub(crate) fn kind_of(target: &dyn MetaMut) -> ValueKind {
  target.reflect().kind()
}

/// Builds the error for a target whose [`MetaMut::reflect_mut`] does not
/// expose the `expected` shape. Returns [`ApplyError::Unsupported`] when
/// `actual` equals `expected` and [`ApplyError::ShapeMismatch`] otherwise.
fn build_container_error<'p>(
  actual: ValueKind,
  path: Vec<PathSegment<'p>>,
  operation: PatchOperationKind,
  expected: ValueKind,
) -> ApplyError<'p> {
  if actual == expected {
    ApplyError::Unsupported { path, operation }
  } else {
    ApplyError::ShapeMismatch {
      path,
      expected,
      actual,
    }
  }
}

/// Maps a failed reflective operation onto [`ApplyError::Unsupported`],
/// discarding whatever error payload the operation returned.
fn unsupported<'p, T, E>(
  result: Result<T, E>,
  path: Vec<PathSegment<'p>>,
  operation: PatchOperationKind,
) -> Result<T, ApplyError<'p>> {
  result.map_err(|_| ApplyError::Unsupported { path, operation })
}

// Inlining avoids passing the owned operation and result across a call boundary.
#[inline(always)]
fn apply_operation<'p>(
  root: &mut dyn MetaMut,
  operation: PatchOperation<'p>,
) -> Result<(), ApplyError<'p>> {
  match operation {
    PatchOperation::Set { path, value } => {
      let operation = PatchOperationKind::Set;
      let (target, path) = resolve_target(root, path, operation)?;
      let expected = value.type_info();
      let actual = target.type_info();
      if expected != actual {
        return Err(ApplyError::TypeMismatch {
          path,
          expected,
          actual,
        });
      }
      unsupported(target.set_dyn(value), path, operation)?;
    }
    PatchOperation::InsertKey { path, key, value } => {
      let operation = PatchOperationKind::InsertKey;
      let (target, path) = resolve_target(root, path, operation)?;
      let ReflectMut::Map(map) = target.reflect_mut() else {
        return Err(build_container_error(
          kind_of(target),
          path,
          operation,
          ValueKind::Map,
        ));
      };
      unsupported(map.insert_key(&key, value), path, operation)?;
    }
    PatchOperation::RemoveKey { path, key } => {
      let operation = PatchOperationKind::RemoveKey;
      let (target, path) = resolve_target(root, path, operation)?;
      let ReflectMut::Map(map) = target.reflect_mut() else {
        return Err(build_container_error(
          kind_of(target),
          path,
          operation,
          ValueKind::Map,
        ));
      };
      unsupported(map.remove_key(&key).ok_or(()), path, operation)?;
    }
    PatchOperation::InsertItem { path, index, value } => {
      let operation = PatchOperationKind::InsertItem;
      let (target, path) = resolve_target(root, path, operation)?;
      with_patch_sequence_mut!(
        target.reflect_mut(),
        |sequence| {
          unsupported(sequence.insert_item(index, value), path, operation)?;
        },
        {
          return Err(build_container_error(
            kind_of(target),
            path,
            operation,
            ValueKind::Sequence,
          ));
        }
      )
    }
    PatchOperation::PushItem { path, value } => {
      let operation = PatchOperationKind::PushItem;
      let (target, path) = resolve_target(root, path, operation)?;
      with_patch_sequence_mut!(
        target.reflect_mut(),
        |sequence| {
          unsupported(sequence.push_item(value), path, operation)?;
        },
        {
          return Err(build_container_error(
            kind_of(target),
            path,
            operation,
            ValueKind::Sequence,
          ));
        }
      )
    }
    PatchOperation::RemoveItem { path, index } => {
      let operation = PatchOperationKind::RemoveItem;
      let (target, path) = resolve_target(root, path, operation)?;
      with_patch_sequence_mut!(
        target.reflect_mut(),
        |sequence| {
          unsupported(sequence.remove_item(index).ok_or(()), path, operation)?;
        },
        {
          return Err(build_container_error(
            kind_of(target),
            path,
            operation,
            ValueKind::Sequence,
          ));
        }
      )
    }
    PatchOperation::MoveItem { path, from, to } => {
      let operation = PatchOperationKind::MoveItem;
      let (target, path) = resolve_target(root, path, operation)?;
      with_patch_sequence_mut!(
        target.reflect_mut(),
        |sequence| {
          // Check the indices here so the error names the offending index.
          let len = sequence.len();
          if let Some(index) = move_index_out_of_bounds(from, to, len) {
            return Err(ApplyError::IndexOutOfBounds {
              path,
              operation,
              index,
              len,
            });
          }
          sequence.move_item(from, to).map_err(|error| match error {
            MoveItemError::RestoreFailed => ApplyError::ItemLost { path, index: from },
            _ => ApplyError::Unsupported { path, operation },
          })?;
        },
        {
          return Err(build_container_error(
            kind_of(target),
            path,
            operation,
            ValueKind::Sequence,
          ));
        }
      )
    }
  }
  Ok(())
}

/// Returns the first index of a move from `from` to `to` that lies outside a
/// sequence of length `len`.
pub(crate) fn move_index_out_of_bounds(from: usize, to: usize, len: usize) -> Option<usize> {
  if from >= len {
    Some(from)
  } else if to > len {
    Some(to)
  } else {
    None
  }
}

pub(crate) fn apply_patch<'p, I>(
  root: &mut dyn MetaMut,
  operations: I,
) -> Result<(), ApplyError<'p>>
where
  I: IntoIterator<Item = PatchOperation<'p>>,
{
  for operation in operations {
    apply_operation(root, operation)?;
  }
  Ok(())
}