mod imports;
mod loop_state;
mod operators;
mod range;
pub(crate) use loop_state::LoopState;
mod statements;
use std::{cell::Cell, rc::Rc, sync::Arc};
use crate::{
ast::{
BinaryOp, Block, CallArgs, Expr, ExprKind, Literal, MapKey, Pattern, PatternKind, UnaryOp,
},
error::{Error, ErrorKind, Result},
library::{self, boolean, fault, integer, key},
span::Span,
value::{Arg, Callable, Object, Value, ValueMap, expansion_error},
};
use operators::{binary, cast};
use range::Range;
pub(crate) use operators::equal;
#[derive(Clone, Debug)]
struct Binding<'a> {
value: Value<'a>,
mutable: bool,
}
#[derive(Clone, Default)]
struct Scope<'a> {
bindings: indexmap::IndexMap<String, Option<Binding<'a>>>,
loop_state: Option<LoopState<'a>>,
data: ValueMap<'a>,
props: Option<Rc<ValueMap<'a>>>,
}
impl<'a> Scope<'a> {
fn view_value(&self, name: &str) -> Option<&Value<'a>> {
self.data
.get(name)
.or_else(|| self.props.as_ref()?.get(name))
}
}
#[derive(Clone)]
struct Undo<'a> {
scope: usize,
binding: usize,
value: Value<'a>,
}
pub type Helper = Arc<dyn for<'a> Fn(&[Value<'a>]) -> Result<Value<'a>> + Send + Sync>;
pub type Clock = Arc<dyn Fn() -> jiff::ZonedDateTime + Send + Sync>;
#[derive(Clone, Default)]
pub(crate) struct Services<'a> {
pub(crate) helpers: Arc<indexmap::IndexMap<String, Helper>>,
pub(crate) methods: Arc<Vec<crate::render::components::MethodRegistration>>,
pub(crate) errors: Option<ValueMap<'a>>,
pub(crate) user: Option<Value<'a>>,
pub(crate) session: ValueMap<'a>,
pub(crate) old_input: ValueMap<'a>,
pub(crate) context: ValueMap<'a>,
pub(crate) clock: Option<Clock>,
pub(crate) translator: Option<Arc<dyn crate::translate::Translator + Send + Sync>>,
pub(crate) locale: Option<Arc<str>>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CodeFlow {
#[default]
Normal,
Break,
Continue,
}
#[derive(Clone)]
pub struct Evaluator<'a> {
layers: Vec<ValueMap<'a>>,
shared_layers: Option<usize>,
facts_visible: bool,
scopes: Vec<Scope<'a>>,
spare_scopes: Vec<Scope<'a>>,
scope_start: usize,
layer_count: usize,
view_start: usize,
undo: Vec<Undo<'a>>,
undo_start: usize,
services: Services<'a>,
method_cache: Rc<crate::render::components::MethodCache<'a>>,
aliases: indexmap::IndexMap<String, String>,
budget: crate::engine::RenderBudget,
shared_budget: bool,
depth: Rc<Cell<usize>>,
expansion: usize,
value_bytes: usize,
data_depth: usize,
flow: CodeFlow,
}
impl<'a> Evaluator<'a> {
pub fn new(layers: impl IntoIterator<Item = ValueMap<'a>>) -> Self {
Self::configured(
layers.into_iter().collect(),
Services::default(),
crate::engine::RenderBudget::new(crate::engine::Limits::default()),
false,
)
}
pub(crate) fn configured(
mut layers: Vec<ValueMap<'a>>,
services: Services<'a>,
budget: crate::engine::RenderBudget,
shared_budget: bool,
) -> Self {
layers.iter_mut().for_each(crate::value::bound_owned_layer);
let limits = budget.limits();
Self {
layer_count: layers.len(),
layers,
shared_layers: None,
facts_visible: true,
scopes: vec![Default::default()],
spare_scopes: Vec::new(),
scope_start: 0,
view_start: 0,
undo: Vec::new(),
undo_start: 0,
services,
method_cache: Rc::default(),
budget,
shared_budget,
depth: Rc::new(Cell::new(0)),
expansion: limits.expansion,
value_bytes: limits.output,
data_depth: limits.depth,
aliases: Default::default(),
flow: CodeFlow::Normal,
}
}
pub(crate) fn retain_shared_layers(mut self, count: Option<usize>) -> Self {
self.shared_layers = count;
self
}
pub(crate) fn with_view<T>(
&mut self,
data: ValueMap<'a>,
isolated: bool,
run: impl FnOnce(&mut Self) -> T,
) -> T {
self.with_view_data(data, None, isolated, run)
}
pub(crate) fn with_component_view<T>(
&mut self,
data: ValueMap<'a>,
props: Rc<ValueMap<'a>>,
run: impl FnOnce(&mut Self) -> T,
) -> T {
self.with_view_data(data, Some(props), true, run)
}
fn with_view_data<T>(
&mut self,
data: ValueMap<'a>,
props: Option<Rc<ValueMap<'a>>>,
isolated: bool,
run: impl FnOnce(&mut Self) -> T,
) -> T {
let start = self.scopes.len();
let view_start = std::mem::replace(&mut self.view_start, start);
let scope_start = self.scope_start;
let layer_count = self.layer_count;
let facts_visible = self.facts_visible;
let aliases = std::mem::take(&mut self.aliases);
let flow = std::mem::take(&mut self.flow);
let boundary = self.undo.len();
let undo_start = std::mem::replace(&mut self.undo_start, boundary);
if isolated {
self.scope_start = start;
self.layer_count = self.layer_count.min(self.shared_layers.unwrap_or(0));
self.facts_visible &= self.shared_layers.is_some();
}
let result = self.scoped(|eval| {
if let Some(scope) = eval.scopes.last_mut() {
scope.data = data;
scope.props = props;
}
run(eval)
});
while self.undo.len() > boundary {
if let Some(undo) = self.undo.pop()
&& let Some((_, Some(binding))) =
self.scopes[undo.scope].bindings.get_index_mut(undo.binding)
{
binding.value = undo.value;
}
}
self.undo_start = undo_start;
self.scope_start = scope_start;
self.layer_count = layer_count;
self.facts_visible = facts_visible;
self.view_start = view_start;
self.aliases = aliases;
self.flow = flow;
result
}
pub(crate) fn import(&mut self, tree: &str) {
use self::imports::register;
register(tree, "", &mut self.aliases);
}
fn path_name<'b>(&self, path: &'b [String]) -> std::borrow::Cow<'b, str> {
match path {
[name] if !self.aliases.contains_key(name) => std::borrow::Cow::Borrowed(name),
_ => std::borrow::Cow::Owned(self.resolve_path(path)),
}
}
fn resolve_path(&self, path: &[String]) -> String {
if let Some((head, tail)) = path.split_first()
&& let Some(prefix) = self.aliases.get(head)
{
return if tail.is_empty() {
prefix.clone()
} else {
format!("{prefix}::{}", tail.join("::"))
};
}
path.join("::")
}
pub(crate) fn lookup(&self, name: &str) -> Option<Value<'a>> {
for scope in self.scopes[self.scope_start..].iter().rev() {
if let Some(binding) = scope.bindings.get(name) {
return binding.as_ref().map(|binding| binding.value.clone());
}
if let Some(value) = scope.view_value(name) {
return Some(value.clone());
}
if name == "loop"
&& let Some(state) = &scope.loop_state
{
return Some(state.materialize());
}
}
let value = self.layers[..self.layer_count]
.iter()
.rev()
.find_map(|layer| layer.get(name))
.cloned();
if value.is_none() && self.facts_visible {
return match name {
"user" => self.services.user.clone(),
"errors" => self
.services
.errors
.as_ref()
.map(|errors| crate::render::errors::error_bag(errors.clone(), "default")),
_ => None,
};
}
value
}
pub(crate) fn bind(&mut self, name: String, value: Value<'a>, mutable: bool) {
if let Some(scope) = self.scopes.last_mut() {
scope
.bindings
.insert(name, Some(Binding { value, mutable }));
}
}
pub(crate) fn unset(&mut self, name: &str) {
if let Some(scope) = self.scopes.last_mut() {
scope.bindings.insert(name.to_owned(), None);
}
}
pub(crate) fn bind_loop(&mut self, state: LoopState<'a>) {
if let Some(scope) = self.scopes.last_mut() {
scope.loop_state = Some(state);
}
}
pub(crate) fn inherited_loop(&self) -> LoopState<'a> {
if let Some(state) = self.local_loop() {
return state.child();
}
LoopState::from_parent(self.lookup("loop").unwrap_or(Value::Null))
}
fn local_loop(&self) -> Option<&LoopState<'a>> {
for scope in self.scopes[self.scope_start..].iter().rev() {
if scope.bindings.contains_key("loop") || scope.view_value("loop").is_some() {
return None;
}
if scope.loop_state.is_some() {
return scope.loop_state.as_ref();
}
}
None
}
pub(crate) fn with_component_binding<T>(
&mut self,
component: Option<Value<'a>>,
run: impl FnOnce(&mut Self) -> T,
) -> T {
let Some(component) = component else {
return run(self);
};
let Some(scope) = self.scopes.len().checked_sub(1) else {
return run(self);
};
let name = "component".to_owned();
let previous = self.scopes[scope].bindings.insert(
name.clone(),
Some(Binding {
value: component,
mutable: false,
}),
);
let result = run(self);
if let Some(previous) = previous {
self.scopes[scope].bindings.insert(name, previous);
} else {
self.scopes[scope].bindings.shift_remove(&name);
}
result
}
pub(crate) fn has_registered_methods(&self) -> bool {
!self.services.methods.is_empty()
}
pub(crate) fn typed_receiver(&self, name: &str, value: Value<'a>) -> Result<Value<'a>> {
if value.is_null() || matches!(value, Value::Object(_)) {
return Ok(value);
}
let name = name.trim();
let mut matches = self.services.methods.iter().filter(|method| {
let qualified = (method.type_name)();
qualified == name || qualified.rsplit("::").next() == Some(name)
});
let Some(method) = matches.next() else {
return Ok(value);
};
if matches.next().is_some() {
return Err(fault(format!("ambiguous method receiver type `{name}`")));
}
(method.wrap)(value)
}
fn registered_method(
&self,
receiver: &Value<'a>,
name: &str,
args: &[Value<'a>],
) -> Result<Value<'a>> {
let receiver_name = receiver.type_name();
if self
.services
.methods
.iter()
.any(|entry| (entry.type_name)() == receiver_name)
{
return Err(fault(format!("unknown method `{name}` on {receiver_name}")));
}
let mut methods = self
.services
.methods
.iter()
.filter(|entry| entry.names.contains(&name));
let Some(method) = methods.next() else {
return Err(fault(format!(
"unknown method `{name}` on {}",
receiver.type_name()
)));
};
if methods.next().is_some() {
return Err(fault(format!(
"ambiguous method `{name}`; declare the receiver type"
)));
}
(method.invoke)(&self.method_cache, receiver, name, args)
}
pub(crate) fn scoped<T>(&mut self, run: impl FnOnce(&mut Self) -> T) -> T {
self.scopes
.push(self.spare_scopes.pop().unwrap_or_default());
let result = run(self);
if let Some(mut scope) = self.scopes.pop() {
scope.bindings.clear();
scope.loop_state = None;
scope.data = ValueMap::new();
scope.props = None;
self.spare_scopes.push(scope);
}
result
}
pub(crate) fn charge_iteration(&self) -> Result<()> {
self.budget.charge_iteration()
}
pub(crate) fn entries<'v>(&self, value: &Value<'v>) -> Result<Vec<(Value<'v>, Value<'v>)>> {
let entries = value.entries(self.expansion_limit())?;
self.charge_expansion(entries.len())?;
Ok(entries)
}
pub(crate) fn expansion_limit(&self) -> usize {
if self.shared_budget {
self.budget.remaining_expansion()
} else {
self.expansion
}
}
pub(crate) fn budget(&self) -> &crate::engine::RenderBudget {
&self.budget
}
pub(crate) fn has_shared_budget(&self) -> bool {
self.shared_budget
}
pub(crate) fn charge_expansion(&self, entries: usize) -> Result<()> {
if self.shared_budget {
self.budget.charge_expansion(entries)?;
}
Ok(())
}
pub(crate) fn bind_pattern(
&mut self,
pattern: &Pattern,
value: &Value<'a>,
mutable: bool,
) -> Result<()> {
if let PatternKind::Binding(name) = &pattern.kind {
self.bind(name.clone(), value.clone(), mutable);
return Ok(());
}
let mut bindings = ValueMap::new();
if !self.pattern(pattern, value, &mut bindings)? {
return Err(at(
fault("binding pattern does not match the value"),
pattern.span,
));
}
for (name, value) in bindings {
self.bind(name, value, mutable);
}
Ok(())
}
pub(crate) fn loop_binding(
&mut self,
pattern: &Pattern,
key: Value<'a>,
value: Value<'a>,
keyed: bool,
) -> Result<()> {
let value =
if keyed && matches!(&pattern.kind, PatternKind::Tuple(items) if items.len() == 2) {
Value::List(vec![key, value])
} else {
value
};
self.bind_pattern(pattern, &value, false)
}
pub fn eval(&mut self, expr: &Expr) -> Result<Value<'a>> {
self.evaluate(expr, false)
}
pub(crate) fn optional(&mut self, expr: &Expr) -> Result<Value<'a>> {
self.evaluate(expr, true)
}
fn evaluate(&mut self, expr: &Expr, missing: bool) -> Result<Value<'a>> {
let depth = self.depth.get();
if depth >= 48 {
return Err(at(
Error::new(ErrorKind::Limit, "expression depth limit exceeded", None),
expr.span,
));
}
self.depth.set(depth + 1);
let result = self.inner(expr, missing).and_then(|value| {
if !value.owned_depth_within(crate::value::MAX_OWNED_DATA_DEPTH) {
value.discard_deep_owned();
return Err(crate::value::owned_data_depth_error());
}
self.check_value(&value)?;
Ok(value)
});
self.depth.set(depth);
result.map_err(|error| at(error, expr.span))
}
pub(crate) fn check_value(&self, value: &Value<'a>) -> Result<()> {
check_value(value, self.expansion, self.value_bytes)
}
pub(crate) fn check_expansion(&self, count: usize) -> Result<()> {
if count > self.expansion {
return Err(expansion_error());
}
Ok(())
}
pub(crate) fn read_field(
receiver: &Value<'a>,
name: &str,
nullable: bool,
) -> Result<Value<'a>> {
if nullable && receiver.is_null() {
return Ok(Value::Null);
}
if let Some(result) = crate::formatting::property(name, receiver) {
return result;
}
if let Some(value) = receiver.field(name) {
return Ok(value);
}
if !matches!(receiver.type_name(), "map") && !matches!(receiver, Value::Object(_)) {
return Err(fault(format!(
"cannot read field `{name}` on {}",
receiver.type_name()
)));
}
if nullable {
return Ok(Value::Null);
}
let keys = match receiver {
Value::Map(fields) => fields.keys().map(String::as_str).collect::<Vec<_>>(),
Value::Json(serde_json::Value::Object(fields)) => {
fields.keys().map(String::as_str).collect()
}
_ => Vec::new(),
};
Err(fault(format!(
"{} has no field `{name}`; available fields: {}",
receiver.type_name(),
keys.join(", ")
)))
}
pub(crate) fn has_alias(&self, name: &str) -> bool {
self.aliases.contains_key(name)
}
fn inner(&mut self, expr: &Expr, missing: bool) -> Result<Value<'a>> {
match &expr.kind {
ExprKind::Literal(value) => Ok(literal(value)),
ExprKind::Path(path) => {
let name = self.path_name(path);
if let Some(value) = self.lookup(&name) {
return Ok(value);
}
if missing {
return Ok(Value::Null);
}
Err(fault(format!("undefined variable or constant `{name}`")))
}
ExprKind::List(items) | ExprKind::Tuple(items) => {
self.check_expansion(items.len())?;
self.charge_expansion(items.len())?;
self.arguments(items).map(Value::List)
}
ExprKind::Map(items) => {
self.check_expansion(items.len())?;
self.charge_expansion(items.len())?;
let mut map = ValueMap::new();
for (field, value) in items {
let field = match field {
MapKey::Static(field) => field.clone(),
MapKey::Computed(expr) => key(&self.eval(expr)?)?,
};
map.insert(field, self.eval(value)?);
}
Ok(Value::Map(map))
}
ExprKind::ConditionalEntry { value, condition } => {
if boolean(&self.eval(condition)?)? {
self.eval(value)
} else {
Ok(Value::Null)
}
}
ExprKind::NamedArgument { value, .. } => self.eval(value),
ExprKind::Field {
receiver,
name,
optional,
} => {
if let ExprKind::Path(path) = &receiver.kind
&& matches!(path.as_slice(), [name] if name == "loop")
&& !self.aliases.contains_key("loop")
&& let Some(state) = self.local_loop()
{
self.check_expansion(LoopState::FIELD_COUNT)
.map_err(|error| at(error, receiver.span))?;
if let Some(value) = state.field(name) {
return Ok(value);
}
}
let nullable = missing || *optional;
let receiver = self.evaluate(receiver, nullable)?;
Self::read_field(&receiver, name, nullable)
}
ExprKind::Index {
receiver,
index,
optional,
} => {
let nullable = missing || *optional;
let receiver = self.evaluate(receiver, nullable)?;
if receiver.is_null() && nullable {
return Ok(Value::Null);
}
let index = self.eval(index)?;
lookup_index(&receiver, &index)?.map_or_else(
|| {
if nullable {
Ok(Value::Null)
} else {
Err(fault(format!(
"missing key or out-of-range index `{}`",
index.display().unwrap_or_default()
)))
}
},
Ok,
)
}
ExprKind::Call { callee, args } => self.call(callee, args),
ExprKind::Method {
receiver,
name,
optional,
args,
} => {
let value = self.evaluate(receiver, *optional || missing)?;
if value.is_null() && (*optional || missing) {
return Ok(Value::Null);
}
if matches!(value.type_name(), "list" | "map") && statements::is_mutator(name) {
return self.mutate(receiver, name, &args.values);
}
if name == "parse" {
return parse_number(&value, args);
}
let operands = self.arguments(&args.values)?;
self.check_string_method(name, &value, &operands)?;
let operands = Operands(operands);
library::method_with_limits(
name,
&value,
operands.borrow(&mut operands.closures()),
self.call_limits(),
)
.unwrap_or_else(|| self.registered_method(&value, name, &operands.0))
}
ExprKind::Try(value) => {
let value = self.eval(value)?;
if value.is_null() {
Err(fault("postfix ? encountered None or a failed parse"))
} else {
Ok(value)
}
}
ExprKind::Cast { value, ty } => cast(&self.eval(value)?, ty),
ExprKind::Unary { op, value } => {
let value = self.eval(value)?;
match op {
UnaryOp::Not => Ok(Value::Bool(!boolean(&value)?)),
UnaryOp::Negate => match value.scalar() {
Value::Int(value) => value
.checked_neg()
.map(Value::Int)
.ok_or_else(|| fault("integer overflow")),
Value::Float(value) => Ok(Value::Float(-value)),
_ => Err(fault("negation requires a number")),
},
}
}
ExprKind::Binary { op, left, right } => {
let left = self.evaluate(left, *op == BinaryOp::Coalesce)?;
match op {
BinaryOp::Coalesce => {
if left.is_null() {
self.eval(right)
} else {
Ok(left)
}
}
BinaryOp::And if !boolean(&left)? => Ok(Value::Bool(false)),
BinaryOp::Or if boolean(&left)? => Ok(Value::Bool(true)),
_ => binary(op, &left, &self.eval(right)?),
}
}
ExprKind::Range {
start,
end,
inclusive,
} => {
let start = start
.as_ref()
.map(|value| self.eval(value).and_then(|value| integer(&value)))
.transpose()?;
let end = end
.as_ref()
.map(|value| self.eval(value).and_then(|value| integer(&value)))
.transpose()?;
Range::new(start, end, *inclusive).map(Value::object)
}
ExprKind::If {
test,
then,
otherwise,
} => {
if boolean(&self.eval(test)?)? {
self.block(then)
} else if let Some(otherwise) = otherwise {
self.eval(otherwise)
} else {
Ok(Value::Null)
}
}
ExprKind::Block(block) => self.block(block),
ExprKind::Match { value, arms } => {
let value = self.eval(value)?;
for arm in arms {
let mut bindings = ValueMap::new();
if self.pattern(&arm.pattern, &value, &mut bindings)? {
let found = self.scoped(|this| {
for (name, value) in bindings {
this.bind(name, value, false);
}
if let Some(guard) = &arm.guard
&& !boolean(&this.eval(guard)?)?
{
return Ok(None);
}
this.eval(&arm.value).map(Some)
})?;
if let Some(value) = found {
return Ok(value);
}
}
}
Err(fault("no match arm matched the value"))
}
ExprKind::Closure { params, body } => {
if let [
Pattern {
kind: PatternKind::Binding(parameter),
..
},
] = params.as_slice()
&& let ExprKind::Field {
receiver,
name,
optional,
} = &body.kind
&& matches!(&receiver.kind, ExprKind::Path(path) if matches!(path.as_slice(), [name] if name == parameter))
&& !self.aliases.contains_key(parameter)
{
return Ok(Value::object(FieldClosure {
name: name.clone(),
optional: *optional,
receiver: receiver.span,
body: body.span,
depth: Rc::clone(&self.depth),
expansion: self.expansion,
value_bytes: self.value_bytes,
}));
}
Ok(Value::object(Closure {
captured: self.clone(),
params: params.clone(),
body: (**body).clone(),
}))
}
}
}
pub(crate) fn arguments(&mut self, expressions: &[Expr]) -> Result<Vec<Value<'a>>> {
expressions.iter().map(|expr| self.eval(expr)).collect()
}
pub(crate) fn encoding_arguments(&mut self, args: &[Expr]) -> Result<Vec<Value<'a>>> {
let mut result = Vec::new();
for (index, expr) in args.iter().enumerate() {
if index == 1
&& let ExprKind::List(flags) = &expr.kind
{
let mut values = Vec::new();
for flag in flags {
if let ExprKind::Path(path) = &flag.kind
&& path.len() == 1
{
values.push(Value::string(path[0].clone()));
} else {
values.push(self.eval(flag)?);
}
}
result.push(Value::List(values));
} else {
result.push(self.eval(expr)?);
}
}
Ok(result)
}
fn call(&mut self, callee: &Expr, args: &CallArgs) -> Result<Value<'a>> {
if let ExprKind::Path(path) = &callee.kind {
let name = self.resolve_path(path);
if self.lookup(&name).is_none() {
if name == "format" {
return self.format(&args.values);
}
if matches!(name.as_str(), "isset" | "empty") {
let value = match args.values.as_slice() {
[value] => self.optional(value)?,
_ => return Err(fault(format!("{name} expects one operand"))),
};
return Ok(Value::Bool(if name == "isset" {
!value.is_null()
} else {
library::blank(&value)
}));
}
let operands = if matches!(name.as_str(), "json" | "js") {
self.encoding_arguments(&args.values)?
} else {
self.arguments(&args.values)?
};
return self.function(&name, operands);
}
}
let callable = self.eval(callee)?;
let args = self.arguments(&args.values)?;
if let Value::Object(callable) = callable
&& let Some(result) = callable.call(&args)
{
return result;
}
Err(fault("value is not callable"))
}
pub(crate) fn function(&self, name: &str, values: Vec<Value<'a>>) -> Result<Value<'a>> {
if matches!(name, "str::repeat" | "php::str_repeat")
&& let [value, rest @ ..] = values.as_slice()
{
self.check_string_method("repeat", value, rest)?;
}
if matches!(name, "json" | "js") {
let (encoded, entries) = library::encode(name, &values, self.call_limits())?;
self.charge_expansion(entries)?;
return Ok(Value::html(encoded));
}
let operands = Operands(values);
let mut closures = operands.closures();
let args = operands.borrow(&mut closures);
let result = if let Some(clock) = &self.services.clock {
library::function_with_clock_and_limits(name, args, clock.as_ref(), self.call_limits())
} else {
library::function_with_limits(name, args, self.call_limits())
};
if let Some(result) = result {
return result;
}
if let Some(helper) = self.services.helpers.get(name) {
return helper(&operands.0);
}
if let Some(result) = library::translations::call(
name,
&operands.0,
self.services.translator.as_deref(),
self.services.locale.as_deref(),
self.call_limits(),
) {
return result;
}
let from = match name {
"session" => Some(&self.services.session),
"old" => Some(&self.services.old_input),
"context" => Some(&self.services.context),
_ => None,
};
if let Some(from) = from {
let [field, rest @ ..] = operands.0.as_slice() else {
return Err(fault(format!("{name} requires a key")));
};
let field = library::string(field)?;
return Ok(from
.get(field)
.cloned()
.or_else(|| rest.first().cloned())
.unwrap_or(Value::Null));
}
if matches!(name, "csrf_token" | "csrf_field") && operands.0.is_empty() {
let token = self
.services
.session
.get("_token")
.ok_or_else(|| fault("CSRF requires a session token"))?;
return if name == "csrf_field" {
let token = token.as_str().map_or_else(
|| token.display().map(std::borrow::Cow::Owned),
|text| Ok(std::borrow::Cow::Borrowed(text)),
)?;
let mut html = String::new();
write_csrf_field(&token, |part| {
self.call_limits()
.check_bytes(html.len().checked_add(part.len()))?;
html.push_str(part);
Ok(())
})?;
Ok(Value::html(html))
} else {
Ok(token.clone())
};
}
Err(fault(format!("unknown function `{name}`")))
}
pub(crate) fn call_limits(&self) -> library::CallLimits {
library::CallLimits {
output: self.budget.remaining_output(),
expansion: self.expansion_limit(),
depth: self.data_depth,
}
}
pub(crate) fn check_value_bytes(&self, bytes: Option<usize>) -> Result<()> {
if bytes.is_none_or(|bytes| bytes > self.value_bytes) {
return Err(Error::new(
ErrorKind::Limit,
"render output limit exceeded while evaluating text",
None,
));
}
Ok(())
}
fn check_string_method(
&self,
name: &str,
value: &Value<'_>,
operands: &[Value<'_>],
) -> Result<()> {
let Some(text) = value.as_str() else {
return Ok(());
};
match (name, operands) {
("repeat", [count]) => {
if let Ok(count) = integer(count)
&& let Ok(count) = usize::try_from(count)
{
self.check_value_bytes(text.len().checked_mul(count))?;
}
}
("replace", [from, to]) => {
if let (Some(from), Some(to)) = (from.as_str(), to.as_str())
&& to.len() > from.len()
{
let bytes = text
.matches(from)
.count()
.checked_mul(to.len() - from.len())
.and_then(|increase| text.len().checked_add(increase));
self.check_value_bytes(bytes)?;
}
}
_ => {}
}
Ok(())
}
fn format(&mut self, args: &[Expr]) -> Result<Value<'a>> {
let [
Expr {
kind: ExprKind::Literal(Literal::String(format)),
..
},
operands @ ..,
] = args
else {
return Err(fault("format requires a literal format string"));
};
let values = self.arguments(operands)?;
let mut output = String::new();
let mut position = 0;
for piece in format_pieces(format)? {
match piece {
FormatPiece::Text(text) => output.push_str(text),
FormatPiece::Positional => {
let value = values
.get(position)
.ok_or_else(|| fault("missing positional format argument"))?;
output.push_str(&value.display()?);
position += 1;
}
FormatPiece::Named(name) => {
let value = self
.lookup(name)
.ok_or_else(|| fault(format!("undefined format variable `{name}`")))?;
output.push_str(&value.display()?);
}
}
}
if position != values.len() {
return Err(fault("unused positional format argument"));
}
Ok(Value::string(output))
}
fn block(&mut self, block: &Block) -> Result<Value<'a>> {
self.scoped(|this| {
this.statements(&block.statements)?;
if this.flow == CodeFlow::Normal
&& let Some(tail) = &block.tail
{
return this.eval(tail);
}
Ok(Value::Null)
})
}
fn pattern(
&self,
pattern: &Pattern,
value: &Value<'a>,
bindings: &mut ValueMap<'a>,
) -> Result<bool> {
Ok(match &pattern.kind {
PatternKind::Binding(name) => {
bindings.insert(name.clone(), value.clone());
true
}
PatternKind::Wildcard => true,
PatternKind::Literal(expected) => {
let expected = literal(expected);
value.type_name() == expected.type_name() && equal(value, &expected)?
}
PatternKind::Path(path) => {
let name = self.resolve_path(path);
let expected = self
.lookup(&name)
.ok_or_else(|| at(fault(format!("unknown constant `{name}`")), pattern.span))?;
value.type_name() == expected.type_name() && equal(value, &expected)?
}
PatternKind::Tuple(patterns) | PatternKind::List(patterns) => {
if value.type_name() != "list" {
return Ok(false);
}
let entries = self.entries(value)?;
if entries.len() != patterns.len() {
return Ok(false);
}
for (pattern, (_, item)) in patterns.iter().zip(entries) {
if !self.pattern(pattern, &item, bindings)? {
return Ok(false);
}
}
true
}
PatternKind::Or(patterns) => {
for pattern in patterns {
let mut attempt = ValueMap::new();
if self.pattern(pattern, value, &mut attempt)? {
bindings.extend(attempt);
return Ok(true);
}
}
false
}
})
}
}
pub(crate) fn at(mut error: Error, span: Span) -> Error {
error.span.get_or_insert(span);
error
}
pub(crate) fn write_csrf_field(
token: &str,
mut write: impl FnMut(&str) -> Result<()>,
) -> Result<()> {
write("<input type=\"hidden\" name=\"_token\" value=\"")?;
crate::encode::escape_parts(token, true, &mut write)?;
write("\" autocomplete=\"off\">")
}
fn literal<'a>(value: &Literal) -> Value<'a> {
match value {
Literal::Null => Value::Null,
Literal::Bool(value) => Value::Bool(*value),
Literal::Int(value) => Value::Int(*value),
Literal::Float(value) => Value::Float(*value),
Literal::String(value) => Value::string(value.clone()),
}
}
pub(crate) fn lookup_index<'a>(
receiver: &Value<'a>,
index: &Value<'a>,
) -> Result<Option<Value<'a>>> {
Ok(match receiver {
Value::List(values) => usize::try_from(integer(index)?)
.ok()
.and_then(|index| values.get(index))
.cloned(),
Value::Json(serde_json::Value::Array(values)) => usize::try_from(integer(index)?)
.ok()
.and_then(|index| values.get(index))
.map(Value::Json),
Value::Map(_) | Value::Json(serde_json::Value::Object(_)) | Value::Object(_) => {
receiver.field(&key(index)?)
}
_ => return Err(fault(format!("cannot index {}", receiver.type_name()))),
})
}
fn parse_number<'a>(receiver: &Value<'_>, args: &CallArgs) -> Result<Value<'a>> {
let ([ty], []) = (args.types.as_slice(), args.values.as_slice()) else {
return Err(fault("parse requires a numeric type and no arguments"));
};
let text = library::string(receiver)?;
Ok(match ty.as_str() {
"i64" => text.parse().map(Value::Int).unwrap_or(Value::Null),
"f64" => text.parse().map(Value::Float).unwrap_or(Value::Null),
_ => return Err(fault(format!("unsupported parse type `{ty}`"))),
})
}
pub(crate) enum FormatPiece<'s> {
Text(&'s str),
Positional,
Named(&'s str),
}
pub(crate) fn format_pieces(mut format: &str) -> Result<Vec<FormatPiece<'_>>> {
let mut pieces = Vec::new();
while let Some(index) = format.find(['{', '}']) {
let (plain, rest) = format.split_at(index);
pieces.push(FormatPiece::Text(plain));
if rest.starts_with("{{") || rest.starts_with("}}") {
pieces.push(FormatPiece::Text(&rest[..1]));
format = &rest[2..];
} else if let Some(rest) = rest.strip_prefix('{') {
let (field, tail) = rest
.split_once('}')
.ok_or_else(|| fault("unterminated format placeholder"))?;
if field.is_empty() {
pieces.push(FormatPiece::Positional);
} else {
let mut chars = field.chars();
if !chars
.next()
.is_some_and(|ch| ch == '_' || ch.is_alphabetic())
|| !chars.all(|ch| ch == '_' || ch.is_alphanumeric())
{
return Err(fault(
"format placeholders must be empty or name a variable",
));
}
pieces.push(FormatPiece::Named(field));
}
format = tail;
} else {
return Err(fault("unmatched } in format string"));
}
}
pieces.push(FormatPiece::Text(format));
Ok(pieces)
}
pub(crate) fn check_value(value: &Value<'_>, expansion: usize, value_bytes: usize) -> Result<()> {
if value.is_rejected_owned_data() {
return Err(crate::value::owned_data_depth_error());
}
let size = match value {
Value::List(items) => items.len(),
Value::Map(items) => items.len(),
Value::Json(serde_json::Value::Array(items)) => items.len(),
Value::Json(serde_json::Value::Object(items)) => items.len(),
_ => 0,
};
if size > expansion {
return Err(expansion_error());
}
if let Value::Str(std::borrow::Cow::Owned(text)) | Value::Html(std::borrow::Cow::Owned(text)) =
value
&& text.len() > value_bytes
{
return Err(Error::new(
ErrorKind::Limit,
"render output limit exceeded while evaluating text",
None,
));
}
Ok(())
}
struct FieldClosure {
name: String,
optional: bool,
receiver: Span,
body: Span,
depth: Rc<Cell<usize>>,
expansion: usize,
value_bytes: usize,
}
impl std::fmt::Debug for FieldClosure {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("closure")
}
}
impl<'a> Object<'a> for FieldClosure {
fn type_name(&self) -> &'static str {
"closure"
}
fn is_callable(&self) -> bool {
true
}
fn call(&self, args: &[Value<'a>]) -> Option<Result<Value<'a>>> {
Some((|| {
let item = args
.first()
.ok_or_else(|| fault("too few arguments for closure"))?;
let depth = self.depth.get();
let limit =
|span| Error::new(ErrorKind::Limit, "expression depth limit exceeded", span);
if depth >= 47 {
return Err(limit(if depth == 47 {
self.receiver
} else {
self.body
}));
}
check_value(item, self.expansion, self.value_bytes)
.map_err(|error| at(error, self.receiver))?;
self.depth.set(depth + 1);
let result = Evaluator::read_field(item, &self.name, self.optional);
self.depth.set(depth);
let value = result.map_err(|error| at(error, self.body))?;
check_value(&value, self.expansion, self.value_bytes)
.map_err(|error| at(error, self.body))?;
Ok(value)
})())
}
}
struct Closure<'a> {
captured: Evaluator<'a>,
params: Vec<Pattern>,
body: Expr,
}
impl std::fmt::Debug for Closure<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("closure")
}
}
impl<'a> Object<'a> for Closure<'a> {
fn type_name(&self) -> &'static str {
"closure"
}
fn is_callable(&self) -> bool {
true
}
fn call(&self, args: &[Value<'a>]) -> Option<Result<Value<'a>>> {
Some((|| {
if args.len() < self.params.len() {
return Err(fault("too few arguments for closure"));
}
let mut env = self.captured.clone();
for (pattern, value) in self.params.iter().zip(args) {
env.bind_pattern(pattern, value, false)?;
}
env.eval(&self.body)
})())
}
}
struct Callback<'a>(Rc<dyn Object<'a> + 'a>);
impl<'a> Callable<'a> for Callback<'a> {
fn call(&mut self, args: &[Value<'a>]) -> Result<Value<'a>> {
self.0
.call(args)
.unwrap_or_else(|| Err(fault("value is not callable")))
}
}
struct Operands<'a>(Vec<Value<'a>>);
impl<'a> Operands<'a> {
fn closures(&self) -> Vec<Option<Callback<'a>>> {
self.0
.iter()
.map(|value| match value {
Value::Object(object) if object.is_callable() => Some(Callback(object.clone())),
_ => None,
})
.collect()
}
fn borrow<'c>(&self, callbacks: &'c mut [Option<Callback<'a>>]) -> Vec<Arg<'a, 'c>> {
self.0
.iter()
.zip(callbacks)
.map(|(value, callback)| match callback {
Some(callback) => Arg::Closure(callback),
None => Arg::Value(value.clone()),
})
.collect()
}
}