Add some helpful macros

This commit is contained in:
soup 2024-05-19 02:04:56 -04:00
parent 482f06ee25
commit 5278f3580c
No known key found for this signature in database

View file

@ -198,16 +198,38 @@ pub struct Newt {
ast: Ast,
}
impl Newt {
fn build(tmpl: &str) -> Self {
pub fn build(tmpl: &str) -> Self {
let ast = parse(tmpl);
Self { ast }
}
fn execute(&self, value: &dyn Value) -> String {
pub fn execute(&self, value: &dyn Value) -> String {
execute(&self.ast, value)
}
}
#[macro_export]
macro_rules! values_list_map {
($($key:literal: $val:expr),* $(,)?) => {{
&[
$(
($key, $val as &dyn Value)
)*,
]
}}
}
#[macro_export]
macro_rules! values {
($($val:expr),* $(,)?) => {{
&[
$(
&$val as &dyn Value,
)*
]
}}
}
#[cfg(test)]
mod test {
use crate::{Newt, Value};
@ -225,7 +247,9 @@ mod test {
fn print_lookup() {
go(
"Hello, {.name}!",
&[("name", &"Ted" as &dyn Value)],
values_list_map! {
"name": &"Ted",
},
"Hello, Ted!",
);
}
@ -234,7 +258,7 @@ mod test {
fn print_for() {
go(
"{for .}{.}, {/for}",
&[&"Bob" as &dyn Value, &"Larry"],
values!["Bob", "Larry"],
"Bob, Larry, ",
);
}
@ -243,15 +267,11 @@ mod test {
fn print_for_nested() {
go(
"{for .items}{for .names}{.}, {/for}{/for}",
&[(
"items",
&[
&[(
"names",
&[&"Bob" as &dyn Value, &"Larry"] as &dyn Value,
)] as &dyn Value,
] as &dyn Value,
)],
values_list_map! {
"items": values![values_list_map! {
"names": values!["Bob", "Larry"],
}]
},
"Bob, Larry, ",
)
}