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
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
//! Global functions and abstractions.
//!
//! This module provides the abstractions for functions that can registered as
//! global functions to the environment via
//! [`add_function`](crate::Environment::add_function).
//!
//! # Using Functions
//!
//! Functions can be called in any place where an expression is valid.  They
//! are useful to retrieve data.  Some functions are special and provided
//! by the engine (like `super`) within certain context, others are global.
//!
//! The following is a motivating example:
//!
//! ```jinja
//! <pre>{{ debug() }}</pre>
//! ```
//!
//! # Custom Functions
//!
//! A custom global function is just a simple rust function which accepts optional
//! arguments and then returns a result.  Global functions are typically used to
//! perform a data loading operation.  For instance these functions can be used
//! to expose data to the template that hasn't been provided by the individual
//! render invocation.
//!
//! ```rust
//! # use minijinja::Environment;
//! # let mut env = Environment::new();
//! use minijinja::{Error, ErrorKind};
//!
//! fn include_file(name: String) -> Result<String, Error> {
//!     std::fs::read_to_string(&name)
//!         .map_err(|e| Error::new(
//!             ErrorKind::InvalidOperation,
//!             "cannot load file"
//!         ).with_source(e))
//! }
//!
//! env.add_function("include_file", include_file);
//! ```
//!
#![cfg_attr(
    feature = "deserialization",
    doc = r#"
# Arguments in Custom Functions

All value arguments in custom functions must implement the [`ArgType`] trait.
An optional leading `&State` or `&mut State` parameter is handled separately.
Standard types, such as `String`, `i32`, `bool`, `f64`, etc, already implement this trait.
There are also helper types that will make it easier to extract an arguments with custom types.
The [`Serde<T>`](crate::value::Serde) type, for instance, can accept any
type `T` that implements the `Deserialize` trait from `serde`.

```rust
# use minijinja::Environment;
# use serde::Deserialize;
# let mut env = Environment::new();
use minijinja::value::Serde;

#[derive(Deserialize)]
struct Person {
    name: String,
    age: i32,
}

fn is_adult(person: Serde<Person>) -> bool {
    person.age >= 18
}

env.add_function("is_adult", is_adult);
```
"#
)]
//!
//! # Note on Keyword Arguments
//!
//! MiniJinja inherits a lot of the runtime model from Jinja2.  That includes support for
//! keyword arguments.  These however are a concept not native to Rust which makes them
//! somewhat uncomfortable to work with.  In MiniJinja keyword arguments are implemented by
//! converting them into an extra parameter represented by a map.  That means if you call
//! a function as `foo(1, 2, three=3, four=4)` the function gets three arguments:
//!
//! ```json
//! [1, 2, {"three": 3, "four": 4}]
//! ```
//!
//! Regular [`Value`] arguments reject the internal keyword-argument value. Functions that
//! declare keyword arguments should use [`Kwargs`](crate::value::Kwargs). Variadic functions
//! that need to forward or manually split all arguments can use
//! [`ValueOrKwargs`](crate::value::ValueOrKwargs).
//!
//! # Built-in Functions
//!
//! When the `builtins` feature is enabled a range of built-in functions are
//! automatically added to the environment.  These are also all provided in
//! this module.  Note though that these functions are not to be
//! called from Rust code as their exact interface (arguments and return types)
//! might change from one MiniJinja version to another.
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

use crate::error::Error;
use crate::utils::SealedMarker;
use crate::value::{ArgType, FunctionArgs, FunctionResult, Object, ObjectRepr, Value};
use crate::vm::State;

type FuncFunc = dyn Fn(&mut State, &[Value]) -> Result<Value, Error> + Sync + Send + 'static;

