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
use std::{
    collections::HashMap,
    sync::{Arc, PoisonError, RwLock},
};

use crate::{
    compile::Program,
    error::{Error, ErrorKind, Result},
    loader::{Loader, Source},
    span::FileId,
};

use super::Environment;

#[derive(Default)]
pub(super) struct Programs(RwLock<HashMap<String, Compiled>>);

struct Compiled {
    text: Arc<str>,
    program: Arc<Program>,
}

impl<L: Loader> Environment<L> {
    pub(crate) fn has_source_transforms(&self) -> bool {
        !self.extensions.prepare.is_empty()
            || !self.extensions.precompilers.is_empty()
            || !self.extensions.templates.is_empty()
    }

    pub(crate) fn cached_program(&self, source: &Source, file: FileId) -> Result<Arc<Program>> {
        let programs = self
            .programs
            .0
            .read()
            .unwrap_or_else(PoisonError::into_inner);
        if let Some(hit) = programs.get(&source.name)
            && hit.program.template.span.file == file
            && (Arc::ptr_eq(&hit.text, &source.text) || hit.text == source.text)
        {
            return Ok(Arc::clone(&hit.program));
        }
        drop(programs);

        if u32::try_from(source.text.len()).is_err() {
            return Err(Error::new(
                ErrorKind::Limit,
                "view source exceeds span limits",
                None,
            ));
        }
        let program = self.loader.compile(source, file, &mut || {
            Program::compile(file, &source.text, &self.directives)
        })?;
        // Never hold the lock while loading or compiling. Concurrent misses may compile
        // independently. Each render keeps its own Arc and subsequent hits verify the source.
        self.programs
            .0
            .write()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(
                source.name.clone(),
                Compiled {
                    text: Arc::clone(&source.text),
                    program: Arc::clone(&program),
                },
            );
        Ok(program)
    }
}