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
use std::ops::{Add, Sub, Mul, Div, Rem};
use std::collections::HashMap;

use lazy_static::lazy_static;

use crate::arg::Arg;

pub type Func = fn(Vec<Arg>) -> Arg;

/// The Operator type, mainly contains a function pointer.
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Op {
    pub name: String,
    pub func: Func,
}

// TODO:
// 1. static hashmap -> built-in ops [done]
// 2. custom ops register to whom? maybe just use a global static mut hashmap
// 3. add more ops [ing]
// 4. use macro to init register ops [done]
// 5. func return Result, error handling? or not.

impl Op {
    /// Constructs a new Operator.
    pub fn new(name: &str, func: Func) -> Op {
        Op {
            name: name.to_owned(),
            func: func,
        }
    }

    /// Get an Operator by name, returns an Option, `None` if not exists.
    pub fn get(name: &str) -> Option<&Op> {
        OPS.get(name)
    }
}

/// Register builtin OPs.
///
/// # Examples
///
/// ```
/// register_builtin!(
///     "var" => var,
///     "=" => eq,
///     "<" => lt,
/// )
/// ```
macro_rules! register_builtin {
    ( $($alias:tt => $func:tt),* $(,)? ) => {
        lazy_static! {
            /// All built-in OPs registered to OPS HashMap.
            static ref OPS: HashMap<&'static str, Op> = {
                let mut map = HashMap::new();
                $(
                map.insert($alias, Op::new($alias, $func as Func));
                map.insert(stringify!($func), Op::new(stringify!($func), $func as Func));
                )*
                map
            };
        }
    };
}

register_builtin!(
    "var" => var,

    // logic operator
    "=" => eq,
    "<" => lt,
    "<=" => le,
    "!=" => ne,
    ">=" => ge,
    ">=" => ge,
    ">" => gt,
    "&" => and,
    "&&" => and,
    "all" => and,
    "|" => or,
    "||" => or,
    "any" => or,
    "!" => not,

    // arithmetic operator
    "+" => add,
    "sum" => add,
    "-" => sub,
    "minus" => sub,
    "neg" => neg,
    "*" => mul,
    "/" => div,
    "%" => rem,
    "mod" => rem,
    "abs" => abs,

    // collection operator
    "in" => r#in,
    "startswith" => startswith,
    "endswith" => endswith,
    "split" => split,
    "join" => join,

    // string operator
    "lower" => lower,
    "upper" => upper,
    "match" => r#match,
    "regex" => regex,

    // casting operator
    "num" => num,
    "string" => string,
);

/// just a placeholder, will not be called
pub fn var(args: Vec<Arg>) -> Arg {
    args[0].clone()
}

pub fn eq(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] == w[1]))
}

/// `lt` is equivalent to the `<` sign, args[0] and args[1] must be the same type.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["lt", 1, 2].unwrap().matches(&json!({})).unwrap());
/// assert!(rule!["lt", "10", "2"].unwrap().matches(&json!({})).unwrap());
/// assert!(rule!["lt", 1.1, 1.23].unwrap().matches(&json!({})).unwrap());
/// assert_eq!(rule!["lt", 1.23, 1.1].unwrap().matches(&json!({})).unwrap(), false);
/// assert_eq!(rule!["lt", 2, 1].unwrap().matches(&json!({})).unwrap(), false);
/// ```
pub fn lt(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] < w[1]))
}

pub fn le(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] <= w[1]))
}

pub fn ne(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] != w[1]))
}

pub fn ge(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] >= w[1]))
}

pub fn gt(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.windows(2).all(|w| w[0] > w[1]))
}

pub fn and(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.iter().all(|v| v.into()))
}

pub fn or(args: Vec<Arg>) -> Arg {
    Arg::Bool(args.iter().any(|v| v.into()))
}

pub fn not(args: Vec<Arg>) -> Arg {
    let b: bool = args.get(0).unwrap_or(&Arg::Null).into();
    Arg::Bool(!b)
}

pub fn add(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    it.next().map(|first| it.fold(first, Add::add)).unwrap_or(Arg::Null)
}

pub fn sub(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    it.next().map(|first| it.fold(first, Sub::sub)).unwrap_or(Arg::Null)
}

pub fn neg(args: Vec<Arg>) -> Arg {
    -args.get(0).unwrap_or(&Arg::Null)
}

pub fn mul(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    it.next().map(|first| it.fold(first, Mul::mul)).unwrap_or(Arg::Null)
}

pub fn div(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    it.next().map(|first| it.fold(first, Div::div)).unwrap_or(Arg::Null)
}

/// The remainder operator %.
/// Aliases: %, rem, mod
pub fn rem(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    it.next().map(|first| it.fold(first, Rem::rem)).unwrap_or(Arg::Null)
}

/// Computes the absolute value of arg[0].
pub fn abs(args: Vec<Arg>) -> Arg {
    let int: i64 = args.get(0).unwrap_or(&Arg::Null).into();
    Arg::Int(int.abs())
}