/// A boxed function.
#[derive(Clone)]
pub(crate) struct BoxedFunction(Arc<FuncFunc>, #[cfg(feature = "debug")] &'static str);

/// A utility trait that represents global functions.
///
/// This trait is used by the [`add_function`](crate::Environment::add_function)
/// method to abstract over different types of functions.
///
/// Functions can optionally accept the [`State`] by immutable reference as an
/// implicit parameter in any position.  They can instead take `&mut State` as
/// their first parameter and additionally up to 4 further parameters.  They
/// share much of their interface with [`filters`](crate::filters).
///
/// A function can return any of the following types:
///
/// * `Rv` where `Rv` implements `Into<Value>`
/// * `Result<Rv, Error>` where `Rv` implements `Into<Value>`
///
/// The parameters can be marked optional by using `Option<T>`.  The last
/// argument can also use [`Rest<T>`](crate::value::Rest) to capture the
/// remaining arguments.  All types are supported for which
/// [`ArgType`] is implemented.
///
/// For a list of built-in functions see [`functions`](crate::functions).
///
/// **Note:** this trait cannot be implemented and only exists drive the
/// functionality of [`add_function`](crate::Environment::add_function)
/// and [`from_function`](crate::value::Value::from_function).  If you want
/// to implement a custom callable, you can directly implement
/// [`Object::call`] which is what the engine actually uses internally.
///
/// This trait is also used for [`filters`](crate::filters) and
/// [`tests`](crate::tests).
///
/// # Basic Example
///
/// ```rust
/// # use minijinja::Environment;
/// # let mut env = Environment::new();
/// use minijinja::{Error, ErrorKind};
///
/// fn include_file(name: String) -> Result<String, Error> {
///     std::fs::read_to_string(&name)
///         .map_err(|e| Error::new(
///             ErrorKind::InvalidOperation,
///             "cannot load file"
///         ).with_source(e))
/// }
///
/// env.add_function("include_file", include_file);
/// ```
///
/// ```jinja
/// {{ include_file("filename.txt") }}
/// ```
///
/// # Mutable State
///
/// A function which needs to modify the execution state can take `&mut State`
/// as its first parameter.  Unlike `&State`, mutable state must be the first
/// parameter and can only be requested once.
///
/// ```rust
/// # use minijinja::Environment;
/// use minijinja::{State, Value};
///
/// fn counter(state: &mut State) -> i64 {
///     let value = state
///         .get_temp("counter")
///         .and_then(|value| i64::try_from(value).ok())
///         .unwrap_or_default()
///         + 1;
///     state.set_temp("counter", Value::from(value));
///     value
/// }
///
/// # let mut env = Environment::new();
/// env.add_function("counter", counter);
/// ```
///
/// # Variadic
///
/// ```
/// # use minijinja::Environment;
/// # let mut env = Environment::new();
/// use minijinja::value::Rest;
///
/// fn sum(values: Rest<i64>) -> i64 {
///     values.iter().sum()
/// }
///
/// env.add_function("sum", sum);
/// ```
///
/// ```jinja
/// {{ sum(1, 2, 3) }} -> 6
/// ```
///
/// # Optional Arguments
///
/// ```
/// # use minijinja::Environment;
/// # let mut env = Environment::new();
/// fn substr(value: String, start: u32, end: Option<u32>) -> String {
///     let end = end.unwrap_or(value.len() as _);
///     value.get(start as usize..end as usize).unwrap_or_default().into()
/// }
///
/// env.add_filter("substr", substr);
/// ```
///
/// ```jinja
/// {{ "Foo Bar Baz"|substr(4) }} -> Bar Baz
/// {{ "Foo Bar Baz"|substr(4, 7) }} -> Bar
/// ```
pub trait Function<Rv, Args: for<'a> FunctionArgs<'a>>: Send + Sync + 'static {
    /// Calls a function with the given arguments.
    #[doc(hidden)]
    fn invoke<'a>(
        &self,
        state: &'a mut State,
        values: &'a [Value],
        _: SealedMarker,
    ) -> Result<Value, Error>;
}

// This is necessary to avoid a bug in the trait solver. See
// https://github.com/mitsuhiko/minijinja/pull/787 for more details.
trait FunctionHelper<Rv, Args> {
    fn invoke_nested(&self, args: Args) -> Rv;
}

macro_rules! tuple_impls {
    ( $( $name:ident )* ) => {
        impl<Func, Rv, $($name),*> FunctionHelper<Rv, ($($name,)*)> for Func
        where
            Func: Fn($($name),*) -> Rv
        {
            fn invoke_nested(&self, args: ($($name,)*)) -> Rv {
                #[allow(non_snake_case)]
                let ($($name,)*) = args;
                (self)($($name,)*)
            }
        }

        impl<Func, Rv, $($name),*> Function<Rv, ($($name,)*)> for Func
        where
            Func: Send + Sync + 'static,
            // the crazy bounds here exist to enable borrowing in closures
            Func: Fn($($name),*) -> Rv + for<'a> FunctionHelper<Rv, ($(<$name as ArgType<'a>>::Output,)*)>,
            Rv: FunctionResult,
            $($name: for<'a> ArgType<'a>,)*
        {
            fn invoke<'a>(
                &self,
                state: &'a mut State,
                values: &'a [Value],
                _: SealedMarker,
            ) -> Result<Value, Error> {
                self.invoke_nested(ok!(<($($name,)*)>::from_values(Some(state), values)))
                    .into_result()
            }
        }
    };
}

