oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
//! Static checking of parsed Blade templates against application-provided shapes.

mod diagnostics;
mod expressions;
mod signatures;
mod templates;
mod types;

pub use diagnostics::{Diagnostic, DiagnosticKind, Fix, Report};

use crate::ast::Template;
use crate::shape::{TypeDesc, TypeRegistry};
use crate::span::{SourceMap, Span};
use std::collections::{BTreeMap, BTreeSet};

use types::{Environment, Ty};

/// Named view, shared, or component data, including names omitted by serialization.
#[derive(Clone, Debug, Default)]
pub struct Scope {
    /// Types of bindings when present.
    pub bindings: BTreeMap<String, TypeDesc>,
    /// Bindings that can be absent, even when their value type is non-null.
    pub absent: BTreeSet<String>,
}

impl Scope {
    /// Creates an empty scope.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a binding that will be present.
    pub fn insert(&mut self, name: String, ty: TypeDesc) -> Option<TypeDesc> {
        self.absent.remove(&name);
        self.bindings.insert(name, ty)
    }

    fn binding_type(&self, name: &str, ty: &TypeDesc, direction: crate::shape::Direction) -> Ty {
        let ty = Ty::shape(ty.clone(), direction);
        if self.absent.contains(name) {
            Ty::Absent(Box::new(ty))
        } else {
            ty
        }
    }
}

impl From<BTreeMap<String, TypeDesc>> for Scope {
    fn from(bindings: BTreeMap<String, TypeDesc>) -> Self {
        Self {
            bindings,
            ..Self::default()
        }
    }
}

impl<const N: usize> From<[(String, TypeDesc); N]> for Scope {
    fn from(bindings: [(String, TypeDesc); N]) -> Self {
        BTreeMap::from(bindings).into()
    }
}

impl<'a> IntoIterator for &'a Scope {
    type Item = (&'a String, &'a TypeDesc);
    type IntoIter = std::collections::btree_map::Iter<'a, String, TypeDesc>;

    fn into_iter(self) -> Self::IntoIter {
        self.bindings.iter()
    }
}

/// Signature of a registered helper, receiver method, or custom condition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Signature {
    /// Positional parameters. Trailing optional shapes may be omitted.
    pub parameters: Vec<TypeDesc>,
    /// Type of each additional argument, if this signature is variadic.
    pub variadic: Option<TypeDesc>,
    /// Return type.
    pub returns: TypeDesc,
}

impl Signature {
    /// Creates a signature with no variadic parameter.
    pub fn new(parameters: Vec<TypeDesc>, returns: TypeDesc) -> Self {
        Self {
            parameters,
            variadic: None,
            returns,
        }
    }
}

/// A resolved component, including any class-component metadata.
#[derive(Clone, Debug, Default)]
pub struct ComponentDefinition<'a> {
    /// Parsed implementation, when available.
    pub template: Option<&'a Template>,
    /// Deserialization shape of registered props, if this is a class component.
    pub props: Option<TypeDesc>,
    /// Named slots and whether each is mandatory.
    pub slots: BTreeMap<String, bool>,
    /// Callable members exposed within the component template.
    pub helpers: BTreeMap<String, Signature>,
    /// Extra values exposed by a class component.
    pub computed: Scope,
}

/// Supplies parsed includes and component contracts. All spans must refer to the checker's source map.
pub trait Resolver {
    /// Resolves an include or layout name.
    fn include(&self, name: &str) -> Option<&Template>;

    /// Resolves a component tag or legacy component name.
    fn component(&self, name: &str) -> Option<ComponentDefinition<'_>>;

    /// Reports whether a tag is handled at runtime with no static prop or slot contract.
    fn has_runtime_component(&self, _name: &str) -> bool {
        false
    }

    /// Returns an application-expanded directive, when available for this invocation.
    fn directive(&self, _name: &str, _arguments: Option<Span>) -> Option<&Template> {
        None
    }
}

impl Resolver for () {
    fn include(&self, _: &str) -> Option<&Template> {
        None
    }
    fn component(&self, _: &str) -> Option<ComponentDefinition<'_>> {
        None
    }
}

/// One URI placeholder in declaration order.
#[derive(Clone, Debug)]
pub struct Placeholder {
    /// Parameter in a named argument map.
    pub name: String,
    /// Expected scalar after any model key has been extracted.
    pub ty: TypeDesc,
    /// Whether the placeholder may be omitted.
    pub optional: bool,
    /// Explicit field to extract when a whole model is supplied.
    pub model_key: Option<String>,
}

/// Routes indexed by the aliases and handler paths the application exposes.
pub type Routes = BTreeMap<String, Vec<Placeholder>>;

