techy 0.2.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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! The trees table: [`TreeSerdeDriver`], its driver, and [`TreeIndex`], its position
//! type.
//!
//! [`TableHandle::register_annotation`] registers a tree annotation type,
//! [`TreeSerialization`] holds the by-kind methods (`serialize_tree` and `tree`), and
//! the value conversions of the core payload types a language's own conversions reuse
//! are defined here too ([`TextContent`] — owned text only — [`SlotRole`] and
//! [`GroupRule`]).
//!
//! A node tree is rebuilt through the node builder. The reader stages the nodes in
//! reverse storage order, so that a node's children exist before it; re-resolves each
//! callable's argument and slot regions from the builder-ready form the wire stores; and
//! calls [`finish`](crate::core::node::NodeTreeBuilder::finish), which mints a fresh
//! layout tag, recomputes the parent table, and re-establishes every region invariant by
//! construction.
//!
//! Everything read is untrusted input: a children range out of bounds, a node no other
//! node claims as a child, a region that does not tile the child list, a content parent
//! outside its region, a span out of bounds, a reference into the wrong table — each is
//! an error naming the node ([`DeserializeError::InNode`]), never a panic.

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

use hashbrown::HashMap;

use crate::node::{
    validate_tree, ArgumentExt, BuildId, CallableData, ChildRegion, CommentData, ContentNodes,
    GroupData, NodeBuildError, NodeExt, NodeKind, NodeTree, NodeTreeBuilder, ParsedArgument,
    ParsedArguments, ParsedSlot, ParsedSlots, SlotExt, SlotRole,
};
use crate::source::TextContent;
use crate::spec::CallableSpec;
use crate::state::{InvocationSyntax, Lang};
use crate::token::GroupRule;

use super::super::engine::{
    DeserializeContext, ObjectSerdeDriver, SerdeSession, SerializeContext, TableHandle, TableRegistry,
};
use super::super::error::{DeserializeError, RegistrationError, SerializeError};
use super::super::object::{DeserializableValue, SerializableLang, SerializableValue};
use super::super::value::{SerialEntry, SerialValue};
use super::super::wire::state::WireGroupRule;
use super::super::wire::tree::{
    WireArgument, WireContent, WireNode, WireNodeKind, WireRange, WireRegion, WireSlot, WireTree,
};
use super::super::wire::{FromSerialValue, ToSerialValue};
use super::source::{deserialize_span, serialize_span};
use super::standard::{StandardTableInterning, StandardTableReading};
use super::{CORE_TREE_IDENTIFIER, TREES_TABLE};

crate::serial_index! {
    /// A position in the trees table — the `Index` type of [`TreeSerdeDriver`]: the
    /// serialized reference to a [`NodeTree`].
    ///
    /// Interning a tree returns a fresh position every time (a tree is a value,
    /// written in full — see [`TreeSerialization::serialize_tree`]).
    pub struct TreeIndex;
}

/// The driver of the trees table (table name `trees`): how a [`NodeTree`] is
/// serialized and rebuilt.
///
/// The trees table is *heterogeneous* by the tree's **annotation type**: a
/// `NodeTree<L, A>` is written under the identifier registered for `A`, and read back
/// through the conversions registered with it.
///
/// The unit annotation (`NodeTree<L>`, the parser's output) is registered by the driver
/// itself, in every session it is registered in, under the identifier `core.tree`, and
/// its annotations are omitted from the wire. Any other annotation type is registered on
/// the table's handle with [`register_annotation`](TableHandle::register_annotation),
/// which serializes each node's annotation through the type's own
/// [`SerializableValue`]/[`DeserializableValue`] conversions — so an annotation that
/// refers to a table object, a [`SourceSpan`](crate::source::SourceSpan) say, interns it
/// like any other value. Serializing a tree whose annotation type is not registered is a
/// [`SerializeError`].
///
/// The table's object type is `dyn Any + Send + Sync`, one table for every annotation
/// type, but the table accepts `NodeTree<L, A>` values only: interning any other object
/// through the general
/// [`SerdeSession::intern`](crate::serialize::SerdeSession::intern) is a
/// [`SerializeError`] naming the object as not a node tree of a registered annotation
/// type. The by-kind methods, typed to node trees, are the [`TreeSerialization`]
/// extension trait's `serialize_tree` and `tree`.
///
/// Registered by [`SerdeSession::new`](crate::serialize::SerdeSession::new); a session
/// composed with [`SerdeSession::empty`](crate::serialize::SerdeSession::empty)
/// registers it with
/// [`SerdeSession::register_table`](crate::serialize::SerdeSession::register_table), and
/// the unit annotation then needs no further registration.
///
/// **Text in language payloads is owned on the wire.** A node's own text payloads
/// (the content of a `Chars` node, a group's delimiters, a comment's parts) may be
/// span-backed ([`TextContent::Spanned`]) on the wire: the reader validates each such
/// byte range against the node's own source before the tree is finished. A callable's
/// invocation syntax and every ext value (a node's, an argument's, a slot's) are
/// language-typed payloads the driver writes and reads through their value
/// conversions, which receive no node — hence no source to validate against. So the
/// writer materializes the invocation syntax against the node's source
/// ([`InvocationSyntax::materialized`]) before converting it, [`TextContent`]'s value
/// conversion writes and reads owned text only, and ext values must not carry spans
/// relative to the node's source (the contract [`NodeTree::materialize`] states — it
/// leaves ext values untouched).
///
/// # Panics
///
/// Serializing a tree does not panic on any tree the parser or the node builder
/// produced, and reading never panics: every wire input is validated.
///
/// The one reachable panic is the crate-wide [`TextContent::resolve`] invariant panic
/// (listed in [Panics](crate::guide::panics)). The writer calls
/// [`InvocationSyntax::materialized`] on each callable node's invocation syntax, so a
/// consumer-built tree that violates the [`TextContent::Spanned`] invariant — a
/// span-backed text of the invocation syntax whose byte range is not a valid range of
/// the node's source — panics there, exactly as [`NodeTree::materialize`] does on such a
/// tree. The write entry points state the condition:
/// [`TreeSerialization::serialize_tree`] and this driver's
/// [`serialize_object`](ObjectSerdeDriver::serialize_object).
pub struct TreeSerdeDriver<L: SerializableLang> {
    lang: core::marker::PhantomData<fn() -> L>,
}

