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
//! Test functions and abstractions.
//!
//! Test functions in MiniJinja are like [`filters`](crate::filters) but a
//! different syntax is used to invoke them and they have to return boolean
//! values.  For instance the expression `{% if foo is defined %}` invokes the
//! [`is_defined`] test to check if the value is indeed an odd number.
//!
//! MiniJinja comes with some built-in test functions that are listed below. To
//! create a custom test write a function that takes at least a value argument
//! that returns a boolean result, then register it with
//! [`add_filter`](crate::Environment::add_test).
//!
//! # Using Tests
//!
//! Tests are useful to "test" a value in a specific way.  For instance if
//! you want to assign different classes to alternating rows one way is
//! using the `odd` test:
//!
//! ```jinja
//! {% if seq is defined %}
//!   <ul>
//!   {% for item in seq %}
//!     <li class="{{ 'even' if loop.index is even else 'odd' }}">{{ item }}</li>
//!   {% endfor %}
//!   </ul>
//! {% endif %}
//! ```
//!
//! # Custom Tests
//!
//! A custom test function is just a simple function which accepts its
//! inputs as parameters and then returns a bool. For instance the following
//! shows a test function which takes an input value and checks if it's
//! lowercase:
//!
//! ```
//! # use minijinja::Environment;
//! # let mut env = Environment::new();
//! fn is_lowercase(value: String) -> bool {
//!     value.chars().all(|x| x.is_lowercase())
//! }
//!
//! env.add_test("lowercase", is_lowercase);
//! ```
//!
//! MiniJinja will perform the necessary conversions automatically.  For more
//! information see the [`Test`] trait.
//!
//! # Built-in Tests
//!
//! When the `builtins` feature is enabled a range of built-in tests 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::sync::Arc;

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

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

#[derive(Clone)]
pub(crate) struct BoxedTest(Arc<TestFunc>);

/// A utility trait that represents the return value of filters.
///
/// It's implemented for the following types:
///
/// * `bool`
/// * `Result<bool, Error>`
///
/// The equivalent for filters or functions is [`FunctionResult`](crate::value::FunctionResult).
pub trait TestResult {
    #[doc(hidden)]
    fn into_result(self) -> Result<bool, Error>;
}

impl TestResult for Result<bool, Error> {
    fn into_result(self) -> Result<bool, Error> {
        self
    }
}

impl TestResult for bool {
    fn into_result(self) -> Result<bool, Error> {
        Ok(self)
    }
}

/// A utility trait that represents test functions.
///
/// This trait is used by the [`add_test`](crate::Environment::add_test) method to abstract over
/// different types of functions that implement tests.  Tests are similar to
/// [`filters`](crate::filters) but they always return boolean values and use a
/// slightly different syntax to filters.  Like filters they accept the [`State`] by
/// reference as first parameter and the value that that the test is applied to as second.
/// Additionally up to 4 further parameters are supported.
///
/// A test function can return any of the following types:
///
/// * `bool`
/// * `Result<bool, Error>`
///
/// Tests accept one mandatory parameter which is the value the filter is
/// applied to and up to 4 extra parameters.  The extra 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 tests see [`tests`](crate::tests).
///
/// # Basic Example
///
/// ```
/// # use minijinja::Environment;
/// # let mut env = Environment::new();
/// use minijinja::State;
///
/// fn is_lowercase(value: String) -> bool {
///     value.chars().all(|x| x.is_lowercase())
/// }
///
/// env.add_test("lowercase", is_lowercase);
/// ```
///
/// ```jinja
/// {{ "foo" is lowercase }} -> true
/// ```
///
/// # Arguments and Optional Arguments
///
/// ```
/// # use minijinja::Environment;
/// # let mut env = Environment::new();
/// use minijinja::State;
///
/// fn is_containing(value: String, other: String) -> bool {
///     value.contains(&other)
/// }
///
/// env.add_test("containing", is_containing);
/// ```
///
/// ```jinja
/// {{ "foo" is containing("o") }} -> true
/// ```
pub trait Test<Rv, Args>: Send + Sync + 'static {
    /// Performs a test to value with the given arguments.
    #[doc(hidden)]
    fn perform(&self, args: Args, _: SealedMarker) -> Rv;
}

macro_rules! tuple_impls {
    ( $( $name:ident )* ) => {
        impl<Func, Rv, $($name),*> Test<Rv, ($($name,)*)> for Func
        where
            Func: Fn($($name),*) -> Rv + Send + Sync + 'static,
            Rv: TestResult,
            $($name: for<'a> ArgType<'a>),*
        {
            fn perform(&self, args: ($($name,)*), _: SealedMarker) -> Rv {
                #[allow(non_snake_case)]
                let ($($name,)*) = args;
                (self)($($name,)*)
            }
        }
    };
}

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 }