/// Return true if args[0] in args[1..].
/// e.g. rule json string: ["in", 1, 1, 2, 3]
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["in", 1, 1, 2, 3].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn r#in(args: Vec<Arg>) -> Arg {
    Arg::Bool(args[1..].contains(&args[0]))
}

/// Return true if args[0] starts with args[1]
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["startswith", "hello", "he"].unwrap().matches(&json!({})).unwrap());
/// assert!(rule!["startswith", "arr", "foo", "bar"].unwrap().matches(&json!({"arr": ["foo", "bar", "baz"]})).unwrap());
/// ```
pub fn startswith(args: Vec<Arg>) -> Arg {
    let ret = match &args[0] {
        Arg::String(s) => Arg::Bool((&s).starts_with(&args[1].to_string())),
        Arg::Array(a) => Arg::Bool(a.starts_with(&args[1..])),
        _ => Arg::Bool(false),
    };
    ret
}

/// Return true if args[0] ends with args[1]
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["endswith", "hello", "lo"].unwrap().matches(&json!({})).unwrap());
/// assert!(rule!["endswith", "arr", "bar", "baz"].unwrap().matches(&json!({"arr": ["foo", "bar", "baz"]})).unwrap());
/// ```
pub fn endswith(args: Vec<Arg>) -> Arg {
    let ret = match &args[0] {
        Arg::String(s) => Arg::Bool((&s).ends_with(&args[1].to_string())),
        Arg::Array(a) => Arg::Bool(a.ends_with(&args[1..])),
        _ => Arg::Bool(false),
    };
    ret
}

/// Convert upper case letters to lower case.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["=", ["lower", "Hi"], "hi"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn lower(args: Vec<Arg>) -> Arg {
    Arg::String(String::from(&args[0]).to_lowercase())
}

/// Convert lower case letters to upper case.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["=", ["upper", "Hi"], "HI"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn upper(args: Vec<Arg>) -> Arg {
    Arg::String(String::from(&args[0]).to_uppercase())
}

/// Split strings using a seperator.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["startswith", ["split", "apple,pear", ","], "apple"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn split(args: Vec<Arg>) -> Arg {
    let s = &String::from(&args[0]);
    let sep = &String::from(&args[1]);
    Arg::Array(s.split(sep).map(|x| Arg::String(x.to_owned())).collect())
}

/// Concatenate strings with a seperator.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["=", ["join", " ", "hello", "world"], "hello world"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn join(args: Vec<Arg>) -> Arg {
    let mut it = args.into_iter();
    let sep = &String::from(&it.nth(0).unwrap_or(Arg::String("".to_owned())));
    Arg::String(it.map(|x| String::from(&x)).collect::<Vec<String>>().join(sep))
}

/// Match string using an Unix shell style pattern.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["match", "hello", "he*"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn r#match(args: Vec<Arg>) -> Arg {
    match glob::Pattern::new(&String::from(&args[1])) {
        Ok(patt) => {
            Arg::Bool(patt.matches(&String::from(&args[0])))
        },
        Err(_) => Arg::Bool(false),
    }
}

/// Match strings using regular expressions.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["regex", "hello", "^he[l-o]*$"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn regex(args: Vec<Arg>) -> Arg {
    match regex::Regex::new(&String::from(&args[1])) {
        Ok(re) => {
            Arg::Bool(re.is_match(&String::from(&args[0])))
        },
        Err(_) => Arg::Bool(false),
    }
}

/// Convert a string into a number.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["=", ["num", "100"], 100].unwrap().matches(&json!({})).unwrap());
/// assert!(rule!["=", ["num", "1.23"], 1.23].unwrap().matches(&json!({})).unwrap());
/// assert_eq!(rule!["=", "100", 100].unwrap().matches(&json!({})).unwrap(), false);
/// ```
pub fn num(args: Vec<Arg>) -> Arg {
    let a = args[0].clone();
    match a {
        Arg::Int(_) => a,
        Arg::Float(_) => a,
        Arg::String(v) => {
            match v.parse::<i64>() {
                Ok(i) => Arg::Int(i),
                Err(_) => match v.parse::<f64>() {
                    Ok(f) => Arg::Float(f),
                    Err(_) => Arg::Int(0i64),
                }
            }
        },
        _ => Arg::Int(Into::<i64>::into(a)),
    }
}

/// Convert a number into a string.
///
/// ```
/// use ::rule::{rule, json};
/// assert!(rule!["=", ["string", 100], "100"].unwrap().matches(&json!({})).unwrap());
/// ```
pub fn string(args: Vec<Arg>) -> Arg {
    Arg::String(String::from(&args[0]))
}

// TODO: add more OPs
//
//    ('contains', None),
//    ('onlycontains/allin', None),
//    uniq
//    bool/notempty
//    empty