temple_dsl/lib.rs
1//! Temple is a small language for shaping data: an input value goes in, a
2//! value of the shape you asked for comes out.
3//!
4//! ```text
5//! let total = input.items.map(i -> i.price * i.qty).sum()
6//!
7//! {
8//! "customer": {{ input.customer.name }},
9//! "total": {{ total }},
10//! "vip": {{ total > 1000 }}
11//! }
12//! ```
13//!
14//! # Rendering a template
15//!
16//! [`Template::compile`] parses and checks the source once; render it as
17//! many times as you like, into a [`Value`] or straight into your own type.
18//!
19//! ```
20//! use serde::Deserialize;
21//! use temple_dsl::{Template, Value};
22//!
23//! #[derive(Deserialize)]
24//! struct Greeting {
25//! text: String,
26//! }
27//!
28//! let template = Template::compile(r#"{ "text": {{ concat("hi ", input.name) }} }"#).unwrap();
29//! let greeting: Greeting = template.render(Value::obj([("name", "Ada")])).unwrap();
30//! assert_eq!(greeting.text, "hi Ada");
31//! ```
32//!
33//! # Embedding temple in another language
34//!
35//! A host parses one expression or value at a time inside its own syntax
36//! ([`ExprUnit::parse_at`], [`TemplateUnit::parse_at`]), checks it against
37//! the [`Names`] it will bind, and evaluates it with an [`Env`] under a
38//! [`Budget`].
39//!
40//! ```
41//! use temple_dsl::{Budget, Env, ExprUnit, Names, Value};
42//!
43//! let names = Names::new().var("limit");
44//! let unit = ExprUnit::compile("input.age >= limit", &names).unwrap();
45//! let env = Env::new().set("limit", 18);
46//! let out = unit
47//! .eval(&Value::obj([("age", Value::Int(21))]), &env, &Budget::new(1_000))
48//! .unwrap();
49//! assert_eq!(out, Value::Bool(true));
50//! ```
51
52#![forbid(unsafe_code)]
53#![warn(missing_docs)]
54
55mod check;
56mod common;
57mod embed;
58mod eval;
59mod syntax;
60mod template;
61
62pub use common::error::{CompileError, EvalError, LoadError, RenderError, Span};
63pub use common::value::Value;
64pub use embed::{
65 Env, ExprUnit, Functions, InputRead, Names, ParsedExpr, ParsedTemplate, TemplateUnit,
66};
67pub use eval::budget::Budget;
68pub use syntax::blob::BLOB_VERSION;
69pub use template::Template;
70
71/// This crate's version, for hosts that record it next to stored blobs.
72pub const VERSION: &str = env!("CARGO_PKG_VERSION");
73
74/// Whether `name` is reserved (`input`, `this`, `let`, …) and so can't name a
75/// variable or function.
76pub fn is_reserved_name(name: &str) -> bool {
77 check::is_reserved(name)
78}
79
80/// Whether `name` is a built-in function, and so can't name a host function.
81pub fn is_builtin_function(name: &str) -> bool {
82 eval::builtins::is_builtin_function(name)
83}