techy 0.1.3

A fast, extensible LaTeX parser for Rust
Documentation
//! Heterogeneous tables — tables holding trait objects of several concrete types.
//!
//! [`DispatchingSerdeDriver`] is such a table's driver, [`ObjectReader`] the registered
//! way to rebuild the objects of one identifier, and [`IdentifierResolver`] a supplier
//! of readers for the identifiers of one prefix. The registration methods are on the
//! table's handle.

use alloc::borrow::Cow;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::any::Any;
use core::fmt;
use core::marker::PhantomData;

use hashbrown::HashMap;

use super::super::error::{DeserializeError, RegistrationError, SerializeError};
use super::super::object::{DeserializableObject, SerializableLang, SerializableObject};
use super::super::value::{SerialEntry, SerialIndex, SerialValue};
use super::context::{DeserializeContext, SerializeContext};
use super::driver::{ObjectSerdeDriver, TableHandle};
use super::session::{SerdeSession, TableRegistry};

/// The driver of a *heterogeneous* table: a table whose objects are trait objects
/// (`Arc<T>` with `T = dyn …`) of several concrete types, each with its own identifier
/// and serialized form.
///
/// Writing needs no registration: every object serializes itself through its own
/// [`SerializableObject::serialize_object`], a supertrait method reached through the
/// trait object.
///
/// Reading dispatches on the entry's identifier, in this order: the readers registered
/// on the table's handle ([`TableHandle::register_type`] /
/// [`register_reader`](TableHandle::register_reader)); then the registered
/// [`IdentifierResolver`]s ([`register_resolver`](TableHandle::register_resolver)), each
/// registered for a *namespace* — an identifier prefix owned by one framework or package
/// — and each asked at most once per identifier, since its answer (a reader or a
/// decline) is kept for the session's lifetime; and, when nothing recognizes the
/// identifier, the error [`DeserializeError::UnknownIdentifier`]. An unknown identifier
/// is an error, never a guess.
///
/// Registrations belong to the session, not to the driver, so one driver value can be
/// registered in any number of sessions.
///
/// `T` is the trait object type; `I` the table's position type (a
/// [`serial_index!`](crate::serialize::serial_index) type). The table is heterogeneous
/// ([`homogeneous_identifier`](ObjectSerdeDriver::homogeneous_identifier) is `None`):
/// its entries record their identifier on the wire.
pub struct DispatchingSerdeDriver<L, T: ?Sized, I> {
    table_name: &'static str,
    types: PhantomData<DriverMarker<L, T, I>>,
}

/// The variance-and-`Send`/`Sync` marker of [`DispatchingSerdeDriver`]'s phantom data
/// (kept out of the field type so the field stays simple).
type DriverMarker<L, T, I> = fn() -> (L, Arc<T>, I);

impl<L, T: ?Sized, I> DispatchingSerdeDriver<L, T, I> {
    /// The driver of the heterogeneous table named `table_name` (a deliberately
    /// chosen, stable name — see [`ObjectSerdeDriver::table_name`]).
    pub fn new(table_name: &'static str) -> Self {
        DispatchingSerdeDriver { table_name, types: PhantomData }
    }
}

impl<L, T: ?Sized, I> fmt::Debug for DispatchingSerdeDriver<L, T, I> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DispatchingSerdeDriver").field("table_name", &self.table_name).finish()
    }
}

