1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 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
//! Render a template to output using the data.
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::rc::Rc;

use serde::Serialize;
use serde_json::{Map, Value};

use crate::{
    error::{HelperError, RenderError},
    escape::EscapeFn,
    helper::{Helper, HelperRegistry, HelperResult, LocalHelper},
    json,
    output::{Output, StringOutput},
    parser::{
        ast::{Block, Call, CallTarget, Node, ParameterValue, Path, Slice},
        path,
    },
    template::Templates,
    trim::{TrimHint, TrimState},
    RenderResult,
};

static PARTIAL_BLOCK: &str = "@partial-block";
static HELPER_MISSING: &str = "helperMissing";
static BLOCK_HELPER_MISSING: &str = "blockHelperMissing";

type HelperValue = Option<Value>;

pub mod context;
pub mod scope;

pub use context::{Context, Property, Type};
pub use scope::Scope;

/// Maximum stack size for helper calls
static STACK_MAX: usize = 32;

/// Call site keeps track of calls so we can
/// detect cyclic calls and therefore prevent
/// stack overflows panics by returning a render
/// error when a cycle is detected.
///
/// Note that we must distinguish between helper
/// types otherwise the `if` helper will not work
/// as expected as it returns values and handles
/// block templates.
#[derive(Eq, PartialEq, Hash, Debug, Clone)]
enum CallSite {
    Partial(String),
    Helper(String),
    BlockHelper(String),
}

impl fmt::Display for CallSite {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", {
            match *self {
                CallSite::Partial(ref name) => format!("partial#{}", name),
                CallSite::Helper(ref name) => format!("helper#{}", name),
                CallSite::BlockHelper(ref name) => format!("block#{}", name),
            }
        })
    }
}

impl Into<String> for CallSite {
    fn into(self) -> String {
        match self {
            CallSite::Partial(name)
            | CallSite::Helper(name)
            | CallSite::BlockHelper(name) => name,
        }
    }
}

/// Render a template.
pub struct Render<'render> {
    strict: bool,
    escape: &'render EscapeFn,
    helpers: &'render HelperRegistry<'render>,
    local_helpers: Rc<RefCell<HashMap<String, Box<dyn LocalHelper + 'render>>>>,
    templates: &'render Templates<'render>,
    partials: HashMap<String, &'render Node<'render>>,
    name: &'render str,
    root: Value,
    writer: Box<&'render mut dyn Output>,
    scopes: Vec<Scope>,
    trim: TrimState,
    hint: Option<TrimHint>,
    end_tag_hint: Option<TrimHint>,
    stack: Vec<CallSite>,
}

impl<'render> Render<'render> {
    /// Create a renderer.
    ///
    /// You should not need to create a renderer directly, instead
    /// use the functions provided by the `Registry`.
    pub fn new<T>(
        strict: bool,
        escape: &'render EscapeFn,
        helpers: &'render HelperRegistry<'render>,
        templates: &'render Templates<'render>,
        name: &'render str,
        data: &T,
        writer: Box<&'render mut dyn Output>,
    ) -> RenderResult<Self>
    where
        T: Serialize,
    {
        let root = serde_json::to_value(data).map_err(RenderError::from)?;
        let scopes: Vec<Scope> = Vec::new();

        Ok(Self {
            strict,
            escape,
            helpers,
            local_helpers: Rc::new(RefCell::new(HashMap::new())),
            templates,
            partials: HashMap::new(),
            name,
            root,
            writer,
            scopes,
            trim: Default::default(),
            hint: None,
            end_tag_hint: None,
            stack: Vec::new(),
        })
    }

    /// Render a node by iterating it's children.
    ///
    /// The supplied node should be a document or block node.
    pub fn render(&mut self, node: &'render Node<'render>) -> RenderResult<()> {
        for event in node.into_iter().event(Default::default()) {
            self.render_node(event.node, event.trim)?;
        }
        Ok(())
    }

