From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- vendor/handlebars/src/block.rs | 126 +++ vendor/handlebars/src/cli.rs | 51 + vendor/handlebars/src/context.rs | 453 +++++++++ vendor/handlebars/src/decorators/inline.rs | 64 ++ vendor/handlebars/src/decorators/mod.rs | 300 ++++++ vendor/handlebars/src/error.rs | 272 +++++ vendor/handlebars/src/grammar.pest | 127 +++ vendor/handlebars/src/grammar.rs | 372 +++++++ vendor/handlebars/src/helpers/block_util.rs | 17 + vendor/handlebars/src/helpers/helper_each.rs | 593 +++++++++++ vendor/handlebars/src/helpers/helper_extras.rs | 112 +++ vendor/handlebars/src/helpers/helper_if.rs | 151 +++ vendor/handlebars/src/helpers/helper_log.rs | 72 ++ vendor/handlebars/src/helpers/helper_lookup.rs | 104 ++ vendor/handlebars/src/helpers/helper_raw.rs | 44 + vendor/handlebars/src/helpers/helper_with.rs | 276 ++++++ vendor/handlebars/src/helpers/mod.rs | 291 ++++++ vendor/handlebars/src/helpers/scripting.rs | 111 +++ vendor/handlebars/src/json/mod.rs | 2 + vendor/handlebars/src/json/path.rs | 138 +++ vendor/handlebars/src/json/value.rs | 202 ++++ vendor/handlebars/src/lib.rs | 417 ++++++++ vendor/handlebars/src/local_vars.rs | 37 + vendor/handlebars/src/macros.rs | 185 ++++ vendor/handlebars/src/output.rs | 48 + vendor/handlebars/src/partial.rs | 333 +++++++ vendor/handlebars/src/registry.rs | 1092 +++++++++++++++++++++ vendor/handlebars/src/render.rs | 1119 +++++++++++++++++++++ vendor/handlebars/src/sources.rs | 34 + vendor/handlebars/src/support.rs | 76 ++ vendor/handlebars/src/template.rs | 1254 ++++++++++++++++++++++++ vendor/handlebars/src/util.rs | 25 + 32 files changed, 8498 insertions(+) create mode 100644 vendor/handlebars/src/block.rs create mode 100644 vendor/handlebars/src/cli.rs create mode 100644 vendor/handlebars/src/context.rs create mode 100644 vendor/handlebars/src/decorators/inline.rs create mode 100644 vendor/handlebars/src/decorators/mod.rs create mode 100644 vendor/handlebars/src/error.rs create mode 100644 vendor/handlebars/src/grammar.pest create mode 100644 vendor/handlebars/src/grammar.rs create mode 100644 vendor/handlebars/src/helpers/block_util.rs create mode 100644 vendor/handlebars/src/helpers/helper_each.rs create mode 100644 vendor/handlebars/src/helpers/helper_extras.rs create mode 100644 vendor/handlebars/src/helpers/helper_if.rs create mode 100644 vendor/handlebars/src/helpers/helper_log.rs create mode 100644 vendor/handlebars/src/helpers/helper_lookup.rs create mode 100644 vendor/handlebars/src/helpers/helper_raw.rs create mode 100644 vendor/handlebars/src/helpers/helper_with.rs create mode 100644 vendor/handlebars/src/helpers/mod.rs create mode 100644 vendor/handlebars/src/helpers/scripting.rs create mode 100644 vendor/handlebars/src/json/mod.rs create mode 100644 vendor/handlebars/src/json/path.rs create mode 100644 vendor/handlebars/src/json/value.rs create mode 100644 vendor/handlebars/src/lib.rs create mode 100644 vendor/handlebars/src/local_vars.rs create mode 100644 vendor/handlebars/src/macros.rs create mode 100644 vendor/handlebars/src/output.rs create mode 100644 vendor/handlebars/src/partial.rs create mode 100644 vendor/handlebars/src/registry.rs create mode 100644 vendor/handlebars/src/render.rs create mode 100644 vendor/handlebars/src/sources.rs create mode 100644 vendor/handlebars/src/support.rs create mode 100644 vendor/handlebars/src/template.rs create mode 100644 vendor/handlebars/src/util.rs (limited to 'vendor/handlebars/src') diff --git a/vendor/handlebars/src/block.rs b/vendor/handlebars/src/block.rs new file mode 100644 index 000000000..1c520bf5b --- /dev/null +++ b/vendor/handlebars/src/block.rs @@ -0,0 +1,126 @@ +use std::collections::BTreeMap; + +use serde_json::value::Value as Json; + +use crate::error::RenderError; +use crate::local_vars::LocalVars; + +#[derive(Clone, Debug)] +pub enum BlockParamHolder { + // a reference to certain context value + Path(Vec), + // an actual value holder + Value(Json), +} + +impl BlockParamHolder { + pub fn value(v: Json) -> BlockParamHolder { + BlockParamHolder::Value(v) + } + + pub fn path(r: Vec) -> BlockParamHolder { + BlockParamHolder::Path(r) + } +} + +/// A map holds block parameters. The parameter can be either a value or a reference +#[derive(Clone, Debug, Default)] +pub struct BlockParams<'reg> { + data: BTreeMap<&'reg str, BlockParamHolder>, +} + +impl<'reg> BlockParams<'reg> { + /// Create a empty block parameter map. + pub fn new() -> BlockParams<'reg> { + BlockParams::default() + } + + /// Add a path reference as the parameter. The `path` is a vector of path + /// segments the relative to current block's base path. + pub fn add_path(&mut self, k: &'reg str, path: Vec) -> Result<(), RenderError> { + self.data.insert(k, BlockParamHolder::path(path)); + Ok(()) + } + + /// Add a value as parameter. + pub fn add_value(&mut self, k: &'reg str, v: Json) -> Result<(), RenderError> { + self.data.insert(k, BlockParamHolder::value(v)); + Ok(()) + } + + /// Get a block parameter by its name. + pub fn get(&self, k: &str) -> Option<&BlockParamHolder> { + self.data.get(k) + } +} + +/// A data structure holds contextual data for current block scope. +#[derive(Debug, Clone, Default)] +pub struct BlockContext<'reg> { + /// the base_path of current block scope + base_path: Vec, + /// the base_value of current block scope, when the block is using a + /// constant or derived value as block base + base_value: Option, + /// current block context variables + block_params: BlockParams<'reg>, + /// local variables in current context + local_variables: LocalVars, +} + +impl<'reg> BlockContext<'reg> { + /// create a new `BlockContext` with default data + pub fn new() -> BlockContext<'reg> { + BlockContext::default() + } + + /// set a local variable into current scope + pub fn set_local_var(&mut self, name: &str, value: Json) { + self.local_variables.put(name, value); + } + + /// get a local variable from current scope + pub fn get_local_var(&self, name: &str) -> Option<&Json> { + self.local_variables.get(name) + } + + /// borrow a reference to current scope's base path + /// all paths inside this block will be relative to this path + pub fn base_path(&self) -> &Vec { + &self.base_path + } + + /// borrow a mutable reference to the base path + pub fn base_path_mut(&mut self) -> &mut Vec { + &mut self.base_path + } + + /// borrow the base value + pub fn base_value(&self) -> Option<&Json> { + self.base_value.as_ref() + } + + /// set the base value + pub fn set_base_value(&mut self, value: Json) { + self.base_value = Some(value); + } + + /// Get a block parameter from this block. + /// Block parameters needed to be supported by the block helper. + /// The typical syntax for block parameter is: + /// + /// ```skip + /// {{#myblock param1 as |block_param1|}} + /// ... + /// {{/myblock}} + /// ``` + /// + pub fn get_block_param(&self, block_param_name: &str) -> Option<&BlockParamHolder> { + self.block_params.get(block_param_name) + } + + /// Set a block parameter into this block. + pub fn set_block_params(&mut self, block_params: BlockParams<'reg>) { + self.block_params = block_params; + } +} diff --git a/vendor/handlebars/src/cli.rs b/vendor/handlebars/src/cli.rs new file mode 100644 index 000000000..571900da2 --- /dev/null +++ b/vendor/handlebars/src/cli.rs @@ -0,0 +1,51 @@ +use std::env; +use std::fs; +use std::process; +use std::str::FromStr; + +use serde_json::value::Value as Json; + +use handlebars::Handlebars; + +fn usage() -> ! { + eprintln!("Usage: handlebars-cli template.hbs '{{\"json\": \"data\"}}'"); + process::exit(1); +} + +fn parse_json(text: &str) -> Json { + let result = if let Some(text) = text.strip_prefix('@') { + fs::read_to_string(text).unwrap() + } else { + text.to_owned() + }; + match Json::from_str(&result) { + Ok(json) => json, + Err(_) => usage(), + } +} + +fn main() { + let mut args = env::args(); + args.next(); // skip own filename + let (filename, json) = match (args.next(), args.next()) { + (Some(filename), Some(json)) => (filename, json), + _ => usage(), + }; + let data = parse_json(&json); + + let mut handlebars = Handlebars::new(); + + handlebars + .register_template_file(&filename, &filename) + .ok() + .unwrap(); + match handlebars.render(&filename, &data) { + Ok(data) => { + println!("{}", data); + } + Err(e) => { + println!("Error rendering {}: {}", filename, e); + process::exit(2); + } + } +} diff --git a/vendor/handlebars/src/context.rs b/vendor/handlebars/src/context.rs new file mode 100644 index 000000000..10e15fd90 --- /dev/null +++ b/vendor/handlebars/src/context.rs @@ -0,0 +1,453 @@ +use std::collections::{HashMap, VecDeque}; + +use serde::Serialize; +use serde_json::value::{to_value, Map, Value as Json}; + +use crate::block::{BlockContext, BlockParamHolder}; +use crate::error::RenderError; +use crate::grammar::Rule; +use crate::json::path::*; +use crate::json::value::ScopedJson; +use crate::util::extend; + +pub type Object = HashMap; + +/// The context wrap data you render on your templates. +/// +#[derive(Debug, Clone)] +pub struct Context { + data: Json, +} + +#[derive(Debug)] +enum ResolvedPath<'a> { + // FIXME: change to borrowed when possible + // full path + AbsolutePath(Vec), + // relative path and path root + RelativePath(Vec), + // relative path against block param value + BlockParamValue(Vec, &'a Json), + // relative path against derived value, + LocalValue(Vec, &'a Json), +} + +fn parse_json_visitor<'a, 'reg>( + relative_path: &[PathSeg], + block_contexts: &'a VecDeque>, + always_for_absolute_path: bool, +) -> ResolvedPath<'a> { + let mut path_context_depth: i64 = 0; + let mut with_block_param = None; + let mut from_root = false; + + // peek relative_path for block param, @root and "../../" + for path_seg in relative_path { + match path_seg { + PathSeg::Named(the_path) => { + if let Some((holder, base_path)) = get_in_block_params(&block_contexts, the_path) { + with_block_param = Some((holder, base_path)); + } + break; + } + PathSeg::Ruled(the_rule) => match the_rule { + Rule::path_root => { + from_root = true; + break; + } + Rule::path_up => path_context_depth += 1, + _ => break, + }, + } + } + + let mut path_stack = Vec::with_capacity(relative_path.len() + 5); + match with_block_param { + Some((BlockParamHolder::Value(ref value), _)) => { + merge_json_path(&mut path_stack, &relative_path[1..]); + ResolvedPath::BlockParamValue(path_stack, value) + } + Some((BlockParamHolder::Path(ref paths), base_path)) => { + extend(&mut path_stack, base_path); + if !paths.is_empty() { + extend(&mut path_stack, paths); + } + merge_json_path(&mut path_stack, &relative_path[1..]); + + ResolvedPath::AbsolutePath(path_stack) + } + None => { + if path_context_depth > 0 { + let blk = block_contexts + .get(path_context_depth as usize) + .or_else(|| block_contexts.front()); + + if let Some(base_value) = blk.and_then(|blk| blk.base_value()) { + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::LocalValue(path_stack, base_value) + } else { + if let Some(base_path) = blk.map(|blk| blk.base_path()) { + extend(&mut path_stack, base_path); + } + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::AbsolutePath(path_stack) + } + } else if from_root { + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::AbsolutePath(path_stack) + } else if always_for_absolute_path { + if let Some(base_value) = block_contexts.front().and_then(|blk| blk.base_value()) { + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::LocalValue(path_stack, base_value) + } else { + if let Some(base_path) = block_contexts.front().map(|blk| blk.base_path()) { + extend(&mut path_stack, base_path); + } + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::AbsolutePath(path_stack) + } + } else { + merge_json_path(&mut path_stack, relative_path); + ResolvedPath::RelativePath(path_stack) + } + } + } +} + +fn get_data<'a>(d: Option<&'a Json>, p: &str) -> Result, RenderError> { + let result = match d { + Some(&Json::Array(ref l)) => p.parse::().map(|idx_u| l.get(idx_u))?, + Some(&Json::Object(ref m)) => m.get(p), + Some(_) => None, + None => None, + }; + Ok(result) +} + +fn get_in_block_params<'a, 'reg>( + block_contexts: &'a VecDeque>, + p: &str, +) -> Option<(&'a BlockParamHolder, &'a Vec)> { + for bc in block_contexts { + let v = bc.get_block_param(p); + if v.is_some() { + return v.map(|v| (v, bc.base_path())); + } + } + + None +} + +pub(crate) fn merge_json(base: &Json, addition: &HashMap<&str, &Json>) -> Json { + let mut base_map = match base { + Json::Object(ref m) => m.clone(), + _ => Map::new(), + }; + + for (k, v) in addition.iter() { + base_map.insert(k.to_string(), (*v).clone()); + } + + Json::Object(base_map) +} + +impl Context { + /// Create a context with null data + pub fn null() -> Context { + Context { data: Json::Null } + } + + /// Create a context with given data + pub fn wraps(e: T) -> Result { + to_value(e) + .map_err(RenderError::from) + .map(|d| Context { data: d }) + } + + /// Navigate the context with relative path and block scopes + pub(crate) fn navigate<'reg, 'rc>( + &'rc self, + relative_path: &[PathSeg], + block_contexts: &VecDeque>, + ) -> Result, RenderError> { + // always use absolute at the moment until we get base_value lifetime issue fixed + let resolved_visitor = parse_json_visitor(&relative_path, block_contexts, true); + + // debug logging + debug!("Accessing context value: {:?}", resolved_visitor); + + match resolved_visitor { + ResolvedPath::AbsolutePath(paths) => { + let mut ptr = Some(self.data()); + for p in paths.iter() { + ptr = get_data(ptr, p)?; + } + + Ok(ptr + .map(|v| ScopedJson::Context(v, paths)) + .unwrap_or_else(|| ScopedJson::Missing)) + } + ResolvedPath::RelativePath(_paths) => { + // relative path is disabled for now + unreachable!() + // let mut ptr = block_contexts.front().and_then(|blk| blk.base_value()); + // for p in paths.iter() { + // ptr = get_data(ptr, p)?; + // } + + // Ok(ptr + // .map(|v| ScopedJson::Context(v, paths)) + // .unwrap_or_else(|| ScopedJson::Missing)) + } + ResolvedPath::BlockParamValue(paths, value) + | ResolvedPath::LocalValue(paths, value) => { + let mut ptr = Some(value); + for p in paths.iter() { + ptr = get_data(ptr, p)?; + } + Ok(ptr + .map(|v| ScopedJson::Derived(v.clone())) + .unwrap_or_else(|| ScopedJson::Missing)) + } + } + } + + /// Return the Json data wrapped in context + pub fn data(&self) -> &Json { + &self.data + } + + /// Return the mutable reference to Json data wrapped in context + pub fn data_mut(&mut self) -> &mut Json { + &mut self.data + } +} + +#[cfg(test)] +mod test { + use crate::block::{BlockContext, BlockParams}; + use crate::context::{self, Context}; + use crate::error::RenderError; + use crate::json::path::Path; + use crate::json::value::{self, ScopedJson}; + use serde_json::value::Map; + use std::collections::{HashMap, VecDeque}; + + fn navigate_from_root<'reg, 'rc>( + ctx: &'rc Context, + path: &str, + ) -> Result, RenderError> { + let relative_path = Path::parse(path).unwrap(); + ctx.navigate(relative_path.segs().unwrap(), &VecDeque::new()) + } + + #[derive(Serialize)] + struct Address { + city: String, + country: String, + } + + #[derive(Serialize)] + struct Person { + name: String, + age: i16, + addr: Address, + titles: Vec, + } + + #[test] + fn test_render() { + let v = "hello"; + let ctx = Context::wraps(&v.to_string()).unwrap(); + assert_eq!( + navigate_from_root(&ctx, "this").unwrap().render(), + v.to_string() + ); + } + + #[test] + fn test_navigation() { + let addr = Address { + city: "Beijing".to_string(), + country: "China".to_string(), + }; + + let person = Person { + name: "Ning Sun".to_string(), + age: 27, + addr, + titles: vec!["programmer".to_string(), "cartographer".to_string()], + }; + + let ctx = Context::wraps(&person).unwrap(); + assert_eq!( + navigate_from_root(&ctx, "./addr/country").unwrap().render(), + "China".to_string() + ); + assert_eq!( + navigate_from_root(&ctx, "addr.[country]").unwrap().render(), + "China".to_string() + ); + + let v = true; + let ctx2 = Context::wraps(&v).unwrap(); + assert_eq!( + navigate_from_root(&ctx2, "this").unwrap().render(), + "true".to_string() + ); + + assert_eq!( + navigate_from_root(&ctx, "titles.[0]").unwrap().render(), + "programmer".to_string() + ); + + assert_eq!( + navigate_from_root(&ctx, "age").unwrap().render(), + "27".to_string() + ); + } + + #[test] + fn test_this() { + let mut map_with_this = Map::new(); + map_with_this.insert("this".to_string(), value::to_json("hello")); + map_with_this.insert("age".to_string(), value::to_json(5usize)); + let ctx1 = Context::wraps(&map_with_this).unwrap(); + + let mut map_without_this = Map::new(); + map_without_this.insert("age".to_string(), value::to_json(4usize)); + let ctx2 = Context::wraps(&map_without_this).unwrap(); + + assert_eq!( + navigate_from_root(&ctx1, "this").unwrap().render(), + "[object]".to_owned() + ); + assert_eq!( + navigate_from_root(&ctx2, "age").unwrap().render(), + "4".to_owned() + ); + } + + #[test] + fn test_merge_json() { + let map = json!({ "age": 4 }); + let s = "hello".to_owned(); + let mut hash = HashMap::new(); + let v = value::to_json("h1"); + hash.insert("tag", &v); + + let ctx_a1 = Context::wraps(&context::merge_json(&map, &hash)).unwrap(); + assert_eq!( + navigate_from_root(&ctx_a1, "age").unwrap().render(), + "4".to_owned() + ); + assert_eq!( + navigate_from_root(&ctx_a1, "tag").unwrap().render(), + "h1".to_owned() + ); + + let ctx_a2 = Context::wraps(&context::merge_json(&value::to_json(s), &hash)).unwrap(); + assert_eq!( + navigate_from_root(&ctx_a2, "this").unwrap().render(), + "[object]".to_owned() + ); + assert_eq!( + navigate_from_root(&ctx_a2, "tag").unwrap().render(), + "h1".to_owned() + ); + } + + #[test] + fn test_key_name_with_this() { + let m = btreemap! { + "this_name".to_string() => "the_value".to_string() + }; + let ctx = Context::wraps(&m).unwrap(); + assert_eq!( + navigate_from_root(&ctx, "this_name").unwrap().render(), + "the_value".to_string() + ); + } + + use serde::ser::Error as SerdeError; + use serde::{Serialize, Serializer}; + + struct UnserializableType {} + + impl Serialize for UnserializableType { + fn serialize(&self, _: S) -> Result + where + S: Serializer, + { + Err(SerdeError::custom("test")) + } + } + + #[test] + fn test_serialize_error() { + let d = UnserializableType {}; + assert!(Context::wraps(&d).is_err()); + } + + #[test] + fn test_root() { + let m = json!({ + "a" : { + "b" : { + "c" : { + "d" : 1 + } + } + }, + "b": 2 + }); + let ctx = Context::wraps(&m).unwrap(); + let mut block = BlockContext::new(); + *block.base_path_mut() = ["a".to_owned(), "b".to_owned()].to_vec(); + + let mut blocks = VecDeque::new(); + blocks.push_front(block); + + assert_eq!( + ctx.navigate(&Path::parse("@root/b").unwrap().segs().unwrap(), &blocks) + .unwrap() + .render(), + "2".to_string() + ); + } + + #[test] + fn test_block_params() { + let m = json!([{ + "a": [1, 2] + }, { + "b": [2, 3] + }]); + + let ctx = Context::wraps(&m).unwrap(); + let mut block_params = BlockParams::new(); + block_params + .add_path("z", ["0".to_owned(), "a".to_owned()].to_vec()) + .unwrap(); + block_params.add_value("t", json!("good")).unwrap(); + + let mut block = BlockContext::new(); + block.set_block_params(block_params); + + let mut blocks = VecDeque::new(); + blocks.push_front(block); + + assert_eq!( + ctx.navigate(&Path::parse("z.[1]").unwrap().segs().unwrap(), &blocks) + .unwrap() + .render(), + "2".to_string() + ); + assert_eq!( + ctx.navigate(&Path::parse("t").unwrap().segs().unwrap(), &blocks) + .unwrap() + .render(), + "good".to_string() + ); + } +} diff --git a/vendor/handlebars/src/decorators/inline.rs b/vendor/handlebars/src/decorators/inline.rs new file mode 100644 index 000000000..373abbc7b --- /dev/null +++ b/vendor/handlebars/src/decorators/inline.rs @@ -0,0 +1,64 @@ +use crate::context::Context; +use crate::decorators::{DecoratorDef, DecoratorResult}; +use crate::error::RenderError; +use crate::registry::Registry; +use crate::render::{Decorator, RenderContext}; + +#[derive(Clone, Copy)] +pub struct InlineDecorator; + +fn get_name<'reg: 'rc, 'rc>(d: &Decorator<'reg, 'rc>) -> Result { + d.param(0) + .ok_or_else(|| RenderError::new("Param required for decorator \"inline\"")) + .and_then(|v| { + v.value() + .as_str() + .map(|v| v.to_owned()) + .ok_or_else(|| RenderError::new("inline name must be string")) + }) +} + +impl DecoratorDef for InlineDecorator { + fn call<'reg: 'rc, 'rc>( + &self, + d: &Decorator<'reg, 'rc>, + _: &'reg Registry<'reg>, + _: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> DecoratorResult { + let name = get_name(d)?; + + let template = d + .template() + .ok_or_else(|| RenderError::new("inline should have a block"))?; + + rc.set_partial(name, template); + Ok(()) + } +} + +pub static INLINE_DECORATOR: InlineDecorator = InlineDecorator; + +#[cfg(test)] +mod test { + use crate::context::Context; + use crate::registry::Registry; + use crate::render::{Evaluable, RenderContext}; + use crate::template::Template; + + #[test] + fn test_inline() { + let t0 = + Template::compile("{{#*inline \"hello\"}}the hello world inline partial.{{/inline}}") + .ok() + .unwrap(); + + let hbs = Registry::new(); + + let ctx = Context::null(); + let mut rc = RenderContext::new(None); + t0.elements[0].eval(&hbs, &ctx, &mut rc).unwrap(); + + assert!(rc.get_partial(&"hello".to_owned()).is_some()); + } +} diff --git a/vendor/handlebars/src/decorators/mod.rs b/vendor/handlebars/src/decorators/mod.rs new file mode 100644 index 000000000..b8bad900f --- /dev/null +++ b/vendor/handlebars/src/decorators/mod.rs @@ -0,0 +1,300 @@ +use crate::context::Context; +use crate::error::RenderError; +use crate::registry::Registry; +use crate::render::{Decorator, RenderContext}; + +pub use self::inline::INLINE_DECORATOR; + +pub type DecoratorResult = Result<(), RenderError>; + +/// Decorator Definition +/// +/// Implement this trait to define your own decorators. Currently decorator +/// shares same definition with helper. +/// +/// In handlebars, it is recommended to use decorator to change context data and update helper +/// definition. +/// ## Updating context data +/// +/// In decorator, you can change some context data you are about to render. +/// +/// ``` +/// use handlebars::*; +/// +/// fn update_data<'reg: 'rc, 'rc>(_: &Decorator, _: &Handlebars, ctx: &Context, rc: &mut RenderContext) +/// -> Result<(), RenderError> { +/// // modify json object +/// let mut new_ctx = ctx.clone(); +/// { +/// let mut data = new_ctx.data_mut(); +/// if let Some(ref mut m) = data.as_object_mut() { +/// m.insert("hello".to_string(), to_json("world")); +/// } +/// } +/// rc.set_context(new_ctx); +/// Ok(()) +/// } +/// +/// ``` +/// +/// ## Define local helper +/// +/// You can override behavior of a helper from position of decorator to the end of template. +/// +/// ``` +/// use handlebars::*; +/// +/// fn override_helper(_: &Decorator, _: &Handlebars, _: &Context, rc: &mut RenderContext) +/// -> Result<(), RenderError> { +/// let new_helper = |h: &Helper, _: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output| +/// -> Result<(), RenderError> { +/// // your helper logic +/// Ok(()) +/// }; +/// rc.register_local_helper("distance", Box::new(new_helper)); +/// Ok(()) +/// } +/// ``` +/// +pub trait DecoratorDef { + fn call<'reg: 'rc, 'rc>( + &'reg self, + d: &Decorator<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> DecoratorResult; +} + +/// Implement DecoratorDef for bare function so we can use function as decorator +impl< + F: for<'reg, 'rc> Fn( + &Decorator<'reg, 'rc>, + &'reg Registry<'reg>, + &'rc Context, + &mut RenderContext<'reg, 'rc>, + ) -> DecoratorResult, + > DecoratorDef for F +{ + fn call<'reg: 'rc, 'rc>( + &'reg self, + d: &Decorator<'reg, 'rc>, + reg: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> DecoratorResult { + (*self)(d, reg, ctx, rc) + } +} + +mod inline; + +#[cfg(test)] +mod test { + use crate::context::Context; + use crate::error::RenderError; + use crate::json::value::{as_string, to_json}; + use crate::output::Output; + use crate::registry::Registry; + use crate::render::{Decorator, Helper, RenderContext}; + + #[test] + fn test_register_decorator() { + let mut handlebars = Registry::new(); + handlebars + .register_template_string("t0", "{{*foo}}".to_string()) + .unwrap(); + + let data = btreemap! { + "hello".to_string() => "world".to_string() + }; + + assert!(handlebars.render("t0", &data).is_err()); + + handlebars.register_decorator( + "foo", + Box::new( + |_: &Decorator<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>| + -> Result<(), RenderError> { Ok(()) }, + ), + ); + assert_eq!(handlebars.render("t0", &data).ok().unwrap(), "".to_string()); + } + + // updating context data disabled for now + #[test] + fn test_update_data_with_decorator() { + let mut handlebars = Registry::new(); + handlebars + .register_template_string("t0", "{{hello}}{{*foo}}{{hello}}".to_string()) + .unwrap(); + + let data = btreemap! { + "hello".to_string() => "world".to_string() + }; + + handlebars.register_decorator( + "foo", + Box::new( + |_: &Decorator<'_, '_>, + _: &Registry<'_>, + ctx: &Context, + rc: &mut RenderContext<'_, '_>| + -> Result<(), RenderError> { + // modify json object + let mut new_ctx = ctx.clone(); + { + let data = new_ctx.data_mut(); + if let Some(ref mut m) = data.as_object_mut().as_mut() { + m.insert("hello".to_string(), to_json("war")); + } + } + rc.set_context(new_ctx); + Ok(()) + }, + ), + ); + + assert_eq!( + handlebars.render("t0", &data).ok().unwrap(), + "worldwar".to_string() + ); + + let data2 = 0; + handlebars.register_decorator( + "bar", + Box::new( + |d: &Decorator<'_, '_>, + _: &Registry<'_>, + _: &Context, + rc: &mut RenderContext<'_, '_>| + -> Result<(), RenderError> { + // modify value + let v = d + .param(0) + .and_then(|v| Context::wraps(v.value()).ok()) + .unwrap_or(Context::null()); + rc.set_context(v); + Ok(()) + }, + ), + ); + handlebars + .register_template_string("t1", "{{this}}{{*bar 1}}{{this}}".to_string()) + .unwrap(); + assert_eq!( + handlebars.render("t1", &data2).ok().unwrap(), + "01".to_string() + ); + + handlebars + .register_template_string( + "t2", + "{{this}}{{*bar \"string_literal\"}}{{this}}".to_string(), + ) + .unwrap(); + assert_eq!( + handlebars.render("t2", &data2).ok().unwrap(), + "0string_literal".to_string() + ); + + handlebars + .register_template_string("t3", "{{this}}{{*bar}}{{this}}".to_string()) + .unwrap(); + assert_eq!( + handlebars.render("t3", &data2).ok().unwrap(), + "0".to_string() + ); + } + + #[test] + fn test_local_helper_with_decorator() { + let mut handlebars = Registry::new(); + handlebars + .register_template_string( + "t0", + "{{distance 4.5}},{{*foo \"miles\"}}{{distance 10.1}},{{*bar}}{{distance 3.4}}" + .to_string(), + ) + .unwrap(); + + handlebars.register_helper( + "distance", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + let s = format!( + "{}m", + h.param(0) + .as_ref() + .map(|v| v.value()) + .unwrap_or(&to_json(0)) + ); + out.write(s.as_ref())?; + Ok(()) + }, + ), + ); + handlebars.register_decorator( + "foo", + Box::new( + |d: &Decorator<'_, '_>, + _: &Registry<'_>, + _: &Context, + rc: &mut RenderContext<'_, '_>| + -> Result<(), RenderError> { + let new_unit = d + .param(0) + .as_ref() + .and_then(|v| as_string(v.value())) + .unwrap_or("") + .to_owned(); + let new_helper = move |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + let s = format!( + "{}{}", + h.param(0) + .as_ref() + .map(|v| v.value()) + .unwrap_or(&to_json(0)), + new_unit + ); + out.write(s.as_ref())?; + Ok(()) + }; + + rc.register_local_helper("distance", Box::new(new_helper)); + Ok(()) + }, + ), + ); + handlebars.register_decorator( + "bar", + Box::new( + |_: &Decorator<'_, '_>, + _: &Registry<'_>, + _: &Context, + rc: &mut RenderContext<'_, '_>| + -> Result<(), RenderError> { + rc.unregister_local_helper("distance"); + Ok(()) + }, + ), + ); + assert_eq!( + handlebars.render("t0", &0).ok().unwrap(), + "4.5m,10.1miles,3.4m".to_owned() + ); + } +} diff --git a/vendor/handlebars/src/error.rs b/vendor/handlebars/src/error.rs new file mode 100644 index 000000000..f4721623f --- /dev/null +++ b/vendor/handlebars/src/error.rs @@ -0,0 +1,272 @@ +use std::error::Error; +use std::fmt; +use std::io::Error as IOError; +use std::num::ParseIntError; +use std::string::FromUtf8Error; + +use serde_json::error::Error as SerdeError; +#[cfg(feature = "dir_source")] +use walkdir::Error as WalkdirError; + +#[cfg(feature = "script_helper")] +use rhai::{EvalAltResult, ParseError}; + +/// Error when rendering data on template. +#[derive(Debug, Default)] +pub struct RenderError { + pub desc: String, + pub template_name: Option, + pub line_no: Option, + pub column_no: Option, + cause: Option>, + unimplemented: bool, +} + +impl fmt::Display for RenderError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match (self.line_no, self.column_no) { + (Some(line), Some(col)) => write!( + f, + "Error rendering \"{}\" line {}, col {}: {}", + self.template_name.as_deref().unwrap_or("Unnamed template"), + line, + col, + self.desc + ), + _ => write!(f, "{}", self.desc), + } + } +} + +impl Error for RenderError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.cause + .as_ref() + .map(|e| e.as_ref() as &(dyn Error + 'static)) + } +} + +impl From for RenderError { + fn from(e: IOError) -> RenderError { + RenderError::from_error("Cannot generate output.", e) + } +} + +impl From for RenderError { + fn from(e: SerdeError) -> RenderError { + RenderError::from_error("Failed to access JSON data.", e) + } +} + +impl From for RenderError { + fn from(e: FromUtf8Error) -> RenderError { + RenderError::from_error("Failed to generate bytes.", e) + } +} + +impl From for RenderError { + fn from(e: ParseIntError) -> RenderError { + RenderError::from_error("Cannot access array/vector with string index.", e) + } +} + +impl From for RenderError { + fn from(e: TemplateError) -> RenderError { + RenderError::from_error("Failed to parse template.", e) + } +} + +#[cfg(feature = "script_helper")] +impl From> for RenderError { + fn from(e: Box) -> RenderError { + RenderError::from_error("Cannot convert data to Rhai dynamic", e) + } +} + +#[cfg(feature = "script_helper")] +impl From for RenderError { + fn from(e: ScriptError) -> RenderError { + RenderError::from_error("Failed to load rhai script", e) + } +} + +impl RenderError { + pub fn new>(desc: T) -> RenderError { + RenderError { + desc: desc.as_ref().to_owned(), + ..Default::default() + } + } + + pub(crate) fn unimplemented() -> RenderError { + RenderError { + unimplemented: true, + ..Default::default() + } + } + + pub fn strict_error(path: Option<&String>) -> RenderError { + let msg = match path { + Some(path) => format!("Variable {:?} not found in strict mode.", path), + None => "Value is missing in strict mode".to_owned(), + }; + RenderError::new(&msg) + } + + pub fn from_error(error_info: &str, cause: E) -> RenderError + where + E: Error + Send + Sync + 'static, + { + let mut e = RenderError::new(error_info); + e.cause = Some(Box::new(cause)); + + e + } + + #[inline] + pub(crate) fn is_unimplemented(&self) -> bool { + self.unimplemented + } +} + +quick_error! { +/// Template parsing error + #[derive(Debug)] + pub enum TemplateErrorReason { + MismatchingClosedHelper(open: String, closed: String) { + display("helper {:?} was opened, but {:?} is closing", + open, closed) + } + MismatchingClosedDecorator(open: String, closed: String) { + display("decorator {:?} was opened, but {:?} is closing", + open, closed) + } + InvalidSyntax { + display("invalid handlebars syntax.") + } + InvalidParam (param: String) { + display("invalid parameter {:?}", param) + } + NestedSubexpression { + display("nested subexpression is not supported") + } + IoError(err: IOError, name: String) { + display("Template \"{}\": {}", name, err) + } + #[cfg(feature = "dir_source")] + WalkdirError(err: WalkdirError) { + display("Walk dir error: {}", err) + } + } +} + +/// Error on parsing template. +#[derive(Debug)] +pub struct TemplateError { + pub reason: TemplateErrorReason, + pub template_name: Option, + pub line_no: Option, + pub column_no: Option, + segment: Option, +} + +impl TemplateError { + pub fn of(e: TemplateErrorReason) -> TemplateError { + TemplateError { + reason: e, + template_name: None, + line_no: None, + column_no: None, + segment: None, + } + } + + pub fn at(mut self, template_str: &str, line_no: usize, column_no: usize) -> TemplateError { + self.line_no = Some(line_no); + self.column_no = Some(column_no); + self.segment = Some(template_segment(template_str, line_no, column_no)); + self + } + + pub fn in_template(mut self, name: String) -> TemplateError { + self.template_name = Some(name); + self + } +} + +impl Error for TemplateError {} + +impl From<(IOError, String)> for TemplateError { + fn from(err_info: (IOError, String)) -> TemplateError { + let (e, name) = err_info; + TemplateError::of(TemplateErrorReason::IoError(e, name)) + } +} + +#[cfg(feature = "dir_source")] +impl From for TemplateError { + fn from(e: WalkdirError) -> TemplateError { + TemplateError::of(TemplateErrorReason::WalkdirError(e)) + } +} + +fn template_segment(template_str: &str, line: usize, col: usize) -> String { + let range = 3; + let line_start = if line >= range { line - range } else { 0 }; + let line_end = line + range; + + let mut buf = String::new(); + for (line_count, line_content) in template_str.lines().enumerate() { + if line_count >= line_start && line_count <= line_end { + buf.push_str(&format!("{:4} | {}\n", line_count, line_content)); + if line_count == line - 1 { + buf.push_str(" |"); + for c in 0..line_content.len() { + if c != col { + buf.push('-'); + } else { + buf.push('^'); + } + } + buf.push('\n'); + } + } + } + + buf +} + +impl fmt::Display for TemplateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match (self.line_no, self.column_no, &self.segment) { + (Some(line), Some(col), &Some(ref seg)) => writeln!( + f, + "Template error: {}\n --> Template error in \"{}\":{}:{}\n |\n{} |\n = reason: {}", + self.reason, + self.template_name + .as_ref() + .unwrap_or(&"Unnamed template".to_owned()), + line, + col, + seg, + self.reason + ), + _ => write!(f, "{}", self.reason), + } + } +} + +#[cfg(feature = "script_helper")] +quick_error! { + #[derive(Debug)] + pub enum ScriptError { + IoError(err: IOError) { + from() + source(err) + } + ParseError(err: ParseError) { + from() + source(err) + } + } +} diff --git a/vendor/handlebars/src/grammar.pest b/vendor/handlebars/src/grammar.pest new file mode 100644 index 000000000..250d9d213 --- /dev/null +++ b/vendor/handlebars/src/grammar.pest @@ -0,0 +1,127 @@ +WHITESPACE = _{ " "|"\t"|"\n"|"\r" } +keywords = { "as" | "else" } + +escape = @{ ("\\" ~ "{{" ~ "{{"?) | ("\\" ~ "\\"+ ~ &"{{") } +raw_text = ${ ( escape | (!"{{" ~ ANY) )+ } +raw_block_text = ${ ( escape | (!"{{{{" ~ ANY) )* } + +literal = { string_literal | + array_literal | + object_literal | + number_literal | + null_literal | + boolean_literal } + +null_literal = @{ "null" ~ !symbol_char } +boolean_literal = @{ ("true"|"false") ~ !symbol_char } +number_literal = @{ "-"? ~ ASCII_DIGIT+ ~ "."? ~ ASCII_DIGIT* ~ ("E" ~ "-"? ~ ASCII_DIGIT+)? } +json_char = { + !("\"" | "\\") ~ ANY + | "\\" ~ ("\"" | "\\" | "/" | "b" | "f" | "n" | "r" | "t") + | "\\" ~ ("u" ~ ASCII_HEX_DIGIT{4}) +} +string_inner = @{ json_char* } +string_literal = ${ "\"" ~ string_inner ~ "\"" } +array_literal = { "[" ~ literal? ~ ("," ~ literal)* ~ "]" } +object_literal = { "{" ~ (string_literal ~ ":" ~ literal)? + ~ ("," ~ string_literal ~ ":" ~ literal)* ~ "}" } + +symbol_char = _{ASCII_ALPHANUMERIC|"-"|"_"|"$"|'\u{80}'..'\u{7ff}'|'\u{800}'..'\u{ffff}'|'\u{10000}'..'\u{10ffff}'} +partial_symbol_char = _{ASCII_ALPHANUMERIC|"-"|"_"|'\u{80}'..'\u{7ff}'|'\u{800}'..'\u{ffff}'|'\u{10000}'..'\u{10ffff}'|"/"|"."} +path_char = _{ "/" } + +identifier = @{ symbol_char+ } +partial_identifier = @{ partial_symbol_char+ | ("[" ~ ANY+ ~ "]") | ("'" ~ (!"'" ~ ("\\'" | ANY))+ ~ "'") } +reference = ${ path_inline } + +name = _{ subexpression | reference } + +param = { !(keywords ~ !symbol_char) ~ (literal | reference | subexpression) } +hash = { identifier ~ "=" ~ param } +block_param = { "as" ~ "|" ~ identifier ~ identifier? ~ "|"} +exp_line = _{ identifier ~ (hash|param)* ~ block_param?} +partial_exp_line = _{ ((partial_identifier|name) ~ (hash|param)*) } + +subexpression = { "(" ~ ((identifier ~ (hash|param)+) | reference) ~ ")" } + +pre_whitespace_omitter = { "~" } +pro_whitespace_omitter = { "~" } + +expression = { !invert_tag ~ "{{" ~ pre_whitespace_omitter? ~ + ((identifier ~ (hash|param)+) | name ) + ~ pro_whitespace_omitter? ~ "}}" } +html_expression_triple_bracket = _{ "{{{" ~ pre_whitespace_omitter? ~ + ((identifier ~ (hash|param)+) | name ) ~ + pro_whitespace_omitter? ~ "}}}" } +amp_expression = _{ "{{" ~ pre_whitespace_omitter? ~ "&" ~ name ~ + pro_whitespace_omitter? ~ "}}" } +html_expression = { html_expression_triple_bracket | amp_expression } + +decorator_expression = { "{{" ~ pre_whitespace_omitter? ~ "*" ~ exp_line ~ +pro_whitespace_omitter? ~ "}}" } +partial_expression = { "{{" ~ pre_whitespace_omitter? ~ ">" ~ partial_exp_line + ~ pro_whitespace_omitter? ~ "}}" } + +invert_tag_item = { "else"|"^" } +invert_tag = { !escape ~ "{{" ~ pre_whitespace_omitter? ~ invert_tag_item + ~ pro_whitespace_omitter? ~ "}}" } +helper_block_start = { "{{" ~ pre_whitespace_omitter? ~ "#" ~ exp_line ~ + pro_whitespace_omitter? ~ "}}" } +helper_block_end = { "{{" ~ pre_whitespace_omitter? ~ "/" ~ identifier ~ + pro_whitespace_omitter? ~ "}}" } +helper_block = _{ helper_block_start ~ template ~ + (invert_tag ~ template)? ~ helper_block_end } + +decorator_block_start = { "{{" ~ pre_whitespace_omitter? ~ "#" ~ "*" + ~ exp_line ~ pro_whitespace_omitter? ~ "}}" } +decorator_block_end = { "{{" ~ pre_whitespace_omitter? ~ "/" ~ identifier ~ + pro_whitespace_omitter? ~ "}}" } +decorator_block = _{ decorator_block_start ~ template ~ + decorator_block_end } + +partial_block_start = { "{{" ~ pre_whitespace_omitter? ~ "#" ~ ">" + ~ partial_exp_line ~ pro_whitespace_omitter? ~ "}}" } +partial_block_end = { "{{" ~ pre_whitespace_omitter? ~ "/" ~ partial_identifier ~ + pro_whitespace_omitter? ~ "}}" } +partial_block = _{ partial_block_start ~ template ~ partial_block_end } + +raw_block_start = { "{{{{" ~ pre_whitespace_omitter? ~ exp_line ~ + pro_whitespace_omitter? ~ "}}}}" } +raw_block_end = { "{{{{" ~ pre_whitespace_omitter? ~ "/" ~ identifier ~ + pro_whitespace_omitter? ~ "}}}}" } +raw_block = _{ raw_block_start ~ raw_block_text ~ raw_block_end } + +hbs_comment = { "{{!" ~ "--" ~ (!"--}}" ~ ANY)* ~ "--" ~ "}}" } +hbs_comment_compact = { "{{!" ~ (!"}}" ~ ANY)* ~ "}}" } + +template = { ( + raw_text | + expression | + html_expression | + helper_block | + raw_block | + hbs_comment | + hbs_comment_compact | + decorator_expression | + decorator_block | + partial_expression | + partial_block )* } + +parameter = _{ param ~ EOI } +handlebars = _{ template ~ EOI } + +// json path visitor +// Disallowed chars: Whitespace ! " # % & ' ( ) * + , . / ; < = > @ [ \ ] ^ ` { | } ~ + +path_id = @{ symbol_char+ } + +path_raw_id = { (!"]" ~ ANY)* } +path_sep = _{ "/" | "." } +path_up = { ".." } +path_key = _{ "[" ~ path_raw_id ~ "]" } +path_root = { "@root" } +path_current = _{ "this" ~ path_sep | "./" } +path_item = _{ path_id|path_key } +path_local = { "@" } +path_inline = ${ path_current? ~ (path_root ~ path_sep)? ~ path_local? ~ (path_up ~ path_sep)* ~ path_item ~ (path_sep ~ path_item)* } +path = _{ path_inline ~ EOI } diff --git a/vendor/handlebars/src/grammar.rs b/vendor/handlebars/src/grammar.rs new file mode 100644 index 000000000..1fd292ce1 --- /dev/null +++ b/vendor/handlebars/src/grammar.rs @@ -0,0 +1,372 @@ +// const _GRAMMAR: &'static str = include_str!("grammar.pest"); + +#[derive(Parser)] +#[grammar = "grammar.pest"] +pub struct HandlebarsParser; + +#[inline] +pub(crate) fn whitespace_matcher(c: char) -> bool { + c == ' ' || c == '\t' +} + +#[inline] +pub(crate) fn newline_matcher(c: char) -> bool { + c == '\n' || c == '\r' +} + +pub(crate) fn ends_with_empty_line(text: &str) -> bool { + text.trim_end_matches(whitespace_matcher) + .ends_with(newline_matcher) +} + +pub(crate) fn starts_with_empty_line(text: &str) -> bool { + text.trim_start_matches(whitespace_matcher) + .starts_with(newline_matcher) +} + +#[cfg(test)] +mod test { + use super::{HandlebarsParser, Rule}; + use pest::Parser; + + macro_rules! assert_rule { + ($rule:expr, $in:expr) => { + assert_eq!( + HandlebarsParser::parse($rule, $in) + .unwrap() + .last() + .unwrap() + .as_span() + .end(), + $in.len() + ); + }; + } + + macro_rules! assert_not_rule { + ($rule:expr, $in:expr) => { + assert!( + HandlebarsParser::parse($rule, $in).is_err() + || HandlebarsParser::parse($rule, $in) + .unwrap() + .last() + .unwrap() + .as_span() + .end() + != $in.len() + ); + }; + } + + macro_rules! assert_rule_match { + ($rule:expr, $in:expr) => { + assert!(HandlebarsParser::parse($rule, $in).is_ok()); + }; + } + + #[test] + fn test_raw_text() { + let s = vec![ + "

