pub enum Parameter {
    Name(String),
    Path(Path),
    Literal(Json),
    Subexpression(Subexpression),
}

Variants§

§

Name(String)

§

Path(Path)

§

Literal(Json)

§

Subexpression(Subexpression)

Implementations§

Examples found in repository?
src/render.rs (line 323)
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    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>,
    indent: Option<&'reg String>,
}

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(),
            indent: dt.indent.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
    }

    pub fn indent(&self) -> Option<&'reg String> {
        self.indent
    }
}

/// 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
    }
}

#[inline]
fn indent_aware_write(
    v: &str,
    rc: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    if let Some(indent) = rc.get_indent_string() {
        out.write(support::str::with_indent(v, indent).as_ref())?;
    } else {
        out.write(v.as_ref())?;
    }
    Ok(())
}

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) => indent_aware_write(v.as_ref(), rc, out),
            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);
                            indent_aware_write(output.as_ref(), rc, out)
                        }
                    }
                } 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(()),
        }
    }
Examples found in repository?
src/render.rs (line 326)
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    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>,
    indent: Option<&'reg String>,
}

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(),
            indent: dt.indent.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
    }

    pub fn indent(&self) -> Option<&'reg String> {
        self.indent
    }
}

/// 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
    }
}

#[inline]
fn indent_aware_write(
    v: &str,
    rc: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    if let Some(indent) = rc.get_indent_string() {
        out.write(support::str::with_indent(v, indent).as_ref())?;
    } else {
        out.write(v.as_ref())?;
    }
    Ok(())
}

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) => indent_aware_write(v.as_ref(), rc, out),
            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);
                            indent_aware_write(output.as_ref(), rc, out)
                        }
                    }
                } 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(()),
        }
    }
Examples found in repository?
src/template.rs (line 83)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
    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, Eq, Clone, Debug)]
pub enum BlockParam {
    Single(Parameter),
    Pair((Parameter, Parameter)),
}

#[derive(PartialEq, Eq, 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, Eq, 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, Eq, 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 {
    pub fn new(exp: ExpressionSpec, block: bool) -> HelperTemplate {
        HelperTemplate {
            name: exp.name,
            params: exp.params,
            hash: exp.hash,
            block_param: exp.block_param,
            block,
            template: None,
            inverse: None,
        }
    }

    // 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, Eq, Clone, Debug)]
pub struct DecoratorTemplate {
    pub name: Parameter,
    pub params: Vec<Parameter>,
    pub hash: HashMap<String, Parameter>,
    pub template: Option<Template>,
    // for partial indent
    pub indent: Option<String>,
}

impl DecoratorTemplate {
    pub fn new(exp: ExpressionSpec) -> DecoratorTemplate {
        DecoratorTemplate {
            name: exp.name,
            params: exp.params,
            hash: exp.hash,
            template: None,
            indent: None,
        }
    }
}

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(RawString(ref mut text)) = t.elements.last_mut() {
            *text = text.trim_end().to_owned();
        }
    }

    // in handlebars, the whitespaces around statement are
    // automatically trimed.
    // this function checks if current span has both leading and
    // trailing whitespaces, which we treat as a standalone statement.
    //
    //
    fn process_standalone_statement(
        template_stack: &mut VecDeque<Template>,
        source: &str,
        current_span: &Span<'_>,
        prevent_indent: bool,
    ) -> bool {
        let with_trailing_newline =
            support::str::starts_with_empty_line(&source[current_span.end()..]);

        if with_trailing_newline {
            let with_leading_newline =
                support::str::ends_with_empty_line(&source[..current_span.start()]);

            // prevent_indent: a special toggle for partial expression
            // (>) that leading whitespaces are kept
            if prevent_indent && with_leading_newline {
                let t = template_stack.front_mut().unwrap();
                // check the last element before current
                if let Some(RawString(ref mut text)) = t.elements.last_mut() {
                    // trim leading space for standalone statement
                    *text = text
                        .trim_end_matches(support::str::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 {
            let s = s.trim_start_matches(support::str::whitespace_matcher);
            RawString(support::str::strip_first_newline(s).to_owned())
        } else {
            RawString(s)
        }
    }

    pub(crate) fn compile2(
        source: &str,
        options: TemplateOptions,
    ) -> 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_required = 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)
                .in_template(options.name())
        })?;

        // 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_required,
                            ),
                            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_required,
                            ),
                            line_no,
                            col_no,
                        );
                    }

                    // reset standalone statement marker
                    trim_line_required = false;
                }

                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_required,
                            ),
                            line_no,
                            col_no,
                        );

                        // reset standalone statement marker
                        trim_line_required = 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::new(exp.clone(), true);
                                helper_stack.push_front(helper_template);
                            }
                            Rule::decorator_block_start | Rule::partial_block_start => {
                                let decorator = DecoratorTemplate::new(exp.clone());
                                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_required = Template::process_standalone_statement(
                            &mut template_stack,
                            source,
                            &span,
                            true,
                        );

                        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_required = Template::process_standalone_statement(
                            &mut template_stack,
                            source,
                            &span,
                            true,
                        );

                        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_required,
                            ),
                            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::new(exp.clone(), false);
                                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 => {
                                // do not auto trim ident spaces for
                                // partial_expression(>)
                                let prevent_indent = rule != Rule::partial_expression;
                                trim_line_required = Template::process_standalone_statement(
                                    &mut template_stack,
                                    source,
                                    &span,
                                    prevent_indent,
                                );

                                // indent for partial expression >
                                let mut indent = None;
                                if rule == Rule::partial_expression
                                    && !options.prevent_indent
                                    && !exp.omit_pre_ws
                                {
                                    indent = support::str::find_trailing_whitespace_chars(
                                        &source[..span.start()],
                                    );
                                }

                                let mut decorator = DecoratorTemplate::new(exp.clone());
                                decorator.indent = indent.map(|s| s.to_owned());

                                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_required = Template::process_standalone_statement(
                                    &mut template_stack,
                                    source,
                                    &span,
                                    true,
                                );

                                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)
                                    .in_template(options.name()));
                                }
                            }
                            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_required = Template::process_standalone_statement(
                                    &mut template_stack,
                                    source,
                                    &span,
                                    true,
                                );

                                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)
                                    .in_template(options.name()));
                                }
                            }
                            _ => unreachable!(),
                        }
                    }
                    Rule::hbs_comment_compact => {
                        trim_line_required = Template::process_standalone_statement(
                            &mut template_stack,
                            source,
                            &span,
                            true,
                        );

                        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_required = Template::process_standalone_statement(
                            &mut template_stack,
                            source,
                            &span,
                            true,
                        );

                        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 mut root_template = template_stack.pop_front().unwrap();
                root_template.name = options.name;
                return Ok(root_template);
            }
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.