techy 0.1.0

A fast, extensible LaTeX parser for Rust
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! The serialization session: [`SerdeSession`], its tables of objects, the
//! registrations it keeps for them, and the segments it emits and absorbs.

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::{Any, TypeId};
use core::fmt;
use core::marker::PhantomData;

use hashbrown::HashMap;

use crate::engine::{DescentGuard, StdDescentGuard, StdDescentGuardInit};

use super::super::error::{DeserializeError, RegistrationError, SerializeError};
use super::super::object::SerializableLang;
use super::super::value::{SerialEntry, SerialIndex, SerialValue, TableId};
use super::super::wire::{FromSerialValue, ToSerialValue};
use super::context::{DeserializeContext, SerializeContext};
use super::driver::{ObjectSerdeDriver, TableHandle};
use super::segment::{check_entry_nesting, Segment, SegmentMeta, SegmentTable, WireEntry};

/// A serialization session: the tables that objects are written into and read back from.
///
/// One session *writes*: objects are interned into its tables, and it emits them as
/// [`Segment`]s to store or transmit. Another session *reads*: segments are pushed into
/// it, and it returns the objects. Both directions use the same tables, so a session
/// that has absorbed a stream can go on interning objects that refer back to what it
/// absorbed. A session exists only for a [`SerializableLang`].
///
/// The [module documentation](crate::serialize) defines the vocabulary and walks both
/// paths in full; [Serializing parses](crate::guide::serialize) is the introductory
/// guide chapter.
///
/// # Tables, identity, and sharing
///
/// A session holds a set of *tables*, one per kind of object, each registered with its
/// [`ObjectSerdeDriver`] ([`register_table`](SerdeSession::register_table)) and numbered
/// in registration order ([`TableId`]).
///
/// Objects are kept in tables so that identity and sharing survive the round trip.
/// *Interning* an object into a table ([`intern`](SerdeSession::intern), or
/// [`SerializeContext::intern`] from inside a serialization call) serializes it once,
/// appends its entry to the table, and returns the entry's typed position. Interning the
/// same object again — the same `Arc`, compared by pointer — returns that position
/// instead of writing a second entry. So a parsing state a thousand nodes refer to is
/// written once and referred to by position, and reading the entries back yields one
/// shared object per entry rather than a thousand equal copies.
///
/// Positions are scoped to the stream, and tables are append-only: a table only ever
/// grows.
///
/// # Writing
///
/// [`new`](SerdeSession::new) creates a session with the crate's standard tables —
/// sources, states, specs, providers, trees, diagnostics, and parse results, whose
/// handles are [`StandardTables`](crate::serialize::StandardTables);
/// [`empty`](SerdeSession::empty) creates one with no tables, for a session composed of
/// other tables. Writing needs no registration beyond the tables themselves: every
/// object serializes itself.
///
/// Intern the objects — with [`intern`](SerdeSession::intern), or with a by-kind method
/// such as
/// [`serialize_parse_result`](crate::serialize::ParseResultSerialization::serialize_parse_result)
/// — then call [`take_segment`](SerdeSession::take_segment), which packages every entry
/// interned since the previous emission and nothing older, or
/// [`take_segment_with_main`](SerdeSession::take_segment_with_main), which additionally
/// records the position of the one entry the segment is about.
///
/// A segment is a value, not bytes. With the `serde` cargo feature [`Segment`]
/// implements `Serialize` and `Deserialize`, so a segment encodes through any serde
/// format; without the feature, [`Segment::to_serial_value`] converts it to the value
/// model and the caller encodes that.
///
/// # Reading
///
/// Give the reading session the same tables, then register what the read side needs: the
/// readers for the identifiers the stream uses
/// ([`register_core_readers`](crate::serialize::register_core_readers), or a language's
/// own helper), and the *reading environment* as user data
/// ([`set_user_data`](SerdeSession::set_user_data), one value per type). The reading
/// environment is how an implementation's `deserialize_object` reaches, through its
/// context, the live objects that serialized data refers to by identity instead of
/// describing them in full — for the crate's own providers, a
/// [`KnownProviders`](crate::serialize::KnownProviders) directory. The session also
/// holds the readers and resolvers registered on heterogeneous tables (see
/// [`DispatchingSerdeDriver`](crate::serialize::DispatchingSerdeDriver)).
///
/// Then push the segments. [`push_segment`](SerdeSession::push_segment) validates a
/// segment, appends its entries to the session's tables, and rebuilds every entry's
/// object through the table's driver; it returns the segment's main entry, translated
/// into this session's numbering. [`object`](SerdeSession::object), or a by-kind method
/// such as [`parse_result`](crate::serialize::ParseResultSerialization::parse_result),
/// reads an object back at its position.
///
/// A *stream* is the sequence of segments one writing session emits. A reading session
/// absorbs the segments of one stream, in order; it can then intern further objects and
/// emit segments of its own that refer back to what it absorbed.
///
/// # Nesting and cycles
///
/// Nested calls — an object's serialization interning the objects it refers to, an
/// entry's deserialization reading the objects it refers to — are bounded by the crate's
/// descent guard ([`with_descent_guard_init`](SerdeSession::with_descent_guard_init)).
/// Reference cycles are detected on both sides and reported as errors, never followed.
///
/// # Examples
///
/// A table of one kind of object, written by one session and read by another. The
/// example uses an [`empty`](SerdeSession::empty) session with a custom table so that it
/// is self-contained; the crate's own object kinds go through the standard tables.
///
/// ```
/// use std::sync::Arc;
/// use techy::core::TrivialLang;
/// use techy::serialize::{
///     DeserializeContext, DeserializeError, ObjectSerdeDriver, SerdeSession, SerialEntry,
///     SerialValue, SerializableLang, SerializeContext, SerializeError,
/// };
///
/// #[derive(Debug, Clone, Copy)]
/// struct MyLang;
/// impl TrivialLang for MyLang {}
/// impl SerializableLang for MyLang {}
///
/// // The object kind, its position type, and its driver.
/// struct Label(String);
/// techy::serial_index! { pub struct LabelIndex; }
/// struct LabelDriver;
///
/// impl ObjectSerdeDriver<MyLang> for LabelDriver {
///     type Object = Label;
///     type Index = LabelIndex;
///     fn table_name(&self) -> &'static str { "labels" }
///     fn homogeneous_identifier(&self) -> Option<&'static str> { Some("example.label") }
///     fn serialize_object(&self, label: &Arc<Label>, _cx: &mut SerializeContext<'_, MyLang>)
///         -> Result<SerialEntry, SerializeError>
///     {
///         Ok(SerialEntry { identifier: "example.label".into(), data: SerialValue::Str(label.0.clone()) })
///     }
///     fn deserialize_object(&self, entry: &SerialEntry, _cx: &mut DeserializeContext<'_, MyLang>)
///         -> Result<Arc<Label>, DeserializeError>
///     {
///         match &entry.data {
///             SerialValue::Str(text) => Ok(Arc::new(Label(text.clone()))),
///             _ => Err(DeserializeError::failed("a label is a string")),
///         }
///     }
/// }
///
/// // Write: intern two objects (one of them twice) and emit a segment.
/// let mut writer = SerdeSession::<MyLang>::empty();
/// let labels = writer.register_table(LabelDriver)?;
/// let shared = Arc::new(Label("shared".into()));
/// let first = writer.intern(labels, &shared)?;
/// let second = writer.intern(labels, &Arc::new(Label("other".into())))?;
/// assert_eq!(writer.intern(labels, &shared)?, first);   // the same position again
/// let segment = writer.take_segment();
///
/// // Read: absorb the segment into another session and read the objects back. The
/// // reader registered its tables in the writer's order, so the writer's positions
/// // are valid in it as they are (see `TableHandle::position` for the general case).
/// let mut reader = SerdeSession::<MyLang>::empty();
/// let labels = reader.register_table(LabelDriver)?;
/// reader.push_segment(segment)?;
/// assert_eq!(reader.object(labels, first)?.0, "shared");
/// assert_eq!(reader.object(labels, second)?.0, "other");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct SerdeSession<L: SerializableLang> {
    tables: Vec<TableState<L>>,
    /// The caller's user data, one value per type.
    user_data: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
    /// The caller-declared profile (see [`set_profile`](SerdeSession::set_profile)):
    /// written into every emitted segment; required of every absorbed one when set.
    profile: Option<String>,
    descent_guard_init: StdDescentGuardInit,
    /// The write side's in-progress stack: `(table ordinal, object address)` of the
    /// objects whose serialization is in progress, outermost first — the write-side
    /// cycle check.
    write_stack: Vec<(usize, usize)>,
    /// The resolver answers memoized during the segment push in progress —
    /// `(table ordinal, identifier)` — forgotten again if the push fails (part of the
    /// rollback). Entries are rebuilt only inside a push, so this is where every
    /// memoization happens.
    memo_journal: Vec<(usize, String)>,
    lang: PhantomData<fn() -> L>,
}