impl<L, T, I> ObjectSerdeDriver<L> for DispatchingSerdeDriver<L, T, I>
where
    L: SerializableLang,
    T: ?Sized + SerializableObject<L> + Send + Sync + 'static,
    I: SerialIndex,
{
    type Object = T;
    type Index = I;

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

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

    fn serialize_object(
        &self,
        object: &Arc<T>,
        cx: &mut SerializeContext<'_, L>,
    ) -> Result<SerialEntry, SerializeError> {
        object.serialize_object(cx)
    }

    /// Rebuilds the object of `entry` through the reader for its identifier.
    ///
    /// The reader is the one registered, in the session `cx` belongs to, on the table of
    /// this driver's [`table_name`](ObjectSerdeDriver::table_name). Readers are found by
    /// table name, so the call works from any deserialization context of that session.
    ///
    /// # Errors
    ///
    /// [`DeserializeError::UnknownIdentifier`] when no reader is registered and no
    /// resolver answers; a resolver's own error; the reader's failure; and
    /// [`DeserializeError::Failed`] when the session has no table of this driver's
    /// name (the driver was called with a context of another session).
    fn deserialize_object(
        &self,
        entry: &SerialEntry,
        cx: &mut DeserializeContext<'_, L>,
    ) -> Result<Arc<T>, DeserializeError> {
        let reader = find_reader::<L, T>(cx, self.table_name, &entry.identifier)?;
        reader.deserialize_object(&entry.data, cx)
    }
}

/// How the objects of one identifier are rebuilt: the read side's registered unit.
///
/// A reader is held by a heterogeneous table's dispatch (see
/// [`DispatchingSerdeDriver`]) and produced by [`IdentifierResolver`]s. It wraps one
/// deserialization routine producing `Arc<T>`: either a type's own
/// [`DeserializableObject`] impl ([`from_type`](ObjectReader::from_type)) or any routine
/// at all ([`new`](ObjectReader::new) — how a resolver wraps a definition it obtained at
/// run time).
///
/// Cloning is cheap: the routine is shared.
pub struct ObjectReader<L: SerializableLang, T: ?Sized> {
    read: Arc<ReadFn<L, T>>,
}

/// The deserialization routine an [`ObjectReader`] wraps.
type ReadFn<L, T> =
    dyn Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<Arc<T>, DeserializeError> + Send + Sync;

impl<L: SerializableLang, T: ?Sized + Send + Sync + 'static> ObjectReader<L, T> {
    /// A reader from a routine: called with the entry's data and the context, it
    /// rebuilds the object.
    pub fn new(
        read: impl Fn(&SerialValue, &mut DeserializeContext<'_, L>) -> Result<Arc<T>, DeserializeError>
            + Send
            + Sync
            + 'static,
    ) -> Self {
        ObjectReader { read: Arc::new(read) }
    }

    /// A reader from a type's own [`DeserializableObject`] impl.
    ///
    /// `C::deserialize_object` rebuilds the value, and `wrap` turns it into the table's
    /// `Arc<T>`: `Arc::new` (with the coercion to the trait object) for a type whose
    /// `Output` is itself, or the identity function for a type whose `Output` is already
    /// an `Arc<T>` — an object looked up in the reading environment.
    pub fn from_type<C: DeserializableObject<L>>(
        wrap: impl Fn(C::Output) -> Arc<T> + Send + Sync + 'static,
    ) -> Self {
        ObjectReader::new(move |value, cx| C::deserialize_object(value, cx).map(&wrap))
    }

    /// Rebuild an object from `value`.
    ///
    /// # Errors
    ///
    /// Whatever the routine reports.
    pub fn deserialize_object(
        &self,
        value: &SerialValue,
        cx: &mut DeserializeContext<'_, L>,
    ) -> Result<Arc<T>, DeserializeError> {
        (self.read)(value, cx)
    }
}

impl<L: SerializableLang, T: ?Sized> Clone for ObjectReader<L, T> {
    fn clone(&self) -> Self {
        ObjectReader { read: Arc::clone(&self.read) }
    }
}

impl<L: SerializableLang, T: ?Sized> fmt::Debug for ObjectReader<L, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObjectReader").finish_non_exhaustive()
    }
}

