| 1 | use std::collections::{HashMap, VecDeque}; |
| 2 | use std::iter::Peekable; |
| 3 | use std::str::FromStr; |
| 4 | |
| 5 | use pest::error::LineColLocation; |
| 6 | use pest::iterators::Pair; |
| 7 | use pest::{Parser, Position, Span}; |
| 8 | use serde_json::value::Value as Json; |
| 9 | |
| 10 | use crate::error::{TemplateError, TemplateErrorReason}; |
| 11 | use crate::grammar::{HandlebarsParser, Rule}; |
| 12 | use crate::json::path::{parse_json_path_from_iter, Path}; |
| 13 | use crate::support; |
| 14 | |
| 15 | use self::TemplateElement::*; |
| 16 | |
| 17 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 18 | pub struct TemplateMapping(pub usize, pub usize); |
| 19 | |
| 20 | /// A handlebars template |
| 21 | #[derive(PartialEq, Eq, Clone, Debug, Default)] |
| 22 | pub struct Template { |
| 23 | pub name: Option<String>, |
| 24 | pub elements: Vec<TemplateElement>, |
| 25 | pub mapping: Vec<TemplateMapping>, |
| 26 | } |
| 27 | |
| 28 | #[derive(Default)] |
| 29 | pub(crate) struct TemplateOptions { |
| 30 | pub(crate) prevent_indent: bool, |
| 31 | pub(crate) name: Option<String>, |
| 32 | } |
| 33 | |
| 34 | impl TemplateOptions { |
| 35 | fn name(&self) -> String { |
| 36 | self.name |
| 37 | .as_ref() |
| 38 | .cloned() |
| 39 | .unwrap_or_else(|| "Unnamed".to_owned()) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 44 | pub struct Subexpression { |
| 45 | // we use box here avoid resursive struct definition |
| 46 | pub element: Box<TemplateElement>, |
| 47 | } |
| 48 | |
| 49 | impl Subexpression { |
| 50 | pub fn new( |
| 51 | name: Parameter, |
| 52 | params: Vec<Parameter>, |
| 53 | hash: HashMap<String, Parameter>, |
| 54 | ) -> Subexpression { |
| 55 | Subexpression { |
| 56 | element: Box::new(Expression(Box::new(HelperTemplate { |
| 57 | name, |
| 58 | params, |
| 59 | hash, |
| 60 | template: None, |
| 61 | inverse: None, |
| 62 | block_param: None, |
| 63 | block: false, |
| 64 | chain: false, |
| 65 | }))), |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub fn is_helper(&self) -> bool { |
| 70 | match *self.as_element() { |
| 71 | TemplateElement::Expression(ref ht) => !ht.is_name_only(), |
| 72 | _ => false, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub fn as_element(&self) -> &TemplateElement { |
| 77 | self.element.as_ref() |
| 78 | } |
| 79 | |
| 80 | pub fn name(&self) -> &str { |
| 81 | match *self.as_element() { |
| 82 | // FIXME: avoid unwrap here |
| 83 | Expression(ref ht) => ht.name.as_name().unwrap(), |
| 84 | _ => unreachable!(), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn params(&self) -> Option<&Vec<Parameter>> { |
| 89 | match *self.as_element() { |
| 90 | Expression(ref ht) => Some(&ht.params), |
| 91 | _ => None, |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | pub fn hash(&self) -> Option<&HashMap<String, Parameter>> { |
| 96 | match *self.as_element() { |
| 97 | Expression(ref ht) => Some(&ht.hash), |
| 98 | _ => None, |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 104 | pub enum BlockParam { |
| 105 | Single(Parameter), |
| 106 | Pair((Parameter, Parameter)), |
| 107 | } |
| 108 | |
| 109 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 110 | pub struct ExpressionSpec { |
| 111 | pub name: Parameter, |
| 112 | pub params: Vec<Parameter>, |
| 113 | pub hash: HashMap<String, Parameter>, |
| 114 | pub block_param: Option<BlockParam>, |
| 115 | pub omit_pre_ws: bool, |
| 116 | pub omit_pro_ws: bool, |
| 117 | } |
| 118 | |
| 119 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 120 | pub enum Parameter { |
| 121 | // for helper name only |
| 122 | Name(String), |
| 123 | // for expression, helper param and hash |
| 124 | Path(Path), |
| 125 | Literal(Json), |
| 126 | Subexpression(Subexpression), |
| 127 | } |
| 128 | |
| 129 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 130 | pub struct HelperTemplate { |
| 131 | pub name: Parameter, |
| 132 | pub params: Vec<Parameter>, |
| 133 | pub hash: HashMap<String, Parameter>, |
| 134 | pub block_param: Option<BlockParam>, |
| 135 | pub template: Option<Template>, |
| 136 | pub inverse: Option<Template>, |
| 137 | pub block: bool, |
| 138 | pub chain: bool, |
| 139 | } |
| 140 | |
| 141 | impl HelperTemplate { |
| 142 | pub fn new(exp: ExpressionSpec, block: bool) -> HelperTemplate { |
| 143 | HelperTemplate { |
| 144 | name: exp.name, |
| 145 | params: exp.params, |
| 146 | hash: exp.hash, |
| 147 | block_param: exp.block_param, |
| 148 | block, |
| 149 | template: None, |
| 150 | inverse: None, |
| 151 | chain: false, |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | pub fn new_chain(exp: ExpressionSpec, block: bool) -> HelperTemplate { |
| 156 | HelperTemplate { |
| 157 | name: exp.name, |
| 158 | params: exp.params, |
| 159 | hash: exp.hash, |
| 160 | block_param: exp.block_param, |
| 161 | block, |
| 162 | template: None, |
| 163 | inverse: None, |
| 164 | chain: true, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // test only |
| 169 | pub(crate) fn with_path(path: Path) -> HelperTemplate { |
| 170 | HelperTemplate { |
| 171 | name: Parameter::Path(path), |
| 172 | params: Vec::with_capacity(5), |
| 173 | hash: HashMap::new(), |
| 174 | block_param: None, |
| 175 | template: None, |
| 176 | inverse: None, |
| 177 | block: false, |
| 178 | chain: false, |
| 179 | } |
| 180 | } |
| 181 | |
| 182 | pub(crate) fn is_name_only(&self) -> bool { |
| 183 | !self.block && self.params.is_empty() && self.hash.is_empty() |
| 184 | } |
| 185 | |
| 186 | fn insert_inverse_node(&mut self, mut node: Box<HelperTemplate>) { |
| 187 | // Create a list in "inverse" member to hold the else-chain. |
| 188 | // Here we create the new template to save the else-chain node. |
| 189 | // The template render could render it successfully without any code add. |
| 190 | let mut new_chain_template = Template::new(); |
| 191 | node.inverse = self.inverse.take(); |
| 192 | new_chain_template.elements.push(HelperBlock(node)); |
| 193 | self.inverse = Some(new_chain_template); |
| 194 | } |
| 195 | |
| 196 | fn ref_chain_head_mut(&mut self) -> Option<&mut Box<HelperTemplate>> { |
| 197 | if self.chain { |
| 198 | if let Some(inverse_tmpl) = &mut self.inverse { |
| 199 | assert_eq!(inverse_tmpl.elements.len(), 1); |
| 200 | if let HelperBlock(helper) = &mut inverse_tmpl.elements[0] { |
| 201 | return Some(helper); |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | None |
| 206 | } |
| 207 | |
| 208 | fn set_chain_template(&mut self, tmpl: Option<Template>) { |
| 209 | if let Some(hepler) = self.ref_chain_head_mut() { |
| 210 | hepler.template = tmpl; |
| 211 | } else { |
| 212 | self.template = tmpl; |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | fn revert_chain_and_set(&mut self, inverse: Option<Template>) { |
| 217 | if self.chain { |
| 218 | let mut prev = None; |
| 219 | |
| 220 | if let Some(head) = self.ref_chain_head_mut() { |
| 221 | if head.template.is_some() { |
| 222 | // Here the prev will hold the head inverse template. |
| 223 | // It will be set when reverse the chain. |
| 224 | prev = inverse; |
| 225 | } else { |
| 226 | // If the head already has template. set the inverse template. |
| 227 | head.template = inverse; |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | // Reverse the else chain, to the normal list order. |
| 232 | while let Some(mut node) = self.inverse.take() { |
| 233 | assert_eq!(node.elements.len(), 1); |
| 234 | if let HelperBlock(c) = &mut node.elements[0] { |
| 235 | self.inverse = c.inverse.take(); |
| 236 | c.inverse = prev; |
| 237 | prev = Some(node); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | self.inverse = prev; |
| 242 | } else { |
| 243 | // If the helper has no else chain. |
| 244 | // set the template to self. |
| 245 | if self.template.is_some() { |
| 246 | self.inverse = inverse; |
| 247 | } else { |
| 248 | self.template = inverse; |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | fn set_chained(&mut self) { |
| 254 | self.chain = true; |
| 255 | } |
| 256 | |
| 257 | pub fn is_chained(&self) -> bool { |
| 258 | self.chain |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 263 | pub struct DecoratorTemplate { |
| 264 | pub name: Parameter, |
| 265 | pub params: Vec<Parameter>, |
| 266 | pub hash: HashMap<String, Parameter>, |
| 267 | pub template: Option<Template>, |
| 268 | // for partial indent |
| 269 | pub indent: Option<String>, |
| 270 | } |
| 271 | |
| 272 | impl DecoratorTemplate { |
| 273 | pub fn new(exp: ExpressionSpec) -> DecoratorTemplate { |
| 274 | DecoratorTemplate { |
| 275 | name: exp.name, |
| 276 | params: exp.params, |
| 277 | hash: exp.hash, |
| 278 | template: None, |
| 279 | indent: None, |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | impl Parameter { |
| 285 | pub fn as_name(&self) -> Option<&str> { |
| 286 | match self { |
| 287 | Parameter::Name(ref n) => Some(n), |
| 288 | Parameter::Path(ref p) => Some(p.raw()), |
| 289 | _ => None, |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | pub fn parse(s: &str) -> Result<Parameter, TemplateError> { |
| 294 | let parser = HandlebarsParser::parse(Rule::parameter, s) |
| 295 | .map_err(|_| TemplateError::of(TemplateErrorReason::InvalidParam(s.to_owned())))?; |
| 296 | |
| 297 | let mut it = parser.flatten().peekable(); |
| 298 | Template::parse_param(s, &mut it, s.len() - 1) |
| 299 | } |
| 300 | |
| 301 | fn debug_name(&self) -> String { |
| 302 | if let Some(name) = self.as_name() { |
| 303 | name.to_owned() |
| 304 | } else { |
| 305 | format!("{self:?}") |
| 306 | } |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | impl Template { |
| 311 | pub fn new() -> Template { |
| 312 | Template::default() |
| 313 | } |
| 314 | |
| 315 | fn push_element(&mut self, e: TemplateElement, line: usize, col: usize) { |
| 316 | self.elements.push(e); |
| 317 | self.mapping.push(TemplateMapping(line, col)); |
| 318 | } |
| 319 | |
| 320 | fn parse_subexpression<'a, I>( |
| 321 | source: &'a str, |
| 322 | it: &mut Peekable<I>, |
| 323 | limit: usize, |
| 324 | ) -> Result<Parameter, TemplateError> |
| 325 | where |
| 326 | I: Iterator<Item = Pair<'a, Rule>>, |
| 327 | { |
| 328 | let espec = Template::parse_expression(source, it.by_ref(), limit)?; |
| 329 | Ok(Parameter::Subexpression(Subexpression::new( |
| 330 | espec.name, |
| 331 | espec.params, |
| 332 | espec.hash, |
| 333 | ))) |
| 334 | } |
| 335 | |
| 336 | fn parse_name<'a, I>( |
| 337 | source: &'a str, |
| 338 | it: &mut Peekable<I>, |
| 339 | _: usize, |
| 340 | ) -> Result<Parameter, TemplateError> |
| 341 | where |
| 342 | I: Iterator<Item = Pair<'a, Rule>>, |
| 343 | { |
| 344 | let name_node = it.next().unwrap(); |
| 345 | let rule = name_node.as_rule(); |
| 346 | let name_span = name_node.as_span(); |
| 347 | match rule { |
| 348 | Rule::identifier | Rule::partial_identifier | Rule::invert_tag_item => { |
| 349 | Ok(Parameter::Name(name_span.as_str().to_owned())) |
| 350 | } |
| 351 | Rule::reference => { |
| 352 | let paths = parse_json_path_from_iter(it, name_span.end()); |
| 353 | Ok(Parameter::Path(Path::new(name_span.as_str(), paths))) |
| 354 | } |
| 355 | Rule::subexpression => { |
| 356 | Template::parse_subexpression(source, it.by_ref(), name_span.end()) |
| 357 | } |
| 358 | _ => unreachable!(), |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | fn parse_param<'a, I>( |
| 363 | source: &'a str, |
| 364 | it: &mut Peekable<I>, |
| 365 | _: usize, |
| 366 | ) -> Result<Parameter, TemplateError> |
| 367 | where |
| 368 | I: Iterator<Item = Pair<'a, Rule>>, |
| 369 | { |
| 370 | let mut param = it.next().unwrap(); |
| 371 | if param.as_rule() == Rule::helper_parameter { |
| 372 | param = it.next().unwrap(); |
| 373 | } |
| 374 | let param_rule = param.as_rule(); |
| 375 | let param_span = param.as_span(); |
| 376 | let result = match param_rule { |
| 377 | Rule::reference => { |
| 378 | let path_segs = parse_json_path_from_iter(it, param_span.end()); |
| 379 | Parameter::Path(Path::new(param_span.as_str(), path_segs)) |
| 380 | } |
| 381 | Rule::literal => { |
| 382 | // Parse the parameter as a JSON literal |
| 383 | let param_literal = it.next().unwrap(); |
| 384 | let json_result = match param_literal.as_rule() { |
| 385 | Rule::string_literal |
| 386 | if it.peek().unwrap().as_rule() == Rule::string_inner_single_quote => |
| 387 | { |
| 388 | // ...unless the parameter is a single-quoted string. |
| 389 | // In that case, transform it to a double-quoted string |
| 390 | // and then parse it as a JSON literal. |
| 391 | let string_inner_single_quote = it.next().unwrap(); |
| 392 | let double_quoted = format!( |
| 393 | "\"{}\"", |
| 394 | string_inner_single_quote |
| 395 | .as_str() |
| 396 | .replace("\\'", "'") |
| 397 | .replace('"', "\\\"") |
| 398 | ); |
| 399 | Json::from_str(&double_quoted) |
| 400 | } |
| 401 | _ => Json::from_str(param_span.as_str()), |
| 402 | }; |
| 403 | if let Ok(json) = json_result { |
| 404 | Parameter::Literal(json) |
| 405 | } else { |
| 406 | return Err(TemplateError::of(TemplateErrorReason::InvalidParam( |
| 407 | param_span.as_str().to_owned(), |
| 408 | ))); |
| 409 | } |
| 410 | } |
| 411 | Rule::subexpression => { |
| 412 | Template::parse_subexpression(source, it.by_ref(), param_span.end())? |
| 413 | } |
| 414 | _ => unreachable!(), |
| 415 | }; |
| 416 | |
| 417 | while let Some(n) = it.peek() { |
| 418 | let n_span = n.as_span(); |
| 419 | if n_span.end() > param_span.end() { |
| 420 | break; |
| 421 | } |
| 422 | it.next(); |
| 423 | } |
| 424 | |
| 425 | Ok(result) |
| 426 | } |
| 427 | |
| 428 | fn parse_hash<'a, I>( |
| 429 | source: &'a str, |
| 430 | it: &mut Peekable<I>, |
| 431 | limit: usize, |
| 432 | ) -> Result<(String, Parameter), TemplateError> |
| 433 | where |
| 434 | I: Iterator<Item = Pair<'a, Rule>>, |
| 435 | { |
| 436 | let name = it.next().unwrap(); |
| 437 | let name_node = name.as_span(); |
| 438 | // identifier |
| 439 | let key = name_node.as_str().to_owned(); |
| 440 | |
| 441 | let value = Template::parse_param(source, it.by_ref(), limit)?; |
| 442 | Ok((key, value)) |
| 443 | } |
| 444 | |
| 445 | fn parse_block_param<'a, I>(_: &'a str, it: &mut Peekable<I>, limit: usize) -> BlockParam |
| 446 | where |
| 447 | I: Iterator<Item = Pair<'a, Rule>>, |
| 448 | { |
| 449 | let p1_name = it.next().unwrap(); |
| 450 | let p1_name_span = p1_name.as_span(); |
| 451 | // identifier |
| 452 | let p1 = p1_name_span.as_str().to_owned(); |
| 453 | |
| 454 | let p2 = it.peek().and_then(|p2_name| { |
| 455 | let p2_name_span = p2_name.as_span(); |
| 456 | if p2_name_span.end() <= limit { |
| 457 | Some(p2_name_span.as_str().to_owned()) |
| 458 | } else { |
| 459 | None |
| 460 | } |
| 461 | }); |
| 462 | |
| 463 | if let Some(p2) = p2 { |
| 464 | it.next(); |
| 465 | BlockParam::Pair((Parameter::Name(p1), Parameter::Name(p2))) |
| 466 | } else { |
| 467 | BlockParam::Single(Parameter::Name(p1)) |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | fn parse_expression<'a, I>( |
| 472 | source: &'a str, |
| 473 | it: &mut Peekable<I>, |
| 474 | limit: usize, |
| 475 | ) -> Result<ExpressionSpec, TemplateError> |
| 476 | where |
| 477 | I: Iterator<Item = Pair<'a, Rule>>, |
| 478 | { |
| 479 | let mut params: Vec<Parameter> = Vec::new(); |
| 480 | let mut hashes: HashMap<String, Parameter> = HashMap::new(); |
| 481 | let mut omit_pre_ws = false; |
| 482 | let mut omit_pro_ws = false; |
| 483 | let mut block_param = None; |
| 484 | |
| 485 | if it.peek().unwrap().as_rule() == Rule::leading_tilde_to_omit_whitespace { |
| 486 | omit_pre_ws = true; |
| 487 | it.next(); |
| 488 | } |
| 489 | |
| 490 | let name = Template::parse_name(source, it.by_ref(), limit)?; |
| 491 | |
| 492 | loop { |
| 493 | let rule; |
| 494 | let end; |
| 495 | if let Some(pair) = it.peek() { |
| 496 | let pair_span = pair.as_span(); |
| 497 | if pair_span.end() < limit { |
| 498 | rule = pair.as_rule(); |
| 499 | end = pair_span.end(); |
| 500 | } else { |
| 501 | break; |
| 502 | } |
| 503 | } else { |
| 504 | break; |
| 505 | } |
| 506 | |
| 507 | it.next(); |
| 508 | |
| 509 | match rule { |
| 510 | Rule::helper_parameter => { |
| 511 | params.push(Template::parse_param(source, it.by_ref(), end)?); |
| 512 | } |
| 513 | Rule::hash => { |
| 514 | let (key, value) = Template::parse_hash(source, it.by_ref(), end)?; |
| 515 | hashes.insert(key, value); |
| 516 | } |
| 517 | Rule::block_param => { |
| 518 | block_param = Some(Template::parse_block_param(source, it.by_ref(), end)); |
| 519 | } |
| 520 | Rule::trailing_tilde_to_omit_whitespace => { |
| 521 | omit_pro_ws = true; |
| 522 | } |
| 523 | _ => {} |
| 524 | } |
| 525 | } |
| 526 | Ok(ExpressionSpec { |
| 527 | name, |
| 528 | params, |
| 529 | hash: hashes, |
| 530 | block_param, |
| 531 | omit_pre_ws, |
| 532 | omit_pro_ws, |
| 533 | }) |
| 534 | } |
| 535 | |
| 536 | fn remove_previous_whitespace(template_stack: &mut VecDeque<Template>) { |
| 537 | let t = template_stack.front_mut().unwrap(); |
| 538 | if let Some(RawString(ref mut text)) = t.elements.last_mut() { |
| 539 | text.trim_end().to_owned().clone_into(text); |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | // in handlebars, the whitespaces around statement are |
| 544 | // automatically trimed. |
| 545 | // this function checks if current span has both leading and |
| 546 | // trailing whitespaces, which we treat as a standalone statement. |
| 547 | // |
| 548 | // |
| 549 | fn process_standalone_statement( |
| 550 | template_stack: &mut VecDeque<Template>, |
| 551 | source: &str, |
| 552 | current_span: &Span<'_>, |
| 553 | prevent_indent: bool, |
| 554 | ) -> bool { |
| 555 | let with_trailing_newline = |
| 556 | support::str::starts_with_empty_line(&source[current_span.end()..]); |
| 557 | |
| 558 | if with_trailing_newline { |
| 559 | let with_leading_newline = |
| 560 | support::str::ends_with_empty_line(&source[..current_span.start()]); |
| 561 | |
| 562 | // prevent_indent: a special toggle for partial expression |
| 563 | // (>) that leading whitespaces are kept |
| 564 | if prevent_indent && with_leading_newline { |
| 565 | let t = template_stack.front_mut().unwrap(); |
| 566 | // check the last element before current |
| 567 | if let Some(RawString(ref mut text)) = t.elements.last_mut() { |
| 568 | // trim leading space for standalone statement |
| 569 | text.trim_end_matches(support::str::whitespace_matcher) |
| 570 | .to_owned() |
| 571 | .clone_into(text); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | // return true when the item is the first element in root template |
| 576 | current_span.start() == 0 || with_leading_newline |
| 577 | } else { |
| 578 | false |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | fn raw_string<'a>( |
| 583 | source: &'a str, |
| 584 | pair: Option<Pair<'a, Rule>>, |
| 585 | trim_start: bool, |
| 586 | trim_start_line: bool, |
| 587 | ) -> TemplateElement { |
| 588 | let mut s = String::from(source); |
| 589 | |
| 590 | if let Some(pair) = pair { |
| 591 | // the source may contains leading space because of pest's limitation |
| 592 | // we calculate none space start here in order to correct the offset |
| 593 | let pair_span = pair.as_span(); |
| 594 | |
| 595 | let current_start = pair_span.start(); |
| 596 | let span_length = pair_span.end() - current_start; |
| 597 | let leading_space_offset = s.len() - span_length; |
| 598 | |
| 599 | // we would like to iterate pair reversely in order to remove certain |
| 600 | // index from our string buffer so here we convert the inner pairs to |
| 601 | // a vector. |
| 602 | for sub_pair in pair.into_inner().rev() { |
| 603 | // remove escaped backslash |
| 604 | if sub_pair.as_rule() == Rule::escape { |
| 605 | let escape_span = sub_pair.as_span(); |
| 606 | |
| 607 | let backslash_pos = escape_span.start(); |
| 608 | let backslash_rel_pos = leading_space_offset + backslash_pos - current_start; |
| 609 | s.remove(backslash_rel_pos); |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | if trim_start { |
| 615 | RawString(s.trim_start().to_owned()) |
| 616 | } else if trim_start_line { |
| 617 | let s = s.trim_start_matches(support::str::whitespace_matcher); |
| 618 | RawString(support::str::strip_first_newline(s).to_owned()) |
| 619 | } else { |
| 620 | RawString(s) |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | pub(crate) fn compile2( |
| 625 | source: &str, |
| 626 | options: TemplateOptions, |
| 627 | ) -> Result<Template, TemplateError> { |
| 628 | let mut helper_stack: VecDeque<HelperTemplate> = VecDeque::new(); |
| 629 | let mut decorator_stack: VecDeque<DecoratorTemplate> = VecDeque::new(); |
| 630 | let mut template_stack: VecDeque<Template> = VecDeque::new(); |
| 631 | |
| 632 | let mut omit_pro_ws = false; |
| 633 | // flag for newline removal of standalone statements |
| 634 | // this option is marked as true when standalone statement is detected |
| 635 | // then the leading whitespaces and newline of next rawstring will be trimed |
| 636 | let mut trim_line_required = false; |
| 637 | |
| 638 | let parser_queue = HandlebarsParser::parse(Rule::handlebars, source).map_err(|e| { |
| 639 | let (line_no, col_no) = match e.line_col { |
| 640 | LineColLocation::Pos(line_col) => line_col, |
| 641 | LineColLocation::Span(line_col, _) => line_col, |
| 642 | }; |
| 643 | TemplateError::of(TemplateErrorReason::InvalidSyntax( |
| 644 | e.variant.message().to_string(), |
| 645 | )) |
| 646 | .at(source, line_no, col_no) |
| 647 | .in_template(options.name()) |
| 648 | })?; |
| 649 | |
| 650 | // dbg!(parser_queue.clone().flatten()); |
| 651 | |
| 652 | // remove escape from our pair queue |
| 653 | let mut it = parser_queue |
| 654 | .flatten() |
| 655 | .filter(|p| { |
| 656 | // remove rules that should be silent but not for now due to pest limitation |
| 657 | !matches!(p.as_rule(), Rule::escape) |
| 658 | }) |
| 659 | .peekable(); |
| 660 | let mut end_pos: Option<Position<'_>> = None; |
| 661 | loop { |
| 662 | if let Some(pair) = it.next() { |
| 663 | let prev_end = end_pos.as_ref().map(|p| p.pos()).unwrap_or(0); |
| 664 | let rule = pair.as_rule(); |
| 665 | let span = pair.as_span(); |
| 666 | |
| 667 | let is_trailing_string = rule != Rule::template |
| 668 | && span.start() != prev_end |
| 669 | && !omit_pro_ws |
| 670 | && rule != Rule::raw_text |
| 671 | && rule != Rule::raw_block_text; |
| 672 | |
| 673 | if is_trailing_string { |
| 674 | // trailing string check |
| 675 | let (line_no, col_no) = span.start_pos().line_col(); |
| 676 | if rule == Rule::raw_block_end { |
| 677 | let mut t = Template::new(); |
| 678 | t.push_element( |
| 679 | Template::raw_string( |
| 680 | &source[prev_end..span.start()], |
| 681 | None, |
| 682 | false, |
| 683 | trim_line_required, |
| 684 | ), |
| 685 | line_no, |
| 686 | col_no, |
| 687 | ); |
| 688 | template_stack.push_front(t); |
| 689 | } else { |
| 690 | let t = template_stack.front_mut().unwrap(); |
| 691 | t.push_element( |
| 692 | Template::raw_string( |
| 693 | &source[prev_end..span.start()], |
| 694 | None, |
| 695 | false, |
| 696 | trim_line_required, |
| 697 | ), |
| 698 | line_no, |
| 699 | col_no, |
| 700 | ); |
| 701 | } |
| 702 | |
| 703 | // reset standalone statement marker |
| 704 | trim_line_required = false; |
| 705 | } |
| 706 | |
| 707 | let (line_no, col_no) = span.start_pos().line_col(); |
| 708 | match rule { |
| 709 | Rule::template => { |
| 710 | template_stack.push_front(Template::new()); |
| 711 | } |
| 712 | Rule::raw_text => { |
| 713 | // leading space fix |
| 714 | let start = if span.start() != prev_end { |
| 715 | prev_end |
| 716 | } else { |
| 717 | span.start() |
| 718 | }; |
| 719 | |
| 720 | let t = template_stack.front_mut().unwrap(); |
| 721 | t.push_element( |
| 722 | Template::raw_string( |
| 723 | &source[start..span.end()], |
| 724 | Some(pair.clone()), |
| 725 | omit_pro_ws, |
| 726 | trim_line_required, |
| 727 | ), |
| 728 | line_no, |
| 729 | col_no, |
| 730 | ); |
| 731 | |
| 732 | // reset standalone statement marker |
| 733 | trim_line_required = false; |
| 734 | } |
| 735 | Rule::helper_block_start |
| 736 | | Rule::raw_block_start |
| 737 | | Rule::decorator_block_start |
| 738 | | Rule::partial_block_start => { |
| 739 | let exp = Template::parse_expression(source, it.by_ref(), span.end())?; |
| 740 | |
| 741 | match rule { |
| 742 | Rule::helper_block_start | Rule::raw_block_start => { |
| 743 | let helper_template = HelperTemplate::new(exp.clone(), true); |
| 744 | helper_stack.push_front(helper_template); |
| 745 | } |
| 746 | Rule::decorator_block_start | Rule::partial_block_start => { |
| 747 | let decorator = DecoratorTemplate::new(exp.clone()); |
| 748 | decorator_stack.push_front(decorator); |
| 749 | } |
| 750 | _ => unreachable!(), |
| 751 | } |
| 752 | |
| 753 | if exp.omit_pre_ws { |
| 754 | Template::remove_previous_whitespace(&mut template_stack); |
| 755 | } |
| 756 | omit_pro_ws = exp.omit_pro_ws; |
| 757 | |
| 758 | // standalone statement check, it also removes leading whitespaces of |
| 759 | // previous rawstring when standalone statement detected |
| 760 | trim_line_required = Template::process_standalone_statement( |
| 761 | &mut template_stack, |
| 762 | source, |
| 763 | &span, |
| 764 | true, |
| 765 | ); |
| 766 | |
| 767 | let t = template_stack.front_mut().unwrap(); |
| 768 | t.mapping.push(TemplateMapping(line_no, col_no)); |
| 769 | } |
| 770 | Rule::invert_tag | Rule::invert_chain_tag => { |
| 771 | // hack: invert_tag structure is similar to ExpressionSpec, so I |
| 772 | // use it here to represent the data |
| 773 | |
| 774 | if rule == Rule::invert_chain_tag { |
| 775 | let _ = Template::parse_name(source, &mut it, span.end())?; |
| 776 | } |
| 777 | let exp = Template::parse_expression(source, it.by_ref(), span.end())?; |
| 778 | |
| 779 | if exp.omit_pre_ws { |
| 780 | Template::remove_previous_whitespace(&mut template_stack); |
| 781 | } |
| 782 | omit_pro_ws = exp.omit_pro_ws; |
| 783 | |
| 784 | // standalone statement check, it also removes leading whitespaces of |
| 785 | // previous rawstring when standalone statement detected |
| 786 | trim_line_required = Template::process_standalone_statement( |
| 787 | &mut template_stack, |
| 788 | source, |
| 789 | &span, |
| 790 | true, |
| 791 | ); |
| 792 | |
| 793 | let t = template_stack.pop_front().unwrap(); |
| 794 | let h = helper_stack.front_mut().unwrap(); |
| 795 | |
| 796 | if rule == Rule::invert_chain_tag { |
| 797 | h.set_chained(); |
| 798 | } |
| 799 | |
| 800 | h.set_chain_template(Some(t)); |
| 801 | if rule == Rule::invert_chain_tag { |
| 802 | h.insert_inverse_node(Box::new(HelperTemplate::new_chain(exp, true))); |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | Rule::raw_block_text => { |
| 807 | let mut t = Template::new(); |
| 808 | t.push_element( |
| 809 | Template::raw_string( |
| 810 | span.as_str(), |
| 811 | Some(pair.clone()), |
| 812 | omit_pro_ws, |
| 813 | trim_line_required, |
| 814 | ), |
| 815 | line_no, |
| 816 | col_no, |
| 817 | ); |
| 818 | template_stack.push_front(t); |
| 819 | } |
| 820 | Rule::expression |
| 821 | | Rule::html_expression |
| 822 | | Rule::decorator_expression |
| 823 | | Rule::partial_expression |
| 824 | | Rule::helper_block_end |
| 825 | | Rule::raw_block_end |
| 826 | | Rule::decorator_block_end |
| 827 | | Rule::partial_block_end => { |
| 828 | let exp = Template::parse_expression(source, it.by_ref(), span.end())?; |
| 829 | |
| 830 | if exp.omit_pre_ws { |
| 831 | Template::remove_previous_whitespace(&mut template_stack); |
| 832 | } |
| 833 | omit_pro_ws = exp.omit_pro_ws; |
| 834 | |
| 835 | match rule { |
| 836 | Rule::expression | Rule::html_expression => { |
| 837 | let helper_template = HelperTemplate::new(exp.clone(), false); |
| 838 | let el = if rule == Rule::expression { |
| 839 | Expression(Box::new(helper_template)) |
| 840 | } else { |
| 841 | HtmlExpression(Box::new(helper_template)) |
| 842 | }; |
| 843 | let t = template_stack.front_mut().unwrap(); |
| 844 | t.push_element(el, line_no, col_no); |
| 845 | } |
| 846 | Rule::decorator_expression | Rule::partial_expression => { |
| 847 | // do not auto trim ident spaces for |
| 848 | // partial_expression(>) |
| 849 | let prevent_indent = rule != Rule::partial_expression; |
| 850 | trim_line_required = Template::process_standalone_statement( |
| 851 | &mut template_stack, |
| 852 | source, |
| 853 | &span, |
| 854 | prevent_indent, |
| 855 | ); |
| 856 | |
| 857 | // indent for partial expression > |
| 858 | let mut indent = None; |
| 859 | if rule == Rule::partial_expression |
| 860 | && !options.prevent_indent |
| 861 | && !exp.omit_pre_ws |
| 862 | { |
| 863 | indent = support::str::find_trailing_whitespace_chars( |
| 864 | &source[..span.start()], |
| 865 | ); |
| 866 | } |
| 867 | |
| 868 | let mut decorator = DecoratorTemplate::new(exp.clone()); |
| 869 | decorator.indent = indent.map(|s| s.to_owned()); |
| 870 | |
| 871 | let el = if rule == Rule::decorator_expression { |
| 872 | DecoratorExpression(Box::new(decorator)) |
| 873 | } else { |
| 874 | PartialExpression(Box::new(decorator)) |
| 875 | }; |
| 876 | let t = template_stack.front_mut().unwrap(); |
| 877 | t.push_element(el, line_no, col_no); |
| 878 | } |
| 879 | Rule::helper_block_end | Rule::raw_block_end => { |
| 880 | // standalone statement check, it also removes leading whitespaces of |
| 881 | // previous rawstring when standalone statement detected |
| 882 | trim_line_required = Template::process_standalone_statement( |
| 883 | &mut template_stack, |
| 884 | source, |
| 885 | &span, |
| 886 | true, |
| 887 | ); |
| 888 | |
| 889 | let mut h = helper_stack.pop_front().unwrap(); |
| 890 | let close_tag_name = exp.name.as_name(); |
| 891 | if h.name.as_name() == close_tag_name { |
| 892 | let prev_t = template_stack.pop_front().unwrap(); |
| 893 | h.revert_chain_and_set(Some(prev_t)); |
| 894 | |
| 895 | let t = template_stack.front_mut().unwrap(); |
| 896 | t.elements.push(HelperBlock(Box::new(h))); |
| 897 | } else { |
| 898 | return Err(TemplateError::of( |
| 899 | TemplateErrorReason::MismatchingClosedHelper( |
| 900 | h.name.debug_name(), |
| 901 | exp.name.debug_name(), |
| 902 | ), |
| 903 | ) |
| 904 | .at(source, line_no, col_no) |
| 905 | .in_template(options.name())); |
| 906 | } |
| 907 | } |
| 908 | Rule::decorator_block_end | Rule::partial_block_end => { |
| 909 | // standalone statement check, it also removes leading whitespaces of |
| 910 | // previous rawstring when standalone statement detected |
| 911 | trim_line_required = Template::process_standalone_statement( |
| 912 | &mut template_stack, |
| 913 | source, |
| 914 | &span, |
| 915 | true, |
| 916 | ); |
| 917 | |
| 918 | let mut d = decorator_stack.pop_front().unwrap(); |
| 919 | let close_tag_name = exp.name.as_name(); |
| 920 | if d.name.as_name() == close_tag_name { |
| 921 | let prev_t = template_stack.pop_front().unwrap(); |
| 922 | d.template = Some(prev_t); |
| 923 | let t = template_stack.front_mut().unwrap(); |
| 924 | if rule == Rule::decorator_block_end { |
| 925 | t.elements.push(DecoratorBlock(Box::new(d))); |
| 926 | } else { |
| 927 | t.elements.push(PartialBlock(Box::new(d))); |
| 928 | } |
| 929 | } else { |
| 930 | return Err(TemplateError::of( |
| 931 | TemplateErrorReason::MismatchingClosedDecorator( |
| 932 | d.name.debug_name(), |
| 933 | exp.name.debug_name(), |
| 934 | ), |
| 935 | ) |
| 936 | .at(source, line_no, col_no) |
| 937 | .in_template(options.name())); |
| 938 | } |
| 939 | } |
| 940 | _ => unreachable!(), |
| 941 | } |
| 942 | } |
| 943 | Rule::hbs_comment_compact => { |
| 944 | trim_line_required = Template::process_standalone_statement( |
| 945 | &mut template_stack, |
| 946 | source, |
| 947 | &span, |
| 948 | true, |
| 949 | ); |
| 950 | |
| 951 | let text = span |
| 952 | .as_str() |
| 953 | .trim_start_matches("{{!") |
| 954 | .trim_end_matches("}}"); |
| 955 | let t = template_stack.front_mut().unwrap(); |
| 956 | t.push_element(Comment(text.to_owned()), line_no, col_no); |
| 957 | } |
| 958 | Rule::hbs_comment => { |
| 959 | trim_line_required = Template::process_standalone_statement( |
| 960 | &mut template_stack, |
| 961 | source, |
| 962 | &span, |
| 963 | true, |
| 964 | ); |
| 965 | |
| 966 | let text = span |
| 967 | .as_str() |
| 968 | .trim_start_matches("{{!--") |
| 969 | .trim_end_matches("--}}"); |
| 970 | let t = template_stack.front_mut().unwrap(); |
| 971 | t.push_element(Comment(text.to_owned()), line_no, col_no); |
| 972 | } |
| 973 | _ => {} |
| 974 | } |
| 975 | |
| 976 | if rule != Rule::template { |
| 977 | end_pos = Some(span.end_pos()); |
| 978 | } |
| 979 | } else { |
| 980 | let prev_end = end_pos.as_ref().map(|e| e.pos()).unwrap_or(0); |
| 981 | if prev_end < source.len() { |
| 982 | let text = &source[prev_end..source.len()]; |
| 983 | // is some called in if check |
| 984 | let (line_no, col_no) = end_pos.unwrap().line_col(); |
| 985 | let t = template_stack.front_mut().unwrap(); |
| 986 | t.push_element(RawString(text.to_owned()), line_no, col_no); |
| 987 | } |
| 988 | let mut root_template = template_stack.pop_front().unwrap(); |
| 989 | root_template.name = options.name; |
| 990 | return Ok(root_template); |
| 991 | } |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | // These two compile functions are kept for compatibility with 4.x |
| 996 | // Template APIs in case that some developers are using them |
| 997 | // without registry. |
| 998 | |
| 999 | pub fn compile(source: &str) -> Result<Template, TemplateError> { |
| 1000 | Self::compile2(source, TemplateOptions::default()) |
| 1001 | } |
| 1002 | |
| 1003 | pub fn compile_with_name<S: AsRef<str>>( |
| 1004 | source: S, |
| 1005 | name: String, |
| 1006 | ) -> Result<Template, TemplateError> { |
| 1007 | Self::compile2( |
| 1008 | source.as_ref(), |
| 1009 | TemplateOptions { |
| 1010 | name: Some(name), |
| 1011 | ..Default::default() |
| 1012 | }, |
| 1013 | ) |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | #[derive(PartialEq, Eq, Clone, Debug)] |
| 1018 | pub enum TemplateElement { |
| 1019 | RawString(String), |
| 1020 | HtmlExpression(Box<HelperTemplate>), |
| 1021 | Expression(Box<HelperTemplate>), |
| 1022 | HelperBlock(Box<HelperTemplate>), |
| 1023 | DecoratorExpression(Box<DecoratorTemplate>), |
| 1024 | DecoratorBlock(Box<DecoratorTemplate>), |
| 1025 | PartialExpression(Box<DecoratorTemplate>), |
| 1026 | PartialBlock(Box<DecoratorTemplate>), |
| 1027 | Comment(String), |
| 1028 | } |
| 1029 | |
| 1030 | #[cfg(test)] |
| 1031 | mod test { |
| 1032 | use super::*; |
| 1033 | use crate::error::TemplateErrorReason; |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn test_parse_escaped_tag_raw_string() { |
| 1037 | let source = r"foo \{{bar}}"; |
| 1038 | let t = Template::compile(source).ok().unwrap(); |
| 1039 | assert_eq!(t.elements.len(), 1); |
| 1040 | assert_eq!( |
| 1041 | *t.elements.get(0).unwrap(), |
| 1042 | RawString("foo {{bar}}".to_string()) |
| 1043 | ); |
| 1044 | } |
| 1045 | |
| 1046 | #[test] |
| 1047 | fn test_pure_backslash_raw_string() { |
| 1048 | let source = r"\\\\"; |
| 1049 | let t = Template::compile(source).ok().unwrap(); |
| 1050 | assert_eq!(t.elements.len(), 1); |
| 1051 | assert_eq!(*t.elements.get(0).unwrap(), RawString(source.to_string())); |
| 1052 | } |
| 1053 | |
| 1054 | #[test] |
| 1055 | fn test_parse_escaped_block_raw_string() { |
| 1056 | let source = r"\{{{{foo}}}} bar"; |
| 1057 | let t = Template::compile(source).ok().unwrap(); |
| 1058 | assert_eq!(t.elements.len(), 1); |
| 1059 | assert_eq!( |
| 1060 | *t.elements.get(0).unwrap(), |
| 1061 | RawString("{{{{foo}}}} bar".to_string()) |
| 1062 | ); |
| 1063 | } |
| 1064 | |
| 1065 | #[test] |
| 1066 | fn test_parse_template() { |
| 1067 | let source = "<h1>{{title}} 你好</h1> {{{content}}} |
| 1068 | {{#if date}}<p>good</p>{{else}}<p>bad</p>{{/if}}<img>{{foo bar}}中文你好 |
| 1069 | {{#unless true}}kitkat{{^}}lollipop{{/unless}}"; |
| 1070 | let t = Template::compile(source).ok().unwrap(); |
| 1071 | |
| 1072 | assert_eq!(t.elements.len(), 10); |
| 1073 | |
| 1074 | assert_eq!(*t.elements.get(0).unwrap(), RawString("<h1>".to_string())); |
| 1075 | assert_eq!( |
| 1076 | *t.elements.get(1).unwrap(), |
| 1077 | Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( |
| 1078 | &["title"] |
| 1079 | )))) |
| 1080 | ); |
| 1081 | |
| 1082 | assert_eq!( |
| 1083 | *t.elements.get(3).unwrap(), |
| 1084 | HtmlExpression(Box::new(HelperTemplate::with_path(Path::with_named_paths( |
| 1085 | &["content"], |
| 1086 | )))) |
| 1087 | ); |
| 1088 | |
| 1089 | match *t.elements.get(5).unwrap() { |
| 1090 | HelperBlock(ref h) => { |
| 1091 | assert_eq!(h.name.as_name().unwrap(), "if".to_string()); |
| 1092 | assert_eq!(h.params.len(), 1); |
| 1093 | assert_eq!(h.template.as_ref().unwrap().elements.len(), 1); |
| 1094 | } |
| 1095 | _ => { |
| 1096 | panic!("Helper expected here."); |
| 1097 | } |
| 1098 | }; |
| 1099 | |
| 1100 | match *t.elements.get(7).unwrap() { |
| 1101 | Expression(ref h) => { |
| 1102 | assert_eq!(h.name.as_name().unwrap(), "foo".to_string()); |
| 1103 | assert_eq!(h.params.len(), 1); |
| 1104 | assert_eq!( |
| 1105 | *(h.params.get(0).unwrap()), |
| 1106 | Parameter::Path(Path::with_named_paths(&["bar"])) |
| 1107 | ) |
| 1108 | } |
| 1109 | _ => { |
| 1110 | panic!("Helper expression here"); |
| 1111 | } |
| 1112 | }; |
| 1113 | |
| 1114 | match *t.elements.get(9).unwrap() { |
| 1115 | HelperBlock(ref h) => { |
| 1116 | assert_eq!(h.name.as_name().unwrap(), "unless".to_string()); |
| 1117 | assert_eq!(h.params.len(), 1); |
| 1118 | assert_eq!(h.inverse.as_ref().unwrap().elements.len(), 1); |
| 1119 | } |
| 1120 | _ => { |
| 1121 | panic!("Helper expression here"); |
| 1122 | } |
| 1123 | }; |
| 1124 | } |
| 1125 | |
| 1126 | #[test] |
| 1127 | fn test_parse_block_partial_path_identifier() { |
| 1128 | let source = "{{#> foo/bar}}{{/foo/bar}}"; |
| 1129 | assert!(Template::compile(source).is_ok()); |
| 1130 | } |
| 1131 | |
| 1132 | #[test] |
| 1133 | fn test_parse_error() { |
| 1134 | let source = "{{#ifequals name compare=\"hello\"}}\nhello\n\t{{else}}\ngood"; |
| 1135 | |
| 1136 | let terr = Template::compile(source).unwrap_err(); |
| 1137 | |
| 1138 | assert!(matches!( |
| 1139 | terr.reason(), |
| 1140 | TemplateErrorReason::InvalidSyntax(_) |
| 1141 | )); |
| 1142 | assert_eq!(terr.pos(), Some((4, 5))); |
| 1143 | } |
| 1144 | |
| 1145 | #[test] |
| 1146 | fn test_subexpression() { |
| 1147 | let source = |
| 1148 | "{{foo (bar)}}{{foo (bar baz)}} hello {{#if (baz bar) then=(bar)}}world{{/if}}"; |
| 1149 | let t = Template::compile(source).ok().unwrap(); |
| 1150 | |
| 1151 | assert_eq!(t.elements.len(), 4); |
| 1152 | match *t.elements.get(0).unwrap() { |
| 1153 | Expression(ref h) => { |
| 1154 | assert_eq!(h.name.as_name().unwrap(), "foo".to_owned()); |
| 1155 | assert_eq!(h.params.len(), 1); |
| 1156 | if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { |
| 1157 | assert_eq!(t.name(), "bar".to_owned()); |
| 1158 | } else { |
| 1159 | panic!("Subexpression expected"); |
| 1160 | } |
| 1161 | } |
| 1162 | _ => { |
| 1163 | panic!("Helper expression expected"); |
| 1164 | } |
| 1165 | }; |
| 1166 | |
| 1167 | match *t.elements.get(1).unwrap() { |
| 1168 | Expression(ref h) => { |
| 1169 | assert_eq!(h.name.as_name().unwrap(), "foo".to_string()); |
| 1170 | assert_eq!(h.params.len(), 1); |
| 1171 | if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { |
| 1172 | assert_eq!(t.name(), "bar".to_owned()); |
| 1173 | if let Some(Parameter::Path(p)) = t.params().unwrap().get(0) { |
| 1174 | assert_eq!(p, &Path::with_named_paths(&["baz"])); |
| 1175 | } else { |
| 1176 | panic!("non-empty param expected "); |
| 1177 | } |
| 1178 | } else { |
| 1179 | panic!("Subexpression expected"); |
| 1180 | } |
| 1181 | } |
| 1182 | _ => { |
| 1183 | panic!("Helper expression expected"); |
| 1184 | } |
| 1185 | }; |
| 1186 | |
| 1187 | match *t.elements.get(3).unwrap() { |
| 1188 | HelperBlock(ref h) => { |
| 1189 | assert_eq!(h.name.as_name().unwrap(), "if".to_string()); |
| 1190 | assert_eq!(h.params.len(), 1); |
| 1191 | assert_eq!(h.hash.len(), 1); |
| 1192 | |
| 1193 | if let &Parameter::Subexpression(ref t) = h.params.get(0).unwrap() { |
| 1194 | assert_eq!(t.name(), "baz".to_owned()); |
| 1195 | if let Some(Parameter::Path(p)) = t.params().unwrap().get(0) { |
| 1196 | assert_eq!(p, &Path::with_named_paths(&["bar"])); |
| 1197 | } else { |
| 1198 | panic!("non-empty param expected "); |
| 1199 | } |
| 1200 | } else { |
| 1201 | panic!("Subexpression expected (baz bar)"); |
| 1202 | } |
| 1203 | |
| 1204 | if let &Parameter::Subexpression(ref t) = h.hash.get("then").unwrap() { |
| 1205 | assert_eq!(t.name(), "bar".to_owned()); |
| 1206 | } else { |
| 1207 | panic!("Subexpression expected (bar)"); |
| 1208 | } |
| 1209 | } |
| 1210 | _ => { |
| 1211 | panic!("HelperBlock expected"); |
| 1212 | } |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | #[test] |
| 1217 | fn test_white_space_omitter() { |
| 1218 | let source = "hello~ {{~world~}} \n !{{~#if true}}else{{/if~}}"; |
| 1219 | let t = Template::compile(source).ok().unwrap(); |
| 1220 | |
| 1221 | assert_eq!(t.elements.len(), 4); |
| 1222 | |
| 1223 | assert_eq!(t.elements[0], RawString("hello~".to_string())); |
| 1224 | assert_eq!( |
| 1225 | t.elements[1], |
| 1226 | Expression(Box::new(HelperTemplate::with_path(Path::with_named_paths( |
| 1227 | &["world"] |
| 1228 | )))) |
| 1229 | ); |
| 1230 | assert_eq!(t.elements[2], RawString("!".to_string())); |
| 1231 | |
| 1232 | let t2 = Template::compile("{{#if true}}1 {{~ else ~}} 2 {{~/if}}") |
| 1233 | .ok() |
| 1234 | .unwrap(); |
| 1235 | assert_eq!(t2.elements.len(), 1); |
| 1236 | match t2.elements[0] { |
| 1237 | HelperBlock(ref h) => { |
| 1238 | assert_eq!( |
| 1239 | h.template.as_ref().unwrap().elements[0], |
| 1240 | RawString("1".to_string()) |
| 1241 | ); |
| 1242 | assert_eq!( |
| 1243 | h.inverse.as_ref().unwrap().elements[0], |
| 1244 | RawString("2".to_string()) |
| 1245 | ); |
| 1246 | } |
| 1247 | _ => unreachable!(), |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | #[test] |
| 1252 | fn test_unclosed_expression() { |
| 1253 | let sources = ["{{invalid", "{{{invalid", "{{invalid}", "{{!hello"]; |
| 1254 | for s in sources.iter() { |
| 1255 | let result = Template::compile(s.to_owned()); |
| 1256 | let err = result.expect_err("expected a syntax error"); |
| 1257 | let syntax_error_msg = match err.reason() { |
| 1258 | TemplateErrorReason::InvalidSyntax(s) => s, |
| 1259 | _ => panic!("InvalidSyntax expected"), |
| 1260 | }; |
| 1261 | assert!( |
| 1262 | syntax_error_msg.contains("expected identifier"), |
| 1263 | "{}", |
| 1264 | syntax_error_msg |
| 1265 | ); |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | #[test] |
| 1270 | fn test_raw_helper() { |
| 1271 | let source = "hello{{{{raw}}}}good{{night}}{{{{/raw}}}}world"; |
| 1272 | match Template::compile(source) { |
| 1273 | Ok(t) => { |
| 1274 | assert_eq!(t.elements.len(), 3); |
| 1275 | assert_eq!(t.elements[0], RawString("hello".to_owned())); |
| 1276 | assert_eq!(t.elements[2], RawString("world".to_owned())); |
| 1277 | match t.elements[1] { |
| 1278 | HelperBlock(ref h) => { |
| 1279 | assert_eq!(h.name.as_name().unwrap(), "raw".to_owned()); |
| 1280 | if let Some(ref ht) = h.template { |
| 1281 | assert_eq!(ht.elements.len(), 1); |
| 1282 | assert_eq!( |
| 1283 | *ht.elements.get(0).unwrap(), |
| 1284 | RawString("good{{night}}".to_owned()) |
| 1285 | ); |
| 1286 | } else { |
| 1287 | panic!("helper template not found"); |
| 1288 | } |
| 1289 | } |
| 1290 | _ => { |
| 1291 | panic!("Unexpected element type"); |
| 1292 | } |
| 1293 | } |
| 1294 | } |
| 1295 | Err(e) => { |
| 1296 | panic!("{}", e); |
| 1297 | } |
| 1298 | } |
| 1299 | } |
| 1300 | |
| 1301 | #[test] |
| 1302 | fn test_literal_parameter_parser() { |
| 1303 | match Template::compile("{{hello 1 name=\"value\" valid=false ref=someref}}") { |
| 1304 | Ok(t) => { |
| 1305 | if let Expression(ref ht) = t.elements[0] { |
| 1306 | assert_eq!(ht.params[0], Parameter::Literal(json!(1))); |
| 1307 | assert_eq!( |
| 1308 | ht.hash["name"], |
| 1309 | Parameter::Literal(Json::String("value".to_owned())) |
| 1310 | ); |
| 1311 | assert_eq!(ht.hash["valid"], Parameter::Literal(Json::Bool(false))); |
| 1312 | assert_eq!( |
| 1313 | ht.hash["ref"], |
| 1314 | Parameter::Path(Path::with_named_paths(&["someref"])) |
| 1315 | ); |
| 1316 | } |
| 1317 | } |
| 1318 | Err(e) => panic!("{}", e), |
| 1319 | } |
| 1320 | } |
| 1321 | |
| 1322 | #[test] |
| 1323 | fn test_template_mapping() { |
| 1324 | match Template::compile("hello\n {{~world}}\n{{#if nice}}\n\thello\n{{/if}}") { |
| 1325 | Ok(t) => { |
| 1326 | assert_eq!(t.mapping.len(), t.elements.len()); |
| 1327 | assert_eq!(t.mapping[0], TemplateMapping(1, 1)); |
| 1328 | assert_eq!(t.mapping[1], TemplateMapping(2, 3)); |
| 1329 | assert_eq!(t.mapping[3], TemplateMapping(3, 1)); |
| 1330 | } |
| 1331 | Err(e) => panic!("{}", e), |
| 1332 | } |
| 1333 | } |
| 1334 | |
| 1335 | #[test] |
| 1336 | fn test_whitespace_elements() { |
| 1337 | let c = Template::compile( |
| 1338 | " {{elem}}\n\t{{#if true}} \ |
| 1339 | {{/if}}\n{{{{raw}}}} {{{{/raw}}}}\n{{{{raw}}}}{{{{/raw}}}}\n", |
| 1340 | ); |
| 1341 | let r = c.unwrap(); |
| 1342 | // the \n after last raw block is dropped by pest |
| 1343 | assert_eq!(r.elements.len(), 9); |
| 1344 | } |
| 1345 | |
| 1346 | #[test] |
| 1347 | fn test_block_param() { |
| 1348 | match Template::compile("{{#each people as |person|}}{{person}}{{/each}}") { |
| 1349 | Ok(t) => { |
| 1350 | if let HelperBlock(ref ht) = t.elements[0] { |
| 1351 | if let Some(BlockParam::Single(Parameter::Name(ref n))) = ht.block_param { |
| 1352 | assert_eq!(n, "person"); |
| 1353 | } else { |
| 1354 | panic!("block param expected.") |
| 1355 | } |
| 1356 | } else { |
| 1357 | panic!("Helper block expected"); |
| 1358 | } |
| 1359 | } |
| 1360 | Err(e) => panic!("{}", e), |
| 1361 | } |
| 1362 | |
| 1363 | match Template::compile("{{#each people as |val key|}}{{person}}{{/each}}") { |
| 1364 | Ok(t) => { |
| 1365 | if let HelperBlock(ref ht) = t.elements[0] { |
| 1366 | if let Some(BlockParam::Pair(( |
| 1367 | Parameter::Name(ref n1), |
| 1368 | Parameter::Name(ref n2), |
| 1369 | ))) = ht.block_param |
| 1370 | { |
| 1371 | assert_eq!(n1, "val"); |
| 1372 | assert_eq!(n2, "key"); |
| 1373 | } else { |
| 1374 | panic!("helper block param expected."); |
| 1375 | } |
| 1376 | } else { |
| 1377 | panic!("Helper block expected"); |
| 1378 | } |
| 1379 | } |
| 1380 | Err(e) => panic!("{}", e), |
| 1381 | } |
| 1382 | } |
| 1383 | |
| 1384 | #[test] |
| 1385 | fn test_decorator() { |
| 1386 | match Template::compile("hello {{* ssh}} world") { |
| 1387 | Err(e) => panic!("{}", e), |
| 1388 | Ok(t) => { |
| 1389 | if let DecoratorExpression(ref de) = t.elements[1] { |
| 1390 | assert_eq!(de.name.as_name(), Some("ssh")); |
| 1391 | assert_eq!(de.template, None); |
| 1392 | } |
| 1393 | } |
| 1394 | } |
| 1395 | |
| 1396 | match Template::compile("hello {{> ssh}} world") { |
| 1397 | Err(e) => panic!("{}", e), |
| 1398 | Ok(t) => { |
| 1399 | if let PartialExpression(ref de) = t.elements[1] { |
| 1400 | assert_eq!(de.name.as_name(), Some("ssh")); |
| 1401 | assert_eq!(de.template, None); |
| 1402 | } |
| 1403 | } |
| 1404 | } |
| 1405 | |
| 1406 | match Template::compile("{{#*inline \"hello\"}}expand to hello{{/inline}}{{> hello}}") { |
| 1407 | Err(e) => panic!("{}", e), |
| 1408 | Ok(t) => { |
| 1409 | if let DecoratorBlock(ref db) = t.elements[0] { |
| 1410 | assert_eq!(db.name, Parameter::Name("inline".to_owned())); |
| 1411 | assert_eq!( |
| 1412 | db.params[0], |
| 1413 | Parameter::Literal(Json::String("hello".to_owned())) |
| 1414 | ); |
| 1415 | assert_eq!( |
| 1416 | db.template.as_ref().unwrap().elements[0], |
| 1417 | TemplateElement::RawString("expand to hello".to_owned()) |
| 1418 | ); |
| 1419 | } |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | match Template::compile("{{#> layout \"hello\"}}expand to hello{{/layout}}{{> hello}}") { |
| 1424 | Err(e) => panic!("{}", e), |
| 1425 | Ok(t) => { |
| 1426 | if let PartialBlock(ref db) = t.elements[0] { |
| 1427 | assert_eq!(db.name, Parameter::Name("layout".to_owned())); |
| 1428 | assert_eq!( |
| 1429 | db.params[0], |
| 1430 | Parameter::Literal(Json::String("hello".to_owned())) |
| 1431 | ); |
| 1432 | assert_eq!( |
| 1433 | db.template.as_ref().unwrap().elements[0], |
| 1434 | TemplateElement::RawString("expand to hello".to_owned()) |
| 1435 | ); |
| 1436 | } |
| 1437 | } |
| 1438 | } |
| 1439 | } |
| 1440 | |
| 1441 | #[test] |
| 1442 | fn test_panic_with_tag_name() { |
| 1443 | let s = "{{#>(X)}}{{/X}}"; |
| 1444 | let result = Template::compile(s); |
| 1445 | assert!(result.is_err()); |
| 1446 | 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, chain: false }) })\" was opened, but \"X\" is closing", format!("{}", result.unwrap_err().reason())); |
| 1447 | } |
| 1448 | } |