/// One table of the session.
pub(super) struct TableState<L: SerializableLang> {
    name: &'static str,
    /// The fixed identifier of a homogeneous table (`None`: heterogeneous).
    homogeneous: Option<&'static str>,
    /// The driver, `Arc<D>` behind `dyn Any` (the session is type-blind; typed access
    /// downcasts).
    driver: Arc<dyn Any + Send + Sync>,
    /// `TypeId::of::<D>()`: what a handle is validated against.
    driver_type: TypeId,
    /// The typed materialization routine for this table's driver type.
    materialize: MaterializeFn<L>,
    /// The entries, by position.
    slots: Vec<Slot>,
    /// Object address → position: the write side's interning map (and the read side's
    /// record of rebuilt objects, so that re-interning one yields its position).
    by_pointer: HashMap<usize, u32>,
    /// The serialized forms of the entries interned since the previous emission, in
    /// position order — always the tail of `slots`.
    outbox: Vec<SerialValue>,
    /// The registrations the session keeps for this table's driver (the readers and
    /// resolvers of a heterogeneous table — a `ReadDispatch<L, T>`; the annotation
    /// conversions of the trees table), created on first use.
    pub(super) registry: Option<Box<dyn TableRegistry>>,
}

/// The registrations of one table, as the type-blind session holds them for the
/// table's driver — the readers by identifier, the resolvers, and the memoized
/// resolver answers of a heterogeneous table; the annotation conversions of the trees
/// table: created on first use through
/// [`registry_mut`](SerdeSession::registry_mut), which downcasts to the concrete
/// registry type, and asked to forget memoized answers when a push is rolled back.
pub(crate) trait TableRegistry: Any + Send + Sync {
    /// The registry as `dyn Any`, for the typed downcast.
    fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync);

    /// Forget the memoized resolver answer for `identifier`, if any (a registry that
    /// memoizes nothing does nothing).
    fn forget_memo(&mut self, identifier: &str);
}

/// One entry of a table.
enum Slot {
    /// Absorbed from a segment, not yet rebuilt: the stored serialized form.
    Pending(SerialValue),
    /// Being rebuilt right now (the read side's cycle check).
    InProgress,
    /// The live object, `Arc<D::Object>` behind `dyn Any`.
    Materialized(Box<dyn Any + Send + Sync>),
}

impl Slot {
    fn is_materialized(&self) -> bool {
        matches!(self, Slot::Materialized(_))
    }
}

/// The erased entry point of [`materialize`]: rebuild one pending entry.
type MaterializeFn<L> = fn(
    &mut SerdeSession<L>,
    &mut StdDescentGuard,
    usize,
    u32,
    Option<(usize, u32)>,
) -> Result<(), DeserializeError>;

/// The address of an `Arc`'s allocation, as the interning key: object identity. The
/// `Arc` is kept alive in the table, so the address cannot be reused while the map
/// holds it.
fn address<T: ?Sized>(object: &Arc<T>) -> usize {
    Arc::as_ptr(object) as *const () as usize
}

impl<L: SerializableLang> SerdeSession<L> {
    /// A session with no tables; register them with
    /// [`register_table`](SerdeSession::register_table).
    pub fn empty() -> SerdeSession<L> {
        SerdeSession {
            tables: Vec::new(),
            user_data: HashMap::new(),
            profile: None,
            descent_guard_init: StdDescentGuardInit::default(),
            write_stack: Vec::new(),
            memo_journal: Vec::new(),
            lang: PhantomData,
        }
    }