/// A supplier of readers for one namespace of a heterogeneous table — a *namespace*
/// being an identifier prefix owned by one framework or package.
///
/// Asked for an identifier no registered reader covers, a resolver answers with the
/// [`ObjectReader`] for it — constructed on demand, from a definition it obtains at run
/// time under its own trust policy — or declines.
///
/// A resolver is registered with a prefix on the table's handle
/// ([`TableHandle::register_resolver`]) and is asked only for identifiers beginning with
/// that prefix. Its answer for an identifier, a reader or a decline, is kept by the
/// session, so it is never asked twice for one identifier; the answers recorded during a
/// segment push that fails are dropped with it.
pub trait IdentifierResolver<L: SerializableLang, T: ?Sized>: Send + Sync {
    /// The reader for `identifier`, or `None` to decline. `cx` gives access to the
    /// session — the caller's user data in particular.
    ///
    /// # Errors
    ///
    /// The resolver recognizes the identifier but cannot supply a reader for it
    /// (typically [`DeserializeError::failed`] with the reason); the deserialization
    /// fails with that error.
    fn resolve(
        &self,
        identifier: &str,
        cx: &mut DeserializeContext<'_, L>,
    ) -> Result<Option<ObjectReader<L, T>>, DeserializeError>;
}

/// The read-side registrations of one heterogeneous table, kept by the session:
/// the readers by identifier (registered), the memoized resolver answers by
/// identifier (a reader, or `None` for a decline), and the resolvers by prefix, in
/// registration order.
pub(super) struct ReadDispatch<L: SerializableLang, T: ?Sized> {
    readers: HashMap<String, ObjectReader<L, T>>,
    memo: HashMap<String, Option<ObjectReader<L, T>>>,
    resolvers: Vec<(String, Arc<dyn IdentifierResolver<L, T>>)>,
}

impl<L: SerializableLang, T: ?Sized> Default for ReadDispatch<L, T> {
    fn default() -> Self {
        ReadDispatch { readers: HashMap::new(), memo: HashMap::new(), resolvers: Vec::new() }
    }
}

impl<L: SerializableLang, T: ?Sized + Send + Sync + 'static> TableRegistry for ReadDispatch<L, T> {
    fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync) {
        self
    }

    fn forget_memo(&mut self, identifier: &str) {
        self.memo.remove(identifier);
    }
}

/// The reader for `identifier` in the table named `table_name` of the session `cx`
/// belongs to: registered reader, else the memoized resolver answer, else the
/// resolvers whose prefix matches — the longest prefix first, registration order
/// among equal lengths — the first answer memoized (a decline by all of them too);
/// else [`DeserializeError::UnknownIdentifier`].
fn find_reader<L: SerializableLang, T: ?Sized + Send + Sync + 'static>(
    cx: &mut DeserializeContext<'_, L>,
    table_name: &'static str,
    identifier: &str,
) -> Result<ObjectReader<L, T>, DeserializeError> {
    let unknown = || DeserializeError::UnknownIdentifier { table: table_name, identifier: String::from(identifier) };
    let Some(ordinal) = cx.session_mut().table_ordinal_by_name(table_name) else {
        return Err(DeserializeError::failed(alloc::format!(
            "the driver of table `{table_name}` was called with a context of a session that has \
             no table of that name"
        )));
    };
    let candidates: Vec<Arc<dyn IdentifierResolver<L, T>>> = {
        let session = cx.session_mut();
        let Some(dispatch) = session.registry_mut::<ReadDispatch<L, T>>(ordinal) else {
            return Err(unknown());
        };
        if let Some(reader) = dispatch.readers.get(identifier) {
            return Ok(reader.clone());
        }
        if let Some(answer) = dispatch.memo.get(identifier) {
            return answer.clone().ok_or_else(unknown);
        }
        // The matching resolvers, cloned out so that they can use the context.
        let mut matching: Vec<(usize, Arc<dyn IdentifierResolver<L, T>>)> = dispatch
            .resolvers
            .iter()
            .filter(|(prefix, _)| identifier.starts_with(prefix.as_str()))
            .map(|(prefix, resolver)| (prefix.len(), Arc::clone(resolver)))
            .collect();
        // Longest prefix first; `sort_by_key` is stable, so registration order decides
        // among equal lengths.
        matching.sort_by_key(|(len, _)| core::cmp::Reverse(*len));
        matching.into_iter().map(|(_, resolver)| resolver).collect()
    };
    let mut answer = None;
    for resolver in candidates {
        // A resolver's error is not an answer: nothing is memoized, the error propagates.
        if let Some(reader) = resolver.resolve(identifier, cx)? {
            answer = Some(reader);
            break;
        }
    }
    let session = cx.session_mut();
    if let Some(dispatch) = session.registry_mut::<ReadDispatch<L, T>>(ordinal) {
        dispatch.memo.insert(String::from(identifier), answer.clone());
        session.record_memo(ordinal, identifier);
    }
    answer.ok_or_else(unknown)
}