helloworld

", + r"hello\{{world}}", + r"hello\{{#if world}}nice\{{/if}}", + r"hello \{{{{raw}}}}hello\{{{{/raw}}}}", + ]; + for i in s.iter() { + assert_rule!(Rule::raw_text, i); + } + + let s_not_escape = vec![r"\\{{hello}}"]; + for i in s_not_escape.iter() { + assert_not_rule!(Rule::raw_text, i); + } + } + + #[test] + fn test_raw_block_text() { + let s = "

{{hello}}

"; + assert_rule!(Rule::raw_block_text, s); + } + + #[test] + fn test_reference() { + let s = vec![ + "a", + "abc", + "../a", + "a.b", + "@abc", + "a.[abc]", + "aBc.[abc]", + "abc.[0].[nice]", + "some-name", + "this.[0].ok", + "this.[$id]", + "[$id]", + "$id", + "this.[null]", + ]; + for i in s.iter() { + assert_rule!(Rule::reference, i); + } + } + + #[test] + fn test_name() { + let s = vec!["if", "(abc)"]; + for i in s.iter() { + assert_rule!(Rule::name, i); + } + } + + #[test] + fn test_param() { + let s = vec!["hello", "\"json literal\"", "nullable", "truestory"]; + for i in s.iter() { + assert_rule!(Rule::param, i); + } + } + + #[test] + fn test_hash() { + let s = vec![ + "hello=world", + "hello=\"world\"", + "hello=(world)", + "hello=(world 0)", + ]; + for i in s.iter() { + assert_rule!(Rule::hash, i); + } + } + + #[test] + fn test_json_literal() { + let s = vec![ + "\"json string\"", + "\"quot: \\\"\"", + "[]", + "[\"hello\"]", + "[1,2,3,4,true]", + "{\"hello\": \"world\"}", + "{}", + "{\"a\":1, \"b\":2 }", + "\"nullable\"", + ]; + for i in s.iter() { + assert_rule!(Rule::literal, i); + } + } + + #[test] + fn test_comment() { + let s = vec!["{{!-- {{this.title}} + --}}", + "{{! -- good --}}"]; + for i in s.iter() { + assert_rule!(Rule::hbs_comment, i); + } + let s2 = vec!["{{! hello }}", "{{! test me }}"]; + for i in s2.iter() { + assert_rule!(Rule::hbs_comment_compact, i); + } + } + + #[test] + fn test_subexpression() { + let s = vec!["(sub)", "(sub 0)", "(sub a=1)"]; + for i in s.iter() { + assert_rule!(Rule::subexpression, i); + } + } + + #[test] + fn test_expression() { + let s = vec![ + "{{exp}}", + "{{(exp)}}", + "{{../exp}}", + "{{exp 1}}", + "{{exp \"literal\"}}", + "{{exp \"literal with space\"}}", + r#"{{exp "literal with escape \\\\"}}"#, + "{{exp ref}}", + "{{exp (sub)}}", + "{{exp (sub 123)}}", + "{{exp []}}", + "{{exp {}}}", + "{{exp key=1}}", + "{{exp key=ref}}", + "{{exp key=(sub)}}", + "{{exp key=(sub 0)}}", + "{{exp key=(sub 0 key=1)}}", + ]; + for i in s.iter() { + assert_rule!(Rule::expression, i); + } + } + + #[test] + fn test_identifier_with_dash() { + let s = vec!["{{exp-foo}}"]; + for i in s.iter() { + assert_rule!(Rule::expression, i); + } + } + + #[test] + fn test_html_expression() { + let s = vec![ + "{{{html}}}", + "{{{(html)}}}", + "{{{(html)}}}", + "{{&html}}", + "{{{html 1}}}", + "{{{html p=true}}}", + ]; + for i in s.iter() { + assert_rule!(Rule::html_expression, i); + } + } + + #[test] + fn test_helper_start() { + let s = vec![ + "{{#if hello}}", + "{{#if (hello)}}", + "{{#if hello=world}}", + "{{#if hello hello=world}}", + "{{#if []}}", + "{{#if {}}}", + "{{#if}}", + "{{~#if hello~}}", + "{{#each people as |person|}}", + "{{#each-obj obj as |val key|}}", + "{{#each assets}}", + ]; + for i in s.iter() { + assert_rule!(Rule::helper_block_start, i); + } + } + + #[test] + fn test_helper_end() { + let s = vec!["{{/if}}", "{{~/if}}", "{{~/if ~}}", "{{/if ~}}"]; + for i in s.iter() { + assert_rule!(Rule::helper_block_end, i); + } + } + + #[test] + fn test_helper_block() { + let s = vec![ + "{{#if hello}}hello{{/if}}", + "{{#if true}}hello{{/if}}", + "{{#if nice ok=1}}hello{{/if}}", + "{{#if}}hello{{else}}world{{/if}}", + "{{#if}}hello{{^}}world{{/if}}", + "{{#if}}{{#if}}hello{{/if}}{{/if}}", + "{{#if}}hello{{~else}}world{{/if}}", + "{{#if}}hello{{else~}}world{{/if}}", + "{{#if}}hello{{~^~}}world{{/if}}", + "{{#if}}{{/if}}", + ]; + for i in s.iter() { + assert_rule!(Rule::helper_block, i); + } + } + + #[test] + fn test_raw_block() { + let s = vec![ + "{{{{if hello}}}}good {{hello}}{{{{/if}}}}", + "{{{{if hello}}}}{{#if nice}}{{/if}}{{{{/if}}}}", + ]; + for i in s.iter() { + assert_rule!(Rule::raw_block, i); + } + } + + #[test] + fn test_block_param() { + let s = vec!["as |person|", "as |val key|"]; + for i in s.iter() { + assert_rule!(Rule::block_param, i); + } + } + + #[test] + fn test_path() { + let s = vec![ + "a", + "a.b.c.d", + "a.[0].[1].[2]", + "a.[abc]", + "a/v/c.d.s", + "a.[0]/b/c/d", + "a.[bb c]/b/c/d", + "a.[0].[#hello]", + "../a/b.[0].[1]", + "this.[0]/[1]/this/a", + "./this_name", + "./goo/[/bar]", + "a.[你好]", + "a.[10].[#comment]", + "a.[]", // empty key + "./[/foo]", + "[foo]", + "@root/a/b", + "nullable", + ]; + for i in s.iter() { + assert_rule_match!(Rule::path, i); + } + } + + #[test] + fn test_decorator_expression() { + let s = vec!["{{* ssh}}", "{{~* ssh}}"]; + for i in s.iter() { + assert_rule!(Rule::decorator_expression, i); + } + } + + #[test] + fn test_decorator_block() { + let s = vec![ + "{{#* inline}}something{{/inline}}", + "{{~#* inline}}hello{{/inline}}", + "{{#* inline \"partialname\"}}something{{/inline}}", + ]; + for i in s.iter() { + assert_rule!(Rule::decorator_block, i); + } + } + + #[test] + fn test_partial_expression() { + let s = vec![ + "{{> hello}}", + "{{> (hello)}}", + "{{~> hello a}}", + "{{> hello a=1}}", + "{{> (hello) a=1}}", + "{{> hello.world}}", + "{{> [a83?f4+.3]}}", + "{{> 'anif?.bar'}}", + ]; + for i in s.iter() { + assert_rule!(Rule::partial_expression, i); + } + } + + #[test] + fn test_partial_block() { + let s = vec!["{{#> hello}}nice{{/hello}}"]; + for i in s.iter() { + assert_rule!(Rule::partial_block, i); + } + } +} diff --git a/vendor/handlebars/src/helpers/block_util.rs b/vendor/handlebars/src/helpers/block_util.rs new file mode 100644 index 000000000..6971fdd8a --- /dev/null +++ b/vendor/handlebars/src/helpers/block_util.rs @@ -0,0 +1,17 @@ +use crate::block::BlockContext; +use crate::json::value::PathAndJson; + +pub(crate) fn create_block<'reg: 'rc, 'rc>( + param: &'rc PathAndJson<'reg, 'rc>, +) -> BlockContext<'reg> { + let mut block = BlockContext::new(); + + if let Some(new_path) = param.context_path() { + *block.base_path_mut() = new_path.clone(); + } else { + // use clone for now + block.set_base_value(param.value().clone()); + } + + block +} diff --git a/vendor/handlebars/src/helpers/helper_each.rs b/vendor/handlebars/src/helpers/helper_each.rs new file mode 100644 index 000000000..4b76e7ce7 --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_each.rs @@ -0,0 +1,593 @@ +use serde_json::value::Value as Json; + +use super::block_util::create_block; +use crate::block::{BlockContext, BlockParams}; +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::{HelperDef, HelperResult}; +use crate::json::value::to_json; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext, Renderable}; +use crate::util::copy_on_push_vec; + +fn update_block_context<'reg>( + block: &mut BlockContext<'reg>, + base_path: Option<&Vec>, + relative_path: String, + is_first: bool, + value: &Json, +) { + if let Some(ref p) = base_path { + if is_first { + *block.base_path_mut() = copy_on_push_vec(p, relative_path); + } else if let Some(ptr) = block.base_path_mut().last_mut() { + *ptr = relative_path; + } + } else { + block.set_base_value(value.clone()); + } +} + +fn set_block_param<'reg: 'rc, 'rc>( + block: &mut BlockContext<'reg>, + h: &Helper<'reg, 'rc>, + base_path: Option<&Vec>, + k: &Json, + v: &Json, +) -> Result<(), RenderError> { + if let Some(bp_val) = h.block_param() { + let mut params = BlockParams::new(); + if base_path.is_some() { + params.add_path(bp_val, Vec::with_capacity(0))?; + } else { + params.add_value(bp_val, v.clone())?; + } + + block.set_block_params(params); + } else if let Some((bp_val, bp_key)) = h.block_param_pair() { + let mut params = BlockParams::new(); + if base_path.is_some() { + params.add_path(bp_val, Vec::with_capacity(0))?; + } else { + params.add_value(bp_val, v.clone())?; + } + params.add_value(bp_key, k.clone())?; + + block.set_block_params(params); + } + + Ok(()) +} + +#[derive(Clone, Copy)] +pub struct EachHelper; + +impl HelperDef for EachHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + let value = h + .param(0) + .ok_or_else(|| RenderError::new("Param not found for helper \"each\""))?; + + let template = h.template(); + + match template { + Some(t) => match *value.value() { + Json::Array(ref list) + if !list.is_empty() || (list.is_empty() && h.inverse().is_none()) => + { + let block_context = create_block(&value); + rc.push_block(block_context); + + let len = list.len(); + + let array_path = value.context_path(); + + for (i, v) in list.iter().enumerate().take(len) { + if let Some(ref mut block) = rc.block_mut() { + let is_first = i == 0usize; + let is_last = i == len - 1; + + let index = to_json(i); + block.set_local_var("first", to_json(is_first)); + block.set_local_var("last", to_json(is_last)); + block.set_local_var("index", index.clone()); + + update_block_context(block, array_path, i.to_string(), is_first, &v); + set_block_param(block, h, array_path, &index, &v)?; + } + + t.render(r, ctx, rc, out)?; + } + + rc.pop_block(); + Ok(()) + } + Json::Object(ref obj) + if !obj.is_empty() || (obj.is_empty() && h.inverse().is_none()) => + { + let block_context = create_block(&value); + rc.push_block(block_context); + + let mut is_first = true; + let obj_path = value.context_path(); + + for (k, v) in obj.iter() { + if let Some(ref mut block) = rc.block_mut() { + let key = to_json(k); + + block.set_local_var("first", to_json(is_first)); + block.set_local_var("key", key.clone()); + + update_block_context(block, obj_path, k.to_string(), is_first, &v); + set_block_param(block, h, obj_path, &key, &v)?; + } + + t.render(r, ctx, rc, out)?; + + if is_first { + is_first = false; + } + } + + rc.pop_block(); + Ok(()) + } + _ => { + if let Some(else_template) = h.inverse() { + else_template.render(r, ctx, rc, out) + } else if r.strict_mode() { + Err(RenderError::strict_error(value.relative_path())) + } else { + Ok(()) + } + } + }, + None => Ok(()), + } + } +} + +pub static EACH_HELPER: EachHelper = EachHelper; + +#[cfg(test)] +mod test { + use crate::json::value::to_json; + use crate::registry::Registry; + use serde_json::value::Value as Json; + use std::collections::BTreeMap; + use std::str::FromStr; + + #[test] + fn test_empty_each() { + let mut hbs = Registry::new(); + hbs.set_strict_mode(true); + + let data = json!({ + "a": [ ], + }); + + let template = "{{#each a}}each{{/each}}"; + assert_eq!(hbs.render_template(template, &data).unwrap(), ""); + } + + #[test] + fn test_each() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string( + "t0", + "{{#each this}}{{@first}}|{{@last}}|{{@index}}:{{this}}|{{/each}}" + ) + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#each this}}{{@first}}|{{@key}}:{{this}}|{{/each}}") + .is_ok()); + + let r0 = handlebars.render("t0", &vec![1u16, 2u16, 3u16]); + assert_eq!( + r0.ok().unwrap(), + "true|false|0:1|false|false|1:2|false|true|2:3|".to_string() + ); + + let mut m: BTreeMap = BTreeMap::new(); + m.insert("ftp".to_string(), 21); + m.insert("http".to_string(), 80); + let r1 = handlebars.render("t1", &m); + assert_eq!(r1.ok().unwrap(), "true|ftp:21|false|http:80|".to_string()); + } + + #[test] + fn test_each_with_parent() { + let json_str = r#"{"a":{"a":99,"c":[{"d":100},{"d":200}]}}"#; + + let data = Json::from_str(json_str).unwrap(); + // println!("data: {}", data); + let mut handlebars = Registry::new(); + + // previously, to access the parent in an each block, + // a user would need to specify ../../b, as the path + // that is computed includes the array index: ./a.c.[0] + assert!(handlebars + .register_template_string("t0", "{{#each a.c}} d={{d}} b={{../a.a}} {{/each}}") + .is_ok()); + + let r1 = handlebars.render("t0", &data); + assert_eq!(r1.ok().unwrap(), " d=100 b=99 d=200 b=99 ".to_string()); + } + + #[test] + fn test_nested_each_with_parent() { + let json_str = r#"{"a": [{"b": [{"d": 100}], "c": 200}]}"#; + + let data = Json::from_str(json_str).unwrap(); + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string( + "t0", + "{{#each a}}{{#each b}}{{d}}:{{../c}}{{/each}}{{/each}}" + ) + .is_ok()); + + let r1 = handlebars.render("t0", &data); + assert_eq!(r1.ok().unwrap(), "100:200".to_string()); + } + + #[test] + fn test_nested_each() { + let json_str = r#"{"a": [{"b": true}], "b": [[1, 2, 3],[4, 5]]}"#; + + let data = Json::from_str(json_str).unwrap(); + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string( + "t0", + "{{#each b}}{{#if ../a}}{{#each this}}{{this}}{{/each}}{{/if}}{{/each}}" + ) + .is_ok()); + + let r1 = handlebars.render("t0", &data); + assert_eq!(r1.ok().unwrap(), "12345".to_string()); + } + + #[test] + fn test_nested_array() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each this.[0]}}{{this}}{{/each}}") + .is_ok()); + + let r0 = handlebars.render("t0", &(vec![vec![1, 2, 3]])); + + assert_eq!(r0.ok().unwrap(), "123".to_string()); + } + + #[test] + fn test_empty_key() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each this}}{{@key}}-{{value}}\n{{/each}}") + .is_ok()); + + let r0 = handlebars + .render( + "t0", + &json!({ + "foo": { + "value": "bar" + }, + "": { + "value": "baz" + } + }), + ) + .unwrap(); + + let mut r0_sp: Vec<_> = r0.split('\n').collect(); + r0_sp.sort(); + + assert_eq!(r0_sp, vec!["", "-baz", "foo-bar"]); + } + + #[test] + fn test_each_else() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each a}}1{{else}}empty{{/each}}") + .is_ok()); + let m1 = btreemap! { + "a".to_string() => Vec::::new(), + }; + let r0 = handlebars.render("t0", &m1).unwrap(); + assert_eq!(r0, "empty"); + + let m2 = btreemap! { + "b".to_string() => Vec::::new() + }; + let r1 = handlebars.render("t0", &m2).unwrap(); + assert_eq!(r1, "empty"); + } + + #[test] + fn test_block_param() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each a as |i|}}{{i}}{{/each}}") + .is_ok()); + let m1 = btreemap! { + "a".to_string() => vec![1,2,3,4,5] + }; + let r0 = handlebars.render("t0", &m1).unwrap(); + assert_eq!(r0, "12345"); + } + + #[test] + fn test_each_object_block_param() { + let mut handlebars = Registry::new(); + let template = "{{#each this as |v k|}}\ + {{#with k as |inner_k|}}{{inner_k}}{{/with}}:{{v}}|\ + {{/each}}"; + assert!(handlebars.register_template_string("t0", template).is_ok()); + + let m = btreemap! { + "ftp".to_string() => 21, + "http".to_string() => 80 + }; + let r0 = handlebars.render("t0", &m); + assert_eq!(r0.ok().unwrap(), "ftp:21|http:80|".to_string()); + } + + #[test] + fn test_each_object_block_param2() { + let mut handlebars = Registry::new(); + let template = "{{#each this as |v k|}}\ + {{#with v as |inner_v|}}{{k}}:{{inner_v}}{{/with}}|\ + {{/each}}"; + + assert!(handlebars.register_template_string("t0", template).is_ok()); + + let m = btreemap! { + "ftp".to_string() => 21, + "http".to_string() => 80 + }; + let r0 = handlebars.render("t0", &m); + assert_eq!(r0.ok().unwrap(), "ftp:21|http:80|".to_string()); + } + + fn test_nested_each_with_path_ups() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string( + "t0", + "{{#each a.b}}{{#each c}}{{../../d}}{{/each}}{{/each}}" + ) + .is_ok()); + + let data = btreemap! { + "a".to_string() => to_json(&btreemap! { + "b".to_string() => vec![btreemap!{"c".to_string() => vec![1]}] + }), + "d".to_string() => to_json(&1) + }; + + let r0 = handlebars.render("t0", &data); + assert_eq!(r0.ok().unwrap(), "1".to_string()); + } + + #[test] + fn test_nested_each_with_path_up_this() { + let mut handlebars = Registry::new(); + let template = "{{#each variant}}{{#each ../typearg}}\ + {{#if @first}}template<{{/if}}{{this}}{{#if @last}}>{{else}},{{/if}}\ + {{/each}}{{/each}}"; + assert!(handlebars.register_template_string("t0", template).is_ok()); + let data = btreemap! { + "typearg".to_string() => vec!["T".to_string()], + "variant".to_string() => vec!["1".to_string(), "2".to_string()] + }; + let r0 = handlebars.render("t0", &data); + assert_eq!(r0.ok().unwrap(), "templatetemplate".to_string()); + } + + #[test] + fn test_key_iteration_with_unicode() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each this}}{{@key}}: {{this}}\n{{/each}}") + .is_ok()); + let data = json!({ + "normal": 1, + "你好": 2, + "#special key": 3, + "😂": 4, + "me.dot.key": 5 + }); + let r0 = handlebars.render("t0", &data).ok().unwrap(); + assert!(r0.contains("normal: 1")); + assert!(r0.contains("你好: 2")); + assert!(r0.contains("#special key: 3")); + assert!(r0.contains("😂: 4")); + assert!(r0.contains("me.dot.key: 5")); + } + + #[test] + fn test_base_path_after_each() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each a}}{{this}}{{/each}} {{b}}") + .is_ok()); + let data = json!({ + "a": [1, 2, 3, 4], + "b": "good", + }); + + let r0 = handlebars.render("t0", &data).ok().unwrap(); + + assert_eq!("1234 good", r0); + } + + #[test] + fn test_else_context() { + let reg = Registry::new(); + let template = "{{#each list}}A{{else}}{{foo}}{{/each}}"; + let input = json!({"list": [], "foo": "bar"}); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("bar", rendered); + } + + #[test] + fn test_block_context_leak() { + let reg = Registry::new(); + let template = "{{#each list}}{{#each inner}}{{this}}{{/each}}{{foo}}{{/each}}"; + let input = json!({"list": [{"inner": [], "foo": 1}, {"inner": [], "foo": 2}]}); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("12", rendered); + } + + #[test] + fn test_derived_array_as_block_params() { + handlebars_helper!(range: |x: u64| (0..x).collect::>()); + let mut reg = Registry::new(); + reg.register_helper("range", Box::new(range)); + let template = "{{#each (range 3) as |i|}}{{i}}{{/each}}"; + let input = json!(0); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("012", rendered); + } + + #[test] + fn test_derived_object_as_block_params() { + handlebars_helper!(point: |x: u64, y: u64| json!({"x":x, "y":y})); + let mut reg = Registry::new(); + reg.register_helper("point", Box::new(point)); + let template = "{{#each (point 0 1) as |i|}}{{i}}{{/each}}"; + let input = json!(0); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("01", rendered); + } + + #[test] + fn test_derived_array_without_block_param() { + handlebars_helper!(range: |x: u64| (0..x).collect::>()); + let mut reg = Registry::new(); + reg.register_helper("range", Box::new(range)); + let template = "{{#each (range 3)}}{{this}}{{/each}}"; + let input = json!(0); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("012", rendered); + } + + #[test] + fn test_derived_object_without_block_params() { + handlebars_helper!(point: |x: u64, y: u64| json!({"x":x, "y":y})); + let mut reg = Registry::new(); + reg.register_helper("point", Box::new(point)); + let template = "{{#each (point 0 1)}}{{this}}{{/each}}"; + let input = json!(0); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("01", rendered); + } + + #[test] + fn test_non_iterable() { + let reg = Registry::new(); + let template = "{{#each this}}each block{{else}}else block{{/each}}"; + let input = json!("strings aren't iterable"); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("else block", rendered); + } + + #[test] + fn test_recursion() { + let mut reg = Registry::new(); + assert!(reg + .register_template_string( + "walk", + "(\ + {{#each this}}\ + {{#if @key}}{{@key}}{{else}}{{@index}}{{/if}}: \ + {{this}} \ + {{> walk this}}, \ + {{/each}}\ + )", + ) + .is_ok()); + + let input = json!({ + "array": [42, {"wow": "cool"}, [[]]], + "object": { "a": { "b": "c", "d": ["e"] } }, + "string": "hi" + }); + let expected_output = "(\ + array: [42, [object], [[], ], ] (\ + 0: 42 (), \ + 1: [object] (wow: cool (), ), \ + 2: [[], ] (0: [] (), ), \ + ), \ + object: [object] (\ + a: [object] (\ + b: c (), \ + d: [e, ] (0: e (), ), \ + ), \ + ), \ + string: hi (), \ + )"; + + let rendered = reg.render("walk", &input).unwrap(); + assert_eq!(expected_output, rendered); + } + + #[test] + fn test_strict_each() { + let mut reg = Registry::new(); + + assert!(reg + .render_template("{{#each data}}{{/each}}", &json!({})) + .is_ok()); + assert!(reg + .render_template("{{#each data}}{{/each}}", &json!({"data": 24})) + .is_ok()); + + reg.set_strict_mode(true); + + assert!(reg + .render_template("{{#each data}}{{/each}}", &json!({})) + .is_err()); + assert!(reg + .render_template("{{#each data}}{{/each}}", &json!({"data": 24})) + .is_err()); + assert!(reg + .render_template("{{#each data}}{{else}}food{{/each}}", &json!({})) + .is_ok()); + assert!(reg + .render_template("{{#each data}}{{else}}food{{/each}}", &json!({"data": 24})) + .is_ok()); + } + + #[test] + fn newline_stripping_for_each() { + let reg = Registry::new(); + + let tpl = r#"
    + {{#each a}} + {{!-- comment --}} +
  • {{this}}
  • + {{/each}} +
"#; + assert_eq!( + r#"
    +
  • 0
  • +
  • 1
  • +
"#, + reg.render_template(tpl, &json!({"a": [0, 1]})).unwrap() + ); + } +} diff --git a/vendor/handlebars/src/helpers/helper_extras.rs b/vendor/handlebars/src/helpers/helper_extras.rs new file mode 100644 index 000000000..fe8f7a7d3 --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_extras.rs @@ -0,0 +1,112 @@ +//! Helpers for boolean operations +use serde_json::Value as Json; + +use crate::json::value::JsonTruthy; + +handlebars_helper!(eq: |x: Json, y: Json| x == y); +handlebars_helper!(ne: |x: Json, y: Json| x != y); +handlebars_helper!(gt: |x: i64, y: i64| x > y); +handlebars_helper!(gte: |x: i64, y: i64| x >= y); +handlebars_helper!(lt: |x: i64, y: i64| x < y); +handlebars_helper!(lte: |x: i64, y: i64| x <= y); +handlebars_helper!(and: |x: Json, y: Json| x.is_truthy(false) && y.is_truthy(false)); +handlebars_helper!(or: |x: Json, y: Json| x.is_truthy(false) || y.is_truthy(false)); +handlebars_helper!(not: |x: Json| !x.is_truthy(false)); +handlebars_helper!(len: |x: Json| { + match x { + Json::Array(a) => a.len(), + Json::Object(m) => m.len(), + Json::String(s) => s.len(), + _ => 0 + } +}); + +#[cfg(test)] +mod test_conditions { + fn test_condition(condition: &str, expected: bool) { + let handlebars = crate::Handlebars::new(); + + let result = handlebars + .render_template( + &format!( + "{{{{#if {condition}}}}}lorem{{{{else}}}}ipsum{{{{/if}}}}", + condition = condition + ), + &json!({}), + ) + .unwrap(); + assert_eq!(&result, if expected { "lorem" } else { "ipsum" }); + } + + #[test] + fn foo() { + test_condition("(gt 5 3)", true); + test_condition("(gt 3 5)", false); + test_condition("(or (gt 3 5) (gt 5 3))", true); + test_condition("(not [])", true); + test_condition("(and null 4)", false); + } + + #[test] + fn test_eq() { + test_condition("(eq 5 5)", true); + test_condition("(eq 5 6)", false); + test_condition(r#"(eq "foo" "foo")"#, true); + test_condition(r#"(eq "foo" "Foo")"#, false); + test_condition(r#"(eq [5] [5])"#, true); + test_condition(r#"(eq [5] [4])"#, false); + test_condition(r#"(eq 5 "5")"#, false); + test_condition(r#"(eq 5 [5])"#, false); + } + + #[test] + fn test_ne() { + test_condition("(ne 5 6)", true); + test_condition("(ne 5 5)", false); + test_condition(r#"(ne "foo" "foo")"#, false); + test_condition(r#"(ne "foo" "Foo")"#, true); + } + + #[test] + fn nested_conditions() { + let handlebars = crate::Handlebars::new(); + + let result = handlebars + .render_template("{{#if (gt 5 3)}}lorem{{else}}ipsum{{/if}}", &json!({})) + .unwrap(); + assert_eq!(&result, "lorem"); + + let result = handlebars + .render_template( + "{{#if (not (gt 5 3))}}lorem{{else}}ipsum{{/if}}", + &json!({}), + ) + .unwrap(); + assert_eq!(&result, "ipsum"); + } + + #[test] + fn test_len() { + let handlebars = crate::Handlebars::new(); + + let result = handlebars + .render_template("{{len value}}", &json!({"value": [1,2,3]})) + .unwrap(); + assert_eq!(&result, "3"); + + let result = handlebars + .render_template("{{len value}}", &json!({"value": {"a" :1, "b": 2}})) + .unwrap(); + assert_eq!(&result, "2"); + + let result = handlebars + .render_template("{{len value}}", &json!({"value": "tomcat"})) + .unwrap(); + assert_eq!(&result, "6"); + + let result = handlebars + .render_template("{{len value}}", &json!({"value": 3})) + .unwrap(); + assert_eq!(&result, "0"); + } +} diff --git a/vendor/handlebars/src/helpers/helper_if.rs b/vendor/handlebars/src/helpers/helper_if.rs new file mode 100644 index 000000000..5a6e42fc0 --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_if.rs @@ -0,0 +1,151 @@ +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::{HelperDef, HelperResult}; +use crate::json::value::JsonTruthy; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext, Renderable}; + +#[derive(Clone, Copy)] +pub struct IfHelper { + positive: bool, +} + +impl HelperDef for IfHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + let param = h + .param(0) + .ok_or_else(|| RenderError::new("Param not found for helper \"if\""))?; + let include_zero = h + .hash_get("includeZero") + .and_then(|v| v.value().as_bool()) + .unwrap_or(false); + + let mut value = param.value().is_truthy(include_zero); + + if !self.positive { + value = !value; + } + + let tmpl = if value { h.template() } else { h.inverse() }; + match tmpl { + Some(ref t) => t.render(r, ctx, rc, out), + None => Ok(()), + } + } +} + +pub static IF_HELPER: IfHelper = IfHelper { positive: true }; +pub static UNLESS_HELPER: IfHelper = IfHelper { positive: false }; + +#[cfg(test)] +mod test { + use crate::helpers::WITH_HELPER; + use crate::registry::Registry; + use serde_json::value::Value as Json; + use std::str::FromStr; + + #[test] + fn test_if() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#if this}}hello{{/if}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#unless this}}hello{{else}}world{{/unless}}") + .is_ok()); + + let r0 = handlebars.render("t0", &true); + assert_eq!(r0.ok().unwrap(), "hello".to_string()); + + let r1 = handlebars.render("t1", &true); + assert_eq!(r1.ok().unwrap(), "world".to_string()); + + let r2 = handlebars.render("t0", &false); + assert_eq!(r2.ok().unwrap(), "".to_string()); + } + + #[test] + fn test_if_context() { + let json_str = r#"{"a":{"b":99,"c":{"d": true}}}"#; + let data = Json::from_str(json_str).unwrap(); + + let mut handlebars = Registry::new(); + handlebars.register_helper("with", Box::new(WITH_HELPER)); + assert!(handlebars + .register_template_string("t0", "{{#if a.c.d}}hello {{a.b}}{{/if}}") + .is_ok()); + assert!(handlebars + .register_template_string( + "t1", + "{{#with a}}{{#if c.d}}hello {{../a.b}}{{/if}}{{/with}}" + ) + .is_ok()); + + let r0 = handlebars.render("t0", &data); + assert_eq!(r0.unwrap(), "hello 99".to_string()); + + let r1 = handlebars.render("t1", &data); + assert_eq!(r1.unwrap(), "hello 99".to_string()); + } + + #[test] + fn test_if_include_zero() { + use std::f64; + let handlebars = Registry::new(); + + assert_eq!( + "0".to_owned(), + handlebars + .render_template("{{#if a}}1{{else}}0{{/if}}", &json!({"a": 0})) + .unwrap() + ); + assert_eq!( + "1".to_owned(), + handlebars + .render_template( + "{{#if a includeZero=true}}1{{else}}0{{/if}}", + &json!({"a": 0}) + ) + .unwrap() + ); + assert_eq!( + "0".to_owned(), + handlebars + .render_template( + "{{#if a includeZero=true}}1{{else}}0{{/if}}", + &json!({ "a": f64::NAN }) + ) + .unwrap() + ); + } + + #[test] + fn test_invisible_line_stripping() { + let hbs = Registry::new(); + assert_eq!( + "yes\n", + hbs.render_template("{{#if a}}\nyes\n{{/if}}\n", &json!({"a": true})) + .unwrap() + ); + + assert_eq!( + "x\ny", + hbs.render_template("{{#if a}}x{{/if}}\ny", &json!({"a": true})) + .unwrap() + ); + + assert_eq!( + "y\nz", + hbs.render_template("{{#if a}}\nx\n{{^}}\ny\n{{/if}}\nz", &json!({"a": false})) + .unwrap() + ); + } +} diff --git a/vendor/handlebars/src/helpers/helper_log.rs b/vendor/handlebars/src/helpers/helper_log.rs new file mode 100644 index 000000000..5821efa35 --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_log.rs @@ -0,0 +1,72 @@ +use crate::context::Context; +#[cfg(not(feature = "no_logging"))] +use crate::error::RenderError; +use crate::helpers::{HelperDef, HelperResult}; +#[cfg(not(feature = "no_logging"))] +use crate::json::value::JsonRender; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext}; +#[cfg(not(feature = "no_logging"))] +use log::Level; +#[cfg(not(feature = "no_logging"))] +use std::str::FromStr; + +#[derive(Clone, Copy)] +pub struct LogHelper; + +#[cfg(not(feature = "no_logging"))] +impl HelperDef for LogHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + _: &'reg Registry<'reg>, + _: &'rc Context, + _: &mut RenderContext<'reg, 'rc>, + _: &mut dyn Output, + ) -> HelperResult { + let param_to_log = h + .params() + .iter() + .map(|p| { + if let Some(ref relative_path) = p.relative_path() { + format!("{}: {}", relative_path, p.value().render()) + } else { + p.value().render() + } + }) + .collect::>() + .join(", "); + + let level = h + .hash_get("level") + .and_then(|v| v.value().as_str()) + .unwrap_or("info"); + + if let Ok(log_level) = Level::from_str(level) { + log!(log_level, "{}", param_to_log) + } else { + return Err(RenderError::new(&format!( + "Unsupported logging level {}", + level + ))); + } + Ok(()) + } +} + +#[cfg(feature = "no_logging")] +impl HelperDef for LogHelper { + fn call<'reg: 'rc, 'rc>( + &self, + _: &Helper<'reg, 'rc>, + _: &Registry<'reg>, + _: &Context, + _: &mut RenderContext<'reg, 'rc>, + _: &mut dyn Output, + ) -> HelperResult { + Ok(()) + } +} + +pub static LOG_HELPER: LogHelper = LogHelper; diff --git a/vendor/handlebars/src/helpers/helper_lookup.rs b/vendor/handlebars/src/helpers/helper_lookup.rs new file mode 100644 index 000000000..bf887debe --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_lookup.rs @@ -0,0 +1,104 @@ +use serde_json::value::Value as Json; + +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::HelperDef; +use crate::json::value::ScopedJson; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext}; + +#[derive(Clone, Copy)] +pub struct LookupHelper; + +impl HelperDef for LookupHelper { + fn call_inner<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + _: &'rc Context, + _: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + let collection_value = h + .param(0) + .ok_or_else(|| RenderError::new("Param not found for helper \"lookup\""))?; + let index = h + .param(1) + .ok_or_else(|| RenderError::new("Insufficient params for helper \"lookup\""))?; + + let value = match *collection_value.value() { + Json::Array(ref v) => index + .value() + .as_u64() + .and_then(|u| v.get(u as usize)) + .unwrap_or(&Json::Null), + Json::Object(ref m) => index + .value() + .as_str() + .and_then(|k| m.get(k)) + .unwrap_or(&Json::Null), + _ => &Json::Null, + }; + if r.strict_mode() && value.is_null() { + Err(RenderError::strict_error(None)) + } else { + Ok(value.clone().into()) + } + } +} + +pub static LOOKUP_HELPER: LookupHelper = LookupHelper; + +#[cfg(test)] +mod test { + use crate::registry::Registry; + + use std::collections::BTreeMap; + + #[test] + fn test_lookup() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#each v1}}{{lookup ../v2 @index}}{{/each}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#each v1}}{{lookup ../v2 1}}{{/each}}") + .is_ok()); + assert!(handlebars + .register_template_string("t2", "{{lookup kk \"a\"}}") + .is_ok()); + + let mut m: BTreeMap> = BTreeMap::new(); + m.insert("v1".to_string(), vec![1u16, 2u16, 3u16]); + m.insert("v2".to_string(), vec![9u16, 8u16, 7u16]); + + let m2 = btreemap! { + "kk".to_string() => btreemap!{"a".to_string() => "world".to_string()} + }; + + let r0 = handlebars.render("t0", &m); + assert_eq!(r0.ok().unwrap(), "987".to_string()); + + let r1 = handlebars.render("t1", &m); + assert_eq!(r1.ok().unwrap(), "888".to_string()); + + let r2 = handlebars.render("t2", &m2); + assert_eq!(r2.ok().unwrap(), "world".to_string()); + } + + #[test] + fn test_strict_lookup() { + let mut hbs = Registry::new(); + + assert_eq!( + hbs.render_template("{{lookup kk 1}}", &json!({"kk": []})) + .unwrap(), + "" + ); + + hbs.set_strict_mode(true); + + assert!(hbs + .render_template("{{lookup kk 1}}", &json!({"kk": []})) + .is_err()); + } +} diff --git a/vendor/handlebars/src/helpers/helper_raw.rs b/vendor/handlebars/src/helpers/helper_raw.rs new file mode 100644 index 000000000..55aef6bfc --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_raw.rs @@ -0,0 +1,44 @@ +use crate::context::Context; +use crate::helpers::{HelperDef, HelperResult}; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext, Renderable}; + +#[derive(Clone, Copy)] +pub struct RawHelper; + +impl HelperDef for RawHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + let tpl = h.template(); + if let Some(t) = tpl { + t.render(r, ctx, rc, out) + } else { + Ok(()) + } + } +} + +pub static RAW_HELPER: RawHelper = RawHelper; + +#[cfg(test)] +mod test { + use crate::registry::Registry; + + #[test] + fn test_raw_helper() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "a{{{{raw}}}}{{content}}{{else}}hello{{{{/raw}}}}") + .is_ok()); + + let r = handlebars.render("t0", &()); + assert_eq!(r.ok().unwrap(), "a{{content}}{{else}}hello"); + } +} diff --git a/vendor/handlebars/src/helpers/helper_with.rs b/vendor/handlebars/src/helpers/helper_with.rs new file mode 100644 index 000000000..c4d31cd0e --- /dev/null +++ b/vendor/handlebars/src/helpers/helper_with.rs @@ -0,0 +1,276 @@ +use super::block_util::create_block; +use crate::block::BlockParams; +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::{HelperDef, HelperResult}; +use crate::json::value::JsonTruthy; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext, Renderable}; + +#[derive(Clone, Copy)] +pub struct WithHelper; + +impl HelperDef for WithHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + let param = h + .param(0) + .ok_or_else(|| RenderError::new("Param not found for helper \"with\""))?; + + if param.value().is_truthy(false) { + let mut block = create_block(¶m); + + if let Some(block_param) = h.block_param() { + let mut params = BlockParams::new(); + if param.context_path().is_some() { + params.add_path(block_param, Vec::with_capacity(0))?; + } else { + params.add_value(block_param, param.value().clone())?; + } + + block.set_block_params(params); + } + + rc.push_block(block); + + if let Some(t) = h.template() { + t.render(r, ctx, rc, out)?; + }; + + rc.pop_block(); + Ok(()) + } else if let Some(t) = h.inverse() { + t.render(r, ctx, rc, out) + } else if r.strict_mode() { + Err(RenderError::strict_error(param.relative_path())) + } else { + Ok(()) + } + } +} + +pub static WITH_HELPER: WithHelper = WithHelper; + +#[cfg(test)] +mod test { + use crate::json::value::to_json; + use crate::registry::Registry; + + #[derive(Serialize)] + struct Address { + city: String, + country: String, + } + + #[derive(Serialize)] + struct Person { + name: String, + age: i16, + addr: Address, + titles: Vec, + } + + #[test] + fn test_with() { + let addr = Address { + city: "Beijing".to_string(), + country: "China".to_string(), + }; + + let person = Person { + name: "Ning Sun".to_string(), + age: 27, + addr, + titles: vec!["programmer".to_string(), "cartographier".to_string()], + }; + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#with addr}}{{city}}{{/with}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#with notfound}}hello{{else}}world{{/with}}") + .is_ok()); + assert!(handlebars + .register_template_string("t2", "{{#with addr/country}}{{this}}{{/with}}") + .is_ok()); + + let r0 = handlebars.render("t0", &person); + assert_eq!(r0.ok().unwrap(), "Beijing".to_string()); + + let r1 = handlebars.render("t1", &person); + assert_eq!(r1.ok().unwrap(), "world".to_string()); + + let r2 = handlebars.render("t2", &person); + assert_eq!(r2.ok().unwrap(), "China".to_string()); + } + + #[test] + fn test_with_block_param() { + let addr = Address { + city: "Beijing".to_string(), + country: "China".to_string(), + }; + + let person = Person { + name: "Ning Sun".to_string(), + age: 27, + addr, + titles: vec!["programmer".to_string(), "cartographier".to_string()], + }; + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#with addr as |a|}}{{a.city}}{{/with}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#with notfound as |c|}}hello{{else}}world{{/with}}") + .is_ok()); + assert!(handlebars + .register_template_string("t2", "{{#with addr/country as |t|}}{{t}}{{/with}}") + .is_ok()); + + let r0 = handlebars.render("t0", &person); + assert_eq!(r0.ok().unwrap(), "Beijing".to_string()); + + let r1 = handlebars.render("t1", &person); + assert_eq!(r1.ok().unwrap(), "world".to_string()); + + let r2 = handlebars.render("t2", &person); + assert_eq!(r2.ok().unwrap(), "China".to_string()); + } + + #[test] + fn test_with_in_each() { + let addr = Address { + city: "Beijing".to_string(), + country: "China".to_string(), + }; + + let person = Person { + name: "Ning Sun".to_string(), + age: 27, + addr, + titles: vec!["programmer".to_string(), "cartographier".to_string()], + }; + + let addr2 = Address { + city: "Beijing".to_string(), + country: "China".to_string(), + }; + + let person2 = Person { + name: "Ning Sun".to_string(), + age: 27, + addr: addr2, + titles: vec!["programmer".to_string(), "cartographier".to_string()], + }; + + let people = vec![person, person2]; + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string( + "t0", + "{{#each this}}{{#with addr}}{{city}}{{/with}}{{/each}}" + ) + .is_ok()); + assert!(handlebars + .register_template_string( + "t1", + "{{#each this}}{{#with addr}}{{../age}}{{/with}}{{/each}}" + ) + .is_ok()); + assert!(handlebars + .register_template_string( + "t2", + "{{#each this}}{{#with addr}}{{@../index}}{{/with}}{{/each}}" + ) + .is_ok()); + + let r0 = handlebars.render("t0", &people); + assert_eq!(r0.ok().unwrap(), "BeijingBeijing".to_string()); + + let r1 = handlebars.render("t1", &people); + assert_eq!(r1.ok().unwrap(), "2727".to_string()); + + let r2 = handlebars.render("t2", &people); + assert_eq!(r2.ok().unwrap(), "01".to_string()); + } + + #[test] + fn test_path_up() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{#with a}}{{#with b}}{{../../d}}{{/with}}{{/with}}") + .is_ok()); + let data = btreemap! { + "a".to_string() => to_json(&btreemap! { + "b".to_string() => vec![btreemap!{"c".to_string() => vec![1]}] + }), + "d".to_string() => to_json(1) + }; + + let r0 = handlebars.render("t0", &data); + assert_eq!(r0.ok().unwrap(), "1".to_string()); + } + + #[test] + fn test_else_context() { + let reg = Registry::new(); + let template = "{{#with list}}A{{else}}{{foo}}{{/with}}"; + let input = json!({"list": [], "foo": "bar"}); + let rendered = reg.render_template(template, &input).unwrap(); + assert_eq!("bar", rendered); + } + + #[test] + fn test_derived_value() { + let hb = Registry::new(); + let data = json!({"a": {"b": {"c": "d"}}}); + let template = "{{#with (lookup a.b \"c\")}}{{this}}{{/with}}"; + assert_eq!("d", hb.render_template(template, &data).unwrap()); + } + + #[test] + fn test_nested_derived_value() { + let hb = Registry::new(); + let data = json!({"a": {"b": {"c": "d"}}}); + let template = "{{#with (lookup a \"b\")}}{{#with this}}{{c}}{{/with}}{{/with}}"; + assert_eq!("d", hb.render_template(template, &data).unwrap()); + } + + #[test] + fn test_strict_with() { + let mut hb = Registry::new(); + + assert_eq!( + hb.render_template("{{#with name}}yes{{/with}}", &json!({})) + .unwrap(), + "" + ); + assert_eq!( + hb.render_template("{{#with name}}yes{{else}}no{{/with}}", &json!({})) + .unwrap(), + "no" + ); + + hb.set_strict_mode(true); + + assert!(hb + .render_template("{{#with name}}yes{{/with}}", &json!({})) + .is_err()); + assert_eq!( + hb.render_template("{{#with name}}yes{{else}}no{{/with}}", &json!({})) + .unwrap(), + "no" + ); + } +} diff --git a/vendor/handlebars/src/helpers/mod.rs b/vendor/handlebars/src/helpers/mod.rs new file mode 100644 index 000000000..bfd50c1f4 --- /dev/null +++ b/vendor/handlebars/src/helpers/mod.rs @@ -0,0 +1,291 @@ +use crate::context::Context; +use crate::error::RenderError; +use crate::json::value::ScopedJson; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{do_escape, Helper, RenderContext}; + +pub use self::helper_each::EACH_HELPER; +pub use self::helper_if::{IF_HELPER, UNLESS_HELPER}; +pub use self::helper_log::LOG_HELPER; +pub use self::helper_lookup::LOOKUP_HELPER; +pub use self::helper_raw::RAW_HELPER; +pub use self::helper_with::WITH_HELPER; + +/// A type alias for `Result<(), RenderError>` +pub type HelperResult = Result<(), RenderError>; + +/// Helper Definition +/// +/// Implement `HelperDef` to create custom helpers. You can retrieve useful information from these arguments. +/// +/// * `&Helper`: current helper template information, contains name, params, hashes and nested template +/// * `&Registry`: the global registry, you can find templates by name from registry +/// * `&Context`: the whole data to render, in most case you can use data from `Helper` +/// * `&mut RenderContext`: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail. +/// * `&mut dyn Output`: where you write output to +/// +/// By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement `HelperDef`. +/// +/// ## Define an inline helper +/// +/// ``` +/// use handlebars::*; +/// +/// fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc: &mut RenderContext<'_, '_>, out: &mut Output) +/// -> HelperResult { +/// // get parameter from helper or throw an error +/// let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or(""); +/// out.write(param.to_uppercase().as_ref())?; +/// Ok(()) +/// } +/// ``` +/// +/// ## Define block helper +/// +/// Block helper is like `#if` or `#each` which has a inner template and an optional *inverse* template (the template in else branch). You can access the inner template by `helper.template()` and `helper.inverse()`. In most cases you will just call `render` on it. +/// +/// ``` +/// use handlebars::*; +/// +/// fn dummy_block<'reg, 'rc>( +/// h: &Helper<'reg, 'rc>, +/// r: &'reg Handlebars<'reg>, +/// ctx: &'rc Context, +/// rc: &mut RenderContext<'reg, 'rc>, +/// out: &mut dyn Output, +/// ) -> HelperResult { +/// h.template() +/// .map(|t| t.render(r, ctx, rc, out)) +/// .unwrap_or(Ok(())) +/// } +/// ``` +/// +/// ## Define helper function using macro +/// +/// In most cases you just need some simple function to call from templates. We have a `handlebars_helper!` macro to simplify the job. +/// +/// ``` +/// use handlebars::*; +/// +/// handlebars_helper!(plus: |x: i64, y: i64| x + y); +/// +/// let mut hbs = Handlebars::new(); +/// hbs.register_helper("plus", Box::new(plus)); +/// ``` +/// +pub trait HelperDef { + /// A simplified api to define helper + /// + /// To implement your own `call_inner`, you will return a new `ScopedJson` + /// which has a JSON value computed from current context. + /// + /// ### Calling from subexpression + /// + /// When calling the helper as a subexpression, the value and its type can + /// be received by upper level helpers. + /// + /// Note that the value can be `json!(null)` which is treated as `false` in + /// helpers like `if` and rendered as empty string. + fn call_inner<'reg: 'rc, 'rc>( + &self, + _: &Helper<'reg, 'rc>, + _: &'reg Registry<'reg>, + _: &'rc Context, + _: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + Err(RenderError::unimplemented()) + } + + /// A complex version of helper interface. + /// + /// This function offers `Output`, which you can write custom string into + /// and render child template. Helpers like `if` and `each` are implemented + /// with this. Because the data written into `Output` are typically without + /// type information. So helpers defined by this function are not composable. + /// + /// ### Calling from subexpression + /// + /// Although helpers defined by this are not composable, when called from + /// subexpression, handlebars tries to parse the string output as JSON to + /// re-build its type. This can be buggy with numrical and other literal values. + /// So it is not recommended to use these helpers in subexpression. + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + match self.call_inner(h, r, ctx, rc) { + Ok(result) => { + if r.strict_mode() && result.is_missing() { + Err(RenderError::strict_error(None)) + } else { + // auto escape according to settings + let output = do_escape(r, rc, result.render()); + out.write(output.as_ref())?; + Ok(()) + } + } + Err(e) => { + if e.is_unimplemented() { + // default implementation, do nothing + Ok(()) + } else { + Err(e) + } + } + } + } +} + +/// implement HelperDef for bare function so we can use function as helper +impl< + F: for<'reg, 'rc> Fn( + &Helper<'reg, 'rc>, + &'reg Registry<'reg>, + &'rc Context, + &mut RenderContext<'reg, 'rc>, + &mut dyn Output, + ) -> HelperResult, + > HelperDef for F +{ + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> HelperResult { + (*self)(h, r, ctx, rc, out) + } +} + +mod block_util; +mod helper_each; +pub(crate) mod helper_extras; +mod helper_if; +mod helper_log; +mod helper_lookup; +mod helper_raw; +mod helper_with; +#[cfg(feature = "script_helper")] +pub(crate) mod scripting; + +// pub type HelperDef = for <'a, 'b, 'c> Fn<(&'a Context, &'b Helper, &'b Registry, &'c mut RenderContext), Result>; +// +// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result { +// h.template().unwrap().render(ctx, r, rc).unwrap() +// } +// +#[cfg(test)] +mod test { + use std::collections::BTreeMap; + + use crate::context::Context; + use crate::error::RenderError; + use crate::helpers::HelperDef; + use crate::json::value::JsonRender; + use crate::output::Output; + use crate::registry::Registry; + use crate::render::{Helper, RenderContext, Renderable}; + + #[derive(Clone, Copy)] + struct MetaHelper; + + impl HelperDef for MetaHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> Result<(), RenderError> { + let v = h.param(0).unwrap(); + + if !h.is_block() { + let output = format!("{}:{}", h.name(), v.value().render()); + out.write(output.as_ref())?; + } else { + let output = format!("{}:{}", h.name(), v.value().render()); + out.write(output.as_ref())?; + out.write("->")?; + h.template().unwrap().render(r, ctx, rc, out)?; + }; + Ok(()) + } + } + + #[test] + fn test_meta_helper() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{foo this}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{#bar this}}nice{{/bar}}") + .is_ok()); + + let meta_helper = MetaHelper; + handlebars.register_helper("helperMissing", Box::new(meta_helper)); + handlebars.register_helper("blockHelperMissing", Box::new(meta_helper)); + + let r0 = handlebars.render("t0", &true); + assert_eq!(r0.ok().unwrap(), "foo:true".to_string()); + + let r1 = handlebars.render("t1", &true); + assert_eq!(r1.ok().unwrap(), "bar:true->nice".to_string()); + } + + #[test] + fn test_helper_for_subexpression() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t2", "{{foo value=(bar 0)}}") + .is_ok()); + + handlebars.register_helper( + "helperMissing", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + let output = format!("{}{}", h.name(), h.param(0).unwrap().value()); + out.write(output.as_ref())?; + Ok(()) + }, + ), + ); + handlebars.register_helper( + "foo", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + let output = format!("{}", h.hash_get("value").unwrap().value().render()); + out.write(output.as_ref())?; + Ok(()) + }, + ), + ); + + let mut data = BTreeMap::new(); + // handlebars should never try to lookup this value because + // subexpressions are now resolved as string literal + data.insert("bar0".to_string(), true); + + let r2 = handlebars.render("t2", &data); + + assert_eq!(r2.ok().unwrap(), "bar0".to_string()); + } +} diff --git a/vendor/handlebars/src/helpers/scripting.rs b/vendor/handlebars/src/helpers/scripting.rs new file mode 100644 index 000000000..cec3b9763 --- /dev/null +++ b/vendor/handlebars/src/helpers/scripting.rs @@ -0,0 +1,111 @@ +use std::collections::{BTreeMap, HashMap}; + +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::HelperDef; +use crate::json::value::{PathAndJson, ScopedJson}; +use crate::registry::Registry; +use crate::render::{Helper, RenderContext}; + +use rhai::serde::{from_dynamic, to_dynamic}; +use rhai::{Dynamic, Engine, Scope, AST}; + +use serde_json::value::Value as Json; + +pub(crate) struct ScriptHelper { + pub(crate) script: AST, +} + +#[inline] +fn call_script_helper<'reg: 'rc, 'rc>( + params: &[PathAndJson<'reg, 'rc>], + hash: &BTreeMap<&'reg str, PathAndJson<'reg, 'rc>>, + engine: &Engine, + script: &AST, +) -> Result, RenderError> { + let params: Dynamic = to_dynamic(params.iter().map(|p| p.value()).collect::>())?; + + let hash: Dynamic = to_dynamic( + hash.iter() + .map(|(k, v)| ((*k).to_owned(), v.value())) + .collect::>(), + )?; + + let mut scope = Scope::new(); + scope.push_dynamic("params", params); + scope.push_dynamic("hash", hash); + + let result = engine + .eval_ast_with_scope::(&mut scope, script) + .map_err(RenderError::from)?; + + let result_json: Json = from_dynamic(&result)?; + + Ok(ScopedJson::Derived(result_json)) +} + +impl HelperDef for ScriptHelper { + fn call_inner<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + reg: &'reg Registry<'reg>, + _ctx: &'rc Context, + _rc: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + call_script_helper(h.params(), h.hash(), ®.engine, &self.script) + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::json::value::{PathAndJson, ScopedJson}; + use rhai::Engine; + + #[test] + fn test_dynamic_convert() { + let j0 = json! { + [{"name": "tomcat"}, {"name": "jetty"}] + }; + + let d0 = to_dynamic(&j0).unwrap(); + assert_eq!("array", d0.type_name()); + + let j1 = json!({ + "name": "tomcat", + "value": 4000, + }); + + let d1 = to_dynamic(&j1).unwrap(); + assert_eq!("map", d1.type_name()); + } + + #[test] + fn test_to_json() { + let d0 = Dynamic::from("tomcat".to_owned()); + + assert_eq!( + Json::String("tomcat".to_owned()), + from_dynamic::(&d0).unwrap() + ); + } + + #[test] + fn test_script_helper_value_access() { + let engine = Engine::new(); + + let script = "let plen = len(params); let p0 = params[0]; let hlen = len(hash); let hme = hash[\"me\"]; plen + \",\" + p0 + \",\" + hlen + \",\" + hme"; + let ast = engine.compile(&script).unwrap(); + + let params = vec![PathAndJson::new(None, ScopedJson::Derived(json!(true)))]; + let hash = btreemap! { + "me" => PathAndJson::new(None, ScopedJson::Derived(json!("no"))), + "you" => PathAndJson::new(None, ScopedJson::Derived(json!("yes"))), + }; + + let result = call_script_helper(¶ms, &hash, &engine, &ast) + .unwrap() + .render(); + assert_eq!("1,true,2,no", &result); + } +} diff --git a/vendor/handlebars/src/json/mod.rs b/vendor/handlebars/src/json/mod.rs new file mode 100644 index 000000000..85f783d0c --- /dev/null +++ b/vendor/handlebars/src/json/mod.rs @@ -0,0 +1,2 @@ +pub(crate) mod path; +pub(crate) mod value; diff --git a/vendor/handlebars/src/json/path.rs b/vendor/handlebars/src/json/path.rs new file mode 100644 index 000000000..8270371b2 --- /dev/null +++ b/vendor/handlebars/src/json/path.rs @@ -0,0 +1,138 @@ +use std::iter::Peekable; + +use pest::iterators::Pair; +use pest::Parser; + +use crate::error::RenderError; +use crate::grammar::{HandlebarsParser, Rule}; + +#[derive(PartialEq, Clone, Debug)] +pub enum PathSeg { + Named(String), + Ruled(Rule), +} + +/// Represents the Json path in templates. +/// +/// It can be either a local variable like `@first`, `../@index`, +/// or a normal relative path like `a/b/c`. +#[derive(PartialEq, Clone, Debug)] +pub enum Path { + Relative((Vec, String)), + Local((usize, String, String)), +} + +impl Path { + pub(crate) fn new(raw: &str, segs: Vec) -> Path { + if let Some((level, name)) = get_local_path_and_level(&segs) { + Path::Local((level, name, raw.to_owned())) + } else { + Path::Relative((segs, raw.to_owned())) + } + } + + pub fn parse(raw: &str) -> Result { + HandlebarsParser::parse(Rule::path, raw) + .map(|p| { + let parsed = p.flatten(); + let segs = parse_json_path_from_iter(&mut parsed.peekable(), raw.len()); + Ok(Path::new(raw, segs)) + }) + .map_err(|_| RenderError::new("Invalid JSON path"))? + } + + pub(crate) fn raw(&self) -> &str { + match self { + Path::Relative((_, ref raw)) => raw, + Path::Local((_, _, ref raw)) => raw, + } + } + + pub(crate) fn current() -> Path { + Path::Relative((Vec::with_capacity(0), "".to_owned())) + } + + // for test only + pub(crate) fn with_named_paths(name_segs: &[&str]) -> Path { + let segs = name_segs + .iter() + .map(|n| PathSeg::Named((*n).to_string())) + .collect(); + Path::Relative((segs, name_segs.join("/"))) + } + + // for test only + pub(crate) fn segs(&self) -> Option<&[PathSeg]> { + match self { + Path::Relative((segs, _)) => Some(segs), + _ => None, + } + } +} + +fn get_local_path_and_level(paths: &[PathSeg]) -> Option<(usize, String)> { + paths.get(0).and_then(|seg| { + if seg == &PathSeg::Ruled(Rule::path_local) { + let mut level = 0; + while paths.get(level + 1)? == &PathSeg::Ruled(Rule::path_up) { + level += 1; + } + if let Some(PathSeg::Named(name)) = paths.get(level + 1) { + Some((level, name.clone())) + } else { + None + } + } else { + None + } + }) +} + +pub(crate) fn parse_json_path_from_iter<'a, I>(it: &mut Peekable, limit: usize) -> Vec +where + I: Iterator>, +{ + let mut path_stack = Vec::with_capacity(5); + while let Some(n) = it.peek() { + let span = n.as_span(); + if span.end() > limit { + break; + } + + match n.as_rule() { + Rule::path_root => { + path_stack.push(PathSeg::Ruled(Rule::path_root)); + } + Rule::path_local => { + path_stack.push(PathSeg::Ruled(Rule::path_local)); + } + Rule::path_up => { + path_stack.push(PathSeg::Ruled(Rule::path_up)); + } + Rule::path_id | Rule::path_raw_id => { + let name = n.as_str(); + if name != "this" { + path_stack.push(PathSeg::Named(name.to_string())); + } + } + _ => {} + } + + it.next(); + } + + path_stack +} + +pub(crate) fn merge_json_path(path_stack: &mut Vec, relative_path: &[PathSeg]) { + for seg in relative_path { + match seg { + PathSeg::Named(ref s) => { + path_stack.push(s.to_owned()); + } + PathSeg::Ruled(Rule::path_root) => {} + PathSeg::Ruled(Rule::path_up) => {} + _ => {} + } + } +} diff --git a/vendor/handlebars/src/json/value.rs b/vendor/handlebars/src/json/value.rs new file mode 100644 index 000000000..863eab0b8 --- /dev/null +++ b/vendor/handlebars/src/json/value.rs @@ -0,0 +1,202 @@ +use serde::Serialize; +use serde_json::value::{to_value, Value as Json}; + +pub(crate) static DEFAULT_VALUE: Json = Json::Null; + +/// A JSON wrapper designed for handlebars internal use case +/// +/// * Constant: the JSON value hardcoded into template +/// * Context: the JSON value referenced in your provided data context +/// * Derived: the owned JSON value computed during rendering process +/// +#[derive(Debug)] +pub enum ScopedJson<'reg: 'rc, 'rc> { + Constant(&'reg Json), + Derived(Json), + // represents a json reference to context value, its full path + Context(&'rc Json, Vec), + Missing, +} + +impl<'reg: 'rc, 'rc> ScopedJson<'reg, 'rc> { + /// get the JSON reference + pub fn as_json(&self) -> &Json { + match self { + ScopedJson::Constant(j) => j, + ScopedJson::Derived(ref j) => j, + ScopedJson::Context(j, _) => j, + _ => &DEFAULT_VALUE, + } + } + + pub fn render(&self) -> String { + self.as_json().render() + } + + pub fn is_missing(&self) -> bool { + matches!(self, ScopedJson::Missing) + } + + pub fn into_derived(self) -> ScopedJson<'reg, 'rc> { + let v = self.as_json(); + ScopedJson::Derived(v.clone()) + } + + pub fn context_path(&self) -> Option<&Vec> { + match self { + ScopedJson::Context(_, ref p) => Some(p), + _ => None, + } + } +} + +impl<'reg: 'rc, 'rc> From for ScopedJson<'reg, 'rc> { + fn from(v: Json) -> ScopedJson<'reg, 'rc> { + ScopedJson::Derived(v) + } +} + +/// Json wrapper that holds the Json value and reference path information +/// +#[derive(Debug)] +pub struct PathAndJson<'reg, 'rc> { + relative_path: Option, + value: ScopedJson<'reg, 'rc>, +} + +impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc> { + pub fn new( + relative_path: Option, + value: ScopedJson<'reg, 'rc>, + ) -> PathAndJson<'reg, 'rc> { + PathAndJson { + relative_path, + value, + } + } + + /// Returns relative path when the value is referenced + /// If the value is from a literal, the path is `None` + pub fn relative_path(&self) -> Option<&String> { + self.relative_path.as_ref() + } + + /// Returns full path to this value if any + pub fn context_path(&self) -> Option<&Vec> { + self.value.context_path() + } + + /// Returns the value + pub fn value(&self) -> &Json { + self.value.as_json() + } + + /// Test if value is missing + pub fn is_value_missing(&self) -> bool { + self.value.is_missing() + } + + pub fn render(&self) -> String { + self.value.render() + } +} + +/// Render Json data with default format +pub trait JsonRender { + fn render(&self) -> String; +} + +pub trait JsonTruthy { + fn is_truthy(&self, include_zero: bool) -> bool; +} + +impl JsonRender for Json { + fn render(&self) -> String { + match *self { + Json::String(ref s) => s.to_string(), + Json::Bool(i) => i.to_string(), + Json::Number(ref n) => n.to_string(), + Json::Null => "".to_owned(), + Json::Array(ref a) => { + let mut buf = String::new(); + buf.push('['); + for i in a.iter() { + buf.push_str(i.render().as_ref()); + buf.push_str(", "); + } + buf.push(']'); + buf + } + Json::Object(_) => "[object]".to_owned(), + } + } +} + +/// Convert any serializable data into Serde Json type +pub fn to_json(src: T) -> Json +where + T: Serialize, +{ + to_value(src).unwrap_or_default() +} + +pub fn as_string(src: &Json) -> Option<&str> { + src.as_str() +} + +impl JsonTruthy for Json { + fn is_truthy(&self, include_zero: bool) -> bool { + match *self { + Json::Bool(ref i) => *i, + Json::Number(ref n) => { + if include_zero { + n.as_f64().map(|f| !f.is_nan()).unwrap_or(false) + } else { + // there is no inifity in json/serde_json + n.as_f64().map(|f| f.is_normal()).unwrap_or(false) + } + } + Json::Null => false, + Json::String(ref i) => !i.is_empty(), + Json::Array(ref i) => !i.is_empty(), + Json::Object(ref i) => !i.is_empty(), + } + } +} + +#[test] +fn test_json_render() { + let raw = "

Hello world

\n

"; + let thing = Json::String(raw.to_string()); + + assert_eq!(raw, thing.render()); +} + +#[test] +fn test_json_number_truthy() { + use std::f64; + assert!(json!(16i16).is_truthy(false)); + assert!(json!(16i16).is_truthy(true)); + + assert!(json!(0i16).is_truthy(true)); + assert!(!json!(0i16).is_truthy(false)); + + assert!(json!(1.0f64).is_truthy(false)); + assert!(json!(1.0f64).is_truthy(true)); + + assert!(json!(Some(16i16)).is_truthy(false)); + assert!(json!(Some(16i16)).is_truthy(true)); + + assert!(!json!(None as Option).is_truthy(false)); + assert!(!json!(None as Option).is_truthy(true)); + + assert!(!json!(f64::NAN).is_truthy(false)); + assert!(!json!(f64::NAN).is_truthy(true)); + + // there is no infinity in json/serde_json + // assert!(json!(f64::INFINITY).is_truthy(false)); + // assert!(json!(f64::INFINITY).is_truthy(true)); + + // assert!(json!(f64::NEG_INFINITY).is_truthy(false)); + // assert!(json!(f64::NEG_INFINITY).is_truthy(true)); +} diff --git a/vendor/handlebars/src/lib.rs b/vendor/handlebars/src/lib.rs new file mode 100644 index 000000000..7e0aac830 --- /dev/null +++ b/vendor/handlebars/src/lib.rs @@ -0,0 +1,417 @@ +#![doc(html_root_url = "https://docs.rs/handlebars/4.1.0")] +#![cfg_attr(docsrs, feature(doc_cfg))] +//! # Handlebars +//! +//! [Handlebars](http://handlebarsjs.com/) is a modern and extensible templating solution originally created in the JavaScript world. It's used by many popular frameworks like [Ember.js](http://emberjs.com) and Chaplin. It's also ported to some other platforms such as [Java](https://github.com/jknack/handlebars.java). +//! +//! And this is handlebars Rust implementation, designed for general purpose text generation. +//! +//! ## Quick Start +//! +//! ``` +//! use std::collections::BTreeMap; +//! use handlebars::Handlebars; +//! +//! fn main() { +//! // create the handlebars registry +//! let mut handlebars = Handlebars::new(); +//! +//! // register the template. The template string will be verified and compiled. +//! let source = "hello {{world}}"; +//! assert!(handlebars.register_template_string("t1", source).is_ok()); +//! +//! // Prepare some data. +//! // +//! // The data type should implements `serde::Serialize` +//! let mut data = BTreeMap::new(); +//! data.insert("world".to_string(), "世界!".to_string()); +//! assert_eq!(handlebars.render("t1", &data).unwrap(), "hello 世界!"); +//! } +//! ``` +//! +//! In this example, we created a template registry and registered a template named `t1`. +//! Then we rendered a `BTreeMap` with an entry of key `world`, the result is just what +//! we expected. +//! +//! I recommend you to walk through handlebars.js' [intro page](http://handlebarsjs.com) +//! if you are not quite familiar with the template language itself. +//! +//! ## Features +//! +//! Handlebars is a real-world templating system that you can use to build +//! your application without pain. +//! +//! ### Isolation of Rust and HTML +//! +//! This library doesn't attempt to use some macro magic to allow you to +//! write your template within your rust code. I admit that it's fun to do +//! that but it doesn't fit real-world use cases. +//! +//! ### Limited but essential control structures built-in +//! +//! Only essential control directives `if` and `each` are built-in. This +//! prevents you from putting too much application logic into your template. +//! +//! ### Extensible helper system +//! +//! Helper is the control system of handlebars language. In the original JavaScript +//! version, you can implement your own helper with JavaScript. +//! +//! Handlebars-rust offers similar mechanism that custom helper can be defined with +//! rust function, or [rhai](https://github.com/jonathandturner/rhai) script. +//! +//! The built-in helpers like `if` and `each` were written with these +//! helper APIs and the APIs are fully available to developers. +//! +//! ### Auto-reload in dev mode +//! +//! By turning on `dev_mode`, handlebars auto reloads any template and scripts that +//! loaded from files or directory. This can be handy for template development. +//! +//! ### Template inheritance +//! +//! Every time I look into a templating system, I will investigate its +//! support for [template inheritance][t]. +//! +//! [t]: https://docs.djangoproject.com/en/1.9/ref/templates/language/#template-inheritance +//! +//! Template include is not sufficient for template reuse. In most cases +//! you will need a skeleton of page as parent (header, footer, etc.), and +//! embed your page into this parent. +//! +//! You can find a real example of template inheritance in +//! `examples/partials.rs` and templates used by this file. +//! +//! ### Strict mode +//! +//! Handlebars, the language designed to work with JavaScript, has no +//! strict restriction on accessing nonexistent fields or indexes. It +//! generates empty strings for such cases. However, in Rust we want to be +//! a little stricter sometimes. +//! +//! By enabling `strict_mode` on handlebars: +//! +//! ``` +//! # use handlebars::Handlebars; +//! # let mut handlebars = Handlebars::new(); +//! handlebars.set_strict_mode(true); +//! ``` +//! +//! You will get a `RenderError` when accessing fields that do not exist. +//! +//! ## Limitations +//! +//! ### Compatibility with original JavaScript version +//! +//! This implementation is **not fully compatible** with the original JavaScript version. +//! +//! First of all, mustache blocks are not supported. I suggest you to use `#if` and `#each` for +//! the same functionality. +//! +//! There are some other minor features missing: +//! +//! * Chained else [#12](https://github.com/sunng87/handlebars-rust/issues/12) +//! +//! Feel free to file an issue on [github](https://github.com/sunng87/handlebars-rust/issues) if +//! you find missing features. +//! +//! ### Types +//! +//! As a static typed language, it's a little verbose to use handlebars. +//! Handlebars templating language is designed against JSON data type. In rust, +//! we will convert user's structs, vectors or maps into Serde-Json's `Value` type +//! in order to use in templates. You have to make sure your data implements the +//! `Serialize` trait from the [Serde](https://serde.rs) project. +//! +//! ## Usage +//! +//! ### Template Creation and Registration +//! +//! Templates are created from `String`s and registered to `Handlebars` with a name. +//! +//! ``` +//! # extern crate handlebars; +//! +//! use handlebars::Handlebars; +//! +//! # fn main() { +//! let mut handlebars = Handlebars::new(); +//! let source = "hello {{world}}"; +//! +//! assert!(handlebars.register_template_string("t1", source).is_ok()) +//! # } +//! ``` +//! +//! On registration, the template is parsed, compiled and cached in the registry. So further +//! usage will benefit from the one-time work. Also features like include, inheritance +//! that involves template reference requires you to register those template first with +//! a name so the registry can find it. +//! +//! If you template is small or just to experiment, you can use `render_template` API +//! without registration. +//! +//! ``` +//! # use std::error::Error; +//! use handlebars::Handlebars; +//! use std::collections::BTreeMap; +//! +//! # fn main() -> Result<(), Box> { +//! let mut handlebars = Handlebars::new(); +//! let source = "hello {{world}}"; +//! +//! let mut data = BTreeMap::new(); +//! data.insert("world".to_string(), "世界!".to_string()); +//! assert_eq!(handlebars.render_template(source, &data)?, "hello 世界!".to_owned()); +//! # Ok(()) +//! # } +//! ``` +//! +//! ### Rendering Something +//! +//! Since handlebars is originally based on JavaScript type system. It supports dynamic features like duck-typing, truthy/falsey values. But for a static language like Rust, this is a little difficult. As a solution, we are using the `serde_json::value::Value` internally for data rendering. +//! +//! That means, if you want to render something, you have to ensure the data type implements the `serde::Serialize` trait. Most rust internal types already have that trait. Use `#derive[Serialize]` for your types to generate default implementation. +//! +//! You can use default `render` function to render a template into `String`. From 0.9, there's `render_to_write` to render text into anything of `std::io::Write`. +//! +//! ``` +//! # use std::error::Error; +//! # #[macro_use] +//! # extern crate serde_derive; +//! # extern crate handlebars; +//! +//! use handlebars::Handlebars; +//! +//! #[derive(Serialize)] +//! struct Person { +//! name: String, +//! age: i16, +//! } +//! +//! # fn main() -> Result<(), Box> { +//! let source = "Hello, {{name}}"; +//! +//! let mut handlebars = Handlebars::new(); +//! assert!(handlebars.register_template_string("hello", source).is_ok()); +//! +//! +//! let data = Person { +//! name: "Ning Sun".to_string(), +//! age: 27 +//! }; +//! assert_eq!(handlebars.render("hello", &data)?, "Hello, Ning Sun".to_owned()); +//! # Ok(()) +//! # } +//! # +//! ``` +//! +//! Or if you don't need the template to be cached or referenced by other ones, you can +//! simply render it without registering. +//! +//! ``` +//! # use std::error::Error; +//! # #[macro_use] +//! # extern crate serde_derive; +//! # extern crate handlebars; +//! use handlebars::Handlebars; +//! # #[derive(Serialize)] +//! # struct Person { +//! # name: String, +//! # age: i16, +//! # } +//! +//! # fn main() -> Result<(), Box> { +//! let source = "Hello, {{name}}"; +//! +//! let mut handlebars = Handlebars::new(); +//! +//! let data = Person { +//! name: "Ning Sun".to_string(), +//! age: 27 +//! }; +//! assert_eq!(handlebars.render_template("Hello, {{name}}", &data)?, +//! "Hello, Ning Sun".to_owned()); +//! # Ok(()) +//! # } +//! ``` +//! +//! #### Escaping +//! +//! As per the handlebars spec, output using `{{expression}}` is escaped by default (to be precise, the characters `&"<>` are replaced by their respective html / xml entities). However, since the use cases of a rust template engine are probably a bit more diverse than those of a JavaScript one, this implementation allows the user to supply a custom escape function to be used instead. For more information see the `EscapeFn` type and `Handlebars::register_escape_fn()` method. In particular, `no_escape()` can be used as the escape function if no escaping at all should be performed. +//! +//! ### Custom Helper +//! +//! Handlebars is nothing without helpers. You can also create your own helpers with rust. Helpers in handlebars-rust are custom struct implements the `HelperDef` trait, concretely, the `call` function. For your convenience, most of stateless helpers can be implemented as bare functions. +//! +//! ``` +//! use std::io::Write; +//! # use std::error::Error; +//! use handlebars::{Handlebars, HelperDef, RenderContext, Helper, Context, JsonRender, HelperResult, Output, RenderError}; +//! +//! // implement by a structure impls HelperDef +//! #[derive(Clone, Copy)] +//! struct SimpleHelper; +//! +//! impl HelperDef for SimpleHelper { +//! fn call<'reg: 'rc, 'rc>(&self, h: &Helper, _: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output) -> HelperResult { +//! let param = h.param(0).unwrap(); +//! +//! out.write("1st helper: ")?; +//! out.write(param.value().render().as_ref())?; +//! Ok(()) +//! } +//! } +//! +//! // implement via bare function +//! fn another_simple_helper (h: &Helper, _: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output) -> HelperResult { +//! let param = h.param(0).unwrap(); +//! +//! out.write("2nd helper: ")?; +//! out.write(param.value().render().as_ref())?; +//! Ok(()) +//! } +//! +//! +//! # fn main() -> Result<(), Box> { +//! let mut handlebars = Handlebars::new(); +//! handlebars.register_helper("simple-helper", Box::new(SimpleHelper)); +//! handlebars.register_helper("another-simple-helper", Box::new(another_simple_helper)); +//! // via closure +//! handlebars.register_helper("closure-helper", +//! Box::new(|h: &Helper, r: &Handlebars, _: &Context, rc: &mut RenderContext, out: &mut dyn Output| -> HelperResult { +//! let param = h.param(0).ok_or(RenderError::new("param not found"))?; +//! +//! out.write("3rd helper: ")?; +//! out.write(param.value().render().as_ref())?; +//! Ok(()) +//! })); +//! +//! let tpl = "{{simple-helper 1}}\n{{another-simple-helper 2}}\n{{closure-helper 3}}"; +//! assert_eq!(handlebars.render_template(tpl, &())?, +//! "1st helper: 1\n2nd helper: 2\n3rd helper: 3".to_owned()); +//! # Ok(()) +//! # } +//! +//! ``` +//! +//! Data available to helper can be found in [Helper](struct.Helper.html). And there are more +//! examples in [HelperDef](trait.HelperDef.html) page. +//! +//! You can learn more about helpers by looking into source code of built-in helpers. +//! +//! +//! ### Script Helper +//! +//! Like our JavaScript counterparts, handlebars allows user to define simple helpers with +//! a scripting language, [rhai](https://docs.rs/crate/rhai/). This can be enabled by +//! turning on `script_helper` feature flag. +//! +//! A sample script: +//! +//! ```handlebars +//! {{percent 0.34 label="%"}} +//! ``` +//! +//! ```rhai +//! // percent.rhai +//! // get first parameter from `params` array +//! let value = params[0]; +//! // get key value pair `label` from `hash` map +//! let label = hash["label"]; +//! +//! // compute the final string presentation +//! (value * 100).to_string() + label +//! ``` +//! +//! A runnable [example](https://github.com/sunng87/handlebars-rust/blob/master/examples/script.rs) can be find in the repo. +//! +//! #### Built-in Helpers +//! +//! * `{{{{raw}}}} ... {{{{/raw}}}}` escape handlebars expression within the block +//! * `{{#if ...}} ... {{else}} ... {{/if}}` if-else block +//! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#if) on how to use this helper.) +//! * `{{#unless ...}} ... {{else}} .. {{/unless}}` if-not-else block +//! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#unless) on how to use this helper.) +//! * `{{#each ...}} ... {{/each}}` iterates over an array or object. Handlebars-rust doesn't support mustache iteration syntax so use `each` instead. +//! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#each) on how to use this helper.) +//! * `{{#with ...}} ... {{/with}}` change current context. Similar to `{{#each}}`, used for replace corresponding mustache syntax. +//! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#with) on how to use this helper.) +//! * `{{lookup ... ...}}` get value from array by `@index` or `@key` +//! (See [the handlebarjs documentation](https://handlebarsjs.com/guide/builtin-helpers.html#lookup) on how to use this helper.) +//! * `{{> ...}}` include template by its name +//! * `{{log ...}}` log value with rust logger, default level: INFO. Currently you cannot change the level. +//! * Boolean helpers that can be used in `if` as subexpression, for example `{{#if (gt 2 1)}} ...`: +//! * `eq` +//! * `ne` +//! * `gt` +//! * `gte` +//! * `lt` +//! * `lte` +//! * `and` +//! * `or` +//! * `not` +//! * `{{len ...}}` returns length of array/object/string +//! +//! ### Template inheritance +//! +//! Handlebars.js' partial system is fully supported in this implementation. +//! Check [example](https://github.com/sunng87/handlebars-rust/blob/master/examples/partials.rs#L49) for details. +//! +//! + +#![allow(dead_code, clippy::upper_case_acronyms)] +#![warn(rust_2018_idioms)] +#![recursion_limit = "200"] + +#[cfg(not(feature = "no_logging"))] +#[macro_use] +extern crate log; + +#[cfg(test)] +#[macro_use] +extern crate maplit; +#[macro_use] +extern crate pest_derive; +#[macro_use] +extern crate quick_error; +#[cfg(test)] +#[macro_use] +extern crate serde_derive; + +#[allow(unused_imports)] +#[macro_use] +extern crate serde_json; + +pub use self::block::{BlockContext, BlockParams}; +pub use self::context::Context; +pub use self::decorators::DecoratorDef; +pub use self::error::{RenderError, TemplateError}; +pub use self::helpers::{HelperDef, HelperResult}; +pub use self::json::path::Path; +pub use self::json::value::{to_json, JsonRender, PathAndJson, ScopedJson}; +pub use self::output::{Output, StringOutput}; +pub use self::registry::{html_escape, no_escape, EscapeFn, Registry as Handlebars}; +pub use self::render::{Decorator, Evaluable, Helper, RenderContext, Renderable}; +pub use self::template::Template; + +#[doc(hidden)] +pub use self::serde_json::Value as JsonValue; + +#[macro_use] +mod macros; +mod block; +mod context; +mod decorators; +mod error; +mod grammar; +mod helpers; +mod json; +mod local_vars; +mod output; +mod partial; +mod registry; +mod render; +mod sources; +mod support; +pub mod template; +mod util; diff --git a/vendor/handlebars/src/local_vars.rs b/vendor/handlebars/src/local_vars.rs new file mode 100644 index 000000000..2a34b1f16 --- /dev/null +++ b/vendor/handlebars/src/local_vars.rs @@ -0,0 +1,37 @@ +use std::collections::BTreeMap; + +use serde_json::value::Value as Json; + +#[derive(Default, Debug, Clone)] +pub(crate) struct LocalVars { + first: Option, + last: Option, + index: Option, + key: Option, + + extra: BTreeMap, +} + +impl LocalVars { + pub fn put(&mut self, key: &str, value: Json) { + match key { + "first" => self.first = Some(value), + "last" => self.last = Some(value), + "index" => self.index = Some(value), + "key" => self.key = Some(value), + _ => { + self.extra.insert(key.to_owned(), value); + } + } + } + + pub fn get(&self, key: &str) -> Option<&Json> { + match key { + "first" => self.first.as_ref(), + "last" => self.last.as_ref(), + "index" => self.index.as_ref(), + "key" => self.key.as_ref(), + _ => self.extra.get(key), + } + } +} diff --git a/vendor/handlebars/src/macros.rs b/vendor/handlebars/src/macros.rs new file mode 100644 index 000000000..14cb0152c --- /dev/null +++ b/vendor/handlebars/src/macros.rs @@ -0,0 +1,185 @@ +/// Macro that allows you to quickly define a handlebars helper by passing a +/// name and a closure. +/// +/// There are several types of arguments available to closure: +/// +/// * Parameters are mapped to closure arguments one by one. Any declared +/// parameters are required +/// * Hash are mapped as named arguments and declared in a bracket block. +/// All named arguments are optional so default value is required. +/// * An optional `*args` provides a vector of all helper parameters. +/// * An optional `**kwargs` provides a map of all helper hash. +/// +/// # Examples +/// +/// ```rust +/// #[macro_use] extern crate handlebars; +/// #[macro_use] extern crate serde_json; +/// +/// handlebars_helper!(is_above_10: |x: u64| x > 10); +/// handlebars_helper!(is_above: |x: u64, { compare: u64 = 10 }| x > compare); +/// +/// # fn main() { +/// # +/// let mut handlebars = handlebars::Handlebars::new(); +/// handlebars.register_helper("is-above-10", Box::new(is_above_10)); +/// handlebars.register_helper("is-above", Box::new(is_above)); +/// +/// let result = handlebars +/// .render_template("{{#if (is-above-10 12)}}great!{{else}}okay{{/if}}", &json!({})) +/// .unwrap(); +/// assert_eq!(&result, "great!"); +/// let result2 = handlebars +/// .render_template("{{#if (is-above 12 compare=10)}}great!{{else}}okay{{/if}}", &json!({})) +/// .unwrap(); +/// assert_eq!(&result2, "great!"); +/// # } +/// ``` + +#[macro_export] +macro_rules! handlebars_helper { + ($struct_name:ident: |$($name:ident: $tpe:tt),* + $($(,)?{$($hash_name:ident: $hash_tpe:tt=$dft_val:literal),*})? + $($(,)?*$args:ident)? + $($(,)?**$kwargs:ident)?| + $body:expr ) => { + #[allow(non_camel_case_types)] + pub struct $struct_name; + + impl $crate::HelperDef for $struct_name { + #[allow(unused_assignments)] + fn call_inner<'reg: 'rc, 'rc>( + &self, + h: &$crate::Helper<'reg, 'rc>, + r: &'reg $crate::Handlebars<'reg>, + _: &'rc $crate::Context, + _: &mut $crate::RenderContext<'reg, 'rc>, + ) -> Result<$crate::ScopedJson<'reg, 'rc>, $crate::RenderError> { + let mut param_idx = 0; + + $( + let $name = h.param(param_idx) + .and_then(|x| { + if r.strict_mode() && x.is_value_missing() { + None + } else { + Some(x.value()) + } + }) + .ok_or_else(|| $crate::RenderError::new(&format!( + "`{}` helper: Couldn't read parameter {}", + stringify!($struct_name), stringify!($name), + ))) + .and_then(|x| + handlebars_helper!(@as_json_value x, $tpe) + .ok_or_else(|| $crate::RenderError::new(&format!( + "`{}` helper: Couldn't convert parameter {} to type `{}`. \ + It's {:?} as JSON. Got these params: {:?}", + stringify!($struct_name), stringify!($name), stringify!($tpe), + x, h.params(), + ))) + )?; + param_idx += 1; + )* + + $( + $( + let $hash_name = h.hash_get(stringify!($hash_name)) + .map(|x| x.value()) + .map(|x| + handlebars_helper!(@as_json_value x, $hash_tpe) + .ok_or_else(|| $crate::RenderError::new(&format!( + "`{}` helper: Couldn't convert hash {} to type `{}`. \ + It's {:?} as JSON. Got these hash: {:?}", + stringify!($struct_name), stringify!($hash_name), stringify!($hash_tpe), + x, h.hash(), + ))) + ) + .unwrap_or_else(|| Ok($dft_val))?; + )* + )? + + $(let $args = h.params().iter().map(|x| x.value()).collect::>();)? + $(let $kwargs = h.hash().iter().map(|(k, v)| (k.to_owned(), v.value())).collect::>();)? + + let result = $body; + Ok($crate::ScopedJson::Derived($crate::JsonValue::from(result))) + } + } + }; + + (@as_json_value $x:ident, object) => { $x.as_object() }; + (@as_json_value $x:ident, array) => { $x.as_array() }; + (@as_json_value $x:ident, str) => { $x.as_str() }; + (@as_json_value $x:ident, i64) => { $x.as_i64() }; + (@as_json_value $x:ident, u64) => { $x.as_u64() }; + (@as_json_value $x:ident, f64) => { $x.as_f64() }; + (@as_json_value $x:ident, bool) => { $x.as_bool() }; + (@as_json_value $x:ident, null) => { $x.as_null() }; + (@as_json_value $x:ident, Json) => { Some($x) }; +} + +#[cfg(feature = "no_logging")] +#[macro_use] +#[doc(hidden)] +pub mod logging { + /// This macro is defined if the `logging` feature is set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! debug { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } + + /// This macro is defined if the `logging` feature is not set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! error { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } + + /// This macro is defined if the `logging` feature is not set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! info { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } + + /// This macro is defined if the `logging` feature is not set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! log { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } + + /// This macro is defined if the `logging` feature is not set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! trace { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } + + /// This macro is defined if the `logging` feature is not set. + /// + /// It ignores all logging calls inside the library. + #[doc(hidden)] + #[macro_export] + macro_rules! warn { + (target: $target:expr, $($arg:tt)*) => {}; + ($($arg:tt)*) => {}; + } +} diff --git a/vendor/handlebars/src/output.rs b/vendor/handlebars/src/output.rs new file mode 100644 index 000000000..f1c5865a5 --- /dev/null +++ b/vendor/handlebars/src/output.rs @@ -0,0 +1,48 @@ +use std::io::{Error as IOError, Write}; +use std::string::FromUtf8Error; + +/// The Output API. +/// +/// Handlebars uses this trait to define rendered output. +pub trait Output { + fn write(&mut self, seg: &str) -> Result<(), IOError>; +} + +pub struct WriteOutput { + write: W, +} + +impl Output for WriteOutput { + fn write(&mut self, seg: &str) -> Result<(), IOError> { + self.write.write_all(seg.as_bytes()) + } +} + +impl WriteOutput { + pub fn new(write: W) -> WriteOutput { + WriteOutput { write } + } +} + +pub struct StringOutput { + buf: Vec, +} + +impl Output for StringOutput { + fn write(&mut self, seg: &str) -> Result<(), IOError> { + self.buf.extend_from_slice(seg.as_bytes()); + Ok(()) + } +} + +impl StringOutput { + pub fn new() -> StringOutput { + StringOutput { + buf: Vec::with_capacity(8 * 1024), + } + } + + pub fn into_string(self) -> Result { + String::from_utf8(self.buf) + } +} diff --git a/vendor/handlebars/src/partial.rs b/vendor/handlebars/src/partial.rs new file mode 100644 index 000000000..a472d5d14 --- /dev/null +++ b/vendor/handlebars/src/partial.rs @@ -0,0 +1,333 @@ +use std::borrow::Cow; +use std::collections::HashMap; + +use serde_json::value::Value as Json; + +use crate::block::BlockContext; +use crate::context::{merge_json, Context}; +use crate::error::RenderError; +use crate::json::path::Path; +use crate::output::Output; +use crate::registry::Registry; +use crate::render::{Decorator, Evaluable, RenderContext, Renderable}; +use crate::template::Template; + +pub(crate) const PARTIAL_BLOCK: &str = "@partial-block"; + +fn find_partial<'reg: 'rc, 'rc: 'a, 'a>( + rc: &'a RenderContext<'reg, 'rc>, + r: &'reg Registry<'reg>, + d: &Decorator<'reg, 'rc>, + name: &str, +) -> Result>, RenderError> { + if let Some(ref partial) = rc.get_partial(name) { + return Ok(Some(Cow::Borrowed(partial))); + } + + if let Some(tpl) = r.get_or_load_template_optional(name) { + return tpl.map(Option::Some); + } + + if let Some(tpl) = d.template() { + return Ok(Some(Cow::Borrowed(tpl))); + } + + Ok(None) +} + +pub fn expand_partial<'reg: 'rc, 'rc>( + d: &Decorator<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, +) -> Result<(), RenderError> { + // try eval inline partials first + if let Some(t) = d.template() { + t.eval(r, ctx, rc)?; + } + + let tname = d.name(); + if rc.is_current_template(tname) { + return Err(RenderError::new("Cannot include self in >")); + } + + // if tname == PARTIAL_BLOCK + let partial = find_partial(rc, r, d, tname)?; + + if let Some(t) = partial { + // clone to avoid lifetime issue + // FIXME refactor this to avoid + let mut local_rc = rc.clone(); + let is_partial_block = tname == PARTIAL_BLOCK; + + if is_partial_block { + local_rc.inc_partial_block_depth(); + } + + let mut block_created = false; + + if let Some(ref base_path) = d.param(0).and_then(|p| p.context_path()) { + // path given, update base_path + let mut block = BlockContext::new(); + *block.base_path_mut() = base_path.to_vec(); + block_created = true; + local_rc.push_block(block); + } else if !d.hash().is_empty() { + let mut block = BlockContext::new(); + // hash given, update base_value + let hash_ctx = d + .hash() + .iter() + .map(|(k, v)| (*k, v.value())) + .collect::>(); + + let merged_context = merge_json( + local_rc.evaluate2(ctx, &Path::current())?.as_json(), + &hash_ctx, + ); + block.set_base_value(merged_context); + block_created = true; + local_rc.push_block(block); + } + + // @partial-block + if let Some(pb) = d.template() { + local_rc.push_partial_block(pb); + } + + let result = t.render(r, ctx, &mut local_rc, out); + + // cleanup + if block_created { + local_rc.pop_block(); + } + + if is_partial_block { + local_rc.dec_partial_block_depth(); + } + + if d.template().is_some() { + local_rc.pop_partial_block(); + } + + result + } else { + Ok(()) + } +} + +#[cfg(test)] +mod test { + use crate::context::Context; + use crate::error::RenderError; + use crate::output::Output; + use crate::registry::Registry; + use crate::render::{Helper, RenderContext}; + + #[test] + fn test() { + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("t0", "{{> t1}}") + .is_ok()); + assert!(handlebars + .register_template_string("t1", "{{this}}") + .is_ok()); + assert!(handlebars + .register_template_string("t2", "{{#> t99}}not there{{/t99}}") + .is_ok()); + assert!(handlebars + .register_template_string("t3", "{{#*inline \"t31\"}}{{this}}{{/inline}}{{> t31}}") + .is_ok()); + assert!(handlebars + .register_template_string( + "t4", + "{{#> t5}}{{#*inline \"nav\"}}navbar{{/inline}}{{/t5}}" + ) + .is_ok()); + assert!(handlebars + .register_template_string("t5", "include {{> nav}}") + .is_ok()); + assert!(handlebars + .register_template_string("t6", "{{> t1 a}}") + .is_ok()); + assert!(handlebars + .register_template_string( + "t7", + "{{#*inline \"t71\"}}{{a}}{{/inline}}{{> t71 a=\"world\"}}" + ) + .is_ok()); + assert!(handlebars.register_template_string("t8", "{{a}}").is_ok()); + assert!(handlebars + .register_template_string("t9", "{{> t8 a=2}}") + .is_ok()); + + assert_eq!(handlebars.render("t0", &1).ok().unwrap(), "1".to_string()); + assert_eq!( + handlebars.render("t2", &1).ok().unwrap(), + "not there".to_string() + ); + assert_eq!(handlebars.render("t3", &1).ok().unwrap(), "1".to_string()); + assert_eq!( + handlebars.render("t4", &1).ok().unwrap(), + "include navbar".to_string() + ); + assert_eq!( + handlebars + .render("t6", &btreemap! {"a".to_string() => "2".to_string()}) + .ok() + .unwrap(), + "2".to_string() + ); + assert_eq!( + handlebars.render("t7", &1).ok().unwrap(), + "world".to_string() + ); + assert_eq!(handlebars.render("t9", &1).ok().unwrap(), "2".to_string()); + } + + #[test] + fn test_include_partial_block() { + let t0 = "hello {{> @partial-block}}"; + let t1 = "{{#> t0}}inner {{this}}{{/t0}}"; + + let mut handlebars = Registry::new(); + assert!(handlebars.register_template_string("t0", t0).is_ok()); + assert!(handlebars.register_template_string("t1", t1).is_ok()); + + let r0 = handlebars.render("t1", &true); + assert_eq!(r0.ok().unwrap(), "hello inner true".to_string()); + } + + #[test] + fn test_self_inclusion() { + let t0 = "hello {{> t1}} {{> t0}}"; + let t1 = "some template"; + let mut handlebars = Registry::new(); + assert!(handlebars.register_template_string("t0", t0).is_ok()); + assert!(handlebars.register_template_string("t1", t1).is_ok()); + + let r0 = handlebars.render("t0", &true); + assert!(r0.is_err()); + } + + #[test] + fn test_issue_143() { + let main_template = "one{{> two }}three{{> two }}"; + let two_partial = "--- two ---"; + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("template", main_template) + .is_ok()); + assert!(handlebars + .register_template_string("two", two_partial) + .is_ok()); + + let r0 = handlebars.render("template", &true); + assert_eq!(r0.ok().unwrap(), "one--- two ---three--- two ---"); + } + + #[test] + fn test_hash_context_outscope() { + let main_template = "In: {{> p a=2}} Out: {{a}}"; + let p_partial = "{{a}}"; + + let mut handlebars = Registry::new(); + assert!(handlebars + .register_template_string("template", main_template) + .is_ok()); + assert!(handlebars.register_template_string("p", p_partial).is_ok()); + + let r0 = handlebars.render("template", &true); + assert_eq!(r0.ok().unwrap(), "In: 2 Out: "); + } + + #[test] + fn test_partial_context_hash() { + let mut hbs = Registry::new(); + hbs.register_template_string("one", "This is a test. {{> two name=\"fred\" }}") + .unwrap(); + hbs.register_template_string("two", "Lets test {{name}}") + .unwrap(); + assert_eq!( + "This is a test. Lets test fred", + hbs.render("one", &0).unwrap() + ); + } + + #[test] + fn test_partial_subexpression_context_hash() { + let mut hbs = Registry::new(); + hbs.register_template_string("one", "This is a test. {{> (x @root) name=\"fred\" }}") + .unwrap(); + hbs.register_template_string("two", "Lets test {{name}}") + .unwrap(); + + hbs.register_helper( + "x", + Box::new( + |_: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + out.write("two")?; + Ok(()) + }, + ), + ); + assert_eq!( + "This is a test. Lets test fred", + hbs.render("one", &0).unwrap() + ); + } + + #[test] + fn test_nested_partial_scope() { + let t = "{{#*inline \"pp\"}}{{a}} {{b}}{{/inline}}{{#each c}}{{> pp a=2}}{{/each}}"; + let data = json!({"c": [{"b": true}, {"b": false}]}); + + let mut handlebars = Registry::new(); + assert!(handlebars.register_template_string("t", t).is_ok()); + let r0 = handlebars.render("t", &data); + assert_eq!(r0.ok().unwrap(), "2 true2 false"); + } + + #[test] + fn test_nested_partials() { + let mut handlebars = Registry::new(); + let template1 = "{{> @partial-block }}"; + let template2 = "{{#> t1 }}{{> @partial-block }}{{/ t1 }}"; + let template3 = "{{#> t2 }}Hello{{/ t2 }}"; + + handlebars + .register_template_string("t1", &template1) + .unwrap(); + handlebars + .register_template_string("t2", &template2) + .unwrap(); + + let page = handlebars.render_template(&template3, &json!({})).unwrap(); + assert_eq!("Hello", page); + } + + #[test] + fn test_up_to_partial_level() { + let outer = r#"{{>inner name="fruit:" vegetables=fruits}}"#; + let inner = "{{#each vegetables}}{{../name}} {{this}},{{/each}}"; + + let data = json!({ "fruits": ["carrot", "tomato"] }); + + let mut handlebars = Registry::new(); + handlebars.register_template_string("outer", outer).unwrap(); + handlebars.register_template_string("inner", inner).unwrap(); + + assert_eq!( + handlebars.render("outer", &data).unwrap(), + "fruit: carrot,fruit: tomato," + ); + } +} diff --git a/vendor/handlebars/src/registry.rs b/vendor/handlebars/src/registry.rs new file mode 100644 index 000000000..e7f5f1cfd --- /dev/null +++ b/vendor/handlebars/src/registry.rs @@ -0,0 +1,1092 @@ +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt::{self, Debug, Formatter}; +use std::io::{Error as IoError, Write}; +use std::path::Path; +use std::sync::Arc; + +use serde::Serialize; + +use crate::context::Context; +use crate::decorators::{self, DecoratorDef}; +#[cfg(feature = "script_helper")] +use crate::error::ScriptError; +use crate::error::{RenderError, TemplateError}; +use crate::helpers::{self, HelperDef}; +use crate::output::{Output, StringOutput, WriteOutput}; +use crate::render::{RenderContext, Renderable}; +use crate::sources::{FileSource, Source}; +use crate::support::str::{self, StringWriter}; +use crate::template::Template; + +#[cfg(feature = "dir_source")] +use std::path; +#[cfg(feature = "dir_source")] +use walkdir::{DirEntry, WalkDir}; + +#[cfg(feature = "script_helper")] +use rhai::Engine; + +#[cfg(feature = "script_helper")] +use crate::helpers::scripting::ScriptHelper; + +/// This type represents an *escape fn*, that is a function whose purpose it is +/// to escape potentially problematic characters in a string. +/// +/// An *escape fn* is represented as a `Box` to avoid unnecessary type +/// parameters (and because traits cannot be aliased using `type`). +pub type EscapeFn = Arc String + Send + Sync>; + +/// The default *escape fn* replaces the characters `&"<>` +/// with the equivalent html / xml entities. +pub fn html_escape(data: &str) -> String { + str::escape_html(data) +} + +/// `EscapeFn` that does not change anything. Useful when using in a non-html +/// environment. +pub fn no_escape(data: &str) -> String { + data.to_owned() +} + +/// The single entry point of your Handlebars templates +/// +/// It maintains compiled templates and registered helpers. +#[derive(Clone)] +pub struct Registry<'reg> { + templates: HashMap, + + helpers: HashMap>, + decorators: HashMap>, + + escape_fn: EscapeFn, + strict_mode: bool, + dev_mode: bool, + #[cfg(feature = "script_helper")] + pub(crate) engine: Arc, + + template_sources: + HashMap + Send + Sync + 'reg>>, + #[cfg(feature = "script_helper")] + script_sources: + HashMap + Send + Sync + 'reg>>, +} + +impl<'reg> Debug for Registry<'reg> { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> { + f.debug_struct("Handlebars") + .field("templates", &self.templates) + .field("helpers", &self.helpers.keys()) + .field("decorators", &self.decorators.keys()) + .field("strict_mode", &self.strict_mode) + .field("dev_mode", &self.dev_mode) + .finish() + } +} + +impl<'reg> Default for Registry<'reg> { + fn default() -> Self { + Self::new() + } +} + +#[cfg(feature = "dir_source")] +fn filter_file(entry: &DirEntry, suffix: &str) -> bool { + let path = entry.path(); + + // ignore hidden files, emacs buffers and files with wrong suffix + !path.is_file() + || path + .file_name() + .map(|s| { + let ds = s.to_string_lossy(); + ds.starts_with('.') || ds.starts_with('#') || !ds.ends_with(suffix) + }) + .unwrap_or(true) +} + +#[cfg(feature = "script_helper")] +fn rhai_engine() -> Engine { + Engine::new() +} + +impl<'reg> Registry<'reg> { + pub fn new() -> Registry<'reg> { + let r = Registry { + templates: HashMap::new(), + template_sources: HashMap::new(), + helpers: HashMap::new(), + decorators: HashMap::new(), + escape_fn: Arc::new(html_escape), + strict_mode: false, + dev_mode: false, + #[cfg(feature = "script_helper")] + engine: Arc::new(rhai_engine()), + #[cfg(feature = "script_helper")] + script_sources: HashMap::new(), + }; + + r.setup_builtins() + } + + fn setup_builtins(mut self) -> Registry<'reg> { + self.register_helper("if", Box::new(helpers::IF_HELPER)); + self.register_helper("unless", Box::new(helpers::UNLESS_HELPER)); + self.register_helper("each", Box::new(helpers::EACH_HELPER)); + self.register_helper("with", Box::new(helpers::WITH_HELPER)); + self.register_helper("lookup", Box::new(helpers::LOOKUP_HELPER)); + self.register_helper("raw", Box::new(helpers::RAW_HELPER)); + self.register_helper("log", Box::new(helpers::LOG_HELPER)); + + self.register_helper("eq", Box::new(helpers::helper_extras::eq)); + self.register_helper("ne", Box::new(helpers::helper_extras::ne)); + self.register_helper("gt", Box::new(helpers::helper_extras::gt)); + self.register_helper("gte", Box::new(helpers::helper_extras::gte)); + self.register_helper("lt", Box::new(helpers::helper_extras::lt)); + self.register_helper("lte", Box::new(helpers::helper_extras::lte)); + self.register_helper("and", Box::new(helpers::helper_extras::and)); + self.register_helper("or", Box::new(helpers::helper_extras::or)); + self.register_helper("not", Box::new(helpers::helper_extras::not)); + self.register_helper("len", Box::new(helpers::helper_extras::len)); + + self.register_decorator("inline", Box::new(decorators::INLINE_DECORATOR)); + self + } + + /// Enable or disable handlebars strict mode + /// + /// By default, handlebars renders empty string for value that + /// undefined or never exists. Since rust is a static type + /// language, we offer strict mode in handlebars-rust. In strict + /// mode, if you were to render a value that doesn't exist, a + /// `RenderError` will be raised. + pub fn set_strict_mode(&mut self, enabled: bool) { + self.strict_mode = enabled; + } + + /// Return strict mode state, default is false. + /// + /// By default, handlebars renders empty string for value that + /// undefined or never exists. Since rust is a static type + /// language, we offer strict mode in handlebars-rust. In strict + /// mode, if you were access a value that doesn't exist, a + /// `RenderError` will be raised. + pub fn strict_mode(&self) -> bool { + self.strict_mode + } + + /// Return dev mode state, default is false + /// + /// With dev mode turned on, handlebars enables a set of development + /// firendly features, that may affect its performance. + pub fn dev_mode(&self) -> bool { + self.dev_mode + } + + /// Enable or disable dev mode + /// + /// With dev mode turned on, handlebars enables a set of development + /// firendly features, that may affect its performance. + pub fn set_dev_mode(&mut self, enabled: bool) { + self.dev_mode = enabled; + } + + /// Register a `Template` + /// + /// This is infallible since the template has already been parsed and + /// insert cannot fail. If there is an existing template with this name it + /// will be overwritten. + pub fn register_template(&mut self, name: &str, tpl: Template) { + self.templates.insert(name.to_string(), tpl); + } + + /// Register a template string + /// + /// Returns `TemplateError` if there is syntax error on parsing the template. + pub fn register_template_string( + &mut self, + name: &str, + tpl_str: S, + ) -> Result<(), TemplateError> + where + S: AsRef, + { + let template = Template::compile_with_name(tpl_str, name.to_owned())?; + self.register_template(name, template); + Ok(()) + } + + /// Register a partial string + /// + /// A named partial will be added to the registry. It will overwrite template with + /// same name. Currently a registered partial is just identical to a template. + pub fn register_partial(&mut self, name: &str, partial_str: S) -> Result<(), TemplateError> + where + S: AsRef, + { + self.register_template_string(name, partial_str) + } + + /// Register a template from a path + pub fn register_template_file

( + &mut self, + name: &str, + tpl_path: P, + ) -> Result<(), TemplateError> + where + P: AsRef, + { + let source = FileSource::new(tpl_path.as_ref().into()); + let template_string = source + .load() + .map_err(|err| TemplateError::from((err, name.to_owned())))?; + + self.register_template_string(name, template_string)?; + if self.dev_mode { + self.template_sources + .insert(name.to_owned(), Arc::new(source)); + } + + Ok(()) + } + + /// Register templates from a directory + /// + /// * `tpl_extension`: the template file extension + /// * `dir_path`: the path of directory + /// + /// Hidden files and tempfile (starts with `#`) will be ignored. All registered + /// will use their relative name as template name. For example, when `dir_path` is + /// `templates/` and `tpl_extension` is `.hbs`, the file + /// `templates/some/path/file.hbs` will be registered as `some/path/file`. + /// + /// This method is not available by default. + /// You will need to enable the `dir_source` feature to use it. + #[cfg(feature = "dir_source")] + #[cfg_attr(docsrs, doc(cfg(feature = "dir_source")))] + pub fn register_templates_directory

( + &mut self, + tpl_extension: &'static str, + dir_path: P, + ) -> Result<(), TemplateError> + where + P: AsRef, + { + let dir_path = dir_path.as_ref(); + + let prefix_len = if dir_path + .to_string_lossy() + .ends_with(|c| c == '\\' || c == '/') + // `/` will work on windows too so we still need to check + { + dir_path.to_string_lossy().len() + } else { + dir_path.to_string_lossy().len() + 1 + }; + + let walker = WalkDir::new(dir_path); + let dir_iter = walker + .min_depth(1) + .into_iter() + .filter(|e| e.is_ok() && !filter_file(e.as_ref().unwrap(), tpl_extension)); + + for entry in dir_iter { + let entry = entry?; + + let tpl_path = entry.path(); + let tpl_file_path = entry.path().to_string_lossy(); + + let tpl_name = &tpl_file_path[prefix_len..tpl_file_path.len() - tpl_extension.len()]; + // replace platform path separator with our internal one + let tpl_canonical_name = tpl_name.replace(path::MAIN_SEPARATOR, "/"); + self.register_template_file(&tpl_canonical_name, &tpl_path)?; + } + + Ok(()) + } + + /// Remove a template from the registry + pub fn unregister_template(&mut self, name: &str) { + self.templates.remove(name); + } + + /// Register a helper + pub fn register_helper(&mut self, name: &str, def: Box) { + self.helpers.insert(name.to_string(), def.into()); + } + + /// Register a [rhai](https://docs.rs/rhai/) script as handlebars helper + /// + /// Currently only simple helpers are supported. You can do computation or + /// string formatting with rhai script. + /// + /// Helper parameters and hash are available in rhai script as array `params` + /// and map `hash`. Example script: + /// + /// ```handlebars + /// {{percent 0.34 label="%"}} + /// ``` + /// + /// ```rhai + /// // percent.rhai + /// let value = params[0]; + /// let label = hash["label"]; + /// + /// (value * 100).to_string() + label + /// ``` + /// + /// + #[cfg(feature = "script_helper")] + #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] + pub fn register_script_helper(&mut self, name: &str, script: &str) -> Result<(), ScriptError> { + let compiled = self.engine.compile(script)?; + let script_helper = ScriptHelper { script: compiled }; + self.helpers + .insert(name.to_string(), Arc::new(script_helper)); + Ok(()) + } + + /// Register a [rhai](https://docs.rs/rhai/) script from file + #[cfg(feature = "script_helper")] + #[cfg_attr(docsrs, doc(cfg(feature = "script_helper")))] + pub fn register_script_helper_file

( + &mut self, + name: &str, + script_path: P, + ) -> Result<(), ScriptError> + where + P: AsRef, + { + let source = FileSource::new(script_path.as_ref().into()); + let script = source.load()?; + + self.script_sources + .insert(name.to_owned(), Arc::new(source)); + self.register_script_helper(name, &script) + } + + /// Register a decorator + pub fn register_decorator( + &mut self, + name: &str, + def: Box, + ) { + self.decorators.insert(name.to_string(), def.into()); + } + + /// Register a new *escape fn* to be used from now on by this registry. + pub fn register_escape_fn String + Send + Sync>( + &mut self, + escape_fn: F, + ) { + self.escape_fn = Arc::new(escape_fn); + } + + /// Restore the default *escape fn*. + pub fn unregister_escape_fn(&mut self) { + self.escape_fn = Arc::new(html_escape); + } + + /// Get a reference to the current *escape fn*. + pub fn get_escape_fn(&self) -> &dyn Fn(&str) -> String { + &*self.escape_fn + } + + /// Return `true` if a template is registered for the given name + pub fn has_template(&self, name: &str) -> bool { + self.get_template(name).is_some() + } + + /// Return a registered template, + pub fn get_template(&self, name: &str) -> Option<&Template> { + self.templates.get(name) + } + + #[inline] + pub(crate) fn get_or_load_template_optional( + &'reg self, + name: &str, + ) -> Option, RenderError>> { + if let (true, Some(source)) = (self.dev_mode, self.template_sources.get(name)) { + let r = source + .load() + .map_err(|e| TemplateError::from((e, name.to_owned()))) + .and_then(|tpl_str| Template::compile_with_name(tpl_str, name.to_owned())) + .map(Cow::Owned) + .map_err(RenderError::from); + Some(r) + } else { + self.templates.get(name).map(|t| Ok(Cow::Borrowed(t))) + } + } + + #[inline] + pub(crate) fn get_or_load_template( + &'reg self, + name: &str, + ) -> Result, RenderError> { + if let Some(result) = self.get_or_load_template_optional(name) { + result + } else { + Err(RenderError::new(format!("Template not found: {}", name))) + } + } + + /// Return a registered helper + pub(crate) fn get_or_load_helper( + &'reg self, + name: &str, + ) -> Result>, RenderError> { + #[cfg(feature = "script_helper")] + if let (true, Some(source)) = (self.dev_mode, self.script_sources.get(name)) { + return source + .load() + .map_err(ScriptError::from) + .and_then(|s| { + let helper = Box::new(ScriptHelper { + script: self.engine.compile(&s)?, + }) as Box; + Ok(Some(helper.into())) + }) + .map_err(RenderError::from); + } + + Ok(self.helpers.get(name).cloned()) + } + + #[inline] + pub(crate) fn has_helper(&self, name: &str) -> bool { + self.helpers.contains_key(name) + } + + /// Return a registered decorator + pub(crate) fn get_decorator( + &self, + name: &str, + ) -> Option<&(dyn DecoratorDef + Send + Sync + 'reg)> { + self.decorators.get(name).map(|v| v.as_ref()) + } + + /// Return all templates registered + pub fn get_templates(&self) -> &HashMap { + &self.templates + } + + /// Unregister all templates + pub fn clear_templates(&mut self) { + self.templates.clear(); + } + + #[inline] + fn render_to_output( + &self, + name: &str, + ctx: &Context, + output: &mut O, + ) -> Result<(), RenderError> + where + O: Output, + { + self.get_or_load_template(name).and_then(|t| { + let mut render_context = RenderContext::new(t.name.as_ref()); + t.render(self, &ctx, &mut render_context, output) + }) + } + + /// Render a registered template with some data into a string + /// + /// * `name` is the template name you registered previously + /// * `data` is the data that implements `serde::Serialize` + /// + /// Returns rendered string or a struct with error information + pub fn render(&self, name: &str, data: &T) -> Result + where + T: Serialize, + { + let mut output = StringOutput::new(); + let ctx = Context::wraps(&data)?; + self.render_to_output(name, &ctx, &mut output)?; + output.into_string().map_err(RenderError::from) + } + + /// Render a registered template with reused context + pub fn render_with_context(&self, name: &str, ctx: &Context) -> Result { + let mut output = StringOutput::new(); + self.render_to_output(name, ctx, &mut output)?; + output.into_string().map_err(RenderError::from) + } + + /// Render a registered template and write some data to the `std::io::Write` + pub fn render_to_write(&self, name: &str, data: &T, writer: W) -> Result<(), RenderError> + where + T: Serialize, + W: Write, + { + let mut output = WriteOutput::new(writer); + let ctx = Context::wraps(data)?; + self.render_to_output(name, &ctx, &mut output) + } + + /// Render a template string using current registry without registering it + pub fn render_template(&self, template_string: &str, data: &T) -> Result + where + T: Serialize, + { + let mut writer = StringWriter::new(); + self.render_template_to_write(template_string, data, &mut writer)?; + Ok(writer.into_string()) + } + + /// Render a template string using reused context data + pub fn render_template_with_context( + &self, + template_string: &str, + ctx: &Context, + ) -> Result { + let tpl = Template::compile(template_string)?; + + let mut out = StringOutput::new(); + { + let mut render_context = RenderContext::new(None); + tpl.render(self, &ctx, &mut render_context, &mut out)?; + } + + out.into_string().map_err(RenderError::from) + } + + /// Render a template string using current registry without registering it + pub fn render_template_to_write( + &self, + template_string: &str, + data: &T, + writer: W, + ) -> Result<(), RenderError> + where + T: Serialize, + W: Write, + { + let tpl = Template::compile(template_string)?; + let ctx = Context::wraps(data)?; + let mut render_context = RenderContext::new(None); + let mut out = WriteOutput::new(writer); + tpl.render(self, &ctx, &mut render_context, &mut out) + } +} + +#[cfg(test)] +mod test { + use crate::context::Context; + use crate::error::RenderError; + use crate::helpers::HelperDef; + use crate::output::Output; + use crate::registry::Registry; + use crate::render::{Helper, RenderContext, Renderable}; + use crate::support::str::StringWriter; + use crate::template::Template; + use std::fs::File; + use std::io::Write; + use tempfile::tempdir; + + #[derive(Clone, Copy)] + struct DummyHelper; + + impl HelperDef for DummyHelper { + fn call<'reg: 'rc, 'rc>( + &self, + h: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> Result<(), RenderError> { + h.template().unwrap().render(r, ctx, rc, out) + } + } + + static DUMMY_HELPER: DummyHelper = DummyHelper; + + #[test] + fn test_registry_operations() { + let mut r = Registry::new(); + + assert!(r.register_template_string("index", "

").is_ok()); + + let tpl = Template::compile("

").unwrap(); + r.register_template("index2", tpl); + + assert_eq!(r.templates.len(), 2); + + r.unregister_template("index"); + assert_eq!(r.templates.len(), 1); + + r.clear_templates(); + assert_eq!(r.templates.len(), 0); + + r.register_helper("dummy", Box::new(DUMMY_HELPER)); + + // built-in helpers plus 1 + let num_helpers = 7; + let num_boolean_helpers = 10; // stuff like gt and lte + let num_custom_helpers = 1; // dummy from above + assert_eq!( + r.helpers.len(), + num_helpers + num_boolean_helpers + num_custom_helpers + ); + } + + #[test] + #[cfg(feature = "dir_source")] + fn test_register_templates_directory() { + use std::fs::DirBuilder; + + let mut r = Registry::new(); + { + let dir = tempdir().unwrap(); + + assert_eq!(r.templates.len(), 0); + + let file1_path = dir.path().join("t1.hbs"); + let mut file1: File = File::create(&file1_path).unwrap(); + writeln!(file1, "

Hello {{world}}!

").unwrap(); + + let file2_path = dir.path().join("t2.hbs"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "

Hola {{world}}!

").unwrap(); + + let file3_path = dir.path().join("t3.hbs"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "

Hallo {{world}}!

").unwrap(); + + let file4_path = dir.path().join(".t4.hbs"); + let mut file4: File = File::create(&file4_path).unwrap(); + writeln!(file4, "

Hallo {{world}}!

").unwrap(); + + r.register_templates_directory(".hbs", dir.path()).unwrap(); + + assert_eq!(r.templates.len(), 3); + assert_eq!(r.templates.contains_key("t1"), true); + assert_eq!(r.templates.contains_key("t2"), true); + assert_eq!(r.templates.contains_key("t3"), true); + assert_eq!(r.templates.contains_key("t4"), false); + + drop(file1); + drop(file2); + drop(file3); + + dir.close().unwrap(); + } + + { + let dir = tempdir().unwrap(); + + let file1_path = dir.path().join("t4.hbs"); + let mut file1: File = File::create(&file1_path).unwrap(); + writeln!(file1, "

Hello {{world}}!

").unwrap(); + + let file2_path = dir.path().join("t5.erb"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "

Hello {{% world %}}!

").unwrap(); + + let file3_path = dir.path().join("t6.html"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "

Hello world!

").unwrap(); + + r.register_templates_directory(".hbs", dir.path()).unwrap(); + + assert_eq!(r.templates.len(), 4); + assert_eq!(r.templates.contains_key("t4"), true); + + drop(file1); + drop(file2); + drop(file3); + + dir.close().unwrap(); + } + + { + let dir = tempdir().unwrap(); + + let _ = DirBuilder::new().create(dir.path().join("french")).unwrap(); + let _ = DirBuilder::new() + .create(dir.path().join("portugese")) + .unwrap(); + let _ = DirBuilder::new() + .create(dir.path().join("italian")) + .unwrap(); + + let file1_path = dir.path().join("french/t7.hbs"); + let mut file1: File = File::create(&file1_path).unwrap(); + writeln!(file1, "

Bonjour {{world}}!

").unwrap(); + + let file2_path = dir.path().join("portugese/t8.hbs"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "

Ola {{world}}!

").unwrap(); + + let file3_path = dir.path().join("italian/t9.hbs"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "

Ciao {{world}}!

").unwrap(); + + r.register_templates_directory(".hbs", dir.path()).unwrap(); + + assert_eq!(r.templates.len(), 7); + assert_eq!(r.templates.contains_key("french/t7"), true); + assert_eq!(r.templates.contains_key("portugese/t8"), true); + assert_eq!(r.templates.contains_key("italian/t9"), true); + + drop(file1); + drop(file2); + drop(file3); + + dir.close().unwrap(); + } + + { + let dir = tempdir().unwrap(); + + let file1_path = dir.path().join("t10.hbs"); + let mut file1: File = File::create(&file1_path).unwrap(); + writeln!(file1, "

Bonjour {{world}}!

").unwrap(); + + let mut dir_path = dir + .path() + .to_string_lossy() + .replace(std::path::MAIN_SEPARATOR, "/"); + if !dir_path.ends_with("/") { + dir_path.push('/'); + } + r.register_templates_directory(".hbs", dir_path).unwrap(); + + assert_eq!(r.templates.len(), 8); + assert_eq!(r.templates.contains_key("t10"), true); + + drop(file1); + dir.close().unwrap(); + } + } + + #[test] + fn test_render_to_write() { + let mut r = Registry::new(); + + assert!(r.register_template_string("index", "

").is_ok()); + + let mut sw = StringWriter::new(); + { + r.render_to_write("index", &(), &mut sw).ok().unwrap(); + } + + assert_eq!("

".to_string(), sw.into_string()); + } + + #[test] + fn test_escape_fn() { + let mut r = Registry::new(); + + let input = String::from("\"<>&"); + + r.register_template_string("test", String::from("{{this}}")) + .unwrap(); + + assert_eq!(""<>&", r.render("test", &input).unwrap()); + + r.register_escape_fn(|s| s.into()); + + assert_eq!("\"<>&", r.render("test", &input).unwrap()); + + r.unregister_escape_fn(); + + assert_eq!(""<>&", r.render("test", &input).unwrap()); + } + + #[test] + fn test_escape() { + let r = Registry::new(); + let data = json!({"hello": "world"}); + + assert_eq!( + "{{hello}}", + r.render_template(r"\{{hello}}", &data).unwrap() + ); + + assert_eq!( + " {{hello}}", + r.render_template(r" \{{hello}}", &data).unwrap() + ); + + assert_eq!(r"\world", r.render_template(r"\\{{hello}}", &data).unwrap()); + } + + #[test] + fn test_strict_mode() { + let mut r = Registry::new(); + assert!(!r.strict_mode()); + + r.set_strict_mode(true); + assert!(r.strict_mode()); + + let data = json!({ + "the_only_key": "the_only_value" + }); + + assert!(r + .render_template("accessing the_only_key {{the_only_key}}", &data) + .is_ok()); + assert!(r + .render_template("accessing non-exists key {{the_key_never_exists}}", &data) + .is_err()); + + let render_error = r + .render_template("accessing non-exists key {{the_key_never_exists}}", &data) + .unwrap_err(); + assert_eq!(render_error.column_no.unwrap(), 26); + + let data2 = json!([1, 2, 3]); + assert!(r + .render_template("accessing valid array index {{this.[2]}}", &data2) + .is_ok()); + assert!(r + .render_template("accessing invalid array index {{this.[3]}}", &data2) + .is_err()); + let render_error2 = r + .render_template("accessing invalid array index {{this.[3]}}", &data2) + .unwrap_err(); + assert_eq!(render_error2.column_no.unwrap(), 31); + } + + use crate::json::value::ScopedJson; + struct GenMissingHelper; + impl HelperDef for GenMissingHelper { + fn call_inner<'reg: 'rc, 'rc>( + &self, + _: &Helper<'reg, 'rc>, + _: &'reg Registry<'reg>, + _: &'rc Context, + _: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + Ok(ScopedJson::Missing) + } + } + + #[test] + fn test_strict_mode_in_helper() { + let mut r = Registry::new(); + r.set_strict_mode(true); + + r.register_helper( + "check_missing", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + _: &mut dyn Output| + -> Result<(), RenderError> { + let value = h.param(0).unwrap(); + assert!(value.is_value_missing()); + Ok(()) + }, + ), + ); + + r.register_helper("generate_missing_value", Box::new(GenMissingHelper)); + + let data = json!({ + "the_key_we_have": "the_value_we_have" + }); + assert!(r + .render_template("accessing non-exists key {{the_key_we_dont_have}}", &data) + .is_err()); + assert!(r + .render_template( + "accessing non-exists key from helper {{check_missing the_key_we_dont_have}}", + &data + ) + .is_ok()); + assert!(r + .render_template( + "accessing helper that generates missing value {{generate_missing_value}}", + &data + ) + .is_err()); + } + + #[test] + fn test_html_expression() { + let reg = Registry::new(); + assert_eq!( + reg.render_template("{{{ a }}}", &json!({"a": "bold"})) + .unwrap(), + "bold" + ); + assert_eq!( + reg.render_template("{{ &a }}", &json!({"a": "bold"})) + .unwrap(), + "bold" + ); + } + + #[test] + fn test_render_context() { + let mut reg = Registry::new(); + + let data = json!([0, 1, 2, 3]); + + assert_eq!( + "0123", + reg.render_template_with_context( + "{{#each this}}{{this}}{{/each}}", + &Context::wraps(&data).unwrap() + ) + .unwrap() + ); + + reg.register_template_string("t0", "{{#each this}}{{this}}{{/each}}") + .unwrap(); + assert_eq!( + "0123", + reg.render_with_context("t0", &Context::wraps(&data).unwrap()) + .unwrap() + ); + } + + #[test] + fn test_keys_starts_with_null() { + env_logger::init(); + let reg = Registry::new(); + let data = json!({ + "optional": true, + "is_null": true, + "nullable": true, + "null": true, + "falsevalue": true, + }); + assert_eq!( + "optional: true --> true", + reg.render_template( + "optional: {{optional}} --> {{#if optional }}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + assert_eq!( + "is_null: true --> true", + reg.render_template( + "is_null: {{is_null}} --> {{#if is_null }}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + assert_eq!( + "nullable: true --> true", + reg.render_template( + "nullable: {{nullable}} --> {{#if nullable }}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + assert_eq!( + "falsevalue: true --> true", + reg.render_template( + "falsevalue: {{falsevalue}} --> {{#if falsevalue }}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + assert_eq!( + "null: true --> false", + reg.render_template( + "null: {{null}} --> {{#if null }}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + assert_eq!( + "null: true --> true", + reg.render_template( + "null: {{null}} --> {{#if this.[null]}}true{{else}}false{{/if}}", + &data + ) + .unwrap() + ); + } + + #[test] + fn test_dev_mode_template_reload() { + let mut reg = Registry::new(); + reg.set_dev_mode(true); + assert!(reg.dev_mode()); + + let dir = tempdir().unwrap(); + let file1_path = dir.path().join("t1.hbs"); + { + let mut file1: File = File::create(&file1_path).unwrap(); + write!(file1, "

Hello {{{{name}}}}!

").unwrap(); + } + + reg.register_template_file("t1", &file1_path).unwrap(); + + assert_eq!( + reg.render("t1", &json!({"name": "Alex"})).unwrap(), + "

Hello Alex!

" + ); + + { + let mut file1: File = File::create(&file1_path).unwrap(); + write!(file1, "

Privet {{{{name}}}}!

").unwrap(); + } + + assert_eq!( + reg.render("t1", &json!({"name": "Alex"})).unwrap(), + "

Privet Alex!

" + ); + + dir.close().unwrap(); + } + + #[test] + #[cfg(feature = "script_helper")] + fn test_script_helper() { + let mut reg = Registry::new(); + + reg.register_script_helper("acc", "params.reduce(|sum, x| x + sum, 0)") + .unwrap(); + + assert_eq!( + reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(), + "10" + ); + } + + #[test] + #[cfg(feature = "script_helper")] + fn test_script_helper_dev_mode() { + let mut reg = Registry::new(); + reg.set_dev_mode(true); + + let dir = tempdir().unwrap(); + let file1_path = dir.path().join("acc.rhai"); + { + let mut file1: File = File::create(&file1_path).unwrap(); + write!(file1, "params.reduce(|sum, x| x + sum, 0)").unwrap(); + } + + reg.register_script_helper_file("acc", &file1_path).unwrap(); + + assert_eq!( + reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(), + "10" + ); + + { + let mut file1: File = File::create(&file1_path).unwrap(); + write!(file1, "params.reduce(|sum, x| x * sum, 1)").unwrap(); + } + + assert_eq!( + reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(), + "24" + ); + + dir.close().unwrap(); + } +} diff --git a/vendor/handlebars/src/render.rs b/vendor/handlebars/src/render.rs new file mode 100644 index 000000000..188ea221a --- /dev/null +++ b/vendor/handlebars/src/render.rs @@ -0,0 +1,1119 @@ +use std::borrow::{Borrow, Cow}; +use std::collections::{BTreeMap, VecDeque}; +use std::fmt; +use std::rc::Rc; + +use serde_json::value::Value as Json; + +use crate::block::BlockContext; +use crate::context::Context; +use crate::error::RenderError; +use crate::helpers::HelperDef; +use crate::json::path::Path; +use crate::json::value::{JsonRender, PathAndJson, ScopedJson}; +use crate::output::{Output, StringOutput}; +use crate::partial; +use crate::registry::Registry; +use crate::template::TemplateElement::*; +use crate::template::{ + BlockParam, DecoratorTemplate, HelperTemplate, Parameter, Template, TemplateElement, + TemplateMapping, +}; + +const HELPER_MISSING: &str = "helperMissing"; +const BLOCK_HELPER_MISSING: &str = "blockHelperMissing"; + +/// The context of a render call +/// +/// This context stores information of a render and a writer where generated +/// content is written to. +/// +#[derive(Clone, Debug)] +pub struct RenderContext<'reg, 'rc> { + inner: Rc>, + blocks: VecDeque>, + // copy-on-write context + modified_context: Option>, +} + +#[derive(Clone)] +pub struct RenderContextInner<'reg: 'rc, 'rc> { + partials: BTreeMap, + partial_block_stack: VecDeque<&'reg Template>, + partial_block_depth: isize, + local_helpers: BTreeMap>, + /// current template name + current_template: Option<&'reg String>, + /// root template name + root_template: Option<&'reg String>, + disable_escape: bool, +} + +impl<'reg: 'rc, 'rc> RenderContext<'reg, 'rc> { + /// Create a render context from a `Write` + pub fn new(root_template: Option<&'reg String>) -> RenderContext<'reg, 'rc> { + let inner = Rc::new(RenderContextInner { + partials: BTreeMap::new(), + partial_block_stack: VecDeque::new(), + partial_block_depth: 0, + local_helpers: BTreeMap::new(), + current_template: None, + root_template, + disable_escape: false, + }); + + let mut blocks = VecDeque::with_capacity(5); + blocks.push_front(BlockContext::new()); + + let modified_context = None; + RenderContext { + inner, + blocks, + modified_context, + } + } + + // TODO: better name + pub(crate) fn new_for_block(&self) -> RenderContext<'reg, 'rc> { + let inner = self.inner.clone(); + + let mut blocks = VecDeque::with_capacity(2); + blocks.push_front(BlockContext::new()); + + let modified_context = self.modified_context.clone(); + + RenderContext { + inner, + blocks, + modified_context, + } + } + + /// Push a block context into render context stack. This is typically + /// called when you entering a block scope. + pub fn push_block(&mut self, block: BlockContext<'reg>) { + self.blocks.push_front(block); + } + + /// Pop and drop current block context. + /// This is typically called when leaving a block scope. + pub fn pop_block(&mut self) { + self.blocks.pop_front(); + } + + /// Borrow a reference to current block context + pub fn block(&self) -> Option<&BlockContext<'reg>> { + self.blocks.front() + } + + /// Borrow a mutable reference to current block context in order to + /// modify some data. + pub fn block_mut(&mut self) -> Option<&mut BlockContext<'reg>> { + self.blocks.front_mut() + } + + fn inner(&self) -> &RenderContextInner<'reg, 'rc> { + self.inner.borrow() + } + + fn inner_mut(&mut self) -> &mut RenderContextInner<'reg, 'rc> { + Rc::make_mut(&mut self.inner) + } + + /// Get the modified context data if any + pub fn context(&self) -> Option> { + self.modified_context.clone() + } + + /// Set new context data into the render process. + /// This is typically called in decorators where user can modify + /// the data they were rendering. + pub fn set_context(&mut self, ctx: Context) { + self.modified_context = Some(Rc::new(ctx)) + } + + /// Evaluate a Json path in current scope. + /// + /// Typically you don't need to evaluate it by yourself. + /// The Helper and Decorator API will provide your evaluated value of + /// their parameters and hash data. + pub fn evaluate( + &self, + context: &'rc Context, + relative_path: &str, + ) -> Result, RenderError> { + let path = Path::parse(relative_path)?; + self.evaluate2(context, &path) + } + + pub(crate) fn evaluate2( + &self, + context: &'rc Context, + path: &Path, + ) -> Result, RenderError> { + match path { + Path::Local((level, name, _)) => Ok(self + .get_local_var(*level, name) + .map(|v| ScopedJson::Derived(v.clone())) + .unwrap_or_else(|| ScopedJson::Missing)), + Path::Relative((segs, _)) => context.navigate(segs, &self.blocks), + } + } + + /// Get registered partial in this render context + pub fn get_partial(&self, name: &str) -> Option<&Template> { + if name == partial::PARTIAL_BLOCK { + return self + .inner() + .partial_block_stack + .get(self.inner().partial_block_depth as usize) + .copied(); + } + self.inner().partials.get(name).copied() + } + + /// Register a partial for this context + pub fn set_partial(&mut self, name: String, partial: &'reg Template) { + self.inner_mut().partials.insert(name, partial); + } + + pub(crate) fn push_partial_block(&mut self, partial: &'reg Template) { + self.inner_mut().partial_block_stack.push_front(partial); + } + + pub(crate) fn pop_partial_block(&mut self) { + self.inner_mut().partial_block_stack.pop_front(); + } + + pub(crate) fn inc_partial_block_depth(&mut self) { + self.inner_mut().partial_block_depth += 1; + } + + pub(crate) fn dec_partial_block_depth(&mut self) { + self.inner_mut().partial_block_depth -= 1; + } + + /// Remove a registered partial + pub fn remove_partial(&mut self, name: &str) { + self.inner_mut().partials.remove(name); + } + + fn get_local_var(&self, level: usize, name: &str) -> Option<&Json> { + self.blocks + .get(level) + .and_then(|blk| blk.get_local_var(&name)) + } + + /// Test if given template name is current template. + pub fn is_current_template(&self, p: &str) -> bool { + self.inner() + .current_template + .map(|s| s == p) + .unwrap_or(false) + } + + /// Register a helper in this render context. + /// This is a feature provided by Decorator where you can create + /// temporary helpers. + pub fn register_local_helper( + &mut self, + name: &str, + def: Box, + ) { + self.inner_mut() + .local_helpers + .insert(name.to_string(), def.into()); + } + + /// Remove a helper from render context + pub fn unregister_local_helper(&mut self, name: &str) { + self.inner_mut().local_helpers.remove(name); + } + + /// Attempt to get a helper from current render context. + pub fn get_local_helper(&self, name: &str) -> Option> { + self.inner().local_helpers.get(name).cloned() + } + + #[inline] + fn has_local_helper(&self, name: &str) -> bool { + self.inner.local_helpers.contains_key(name) + } + + /// Returns the current template name. + /// Note that the name can be vary from root template when you are rendering + /// from partials. + pub fn get_current_template_name(&self) -> Option<&'reg String> { + self.inner().current_template + } + + /// Set the current template name. + pub fn set_current_template_name(&mut self, name: Option<&'reg String>) { + self.inner_mut().current_template = name; + } + + /// Get root template name if any. + /// This is the template name that you call `render` from `Handlebars`. + pub fn get_root_template_name(&self) -> Option<&'reg String> { + self.inner().root_template + } + + /// Get the escape toggle + pub fn is_disable_escape(&self) -> bool { + self.inner().disable_escape + } + + /// Set the escape toggle. + /// When toggle is on, escape_fn will be called when rendering. + pub fn set_disable_escape(&mut self, disable: bool) { + self.inner_mut().disable_escape = disable + } +} + +impl<'reg, 'rc> fmt::Debug for RenderContextInner<'reg, 'rc> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.debug_struct("RenderContextInner") + .field("partials", &self.partials) + .field("partial_block_stack", &self.partial_block_stack) + .field("root_template", &self.root_template) + .field("current_template", &self.current_template) + .field("disable_eacape", &self.disable_escape) + .finish() + } +} + +/// Render-time Helper data when using in a helper definition +#[derive(Debug)] +pub struct Helper<'reg, 'rc> { + name: Cow<'reg, str>, + params: Vec>, + hash: BTreeMap<&'reg str, PathAndJson<'reg, 'rc>>, + template: Option<&'reg Template>, + inverse: Option<&'reg Template>, + block_param: Option<&'reg BlockParam>, + block: bool, +} + +impl<'reg: 'rc, 'rc> Helper<'reg, 'rc> { + fn try_from_template( + ht: &'reg HelperTemplate, + registry: &'reg Registry<'reg>, + context: &'rc Context, + render_context: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + let name = ht.name.expand_as_name(registry, context, render_context)?; + let mut pv = Vec::with_capacity(ht.params.len()); + for p in &ht.params { + let r = p.expand(registry, context, render_context)?; + pv.push(r); + } + + let mut hm = BTreeMap::new(); + for (k, p) in &ht.hash { + let r = p.expand(registry, context, render_context)?; + hm.insert(k.as_ref(), r); + } + + Ok(Helper { + name, + params: pv, + hash: hm, + template: ht.template.as_ref(), + inverse: ht.inverse.as_ref(), + block_param: ht.block_param.as_ref(), + block: ht.block, + }) + } + + /// Returns helper name + pub fn name(&self) -> &str { + &self.name + } + + /// Returns all helper params, resolved within the context + pub fn params(&self) -> &Vec> { + &self.params + } + + /// Returns nth helper param, resolved within the context. + /// + /// ## Example + /// + /// To get the first param in `{{my_helper abc}}` or `{{my_helper 2}}`, + /// use `h.param(0)` in helper definition. + /// Variable `abc` is auto resolved in current context. + /// + /// ``` + /// use handlebars::*; + /// + /// fn my_helper(h: &Helper, rc: &mut RenderContext) -> Result<(), RenderError> { + /// let v = h.param(0).map(|v| v.value()) + /// .ok_or(RenderError::new("param not found")); + /// // .. + /// Ok(()) + /// } + /// ``` + pub fn param(&self, idx: usize) -> Option<&PathAndJson<'reg, 'rc>> { + self.params.get(idx) + } + + /// Returns hash, resolved within the context + pub fn hash(&self) -> &BTreeMap<&'reg str, PathAndJson<'reg, 'rc>> { + &self.hash + } + + /// Return hash value of a given key, resolved within the context + /// + /// ## Example + /// + /// To get the first param in `{{my_helper v=abc}}` or `{{my_helper v=2}}`, + /// use `h.hash_get("v")` in helper definition. + /// Variable `abc` is auto resolved in current context. + /// + /// ``` + /// use handlebars::*; + /// + /// fn my_helper(h: &Helper, rc: &mut RenderContext) -> Result<(), RenderError> { + /// let v = h.hash_get("v").map(|v| v.value()) + /// .ok_or(RenderError::new("param not found")); + /// // .. + /// Ok(()) + /// } + /// ``` + pub fn hash_get(&self, key: &str) -> Option<&PathAndJson<'reg, 'rc>> { + self.hash.get(key) + } + + /// Returns the default inner template if the helper is a block helper. + /// + /// Typically you will render the template via: `template.render(registry, render_context)` + /// + pub fn template(&self) -> Option<&'reg Template> { + self.template + } + + /// Returns the template of `else` branch if any + pub fn inverse(&self) -> Option<&'reg Template> { + self.inverse + } + + /// Returns if the helper is a block one `{{#helper}}{{/helper}}` or not `{{helper 123}}` + pub fn is_block(&self) -> bool { + self.block + } + + /// Returns if the helper has either a block param or block param pair + pub fn has_block_param(&self) -> bool { + self.block_param.is_some() + } + + /// Returns block param if any + pub fn block_param(&self) -> Option<&'reg str> { + if let Some(&BlockParam::Single(Parameter::Name(ref s))) = self.block_param { + Some(s) + } else { + None + } + } + + /// Return block param pair (for example |key, val|) if any + pub fn block_param_pair(&self) -> Option<(&'reg str, &'reg str)> { + if let Some(&BlockParam::Pair((Parameter::Name(ref s1), Parameter::Name(ref s2)))) = + self.block_param + { + Some((s1, s2)) + } else { + None + } + } +} + +/// Render-time Decorator data when using in a decorator definition +#[derive(Debug)] +pub struct Decorator<'reg, 'rc> { + name: Cow<'reg, str>, + params: Vec>, + hash: BTreeMap<&'reg str, PathAndJson<'reg, 'rc>>, + template: Option<&'reg Template>, +} + +impl<'reg: 'rc, 'rc> Decorator<'reg, 'rc> { + fn try_from_template( + dt: &'reg DecoratorTemplate, + registry: &'reg Registry<'reg>, + context: &'rc Context, + render_context: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + let name = dt.name.expand_as_name(registry, context, render_context)?; + + let mut pv = Vec::with_capacity(dt.params.len()); + for p in &dt.params { + let r = p.expand(registry, context, render_context)?; + pv.push(r); + } + + let mut hm = BTreeMap::new(); + for (k, p) in &dt.hash { + let r = p.expand(registry, context, render_context)?; + hm.insert(k.as_ref(), r); + } + + Ok(Decorator { + name, + params: pv, + hash: hm, + template: dt.template.as_ref(), + }) + } + + /// Returns helper name + pub fn name(&self) -> &str { + self.name.as_ref() + } + + /// Returns all helper params, resolved within the context + pub fn params(&self) -> &Vec> { + &self.params + } + + /// Returns nth helper param, resolved within the context + pub fn param(&self, idx: usize) -> Option<&PathAndJson<'reg, 'rc>> { + self.params.get(idx) + } + + /// Returns hash, resolved within the context + pub fn hash(&self) -> &BTreeMap<&'reg str, PathAndJson<'reg, 'rc>> { + &self.hash + } + + /// Return hash value of a given key, resolved within the context + pub fn hash_get(&self, key: &str) -> Option<&PathAndJson<'reg, 'rc>> { + self.hash.get(key) + } + + /// Returns the default inner template if any + pub fn template(&self) -> Option<&'reg Template> { + self.template + } +} + +/// Render trait +pub trait Renderable { + /// render into RenderContext's `writer` + fn render<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + context: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> Result<(), RenderError>; + + /// render into string + fn renders<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result { + let mut so = StringOutput::new(); + self.render(registry, ctx, rc, &mut so)?; + so.into_string().map_err(RenderError::from) + } +} + +/// Evaluate decorator +pub trait Evaluable { + fn eval<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + context: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result<(), RenderError>; +} + +#[inline] +fn call_helper_for_value<'reg: 'rc, 'rc>( + hd: &dyn HelperDef, + ht: &Helper<'reg, 'rc>, + r: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, +) -> Result, RenderError> { + match hd.call_inner(ht, r, ctx, rc) { + Ok(result) => Ok(PathAndJson::new(None, result)), + Err(e) => { + if e.is_unimplemented() { + // parse value from output + let mut so = StringOutput::new(); + + // here we don't want subexpression result escaped, + // so we temporarily disable it + let disable_escape = rc.is_disable_escape(); + rc.set_disable_escape(true); + + hd.call(ht, r, ctx, rc, &mut so)?; + rc.set_disable_escape(disable_escape); + + let string = so.into_string().map_err(RenderError::from)?; + Ok(PathAndJson::new( + None, + ScopedJson::Derived(Json::String(string)), + )) + } else { + Err(e) + } + } + } +} + +impl Parameter { + pub fn expand_as_name<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + match self { + Parameter::Name(ref name) => Ok(Cow::Borrowed(name)), + Parameter::Path(ref p) => Ok(Cow::Borrowed(p.raw())), + Parameter::Subexpression(_) => self + .expand(registry, ctx, rc) + .map(|v| v.value().render()) + .map(Cow::Owned), + Parameter::Literal(ref j) => Ok(Cow::Owned(j.render())), + } + } + + pub fn expand<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result, RenderError> { + match self { + Parameter::Name(ref name) => { + // FIXME: raise error when expanding with name? + Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing)) + } + Parameter::Path(ref path) => { + if let Some(rc_context) = rc.context() { + let result = rc.evaluate2(rc_context.borrow(), path)?; + Ok(PathAndJson::new( + Some(path.raw().to_owned()), + ScopedJson::Derived(result.as_json().clone()), + )) + } else { + let result = rc.evaluate2(ctx, path)?; + Ok(PathAndJson::new(Some(path.raw().to_owned()), result)) + } + } + Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))), + Parameter::Subexpression(ref t) => match *t.as_element() { + Expression(ref ht) => { + let name = ht.name.expand_as_name(registry, ctx, rc)?; + + let h = Helper::try_from_template(ht, registry, ctx, rc)?; + if let Some(ref d) = rc.get_local_helper(&name) { + call_helper_for_value(d.as_ref(), &h, registry, ctx, rc) + } else { + let mut helper = registry.get_or_load_helper(&name)?; + + if helper.is_none() { + helper = registry.get_or_load_helper(if ht.block { + BLOCK_HELPER_MISSING + } else { + HELPER_MISSING + })?; + } + + helper + .ok_or_else(|| { + RenderError::new(format!("Helper not defined: {:?}", ht.name)) + }) + .and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)) + } + } + _ => unreachable!(), + }, + } + } +} + +impl Renderable for Template { + fn render<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> Result<(), RenderError> { + rc.set_current_template_name(self.name.as_ref()); + let iter = self.elements.iter(); + + for (idx, t) in iter.enumerate() { + t.render(registry, ctx, rc, out).map_err(|mut e| { + // add line/col number if the template has mapping data + if e.line_no.is_none() { + if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) { + e.line_no = Some(line); + e.column_no = Some(col); + } + } + + if e.template_name.is_none() { + e.template_name = self.name.clone(); + } + + e + })?; + } + Ok(()) + } +} + +impl Evaluable for Template { + fn eval<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result<(), RenderError> { + let iter = self.elements.iter(); + + for (idx, t) in iter.enumerate() { + t.eval(registry, ctx, rc).map_err(|mut e| { + if e.line_no.is_none() { + if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) { + e.line_no = Some(line); + e.column_no = Some(col); + } + } + + e.template_name = self.name.clone(); + e + })?; + } + Ok(()) + } +} + +fn helper_exists<'reg: 'rc, 'rc>( + name: &str, + reg: &Registry<'reg>, + rc: &RenderContext<'reg, 'rc>, +) -> bool { + rc.has_local_helper(name) || reg.has_helper(name) +} + +#[inline] +fn render_helper<'reg: 'rc, 'rc>( + ht: &'reg HelperTemplate, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, +) -> Result<(), RenderError> { + let h = Helper::try_from_template(ht, registry, ctx, rc)?; + debug!( + "Rendering helper: {:?}, params: {:?}, hash: {:?}", + h.name(), + h.params(), + h.hash() + ); + if let Some(ref d) = rc.get_local_helper(h.name()) { + d.call(&h, registry, ctx, rc, out) + } else { + let mut helper = registry.get_or_load_helper(h.name())?; + + if helper.is_none() { + helper = registry.get_or_load_helper(if ht.block { + BLOCK_HELPER_MISSING + } else { + HELPER_MISSING + })?; + } + + helper + .ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name()))) + .and_then(|d| d.call(&h, registry, ctx, rc, out)) + } +} + +pub(crate) fn do_escape(r: &Registry<'_>, rc: &RenderContext<'_, '_>, content: String) -> String { + if !rc.is_disable_escape() { + r.get_escape_fn()(&content) + } else { + content + } +} + +impl Renderable for TemplateElement { + fn render<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + out: &mut dyn Output, + ) -> Result<(), RenderError> { + match *self { + RawString(ref v) => { + out.write(v.as_ref())?; + Ok(()) + } + Expression(ref ht) | HtmlExpression(ref ht) => { + let is_html_expression = matches!(self, HtmlExpression(_)); + if is_html_expression { + rc.set_disable_escape(true); + } + + // test if the expression is to render some value + let result = if ht.is_name_only() { + let helper_name = ht.name.expand_as_name(registry, ctx, rc)?; + if helper_exists(&helper_name, registry, rc) { + render_helper(ht, registry, ctx, rc, out) + } else { + debug!("Rendering value: {:?}", ht.name); + let context_json = ht.name.expand(registry, ctx, rc)?; + if context_json.is_value_missing() { + if registry.strict_mode() { + Err(RenderError::strict_error(context_json.relative_path())) + } else { + // helper missing + if let Some(hook) = registry.get_or_load_helper(HELPER_MISSING)? { + let h = Helper::try_from_template(ht, registry, ctx, rc)?; + hook.call(&h, registry, ctx, rc, out) + } else { + Ok(()) + } + } + } else { + let rendered = context_json.value().render(); + let output = do_escape(registry, rc, rendered); + out.write(output.as_ref())?; + Ok(()) + } + } + } else { + // this is a helper expression + render_helper(ht, registry, ctx, rc, out) + }; + + if is_html_expression { + rc.set_disable_escape(false); + } + + result + } + HelperBlock(ref ht) => render_helper(ht, registry, ctx, rc, out), + DecoratorExpression(_) | DecoratorBlock(_) => self.eval(registry, ctx, rc), + PartialExpression(ref dt) | PartialBlock(ref dt) => { + let di = Decorator::try_from_template(dt, registry, ctx, rc)?; + + partial::expand_partial(&di, registry, ctx, rc, out) + } + _ => Ok(()), + } + } +} + +impl Evaluable for TemplateElement { + fn eval<'reg: 'rc, 'rc>( + &'reg self, + registry: &'reg Registry<'reg>, + ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + ) -> Result<(), RenderError> { + match *self { + DecoratorExpression(ref dt) | DecoratorBlock(ref dt) => { + let di = Decorator::try_from_template(dt, registry, ctx, rc)?; + match registry.get_decorator(di.name()) { + Some(d) => d.call(&di, registry, ctx, rc), + None => Err(RenderError::new(format!( + "Decorator not defined: {:?}", + dt.name + ))), + } + } + _ => Ok(()), + } + } +} + +#[test] +fn test_raw_string() { + let r = Registry::new(); + let raw_string = RawString("

hello world

".to_string()); + + let mut out = StringOutput::new(); + let ctx = Context::null(); + { + let mut rc = RenderContext::new(None); + raw_string.render(&r, &ctx, &mut rc, &mut out).ok().unwrap(); + } + assert_eq!( + out.into_string().unwrap(), + "

hello world

".to_string() + ); +} + +#[test] +fn test_expression() { + let r = Registry::new(); + let element = Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["hello"], + )))); + + let mut out = StringOutput::new(); + let mut m: BTreeMap = BTreeMap::new(); + let value = "

".to_string(); + m.insert("hello".to_string(), value); + let ctx = Context::wraps(&m).unwrap(); + { + let mut rc = RenderContext::new(None); + element.render(&r, &ctx, &mut rc, &mut out).ok().unwrap(); + } + + assert_eq!( + out.into_string().unwrap(), + "<p></p>".to_string() + ); +} + +#[test] +fn test_html_expression() { + let r = Registry::new(); + let element = HtmlExpression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["hello"], + )))); + + let mut out = StringOutput::new(); + let mut m: BTreeMap = BTreeMap::new(); + let value = "world"; + m.insert("hello".to_string(), value.to_string()); + let ctx = Context::wraps(&m).unwrap(); + { + let mut rc = RenderContext::new(None); + element.render(&r, &ctx, &mut rc, &mut out).ok().unwrap(); + } + + assert_eq!(out.into_string().unwrap(), value.to_string()); +} + +#[test] +fn test_template() { + let r = Registry::new(); + let mut out = StringOutput::new(); + let mut m: BTreeMap = BTreeMap::new(); + let value = "world".to_string(); + m.insert("hello".to_string(), value); + let ctx = Context::wraps(&m).unwrap(); + + let elements: Vec = vec![ + RawString("

".to_string()), + Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["hello"], + )))), + RawString("

".to_string()), + Comment("".to_string()), + ]; + + let template = Template { + elements, + name: None, + mapping: Vec::new(), + }; + + { + let mut rc = RenderContext::new(None); + template.render(&r, &ctx, &mut rc, &mut out).ok().unwrap(); + } + + assert_eq!(out.into_string().unwrap(), "

world

".to_string()); +} + +#[test] +fn test_render_context_promotion_and_demotion() { + use crate::json::value::to_json; + let mut render_context = RenderContext::new(None); + let mut block = BlockContext::new(); + + block.set_local_var("index", to_json(0)); + render_context.push_block(block); + + render_context.push_block(BlockContext::new()); + assert_eq!( + render_context.get_local_var(1, "index").unwrap(), + &to_json(0) + ); + + render_context.pop_block(); + + assert_eq!( + render_context.get_local_var(0, "index").unwrap(), + &to_json(0) + ); +} + +#[test] +fn test_render_subexpression_issue_115() { + use crate::support::str::StringWriter; + + let mut r = Registry::new(); + r.register_helper( + "format", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + out.write(format!("{}", h.param(0).unwrap().value().render()).as_ref()) + .map(|_| ()) + .map_err(RenderError::from) + }, + ), + ); + + let mut sw = StringWriter::new(); + let mut m: BTreeMap = BTreeMap::new(); + m.insert("a".to_string(), "123".to_string()); + + { + if let Err(e) = r.render_template_to_write("{{format (format a)}}", &m, &mut sw) { + panic!("{}", e); + } + } + + assert_eq!(sw.into_string(), "123".to_string()); +} + +#[test] +fn test_render_error_line_no() { + let mut r = Registry::new(); + let m: BTreeMap = BTreeMap::new(); + + let name = "invalid_template"; + assert!(r + .register_template_string(name, "

\n{{#if true}}\n {{#each}}{{/each}}\n{{/if}}") + .is_ok()); + + if let Err(e) = r.render(name, &m) { + assert_eq!(e.line_no.unwrap(), 3); + assert_eq!(e.column_no.unwrap(), 3); + assert_eq!(e.template_name, Some(name.to_owned())); + } else { + panic!("Error expected"); + } +} + +#[test] +fn test_partial_failback_render() { + let mut r = Registry::new(); + + assert!(r + .register_template_string("parent", "{{> layout}}") + .is_ok()); + assert!(r + .register_template_string( + "child", + "{{#*inline \"layout\"}}content{{/inline}}{{#> parent}}{{> seg}}{{/parent}}" + ) + .is_ok()); + assert!(r.register_template_string("seg", "1234").is_ok()); + + let r = r.render("child", &true).expect("should work"); + assert_eq!(r, "content"); +} + +#[test] +fn test_key_with_slash() { + let mut r = Registry::new(); + + assert!(r + .register_template_string("t", "{{#each this}}{{@key}}: {{this}}\n{{/each}}") + .is_ok()); + + let r = r.render("t", &json!({"/foo": "bar"})).unwrap(); + + assert_eq!(r, "/foo: bar\n"); +} + +#[test] +fn test_comment() { + let r = Registry::new(); + + assert_eq!( + r.render_template("Hello {{this}} {{! test me }}", &0) + .unwrap(), + "Hello 0 " + ); +} + +#[test] +fn test_zero_args_heler() { + let mut r = Registry::new(); + + r.register_helper( + "name", + Box::new( + |_: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { out.write("N/A").map_err(Into::into) }, + ), + ); + + r.register_template_string("t0", "Output name: {{name}}") + .unwrap(); + r.register_template_string("t1", "Output name: {{first_name}}") + .unwrap(); + r.register_template_string("t2", "Output name: {{./name}}") + .unwrap(); + + // when "name" is available in context, use context first + assert_eq!( + r.render("t0", &json!({"name": "Alex"})).unwrap(), + "Output name: N/A" + ); + + // when "name" is unavailable, call helper with same name + assert_eq!( + r.render("t2", &json!({"name": "Alex"})).unwrap(), + "Output name: Alex" + ); + + // output nothing when neither context nor helper available + assert_eq!( + r.render("t1", &json!({"name": "Alex"})).unwrap(), + "Output name: " + ); + + // generate error in strict mode for above case + r.set_strict_mode(true); + assert!(r.render("t1", &json!({"name": "Alex"})).is_err()); + + // output nothing when helperMissing was defined + r.set_strict_mode(false); + r.register_helper( + "helperMissing", + Box::new( + |h: &Helper<'_, '_>, + _: &Registry<'_>, + _: &Context, + _: &mut RenderContext<'_, '_>, + out: &mut dyn Output| + -> Result<(), RenderError> { + let name = h.name(); + out.write(&format!("{} not resolved", name))?; + Ok(()) + }, + ), + ); + assert_eq!( + r.render("t1", &json!({"name": "Alex"})).unwrap(), + "Output name: first_name not resolved" + ); +} diff --git a/vendor/handlebars/src/sources.rs b/vendor/handlebars/src/sources.rs new file mode 100644 index 000000000..8c8b2ba57 --- /dev/null +++ b/vendor/handlebars/src/sources.rs @@ -0,0 +1,34 @@ +use std::fs::File; +use std::io::{BufReader, Error as IOError, Read}; +use std::path::PathBuf; + +pub(crate) trait Source { + type Item; + type Error; + + fn load(&self) -> Result; +} + +pub(crate) struct FileSource { + path: PathBuf, +} + +impl FileSource { + pub(crate) fn new(path: PathBuf) -> FileSource { + FileSource { path } + } +} + +impl Source for FileSource { + type Item = String; + type Error = IOError; + + fn load(&self) -> Result { + let mut reader = BufReader::new(File::open(&self.path)?); + + let mut buf = String::new(); + reader.read_to_string(&mut buf)?; + + Ok(buf) + } +} diff --git a/vendor/handlebars/src/support.rs b/vendor/handlebars/src/support.rs new file mode 100644 index 000000000..bd5564d32 --- /dev/null +++ b/vendor/handlebars/src/support.rs @@ -0,0 +1,76 @@ +pub mod str { + use std::io::{Result, Write}; + + #[derive(Debug)] + pub struct StringWriter { + buf: Vec, + } + + impl Default for StringWriter { + fn default() -> Self { + Self::new() + } + } + + impl StringWriter { + pub fn new() -> StringWriter { + StringWriter { + buf: Vec::with_capacity(8 * 1024), + } + } + + pub fn into_string(self) -> String { + if let Ok(s) = String::from_utf8(self.buf) { + s + } else { + String::new() + } + } + } + + impl Write for StringWriter { + fn write(&mut self, buf: &[u8]) -> Result { + self.buf.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> Result<()> { + Ok(()) + } + } + + /// See https://github.com/handlebars-lang/handlebars.js/blob/37411901da42200ced8e1a7fc2f67bf83526b497/lib/handlebars/utils.js#L1 + pub fn escape_html(s: &str) -> String { + let mut output = String::new(); + for c in s.chars() { + match c { + '<' => output.push_str("<"), + '>' => output.push_str(">"), + '"' => output.push_str("""), + '&' => output.push_str("&"), + '\'' => output.push_str("'"), + '`' => output.push_str("`"), + '=' => output.push_str("="), + _ => output.push(c), + } + } + output + } + + #[cfg(test)] + mod test { + use crate::support::str::StringWriter; + use std::io::Write; + + #[test] + fn test_string_writer() { + let mut sw = StringWriter::new(); + + let _ = sw.write("hello".to_owned().into_bytes().as_ref()); + let _ = sw.write("world".to_owned().into_bytes().as_ref()); + + let s = sw.into_string(); + assert_eq!(s, "helloworld".to_string()); + } + } +} diff --git a/vendor/handlebars/src/template.rs b/vendor/handlebars/src/template.rs new file mode 100644 index 000000000..87f853799 --- /dev/null +++ b/vendor/handlebars/src/template.rs @@ -0,0 +1,1254 @@ +use std::collections::{HashMap, VecDeque}; +use std::convert::From; +use std::iter::Peekable; +use std::str::FromStr; + +use pest::error::LineColLocation; +use pest::iterators::Pair; +use pest::{Parser, Position, Span}; +use serde_json::value::Value as Json; + +use crate::error::{TemplateError, TemplateErrorReason}; +use crate::grammar::{self, HandlebarsParser, Rule}; +use crate::json::path::{parse_json_path_from_iter, Path}; + +use self::TemplateElement::*; + +#[derive(PartialEq, Clone, Debug)] +pub struct TemplateMapping(pub usize, pub usize); + +/// A handlebars template +#[derive(PartialEq, Clone, Debug, Default)] +pub struct Template { + pub name: Option, + pub elements: Vec, + pub mapping: Vec, +} + +#[derive(PartialEq, Clone, Debug)] +pub struct Subexpression { + // we use box here avoid resursive struct definition + pub element: Box, +} + +impl Subexpression { + pub fn new( + name: Parameter, + params: Vec, + hash: HashMap, + ) -> Subexpression { + Subexpression { + element: Box::new(Expression(Box::new(HelperTemplate { + name, + params, + hash, + template: None, + inverse: None, + block_param: None, + block: false, + }))), + } + } + + pub fn is_helper(&self) -> bool { + match *self.as_element() { + TemplateElement::Expression(ref ht) => !ht.is_name_only(), + _ => false, + } + } + + pub fn as_element(&self) -> &TemplateElement { + self.element.as_ref() + } + + pub fn name(&self) -> &str { + match *self.as_element() { + // FIXME: avoid unwrap here + Expression(ref ht) => ht.name.as_name().unwrap(), + _ => unreachable!(), + } + } + + pub fn params(&self) -> Option<&Vec> { + match *self.as_element() { + Expression(ref ht) => Some(&ht.params), + _ => None, + } + } + + pub fn hash(&self) -> Option<&HashMap> { + match *self.as_element() { + Expression(ref ht) => Some(&ht.hash), + _ => None, + } + } +} + +#[derive(PartialEq, Clone, Debug)] +pub enum BlockParam { + Single(Parameter), + Pair((Parameter, Parameter)), +} + +#[derive(PartialEq, Clone, Debug)] +pub struct ExpressionSpec { + pub name: Parameter, + pub params: Vec, + pub hash: HashMap, + pub block_param: Option, + pub omit_pre_ws: bool, + pub omit_pro_ws: bool, +} + +#[derive(PartialEq, Clone, Debug)] +pub enum Parameter { + // for helper name only + Name(String), + // for expression, helper param and hash + Path(Path), + Literal(Json), + Subexpression(Subexpression), +} + +#[derive(PartialEq, Clone, Debug)] +pub struct HelperTemplate { + pub name: Parameter, + pub params: Vec, + pub hash: HashMap, + pub block_param: Option, + pub template: Option