temple-dsl 0.2.0

A small, fast Rust DSL for shaping data — input in, strongly-typed Rust value out.
Documentation
//! The tree-walking evaluator. This root holds the two dispatch entry points
//! (`evaluate` over output nodes, `evaluate_expr` over expressions) and the
//! shared `Scope`; the per-domain machinery lives in the submodules below.

use crate::error::RenderError;
use crate::parse::{Expr, ExprKind, InterpPart, OutKind, OutNode};
use crate::value::Value;
use indexmap::IndexMap;
use smol_str::SmolStr;
use std::collections::HashMap;

mod functions;
mod methods;
mod ops;
mod path;

pub use functions::is_known_function;

pub type Scope = HashMap<SmolStr, Value>;

pub fn evaluate(
    node: &OutNode,
    input: &Value,
    lets: &Scope,
    this: &Scope,
) -> Result<Value, RenderError> {
    match &node.kind {
        OutKind::Literal(lit) => Ok(lit.to_value()),
        OutKind::Hole(expr) => evaluate_expr(expr, input, lets, this),
        OutKind::Object(fields) => {
            let mut obj = IndexMap::with_capacity(fields.len());
            for (key, value_node) in fields {
                obj.insert(key.clone(), evaluate(value_node, input, lets, this)?);
            }
            Ok(Value::Obj(obj))
        }
        OutKind::Array(items) => {
            let mut arr = Vec::with_capacity(items.len());
            for item in items {
                arr.push(evaluate(item, input, lets, this)?);
            }
            Ok(Value::Arr(arr))
        }
        OutKind::Interp(parts) => {
            let mut s = String::new();
            for part in parts {
                match part {
                    InterpPart::Text(t) => s.push_str(t),
                    InterpPart::Hole(expr) => {
                        let v = evaluate_expr(expr, input, lets, this)?;
                        s.push_str(&functions::scalar_to_string(&v, expr.span)?);
                    }
                }
            }
            Ok(Value::Str(s.into()))
        }
    }
}

pub fn evaluate_expr(
    expr: &Expr,
    input: &Value,
    lets: &Scope,
    this: &Scope,
) -> Result<Value, RenderError> {
    match &expr.kind {
        ExprKind::Literal(lit) => Ok(lit.to_value()),
        ExprKind::Path {
            root,
            root_span,
            segments,
        } => path::evaluate_path(root, *root_span, segments, input, lets, this),
        ExprKind::Binary { op, lhs, rhs } => {
            ops::evaluate_binary(*op, lhs, rhs, expr.span, input, lets, this)
        }
        ExprKind::Unary { op, operand } => {
            ops::evaluate_unary(*op, operand, expr.span, input, lets, this)
        }
        ExprKind::Ternary {
            cond,
            then_branch,
            else_branch,
        } => {
            let c = evaluate_expr(cond, input, lets, this)?;
            let b = ops::require_bool(&c, cond.span)?;
            if b {
                evaluate_expr(then_branch, input, lets, this)
            } else {
                evaluate_expr(else_branch, input, lets, this)
            }
        }
        ExprKind::When { branches, fallback } => {
            for branch in branches {
                let c = evaluate_expr(&branch.cond, input, lets, this)?;
                let b = ops::require_bool(&c, branch.cond.span)?;
                if b {
                    return evaluate_expr(&branch.result, input, lets, this);
                }
            }
            match fallback {
                Some(fb) => evaluate_expr(fb, input, lets, this),
                None => Err(RenderError::WhenNoMatch { span: expr.span }),
            }
        }
        ExprKind::Lambda { .. } => Err(RenderError::TypeMismatch {
            expected: "value",
            got: "lambda (only valid as a method argument)".to_string(),
            span: expr.span,
        }),
        ExprKind::ArrayLit(items) => {
            let mut out = Vec::with_capacity(items.len());
            for item in items {
                out.push(evaluate_expr(item, input, lets, this)?);
            }
            Ok(Value::Arr(out))
        }
        ExprKind::ObjectLit(entries) => {
            let mut obj = IndexMap::with_capacity(entries.len());
            for (k, e) in entries {
                obj.insert(k.clone(), evaluate_expr(e, input, lets, this)?);
            }
            Ok(Value::Obj(obj))
        }
        ExprKind::FuncCall {
            name,
            name_span,
            args,
        } => {
            let mut values = Vec::with_capacity(args.len());
            for a in args {
                values.push(evaluate_expr(a, input, lets, this)?);
            }
            functions::call_func(name, &values, *name_span)
        }
    }
}