    /// Sets the descent guard that bounds nested serialization and deserialization
    /// calls.
    ///
    /// Each level of nesting — an object's serialization interning the objects it refers
    /// to, an entry's deserialization reading the objects it refers to — is one
    /// *descent*. The guard applies to every subsequent
    /// [`intern`](SerdeSession::intern), [`object`](SerdeSession::object), and
    /// [`push_segment`](SerdeSession::push_segment) call; each such call is one run with
    /// a fresh guard. The default is the crate-wide default ([`StdDescentGuardInit`], a
    /// stack budget).
    ///
    /// Exceeding the limit is a `DescentLimitExceeded` error
    /// ([`SerializeError::DescentLimitExceeded`] when writing,
    /// [`DeserializeError::DescentLimitExceeded`] when reading). The guard's early
    /// warning that the limit is getting close has no observer here and is discarded.
    pub fn with_descent_guard_init(mut self, init: StdDescentGuardInit) -> SerdeSession<L> {
        self.descent_guard_init = init;
        self
    }

    /// Declares the session's *profile*: a caller-chosen string naming the configuration
    /// that can read the session's stream fully.
    ///
    /// The profile names the environment and version whose packages, spec types,
    /// annotation identifiers, and readers resolve every identity and identifier the
    /// stream refers to. A name like `"myframework 2.3 / techy 1"` is the caller's to
    /// choose and to keep meaningful; the crate compares it and does nothing else with
    /// it.
    ///
    /// Every segment the session emits then records the profile (in the segment's
    /// [`meta`](Segment::meta)), and every segment pushed into the session must record
    /// the same one: [`push_segment`](SerdeSession::push_segment) rejects a segment whose
    /// profile differs or is missing ([`DeserializeError::ProfileMismatch`]), before any
    /// entry is touched. A session that declares no profile writes none and accepts any.
    ///
    /// This makes the caller's contract about the reading environment checkable: a stream
    /// written for one configuration is refused up front by a reader configured for
    /// another, instead of failing later on some unresolvable entry — or, worse, reading
    /// through with a package of the same name that defines things differently.
    pub fn set_profile(&mut self, profile: impl Into<String>) {
        self.profile = Some(profile.into());
    }

    /// The session's declared profile, if any (see [`set_profile`](SerdeSession::set_profile)).
    pub fn profile(&self) -> Option<&str> {
        self.profile.as_deref()
    }

    // --- registration -----------------------------------------------------------------

    /// Registers a table with its driver, returning the typed handle to intern and read
    /// through.
    ///
    /// Tables are numbered in registration order; the number is the handle's
    /// [`id`](TableHandle::id).
    ///
    /// # Errors
    ///
    /// [`RegistrationError::DuplicateTableName`] when a table of the driver's
    /// [`table_name`](ObjectSerdeDriver::table_name) is already registered;
    /// [`RegistrationError::EmptyHomogeneousIdentifier`] when the driver's
    /// [`homogeneous_identifier`](ObjectSerdeDriver::homogeneous_identifier) is
    /// `Some("")` (an identifier is a real, non-empty string);
    /// [`RegistrationError::TooManyTables`] at `u32::MAX` tables.
    pub fn register_table<D: ObjectSerdeDriver<L>>(
        &mut self,
        driver: D,
    ) -> Result<TableHandle<D>, RegistrationError> {
        let name = driver.table_name();
        if self.tables.iter().any(|table| table.name == name) {
            return Err(RegistrationError::DuplicateTableName { name });
        }
        if driver.homogeneous_identifier() == Some("") {
            return Err(RegistrationError::EmptyHomogeneousIdentifier { table: name });
        }
        let ordinal = u32::try_from(self.tables.len()).map_err(|_| RegistrationError::TooManyTables)?;
        if ordinal == u32::MAX {
            return Err(RegistrationError::TooManyTables);
        }
        self.tables.push(TableState {
            name,
            homogeneous: driver.homogeneous_identifier(),
            driver: Arc::new(driver),
            driver_type: TypeId::of::<D>(),
            materialize: materialize_erased::<L, D>,
            slots: Vec::new(),
            by_pointer: HashMap::new(),
            outbox: Vec::new(),
            registry: None,
        });
        Ok(TableHandle::new(TableId::new(ordinal)))
    }

    /// Returns the handle of the table named `name`, if this session has a table of that
    /// name registered with driver type `D`.
    ///
    /// This is how code that did not register a table finds it — a driver referring to
    /// another table, or the accessors of the crate's own standard tables — given the
    /// table's name (its driver's [`table_name`](ObjectSerdeDriver::table_name)) and its
    /// driver type. `None` when no table of that name is registered, or when it is
    /// registered with a different driver type.
    pub fn table_handle<D: ObjectSerdeDriver<L>>(&self, name: &str) -> Option<TableHandle<D>> {
        let ordinal = self.table_ordinal_by_name(name)?;
        let table = self.tables.get(ordinal)?;
        (table.driver_type == TypeId::of::<D>()).then(|| TableHandle::new(TableId::new(ordinal as u32)))
    }

