Skip to main content

flm_core/lang/
serialize.rs

1//! Storing an FLM parse in techy's serialized form and reading it back: FLM's
2//! part of techy's serialization.
3//!
4//! techy can write a whole parse (the node tree, the parsing states and sources
5//! behind it, the specifications and providers it used, the diagnostics) into a
6//! format-independent serialized value, and rebuild it elsewhere with shared
7//! values and identities preserved. A language takes part by implementing
8//! techy's `SerializableLang`, which requires a way to write and read every type
9//! the language adds to a parse. This module provides that for FLM.
10//!
11//! An embedding program does not use this module directly: the functions of
12//! [`crate::dump::session`] ([`writer`](crate::dump::session::writer),
13//! [`reader`](crate::dump::session::reader)) prepare a session with everything
14//! described here, and that module re-exports the public types of this one.
15//!
16//! Most of the conversions are derived on the types themselves, because their
17//! serialized form is their Rust form: the group classes and callable forms,
18//! the source origin, the text source map, the restricted-interior policy, the
19//! parsing settings. Two are written by hand here, because their serialized
20//! form differs from their Rust form:
21//!
22//! - the **node extension** ([`FlmNodeExt`]): the element is written by its
23//!   stable name and looked up again when read;
24//! - the **state extension** ([`FlmStateExt`]): the structural elements are
25//!   written by their names and read back as the *reading* language's own
26//!   shared set.
27//!
28//! # Specifications and providers
29//!
30//! A specification a node records is stored in one of two ways.
31//!
32//! - **By identity**, for a specification a package holds: a package records
33//!   on every specification it hands out a *provenance stamp*
34//!   ([`SpecProvenance`](techy::core::specs::SpecProvenance)), which identifies the
35//!   package that holds the specification and the name the package holds it
36//!   under. An [`FlmCallable`] and an environment's specification are written
37//!   as that stamp, and read back as the same value that the reading language's
38//!   package of that name holds. The fallback provider
39//!   ([`FlmFallbackProvider`]) is written by its name and read back as the
40//!   reading language's own fallback provider in the same way.
41//! - **Self-contained**, for the two specifications that belong to no package
42//!   and are never parsed: [`FlmSynthesizedSpec`] and [`FlmPresentationSpec`]
43//!   are written as their element's name, and rebuilt around the element of
44//!   that name when read.
45//!
46//! [`register`] installs the readers of these forms on a reading session.
47//!
48//! # The environment a session needs
49//!
50//! Reading needs a value for every name in the serialized data: the reading
51//! language's packages, given as techy's `KnownProviders`, and FLM's
52//! [`ReadEnvironment`], which holds the structural elements, an
53//! [`ElementResolver`] for every other element name, and the
54//! [`PayloadReaders`] that rebuild the typed payloads of nodes. Both are set as
55//! the session's user data.
56//!
57//! Writing needs one value, and only to write elements precisely: a
58//! [`WriteEnvironment`], which records, for every element that a registered
59//! specification carries, which specification that is.
60//!
61//! These types are declared here because the conversions read them from the
62//! session, but their public path is [`crate::dump::session`]
63//! ([`crate::dump::session::ReadEnvironment`], and so on).
64//! That module also provides the functions that prepare a session with them,
65//! which an embedding program should use.
66//!
67//! # Why a node extension records its element twice
68//!
69//! Two element *values* may share one stable name (`\section` and
70//! `\subsection` are two values of one heading element), so a name alone
71//! cannot say which value a node carried. A node extension is therefore written
72//! with the name *and*, when the write environment records which registered
73//! specification carries that exact value, a reference to that specification.
74//! When reading, the element is taken from the specification, by identity. An
75//! element written without a specification is looked up by its name: a
76//! structural element is the reading language's own, and any other element is
77//! the element resolver's answer. Two kinds of elements are written so: the
78//! structural elements, which the write environment of a language
79//! ([`WriteEnvironment::for_lang`]) never records, and the elements of the two
80//! self-contained specifications. Without a write environment, only the name is
81//! written.
82//!
83//! For the same reason, a name shared by several values is refused, not
84//! guessed, where only a name is available: the resolver returns
85//! [`AmbiguousElement`], and the read fails with it as the cause. With the write
86//! environment of a language, the element of a parsed callable never depends on
87//! the resolver: it is read through its specification, or, for the node of a
88//! tack-on field, which carries the structural field element
89//! ([`StructuralElements::field`]), as the reading language's own element of
90//! that name.
91//!
92//! # Serialized names
93//!
94//! FLM's own serialized identifiers are [`SYNTHESIZED_IDENTIFIER`],
95//! [`PRESENTATION_IDENTIFIER`] and [`FALLBACK_GATE_IDENTIFIER`]. Its keys are
96//! `element`, `spec`, `source_map` and `payload` for a node extension, and
97//! `structural`, `restricted_interior` and `parsing` for a state extension.
98//! They are as stable as FLM's element names.
99
100use std::collections::BTreeMap;
101use std::fmt;
102use std::sync::Arc;
103
104use techy::core::ClosedVocabulary;
105use techy::core::specs::{CallableSpec, SpecsProvider};
106use techy::latexlike::Mode;
107use techy::serialize::{
108    DeserializableObject, DeserializableValue, DeserializeContext, DeserializeError,
109    KnownProviders, RegistrationError, SerdeSession, SerialEntry, SerialIndex, SerialValue,
110    SerializableLang, SerializableObject, SerializableValue, SerializeContext, SerializeError,
111    SpecIndex, StandardTableInterning, StandardTableReading, StandardTables,
112};
113
114use crate::model::element::ElementSpec;
115use crate::model::names::ElementName;
116use crate::lang::build::BuiltLang;
117use crate::lang::ext::{FlmNodeExt, FlmStateExt, PresPayload, TextSourceMap, RestrictedInterior};
118use crate::lang::flm::{Flm, FlmCallableType};
119use crate::lang::mint::specs::element_of_spec;
120use crate::lang::mint::{
121    FlmCallable, FlmFallbackProvider, FlmPresentationSpec, FlmSynthesizedSpec, FlmUnknownMacroSpec,
122};
123use crate::lang::rules::FlmParsing;
124use crate::lang::structural::StructuralElements;
125
126// --- the language opts in ------------------------------------------------------------
127
128/// FLM parses can be serialized and read back: every type the language adds to
129/// a parse has its conversions, derived on the plain types and written by hand
130/// in this module for the node and state extensions.
131impl SerializableLang for Flm {}
132
133// --- stored identifiers -------------------------------------------------------------------
134
135/// The serialized identifier of an [`FlmSynthesizedSpec`]: `flm.synthesized`.
136/// Its serialized form is `{element}`.
137pub const SYNTHESIZED_IDENTIFIER: &str = "flm.synthesized";
138
139/// The serialized identifier of an [`FlmPresentationSpec`]: `flm.presentation`.
140/// Its serialized form is `{element}`.
141pub const PRESENTATION_IDENTIFIER: &str = "flm.presentation";
142
143/// The serialized identifier of an [`FlmFallbackProvider`]:
144/// `flm.fallback-gate`. Its serialized form is `{name}`.
145pub const FALLBACK_GATE_IDENTIFIER: &str = "flm.fallback-gate";
146
147// --- the reading environment: elements and payloads ----------------------------------------
148
149pub use crate::model::element::AmbiguousElement;
150
151/// An element resolver: the lookup with which a reading session turns a
152/// serialized element name back into an element value.
153///
154/// On the wire, an element is written by its stable type name, so this is the
155/// lookup from that name back to the element value the registry holds under
156/// it. The registry implements it; a test can use
157/// [`crate::dump::session::ElementTable`], a set of structural elements and a
158/// map.
159///
160/// It need not return the structural elements: the reading environment looks
161/// names up in the reading language's own set first
162/// ([`ReadEnvironment::resolve_element`]).
163///
164/// Its public path is [`crate::dump::session::ElementResolver`].
165pub trait ElementResolver: Send + Sync {
166    /// Returns the element value registered under `name`, or `Ok(None)` (not
167    /// an error) when no value is registered under it.
168    ///
169    /// # Errors
170    ///
171    /// [`AmbiguousElement`], which identifies the owner of each value, when
172    /// several values share the name: a name is never resolved by guessing.
173    fn resolve_element(&self, name: &str) -> Result<Option<Arc<ElementSpec>>, AmbiguousElement>;
174}
175
176impl<T: ElementResolver + ?Sized> ElementResolver for Arc<T> {
177    fn resolve_element(&self, name: &str) -> Result<Option<Arc<ElementSpec>>, AmbiguousElement> {
178        (**self).resolve_element(name)
179    }
180}
181
182/// A payload reader: a function that rebuilds the typed payload of a node of one
183/// element from its serialized form.
184///
185/// A reader receives **exactly the value [`PresPayload::project`] returned** for
186/// a payload of that element, and the reading context. A projected payload is
187/// self-contained data, with nothing that only makes sense next to the tree it
188/// came from, so a reader is usually the derived conversion of the payload
189/// type.
190pub type PayloadReader = Arc<
191    dyn Fn(
192            &SerialValue,
193            &mut DeserializeContext<'_, Flm>,
194        ) -> Result<Arc<dyn PresPayload>, DeserializeError>
195        + Send
196        + Sync,
197>;
198
199/// The payload readers of a reading session, one per element, keyed by the
200/// element's stable name.
201///
202/// A backend registers one reader for each of its presentation elements whose
203/// nodes carry a payload, and a feature registers one for an element whose
204/// rebuilt nodes carry a payload (see [`PresPayload`]). Reading a payload of an
205/// element with no reader registered fails with an error that identifies the
206/// element.
207///
208/// Its public path is [`crate::dump::session::PayloadReaders`].
209#[derive(Clone, Default)]
210pub struct PayloadReaders {
211    readers: BTreeMap<ElementName, PayloadReader>,
212}
213
214impl PayloadReaders {
215    /// Returns a set with no reader in it.
216    pub fn new() -> PayloadReaders {
217        PayloadReaders::default()
218    }
219
220    /// Registers `reader` for the payloads of the element named `element`, and
221    /// returns the reader it replaced, if there was one.
222    pub fn register<F>(
223        &mut self,
224        element: impl Into<ElementName>,
225        reader: F,
226    ) -> Option<PayloadReader>
227    where
228        F: Fn(
229                &SerialValue,
230                &mut DeserializeContext<'_, Flm>,
231            ) -> Result<Arc<dyn PresPayload>, DeserializeError>
232            + Send
233            + Sync
234            + 'static,
235    {
236        self.readers.insert(element.into(), Arc::new(reader))
237    }
238
239    /// Returns the reader registered for the element named `element`, if there
240    /// is one.
241    pub fn get(&self, element: &str) -> Option<&PayloadReader> {
242        self.readers.get(element)
243    }
244
245    /// Returns the names of the elements that have a reader, in name order.
246    pub fn elements(&self) -> impl Iterator<Item = &ElementName> + '_ {
247        self.readers.keys()
248    }
249
250    /// Returns how many readers are registered.
251    pub fn len(&self) -> usize {
252        self.readers.len()
253    }
254
255    /// Returns whether no reader is registered at all.
256    pub fn is_empty(&self) -> bool {
257        self.readers.is_empty()
258    }
259}
260
261impl fmt::Debug for PayloadReaders {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.debug_list().entries(self.readers.keys()).finish()
264    }
265}
266
267/// The read environment: FLM's part of what a reading session needs. The other
268/// part is techy's `KnownProviders`, the reading language's packages.
269///
270/// It holds three things: the reading language's structural elements, which
271/// every state extension read in the session shares; the [`ElementResolver`]
272/// for every other element name in the serialized data; and the
273/// [`PayloadReaders`].
274///
275/// It must be set as the session's user data;
276/// [`crate::dump::session::reader`] does that, along with everything else a
277/// reading session needs. Its public path is
278/// [`crate::dump::session::ReadEnvironment`].
279#[derive(Clone)]
280pub struct ReadEnvironment {
281    structural: Arc<StructuralElements>,
282    elements: Arc<dyn ElementResolver>,
283    payloads: Arc<PayloadReaders>,
284}
285
286impl ReadEnvironment {
287    /// Returns an environment with the given structural elements and element
288    /// resolver, and no payload reader. Add readers with
289    /// [`ReadEnvironment::with_payload_readers`].
290    pub fn new(
291        structural: Arc<StructuralElements>,
292        elements: Arc<dyn ElementResolver>,
293    ) -> ReadEnvironment {
294        ReadEnvironment { structural, elements, payloads: Arc::new(PayloadReaders::new()) }
295    }
296
297    /// Builder: sets the payload readers, replacing any already set.
298    pub fn with_payload_readers(mut self, readers: PayloadReaders) -> ReadEnvironment {
299        self.payloads = Arc::new(readers);
300        self
301    }
302
303    /// Returns the structural elements that every state extension read in this
304    /// session shares.
305    pub fn structural(&self) -> &Arc<StructuralElements> {
306        &self.structural
307    }
308
309    /// Returns the element named `name`: a structural element of this
310    /// environment's set when the name is one, and otherwise what the element
311    /// resolver returns.
312    ///
313    /// # Errors
314    ///
315    /// [`AmbiguousElement`] when several element values share the name.
316    pub fn resolve_element(
317        &self,
318        name: &str,
319    ) -> Result<Option<Arc<ElementSpec>>, AmbiguousElement> {
320        match self.structural.by_name(name) {
321            Some(element) => Ok(Some(Arc::clone(element))),
322            None => self.elements.resolve_element(name),
323        }
324    }
325
326    /// Returns the payload reader of the element named `element`, if one is
327    /// registered.
328    pub fn payload_reader(&self, element: &str) -> Option<&PayloadReader> {
329        self.payloads.get(element)
330    }
331}
332
333impl fmt::Debug for ReadEnvironment {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        f.debug_struct("ReadEnvironment")
336            .field("structural", &self.structural)
337            .field("payloads", &self.payloads)
338            .finish_non_exhaustive()
339    }
340}
341
342/// Returns the read environment from the session's user data, or the error
343/// that says how to prepare the session.
344fn read_environment(cx: &DeserializeContext<'_, Flm>) -> Result<ReadEnvironment, DeserializeError> {
345    cx.user_data::<ReadEnvironment>().cloned().ok_or_else(|| {
346        DeserializeError::failed(
347            "reading FLM data requires a read environment (the structural elements, the \
348             element resolver and the payload readers): prepare the session with \
349             flm_core::dump::session::reader",
350        )
351    })
352}
353
354/// Returns the element from a resolver's result, or the read error: no element
355/// of that name is known, or several values share it, in which case
356/// [`AmbiguousElement`] is the error's cause.
357fn resolved_element(
358    name: &str,
359    resolution: Result<Option<Arc<ElementSpec>>, AmbiguousElement>,
360) -> Result<Arc<ElementSpec>, DeserializeError> {
361    match resolution {
362        Ok(Some(element)) => Ok(element),
363        Ok(None) => Err(DeserializeError::failed(format!(
364            "the element resolver of the read environment finds no element `{name}`"
365        ))),
366        Err(ambiguous) => {
367            Err(DeserializeError::failed(ambiguous.to_string()).with_cause(ambiguous))
368        }
369    }
370}
371
372/// Returns the element named `name` in the session's read environment, or the
373/// read error.
374fn resolve_element(
375    cx: &DeserializeContext<'_, Flm>,
376    name: &str,
377) -> Result<Arc<ElementSpec>, DeserializeError> {
378    resolved_element(name, read_environment(cx)?.resolve_element(name))
379}
380
381// --- the writing environment: which spec carries an element ---------------------------------
382
383/// The write environment: FLM's part of what a writing session needs. It
384/// records, for every element value that a registered specification carries,
385/// which specification that is.
386///
387/// A node extension writes a reference to that specification beside the
388/// element's name, so the element reads back as the exact value even when
389/// several values share one name (see the [module
390/// documentation](self#why-a-node-extension-records-its-element-twice)).
391/// Without this environment, a node extension writes the name alone, and the
392/// reading side's element resolver decides.
393///
394/// Build a language's environment with [`WriteEnvironment::for_lang`], and set
395/// it as the session's user data; [`crate::dump::session::writer`] does both.
396/// Its public path is [`crate::dump::session::WriteEnvironment`].
397#[derive(Default)]
398pub struct WriteEnvironment {
399    /// Keyed by the element value's identity (its `Arc` pointer); the
400    /// specification keeps the element alive, so a key never dangles.
401    element_specs: BTreeMap<usize, Arc<dyn CallableSpec<Flm>>>,
402}
403
404impl WriteEnvironment {
405    /// Returns an environment that records no element yet.
406    pub fn new() -> WriteEnvironment {
407        WriteEnvironment::default()
408    }
409
410    /// Returns the environment of a writing session over `lang`. It records the
411    /// specifications of every provider of the language, those of its initial
412    /// parsing state followed by [`BuiltLang::providers`], as
413    /// [`for_providers`](Self::for_providers) does, and leaves out the
414    /// structural elements ([`BuiltLang::structural`]): a node carrying one is
415    /// written with the element's name alone, which the reading side resolves
416    /// to its own structural element of that name.
417    ///
418    /// Of the structural elements, only the field element
419    /// ([`StructuralElements::field`]) is carried by specifications that a
420    /// provider lists: the specification of every tack-on field carries it,
421    /// so none of them identifies it better than its name.
422    pub fn for_lang(lang: &BuiltLang) -> WriteEnvironment {
423        let providers = lang.initial_state().scopes().providers().iter().chain(lang.providers());
424        let mut environment = WriteEnvironment::for_providers(providers);
425        for element in lang.structural().all() {
426            environment.element_specs.remove(&(Arc::as_ptr(element) as usize));
427        }
428        environment
429    }
430
431    /// Returns the environment built by asking each of `providers` for the
432    /// names it registers. A provider that cannot list its names, such as the
433    /// fallback provider, adds nothing.
434    ///
435    /// The result depends only on the input: the providers are taken from the
436    /// last to the first, and within each, callable forms and parsing modes in
437    /// their fixed order and names in sorted order. Where specifications of
438    /// several providers carry one element, the one of the provider latest in
439    /// the list is recorded: the features' packages are listed in registration
440    /// order, so between features, the specification of the feature placed
441    /// last. Within one provider, the first one found is recorded.
442    ///
443    /// Every element that a specification carries is recorded, a structural
444    /// element included; [`for_lang`](Self::for_lang) builds the environment
445    /// of a language, without its structural elements.
446    pub fn for_providers<'a>(
447        providers: impl IntoIterator<Item = &'a Arc<dyn SpecsProvider<Flm>>>,
448    ) -> WriteEnvironment {
449        // Between features, the one placed last wins, as wherever the
450        // registration order picks between items of several features, so that
451        // the order the user states decides.
452        let providers: Vec<&Arc<dyn SpecsProvider<Flm>>> = providers.into_iter().collect();
453        let mut environment = WriteEnvironment::new();
454        for provider in providers.into_iter().rev() {
455            environment.index_provider(&**provider);
456        }
457        environment
458    }
459
460    /// Records, for every element that a specification of `provider` carries
461    /// and that is not recorded yet, that specification.
462    pub fn index_provider(&mut self, provider: &dyn SpecsProvider<Flm>) {
463        for &callable_type in FlmCallableType::ALL {
464            for &mode in Mode::ALL {
465                let Some(entries) = provider.iter_symbols(callable_type, mode) else {
466                    continue;
467                };
468                let mut symbols: Vec<(String, Arc<dyn CallableSpec<Flm>>)> =
469                    entries.map(|entry| (entry.name.to_string(), Arc::clone(entry.spec))).collect();
470                symbols.sort_by(|a, b| a.0.cmp(&b.0));
471                for (_, spec) in symbols {
472                    self.index_spec(spec);
473                }
474            }
475        }
476    }
477
478    /// Records `spec` for the element it carries, unless that element is
479    /// recorded already. A specification carrying no element is ignored.
480    pub fn index_spec(&mut self, spec: Arc<dyn CallableSpec<Flm>>) {
481        if let Some(element) = element_of_spec(&*spec) {
482            self.element_specs.entry(Arc::as_ptr(element) as usize).or_insert(spec);
483        }
484    }
485
486    /// Returns the specification recorded for `element`, if there is one.
487    pub fn spec_of(&self, element: &Arc<ElementSpec>) -> Option<&Arc<dyn CallableSpec<Flm>>> {
488        self.element_specs.get(&(Arc::as_ptr(element) as usize))
489    }
490
491    /// Returns how many elements have a recorded specification.
492    pub fn len(&self) -> usize {
493        self.element_specs.len()
494    }
495
496    /// Returns whether no element has a recorded specification.
497    pub fn is_empty(&self) -> bool {
498        self.element_specs.is_empty()
499    }
500}
501
502impl fmt::Debug for WriteEnvironment {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        f.debug_struct("WriteEnvironment").field("elements", &self.element_specs.len()).finish()
505    }
506}
507
508// --- stored table positions -----------------------------------------------------------
509
510/// Returns a position in one of the session's tables, in its serialized form.
511fn index_value<I: SerialIndex>(position: I) -> SerialValue {
512    SerialValue::Index { table: position.table(), index: position.index() }
513}
514
515/// Returns a serialized table reference as a typed position. The session has
516/// already translated it into its own numbering before any conversion reads it.
517fn index_from<I: SerialIndex>(
518    value: &SerialValue,
519    what: &'static str,
520) -> Result<I, DeserializeError> {
521    match value {
522        SerialValue::Index { table, index } => Ok(I::from_parts(*table, *index)),
523        other => Err(DeserializeError::failed(format!(
524            "{what}: expected a table reference, found {other:?}"
525        ))),
526    }
527}
528
529// --- the state extension ---------------------------------------------------------------------
530
531/// The serialized form of a state extension.
532#[derive(SerializableValue, DeserializableValue)]
533struct WireStateExt {
534    #[serial(name = "structural")]
535    structural: Vec<String>,
536    #[serial(name = "restricted_interior")]
537    restricted_interior: RestrictedInterior,
538    #[serial(name = "parsing")]
539    parsing: FlmParsing,
540}
541
542/// A state extension is written as `{structural, restricted_interior,
543/// parsing}`, where `structural` is the list of structural element names in
544/// their fixed order and `parsing` the parsing settings under their field
545/// names. The elements are written by name only, because a state refers to
546/// elements and does not own them.
547impl SerializableValue<Flm> for FlmStateExt {
548    fn serialize_value(
549        &self,
550        cx: &mut SerializeContext<'_, Flm>,
551    ) -> Result<SerialValue, SerializeError> {
552        let wire = WireStateExt {
553            structural: self
554                .structural
555                .all()
556                .iter()
557                .map(|element| element.name.to_string())
558                .collect(),
559            restricted_interior: self.restricted_interior.clone(),
560            parsing: FlmParsing::clone(&self.parsing),
561        };
562        wire.serialize_value(cx)
563    }
564}
565
566/// The structural elements are read back as the reading language's own shared
567/// set ([`ReadEnvironment::structural`]), so every state read in one session
568/// shares it. The serialized names are first checked against that set, and a
569/// mismatch is a read error, never a silent substitution.
570impl DeserializableValue<Flm> for FlmStateExt {
571    fn deserialize_value(
572        value: &SerialValue,
573        cx: &mut DeserializeContext<'_, Flm>,
574    ) -> Result<Self, DeserializeError> {
575        let wire = WireStateExt::deserialize_value(value, cx)?;
576        let environment = read_environment(cx)?;
577        let structural = Arc::clone(environment.structural());
578        let names: Vec<&str> =
579            structural.all().iter().map(|element| element.name.as_str()).collect();
580        if wire.structural != names {
581            return Err(DeserializeError::failed(format!(
582                "the serialized parsing state lists the structural elements {:?}, but the \
583                 structural elements of the reading language are {names:?}",
584                wire.structural
585            )));
586        }
587        Ok(FlmStateExt {
588            structural,
589            restricted_interior: wire.restricted_interior,
590            parsing: Arc::new(wire.parsing),
591        })
592    }
593}
594
595// --- the node extension -------------------------------------------------------------------
596
597/// The serialized form of a node extension.
598#[derive(SerializableValue, DeserializableValue)]
599#[serial(lang = Flm)]
600struct WireNodeExt {
601    #[serial(name = "element")]
602    element: String,
603    #[serial(name = "spec")]
604    spec: Option<SerialValue>,
605    #[serial(name = "source_map")]
606    source_map: Option<TextSourceMap>,
607    #[serial(name = "payload")]
608    payload: Option<SerialValue>,
609}
610
611/// A node extension is written as `{element, spec?, source_map?, payload?}`:
612/// the element's stable name; a reference to the specification carrying that
613/// exact element value, when the [`WriteEnvironment`] records one; the source
614/// map, when the node has one; and the payload's projection
615/// ([`PresPayload::project`]), when the node has a payload.
616impl SerializableValue<Flm> for FlmNodeExt {
617    fn serialize_value(
618        &self,
619        cx: &mut SerializeContext<'_, Flm>,
620    ) -> Result<SerialValue, SerializeError> {
621        let carrier = cx
622            .user_data::<WriteEnvironment>()
623            .and_then(|environment| environment.spec_of(&self.element).cloned());
624        let spec = match carrier {
625            Some(spec) => Some(index_value(cx.intern_spec(&spec)?)),
626            None => None,
627        };
628        let wire = WireNodeExt {
629            element: self.element.name.to_string(),
630            spec,
631            source_map: self.source_map.as_deref().cloned(),
632            payload: self.payload.as_ref().map(|payload| payload.project()),
633        };
634        wire.serialize_value(cx)
635    }
636}
637
638/// When a reference to a specification is written, the element is the one that
639/// specification carries, by identity, and its name must agree with the written
640/// name. Otherwise it is the read environment's element of that name. A payload
641/// is rebuilt by the reader registered for the element ([`PayloadReaders`]).
642impl DeserializableValue<Flm> for FlmNodeExt {
643    fn deserialize_value(
644        value: &SerialValue,
645        cx: &mut DeserializeContext<'_, Flm>,
646    ) -> Result<Self, DeserializeError> {
647        let wire = WireNodeExt::deserialize_value(value, cx)?;
648        let environment = read_environment(cx)?;
649        let element = match &wire.spec {
650            Some(reference) => {
651                let position: SpecIndex =
652                    index_from(reference, "the node extension's specification")?;
653                let spec = cx.spec(position)?;
654                let element = element_of_spec(&*spec).cloned().ok_or_else(|| {
655                    DeserializeError::failed(format!(
656                        "the node extension of the element `{}` refers to a specification that \
657                         carries no element",
658                        wire.element
659                    ))
660                })?;
661                if element.name.as_str() != wire.element {
662                    return Err(DeserializeError::failed(format!(
663                        "the node extension gives the element `{}`, but its specification \
664                         carries the element `{}`",
665                        wire.element, element.name
666                    )));
667                }
668                element
669            }
670            None => resolved_element(&wire.element, environment.resolve_element(&wire.element))?,
671        };
672        let payload = match &wire.payload {
673            Some(value) => {
674                let reader =
675                    environment.payload_reader(&wire.element).cloned().ok_or_else(|| {
676                        DeserializeError::failed(format!(
677                            "no payload reader is registered for the element `{}`",
678                            wire.element
679                        ))
680                    })?;
681                Some(reader(value, cx)?)
682            }
683            None => None,
684        };
685        Ok(FlmNodeExt {
686            element,
687            source_map: wire.source_map.map(Arc::new),
688            payload,
689        })
690    }
691}
692
693// --- the specs -----------------------------------------------------------------------------
694
695/// Written by identity, through the provenance stamp of the package that holds
696/// this specification (the record of that package and of the name it holds the
697/// specification under; see [`crate::lang::serialize`]): the reading side finds
698/// the value that the package of that name holds. A wrapper built outside a package has no stamp and cannot
699/// be written (`SerializeError::MissingProvenance`).
700impl SerializableObject<Flm> for FlmCallable {
701    fn serialize_object(
702        &self,
703        cx: &mut SerializeContext<'_, Flm>,
704    ) -> Result<SerialEntry, SerializeError> {
705        match self.provenance() {
706            Some(provenance) => provenance.serialize_object(cx),
707            None => Err(SerializeError::MissingProvenance { spec: "FlmCallable" }),
708        }
709    }
710}
711
712/// Never written in practice: the language's specification for unknown macros
713/// is the *inner* specification of an [`FlmCallable`] held by the fallback
714/// package, and a node records that wrapper, which is written by identity
715/// through the package's stamp. This implementation exists because
716/// `CallableSpec` requires one; it returns the same missing-stamp error as a
717/// wrapper without a stamp would.
718impl SerializableObject<Flm> for FlmUnknownMacroSpec {
719    fn serialize_object(
720        &self,
721        _cx: &mut SerializeContext<'_, Flm>,
722    ) -> Result<SerialEntry, SerializeError> {
723        Err(SerializeError::MissingProvenance { spec: "FlmUnknownMacroSpec" })
724    }
725}
726
727/// The serialized form of the two specifications that belong to no package:
728/// the element's name.
729#[derive(SerializableValue, DeserializableValue)]
730struct WireElementSpec {
731    #[serial(name = "element")]
732    element: String,
733}
734
735/// Written as `{element}` under [`SYNTHESIZED_IDENTIFIER`].
736impl SerializableObject<Flm> for FlmSynthesizedSpec {
737    fn serialize_object(
738        &self,
739        cx: &mut SerializeContext<'_, Flm>,
740    ) -> Result<SerialEntry, SerializeError> {
741        let wire = WireElementSpec { element: self.element().name.to_string() };
742        Ok(SerialEntry {
743            identifier: SYNTHESIZED_IDENTIFIER.into(),
744            data: wire.serialize_value(cx)?,
745        })
746    }
747}
748
749/// Rebuilt around the read environment's element of the written name.
750impl DeserializableObject<Flm> for FlmSynthesizedSpec {
751    type Output = FlmSynthesizedSpec;
752
753    fn deserialize_object(
754        value: &SerialValue,
755        cx: &mut DeserializeContext<'_, Flm>,
756    ) -> Result<FlmSynthesizedSpec, DeserializeError> {
757        let wire = WireElementSpec::deserialize_value(value, cx)?;
758        Ok(FlmSynthesizedSpec::new(resolve_element(cx, &wire.element)?))
759    }
760}
761
762/// Written as `{element}` under [`PRESENTATION_IDENTIFIER`].
763impl SerializableObject<Flm> for FlmPresentationSpec {
764    fn serialize_object(
765        &self,
766        cx: &mut SerializeContext<'_, Flm>,
767    ) -> Result<SerialEntry, SerializeError> {
768        let wire = WireElementSpec { element: self.element().name.to_string() };
769        Ok(SerialEntry {
770            identifier: PRESENTATION_IDENTIFIER.into(),
771            data: wire.serialize_value(cx)?,
772        })
773    }
774}
775
776/// Rebuilt around the read environment's element of the written name.
777impl DeserializableObject<Flm> for FlmPresentationSpec {
778    type Output = FlmPresentationSpec;
779
780    fn deserialize_object(
781        value: &SerialValue,
782        cx: &mut DeserializeContext<'_, Flm>,
783    ) -> Result<FlmPresentationSpec, DeserializeError> {
784        let wire = WireElementSpec::deserialize_value(value, cx)?;
785        Ok(FlmPresentationSpec::new(resolve_element(cx, &wire.element)?))
786    }
787}
788
789// --- the fallback gate ---------------------------------------------------------------------
790
791/// The serialized form of the fallback provider: its name.
792#[derive(SerializableValue, DeserializableValue)]
793struct WireFallbackGate {
794    #[serial(name = "name")]
795    name: String,
796}
797
798/// Written by identity as `{name}` under [`FALLBACK_GATE_IDENTIFIER`]: the gate
799/// belongs to the reading language, as a package does. The specifications it
800/// returns are held in the fallback package, which is written by identity
801/// separately.
802impl SerializableObject<Flm> for FlmFallbackProvider {
803    fn serialize_object(
804        &self,
805        cx: &mut SerializeContext<'_, Flm>,
806    ) -> Result<SerialEntry, SerializeError> {
807        let wire = WireFallbackGate { name: String::from(self.name()) };
808        Ok(SerialEntry {
809            identifier: FALLBACK_GATE_IDENTIFIER.into(),
810            data: wire.serialize_value(cx)?,
811        })
812    }
813}
814
815/// Looked up among the reading session's providers (techy's `KnownProviders`
816/// in its user data): the gate registered under the written name.
817impl DeserializableObject<Flm> for FlmFallbackProvider {
818    type Output = Arc<dyn SpecsProvider<Flm>>;
819
820    fn deserialize_object(
821        value: &SerialValue,
822        cx: &mut DeserializeContext<'_, Flm>,
823    ) -> Result<Self::Output, DeserializeError> {
824        let wire = WireFallbackGate::deserialize_value(value, cx)?;
825        let missing = || DeserializeError::MissingProvider { name: wire.name.clone() };
826        let known = cx.user_data::<KnownProviders<Flm>>().ok_or_else(missing)?;
827        known.resolve(&wire.name)?.ok_or_else(missing)
828    }
829}
830
831// --- registration --------------------------------------------------------------------------
832
833/// Prepares a reading session to read FLM data: registers the readers of
834/// techy's own serialized forms and of its LaTeX-like preset, then FLM's (the
835/// two self-contained specifications, [`SYNTHESIZED_IDENTIFIER`] and
836/// [`PRESENTATION_IDENTIFIER`], and the fallback provider,
837/// [`FALLBACK_GATE_IDENTIFIER`]).
838///
839/// Call it once per reading session; a writing session needs nothing
840/// registered. Registering the readers is only part of the preparation: the
841/// session also needs techy's `KnownProviders` and a [`ReadEnvironment`] as its
842/// user data. [`crate::dump::session::reader`] does all of it at once, and an
843/// embedding program should call that function instead.
844///
845/// # Errors
846///
847/// `RegistrationError::UnknownTableName`, which identifies the specifications
848/// table, when the session does not have techy's standard tables;
849/// `RegistrationError::DuplicateIdentifier` when the readers are registered
850/// already.
851pub fn register(session: &mut SerdeSession<Flm>) -> Result<(), RegistrationError> {
852    techy::latexlike::serialize::register(session)?;
853    // techy's `standard_tables()` answers `None` without saying which table is
854    // missing; the specs table is named, as the first this function needs.
855    let StandardTables { specs, providers, .. } = session
856        .standard_tables()
857        .ok_or_else(|| RegistrationError::UnknownTableName { name: String::from("specs") })?;
858    specs.register_type::<FlmSynthesizedSpec>(session, SYNTHESIZED_IDENTIFIER, |spec| {
859        Arc::new(spec) as Arc<dyn CallableSpec<Flm>>
860    })?;
861    specs.register_type::<FlmPresentationSpec>(session, PRESENTATION_IDENTIFIER, |spec| {
862        Arc::new(spec) as Arc<dyn CallableSpec<Flm>>
863    })?;
864    providers.register_type::<FlmFallbackProvider>(session, FALLBACK_GATE_IDENTIFIER, |gate| gate)?;
865    Ok(())
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use techy::core::specs::Scope;
872    use techy::latexlike::{MacroSpec, ParagraphBreakSpec};
873
874    use crate::lang::build::{build_language, LangInputs};
875    use crate::lang::mint::{ElementDef, SyntaxDef};
876
877    #[test]
878    fn a_provider_that_is_not_a_package_is_indexed_through_its_enumeration() {
879        // A parse-time scope (a definition made mid-parse) is a provider that is
880        // not a package; its definitions reach the environment through techy's
881        // own enumeration, `SpecsProvider::iter_symbols`.
882        let element = Arc::new(ElementSpec::new("t.emph"));
883        let spec: Arc<dyn CallableSpec<Flm>> = Arc::new(FlmCallable::new(
884            MacroSpec::<Flm>::new(Vec::new()),
885            Arc::clone(&element),
886        ));
887        let mut scope = Scope::<Flm>::new("parse-time");
888        scope.insert(FlmCallableType::Macro, "emph", spec);
889        let provider: Arc<dyn SpecsProvider<Flm>> = Arc::new(scope);
890        let environment = WriteEnvironment::for_providers([&provider]);
891        let indexed = environment.spec_of(&element).expect("the scope's definition is indexed");
892        assert!(Arc::ptr_eq(element_of_spec(&**indexed).unwrap(), &element));
893    }
894
895    #[test]
896    fn of_two_providers_carrying_one_element_the_later_ones_spec_is_recorded() {
897        let element = Arc::new(ElementSpec::new("t.emph"));
898        let provider = |name: &str, macro_name: &str| -> (Arc<dyn SpecsProvider<Flm>>, Arc<dyn CallableSpec<Flm>>) {
899            let spec: Arc<dyn CallableSpec<Flm>> = Arc::new(FlmCallable::new(
900                MacroSpec::<Flm>::new(Vec::new()),
901                Arc::clone(&element),
902            ));
903            let mut scope = Scope::<Flm>::new(name);
904            scope.insert(FlmCallableType::Macro, macro_name, Arc::clone(&spec));
905            (Arc::new(scope), spec)
906        };
907        let (earlier, _) = provider("earlier", "emph");
908        let (later, later_spec) = provider("later", "textit");
909        let environment = WriteEnvironment::for_providers([&earlier, &later]);
910        let indexed = environment.spec_of(&element).expect("the element is indexed");
911        assert!(Arc::ptr_eq(indexed, &later_spec));
912    }
913
914    #[test]
915    fn the_write_environment_indexes_the_spec_carrying_a_declared_element() {
916        let element = Arc::new(ElementSpec::new("t.emph"));
917        let def = ElementDef::new(
918            "t",
919            ["emph"],
920            SyntaxDef::Macro { args: Vec::new() },
921            Arc::clone(&element),
922        );
923        let mut inputs = LangInputs::new();
924        inputs.elements.push(def);
925        let lang = build_language(inputs);
926        let environment = WriteEnvironment::for_lang(&lang);
927        let spec = environment.spec_of(&element).expect("the element's spec is indexed");
928        assert!(Arc::ptr_eq(element_of_spec(&**spec).unwrap(), &element));
929        assert!(environment.spec_of(&lang.structural().text).is_none());
930    }
931
932    #[test]
933    fn a_spec_carrying_no_element_is_not_indexed() {
934        let mut environment = WriteEnvironment::new();
935        environment.index_spec(Arc::new(ParagraphBreakSpec) as Arc<dyn CallableSpec<Flm>>);
936        assert!(environment.is_empty());
937    }
938}