Skip to main content

tilo_resource/
table.rs

1//! A model type's storage contract as data.
2//!
3//! What a record does with its fields — read them, write them, compare them,
4//! edit, check and describe them — is the same walk for every record, over
5//! each field's own type. `#[derive(Model)]` describes a record as a table
6//! of its fields ([`ResourceDesc`]) and three small functions reaching into it
7//! (a field by position, the same mutably, and building one from its
8//! fields), and every [`Model`] operation of a record is one function here,
9//! compiled once into the runtime. A field's type is reached through
10//! its [`ModelTable`]: the type's [`Model`] functions with the type erased,
11//! built once per type, and for the types this crate defines, once.
12
13use std::any::Any;
14use std::marker::PhantomData;
15use tilo_sort::CompactSort as _;
16
17use automerge::{ObjId, ObjType, Value};
18
19use crate::action::{ActionCx, Refusal};
20use crate::delta::{Delta, Touch};
21use crate::items::{ItemCollection, ItemSource, ItemText};
22use crate::model::{Doc, Fresh, LocatedAt as _, Model, ModelError, Slot};
23use crate::path::{Edit, EditOp, OpDescription, Segment};
24use crate::resource::Place;
25
26pub(crate) mod fresh;
27mod item_paths;
28pub use item_paths::{holds_nested_items, item_json, names_item, reads_item};
29
30/// A value's fields made with the map holding it in one batch, and the
31/// fields its `store` writes into it after, by position, with whether each
32/// was made with the map ([`Fresh::Made`](crate::Fresh::Made)).
33pub(crate) type Fields = (automerge::hydrate::Map, Vec<(usize, bool)>);
34
35/// A model type's [`Model`] functions, its type erased. Each takes the table
36/// it was reached through, which for a record carries its [`ResourceDesc`].
37/// A value is handed over as `&dyn Any` of the type; a value made is put
38/// into an `&mut dyn Any` of `Option` of the type.
39#[allow(
40    clippy::type_complexity,
41    reason = "each field is one Model function, with the same parameters"
42)]
43pub struct ModelOps {
44    pub(crate) to_json: fn(&ModelTable, &dyn Any) -> serde_json::Value,
45    pub(crate) from_json:
46        fn(&ModelTable, &serde_json::Value, &mut dyn Any) -> Result<(), ModelError>,
47    pub(crate) load:
48        fn(&ModelTable, &Doc, &Value<'_>, &ObjId, &mut dyn Any) -> Result<(), ModelError>,
49    pub(crate) missing: fn(&ModelTable, &mut dyn Any) -> Result<(), ModelError>,
50    /// Read the value anew in place: from what a slot holds, or its missing
51    /// value when the slot holds nothing.
52    pub(crate) reload:
53        fn(&ModelTable, &mut dyn Any, &Doc, Option<(&Value<'_>, &ObjId)>) -> Result<(), ModelError>,
54    pub(crate) store: fn(&ModelTable, &dyn Any, &mut Doc, Slot<'_>) -> Result<(), ModelError>,
55    /// [`Model::fresh`].
56    pub(crate) fresh: fn(&ModelTable, &dyn Any, automerge::TextEncoding) -> Fresh,
57    pub(crate) stores_as: fn(&ModelTable, &dyn Any, &dyn Any) -> bool,
58    pub(crate) store_changed:
59        fn(&ModelTable, &dyn Any, &dyn Any, &mut Doc, Slot<'_>, &Delta) -> Result<(), ModelError>,
60    pub(crate) refresh:
61        fn(&ModelTable, &mut dyn Any, &Doc, &Value<'_>, &ObjId, &Delta) -> Result<(), ModelError>,
62    pub(crate) read_whole: fn(&ModelTable, &mut dyn Any, &Doc) -> Result<(), ModelError>,
63    pub(crate) edit: fn(
64        &ModelTable,
65        &mut Doc,
66        Slot<'_>,
67        &[Segment],
68        &EditOp,
69        &mut ActionCx,
70    ) -> Result<(), ModelError>,
71    pub(crate) diff: fn(&ModelTable, &dyn Any, &dyn Any, &[Segment], &mut Vec<Edit<()>>),
72    pub(crate) collect_text: fn(&ModelTable, &dyn Any, &mut Vec<String>),
73    pub(crate) check: fn(&ModelTable, &dyn Any) -> Result<(), Refusal>,
74    pub(crate) get_at: for<'a> fn(&ModelTable, &'a dyn Any, &[Segment]) -> Option<&'a dyn Any>,
75    pub(crate) label: fn(&ModelTable, &dyn Any) -> Option<String>,
76    pub(crate) nested_collections: fn(&ModelTable, &dyn Any) -> Vec<ItemCollection>,
77    pub(crate) op_coalesces:
78        fn(&ModelTable, &[Segment], &serde_json::Value, &serde_json::Value) -> Option<bool>,
79    pub(crate) op_continuable: fn(&ModelTable, &[Segment], &serde_json::Value) -> Option<bool>,
80    pub(crate) op_describe:
81        fn(&ModelTable, &[Segment], &serde_json::Value) -> Option<OpDescription>,
82    pub(crate) op_lands: fn(&ModelTable, &dyn Any, &[Segment], &serde_json::Value) -> Option<Place>,
83    pub(crate) op_schemas: fn(&ModelTable, &str, &mut Vec<(String, serde_json::Value)>),
84    /// What an edit that writes a new value carries of the value's JSON
85    /// form ([`crate::shape::without_absent`]).
86    pub(crate) without_absent: fn(&ModelTable, serde_json::Value) -> serde_json::Value,
87}
88
89/// A model type as data: its erased [`Model`] functions, what it is (a
90/// record's fields), and what it holds (a collection's items).
91pub struct ModelTable {
92    pub(crate) ops: &'static ModelOps,
93    desc: Desc,
94    /// Its [`Model::CHECKS`].
95    pub checks: bool,
96    /// Its [`Model::OPS`].
97    pub has_ops: bool,
98    /// Its [`Model::SCALAR`].
99    pub scalar: bool,
100}
101
102/// What a type's table knows of its shape, beyond its functions.
103#[derive(Clone, Copy)]
104enum Desc {
105    /// Its own functions do everything.
106    Own,
107    /// A record of fields.
108    Record(&'static ResourceDesc),
109    /// An `Option` of a value.
110    Option(&'static OptionDesc),
111    /// A collection of items.
112    Collection(&'static crate::collection::CollectionDesc),
113    /// An enum of unit variants.
114    Unit(&'static UnitDesc),
115    /// A value stored whole as JSON text.
116    Json(&'static JsonDesc),
117    /// A list of values.
118    Vec(&'static VecDesc),
119    /// A map of string keys.
120    Map(&'static MapDesc),
121    /// A set of elements stored as map keys.
122    Set(&'static crate::storage::SetDesc),
123}
124
125impl ModelTable {
126    pub(crate) const fn record(&self) -> Option<&'static ResourceDesc> {
127        match self.desc {
128            Desc::Record(record) => Some(record),
129            _ => None,
130        }
131    }
132
133    pub(crate) const fn collection(&self) -> Option<&'static crate::collection::CollectionDesc> {
134        match self.desc {
135            Desc::Collection(collection) => Some(collection),
136            _ => None,
137        }
138    }
139
140    /// The table of a collection.
141    #[must_use]
142    pub const fn of_collection(
143        collection: &'static crate::collection::CollectionDesc,
144        checks: bool,
145        has_ops: bool,
146    ) -> Self {
147        Self {
148            ops: &crate::collection::COLLECTION_OPS,
149            desc: Desc::Collection(collection),
150            checks,
151            has_ops,
152            scalar: false,
153        }
154    }
155
156    pub(crate) const fn set(&self) -> Option<&'static crate::storage::SetDesc> {
157        match self.desc {
158            Desc::Set(set) => Some(set),
159            _ => None,
160        }
161    }
162
163    /// The table of a set.
164    #[must_use]
165    pub const fn of_set(set: &'static crate::storage::SetDesc, checks: bool) -> Self {
166        Self {
167            ops: &crate::storage::SET_OPS,
168            desc: Desc::Set(set),
169            checks,
170            has_ops: false,
171            scalar: false,
172        }
173    }
174
175    const fn option(&self) -> Option<&'static OptionDesc> {
176        match self.desc {
177            Desc::Option(option) => Some(option),
178            _ => None,
179        }
180    }
181
182    /// Whether a value of this table's type holds a value of `target`'s:
183    /// it is one, or a field of it is, an option's value, or an item of a
184    /// collection of it, at any depth a record nests.
185    pub(crate) fn holds(&'static self, target: &'static Self) -> bool {
186        fn within(table: &'static ModelTable, target: &'static ModelTable, depth: u8) -> bool {
187            if std::ptr::eq(table, target) {
188                return true;
189            }
190            // Records nest a handful deep; a type that holds itself (a tree
191            // of boxed nodes) is not walked without end.
192            if depth >= 16 {
193                return false;
194            }
195            if let Some(option) = table.option() {
196                return within(option.inner, target, depth.saturating_add(1));
197            }
198            table.record().is_some_and(|record| {
199                record.fields.iter().any(|field| {
200                    within(field.table, target, depth.saturating_add(1))
201                        || field.items.is_some_and(|items| {
202                            within(items.item_table, target, depth.saturating_add(1))
203                        })
204                })
205            })
206        }
207        within(self, target, 0)
208    }
209}
210
211/// A collection type's [`ItemSource`] functions, its type erased.
212pub struct ItemOps {
213    item_collection: fn(&dyn Any, &'static str) -> Option<ItemCollection>,
214    item_presence: fn(&dyn Any) -> usize,
215    label_of_item: fn(&dyn Any, &crate::Id) -> Option<String>,
216    item_texts: fn(&dyn Any, &'static str, &mut Vec<ItemText>),
217    nested_items: fn(&dyn Any, &'static str, &mut Vec<ItemCollection>),
218    /// The items, whatever their type.
219    pub(crate) list: for<'a> fn(&'a dyn Any) -> Option<&'a dyn crate::collection::ItemList>,
220    /// The items' type's table.
221    pub(crate) item_table: &'static ModelTable,
222}
223
224/// A collection whose items are published: its items' type's table.
225pub trait PublishedItems: crate::collection::ItemList + ItemSource + 'static {
226    const ITEM_TABLE: &'static ModelTable;
227}
228
229/// One field of a record, as [`ResourceDesc`] lists it.
230pub struct FieldDesc {
231    /// The key it is stored under.
232    pub key: &'static str,
233    /// Its Rust name.
234    pub name: &'static str,
235    /// Its type's table.
236    pub table: &'static ModelTable,
237    /// Changed only by the record's verbs (`#[model(readonly)]`).
238    pub readonly: bool,
239    /// Read all of it whenever it is read (`#[model(whole)]`).
240    pub whole: bool,
241    /// Left unread by a view's reader until a view demands its item
242    /// (`#[model(demanded)]`, [`for_view`]).
243    pub demanded: bool,
244    /// Its items, for a collection whose items are published.
245    pub items: Option<&'static ItemOps>,
246}
247
248/// Read a record, boxed, from the map it is stored in.
249pub type ReadResource = fn(&Doc, &ObjId) -> Result<Box<dyn Any>, ModelError>;
250
251/// A record's own invariant (`#[model(check = path)]`).
252pub struct OwnCheck {
253    /// Check a record.
254    pub check: fn(&dyn Any) -> Result<(), Refusal>,
255    /// Read a record from the map it is stored in, to check it after an
256    /// edit of one of its fields.
257    pub read: ReadResource,
258    /// What the check reads (`#[model(check_reads, check_items)]`); `None`
259    /// when it may read anything, so every edit inside the record checks it.
260    pub reads: Option<CheckReads>,
261}
262
263/// What a record's own check reads: an edit that touches none of it cannot
264/// break the invariant, so the record is not read again to check it.
265pub struct CheckReads {
266    /// The keys of the fields it reads.
267    pub fields: &'static [&'static str],
268    /// The keys of the collections whose items it counts but does not read
269    /// into: adding, removing or replacing an item touches it, an edit
270    /// inside one does not.
271    pub items: &'static [&'static str],
272}
273
274impl CheckReads {
275    /// Whether an edit at `path` (from the record) can change what the
276    /// check reads.
277    #[must_use]
278    pub fn touched_by(&self, path: &[Segment]) -> bool {
279        match path.split_first() {
280            Some((Segment::Field(key), rest)) => {
281                self.fields.contains(&key.as_str())
282                    || (self.items.contains(&key.as_str()) && rest.len() <= 1)
283            }
284            // The whole record, or a path it does not know: checked.
285            None | Some(_) => true,
286        }
287    }
288}
289
290/// A record type as `#[derive(Model)]` describes it. See the [module
291/// docs](self).
292pub struct ResourceDesc {
293    /// Its stored fields, in declaration order.
294    pub fields: &'static [FieldDesc],
295    /// The field at a position of a record.
296    pub field: for<'a> fn(&'a dyn Any, usize) -> Option<&'a dyn Any>,
297    /// The same, mutably.
298    pub field_mut: for<'a> fn(&'a mut dyn Any, usize) -> Option<&'a mut dyn Any>,
299    /// A record from its fields, in order, put into an `Option` of it.
300    pub build: fn(&mut dyn FieldSource, &mut dyn Any) -> Result<(), ModelError>,
301    /// An empty `Option` of the record, for [`Self::build`] to fill.
302    pub empty: fn() -> Box<dyn Any>,
303    /// The record in a filled `Option` of it.
304    pub unwrap: fn(&dyn Any) -> Option<&dyn Any>,
305    /// Move the record out of a filled `Option` (the second) over a record
306    /// (the first).
307    pub replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
308    /// Its own invariant.
309    pub own_check: Option<OwnCheck>,
310    /// The position of its `#[model(label)]` field.
311    pub label: Option<usize>,
312    /// The positions of the fields its label joins (`#[model(label = "..")]`).
313    pub label_parts: &'static [usize],
314    /// What names it, where its name is not a field's text as stored
315    /// (`#[model(label = path)]`).
316    pub label_with: Option<fn(&dyn Any) -> Option<String>>,
317    /// Its type's name: what a deferred check is known by.
318    pub name: fn() -> &'static str,
319    /// Its stored shape.
320    pub shape: crate::Shape,
321    /// Its [`Model::CHECKS`].
322    pub checks: bool,
323    /// Its [`Model::OPS`].
324    pub has_ops: bool,
325}
326
327/// Where a record being built takes its fields from, one after the other.
328pub trait FieldSource {
329    /// The next field's value, put into `out`, an `Option` of its type.
330    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError>;
331
332    /// The field just read: read all of it (`#[model(whole)]`) and move on.
333    fn read(&mut self, value: &mut dyn Any) -> Result<(), ModelError>;
334}
335
336/// The next field of `source`, a `T`.
337pub fn take<T: 'static>(source: &mut dyn FieldSource) -> Result<T, ModelError> {
338    let mut out: Option<T> = None;
339    source.next(&mut out)?;
340    let Some(mut value) = out else {
341        return Err(mismatch());
342    };
343    source.read(&mut value)?;
344    Ok(value)
345}
346
347/// The next field of `source`, a `T`, or what `repair` derives for it when
348/// the document holds none: a field declared `#[model(default = ..)]`, so a
349/// record missing it (written by an older app, or half-made by an edit that
350/// raced its deletion) still reads, and the next whole write stores it.
351pub fn take_or<T: 'static>(
352    source: &mut dyn FieldSource,
353    repair: impl FnOnce() -> T,
354) -> Result<T, ModelError> {
355    let mut out: Option<T> = None;
356    match source.next(&mut out) {
357        Ok(()) => {}
358        Err(ModelError::Missing { .. }) => out = Some(repair()),
359        Err(error) => return Err(error),
360    }
361    let Some(mut value) = out else {
362        return Err(mismatch());
363    };
364    source.read(&mut value)?;
365    Ok(value)
366}
367
368/// Put `value` into `out`, an `Option` of its type.
369///
370/// # Errors
371/// When `out` is of another type.
372pub fn put<T: 'static>(out: &mut dyn Any, value: T) -> Result<(), ModelError> {
373    match out.downcast_mut::<Option<T>>() {
374        Some(slot) => {
375            *slot = Some(value);
376            Ok(())
377        }
378        None => Err(mismatch()),
379    }
380}
381
382/// An empty `Option` of `T`.
383#[must_use]
384pub fn empty_of<T: 'static>() -> Box<dyn Any> {
385    Box::new(None::<T>)
386}
387
388/// The `T` in a filled `Option` of it.
389#[must_use]
390pub fn unwrap_of<T: 'static>(filled: &dyn Any) -> Option<&dyn Any> {
391    match filled.downcast_ref::<Option<T>>()? {
392        Some(value) => Some(value),
393        None => None,
394    }
395}
396
397/// Swap the `T` in `filled`, an `Option` of it, with `target`: `filled`
398/// then holds what `target` held, dropped with it.
399///
400/// # Errors
401/// When either is of another type, or `filled` is empty.
402pub fn replace_of<T: 'static>(
403    target: &mut dyn Any,
404    filled: &mut dyn Any,
405) -> Result<(), ModelError> {
406    match (
407        target.downcast_mut::<T>(),
408        filled.downcast_mut::<Option<T>>(),
409    ) {
410        (Some(target), Some(Some(value))) => {
411            std::mem::swap(target, value);
412            Ok(())
413        }
414        _ => Err(mismatch()),
415    }
416}
417
418/// A value handed to a table of another type: a bug in the caller.
419#[inline(never)]
420pub(crate) fn mismatch() -> ModelError {
421    ModelError::invalid("a value of another type")
422}
423
424/// The table of `T`, from its own [`Model`] functions.
425pub struct TableOf<T>(PhantomData<T>);
426
427/// `TABLE` of a type this crate defines, inside its `impl Model`: built
428/// here, once, rather than in every app holding a field of it.
429#[doc(hidden)]
430#[macro_export]
431macro_rules! __own_table {
432    ($ty:ty) => {
433        const TABLE: &'static $crate::table::ModelTable = {
434            static TABLE: $crate::table::ModelTable = $crate::table::TableOf::<$ty>::TABLE;
435            &TABLE
436        };
437    };
438}
439
440impl<T: Model> TableOf<T> {
441    /// `T`'s functions.
442    pub const OPS: ModelOps = ModelOps {
443        without_absent: crate::shape::kept_whole,
444        to_json: to_json_of::<T>,
445        from_json: from_json_of::<T>,
446        load: load_of::<T>,
447        missing: missing_of::<T>,
448        reload: reload_of::<T>,
449        store: store_of::<T>,
450        fresh: fresh::fresh_of::<T>,
451        stores_as: stores_as_of::<T>,
452        store_changed: store_changed_of::<T>,
453        refresh: refresh_of::<T>,
454        read_whole: read_whole_of::<T>,
455        edit: edit_of::<T>,
456        diff: diff_of::<T>,
457        collect_text: collect_text_of::<T>,
458        check: if T::CHECKS { check_of::<T> } else { no_check },
459        get_at: get_at_of::<T>,
460        label: label_of::<T>,
461        nested_collections: nested_collections_of::<T>,
462        op_coalesces: if T::OPS {
463            op_coalesces_of::<T>
464        } else {
465            no_coalesces
466        },
467        op_continuable: if T::OPS {
468            op_continuable_of::<T>
469        } else {
470            no_continuable
471        },
472        op_describe: if T::OPS {
473            op_describe_of::<T>
474        } else {
475            no_describe
476        },
477        op_lands: if T::OPS { op_lands_of::<T> } else { no_lands },
478        op_schemas: if T::OPS {
479            op_schemas_of::<T>
480        } else {
481            no_schemas
482        },
483    };
484
485    /// `T`'s table.
486    pub const TABLE: ModelTable = ModelTable {
487        ops: &Self::OPS,
488        desc: Desc::Own,
489        checks: T::CHECKS,
490        has_ops: T::OPS,
491        scalar: T::SCALAR,
492    };
493}
494
495fn to_json_of<T: Model>(_: &ModelTable, value: &dyn Any) -> serde_json::Value {
496    value
497        .downcast_ref::<T>()
498        .map_or(serde_json::Value::Null, Model::to_json)
499}
500
501fn from_json_of<T: Model>(
502    _: &ModelTable,
503    value: &serde_json::Value,
504    out: &mut dyn Any,
505) -> Result<(), ModelError> {
506    put(out, T::from_json(value)?)
507}
508
509fn load_of<T: Model>(
510    _: &ModelTable,
511    doc: &Doc,
512    value: &Value<'_>,
513    id: &ObjId,
514    out: &mut dyn Any,
515) -> Result<(), ModelError> {
516    put(out, T::load(doc, value, id)?)
517}
518
519fn missing_of<T: Model>(_: &ModelTable, out: &mut dyn Any) -> Result<(), ModelError> {
520    put(out, T::missing()?)
521}
522
523fn reload_of<T: Model>(
524    _: &ModelTable,
525    target: &mut dyn Any,
526    doc: &Doc,
527    slot: Option<(&Value<'_>, &ObjId)>,
528) -> Result<(), ModelError> {
529    let Some(target) = target.downcast_mut::<T>() else {
530        return Err(mismatch());
531    };
532    *target = match slot {
533        Some((value, id)) => T::load(doc, value, id)?,
534        None => T::missing()?,
535    };
536    Ok(())
537}
538
539fn store_of<T: Model>(
540    _: &ModelTable,
541    value: &dyn Any,
542    doc: &mut Doc,
543    slot: Slot<'_>,
544) -> Result<(), ModelError> {
545    match value.downcast_ref::<T>() {
546        Some(value) => value.store(doc, slot),
547        None => Err(mismatch()),
548    }
549}
550
551fn stores_as_of<T: Model>(_: &ModelTable, value: &dyn Any, before: &dyn Any) -> bool {
552    match (value.downcast_ref::<T>(), before.downcast_ref::<T>()) {
553        (Some(value), Some(before)) => value.stores_as(before),
554        _ => false,
555    }
556}
557
558fn store_changed_of<T: Model>(
559    _: &ModelTable,
560    value: &dyn Any,
561    before: &dyn Any,
562    doc: &mut Doc,
563    slot: Slot<'_>,
564    dirty: &Delta,
565) -> Result<(), ModelError> {
566    match (value.downcast_ref::<T>(), before.downcast_ref::<T>()) {
567        (Some(value), Some(before)) => value.store_changed(before, doc, slot, dirty),
568        _ => Err(mismatch()),
569    }
570}
571
572fn refresh_of<T: Model>(
573    _: &ModelTable,
574    target: &mut dyn Any,
575    doc: &Doc,
576    value: &Value<'_>,
577    id: &ObjId,
578    delta: &Delta,
579) -> Result<(), ModelError> {
580    match target.downcast_mut::<T>() {
581        Some(target) => target.refresh(doc, value, id, delta),
582        None => Err(mismatch()),
583    }
584}
585
586fn read_whole_of<T: Model>(
587    _: &ModelTable,
588    target: &mut dyn Any,
589    doc: &Doc,
590) -> Result<(), ModelError> {
591    match target.downcast_mut::<T>() {
592        Some(target) => target.read_whole(doc),
593        None => Err(mismatch()),
594    }
595}
596
597fn edit_of<T: Model>(
598    _: &ModelTable,
599    doc: &mut Doc,
600    slot: Slot<'_>,
601    path: &[Segment],
602    op: &EditOp,
603    cx: &mut ActionCx,
604) -> Result<(), ModelError> {
605    T::edit(doc, slot, path, op, cx)
606}
607
608fn diff_of<T: Model>(
609    _: &ModelTable,
610    before: &dyn Any,
611    after: &dyn Any,
612    path: &[Segment],
613    out: &mut Vec<Edit<()>>,
614) {
615    if let (Some(before), Some(after)) = (before.downcast_ref::<T>(), after.downcast_ref::<T>()) {
616        before.diff(after, path, out);
617    }
618}
619
620fn collect_text_of<T: Model>(_: &ModelTable, value: &dyn Any, out: &mut Vec<String>) {
621    if let Some(value) = value.downcast_ref::<T>() {
622        value.collect_text(out);
623    }
624}
625
626fn check_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Result<(), Refusal> {
627    value.downcast_ref::<T>().map_or(Ok(()), Model::check)
628}
629
630#[allow(
631    clippy::unnecessary_wraps,
632    reason = "a table function: every type's check returns a result"
633)]
634fn no_check(_: &ModelTable, _: &dyn Any) -> Result<(), Refusal> {
635    Ok(())
636}
637
638fn label_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Option<String> {
639    value.downcast_ref::<T>()?.label()
640}
641
642fn nested_collections_of<T: Model>(_: &ModelTable, value: &dyn Any) -> Vec<ItemCollection> {
643    value
644        .downcast_ref::<T>()
645        .map_or_else(Vec::new, Model::nested_collections)
646}
647
648/// No label, no collections inside: what a value of a type with neither
649/// answers.
650pub(crate) fn no_label(_: &ModelTable, _: &dyn Any) -> Option<String> {
651    None
652}
653
654pub(crate) fn no_nested(_: &ModelTable, _: &dyn Any) -> Vec<ItemCollection> {
655    Vec::new()
656}
657
658fn get_at_of<'a, T: Model>(
659    _: &ModelTable,
660    value: &'a dyn Any,
661    path: &[Segment],
662) -> Option<&'a dyn Any> {
663    value.downcast_ref::<T>()?.get_at(path)
664}
665
666fn op_coalesces_of<T: Model>(
667    _: &ModelTable,
668    path: &[Segment],
669    previous: &serde_json::Value,
670    next: &serde_json::Value,
671) -> Option<bool> {
672    T::op_coalesces(path, previous, next)
673}
674
675fn no_coalesces(
676    _: &ModelTable,
677    _: &[Segment],
678    _: &serde_json::Value,
679    _: &serde_json::Value,
680) -> Option<bool> {
681    None
682}
683
684fn op_continuable_of<T: Model>(
685    _: &ModelTable,
686    path: &[Segment],
687    op: &serde_json::Value,
688) -> Option<bool> {
689    T::op_continuable(path, op)
690}
691
692fn no_continuable(_: &ModelTable, _: &[Segment], _: &serde_json::Value) -> Option<bool> {
693    None
694}
695
696fn op_describe_of<T: Model>(
697    _: &ModelTable,
698    path: &[Segment],
699    op: &serde_json::Value,
700) -> Option<OpDescription> {
701    T::op_describe(path, op)
702}
703
704fn no_describe(_: &ModelTable, _: &[Segment], _: &serde_json::Value) -> Option<OpDescription> {
705    None
706}
707
708fn op_lands_of<T: Model>(
709    _: &ModelTable,
710    value: &dyn Any,
711    path: &[Segment],
712    op: &serde_json::Value,
713) -> Option<Place> {
714    value.downcast_ref::<T>()?.op_lands(path, op)
715}
716
717fn no_lands(_: &ModelTable, _: &dyn Any, _: &[Segment], _: &serde_json::Value) -> Option<Place> {
718    None
719}
720
721fn op_schemas_of<T: Model>(
722    _: &ModelTable,
723    prefix: &str,
724    out: &mut Vec<(String, serde_json::Value)>,
725) {
726    T::op_schemas(prefix, out);
727}
728
729fn no_schemas(_: &ModelTable, _: &str, _: &mut Vec<(String, serde_json::Value)>) {}
730
731/// The [`ItemOps`] of a collection type.
732pub struct ItemOpsOf<C>(PhantomData<C>);
733
734impl<C: PublishedItems> ItemOpsOf<C> {
735    pub const OPS: ItemOps = ItemOps {
736        list: |value| Some(value.downcast_ref::<C>()? as &dyn crate::collection::ItemList),
737        item_table: C::ITEM_TABLE,
738        item_collection: item_collection_of::<C>,
739        item_presence: item_presence_of::<C>,
740        label_of_item: label_of_item_of::<C>,
741        item_texts: item_texts_of::<C>,
742        nested_items: nested_items_of::<C>,
743    };
744}
745
746fn item_collection_of<C: ItemSource + 'static>(
747    value: &dyn Any,
748    field: &'static str,
749) -> Option<ItemCollection> {
750    Some(value.downcast_ref::<C>()?.item_collection(field))
751}
752
753fn item_presence_of<C: ItemSource + 'static>(value: &dyn Any) -> usize {
754    value
755        .downcast_ref::<C>()
756        .map_or(0, ItemSource::item_presence)
757}
758
759fn label_of_item_of<C: ItemSource + 'static>(value: &dyn Any, id: &crate::Id) -> Option<String> {
760    value.downcast_ref::<C>()?.label_of_item(id)
761}
762
763fn item_texts_of<C: ItemSource + 'static>(
764    value: &dyn Any,
765    field: &'static str,
766    found: &mut Vec<ItemText>,
767) {
768    if let Some(value) = value.downcast_ref::<C>() {
769        value.item_texts(field, found);
770    }
771}
772
773fn nested_items_of<C: ItemSource + 'static>(
774    value: &dyn Any,
775    field: &'static str,
776    out: &mut Vec<ItemCollection>,
777) {
778    if let Some(value) = value.downcast_ref::<C>() {
779        value.nested_items(field, out);
780    }
781}
782
783/// The table of a `String` stored whole, last writer winning
784/// (`#[model(atom)]`): an id or a name two people setting at once must not
785/// interleave.
786pub static ATOM_STRING: ModelTable = ModelTable {
787    ops: &ATOM_STRING_OPS,
788    desc: Desc::Own,
789    checks: false,
790    has_ops: false,
791    scalar: true,
792};
793
794/// A type `#[model(atom)]` stores whole: one value, last writer wins, never
795/// merged part by part. A colour, a name from a list or an encoded path
796/// merged by character or element reads as no value at all.
797pub trait Atomic: Model {
798    /// The table the field is stored by.
799    const ATOM: &'static ModelTable;
800}
801
802impl Atomic for String {
803    const ATOM: &'static ModelTable = &ATOM_STRING;
804}
805
806/// `None` is an absent key, as for any `Option`; a present value is stored
807/// whole.
808impl<T: Atomic> Atomic for Option<T> {
809    const ATOM: &'static ModelTable = &AtomOptionOf::<T>::TABLE;
810}
811
812/// The table of an optional atom.
813struct AtomOptionOf<T>(PhantomData<T>);
814
815impl<T: Atomic> AtomOptionOf<T> {
816    const DESC: OptionDesc = OptionDesc {
817        inner: T::ATOM,
818        get: option_get::<T>,
819        get_mut: option_get_mut::<T>,
820        slot: option_slot::<T>,
821        clear: option_clear::<T>,
822        staged: (empty_of::<Option<T>>, unwrap_of::<Option<T>>),
823    };
824
825    const TABLE: ModelTable = ModelTable {
826        ops: &OPTION_OPS,
827        desc: Desc::Option(&Self::DESC),
828        checks: false,
829        has_ops: false,
830        scalar: true,
831    };
832}
833
834/// An id is one scalar already.
835impl Atomic for crate::Id {
836    const ATOM: &'static ModelTable = <Self as Model>::TABLE;
837}
838
839/// A list stored as one JSON text: a shape's points, not a list two people
840/// edit item by item.
841impl<T> Atomic for Vec<T>
842where
843    T: Model + serde::Serialize + serde::de::DeserializeOwned + PartialEq,
844{
845    const ATOM: &'static ModelTable = &ModelTable::of_json(&JsonOf::<Self>::COMPARED);
846}
847
848static ATOM_STRING_OPS: ModelOps = ModelOps {
849    without_absent: crate::shape::kept_whole,
850    to_json: atom_to_json,
851    from_json: atom_from_json,
852    load: atom_load,
853    missing: atom_missing,
854    reload: atom_reload,
855    store: atom_store,
856    fresh: |_, value, encoding| atom_of(value).map_or(Fresh::Store, |atom| atom.fresh(encoding)),
857    stores_as: atom_stores_as,
858    store_changed: atom_store_changed,
859    refresh: atom_refresh,
860    read_whole: atom_read_whole,
861    edit: atom_edit,
862    diff: atom_diff,
863    collect_text: atom_collect_text,
864    check: no_check,
865    get_at: atom_get_at,
866    label: no_label,
867    nested_collections: no_nested,
868    op_coalesces: no_coalesces,
869    op_continuable: no_continuable,
870    op_describe: no_describe,
871    op_lands: no_lands,
872    op_schemas: no_schemas,
873};
874
875fn atom_text(value: &dyn Any) -> Result<&String, ModelError> {
876    value.downcast_ref::<String>().ok_or_else(mismatch)
877}
878
879fn atom_of(value: &dyn Any) -> Result<crate::Atom, ModelError> {
880    Ok(crate::Atom(atom_text(value)?.clone()))
881}
882
883// What the record shows of the field is the `String`'s; what it stores is
884// the `Atom`'s.
885
886fn atom_to_json(_: &ModelTable, value: &dyn Any) -> serde_json::Value {
887    atom_text(value).map_or(serde_json::Value::Null, Model::to_json)
888}
889
890fn atom_from_json(
891    _: &ModelTable,
892    value: &serde_json::Value,
893    out: &mut dyn Any,
894) -> Result<(), ModelError> {
895    put(out, String::from_json(value)?)
896}
897
898fn atom_load(
899    _: &ModelTable,
900    doc: &Doc,
901    value: &Value<'_>,
902    id: &ObjId,
903    out: &mut dyn Any,
904) -> Result<(), ModelError> {
905    put(out, crate::Atom::load(doc, value, id)?.0)
906}
907
908fn atom_missing(_: &ModelTable, out: &mut dyn Any) -> Result<(), ModelError> {
909    put(out, crate::Atom::missing()?.0)
910}
911
912fn atom_reload(
913    _: &ModelTable,
914    target: &mut dyn Any,
915    doc: &Doc,
916    slot: Option<(&Value<'_>, &ObjId)>,
917) -> Result<(), ModelError> {
918    let Some(target) = target.downcast_mut::<String>() else {
919        return Err(mismatch());
920    };
921    *target = match slot {
922        Some((value, id)) => crate::Atom::load(doc, value, id)?.0,
923        None => crate::Atom::missing()?.0,
924    };
925    Ok(())
926}
927
928fn atom_store(
929    _: &ModelTable,
930    value: &dyn Any,
931    doc: &mut Doc,
932    slot: Slot<'_>,
933) -> Result<(), ModelError> {
934    atom_of(value)?.store(doc, slot)
935}
936
937fn atom_stores_as(_: &ModelTable, value: &dyn Any, before: &dyn Any) -> bool {
938    match (atom_of(value), atom_of(before)) {
939        (Ok(value), Ok(before)) => value.stores_as(&before),
940        _ => false,
941    }
942}
943
944fn atom_store_changed(
945    _: &ModelTable,
946    value: &dyn Any,
947    before: &dyn Any,
948    doc: &mut Doc,
949    slot: Slot<'_>,
950    dirty: &Delta,
951) -> Result<(), ModelError> {
952    atom_of(value)?.store_changed(&atom_of(before)?, doc, slot, dirty)
953}
954
955fn atom_refresh(
956    _: &ModelTable,
957    target: &mut dyn Any,
958    doc: &Doc,
959    value: &Value<'_>,
960    id: &ObjId,
961    delta: &Delta,
962) -> Result<(), ModelError> {
963    let Some(target) = target.downcast_mut::<String>() else {
964        return Err(mismatch());
965    };
966    let mut atom = crate::Atom(std::mem::take(target));
967    let refreshed = atom.refresh(doc, value, id, delta);
968    *target = atom.0;
969    refreshed
970}
971
972#[allow(
973    clippy::unnecessary_wraps,
974    reason = "a table function: reading whole may fail for other types"
975)]
976fn atom_read_whole(_: &ModelTable, _: &mut dyn Any, _: &Doc) -> Result<(), ModelError> {
977    Ok(())
978}
979
980fn atom_edit(
981    _: &ModelTable,
982    doc: &mut Doc,
983    slot: Slot<'_>,
984    path: &[Segment],
985    op: &EditOp,
986    cx: &mut ActionCx,
987) -> Result<(), ModelError> {
988    crate::Atom::edit(doc, slot, path, op, cx)
989}
990
991fn atom_diff(
992    _: &ModelTable,
993    before: &dyn Any,
994    after: &dyn Any,
995    path: &[Segment],
996    out: &mut Vec<Edit<()>>,
997) {
998    if let (Ok(before), Ok(after)) = (atom_text(before), atom_text(after)) {
999        before.diff(after, path, out);
1000    }
1001}
1002
1003fn atom_collect_text(_: &ModelTable, value: &dyn Any, out: &mut Vec<String>) {
1004    if let Ok(text) = atom_text(value) {
1005        text.collect_text(out);
1006    }
1007}
1008
1009fn atom_get_at<'a>(_: &ModelTable, value: &'a dyn Any, path: &[Segment]) -> Option<&'a dyn Any> {
1010    path.is_empty().then_some(value)
1011}
1012
1013/// The functions of every record, over its [`ResourceDesc`].
1014pub static RESOURCE_OPS: ModelOps = ModelOps {
1015    without_absent: crate::shape::resource_without_absent,
1016    to_json: |table, value| match table.record() {
1017        Some(record) => to_json(record, value),
1018        None => serde_json::Value::Null,
1019    },
1020    from_json: |table, value, out| from_json(described(table)?, value, out),
1021    load: |table, doc, value, id, out| load(described(table)?, doc, value, id, out),
1022    missing: |table, out| missing(described(table)?, out),
1023    reload: |table, target, doc, slot| reload(described(table)?, target, doc, slot),
1024    store: |table, value, doc, slot| store(described(table)?, value, doc, slot),
1025    fresh: fresh::fields_made,
1026    stores_as: |table, value, before| {
1027        table
1028            .record()
1029            .is_some_and(|record| stores_as(record, value, before))
1030    },
1031    store_changed: |table, value, before, doc, slot, dirty| {
1032        store_changed(described(table)?, value, before, doc, slot, dirty)
1033    },
1034    refresh: |table, target, doc, value, id, delta| {
1035        refresh(described(table)?, target, doc, value, id, delta)
1036    },
1037    read_whole: |_, _, _| Ok(()),
1038    edit: |table, doc, slot, path, op, cx| edit(described(table)?, doc, slot, path, op, cx),
1039    diff: |table, before, after, path, out| {
1040        if let Some(record) = table.record() {
1041            diff(record, before, after, path, out);
1042        }
1043    },
1044    collect_text: |table, value, out| {
1045        if let Some(record) = table.record() {
1046            collect_text(record, value, out);
1047        }
1048    },
1049    check: |table, value| match table.record() {
1050        Some(record) => check(record, value),
1051        None => Ok(()),
1052    },
1053    get_at: |table, value, path| get_at(table.record()?, value, path),
1054    label: |table, value| label(table.record()?, value),
1055    nested_collections: |table, value| {
1056        table
1057            .record()
1058            .map_or_else(Vec::new, |record| item_collections(record, value))
1059    },
1060    op_coalesces: |table, path, previous, next| op_coalesces(table.record()?, path, previous, next),
1061    op_continuable: |table, path, op| op_continuable(table.record()?, path, op),
1062    op_describe: |table, path, op| op_describe(table.record()?, path, op),
1063    op_lands: |table, value, path, op| op_lands(table.record()?, value, path, op),
1064    op_schemas: |table, prefix, out| {
1065        if let Some(record) = table.record() {
1066            op_schemas(record, prefix, out);
1067        }
1068    },
1069};
1070
1071impl ModelTable {
1072    /// The table of the record `record`.
1073    #[must_use]
1074    pub const fn of_resource(record: &'static ResourceDesc) -> Self {
1075        Self {
1076            ops: &RESOURCE_OPS,
1077            desc: Desc::Record(record),
1078            checks: record.checks,
1079            has_ops: record.has_ops,
1080            scalar: false,
1081        }
1082    }
1083}
1084
1085pub(super) fn described(table: &ModelTable) -> Result<&'static ResourceDesc, ModelError> {
1086    table.record().ok_or_else(mismatch)
1087}
1088
1089/// The value of the field at `index` of `record`.
1090pub(super) fn field_of<'a>(
1091    record: &ResourceDesc,
1092    value: &'a dyn Any,
1093    index: usize,
1094) -> Result<&'a dyn Any, ModelError> {
1095    (record.field)(value, index).ok_or_else(mismatch)
1096}
1097
1098/// The same, mutably.
1099fn field_of_mut<'a>(
1100    record: &ResourceDesc,
1101    value: &'a mut dyn Any,
1102    index: usize,
1103) -> Result<&'a mut dyn Any, ModelError> {
1104    (record.field_mut)(value, index).ok_or_else(mismatch)
1105}
1106
1107/// [`Model::to_json`] of a record.
1108#[must_use]
1109pub fn to_json(record: &ResourceDesc, value: &dyn Any) -> serde_json::Value {
1110    let mut fields = serde_json::Map::new();
1111    for (index, field) in record.fields.iter().enumerate() {
1112        if let Some(inner) = (record.field)(value, index) {
1113            fields.insert(
1114                field.key.to_owned(),
1115                (field.table.ops.to_json)(field.table, inner),
1116            );
1117        }
1118    }
1119    serde_json::Value::Object(fields)
1120}
1121
1122/// Fields read from a record's JSON form.
1123struct JsonSource<'a> {
1124    record: &'a ResourceDesc,
1125    fields: &'a serde_json::Map<String, serde_json::Value>,
1126    index: usize,
1127}
1128
1129impl FieldSource for JsonSource<'_> {
1130    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
1131        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
1132        match self.fields.get(field.key) {
1133            Some(value) => (field.table.ops.from_json)(field.table, value, out),
1134            None => (field.table.ops.missing)(field.table, out),
1135        }
1136        .located(field.key)
1137    }
1138
1139    fn read(&mut self, _: &mut dyn Any) -> Result<(), ModelError> {
1140        self.index = self.index.saturating_add(1);
1141        Ok(())
1142    }
1143}
1144
1145/// The missing value of each field of a record.
1146struct MissingSource<'a> {
1147    record: &'a ResourceDesc,
1148    index: usize,
1149}
1150
1151impl FieldSource for MissingSource<'_> {
1152    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
1153        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
1154        (field.table.ops.missing)(field.table, out).located(field.key)
1155    }
1156
1157    fn read(&mut self, _: &mut dyn Any) -> Result<(), ModelError> {
1158        self.index = self.index.saturating_add(1);
1159        Ok(())
1160    }
1161}
1162
1163/// Fields read from what each key of a record's map holds.
1164struct DocSource<'a> {
1165    record: &'a ResourceDesc,
1166    doc: &'a Doc,
1167    slots: Vec<crate::model::MapSlot>,
1168    index: usize,
1169}
1170
1171impl FieldSource for DocSource<'_> {
1172    fn next(&mut self, out: &mut dyn Any) -> Result<(), ModelError> {
1173        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
1174        match crate::model::take_slot(&mut self.slots, self.index) {
1175            Some((value, id)) if !skipped(field) => {
1176                // What reading a demanded field costs is what a view asked for: counted, so a
1177                // test holds a list of thousands to reading none of them.
1178                let _phase = field
1179                    .demanded
1180                    .then(|| crate::profiling::Phase::start("resource.read_demanded"));
1181                (field.table.ops.load)(field.table, self.doc, &value, &id, out)
1182            }
1183            _ => (field.table.ops.missing)(field.table, out),
1184        }
1185        .located(field.key)
1186    }
1187
1188    fn read(&mut self, value: &mut dyn Any) -> Result<(), ModelError> {
1189        let field = self.record.fields.get(self.index).ok_or_else(mismatch)?;
1190        self.index = self.index.saturating_add(1);
1191        if field.whole && !skipped(field) {
1192            (field.table.ops.read_whole)(field.table, value, self.doc).located(field.key)?;
1193        }
1194        Ok(())
1195    }
1196}
1197
1198thread_local! {
1199    /// Whether what is read now is read for a view ([`for_view`]).
1200    static FOR_VIEW: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1201}
1202
1203/// Call `read` as a view's reader reads: every `#[model(demanded)]` field it
1204/// meets reads as its missing value, unread, until a view demands the item
1205/// holding it and the resource's [`load`](crate::Resource::load) reads that
1206/// item whole. A read outside it reads every field as stored.
1207pub fn for_view<T>(read: impl FnOnce() -> T) -> T {
1208    let before = FOR_VIEW.with(|flag| flag.replace(true));
1209    let read = read();
1210    FOR_VIEW.with(|flag| flag.set(before));
1211    read
1212}
1213
1214/// Call `read` reading every field as stored, inside a read for a view too:
1215/// what a resource's `load` reads of the items a view demands.
1216pub fn whole<T>(read: impl FnOnce() -> T) -> T {
1217    let before = FOR_VIEW.with(|flag| flag.replace(false));
1218    let read = read();
1219    FOR_VIEW.with(|flag| flag.set(before));
1220    read
1221}
1222
1223/// Whether `field` is left unread here: a demanded one, read for a view.
1224fn skipped(field: &FieldDesc) -> bool {
1225    field.demanded && FOR_VIEW.with(std::cell::Cell::get)
1226}
1227
1228/// Whether a value of `table` holds a `#[model(demanded)]` field anywhere
1229/// (in its fields, their collections' items, and theirs): whether what a
1230/// view's reader holds of it may be less than the document holds.
1231#[must_use]
1232pub fn reads_on_demand(table: &ModelTable) -> bool {
1233    fn walk(table: &ModelTable, depth: usize) -> bool {
1234        if depth > 16 {
1235            return false;
1236        }
1237        if let Some(desc) = table.collection() {
1238            return walk(desc.item(), depth.saturating_add(1));
1239        }
1240        described(table).is_ok_and(|desc| {
1241            desc.fields
1242                .iter()
1243                .any(|field| field.demanded || walk(field.table, depth.saturating_add(1)))
1244        })
1245    }
1246    walk(table, 0)
1247}
1248
1249/// [`Model::from_json`] of a record, put into `out`.
1250///
1251/// # Errors
1252/// Why `value` is not the record's JSON form.
1253pub fn from_json(
1254    record: &ResourceDesc,
1255    value: &serde_json::Value,
1256    out: &mut dyn Any,
1257) -> Result<(), ModelError> {
1258    match value {
1259        serde_json::Value::Object(fields) => (record.build)(
1260            &mut JsonSource {
1261                record,
1262                fields,
1263                index: 0,
1264            },
1265            out,
1266        ),
1267        serde_json::Value::Null => missing(record, out),
1268        _ => Err(ModelError::shape("an object")),
1269    }
1270}
1271
1272/// [`Model::missing`] of a record, put into `out`.
1273pub fn missing(record: &ResourceDesc, out: &mut dyn Any) -> Result<(), ModelError> {
1274    (record.build)(&mut MissingSource { record, index: 0 }, out)
1275}
1276
1277/// [`Model::load`] of a record, put into `out`.
1278pub fn load(
1279    record: &ResourceDesc,
1280    doc: &Doc,
1281    value: &Value<'_>,
1282    id: &ObjId,
1283    out: &mut dyn Any,
1284) -> Result<(), ModelError> {
1285    match value {
1286        Value::Object(ObjType::Map) => read_fields(record, doc, id, out),
1287        _ => Err(ModelError::shape("a map")),
1288    }
1289}
1290
1291/// [`Fields::read_fields`](crate::Fields::read_fields), put into `out`:
1292/// every stored field read in one walk of the map.
1293pub fn read_fields(
1294    record: &ResourceDesc,
1295    doc: &Doc,
1296    obj: &ObjId,
1297    out: &mut dyn Any,
1298) -> Result<(), ModelError> {
1299    read_fields_over(record, doc, std::slice::from_ref(obj), out)
1300}
1301
1302/// Read the record from the maps `objs`, field by field: each field from
1303/// the first map that holds it. Two replicas that made the same item
1304/// concurrently each made a map for it, and the document keeps both under
1305/// one key; this reads them as one item, so a field only the losing map
1306/// holds is not lost.
1307pub(crate) fn read_fields_merged(
1308    record: &ResourceDesc,
1309    doc: &Doc,
1310    objs: &[ObjId],
1311    out: &mut dyn Any,
1312) -> Result<(), ModelError> {
1313    read_fields_over(record, doc, objs, out)
1314}
1315
1316/// Read the record from `objs`, each field from the first map holding it.
1317fn read_fields_over(
1318    record: &ResourceDesc,
1319    doc: &Doc,
1320    objs: &[ObjId],
1321    out: &mut dyn Any,
1322) -> Result<(), ModelError> {
1323    let mut keys: Vec<&str> = Vec::with_capacity(record.fields.len());
1324    for field in record.fields {
1325        keys.push(field.key);
1326    }
1327    let mut slots: Vec<crate::model::MapSlot> = vec![None; keys.len()];
1328    let mut objs = objs.iter();
1329    if let Some(first) = objs.next() {
1330        crate::model::fill_slots(doc, first, &keys, &mut slots);
1331    }
1332    for obj in objs {
1333        let mut found = vec![None; keys.len()];
1334        crate::model::fill_slots(doc, obj, &keys, &mut found);
1335        for (slot, found) in slots.iter_mut().zip(found) {
1336            if slot.is_none() {
1337                *slot = found;
1338            }
1339        }
1340    }
1341    (record.build)(
1342        &mut DocSource {
1343            record,
1344            doc,
1345            slots,
1346            index: 0,
1347        },
1348        out,
1349    )
1350}
1351
1352fn reload(
1353    record: &ResourceDesc,
1354    target: &mut dyn Any,
1355    doc: &Doc,
1356    slot: Option<(&Value<'_>, &ObjId)>,
1357) -> Result<(), ModelError> {
1358    // A record is replaced by one read anew through its own table.
1359    let mut fresh = (record.empty)();
1360    if let Some((value, id)) = slot {
1361        load(record, doc, value, id, fresh.as_mut())?;
1362    } else {
1363        missing(record, fresh.as_mut())?;
1364    }
1365    (record.replace)(target, fresh.as_mut())
1366}
1367
1368/// [`Fields::write_fields`](crate::Fields::write_fields) of a record.
1369pub fn write_fields(
1370    desc: &ResourceDesc,
1371    value: &dyn Any,
1372    doc: &mut Doc,
1373    obj: &ObjId,
1374) -> Result<(), ModelError> {
1375    write_fields_leaving(desc, value, doc, obj)
1376}
1377
1378/// [`write_fields`], leaving out a scalar field that holds what its absent
1379/// key reads as ([`Model::missing`]) where the map does not hold its key: it
1380/// reads the same without a write.
1381fn write_fields_leaving(
1382    desc: &ResourceDesc,
1383    value: &dyn Any,
1384    doc: &mut Doc,
1385    obj: &ObjId,
1386) -> Result<(), ModelError> {
1387    let mut staged = (desc.empty)();
1388    let absent = missing(desc, staged.as_mut())
1389        .ok()
1390        .and_then(|()| (desc.unwrap)(staged.as_ref()));
1391    for (index, field) in desc.fields.iter().enumerate() {
1392        let inner = field_of(desc, value, index)?;
1393        if field.table.scalar
1394            && absent
1395                .and_then(|absent| (desc.field)(absent, index))
1396                .is_some_and(|empty| (field.table.ops.stores_as)(field.table, inner, empty))
1397            && Slot::Key(obj, field.key).current(doc)?.is_none()
1398        {
1399            continue;
1400        }
1401        (field.table.ops.store)(field.table, inner, doc, Slot::Key(obj, field.key))
1402            .located(field.key)?;
1403    }
1404    Ok(())
1405}
1406
1407/// [`Model::store`] of a record. One whose map is made now is made with
1408/// every field that can be at once ([`fresh_fields`]): twenty fields are
1409/// one batch, not twenty writes each looking up its key first.
1410pub fn store(
1411    desc: &ResourceDesc,
1412    value: &dyn Any,
1413    doc: &mut Doc,
1414    at: Slot<'_>,
1415) -> Result<(), ModelError> {
1416    if let Some((Value::Object(ObjType::Map), obj)) = at.current(doc)? {
1417        return write_fields_leaving(desc, value, doc, &obj);
1418    }
1419    fresh::store_made(desc, value, doc, at)
1420}
1421
1422/// [`Model::stores_as`] of a record.
1423#[must_use]
1424pub fn stores_as(desc: &ResourceDesc, value: &dyn Any, before: &dyn Any) -> bool {
1425    for (index, field) in desc.fields.iter().enumerate() {
1426        let (Some(now), Some(was)) = ((desc.field)(value, index), (desc.field)(before, index))
1427        else {
1428            return false;
1429        };
1430        if !(field.table.ops.stores_as)(field.table, now, was) {
1431            return false;
1432        }
1433    }
1434    true
1435}
1436
1437/// [`Fields::write_changed_fields`](crate::Fields::write_changed_fields) of
1438/// a record: each field written as `write_key_changed` writes it.
1439pub fn write_changed_fields(
1440    desc: &ResourceDesc,
1441    value: &dyn Any,
1442    before: &dyn Any,
1443    doc: &mut Doc,
1444    obj: &ObjId,
1445    dirty: &Delta,
1446) -> Result<(), ModelError> {
1447    for (index, field) in desc.fields.iter().enumerate() {
1448        let now = field_of(desc, value, index)?;
1449        let was = field_of(desc, before, index)?;
1450        write_key_changed(field.table, (now, was), doc, obj, field.key, dirty)?;
1451    }
1452    Ok(())
1453}
1454
1455/// Write `now` under `key` of the map `obj`, which holds `was`: what
1456/// [`crate::model::write_key_changed`] writes, through `table`.
1457///
1458/// # Errors
1459/// The document's write error, located at `key`.
1460pub(crate) fn write_key_changed(
1461    table: &ModelTable,
1462    (now, was): (&dyn Any, &dyn Any),
1463    doc: &mut Doc,
1464    obj: &ObjId,
1465    key: &str,
1466    dirty: &Delta,
1467) -> Result<(), ModelError> {
1468    let ops = table.ops;
1469    match dirty.key(obj, key) {
1470        Touch::Written => (ops.store)(table, now, doc, Slot::Key(obj, key)).located(key),
1471        Touch::Untouched if (ops.stores_as)(table, now, was) => Ok(()),
1472        Touch::Untouched | Touch::Below => {
1473            (ops.store_changed)(table, now, was, doc, Slot::Key(obj, key), dirty).located(key)
1474        }
1475    }
1476}
1477
1478/// [`Model::store_changed`] of a record.
1479pub fn store_changed(
1480    desc: &ResourceDesc,
1481    value: &dyn Any,
1482    before: &dyn Any,
1483    doc: &mut Doc,
1484    at: Slot<'_>,
1485    dirty: &Delta,
1486) -> Result<(), ModelError> {
1487    // A value whose map is gone (deleted by a change this one raced) is
1488    // written whole, as a whole write would: writing only the fields that
1489    // changed into a map made now would leave the others missing, an item
1490    // no replica can read.
1491    if !matches!(at.current(doc)?, Some((Value::Object(ObjType::Map), _))) {
1492        return store(desc, value, doc, at);
1493    }
1494    let obj = at.object(doc, ObjType::Map)?;
1495    write_changed_fields(desc, value, before, doc, &obj, dirty)
1496}
1497
1498/// [`Model::refresh`] of a record.
1499pub fn refresh(
1500    record: &ResourceDesc,
1501    target: &mut dyn Any,
1502    doc: &Doc,
1503    value: &Value<'_>,
1504    id: &ObjId,
1505    delta: &Delta,
1506) -> Result<(), ModelError> {
1507    match value {
1508        Value::Object(ObjType::Map) => refresh_fields(record, target, doc, id, delta),
1509        _ => Err(ModelError::shape("a map")),
1510    }
1511}
1512
1513/// [`Fields::refresh_fields`](crate::Fields::refresh_fields) of a record:
1514/// a map changed all over is read anew, else each touched field.
1515pub fn refresh_fields(
1516    record: &ResourceDesc,
1517    target: &mut dyn Any,
1518    doc: &Doc,
1519    obj: &ObjId,
1520    delta: &Delta,
1521) -> Result<(), ModelError> {
1522    if delta.under(obj).is_all() {
1523        let mut fresh = (record.empty)();
1524        read_fields(record, doc, obj, fresh.as_mut())?;
1525        return (record.replace)(target, fresh.as_mut());
1526    }
1527    for (index, field) in record.fields.iter().enumerate() {
1528        let inner = field_of_mut(record, target, index)?;
1529        refresh_key(field, inner, doc, obj, delta)?;
1530    }
1531    Ok(())
1532}
1533
1534/// Bring the field `field`, read earlier from the map `obj`, up to date
1535/// after `delta`: untouched keeps it, a written slot reads it again, a
1536/// change inside what it holds refreshes it in place.
1537fn refresh_key(
1538    field: &FieldDesc,
1539    target: &mut dyn Any,
1540    doc: &Doc,
1541    obj: &ObjId,
1542    delta: &Delta,
1543) -> Result<(), ModelError> {
1544    refresh_slot(field.table, target, doc, obj, field.key, delta)?;
1545    if field.whole {
1546        (field.table.ops.read_whole)(field.table, target, doc).located(field.key)?;
1547    }
1548    Ok(())
1549}
1550
1551/// Make `target`, a value of `table`'s type just stored whole under `key` of
1552/// the map `obj`, what reading it back gives. A value reads back as it was
1553/// written but for what holds operations ([`ModelTable::has_ops`]): rich text
1554/// reads back as the structure the document made of it. So of a struct's
1555/// fields only those are read again, from where they were written; any other
1556/// value holding operations is read again whole.
1557///
1558/// # Errors
1559/// Why what was written does not read.
1560pub(crate) fn settle(
1561    table: &ModelTable,
1562    target: &mut dyn Any,
1563    doc: &Doc,
1564    (obj, key): (&ObjId, &str),
1565) -> Result<(), ModelError> {
1566    if !table.has_ops {
1567        return Ok(());
1568    }
1569    let stored = automerge::ReadDoc::get(doc, obj, key)?;
1570    let (Ok(desc), Some((Value::Object(ObjType::Map), map))) = (described(table), &stored) else {
1571        let stored = stored.as_ref().map(|(value, id)| (value, id));
1572        return (table.ops.reload)(table, target, doc, stored);
1573    };
1574    for (index, field) in desc.fields.iter().enumerate() {
1575        if !field.table.has_ops {
1576            continue;
1577        }
1578        let inner = field_of_mut(desc, target, index)?;
1579        let written = automerge::ReadDoc::get(doc, map, field.key)
1580            .map_err(ModelError::from)
1581            .located(field.key)?;
1582        (field.table.ops.reload)(
1583            field.table,
1584            inner,
1585            doc,
1586            written.as_ref().map(|(value, id)| (value, id)),
1587        )
1588        .located(field.key)?;
1589        if field.whole {
1590            (field.table.ops.read_whole)(field.table, inner, doc).located(field.key)?;
1591        }
1592    }
1593    Ok(())
1594}
1595
1596/// Bring `target`, read earlier from `key` of the map `obj`, up to date
1597/// after `delta`, through `table`: what [`crate::model::refresh_key`] does.
1598///
1599/// # Errors
1600/// Why it does not read, located at `key`.
1601pub(crate) fn refresh_slot(
1602    table: &ModelTable,
1603    target: &mut dyn Any,
1604    doc: &Doc,
1605    obj: &ObjId,
1606    key: &str,
1607    delta: &Delta,
1608) -> Result<(), ModelError> {
1609    let ops = table.ops;
1610    match delta.key(obj, key) {
1611        Touch::Untouched => Ok(()),
1612        Touch::Written => {
1613            let slot = crate::model::get_slot(doc, obj, key).located(key)?;
1614            (ops.reload)(
1615                table,
1616                target,
1617                doc,
1618                slot.as_ref().map(|(value, id)| (value, id)),
1619            )
1620            .located(key)
1621        }
1622        Touch::Below => match crate::model::get_slot(doc, obj, key).located(key)? {
1623            Some((value, id)) => (ops.refresh)(table, target, doc, &value, &id, delta).located(key),
1624            None => (ops.reload)(table, target, doc, None).located(key),
1625        },
1626    }
1627}
1628
1629/// Put what `slot` holds into `out`, an `Option` of `table`'s type: its
1630/// value, or its missing value when it holds nothing.
1631pub(crate) fn load_slot(
1632    table: &ModelTable,
1633    doc: &Doc,
1634    slot: Option<(&Value<'_>, &ObjId)>,
1635    out: &mut dyn Any,
1636) -> Result<(), ModelError> {
1637    match slot {
1638        Some((value, id)) => (table.ops.load)(table, doc, value, id, out),
1639        None => (table.ops.missing)(table, out),
1640    }
1641}
1642
1643/// [`Model::edit`] of a record.
1644pub fn edit(
1645    record: &ResourceDesc,
1646    doc: &mut Doc,
1647    slot: Slot<'_>,
1648    path: &[Segment],
1649    op: &EditOp,
1650    cx: &mut ActionCx,
1651) -> Result<(), ModelError> {
1652    let obj = slot.object(doc, ObjType::Map)?;
1653    edit_fields(record, doc, &obj, path, op, cx)
1654}
1655
1656/// [`Fields::edit_fields`](crate::Fields::edit_fields) of a record: a field
1657/// segment routes the edit to its field; a `set` of the record replaces it
1658/// whole; the record's own check runs after.
1659pub fn edit_fields(
1660    record: &ResourceDesc,
1661    doc: &mut Doc,
1662    obj: &ObjId,
1663    path: &[Segment],
1664    op: &EditOp,
1665    cx: &mut ActionCx,
1666) -> Result<(), ModelError> {
1667    // Builds with debug assertions (tests, dev runs) check the record
1668    // whole after an edit its declared reads say cannot break it, so a
1669    // declaration that leaves out a field the check reads is caught.
1670    #[cfg(debug_assertions)]
1671    let unchecked_was_valid = skips_check(record, path).then(|| valid_at(record, doc, obj));
1672    match path.split_first() {
1673        Some((Segment::Field(key), rest)) => {
1674            let Some(field) = record.fields.iter().find(|field| field.key == key) else {
1675                let editable: Vec<&str> = record
1676                    .fields
1677                    .iter()
1678                    .filter(|field| !field.readonly)
1679                    .map(|field| field.key)
1680                    .collect();
1681                return Err(ModelError::invalid(format!(
1682                    "no field `{key}`; the fields here are {}",
1683                    editable.join(", ")
1684                )));
1685            };
1686            // The outside settling an outbox entry, or forgetting a settled
1687            // one, is no edit of the field's content: a read-only outbox
1688            // takes them. A reaction is always the invoker's own (the
1689            // `Reactions` it reaches stores who invoked it), so it cannot
1690            // forge anything a read-only field protects: a read-only
1691            // message takes its reactions. Only a `Reactions` value accepts
1692            // them; anything else refuses them as unsupported.
1693            if field.readonly
1694                && !matches!(
1695                    op,
1696                    EditOp::Settle { .. }
1697                        | EditOp::Forget { .. }
1698                        | EditOp::React { .. }
1699                        | EditOp::Unreact { .. }
1700                )
1701            {
1702                return Err(ModelError::Refused(format!(
1703                    "`{}` is changed only by the record's actions",
1704                    field.name
1705                )));
1706            }
1707            (field.table.ops.edit)(field.table, doc, Slot::Key(obj, field.key), rest, op, cx)
1708                .located(field.key)?;
1709        }
1710        None => match op {
1711            EditOp::Set { value } => {
1712                if record.fields.iter().any(|field| field.readonly) {
1713                    return Err(ModelError::Refused(String::from(
1714                        "a record with read-only fields is not replaced whole",
1715                    )));
1716                }
1717                let mut whole = (record.empty)();
1718                from_json(record, value, whole.as_mut())?;
1719                let whole = (record.unwrap)(whole.as_ref()).ok_or_else(mismatch)?;
1720                check(record, whole).map_err(ModelError::refused)?;
1721                write_fields(record, whole, doc, obj)?;
1722            }
1723            other => return Err(ModelError::unsupported(other)),
1724        },
1725        Some((segment, _)) => {
1726            return Err(ModelError::invalid(format!(
1727                "nothing in this record is called `{segment}`"
1728            )));
1729        }
1730    }
1731    if let Some(own) = &record.own_check
1732        && own
1733            .reads
1734            .as_ref()
1735            .is_none_or(|reads| reads.touched_by(path))
1736    {
1737        let checked = obj.clone();
1738        let (read, own_check) = (own.read, own.check);
1739        crate::group::check_or_defer(format!("{}@{:?}", (record.name)(), obj), doc, move |doc| {
1740            match read(doc, &checked) {
1741                Ok(current) => own_check(current.as_ref()),
1742                Err(error) => Err(Refusal::new(error.to_string())),
1743            }
1744        })
1745        .map_err(ModelError::refused)?;
1746    }
1747    #[cfg(debug_assertions)]
1748    if unchecked_was_valid == Some(true) {
1749        guard_declared_reads(record, doc, obj, path)?;
1750    }
1751    Ok(())
1752}
1753
1754/// Whether an edit at `path` skips `record`'s own check, by what the check
1755/// declares it reads.
1756#[cfg(debug_assertions)]
1757fn skips_check(record: &ResourceDesc, path: &[Segment]) -> bool {
1758    record
1759        .own_check
1760        .as_ref()
1761        .and_then(|own| own.reads.as_ref())
1762        .is_some_and(|reads| !reads.touched_by(path))
1763}
1764
1765/// Whether the record at `obj` passes its own check.
1766#[cfg(debug_assertions)]
1767fn valid_at(record: &ResourceDesc, doc: &Doc, obj: &ObjId) -> bool {
1768    record.own_check.as_ref().is_none_or(|own| {
1769        (own.read)(doc, obj).is_ok_and(|current| (own.check)(current.as_ref()).is_ok())
1770    })
1771}
1772
1773/// Check the record at `obj`, valid before an edit at `path` its declared
1774/// reads skip, once the edit (or its group) is done; a refusal means the
1775/// declaration leaves out a field the check reads.
1776#[cfg(debug_assertions)]
1777fn guard_declared_reads(
1778    record: &ResourceDesc,
1779    doc: &Doc,
1780    obj: &ObjId,
1781    path: &[Segment],
1782) -> Result<(), ModelError> {
1783    let Some(own) = &record.own_check else {
1784        return Ok(());
1785    };
1786    let (read, own_check, name) = (own.read, own.check, record.name);
1787    let at = path
1788        .iter()
1789        .map(ToString::to_string)
1790        .collect::<Vec<_>>()
1791        .join("/");
1792    let checked = obj.clone();
1793    crate::group::check_or_defer(format!("{}@{:?}#reads", name(), obj), doc, move |doc| {
1794        if let Ok(current) = read(doc, &checked)
1795            && let Err(refusal) = own_check(current.as_ref())
1796        {
1797            undeclared_read(name(), &at, &refusal);
1798        }
1799        Ok(())
1800    })
1801    .map_err(ModelError::refused)
1802}
1803
1804#[cfg(debug_assertions)]
1805#[allow(
1806    clippy::panic,
1807    reason = "a check that reads what it does not declare is a bug in the record's declaration, \
1808              which only builds with debug assertions look for"
1809)]
1810fn undeclared_read(name: &str, at: &str, refusal: &Refusal) -> ! {
1811    panic!(
1812        "`{name}`'s check refuses an edit at `{at}` ({refusal}), but its `check_reads` / \
1813         `check_items` say that edit cannot change what it reads: add the field it reads"
1814    )
1815}
1816
1817/// [`Model::check`] of a record: its own invariant, then its fields'.
1818pub fn check(record: &ResourceDesc, value: &dyn Any) -> Result<(), Refusal> {
1819    if !record.checks {
1820        return Ok(());
1821    }
1822    if let Some(own) = &record.own_check {
1823        (own.check)(value)?;
1824    }
1825    for (index, field) in record.fields.iter().enumerate() {
1826        if field.table.checks
1827            && let Some(inner) = (record.field)(value, index)
1828        {
1829            (field.table.ops.check)(field.table, inner)?;
1830        }
1831    }
1832    Ok(())
1833}
1834
1835/// The first non-empty line of the text the field at `index` carries.
1836fn first_line(record: &ResourceDesc, value: &dyn Any, index: usize) -> Option<String> {
1837    let field = record.fields.get(index)?;
1838    let inner = (record.field)(value, index)?;
1839    let mut text = Vec::new();
1840    (field.table.ops.collect_text)(field.table, inner, &mut text);
1841    crate::__private::first_line_of(text)
1842}
1843
1844/// [`Model::label`] of a record: what its `label = path` names it, else the
1845/// texts of its label fields joined by spaces, else its `#[model(label)]`
1846/// field.
1847#[must_use]
1848pub fn label(record: &ResourceDesc, value: &dyn Any) -> Option<String> {
1849    if let Some(name) = record.label_with {
1850        return name(value).filter(|label| !label.is_empty());
1851    }
1852    if !record.label_parts.is_empty() {
1853        let mut parts = Vec::new();
1854        for index in record.label_parts {
1855            if let Some(part) = first_line(record, value, *index) {
1856                parts.push(part);
1857            }
1858        }
1859        if !parts.is_empty() {
1860            return Some(parts.join(" "));
1861        }
1862    }
1863    first_line(record, value, record.label?)
1864}
1865
1866/// The field `key` of `record`, with `rest`, when `path` starts at a field
1867/// whose type has a vocabulary of its own.
1868fn ops_field<'p>(
1869    record: &ResourceDesc,
1870    path: &'p [Segment],
1871) -> Option<(usize, &'static FieldDesc, &'p [Segment])> {
1872    let Some((Segment::Field(key), rest)) = path.split_first() else {
1873        return None;
1874    };
1875    let (index, field) = record
1876        .fields
1877        .iter()
1878        .enumerate()
1879        .find(|(_, field)| field.key == key)?;
1880    field.table.has_ops.then_some((index, field, rest))
1881}
1882
1883/// [`Model::op_coalesces`] of a record.
1884#[must_use]
1885pub fn op_coalesces(
1886    record: &ResourceDesc,
1887    path: &[Segment],
1888    previous: &serde_json::Value,
1889    next: &serde_json::Value,
1890) -> Option<bool> {
1891    let (_, field, rest) = ops_field(record, path)?;
1892    (field.table.ops.op_coalesces)(field.table, rest, previous, next)
1893}
1894
1895/// [`Model::op_continuable`] of a record.
1896#[must_use]
1897pub fn op_continuable(
1898    record: &ResourceDesc,
1899    path: &[Segment],
1900    op: &serde_json::Value,
1901) -> Option<bool> {
1902    let (_, field, rest) = ops_field(record, path)?;
1903    (field.table.ops.op_continuable)(field.table, rest, op)
1904}
1905
1906/// [`Model::op_describe`] of a record.
1907#[must_use]
1908pub fn op_describe(
1909    record: &ResourceDesc,
1910    path: &[Segment],
1911    op: &serde_json::Value,
1912) -> Option<OpDescription> {
1913    let (_, field, rest) = ops_field(record, path)?;
1914    (field.table.ops.op_describe)(field.table, rest, op)
1915}
1916
1917/// [`Model::op_lands`] of a record.
1918#[must_use]
1919pub fn op_lands(
1920    record: &ResourceDesc,
1921    value: &dyn Any,
1922    path: &[Segment],
1923    op: &serde_json::Value,
1924) -> Option<Place> {
1925    let (index, field, rest) = ops_field(record, path)?;
1926    let inner = (record.field)(value, index)?;
1927    (field.table.ops.op_lands)(field.table, inner, rest, op)
1928}
1929
1930/// [`Model::op_schemas`] of a record: only a field whose type has a
1931/// vocabulary of its own is visited.
1932pub fn op_schemas(record: &ResourceDesc, prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
1933    // A type nested in itself has no vocabulary of its own deeper than
1934    // this.
1935    if prefix.matches('.').count() > 16 {
1936        return;
1937    }
1938    for field in record.fields {
1939        if field.table.has_ops {
1940            (field.table.ops.op_schemas)(field.table, &format!("{prefix}{}.", field.key), out);
1941        }
1942    }
1943}
1944
1945/// [`Model::get_at`] of a record.
1946#[must_use]
1947pub fn get_at<'a>(
1948    record: &ResourceDesc,
1949    value: &'a dyn Any,
1950    path: &[Segment],
1951) -> Option<&'a dyn Any> {
1952    match path.split_first() {
1953        None => Some(value),
1954        Some((Segment::Field(key), rest)) => {
1955            let (index, field) = record
1956                .fields
1957                .iter()
1958                .enumerate()
1959                .find(|(_, field)| field.key == key)?;
1960            let inner = (record.field)(value, index)?;
1961            (field.table.ops.get_at)(field.table, inner, rest)
1962        }
1963        Some(_) => None,
1964    }
1965}
1966
1967/// [`Model::collect_text`] of a record.
1968pub fn collect_text(record: &ResourceDesc, value: &dyn Any, out: &mut Vec<String>) {
1969    for (index, field) in record.fields.iter().enumerate() {
1970        if let Some(inner) = (record.field)(value, index) {
1971            (field.table.ops.collect_text)(field.table, inner, out);
1972        }
1973    }
1974}
1975
1976/// [`Model::diff`] of a record: each field that is not read-only, at its
1977/// key. A field that would store as it is ([`Model::stores_as`]) has
1978/// nothing to submit and is passed over, compared in memory: no path made
1979/// for it, nothing turned into JSON. The path of a field compared further
1980/// is made once, in one buffer.
1981pub fn diff(
1982    record: &ResourceDesc,
1983    before: &dyn Any,
1984    after: &dyn Any,
1985    path: &[Segment],
1986    out: &mut Vec<Edit<()>>,
1987) {
1988    let mut at: Vec<Segment> = Vec::new();
1989    for (index, field) in record.fields.iter().enumerate() {
1990        if field.readonly {
1991            continue;
1992        }
1993        let (Some(was), Some(now)) = ((record.field)(before, index), (record.field)(after, index))
1994        else {
1995            continue;
1996        };
1997        if (field.table.ops.stores_as)(field.table, now, was) {
1998            continue;
1999        }
2000        if at.is_empty() {
2001            at.reserve_exact(path.len().saturating_add(1));
2002            at.extend_from_slice(path);
2003        } else {
2004            at.truncate(path.len());
2005        }
2006        at.push(Segment::Field(field.key.to_owned()));
2007        (field.table.ops.diff)(field.table, was, now, &at, out);
2008    }
2009}
2010
2011/// [`Fields::item_collections`](crate::Fields::item_collections) of a
2012/// record: each collection field's first page, then the collections inside
2013/// their items.
2014#[must_use]
2015pub fn item_collections(record: &ResourceDesc, value: &dyn Any) -> Vec<ItemCollection> {
2016    let mut out = Vec::new();
2017    for (index, field) in record.fields.iter().enumerate() {
2018        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index))
2019            && let Some(collection) = (items.item_collection)(inner, field.name)
2020        {
2021            out.push(collection);
2022        }
2023    }
2024    for (index, field) in record.fields.iter().enumerate() {
2025        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index)) {
2026            (items.nested_items)(inner, field.name, &mut out);
2027        }
2028    }
2029    out
2030}
2031
2032/// Every item the record `table` names holds, by the collection field holding
2033/// it: the id and the label each item is offered under, in the order the
2034/// collection keeps them. Nothing is left out: [`item_collections`] is the
2035/// page a publication carries, which a record with thousands of items is not.
2036#[must_use]
2037pub fn resource_items(
2038    table: &'static ModelTable,
2039    record: &dyn Any,
2040) -> Vec<(&'static str, Vec<(crate::Id, String)>)> {
2041    let Some(desc) = table.record() else {
2042        return Vec::new();
2043    };
2044    let mut out = Vec::new();
2045    for (index, field) in desc.fields.iter().enumerate() {
2046        let Some(items) = field.items else {
2047            continue;
2048        };
2049        let Some(inner) = (desc.field)(record, index) else {
2050            continue;
2051        };
2052        let Some(list) = (items.list)(inner) else {
2053            continue;
2054        };
2055        let mut found = Vec::with_capacity(list.count());
2056        for at in 0..list.count() {
2057            let Some((id, _)) = list.item(at) else {
2058                continue;
2059            };
2060            let label = (items.label_of_item)(inner, &id).unwrap_or_else(|| id.as_str().to_owned());
2061            found.push((id, label));
2062        }
2063        out.push((field.name, found));
2064    }
2065    out
2066}
2067
2068/// The collection fields of published items a model of the table `table`
2069/// holds, by name: where an item's id (`<kind>/<field>/<item>`) may stand,
2070/// read from the table alone.
2071#[must_use]
2072pub fn item_fields(table: &'static ModelTable) -> Vec<&'static str> {
2073    table.record().map_or_else(Vec::new, |desc| {
2074        desc.fields
2075            .iter()
2076            .filter(|field| field.items.is_some())
2077            .map(|field| field.name)
2078            .collect()
2079    })
2080}
2081
2082/// [`Fields::item_collection_sizes`](crate::Fields::item_collection_sizes)
2083/// of a record.
2084#[must_use]
2085pub fn item_collection_sizes(record: &ResourceDesc, value: &dyn Any) -> Vec<(&'static str, usize)> {
2086    let mut out = Vec::new();
2087    for (index, field) in record.fields.iter().enumerate() {
2088        if let Some(items) = field.items {
2089            let presence = (record.field)(value, index).map_or(0, items.item_presence);
2090            out.push((field.name, presence));
2091        }
2092    }
2093    out
2094}
2095
2096/// [`Fields::item_label`](crate::Fields::item_label) of a record.
2097#[must_use]
2098pub fn item_label(
2099    record: &ResourceDesc,
2100    value: &dyn Any,
2101    name: &str,
2102    id: &crate::Id,
2103) -> Option<String> {
2104    let (index, field) = record
2105        .fields
2106        .iter()
2107        .enumerate()
2108        .find(|(_, field)| field.items.is_some() && field.name == name)?;
2109    let items = field.items?;
2110    (items.label_of_item)((record.field)(value, index)?, id)
2111}
2112
2113/// Resolve `reference` to an item of the collection field `name`.
2114///
2115/// A reference is the item's id, an address its app publishes it under
2116/// (`<kind>/<field>/<id>`, `<kind>.<field>:<id>`, or either form of a
2117/// nested item's), or the label its collection publishes it under — which
2118/// is what a person or an agent knows it by, or its number counting from 1
2119/// as the collection lists it. A reference naming none of the
2120/// collection's items is refused with the items there are, so a name that
2121/// was mistyped or renamed is never reported as an item that went away.
2122pub fn item_named(
2123    record: &ResourceDesc,
2124    value: &dyn Any,
2125    name: &str,
2126    reference: &str,
2127) -> Result<crate::Id, crate::Refusal> {
2128    item_named_as(record, value, name, None, reference)
2129}
2130
2131/// [`item_named`] in the words `what` names the items by — `("project or
2132/// area", "projects and areas")` where the field's own name is not what the
2133/// app calls them — the field's words when it is `None`.
2134pub fn item_named_as(
2135    record: &ResourceDesc,
2136    value: &dyn Any,
2137    name: &str,
2138    what: Option<(&str, &str)>,
2139    reference: &str,
2140) -> Result<crate::Id, crate::Refusal> {
2141    let many = tilo_actions::in_words(name);
2142    let one = tilo_actions::singular(&many);
2143    let (one, many) = what.unwrap_or((&one, &many));
2144    let Some((index, field)) = record
2145        .fields
2146        .iter()
2147        .enumerate()
2148        .find(|(_, field)| field.items.is_some() && field.name == name)
2149    else {
2150        return Err(crate::Refusal::new(format!("this record keeps no {name}")));
2151    };
2152    let asked = reference.trim();
2153    if asked.is_empty() {
2154        return Err(crate::Refusal::new(format!(
2155            "name the {one}, by its id or its name"
2156        )));
2157    }
2158    let Some(items) = field.items else {
2159        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
2160    };
2161    let Some(inner) = (record.field)(value, index) else {
2162        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
2163    };
2164    let Some(list) = (items.list)(inner) else {
2165        return Err(crate::Refusal::new(format!("this record keeps no {many}")));
2166    };
2167    // Its id first, then the item part of any address it is published under:
2168    // neither reads a label, so the common case — a caller that kept the id
2169    // — costs a scan of the ids alone.
2170    let by_id = |candidate: &str| {
2171        (0..list.count()).find_map(|at| {
2172            let (id, _) = list.item(at)?;
2173            (id.as_str() == candidate).then_some(id)
2174        })
2175    };
2176    if let Some(id) = by_id(asked) {
2177        return Ok(id);
2178    }
2179    for candidate in item_parts(asked) {
2180        if let Some(id) = by_id(&candidate) {
2181            return Ok(id);
2182        }
2183    }
2184    // Then the name the collection publishes it under, which is what a
2185    // person types.
2186    let named: Vec<(crate::Id, String)> = (0..list.count())
2187        .filter_map(|at| {
2188            let (id, item) = list.item(at)?;
2189            let label = crate::collection::label_of(items.item_table, &id, item);
2190            label.eq_ignore_ascii_case(asked).then_some((id, label))
2191        })
2192        .collect();
2193    match named.as_slice() {
2194        [(id, _)] => return Ok(id.clone()),
2195        [_, ..] => {
2196            let ids: Vec<&str> = named.iter().map(|(id, _)| id.as_str()).collect();
2197            return Err(crate::Refusal::new(format!(
2198                "more than one {one} is named {asked}; name it by its id: {}",
2199                ids.join(", ")
2200            )));
2201        }
2202        [] => {}
2203    }
2204    if let Ok(number) = asked.parse::<usize>() {
2205        return number
2206            .checked_sub(1)
2207            .and_then(|at| list.item(at))
2208            .map(|(id, _)| id)
2209            .ok_or_else(|| {
2210                crate::Refusal::new(format!(
2211                    "no {one} {number}: the {many} are numbered 1 to {}",
2212                    list.count()
2213                ))
2214            });
2215    }
2216    let listed: Vec<String> = (0..list.count())
2217        .filter_map(|at| {
2218            let (id, item) = list.item(at)?;
2219            Some(crate::collection::label_of(items.item_table, &id, item))
2220        })
2221        .collect();
2222    let shown: Vec<&str> = listed.iter().map(String::as_str).take(12).collect();
2223    let more = listed.len().saturating_sub(shown.len());
2224    let holds = if shown.is_empty() {
2225        "none yet".to_owned()
2226    } else if more > 0 {
2227        format!("{} and {more} more", shown.join(", "))
2228    } else {
2229        shown.join(", ")
2230    };
2231    Err(crate::Refusal::new(format!(
2232        "no {one} named {asked}; {many}: {holds}"
2233    )))
2234}
2235
2236/// Whether the collection field `name` holds the item `id`, counting one it
2237/// keeps out because it no longer reads: the check an action makes before it
2238/// resolves a reference, so one that already names the id costs a scan of the
2239/// ids alone.
2240#[must_use]
2241pub fn item_holds(record: &ResourceDesc, value: &dyn Any, name: &str, id: &str) -> bool {
2242    let Some((index, field)) = record
2243        .fields
2244        .iter()
2245        .enumerate()
2246        .find(|(_, field)| field.items.is_some() && field.name == name)
2247    else {
2248        return false;
2249    };
2250    let Some(items) = field.items else {
2251        return false;
2252    };
2253    let Some(inner) = (record.field)(value, index) else {
2254        return false;
2255    };
2256    (items.list)(inner).is_some_and(|list| {
2257        list.quarantines(id)
2258            || (0..list.count())
2259                .any(|at| list.item(at).is_some_and(|(held, _)| held.as_str() == id))
2260    })
2261}
2262
2263/// Whether `reference` is the id of an item of any of the record's
2264/// collections: an action that names one may hold it in a collection other
2265/// than the one its parameter is named after ([`item_named`]).
2266#[must_use]
2267pub fn item_id_any(record: &ResourceDesc, value: &dyn Any, reference: &str) -> bool {
2268    record
2269        .fields
2270        .iter()
2271        .enumerate()
2272        .filter_map(|(index, field)| Some((field.items?, (record.field)(value, index)?)))
2273        .any(|(items, inner)| {
2274            (items.list)(inner).is_some_and(|list| {
2275                (0..list.count()).any(|at| {
2276                    list.item(at)
2277                        .is_some_and(|(id, _)| id.as_str() == reference)
2278                })
2279            })
2280        })
2281}
2282
2283/// The item an address names, as written: the last segment of an item
2284/// resource id (`<kind>/<field>/<id>`, and the nested forms), or of an
2285/// item's stable address (`<kind>.<field>:<id>`), or the id an outline
2286/// writes after an item (`{#<id>}`).
2287fn item_parts(reference: &str) -> Vec<String> {
2288    let mut parts = Vec::new();
2289    if let Some(id) = reference
2290        .strip_prefix("{#")
2291        .and_then(|rest| rest.strip_suffix('}'))
2292    {
2293        parts.push(id.to_owned());
2294    }
2295    if let Some(last) = reference.rsplit('/').next()
2296        && last != reference
2297    {
2298        parts.push(last.to_owned());
2299    }
2300    if let Some(form) = tilo_actions::item_form_of(reference)
2301        && let Some(last) = form.rsplit('/').next()
2302    {
2303        parts.push(last.to_owned());
2304    }
2305    parts
2306}
2307
2308/// [`Fields::item_search`](crate::Fields::item_search) of a record.
2309#[must_use]
2310pub fn item_search(record: &ResourceDesc, value: &dyn Any) -> Vec<ItemText> {
2311    let mut found = Vec::new();
2312    for (index, field) in record.fields.iter().enumerate() {
2313        if let (Some(items), Some(inner)) = (field.items, (record.field)(value, index)) {
2314            (items.item_texts)(inner, field.name, &mut found);
2315        }
2316    }
2317    found
2318}
2319
2320/// [`Model::diff`] of a record into edits of the record `E`.
2321pub fn diff_into<E>(
2322    record: &ResourceDesc,
2323    before: &dyn Any,
2324    after: &dyn Any,
2325    path: &[Segment],
2326    out: &mut Vec<Edit<E>>,
2327) {
2328    let mut found = Vec::new();
2329    diff(record, before, after, path, &mut found);
2330    out.reserve(found.len());
2331    for edit in found {
2332        out.push(edit.retyped());
2333    }
2334}
2335
2336/// The value a record function put into `out`.
2337pub fn filled<T>(out: Option<T>) -> Result<T, ModelError> {
2338    match out {
2339        Some(value) => Ok(value),
2340        None => Err(mismatch()),
2341    }
2342}
2343
2344/// The value in a filled `Option` of its type.
2345pub(crate) type Unstage = for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>;
2346
2347/// [`Model::edit`] of a value edited only as a whole, through its table:
2348/// `set` at its own path, checked before it is written. `staged` is an empty
2349/// `Option` of the type, which `unstage` reads the value back out of.
2350pub(crate) fn edit_whole(
2351    table: &ModelTable,
2352    (staged, unstage): (Box<dyn Any>, Unstage),
2353    nullable: bool,
2354    doc: &mut Doc,
2355    slot: Slot<'_>,
2356    path: &[Segment],
2357    op: &EditOp,
2358) -> Result<(), ModelError> {
2359    if let Some(segment) = path.first() {
2360        return Err(ModelError::invalid(format!(
2361            "nothing inside this value is called `{segment}`"
2362        )));
2363    }
2364    match op {
2365        EditOp::Set { value } if value.is_null() && !nullable => Err(ModelError::invalid(
2366            "`null` is no value of this field: set a value of its type",
2367        )),
2368        EditOp::Set { value } => {
2369            let mut staged = staged;
2370            (table.ops.from_json)(table, value, staged.as_mut())?;
2371            let made = unstage(staged.as_ref()).ok_or_else(mismatch)?;
2372            (table.ops.check)(table, made).map_err(ModelError::refused)?;
2373            (table.ops.store)(table, made, doc, slot)
2374        }
2375        other => Err(ModelError::unsupported(other)),
2376    }
2377}
2378
2379/// What `Option<T>`'s table reaches into one with.
2380#[allow(
2381    clippy::type_complexity,
2382    reason = "each field reaches into the option one way"
2383)]
2384pub struct OptionDesc {
2385    /// `T`'s table.
2386    pub inner: &'static ModelTable,
2387    /// The present value of an option.
2388    pub get: for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>,
2389    /// The same, mutably.
2390    pub get_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Any>,
2391    /// Put an absent option into `out` (an `Option` of the option) and hand
2392    /// back that option, for `T`'s table to put a value into.
2393    pub slot: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Any>,
2394    /// Make an option absent.
2395    pub clear: fn(&mut dyn Any),
2396    /// An empty `Option` of the option, and the option in a filled one.
2397    pub staged: (
2398        fn() -> Box<dyn Any>,
2399        for<'a> fn(&'a dyn Any) -> Option<&'a dyn Any>,
2400    ),
2401}
2402
2403/// The [`OptionDesc`] of `Option<T>`.
2404pub struct OptionOf<T>(PhantomData<T>);
2405
2406impl<T: Model> OptionOf<T> {
2407    pub const DESC: OptionDesc = OptionDesc {
2408        inner: T::TABLE,
2409        get: option_get::<T>,
2410        get_mut: option_get_mut::<T>,
2411        slot: option_slot::<T>,
2412        clear: option_clear::<T>,
2413        staged: (empty_of::<Option<T>>, unwrap_of::<Option<T>>),
2414    };
2415
2416    /// `Option<T>`'s table.
2417    pub const TABLE: ModelTable = ModelTable {
2418        ops: &OPTION_OPS,
2419        desc: Desc::Option(&Self::DESC),
2420        checks: T::CHECKS,
2421        has_ops: T::OPS,
2422        scalar: T::SCALAR,
2423    };
2424}
2425
2426fn option_get<T: 'static>(value: &dyn Any) -> Option<&dyn Any> {
2427    match value.downcast_ref::<Option<T>>()? {
2428        Some(inner) => Some(inner),
2429        None => None,
2430    }
2431}
2432
2433fn option_get_mut<T: 'static>(value: &mut dyn Any) -> Option<&mut dyn Any> {
2434    match value.downcast_mut::<Option<T>>()? {
2435        Some(inner) => Some(inner),
2436        None => None,
2437    }
2438}
2439
2440fn option_slot<T: 'static>(out: &mut dyn Any) -> Option<&mut dyn Any> {
2441    let out = out.downcast_mut::<Option<Option<T>>>()?;
2442    Some(out.insert(None))
2443}
2444
2445fn option_clear<T: 'static>(value: &mut dyn Any) {
2446    if let Some(value) = value.downcast_mut::<Option<T>>() {
2447        *value = None;
2448    }
2449}
2450
2451fn optional(table: &ModelTable) -> Result<&'static OptionDesc, ModelError> {
2452    table.option().ok_or_else(mismatch)
2453}
2454
2455fn is_null(value: &Value<'_>) -> bool {
2456    matches!(value, Value::Scalar(scalar) if matches!(scalar.as_ref(), automerge::ScalarValue::Null))
2457}
2458
2459/// The functions of every `Option`: `None` is an absent key (or a null list
2460/// element).
2461pub static OPTION_OPS: ModelOps = ModelOps {
2462    without_absent: crate::shape::kept_whole,
2463    to_json: |table, value| match table.option() {
2464        Some(option) => match (option.get)(value) {
2465            Some(inner) => (option.inner.ops.to_json)(option.inner, inner),
2466            None => serde_json::Value::Null,
2467        },
2468        None => serde_json::Value::Null,
2469    },
2470    from_json: |table, value, out| {
2471        let option = optional(table)?;
2472        let slot = (option.slot)(out).ok_or_else(mismatch)?;
2473        if value.is_null() {
2474            return Ok(());
2475        }
2476        (option.inner.ops.from_json)(option.inner, value, slot)
2477    },
2478    load: |table, doc, value, id, out| {
2479        let option = optional(table)?;
2480        let slot = (option.slot)(out).ok_or_else(mismatch)?;
2481        if is_null(value) {
2482            return Ok(());
2483        }
2484        (option.inner.ops.load)(option.inner, doc, value, id, slot)
2485    },
2486    missing: |table, out| {
2487        let option = optional(table)?;
2488        (option.slot)(out).ok_or_else(mismatch)?;
2489        Ok(())
2490    },
2491    reload: |table, target, doc, slot| {
2492        let option = optional(table)?;
2493        match slot {
2494            Some((value, id)) if !is_null(value) => {
2495                // The option is itself where `T`'s table puts a value.
2496                (option.inner.ops.load)(option.inner, doc, value, id, target)
2497            }
2498            _ => {
2499                (option.clear)(target);
2500                Ok(())
2501            }
2502        }
2503    },
2504    store: |table, value, doc, slot| {
2505        let option = optional(table)?;
2506        match (option.get)(value) {
2507            Some(inner) => (option.inner.ops.store)(option.inner, inner, doc, slot),
2508            None => slot.remove(doc),
2509        }
2510    },
2511    fresh: |table, value, encoding| match table.option() {
2512        Some(option) => match (option.get)(value) {
2513            Some(inner) => (option.inner.ops.fresh)(option.inner, inner, encoding),
2514            None => Fresh::Nothing,
2515        },
2516        None => Fresh::Store,
2517    },
2518    stores_as: |table, value, before| {
2519        let Some(option) = table.option() else {
2520            return false;
2521        };
2522        match ((option.get)(value), (option.get)(before)) {
2523            (Some(value), Some(before)) => {
2524                (option.inner.ops.stores_as)(option.inner, value, before)
2525            }
2526            (None, None) => true,
2527            _ => false,
2528        }
2529    },
2530    store_changed: |table, value, before, doc, slot, dirty| {
2531        let option = optional(table)?;
2532        match ((option.get)(value), (option.get)(before)) {
2533            (Some(value), Some(before)) => {
2534                (option.inner.ops.store_changed)(option.inner, value, before, doc, slot, dirty)
2535            }
2536            _ => (OPTION_OPS.store)(table, value, doc, slot),
2537        }
2538    },
2539    refresh: |table, target, doc, value, id, delta| {
2540        let option = optional(table)?;
2541        if !is_null(value)
2542            && let Some(inner) = (option.get_mut)(target)
2543        {
2544            return (option.inner.ops.refresh)(option.inner, inner, doc, value, id, delta);
2545        }
2546        (OPTION_OPS.reload)(table, target, doc, Some((value, id)))
2547    },
2548    read_whole: |_, _, _| Ok(()),
2549    edit: |table, doc, slot, path, op, cx| {
2550        let option = optional(table)?;
2551        if path.is_empty() && matches!(op, EditOp::Set { .. }) {
2552            let staged = ((option.staged.0)(), option.staged.1);
2553            return edit_whole(table, staged, true, doc, slot, path, op);
2554        }
2555        match slot.current(doc)? {
2556            Some((value, _)) if !is_null(&value) => {
2557                (option.inner.ops.edit)(option.inner, doc, slot, path, op, cx)
2558            }
2559            _ => Err(ModelError::invalid("the value is absent")),
2560        }
2561    },
2562    diff: |table, before, after, path, out| {
2563        let Some(option) = table.option() else {
2564            return;
2565        };
2566        match ((option.get)(before), (option.get)(after)) {
2567            (Some(before), Some(after)) => {
2568                (option.inner.ops.diff)(option.inner, before, after, path, out);
2569            }
2570            (None, None) => {}
2571            _ => out.push(Edit::new(
2572                path.to_vec(),
2573                EditOp::Set {
2574                    value: (OPTION_OPS.to_json)(table, after),
2575                },
2576            )),
2577        }
2578    },
2579    collect_text: |table, value, out| {
2580        if let Some(option) = table.option()
2581            && let Some(inner) = (option.get)(value)
2582        {
2583            (option.inner.ops.collect_text)(option.inner, inner, out);
2584        }
2585    },
2586    check: |table, value| match table.option() {
2587        Some(option) => match (option.get)(value) {
2588            Some(inner) => (option.inner.ops.check)(option.inner, inner),
2589            None => Ok(()),
2590        },
2591        None => Ok(()),
2592    },
2593    get_at: |table, value, path| {
2594        if path.is_empty() {
2595            return Some(value);
2596        }
2597        let option = table.option()?;
2598        (option.inner.ops.get_at)(option.inner, (option.get)(value)?, path)
2599    },
2600    label: |table, value| {
2601        let option = table.option()?;
2602        (option.inner.ops.label)(option.inner, (option.get)(value)?)
2603    },
2604    nested_collections: no_nested,
2605    op_coalesces: |table, path, previous, next| {
2606        let option = table.option()?;
2607        (option.inner.ops.op_coalesces)(option.inner, path, previous, next)
2608    },
2609    op_continuable: |table, path, op| {
2610        let option = table.option()?;
2611        (option.inner.ops.op_continuable)(option.inner, path, op)
2612    },
2613    op_describe: |table, path, op| {
2614        let option = table.option()?;
2615        (option.inner.ops.op_describe)(option.inner, path, op)
2616    },
2617    op_lands: |table, value, path, op| {
2618        let option = table.option()?;
2619        (option.inner.ops.op_lands)(option.inner, (option.get)(value)?, path, op)
2620    },
2621    op_schemas: |table, prefix, out| {
2622        if let Some(option) = table.option() {
2623            (option.inner.ops.op_schemas)(option.inner, prefix, out);
2624        }
2625    },
2626};
2627
2628/// A value of a type whose table does the work ([`Model::to_json`] of an
2629/// `Option`, a `Collection`): the type's functions as the table runs them.
2630pub struct Run<'t>(pub &'t ModelTable);
2631
2632impl Run<'_> {
2633    #[must_use]
2634    pub fn to_json(&self, value: &dyn Any) -> serde_json::Value {
2635        (self.0.ops.to_json)(self.0, value)
2636    }
2637
2638    /// # Errors
2639    /// Why `value` is no JSON form of the type.
2640    pub fn from_json<T: 'static>(&self, value: &serde_json::Value) -> Result<T, ModelError> {
2641        let mut out: Option<T> = None;
2642        (self.0.ops.from_json)(self.0, value, &mut out)?;
2643        filled(out)
2644    }
2645
2646    pub fn load<T: 'static>(
2647        &self,
2648        doc: &Doc,
2649        value: &Value<'_>,
2650        id: &ObjId,
2651    ) -> Result<T, ModelError> {
2652        let mut out: Option<T> = None;
2653        (self.0.ops.load)(self.0, doc, value, id, &mut out)?;
2654        filled(out)
2655    }
2656
2657    pub fn missing<T: 'static>(&self) -> Result<T, ModelError> {
2658        let mut out: Option<T> = None;
2659        (self.0.ops.missing)(self.0, &mut out)?;
2660        filled(out)
2661    }
2662
2663    pub fn store(&self, value: &dyn Any, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2664        (self.0.ops.store)(self.0, value, doc, slot)
2665    }
2666
2667    #[must_use]
2668    pub fn stores_as(&self, value: &dyn Any, before: &dyn Any) -> bool {
2669        (self.0.ops.stores_as)(self.0, value, before)
2670    }
2671
2672    pub fn store_changed(
2673        &self,
2674        value: &dyn Any,
2675        before: &dyn Any,
2676        doc: &mut Doc,
2677        slot: Slot<'_>,
2678        dirty: &Delta,
2679    ) -> Result<(), ModelError> {
2680        (self.0.ops.store_changed)(self.0, value, before, doc, slot, dirty)
2681    }
2682
2683    pub fn refresh(
2684        &self,
2685        target: &mut dyn Any,
2686        doc: &Doc,
2687        value: &Value<'_>,
2688        id: &ObjId,
2689        delta: &Delta,
2690    ) -> Result<(), ModelError> {
2691        (self.0.ops.refresh)(self.0, target, doc, value, id, delta)
2692    }
2693
2694    pub fn edit(
2695        &self,
2696        doc: &mut Doc,
2697        slot: Slot<'_>,
2698        path: &[Segment],
2699        op: &EditOp,
2700        cx: &mut ActionCx,
2701    ) -> Result<(), ModelError> {
2702        (self.0.ops.edit)(self.0, doc, slot, path, op, cx)
2703    }
2704
2705    pub fn diff<E>(
2706        &self,
2707        before: &dyn Any,
2708        after: &dyn Any,
2709        path: &[Segment],
2710        out: &mut Vec<Edit<E>>,
2711    ) {
2712        let mut found = Vec::new();
2713        (self.0.ops.diff)(self.0, before, after, path, &mut found);
2714        out.reserve(found.len());
2715        for edit in found {
2716            out.push(edit.retyped());
2717        }
2718    }
2719
2720    pub fn collect_text(&self, value: &dyn Any, out: &mut Vec<String>) {
2721        (self.0.ops.collect_text)(self.0, value, out);
2722    }
2723
2724    pub fn check(&self, value: &dyn Any) -> Result<(), Refusal> {
2725        (self.0.ops.check)(self.0, value)
2726    }
2727
2728    #[must_use]
2729    pub fn get_at<'a>(&self, value: &'a dyn Any, path: &[Segment]) -> Option<&'a dyn Any> {
2730        (self.0.ops.get_at)(self.0, value, path)
2731    }
2732
2733    #[must_use]
2734    pub fn op_coalesces(
2735        &self,
2736        path: &[Segment],
2737        previous: &serde_json::Value,
2738        next: &serde_json::Value,
2739    ) -> Option<bool> {
2740        (self.0.ops.op_coalesces)(self.0, path, previous, next)
2741    }
2742
2743    #[must_use]
2744    pub fn op_continuable(&self, path: &[Segment], op: &serde_json::Value) -> Option<bool> {
2745        (self.0.ops.op_continuable)(self.0, path, op)
2746    }
2747
2748    #[must_use]
2749    pub fn op_describe(&self, path: &[Segment], op: &serde_json::Value) -> Option<OpDescription> {
2750        (self.0.ops.op_describe)(self.0, path, op)
2751    }
2752
2753    #[must_use]
2754    pub fn op_lands(
2755        &self,
2756        value: &dyn Any,
2757        path: &[Segment],
2758        op: &serde_json::Value,
2759    ) -> Option<Place> {
2760        (self.0.ops.op_lands)(self.0, value, path, op)
2761    }
2762
2763    pub fn op_schemas(&self, prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
2764        (self.0.ops.op_schemas)(self.0, prefix, out);
2765    }
2766}
2767
2768/// A `#[derive(Model)]` enum of unit variants, each stored as its name.
2769pub struct UnitDesc {
2770    /// The variants' stored names, in declaration order.
2771    pub names: &'static [&'static str],
2772    /// The names the variants have in a value's JSON form (serde's), in
2773    /// declaration order: a caller reads and writes these, while the
2774    /// document keeps the stored one.
2775    pub wire: &'static [&'static str],
2776    /// The `#[default]` variant's position.
2777    pub default: Option<usize>,
2778    /// The position of a value's variant.
2779    pub index: fn(&dyn Any) -> Option<usize>,
2780    /// Put the variant at a position into `out`, an `Option` of the enum.
2781    pub make: fn(usize, &mut dyn Any) -> Result<(), ModelError>,
2782    /// Set a value to the variant at a position.
2783    pub set: fn(usize, &mut dyn Any) -> Result<(), ModelError>,
2784    /// An empty `Option` of the enum and the enum in a filled one.
2785    pub staged: (fn() -> Box<dyn Any>, Unstage),
2786}
2787
2788impl ModelTable {
2789    /// The table of an enum of unit variants.
2790    #[must_use]
2791    pub const fn of_unit(unit: &'static UnitDesc) -> Self {
2792        Self {
2793            ops: &UNIT_OPS,
2794            desc: Desc::Unit(unit),
2795            checks: false,
2796            has_ops: false,
2797            scalar: true,
2798        }
2799    }
2800
2801    const fn unit(&self) -> Option<&'static UnitDesc> {
2802        match self.desc {
2803            Desc::Unit(unit) => Some(unit),
2804            _ => None,
2805        }
2806    }
2807}
2808
2809fn units(table: &ModelTable) -> Result<&'static UnitDesc, ModelError> {
2810    table.unit().ok_or_else(mismatch)
2811}
2812
2813/// The stored name of `value`'s variant.
2814fn unit_name(table: &ModelTable, value: &dyn Any) -> Option<&'static str> {
2815    let unit = table.unit()?;
2816    unit.names.get((unit.index)(value)?).copied()
2817}
2818
2819/// The name `value`'s variant has in a value's JSON form.
2820fn unit_wire_name(table: &ModelTable, value: &dyn Any) -> Option<&'static str> {
2821    let unit = table.unit()?;
2822    unit.wire.get((unit.index)(value)?).copied()
2823}
2824
2825/// The position of the variant stored as `text`.
2826fn unit_named(unit: &UnitDesc, text: &str) -> Result<usize, ModelError> {
2827    unit.names
2828        .iter()
2829        .position(|name| *name == text)
2830        .ok_or_else(|| ModelError::invalid(format!("unknown variant `{text}`")))
2831}
2832
2833/// The position of the variant whose JSON form is `text`.
2834fn unit_wire_named(unit: &UnitDesc, text: &str) -> Result<usize, ModelError> {
2835    unit.wire
2836        .iter()
2837        .position(|name| *name == text)
2838        .ok_or_else(|| ModelError::invalid(format!("unknown variant `{text}`")))
2839}
2840
2841/// [`Model::value_schema`] of an enum of the variants `names`.
2842#[must_use]
2843pub fn unit_schema(names: &[&str]) -> serde_json::Value {
2844    serde_json::json!({"type": "string", "enum": names})
2845}
2846
2847/// The functions of every enum of unit variants.
2848pub static UNIT_OPS: ModelOps = ModelOps {
2849    without_absent: crate::shape::kept_whole,
2850    to_json: |table, value| {
2851        unit_wire_name(table, value).map_or(serde_json::Value::Null, |name| {
2852            serde_json::Value::String(name.to_owned())
2853        })
2854    },
2855    from_json: |table, value, out| {
2856        let unit = units(table)?;
2857        match value {
2858            serde_json::Value::String(text) => (unit.make)(unit_wire_named(unit, text)?, out),
2859            serde_json::Value::Null => (UNIT_OPS.missing)(table, out),
2860            _ => Err(ModelError::shape("a variant name")),
2861        }
2862    },
2863    load: |table, doc, value, id, out| {
2864        let unit = units(table)?;
2865        let crate::Atom(text) = crate::Atom::load(doc, value, id)?;
2866        (unit.make)(unit_named(unit, &text)?, out)
2867    },
2868    missing: |table, out| {
2869        let unit = units(table)?;
2870        match unit.default {
2871            Some(default) => (unit.make)(default, out),
2872            None => Err(ModelError::Missing {
2873                path: String::new(),
2874            }),
2875        }
2876    },
2877    reload: |table, target, doc, slot| {
2878        let unit = units(table)?;
2879        let index = match slot {
2880            Some((value, id)) => {
2881                let crate::Atom(text) = crate::Atom::load(doc, value, id)?;
2882                unit_named(unit, &text)?
2883            }
2884            None => unit.default.ok_or_else(|| ModelError::Missing {
2885                path: String::new(),
2886            })?,
2887        };
2888        (unit.set)(index, target)
2889    },
2890    store: |table, value, doc, slot| {
2891        let name = unit_name(table, value).ok_or_else(mismatch)?;
2892        slot.put_scalar(doc, automerge::ScalarValue::Str(name.into()))
2893    },
2894    fresh: |table, value, _| {
2895        unit_name(table, value).map_or(Fresh::Store, |name| {
2896            Fresh::scalar(automerge::ScalarValue::Str(name.into()))
2897        })
2898    },
2899    stores_as: |table, value, before| {
2900        table.unit().is_some_and(|unit| {
2901            (unit.index)(value).is_some() && (unit.index)(value) == (unit.index)(before)
2902        })
2903    },
2904    store_changed: |table, value, _, doc, slot, _| (UNIT_OPS.store)(table, value, doc, slot),
2905    refresh: |table, target, doc, value, id, _| {
2906        (UNIT_OPS.reload)(table, target, doc, Some((value, id)))
2907    },
2908    read_whole: |_, _, _| Ok(()),
2909    edit: |table, doc, slot, path, op, _| {
2910        let unit = units(table)?;
2911        edit_whole(
2912            table,
2913            ((unit.staged.0)(), unit.staged.1),
2914            false,
2915            doc,
2916            slot,
2917            path,
2918            op,
2919        )
2920    },
2921    diff: |table, before, after, path, out| {
2922        let value = (UNIT_OPS.to_json)(table, after);
2923        if (UNIT_OPS.to_json)(table, before) != value {
2924            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
2925        }
2926    },
2927    collect_text: |table, value, out| {
2928        // The case the surface shows, not the token a value's JSON form spells.
2929        if let Some(name) = unit_wire_name(table, value) {
2930            out.push(tilo_actions::field_type::label_of(name));
2931        }
2932    },
2933    check: |_, _| Ok(()),
2934    get_at: |_, value, path| path.is_empty().then_some(value),
2935    label: no_label,
2936    nested_collections: no_nested,
2937    op_coalesces: no_coalesces,
2938    op_continuable: no_continuable,
2939    op_describe: no_describe,
2940    op_lands: no_lands,
2941    op_schemas: no_schemas,
2942};
2943
2944/// Put `variant` into `out`, an `Option` of its enum.
2945///
2946/// # Errors
2947/// When there is no such variant or `out` is of another type.
2948pub fn put_variant<T: 'static>(variant: Option<T>, out: &mut dyn Any) -> Result<(), ModelError> {
2949    put(out, variant.ok_or_else(mismatch)?)
2950}
2951
2952/// Set `target` to `variant`.
2953///
2954/// # Errors
2955/// When there is no such variant or `target` is of another type.
2956pub fn set_variant<T: 'static>(variant: Option<T>, target: &mut dyn Any) -> Result<(), ModelError> {
2957    *target.downcast_mut::<T>().ok_or_else(mismatch)? = variant.ok_or_else(mismatch)?;
2958    Ok(())
2959}
2960
2961/// A type stored whole through its serde form: as one JSON string, last
2962/// writer winning ([`json_model!`](crate::json_model)), or as that form's
2963/// maps, lists and scalars ([`value_model!`](crate::value_model)).
2964#[allow(
2965    clippy::type_complexity,
2966    reason = "each field converts the value one way"
2967)]
2968pub struct JsonDesc {
2969    /// The value's JSON form.
2970    pub to_value: fn(&dyn Any) -> serde_json::Value,
2971    /// The value's JSON form, or why it has none: what its stored text is
2972    /// written from (`json_text`).
2973    pub try_value: fn(&dyn Any) -> Result<serde_json::Value, ModelError>,
2974    /// The value serialised, as compact JSON text: equal texts are equal
2975    /// JSON forms, so two values compare without building either form.
2976    pub bytes: fn(&dyn Any) -> Option<Vec<u8>>,
2977    /// Whether two values are equal in memory, for a type whose equal values
2978    /// have equal JSON forms (a derived `PartialEq`): a diff passes over an
2979    /// equal pair without serialising either. `None` when the type has no
2980    /// such equality; unequal values are still compared by their forms.
2981    pub equal: Option<fn(&dyn Any, &dyn Any) -> bool>,
2982    /// Put the value of a JSON form into `out`, an `Option` of the type. The
2983    /// stored text is read through it too (`json_text`).
2984    pub from_value: fn(&serde_json::Value, &mut dyn Any) -> Result<(), ModelError>,
2985    /// Put the type's default into `out`.
2986    pub default: fn(&mut dyn Any) -> Result<(), ModelError>,
2987    /// `null` reads as the default rather than through serde.
2988    pub null_default: bool,
2989    /// Stored as its JSON form's maps, lists and scalars
2990    /// ([`value_model!`](crate::value_model)) rather than as JSON text.
2991    pub structural: bool,
2992    /// An empty `Option` of the type, the value in a filled one, and moving
2993    /// it out over another.
2994    pub staged: (fn() -> Box<dyn Any>, Unstage),
2995    pub replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
2996}
2997
2998impl ModelTable {
2999    /// The table of a type stored as JSON text.
3000    #[must_use]
3001    pub const fn of_json(json: &'static JsonDesc) -> Self {
3002        Self {
3003            ops: &JSON_OPS,
3004            desc: Desc::Json(json),
3005            checks: false,
3006            has_ops: false,
3007            scalar: false,
3008        }
3009    }
3010
3011    const fn json(&self) -> Option<&'static JsonDesc> {
3012        match self.desc {
3013            Desc::Json(json) => Some(json),
3014            _ => None,
3015        }
3016    }
3017}
3018
3019fn jsons(table: &ModelTable) -> Result<&'static JsonDesc, ModelError> {
3020    table.json().ok_or_else(mismatch)
3021}
3022
3023/// An error of serde as a model error.
3024#[allow(
3025    clippy::needless_pass_by_value,
3026    reason = "`map_err` hands it the error by value"
3027)]
3028fn serde_invalid(error: serde_json::Error) -> ModelError {
3029    ModelError::invalid(error.to_string())
3030}
3031
3032/// Put the value the stored JSON `text` holds into `out`: parsed once as
3033/// JSON, then read as the type through its one JSON reader.
3034fn json_from_text(json: &JsonDesc, text: &str, out: &mut dyn Any) -> Result<(), ModelError> {
3035    let value: serde_json::Value = serde_json::from_str(text).map_err(serde_invalid)?;
3036    (json.from_value)(&value, out)
3037}
3038
3039/// The JSON text a value of a type stored as JSON text is stored as.
3040fn json_text(json: &JsonDesc, value: &dyn Any) -> Result<String, ModelError> {
3041    (json.try_value)(value).map(|value| value.to_string())
3042}
3043
3044/// The serde functions of a type stored as JSON text.
3045pub struct JsonOf<T>(PhantomData<T>);
3046
3047impl<T: serde::Serialize + serde::de::DeserializeOwned + Default + 'static> JsonOf<T> {
3048    /// A type stored as itself, compared only by its JSON form.
3049    pub const PLAIN: JsonDesc = JsonDesc {
3050        to_value: |value| {
3051            value
3052                .downcast_ref::<T>()
3053                .and_then(|value| crate::__private::json_via_bytes(value).ok())
3054                .unwrap_or(serde_json::Value::Null)
3055        },
3056        try_value: |value| {
3057            crate::__private::json_via_bytes(value.downcast_ref::<T>().ok_or_else(mismatch)?)
3058                .map_err(serde_invalid)
3059        },
3060        bytes: |value| serde_json::to_vec(value.downcast_ref::<T>()?).ok(),
3061        equal: None,
3062        from_value: |value, out| {
3063            put::<T>(
3064                out,
3065                serde_json::from_value(value.clone()).map_err(serde_invalid)?,
3066            )
3067        },
3068        default: |out| put(out, T::default()),
3069        null_default: true,
3070        structural: false,
3071        staged: (empty_of::<T>, unwrap_of::<T>),
3072        replace: replace_of::<T>,
3073    };
3074}
3075
3076impl<T> JsonOf<T>
3077where
3078    T: serde::Serialize + serde::de::DeserializeOwned + Default + PartialEq + 'static,
3079{
3080    /// A [`json_model!`](crate::json_model) type, compared in memory first:
3081    /// its `PartialEq` holds only between values of equal JSON forms, as a
3082    /// derived one does, so an equal pair needs neither serialised.
3083    pub const COMPARED: JsonDesc = JsonDesc {
3084        equal: Some(|value, other| {
3085            matches!(
3086                (value.downcast_ref::<T>(), other.downcast_ref::<T>()),
3087                (Some(value), Some(other)) if value == other
3088            )
3089        }),
3090        ..Self::PLAIN
3091    };
3092}
3093
3094/// The serde functions of a [`value_model!`](crate::value_model) type,
3095/// stored as its JSON form's maps, lists and scalars.
3096pub struct ValueOf<T>(PhantomData<T>);
3097
3098impl<T> ValueOf<T>
3099where
3100    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + 'static,
3101{
3102    /// A type with no value of its own for an absent slot.
3103    pub const DESC: JsonDesc = JsonDesc {
3104        to_value: |value| {
3105            value
3106                .downcast_ref::<T>()
3107                .and_then(|value| crate::__private::json_via_bytes(value).ok())
3108                .unwrap_or(serde_json::Value::Null)
3109        },
3110        try_value: |value| {
3111            crate::__private::json_via_bytes(value.downcast_ref::<T>().ok_or_else(mismatch)?)
3112                .map_err(serde_invalid)
3113        },
3114        bytes: |value| serde_json::to_vec(value.downcast_ref::<T>()?).ok(),
3115        equal: Some(|value, other| {
3116            matches!(
3117                (value.downcast_ref::<T>(), other.downcast_ref::<T>()),
3118                (Some(value), Some(other)) if value == other
3119            )
3120        }),
3121        from_value: |value, out| {
3122            put::<T>(
3123                out,
3124                serde_json::from_value(value.clone()).map_err(serde_invalid)?,
3125            )
3126        },
3127        default: |_| {
3128            Err(ModelError::Missing {
3129                path: String::new(),
3130            })
3131        },
3132        null_default: false,
3133        structural: true,
3134        staged: (empty_of::<T>, unwrap_of::<T>),
3135        replace: replace_of::<T>,
3136    };
3137}
3138
3139impl<T> ValueOf<T>
3140where
3141    T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + Default + 'static,
3142{
3143    /// A type whose `Default` is the value of an absent slot.
3144    pub const DEFAULTED: JsonDesc = JsonDesc {
3145        default: |out| put(out, T::default()),
3146        null_default: true,
3147        ..Self::DESC
3148    };
3149}
3150
3151/// The functions of every type stored as JSON text.
3152pub static JSON_OPS: ModelOps = ModelOps {
3153    without_absent: crate::shape::kept_whole,
3154    fresh: fresh::json_made,
3155    to_json: |table, value| match table.json() {
3156        Some(json) => (json.to_value)(value),
3157        None => serde_json::Value::Null,
3158    },
3159    from_json: |table, value, out| {
3160        let json = jsons(table)?;
3161        if json.null_default && value.is_null() {
3162            return (json.default)(out);
3163        }
3164        (json.from_value)(value, out)
3165    },
3166    load: |table, doc, value, id, out| {
3167        let json = jsons(table)?;
3168        if json.structural {
3169            let read = <serde_json::Value as Model>::load(doc, value, id)?;
3170            if read.is_null() && json.null_default {
3171                return (json.default)(out);
3172            }
3173            return (json.from_value)(&read, out);
3174        }
3175        match value {
3176            Value::Scalar(scalar) => match scalar.as_ref() {
3177                automerge::ScalarValue::Str(text) => json_from_text(json, text, out),
3178                automerge::ScalarValue::Null => (json.default)(out),
3179                _ => Err(ModelError::shape("a JSON string")),
3180            },
3181            Value::Object(_) => Err(ModelError::shape("a JSON string")),
3182        }
3183    },
3184    missing: |table, out| (jsons(table)?.default)(out),
3185    reload: |table, target, doc, slot| {
3186        let json = jsons(table)?;
3187        let mut staged = (json.staged.0)();
3188        match slot {
3189            Some((value, id)) => (JSON_OPS.load)(table, doc, value, id, staged.as_mut())?,
3190            None => (json.default)(staged.as_mut())?,
3191        }
3192        (json.replace)(target, staged.as_mut())
3193    },
3194    store: |table, value, doc, slot| {
3195        let json = jsons(table)?;
3196        if json.structural {
3197            return (json.try_value)(value)?.store(doc, slot);
3198        }
3199        let text = json_text(json, value)?;
3200        slot.put_scalar(doc, automerge::ScalarValue::Str(text.into()))
3201    },
3202    // Equal values of a structural type store the same maps, lists and
3203    // scalars; JSON text is written again, as it always was.
3204    stores_as: |table, value, before| {
3205        table.json().is_some_and(|json| {
3206            json.structural && json.equal.is_some_and(|equal| equal(value, before))
3207        })
3208    },
3209    store_changed: |table, value, _, doc, slot, _| (JSON_OPS.store)(table, value, doc, slot),
3210    refresh: |table, target, doc, value, id, _| {
3211        (JSON_OPS.reload)(table, target, doc, Some((value, id)))
3212    },
3213    read_whole: |_, _, _| Ok(()),
3214    edit: |table, doc, slot, path, op, _| {
3215        let json = jsons(table)?;
3216        edit_whole(
3217            table,
3218            ((json.staged.0)(), json.staged.1),
3219            true,
3220            doc,
3221            slot,
3222            path,
3223            op,
3224        )
3225    },
3226    diff: |table, before, after, path, out| {
3227        // Values equal in memory have equal forms; the same text is the same
3228        // form; a different text may still be (a map's keys serialised in
3229        // another order), so the forms decide.
3230        if let Some(json) = table.json() {
3231            if json.equal.is_some_and(|equal| equal(before, after)) {
3232                return;
3233            }
3234            if let Some(was) = (json.bytes)(before)
3235                && (json.bytes)(after).is_some_and(|now| now == was)
3236            {
3237                return;
3238            }
3239        }
3240        let value = (JSON_OPS.to_json)(table, after);
3241        if (JSON_OPS.to_json)(table, before) != value {
3242            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
3243        }
3244    },
3245    collect_text: |_, _, _| {},
3246    check: |_, _| Ok(()),
3247    get_at: |_, value, path| path.is_empty().then_some(value),
3248    label: no_label,
3249    nested_collections: no_nested,
3250    op_coalesces: no_coalesces,
3251    op_continuable: no_continuable,
3252    op_describe: no_describe,
3253    op_lands: no_lands,
3254    op_schemas: no_schemas,
3255};
3256
3257/// A list's items, whatever their type.
3258pub trait ListItems {
3259    fn count(&self) -> usize;
3260    fn item_at(&self, at: usize) -> Option<&dyn Any>;
3261    /// Append an item, put by `fill` into an `Option` of the item type.
3262    ///
3263    /// # Errors
3264    /// What `fill` refused.
3265    fn push_filled(
3266        &mut self,
3267        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
3268    ) -> Result<(), ModelError>;
3269}
3270
3271impl<T: 'static> ListItems for Vec<T> {
3272    fn count(&self) -> usize {
3273        self.len()
3274    }
3275
3276    fn item_at(&self, at: usize) -> Option<&dyn Any> {
3277        self.get(at).map(|item| item as &dyn Any)
3278    }
3279
3280    fn push_filled(
3281        &mut self,
3282        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
3283    ) -> Result<(), ModelError> {
3284        let mut slot: Option<T> = None;
3285        fill(&mut slot)?;
3286        self.push(filled(slot)?);
3287        Ok(())
3288    }
3289}
3290
3291/// What `Vec<T>`'s table reaches into one with.
3292pub struct VecDesc {
3293    item: &'static ModelTable,
3294    items: for<'a> fn(&'a dyn Any) -> Option<&'a dyn ListItems>,
3295    /// Put an empty list into `out` (an `Option` of it), and hand it back.
3296    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn ListItems>,
3297    staged: (fn() -> Box<dyn Any>, Unstage),
3298    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
3299}
3300
3301/// The [`VecDesc`] of `Vec<T>`.
3302pub struct VecOf<T>(PhantomData<T>);
3303
3304impl<T: Model> VecOf<T> {
3305    pub const DESC: VecDesc = VecDesc {
3306        item: T::TABLE,
3307        items: |value| Some(value.downcast_ref::<Vec<T>>()? as &dyn ListItems),
3308        fresh: |out| {
3309            let out = out.downcast_mut::<Option<Vec<T>>>()?;
3310            Some(out.insert(Vec::new()) as &mut dyn ListItems)
3311        },
3312        staged: (empty_of::<Vec<T>>, unwrap_of::<Vec<T>>),
3313        replace: replace_of::<Vec<T>>,
3314    };
3315
3316    pub const TABLE: ModelTable = ModelTable {
3317        ops: &VEC_OPS,
3318        desc: Desc::Vec(&Self::DESC),
3319        checks: T::CHECKS,
3320        has_ops: T::OPS,
3321        scalar: false,
3322    };
3323}
3324
3325impl ModelTable {
3326    const fn list(&self) -> Option<&'static VecDesc> {
3327        match self.desc {
3328            Desc::Vec(list) => Some(list),
3329            _ => None,
3330        }
3331    }
3332}
3333
3334fn lists(table: &ModelTable) -> Result<&'static VecDesc, ModelError> {
3335    table.list().ok_or_else(mismatch)
3336}
3337
3338/// The functions of every `Vec`: a list of values.
3339pub static VEC_OPS: ModelOps = ModelOps {
3340    without_absent: crate::shape::kept_whole,
3341    fresh: fresh::list_made,
3342    to_json: |table, value| {
3343        let (Some(list), Some(items)) = (
3344            table.list(),
3345            table.list().and_then(|list| (list.items)(value)),
3346        ) else {
3347            return serde_json::Value::Null;
3348        };
3349        let mut out = Vec::with_capacity(items.count());
3350        for at in 0..items.count() {
3351            if let Some(item) = items.item_at(at) {
3352                out.push((list.item.ops.to_json)(list.item, item));
3353            }
3354        }
3355        serde_json::Value::Array(out)
3356    },
3357    from_json: |table, value, out| {
3358        let list = lists(table)?;
3359        let fresh = (list.fresh)(out).ok_or_else(mismatch)?;
3360        match value {
3361            serde_json::Value::Array(items) => {
3362                for (index, item) in items.iter().enumerate() {
3363                    fresh.push_filled(&mut |into| {
3364                        (list.item.ops.from_json)(list.item, item, into).located(&index.to_string())
3365                    })?;
3366                }
3367                Ok(())
3368            }
3369            serde_json::Value::Null => Ok(()),
3370            _ => Err(ModelError::shape("a list")),
3371        }
3372    },
3373    load: |table, doc, value, id, out| {
3374        let list = lists(table)?;
3375        if !matches!(value, Value::Object(ObjType::List)) {
3376            return Err(ModelError::shape("a list"));
3377        }
3378        let fresh = (list.fresh)(out).ok_or_else(mismatch)?;
3379        for index in 0..automerge::ReadDoc::length(doc, id) {
3380            let slot = crate::model::get_item(doc, id, index)?;
3381            fresh.push_filled(&mut |into| {
3382                load_slot(list.item, doc, slot.as_ref().map(|(v, i)| (v, i)), into)
3383                    .located(&index.to_string())
3384            })?;
3385        }
3386        Ok(())
3387    },
3388    missing: |table, out| {
3389        (lists(table)?.fresh)(out).ok_or_else(mismatch)?;
3390        Ok(())
3391    },
3392    reload: |table, target, doc, slot| {
3393        let list = lists(table)?;
3394        let mut staged = (list.staged.0)();
3395        match slot {
3396            Some((value, id)) => (VEC_OPS.load)(table, doc, value, id, staged.as_mut())?,
3397            None => (VEC_OPS.missing)(table, staged.as_mut())?,
3398        }
3399        (list.replace)(target, staged.as_mut())
3400    },
3401    store: |table, value, doc, slot| {
3402        let list = lists(table)?;
3403        let items = (list.items)(value).ok_or_else(mismatch)?;
3404        let obj = slot.object(doc, ObjType::List)?;
3405        let existing = automerge::ReadDoc::length(doc, &obj);
3406        for index in 0..items.count() {
3407            let Some(item) = items.item_at(index) else {
3408                continue;
3409            };
3410            let slot = if index < existing {
3411                Slot::Index(&obj, index)
3412            } else {
3413                Slot::Insert(&obj, index)
3414            };
3415            (list.item.ops.store)(list.item, item, doc, slot).located(&index.to_string())?;
3416        }
3417        for index in (items.count()..existing).rev() {
3418            automerge::transaction::Transactable::delete(doc, &obj, index)?;
3419        }
3420        Ok(())
3421    },
3422    stores_as: |table, value, before| {
3423        let Some(list) = table.list() else {
3424            return false;
3425        };
3426        let (Some(now), Some(was)) = ((list.items)(value), (list.items)(before)) else {
3427            return false;
3428        };
3429        now.count() == was.count()
3430            && (0..now.count()).all(|at| match (now.item_at(at), was.item_at(at)) {
3431                (Some(now), Some(was)) => (list.item.ops.stores_as)(list.item, now, was),
3432                _ => false,
3433            })
3434    },
3435    store_changed: |table, value, _, doc, slot, _| (VEC_OPS.store)(table, value, doc, slot),
3436    refresh: |table, target, doc, value, id, _| {
3437        (VEC_OPS.reload)(table, target, doc, Some((value, id)))
3438    },
3439    read_whole: |_, _, _| Ok(()),
3440    edit: |table, doc, slot, path, op, _| {
3441        let list = lists(table)?;
3442        edit_whole(
3443            table,
3444            ((list.staged.0)(), list.staged.1),
3445            false,
3446            doc,
3447            slot,
3448            path,
3449            op,
3450        )
3451    },
3452    diff: |table, before, after, path, out| {
3453        let value = (VEC_OPS.to_json)(table, after);
3454        if (VEC_OPS.to_json)(table, before) != value {
3455            out.push(Edit::new(path.to_vec(), EditOp::Set { value }));
3456        }
3457    },
3458    collect_text: |table, value, out| {
3459        if let Some(list) = table.list()
3460            && let Some(items) = (list.items)(value)
3461        {
3462            for at in 0..items.count() {
3463                if let Some(item) = items.item_at(at) {
3464                    (list.item.ops.collect_text)(list.item, item, out);
3465                }
3466            }
3467        }
3468    },
3469    check: |table, value| {
3470        let Some(list) = table.list() else {
3471            return Ok(());
3472        };
3473        if !list.item.checks {
3474            return Ok(());
3475        }
3476        if let Some(items) = (list.items)(value) {
3477            for at in 0..items.count() {
3478                if let Some(item) = items.item_at(at) {
3479                    (list.item.ops.check)(list.item, item)?;
3480                }
3481            }
3482        }
3483        Ok(())
3484    },
3485    get_at: |_, value, path| path.is_empty().then_some(value),
3486    label: no_label,
3487    nested_collections: no_nested,
3488    op_coalesces: no_coalesces,
3489    op_continuable: no_continuable,
3490    op_describe: no_describe,
3491    op_lands: no_lands,
3492    op_schemas: no_schemas,
3493};
3494
3495/// A map's entries, whatever their value type.
3496pub trait MapEntries {
3497    fn count(&self) -> usize;
3498    /// Each entry in key order.
3499    fn each(&self, visit: &mut dyn FnMut(&str, &dyn Any));
3500    fn value(&self, key: &str) -> Option<&dyn Any>;
3501    fn value_mut(&mut self, key: &str) -> Option<&mut dyn Any>;
3502    fn remove_key(&mut self, key: &str);
3503    /// Insert (or replace) `key`, its value put by `fill` into an `Option`
3504    /// of the value type.
3505    ///
3506    /// # Errors
3507    /// What `fill` refused.
3508    fn insert_filled(
3509        &mut self,
3510        key: String,
3511        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
3512    ) -> Result<(), ModelError>;
3513    /// Insert (or replace) `key` with the value moved out of `staged`, a
3514    /// filled `Option` of the value type.
3515    ///
3516    /// # Errors
3517    /// When `staged` is of another type or empty.
3518    fn insert_moved(&mut self, key: String, staged: &mut dyn Any) -> Result<(), ModelError>;
3519    /// The keys whose entries may differ from those of `before`, a map of
3520    /// this same type, in key order, once each: under any other key both
3521    /// hold the same entry. `None`, the default, when the map cannot tell,
3522    /// and every entry is compared.
3523    fn differing_keys<'a>(&'a self, before: &'a dyn Any) -> Option<Vec<&'a str>> {
3524        let _ = before;
3525        None
3526    }
3527}
3528
3529impl<T: 'static> MapEntries for std::collections::BTreeMap<String, T> {
3530    fn count(&self) -> usize {
3531        self.len()
3532    }
3533
3534    fn each(&self, visit: &mut dyn FnMut(&str, &dyn Any)) {
3535        for (key, value) in self {
3536            visit(key, value);
3537        }
3538    }
3539
3540    fn value(&self, key: &str) -> Option<&dyn Any> {
3541        self.get(key).map(|value| value as &dyn Any)
3542    }
3543
3544    fn value_mut(&mut self, key: &str) -> Option<&mut dyn Any> {
3545        self.get_mut(key).map(|value| value as &mut dyn Any)
3546    }
3547
3548    fn remove_key(&mut self, key: &str) {
3549        self.remove(key);
3550    }
3551
3552    fn insert_filled(
3553        &mut self,
3554        key: String,
3555        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
3556    ) -> Result<(), ModelError> {
3557        let mut slot: Option<T> = None;
3558        fill(&mut slot)?;
3559        self.insert(key, filled(slot)?);
3560        Ok(())
3561    }
3562
3563    fn insert_moved(&mut self, key: String, staged: &mut dyn Any) -> Result<(), ModelError> {
3564        let value = staged
3565            .downcast_mut::<Option<T>>()
3566            .and_then(Option::take)
3567            .ok_or_else(mismatch)?;
3568        self.insert(key, value);
3569        Ok(())
3570    }
3571}
3572
3573/// What the table of a map of string keys reaches into one with.
3574pub struct MapDesc {
3575    item: &'static ModelTable,
3576    item_nullable: bool,
3577    entries: for<'a> fn(&'a dyn Any) -> Option<&'a dyn MapEntries>,
3578    entries_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
3579    /// Put an empty map into `out` (an `Option` of it), and hand it back.
3580    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
3581    staged: (fn() -> Box<dyn Any>, Unstage),
3582    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
3583    item_staged: (fn() -> Box<dyn Any>, Unstage),
3584}
3585
3586/// The [`MapDesc`] of the map `M` of string keys to `T`s: a
3587/// `BTreeMap<String, T>` ([`MapOf`]) or a [`Map`](crate::Map), stored
3588/// alike.
3589pub struct MapIn<T, M>(PhantomData<fn() -> (T, M)>);
3590
3591/// The [`MapDesc`] of `BTreeMap<String, T>`.
3592pub type MapOf<T> = MapIn<T, std::collections::BTreeMap<String, T>>;
3593
3594impl<T: Model, M: MapEntries + Default + 'static> MapIn<T, M> {
3595    pub const DESC: MapDesc = MapDesc {
3596        item: T::TABLE,
3597        item_nullable: T::NULLABLE,
3598        entries: |value| Some(value.downcast_ref::<M>()? as &dyn MapEntries),
3599        entries_mut: |value| Some(value.downcast_mut::<M>()? as &mut dyn MapEntries),
3600        fresh: |out| {
3601            let out = out.downcast_mut::<Option<M>>()?;
3602            Some(out.insert(M::default()) as &mut dyn MapEntries)
3603        },
3604        staged: (empty_of::<M>, unwrap_of::<M>),
3605        replace: replace_of::<M>,
3606        item_staged: (empty_of::<T>, unwrap_of::<T>),
3607    };
3608
3609    pub const TABLE: ModelTable = ModelTable {
3610        ops: &MAP_OPS,
3611        desc: Desc::Map(&Self::DESC),
3612        checks: T::CHECKS,
3613        has_ops: T::OPS,
3614        scalar: false,
3615    };
3616}
3617
3618impl ModelTable {
3619    const fn map(&self) -> Option<&'static MapDesc> {
3620        match self.desc {
3621            Desc::Map(map) => Some(map),
3622            _ => None,
3623        }
3624    }
3625}
3626
3627fn maps(table: &ModelTable) -> Result<&'static MapDesc, ModelError> {
3628    table.map().ok_or_else(mismatch)
3629}
3630
3631/// The value at the key `path` starts at, and the rest of the path, when
3632/// the map's values have a vocabulary of their own.
3633fn keyed<'p>(
3634    table: &ModelTable,
3635    path: &'p [Segment],
3636) -> Option<(&'static MapDesc, &'p str, &'p [Segment])> {
3637    match path.split_first() {
3638        Some((Segment::Key(key), rest)) if table.has_ops => Some((table.map()?, key, rest)),
3639        _ => None,
3640    }
3641}
3642
3643/// The functions of every map of string keys: a map, one key per entry.
3644pub static MAP_OPS: ModelOps = ModelOps {
3645    without_absent: crate::shape::kept_whole,
3646    fresh: fresh::stored_after,
3647    to_json: |table, value| {
3648        let mut out = serde_json::Map::new();
3649        if let Some(map) = table.map()
3650            && let Some(entries) = (map.entries)(value)
3651        {
3652            entries.each(&mut |key, value| {
3653                out.insert(key.to_owned(), (map.item.ops.to_json)(map.item, value));
3654            });
3655        }
3656        serde_json::Value::Object(out)
3657    },
3658    from_json: |table, value, out| {
3659        let map = maps(table)?;
3660        match value {
3661            serde_json::Value::Object(entries) => {
3662                let fresh = (map.fresh)(out).ok_or_else(mismatch)?;
3663                for (key, value) in entries {
3664                    fresh.insert_filled(key.clone(), &mut |into| {
3665                        (map.item.ops.from_json)(map.item, value, into).located(key)
3666                    })?;
3667                }
3668                Ok(())
3669            }
3670            serde_json::Value::Null => {
3671                (map.fresh)(out).ok_or_else(mismatch)?;
3672                Ok(())
3673            }
3674            _ => Err(ModelError::shape("a map")),
3675        }
3676    },
3677    load: |table, doc, value, id, out| {
3678        let map = maps(table)?;
3679        if !matches!(value, Value::Object(ObjType::Map)) {
3680            return Err(ModelError::shape("a map"));
3681        }
3682        let fresh = (map.fresh)(out).ok_or_else(mismatch)?;
3683        // One walk of the map rather than a lookup per key.
3684        for (key, slot) in crate::model::map_slots(doc, id) {
3685            fresh.insert_filled(key.clone(), &mut |into| {
3686                load_slot(map.item, doc, slot.as_ref().map(|(v, i)| (v, i)), into).located(&key)
3687            })?;
3688        }
3689        Ok(())
3690    },
3691    missing: |table, out| {
3692        (maps(table)?.fresh)(out).ok_or_else(mismatch)?;
3693        Ok(())
3694    },
3695    reload: |table, target, doc, slot| {
3696        let map = maps(table)?;
3697        let mut staged = (map.staged.0)();
3698        match slot {
3699            Some((value, id)) => (MAP_OPS.load)(table, doc, value, id, staged.as_mut())?,
3700            None => (MAP_OPS.missing)(table, staged.as_mut())?,
3701        }
3702        (map.replace)(target, staged.as_mut())
3703    },
3704    store: |table, value, doc, slot| {
3705        let map = maps(table)?;
3706        let entries = (map.entries)(value).ok_or_else(mismatch)?;
3707        let obj = slot.object(doc, ObjType::Map)?;
3708        let stale: Vec<String> = automerge::ReadDoc::keys(doc, &obj)
3709            .filter(|key| entries.value(key).is_none())
3710            .collect();
3711        for key in stale {
3712            automerge::transaction::Transactable::delete(doc, &obj, key.as_str())?;
3713        }
3714        let mut written = Ok(());
3715        entries.each(&mut |key, value| {
3716            if written.is_ok() {
3717                written =
3718                    (map.item.ops.store)(map.item, value, doc, Slot::Key(&obj, key)).located(key);
3719            }
3720        });
3721        written
3722    },
3723    stores_as: |table, value, before| {
3724        let Some(map) = table.map() else {
3725            return false;
3726        };
3727        let (Some(now), Some(was)) = ((map.entries)(value), (map.entries)(before)) else {
3728            return false;
3729        };
3730        if now.count() != was.count() {
3731            return false;
3732        }
3733        let stores_as = |key: &str, value: &dyn Any| {
3734            was.value(key)
3735                .is_some_and(|before| (map.item.ops.stores_as)(map.item, value, before))
3736        };
3737        // Under any other key both hold the same entry.
3738        if let Some(keys) = now.differing_keys(before) {
3739            return keys
3740                .into_iter()
3741                .all(|key| now.value(key).is_some_and(|value| stores_as(key, value)));
3742        }
3743        let mut same = true;
3744        now.each(&mut |key, value| same = same && stores_as(key, value));
3745        same
3746    },
3747    store_changed: |table, value, before, doc, slot, dirty| {
3748        let map = maps(table)?;
3749        let now = (map.entries)(value).ok_or_else(mismatch)?;
3750        let was = (map.entries)(before).ok_or_else(mismatch)?;
3751        let Some(differing) = now.differing_keys(before) else {
3752            return (MAP_OPS.store)(table, value, doc, slot);
3753        };
3754        // A slot holding no map yet is written whole, as is a map someone
3755        // else changed otherwise than key by key.
3756        let Some((Value::Object(ObjType::Map), obj)) = slot.current(doc)? else {
3757            return (MAP_OPS.store)(table, value, doc, slot);
3758        };
3759        let touched = dirty.under(&obj);
3760        if touched.is_all() {
3761            return (MAP_OPS.store)(table, value, doc, slot);
3762        }
3763        // Under any other key the entry is the one `before` holds, and the
3764        // map holds it as a store left it: storing it writes nothing.
3765        let mut keys = differing;
3766        keys.extend(touched.keys());
3767        keys.compact_sort();
3768        keys.dedup();
3769        // What `store` writes: the stale keys deleted, then each entry
3770        // written, both in key order.
3771        for key in &keys {
3772            if now.value(key).is_none() && automerge::ReadDoc::get(doc, &obj, *key)?.is_some() {
3773                automerge::transaction::Transactable::delete(doc, &obj, *key)?;
3774            }
3775        }
3776        for key in &keys {
3777            let Some(next) = now.value(key) else {
3778                continue;
3779            };
3780            match was.value(key) {
3781                Some(held) => write_key_changed(map.item, (next, held), doc, &obj, key, dirty)?,
3782                None => {
3783                    (map.item.ops.store)(map.item, next, doc, Slot::Key(&obj, key)).located(key)?;
3784                }
3785            }
3786        }
3787        Ok(())
3788    },
3789    refresh: |table, target, doc, value, id, delta| {
3790        let map = maps(table)?;
3791        let touched = delta.under(id);
3792        if touched.is_all() {
3793            return (MAP_OPS.reload)(table, target, doc, Some((value, id)));
3794        }
3795        let entries = (map.entries_mut)(target).ok_or_else(mismatch)?;
3796        for key in touched.keys() {
3797            match crate::model::get_slot(doc, id, key)? {
3798                None => entries.remove_key(key),
3799                Some((value, slot)) => match entries.value_mut(key) {
3800                    Some(existing) => refresh_slot(map.item, existing, doc, id, key, delta)?,
3801                    None => entries.insert_filled(key.to_owned(), &mut |into| {
3802                        (map.item.ops.load)(map.item, doc, &value, &slot, into).located(key)
3803                    })?,
3804                },
3805            }
3806        }
3807        Ok(())
3808    },
3809    read_whole: |_, _, _| Ok(()),
3810    edit: |table, doc, slot, path, op, cx| {
3811        let map = maps(table)?;
3812        let item = map.item;
3813        match (path.split_first(), op) {
3814            (None, EditOp::RemoveKey { key }) => {
3815                let obj = slot.object(doc, ObjType::Map)?;
3816                Slot::Key(&obj, key).remove(doc)
3817            }
3818            (Some((Segment::Key(key), rest)), op) => {
3819                let obj = slot.object(doc, ObjType::Map)?;
3820                if rest.is_empty() && matches!(op, EditOp::Set { .. }) {
3821                    let staged = ((map.item_staged.0)(), map.item_staged.1);
3822                    return edit_whole(
3823                        item,
3824                        staged,
3825                        map.item_nullable,
3826                        doc,
3827                        Slot::Key(&obj, key),
3828                        rest,
3829                        op,
3830                    )
3831                    .located(key);
3832                }
3833                // An edit inside an entry that is not there yet starts it
3834                // from its value's empty value (a rule for an app that had
3835                // none).
3836                if automerge::ReadDoc::get(doc, &obj, key.as_str())?.is_none() {
3837                    let mut empty = (map.item_staged.0)();
3838                    (item.ops.missing)(item, empty.as_mut())
3839                        .map_err(|_| ModelError::invalid(format!("no entry `{key}`")))?;
3840                    let empty = (map.item_staged.1)(empty.as_ref()).ok_or_else(mismatch)?;
3841                    (item.ops.store)(item, empty, doc, Slot::Key(&obj, key)).located(key)?;
3842                }
3843                (item.ops.edit)(item, doc, Slot::Key(&obj, key), rest, op, cx).located(key)
3844            }
3845            _ => {
3846                let staged = ((map.staged.0)(), map.staged.1);
3847                edit_whole(table, staged, false, doc, slot, path, op)
3848            }
3849        }
3850    },
3851    diff: |table, before, after, path, out| {
3852        let Some(map) = table.map() else {
3853            return;
3854        };
3855        let (Some(was), Some(now)) = ((map.entries)(before), (map.entries)(after)) else {
3856            return;
3857        };
3858        let at = |key: &str| {
3859            let mut at = path.to_vec();
3860            at.push(Segment::Key(key.to_owned()));
3861            at
3862        };
3863        // An entry `before` holds: changed, or removed.
3864        let kept = |key: &str, before: &dyn Any, out: &mut Vec<Edit<()>>| match now.value(key) {
3865            Some(next) => (map.item.ops.diff)(map.item, before, next, &at(key), out),
3866            None => out.push(Edit::new(
3867                path.to_vec(),
3868                EditOp::RemoveKey {
3869                    key: key.to_owned(),
3870                },
3871            )),
3872        };
3873        // An entry `after` holds: added, when `before` had none.
3874        let added = |key: &str, next: &dyn Any, out: &mut Vec<Edit<()>>| {
3875            if was.value(key).is_none() {
3876                out.push(Edit::new(
3877                    at(key),
3878                    EditOp::Set {
3879                        value: (map.item.ops.to_json)(map.item, next),
3880                    },
3881                ));
3882            }
3883        };
3884        // Under any other key both hold the same entry: no edit.
3885        if let Some(keys) = now.differing_keys(before) {
3886            for key in &keys {
3887                if let Some(before) = was.value(key) {
3888                    kept(key, before, out);
3889                }
3890            }
3891            for key in &keys {
3892                if let Some(next) = now.value(key) {
3893                    added(key, next, out);
3894                }
3895            }
3896        } else {
3897            was.each(&mut |key, before| kept(key, before, out));
3898            now.each(&mut |key, next| added(key, next, out));
3899        }
3900    },
3901    collect_text: |table, value, out| {
3902        if let Some(map) = table.map()
3903            && let Some(entries) = (map.entries)(value)
3904        {
3905            entries.each(&mut |_, value| (map.item.ops.collect_text)(map.item, value, out));
3906        }
3907    },
3908    check: |table, value| {
3909        let Some(map) = table.map() else {
3910            return Ok(());
3911        };
3912        if !map.item.checks {
3913            return Ok(());
3914        }
3915        let Some(entries) = (map.entries)(value) else {
3916            return Ok(());
3917        };
3918        let mut checked = Ok(());
3919        entries.each(&mut |_, value| {
3920            if checked.is_ok() {
3921                checked = (map.item.ops.check)(map.item, value);
3922            }
3923        });
3924        checked
3925    },
3926    get_at: |table, value, path| match path.split_first() {
3927        None => Some(value),
3928        Some((Segment::Key(key), rest)) => {
3929            let map = table.map()?;
3930            (map.item.ops.get_at)(map.item, (map.entries)(value)?.value(key)?, rest)
3931        }
3932        Some(_) => None,
3933    },
3934    label: no_label,
3935    nested_collections: no_nested,
3936    op_coalesces: |table, path, previous, next| {
3937        let (map, _, rest) = keyed(table, path)?;
3938        (map.item.ops.op_coalesces)(map.item, rest, previous, next)
3939    },
3940    op_continuable: |table, path, op| {
3941        let (map, _, rest) = keyed(table, path)?;
3942        (map.item.ops.op_continuable)(map.item, rest, op)
3943    },
3944    op_describe: |table, path, op| {
3945        let (map, _, rest) = keyed(table, path)?;
3946        (map.item.ops.op_describe)(map.item, rest, op)
3947    },
3948    op_lands: |table, value, path, op| {
3949        let (map, key, rest) = keyed(table, path)?;
3950        (map.item.ops.op_lands)(map.item, (map.entries)(value)?.value(key)?, rest, op)
3951    },
3952    op_schemas: |table, prefix, out| {
3953        if table.has_ops
3954            && let Some(map) = table.map()
3955        {
3956            (map.item.ops.op_schemas)(map.item, &format!("{prefix}*."), out);
3957        }
3958    },
3959};