    /// Get a mutable reference to the output destination.
    ///
    /// You should prefer the `write()` and `write_escaped()` functions
    /// when writing strings but if you want to write bytes directly to
    /// the output destination you can use this reference.
    pub fn out(&mut self) -> &mut Box<&'render mut dyn Output> {
        &mut self.writer
    }

    /// Write a string to the output destination.
    pub fn write(&mut self, s: &str) -> HelperResult<usize> {
        self.write_str(s, false)
            .map_err(Box::new)
            .map_err(HelperError::from)
    }

    /// Write a string to the output destination and escape the content
    /// using the current escape function.
    pub fn write_escaped(&mut self, s: &str) -> HelperResult<usize> {
        self.write_str(s, true)
            .map_err(Box::new)
            .map_err(HelperError::from)
    }

    /// Push a scope onto the stack.
    pub fn push_scope(&mut self, scope: Scope) {
        self.scopes.push(scope);
    }

    /// Remove a scope from the stack.
    pub fn pop_scope(&mut self) -> Option<Scope> {
        self.scopes.pop()
    }

    /// Get a mutable reference to the current scope.
    pub fn scope_mut(&mut self) -> Option<&mut Scope> {
        self.scopes.last_mut()
    }

    /// Reference to the root data for the render.
    pub fn root(&self) -> &Value {
        &self.root
    }

    /// Evaluate the block conditionals and find
    /// the first node that should be rendered.
    pub fn inverse<'a>(
        &mut self,
        template: &'a Node<'a>,
    ) -> Result<Option<&'a Node<'a>>, HelperError> {
        let mut alt: Option<&'a Node<'_>> = None;
        let mut branch: Option<&'a Node<'_>> = None;

        match template {
            Node::Block(ref block) => {
                if !block.conditions().is_empty() {
                    for node in block.conditions().iter() {
                        match node {
                            Node::Block(clause) => {
                                // Got an else clause, last one wins!
                                if clause.call().is_empty() {
                                    alt = Some(node);
                                } else {
                                    if let Some(value) = self
                                        .call(clause.call())
                                        .map_err(Box::new)?
                                    {
                                        if json::is_truthy(&value) {
                                            branch = Some(node);
                                            break;
                                        }
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
            _ => {}
        }

        Ok(branch.or(alt))
    }

    /// Render an inner template.
    ///
    /// Block helpers should call this when they want to render an inner template.
    pub fn template(
        &mut self,
        node: &'render Node<'render>,
    ) -> Result<(), HelperError> {
        let mut hint: Option<TrimHint> = None;
        for event in node.into_iter().event(self.hint) {
            let mut trim = event.trim;

            if event.first {
                let hint = node.trim();
                if hint.after {
                    trim.start = true;
                }
            }

            if event.last {
                match node {
                    Node::Block(ref block) => {
                        let last_hint = block.trim_close();
                        if last_hint.before {
                            trim.end = true;
                        }
                        hint = Some(last_hint);
                    }
                    _ => {}
                }
            }

            self.render_node(event.node, trim)
                .map_err(|e| HelperError::Render(Box::new(e)))?;
        }

        // Store the hint so we can remove leading whitespace
        // after a block end tag
        self.end_tag_hint = hint;

        Ok(())
    }

    /// Render a node and buffer the result to a string.
    ///
    /// The call stack and scopes are inherited from this renderer.
    ///
    /// The supplied node should be a document or block node.
    pub fn buffer(&self, node: &'render Node<'render>) -> Result<String, HelperError> {

        let mut writer = StringOutput::new();
        let mut rc = Render::new(
            self.strict,
            self.escape,
            self.helpers,
            self.templates,
            self.name,
            &self.root,
            Box::new(&mut writer),
        ).map_err(Box::new)?;

        // Inherit the stack and scope from this renderer
        rc.stack = self.stack.clone();
        rc.scopes = self.scopes.clone();
        //rc.local_helpers = Rc::clone(&self.local_helpers);

        rc.render(node).map_err(Box::new)?;

        // Must drop the renderer to take ownership of the string buffer
        drop(rc);

        Ok(writer.into())
    }

    /// Evaluate a path and return the resolved value.
    ///
    /// This allows helpers to find variables in the template data
    /// using the familiar path syntax such as `@root.name`.
    ///
    /// Paths are evaluated using the current scope so local variables
    /// in the current scope will be resolved.
    ///
    /// Paths are dynamically evaluated so syntax errors are caught and
    /// returned wrapped as `HelperError`.
    ///
    /// Sub-expressions are not executed.
    pub fn evaluate<'a>(
        &'a self,
        value: &str,
    ) -> HelperResult<Option<&'a Value>> {
        if let Some(path) = path::from_str(value)? {
            return Ok(self.lookup(&path));
        }
        Ok(None)
    }

    /// Infallible variable lookup by path.
    fn lookup<'a>(&'a self, path: &Path<'_>) -> Option<&'a Value> {
        //println!("Lookup path {:?}", path.as_str());
        //println!("Lookup path {:?}", path);

        // Handle explicit `@root` reference
        if path.is_root() {
            json::find_parts(
                path.components().iter().skip(1).map(|c| c.as_value()),
                &self.root,
            )
        // Handle explicit this
        } else if path.is_explicit() {
            let value = if let Some(scope) = self.scopes.last() {
                if let Some(base) = scope.base_value() {
                    base
                } else {
                    &self.root
                }
            } else {
                &self.root
            };

            // Handle explicit this only
            if path.components().len() == 1 {
                Some(value)
            // Otherwise lookup in this context
            } else {
                json::find_parts(
                    path.components().iter().skip(1).map(|c| c.as_value()),
                    value,
                )
            }
        // Handle local @variable references which must
        // be resolved using the current scope
        } else if path.is_local() {
            if let Some(scope) = self.scopes.last() {
                json::find_parts(
                    path.components().iter().map(|c| c.as_value()),
                    scope.locals(),
                )
            } else {
                None
            }
        } else if path.parents() > 0 {
            // Combine so that the root object is
            // treated as a scope
            let mut all = vec![&self.root];
            let mut values: Vec<&'a Value> =
                self.scopes.iter().map(|s| s.locals()).collect();
            all.append(&mut values);

            if all.len() > path.parents() as usize {
                let index: usize = all.len() - (path.parents() as usize + 1);
                if let Some(value) = all.get(index) {
                    json::find_parts(
                        path.components().iter().map(|c| c.as_value()),
                        value,
                    )
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            // Lookup in the current scope
            if let Some(scope) = self.scopes.last() {
                json::find_parts(
                    path.components().iter().map(|c| c.as_value()),
                    scope.locals(),
                )
                .or(json::find_parts(
                    path.components().iter().map(|c| c.as_value()),
                    &self.root,
                ))
            // Lookup in the root scope
            } else {
                json::find_parts(
                    path.components().iter().map(|c| c.as_value()),
                    &self.root,
                )
            }
        }
    }

    /// Create the context arguments list.
    fn arguments(&mut self, call: &Call<'_>) -> RenderResult<Vec<Value>> {
        let mut out: Vec<Value> = Vec::new();
        for p in call.arguments() {
            let arg = match p {
                ParameterValue::Json(val) => val.clone(),
                ParameterValue::Path(ref path) => {
                    self.lookup(path).cloned().unwrap_or(Value::Null)
                }
                ParameterValue::SubExpr(ref call) => {
                    self.statement(call)?.unwrap_or(Value::Null)
                }
            };
            out.push(arg);
        }
        Ok(out)
    }

    /// Create the context hash parameters.
    fn hash(&mut self, call: &Call<'_>) -> RenderResult<Map<String, Value>> {
        let mut out = Map::new();
        for (k, p) in call.hash() {
            let (key, value) = match p {
                ParameterValue::Json(val) => (k.to_string(), val.clone()),
                ParameterValue::Path(ref path) => {
                    let val = self.lookup(path).cloned().unwrap_or(Value::Null);
                    (k.to_string(), val)
                }
                ParameterValue::SubExpr(ref call) => (
                    k.to_string(),
                    self.statement(call)?.unwrap_or(Value::Null),
                ),
            };
            out.insert(key, value);
        }

        Ok(out)
    }

    /// Register a local helper.
    ///
    /// Local helpers are available for the scope of the parent helper.
    pub fn register_local_helper(
        &mut self,
        name: &'render str,
        helper: Box<dyn LocalHelper + 'render>,
    ) {
        let registry = Rc::make_mut(&mut self.local_helpers);
        registry.borrow_mut().insert(name.to_string(), helper);
    }

    /// Remove a local helper.
    ///
    /// Local helpers will be removed once a helper call has finished
    /// but you can call this if you want to be explicit.
    pub fn unregister_local_helper(&mut self, name: &'render str) {
        let registry = Rc::make_mut(&mut self.local_helpers);
        registry.borrow_mut().remove(name);
    }

    fn invoke(
        &mut self,
        name: &str,
        call: &Call<'_>,
        content: Option<&'render Node<'render>>,
        text: Option<&'render str>,
        property: Option<Property>,
    ) -> RenderResult<HelperValue> {
        let site = if content.is_some() {
            CallSite::BlockHelper(name.to_string())
        } else {
            CallSite::Helper(name.to_string())
        };

        let amount = self.stack.iter().filter(|&n| *n == site).count();
        if amount >= STACK_MAX {
            return Err(RenderError::HelperCycle(site.into()));
        }
        self.stack.push(site);

        let args = self.arguments(call)?;
        let hash = self.hash(call)?;
        let mut context =
            Context::new(call, name.to_owned(), args, hash, text, property);

        let local_helpers = Rc::clone(&self.local_helpers);

        let value: Option<Value> =
            if let Some(helper) = local_helpers.borrow().get(name) {
                helper.call(self, &mut context, content)?
            } else if let Some(helper) = self.helpers.get(name) {
                helper.call(self, &mut context, content)?
            } else {
                None
            };

        drop(local_helpers);

        self.stack.pop();

        Ok(value)
    }

    fn has_helper(&mut self, name: &str) -> bool {
        self.local_helpers.borrow().get(name).is_some()
            || self.helpers.get(name).is_some()
    }

    // Fallible version of path lookup.
    fn resolve(&mut self, path: &Path<'_>) -> RenderResult<HelperValue> {
        if let Some(value) = self.lookup(path).cloned().take() {
            Ok(Some(value))
        } else {
            if self.strict {
                Err(RenderError::VariableNotFound(path.as_str().to_string()))
            } else {
                // TODO: call a missing_variable handler?
                Ok(None)
            }
        }
    }

    /// Invoke a call and return the result.
    pub(crate) fn call(
        &mut self,
        call: &Call<'_>,
    ) -> RenderResult<HelperValue> {
        match call.target() {
            CallTarget::Path(ref path) => {
                // Explicit paths should resolve to a lookup
                if path.is_explicit() {
                    Ok(self.lookup(path).cloned())
                // Simple paths may be helpers
                } else if path.is_simple() {
                    if self.has_helper(path.as_str()) {
                        self.invoke(path.as_str(), call, None, None, None)
                    } else {
                        let value = self.lookup(path).cloned();
                        if let None = value {
                            if self.has_helper(HELPER_MISSING) {
                                return self.invoke(
                                    HELPER_MISSING,
                                    call,
                                    None,
                                    None,
                                    None,
                                );
                            } else {
                                // TODO: also error if Call has arguments or parameters
                                if self.strict {
                                    return Err(RenderError::VariableNotFound(
                                        path.as_str().to_string(),
                                    ));
                                }
                            }
                        }
                        Ok(value)
                    }
                } else {
                    self.resolve(path)
                }
            }
            CallTarget::SubExpr(ref sub) => self.call(sub),
        }
    }

    fn statement(&mut self, call: &Call<'_>) -> RenderResult<HelperValue> {
        if call.is_partial() {
            self.render_partial(call, None)?;
            Ok(None)
        } else {
            Ok(self.call(call)?)
        }
    }

    fn get_partial_name<'a>(
        &mut self,
        call: &Call<'_>,
    ) -> RenderResult<String> {
        match call.target() {
            CallTarget::Path(ref path) => {
                if path.as_str() == PARTIAL_BLOCK {
                    return Ok(PARTIAL_BLOCK.to_string());
                } else if path.is_simple() {
                    return Ok(path.as_str().to_string());
                } else {
                    panic!("Partials must be simple identifiers");
                }
            }
            CallTarget::SubExpr(ref call) => {
                let result = self.statement(call)?.unwrap_or(Value::Null);
                return Ok(json::stringify(&result));
            }
        }
    }

    fn render_partial(
        &mut self,
        call: &Call<'_>,
        partial_block: Option<&'render Node<'render>>,
    ) -> RenderResult<()> {
        let name = self.get_partial_name(call)?;

        let site = CallSite::Partial(name.to_string());
        if self.stack.contains(&site) {
            return Err(RenderError::PartialCycle(site.into()));
        }
        self.stack.push(site);

        if let Some(node) = partial_block {
            self.partials.insert(PARTIAL_BLOCK.to_string(), node);
        }

        let node = if let Some(local_partial) = self.partials.get(&name) {
            local_partial
        } else {
            let template = self
                .templates
                .get(&name)
                .ok_or_else(|| RenderError::PartialNotFound(name))?;

            template.node()
        };

        let hash = self.hash(call)?;
        let scope = Scope::from(hash);
        self.scopes.push(scope);
        // WARN: We must iterate the document child nodes
        // WARN: when rendering partials otherwise the
        // WARN: rendering process will halt after the first partial!
        for event in node.into_iter().event(self.hint) {
            self.render_node(event.node, event.trim)?;
        }
        self.scopes.pop();

        self.stack.pop();

        Ok(())
    }

    fn block_helper_missing(
        &mut self,
        node: &'render Node<'render>,
        block: &'render Block<'render>,
        call: &'render Call<'render>,
        text: Option<&str>,
        raw: bool,
    ) -> RenderResult<()> {
        // Handling a raw block without a corresponding helper
        // so we just write out the content
        if raw {
            if let Some(text) = text {
                self.write_str(text, false)?;
            }
        } else {
            match call.target() {
                CallTarget::Path(ref path) => {
                    if let Some(value) = self.lookup(path).cloned() {
                        if self.has_helper(BLOCK_HELPER_MISSING) {
                            let prop = Property {
                                name: path.as_str().to_string(),
                                value,
                            };
                            self.invoke(
                                BLOCK_HELPER_MISSING,
                                call,
                                Some(node),
                                None,
                                Some(prop),
                            )?;
                        } else {
                            // Default behavior is to just render the block
                            self.template(node)?;
                        }
                    } else if self.has_helper(HELPER_MISSING) {
                        self.invoke(HELPER_MISSING, call, None, None, None)?;
                    } else {
                        if self.strict {
                            return Err(RenderError::HelperNotFound(
                                path.as_str().to_string(),
                            ));
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(())
    }

    fn block(
        &mut self,
        node: &'render Node<'render>,
        block: &'render Block<'render>,
    ) -> RenderResult<()> {
        let call = block.call();
        let raw = block.is_raw();

        if call.is_partial() {
            self.render_partial(call, Some(node))?;
        } else {
            match call.target() {
                CallTarget::Path(ref path) => {
                    if path.is_simple() {
                        let mut text: Option<&str> = None;

                        if raw {
                            // Raw block nodes should have a single Text child node
                            text = if !block.nodes().is_empty() {
                                Some(block.nodes().get(0).unwrap().as_str())
                            // Empty raw block should be treated as the empty string
                            } else {
                                Some("")
                            };

                            // Store the hint so we can remove leading whitespace
                            // after a raw block end tag
                            match node {
                                Node::Block(ref block) => {
                                    let hint = block.trim_close();

                                    // Trim leading inside a raw block
                                    if node.trim().after {
                                        if let Some(ref content) = text {
                                            text = Some(content.trim_start());
                                        }
                                    }

                                    // Trim trailing inside a raw block
                                    if hint.before {
                                        if let Some(ref content) = text {
                                            text = Some(content.trim_end());
                                        }
                                    }

                                    // Trim after the end tag
                                    self.end_tag_hint = Some(hint);
                                }
                                _ => {}
                            }
                        }

                        if self.has_helper(path.as_str()) {
                            self.invoke(
                                path.as_str(),
                                call,
                                Some(node),
                                text,
                                None,
                            )?;
                        } else {
                            return self.block_helper_missing(
                                node, block, call, text, raw,
                            );
                        }
                    } else {
                        panic!(
                            "Block helpers identifiers must be simple paths"
                        );
                    }
                }
                //CallTarget::SubExpr(ref sub) => self.call(sub),
                _ => todo!("Handle block sub expression for call target"),
            }
        }
        Ok(())
    }

    pub(crate) fn render_node(
        &mut self,
        node: &'render Node<'render>,
        trim: TrimState,
    ) -> RenderResult<()> {
        self.trim = trim;
        self.hint = Some(node.trim());

        if let Some(hint) = self.end_tag_hint.take() {
            if hint.after {
                self.trim.start = true;
            }
        }

        //println!("Current trim {:?}", &self.trim);

        match node {
            Node::Text(ref n) => {
                //println!("Writing text {}", n.as_str());
                self.write_str(n.as_str(), false)?;
            }
            Node::RawStatement(ref n) => {
                let raw = &n.as_str()[1..];
                self.write_str(raw, false)?;
            }
            Node::RawComment(_) => {}
            Node::Comment(_) => {}
            Node::Document(_) => {}
            Node::Statement(ref call) => {
                if let Some(ref value) = self.statement(call)? {
                    let val = json::stringify(value);
                    self.write_str(&val, call.is_escaped())?;
                }
            }
            Node::Block(ref block) => {
                self.block(node, block)?;
            }
        }

        Ok(())
    }

    fn write_str(&mut self, s: &str, escape: bool) -> RenderResult<usize> {
        let val = if self.trim.start { s.trim_start() } else { s };
        let val = if self.trim.end { val.trim_end() } else { val };
        if val.is_empty() {
            return Ok(0);
        }

        if escape {
            let escaped = (self.escape)(val);
            Ok(self.writer.write_str(&escaped).map_err(RenderError::from)?)
        } else {
            Ok(self.writer.write_str(val).map_err(RenderError::from)?)
        }
    }
}