moduforge-rules-expression 0.5.0

moduforge 表达式规则
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
use ahash::HashMap;
use rust_decimal::prelude::Zero;
use rust_decimal::Decimal;
use serde_json::Value;
use std::any::Any;
use std::cell::RefCell;
use std::collections::hash_map::Entry;
use std::fmt::{Debug, Display, Formatter};
use std::ops::Deref;
use std::rc::Rc;

mod conv;
mod de;
mod ser;
mod types;

pub use de::VariableDeserializer;
pub use types::VariableType;

pub(crate) type RcCell<T> = Rc<RefCell<T>>;

pub enum Variable {
    Null,
    Bool(bool),
    Number(Decimal),
    String(Rc<str>),
    Array(RcCell<Vec<Variable>>),
    Object(RcCell<HashMap<Rc<str>, Variable>>),
    Dynamic(Rc<dyn DynamicVariable>),
}

pub trait DynamicVariable: Display {
    fn type_name(&self) -> &'static str;

    fn as_any(&self) -> &dyn Any;

    fn to_value(&self) -> Value;
}

impl Variable {
    pub fn from_array(arr: Vec<Self>) -> Self {
        Self::Array(Rc::new(RefCell::new(arr)))
    }

    pub fn from_object(obj: HashMap<Rc<str>, Self>) -> Self {
        Self::Object(Rc::new(RefCell::new(obj)))
    }

    pub fn empty_object() -> Self {
        Variable::Object(Default::default())
    }

