mod data;
mod source;
mod views;
pub(crate) use source::compile;
use std::sync::Arc;
use indexmap::{IndexMap, IndexSet};
use crate::{
engine::RequestContext,
error::Result,
eval::Helper,
library::{boolean, fault, integer, string},
shape::TypeDesc,
value::Value,
};
pub use data::ViewData;
pub(crate) use data::{DisplayHandler, ViewEvent, display_data, matching, normalize};
type SourceHook = Box<dyn Fn(&str) -> String + Send + Sync>;
#[derive(Default)]
pub(crate) struct Extensions {
pub(crate) templates: IndexMap<String, String>,
pub(crate) function_directives: IndexMap<String, FunctionDirective>,
pub(crate) conditions: IndexMap<String, (Helper, Vec<TypeDesc>)>,
pub(crate) legacy_conditions: IndexSet<String>,
pub(crate) prepare: Vec<SourceHook>,
pub(crate) precompilers: Vec<SourceHook>,
pub(crate) creators: Vec<ViewEvent>,
pub(crate) composers: Vec<ViewEvent>,
pub(crate) display: IndexMap<String, DisplayHandler>,
}
pub(crate) type FunctionDirective = Box<
dyn for<'r, 'a> Fn(
DirectiveArgs<'r, 'a>,
&mut DirectiveOutput<'_>,
&DirectiveContext<'r, 'a>,
) -> Result<()>
+ Send
+ Sync,
>;
pub struct DirectiveArgs<'r, 'a>(pub(crate) &'r [Value<'a>]);
impl<'r, 'a> DirectiveArgs<'r, 'a> {
pub fn values(&self) -> &'r [Value<'a>] {
self.0
}
pub fn get(&self, index: usize) -> Result<&'r Value<'a>> {
self.0
.get(index)
.ok_or_else(|| fault(format!("missing directive argument {index}")))
}
pub fn string(&self, index: usize) -> Result<&'r str> {
string(self.get(index)?)
}
pub fn integer(&self, index: usize) -> Result<i64> {
integer(self.get(index)?)
}
pub fn date(&self, index: usize) -> Result<&'r Value<'a>> {
self.get(index)
}
}
pub struct DirectiveOutput<'a> {
pub(crate) text: &'a mut String,
pub(crate) budget: &'a crate::engine::RenderBudget,
pub(crate) double_encode: bool,
}
impl DirectiveOutput<'_> {
pub fn escaped(&mut self, text: &str) -> Result<()> {
self.raw(&crate::encode::e_with_double_encode(
text,
self.double_encode,
))
}
pub fn raw(&mut self, html: &str) -> Result<()> {
self.budget.charge_output(html.len())?;
self.text.push_str(html);
Ok(())
}
}
pub struct DirectiveContext<'r, 'a> {
pub(crate) request: &'r RequestContext<'a>,
pub(crate) evaluator: &'r crate::eval::Evaluator<'a>,
}
impl<'r, 'a> DirectiveContext<'r, 'a> {
pub fn request(&self) -> &'r RequestContext<'a> {
self.request
}
pub fn call(&self, name: &str, values: Vec<Value<'a>>) -> Result<Value<'a>> {
self.evaluator.function(name, values)
}
pub fn translate(&self, message: impl Into<String>) -> Result<String> {
self.call("__", vec![Value::string(message.into())])?
.display()
}
pub fn format_date(&self, date: &Value<'a>, format: &str) -> Result<String> {
let date = self.call("date", vec![date.clone()])?;
crate::formatting::method(
"format",
&date,
vec![crate::value::Arg::Value(Value::string(format.to_owned()))],
)
.ok_or_else(|| fault("date formatting is unavailable"))??
.display()
}
}
pub trait ConditionArgument {
const OPTIONAL: bool = false;
type Borrowed<'a>;
fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>>;
fn shape() -> TypeDesc;
}
macro_rules! condition_arg {
($ty:ty, $borrowed:ty, $read:ident, $shape:ident) => {
impl ConditionArgument for $ty {
type Borrowed<'a> = $borrowed;
fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>> {
$read(value)
}
fn shape() -> TypeDesc {
TypeDesc::$shape
}
}
};
}
condition_arg!(&'static str, &'a str, string, String);
condition_arg!(String, String, owned_string, String);
fn owned_string(value: &Value<'_>) -> Result<String> {
string(value).map(str::to_owned)
}
condition_arg!(i64, i64, integer, Int);
condition_arg!(bool, bool, boolean, Bool);
fn float(value: &Value<'_>) -> Result<f64> {
match value.scalar() {
Value::Float(value) => Ok(value),
_ => Err(fault(format!("expected float, got {}", value.type_name()))),
}
}
condition_arg!(f64, f64, float, Float);
impl<T: ConditionArgument> ConditionArgument for Option<T> {
const OPTIONAL: bool = true;
type Borrowed<'a> = Option<T::Borrowed<'a>>;
fn read<'a>(value: &'a Value<'_>) -> Result<Self::Borrowed<'a>> {
(!value.is_null()).then(|| T::read(value)).transpose()
}
fn shape() -> TypeDesc {
TypeDesc::Option(Box::new(T::shape()))
}
}
pub trait Condition<Args> {
fn into_condition(self) -> (Helper, Vec<TypeDesc>);
}
impl<F> Condition<()> for F
where
F: Fn() -> bool + Send + Sync + 'static,
{
fn into_condition(self) -> (Helper, Vec<TypeDesc>) {
(
Arc::new(move |args| {
if !args.is_empty() {
return Err(fault("condition expects no arguments"));
}
Ok(Value::Bool(self()))
}),
Vec::new(),
)
}
}
macro_rules! condition {
($($arg:ident : $value:ident),+) => {
impl<F, $($arg),+> Condition<($($arg,)+)> for F
where
$($arg: ConditionArgument + 'static,)+
F: Fn($($arg),+) -> bool + for<'v> Fn($($arg::Borrowed<'v>),+) -> bool
+ Send + Sync + 'static,
{
fn into_condition(self) -> (Helper, Vec<TypeDesc>) {
(Arc::new(move |args| {
let optional = [$($arg::OPTIONAL),+];
let max = optional.len();
let min = optional.iter().rposition(|optional| !optional).map_or(0, |index| index + 1);
if !(min..=max).contains(&args.len()) {
return Err(fault(format!("condition expects {min} to {max} arguments, got {}", args.len())));
}
let mut args = args.iter();
$(let $value = $arg::read(args.next().unwrap_or(&Value::Null))?;)+
Ok(Value::Bool(self($($value),+)))
}), vec![$($arg::shape()),+])
}
}
};
}
condition!(A: a);
condition!(A: a, B: b);
condition!(A: a, B: b, C: c);
condition!(A: a, B: b, C: c, D: d);
condition!(A: a, B: b, C: c, D: d, E: e);
condition!(A: a, B: b, C: c, D: d, E: e, G: g);
impl<L: crate::loader::Loader> crate::engine::EnvironmentBuilder<L> {
pub fn directive(mut self, name: &str, template: impl Into<String>) -> Self {
self.clear_inline(name);
self.0.directives.register_exact_directive(name, true);
self.0
.extensions
.templates
.insert(name.to_owned(), template.into());
self
}
pub fn directive_fn<F>(mut self, name: &str, callback: F) -> Self
where
F: for<'r, 'a> Fn(
DirectiveArgs<'r, 'a>,
&mut DirectiveOutput<'_>,
&DirectiveContext<'r, 'a>,
) -> Result<()>
+ Send
+ Sync
+ 'static,
{
self.clear_inline(name);
self.0.directives.register_exact_directive(name, true);
self.0
.extensions
.function_directives
.insert(name.to_owned(), Box::new(callback));
self
}
pub(crate) fn clear_inline(&mut self, name: &str) {
self.0.extensions.templates.shift_remove(name);
self.0.extensions.function_directives.shift_remove(name);
self.0.aliases.shift_remove(name);
}
pub fn condition<Args>(mut self, name: &str, callback: impl Condition<Args>) -> Self {
self.0.directives.register_exact_condition(name);
self.0
.extensions
.conditions
.insert(name.to_owned(), callback.into_condition());
self
}
pub(crate) fn install_condition_check(&mut self) {
let extensions = &self.0.extensions;
let mut conditions: IndexMap<_, _> = extensions
.legacy_conditions
.iter()
.filter_map(|name| Some((name.clone(), self.0.helpers.get(name)?.clone())))
.collect();
conditions.extend(
extensions
.conditions
.iter()
.map(|(name, (callback, _))| (name.clone(), callback.clone())),
);
if conditions.is_empty() {
return;
}
Arc::make_mut(&mut self.0.helpers).insert(
"Blade::check".into(),
Arc::new(move |args| {
let [name, args @ ..] = args else {
return Err(fault("Blade::check requires a condition name"));
};
let name = string(name)?;
let condition = conditions
.get(name)
.ok_or_else(|| fault(format!("unknown condition `{name}`")))?;
condition(args)
}),
);
}
pub fn prepare_source(
mut self,
callback: impl Fn(&str) -> String + Send + Sync + 'static,
) -> Self {
self.0.extensions.prepare.push(Box::new(callback));
self
}
pub fn precompiler(
mut self,
callback: impl Fn(&str) -> String + Send + Sync + 'static,
) -> Self {
self.0.extensions.precompilers.push(Box::new(callback));
self
}
pub fn stringable(
mut self,
name: impl Into<String>,
callback: impl Fn(&Value<'_>) -> String + Send + Sync + 'static,
) -> Self {
self.0
.extensions
.display
.insert(name.into(), Arc::new(callback));
self
}
pub fn creator<I, P, F, T>(mut self, patterns: I, callback: F) -> Self
where
I: IntoIterator<Item = P>,
P: AsRef<str>,
T: crate::Shape + serde::Serialize,
F: for<'a> Fn(ViewData<'_, 'a>) -> T + Send + Sync + 'static,
{
self.0
.extensions
.creators
.extend(ViewEvent::register(patterns, callback));
self
}
pub fn composer<I, P, F, T>(mut self, patterns: I, callback: F) -> Self
where
I: IntoIterator<Item = P>,
P: AsRef<str>,
T: crate::Shape + serde::Serialize,
F: for<'a> Fn(ViewData<'_, 'a>) -> T + Send + Sync + 'static,
{
self.0
.extensions
.composers
.extend(ViewEvent::register(patterns, callback));
self
}
}