flm_core/core/data/table.rs
1//! Tables and the ways to refer to them: the trait [`Table`] that a table's
2//! value type implements, the declaration [`TableDef`], the captured value type
3//! [`TableType`], the registry-assigned number [`TableId`], and the typed table
4//! keys [`TableName<T>`] and [`TableHandle<T>`].
5//!
6//! A table is typed data that one stage writes beside the frozen trees and other
7//! stages read; its identity is its registered dotted name, never its Rust type,
8//! and that name is also a [capability](crate::core::registry::CapabilityDef),
9//! the capability of the table having been written ([`Table`]).
10//!
11//! # Names, value types and table numbers
12//!
13//! A feature declares a table ([`TableDef`]) under a dotted name that the
14//! feature owns (`flm.labels`, `flm.lowered.html`), with one Rust value type.
15//! When the registry is built, each declared table receives a [`TableId`], a
16//! number that the store uses as the table's key.
17//!
18//! The name, not the Rust type, identifies a table, because one Rust type can
19//! hold several tables: the type holding lowered trees is declared once per
20//! backend, so the type alone cannot say which table is meant. The value type is
21//! captured at declaration as a [`TableType`] (its Rust `TypeId` together with
22//! its operations as plain function pointers), so that the store, its fold
23//! ([`fold_outs`](crate::core::data::store::fold_outs)) and the inspection dumps
24//! ([`crate::dump`]) can handle every table without naming its Rust type.
25//!
26//! When the registry is built, it compares the value type of every table
27//! reference in a stage's declarations with the table's declared value type. At
28//! every access through a typed table key,
29//! [`ComputedView::get`](crate::core::data::store::ComputedView::get),
30//! [`StageOut::table`](crate::core::data::store::StageOut::table) and
31//! [`Run::table`](crate::core::run::Run::table) compare the key's value type
32//! with the declared one and return
33//! [`AccessError::TypeMismatch`](crate::core::data::store::AccessError::TypeMismatch)
34//! on a mismatch, so the conversion back to the value type behind the key cannot
35//! fail.
36//!
37//! # Typed table keys
38//!
39//! A reader or a writer refers to a table through a typed table key, which
40//! carries the table's name and its value type, so that a read returns the
41//! value already typed:
42//!
43//! - a [`TableName<T>`] constant, for a table with a name fixed at compile
44//! time; the crate that defines the value type exports it beside the type
45//! (`pub const LABELS: TableName<Labels> = TableName::new("flm.labels")`);
46//! - a [`TableHandle<T>`], for a table declared under a name computed at run
47//! time;
48//! - the value type itself, when it implements [`SingletonTable`] because
49//! exactly one table uses it: `T::NAME` is then the name that the store's
50//! singleton methods use.
51//!
52//! The read and write methods of a stage
53//! ([`ComputedView::get`](crate::core::data::store::ComputedView::get),
54//! [`StageOut::table`](crate::core::data::store::StageOut::table),
55//! [`StageCx::get`](crate::core::run::StageCx::get)), [`Run::table`](crate::core::run::Run::table)
56//! and [`Externals::install`](crate::core::run::Externals::install) accept any
57//! [`TableKey`]. Every typed table key has a
58//! type-erased form, [`TableRef`] (the name plus the identity of the value
59//! type), which stage declarations, plans and messages carry.
60//!
61//! # A table's name is a capability
62//!
63//! Every table's name is also a
64//! [capability](crate::core::registry::CapabilityDef): the capability of the
65//! table having been written. A stage that declares a write of the table therefore provides
66//! that capability, and a stage that declares a read of it requires it; the
67//! registry derives both. See [stages, capabilities, and
68//! plans](crate::guide::concepts_overview#stages-capabilities-and-plans).
69
70// This module uses the name newtypes of `crate::model::names` and techy's
71// serialized-value type; it does not depend on the registry, on stages, on plan
72// construction or on the runner.
73
74use std::any::{Any, TypeId};
75use std::fmt;
76use std::marker::PhantomData;
77
78use techy::core::node::NodeTree;
79use techy::serialize::SerialValue;
80
81use crate::lang::Flm;
82use crate::model::addr::{NodeAddr, TreeId};
83use crate::model::names::{CapName, FeatureName};
84use crate::model::options::short_type_name;
85
86/// The context through which a table writes node addresses, tree identifiers
87/// and trees when it serializes itself for inspection ([`Table::project`]).
88///
89/// A table that holds node addresses or tree identifiers calls these methods
90/// rather than writing an address itself, so that the serialized form of every
91/// table writes addresses the same way. The library's implementation is
92/// [`TableProjection`](crate::dump::project::TableProjection), which resolves
93/// each address against the trees it was built over.
94///
95/// A table that holds a [synthesized
96/// value](crate::guide::concepts_overview#synthesized-values) writes that tree
97/// in full through [`ProjectCx::tree`], never by its identifier: value catch-up
98/// gives a synthesized value its identifier, numbered per stage call
99/// ([`StageCx::resolve_value`](crate::core::run::StageCx::resolve_value)), so the
100/// identifier means something only inside the stage call that brought the value
101/// up to date, and a reader of the serialized table could not resolve it. See
102/// [`TreeId`].
103///
104/// See also [`crate::dump::project`].
105pub trait ProjectCx {
106 /// Writes a node address; the library's implementation writes the node's
107 /// element name and source position, as `element@line:col`.
108 fn node_ref(&self, addr: NodeAddr) -> SerialValue;
109
110 /// Writes a tree identifier.
111 fn tree_ref(&self, id: TreeId) -> SerialValue;
112
113 /// Writes a synthesized value that a table holds: the tree itself, in
114 /// full. The library's implementation writes its nodes as it writes any
115 /// tree; the default implementation writes the tree's plain text
116 /// ([`plain_text`](crate::lang::text::plain_text)).
117 fn tree(&self, tree: &NodeTree<Flm>) -> SerialValue {
118 SerialValue::Str(crate::lang::text::plain_text(tree))
119 }
120}
121
122/// What a table piece holds: data keyed by node address, nothing, or a fact
123/// about the document as a whole.
124///
125/// A table piece is the part of one table that one stage invocation produced;
126/// the runner folds the pieces into the store ([`Table::absorb`]), and a
127/// piece's class says whether it states a fact about the document as a whole.
128/// A table's value type classifies its own table pieces with
129/// [`Table::piece_class`].
130///
131/// The class matters only during [value
132/// catch-up](crate::guide::concepts_overview#value-catch-up), which runs
133/// per-tree stages (stages of
134/// [`Scope::PerTree`](crate::core::stage::Scope::PerTree), run once for each
135/// tree) again over a [synthesized
136/// value](crate::guide::concepts_overview#synthesized-values) and folds their
137/// table pieces into a catch-up store of its own. A table piece keyed by node
138/// address, or an empty one, is accepted there. A table piece that states a
139/// fact about the document as a whole (a label declared inside the synthesized
140/// value, a numbered point) is refused with
141/// [`StoreError::DocumentFactInValue`](crate::core::data::store::StoreError::DocumentFactInValue),
142/// because a synthesized value is not part of the document and must not add to
143/// the document's facts.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum PieceClass {
146 /// The table piece holds data keyed by node address; an empty table keyed
147 /// by node address also returns this class.
148 NodeKeyed,
149 /// The table piece of a table not keyed by node address holds nothing.
150 Empty,
151 /// The table piece states a fact about the document as a whole, such as
152 /// an entry keyed by a label or a count; a synthesized value may not
153 /// produce one.
154 DocumentFact,
155}
156
157/// The trait of a table's value type.
158///
159/// A table is typed data that one stage writes beside the frozen trees and other
160/// stages read; its identity is its registered dotted name, never its Rust type,
161/// and that name is also a [capability](crate::core::registry::CapabilityDef).
162/// See [frozen trees and computed
163/// data](crate::guide::concepts_overview#frozen-trees-and-computed-data) for
164/// why computed data is kept in tables, and the [module documentation](self) for
165/// how names, value types and typed table keys relate.
166///
167/// A map keyed by node address and a map keyed by a symbolic name are the usual
168/// shapes of a table, but any value type can be one: a document-wide count is a
169/// table whose [`absorb`](Table::absorb) adds.
170///
171/// To add a table, implement this trait on its value type, declare the table
172/// in a feature with
173/// [`FeatureBuilder::table`](crate::core::registry::FeatureBuilder::table) (or
174/// [`FeatureBuilder::external_table`](crate::core::registry::FeatureBuilder::external_table)
175/// for a table no stage writes), declare it as a write of the stage that
176/// produces it ([`StageDecl::writes`](crate::core::stage::StageDecl::writes)) and
177/// as a read of each stage that reads it
178/// ([`Needs::reads`](crate::core::stage::Needs::reads)), and export a
179/// [`TableName`] constant for its readers. A stage
180/// writes its part of the table through
181/// [`StageOut::table`](crate::core::data::store::StageOut::table), and a later
182/// stage reads the whole table through
183/// [`StageCx::get`](crate::core::run::StageCx::get).
184///
185/// The value type must implement `Default`: a stage's table piece starts as the
186/// default value, and a stage that declared a write but produced nothing still
187/// installs a default (empty) table.
188///
189/// See also [`SingletonTable`] for a value type used by exactly one table, and
190/// [`TableType`] for the type-erased form of a value type.
191pub trait Table: Any + Send + Sync + Default {
192 /// Combines `piece`, a table piece produced by the same stage, into
193 /// `self`.
194 ///
195 /// The runner calls this when it folds one stage's table pieces into the
196 /// store: it keeps the first table piece and absorbs each following one
197 /// into it, in the run's order of the trees
198 /// ([`Run::tree_order`](crate::core::run::Run::tree_order)). The resulting
199 /// table must therefore depend only on the table pieces and their order.
200 /// The table type decides what happens on a collision: a table of labels,
201 /// for example, records the duplicate so that a later check stage can
202 /// report it.
203 fn absorb(&mut self, piece: Self);
204
205 /// Serializes the table as plain data, for the inspection dumps
206 /// ([`crate::dump`]) and tests.
207 ///
208 /// The default implementation returns a placeholder holding the short name
209 /// of the Rust type, `<TypeName>`. A table with a readable serialized form
210 /// overrides it and writes every node address, tree identifier or
211 /// synthesized value it holds through `cx`; see [`ProjectCx`].
212 fn project(&self, cx: &dyn ProjectCx) -> SerialValue {
213 let _ = cx;
214 SerialValue::Str(format!("<{}>", short_type_name(std::any::type_name::<Self>())))
215 }
216
217 /// Classifies `self`, taken as a table piece: see [`PieceClass`].
218 ///
219 /// The runner calls this only on the table pieces produced during value
220 /// catch-up. The default implementation returns
221 /// [`NodeKeyed`](PieceClass::NodeKeyed), which fits every table keyed by
222 /// node address. A table keyed symbolically, or holding a document-wide
223 /// value, returns [`Empty`](PieceClass::Empty) when it holds nothing and
224 /// [`DocumentFact`](PieceClass::DocumentFact) otherwise.
225 fn piece_class(&self) -> PieceClass {
226 PieceClass::NodeKeyed
227 }
228}
229
230/// A table value type that exactly one table uses: [`NAME`](SingletonTable::NAME)
231/// is that table's name.
232///
233/// A value type that implements this trait lets a reader or a writer refer to
234/// its table by the Rust type alone: [`StageCx::get_singleton`],
235/// [`ComputedView::get_singleton`] and [`StageOut::table_singleton`] find the
236/// name through it.
237///
238/// A value type declared under several names, such as the type holding one
239/// backend's lowered trees, must not implement this trait, since it has no
240/// single name. For that reason `NAME` is defined on this separate trait rather
241/// than on [`Table`]: on [`Table`], it would force such a value type to invent a
242/// name.
243///
244/// [`StageCx::get_singleton`]: crate::core::run::StageCx::get_singleton
245/// [`ComputedView::get_singleton`]: crate::core::data::store::ComputedView::get_singleton
246/// [`StageOut::table_singleton`]: crate::core::data::store::StageOut::table_singleton
247pub trait SingletonTable: Table {
248 /// The name of the one table that uses this value type.
249 const NAME: &'static str;
250
251 /// The typed table key ([`TableName`]) of that one table.
252 fn table_name() -> TableName<Self>
253 where
254 Self: Sized,
255 {
256 TableName::new(Self::NAME)
257 }
258}
259
260type ErasedTable = Box<dyn Any + Send + Sync>;
261
262// The three helpers below downcast a type-erased table back to `T`. The
263// downcast is unreachable-by-construction — the store keys by `TableId` and the
264// registry verified the value type at declaration — so they `expect` with a
265// message naming the invariant rather than returning a result nobody could
266// act on.
267
268fn make_default_erased<T: Table>() -> ErasedTable {
269 Box::new(T::default())
270}
271
272fn absorb_erased<T: Table>(acc: &mut ErasedTable, piece: ErasedTable) {
273 let piece = *piece
274 .downcast::<T>()
275 .expect("a table piece is combined only with a piece of its declared type");
276 acc.downcast_mut::<T>()
277 .expect("a table piece is combined only with a piece of its declared type")
278 .absorb(piece);
279}
280
281fn project_erased<T: Table>(table: &(dyn Any + Send + Sync), cx: &dyn ProjectCx) -> SerialValue {
282 table.downcast_ref::<T>().expect("a table is projected through its declared type").project(cx)
283}
284
285fn piece_class_erased<T: Table>(table: &(dyn Any + Send + Sync)) -> PieceClass {
286 table
287 .downcast_ref::<T>()
288 .expect("a table is classified through its declared type")
289 .piece_class()
290}
291
292/// A table value type's identity and operations, captured when the table is
293/// declared, so that the store, its fold
294/// ([`fold_outs`](crate::core::data::store::fold_outs)) and the inspection dumps
295/// ([`crate::dump`]) can handle every table without naming its Rust type.
296///
297/// A `TableType` holds the value type's `TypeId` (checked so that converting a
298/// type-erased table back to its value type cannot fail), its Rust name (for
299/// messages), a constructor of an empty value (so that a declared write with no
300/// table piece still installs a table), and the three operations of [`Table`]:
301/// [`absorb`](Table::absorb), [`project`](Table::project) and
302/// [`piece_class`](Table::piece_class).
303///
304/// Create one with [`TableType::of`]. A [`TableDef`] carries one, and so do the
305/// resolved reads and writes of a stage
306/// ([`ReadEntry`](crate::core::data::store::ReadEntry),
307/// [`WriteEntry`](crate::core::data::store::WriteEntry)).
308///
309/// Two `TableType`s are equal exactly when they capture the same Rust type.
310#[derive(Clone, Copy)]
311pub struct TableType {
312 type_id: TypeId,
313 type_name: &'static str,
314 make_default: fn() -> ErasedTable,
315 absorb: fn(&mut ErasedTable, ErasedTable),
316 project: fn(&(dyn Any + Send + Sync), &dyn ProjectCx) -> SerialValue,
317 piece_class: fn(&(dyn Any + Send + Sync)) -> PieceClass,
318}
319
320impl TableType {
321 /// Captures the identity and operations of the value type `T`.
322 pub fn of<T: Table>() -> TableType {
323 TableType {
324 type_id: TypeId::of::<T>(),
325 type_name: std::any::type_name::<T>(),
326 make_default: make_default_erased::<T>,
327 absorb: absorb_erased::<T>,
328 project: project_erased::<T>,
329 piece_class: piece_class_erased::<T>,
330 }
331 }
332
333 /// The value type's `TypeId`.
334 pub fn type_id(&self) -> TypeId {
335 self.type_id
336 }
337
338 /// The value type's full Rust name.
339 pub fn type_name(&self) -> &'static str {
340 self.type_name
341 }
342
343 /// The value type's short name, for messages.
344 pub fn short_name(&self) -> &'static str {
345 short_type_name(self.type_name)
346 }
347
348 /// Whether `T` is the captured value type.
349 pub fn is<T: Any>(&self) -> bool {
350 self.type_id == TypeId::of::<T>()
351 }
352
353 /// Creates an empty table of the value type (its `Default` value),
354 /// type-erased.
355 pub fn make_default(&self) -> ErasedTable {
356 (self.make_default)()
357 }
358
359 /// Absorbs the table piece `piece` into `acc`, through the value type's
360 /// [`Table::absorb`].
361 ///
362 /// # Panics
363 ///
364 /// Panics if `acc` or `piece` is not a value of the captured value type.
365 /// The store keys tables by [`TableId`] and the registry checked the value
366 /// type when the table was declared, so a caller working through the store
367 /// cannot cause this panic.
368 pub fn absorb(&self, acc: &mut ErasedTable, piece: ErasedTable) {
369 (self.absorb)(acc, piece)
370 }
371
372 /// Serializes `table` for inspection, through the value type's
373 /// [`Table::project`].
374 ///
375 /// # Panics
376 ///
377 /// Panics if `table` is not a value of the captured value type; see
378 /// [`absorb`](TableType::absorb).
379 pub fn project(&self, table: &(dyn Any + Send + Sync), cx: &dyn ProjectCx) -> SerialValue {
380 (self.project)(table, cx)
381 }
382
383 /// Classifies the table piece `table`, through the value type's
384 /// [`Table::piece_class`].
385 ///
386 /// # Panics
387 ///
388 /// Panics if `table` is not a value of the captured value type; see
389 /// [`absorb`](TableType::absorb).
390 pub fn piece_class(&self, table: &(dyn Any + Send + Sync)) -> PieceClass {
391 (self.piece_class)(table)
392 }
393}
394
395impl PartialEq for TableType {
396 fn eq(&self, other: &TableType) -> bool {
397 self.type_id == other.type_id
398 }
399}
400
401impl Eq for TableType {}
402
403impl fmt::Debug for TableType {
404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405 write!(f, "TableType({})", self.short_name())
406 }
407}
408
409/// A table as a feature declares it: its name, which is also its capability;
410/// its value type; its description; and the feature that owns it.
411///
412/// [`FeatureBuilder::table`](crate::core::registry::FeatureBuilder::table) and
413/// [`FeatureBuilder::external_table`](crate::core::registry::FeatureBuilder::external_table)
414/// create it; the built registry holds it in the table's
415/// [`TableEntry`](crate::core::registry::TableEntry).
416///
417/// It is written to data with `Serialize`; see [serialized
418/// forms](crate::core::registry#serialized-forms).
419#[derive(Debug, Clone)]
420#[derive(serde::Serialize, schemars::JsonSchema)]
421pub struct TableDef {
422 /// The table's dotted name, which is also the name of the capability of
423 /// the table having been written.
424 pub name: CapName,
425 /// The value type's captured identity and operations.
426 #[serde(skip)]
427 pub ty: TableType,
428 /// A description of what the table holds, written for a person. For an
429 /// external table that a run needs and the caller did not install, the
430 /// error [`RunError::MissingExternal`](crate::core::run::RunError::MissingExternal)
431 /// includes it.
432 pub docs: String,
433 /// The feature that declared the table.
434 pub owner: FeatureName,
435}
436
437/// The number of a declared table within one registry; the store keys its
438/// tables by it.
439///
440/// The registry assigns the numbers when it is built, consecutively and in its
441/// own deterministic order. A `TableId` identifies a table only within the
442/// registry that assigned it: the same number in another registry may refer to
443/// another table. Its `Display` form is `table#N`.
444///
445/// It is written to data with `Serialize`; see [serialized
446/// forms](crate::core::registry#serialized-forms).
447#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
448#[derive(serde::Serialize, schemars::JsonSchema)]
449pub struct TableId(pub u32);
450
451impl fmt::Display for TableId {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453 write!(f, "table#{}", self.0)
454 }
455}
456
457/// The type-erased form of a typed table key: the table's name together with
458/// the identity of the value type the key expects.
459///
460/// Stage declarations, plans and messages carry a `TableRef`, because none of
461/// them is generic over the value type. The registry checks every `TableRef`
462/// of a stage declaration against the [`TableDef`] of the same name when it is
463/// built; a typed table key used at an access site is checked again there.
464/// Its `Display` form is the name followed by the value type's short name in
465/// parentheses.
466///
467/// It is written to data with `Serialize`; see [serialized
468/// forms](crate::core::registry#serialized-forms).
469#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
470#[derive(serde::Serialize, schemars::JsonSchema)]
471pub struct TableRef {
472 /// The table's name.
473 pub name: CapName,
474 /// The expected value type's identity.
475 #[serde(skip)]
476 pub type_id: TypeId,
477 /// The expected value type's full Rust name, for messages.
478 pub type_name: &'static str,
479}
480
481impl TableRef {
482 /// Creates a reference to the table `name`, whose value type is `T`.
483 pub fn of<T: Table>(name: impl Into<CapName>) -> TableRef {
484 TableRef {
485 name: name.into(),
486 type_id: TypeId::of::<T>(),
487 type_name: std::any::type_name::<T>(),
488 }
489 }
490
491 /// The value type's short name, for messages.
492 pub fn short_type_name(&self) -> &'static str {
493 short_type_name(self.type_name)
494 }
495}
496
497impl fmt::Display for TableRef {
498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
499 write!(f, "{} ({})", self.name, self.short_type_name())
500 }
501}
502
503/// A typed table key: a value that refers to a table together with its value
504/// type, namely a [`TableName`], a [`TableHandle`], or a reference to either.
505///
506/// The read and write methods of [`ComputedView`], [`StageOut`], [`StageCx`]
507/// and [`Run`], and [`Externals::install`], are generic over this trait, so a
508/// caller passes whichever key it has.
509///
510/// [`ComputedView`]: crate::core::data::store::ComputedView
511/// [`StageOut`]: crate::core::data::store::StageOut
512/// [`StageCx`]: crate::core::run::StageCx
513/// [`Run`]: crate::core::run::Run
514/// [`Externals::install`]: crate::core::run::Externals::install
515pub trait TableKey {
516 /// The table's value type.
517 type Table: Table;
518
519 /// The type-erased form of this key.
520 fn table_ref(&self) -> TableRef;
521
522 /// The table's name.
523 fn table_name(&self) -> CapName {
524 self.table_ref().name
525 }
526}
527
528impl<K: TableKey + ?Sized> TableKey for &K {
529 type Table = K::Table;
530
531 fn table_ref(&self) -> TableRef {
532 (**self).table_ref()
533 }
534}
535
536/// A typed table key for a table whose name is fixed at compile time.
537///
538/// The crate that defines a table's value type exports one constant of this
539/// type beside the value type for each table it declares under a fixed name:
540///
541/// ```
542/// use flm_core::core::data::table::{Table, TableName};
543///
544/// #[derive(Default)]
545/// struct Labels;
546/// impl Table for Labels {
547/// fn absorb(&mut self, _piece: Labels) {}
548/// }
549///
550/// pub const LABELS: TableName<Labels> = TableName::new("example.labels");
551/// assert_eq!(LABELS.name(), "example.labels");
552/// ```
553///
554/// Use a [`TableHandle`] instead when the name is known only at run time;
555/// [`TableName::handle`] converts a `TableName` into one.
556pub struct TableName<T> {
557 name: &'static str,
558 _table: PhantomData<fn() -> T>,
559}
560
561impl<T: Table> TableName<T> {
562 /// Creates the key of the table `name`, whose value type is `T`. The
563 /// function is `const`, so the key can be a constant.
564 pub const fn new(name: &'static str) -> TableName<T> {
565 TableName { name, _table: PhantomData }
566 }
567
568 /// The table's name.
569 pub const fn name(&self) -> &'static str {
570 self.name
571 }
572
573 /// The [`TableHandle`] of the same table.
574 pub fn handle(&self) -> TableHandle<T> {
575 TableHandle::new(self.name)
576 }
577}
578
579impl<T> Clone for TableName<T> {
580 fn clone(&self) -> TableName<T> {
581 *self
582 }
583}
584
585impl<T> Copy for TableName<T> {}
586
587impl<T> fmt::Debug for TableName<T> {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 write!(f, "TableName<{}>({:?})", short_type_name(std::any::type_name::<T>()), self.name)
590 }
591}
592
593impl<T: Table> TableKey for TableName<T> {
594 type Table = T;
595
596 fn table_ref(&self) -> TableRef {
597 TableRef::of::<T>(self.name)
598 }
599}
600
601/// A typed table key for a table whose name is known only at run time.
602///
603/// Use it for a table declared under a computed name, such as the table of
604/// lowered trees of each backend, `flm.lowered.<backend>`, or under a name read
605/// from configuration. Where the name is fixed at compile time, use a
606/// [`TableName`] instead.
607///
608/// [`FeatureBuilder::table`](crate::core::registry::FeatureBuilder::table)
609/// returns a handle for the table it declares. The registry checks the name and
610/// the value type when it is built, so a handle returned by a declaration always
611/// reads the table as its own value type. A handle created by hand, pairing a
612/// name with a value type that the registry does not pair it with, is refused
613/// at the access site with
614/// [`AccessError::TypeMismatch`](crate::core::data::store::AccessError::TypeMismatch);
615/// it does not cause a panic.
616#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
617pub struct TableHandle<T> {
618 name: CapName,
619 _table: PhantomData<fn() -> T>,
620}
621
622impl<T: Table> TableHandle<T> {
623 /// Creates the handle of the table `name`, whose value type is `T`.
624 pub fn new(name: impl Into<CapName>) -> TableHandle<T> {
625 TableHandle { name: name.into(), _table: PhantomData }
626 }
627
628 /// The table's name.
629 pub fn name(&self) -> &CapName {
630 &self.name
631 }
632}
633
634impl<T> Clone for TableHandle<T> {
635 fn clone(&self) -> TableHandle<T> {
636 TableHandle { name: self.name.clone(), _table: PhantomData }
637 }
638}
639
640impl<T> fmt::Debug for TableHandle<T> {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642 write!(f, "TableHandle<{}>({:?})", short_type_name(std::any::type_name::<T>()), self.name)
643 }
644}
645
646impl<T: Table> TableKey for TableHandle<T> {
647 type Table = T;
648
649 fn table_ref(&self) -> TableRef {
650 TableRef::of::<T>(self.name.clone())
651 }
652}
653
654impl<T: Table> From<TableName<T>> for TableHandle<T> {
655 fn from(name: TableName<T>) -> TableHandle<T> {
656 name.handle()
657 }
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663
664 #[derive(Default)]
665 struct Count(u32);
666
667 impl Table for Count {
668 fn absorb(&mut self, piece: Count) {
669 self.0 += piece.0;
670 }
671 }
672
673 impl SingletonTable for Count {
674 const NAME: &'static str = "test.count";
675 }
676
677 const COUNT: TableName<Count> = TableName::new("test.count");
678
679 #[test]
680 fn a_table_type_absorbs_and_defaults_through_the_vtable() {
681 let ty = TableType::of::<Count>();
682 let mut acc = ty.make_default();
683 ty.absorb(&mut acc, Box::new(Count(2)));
684 ty.absorb(&mut acc, Box::new(Count(3)));
685 assert_eq!(acc.downcast_ref::<Count>().unwrap().0, 5);
686 assert!(ty.is::<Count>());
687 assert_eq!(ty.short_name(), "Count");
688 }
689
690 #[test]
691 fn typed_keys_erase_to_the_same_reference() {
692 let by_const = COUNT.table_ref();
693 let by_handle = TableHandle::<Count>::new("test.count").table_ref();
694 let by_singleton = Count::table_name().table_ref();
695 assert_eq!(by_const, by_handle);
696 assert_eq!(by_const, by_singleton);
697 let by_reference = <&TableName<Count> as TableKey>::table_ref(&&COUNT);
698 assert_eq!(by_reference, by_const);
699 assert_eq!(by_const.short_type_name(), "Count");
700 }
701
702 #[test]
703 fn the_default_projection_names_the_type() {
704 struct NoCx;
705 impl ProjectCx for NoCx {
706 fn node_ref(&self, _: NodeAddr) -> SerialValue {
707 SerialValue::Null
708 }
709 fn tree_ref(&self, _: TreeId) -> SerialValue {
710 SerialValue::Null
711 }
712 }
713 assert_eq!(Count(1).project(&NoCx), SerialValue::Str("<Count>".to_string()));
714 assert_eq!(Count(1).piece_class(), PieceClass::NodeKeyed);
715 }
716}