impl<L: SerializableLang> TreeSerdeDriver<L> {
    /// The driver (it has no configuration).
    pub fn new() -> TreeSerdeDriver<L> {
        TreeSerdeDriver { lang: core::marker::PhantomData }
    }
}

impl<L: SerializableLang> Default for TreeSerdeDriver<L> {
    fn default() -> Self {
        TreeSerdeDriver::new()
    }
}

impl<L: SerializableLang> fmt::Debug for TreeSerdeDriver<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TreeSerdeDriver").finish()
    }
}

impl<L: SerializableLang> ObjectSerdeDriver<L> for TreeSerdeDriver<L> {
    type Object = dyn Any + Send + Sync;
    type Index = TreeIndex;

    fn table_name(&self) -> &'static str {
        TREES_TABLE
    }

    fn homogeneous_identifier(&self) -> Option<&'static str> {
        None
    }

    /// Writes the node tree in `object` as an entry of the trees table.
    ///
    /// # Panics
    ///
    /// Each callable node's invocation syntax is materialized against that node's own
    /// source before it is written ([`InvocationSyntax::materialized`]), so this panics
    /// if a range recorded there is not a valid `char`-boundary range of that source.
    /// That is a broken tree invariant, which no parsed input can cause and which
    /// [`validate_tree`](crate::core::node::validate_tree) detects; the panic is
    /// [`TextContent::resolve`](crate::source::TextContent::resolve)'s (see the [list of
    /// panicking items](crate::guide::panics)).
    fn serialize_object(
        &self,
        object: &Arc<dyn Any + Send + Sync>,
        cx: &mut SerializeContext<'_, L>,
    ) -> Result<SerialEntry, SerializeError> {
        let type_id = (**object).type_id();
        let codec = codec_by_type::<L>(cx, type_id)?;
        let data = (codec.serialize)(object, cx)?;
        Ok(SerialEntry { identifier: codec.identifier.clone(), data })
    }

    fn deserialize_object(
        &self,
        entry: &SerialEntry,
        cx: &mut DeserializeContext<'_, L>,
    ) -> Result<Arc<dyn Any + Send + Sync>, DeserializeError> {
        let codec = codec_by_identifier::<L>(cx, &entry.identifier)?;
        (codec.deserialize)(&entry.data, cx)
    }
}

// --- the annotation codecs ------------------------------------------------------------

/// The serialize and deserialize routines for trees of one annotation type, keyed in
/// the trees table's registry by the type and by its identifier.
struct TreeCodec<L: SerializableLang> {
    identifier: Cow<'static, str>,
    serialize: Arc<SerializeTreeFn<L>>,
    deserialize: Arc<DeserializeTreeFn<L>>,
}

type SerializeTreeFn<L> = dyn Fn(&Arc<dyn Any + Send + Sync>, &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
    + Send
    + Sync;
type DeserializeTreeFn<L> = dyn Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<Arc<dyn Any + Send + Sync>, DeserializeError>
    + Send
    + Sync;

impl<L: SerializableLang> Clone for TreeCodec<L> {
    fn clone(&self) -> Self {
        TreeCodec {
            identifier: self.identifier.clone(),
            serialize: Arc::clone(&self.serialize),
            deserialize: Arc::clone(&self.deserialize),
        }
    }
}

/// The trees table's registry: the codecs by annotation type (for writing) and by
/// identifier (for reading). Created on first use with the unit annotation's codec
/// (`core.tree`) registered, so every trees table has it.
struct TreeRegistry<L: SerializableLang> {
    by_type: HashMap<TypeId, TreeCodec<L>>,
    by_identifier: HashMap<String, TreeCodec<L>>,
}

impl<L: SerializableLang> Default for TreeRegistry<L> {
    fn default() -> Self {
        let mut registry = TreeRegistry { by_type: HashMap::new(), by_identifier: HashMap::new() };
        let unit = unit_tree_codec::<L>();
        registry.by_type.insert(TypeId::of::<NodeTree<L, ()>>(), unit.clone());
        registry.by_identifier.insert(unit.identifier.to_string(), unit);
        registry
    }
}

impl<L: SerializableLang> TableRegistry for TreeRegistry<L> {
    fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync) {
        self
    }

    fn forget_memo(&mut self, _identifier: &str) {
        // The trees table memoizes nothing.
    }
}

