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
use little::{ Mem, Instruction };
use value::Value;
use error::TemplateResult;
use mold::Staging;

mod body;
mod expr;
mod module;

pub trait Compile<'c> {
    fn compile<'r>(&'r self, stage: &'r mut Staging<'c, Value>) -> TemplateResult<()>;
}

/// Represents a mess created by a compiled expression.
///
/// It is up to the caller to clean up this mess by calling `finalize` on this struct.
pub struct CompiledExpression {
    origin: &'static str,
    stack_length: u16,
    result: Option<Mem>,
    finalized: bool,
}

impl CompiledExpression {
    pub fn with_result(origin: &'static str, result: Mem) -> CompiledExpression {
        CompiledExpression {
            origin: origin,
            stack_length: 0,
            result: Some(result),
            finalized: false,
        }
    }

    pub fn empty(origin: &'static str) -> CompiledExpression {
        CompiledExpression {
            origin: origin,
            stack_length: 0,
            result: None,
            finalized: false,
        }
    }

    pub fn new(origin: &'static str, result: Mem, stack_length: u16) -> CompiledExpression {
        CompiledExpression {
            origin: origin,
            stack_length: stack_length,
            result: Some(result),
            finalized: false,
        }
    }

    pub fn result(&self) -> Option<Mem> {
        self.result.clone()
    }

    pub fn finalize<'c, 'r>(mut self, stage: &'r mut Staging<'c, Value>) -> TemplateResult<()> {
        if self.stack_length > 0 {
            trace!("finalize {}", self.origin);
            stage.instr(Instruction::Pop { times: self.stack_length });
        }
        self.finalized = true;
        Ok(())
    }
}

impl Drop for CompiledExpression {
    fn drop(&mut self) {
        if !self.finalized {
            panic!("finalize never called on {}!", self.origin);
        }
    }
}

pub trait CompileExpression<'c> {
    /// Compiles ast subnodes that return result in
    fn compile<'r>(&'r self, stage: &'r mut Staging<'c, Value>) -> TemplateResult<CompiledExpression>;
}