oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
Documentation
//! Type descriptions for checking view data and component props.

mod builtins;
mod registration;

pub use oxblade_macros::{Shape, Shared, View};
pub use registration::{
    Shared, SharedRegistration, View, ViewModel, ViewRegistration, shared_models, view, view_models,
};

use std::collections::{BTreeMap, BTreeSet};

/// The direction in which Serde processes a type.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Direction {
    /// Data supplied to the template by a view model.
    Serialize,
    /// Data accepted by a component prop.
    Deserialize,
}

/// A position in the Rust source that declares a type, field or variant.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SourceLocation {
    /// The compiler's source file path.
    pub file: &'static str,
    /// The one-based line number.
    pub line: u32,
    /// The one-based column number.
    pub column: u32,
}

/// A type as seen at the template boundary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TypeDesc {
    /// A JSON null.
    Null,
    /// A boolean.
    Bool,
    /// An integer.
    Int,
    /// A floating-point number.
    Float,
    /// A UTF-8 string.
    String,
    /// A printable prop accepting strings, integers, floats and null.
    Text,
    /// A string carrying trusted markup provenance when produced by the view serializer.
    Html,
    /// A date or time represented as text at the JSON boundary.
    Date,
    /// A specific string value such as a Serde discriminator.
    Literal(&'static str),
    /// A value that can also be null.
    Option(Box<TypeDesc>),
    /// A homogeneous array.
    List {
        /// Type of each element.
        element: Box<TypeDesc>,
        /// The exact length of a fixed array, if known.
        length: Option<usize>,
    },
    /// A positional sequence, in wire order.
    Tuple(Vec<TupleElement>),
    /// An ordered map. JSON encodes supported non-string keys as object member names.
    Map {
        /// Logical type of each key.
        key: Box<TypeDesc>,
        /// Type of each value.
        value: Box<TypeDesc>,
    },
    /// Named fields in declaration order, including flattened members.
    Struct(Vec<FieldDesc>),
    /// A Serde enum with its tag strategy and ordered variants.
    Enum(EnumDesc),
    /// Alternative representations of a single type. An empty union has no valid values.
    Union(Vec<TypeDesc>),
    /// An unchecked value.
    Any,
    /// A named type in the registry for the current direction.
    Ref(&'static str),
    /// A type with a named template display handler.
    Display {
        /// Registered handler name.
        name: &'static str,
        /// Underlying wire representation.
        ty: Box<TypeDesc>,
    },
}

/// How a named field can occur at the wire boundary.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Presence {
    /// The key may be omitted. The type still describes a value when the key is present.
    Absent,
    /// The key is required and its value is optional.
    Nullable,
    /// The key is required.
    Required,
}

/// A named field in a struct or enum payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FieldDesc {
    /// Primary wire name in this direction.
    pub name: &'static str,
    /// Additional accepted input names. Empty for output.
    pub aliases: Vec<&'static str>,
    /// Whether a key may be missing or its value may be null.
    pub presence: Presence,
    /// Whether this type contributes keys to the enclosing object instead of using its own key.
    pub flatten: bool,
    /// Value type, or the source of keys if flattened.
    pub ty: TypeDesc,
    /// Where the field was declared.
    pub source: SourceLocation,
}

/// A position in a tuple or tuple variant.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TupleElement {
    /// The type at this position.
    pub ty: TypeDesc,
    /// Whether Serde can omit this output position or default a missing input position.
    pub omittable: bool,
}

/// How Serde distinguishes variants on the wire.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum EnumTag {
    /// A unit variant is a string. On input it may also be an object with a null payload.
    /// Other variants use an object with the variant name as its key.
    External,
    /// A discriminator is inserted into the variant object.
    Internal {
        /// Name of the discriminator field.
        tag: &'static str,
    },
    /// A discriminator and optional payload are stored in separate object fields.
    Adjacent {
        /// Name of the discriminator field.
        tag: &'static str,
        /// Name of the payload field.
        content: &'static str,
    },
    /// Only the variant payload appears on the wire.
    Untagged,
}

/// A Serde enum's representation in one direction.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumDesc {
    /// Default tagging strategy.
    pub tag: EnumTag,
    /// Variants in declaration order, including the first-match order for untagged input.
    pub variants: Vec<VariantDesc>,
}

/// One Serde enum variant.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VariantDesc {
    /// Wire name or discriminator value.
    pub name: &'static str,
    /// Additional accepted variant names. Empty for output.
    pub aliases: Vec<&'static str>,
    /// Whether this variant omits the enclosing enum's tag even in a tagged enum.
    pub untagged: bool,
    /// Variant content. `None` means a unit variant.
    pub payload: Option<TypeDesc>,
    /// Whether a non-unit adjacent variant can deserialize with its content field omitted.
    pub payload_omittable: bool,
    /// Where the variant was declared.
    pub source: SourceLocation,
}

/// A registered definition for a named type in one direction.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NamedType {
    /// The Rust name as written, without module or generic arguments.
    pub name: &'static str,
    /// Where the type was declared.
    pub source: SourceLocation,
    /// Definition referenced by a `TypeDesc::Ref`.
    pub ty: TypeDesc,
}