    /// The ordinal of the table `handle` names, if the handle is one of this
    /// session's: the table exists and is registered with driver type `D`. `Err` is
    /// the handle's id, for the caller's `UnknownTable` error.
    pub(crate) fn table_index<D: 'static>(&self, handle: TableHandle<D>) -> Result<usize, TableId> {
        let ordinal = usize::try_from(handle.id().ordinal()).map_err(|_| handle.id())?;
        match self.tables.get(ordinal) {
            Some(table) if table.driver_type == handle.driver_type_id() => Ok(ordinal),
            _ => Err(handle.id()),
        }
    }

    /// The name of table `ordinal` (a valid ordinal).
    pub(crate) fn table_name(&self, ordinal: usize) -> &'static str {
        self.tables.get(ordinal).map_or("?", |table| table.name)
    }

    /// The ordinal of the table named `name`, if registered.
    pub(crate) fn table_ordinal_by_name(&self, name: &str) -> Option<usize> {
        self.tables.iter().position(|table| table.name == name)
    }

    /// The table `ordinal`'s registry, typed — created on first use. `None` when the
    /// table's registry was created for another registry type (or the ordinal names
    /// no table).
    pub(crate) fn registry_mut<R: TableRegistry + Default>(&mut self, ordinal: usize) -> Option<&mut R> {
        let table = self.tables.get_mut(ordinal)?;
        table
            .registry
            .get_or_insert_with(|| Box::new(R::default()) as Box<dyn TableRegistry>)
            .as_any_mut()
            .downcast_mut::<R>()
    }

    /// Record that the resolver answer for `identifier` in table `ordinal` was
    /// memoized during the push in progress (forgotten again if the push fails).
    pub(super) fn record_memo(&mut self, ordinal: usize, identifier: &str) {
        self.memo_journal.push((ordinal, String::from(identifier)));
    }

    // --- user data ----------------------------------------------------------------------

    /// Sets the caller's user data of type `T`: any value, one per type.
    ///
    /// Setting a value of a type already set replaces that value and leaves the values of
    /// other types in place. Values are keyed by type, so the crate's environment value
    /// and a framework's own coexist in one session.
    ///
    /// This is what serialization and deserialization calls see through their context's
    /// `user_data::<T>()` ([`SerializeContext::user_data`],
    /// [`DeserializeContext::user_data`]). It is above all the *reading environment* —
    /// the live objects that serialized data refers to by identity, such as the crate's
    /// own [`KnownProviders`](crate::serialize::KnownProviders) — but an implementation
    /// may store anything it needs there.
    pub fn set_user_data<T: Any + Send + Sync>(&mut self, data: T) {
        self.user_data.insert(TypeId::of::<T>(), Box::new(data));
    }

    /// Returns the caller's user data of type `T`, if a value of that type was set
    /// ([`set_user_data`](SerdeSession::set_user_data)).
    pub fn user_data<T: Any>(&self) -> Option<&T> {
        self.user_data.get(&TypeId::of::<T>())?.downcast_ref::<T>()
    }

    // --- writing ------------------------------------------------------------------------

    /// Interns `object` into the table `table`, returning its typed position.
    ///
    /// This is the top-level entry point of the write side;
    /// [`SerializeContext::intern`] is the same operation from inside a serialization
    /// call.
    ///
    /// An object already interned in the table — the same `Arc`, by pointer identity —
    /// yields its existing position without being serialized again. A new object is
    /// serialized by the table's driver, which may intern the objects it refers to,
    /// recursively; it is then appended to the table after the objects it interned, so
    /// every reference points to an earlier position.
    ///
    /// Objects interned by the nested interning of a call that then fails stay interned.
    ///
    /// # Errors
    ///
    /// The handle is not one of this session's ([`SerializeError::UnknownTable`]);
    /// the driver's failure, wrapped in [`SerializeError::InTable`]; the object refers
    /// back to itself ([`SerializeError::ReferenceCycle`]); the nesting of interning
    /// calls exceeds the descent limit ([`SerializeError::DescentLimitExceeded`]);
    /// the entry the driver produced for a homogeneous table has an identifier
    /// other than the table's ([`SerializeError::UnexpectedIdentifier`]); the entry
    /// nests too deep for a segment
    /// ([`SerialValueError::NestingTooDeep`](crate::serialize::SerialValueError::NestingTooDeep)
    /// in [`SerializeError::Value`], wrapped in `InTable`; see
    /// [`SerialValue::MAX_NESTING_DEPTH`] — the object is not interned then); the
    /// table is full ([`SerializeError::TableFull`]).
    pub fn intern<D: ObjectSerdeDriver<L>>(
        &mut self,
        table: TableHandle<D>,
        object: &Arc<D::Object>,
    ) -> Result<D::Index, SerializeError> {
        let mut guard = StdDescentGuard::init(&self.descent_guard_init);
        self.intern_with_guard(&mut guard, table, object)
    }

    /// [`intern`](SerdeSession::intern) within a run whose guard is `guard`.
    pub(super) fn intern_with_guard<D: ObjectSerdeDriver<L>>(
        &mut self,
        guard: &mut StdDescentGuard,
        table: TableHandle<D>,
        object: &Arc<D::Object>,
    ) -> Result<D::Index, SerializeError> {
        let ordinal = self.table_index(table).map_err(|table| SerializeError::UnknownTable { table })?;
        let table_id = TableId::new(ordinal as u32);
        let name = self.tables[ordinal].name;
        let pointer = address(object);
        if let Some(&position) = self.tables[ordinal].by_pointer.get(&pointer) {
            return Ok(D::Index::from_parts(table_id, position));
        }
        if self.write_stack.iter().any(|&(t, p)| t == ordinal && p == pointer) {
            // The innermost in-progress object is the one whose serialization interned
            // this one again.
            let referrer = self.write_stack.last().map_or(name, |&(t, _)| self.tables[t].name);
            return Err(SerializeError::ReferenceCycle { table: name, referrer });
        }
        // The descent: the driver call, with the guard's permission. Warnings have no
        // observer here.
        if let Err(refusal) = guard.try_enter() {
            return Err(SerializeError::DescentLimitExceeded { detail: refusal.detail });
        }
        self.write_stack.push((ordinal, pointer));
        let result = match self.driver::<D>(ordinal) {
            Some(driver) => {
                let mut cx = SerializeContext::new(self, guard);
                driver.serialize_object(object, &mut cx)
            }
            None => Err(SerializeError::UnknownTable { table: table_id }),
        };
        self.write_stack.pop();
        guard.exit();
        let entry = result.map_err(|error| error.in_table(name))?;

        // Post-order: the position is assigned after the objects this one interned.
        let state = &mut self.tables[ordinal];
        let wire = match state.homogeneous {
            Some(expected) => {
                if entry.identifier != expected {
                    return Err(SerializeError::UnexpectedIdentifier {
                        table: name,
                        expected,
                        found: String::from(&*entry.identifier),
                    });
                }
                entry.data
            }
            None => WireEntry { identifier: entry.identifier, data: entry.data }.to_serial_value()?,
        };
        // The nesting bound: an entry whose stored form nests too deep for a segment
        // is refused here, where the culprit is known, instead of being emitted into a
        // segment no reader accepts.
        check_entry_nesting(&wire).map_err(|error| SerializeError::from(error).in_table(name))?;
        let position = u32::try_from(state.slots.len()).map_err(|_| SerializeError::TableFull { table: name })?;
        if position == u32::MAX {
            return Err(SerializeError::TableFull { table: name });
        }
        state.slots.push(Slot::Materialized(Box::new(object.clone())));
        state.by_pointer.insert(pointer, position);
        state.outbox.push(wire);
        Ok(D::Index::from_parts(table_id, position))
    }

    /// The driver of table `ordinal` as `Arc<D>` (a clone, so the session is free
    /// while the driver runs); `None` if the table's driver is not a `D`.
    fn driver<D: ObjectSerdeDriver<L>>(&self, ordinal: usize) -> Option<Arc<D>> {
        Arc::clone(&self.tables.get(ordinal)?.driver).downcast::<D>().ok()
    }

    /// Emits a segment: every entry interned into any table since the previous emission
    /// (or since the session was created), and nothing older.
    ///
    /// Entries absorbed with [`push_segment`](SerdeSession::push_segment) are never
    /// re-emitted. Every registered table appears in the segment, in registration order,
    /// with the position its entries start at — so that a reading session can check that
    /// the segment continues the stream — and with no entries when nothing new was
    /// interned into it.
    ///
    /// The segment's version is [`Segment::VERSION`]; its metadata records the session's
    /// profile when one is declared ([`set_profile`](SerdeSession::set_profile)); it
    /// names no main entry (see
    /// [`take_segment_with_main`](SerdeSession::take_segment_with_main)).
    ///
    /// The output is deterministic: entries in position order, tables in registration
    /// order. Two sessions that intern the same objects in the same order emit equal
    /// segments.
    pub fn take_segment(&mut self) -> Segment {
        self.emit_segment(None)
    }

    /// Emits a segment as [`take_segment`](SerdeSession::take_segment) does, naming
    /// `main` as its main entry.
    ///
    /// The main entry is the position of the one entry the segment is about — the parse
    /// result of this line in a stream of parse results, say — so that a reader finds it
    /// without knowing the layout of the tables.
    /// [`push_segment`](SerdeSession::push_segment) returns it translated into the
    /// reading session's numbering; [`Segment::main`] reports it as this session numbers
    /// it.
    ///
    /// `main` is a typed position this session minted (an
    /// [`intern`](SerdeSession::intern) result, of this segment or of an earlier one of
    /// the same stream); the entry must exist in the session.
    ///
    /// # Errors
    ///
    /// The position's table is not one of this session's
    /// ([`SerializeError::UnknownTable`]) or the position lies beyond the table's
    /// end ([`SerializeError::IndexOutOfRange`]); nothing is emitted then, and the
    /// pending entries stay pending for the next emission.
    pub fn take_segment_with_main(&mut self, main: impl SerialIndex) -> Result<Segment, SerializeError> {
        let table = self
            .tables
            .get(main.table().ordinal() as usize)
            .ok_or(SerializeError::UnknownTable { table: main.table() })?;
        let len = table.slots.len() as u32;
        if main.index() >= len {
            return Err(SerializeError::IndexOutOfRange { table: table.name, index: main.index(), len });
        }
        Ok(self.emit_segment(Some((main.table(), main.index()))))
    }

    /// The body of [`take_segment`](SerdeSession::take_segment) and
    /// [`take_segment_with_main`](SerdeSession::take_segment_with_main): drain every
    /// outbox into a segment naming `main`.
    fn emit_segment(&mut self, main: Option<(TableId, u32)>) -> Segment {
        let tables = self
            .tables
            .iter_mut()
            .enumerate()
            .map(|(ordinal, table)| {
                let entries = core::mem::take(&mut table.outbox);
                // Invariant: the outbox is the tail of the slots (every interned entry
                // pushes both), so the entries start where the slots minus the outbox
                // end; slot counts stay below `u32::MAX` (the table-full checks).
                debug_assert!(entries.len() <= table.slots.len(), "the outbox is the tail of the slots");
                let start = table.slots.len().saturating_sub(entries.len()) as u32;
                SegmentTable::new(String::from(table.name), TableId::new(ordinal as u32), start, entries)
            })
            .collect();
        Segment::new(Segment::VERSION, SegmentMeta::new(self.profile.clone()), tables, main)
    }

    // --- reading ------------------------------------------------------------------------

    /// Absorbs a segment: appends its entries to the session's tables and rebuilds every
    /// object, so that they can be read back ([`object`](SerdeSession::object)) and
    /// interned again (an absorbed object interned into its table yields its existing
    /// position, and is not written out again).
    ///
    /// The segment is validated as untrusted input before anything is rebuilt. Its
    /// version must be [`Segment::VERSION`]. When this session declares a profile
    /// ([`set_profile`](SerdeSession::set_profile)), the segment's must be the same; a
    /// session without one accepts any. Each of the segment's tables is matched to a
    /// table of this session *by name*, since registration order may differ between
    /// writer and reader, and its entries must start exactly where the session's table
    /// ends — the segments of a stream are pushed in order, each once. Every table
    /// reference inside the entries is then translated from the writer's table numbering
    /// to this session's, through the segment's table directory.
    ///
    /// The session must have no entries pending emission — nothing interned since the
    /// last [`take_segment`](SerdeSession::take_segment) — because a segment continues
    /// the stream the session has emitted so far.
    ///
    /// Every new entry is then rebuilt by its table's driver, table by table in
    /// registration order and entry by entry in position order; an entry referred to
    /// before its turn is rebuilt on demand.
    ///
    /// Returns the segment's main entry ([`Segment::main`]), if it names one, translated
    /// into this session's numbering: the table's id in this session and the position,
    /// validated to exist once the segment is absorbed, as a `(TableId, u32)` pair. The
    /// typed position is `handle.position(index)` for the handle whose
    /// [`id`](TableHandle::id) is that table (see [`TableHandle::position`]). `None` for
    /// a segment naming no main entry.
    ///
    /// **The segments pushed into one session must all come from one stream, in order**
    /// — the caller's obligation. The session checks that each segment continues its
    /// tables (the start positions), which catches a skipped or repeated segment; it
    /// cannot recognize a segment of another stream whose positions happen to line up,
    /// and would absorb it as a continuation. A declared profile narrows this to streams
    /// of the same profile.
    ///
    /// On any error the session is left exactly as it was before the call: the segment's
    /// entries are dropped, the session stays usable, and the error names what failed.
    ///
    /// # Errors
    ///
    /// [`DeserializeError::UnsupportedVersion`],
    /// [`ProfileMismatch`](DeserializeError::ProfileMismatch),
    /// [`UnknownTableName`](DeserializeError::UnknownTableName),
    /// [`DuplicateSegmentTable`](DeserializeError::DuplicateSegmentTable),
    /// [`SegmentOutOfOrder`](DeserializeError::SegmentOutOfOrder),
    /// [`UnemittedEntries`](DeserializeError::UnemittedEntries),
    /// [`TableFull`](DeserializeError::TableFull), and
    /// [`UnknownWriterTable`](DeserializeError::UnknownWriterTable) for a segment that
    /// does not fit the session (the last two also for a main entry naming a table
    /// the directory does not list, or a position beyond the table's end after the
    /// push: [`IndexOutOfRange`](DeserializeError::IndexOutOfRange)). An entry nesting
    /// too deep for a segment is
    /// [`SerialValueError::NestingTooDeep`](crate::serialize::SerialValueError::NestingTooDeep)
    /// in [`Value`](DeserializeError::Value), wrapped in
    /// [`InEntry`](DeserializeError::InEntry) — checked without recursion before any
    /// entry is walked; see [`SerialValue::MAX_NESTING_DEPTH`].
    ///
    /// Then, from rebuilding the entries: a driver's failure — or a heterogeneous
    /// table's entry
    /// that is not the identifier-and-data map ([`Value`](DeserializeError::Value)) —
    /// wrapped in [`InEntry`](DeserializeError::InEntry), a reference cycle
    /// ([`ReferenceCycle`](DeserializeError::ReferenceCycle)), a reference beyond a
    /// table's end ([`IndexOutOfRange`](DeserializeError::IndexOutOfRange)) or into
    /// the wrong table ([`WrongTable`](DeserializeError::WrongTable)), or the descent
    /// limit ([`DescentLimitExceeded`](DeserializeError::DescentLimitExceeded)); and
    /// [`Internal`](DeserializeError::Internal) should the session's own check after
    /// rebuilding — every new entry holds its object — fail (a bug of this crate).
    pub fn push_segment(&mut self, segment: Segment) -> Result<Option<(TableId, u32)>, DeserializeError> {
        let (version, meta, tables, main) = segment.into_parts();
        if version != Segment::VERSION {
            return Err(DeserializeError::UnsupportedVersion { found: version, expected: Segment::VERSION });
        }
        if let Some(expected) = &self.profile {
            if meta.profile() != Some(expected.as_str()) {
                return Err(DeserializeError::ProfileMismatch {
                    expected: expected.clone(),
                    found: meta.profile().map(String::from),
                });
            }
        }

        // A segment continues the stream the session has emitted so far: nothing
        // interned since the last emission may still be pending (absorb every segment
        // first, then append and emit — the read-then-append flow).
        if let Some(table) = self.tables.iter().find(|table| !table.outbox.is_empty()) {
            return Err(DeserializeError::UnemittedEntries { table: table.name });
        }

        // Validate the table directory against this session, and plan the appends,
        // before touching any state.
        let mut writer_to_reader: HashMap<u32, usize> = HashMap::new();
        let mut planned: Vec<(usize, Vec<SerialValue>)> = Vec::with_capacity(tables.len());
        for segment_table in tables {
            let (name, id, start, entries) = segment_table.into_parts();
            let ordinal = self
                .tables
                .iter()
                .position(|table| table.name == name)
                .ok_or_else(|| DeserializeError::UnknownTableName { name: name.clone() })?;
            if planned.iter().any(|(t, _)| *t == ordinal) {
                return Err(DeserializeError::DuplicateSegmentTable { name });
            }
            if writer_to_reader.insert(id.ordinal(), ordinal).is_some() {
                return Err(DeserializeError::DuplicateSegmentTable { name });
            }
            let table = &self.tables[ordinal];
            let len = table.slots.len() as u32;
            if start != len {
                return Err(DeserializeError::SegmentOutOfOrder { table: table.name, expected: len, found: start });
            }
            let fits = u32::try_from(entries.len()).ok().and_then(|n| len.checked_add(n));
            match fits {
                Some(end) if end < u32::MAX => {}
                _ => return Err(DeserializeError::TableFull { table: table.name }),
            }
            // The nesting bound, checked without recursion before any entry is walked
            // (translated, parsed, or handed to a driver): every entry of this
            // segment must fit a segment's serialized form. For a segment obtained
            // from the wire this is defense in depth — `Segment::from_serial_value`
            // and the serde `Deserialize` impl already bound the whole value, which
            // implies the per-entry bound — but a `Segment` built in memory reaches
            // here unchecked.
            for (offset, entry) in entries.iter().enumerate() {
                if let Err(error) = check_entry_nesting(entry) {
                    // `offset < entries.len()`, which fits `u32` (checked above).
                    let position = len.saturating_add(u32::try_from(offset).unwrap_or(u32::MAX));
                    return Err(DeserializeError::from(error).in_entry(table.name, position, None));
                }
            }
            planned.push((ordinal, entries));
        }

        // Translate every table reference into this session's numbering.
        for (_, entries) in &mut planned {
            for entry in entries.iter_mut() {
                translate_indices(entry, &writer_to_reader)?;
            }
        }

        // The main entry, translated and checked against the lengths after the push
        // (its table's planned entries included) — before anything is touched.
        let main = match main {
            None => None,
            Some((table, index)) => {
                let ordinal = *writer_to_reader
                    .get(&table.ordinal())
                    .ok_or(DeserializeError::UnknownWriterTable { table })?;
                let appended = planned.iter().find(|(t, _)| *t == ordinal).map_or(0, |(_, entries)| entries.len());
                // The table-full check above bounds `len + appended` below `u32::MAX`.
                let len = (self.tables[ordinal].slots.len() + appended) as u32;
                if index >= len {
                    return Err(DeserializeError::IndexOutOfRange { table: self.tables[ordinal].name, index, len });
                }
                Some((TableId::new(ordinal as u32), index))
            }
        };

        // Append as pending, remembering the old lengths for the rollback.
        let old_lens: Vec<usize> = self.tables.iter().map(|table| table.slots.len()).collect();
        for (ordinal, entries) in planned {
            self.tables[ordinal].slots.extend(entries.into_iter().map(Slot::Pending));
        }

        // Rebuild every new entry, eagerly and in order.
        self.memo_journal.clear();
        let mut guard = StdDescentGuard::init(&self.descent_guard_init);
        let result = self.materialize_new_entries(&mut guard, &old_lens);
        let memoized = core::mem::take(&mut self.memo_journal);
        if result.is_err() {
            for (table, &old_len) in self.tables.iter_mut().zip(&old_lens) {
                table.slots.truncate(old_len);
                let old_len = old_len as u32;
                table.by_pointer.retain(|_, position| *position < old_len);
            }
            // The resolver answers recorded during the push are part of what it did.
            for (ordinal, identifier) in memoized {
                if let Some(registry) = self.tables.get_mut(ordinal).and_then(|table| table.registry.as_mut()) {
                    registry.forget_memo(&identifier);
                }
            }
        }
        result.map(|()| main)
    }

    /// Rebuild every entry beyond `old_lens`, table by table, position by position.
    /// Returns `Ok` only when every new entry is rebuilt: an entry whose rebuilding
    /// failed is left pending (see [`materialize_entered`]), so a failure swallowed by
    /// the driver of an entry that referred to it — a driver treating a reference as
    /// optional — is met again here, in the entry's own turn, and fails the push.
    fn materialize_new_entries(
        &mut self,
        guard: &mut StdDescentGuard,
        old_lens: &[usize],
    ) -> Result<(), DeserializeError> {
        for (ordinal, &old_len) in old_lens.iter().enumerate() {
            let mut position = old_len;
            while position < self.tables[ordinal].slots.len() {
                if let Slot::Pending(_) = self.tables[ordinal].slots[position] {
                    let materialize = self.tables[ordinal].materialize;
                    materialize(self, guard, ordinal, position as u32, None)?;
                }
                position += 1;
            }
        }
        // Defense in depth: after the pass, every new slot holds its object (a
        // rebuilding that failed has returned the error above; none is still in
        // progress once every call has returned). A slot found otherwise is a bug of
        // this crate, reported rather than left to misreport later.
        for (ordinal, &old_len) in old_lens.iter().enumerate() {
            let table = &self.tables[ordinal];
            if let Some(offset) = table.slots[old_len..].iter().position(|slot| !slot.is_materialized()) {
                return Err(DeserializeError::Internal {
                    detail: alloc::format!(
                        "entry #{} of table `{}` was left unrebuilt after the segment's entries were processed",
                        old_len.saturating_add(offset),
                        table.name
                    ),
                });
            }
        }
        Ok(())
    }

    /// Returns the object stored at position `index` of table `table`.
    ///
    /// This is the top-level entry point of the read side;
    /// [`DeserializeContext::object`] is the same operation from inside a
    /// deserialization call. Every entry of an absorbed segment is rebuilt when the
    /// segment is pushed, so this call is a lookup, and the same position always yields
    /// the same `Arc`.
    ///
    /// The position must be one of this session's own: a typed position holds the
    /// [`TableId`] of the session that minted it (see [`SerialIndex`]), so a position
    /// minted by another session — a writing session whose registration order differs —
    /// names the wrong table here. Between sessions a position travels as its table's
    /// name and its bare `u32` index ([`SerialIndex::index`]), and is rebuilt on this
    /// side with [`TableHandle::position`].
    ///
    /// # Errors
    ///
    /// The handle is not one of this session's ([`DeserializeError::UnknownTable`]);
    /// the position belongs to another table ([`DeserializeError::WrongTable`]) or
    /// lies beyond the table's end ([`DeserializeError::IndexOutOfRange`]).
    pub fn object<D: ObjectSerdeDriver<L>>(
        &mut self,
        table: TableHandle<D>,
        index: D::Index,
    ) -> Result<Arc<D::Object>, DeserializeError> {
        let mut guard = StdDescentGuard::init(&self.descent_guard_init);
        self.object_with_guard(&mut guard, table, index, None)
    }

    /// [`object`](SerdeSession::object) within a run whose guard is `guard`, from
    /// the entry `referrer` (the entry being deserialized), if any.
    pub(super) fn object_with_guard<D: ObjectSerdeDriver<L>>(
        &mut self,
        guard: &mut StdDescentGuard,
        table: TableHandle<D>,
        index: D::Index,
        referrer: Option<(usize, u32)>,
    ) -> Result<Arc<D::Object>, DeserializeError> {
        let ordinal = self.table_index(table).map_err(|table| DeserializeError::UnknownTable { table })?;
        let name = self.tables[ordinal].name;
        if index.table() != table.id() {
            return Err(DeserializeError::WrongTable { expected: name, found: index.table() });
        }
        let position = index.index();
        let len = self.tables[ordinal].slots.len() as u32;
        if position >= len {
            return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len });
        }
        materialize::<L, D>(self, guard, ordinal, position, referrer)
    }

    /// The number of entries of table `ordinal` (crate-internal, for tests).
    #[cfg(test)]
    pub(super) fn table_len(&self, ordinal: usize) -> usize {
        self.tables[ordinal].slots.len()
    }
}