tuple_impls! {}
tuple_impls! { A }
tuple_impls! { A B }
tuple_impls! { A B C }
tuple_impls! { A B C D }
tuple_impls! { A B C D E }

/// Internal argument marker for functions receiving mutable state.
#[doc(hidden)]
pub struct FunctionArgsWithMutState<Args>(PhantomData<fn() -> Args>);

impl<'a, Args> FunctionArgs<'a> for FunctionArgsWithMutState<Args>
where
    Args: FunctionArgs<'a>,
{
    type Output = Args::Output;

    fn from_values(state: Option<&'a State>, values: &'a [Value]) -> Result<Self::Output, Error> {
        Args::from_values(state, values)
    }

    fn from_values_mut(state: Option<&State>, values: &'a [Value]) -> Result<Self::Output, Error> {
        Args::from_values_mut(state, values)
    }
}

trait FunctionMutHelper<Rv, Args> {
    fn invoke_nested_mut(&self, state: &mut State<'_, '_>, args: Args) -> Rv;
}

macro_rules! tuple_mut_impls {
    ( $( $name:ident )* ) => {
        impl<Func, Rv, $($name),*> FunctionMutHelper<Rv, ($($name,)*)> for Func
        where
            Func: Fn(&mut State<'_, '_>, $($name),*) -> Rv
        {
            fn invoke_nested_mut(&self, state: &mut State<'_, '_>, args: ($($name,)*)) -> Rv {
                #[allow(non_snake_case)]
                let ($($name,)*) = args;
                (self)(state, $($name),*)
            }
        }

        impl<Func, Rv, $($name),*> Function<Rv, FunctionArgsWithMutState<($($name,)*)>> for Func
        where
            Func: Send + Sync + 'static,
            // the crazy bounds here exist to enable borrowing in closures
            Func: Fn(&mut State<'_, '_>, $($name),*) -> Rv
                + for<'a> FunctionMutHelper<Rv, ($(<$name as ArgType<'a>>::Output,)*)>,
            Rv: FunctionResult,
            $($name: for<'a> ArgType<'a>,)*
        {
            fn invoke<'a>(
                &self,
                state: &'a mut State,
                values: &'a [Value],
                _: SealedMarker,
            ) -> Result<Value, Error> {
                let args = ok!(<($($name,)*)>::from_values_mut(Some(state), values));
                self.invoke_nested_mut(state, args).into_result()
            }
        }
    };
}

tuple_mut_impls! {}
tuple_mut_impls! { A }
tuple_mut_impls! { A B }
tuple_mut_impls! { A B C }
tuple_mut_impls! { A B C D }

impl BoxedFunction {
    /// Creates a new boxed filter.
    pub fn new<F, Rv, Args>(f: F) -> BoxedFunction
    where
        F: Function<Rv, Args>,
        Rv: FunctionResult,
        Args: for<'a> FunctionArgs<'a>,
    {
        BoxedFunction(
            Arc::new(move |state, args| f.invoke(state, args, SealedMarker)),
            #[cfg(feature = "debug")]
            std::any::type_name::<F>(),
        )
    }

    /// Creates a value from a boxed function.
    pub fn to_value(&self) -> Value {
        Value::from_object(self.clone())
    }
}

impl fmt::Debug for BoxedFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(feature = "debug")]
        {
            if !self.1.is_empty() {
                return f.write_str(self.1);
            }
        }
        f.write_str("function")
    }
}

impl Object for BoxedFunction {
    fn repr(self: &Arc<Self>) -> ObjectRepr {
        ObjectRepr::Plain
    }

    fn call(self: &Arc<Self>, state: &mut State, args: &[Value]) -> Result<Value, Error> {
        (self.0)(state, args)
    }
}

#[cfg(feature = "builtins")]
mod builtins {
    use std::cmp::Ordering;

    use super::*;

    use crate::error::ErrorKind;
    use crate::value::{Rest, ValueMap, ValueRepr};

