minijinja 3.0.0-alpha.0

a powerful template engine for Rust with minimal dependencies
Documentation
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
use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use std::fmt;

use crate::environment::Environment;
use crate::error::{Error, ErrorKind};
use crate::value::Value;
use crate::vm::loop_object::LoopState;

#[cfg(feature = "macros")]
use crate::vm::{Closure, ClosureId};

type Locals<'env> = BTreeMap<&'env str, Value>;

pub(crate) struct Frame<'env> {
    pub(crate) locals: Locals<'env>,
    pub(crate) ctx: Value,
    pub(crate) current_loop: Option<LoopState>,

    // normally a frame does not carry a closure, but it can when a macro is
    // declared.  Once that happens, all writes to the frames locals are also
    // duplicated into the closure.  Macros declared on that level, then share
    // the closure object to enclose the parent values.  This emulates the
    // behavior of closures in Jinja2.
    #[cfg(feature = "macros")]
    pub(crate) closure: Option<ClosureId>,
    #[cfg(feature = "macros")]
    pub(crate) closure_context: Option<ClosureId>,
}

impl<'env> Default for Frame<'env> {
    fn default() -> Frame<'env> {
        Frame::new(Value::UNDEFINED)
    }
}

impl<'env> Frame<'env> {
    /// Creates a new frame with the given context and no validation
    pub fn new(ctx: Value) -> Frame<'env> {
        Frame {
            locals: Locals::new(),
            ctx,
            current_loop: None,
            #[cfg(feature = "macros")]
            closure: None,
            #[cfg(feature = "macros")]
            closure_context: None,
        }
    }

    /// Creates a new frame with the given context and validates the value is not invalid
    pub fn new_checked(root: Value) -> Result<Frame<'env>, Error> {
        Ok(Frame::new(ok!(root.validate())))
    }
}

#[cfg(feature = "internal_debug")]
impl fmt::Debug for Frame<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut m = f.debug_map();
        m.entry(&"locals", &self.locals);
        if let Some(LoopState {
            object: ref controller,
            ..
        }) = self.current_loop
        {
            m.entry(&"loop", controller);
        }
        if !self.ctx.is_undefined() {
            m.entry(&"ctx", &self.ctx);
        }
        m.finish()
    }
}

#[cfg_attr(feature = "internal_debug", derive(Debug))]
pub(crate) struct Stack {
    values: Vec<Value>,
}

impl Default for Stack {
    fn default() -> Stack {
        Stack {
            values: Vec::with_capacity(24),
        }
    }
}

impl Stack {
    pub fn push(&mut self, arg: Value) {
        self.values.push(arg);
    }

    #[track_caller]
    pub fn pop(&mut self) -> Value {
        self.values.pop().unwrap()
    }

    pub fn reverse_top(&mut self, n: usize) {
        let start = self.values.len() - n;
        self.values[start..].reverse();
    }

    pub fn get_call_args(&mut self, n: Option<u16>) -> &[Value] {
        let n = match n {
            Some(n) => n as usize,
            None => self.pop().as_usize().unwrap(),
        };
        &self.values[self.values.len() - n..]
    }

    pub fn drop_top(&mut self, n: usize) {
        self.values.truncate(self.values.len() - n);
    }

    pub fn try_pop(&mut self) -> Option<Value> {
        self.values.pop()
    }

    #[track_caller]
    pub fn peek(&self) -> &Value {
        self.values.last().unwrap()
    }
}

impl From<Vec<Value>> for Stack {
    fn from(values: Vec<Value>) -> Stack {
        Stack { values }
    }
}

pub(crate) struct Context<'env> {
    env: &'env Environment<'env>,
    stack: Vec<Frame<'env>>,
    #[cfg(any(feature = "macros", feature = "multi_template"))]
    outer_stack_depth: usize,
    recursion_limit: usize,
}

pub(super) struct ContextDebug<'a, 'env> {
    context: &'a Context<'env>,
    #[cfg(feature = "macros")]
    closures: &'a [Closure<'env>],
}

impl fmt::Debug for ContextDebug<'_, '_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut vars = Vec::from_iter(self.context.known_variables(
            #[cfg(feature = "macros")]
            self.closures,
            false,
        ));
        vars.sort();
        f.debug_map()
            .entries(vars.into_iter().map(|key| {
                let value = self
                    .context
                    .load(
                        #[cfg(feature = "macros")]
                        self.closures,
                        &key,
                    )
                    .unwrap_or_default();
                (key, value)
            }))
            .finish()
    }
}