/// Rebuild the entry at `position` of table `ordinal` (whose driver is `D`) if it is
/// pending, and return its object; `referrer` is the entry whose deserialization
/// asked for it, for the cycle error.
fn materialize<L: SerializableLang, D: ObjectSerdeDriver<L>>(
    session: &mut SerdeSession<L>,
    guard: &mut StdDescentGuard,
    ordinal: usize,
    position: u32,
    referrer: Option<(usize, u32)>,
) -> Result<Arc<D::Object>, DeserializeError> {
    let name = session.tables[ordinal].name;
    let table_id = TableId::new(ordinal as u32);
    match session.tables[ordinal].slots.get(position as usize) {
        Some(Slot::Materialized(object)) => {
            return object
                .downcast_ref::<Arc<D::Object>>()
                .cloned()
                .ok_or(DeserializeError::UnknownTable { table: table_id });
        }
        Some(Slot::InProgress) => {
            let (referrer_table, referrer_index) = referrer.unwrap_or((ordinal, position));
            return Err(DeserializeError::ReferenceCycle {
                table: name,
                index: position,
                referrer_table: session.table_name(referrer_table),
                referrer_index,
            });
        }
        Some(Slot::Pending(_)) => {}
        None => {
            let len = session.tables[ordinal].slots.len() as u32;
            return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len });
        }
    }
    // The descent: the driver call, with the guard's permission. Warnings have no
    // observer here.
    if let Err(refusal) = guard.try_enter() {
        return Err(DeserializeError::DescentLimitExceeded { detail: refusal.detail });
    }
    let result = materialize_entered::<L, D>(session, guard, ordinal, position);
    guard.exit();
    result
}