/// The codec for the annotation type of the tree stored in `object`, in the session
/// `cx` belongs to. Cloned out so the session is free while it runs.
fn codec_by_type<L: SerializableLang>(
    cx: &mut SerializeContext<'_, L>,
    type_id: TypeId,
) -> Result<TreeCodec<L>, SerializeError> {
    let ordinal = cx
        .session_mut()
        .table_ordinal_by_name(TREES_TABLE)
        .ok_or_else(|| SerializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
    let registry = cx
        .session_mut()
        .registry_mut::<TreeRegistry<L>>(ordinal)
        .ok_or_else(|| {
            SerializeError::failed(alloc::format!(
                "Misconfigured table ‘{TREES_TABLE}’: the table is not registered with the tree driver"
            ))
        })?;
    registry.by_type.get(&type_id).cloned().ok_or_else(|| {
        SerializeError::failed(alloc::format!(
            "Unsupported object for table ‘{TREES_TABLE}’: the table accepts only node trees \
             of an annotation type registered with ‘TableHandle::register_annotation’"
        ))
    })
}

/// The codec for `identifier` in the trees table of the session `cx` belongs to.
fn codec_by_identifier<L: SerializableLang>(
    cx: &mut DeserializeContext<'_, L>,
    identifier: &str,
) -> Result<TreeCodec<L>, DeserializeError> {
    let ordinal = cx.session_mut().table_ordinal_by_name(TREES_TABLE).ok_or_else(|| {
        DeserializeError::failed(alloc::format!(
            "Missing table ‘{TREES_TABLE}’: no table of this name is registered in the \
             session of the context"
        ))
    })?;
    let registry = cx
        .session_mut()
        .registry_mut::<TreeRegistry<L>>(ordinal)
        .ok_or_else(|| {
            DeserializeError::failed(alloc::format!(
                "Misconfigured table ‘{TREES_TABLE}’: the table is not registered with the tree driver"
            ))
        })?;
    registry.by_identifier.get(identifier).cloned().ok_or_else(|| DeserializeError::UnknownIdentifier {
        table: TREES_TABLE,
        identifier: identifier.to_string(),
    })
}

/// The codec of the unit annotation (`core.tree`): the annotations are omitted from
/// the wire and rebuilt as one `()` per node.
fn unit_tree_codec<L: SerializableLang>() -> TreeCodec<L> {
    TreeCodec {
        identifier: Cow::Borrowed(CORE_TREE_IDENTIFIER),
        serialize: Arc::new(|object, cx| {
            let tree = downcast_tree::<L, ()>(object)?;
            let nodes = serialize_nodes(tree, cx)?;
            Ok(WireTree { nodes, annotations: None }.to_serial_value()?)
        }),
        deserialize: Arc::new(|data, cx| {
            let wire = WireTree::from_serial_value(data)?;
            let annotations = alloc::vec![(); wire.nodes.len()];
            let tree = rebuild_tree::<L, ()>(wire.nodes, annotations, cx)?;
            Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
        }),
    }
}

/// The codec of an annotation type `A`: each node's annotation is serialized through
/// `A`'s own value conversion, one wire value per node.
fn value_tree_codec<L, A>(identifier: Cow<'static, str>) -> TreeCodec<L>
where
    L: SerializableLang,
    A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
{
    TreeCodec {
        identifier,
        serialize: Arc::new(|object, cx| {
            let tree = downcast_tree::<L, A>(object)?;
            let nodes = serialize_nodes(tree, cx)?;
            let annotations = serialize_annotations(tree, |annotation, cx| annotation.serialize_value(cx), cx)?;
            Ok(WireTree { nodes, annotations: Some(annotations) }.to_serial_value()?)
        }),
        deserialize: Arc::new(|data, cx| {
            let wire = WireTree::from_serial_value(data)?;
            let (nodes, annotations) = deserialize_annotations(
                wire,
                |value, cx| <A as DeserializableValue<L>>::deserialize_value(value, cx),
                cx,
            )?;
            let tree = rebuild_tree::<L, A>(nodes, annotations, cx)?;
            Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
        }),
    }
}

/// The annotations of `tree`, one wire value per node through `serialize`; a failure
/// is wrapped in [`SerializeError::InNode`] with the node's position.
fn serialize_annotations<L: SerializableLang, A>(
    tree: &NodeTree<L, A>,
    serialize: impl Fn(&A, &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>,
    cx: &mut SerializeContext<'_, L>,
) -> Result<Vec<SerialValue>, SerializeError> {
    tree.annotations()
        .iter()
        .zip(tree.nodes())
        .enumerate()
        .map(|(index, (annotation, node))| {
            serialize(annotation, cx).map_err(|error| error.in_node(index as u32, callable_name(&node.kind)))
        })
        .collect()
}

/// The annotations of a wire tree of a non-unit annotation type — required, one per
/// node — read through `deserialize`, and the wire nodes; a failure at an annotation is
/// wrapped in [`DeserializeError::InNode`] with the node's position.
fn deserialize_annotations<L: SerializableLang, A>(
    mut wire: WireTree,
    deserialize: impl Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<A, DeserializeError>,
    cx: &mut DeserializeContext<'_, L>,
) -> Result<(Vec<WireNode>, Vec<A>), DeserializeError> {
    let node_count = wire.nodes.len();
    let list = wire.annotations.take().ok_or_else(|| {
        DeserializeError::failed(
            "Missing annotations in a tree entry (only trees with the unit annotation type have no \
             annotations)",
        )
    })?;
    if list.len() != node_count {
        return Err(DeserializeError::failed(alloc::format!(
            "Wrong number of annotations in a tree entry ({} annotations for {node_count} nodes)",
            list.len()
        )));
    }
    let annotations = list
        .iter()
        .zip(&wire.nodes)
        .enumerate()
        .map(|(index, (value, node))| {
            deserialize(value, cx).map_err(|error| error.in_node(index as u32, wire_callable_name(node)))
        })
        .collect::<Result<Vec<A>, _>>()?;
    Ok((wire.nodes, annotations))
}

/// The `NodeTree<L, A>` behind an erased tree object, or a serialize error (never
/// reached in practice: the codec is chosen by the object's own type).
fn downcast_tree<L: SerializableLang, A: 'static>(
    object: &Arc<dyn Any + Send + Sync>,
) -> Result<&NodeTree<L, A>, SerializeError> {
    (**object)
        .downcast_ref::<NodeTree<L, A>>()
        .ok_or_else(|| {
            SerializeError::failed(
                "Annotation type mismatch: the tree codec was called on a tree of another \
                 annotation type",
            )
        })
}

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

impl<L: SerializableLang> TableHandle<TreeSerdeDriver<L>> {
    /// Registers tree annotation type `A` under `identifier` in this trees table of
    /// `session`.
    ///
    /// `NodeTree<L, A>` values are then serialized and read back through `A`'s own
    /// [`SerializableValue`] / [`DeserializableValue`] conversions, one wire value per
    /// node. The unit annotation (`NodeTree<L>`) is pre-registered under `core.tree` and
    /// needs no registration.
    ///
    /// An annotation value must not hold spans relative to a node's source, because the
    /// conversion runs without access to any node. A
    /// [`SourceSpan`](crate::source::SourceSpan), which names its own source, is fine.
    ///
    /// # Errors
    ///
    /// [`RegistrationError::UnknownTable`] when the handle is not one of `session`'s;
    /// [`RegistrationError::DuplicateIdentifier`] when `identifier` is already
    /// registered in the table; [`RegistrationError::DuplicateAnnotationType`] when `A`
    /// is already registered.
    pub fn register_annotation<A>(
        self,
        session: &mut SerdeSession<L>,
        identifier: impl Into<Cow<'static, str>>,
    ) -> Result<(), RegistrationError>
    where
        A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
    {
        register_codec::<L>(self, session, TypeId::of::<NodeTree<L, A>>(), value_tree_codec::<L, A>(identifier.into()))
    }

    /// Registers tree annotation type `A` under `identifier` through the serde bridge.
    ///
    /// `A`'s annotations are serialized with [`to_value`](crate::serialize::to_value) and
    /// read back with [`from_value`](crate::serialize::from_value). This is the
    /// convenience for a plain-data annotation type — one whose values refer to no table
    /// object, so that they need no serialization context. An annotation type that does
    /// refer to a table object (a [`SourceSpan`](crate::source::SourceSpan)) uses
    /// [`register_annotation`](TableHandle::register_annotation) instead.
    ///
    /// Available with the `serde` cargo feature.
    ///
    /// # Errors
    ///
    /// As [`register_annotation`](TableHandle::register_annotation).
    #[cfg(feature = "serde")]
    pub fn register_serde_annotation<A>(
        self,
        session: &mut SerdeSession<L>,
        identifier: impl Into<Cow<'static, str>>,
    ) -> Result<(), RegistrationError>
    where
        A: serde::Serialize + serde::de::DeserializeOwned + Clone + Debug + Send + Sync + 'static,
    {
        register_codec::<L>(self, session, TypeId::of::<NodeTree<L, A>>(), serde_tree_codec::<L, A>(identifier.into()))
    }
}

/// The codec of a plain-data annotation type `A`, through the serde bridge (see
/// [`register_serde_annotation`](TableHandle::register_serde_annotation)).
#[cfg(feature = "serde")]
fn serde_tree_codec<L, A>(identifier: Cow<'static, str>) -> TreeCodec<L>
where
    L: SerializableLang,
    A: serde::Serialize + serde::de::DeserializeOwned + Clone + Debug + Send + Sync + 'static,
{
    TreeCodec {
        identifier,
        serialize: Arc::new(|object, cx| {
            let tree = downcast_tree::<L, A>(object)?;
            let nodes = serialize_nodes(tree, cx)?;
            let annotations = serialize_annotations(
                tree,
                |annotation, _cx| super::super::bridge::to_value(annotation).map_err(SerializeError::from),
                cx,
            )?;
            Ok(WireTree { nodes, annotations: Some(annotations) }.to_serial_value()?)
        }),
        deserialize: Arc::new(|data, cx| {
            let wire = WireTree::from_serial_value(data)?;
            let (nodes, annotations) = deserialize_annotations(
                wire,
                |value, _cx| super::super::bridge::from_value::<A>(value).map_err(DeserializeError::from),
                cx,
            )?;
            let tree = rebuild_tree::<L, A>(nodes, annotations, cx)?;
            Ok(Arc::new(tree) as Arc<dyn Any + Send + Sync>)
        }),
    }
}

fn register_codec<L: SerializableLang>(
    handle: TableHandle<TreeSerdeDriver<L>>,
    session: &mut SerdeSession<L>,
    type_id: TypeId,
    codec: TreeCodec<L>,
) -> Result<(), RegistrationError> {
    let ordinal = session.table_index(handle).map_err(|table| RegistrationError::UnknownTable { table })?;
    let table = session.table_name(ordinal);
    let registry = session
        .registry_mut::<TreeRegistry<L>>(ordinal)
        .ok_or(RegistrationError::UnknownTable { table: handle.id() })?;
    if registry.by_identifier.contains_key(&*codec.identifier) {
        return Err(RegistrationError::DuplicateIdentifier { table, identifier: codec.identifier.to_string() });
    }
    if registry.by_type.contains_key(&type_id) {
        return Err(RegistrationError::DuplicateAnnotationType { table });
    }
    registry.by_type.insert(type_id, codec.clone());
    registry.by_identifier.insert(codec.identifier.to_string(), codec);
    Ok(())
}

// --- the by-kind methods ----------------------------------------------------------------

/// Serializing a node tree into a session's trees table and reading one back:
/// `serialize_tree` and `tree` on a [`SerdeSession`].
///
/// These are the convenience methods over the general
/// [`SerdeSession::intern`](crate::serialize::SerdeSession::intern) /
/// [`SerdeSession::object`](crate::serialize::SerdeSession::object) with the trees table
/// handle.
///
/// An extension trait: bring it into scope with `use techy::serialize::TreeSerialization;`.
pub trait TreeSerialization<L: SerializableLang> {
    /// Serializes `tree` into the trees table, returning its position.
    ///
    /// Every call writes a new entry: a node tree is a value, written in full, so two
    /// calls with equal trees produce two entries — unlike an interned source or state,
    /// which is written once and shared.
    ///
    /// The tree's annotation type must be registered
    /// ([`TableHandle::register_annotation`]; the unit annotation is pre-registered).
    ///
    /// # Errors
    ///
    /// The session has no trees table ([`SerializeError::UnknownTableName`]); the
    /// annotation type is not registered ([`SerializeError::Failed`], wrapped in
    /// [`SerializeError::InTable`]); a node's serialization fails (its error, wrapped
    /// in [`SerializeError::InNode`] and [`SerializeError::InTable`]); the errors of
    /// [`SerdeSession::intern`](crate::serialize::SerdeSession::intern).
    ///
    /// # Panics
    ///
    /// Each callable node's invocation syntax is materialized against that node's own
    /// source before it is written ([`InvocationSyntax::materialized`]), so this panics
    /// if a range recorded there is not a valid `char`-boundary range of that source.
    /// That is a broken tree invariant, which no parsed input can cause and which
    /// [`validate_tree`](crate::core::node::validate_tree) detects; the panic is
    /// [`TextContent::resolve`](crate::source::TextContent::resolve)'s (see the [list of
    /// panicking items](crate::guide::panics)).
    fn serialize_tree<A>(&mut self, tree: &NodeTree<L, A>) -> Result<TreeIndex, SerializeError>
    where
        A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static;

    /// Returns the tree at `position` of the trees table, rebuilt with annotation type
    /// `A`.
    ///
    /// `A` must be the annotation type that the tree was serialized with. For instance,
    /// a tree produced by the parser (`NodeTree<L>`) is read with `A = ()`.
    ///
    /// # Errors
    ///
    /// - [`DeserializeError::UnknownTableName`] if the session has no trees table.
    /// - [`DeserializeError::AnnotationTypeMismatch`] if the tree at `position` was
    ///   serialized with an annotation type other than `A`.
    /// - The errors of [`SerdeSession::object`](crate::serialize::SerdeSession::object).
    fn tree<A>(&mut self, position: TreeIndex) -> Result<NodeTree<L, A>, DeserializeError>
    where
        A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static;
}

/// The identifier registered in `session`'s trees table for the tree type `tree_type`
/// (`TypeId::of::<NodeTree<L, A>>()`), when there is one.
fn registered_identifier<L: SerializableLang>(session: &mut SerdeSession<L>, tree_type: TypeId) -> Option<String> {
    let ordinal = session.table_ordinal_by_name(TREES_TABLE)?;
    let registry = session.registry_mut::<TreeRegistry<L>>(ordinal)?;
    registry.by_type.get(&tree_type).map(|codec| codec.identifier.to_string())
}

impl<L: SerializableLang> TreeSerialization<L> for SerdeSession<L> {
    fn serialize_tree<A>(&mut self, tree: &NodeTree<L, A>) -> Result<TreeIndex, SerializeError>
    where
        A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
    {
        let handle = self
            .table_handle::<TreeSerdeDriver<L>>(TREES_TABLE)
            .ok_or_else(|| SerializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
        let object: Arc<dyn Any + Send + Sync> = Arc::new(tree.clone());
        self.intern(handle, &object)
    }

    fn tree<A>(&mut self, position: TreeIndex) -> Result<NodeTree<L, A>, DeserializeError>
    where
        A: SerializableValue<L> + DeserializableValue<L> + Clone + Debug + Send + Sync + 'static,
    {
        let handle = self
            .table_handle::<TreeSerdeDriver<L>>(TREES_TABLE)
            .ok_or_else(|| DeserializeError::UnknownTableName { name: TREES_TABLE.to_string() })?;
        let object = self.object(handle, position)?;
        tree_of_object(self, object)
    }
}

/// The `NodeTree<L, A>` a trees-table object holds, cloned out — or, when the object
/// is a tree of another annotation type, the error naming the identifier it was
/// serialized under and the annotation type requested. Shared by the
/// [`TreeSerialization`] methods and the parse-result reader.
pub(crate) fn tree_of_object<L: SerializableLang, A: Clone + Send + Sync + 'static>(
    session: &mut SerdeSession<L>,
    object: Arc<dyn Any + Send + Sync>,
) -> Result<NodeTree<L, A>, DeserializeError> {
    match object.downcast::<NodeTree<L, A>>() {
        Ok(tree) => Ok((*tree).clone()),
        Err(object) => {
            // The stored tree's codec is registered (it was read through it); the
            // requested type may not be.
            let stored = registered_identifier(session, (*object).type_id());
            let requested = core::any::type_name::<A>();
            let requested_identifier = registered_identifier(session, TypeId::of::<NodeTree<L, A>>());
            Err(DeserializeError::AnnotationTypeMismatch { stored, requested, requested_identifier })
        }
    }
}

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

/// The nodes of `tree` in storage order — annotation-blind (the annotations are
/// serialized by the codec). A failure at a node is wrapped in
/// [`SerializeError::InNode`] with the node's position and, for a callable, its name.
fn serialize_nodes<L: SerializableLang, A>(
    tree: &NodeTree<L, A>,
    cx: &mut SerializeContext<'_, L>,
) -> Result<Vec<WireNode>, SerializeError> {
    let nodes = tree.nodes();
    nodes
        .iter()
        .enumerate()
        .map(|(index, data)| {
            serialize_node(index as u32, data, nodes, cx)
                .map_err(|error| error.in_node(index as u32, callable_name(&data.kind)))
        })
        .collect()
}

/// The invocation name of a callable node, for the location wrappers.
fn callable_name<L: Lang>(kind: &NodeKind<L>) -> Option<String> {
    match kind {
        NodeKind::Callable(data) => Some(data.name.to_string()),
        _ => None,
    }
}

fn serialize_node<L: SerializableLang>(
    index: u32,
    data: &crate::node::NodeData<L>,
    nodes: &[crate::node::NodeData<L>],
    cx: &mut SerializeContext<'_, L>,
) -> Result<WireNode, SerializeError> {
    let kind = serialize_kind(index, data, nodes, cx)?;
    let span = serialize_span(&data.span, cx)?;
    let state = cx.intern_state(&data.parsing_state)?;
    let ext = data.ext.serialize_value(cx)?;
    let children = WireRange { start: data.children.start, end: data.children.end };
    Ok(WireNode { kind, span, state, ext, children })
}

fn serialize_kind<L: SerializableLang>(
    index: u32,
    data: &crate::node::NodeData<L>,
    nodes: &[crate::node::NodeData<L>],
    cx: &mut SerializeContext<'_, L>,
) -> Result<WireNodeKind, SerializeError> {
    match &data.kind {
        NodeKind::Chars { content } => Ok(WireNodeKind::Chars { content: content.clone() }),
        NodeKind::Group(group) => Ok(WireNodeKind::Group {
            group_type: group.group_type.serialize_value(cx)?,
            open: group.open.clone(),
            close: group.close.clone(),
        }),
        NodeKind::Comment(comment) => Ok(WireNodeKind::Comment {
            start: comment.start.clone(),
            content: comment.content.clone(),
            post_space: comment.post_space.clone(),
        }),
        NodeKind::List => Ok(WireNodeKind::List),
        NodeKind::Callable(callable) => {
            let children_start = data.children.start;
            let arguments = callable
                .arguments
                .iter()
                .enumerate()
                .map(|(arg_index, argument)| {
                    serialize_argument(arg_index, argument, &callable.spec, index, children_start, nodes, cx)
                })
                .collect::<Result<Vec<_>, _>>()?;
            let slots = callable
                .slots
                .iter()
                .map(|slot| serialize_slot(slot, index, children_start, nodes, cx))
                .collect::<Result<Vec<_>, _>>()?;
            // The invocation syntax is materialized against the node's own source
            // first: its value conversion receives no node, so span-backed text
            // inside it could not be validated on reading (see `TreeSerdeDriver`).
            let invocation_syntax = callable.invocation_syntax.materialized(data.span.source()).serialize_value(cx)?;
            Ok(WireNodeKind::Callable {
                callable_type: callable.callable_type.serialize_value(cx)?,
                name: callable.name.to_string(),
                spec: cx.intern_spec(&callable.spec)?,
                arguments,
                slots,
                invocation_syntax,
            })
        }
    }
}

fn serialize_argument<L: SerializableLang>(
    arg_index: usize,
    argument: &ParsedArgument<L>,
    callable_spec: &Arc<dyn CallableSpec<L>>,
    callable_index: u32,
    children_start: u32,
    nodes: &[crate::node::NodeData<L>],
    cx: &mut SerializeContext<'_, L>,
) -> Result<WireArgument, SerializeError> {
    let spec_payload = callable_spec.serialize_argument_spec(arg_index, &argument.spec, cx)?;
    let region = argument.region.as_ref().map(|region| serialize_region(region, callable_index, children_start, nodes));
    let ext = argument.ext.as_ref().map(|ext| ext.serialize_value(cx)).transpose()?;
    Ok(WireArgument { region, ext, spec_payload })
}

fn serialize_slot<L: SerializableLang>(
    slot: &ParsedSlot<L>,
    callable_index: u32,
    children_start: u32,
    nodes: &[crate::node::NodeData<L>],
    cx: &mut SerializeContext<'_, L>,
) -> Result<WireSlot, SerializeError> {
    Ok(WireSlot {
        name: slot.name().map(String::from),
        region: serialize_region(&slot.region, callable_index, children_start, nodes),
        role: slot.role,
        ext: slot.ext.serialize_value(cx)?,
    })
}

/// The builder-ready form of a resolved region (see [`WireRegion`]): its node offsets
/// within the callable's child list and its content designation — in the region's own
/// node list when the content parent is the callable itself, else among the children
/// of the content parent (a node inside the region).
fn serialize_region<L: Lang>(
    region: &ChildRegion,
    callable_index: u32,
    children_start: u32,
    nodes: &[crate::node::NodeData<L>],
) -> WireRegion {
    let region_children = region.children();
    let region_start = region_children.start;
    let children = WireRange { start: region_start - children_start, end: region_children.end - children_start };
    let content_parent = region.content_parent().index() as u32;
    let content_range = region.content_range();
    let content = if content_parent == callable_index {
        WireContent::InRegion { start: content_range.start - region_start, end: content_range.end - region_start }
    } else {
        let parent_start = nodes[content_parent as usize].children.start;
        WireContent::InChildrenOf {
            node: content_parent,
            start: content_range.start - parent_start,
            end: content_range.end - parent_start,
        }
    };
    WireRegion { children, content }
}

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

/// Rebuild a tree from its wire nodes and annotations through the node builder.
///
/// The wire node list must be exactly the nodes reachable from the root: every node
/// but the root is listed among the children of exactly one node stored before it,
/// and the root among nobody's — checked here, so that no node is silently dropped
/// (the builder drops staged nodes the root does not reach) and none is claimed twice.
/// A failure at a node is wrapped in [`DeserializeError::InNode`] with the node's
/// position and, for a callable, its name.
fn rebuild_tree<L: SerializableLang, A>(
    wire_nodes: Vec<WireNode>,
    annotations: Vec<A>,
    cx: &mut DeserializeContext<'_, L>,
) -> Result<NodeTree<L, A>, DeserializeError> {
    let node_count = wire_nodes.len();
    if node_count == 0 {
        return Err(DeserializeError::failed("Missing root node: a node tree must have at least one node"));
    }
    if u32::try_from(node_count).is_err() {
        return Err(DeserializeError::failed("Too many nodes in a node tree (at most u32::MAX nodes)"));
    }
    // `node_count == annotations.len()` by the codec; guard anyway.
    if annotations.len() != node_count {
        return Err(DeserializeError::failed(alloc::format!(
            "Wrong number of annotations in a tree entry ({} annotations for {node_count} nodes)",
            annotations.len()
        )));
    }

    let mut builder = NodeTreeBuilder::<L, A>::new();
    // The staging map: wire position → builder id, filled in reverse storage order.
    let mut build_id_of: Vec<Option<BuildId>> = alloc::vec![None; node_count];
    // Which node lists each node among its children (`None`: no node so far).
    let mut claimed_by: Vec<Option<u32>> = alloc::vec![None; node_count];

    // Stage in reverse storage order: a node's children (and every region's content
    // parent, a descendant) are stored after it, so they are staged first.
    for (index, annotation) in annotations.into_iter().enumerate().rev() {
        let wire = &wire_nodes[index];
        let build_id =
            stage_node(index as u32, wire, &build_id_of, &mut claimed_by, &mut builder, annotation, cx)
                .map_err(|error| error.in_node(index as u32, wire_callable_name(wire)))?;
        build_id_of[index] = Some(build_id);
    }

    // Every node but the root is some node's child; the root is nobody's (a children
    // range reaching position 0 fails the stored-after-its-parent check in `stage_node`).
    if let Some(unclaimed) = (1..node_count).find(|&index| claimed_by[index].is_none()) {
        return Err(DeserializeError::failed(
            "Unreachable node: no node lists this node among its children",
        )
        .in_node(unclaimed as u32, wire_callable_name(&wire_nodes[unclaimed])));
    }

    // `node_count >= 1` and every position was staged: node 0 has a build id.
    let root = build_id_of[0].expect("the root node was staged");
    let tree = builder.finish(root).map_err(|error| builder_failure(error, &build_id_of))?;
    // Defense in depth: the builder enforces the all-trees law, but the reader is a
    // total validator of untrusted input.
    validate_tree(&tree).map_err(|violation| {
        DeserializeError::failed(violation.to_string()).with_cause(violation)
    })?;
    // Every node was claimed once, so the builder reached every node from the root; a
    // shorter tree would be a bug in this reader or in the builder.
    if tree.node_count() != node_count {
        return Err(DeserializeError::Internal {
            detail: alloc::format!(
                "Wrong number of nodes in a rebuilt tree: {} nodes (expected {node_count})",
                tree.node_count()
            ),
        });
    }
    Ok(tree)
}

/// Validate and stage wire node `index`: its children range (in bounds, stored after
/// the node, each child listed by this node alone), then its kind, span, state, ext,
/// and annotation, into `builder`. Records this node as the one listing its children in
/// `claimed_by`.
fn stage_node<L: SerializableLang, A>(
    index: u32,
    wire: &WireNode,
    build_id_of: &[Option<BuildId>],
    claimed_by: &mut [Option<u32>],
    builder: &mut NodeTreeBuilder<L, A>,
    annotation: A,
    cx: &mut DeserializeContext<'_, L>,
) -> Result<BuildId, DeserializeError> {
    let node_count = build_id_of.len();
    let (child_start, child_end) = (wire.children.start, wire.children.end);
    if child_start > child_end || child_end as usize > node_count {
        return Err(DeserializeError::failed(alloc::format!(
            "Invalid children range {child_start}..{child_end} ({node_count} nodes in the tree)"
        )));
    }
    if child_start != child_end && child_start <= index {
        return Err(DeserializeError::failed(alloc::format!(
            "Invalid children range {child_start}..{child_end}: the children of a node must be \
             stored after the node"
        )));
    }
    let mut children = Vec::with_capacity((child_end - child_start) as usize);
    for child in child_start..child_end {
        if let Some(other) = claimed_by[child as usize] {
            return Err(DeserializeError::failed(alloc::format!(
                "Node #{child} has two parents (node #{other} and node #{index})"
            )));
        }
        claimed_by[child as usize] = Some(index);
        // Stored after this node, hence staged before it (staging runs in reverse).
        let build_id = build_id_of[child as usize].ok_or_else(|| DeserializeError::Internal {
            detail: alloc::format!("Child node #{child} of node #{index} was not staged before its parent"),
        })?;
        children.push(build_id);
    }

    let kind = rebuild_kind(wire, build_id_of, cx)?;
    let span = deserialize_span(wire.span, cx)?;
    let state = cx.state(wire.state)?;
    let ext = <NodeExt<L> as DeserializableValue<L>>::deserialize_value(&wire.ext, cx)?;
    builder.add(kind, span, state, children, ext, annotation).map_err(|error| builder_failure(error, build_id_of))
}

/// The invocation name of a callable wire node, for the location wrappers.
fn wire_callable_name(wire: &WireNode) -> Option<String> {
    match &wire.kind {
        WireNodeKind::Callable { name, .. } => Some(name.clone()),
        _ => None,
    }
}

/// The wire position a builder id was staged for — the staging map inverted (a linear
/// search, on error paths only).
fn wire_position_of(build_id_of: &[Option<BuildId>], id: BuildId) -> Option<usize> {
    build_id_of.iter().position(|staged| *staged == Some(id))
}

/// A builder error as a read error: the message names wire node positions rather than
/// builder ids, and the builder error itself is kept as the cause.
fn builder_failure(error: NodeBuildError, build_id_of: &[Option<BuildId>]) -> DeserializeError {
    let node = |id: BuildId| match wire_position_of(build_id_of, id) {
        Some(position) => alloc::format!("node #{position}"),
        None => alloc::format!("node {}", id.number()),
    };
    let detail = match &error {
        NodeBuildError::ChildNotStaged { child } => {
            alloc::format!("Invalid child {}: the node was not staged before its parent", node(*child))
        }
        NodeBuildError::ChildAlreadyClaimed { child } => {
            alloc::format!("Invalid child {}: the node is already the child of another node", node(*child))
        }
        NodeBuildError::ContentParentNotStaged { parent } => {
            alloc::format!("Invalid content parent {}: the node was not staged before its callable", node(*parent))
        }
        NodeBuildError::RootNotStaged { root } => {
            alloc::format!("Invalid root {}: the node was not staged", node(*root))
        }
        NodeBuildError::RootClaimed { root } => {
            alloc::format!("Invalid root {}: the node is the child of another node", node(*root))
        }
        NodeBuildError::ContentParentUnreachable { parent } => {
            alloc::format!("Invalid content parent {}: the node is not reachable from the root", node(*parent))
        }
        NodeBuildError::ContentParentOutsideSubtree { parent } => alloc::format!(
            "Invalid content parent {}: the node is not inside the subtree of its callable",
            node(*parent)
        ),
        NodeBuildError::ContentParentOutsideRegion { parent } => alloc::format!(
            "Invalid content parent {}: the node is not inside its argument or slot region",
            node(*parent)
        ),
        other => other.to_string(),
    };
    DeserializeError::failed(detail).with_cause(error)
}

fn rebuild_kind<L: SerializableLang>(
    wire: &WireNode,
    build_id_of: &[Option<BuildId>],
    cx: &mut DeserializeContext<'_, L>,
) -> Result<NodeKind<L>, DeserializeError> {
    match &wire.kind {
        WireNodeKind::Chars { content } => Ok(NodeKind::Chars { content: content.clone() }),
        WireNodeKind::Group { group_type, open, close } => {
            let group_type = <Option<L::GroupTypeId> as DeserializableValue<L>>::deserialize_value(group_type, cx)?;
            Ok(NodeKind::Group(Box::new(GroupData { group_type, open: open.clone(), close: close.clone() })))
        }
        WireNodeKind::Comment { start, content, post_space } => Ok(NodeKind::Comment(Box::new(CommentData {
            start: start.clone(),
            content: content.clone(),
            post_space: post_space.clone(),
        }))),
        WireNodeKind::List => Ok(NodeKind::List),
        WireNodeKind::Callable { callable_type, name, spec, arguments, slots, invocation_syntax } => {
            let callable_type = <L::CallableTypeId as DeserializableValue<L>>::deserialize_value(callable_type, cx)?;
            let spec = cx.spec(*spec)?;
            let arguments = arguments
                .iter()
                .enumerate()
                .map(|(arg_index, wire)| rebuild_argument(arg_index, wire, &spec, build_id_of, cx))
                .collect::<Result<Vec<_>, _>>()?;
            let slots = slots
                .iter()
                .map(|wire| rebuild_slot(wire, build_id_of, cx))
                .collect::<Result<Vec<_>, _>>()?;
            let invocation_syntax =
                <L::InvocationSyntax as DeserializableValue<L>>::deserialize_value(invocation_syntax, cx)?;
            Ok(NodeKind::Callable(Box::new(CallableData {
                callable_type,
                name: name.as_str().into(),
                spec,
                arguments: ParsedArguments::new(arguments),
                slots: ParsedSlots::new(slots),
                invocation_syntax,
            })))
        }
    }
}

fn rebuild_argument<L: SerializableLang>(
    arg_index: usize,
    wire: &WireArgument,
    callable_spec: &Arc<dyn CallableSpec<L>>,
    build_id_of: &[Option<BuildId>],
    cx: &mut DeserializeContext<'_, L>,
) -> Result<ParsedArgument<L>, DeserializeError> {
    let spec = callable_spec.deserialize_argument_spec(arg_index, wire.spec_payload.as_ref(), cx)?;
    match &wire.region {
        Some(region) => {
            let region = staged_region(region, build_id_of)?;
            // A provided argument's ext follows its region: the writer writes it (null
            // for the unit ext), and the reader accepts a null value or an omitted key
            // alike as the ext's null form (an `Option<SerialValue>` field reads a
            // present null as `None`).
            let null = SerialValue::Null;
            let ext_value = wire.ext.as_ref().unwrap_or(&null);
            let ext = <ArgumentExt<L> as DeserializableValue<L>>::deserialize_value(ext_value, cx)?;
            Ok(ParsedArgument::provided(spec, region, ext))
        }
        None => {
            // An absent argument has no ext: one on the wire is not silently dropped.
            if wire.ext.is_some() {
                return Err(DeserializeError::failed(alloc::format!(
                    "Unexpected ext on absent argument #{} (an absent argument has no ext)",
                    arg_index.saturating_add(1)
                )));
            }
            Ok(ParsedArgument::absent(spec))
        }
    }
}

fn rebuild_slot<L: SerializableLang>(
    wire: &WireSlot,
    build_id_of: &[Option<BuildId>],
    cx: &mut DeserializeContext<'_, L>,
) -> Result<ParsedSlot<L>, DeserializeError> {
    let region = staged_region(&wire.region, build_id_of)?;
    let ext = <SlotExt<L> as DeserializableValue<L>>::deserialize_value(&wire.ext, cx)?;
    match &wire.name {
        Some(name) => Ok(ParsedSlot::new(region, name.as_str(), wire.role, ext)),
        None => Ok(ParsedSlot::new_unnamed(region, wire.role, ext)),
    }
}

/// Convert a wire region into the builder's staged form: the region's child offsets
/// and its content designation ([`ContentNodes`]) in build-id terms. An
/// `in_children_of` content parent must be a node inside the region — a descendant of
/// the callable, stored after it, hence already staged (the callable itself is not
/// staged yet, so naming it is that error too); the builder checks that it lies inside
/// the region's own subtree when the tree is finished.
fn staged_region(wire: &WireRegion, build_id_of: &[Option<BuildId>]) -> Result<ChildRegion, DeserializeError> {
    let children = wire.children.start..wire.children.end;
    let content = match wire.content {
        WireContent::InRegion { start, end } => ContentNodes::InRegion(start..end),
        WireContent::InChildrenOf { node: parent, start, end } => {
            let build_id = match build_id_of.get(parent as usize) {
                None => {
                    return Err(DeserializeError::failed(alloc::format!(
                        "Content parent node #{parent} of a region is out of range ({} nodes in the tree)",
                        build_id_of.len()
                    )))
                }
                Some(None) => {
                    return Err(DeserializeError::failed(alloc::format!(
                        "Invalid content parent node #{parent} of a region: the content parent must be a \
                         node inside the region, stored after its callable"
                    )))
                }
                Some(Some(build_id)) => *build_id,
            };
            ContentNodes::InChildrenOf(build_id, start..end)
        }
    };
    Ok(ChildRegion::new(children, content))
}

// --- value conversions of core payload types (owned text only, see the TreeSerdeDriver
// docs; a language's own conversions reuse them)

/// The value conversion of textual content — used for text inside a language-typed
/// payload, such as a callable's invocation syntax or an ext value — writes **owned text
/// only**: `{owned: "text"}`.
///
/// A [`Spanned`](TextContent::Spanned) value is an error. The conversion receives no
/// node, so a byte range into the carrying node's source could not be validated on
/// reading; span-backed text must be materialized against the node's source first
/// ([`TextContent::materialized`]). For a callable's invocation syntax the tree writer
/// does so through [`InvocationSyntax::materialized`] before converting the payload; see
/// [`TreeSerdeDriver`].
///
/// The text payloads of the nodes themselves — a `Chars` node's content, a group's
/// delimiters, a comment's parts — do not go through this conversion: the tree driver
/// writes them span-backed and validates the ranges against the node's source.
impl<L: Lang> SerializableValue<L> for TextContent {
    fn serialize_value(&self, _cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
    where
        L: SerializableLang,
    {
        match self {
            TextContent::Owned(_) => Ok(self.to_serial_value()?),
            TextContent::Spanned(span) => Err(SerializeError::failed(alloc::format!(
                "Unsupported span-backed text ({span:?}) in a language payload: convert the text \
                 with ‘TextContent::materialized’ before serializing the payload"
            ))),
        }
    }
}

/// Reads `{owned: "text"}` only; a `{spanned: {start, end}}` value is an error (see
/// the write side above: without the node, the range could not be validated).
impl<L: Lang> DeserializableValue<L> for TextContent {
    fn deserialize_value(value: &SerialValue, _cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
    where
        L: SerializableLang,
    {
        match TextContent::from_serial_value(value)? {
            owned @ TextContent::Owned(_) => Ok(owned),
            TextContent::Spanned(span) => Err(DeserializeError::failed(alloc::format!(
                "Invalid span-backed text ({span:?}) in a language payload: text in a language \
                 payload must be owned text"
            ))),
        }
    }
}

/// A slot's role is `"content"`, `"attached"`, or `"hidden"`.
impl<L: Lang> SerializableValue<L> for SlotRole {
    fn serialize_value(&self, _cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
    where
        L: SerializableLang,
    {
        Ok(self.to_serial_value()?)
    }
}

impl<L: Lang> DeserializableValue<L> for SlotRole {
    fn deserialize_value(value: &SerialValue, _cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
    where
        L: SerializableLang,
    {
        Ok(SlotRole::from_serial_value(value)?)
    }
}

/// A group rule is `{group_type, open, close}` — its class in the language's own form,
/// its delimiters as strings.
impl<L: Lang> SerializableValue<L> for GroupRule<L> {
    fn serialize_value(&self, cx: &mut SerializeContext<'_, L>) -> Result<SerialValue, SerializeError>
    where
        L: SerializableLang,
    {
        let wire = WireGroupRule {
            group_type: self.group_type.serialize_value(cx)?,
            open: self.open.clone(),
            close: self.close.clone(),
        };
        Ok(wire.to_serial_value()?)
    }
}

impl<L: Lang> DeserializableValue<L> for GroupRule<L> {
    fn deserialize_value(value: &SerialValue, cx: &mut DeserializeContext<'_, L>) -> Result<Self, DeserializeError>
    where
        L: SerializableLang,
    {
        let wire = WireGroupRule::from_serial_value(value)?;
        Ok(GroupRule {
            group_type: <L::GroupTypeId as DeserializableValue<L>>::deserialize_value(&wire.group_type, cx)?,
            open: wire.open,
            close: wire.close,
        })
    }
}