flm_core/dump/session.rs
1//! Serialization sessions for FLM: writing parsed fragments and trees in
2//! techy's serialized form (the *wire form*) and reading them back into
3//! in-memory objects.
4//!
5//! The wire form is techy's lossless serialization of a parse, which
6//! [`crate::lang::serialize`] implements for FLM. Unlike the one-way
7//! [projection](crate::dump::project), it reads back into in-memory objects with
8//! their sharing and identity intact. The `flm dump --view wire` command
9//! prints it, the library's round-trip tests use it, and a program can use it
10//! to store parses (for example in a cache) and read them back.
11//!
12//! A techy serialization session holds one table per kind of object (sources,
13//! parsing states, trees, diagnostics, and so on) and writes each object once.
14//! An FLM session holds techy's standard tables plus one table of this
15//! library's own, `flm.fragments` ([`FragmentSerdeDriver`]), whose entry for a
16//! fragment ties together its source, its tree, its diagnostics and its region
17//! layout ([`FragmentLayout`]).
18//!
19//! # Creating a session
20//!
21//! - [`writer`] creates a writing session over a built language
22//! ([`BuiltLang`], available as
23//! [`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang)). The
24//! language supplies the writing environment
25//! ([`WriteEnvironment::for_lang`]), which records which specification
26//! carries which element.
27//! - [`reader`] and [`reader_with`] create a reading session over a built
28//! language. Reading needs the reading environment: the language's
29//! specification providers ([`known_providers`]), its [structural
30//! elements](crate::lang::structural::StructuralElements), an
31//! [`ElementResolver`] for every other element name found in the data (an
32//! [`ElementTable`] when no registry is at hand), and the [`PayloadReaders`]
33//! that rebuild the payloads of presentation nodes.
34//!
35//! Every session is created with the recursion guard of the language
36//! ([`BuiltLang::guard`]), so that writing or
37//! reading a deeply nested tree is refused instead of overflowing the stack.
38//! Like every guarded run, writing and reading must therefore execute on a
39//! [worker thread](crate::lang::guard::on_worker_thread), a thread created with
40//! enough stack; the functions of this module do not create one.
41//!
42//! Once a session is created, [`write_fragment`] and [`write_tree`] write objects
43//! into a writing session, and [`read_fragment`] and [`read_tree`] read them from a reading
44//! session. [`json::segment_line`](crate::dump::json::segment_line) writes the
45//! segment a session emits as one line of JSON.
46//!
47//! A techy *profile* is a string that a writing session records in its stream
48//! and that a reading session compares with its own: a stream with a different
49//! profile is refused. No session of this module sets one, because only the
50//! program can declare which configurations are compatible: a program that
51//! caches serialized data calls techy's
52//! [`set_profile`](crate::techy::serialize::SerdeSession::set_profile) on both its writer and its reader with the same
53//! string, such as its registry's
54//! [`digest`](crate::core::registry::FlmRegistry::digest), while a debugging
55//! dump sets none, so that any stream can be inspected.
56//!
57//! # What a round trip preserves
58//!
59//! Writing a fragment and reading it back preserves: the tree's structure;
60//! every span, into the same sources, shared; each node's parsing state,
61//! shared as before and rebuilt once per state; the specifications by identity
62//! (the instances the language's packages hold); the elements by identity,
63//! through those specifications, otherwise through the element resolver; the
64//! structural elements (the reading language's own); the diagnostics'
65//! identifiers, data and spans; the diagnostics collection's retention limit and
66//! its counts (the number of suppressed diagnostics and the number of errors,
67//! so that a fragment reports the same thing about whether it holds errors on
68//! both sides); and the fragment's region layout. The collection is rebuilt
69//! from those parts, and counts that contradict each other are refused
70//! ([`DeserializeError::InconsistentDiagnosticCounts`]) rather than corrected.
71//!
72//! A round trip does not preserve node ids and tree tags, which are new on
73//! reading, nor the Rust types of diagnostic conditions, which come back as
74//! techy's deserialized condition carrying the same identifier and data.
75//!
76//! # Identity and positions
77//!
78//! A fragment is an *object* of its table: writing the same `Arc<Fragment>`
79//! twice yields one entry, because a fragment's identity is that `Arc`. Its tree
80//! is written by its own `Arc` as well, so no tree is copied on writing.
81//!
82//! Every position these functions return or take ([`FragmentIndex`], techy's
83//! [`TreeIndex`]) belongs to the session that assigned it and must never be
84//! passed to another session. A position is carried between sessions as its
85//! table's name together with its numeric index, and the receiving session
86//! rebuilds it against its own table.
87
88use std::any::Any;
89use std::collections::BTreeMap;
90use std::fmt;
91use std::sync::Arc;
92
93use techy::core::node::NodeTree;
94use techy::error::Diagnostics;
95use techy::serialize::{
96 DeserializableValue, DeserializeContext, DeserializeError, DiagnosticIndex, KnownProviders,
97 ObjectSerdeDriver, RegistrationError, SerdeSession, SerialEntry, SerialIndex, SerialValue,
98 SerializableValue, SerializeContext, SerializeError, SourceIndex, StandardTableInterning,
99 StandardTableReading, StandardTables, TableHandle, TreeIndex,
100};
101
102use crate::model::doc::{Fragment, FragmentLayout};
103use crate::model::element::ElementSpec;
104use crate::model::names::{ElementName, FeatureName};
105use crate::core::registry::HOST_FEATURE;
106use crate::lang::build::BuiltLang;
107use crate::lang::flm::Flm;
108use crate::lang::guard;
109use crate::lang::structural::StructuralElements;
110
111/// The environment types and the registration function of a reading session,
112/// re-exported here as their canonical public path. They are defined in
113/// [`crate::lang::serialize`], beside the conversions that read them from the
114/// session.
115pub use crate::lang::serialize::{
116 AmbiguousElement, ElementResolver, FALLBACK_GATE_IDENTIFIER, PRESENTATION_IDENTIFIER,
117 PayloadReader, PayloadReaders, ReadEnvironment, SYNTHESIZED_IDENTIFIER, WriteEnvironment,
118 register,
119};
120
121// --- a map-based element resolver ---------------------------------------------------------
122
123/// An [`ElementResolver`] that looks element values up by name in a table the
124/// caller fills: what a test, or a program without a registry, passes to
125/// [`reader`].
126///
127/// Fill it with the structural elements of a language
128/// ([`with_structural`](ElementTable::with_structural)) and the elements its
129/// declarations carry ([`with`](ElementTable::with),
130/// [`from_elements`](ElementTable::from_elements)). Every element value
131/// inserted under a name is kept. A name held by several values resolves to
132/// the error [`AmbiguousElement`] rather than to one of them, because a reader
133/// that has only a name cannot tell which value was written.
134#[derive(Clone, Default)]
135pub struct ElementTable {
136 elements: BTreeMap<ElementName, Vec<Arc<ElementSpec>>>,
137}
138
139impl ElementTable {
140 /// Creates an empty table.
141 pub fn new() -> ElementTable {
142 ElementTable::default()
143 }
144
145 /// Creates a table holding the given element values.
146 pub fn from_elements(elements: impl IntoIterator<Item = Arc<ElementSpec>>) -> ElementTable {
147 let mut table = ElementTable::new();
148 for element in elements {
149 table.insert(element);
150 }
151 table
152 }
153
154 /// Builder: adds one element value.
155 pub fn with(mut self, element: Arc<ElementSpec>) -> ElementTable {
156 self.insert(element);
157 self
158 }
159
160 /// Builder: adds every element of a set of structural elements, such as a
161 /// language's ([`BuiltLang::structural`]).
162 pub fn with_structural(mut self, structural: &StructuralElements) -> ElementTable {
163 for element in structural.all() {
164 self.insert(Arc::clone(element));
165 }
166 self
167 }
168
169 /// Adds one element value under its name and returns how many values the
170 /// name now holds. The same `Arc` is never added twice.
171 pub fn insert(&mut self, element: Arc<ElementSpec>) -> usize {
172 let values = self.elements.entry(element.name.clone()).or_default();
173 if !values.iter().any(|held| Arc::ptr_eq(held, &element)) {
174 values.push(element);
175 }
176 values.len()
177 }
178
179 /// Returns the element values held under `name`, in insertion order (empty
180 /// when the name is not held).
181 pub fn values(&self, name: &str) -> &[Arc<ElementSpec>] {
182 self.elements.get(name).map_or(&[], Vec::as_slice)
183 }
184
185 /// Returns the names held, in sorted order.
186 pub fn names(&self) -> impl Iterator<Item = &ElementName> + '_ {
187 self.elements.keys()
188 }
189}
190
191impl ElementResolver for ElementTable {
192 /// Returns the one value held under `name`, `None` when there is none, and
193 /// [`AmbiguousElement`] when there are several. A table does not record which
194 /// feature declared a value, so the error lists the host
195 /// ([`HOST_FEATURE`]) as the owner, once per value.
196 fn resolve_element(&self, name: &str) -> Result<Option<Arc<ElementSpec>>, AmbiguousElement> {
197 match self.values(name) {
198 [] => Ok(None),
199 [one] => Ok(Some(Arc::clone(one))),
200 several => Err(AmbiguousElement {
201 name: ElementName::from(name),
202 owners: vec![FeatureName::from(HOST_FEATURE); several.len()],
203 }),
204 }
205 }
206}
207
208impl fmt::Debug for ElementTable {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_map()
211 .entries(self.elements.iter().map(|(name, values)| (name, values.len())))
212 .finish()
213 }
214}
215
216// --- the fragments table -----------------------------------------------------------------
217
218/// The name of the fragments table that every FLM session holds beside techy's
219/// standard tables ([`FragmentSerdeDriver`]).
220pub const FRAGMENTS_TABLE: &str = "flm.fragments";
221
222/// The identifier of a fragment's entry in the fragments table.
223pub const FRAGMENT_IDENTIFIER: &str = "flm.fragment";
224
225/// The serialized name of techy's trees table, given in the `UnknownTableName`
226/// error when a session lacks the standard tables. techy's `standard_tables()`
227/// returns `None` without saying which table is missing; the trees table is the
228/// one every function here needs.
229const TREES_TABLE: &str = "trees";
230
231techy::serial_index! {
232 /// A position in the fragments table, the serialized reference to a
233 /// [`Fragment`] (the `Index` type of [`FragmentSerdeDriver`]). It belongs to
234 /// the session that assigned it; see the [module documentation](self).
235 pub struct FragmentIndex;
236}
237
238/// Writes and reads the entries of the fragments table ([`FRAGMENTS_TABLE`]),
239/// which holds one kind of object, fragments ([`FRAGMENT_IDENTIFIER`]).
240///
241/// [`writer`] and [`reader`] register it on every FLM session. A fragment's
242/// entry is `{source, tree, diagnostics: {items, limit, suppressed,
243/// error_count}, layout}`:
244///
245/// - `source`: the position of the fragment's source in the sources table;
246/// - `tree`: the position of its tree in the trees table (the tree written by
247/// its `Arc`, as a tree with techy's unit annotation, that is, with no
248/// per-node annotation value);
249/// - `diagnostics`: the positions of its retained diagnostics in the
250/// diagnostics table, in the order they were recorded, with the collection's
251/// retention limit, its number of suppressed diagnostics and its number of
252/// errors;
253/// - `layout`: the fragment's region layout ([`FragmentLayout`]), `blocks`,
254/// `inline` or `inline-or-blocks`.
255///
256/// Reading rebuilds the fragment from the shared source, the rebuilt tree and
257/// a diagnostics collection rebuilt from the retained items, the limit and the
258/// counts after techy checks that the counts are consistent. An entry whose
259/// tree was parsed from another source than the entry's source is refused. The
260/// [module documentation](self) says what a round trip preserves.
261#[derive(Debug, Default)]
262pub struct FragmentSerdeDriver;
263
264/// The fields of a fragment's entry in the fragments table.
265#[derive(SerializableValue, DeserializableValue)]
266struct WireFragment {
267 #[serial(name = "source")]
268 source: SerialValue,
269 #[serial(name = "tree")]
270 tree: SerialValue,
271 #[serial(name = "diagnostics")]
272 diagnostics: WireDiagnostics,
273 #[serial(name = "layout")]
274 layout: String,
275}
276
277/// The fields of a fragment's diagnostics in its entry: the positions of the
278/// retained diagnostics, the collection's retention limit and its counts.
279#[derive(SerializableValue, DeserializableValue)]
280struct WireDiagnostics {
281 #[serial(name = "items")]
282 items: Vec<SerialValue>,
283 #[serial(name = "limit")]
284 limit: usize,
285 #[serial(name = "suppressed")]
286 suppressed: usize,
287 #[serial(name = "error_count")]
288 error_count: usize,
289}
290
291fn index_value<I: SerialIndex>(position: I) -> SerialValue {
292 SerialValue::Index { table: position.table(), index: position.index() }
293}
294
295fn index_from<I: SerialIndex>(value: &SerialValue, what: &str) -> Result<I, DeserializeError> {
296 match value {
297 SerialValue::Index { table, index } => Ok(I::from_parts(*table, *index)),
298 other => Err(DeserializeError::failed(format!(
299 "{what}: expected a table reference, found {other:?}"
300 ))),
301 }
302}
303
304fn layout_name(layout: FragmentLayout) -> &'static str {
305 match layout {
306 FragmentLayout::Blocks => "blocks",
307 FragmentLayout::Inline => "inline",
308 FragmentLayout::InlineOrBlocks => "inline-or-blocks",
309 }
310}
311
312fn layout_from(name: &str) -> Result<FragmentLayout, DeserializeError> {
313 match name {
314 "blocks" => Ok(FragmentLayout::Blocks),
315 "inline" => Ok(FragmentLayout::Inline),
316 "inline-or-blocks" => Ok(FragmentLayout::InlineOrBlocks),
317 other => Err(DeserializeError::failed(format!(
318 "the fragment layout `{other}` must be one of `blocks`, `inline` and `inline-or-blocks`"
319 ))),
320 }
321}
322
323fn no_table_to_write(name: &str) -> SerializeError {
324 SerializeError::UnknownTableName { name: String::from(name) }
325}
326
327fn no_table_to_read(name: &str) -> DeserializeError {
328 DeserializeError::UnknownTableName { name: String::from(name) }
329}
330
331impl ObjectSerdeDriver<Flm> for FragmentSerdeDriver {
332 type Object = Fragment;
333 type Index = FragmentIndex;
334
335 fn table_name(&self) -> &'static str {
336 FRAGMENTS_TABLE
337 }
338
339 fn homogeneous_identifier(&self) -> Option<&'static str> {
340 Some(FRAGMENT_IDENTIFIER)
341 }
342
343 fn serialize_object(
344 &self,
345 fragment: &Arc<Fragment>,
346 cx: &mut SerializeContext<'_, Flm>,
347 ) -> Result<SerialEntry, SerializeError> {
348 let StandardTables { trees, diagnostics, .. } =
349 cx.standard_tables().ok_or_else(|| no_table_to_write(TREES_TABLE))?;
350 let source = cx.intern_source(fragment.source())?;
351 let tree_arc: Arc<NodeTree<Flm>> = Arc::clone(fragment.tree());
352 let tree_object: Arc<dyn Any + Send + Sync> = tree_arc;
353 let tree = cx.intern(trees, &tree_object)?;
354 let items = fragment
355 .diags()
356 .iter()
357 .map(|diagnostic| {
358 cx.intern(diagnostics, &Arc::new(diagnostic.clone())).map(index_value)
359 })
360 .collect::<Result<Vec<_>, _>>()?;
361 let wire = WireFragment {
362 source: index_value(source),
363 tree: index_value(tree),
364 diagnostics: WireDiagnostics {
365 items,
366 limit: fragment.diags().limit(),
367 suppressed: fragment.diags().suppressed(),
368 error_count: fragment.diags().error_count(),
369 },
370 layout: String::from(layout_name(fragment.layout())),
371 };
372 Ok(SerialEntry { identifier: FRAGMENT_IDENTIFIER.into(), data: wire.serialize_value(cx)? })
373 }
374
375 fn deserialize_object(
376 &self,
377 entry: &SerialEntry,
378 cx: &mut DeserializeContext<'_, Flm>,
379 ) -> Result<Arc<Fragment>, DeserializeError> {
380 let wire = WireFragment::deserialize_value(&entry.data, cx)?;
381 let StandardTables { trees, diagnostics, .. } =
382 cx.standard_tables().ok_or_else(|| no_table_to_read(TREES_TABLE))?;
383 let source =
384 cx.source(index_from::<SourceIndex>(&wire.source, "the fragment's source")?)?;
385 let tree_object =
386 cx.object(trees, index_from::<TreeIndex>(&wire.tree, "the fragment's tree")?)?;
387 let tree = tree_object.downcast::<NodeTree<Flm>>().map_err(|_| {
388 DeserializeError::failed(
389 "the entry of the fragment's tree is not a tree of FLM nodes (`NodeTree<Flm>`)",
390 )
391 })?;
392 if !Arc::ptr_eq(tree.root().span().source(), &source) {
393 return Err(DeserializeError::failed(
394 "the fragment's source is not the source its tree was parsed from",
395 ));
396 }
397 let mut items = Vec::with_capacity(wire.diagnostics.items.len());
398 for item in &wire.diagnostics.items {
399 let position = index_from::<DiagnosticIndex>(item, "a fragment diagnostic")?;
400 items.push((*cx.object(diagnostics, position)?).clone());
401 }
402 let WireDiagnostics { limit, suppressed, error_count, .. } = wire.diagnostics;
403 let diags = Diagnostics::from_parts(items, limit, suppressed, error_count)
404 .map_err(DeserializeError::InconsistentDiagnosticCounts)?;
405 let layout = layout_from(&wire.layout)?;
406 Ok(Arc::new(Fragment::new(source, tree, diags, layout)))
407 }
408}
409
410/// Returns the handle of the fragments table of `session`, or `None` when the
411/// session has none (a session not created by [`writer`] or [`reader`]).
412pub fn fragments_table(session: &SerdeSession<Flm>) -> Option<TableHandle<FragmentSerdeDriver>> {
413 session.table_handle::<FragmentSerdeDriver>(FRAGMENTS_TABLE)
414}
415
416// --- the sessions ----------------------------------------------------------------------------
417
418/// Returns the specification providers (techy's packages, and FLM's fallback
419/// gate) against which a reading session resolves the serialized references to
420/// specifications: every provider of the language's initial parsing state
421/// (techy's built-in `_builtin` package included) and every provider the
422/// language built from the features' declarations ([`BuiltLang::providers`]).
423///
424/// These are the very instances the language's parses use, so data read back
425/// shares them with freshly parsed data. techy's recipe for its `_builtin`
426/// package (the description from which techy rebuilds that package) is added
427/// as well, used only for a name that no provider above
428/// holds. [`reader_with`] sets this value on the session.
429pub fn known_providers(lang: &BuiltLang) -> KnownProviders<Flm> {
430 let mut known = KnownProviders::<Flm>::new();
431 for provider in lang.initial_state().scopes().providers() {
432 known.insert(Arc::clone(provider));
433 }
434 for provider in lang.providers() {
435 known.insert(Arc::clone(provider));
436 }
437 techy::latexlike::serialize::register_package_recipes(&mut known);
438 known
439}
440
441/// Creates a session with the standard tables and the fragments table, under the
442/// language's recursion-guard policy.
443fn session(lang: &BuiltLang) -> Result<SerdeSession<Flm>, RegistrationError> {
444 let mut session = guard::serde_session(SerdeSession::<Flm>::new(), lang.guard());
445 session.register_table(FragmentSerdeDriver)?;
446 Ok(session)
447}
448
449/// Creates a writing session over the built language `lang`.
450///
451/// The session holds techy's standard tables and the fragments table, runs
452/// under the language's recursion guard, and carries the language's writing
453/// environment ([`WriteEnvironment::for_lang`]), so that each node records the
454/// specification that carries its element; a node of a [structural
455/// element](crate::lang::structural) records its element's name alone. Writing needs no reading
456/// environment. No profile is set (see the [module documentation](self)): a
457/// program that caches serialized data calls techy's
458/// [`set_profile`](SerdeSession::set_profile) on the returned session.
459///
460/// Write objects with [`write_fragment`] and [`write_tree`], then take the
461/// session's output with techy's
462/// [`take_segment`](SerdeSession::take_segment), or with
463/// [`take_segment_with_main`](SerdeSession::take_segment_with_main) to record
464/// one position as the segment's *main entry* (the object a reader should
465/// start from), and write it with
466/// [`segment_line`](crate::dump::json::segment_line).
467///
468/// # Panics
469///
470/// Only if a new session refused the fragments table, which cannot happen: a
471/// session holding just the standard tables accepts one more table with a
472/// distinct name and a non-empty identifier. The
473/// `expect` states an invariant of this module, and no requirement on the
474/// caller is involved. This is why `writer` returns the session directly while
475/// [`reader`] returns a `Result`: the registrations of a reader (techy's and
476/// FLM's readers, [`register`]) can fail.
477pub fn writer(lang: &BuiltLang) -> SerdeSession<Flm> {
478 let mut session = session(lang).expect("a fresh session accepts the fragments table");
479 session.set_user_data(WriteEnvironment::for_lang(lang));
480 session
481}
482
483/// Creates a reading session over the built language `lang`, in which
484/// `elements` resolves every element name other than the structural elements.
485///
486/// This is [`reader_with`] with no payload readers; use [`reader_with`] to read
487/// trees that hold presentation nodes.
488///
489/// # Errors
490///
491/// The registration errors of [`register`].
492pub fn reader(
493 lang: &BuiltLang,
494 elements: Arc<dyn ElementResolver>,
495) -> Result<SerdeSession<Flm>, RegistrationError> {
496 reader_with(lang, elements, PayloadReaders::new())
497}
498
499/// Creates a reading session over the built language `lang`, with payload
500/// readers.
501///
502/// The session holds the same tables as a [`writer`]'s, runs under the
503/// language's recursion guard, and carries the reading environment: the
504/// language's specification providers ([`known_providers`]), its structural
505/// elements, `elements` to resolve every other element name found in the data,
506/// and `payloads` to rebuild the payloads of presentation nodes. The readers of
507/// FLM's stored forms are registered on it ([`register`]). No profile is set
508/// (see the [module documentation](self)): a program that caches serialized
509/// data calls techy's [`set_profile`](SerdeSession::set_profile) with the same
510/// string as on its writer.
511///
512/// Give the session a segment with techy's
513/// [`push_segment`](SerdeSession::push_segment), which returns the position of
514/// the segment's main entry (the object the writer recorded as the one to
515/// start from), if it has one; then read objects with [`read_fragment`] and
516/// [`read_tree`].
517///
518/// # Errors
519///
520/// The registration errors of [`register`].
521pub fn reader_with(
522 lang: &BuiltLang,
523 elements: Arc<dyn ElementResolver>,
524 payloads: PayloadReaders,
525) -> Result<SerdeSession<Flm>, RegistrationError> {
526 let mut session = session(lang)?;
527 session.set_user_data(known_providers(lang));
528 session.set_user_data(
529 ReadEnvironment::new(Arc::clone(lang.structural()), elements)
530 .with_payload_readers(payloads),
531 );
532 register(&mut session)?;
533 Ok(session)
534}
535
536/// Writes `fragment` into the fragments table of `session` and returns its
537/// position, which belongs to `session`. Writing the same `Arc` again returns
538/// the existing position.
539///
540/// Call it on a worker thread (see the [module documentation](self)).
541///
542/// # Errors
543///
544/// [`SerializeError::UnknownTableName`] if the session has no fragments table
545/// (it was not created by [`writer`]); [`SerializeError::MissingProvenance`] if a
546/// specification belongs to no package; the other errors of techy's writing
547/// (interning) of an object.
548pub fn write_fragment(
549 session: &mut SerdeSession<Flm>,
550 fragment: &Arc<Fragment>,
551) -> Result<FragmentIndex, SerializeError> {
552 let table = fragments_table(session).ok_or_else(|| no_table_to_write(FRAGMENTS_TABLE))?;
553 session.intern(table, fragment)
554}
555
556/// Reads the fragment at `position` of the fragments table of `session`, and
557/// returns the `Arc` the session holds: the same one for every call with that
558/// position.
559///
560/// `position` must belong to `session`, never be taken from another session.
561/// For a segment pushed into `session`, rebuild it from the index that
562/// [`push_segment`](SerdeSession::push_segment) returned for the segment's main
563/// entry, with techy's [`TableHandle::position`] on the handle from
564/// [`fragments_table`].
565/// Call this function on a worker thread (see the [module
566/// documentation](self)).
567///
568/// # Errors
569///
570/// [`DeserializeError::UnknownTableName`] if the session has no fragments table;
571/// the other errors of techy's reading of an object.
572pub fn read_fragment(
573 session: &mut SerdeSession<Flm>,
574 position: FragmentIndex,
575) -> Result<Arc<Fragment>, DeserializeError> {
576 let table = fragments_table(session).ok_or_else(|| no_table_to_read(FRAGMENTS_TABLE))?;
577 session.object(table, position)
578}
579
580/// Writes `tree` into the trees table of `session` and returns its position,
581/// which belongs to `session`.
582///
583/// The tree is written by its `Arc`, without a copy; writing the same `Arc`
584/// again returns the existing position. Call this function on a worker thread
585/// (see the [module documentation](self)).
586///
587/// # Errors
588///
589/// [`SerializeError::UnknownTableName`] if the session has no trees table; the
590/// other errors of techy's writing (interning) of an object.
591pub fn write_tree(
592 session: &mut SerdeSession<Flm>,
593 tree: &Arc<NodeTree<Flm>>,
594) -> Result<TreeIndex, SerializeError> {
595 let table =
596 session.standard_tables().ok_or_else(|| no_table_to_write(TREES_TABLE))?.trees;
597 let tree_arc: Arc<NodeTree<Flm>> = Arc::clone(tree);
598 let object: Arc<dyn Any + Send + Sync> = tree_arc;
599 session.intern(table, &object)
600}
601
602/// Reads the tree at `position` of the trees table of `session`, and returns
603/// the shared `Arc` the session holds.
604///
605/// `position` must belong to `session`, never be taken from another session.
606/// For a segment pushed into `session`, rebuild it from the index that
607/// [`push_segment`](SerdeSession::push_segment) returned for the segment's main
608/// entry, with techy's [`TableHandle::position`] on the trees table's handle
609/// (the `trees` field of
610/// [`SerdeSession::standard_tables`](SerdeSession::standard_tables)). Call this
611/// function on a worker thread (see the [module documentation](self)).
612///
613/// # Errors
614///
615/// [`DeserializeError::UnknownTableName`] if the session has no trees table; a
616/// failure if the entry is not a `NodeTree<Flm>` (a tree of FLM nodes with
617/// techy's unit annotation); the other errors of
618/// techy's reading of an object.
619pub fn read_tree(
620 session: &mut SerdeSession<Flm>,
621 position: TreeIndex,
622) -> Result<Arc<NodeTree<Flm>>, DeserializeError> {
623 let table = session.standard_tables().ok_or_else(|| no_table_to_read(TREES_TABLE))?.trees;
624 let object = session.object(table, position)?;
625 object
626 .downcast::<NodeTree<Flm>>()
627 .map_err(|_| {
628 DeserializeError::failed("the entry is not a tree of FLM nodes (`NodeTree<Flm>`)")
629 })
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 #[test]
637 fn an_element_table_reports_a_name_several_values_share() {
638 let first = Arc::new(ElementSpec::new("t.heading"));
639 let second = Arc::new(ElementSpec::new("t.heading"));
640 let table = ElementTable::new().with(Arc::clone(&first)).with(Arc::clone(&second));
641 let error = table.resolve_element("t.heading").unwrap_err();
642 let host = FeatureName::from(HOST_FEATURE);
643 let name = ElementName::from("t.heading");
644 let expected = AmbiguousElement { name, owners: vec![host; 2] };
645 assert_eq!(error, expected);
646 assert!(table.resolve_element("t.other").unwrap().is_none());
647 }
648
649 #[test]
650 fn an_element_table_resolves_a_name_with_one_value() {
651 let element = Arc::new(ElementSpec::new("t.emph"));
652 let mut table = ElementTable::new();
653 assert_eq!(table.insert(Arc::clone(&element)), 1);
654 assert_eq!(table.insert(Arc::clone(&element)), 1, "the same value is held once");
655 let resolved = table.resolve_element("t.emph").unwrap().expect("the name resolves");
656 assert!(Arc::ptr_eq(&resolved, &element));
657 }
658
659 #[test]
660 fn a_reading_environment_over_a_language_holds_every_minted_provider() {
661 let lang = crate::lang::build::build_language(crate::lang::build::LangInputs::new());
662 let known = known_providers(&lang);
663 for provider in lang.providers() {
664 assert!(known.get(provider.name()).is_some(), "`{}` is held", provider.name());
665 }
666 assert!(known.get("_builtin").is_some(), "the seed's dispatch package is held");
667 }
668}