impl<'env> Context<'env> {
    pub(super) fn debug<'a>(
        &'a self,
        #[cfg(feature = "macros")] closures: &'a [Closure<'env>],
    ) -> ContextDebug<'a, 'env> {
        ContextDebug {
            context: self,
            #[cfg(feature = "macros")]
            closures,
        }
    }

    /// Creates an empty context.
    pub fn new(env: &'env Environment<'env>) -> Context<'env> {
        Context {
            env,
            stack: Vec::with_capacity(40),
            #[cfg(any(feature = "macros", feature = "multi_template"))]
            outer_stack_depth: 0,
            recursion_limit: env.recursion_limit(),
        }
    }

    /// Creates a context
    pub fn new_with_frame(env: &'env Environment<'env>, frame: Frame<'env>) -> Context<'env> {
        let mut rv = Context::new(env);
        rv.stack.push(frame);
        rv
    }

    #[cfg(feature = "macros")]
    pub fn reset_with_frame(&mut self, frame: Frame<'env>) {
        self.clear();
        self.stack.push(frame);
    }

    #[cfg(feature = "macros")]
    pub fn clear(&mut self) {
        self.stack.clear();
        self.outer_stack_depth = 0;
    }

    /// The env
    #[inline(always)]
    pub fn env(&self) -> &'env Environment<'env> {
        self.env
    }

    /// Stores a variable in the context.
    pub fn store(
        &mut self,
        #[cfg(feature = "macros")] closures: &mut [Closure<'env>],
        key: &'env str,
        value: Value,
    ) {
        let top = self.stack.last_mut().unwrap();
        #[cfg(feature = "macros")]
        if let Some(closure) = top.closure {
            closures[closure].insert(key, value.clone());
        }
        top.locals.insert(key, value);
    }

    /// Adds a value to a closure if missing.
    ///
    /// All macros declared on a certain level reuse the same closure.  This is
    /// done to emulate the behavior of how scopes work in Jinja2 in Python.
    #[cfg(feature = "macros")]
    pub fn enclose(&self, closures: &mut [Closure<'env>], key: &'env str) {
        let closure = self.stack.last().unwrap().closure.unwrap();
        if !closures[closure].contains_key(key) {
            let value = self.load(closures, key).unwrap_or(Value::UNDEFINED);
            closures[closure].insert(key, value);
        }
    }

    /// Returns the closure receiving stores in the current frame.
    #[cfg(feature = "macros")]
    pub fn closure(&self) -> Option<ClosureId> {
        self.stack.last().unwrap().closure
    }

    /// Temporarily takes the closure.
    ///
    /// This is done because includes are in the same scope as the module that
    /// triggers the import, but we do not want to allow closures to be modified
    /// from another file as this would be very confusing.
    ///
    /// This means that if you override a variable referenced by a macro after
    /// including in the parent template, it will not override the value seen by
    /// the macro.
    #[cfg(all(feature = "multi_template", feature = "macros"))]
    pub fn take_closure(&mut self) -> Option<ClosureId> {
        self.stack.last_mut().unwrap().closure.take()
    }

    /// Puts the closure back.
    #[cfg(feature = "macros")]
    pub fn reset_closure(&mut self, closure: Option<ClosureId>) {
        self.stack.last_mut().unwrap().closure = closure;
    }

    /// Return the base context value
    #[cfg(feature = "macros")]
    pub fn clone_base(&self) -> Value {
        self.stack
            .first()
            .map(|x| x.ctx.clone())
            .unwrap_or_default()
    }

    /// Looks up a variable in the context.
    pub fn load(
        &self,
        #[cfg(feature = "macros")] closures: &[Closure<'env>],
        key: &str,
    ) -> Option<Value> {
        for frame in self.stack.iter().rev() {
            // look at locals first
            if let Some(value) = frame.locals.get(key) {
                return Some(value.clone());
            }

            // if we are a loop, check if we are looking up the special loop var.
            if let Some(ref l) = frame.current_loop {
                if l.with_loop_var && key == "loop" {
                    return Some(Value::from_dyn_object(l.object.clone()));
                }
            }

            #[cfg(feature = "macros")]
            if let Some(closure) = frame.closure_context {
                if let Some(value) = closures.get(closure).and_then(|closure| closure.get(key)) {
                    return Some(value.clone());
                }
            }

            // perform a fast lookup.  This one will not produce errors if the
            // context is undefined or of the wrong type.
            if let Some(rv) = frame.ctx.get_attr_fast(key) {
                return Some(rv);
            }
        }

        self.env.get_global(key)
    }

    /// Returns an iterable of all declared variables.
    pub fn known_variables(
        &self,
        #[cfg(feature = "macros")] closures: &[Closure<'env>],
        with_globals: bool,
    ) -> HashSet<Cow<'_, str>> {
        let mut seen = HashSet::<Cow<'_, str>>::new();
        for frame in self.stack.iter().rev() {
            for key in frame.locals.keys() {
                seen.insert(Cow::Borrowed(*key));
            }

            if let Some(ref l) = frame.current_loop {
                if l.with_loop_var {
                    seen.insert(Cow::Borrowed("loop"));
                }
            }

            #[cfg(feature = "macros")]
            if let Some(closure) = frame.closure_context {
                if let Some(closure) = closures.get(closure) {
                    seen.extend(closure.keys().map(|key| Cow::Borrowed(*key)));
                }
            }

            if let Ok(iter) = frame.ctx.try_iter() {
                for key in iter {
                    if let Some(str_key) = key.as_str() {
                        if !seen.contains(&Cow::Borrowed(str_key))
                            && frame.ctx.get_item(&key).is_ok()
                        {
                            seen.insert(Cow::Owned(str_key.to_owned()));
                        }
                    }
                }
            }
        }
        if with_globals {
            seen.extend(self.env.globals().map(|x| Cow::Borrowed(x.0)));
        }
        seen
    }

    /// Pushes a new layer.
    pub fn push_frame(&mut self, layer: Frame<'env>) -> Result<(), Error> {
        self.stack.push(layer);
        if let Err(err) = self.check_depth() {
            self.stack.pop();
            return Err(err);
        }
        Ok(())
    }

    /// Pops the topmost layer.
    #[track_caller]
    pub fn pop_frame(&mut self) -> Frame<'env> {
        self.stack.pop().unwrap()
    }

    /// Returns the root locals (exports)
    #[track_caller]
    pub fn exports(&self) -> &Locals<'env> {
        &self.stack.first().unwrap().locals
    }

    /// Returns the current locals mutably.
    #[track_caller]
    #[cfg(feature = "multi_template")]
    pub fn current_locals_mut(&mut self) -> &mut Locals<'env> {
        &mut self.stack.last_mut().unwrap().locals
    }

    /// Returns the current innermost loop state.
    pub fn current_loop(&self) -> Option<&LoopState> {
        self.stack
            .iter()
            .rev()
            .find_map(|frame| frame.current_loop.as_ref())
    }

    pub fn next_loop_item(&mut self) -> Option<Value> {
        let frame = self
            .stack
            .iter_mut()
            .rev()
            .find(|x| x.current_loop.is_some())?;
        let item = frame.current_loop.as_mut()?.next();
        if item.is_some() {
            frame.locals.clear();
        }
        item
    }

    #[cfg(feature = "multi_template")]
    pub(super) fn stack_depth(&self) -> usize {
        self.stack.len()
    }

    #[cfg(feature = "multi_template")]
    pub(super) fn restore_stack_depth(&mut self, depth: usize) {
        debug_assert!(self.stack.len() >= depth);
        self.stack.truncate(depth);
    }

    /// The real depth of the context.
    #[cfg(any(feature = "macros", feature = "multi_template"))]
    pub fn depth(&self) -> usize {
        self.outer_stack_depth + self.stack.len()
    }

    /// The real depth of the context.
    #[cfg(not(any(feature = "macros", feature = "multi_template")))]
    pub fn depth(&self) -> usize {
        self.stack.len()
    }

    /// Increase the stack depth.
    #[cfg(any(feature = "macros", feature = "multi_template"))]
    pub fn incr_depth(&mut self, delta: usize) -> Result<(), Error> {
        self.outer_stack_depth += delta;
        if let Err(err) = self.check_depth() {
            self.outer_stack_depth -= delta;
            return Err(err);
        }
        Ok(())
    }

    /// Decrease the stack depth.
    #[cfg(feature = "multi_template")]
    pub fn decr_depth(&mut self, delta: usize) {
        self.outer_stack_depth -= delta;
    }

    fn check_depth(&self) -> Result<(), Error> {
        if self.depth() > self.recursion_limit {
            return Err(Error::new(
                ErrorKind::InvalidOperation,
                "recursion limit exceeded",
            ));
        }
        Ok(())
    }
}