/// The granted-descent body of [`materialize`]: take the pending value out, rebuild,
/// store. On any failure the slot is put back as pending, with its stored value: a
/// failed rebuilding leaves no trace (the slot is neither poisoned as in-progress —
/// which would misreport as a cycle later — nor emptied), so that a later attempt
/// meets the entry again exactly as it was.
fn materialize_entered<L: SerializableLang, D: ObjectSerdeDriver<L>>(
    session: &mut SerdeSession<L>,
    guard: &mut StdDescentGuard,
    ordinal: usize,
    position: u32,
) -> Result<Arc<D::Object>, DeserializeError> {
    let name = session.tables[ordinal].name;
    let table_id = TableId::new(ordinal as u32);
    let slot = &mut session.tables[ordinal].slots[position as usize];
    let value = match core::mem::replace(slot, Slot::InProgress) {
        Slot::Pending(value) => value,
        // Checked by the caller; restore and report rather than assume.
        other => {
            *slot = other;
            return Err(DeserializeError::IndexOutOfRange { table: name, index: position, len: 0 });
        }
    };
    // The entry handed to the driver, and — for a heterogeneous table, whose stored
    // form the entry is parsed out of — the stored value itself, kept to restore.
    let (entry, stored) = match session.tables[ordinal].homogeneous {
        Some(identifier) => (SerialEntry { identifier: Cow::Borrowed(identifier), data: value }, None),
        None => match WireEntry::from_serial_value(&value) {
            Ok(wire) => (SerialEntry { identifier: wire.identifier, data: wire.data }, Some(value)),
            Err(error) => {
                session.tables[ordinal].slots[position as usize] = Slot::Pending(value);
                return Err(DeserializeError::from(error).in_entry(name, position, None));
            }
        },
    };
    let Some(driver) = session.driver::<D>(ordinal) else {
        let SerialEntry { data, .. } = entry;
        session.tables[ordinal].slots[position as usize] = Slot::Pending(stored.unwrap_or(data));
        return Err(DeserializeError::UnknownTable { table: table_id });
    };
    let result = {
        let mut cx = DeserializeContext::new(session, guard, Some((ordinal, position)));
        driver.deserialize_object(&entry, &mut cx)
    };
    match result {
        Ok(object) => {
            let table = &mut session.tables[ordinal];
            table.slots[position as usize] = Slot::Materialized(Box::new(object.clone()));
            table.by_pointer.entry(address(&object)).or_insert(position);
            Ok(object)
        }
        Err(error) => {
            let SerialEntry { identifier, data } = entry;
            session.tables[ordinal].slots[position as usize] = Slot::Pending(stored.unwrap_or(data));
            Err(error.in_entry(name, position, Some(identifier)))
        }
    }
}

