use crate::{
error::{Error, ErrorKind, Result},
library::{CallLimits, data_depth_error},
value::{Arg, Callable, Value, ValueMap},
};
use serde_json::Value as Json;
use std::{cmp::Ordering, rc::Rc};
pub(super) type Row<'a> = (Value<'a>, Value<'a>);
pub(super) fn error(message: impl Into<String>) -> Error {
Error::new(ErrorKind::Render, message, None)
}
pub(super) fn normalized<'a>(value: &Value<'a>) -> Value<'a> {
value.scalar()
}
pub(super) fn is_null(value: &Value<'_>) -> bool {
value.is_null()
}
pub(super) fn is_map(value: &Value<'_>) -> bool {
matches!(value, Value::Map(_) | Value::Json(Json::Object(_)))
}
pub(super) fn is_list(value: &Value<'_>) -> bool {
matches!(value, Value::List(_) | Value::Json(Json::Array(_)))
}
pub(super) fn is_collection(value: &Value<'_>) -> bool {
is_list(value) || is_map(value)
}
pub(super) fn size(value: &Value<'_>) -> usize {
match value {
Value::List(items) => items.len(),
Value::Map(items) => items.len(),
Value::Json(Json::Array(items)) => items.len(),
Value::Json(Json::Object(items)) => items.len(),
_ => 0,
}
}
pub(super) fn index<'a>(n: usize) -> Value<'a> {
Value::Int(n as i64)
}
pub(super) fn rows<'a>(value: &Value<'a>) -> Result<Vec<Row<'a>>> {
if !is_collection(value) {
return Err(error("expected a list or map"));
}
let mut entries = value.entries(usize::MAX)?;
for (_, value) in &mut entries {
if matches!(value, Value::Json(_)) {
*value = value.scalar();
}
}
Ok(entries)
}
pub(super) fn values<'a>(value: &Value<'a>) -> Result<Vec<Value<'a>>> {
Ok(rows(value)?.into_iter().map(|(_, v)| v).collect())
}
pub(super) fn collection<'a>(keyed: bool, rows: impl IntoIterator<Item = Row<'a>>) -> Value<'a> {
if keyed {
Value::Map(
rows.into_iter()
.map(|(k, v)| {
let k = match k {
Value::Str(k) => k.into_owned(),
Value::Int(k) => k.to_string(),
_ => unreachable!("collection row keys are strings or integers"),
};
(k, v)
})
.collect(),
)
} else {
Value::List(rows.into_iter().map(|(_, value)| value).collect())
}
}
pub(super) fn key(value: &Value<'_>) -> Result<String> {
match normalized(value) {
Value::Str(s) => Ok(s.into_owned()),
Value::Int(n) => Ok(n.to_string()),
_ => Err(error("collection keys must be strings or integers")),
}
}
pub(super) fn keys(value: &Value<'_>) -> Result<Vec<String>> {
if is_collection(value) {
values(value)?.iter().map(key).collect()
} else {
Ok(vec![key(value)?])
}
}
pub(super) fn integer(value: &Value<'_>) -> Result<i64> {
match normalized(value) {
Value::Int(n) => Ok(n),
_ => Err(error("expected an integer")),
}
}
pub(super) fn string<'a>(value: &Value<'a>) -> Result<std::borrow::Cow<'a, str>> {
match normalized(value) {
Value::Str(s) => Ok(s),
_ => Err(error("expected a string")),
}
}
pub(super) fn boolean(value: &Value<'_>) -> Result<bool> {
match normalized(value) {
Value::Bool(b) => Ok(b),
_ => Err(error("collection predicates must return a bool")),
}
}
pub(super) fn signed_offset(len: usize, offset: i64) -> usize {
if offset < 0 {
len.saturating_sub(magnitude(offset))
} else {
len.min(magnitude(offset))
}
}
pub(super) fn magnitude(n: i64) -> usize {
usize::try_from(n.unsigned_abs()).unwrap_or(usize::MAX)
}
pub(super) fn get_key<'a>(value: &Value<'a>, key: &str) -> Option<Value<'a>> {
let list_index = || key.parse::<usize>().ok().filter(|n| n.to_string() == key);
match value {
Value::List(items) => items.get(list_index()?).cloned(),
Value::Json(Json::Array(items)) => items
.get(list_index()?)
.map(|v| normalized(&Value::Json(v))),
_ => value.field(key).map(|v| normalized(&v)),
}
}
pub(super) fn data_get<'a>(
value: &Value<'a>,
path: &str,
depth: usize,
) -> Result<Option<Value<'a>>> {
fn descend<'a>(value: &Value<'a>, path: &[&str], depth: usize) -> Result<Option<Value<'a>>> {
let mut current = value.clone();
for (i, segment) in path.iter().enumerate() {
let next = match *segment {
"*" => {
let Ok(children) = values(¤t) else {
return Ok(None);
};
let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
let rest = &path[i + 1..];
let flatten = rest.contains(&"*");
let mut found = Vec::new();
for child in children {
let hit = descend(&child, rest, depth)?.unwrap_or(Value::Null);
if flatten {
found.extend(values(&hit).unwrap_or_default());
} else {
found.push(hit);
}
}
return Ok(Some(Value::List(found)));
}
"{first}" => rows(¤t)
.ok()
.and_then(|rows| rows.into_iter().next())
.map(|(_, item)| item),
"{last}" => rows(¤t)
.ok()
.and_then(|rows| rows.into_iter().next_back())
.map(|(_, item)| item),
"\\*" | "\\{first}" | "\\{last}" => get_key(¤t, &segment[1..]),
segment => get_key(¤t, segment),
};
let Some(next) = next else {
return Ok(None);
};
current = next;
}
Ok(Some(current.scalar()))
}
descend(value, &path.split('.').collect::<Vec<_>>(), depth)
}
pub(super) fn get_path<'a>(value: &Value<'a>, path: &str) -> Option<Value<'a>> {
get_key(value, path).or_else(|| {
let (first, rest) = path.split_once('.')?;
let mut current = get_key(value, first)?;
for segment in rest.split('.') {
current = get_key(¤t, segment)?;
}
Some(current)
})
}
pub(super) fn equal<'a>(a: &Value<'a>, b: &Value<'a>, depth: usize) -> Result<bool> {
if is_map(a) && is_map(b) {
if size(a) != size(b) {
return Ok(false);
}
let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
for (k, v) in rows(a)? {
let Some(other) = get_key(b, &key(&k)?) else {
return Ok(false);
};
if !equal(&v, &other, depth)? {
return Ok(false);
}
}
return Ok(true);
}
if is_list(a) && is_list(b) {
if size(a) != size(b) {
return Ok(false);
}
let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
let a = values(a)?;
let b = values(b)?;
return any_match(a.iter().zip(&b), |(a, b)| Ok(!equal(a, b, depth)?))
.map(|different| !different);
}
if is_collection(a) || is_collection(b) {
return Ok(false);
}
Ok(match (normalized(a), normalized(b)) {
(Value::Null, Value::Null) => true,
(Value::Bool(a), Value::Bool(b)) => a == b,
(Value::Int(a), Value::Int(b)) => a == b,
(Value::Float(a), Value::Float(b)) => a == b,
(Value::Str(a), Value::Str(b)) | (Value::Html(a), Value::Html(b)) => a == b,
(Value::Object(a), Value::Object(b)) => Rc::ptr_eq(&a, &b),
_ => false,
})
}
pub(super) fn any_match<T>(
items: impl IntoIterator<Item = T>,
mut test: impl FnMut(T) -> Result<bool>,
) -> Result<bool> {
for item in items {
if test(item)? {
return Ok(true);
}
}
Ok(false)
}
pub(super) fn compare(a: &Value<'_>, b: &Value<'_>, depth: usize) -> Result<Ordering> {
fn unwrapped<'v, 'a>(mut value: &'v Value<'a>) -> &'v Value<'a> {
while let Value::Object(object) = value {
let Some(inner) = object.underlying() else {
break;
};
value = inner;
}
value
}
let (a, b) = (unwrapped(a), unwrapped(b));
if is_list(a) && is_list(b) {
let depth = depth.checked_sub(1).ok_or_else(data_depth_error)?;
let a = values(a)?;
let b = values(b)?;
for (a, b) in a.iter().zip(&b) {
let order = compare(a, b, depth)?;
if order != Ordering::Equal {
return Ok(order);
}
}
return Ok(a.len().cmp(&b.len()));
}
let incompatible = || error("collection ordering requires values of the same ordered type");
if is_collection(a) || is_collection(b) {
return Err(incompatible());
}
match (normalized(a), normalized(b)) {
(Value::Null, Value::Null) => Ok(Ordering::Equal),
(Value::Int(a), Value::Int(b)) => Ok(a.cmp(&b)),
(Value::Float(a), Value::Float(b)) => {
a.partial_cmp(&b).ok_or_else(|| error("cannot order NaN"))
}
(Value::Bool(a), Value::Bool(b)) => Ok(a.cmp(&b)),
(Value::Str(a), Value::Str(b)) | (Value::Html(a), Value::Html(b)) => Ok(a.cmp(&b)),
_ => Err(incompatible()),
}
}
pub(super) struct Args<'a, 'c>(pub(super) Vec<Arg<'a, 'c>>, pub(super) CallLimits);
impl<'a, 'c> Args<'a, 'c> {
pub(super) fn count(&self, name: &str, min: usize, max: usize) -> Result<()> {
if (min..=max).contains(&self.0.len()) {
Ok(())
} else {
Err(error(format!(
"{name} expects {min}..={max} arguments, got {}",
self.0.len()
)))
}
}
pub(super) fn value(&self, i: usize) -> Result<Value<'a>> {
match self.0.get(i) {
Some(Arg::Value(v)) => Ok(normalized(v)),
Some(Arg::Closure(_)) => Err(error("expected a value, received a closure")),
None => Ok(Value::Null),
}
}
pub(super) fn int(&self, i: usize, default: i64) -> Result<i64> {
let value = self.value(i)?;
if is_null(&value) {
Ok(default)
} else {
integer(&value)
}
}
pub(super) fn bool(&self, i: usize, default: bool) -> Result<bool> {
let value = self.value(i)?;
if is_null(&value) {
Ok(default)
} else {
boolean(&value)
}
}
pub(super) fn closure(&mut self, i: usize) -> Result<&mut dyn Callable<'a>> {
match self.0.get_mut(i) {
Some(Arg::Closure(call)) => Ok(&mut **call),
_ => Err(error("expected a closure argument")),
}
}
pub(super) fn has_closure(&self, i: usize) -> bool {
matches!(self.0.get(i), Some(Arg::Closure(_)))
}
pub(super) fn call(&mut self, i: usize, args: &[Value<'a>]) -> Result<Value<'a>> {
self.closure(i)?.call(args)
}
pub(super) fn default(&mut self, i: usize) -> Result<Value<'a>> {
if self.has_closure(i) {
self.call(i, &[])
} else {
self.value(i)
}
}
pub(super) fn selector(&mut self, i: usize, (k, v): &Row<'a>) -> Result<Value<'a>> {
if self.has_closure(i) {
return self.call(i, &[v.clone(), k.clone()]);
}
let selector = self.value(i)?;
if is_null(&selector) {
Ok(normalized(v))
} else {
Ok(data_get(v, &key(&selector)?, self.1.data_depth())?.unwrap_or(Value::Null))
}
}
}
pub(super) fn json(value: &Value<'_>, depth: usize) -> Result<Json> {
let child_depth = || depth.checked_sub(1).ok_or_else(data_depth_error);
match value {
Value::Json(Json::Array(values)) => {
let depth = child_depth()?;
Ok(Json::Array(
values
.iter()
.map(|value| json(&Value::Json(value), depth))
.collect::<Result<_>>()?,
))
}
Value::Json(Json::Object(values)) => {
let depth = child_depth()?;
Ok(Json::Object(
values
.iter()
.map(|(key, value)| Ok((key.clone(), json(&Value::Json(value), depth)?)))
.collect::<Result<_>>()?,
))
}
Value::Json(v) => Ok((*v).clone()),
Value::Null => Ok(Json::Null),
Value::Bool(v) => Ok(Json::Bool(*v)),
Value::Int(v) => Ok(Json::from(*v)),
Value::Float(v) => serde_json::Number::from_f64(*v)
.map(Json::Number)
.ok_or_else(|| error("cannot encode non-finite float")),
Value::Str(v) | Value::Html(v) => Ok(Json::String(v.to_string())),
Value::List(v) => {
let depth = child_depth()?;
Ok(Json::Array(
v.iter().map(|v| json(v, depth)).collect::<Result<_>>()?,
))
}
Value::Map(v) => {
let depth = child_depth()?;
Ok(Json::Object(
v.iter()
.map(|(k, v)| Ok((k.clone(), json(v, depth)?)))
.collect::<Result<_>>()?,
))
}
Value::Object(_) => Err(error("cannot serialize a render object as collection data")),
}
}
pub(super) fn from_json<'a>(value: Json) -> Value<'a> {
match value {
Json::Null => Value::Null,
Json::Bool(v) => Value::Bool(v),
Json::Number(v) => v
.as_i64()
.map(Value::Int)
.unwrap_or_else(|| Value::Float(v.as_f64().unwrap_or_default())),
Json::String(v) => Value::string(v),
Json::Array(v) => Value::List(v.into_iter().map(from_json).collect()),
Json::Object(v) => Value::Map(v.into_iter().map(|(k, v)| (k, from_json(v))).collect()),
}
}
pub(super) fn map<'a>() -> ValueMap<'a> {
ValueMap::new()
}