/// Definitions encountered while walking shapes. Recursive references use Rust's qualified type names.
#[derive(Default, Debug)]
pub struct TypeRegistry {
    definitions: BTreeMap<Direction, BTreeMap<&'static str, NamedType>>,
    pending: BTreeSet<(&'static str, Direction)>,
}

impl TypeRegistry {
    /// Looks up a reference in the direction in which it was produced.
    pub fn get(&self, id: &str, direction: Direction) -> Option<&NamedType> {
        self.definitions.get(&direction)?.get(id)
    }

    /// Lists definitions, including distinct instantiations of generic types.
    pub fn iter(&self) -> impl Iterator<Item = (&'static str, Direction, &NamedType)> {
        self.definitions.iter().flat_map(|(&direction, types)| {
            types.iter().map(move |(&id, named)| (id, direction, named))
        })
    }

    /// Loads the linked nongeneric types, even when they are not yet reached by a view or prop.
    pub fn register_linked(&mut self, direction: Direction) {
        for entry in inventory::iter::<__private::ShapeRegistration> {
            (entry.describe)(self, direction);
        }
    }

    /// Defines a named shape once per direction and returns its reference, even during recursion.
    pub fn define<T: ?Sized>(
        &mut self,
        direction: Direction,
        name: &'static str,
        source: SourceLocation,
        describe: impl FnOnce(&mut Self) -> TypeDesc,
    ) -> TypeDesc {
        let id = std::any::type_name::<T>();
        let key = (id, direction);
        if self.get(id, direction).is_none() && self.pending.insert(key) {
            let ty = describe(self);
            self.pending.remove(&key);
            self.definitions
                .entry(direction)
                .or_default()
                .insert(id, NamedType { name, source, ty });
        }
        TypeDesc::Ref(id)
    }
}

/// Describes the values Serde writes for templates and accepts for component props.
#[diagnostic::on_unimplemented(
    message = "`{Self}` has no oxblade Shape",
    note = "For unordered HashMap or HashSet values, use IndexMap, BTreeMap, or an ordered sequence for deterministic output"
)]
pub trait Shape {
    /// Describes this type, registering any named types it references.
    fn describe(registry: &mut TypeRegistry, direction: Direction) -> TypeDesc;

    /// Describes values serialized into a view.
    fn serialize_shape(registry: &mut TypeRegistry) -> TypeDesc {
        Self::describe(registry, Direction::Serialize)
    }

    /// Describes values accepted by a component prop.
    fn deserialize_shape(registry: &mut TypeRegistry) -> TypeDesc {
        Self::describe(registry, Direction::Deserialize)
    }
}

/// Printable component prop data.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum Text {
    /// Plain text.
    String(String),
    /// A signed integer.
    Int(i64),
    /// An unsigned integer outside the signed range.
    Unsigned(u64),
    /// A floating-point number.
    Float(f64),
    /// A null value that prints nothing.
    Empty,
}

impl std::fmt::Display for Text {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(value) => value.fmt(formatter),
            Self::Int(value) => value.fmt(formatter),
            Self::Unsigned(value) => value.fmt(formatter),
            Self::Float(value) => value.fmt(formatter),
            Self::Empty => Ok(()),
        }
    }
}

/// Explicitly trusted HTML from application code. Serializes as a string and cannot be deserialized.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Html(String);

impl Html {
    /// Serde newtype marker that the engine's view serializer can observe for provenance.
    pub const SERDE_NAME: &str = "__oxblade_html";

    /// Marks an already safe string as trusted. The caller must escape any untrusted fragments first.
    pub fn new(html: impl Into<String>) -> Self {
        Self(html.into())
    }

    /// Returns the trusted markup.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl serde::Serialize for Html {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_newtype_struct(Self::SERDE_NAME, &self.0)
    }
}

/// Implementation details used by the derive macros.
#[doc(hidden)]
pub mod __private {
    use super::{Direction, SourceLocation, TypeDesc, TypeRegistry};

    /// Re-export for macro consumers.
    pub use inventory::submit;

    /// An inventory entry for a named type.
    pub struct ShapeRegistration {
        /// Function that inserts the named definition.
        pub describe: fn(&mut TypeRegistry, Direction) -> TypeDesc,
    }

    inventory::collect!(ShapeRegistration);

    /// Encloses a descriptor in a display annotation when one is present.
    pub fn display(ty: TypeDesc, name: &'static str) -> TypeDesc {
        TypeDesc::Display {
            name,
            ty: Box::new(ty),
        }
    }

    /// Whether a value's outer representation is optional.
    pub fn is_option(ty: &TypeDesc) -> bool {
        match ty {
            TypeDesc::Display { ty, .. } => is_option(ty),
            TypeDesc::Option(_) => true,
            _ => false,
        }
    }

    /// Whether an optional wire value is known, including through newtype definitions.
    pub fn is_nullable(ty: &TypeDesc, registry: &TypeRegistry, direction: Direction) -> bool {
        let mut ty = ty;
        let mut visited = None;
        loop {
            match ty {
                TypeDesc::Ref(name) => {
                    if !visited
                        .get_or_insert_with(std::collections::BTreeSet::new)
                        .insert(*name)
                    {
                        return false;
                    }
                    let Some(named) = registry.get(name, direction) else {
                        return false;
                    };
                    ty = &named.ty;
                }
                TypeDesc::Display { ty: inner, .. } => ty = inner,
                _ => return is_option(ty),
            }
        }
    }

    /// Source location of the invocation.
    pub const fn source(file: &'static str, line: u32, column: u32) -> SourceLocation {
        SourceLocation { file, line, column }
    }
}