    pub fn empty_array() -> Self {
        Variable::Array(Default::default())
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Variable::String(s) => Some(s.as_ref()),
            _ => None,
        }
    }

    pub fn as_rc_str(&self) -> Option<Rc<str>> {
        match self {
            Variable::String(s) => Some(s.clone()),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<RcCell<Vec<Variable>>> {
        match self {
            Variable::Array(arr) => Some(arr.clone()),
            _ => None,
        }
    }

    pub fn is_array(&self) -> bool {
        match self {
            Variable::Array(_) => true,
            _ => false,
        }
    }

    pub fn as_object(&self) -> Option<RcCell<HashMap<Rc<str>, Variable>>> {
        match self {
            Variable::Object(obj) => Some(obj.clone()),
            _ => None,
        }
    }

    pub fn is_object(&self) -> bool {
        match self {
            Variable::Object(_) => true,
            _ => false,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Variable::Bool(b) => Some(*b),
            _ => None,
        }
    }

    pub fn as_number(&self) -> Option<Decimal> {
        match self {
            Variable::Number(n) => Some(*n),
            _ => None,
        }
    }

    pub fn type_name(&self) -> &'static str {
        match self {
            Variable::Null => "null",
            Variable::Bool(_) => "bool",
            Variable::Number(_) => "number",
            Variable::String(_) => "string",
            Variable::Array(_) => "array",
            Variable::Object(_) => "object",
            Variable::Dynamic(d) => d.type_name(),
        }
    }

    pub fn dynamic<T: DynamicVariable + 'static>(&self) -> Option<&T> {
        match self {
            Variable::Dynamic(d) => d.as_any().downcast_ref::<T>(),
            _ => None,
        }
    }

    pub fn to_value(&self) -> Value {
        Value::from(self.shallow_clone())
    }

    pub fn dot(
        &self,
        key: &str,
    ) -> Option<Variable> {
        key.split('.').try_fold(self.shallow_clone(), |var, part| match var {
            Variable::Object(obj) => {
                let reference = obj.borrow();
                reference.get(part).map(|v| v.shallow_clone())
            },
            _ => None,
        })
    }

    fn dot_head(
        &self,
        key: &str,
    ) -> Option<Variable> {
        let mut parts = Vec::from_iter(key.split('.'));
        parts.pop();

        parts.iter().try_fold(self.shallow_clone(), |var, part| match var {
            Variable::Object(obj) => {
                let mut obj_ref = obj.borrow_mut();
                Some(match obj_ref.entry(Rc::from(*part)) {
                    Entry::Occupied(occ) => occ.get().shallow_clone(),
                    Entry::Vacant(vac) => {
                        vac.insert(Self::empty_object()).shallow_clone()
                    },
                })
            },
            _ => None,
        })
    }

    fn dot_head_detach(
        &self,
        key: &str,
    ) -> (Variable, Option<Variable>) {
        let mut parts = Vec::from_iter(key.split('.'));
        parts.pop();

        let cloned_self = self.depth_clone(1);
        let head =
            parts.iter().try_fold(cloned_self.shallow_clone(), |var, part| {
                match var {
                    Variable::Object(obj) => {
                        let mut obj_ref = obj.borrow_mut();
                        Some(match obj_ref.entry(Rc::from(*part)) {
                            Entry::Occupied(mut occ) => {
                                let var = occ.get();
                                let new_obj = match var {
                                    Variable::Object(_) => var.depth_clone(1),
                                    _ => Variable::empty_object(),
                                };

                                occ.insert(new_obj.shallow_clone());
                                new_obj
                            },
                            Entry::Vacant(vac) => {
                                vac.insert(Self::empty_object()).shallow_clone()
                            },
                        })
                    },
                    _ => None,
                }
            });

        (cloned_self, head)
    }

    pub fn dot_remove(
        &self,
        key: &str,
    ) -> Option<Variable> {
        let last_part = key.split('.').last()?;
        let head = self.dot_head(key)?;
        let Variable::Object(object_ref) = head else {
            return None;
        };

        let mut object = object_ref.borrow_mut();
        object.remove(last_part)
    }

    pub fn dot_insert(
        &self,
        key: &str,
        variable: Variable,
    ) -> Option<Variable> {
        let last_part = key.split('.').last()?;
        let head = self.dot_head(key)?;
        let Variable::Object(object_ref) = head else {
            return None;
        };

        let mut object = object_ref.borrow_mut();
        object.insert(Rc::from(last_part), variable)
    }

    pub fn dot_insert_detached(
        &self,
        key: &str,
        variable: Variable,
    ) -> Option<Variable> {
        let last_part = key.split('.').last()?;
        let (new_var, head_opt) = self.dot_head_detach(key);
        let head = head_opt?;
        let Variable::Object(object_ref) = head else {
            return None;
        };

        let mut object = object_ref.borrow_mut();
        object.insert(Rc::from(last_part), variable);
        Some(new_var)
    }

    pub fn merge(
        &mut self,
        patch: &Variable,
    ) -> Variable {
        let _ = merge_variables(self, patch, true, MergeStrategy::InPlace);

        self.shallow_clone()
    }

    pub fn merge_clone(
        &mut self,
        patch: &Variable,
    ) -> Variable {
        let mut new_self = self.shallow_clone();

        let _ = merge_variables(
            &mut new_self,
            patch,
            true,
            MergeStrategy::CloneOnWrite,
        );
        new_self
    }

    pub fn shallow_clone(&self) -> Self {
        match self {
            Variable::Null => Variable::Null,
            Variable::Bool(b) => Variable::Bool(*b),
            Variable::Number(n) => Variable::Number(*n),
            Variable::String(s) => Variable::String(s.clone()),
            Variable::Array(a) => Variable::Array(a.clone()),
            Variable::Object(o) => Variable::Object(o.clone()),
            Variable::Dynamic(d) => Variable::Dynamic(d.clone()),
        }
    }

    pub fn deep_clone(&self) -> Self {
        match self {
            Variable::Array(a) => {
                let arr = a.borrow();
                Variable::from_array(
                    arr.iter().map(|v| v.deep_clone()).collect(),
                )
            },
            Variable::Object(o) => {
                let obj = o.borrow();
                Variable::from_object(
                    obj.iter()
                        .map(|(k, v)| (k.clone(), v.deep_clone()))
                        .collect(),
                )
            },
            _ => self.shallow_clone(),
        }
    }

    pub fn depth_clone(
        &self,
        depth: usize,
    ) -> Self {
        match depth.is_zero() {
            true => self.shallow_clone(),
            false => match self {
                Variable::Array(a) => {
                    let arr = a.borrow();
                    Variable::from_array(
                        arr.iter().map(|v| v.depth_clone(depth - 1)).collect(),
                    )
                },
                Variable::Object(o) => {
                    let obj = o.borrow();
                    Variable::from_object(
                        obj.iter()
                            .map(|(k, v)| (k.clone(), v.depth_clone(depth - 1)))
                            .collect(),
                    )
                },
                _ => self.shallow_clone(),
            },
        }
    }
}

impl Clone for Variable {
    fn clone(&self) -> Self {
        self.shallow_clone()
    }
}

#[derive(Copy, Clone)]
enum MergeStrategy {
    InPlace,
    CloneOnWrite,
}

