diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-17 12:02:58 +0000 |
commit | 698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch) | |
tree | 173a775858bd501c378080a10dca74132f05bc50 /vendor/handlebars/src | |
parent | Initial commit. (diff) | |
download | rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip |
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
32 files changed, 8498 insertions, 0 deletions
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<String>), + // an actual value holder + Value(Json), +} + +impl BlockParamHolder { + pub fn value(v: Json) -> BlockParamHolder { + BlockParamHolder::Value(v) + } + + pub fn path(r: Vec<String>) -> 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<String>) -> 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<String>, + /// the base_value of current block scope, when the block is using a + /// constant or derived value as block base + base_value: Option<Json>, + /// 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<String> { + &self.base_path + } + + /// borrow a mutable reference to the base path + pub fn base_path_mut(&mut self) -> &mut Vec<String> { + &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<String, Json>; + +/// 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<String>), + // relative path and path root + RelativePath(Vec<String>), + // relative path against block param value + BlockParamValue(Vec<String>, &'a Json), + // relative path against derived value, + LocalValue(Vec<String>, &'a Json), +} + +fn parse_json_visitor<'a, 'reg>( + relative_path: &[PathSeg], + block_contexts: &'a VecDeque<BlockContext<'reg>>, + 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<Option<&'a Json>, RenderError> { + let result = match d { + Some(&Json::Array(ref l)) => p.parse::<usize>().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<BlockContext<'reg>>, + p: &str, +) -> Option<(&'a BlockParamHolder, &'a Vec<String>)> { + 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<T: Serialize>(e: T) -> Result<Context, RenderError> { + 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<BlockContext<'reg>>, + ) -> Result<ScopedJson<'reg, 'rc>, 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<ScopedJson<'reg, 'rc>, 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<String>, + } + + #[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<S>(&self, _: S) -> Result<S::Ok, S::Error> + 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<String, RenderError> { + 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<String>, + pub line_no: Option<usize>, + pub column_no: Option<usize>, + cause: Option<Box<dyn Error + Send + Sync + 'static>>, + 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<IOError> for RenderError { + fn from(e: IOError) -> RenderError { + RenderError::from_error("Cannot generate output.", e) + } +} + +impl From<SerdeError> for RenderError { + fn from(e: SerdeError) -> RenderError { + RenderError::from_error("Failed to access JSON data.", e) + } +} + +impl From<FromUtf8Error> for RenderError { + fn from(e: FromUtf8Error) -> RenderError { + RenderError::from_error("Failed to generate bytes.", e) + } +} + +impl From<ParseIntError> for RenderError { + fn from(e: ParseIntError) -> RenderError { + RenderError::from_error("Cannot access array/vector with string index.", e) + } +} + +impl From<TemplateError> for RenderError { + fn from(e: TemplateError) -> RenderError { + RenderError::from_error("Failed to parse template.", e) + } +} + +#[cfg(feature = "script_helper")] +impl From<Box<EvalAltResult>> for RenderError { + fn from(e: Box<EvalAltResult>) -> RenderError { + RenderError::from_error("Cannot convert data to Rhai dynamic", e) + } +} + +#[cfg(feature = "script_helper")] +impl From<ScriptError> for RenderError { + fn from(e: ScriptError) -> RenderError { + RenderError::from_error("Failed to load rhai script", e) + } +} + +impl RenderError { + pub fn new<T: AsRef<str>>(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<E>(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<String>, + pub line_no: Option<usize>, + pub column_no: Option<usize>, + segment: Option<String>, +} + +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<WalkdirError> 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![ + "<h1> helloworld </h1> ", + 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 = "<h1> {{hello}} </h1>"; + 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!["{{!-- <hello {{ a-b c-d}} {{d-c}} ok --}}", + "{{!-- + <li><a href=\"{{up-dir nest-count}}{{base-url}}index.html\">{{this.title}}</a></li> + --}}", + "{{! -- 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<String>>, + 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<String>>, + 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<String, u16> = 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::<String>::new(), + }; + let r0 = handlebars.render("t0", &m1).unwrap(); + assert_eq!(r0, "empty"); + + let m2 = btreemap! { + "b".to_string() => Vec::<String>::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(), "template<T>template<T>".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::<Vec<u64>>()); + 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::<Vec<u64>>()); + 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#"<ul> + {{#each a}} + {{!-- comment --}} + <li>{{this}}</li> + {{/each}} +</ul>"#; + assert_eq!( + r#"<ul> + <li>0</li> + <li>1</li> +</ul>"#, + 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::<Vec<String>>() + .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<ScopedJson<'reg, 'rc>, 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<String, Vec<u16>> = 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<String>, + } + + #[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<ScopedJson<'reg, 'rc>, 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<String, RenderError>>; +// +// pub fn helper_dummy (ctx: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> { +// 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<ScopedJson<'reg, 'rc>, RenderError> { + let params: Dynamic = to_dynamic(params.iter().map(|p| p.value()).collect::<Vec<&Json>>())?; + + let hash: Dynamic = to_dynamic( + hash.iter() + .map(|(k, v)| ((*k).to_owned(), v.value())) + .collect::<HashMap<String, &Json>>(), + )?; + + let mut scope = Scope::new(); + scope.push_dynamic("params", params); + scope.push_dynamic("hash", hash); + + let result = engine + .eval_ast_with_scope::<Dynamic>(&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<ScopedJson<'reg, 'rc>, 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::<Json>(&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<PathSeg>, String)), + Local((usize, String, String)), +} + +impl Path { + pub(crate) fn new(raw: &str, segs: Vec<PathSeg>) -> 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<Path, RenderError> { + 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<I>, limit: usize) -> Vec<PathSeg> +where + I: Iterator<Item = Pair<'a, Rule>>, +{ + 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<String>, 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<String>), + 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<String>> { + match self { + ScopedJson::Context(_, ref p) => Some(p), + _ => None, + } + } +} + +impl<'reg: 'rc, 'rc> From<Json> 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<String>, + value: ScopedJson<'reg, 'rc>, +} + +impl<'reg: 'rc, 'rc> PathAndJson<'reg, 'rc> { + pub fn new( + relative_path: Option<String>, + 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<String>> { + 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<T>(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 = "<p>Hello world</p>\n<p thing=\"hello\"</p>"; + 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<i16>).is_truthy(false)); + assert!(!json!(None as Option<i16>).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<Error>> { +//! 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<Error>> { +//! 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<dyn Error>> { +//! 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<dyn Error>> { +//! 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<Json>, + last: Option<Json>, + index: Option<Json>, + key: Option<Json>, + + extra: BTreeMap<String, Json>, +} + +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::<Vec<&serde_json::Value>>();)? + $(let $kwargs = h.hash().iter().map(|(k, v)| (k.to_owned(), v.value())).collect::<std::collections::BTreeMap<&str, &serde_json::Value>>();)? + + 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<W: Write> { + write: W, +} + +impl<W: Write> Output for WriteOutput<W> { + fn write(&mut self, seg: &str) -> Result<(), IOError> { + self.write.write_all(seg.as_bytes()) + } +} + +impl<W: Write> WriteOutput<W> { + pub fn new(write: W) -> WriteOutput<W> { + WriteOutput { write } + } +} + +pub struct StringOutput { + buf: Vec<u8>, +} + +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, FromUtf8Error> { + 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<Option<Cow<'a, Template>>, 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::<HashMap<&str, &Json>>(); + + 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 = "<outer>{{> @partial-block }}</outer>"; + let template2 = "{{#> t1 }}<inner>{{> @partial-block }}</inner>{{/ 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!("<outer><inner>Hello</inner></outer>", 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<dyn Fn(&str) -> 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<String, Template>, + + helpers: HashMap<String, Arc<dyn HelperDef + Send + Sync + 'reg>>, + decorators: HashMap<String, Arc<dyn DecoratorDef + Send + Sync + 'reg>>, + + escape_fn: EscapeFn, + strict_mode: bool, + dev_mode: bool, + #[cfg(feature = "script_helper")] + pub(crate) engine: Arc<Engine>, + + template_sources: + HashMap<String, Arc<dyn Source<Item = String, Error = IoError> + Send + Sync + 'reg>>, + #[cfg(feature = "script_helper")] + script_sources: + HashMap<String, Arc<dyn Source<Item = String, Error = IoError> + 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<S>( + &mut self, + name: &str, + tpl_str: S, + ) -> Result<(), TemplateError> + where + S: AsRef<str>, + { + 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<S>(&mut self, name: &str, partial_str: S) -> Result<(), TemplateError> + where + S: AsRef<str>, + { + self.register_template_string(name, partial_str) + } + + /// Register a template from a path + pub fn register_template_file<P>( + &mut self, + name: &str, + tpl_path: P, + ) -> Result<(), TemplateError> + where + P: AsRef<Path>, + { + 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<P>( + &mut self, + tpl_extension: &'static str, + dir_path: P, + ) -> Result<(), TemplateError> + where + P: AsRef<Path>, + { + 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<dyn HelperDef + Send + Sync + 'reg>) { + 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<P>( + &mut self, + name: &str, + script_path: P, + ) -> Result<(), ScriptError> + where + P: AsRef<Path>, + { + 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<dyn DecoratorDef + Send + Sync + 'reg>, + ) { + 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<F: 'static + Fn(&str) -> 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<Result<Cow<'reg, Template>, 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<Cow<'reg, Template>, 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<Option<Arc<dyn HelperDef + Send + Sync + 'reg>>, 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<dyn HelperDef + Send + Sync>; + 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<String, Template> { + &self.templates + } + + /// Unregister all templates + pub fn clear_templates(&mut self) { + self.templates.clear(); + } + + #[inline] + fn render_to_output<O>( + &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<T>(&self, name: &str, data: &T) -> Result<String, RenderError> + 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<String, RenderError> { + 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<T, W>(&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<T>(&self, template_string: &str, data: &T) -> Result<String, RenderError> + 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<String, RenderError> { + 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<T, W>( + &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", "<h1></h1>").is_ok()); + + let tpl = Template::compile("<h2></h2>").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, "<h1>Hello {{world}}!</h1>").unwrap(); + + let file2_path = dir.path().join("t2.hbs"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "<h1>Hola {{world}}!</h1>").unwrap(); + + let file3_path = dir.path().join("t3.hbs"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "<h1>Hallo {{world}}!</h1>").unwrap(); + + let file4_path = dir.path().join(".t4.hbs"); + let mut file4: File = File::create(&file4_path).unwrap(); + writeln!(file4, "<h1>Hallo {{world}}!</h1>").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, "<h1>Hello {{world}}!</h1>").unwrap(); + + let file2_path = dir.path().join("t5.erb"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "<h1>Hello {{% world %}}!</h1>").unwrap(); + + let file3_path = dir.path().join("t6.html"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "<h1>Hello world!</h1>").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, "<h1>Bonjour {{world}}!</h1>").unwrap(); + + let file2_path = dir.path().join("portugese/t8.hbs"); + let mut file2: File = File::create(&file2_path).unwrap(); + writeln!(file2, "<h1>Ola {{world}}!</h1>").unwrap(); + + let file3_path = dir.path().join("italian/t9.hbs"); + let mut file3: File = File::create(&file3_path).unwrap(); + writeln!(file3, "<h1>Ciao {{world}}!</h1>").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, "<h1>Bonjour {{world}}!</h1>").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", "<h1></h1>").is_ok()); + + let mut sw = StringWriter::new(); + { + r.render_to_write("index", &(), &mut sw).ok().unwrap(); + } + + assert_eq!("<h1></h1>".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<ScopedJson<'reg, 'rc>, 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": "<b>bold</b>"})) + .unwrap(), + "<b>bold</b>" + ); + assert_eq!( + reg.render_template("{{ &a }}", &json!({"a": "<b>bold</b>"})) + .unwrap(), + "<b>bold</b>" + ); + } + + #[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, "<h1>Hello {{{{name}}}}!</h1>").unwrap(); + } + + reg.register_template_file("t1", &file1_path).unwrap(); + + assert_eq!( + reg.render("t1", &json!({"name": "Alex"})).unwrap(), + "<h1>Hello Alex!</h1>" + ); + + { + let mut file1: File = File::create(&file1_path).unwrap(); + write!(file1, "<h1>Privet {{{{name}}}}!</h1>").unwrap(); + } + + assert_eq!( + reg.render("t1", &json!({"name": "Alex"})).unwrap(), + "<h1>Privet Alex!</h1>" + ); + + 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<RenderContextInner<'reg, 'rc>>, + blocks: VecDeque<BlockContext<'reg>>, + // copy-on-write context + modified_context: Option<Rc<Context>>, +} + +#[derive(Clone)] +pub struct RenderContextInner<'reg: 'rc, 'rc> { + partials: BTreeMap<String, &'reg Template>, + partial_block_stack: VecDeque<&'reg Template>, + partial_block_depth: isize, + local_helpers: BTreeMap<String, Rc<dyn HelperDef + Send + Sync + 'rc>>, + /// 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<Rc<Context>> { + 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<ScopedJson<'reg, 'rc>, RenderError> { + let path = Path::parse(relative_path)?; + self.evaluate2(context, &path) + } + + pub(crate) fn evaluate2( + &self, + context: &'rc Context, + path: &Path, + ) -> Result<ScopedJson<'reg, 'rc>, 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<dyn HelperDef + Send + Sync + 'rc>, + ) { + 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<Rc<dyn HelperDef + Send + Sync + 'rc>> { + 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<PathAndJson<'reg, 'rc>>, + 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<Helper<'reg, 'rc>, 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<PathAndJson<'reg, 'rc>> { + &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<PathAndJson<'reg, 'rc>>, + 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<Decorator<'reg, 'rc>, 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<PathAndJson<'reg, 'rc>> { + &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<String, RenderError> { + 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<PathAndJson<'reg, 'rc>, 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<Cow<'reg, str>, 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<PathAndJson<'reg, 'rc>, 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("<h1>hello world</h1>".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(), + "<h1>hello world</h1>".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<String, String> = BTreeMap::new(); + let value = "<p></p>".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<String, String> = 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<String, String> = BTreeMap::new(); + let value = "world".to_string(); + m.insert("hello".to_string(), value); + let ctx = Context::wraps(&m).unwrap(); + + let elements: Vec<TemplateElement> = vec![ + RawString("<h1>".to_string()), + Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["hello"], + )))), + RawString("</h1>".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(), "<h1>world</h1>".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<String, String> = 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<String, String> = BTreeMap::new(); + + let name = "invalid_template"; + assert!(r + .register_template_string(name, "<h1>\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", "<html>{{> layout}}</html>") + .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, "<html>content</html>"); +} + +#[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<Self::Item, Self::Error>; +} + +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<Self::Item, Self::Error> { + 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<u8>, + } + + 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<usize> { + 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<String>, + pub elements: Vec<TemplateElement>, + pub mapping: Vec<TemplateMapping>, +} + +#[derive(PartialEq, Clone, Debug)] +pub struct Subexpression { + // we use box here avoid resursive struct definition + pub element: Box<TemplateElement>, +} + +impl Subexpression { + pub fn new( + name: Parameter, + params: Vec<Parameter>, + hash: HashMap<String, Parameter>, + ) -> 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<Parameter>> { + match *self.as_element() { + Expression(ref ht) => Some(&ht.params), + _ => None, + } + } + + pub fn hash(&self) -> Option<&HashMap<String, Parameter>> { + 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<Parameter>, + pub hash: HashMap<String, Parameter>, + pub block_param: Option<BlockParam>, + 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<Parameter>, + pub hash: HashMap<String, Parameter>, + pub block_param: Option<BlockParam>, + pub template: Option<Template>, + pub inverse: Option<Template>, + pub block: bool, +} + +impl HelperTemplate { + // test only + pub(crate) fn with_path(path: Path) -> HelperTemplate { + HelperTemplate { + name: Parameter::Path(path), + params: Vec::with_capacity(5), + hash: HashMap::new(), + block_param: None, + template: None, + inverse: None, + block: false, + } + } + + pub(crate) fn is_name_only(&self) -> bool { + !self.block && self.params.is_empty() && self.hash.is_empty() + } +} + +#[derive(PartialEq, Clone, Debug)] +pub struct DecoratorTemplate { + pub name: Parameter, + pub params: Vec<Parameter>, + pub hash: HashMap<String, Parameter>, + pub template: Option<Template>, +} + +impl Parameter { + pub fn as_name(&self) -> Option<&str> { + match self { + Parameter::Name(ref n) => Some(n), + Parameter::Path(ref p) => Some(p.raw()), + _ => None, + } + } + + pub fn parse(s: &str) -> Result<Parameter, TemplateError> { + let parser = HandlebarsParser::parse(Rule::parameter, s) + .map_err(|_| TemplateError::of(TemplateErrorReason::InvalidParam(s.to_owned())))?; + + let mut it = parser.flatten().peekable(); + Template::parse_param(s, &mut it, s.len() - 1) + } + + fn debug_name(&self) -> String { + if let Some(name) = self.as_name() { + name.to_owned() + } else { + format!("{:?}", self) + } + } +} + +impl Template { + pub fn new() -> Template { + Template::default() + } + + fn push_element(&mut self, e: TemplateElement, line: usize, col: usize) { + self.elements.push(e); + self.mapping.push(TemplateMapping(line, col)); + } + + fn parse_subexpression<'a, I>( + source: &'a str, + it: &mut Peekable<I>, + limit: usize, + ) -> Result<Parameter, TemplateError> + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let espec = Template::parse_expression(source, it.by_ref(), limit)?; + Ok(Parameter::Subexpression(Subexpression::new( + espec.name, + espec.params, + espec.hash, + ))) + } + + fn parse_name<'a, I>( + source: &'a str, + it: &mut Peekable<I>, + _: usize, + ) -> Result<Parameter, TemplateError> + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let name_node = it.next().unwrap(); + let rule = name_node.as_rule(); + let name_span = name_node.as_span(); + match rule { + Rule::identifier | Rule::partial_identifier | Rule::invert_tag_item => { + Ok(Parameter::Name(name_span.as_str().to_owned())) + } + Rule::reference => { + let paths = parse_json_path_from_iter(it, name_span.end()); + Ok(Parameter::Path(Path::new(name_span.as_str(), paths))) + } + Rule::subexpression => { + Template::parse_subexpression(source, it.by_ref(), name_span.end()) + } + _ => unreachable!(), + } + } + + fn parse_param<'a, I>( + source: &'a str, + it: &mut Peekable<I>, + _: usize, + ) -> Result<Parameter, TemplateError> + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let mut param = it.next().unwrap(); + if param.as_rule() == Rule::param { + param = it.next().unwrap(); + } + let param_rule = param.as_rule(); + let param_span = param.as_span(); + let result = match param_rule { + Rule::reference => { + let path_segs = parse_json_path_from_iter(it, param_span.end()); + Parameter::Path(Path::new(param_span.as_str(), path_segs)) + } + Rule::literal => { + let s = param_span.as_str(); + if let Ok(json) = Json::from_str(s) { + Parameter::Literal(json) + } else { + Parameter::Name(s.to_owned()) + } + } + Rule::subexpression => { + Template::parse_subexpression(source, it.by_ref(), param_span.end())? + } + _ => unreachable!(), + }; + + while let Some(n) = it.peek() { + let n_span = n.as_span(); + if n_span.end() > param_span.end() { + break; + } + it.next(); + } + + Ok(result) + } + + fn parse_hash<'a, I>( + source: &'a str, + it: &mut Peekable<I>, + limit: usize, + ) -> Result<(String, Parameter), TemplateError> + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let name = it.next().unwrap(); + let name_node = name.as_span(); + // identifier + let key = name_node.as_str().to_owned(); + + let value = Template::parse_param(source, it.by_ref(), limit)?; + Ok((key, value)) + } + + fn parse_block_param<'a, I>(_: &'a str, it: &mut Peekable<I>, limit: usize) -> BlockParam + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let p1_name = it.next().unwrap(); + let p1_name_span = p1_name.as_span(); + // identifier + let p1 = p1_name_span.as_str().to_owned(); + + let p2 = it.peek().and_then(|p2_name| { + let p2_name_span = p2_name.as_span(); + if p2_name_span.end() <= limit { + Some(p2_name_span.as_str().to_owned()) + } else { + None + } + }); + + if let Some(p2) = p2 { + it.next(); + BlockParam::Pair((Parameter::Name(p1), Parameter::Name(p2))) + } else { + BlockParam::Single(Parameter::Name(p1)) + } + } + + fn parse_expression<'a, I>( + source: &'a str, + it: &mut Peekable<I>, + limit: usize, + ) -> Result<ExpressionSpec, TemplateError> + where + I: Iterator<Item = Pair<'a, Rule>>, + { + let mut params: Vec<Parameter> = Vec::new(); + let mut hashes: HashMap<String, Parameter> = HashMap::new(); + let mut omit_pre_ws = false; + let mut omit_pro_ws = false; + let mut block_param = None; + + if it.peek().unwrap().as_rule() == Rule::pre_whitespace_omitter { + omit_pre_ws = true; + it.next(); + } + + let name = Template::parse_name(source, it.by_ref(), limit)?; + + loop { + let rule; + let end; + if let Some(pair) = it.peek() { + let pair_span = pair.as_span(); + if pair_span.end() < limit { + rule = pair.as_rule(); + end = pair_span.end(); + } else { + break; + } + } else { + break; + } + + it.next(); + + match rule { + Rule::param => { + params.push(Template::parse_param(source, it.by_ref(), end)?); + } + Rule::hash => { + let (key, value) = Template::parse_hash(source, it.by_ref(), end)?; + hashes.insert(key, value); + } + Rule::block_param => { + block_param = Some(Template::parse_block_param(source, it.by_ref(), end)); + } + Rule::pro_whitespace_omitter => { + omit_pro_ws = true; + } + _ => {} + } + } + Ok(ExpressionSpec { + name, + params, + hash: hashes, + block_param, + omit_pre_ws, + omit_pro_ws, + }) + } + + fn remove_previous_whitespace(template_stack: &mut VecDeque<Template>) { + let t = template_stack.front_mut().unwrap(); + if let Some(el) = t.elements.last_mut() { + if let RawString(ref mut text) = el { + *text = text.trim_end().to_owned(); + } + } + } + + fn process_standalone_statement( + template_stack: &mut VecDeque<Template>, + source: &str, + current_span: &Span<'_>, + ) -> bool { + let with_trailing_newline = grammar::starts_with_empty_line(&source[current_span.end()..]); + + if with_trailing_newline { + let with_leading_newline = + grammar::ends_with_empty_line(&source[..current_span.start()]); + + if with_leading_newline { + let t = template_stack.front_mut().unwrap(); + // check the last element before current + if let Some(el) = t.elements.last_mut() { + if let RawString(ref mut text) = el { + // trim leading space for standalone statement + *text = text + .trim_end_matches(grammar::whitespace_matcher) + .to_owned(); + } + } + } + + // return true when the item is the first element in root template + current_span.start() == 0 || with_leading_newline + } else { + false + } + } + + fn raw_string<'a>( + source: &'a str, + pair: Option<Pair<'a, Rule>>, + trim_start: bool, + trim_start_line: bool, + ) -> TemplateElement { + let mut s = String::from(source); + + if let Some(pair) = pair { + // the source may contains leading space because of pest's limitation + // we calculate none space start here in order to correct the offset + let pair_span = pair.as_span(); + + let current_start = pair_span.start(); + let span_length = pair_span.end() - current_start; + let leading_space_offset = s.len() - span_length; + + // we would like to iterate pair reversely in order to remove certain + // index from our string buffer so here we convert the inner pairs to + // a vector. + for sub_pair in pair.into_inner().rev() { + // remove escaped backslash + if sub_pair.as_rule() == Rule::escape { + let escape_span = sub_pair.as_span(); + + let backslash_pos = escape_span.start(); + let backslash_rel_pos = leading_space_offset + backslash_pos - current_start; + s.remove(backslash_rel_pos); + } + } + } + + if trim_start { + RawString(s.trim_start().to_owned()) + } else if trim_start_line { + RawString( + s.trim_start_matches(grammar::whitespace_matcher) + .trim_start_matches(grammar::newline_matcher) + .to_owned(), + ) + } else { + RawString(s) + } + } + + pub fn compile<'a>(source: &'a str) -> Result<Template, TemplateError> { + let mut helper_stack: VecDeque<HelperTemplate> = VecDeque::new(); + let mut decorator_stack: VecDeque<DecoratorTemplate> = VecDeque::new(); + let mut template_stack: VecDeque<Template> = VecDeque::new(); + + let mut omit_pro_ws = false; + // flag for newline removal of standalone statements + // this option is marked as true when standalone statement is detected + // then the leading whitespaces and newline of next rawstring will be trimed + let mut trim_line_requiered = false; + + let parser_queue = HandlebarsParser::parse(Rule::handlebars, source).map_err(|e| { + let (line_no, col_no) = match e.line_col { + LineColLocation::Pos(line_col) => line_col, + LineColLocation::Span(line_col, _) => line_col, + }; + TemplateError::of(TemplateErrorReason::InvalidSyntax).at(source, line_no, col_no) + })?; + + // dbg!(parser_queue.clone().flatten()); + + // remove escape from our pair queue + let mut it = parser_queue + .flatten() + .filter(|p| { + // remove rules that should be silent but not for now due to pest limitation + !matches!(p.as_rule(), Rule::escape) + }) + .peekable(); + let mut end_pos: Option<Position<'_>> = None; + loop { + if let Some(pair) = it.next() { + let prev_end = end_pos.as_ref().map(|p| p.pos()).unwrap_or(0); + let rule = pair.as_rule(); + let span = pair.as_span(); + + let is_trailing_string = rule != Rule::template + && span.start() != prev_end + && !omit_pro_ws + && rule != Rule::raw_text + && rule != Rule::raw_block_text; + + if is_trailing_string { + // trailing string check + let (line_no, col_no) = span.start_pos().line_col(); + if rule == Rule::raw_block_end { + let mut t = Template::new(); + t.push_element( + Template::raw_string( + &source[prev_end..span.start()], + None, + false, + trim_line_requiered, + ), + line_no, + col_no, + ); + template_stack.push_front(t); + } else { + let t = template_stack.front_mut().unwrap(); + t.push_element( + Template::raw_string( + &source[prev_end..span.start()], + None, + false, + trim_line_requiered, + ), + line_no, + col_no, + ); + } + } + + let (line_no, col_no) = span.start_pos().line_col(); + match rule { + Rule::template => { + template_stack.push_front(Template::new()); + } + Rule::raw_text => { + // leading space fix + let start = if span.start() != prev_end { + prev_end + } else { + span.start() + }; + + let t = template_stack.front_mut().unwrap(); + t.push_element( + Template::raw_string( + &source[start..span.end()], + Some(pair.clone()), + omit_pro_ws, + trim_line_requiered, + ), + line_no, + col_no, + ); + + // reset standalone statement marker + trim_line_requiered = false; + } + Rule::helper_block_start + | Rule::raw_block_start + | Rule::decorator_block_start + | Rule::partial_block_start => { + let exp = Template::parse_expression(source, it.by_ref(), span.end())?; + + match rule { + Rule::helper_block_start | Rule::raw_block_start => { + let helper_template = HelperTemplate { + name: exp.name, + params: exp.params, + hash: exp.hash, + block_param: exp.block_param, + block: true, + template: None, + inverse: None, + }; + helper_stack.push_front(helper_template); + } + Rule::decorator_block_start | Rule::partial_block_start => { + let decorator = DecoratorTemplate { + name: exp.name, + params: exp.params, + hash: exp.hash, + template: None, + }; + decorator_stack.push_front(decorator); + } + _ => unreachable!(), + } + + if exp.omit_pre_ws { + Template::remove_previous_whitespace(&mut template_stack); + } + omit_pro_ws = exp.omit_pro_ws; + + // standalone statement check, it also removes leading whitespaces of + // previous rawstring when standalone statement detected + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let t = template_stack.front_mut().unwrap(); + t.mapping.push(TemplateMapping(line_no, col_no)); + } + Rule::invert_tag => { + // hack: invert_tag structure is similar to ExpressionSpec, so I + // use it here to represent the data + let exp = Template::parse_expression(source, it.by_ref(), span.end())?; + + if exp.omit_pre_ws { + Template::remove_previous_whitespace(&mut template_stack); + } + omit_pro_ws = exp.omit_pro_ws; + + // standalone statement check, it also removes leading whitespaces of + // previous rawstring when standalone statement detected + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let t = template_stack.pop_front().unwrap(); + let h = helper_stack.front_mut().unwrap(); + h.template = Some(t); + } + Rule::raw_block_text => { + let mut t = Template::new(); + t.push_element( + Template::raw_string( + span.as_str(), + Some(pair.clone()), + omit_pro_ws, + trim_line_requiered, + ), + line_no, + col_no, + ); + template_stack.push_front(t); + } + Rule::expression + | Rule::html_expression + | Rule::decorator_expression + | Rule::partial_expression + | Rule::helper_block_end + | Rule::raw_block_end + | Rule::decorator_block_end + | Rule::partial_block_end => { + let exp = Template::parse_expression(source, it.by_ref(), span.end())?; + + if exp.omit_pre_ws { + Template::remove_previous_whitespace(&mut template_stack); + } + omit_pro_ws = exp.omit_pro_ws; + + match rule { + Rule::expression | Rule::html_expression => { + let helper_template = HelperTemplate { + name: exp.name, + params: exp.params, + hash: exp.hash, + block_param: exp.block_param, + block: false, + template: None, + inverse: None, + }; + let el = if rule == Rule::expression { + Expression(Box::new(helper_template)) + } else { + HtmlExpression(Box::new(helper_template)) + }; + let t = template_stack.front_mut().unwrap(); + t.push_element(el, line_no, col_no); + } + Rule::decorator_expression | Rule::partial_expression => { + let decorator = DecoratorTemplate { + name: exp.name, + params: exp.params, + hash: exp.hash, + template: None, + }; + let el = if rule == Rule::decorator_expression { + DecoratorExpression(Box::new(decorator)) + } else { + PartialExpression(Box::new(decorator)) + }; + let t = template_stack.front_mut().unwrap(); + t.push_element(el, line_no, col_no); + } + Rule::helper_block_end | Rule::raw_block_end => { + // standalone statement check, it also removes leading whitespaces of + // previous rawstring when standalone statement detected + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let mut h = helper_stack.pop_front().unwrap(); + let close_tag_name = exp.name.as_name(); + if h.name.as_name() == close_tag_name { + let prev_t = template_stack.pop_front().unwrap(); + if h.template.is_some() { + h.inverse = Some(prev_t); + } else { + h.template = Some(prev_t); + } + let t = template_stack.front_mut().unwrap(); + t.elements.push(HelperBlock(Box::new(h))); + } else { + return Err(TemplateError::of( + TemplateErrorReason::MismatchingClosedHelper( + h.name.debug_name(), + exp.name.debug_name(), + ), + ) + .at(source, line_no, col_no)); + } + } + Rule::decorator_block_end | Rule::partial_block_end => { + // standalone statement check, it also removes leading whitespaces of + // previous rawstring when standalone statement detected + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let mut d = decorator_stack.pop_front().unwrap(); + let close_tag_name = exp.name.as_name(); + if d.name.as_name() == close_tag_name { + let prev_t = template_stack.pop_front().unwrap(); + d.template = Some(prev_t); + let t = template_stack.front_mut().unwrap(); + if rule == Rule::decorator_block_end { + t.elements.push(DecoratorBlock(Box::new(d))); + } else { + t.elements.push(PartialBlock(Box::new(d))); + } + } else { + return Err(TemplateError::of( + TemplateErrorReason::MismatchingClosedDecorator( + d.name.debug_name(), + exp.name.debug_name(), + ), + ) + .at(source, line_no, col_no)); + } + } + _ => unreachable!(), + } + } + Rule::hbs_comment_compact => { + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let text = span + .as_str() + .trim_start_matches("{{!") + .trim_end_matches("}}"); + let t = template_stack.front_mut().unwrap(); + t.push_element(Comment(text.to_owned()), line_no, col_no); + } + Rule::hbs_comment => { + trim_line_requiered = Template::process_standalone_statement( + &mut template_stack, + source, + &span, + ); + + let text = span + .as_str() + .trim_start_matches("{{!--") + .trim_end_matches("--}}"); + let t = template_stack.front_mut().unwrap(); + t.push_element(Comment(text.to_owned()), line_no, col_no); + } + _ => {} + } + + if rule != Rule::template { + end_pos = Some(span.end_pos()); + } + } else { + let prev_end = end_pos.as_ref().map(|e| e.pos()).unwrap_or(0); + if prev_end < source.len() { + let text = &source[prev_end..source.len()]; + // is some called in if check + let (line_no, col_no) = end_pos.unwrap().line_col(); + let t = template_stack.front_mut().unwrap(); + t.push_element(RawString(text.to_owned()), line_no, col_no); + } + let root_template = template_stack.pop_front().unwrap(); + return Ok(root_template); + } + } + } + + pub fn compile_with_name<S: AsRef<str>>( + source: S, + name: String, + ) -> Result<Template, TemplateError> { + match Template::compile(source.as_ref()) { + Ok(mut t) => { + t.name = Some(name); + Ok(t) + } + Err(e) => Err(e.in_template(name)), + } + } +} + +#[derive(PartialEq, Clone, Debug)] +pub enum TemplateElement { + RawString(String), + HtmlExpression(Box<HelperTemplate>), + Expression(Box<HelperTemplate>), + HelperBlock(Box<HelperTemplate>), + DecoratorExpression(Box<DecoratorTemplate>), + DecoratorBlock(Box<DecoratorTemplate>), + PartialExpression(Box<DecoratorTemplate>), + PartialBlock(Box<DecoratorTemplate>), + Comment(String), +} + +#[cfg(test)] +mod test { + use super::*; + use crate::error::TemplateErrorReason; + + #[test] + fn test_parse_escaped_tag_raw_string() { + let source = r"foo \{{bar}}"; + let t = Template::compile(source).ok().unwrap(); + assert_eq!(t.elements.len(), 1); + assert_eq!( + *t.elements.get(0).unwrap(), + RawString("foo {{bar}}".to_string()) + ); + } + + #[test] + fn test_pure_backslash_raw_string() { + let source = r"\\\\"; + let t = Template::compile(source).ok().unwrap(); + assert_eq!(t.elements.len(), 1); + assert_eq!(*t.elements.get(0).unwrap(), RawString(source.to_string())); + } + + #[test] + fn test_parse_escaped_block_raw_string() { + let source = r"\{{{{foo}}}} bar"; + let t = Template::compile(source).ok().unwrap(); + assert_eq!(t.elements.len(), 1); + assert_eq!( + *t.elements.get(0).unwrap(), + RawString("{{{{foo}}}} bar".to_string()) + ); + } + + #[test] + fn test_parse_template() { + let source = "<h1>{{title}} 你好</h1> {{{content}}} +{{#if date}}<p>good</p>{{else}}<p>bad</p>{{/if}}<img>{{foo bar}}中文你好 +{{#unless true}}kitkat{{^}}lollipop{{/unless}}"; + let t = Template::compile(source).ok().unwrap(); + + assert_eq!(t.elements.len(), 10); + + assert_eq!(*t.elements.get(0).unwrap(), RawString("<h1>".to_string())); + assert_eq!( + *t.elements.get(1).unwrap(), + Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["title"] + )))) + ); + + assert_eq!( + *t.elements.get(3).unwrap(), + HtmlExpression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["content"], + )))) + ); + + match *t.elements.get(5).unwrap() { + HelperBlock(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "if".to_string()); + assert_eq!(h.params.len(), 1); + assert_eq!(h.template.as_ref().unwrap().elements.len(), 1); + } + _ => { + panic!("Helper expected here."); + } + }; + + match *t.elements.get(7).unwrap() { + Expression(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "foo".to_string()); + assert_eq!(h.params.len(), 1); + assert_eq!( + *(h.params.get(0).unwrap()), + Parameter::Path(Path::with_named_paths(&["bar"])) + ) + } + _ => { + panic!("Helper expression here"); + } + }; + + match *t.elements.get(9).unwrap() { + HelperBlock(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "unless".to_string()); + assert_eq!(h.params.len(), 1); + assert_eq!(h.inverse.as_ref().unwrap().elements.len(), 1); + } + _ => { + panic!("Helper expression here"); + } + }; + } + + #[test] + fn test_parse_block_partial_path_identifier() { + let source = "{{#> foo/bar}}{{/foo/bar}}"; + assert!(Template::compile(source).is_ok()); + } + + #[test] + fn test_parse_error() { + let source = "{{#ifequals name compare=\"hello\"}}\nhello\n\t{{else}}\ngood"; + + let terr = Template::compile(source).unwrap_err(); + + assert!(matches!(terr.reason, TemplateErrorReason::InvalidSyntax)); + assert_eq!(terr.line_no.unwrap(), 4); + assert_eq!(terr.column_no.unwrap(), 5); + } + + #[test] + fn test_subexpression() { + let source = + "{{foo (bar)}}{{foo (bar baz)}} hello {{#if (baz bar) then=(bar)}}world{{/if}}"; + let t = Template::compile(source).ok().unwrap(); + + assert_eq!(t.elements.len(), 4); + match *t.elements.get(0).unwrap() { + Expression(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "foo".to_owned()); + assert_eq!(h.params.len(), 1); + if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { + assert_eq!(t.name(), "bar".to_owned()); + } else { + panic!("Subexpression expected"); + } + } + _ => { + panic!("Helper expression expected"); + } + }; + + match *t.elements.get(1).unwrap() { + Expression(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "foo".to_string()); + assert_eq!(h.params.len(), 1); + if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { + assert_eq!(t.name(), "bar".to_owned()); + if let Some(Parameter::Path(p)) = t.params().unwrap().get(0) { + assert_eq!(p, &Path::with_named_paths(&["baz"])); + } else { + panic!("non-empty param expected "); + } + } else { + panic!("Subexpression expected"); + } + } + _ => { + panic!("Helper expression expected"); + } + }; + + match *t.elements.get(3).unwrap() { + HelperBlock(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "if".to_string()); + assert_eq!(h.params.len(), 1); + assert_eq!(h.hash.len(), 1); + + if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { + assert_eq!(t.name(), "baz".to_owned()); + if let Some(Parameter::Path(p)) = t.params().unwrap().get(0) { + assert_eq!(p, &Path::with_named_paths(&["bar"])); + } else { + panic!("non-empty param expected "); + } + } else { + panic!("Subexpression expected (baz bar)"); + } + + if let &Parameter::Subexpression(ref t) = h.hash.get("then").unwrap() { + assert_eq!(t.name(), "bar".to_owned()); + } else { + panic!("Subexpression expected (bar)"); + } + } + _ => { + panic!("HelperBlock expected"); + } + } + } + + #[test] + fn test_white_space_omitter() { + let source = "hello~ {{~world~}} \n !{{~#if true}}else{{/if~}}"; + let t = Template::compile(source).ok().unwrap(); + + assert_eq!(t.elements.len(), 4); + + assert_eq!(t.elements[0], RawString("hello~".to_string())); + assert_eq!( + t.elements[1], + Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( + &["world"] + )))) + ); + assert_eq!(t.elements[2], RawString("!".to_string())); + + let t2 = Template::compile("{{#if true}}1 {{~ else ~}} 2 {{~/if}}") + .ok() + .unwrap(); + assert_eq!(t2.elements.len(), 1); + match t2.elements[0] { + HelperBlock(ref h) => { + assert_eq!( + h.template.as_ref().unwrap().elements[0], + RawString("1".to_string()) + ); + assert_eq!( + h.inverse.as_ref().unwrap().elements[0], + RawString("2".to_string()) + ); + } + _ => unreachable!(), + } + } + + #[test] + fn test_unclosed_expression() { + let sources = ["{{invalid", "{{{invalid", "{{invalid}", "{{!hello"]; + for s in sources.iter() { + let result = Template::compile(s.to_owned()); + if let Err(e) = result { + match e.reason { + TemplateErrorReason::InvalidSyntax => {} + _ => { + panic!("Unexpected error type {}", e); + } + } + } else { + panic!("Undetected error"); + } + } + } + + #[test] + fn test_raw_helper() { + let source = "hello{{{{raw}}}}good{{night}}{{{{/raw}}}}world"; + match Template::compile(source) { + Ok(t) => { + assert_eq!(t.elements.len(), 3); + assert_eq!(t.elements[0], RawString("hello".to_owned())); + assert_eq!(t.elements[2], RawString("world".to_owned())); + match t.elements[1] { + HelperBlock(ref h) => { + assert_eq!(h.name.as_name().unwrap(), "raw".to_owned()); + if let Some(ref ht) = h.template { + assert_eq!(ht.elements.len(), 1); + assert_eq!( + *ht.elements.get(0).unwrap(), + RawString("good{{night}}".to_owned()) + ); + } else { + panic!("helper template not found"); + } + } + _ => { + panic!("Unexpected element type"); + } + } + } + Err(e) => { + panic!("{}", e); + } + } + } + + #[test] + fn test_literal_parameter_parser() { + match Template::compile("{{hello 1 name=\"value\" valid=false ref=someref}}") { + Ok(t) => { + if let Expression(ref ht) = t.elements[0] { + assert_eq!(ht.params[0], Parameter::Literal(json!(1))); + assert_eq!( + ht.hash["name"], + Parameter::Literal(Json::String("value".to_owned())) + ); + assert_eq!(ht.hash["valid"], Parameter::Literal(Json::Bool(false))); + assert_eq!( + ht.hash["ref"], + Parameter::Path(Path::with_named_paths(&["someref"])) + ); + } + } + Err(e) => panic!("{}", e), + } + } + + #[test] + fn test_template_mapping() { + match Template::compile("hello\n {{~world}}\n{{#if nice}}\n\thello\n{{/if}}") { + Ok(t) => { + assert_eq!(t.mapping.len(), t.elements.len()); + assert_eq!(t.mapping[0], TemplateMapping(1, 1)); + assert_eq!(t.mapping[1], TemplateMapping(2, 3)); + assert_eq!(t.mapping[3], TemplateMapping(3, 1)); + } + Err(e) => panic!("{}", e), + } + } + + #[test] + fn test_whitespace_elements() { + let c = Template::compile( + " {{elem}}\n\t{{#if true}} \ + {{/if}}\n{{{{raw}}}} {{{{/raw}}}}\n{{{{raw}}}}{{{{/raw}}}}\n", + ); + let r = c.unwrap(); + // the \n after last raw block is dropped by pest + assert_eq!(r.elements.len(), 9); + } + + #[test] + fn test_block_param() { + match Template::compile("{{#each people as |person|}}{{person}}{{/each}}") { + Ok(t) => { + if let HelperBlock(ref ht) = t.elements[0] { + if let Some(BlockParam::Single(Parameter::Name(ref n))) = ht.block_param { + assert_eq!(n, "person"); + } else { + panic!("block param expected.") + } + } else { + panic!("Helper block expected"); + } + } + Err(e) => panic!("{}", e), + } + + match Template::compile("{{#each people as |val key|}}{{person}}{{/each}}") { + Ok(t) => { + if let HelperBlock(ref ht) = t.elements[0] { + if let Some(BlockParam::Pair(( + Parameter::Name(ref n1), + Parameter::Name(ref n2), + ))) = ht.block_param + { + assert_eq!(n1, "val"); + assert_eq!(n2, "key"); + } else { + panic!("helper block param expected."); + } + } else { + panic!("Helper block expected"); + } + } + Err(e) => panic!("{}", e), + } + } + + #[test] + fn test_decorator() { + match Template::compile("hello {{* ssh}} world") { + Err(e) => panic!("{}", e), + Ok(t) => { + if let DecoratorExpression(ref de) = t.elements[1] { + assert_eq!(de.name.as_name(), Some("ssh")); + assert_eq!(de.template, None); + } + } + } + + match Template::compile("hello {{> ssh}} world") { + Err(e) => panic!("{}", e), + Ok(t) => { + if let PartialExpression(ref de) = t.elements[1] { + assert_eq!(de.name.as_name(), Some("ssh")); + assert_eq!(de.template, None); + } + } + } + + match Template::compile("{{#*inline \"hello\"}}expand to hello{{/inline}}{{> hello}}") { + Err(e) => panic!("{}", e), + Ok(t) => { + if let DecoratorBlock(ref db) = t.elements[0] { + assert_eq!(db.name, Parameter::Name("inline".to_owned())); + assert_eq!( + db.params[0], + Parameter::Literal(Json::String("hello".to_owned())) + ); + assert_eq!( + db.template.as_ref().unwrap().elements[0], + TemplateElement::RawString("expand to hello".to_owned()) + ); + } + } + } + + match Template::compile("{{#> layout \"hello\"}}expand to hello{{/layout}}{{> hello}}") { + Err(e) => panic!("{}", e), + Ok(t) => { + if let PartialBlock(ref db) = t.elements[0] { + assert_eq!(db.name, Parameter::Name("layout".to_owned())); + assert_eq!( + db.params[0], + Parameter::Literal(Json::String("hello".to_owned())) + ); + assert_eq!( + db.template.as_ref().unwrap().elements[0], + TemplateElement::RawString("expand to hello".to_owned()) + ); + } + } + } + } + + #[test] + fn test_panic_with_tag_name() { + let s = "{{#>(X)}}{{/X}}"; + let result = Template::compile(s); + assert!(result.is_err()); + assert_eq!("decorator \"Subexpression(Subexpression { element: Expression(HelperTemplate { name: Path(Relative(([Named(\\\"X\\\")], \\\"X\\\"))), params: [], hash: {}, block_param: None, template: None, inverse: None, block: false }) })\" was opened, but \"X\" is closing", format!("{}", result.unwrap_err().reason)); + } +} diff --git a/vendor/handlebars/src/util.rs b/vendor/handlebars/src/util.rs new file mode 100644 index 000000000..7bfca24ce --- /dev/null +++ b/vendor/handlebars/src/util.rs @@ -0,0 +1,25 @@ +pub(crate) fn empty_or_none<T>(input: &[T]) -> Option<&[T]> { + if input.is_empty() { + None + } else { + Some(input) + } +} + +#[inline] +pub(crate) fn copy_on_push_vec<T>(input: &[T], el: T) -> Vec<T> +where + T: Clone, +{ + let mut new_vec = Vec::with_capacity(input.len() + 1); + new_vec.extend_from_slice(input); + new_vec.push(el); + new_vec +} + +#[inline] +pub(crate) fn extend(base: &mut Vec<String>, slice: &[String]) { + for i in slice { + base.push(i.to_owned()); + } +} |