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
use std::io::Write;

use liquid_core::error::ResultLiquidReplaceExt;
use liquid_core::model::{Value, ValueView};
use liquid_core::Language;
use liquid_core::Renderable;
use liquid_core::Result;
use liquid_core::Runtime;
use liquid_core::{ParseTag, TagReflection, TagTokenIter};

#[derive(Clone, Debug)]
struct Increment {
    id: String,
}

impl Renderable for Increment {
    fn render_to(&self, writer: &mut dyn Write, runtime: &mut Runtime<'_>) -> Result<()> {
        let mut val = runtime
            .stack()
            .get_index(&self.id)
            .and_then(|i| i.as_scalar())
            .and_then(|i| i.to_integer())
            .unwrap_or(0);

        write!(writer, "{}", val).replace("Failed to render")?;
        val += 1;
        runtime
            .stack_mut()
            .set_index(self.id.to_owned(), Value::scalar(val));
        Ok(())
    }
}

#[derive(Copy, Clone, Debug, Default)]
pub struct IncrementTag;

impl IncrementTag {
    pub fn new() -> Self {
        Self::default()
    }
}

impl TagReflection for IncrementTag {
    fn tag(&self) -> &'static str {
        "increment"
    }

    fn description(&self) -> &'static str {
        ""
    }
}

impl ParseTag for IncrementTag {
    fn parse(
        &self,
        mut arguments: TagTokenIter<'_>,
        _options: &Language,
    ) -> Result<Box<dyn Renderable>> {
        let id = arguments
            .expect_next("Identifier expected.")?
            .expect_identifier()
            .into_result()?
            .to_string();

        // no more arguments should be supplied, trying to supply them is an error
        arguments.expect_nothing()?;

        Ok(Box::new(Increment { id }))
    }

    fn reflection(&self) -> &dyn TagReflection {
        self
    }
}

#[derive(Clone, Debug)]
struct Decrement {
    id: String,
}

impl Renderable for Decrement {
    fn render_to(&self, writer: &mut dyn Write, runtime: &mut Runtime<'_>) -> Result<()> {
        let mut val = runtime
            .stack()
            .get_index(&self.id)
            .and_then(|i| i.as_scalar())
            .and_then(|i| i.to_integer())
            .unwrap_or(0);

        val -= 1;
        write!(writer, "{}", val).replace("Failed to render")?;
        runtime
            .stack_mut()
            .set_index(self.id.to_owned(), Value::scalar(val));
        Ok(())
    }
}

#[derive(Copy, Clone, Debug, Default)]
pub struct DecrementTag;

impl DecrementTag {
    pub fn new() -> Self {
        Self::default()
    }
}

impl TagReflection for DecrementTag {
    fn tag(&self) -> &'static str {
        "decrement"
    }

    fn description(&self) -> &'static str {
        ""
    }
}

impl ParseTag for DecrementTag {
    fn parse(
        &self,
        mut arguments: TagTokenIter<'_>,
        _options: &Language,
    ) -> Result<Box<dyn Renderable>> {
        let id = arguments
            .expect_next("Identifier expected.")?
            .expect_identifier()
            .into_result()?
            .to_string();

        // no more arguments should be supplied, trying to supply them is an error
        arguments.expect_nothing()?;

        Ok(Box::new(Decrement { id }))
    }

    fn reflection(&self) -> &dyn TagReflection {
        self
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use liquid_core::parser;
    use liquid_core::runtime;

    use crate::stdlib;

    fn options() -> Language {
        let mut options = Language::default();
        options
            .tags
            .register("assign".to_string(), stdlib::AssignTag.into());
        options
            .tags
            .register("increment".to_string(), IncrementTag.into());
        options
            .tags
            .register("decrement".to_string(), DecrementTag.into());
        options
    }

    #[test]
    fn increment() {
        let text = "{% increment val %}{{ val }}";
        let template = parser::parse(text, &options())
            .map(runtime::Template::new)
            .unwrap();

        let mut runtime = Runtime::new();
        let output = template.render(&mut runtime).unwrap();
        assert_eq!(output, "01");
    }

    #[test]
    fn decrement() {
        let text = "{% decrement val %}{{ val }}";
        let template = parser::parse(text, &options())
            .map(runtime::Template::new)
            .unwrap();

        let mut runtime = Runtime::new();
        let output = template.render(&mut runtime).unwrap();
        assert_eq!(output, "-1-1");
    }

    #[test]
    fn increment_and_decrement() {
        let text = "{% increment val %}{% increment val %}{% decrement val %}{% decrement val %}";
        let template = parser::parse(text, &options())
            .map(runtime::Template::new)
            .unwrap();

        let mut runtime = Runtime::new();
        let output = template.render(&mut runtime).unwrap();
        assert_eq!(output, "0110");
    }

    #[test]
    fn assign_and_increment() {
        let text = "{%- assign val = 9 -%}{% increment val %}{% increment val %}{{ val }}";
        let template = parser::parse(text, &options())
            .map(runtime::Template::new)
            .unwrap();

        let mut runtime = Runtime::new();
        let output = template.render(&mut runtime).unwrap();
        assert_eq!(output, "019");
    }
}