use crate::{
attributes::{
AttributeBag, AttributeError, AttributeValue, Attributes, sanitize_component_attribute,
validate_name,
},
encode::{JsonKind, JsonValue},
engine::RenderBudget,
error::{Error, ErrorKind, Result},
eval::Evaluator,
library::{boolean, fault, key, string},
value::{Arg, Object, Value, expansion_error},
};
use super::super::directives::css_value;
#[derive(Clone, Debug)]
pub(super) struct Bag(pub(super) AttributeBag, pub(super) BagLimits);
impl Bag {
fn html(&self, bag: &AttributeBag) -> Result<String> {
bag.to_html_bounded(self.1.output_limit()).map_err(|error| {
if error == AttributeError::OutputLimit {
Error::new(ErrorKind::Limit, error.to_string(), None)
} else {
fault(error.to_string())
}
})
}
fn with_bag<'a>(&self, bag: AttributeBag) -> Value<'a> {
Value::object(Self(bag, self.1.clone()))
}
pub(super) fn extract<'b>(value: &'b Value<'_>) -> Option<&'b AttributeBag> {
let Value::Object(object) = value else {
return None;
};
object.as_any()?.downcast_ref::<Self>().map(|bag| &bag.0)
}
}
#[derive(Debug)]
struct Prepend(AttributeValue);
impl Object<'_> for Prepend {
fn type_name(&self) -> &'static str {
"prepended attribute"
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
Some(self)
}
}
impl<'a> Object<'a> for Bag {
fn type_name(&self) -> &'static str {
"attribute bag"
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
Some(self)
}
fn display(&self) -> Result<String> {
self.html(&self.0)
}
fn is_trusted_html(&self) -> bool {
true
}
fn json_kind(&self) -> JsonKind<'_> {
self.0.json_kind()
}
fn field(&self, name: &str) -> Option<Value<'a>> {
self.0.get(name).map(value_from_attribute)
}
fn call(&self, args: &[Value<'a>]) -> Option<Result<Value<'a>>> {
Some((|| {
let defaults = match args {
[] => Attributes::new(),
[value] => self.1.converter().map(value, None)?,
_ => return Err(fault("attribute bag invocation accepts an optional map")),
};
let bag = self
.0
.merge(&defaults, true)
.map_err(|error| fault(error.to_string()))?;
self.html(&bag).map(Value::html)
})())
}
fn method(&self, name: &str, mut args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
let mut method = || {
Ok(match (name, args.as_mut_slice()) {
("class" | "style", [Arg::Value(items)]) => {
let css = css_value(items, name == "class", self.1.output_limit(), |value| {
self.1.entries(value)
})?;
let defaults = [(name.to_owned(), AttributeValue::Text(css))].into();
self.with_bag(
self.0
.merge(&defaults, true)
.map_err(|err| fault(err.to_string()))?,
)
}
("merge", []) => self.with_bag(
self.0
.merge(&Attributes::new(), true)
.map_err(|error| fault(error.to_string()))?,
),
("merge", [Arg::Value(defaults), rest @ ..]) => {
let defaults = self.1.converter().map(defaults, None)?;
let escape = match rest {
[] => true,
[Arg::Value(value)] => boolean(value)?,
_ => return Err(fault("merge accepts a map and an optional escape flag")),
};
self.with_bag(
self.0
.merge(&defaults, escape)
.map_err(|err| fault(err.to_string()))?,
)
}
(
"only"
| "except"
| "only_props"
| "except_props"
| "where_starts_with"
| "where_doesnt_start_with"
| "that_start_with"
| "has"
| "has_any"
| "missing",
[Arg::Value(names)],
) => {
if names.is_null() && matches!(name, "only" | "except") {
return Ok(Value::object(self.clone()));
}
let keys = if matches!(name, "only_props" | "except_props")
&& names.type_name() == "map"
{
self.1
.entries(names)?
.into_iter()
.map(|(key, _)| string(&key).map(str::to_owned))
.collect::<Result<Vec<_>>>()?
} else {
self.1.keys(names)?
};
let keys = keys.iter().map(String::as_str).collect::<Vec<_>>();
let bag = match name {
"only" => self.0.only(&keys),
"except" => self.0.except(&keys),
"only_props" => self.0.only_props(&keys),
"except_props" => self.0.except_props(&keys),
"where_starts_with" | "that_start_with" => self.0.where_starts_with(&keys),
"where_doesnt_start_with" => self.0.where_doesnt_start_with(&keys),
"has" => return Ok(Value::Bool(self.0.has(&keys))),
"has_any" => return Ok(Value::Bool(self.0.has_any(&keys))),
_ => return Ok(Value::Bool(self.0.missing(&keys))),
};
self.with_bag(bag)
}
("get", [Arg::Value(field), rest @ ..]) => read(self.0.get(string(field)?), rest)?,
("first", rest) => read(self.0.first(), rest)?,
("offset_exists", [Arg::Value(field)]) => {
Value::Bool(self.0.offset_exists(string(field)?))
}
("offset_get", [Arg::Value(field)]) => {
read(self.0.offset_get(string(field)?), &mut [])?
}
("set_attributes", [Arg::Value(value)]) => {
self.with_bag(self.1.replacement_bag(value)?)
}
("offset_set", [Arg::Value(field), Arg::Value(value)]) => {
let mut bag = self.0.clone();
bag.offset_set(
attribute_name(string(field)?)?,
sanitize_component_attribute(
self.1.converter().value(value, self.1.depth)?,
),
);
self.with_bag(bag)
}
("offset_unset", [Arg::Value(field)]) => {
let mut bag = self.0.clone();
bag.offset_unset(string(field)?);
self.with_bag(bag)
}
("prepends", [Arg::Value(value)]) => {
let value = self
.0
.prepends(self.1.converter().value(value, self.1.depth)?);
if !value.depth_within(crate::value::MAX_OWNED_DATA_DEPTH) {
return Err(crate::library::data_depth_error());
}
Value::object(Prepend(value))
}
("is_empty" | "is_not_empty", []) => {
let empty = self.html(&self.0)?.is_empty();
Value::Bool(empty == (name == "is_empty"))
}
("to_html", []) => Value::html(self.display()?),
("get_attributes" | "all" | "to_array" | "json_serialize" | "get_iterator", []) => {
attributes_map(self.0.all())
}
("all", [Arg::Value(keys)]) => {
if keys.is_null() {
return Ok(attributes_map(self.0.all()));
}
let keys = self.1.keys(keys)?;
let keys = keys.iter().map(String::as_str).collect::<Vec<_>>();
attributes_map(&self.0.all_for(&keys))
}
("when" | "unless", [condition, Arg::Closure(yes), rest @ ..]) => {
let bag = Value::object(self.clone());
let test = match condition {
Arg::Value(value) => value.clone(),
Arg::Closure(predicate) => predicate.call(std::slice::from_ref(&bag))?,
};
let callback = match (boolean(&test)? == (name == "when"), rest) {
(true, [] | [Arg::Closure(_)]) => Some(yes),
(false, [Arg::Closure(no)]) => Some(no),
(false, []) => None,
_ => {
return Err(fault(
"when and unless accept an optional fallback closure",
));
}
};
if let Some(callback) = callback {
let value = callback.call(&[bag.clone(), test])?;
if !value.is_null() {
return Ok(value);
}
}
bag
}
("filter", [Arg::Closure(callback)]) => {
let mut filtered = Attributes::new();
for (field, value) in &self.0 {
if boolean(
&callback.call(&[
value_from_attribute(value),
Value::string(field.clone()),
])?,
)? {
filtered.insert(field.clone(), value.clone());
}
}
self.with_bag(AttributeBag::new(filtered))
}
_ => return Err(fault(format!("invalid attribute bag method `{name}`"))),
})
};
Some(method())
}
}
fn read<'a>(value: Option<&AttributeValue>, args: &mut [Arg<'a, '_>]) -> Result<Value<'a>> {
match (value, args) {
(Some(value), [] | [_]) => Ok(value_from_attribute(value)),
(None, []) => Ok(Value::Null),
(None, [Arg::Value(value)]) => Ok(value.clone()),
(None, [Arg::Closure(fallback)]) => fallback.call(&[]),
_ => Err(fault("expected an optional default value")),
}
}
fn attributes_map<'a>(values: &Attributes) -> Value<'a> {
Value::Map(
values
.iter()
.map(|(key, value)| (key.clone(), value_from_attribute(value)))
.collect(),
)
}
pub(super) fn attribute_name(name: &str) -> Result<&str> {
validate_name(name).map_err(|error| fault(error.to_string()))?;
Ok(name)
}
#[derive(Clone, Debug)]
pub(super) struct BagLimits {
expansion: usize,
depth: usize,
budget: RenderBudget,
shared_budget: bool,
}
impl BagLimits {
pub(super) fn new(eval: &Evaluator<'_>) -> Self {
let limits = eval.call_limits();
Self {
expansion: limits.expansion,
depth: limits.depth.min(crate::value::MAX_OWNED_DATA_DEPTH),
budget: eval.budget().clone(),
shared_budget: eval.has_shared_budget(),
}
}
fn expansion_limit(&self) -> usize {
if self.shared_budget {
self.budget.remaining_expansion()
} else {
self.expansion
}
}
fn charge_expansion(&self, entries: usize) -> Result<()> {
if self.shared_budget {
self.budget.charge_expansion(entries)?;
}
Ok(())
}
fn entries<'a>(&self, value: &Value<'a>) -> Result<Vec<(Value<'a>, Value<'a>)>> {
let entries = value.entries(self.expansion_limit())?;
self.charge_expansion(entries.len())?;
Ok(entries)
}
fn output_limit(&self) -> usize {
self.budget.remaining_output()
}
fn keys(&self, value: &Value<'_>) -> Result<Vec<String>> {
if let Some(key) = value.as_str() {
return Ok(vec![key.to_owned()]);
}
self.entries(value)?
.into_iter()
.map(|(_, key)| string(&key).map(str::to_owned))
.collect()
}
pub(super) fn converter(&self) -> AttributeConverter<'_> {
AttributeConverter {
limits: self,
remaining: self.expansion_limit(),
bytes: self.output_limit(),
}
}
pub(super) fn value(&self, value: &Value<'_>) -> Result<AttributeValue> {
self.converter().value(value, self.depth)
}
pub(super) fn replacement_bag(&self, value: &Value<'_>) -> Result<AttributeBag> {
if let Some(bag) = Bag::extract(value) {
return Ok(bag.clone());
}
let parent = value.field("attributes");
let parent = parent.as_ref().and_then(Bag::extract);
let attributes = self
.converter()
.map(value, parent.map(|_| "attributes"))?
.into_iter()
.map(|(name, value)| (name, sanitize_component_attribute(value)))
.collect();
if let Some(parent) = parent {
parent
.merge(&attributes, false)
.map_err(|error| fault(error.to_string()))
} else {
Ok(AttributeBag::new(attributes))
}
}
}
pub(super) struct AttributeConverter<'l> {
limits: &'l BagLimits,
remaining: usize,
bytes: usize,
}
impl AttributeConverter<'_> {
fn map(&mut self, value: &Value<'_>, skip: Option<&str>) -> Result<Attributes> {
if !matches!(value.type_name(), "map" | "list") {
return Err(fault("expected an attribute map"));
}
self.array(value, self.limits.depth, true, skip)
}
fn value(&mut self, value: &Value<'_>, depth: usize) -> Result<AttributeValue> {
if let Some(text) = value.as_str() {
self.charge_bytes(text.len())?;
return Ok(AttributeValue::Text(text.to_owned()));
}
if let Value::Html(text) = value {
self.charge_bytes(text.len())?;
return Ok(AttributeValue::Html(text.to_string()));
}
if matches!(
value,
Value::List(_)
| Value::Map(_)
| Value::Json(serde_json::Value::Object(_) | serde_json::Value::Array(_))
) {
return Ok(AttributeValue::Array(
self.array(value, depth, false, None)?,
));
}
Ok(match value.scalar() {
Value::Null => AttributeValue::Null,
Value::Bool(value) => AttributeValue::Bool(value),
Value::Int(value) => AttributeValue::Integer(value),
Value::Float(value) => AttributeValue::Float(value),
Value::Str(value) => {
self.charge_bytes(value.len())?;
AttributeValue::Text(value.into_owned())
}
Value::Html(value) => {
self.charge_bytes(value.len())?;
AttributeValue::Html(value.into_owned())
}
Value::Object(ref object) => {
if let Some(value) = object
.as_any()
.and_then(|obj| obj.downcast_ref::<Prepend>())
{
if !value.0.depth_within(depth) {
return Err(crate::library::data_depth_error());
}
value.0.clone()
} else if !object.is_trusted_html()
&& matches!(object.json_kind(), JsonKind::Object(_) | JsonKind::Array(_))
{
AttributeValue::Array(self.array(value, depth, false, None)?)
} else {
let text = object.display()?;
self.charge_bytes(text.len())?;
if object.is_trusted_html() {
AttributeValue::Html(text)
} else {
AttributeValue::Stringable(text)
}
}
}
_ => AttributeValue::Array(self.array(value, depth, false, None)?),
})
}
fn charge_bytes(&mut self, bytes: usize) -> Result<()> {
self.bytes = self.bytes.checked_sub(bytes).ok_or_else(|| {
crate::error::Error::new(
crate::error::ErrorKind::Limit,
"render output limit exceeded while converting attributes",
None,
)
})?;
Ok(())
}
fn array(
&mut self,
value: &Value<'_>,
depth: usize,
validate_names: bool,
skip: Option<&str>,
) -> Result<Attributes> {
let depth = depth
.checked_sub(1)
.ok_or_else(crate::library::data_depth_error)?;
let entries = value.entries(self.remaining.min(self.limits.expansion_limit()))?;
self.remaining = self
.remaining
.checked_sub(entries.len())
.ok_or_else(expansion_error)?;
self.limits.charge_expansion(entries.len())?;
let mut attributes = Attributes::with_capacity(entries.len());
for (name, value) in entries {
let name = key(&name)?;
self.charge_bytes(name.len())?;
if skip == Some(&name) {
continue;
}
if validate_names {
attribute_name(&name)?;
}
attributes.insert(name, self.value(&value, depth)?);
}
Ok(attributes)
}
}
pub(super) fn value_from_attribute<'a>(value: &AttributeValue) -> Value<'a> {
match value {
AttributeValue::Null => Value::Null,
AttributeValue::Bool(value) => Value::Bool(*value),
AttributeValue::Integer(value) => Value::Int(*value),
AttributeValue::Float(value) => Value::Float(*value),
AttributeValue::Text(value)
| AttributeValue::Stringable(value)
| AttributeValue::Escapable { text: value, .. } => Value::string(value.clone()),
AttributeValue::Html(value) => Value::html(value.clone()),
AttributeValue::Prepended(_) => Value::object(Prepend(value.clone())),
AttributeValue::Array(values) => Value::Map(
values
.iter()
.map(|(key, value)| (key.clone(), value_from_attribute(value)))
.collect(),
),
}
}