/// [`materialize`] as the erased routine stored per table.
fn materialize_erased<L: SerializableLang, D: ObjectSerdeDriver<L>>(
    session: &mut SerdeSession<L>,
    guard: &mut StdDescentGuard,
    ordinal: usize,
    position: u32,
    referrer: Option<(usize, u32)>,
) -> Result<(), DeserializeError> {
    materialize::<L, D>(session, guard, ordinal, position, referrer).map(|_| ())
}

/// Rewrite every `Index` inside `value` from the writer's table numbering to the
/// reader's, through `writer_to_reader`. Iterative, so a deeply nested value cannot
/// exhaust the stack.
fn translate_indices(
    value: &mut SerialValue,
    writer_to_reader: &HashMap<u32, usize>,
) -> Result<(), DeserializeError> {
    let mut pending: Vec<&mut SerialValue> = Vec::from([value]);
    while let Some(value) = pending.pop() {
        match value {
            SerialValue::Index { table, .. } => {
                let reader = writer_to_reader
                    .get(&table.ordinal())
                    .ok_or(DeserializeError::UnknownWriterTable { table: *table })?;
                *table = TableId::new(*reader as u32);
            }
            SerialValue::List(items) => pending.extend(items.iter_mut()),
            SerialValue::Map(entries) => pending.extend(entries.iter_mut().map(|(_, value)| value)),
            SerialValue::Null
            | SerialValue::Bool(_)
            | SerialValue::Int(_)
            | SerialValue::Str(_)
            | SerialValue::Bytes(_) => {}
        }
    }
    Ok(())
}

impl<L: SerializableLang> fmt::Debug for SerdeSession<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Tables<'a, L: SerializableLang>(&'a [TableState<L>]);
        impl<L: SerializableLang> fmt::Debug for Tables<'_, L> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                let mut list = f.debug_list();
                for table in self.0 {
                    list.entry(&format_args!(
                        "{}: {} entries ({} pending emission)",
                        table.name,
                        table.slots.len(),
                        table.outbox.len()
                    ));
                }
                list.finish()
            }
        }
        f.debug_struct("SerdeSession")
            .field("tables", &Tables(&self.tables))
            .field("user_data", &format_args!("{} value(s)", self.user_data.len()))
            .field("descent_guard_init", &self.descent_guard_init)
            .finish()
    }
}