/// Dependencies and application registrations for a checking run.
pub struct Checker<'a> {
    /// Registered named shapes in their respective Serde directions.
    pub types: &'a TypeRegistry,
    /// Original source text for diagnostics and source-only lints.
    pub sources: &'a SourceMap,
    /// Include and component resolver.
    pub resolver: &'a dyn Resolver,
    /// Route aliases and handler paths.
    pub routes: Routes,
    /// Shared values inherited by views and components.
    pub shared: Scope,
    /// Shared values for which middleware execution cannot be established.
    pub middleware: BTreeSet<String>,
    /// Registered helper signatures indexed by template name.
    pub helpers: BTreeMap<String, Signature>,
    /// Registered methods indexed by qualified shape name and method name.
    pub methods: BTreeMap<(String, String), Signature>,
    /// Registered condition signatures.
    pub conditions: BTreeMap<String, Signature>,
    /// Paginator shape references and the serialized type of their items.
    pub paginators: BTreeMap<String, TypeDesc>,
    /// Emit warnings for unread fields of each supplied root scope.
    pub warn_unused_fields: bool,
    /// Constants imported from application code, indexed by template path.
    pub constants: Scope,
}

impl<'a> Checker<'a> {
    /// Creates a checker with the built-in signatures and no application registrations.
    pub fn new(
        types: &'a TypeRegistry,
        sources: &'a SourceMap,
        resolver: &'a dyn Resolver,
    ) -> Self {
        Self {
            types,
            sources,
            resolver,
            routes: Routes::new(),
            shared: Scope::new(),
            middleware: BTreeSet::new(),
            helpers: BTreeMap::new(),
            methods: BTreeMap::new(),
            conditions: BTreeMap::new(),
            paginators: BTreeMap::new(),
            constants: Scope::new(),
            warn_unused_fields: true,
        }
    }

    /// Checks one root and its reachable templates.
    pub fn check(&self, template: &Template, scope: &Scope) -> Report {
        self.check_views([(template, scope)])
    }

    /// Checks roots together so repeated partial findings collect callers across views.
    pub fn check_views<'b>(
        &self,
        roots: impl IntoIterator<Item = (&'b Template, &'b Scope)>,
    ) -> Report {
        let mut run = Run::new(self);
        for (template, scope) in roots {
            let mut env = run.root();
            for (name, ty) in scope {
                env.bind_model(
                    name,
                    scope.binding_type(name, ty, crate::shape::Direction::Serialize),
                );
            }
            run.frames.push(Frame::default());
            run.template(template, &mut env);
            let frame = run.frames.pop().unwrap_or_default();
            if self.warn_unused_fields {
                for name in scope
                    .bindings
                    .keys()
                    .filter(|name| !frame.reads.contains(*name))
                {
                    run.warn(
                        "unused-view-field",
                        Span::new(template.span.file, template.span.start, template.span.start),
                        format!("view-model field `{name}` is never read"),
                    );
                }
            }
        }
        run.report.templates = run.visited.len();
        run.report
    }

    /// Extracts the fields of a serialized shape for use as a root scope.
    pub fn scope(&self, shape: TypeDesc) -> Scope {
        types::shape_fields(self.types, &shape, crate::shape::Direction::Serialize)
    }
}

#[derive(Clone, Default)]
struct Frame {
    diagnostics: BTreeSet<usize>,
    reads: BTreeSet<String>,
}

struct Memo {
    scope: Environment,
    frame: Frame,
}

struct Run<'a, 'config> {
    config: &'a Checker<'config>,
    report: Report,
    frames: Vec<Frame>,
    active: Vec<Span>,
    visited: BTreeSet<u32>,
    memo: BTreeMap<(u32, u32, u32), Vec<Memo>>,
}

impl<'a, 'config> Run<'a, 'config> {
    fn new(config: &'a Checker<'config>) -> Self {
        Self {
            config,
            report: Report::default(),
            frames: Vec::new(),
            active: Vec::new(),
            visited: BTreeSet::new(),
            memo: BTreeMap::new(),
        }
    }

    fn root(&self) -> Environment {
        let mut env = Environment::default();
        env.bind("errors".into(), Ty::Errors, false);
        for (name, ty) in &self.config.shared {
            env.bind(
                name.clone(),
                self.config
                    .shared
                    .binding_type(name, ty, crate::shape::Direction::Serialize),
                false,
            );
            if self.config.middleware.contains(name) {
                env.mark_middleware(name);
            }
        }
        env
    }

    fn issue(
        &mut self,
        kind: DiagnosticKind,
        code: &'static str,
        span: Span,
        message: impl Into<String>,
    ) -> usize {
        let index = self
            .report
            .add(self.config.sources, kind, code, span, message.into());
        if let Some(frame) = self.frames.last_mut() {
            frame.diagnostics.insert(index);
        }
        index
    }

    fn error(&mut self, code: &'static str, span: Span, message: impl Into<String>) {
        self.issue(DiagnosticKind::Error, code, span, message);
    }

    fn warn(&mut self, code: &'static str, span: Span, message: impl Into<String>) {
        self.issue(DiagnosticKind::Warning, code, span, message);
    }

    fn unchecked(&mut self, code: &'static str, span: Span, message: impl Into<String>) {
        self.issue(DiagnosticKind::Unchecked, code, span, message);
    }
}