#![allow(clippy::missing_docs_in_private_items)]
use rust_decimal::Decimal;
use std::collections::HashMap;
use crate::error::MissingTimezoneContextError;
use crate::evaluator::Environment;
use crate::types::{Date as TypeDate, Value as TypeValue, parse_datetime_literal};
#[derive(Debug, Clone)]
pub struct RepeatContext {
pub current: TypeValue,
pub index: usize,
pub count: usize,
pub parent: Option<Box<RepeatContext>>,
pub collection: Vec<TypeValue>,
}
#[derive(Debug, Clone)]
pub struct MipState {
pub valid: bool,
pub relevant: bool,
pub readonly: bool,
pub required: bool,
}
#[allow(missing_docs)]
impl Default for MipState {
fn default() -> Self {
Self {
valid: true,
relevant: true,
readonly: false,
required: false,
}
}
}
pub struct FormspecEnvironment {
pub data: HashMap<String, TypeValue>,
pub instances: HashMap<String, TypeValue>,
pub mip_states: HashMap<String, MipState>,
pub variables: HashMap<String, TypeValue>,
pub repeat_context: Option<RepeatContext>,
pub current_datetime: Option<TypeDate>,
pub locale: Option<String>,
pub date_formats: HashMap<String, String>,
pub meta: HashMap<String, TypeValue>,
}
impl FormspecEnvironment {
pub fn new() -> Self {
Self {
data: HashMap::new(),
instances: HashMap::new(),
mip_states: HashMap::new(),
variables: HashMap::new(),
repeat_context: None,
current_datetime: None,
locale: None,
date_formats: HashMap::new(),
meta: HashMap::new(),
}
}
pub fn set_field(&mut self, path: &str, value: TypeValue) {
self.data.insert(path.to_string(), value);
}
pub fn set_instance(&mut self, name: &str, value: TypeValue) {
self.instances.insert(name.to_string(), value);
}
pub fn set_mip(&mut self, path: &str, state: MipState) {
self.mip_states.insert(path.to_string(), state);
}
pub fn set_variable(&mut self, name: &str, value: TypeValue) {
self.variables.insert(name.to_string(), value);
}
pub fn set_locale(&mut self, code: &str) {
self.locale = Some(code.to_string());
}
pub fn set_date_format(&mut self, style: &str, pattern: &str) {
self.date_formats
.insert(style.to_string(), pattern.to_string());
}
pub fn set_meta(&mut self, key: &str, value: TypeValue) {
self.meta.insert(key.to_string(), value);
}
pub fn set_now_from_iso(&mut self, iso: &str) {
let candidate = if iso.starts_with('@') {
iso.to_string()
} else {
format!("@{iso}")
};
self.current_datetime = parse_datetime_literal(&candidate);
}
pub fn push_repeat(
&mut self,
current: TypeValue,
index: usize,
count: usize,
collection: Vec<TypeValue>,
) {
let parent = self.repeat_context.take().map(Box::new);
self.repeat_context = Some(RepeatContext {
current,
index,
count,
parent,
collection,
});
}
pub fn pop_repeat(&mut self) {
if let Some(ctx) = self.repeat_context.take() {
self.repeat_context = ctx.parent.map(|b| *b);
}
}
}
#[allow(missing_docs)]
impl Default for FormspecEnvironment {
fn default() -> Self {
Self::new()
}
}
pub fn resolve_value_path(val: &TypeValue, segments: &[String]) -> TypeValue {
let mut current = val.clone();
for seg in segments {
match ¤t {
TypeValue::Object(entries) => match entries.get(seg.as_str()) {
Some(v) => current = v.clone(),
None => return TypeValue::Null,
},
TypeValue::Array(entries) => {
current = TypeValue::Array(
entries
.iter()
.map(|entry| match entry {
TypeValue::Object(fields) => {
fields.get(seg.as_str()).cloned().unwrap_or(TypeValue::Null)
}
_ => TypeValue::Null,
})
.collect(),
);
}
_ => return TypeValue::Null,
}
}
current
}
fn project_repeat_field(
data: &HashMap<String, TypeValue>,
segments: &[String],
) -> Option<TypeValue> {
if segments.len() < 2 {
return None;
}
for split in 1..segments.len() {
let group_path = segments[..split].join(".");
let prefix = format!("{group_path}[");
let suffix = format!(".{}", segments[split..].join("."));
let mut projected = Vec::new();
for (key, value) in data {
let Some(rest) = key.strip_prefix(&prefix) else {
continue;
};
let Some((idx, tail)) = rest.split_once(']') else {
continue;
};
if tail != suffix {
continue;
}
let Ok(index) = idx.parse::<usize>() else {
continue;
};
projected.push((index, value.clone()));
}
if !projected.is_empty() {
projected.sort_by_key(|(index, _)| *index);
return Some(TypeValue::Array(
projected.into_iter().map(|(_, value)| value).collect(),
));
}
}
None
}
fn mip_path(path: &[String]) -> String {
path.join(".")
}
#[allow(missing_docs)]
impl Environment for FormspecEnvironment {
fn resolve_field(&self, segments: &[String]) -> TypeValue {
if segments.is_empty() {
if let Some(val) = self.data.get("") {
return val.clone();
}
if let Some(ctx) = &self.repeat_context {
return ctx.current.clone();
}
return TypeValue::Null;
}
let key = segments.join(".");
if let Some(val) = self.data.get(&key) {
return val.clone();
}
if let Some(val) = self.data.get(&segments[0]) {
if segments.len() == 1 {
return val.clone();
}
return resolve_value_path(val, &segments[1..]);
}
if let Some(projected) = project_repeat_field(&self.data, segments) {
return projected;
}
TypeValue::Null
}
fn resolve_context(&self, name: &str, arg: Option<&str>, tail: &[String]) -> TypeValue {
match name {
"current" => {
if let Some(ctx) = &self.repeat_context {
let base = ctx.current.clone();
if tail.is_empty() {
base
} else {
resolve_value_path(&base, tail)
}
} else {
TypeValue::Null
}
}
"index" => {
if let Some(ctx) = &self.repeat_context {
TypeValue::Number(Decimal::from(ctx.index as i64))
} else {
TypeValue::Null
}
}
"count" => {
if let Some(ctx) = &self.repeat_context {
TypeValue::Number(Decimal::from(ctx.count as i64))
} else {
TypeValue::Null
}
}
"instance" => {
if let Some(inst_name) = arg {
if let Some(val) = self.instances.get(inst_name) {
if tail.is_empty() {
val.clone()
} else {
resolve_value_path(val, tail)
}
} else {
TypeValue::Null
}
} else {
TypeValue::Null
}
}
_ => {
if let Some(val) = self.variables.get(name) {
if tail.is_empty() {
val.clone()
} else {
resolve_value_path(val, tail)
}
} else {
TypeValue::Null
}
}
}
}
fn mip_valid(&self, path: &[String]) -> TypeValue {
let key = mip_path(path);
TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.valid))
}
fn mip_relevant(&self, path: &[String]) -> TypeValue {
let key = mip_path(path);
TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.relevant))
}
fn mip_readonly(&self, path: &[String]) -> TypeValue {
let key = mip_path(path);
TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.readonly))
}
fn mip_required(&self, path: &[String]) -> TypeValue {
let key = mip_path(path);
TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.required))
}
fn repeat_prev(&self) -> TypeValue {
if let Some(ctx) = &self.repeat_context
&& ctx.index > 1
{
return ctx
.collection
.get(ctx.index - 2)
.cloned()
.unwrap_or(TypeValue::Null);
}
TypeValue::Null
}
fn repeat_next(&self) -> TypeValue {
if let Some(ctx) = &self.repeat_context
&& ctx.index < ctx.count
{
return ctx
.collection
.get(ctx.index)
.cloned()
.unwrap_or(TypeValue::Null);
}
TypeValue::Null
}
fn repeat_parent(&self) -> TypeValue {
if let Some(ctx) = &self.repeat_context
&& let Some(parent) = &ctx.parent
{
return parent.current.clone();
}
TypeValue::Null
}
fn current_date(&self) -> Result<TypeDate, MissingTimezoneContextError> {
self.current_datetime().map(|dt| TypeDate::Date {
year: dt.year(),
month: dt.month(),
day: dt.day(),
})
}
fn current_datetime(&self) -> Result<TypeDate, MissingTimezoneContextError> {
self.current_datetime
.clone()
.ok_or_else(MissingTimezoneContextError::not_configured)
}
fn locale(&self) -> Option<&str> {
self.locale.as_deref()
}
fn date_format(&self, style: &str) -> Option<&str> {
self.date_formats.get(style).map(String::as_str)
}
fn runtime_meta(&self, key: &str) -> TypeValue {
self.meta.get(key).cloned().unwrap_or(TypeValue::Null)
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::missing_docs_in_private_items)]
use super::*;
use indexmap::IndexMap;
fn s(v: &str) -> TypeValue {
TypeValue::String(v.to_string())
}
fn num(n: i64) -> TypeValue {
TypeValue::Number(Decimal::from(n))
}
#[test]
fn test_basic_field_resolution() {
let mut env = FormspecEnvironment::new();
env.set_field("name", s("Alice"));
env.set_field("age", num(30));
assert_eq!(env.resolve_field(&["name".into()]), s("Alice"));
assert_eq!(env.resolve_field(&["age".into()]), num(30));
assert_eq!(env.resolve_field(&["missing".into()]), TypeValue::Null);
}
#[test]
fn test_nested_field_resolution() {
let mut env = FormspecEnvironment::new();
let addr = TypeValue::Object(IndexMap::from([
("city".to_string(), s("NYC")),
("zip".to_string(), s("10001")),
]));
env.set_field("address", addr);
assert_eq!(
env.resolve_field(&["address".into(), "city".into()]),
s("NYC")
);
assert_eq!(
env.resolve_field(&["address".into(), "missing".into()]),
TypeValue::Null
);
}
#[test]
fn test_repeat_field_projection_from_flat_rows() {
let mut env = FormspecEnvironment::new();
env.set_field("rows[0].score", num(80));
env.set_field("rows[1].score", num(30));
env.set_field("rows[2].score", num(50));
assert_eq!(
env.resolve_field(&["rows".into(), "score".into()]),
TypeValue::Array(vec![num(80), num(30), num(50)]),
);
}
#[test]
fn test_repeat_context() {
let mut env = FormspecEnvironment::new();
let items = vec![num(10), num(20), num(30)];
env.push_repeat(num(20), 2, 3, items);
assert_eq!(env.resolve_context("current", None, &[]), num(20));
assert_eq!(env.resolve_context("index", None, &[]), num(2));
assert_eq!(env.resolve_context("count", None, &[]), num(3));
assert_eq!(env.repeat_prev(), num(10));
assert_eq!(env.repeat_next(), num(30));
}
#[test]
fn test_nested_repeat_context() {
let mut env = FormspecEnvironment::new();
let outer = vec![s("A"), s("B")];
env.push_repeat(s("A"), 1, 2, outer);
let inner = vec![num(1), num(2), num(3)];
env.push_repeat(num(2), 2, 3, inner);
assert_eq!(env.resolve_context("current", None, &[]), num(2));
assert_eq!(env.repeat_parent(), s("A"));
env.pop_repeat();
assert_eq!(env.resolve_context("current", None, &[]), s("A"));
}
#[test]
fn test_named_instances() {
let mut env = FormspecEnvironment::new();
let config = TypeValue::Object(IndexMap::from([("maxRetries".to_string(), num(3))]));
env.set_instance("config", config);
assert_eq!(
env.resolve_context("instance", Some("config"), &["maxRetries".into()]),
num(3)
);
assert_eq!(
env.resolve_context("instance", Some("missing"), &[]),
TypeValue::Null
);
}
#[test]
fn test_variables() {
let mut env = FormspecEnvironment::new();
env.set_variable("total", num(100));
assert_eq!(env.resolve_context("total", None, &[]), num(100));
}
#[test]
fn test_mip_states() {
let mut env = FormspecEnvironment::new();
env.set_mip(
"email",
MipState {
valid: false,
relevant: true,
readonly: false,
required: true,
},
);
assert_eq!(env.mip_valid(&["email".into()]), TypeValue::Boolean(false));
assert_eq!(
env.mip_relevant(&["email".into()]),
TypeValue::Boolean(true)
);
assert_eq!(
env.mip_readonly(&["email".into()]),
TypeValue::Boolean(false)
);
assert_eq!(
env.mip_required(&["email".into()]),
TypeValue::Boolean(true)
);
assert_eq!(env.mip_valid(&["unknown".into()]), TypeValue::Boolean(true));
assert_eq!(
env.mip_required(&["unknown".into()]),
TypeValue::Boolean(false)
);
}
#[test]
fn test_bare_dollar_in_repeat() {
let mut env = FormspecEnvironment::new();
let items = vec![num(10), num(20)];
env.push_repeat(num(10), 1, 2, items);
assert_eq!(env.resolve_field(&[]), num(10));
}
}