fn merge_variables(
    doc: &mut Variable,
    patch: &Variable,
    top_level: bool,
    strategy: MergeStrategy,
) -> bool {
    if patch.is_array() && top_level {
        *doc = patch.shallow_clone();
        return true;
    }

    if !patch.is_object() && top_level {
        return false;
    }

    if doc.is_object() && patch.is_object() {
        let doc_ref = doc.as_object().unwrap();
        let patch_ref = patch.as_object().unwrap();
        if Rc::ptr_eq(&doc_ref, &patch_ref) {
            return false;
        }

        let patch = patch_ref.borrow();
        match strategy {
            MergeStrategy::InPlace => {
                let mut map = doc_ref.borrow_mut();
                for (key, value) in patch.deref() {
                    if value == &Variable::Null {
                        map.remove(key);
                    } else {
                        let entry =
                            map.entry(key.clone()).or_insert(Variable::Null);
                        merge_variables(entry, value, false, strategy);
                    }
                }

                return true;
            },
            MergeStrategy::CloneOnWrite => {
                let mut changed = false;
                let mut new_map = None;

                for (key, value) in patch.deref() {
                    // Get or create the new map if we haven't yet
                    let map = if let Some(ref mut m) = new_map {
                        m
                    } else {
                        let m = doc_ref.borrow().clone();
                        new_map = Some(m);
                        new_map.as_mut().unwrap()
                    };

                    if value == &Variable::Null {
                        // Remove null values
                        if map.remove(key).is_some() {
                            changed = true;
                        }
                    } else {
                        // Handle nested merging
                        let entry =
                            map.entry(key.clone()).or_insert(Variable::Null);
                        if merge_variables(entry, value, false, strategy) {
                            changed = true;
                        }
                    }
                }

                // Only update doc if changes were made
                if changed {
                    if let Some(new_map) = new_map {
                        *doc = Variable::Object(Rc::new(RefCell::new(new_map)));
                    }
                    return true;
                }

                return false;
            },
        }
    } else {
        let new_value = patch.shallow_clone();
        if *doc != new_value {
            *doc = new_value;
            return true;
        }

        return false;
    }
}

impl Display for Variable {
    fn fmt(
        &self,
        f: &mut Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Variable::Null => write!(f, "null"),
            Variable::Bool(b) => match *b {
                true => write!(f, "true"),
                false => write!(f, "false"),
            },
            Variable::Number(n) => write!(f, "{n}"),
            Variable::String(s) => write!(f, "\"{s}\""),
            Variable::Array(arr) => {
                let arr = arr.borrow();
                let s = arr
                    .iter()
                    .map(|v| v.to_string())
                    .collect::<Vec<String>>()
                    .join(",");
                write!(f, "[{s}]")
            },
            Variable::Object(obj) => {
                let obj = obj.borrow();
                let s = obj
                    .iter()
                    .map(|(k, v)| format!("\"{k}\":{v}"))
                    .collect::<Vec<String>>()
                    .join(",");

                write!(f, "{{{s}}}")
            },
            Variable::Dynamic(d) => write!(f, "{d}"),
        }
    }
}

impl Debug for Variable {
    fn fmt(
        &self,
        f: &mut Formatter<'_>,
    ) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl PartialEq for Variable {
    fn eq(
        &self,
        other: &Self,
    ) -> bool {
        match (&self, &other) {
            (Variable::Null, Variable::Null) => true,
            (Variable::Bool(b1), Variable::Bool(b2)) => b1 == b2,
            (Variable::Number(n1), Variable::Number(n2)) => n1 == n2,
            (Variable::String(s1), Variable::String(s2)) => s1 == s2,
            (Variable::Array(a1), Variable::Array(a2)) => a1 == a2,
            (Variable::Object(obj1), Variable::Object(obj2)) => obj1 == obj2,
            (Variable::Dynamic(d1), Variable::Dynamic(d2)) => {
                Rc::ptr_eq(d1, d2)
            },
            _ => false,
        }
    }
}

impl Eq for Variable {}

#[cfg(test)]
mod tests {
    use crate::Variable;
    use rust_decimal_macros::dec;
    use serde_json::json;

    #[test]
    fn insert_detached() {
        let some_data: Variable =
            json!({ "customer": { "firstName": "John" }}).into();

        let a_a = some_data
            .dot_insert_detached("a.a", Variable::Number(dec!(1)))
            .unwrap();
        let a_b =
            a_a.dot_insert_detached("a.b", Variable::Number(dec!(2))).unwrap();
        let a_c =
            a_b.dot_insert_detached("a.c", Variable::Number(dec!(3))).unwrap();

        assert_eq!(a_a.dot("a"), Some(Variable::from(json!({ "a": 1 }))));
        assert_eq!(
            a_b.dot("a"),
            Some(Variable::from(json!({ "a": 1, "b": 2 })))
        );
        assert_eq!(
            a_c.dot("a"),
            Some(Variable::from(json!({ "a": 1, "b": 2, "c": 3 })))
        );
    }
}