impl<L, T, I> TableHandle<DispatchingSerdeDriver<L, T, I>>
where
    L: SerializableLang,
    T: ?Sized + SerializableObject<L> + Send + Sync + 'static,
    I: SerialIndex,
{
    /// Registers the reader for `identifier` in this table of `session`, from `C`'s own
    /// [`DeserializableObject`] impl.
    ///
    /// Entries with that identifier are then rebuilt by `C::deserialize_object`, and
    /// `wrap` turns the result into the table's `Arc<T>` (see
    /// [`ObjectReader::from_type`]).
    ///
    /// # Errors
    ///
    /// [`RegistrationError::UnknownTable`] when the handle is not one of `session`'s;
    /// [`RegistrationError::DuplicateIdentifier`] when a reader for `identifier` is
    /// already registered (or a resolver's reader for it was kept).
    pub fn register_type<C: DeserializableObject<L>>(
        self,
        session: &mut SerdeSession<L>,
        identifier: impl Into<Cow<'static, str>>,
        wrap: impl Fn(C::Output) -> Arc<T> + Send + Sync + 'static,
    ) -> Result<(), RegistrationError> {
        self.register_reader(session, identifier, ObjectReader::from_type::<C>(wrap))
    }

    /// Register `reader` as the reader for `identifier` in this table of `session`.
    ///
    /// # Errors
    ///
    /// As [`register_type`](TableHandle::register_type).
    pub fn register_reader(
        self,
        session: &mut SerdeSession<L>,
        identifier: impl Into<Cow<'static, str>>,
        reader: ObjectReader<L, T>,
    ) -> Result<(), RegistrationError> {
        let ordinal = session.table_index(self).map_err(|table| RegistrationError::UnknownTable { table })?;
        let table = session.table_name(ordinal);
        let identifier: Cow<'static, str> = identifier.into();
        let dispatch = session
            .registry_mut::<ReadDispatch<L, T>>(ordinal)
            .ok_or(RegistrationError::UnknownTable { table: self.id() })?;
        let kept_reader = matches!(dispatch.memo.get(&*identifier), Some(Some(_)));
        if dispatch.readers.contains_key(&*identifier) || kept_reader {
            return Err(RegistrationError::DuplicateIdentifier { table, identifier: identifier.into_owned() });
        }
        dispatch.readers.insert(identifier.into_owned(), reader);
        Ok(())
    }

    /// Registers `resolver` for the identifiers beginning with `prefix` — its namespace
    /// — in this table of `session`.
    ///
    /// Several resolvers may be registered, with any prefixes; the empty prefix matches
    /// every identifier. For an identifier no registered reader covers, the resolvers
    /// whose prefix matches are asked in order of decreasing prefix length — the most
    /// specific first, registration order among equal lengths — until one answers.
    ///
    /// The answer, either the reader or the decline of every matching resolver, is kept
    /// for the session's lifetime, so no resolver is asked twice for one identifier.
    ///
    /// # Errors
    ///
    /// [`RegistrationError::UnknownTable`] when the handle is not one of `session`'s.
    pub fn register_resolver(
        self,
        session: &mut SerdeSession<L>,
        prefix: impl Into<String>,
        resolver: Arc<dyn IdentifierResolver<L, T>>,
    ) -> Result<(), RegistrationError> {
        let ordinal = session.table_index(self).map_err(|table| RegistrationError::UnknownTable { table })?;
        let dispatch = session
            .registry_mut::<ReadDispatch<L, T>>(ordinal)
            .ok_or(RegistrationError::UnknownTable { table: self.id() })?;
        dispatch.resolvers.push((prefix.into(), resolver));
        Ok(())
    }
}