    /// Returns a range.
    ///
    /// Return a list containing an arithmetic progression of integers. `range(i,
    /// j)` returns `[i, i+1, i+2, ..., j-1]`. `lower` defaults to 0. When `step` is
    /// given, it specifies the increment (or decrement). For example, `range(4)`
    /// and `range(0, 4, 1)` return `[0, 1, 2, 3]`. The end point is omitted.
    ///
    /// ```jinja
    /// <ul>
    /// {% for num in range(1, 11) %}
    ///   <li>{{ num }}
    /// {% endfor %}
    /// </ul>
    /// ```
    ///
    /// This function will refuse to create ranges over 10.000 items.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn range(lower: isize, upper: Option<isize>, step: Option<isize>) -> Result<Value, Error> {
        fn to_result<I: ExactSizeIterator<Item = isize> + Send + Sync + Clone + 'static>(
            i: I,
        ) -> Result<Value, Error> {
            if i.len() > 100000 {
                Err(Error::new(
                    ErrorKind::InvalidOperation,
                    "range has too many elements",
                ))
            } else {
                Ok(Value::make_iterable(move || i.clone()))
            }
        }

        let rng = match upper {
            Some(upper) => lower..upper,
            None => 0..lower,
        };

        let Some(step) = step else {
            return to_result(rng);
        };

        match step.cmp(&0) {
            Ordering::Equal => Err(Error::new(
                ErrorKind::InvalidOperation,
                "cannot create range with step of 0",
            )),
            Ordering::Greater => to_result(rng.step_by(step as usize)),
            Ordering::Less => {
                // handle negative steps
                debug_assert!(step < 0);
                let (start, end) = match upper {
                    Some(upper) => (lower, upper),
                    None => (0, lower),
                };

                let len = if start <= end {
                    0
                } else {
                    ((start - end + (-step) - 1) / (-step)) as usize
                };

                let iter = (0..len).map(move |i| start + (i as isize) * step);
                to_result(iter)
            }
        }
    }

    /// Creates a dictionary.
    ///
    /// This is a convenient alternative for a dictionary literal.
    /// `{"foo": "bar"}` is the same as `dict(foo="bar")`.
    ///
    /// ```jinja
    /// <script>const CONFIG = {{ dict(
    ///   DEBUG=true,
    ///   API_URL_PREFIX="/api"
    /// )|tojson }};</script>
    /// ```
    ///
    /// Additionally this can be used to merge objects by passing extra keyword
    /// arguments:
    ///
    /// ```jinja
    /// {% set new_dict = dict(old_dict, extra_value=2) %}
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn dict(value: Option<Value>, update_with: crate::value::Kwargs) -> Result<Value, Error> {
        let mut rv = match value {
            None => ValueMap::default(),
            Some(value) => match value.0 {
                ValueRepr::Undefined(_) => ValueMap::default(),
                ValueRepr::Object(obj) if obj.repr() == ObjectRepr::Map => {
                    obj.try_iter_pairs().into_iter().flatten().collect()
                }
                _ => return Err(Error::from(ErrorKind::InvalidOperation)),
            },
        };

        if update_with.values.is_true() {
            rv.extend(
                update_with
                    .values
                    .iter()
                    .map(|(k, v)| (k.clone(), v.clone())),
            );
        }

        Ok(Value::from_object(rv))
    }

    /// Outputs the current context or the arguments stringified.
    ///
    /// This is a useful function to quickly figure out the state of affairs
    /// in a template.  It emits a stringified debug dump of the current
    /// engine state including the layers of the context, the current block
    /// and auto escaping setting.  The exact output is not defined and might
    /// change from one version of Jinja2 to the next.
    ///
    /// ```jinja
    /// <pre>{{ debug() }}</pre>
    /// <pre>{{ debug(variable1, variable2) }}</pre>
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn debug(state: &State, args: Rest<Value>) -> String {
        if args.is_empty() {
            format!("{state:#?}")
        } else if args.len() == 1 {
            format!("{:#?}", args.0[0])
        } else {
            format!("{:#?}", &args.0[..])
        }
    }

    /// Creates a new container that allows attribute assignment using the `{% set %}` tag.
    ///
    /// ```jinja
    /// {% set ns = namespace() %}
    /// {% set ns.foo = 'bar' %}
    /// ```
    ///
    /// The main purpose of this is to allow carrying a value from within a loop body
    /// to an outer scope. Initial values can be provided as a dict, as keyword arguments,
    /// or both (same behavior as [`dict`]).
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn namespace(defaults: Option<crate::value::ValueOrKwargs>) -> Result<Value, Error> {
        let ns = crate::value::namespace_object::Namespace::default();
        if let Some(defaults) = defaults {
            let defaults = defaults.into_value();
            if let Some(pairs) = defaults
                .as_object()
                .filter(|x| matches!(x.repr(), ObjectRepr::Map))
                .and_then(|x| x.try_iter_pairs())
            {
                for (key, value) in pairs {
                    if let Some(key) = key.as_str() {
                        ns.set_value(key, value);
                    }
                }
            } else {
                return Err(Error::new(
                    ErrorKind::InvalidOperation,
                    format!(
                        "expected object or keyword arguments, got {}",
                        defaults.kind()
                    ),
                ));
            }
        }
        Ok(Value::from_object(ns))
    }
}

#[cfg(feature = "builtins")]
pub use self::builtins::*;