impl BoxedTest {
    /// Creates a new boxed filter.
    pub fn new<F, Rv, Args>(f: F) -> BoxedTest
    where
        F: Test<Rv, Args> + for<'a> Test<Rv, <Args as FunctionArgs<'a>>::Output>,
        Rv: TestResult,
        Args: for<'a> FunctionArgs<'a>,
    {
        BoxedTest(Arc::new(move |state, args| -> Result<bool, Error> {
            f.perform(ok!(Args::from_values(Some(state), args)), SealedMarker)
                .into_result()
        }))
    }

    /// Applies the filter to a value and argument.
    pub fn perform(&self, state: &State, args: &[Value]) -> Result<bool, Error> {
        (self.0)(state, args)
    }
}

/// Checks if a value is undefined.
///
/// ```jinja
/// {{ 42 is undefined }} -> false
/// ```
pub fn is_undefined(v: Value) -> bool {
    v.is_undefined()
}

/// Checks if a value is defined.
///
/// ```jinja
/// {{ 42 is defined }} -> true
/// ```
pub fn is_defined(v: Value) -> bool {
    !v.is_undefined()
}

/// Checks if a value is none.
///
/// ```jinja
/// {{ none is none }} -> true
/// ```
pub fn is_none(v: Value) -> bool {
    v.is_none()
}

/// Checks if a value is safe.
///
/// ```jinja
/// {{ "<hello>"|escape is safe }} -> true
/// ```
///
/// This filter is also registered with the `escaped` alias.
pub fn is_safe(v: Value) -> bool {
    v.is_safe()
}

#[cfg(feature = "builtins")]
mod builtins {
    use super::*;

    use std::borrow::Cow;

    use crate::value::ops::{coerce, CoerceResult};
    use crate::value::ValueKind;

