-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
value.rs
1926 lines (1724 loc) · 59.5 KB
/
value.rs
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Provides a dynamic value type abstraction.
//!
//! This module gives access to a dynamically typed value which is used by
//! the template engine during execution.
//!
//! For the most part the existence of the value type can be ignored as
//! MiniJinja will perform the necessary conversions for you. For instance
//! if you write a filter that converts a string you can directly declare the
//! filter to take a [`String`](std::string::String). However for some more
//! advanced use cases it's useful to know that this type exists.
//!
//! # Converting Values
//!
//! Values are typically created via the [`From`] trait:
//!
//! ```
//! # use minijinja::value::Value;
//! let value = Value::from(42);
//! ```
//!
//! MiniJinja will however create values via an indirection via [`serde`] when
//! a template is rendered or an expression is evaluated. This can also be
//! triggered manually by using the [`Value::from_serializable`] method:
//!
//! ```
//! # use minijinja::value::Value;
//! let value = Value::from_serializable(&[1, 2, 3]);
//! ```
//!
//! To to into the inverse directly the various [`TryFrom`](std::convert::TryFrom)
//! implementations can be used:
//!
//! ```
//! # use minijinja::value::Value;
//! use std::convert::TryFrom;
//! let v = u64::try_from(Value::from(42)).unwrap();
//! ```
//!
//! # Value Function Arguments
//!
//! [Filters](crate::filters) and [tests](crate::tests) can take values as arguments
//! but optionally also rust types directly. This conversion for function arguments
//! is performed by the [`FunctionArgs`] trait.
//!
//! # Memory Management
//!
//! Values are immutable objects which are internally reference counted which
//! means they can be copied relatively cheaply. Special care must be taken
//! so that cycles are not created to avoid causing memory leaks.
//!
//! # HTML Escaping
//!
//! MiniJinja inherits the general desire to be clever about escaping. For this
//! prupose a value will (when auto escaping is enabled) always be escaped. To
//! prevent this behavior the [`safe`](crate::filters::safe) filter can be used
//! in the template. Outside of templates the [`Value::from_safe_string`] method
//! can be used to achieve the same result.
//!
//! # Dynamic Objects
//!
//! Values can also hold "dynamic" objects. These are objects which implement the
//! [`Object`] trait. These can be used to implement dynamic functionality such as
//! stateful values and more.
// this module is based on the content module in insta which in turn is based
// on the content module in serde::private::ser.
use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::fmt::{self, Write};
use std::sync::atomic::{self, AtomicBool, AtomicUsize};
use serde::ser::{self, Serialize, Serializer};
use crate::error::{Error, ErrorKind};
use crate::key::{Key, KeySerializer};
use crate::utils::{matches, OnDrop};
use crate::vm::State;
#[cfg(test)]
use similar_asserts::assert_eq;
#[cfg(feature = "sync")]
pub(crate) type RcType<T> = std::sync::Arc<T>;
#[cfg(not(feature = "sync"))]
pub(crate) type RcType<T> = std::rc::Rc<T>;
// We use in-band signalling to roundtrip some internal values. This is
// not ideal but unfortunately there is no better system in serde today.
const VALUE_HANDLE_MARKER: &str = "\x01__minijinja_ValueHandle";
#[cfg(feature = "preserve_order")]
pub(crate) type ValueMap = indexmap::IndexMap<Key<'static>, Value>;
#[cfg(not(feature = "preserve_order"))]
pub(crate) type ValueMap = std::collections::BTreeMap<Key<'static>, Value>;
thread_local! {
static INTERNAL_SERIALIZATION: AtomicBool = AtomicBool::new(false);
static LAST_VALUE_HANDLE: AtomicUsize = AtomicUsize::new(0);
static VALUE_HANDLES: RefCell<BTreeMap<usize, Value>> = RefCell::new(BTreeMap::new());
}
/// Function that returns true when serialization for [`Value`] is taking place.
///
/// MiniJinja internally creates [`Value`] objects from all values passed to the
/// engine. It does this by going through the regular serde serialization trait.
/// In some cases users might want to customize the serialization specifically for
/// MiniJinja because they want to tune the object for the template engine
/// independently of what is normally serialized to disk.
///
/// This function returns `true` when MiniJinja is serializing to [`Value`] and
/// `false` otherwise. You can call this within your own [`Serialize`]
/// implementation to change the output format.
///
/// This is particularly useful as serialization for MiniJinja does not need to
/// support deserialization. So it becomes possible to completely change what
/// gets sent there, even at the cost of serializing something that cannot be
/// deserialized.
pub fn serializing_for_value() -> bool {
INTERNAL_SERIALIZATION.with(|flag| flag.load(atomic::Ordering::Relaxed))
}
/// Enables a temporary code section within which some value
/// optimizations are enabled. Currently this is exclusively
/// used to automatically intern keys when the `key_interning`
/// feature is enabled.
#[inline(always)]
pub(crate) fn with_value_optimization<R, F: FnOnce() -> R>(f: F) -> R {
#[cfg(not(feature = "key_interning"))]
{
f()
}
#[cfg(feature = "key_interning")]
{
crate::key::key_interning::with(f)
}
}
/// Executes code within the context of internal serialization
/// which causes the value type to enable the internal round
/// tripping serialization.
fn with_internal_serialization<R, F: FnOnce() -> R>(f: F) -> R {
INTERNAL_SERIALIZATION.with(|flag| {
let old = flag.load(atomic::Ordering::Relaxed);
flag.store(true, atomic::Ordering::Relaxed);
let _on_drop = OnDrop::new(|| {
flag.store(old, atomic::Ordering::Relaxed);
});
with_value_optimization(f)
})
}
/// Helper trait representing valid filter and test arguments.
///
/// Since it's more convenient to write filters and tests with concrete
/// types instead of values, this helper trait exists to automatically
/// perform this conversion. It is implemented for functions up to an
/// arity of 5 parameters.
///
/// For each argument the conversion is performed via the [`ArgType`]
/// trait which is implemented for some primitive concrete types as well
/// as these types wrapped in [`Option`].
pub trait FunctionArgs: Sized {
/// Converts to function arguments from a slice of values.
fn from_values(values: Vec<Value>) -> Result<Self, Error>;
}
/// A trait implemented by all filter/test argument types.
///
/// This trait is the companion to [`FunctionArgs`]. It's passed an
/// `Option<Value>` where `Some` means the argument was provided or
/// `None` if it was not. This is used to implement optional arguments
/// to functions.
pub trait ArgType: Sized {
fn from_value(value: Option<Value>) -> Result<Self, Error>;
}
macro_rules! tuple_impls {
( $( $name:ident )* ) => {
impl<$($name: ArgType,)*> FunctionArgs for ($($name,)*) {
fn from_values(values: Vec<Value>) -> Result<Self, Error> {
#![allow(non_snake_case, unused)]
let arg_count = 0 $(
+ { let $name = (); 1 }
)*;
if values.len() > arg_count {
return Err(Error::new(
ErrorKind::InvalidArguments,
"received unexpected extra arguments",
));
}
{
let mut idx = 0;
$(
let $name = ArgType::from_value(values.get(idx).cloned())?;
idx += 1;
)*
Ok(( $($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 }
/// Describes the kind of value.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum ValueKind {
Undefined,
None,
Bool,
Number,
Char,
String,
Bytes,
Seq,
Map,
}
impl fmt::Display for ValueKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ty = match *self {
ValueKind::Undefined => "undefined",
ValueKind::None => "none",
ValueKind::Bool => "bool",
ValueKind::Number => "number",
ValueKind::Char => "char",
ValueKind::String => "string",
ValueKind::Bytes => "bytes",
ValueKind::Seq => "sequence",
ValueKind::Map => "map",
};
write!(f, "{}", ty)
}
}
#[derive(Clone)]
pub(crate) enum ValueRepr {
Undefined,
Bool(bool),
U64(u64),
I64(i64),
F64(f64),
Char(char),
None,
U128(RcType<u128>),
I128(RcType<i128>),
String(RcType<String>),
SafeString(RcType<String>),
Bytes(RcType<Vec<u8>>),
Seq(RcType<Vec<Value>>),
Map(RcType<ValueMap>),
Dynamic(RcType<dyn Object>),
}
impl fmt::Debug for ValueRepr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValueRepr::Undefined => write!(f, "Undefined"),
ValueRepr::Bool(val) => fmt::Debug::fmt(val, f),
ValueRepr::U64(val) => fmt::Debug::fmt(val, f),
ValueRepr::I64(val) => fmt::Debug::fmt(val, f),
ValueRepr::F64(val) => fmt::Debug::fmt(val, f),
ValueRepr::Char(val) => fmt::Debug::fmt(val, f),
ValueRepr::None => write!(f, "None"),
ValueRepr::U128(val) => fmt::Debug::fmt(val, f),
ValueRepr::I128(val) => fmt::Debug::fmt(val, f),
ValueRepr::String(val) => fmt::Debug::fmt(val, f),
ValueRepr::SafeString(val) => fmt::Debug::fmt(val, f),
ValueRepr::Bytes(val) => fmt::Debug::fmt(val, f),
ValueRepr::Seq(val) => fmt::Debug::fmt(val, f),
ValueRepr::Map(val) => fmt::Debug::fmt(val, f),
ValueRepr::Dynamic(val) => fmt::Debug::fmt(val, f),
}
}
}
/// Represents a dynamically typed value in the template engine.
#[derive(Clone)]
pub struct Value(pub(crate) ValueRepr);
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(ValueRepr::None, ValueRepr::None) => true,
(ValueRepr::String(a), ValueRepr::String(b))
| (ValueRepr::SafeString(a), ValueRepr::SafeString(b)) => a == b,
(ValueRepr::Bytes(a), ValueRepr::Bytes(b)) => a == b,
_ => match coerce(self, other) {
Some(CoerceResult::F64(a, b)) => a == b,
Some(CoerceResult::I128(a, b)) => a == b,
Some(CoerceResult::String(a, b)) => a == b,
None => false,
},
}
}
}
impl Eq for Value {}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (&self.0, &other.0) {
(ValueRepr::None, ValueRepr::None) => Some(Ordering::Equal),
(ValueRepr::String(a), ValueRepr::String(b))
| (ValueRepr::SafeString(a), ValueRepr::SafeString(b)) => a.partial_cmp(b),
(ValueRepr::Bytes(a), ValueRepr::Bytes(b)) => a.partial_cmp(b),
_ => match coerce(self, other) {
Some(CoerceResult::F64(a, b)) => a.partial_cmp(&b),
Some(CoerceResult::I128(a, b)) => a.partial_cmp(&b),
Some(CoerceResult::String(a, b)) => a.partial_cmp(&b),
None => None,
},
}
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
fmt::Debug::fmt(&self.0, f)
}
}
impl From<ValueRepr> for Value {
#[inline(always)]
fn from(val: ValueRepr) -> Value {
Value(val)
}
}
impl<'a> From<&'a [u8]> for Value {
#[inline(always)]
fn from(val: &'a [u8]) -> Self {
ValueRepr::Bytes(RcType::new(val.into())).into()
}
}
impl<'a> From<&'a str> for Value {
#[inline(always)]
fn from(val: &'a str) -> Self {
ValueRepr::String(RcType::new(val.into())).into()
}
}
impl From<String> for Value {
#[inline(always)]
fn from(val: String) -> Self {
ValueRepr::String(RcType::new(val)).into()
}
}
impl<'a> From<Cow<'a, str>> for Value {
#[inline(always)]
fn from(val: Cow<'a, str>) -> Self {
match val {
Cow::Borrowed(x) => x.into(),
Cow::Owned(x) => x.into(),
}
}
}
impl From<()> for Value {
#[inline(always)]
fn from(_: ()) -> Self {
ValueRepr::None.into()
}
}
impl From<i128> for Value {
#[inline(always)]
fn from(val: i128) -> Self {
ValueRepr::I128(RcType::new(val)).into()
}
}
impl From<u128> for Value {
#[inline(always)]
fn from(val: u128) -> Self {
ValueRepr::U128(RcType::new(val)).into()
}
}
impl<'a> From<Key<'a>> for Value {
fn from(val: Key) -> Self {
match val {
Key::Bool(val) => val.into(),
Key::I64(val) => val.into(),
Key::Char(val) => val.into(),
Key::String(val) => ValueRepr::String(val).into(),
Key::Str(val) => val.into(),
}
}
}
impl<K: Into<Key<'static>>, V: Into<Value>> From<BTreeMap<K, V>> for Value {
fn from(val: BTreeMap<K, V>) -> Self {
ValueRepr::Map(RcType::new(
val.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
))
.into()
}
}
impl<T: Into<Value>> From<Vec<T>> for Value {
fn from(val: Vec<T>) -> Self {
ValueRepr::Seq(RcType::new(val.into_iter().map(|x| x.into()).collect())).into()
}
}
macro_rules! value_from {
($src:ty, $dst:ident) => {
impl From<$src> for Value {
#[inline(always)]
fn from(val: $src) -> Self {
ValueRepr::$dst(val as _).into()
}
}
};
}
value_from!(bool, Bool);
value_from!(u8, U64);
value_from!(u16, U64);
value_from!(u32, U64);
value_from!(u64, U64);
value_from!(i8, I64);
value_from!(i16, I64);
value_from!(i32, I64);
value_from!(i64, I64);
value_from!(f32, F64);
value_from!(f64, F64);
value_from!(char, Char);
enum CoerceResult {
I128(i128, i128),
F64(f64, f64),
String(String, String),
}
fn as_f64(value: &Value) -> Option<f64> {
Some(match value.0 {
ValueRepr::Bool(x) => x as i64 as f64,
ValueRepr::U64(x) => x as f64,
ValueRepr::U128(ref x) => **x as f64,
ValueRepr::I64(x) => x as f64,
ValueRepr::I128(ref x) => **x as f64,
ValueRepr::F64(x) => x,
_ => return None,
})
}
fn coerce(a: &Value, b: &Value) -> Option<CoerceResult> {
match (&a.0, &b.0) {
// equal mappings are trivial
(ValueRepr::U64(a), ValueRepr::U64(b)) => Some(CoerceResult::I128(*a as i128, *b as i128)),
(ValueRepr::U128(a), ValueRepr::U128(b)) => {
Some(CoerceResult::I128(**a as i128, **b as i128))
}
(ValueRepr::String(a), ValueRepr::String(b)) => {
Some(CoerceResult::String(a.to_string(), b.to_string()))
}
(ValueRepr::I64(a), ValueRepr::I64(b)) => Some(CoerceResult::I128(*a as i128, *b as i128)),
(ValueRepr::I128(ref a), ValueRepr::I128(ref b)) => Some(CoerceResult::I128(**a, **b)),
(ValueRepr::F64(a), ValueRepr::F64(b)) => Some(CoerceResult::F64(*a, *b)),
// are floats involved?
(ValueRepr::F64(a), _) => Some(CoerceResult::F64(*a, as_f64(b)?)),
(_, ValueRepr::F64(b)) => Some(CoerceResult::F64(as_f64(a)?, *b)),
// everything else goes up to i128
_ => Some(CoerceResult::I128(
i128::try_from(a.clone()).ok()?,
i128::try_from(b.clone()).ok()?,
)),
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ValueRepr::Undefined => Ok(()),
ValueRepr::Bool(val) => write!(f, "{}", val),
ValueRepr::U64(val) => write!(f, "{}", val),
ValueRepr::I64(val) => write!(f, "{}", val),
ValueRepr::F64(val) => {
let mut num = val.to_string();
if !num.contains('.') {
num.push_str(".0");
}
write!(f, "{}", num)
}
ValueRepr::Char(val) => write!(f, "{}", val),
ValueRepr::None => write!(f, "none"),
ValueRepr::I128(val) => write!(f, "{}", val),
ValueRepr::String(val) => write!(f, "{}", val),
ValueRepr::SafeString(val) => write!(f, "{}", val),
ValueRepr::Bytes(val) => write!(f, "{}", String::from_utf8_lossy(val)),
ValueRepr::Seq(values) => {
write!(f, "[")?;
for (idx, val) in values.iter().enumerate() {
if idx > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}", val)?;
}
write!(f, "]")
}
ValueRepr::Map(m) => {
write!(f, "{{")?;
for (idx, (key, val)) in m.iter().enumerate() {
if idx > 0 {
write!(f, ", ")?;
}
write!(f, "{:?}: {:?}", key, val)?;
}
write!(f, "}}")
}
ValueRepr::U128(val) => write!(f, "{}", val),
ValueRepr::Dynamic(x) => write!(f, "{}", x),
}
}
}
impl Default for Value {
fn default() -> Value {
ValueRepr::None.into()
}
}
fn int_as_value(val: i128) -> Value {
if val as i64 as i128 == val {
(val as i64).into()
} else {
val.into()
}
}
fn impossible_op(op: &str, lhs: &Value, rhs: &Value) -> Error {
Error::new(
ErrorKind::ImpossibleOperation,
format!(
"tried to use {} operator on unsupported types {} and {}",
op,
lhs.kind(),
rhs.kind()
),
)
}
macro_rules! math_binop {
($name:ident, $int:ident, $float:tt) => {
pub(crate) fn $name(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
fn do_it(lhs: &Value, rhs: &Value) -> Option<Value> {
match coerce(lhs, rhs)? {
CoerceResult::I128(a, b) => Some(int_as_value(a.$int(b))),
CoerceResult::F64(a, b) => Some((a $float b).into()),
_ => None
}
}
do_it(lhs, rhs).ok_or_else(|| {
impossible_op(stringify!($float), lhs, rhs)
})
}
}
}
pub(crate) fn add(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
fn do_it(lhs: &Value, rhs: &Value) -> Option<Value> {
match coerce(lhs, rhs)? {
CoerceResult::I128(a, b) => Some(int_as_value(a.wrapping_add(b))),
CoerceResult::F64(a, b) => Some((a + b).into()),
CoerceResult::String(a, b) => Some(Value::from([a, b].concat())),
}
}
do_it(lhs, rhs).ok_or_else(|| impossible_op("+", lhs, rhs))
}
math_binop!(sub, wrapping_sub, -);
math_binop!(mul, wrapping_mul, *);
math_binop!(rem, wrapping_rem_euclid, %);
pub(crate) fn div(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
fn do_it(lhs: &Value, rhs: &Value) -> Option<Value> {
let a = as_f64(lhs)?;
let b = as_f64(rhs)?;
Some((a / b).into())
}
do_it(lhs, rhs).ok_or_else(|| impossible_op("/", lhs, rhs))
}
pub(crate) fn int_div(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
fn do_it(lhs: &Value, rhs: &Value) -> Option<Value> {
match coerce(lhs, rhs)? {
CoerceResult::I128(a, b) => Some(int_as_value(a.div_euclid(b))),
CoerceResult::F64(a, b) => Some(a.div_euclid(b).into()),
CoerceResult::String(_, _) => None,
}
}
do_it(lhs, rhs).ok_or_else(|| impossible_op("//", lhs, rhs))
}
/// Implements a binary `pow` operation on values.
pub(crate) fn pow(lhs: &Value, rhs: &Value) -> Result<Value, Error> {
pub fn do_it(lhs: &Value, rhs: &Value) -> Option<Value> {
match coerce(lhs, rhs)? {
CoerceResult::I128(a, b) => Some(int_as_value(a.pow(TryFrom::try_from(b).ok()?))),
CoerceResult::F64(a, b) => Some((a.powf(b)).into()),
CoerceResult::String(_, _) => None,
}
}
do_it(lhs, rhs).ok_or_else(|| impossible_op("**", lhs, rhs))
}
/// Implements an unary `neg` operation on value.
pub(crate) fn neg(val: &Value) -> Result<Value, Error> {
fn do_it(val: &Value) -> Option<Value> {
match val.0 {
ValueRepr::F64(x) => return Some((-x).into()),
_ => {
if let Ok(x) = i128::try_from(val.clone()) {
return Some(int_as_value(-x));
}
}
}
None
}
if val.kind() != ValueKind::Number {
Err(Error::from(ErrorKind::ImpossibleOperation))
} else {
do_it(val).ok_or_else(|| Error::from(ErrorKind::ImpossibleOperation))
}
}
/// Attempts a string concatenation.
pub(crate) fn string_concat(mut left: Value, right: &Value) -> Value {
match left.0 {
// if we're a string and we have a single reference to it, we can
// directly append into ourselves and reconstruct the value
ValueRepr::String(ref mut s) => {
write!(RcType::make_mut(s), "{}", right).ok();
left
}
// otherwise we use format! to concat the two values
_ => Value::from(format!("{}{}", left, right)),
}
}
/// Implements a containment operation on values.
pub(crate) fn contains(container: &Value, value: &Value) -> Result<Value, Error> {
match container.0 {
ValueRepr::Seq(ref values) => Ok(Value::from(values.contains(value))),
ValueRepr::Map(ref map) => {
let key = match value.clone().try_into_key() {
Ok(key) => key,
Err(_) => return Ok(Value::from(false)),
};
return Ok(Value::from(map.get(&key).is_some()));
}
ValueRepr::String(ref s) | ValueRepr::SafeString(ref s) => {
return Ok(Value::from(if let Some(s2) = value.as_str() {
s.contains(&s2)
} else {
s.contains(&value.to_string())
}));
}
_ => Err(Error::new(
ErrorKind::ImpossibleOperation,
"cannot perform a containment check on this value",
)),
}
}
macro_rules! primitive_try_from {
($ty:ident, {
$($pat:pat $(if $if_expr:expr)? => $expr:expr,)*
}) => {
impl TryFrom<Value> for $ty {
type Error = Error;
fn try_from(value: Value) -> Result<Self, Self::Error> {
let opt = match value.0 {
$($pat $(if $if_expr)? => TryFrom::try_from($expr).ok(),)*
_ => None
};
opt.ok_or_else(|| {
Error::new(
ErrorKind::ImpossibleOperation,
format!("cannot convert {} to {}", value.kind(), stringify!($ty))
)
})
}
}
impl ArgType for $ty {
fn from_value(value: Option<Value>) -> Result<Self, Error> {
match value {
Some(value) => TryFrom::try_from(value),
None => Err(Error::new(ErrorKind::UndefinedError, concat!("missing argument")))
}
}
}
impl ArgType for Option<$ty> {
fn from_value(value: Option<Value>) -> Result<Self, Error> {
match value {
Some(value) => {
if value.is_undefined() || value.is_none() {
Ok(None)
} else {
TryFrom::try_from(value).map(Some)
}
}
None => Ok(None),
}
}
}
}
}
macro_rules! primitive_int_try_from {
($ty:ident) => {
primitive_try_from!($ty, {
ValueRepr::Bool(val) => val as usize,
ValueRepr::I64(val) => val,
ValueRepr::U64(val) => val,
// for the intention here see Key::from_borrowed_value
ValueRepr::F64(val) if (val as i64 as f64 == val) => val as i64,
ValueRepr::I128(ref val) => **val,
ValueRepr::U128(ref val) => **val,
});
}
}
primitive_int_try_from!(u8);
primitive_int_try_from!(u16);
primitive_int_try_from!(u32);
primitive_int_try_from!(u64);
primitive_int_try_from!(u128);
primitive_int_try_from!(i8);
primitive_int_try_from!(i16);
primitive_int_try_from!(i32);
primitive_int_try_from!(i64);
primitive_int_try_from!(i128);
primitive_int_try_from!(usize);
primitive_try_from!(bool, {
ValueRepr::Bool(val) => val,
});
primitive_try_from!(f64, {
ValueRepr::F64(val) => val,
});
macro_rules! infallible_conversion {
($ty:ty) => {
impl ArgType for $ty {
fn from_value(value: Option<Value>) -> Result<Self, Error> {
match value {
Some(value) => Ok(value.clone().into()),
None => Err(Error::new(
ErrorKind::UndefinedError,
concat!("missing argument"),
)),
}
}
}
impl ArgType for Option<$ty> {
fn from_value(value: Option<Value>) -> Result<Self, Error> {
match value {
Some(value) => {
if value.is_undefined() || value.is_none() {
Ok(None)
} else {
Ok(Some(value.clone().into()))
}
}
None => Ok(None),
}
}
}
};
}
infallible_conversion!(String);
infallible_conversion!(Value);
impl From<Value> for String {
fn from(val: Value) -> Self {
val.to_string()
}
}
impl From<usize> for Value {
fn from(val: usize) -> Self {
Value::from(val as u64)
}
}
impl<T: ArgType> ArgType for Vec<T> {
fn from_value(value: Option<Value>) -> Result<Self, Error> {
match value {
None => Ok(Vec::new()),
Some(values) => {
let values = values.try_into_vec()?;
let mut rv = Vec::new();
for value in values {
rv.push(ArgType::from_value(Some(value))?);
}
Ok(rv)
}
}
}
}
#[allow(clippy::len_without_is_empty)]
impl Value {
/// The undefined value
pub const UNDEFINED: Value = Value(ValueRepr::Undefined);
/// Creates a value from something that can be serialized.
///
/// During serialization of the value, [`serializing_for_value`] will return
/// `true` which makes it possible to customize serialization for MiniJinja.
/// For more information see [`serializing_for_value`].
pub fn from_serializable<T: Serialize>(value: &T) -> Value {
with_internal_serialization(|| Serialize::serialize(value, ValueSerializer).unwrap())
}
/// Creates a value from a safe string.
pub fn from_safe_string(value: String) -> Value {
ValueRepr::SafeString(RcType::new(value)).into()
}
/// Creates a value from a reference counted dynamic object.
pub(crate) fn from_rc_object<T: Object + 'static>(value: RcType<T>) -> Value {
ValueRepr::Dynamic(value as RcType<dyn Object>).into()
}
/// Creates a value from a dynamic object.
pub fn from_object<T: Object + 'static>(value: T) -> Value {
Value::from_rc_object(RcType::new(value))
}
/// Returns some reference to the boxed object if it is of type `T`, or None if it isn’t.
///
/// This is basically the "reverse" of [`from_object`](Self::from_object).
///
/// # Example
///
/// ```rust
/// # use minijinja::value::{Value, Object};
/// use std::fmt;
///
/// #[derive(Debug)]
/// struct Thing {
/// id: usize,
/// }
///
/// impl fmt::Display for Thing {
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// fmt::Debug::fmt(self, f)
/// }
/// }
///
/// impl Object for Thing {}
///
/// let x_value = Value::from_object(Thing { id: 42 });
/// let thing = x_value.downcast_object_ref::<Thing>().unwrap();
/// assert_eq!(thing.id, 42);
/// ```
pub fn downcast_object_ref<T: Object>(&self) -> Option<&T> {
if let ValueRepr::Dynamic(ref obj) = self.0 {
if (**obj).type_id() == TypeId::of::<T>() {
unsafe {
// newer versions of Rust have RcType::as_ptr but we support
// rust versions down to 1.41.0 so we need to use a workaround here.
let count = RcType::strong_count(obj);
let clone = obj.clone();
let raw: *const (dyn Object) = RcType::into_raw(clone);
let rv = (raw as *const u8 as *const T).as_ref();
RcType::from_raw(raw);
debug_assert_eq!(count, RcType::strong_count(obj));
return rv;
}
}
}
None
}
/// Returns the value kind.
pub fn kind(&self) -> ValueKind {
match self.0 {
ValueRepr::Undefined => ValueKind::Undefined,
ValueRepr::Bool(_) => ValueKind::Bool,
ValueRepr::U64(_) | ValueRepr::I64(_) | ValueRepr::F64(_) => ValueKind::Number,
ValueRepr::Char(_) => ValueKind::Char,
ValueRepr::None => ValueKind::None,
ValueRepr::I128(_) => ValueKind::Number,
ValueRepr::String(_) | ValueRepr::SafeString(_) => ValueKind::String,
ValueRepr::Bytes(_) => ValueKind::Bytes,
ValueRepr::U128(_) => ValueKind::Number,
ValueRepr::Seq(_) => ValueKind::Seq,
ValueRepr::Map(_) | ValueRepr::Dynamic(_) => ValueKind::Map,
}
}
/// If the value is a string, return it.
pub fn as_str(&self) -> Option<&str> {
match &self.0 {
ValueRepr::String(ref s) => Some(s.as_str()),
ValueRepr::SafeString(ref s) => Some(s.as_str()),
_ => None,
}
}
/// Is this value true?
pub fn is_true(&self) -> bool {
match self.0 {
ValueRepr::Bool(val) => val,
ValueRepr::U64(x) => x != 0,
ValueRepr::U128(ref x) => **x != 0,
ValueRepr::I64(x) => x != 0,
ValueRepr::I128(ref x) => **x != 0,
ValueRepr::F64(x) => x != 0.0,
ValueRepr::Char(x) => x != '\x00',
ValueRepr::String(ref x) => !x.is_empty(),
ValueRepr::SafeString(ref x) => !x.is_empty(),
ValueRepr::Bytes(ref x) => !x.is_empty(),
ValueRepr::None | ValueRepr::Undefined => false,
ValueRepr::Seq(ref x) => !x.is_empty(),
ValueRepr::Map(ref x) => !x.is_empty(),
ValueRepr::Dynamic(_) => true,
}
}
/// Returns `true` if this value is safe.
pub fn is_safe(&self) -> bool {
matches!(&self.0, ValueRepr::SafeString(_))
}
/// Returns `true` if this value is undefined.
pub fn is_undefined(&self) -> bool {
matches!(&self.0, ValueRepr::Undefined)
}
/// Returns `true` if this value is none.
pub fn is_none(&self) -> bool {
matches!(&self.0, ValueRepr::None)
}
/// Returns the length of the contained value.
pub fn len(&self) -> Option<usize> {
match self.0 {
ValueRepr::String(ref s) | ValueRepr::SafeString(ref s) => Some(s.chars().count()),
ValueRepr::Map(ref items) => Some(items.len()),
ValueRepr::Seq(ref items) => Some(items.len()),
ValueRepr::Dynamic(ref dy) => Some(dy.attributes().len()),
_ => None,
}
}
/// Looks up an attribute by attribute name.
pub fn get_attr(&self, key: &str) -> Result<Value, Error> {
let value = match self.0 {
ValueRepr::Map(ref items) => {
let lookup_key = Key::Str(key);
items.get(&lookup_key).cloned()
}
ValueRepr::Dynamic(ref dy) => dy.get_attr(key),
ValueRepr::Undefined => {
return Err(Error::from(ErrorKind::UndefinedError));
}
_ => None,
};
Ok(value.unwrap_or(Value::UNDEFINED))
}
/// Looks up an item (or attribute) by key.
///
/// This is similar to [`get_attr`](Value::get_attr) but instead of using
/// a string key this can be any key. For instance this can be used to
/// index into sequences.
pub fn get_item(&self, key: &Value) -> Result<Value, Error> {
if let ValueRepr::Undefined = self.0 {
Err(Error::from(ErrorKind::UndefinedError))