    /// Return true if the object is a boolean value.
    ///
    /// ```jinja
    /// {{ true is boolean }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_boolean(v: Value) -> bool {
        v.kind() == ValueKind::Bool
    }

    /// Checks if a value is odd.
    ///
    /// ```jinja
    /// {{ 41 is odd }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_odd(v: Value) -> bool {
        i128::try_from(v).ok().map_or(false, |x| x % 2 != 0)
    }

    /// Checks if a value is even.
    ///
    /// ```jinja
    /// {{ 42 is even }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_even(v: Value) -> bool {
        i128::try_from(v).ok().map_or(false, |x| x % 2 == 0)
    }

    /// Return true if the value is divisible by another one.
    ///
    /// ```jinja
    /// {{ 42 is divisibleby(2) }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_divisibleby(v: Value, other: Value) -> bool {
        match coerce(&v, &other) {
            Some(CoerceResult::I128(a, b)) => (a % b) == 0,
            Some(CoerceResult::F64(a, b)) => (a % b) == 0.0,
            _ => false,
        }
    }

    /// Checks if this value is a number.
    ///
    /// ```jinja
    /// {{ 42 is number }} -> true
    /// {{ "42" is number }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_number(v: Value) -> bool {
        matches!(v.kind(), ValueKind::Number)
    }

    /// Checks if this value is an integer.
    ///
    /// ```jinja
    /// {{ 42 is integer }} -> true
    /// {{ 42.0 is integer }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_integer(v: Value) -> bool {
        matches!(
            v.0,
            crate::value::ValueRepr::U64(_)
                | crate::value::ValueRepr::I64(_)
                | crate::value::ValueRepr::U128(_)
                | crate::value::ValueRepr::I128(_)
        )
    }

    /// Checks if this value is a float
    ///
    /// ```jinja
    /// {{ 42 is float }} -> false
    /// {{ 42.0 is float }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_float(v: Value) -> bool {
        matches!(v.0, crate::value::ValueRepr::F64(_))
    }

    /// Checks if this value is a string.
    ///
    /// ```jinja
    /// {{ "42" is string }} -> true
    /// {{ 42 is string }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_string(v: Value) -> bool {
        matches!(v.kind(), ValueKind::String)
    }

    /// Checks if this value is a sequence
    ///
    /// ```jinja
    /// {{ [1, 2, 3] is sequence }} -> true
    /// {{ 42 is sequence }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_sequence(v: Value) -> bool {
        matches!(v.kind(), ValueKind::Seq)
    }

    /// Checks if this value can be iterated over.
    ///
    /// ```jinja
    /// {{ [1, 2, 3] is iterable }} -> true
    /// {{ 42 is iterable }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_iterable(v: Value) -> bool {
        v.try_iter().is_ok()
    }

    /// Checks if this value is a mapping
    ///
    /// ```jinja
    /// {{ {"foo": "bar"} is mapping }} -> true
    /// {{ [1, 2, 3] is mapping }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_mapping(v: Value) -> bool {
        matches!(v.kind(), ValueKind::Map)
    }

    /// Checks if the value is starting with a string.
    ///
    /// ```jinja
    /// {{ "foobar" is startingwith("foo") }} -> true
    /// {{ "foobar" is startingwith("bar") }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_startingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool {
        v.starts_with(&other as &str)
    }

    /// Checks if the value is ending with a string.
    ///
    /// ```jinja
    /// {{ "foobar" is endingwith("bar") }} -> true
    /// {{ "foobar" is endingwith("foo") }} -> false
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    pub fn is_endingwith(v: Cow<'_, str>, other: Cow<'_, str>) -> bool {
        v.ends_with(&other as &str)
    }

    /// Test version of `==`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 1 is eq 1 }} -> true
    /// {{ [1, 2, 3]|select("==", 1) }} => [1]
    /// ```
    ///
    /// By default aliased to `equalto` and `==`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_eq(value: &Value, other: &Value) -> bool {
        *value == *other
    }

    /// Test version of `!=`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 2 is ne 1 }} -> true
    /// {{ [1, 2, 3]|select("!=", 1) }} => [2, 3]
    /// ```
    ///
    /// By default aliased to `!=`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_ne(value: &Value, other: &Value) -> bool {
        *value != *other
    }

    /// Test version of `<`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 1 is lt 2 }} -> true
    /// {{ [1, 2, 3]|select("<", 2) }} => [1]
    /// ```
    ///
    /// By default aliased to `lessthan` and `<`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_lt(value: &Value, other: &Value) -> bool {
        *value < *other
    }

    /// Test version of `<=`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 1 is le 2 }} -> true
    /// {{ [1, 2, 3]|select("<=", 2) }} => [1, 2]
    /// ```
    ///
    /// By default aliased to `<=`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_le(value: &Value, other: &Value) -> bool {
        *value <= *other
    }

    /// Test version of `>`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 2 is gt 1 }} -> true
    /// {{ [1, 2, 3]|select(">", 2) }} => [3]
    /// ```
    ///
    /// By default aliased to `greaterthan` and `>`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_gt(value: &Value, other: &Value) -> bool {
        *value > *other
    }

    /// Test version of `>=`.
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    ///
    /// ```jinja
    /// {{ 2 is ge 1 }} -> true
    /// {{ [1, 2, 3]|select(">=", 2) }} => [2, 3]
    /// ```
    ///
    /// By default aliased to `>=`.
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_ge(value: &Value, other: &Value) -> bool {
        *value >= *other
    }

    /// Test version of `in`.
    ///
    /// ```jinja
    /// {{ 1 is in [1, 2, 3] }} -> true
    /// {{ [1, 2, 3]|select("in", [1, 2]) }} => [1, 2]
    /// ```
    ///
    /// This is useful when combined with [`select`](crate::filters::select).
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_in(state: &State, value: &Value, other: &Value) -> Result<bool, Error> {
        ok!(state.undefined_behavior().assert_iterable(value));
        Ok(crate::value::ops::contains(other, value)
            .map(|value| value.is_true())
            .unwrap_or(false))
    }

    /// Checks if a value is `true`.
    ///
    /// ```jinja
    /// {% if value is true %}...{% endif %}
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_true(value: &Value) -> bool {
        matches!(value.0, crate::value::ValueRepr::Bool(true))
    }

    /// Checks if a value is `false`.
    ///
    /// ```jinja
    /// {% if value is false %}...{% endif %}
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_false(value: &Value) -> bool {
        matches!(value.0, crate::value::ValueRepr::Bool(false))
    }

    /// Checks if a filter with a given name is available.
    ///
    /// ```jinja
    /// {% if 'tojson' is filter %}...{% endif %}
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_filter(state: &State, name: &str) -> bool {
        state.env.get_filter(name).is_some()
    }

    /// Checks if a test with a given name is available.
    ///
    /// ```jinja
    /// {% if 'greaterthan' is test %}...{% endif %}
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_test(state: &State, name: &str) -> bool {
        state.env.get_test(name).is_some()
    }

    /// Checks if a string is all lowercase.
    ///
    /// ```jinja
    /// {{ 'foo' is lower }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_lower(name: &str) -> bool {
        name.chars().all(|x| x.is_lowercase())
    }

    /// Checks if a string is all uppercase.
    ///
    /// ```jinja
    /// {{ 'FOO' is upper }} -> true
    /// ```
    #[cfg_attr(docsrs, doc(cfg(feature = "builtins")))]
    #[cfg(feature = "builtins")]
    pub fn is_upper(name: &str) -> bool {
        name.chars().all(|x| x.is_uppercase())
    }
}

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