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
use serde_json::Value;

use crate::ast::*;
use crate::context::Context;
use crate::engine::Engine;
use crate::error::*;

/// Item to evaluate
struct Item {
    /// Item position
    position: Identifier,
    /// Item expression (`$$eval` value)
    expression: String,
}

/// Creates an item to evaluate if applicable
///
/// `value` must be an object containing the `$$eval` keyword and value of this
/// keyword must be a `String`.
///
/// # Arguments
///
/// * `value` - A JSON value to create item from
/// * `position` - A JSON value position
/// * `keyword` - An evaluation keyword
fn item_to_eval(value: &Value, position: &Identifier, keyword: &str) -> Result<Option<Item>> {
    match value {
        Value::Object(ref object) => {
            if let Some(ref value) = object.get(keyword) {
                // Object with $$eval keyword, must be a string
                let expression = value.as_str().ok_or_else(|| {
                    Error::with_message("unable to evaluate")
                        .context("reason", "eval keyword value is not a string")
                        .context("value", value.to_string())
                        .context("position", format!("{:?}", position))
                })?;
                Ok(Some(Item {
                    position: position.clone(),
                    expression: expression.to_string(),
                }))
            } else {
                // Object, but not $$eval keyword
                Ok(None)
            }
        }
        _ => {
            // Not an object, nothing to evaluate
            Ok(None)
        }
    }
}

/// Creates list of items to evaluate
///
/// It traverses the whole JSON recuresively.
///
/// # Arguments
///
/// * `value` - A value to traverse
/// * `position` - Current value position
/// * `keyword` - An evaluation keyword
fn items_to_eval(value: &Value, position: &Identifier, keyword: &str) -> Result<Option<Vec<Item>>> {
    match value {
        Value::Null | Value::String(_) | Value::Number(_) | Value::Bool(_) => {
            // There's nothing to evaluate
            Ok(None)
        }
        Value::Array(ref array) => {
            // We have to check if this array contains objects to evaluate
            let mut result = vec![];

            for (idx, value) in array.iter().enumerate() {
                if let Some(items) = items_to_eval(value, &position.clone().index(idx as isize), keyword)? {
                    result.extend(items);
                }
            }

            if result.is_empty() {
                Ok(None)
            } else {
                Ok(Some(result))
            }
        }
        Value::Object(ref object) => match item_to_eval(value, &position, keyword)? {
            Some(item) => {
                // Object contains $$eval and value is a string
                Ok(Some(vec![item]))
            }
            None => {
                // Object does not contain $$eval, check object key/value pairs recursively
                let mut result = vec![];

                for (k, v) in object {
                    if let Some(items) = items_to_eval(v, &position.clone().name(k.to_string()), keyword)? {
                        result.extend(items);
                    }
                }

                if result.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(result))
                }
            }
        },
    }
}

/// Replaces value in a JSON
///
/// # Arguments
///
/// * `data` - A JSON
/// * `new_value` - New value to use
/// * `position` - A position of the new value
fn replace_value(data: Value, new_value: Value, position: &Identifier) -> Value {
    if position.values.is_empty() {
        // Empty position = root = whole JSON
        return new_value;
    }

    let mut data = data;
    let mut current = &mut data;
    for value in &position.values {
        match value {
            // .unwrap()'s are safe - position was constructed by us
            IdentifierValue::Name(ref name) => current = current.get_mut(name).unwrap(),
            IdentifierValue::Index(ref index) => current = current.get_mut(*index as usize).unwrap(),
            _ => unreachable!(),
        }
    }

    *current = new_value;
    data
}

// This is pretty naive, multi pass evaluation. It works in this way:
//
//   * evaluate all items, one by one,
//   * do not fail if it fails, just increase the counters
//   * nothing failed? return what we have, success
//   * at least one item failed to evaluate?
//     * no item succeeded? return an error
//   * try again with another pass
//
// It's good enough for now.
//
// We will see what kind of DSLs we will have and if we will need to create
// dependency tree, detect circular dependencies, analyze if we can evaluate
// before the actual evaluation, etc.
fn eval_with_items(data: Value, items: &[Item], engine: &Engine, context: &mut Context) -> Result<Value> {
    let mut fail_counter;
    let mut success_counter;
    let mut data = data;

    loop {
        fail_counter = 0;
        success_counter = 0;

        for item in items {
            match engine.eval(&item.expression, &item.position, &data, context) {
                Err(_) => fail_counter += 1,
                Ok(new_value) => {
                    data = replace_value(data, new_value, &item.position);
                    success_counter += 1;
                }
            };
        }

        if fail_counter == 0 {
            // Nothing failed, return what we have
            return Ok(data);
        }

        if fail_counter > 0 && success_counter == 0 {
            // Something failed, but not even one item was evaluated, another pass won't help, fail
            return Err(Error::with_message("unable to evaluate"));
        }

        // Something failed here, but also at least one item was evaluated. Try
        // another pass to check if we can evaluate more.
    }
}

#[deprecated(since = "0.0.16", note = "please use `evaluate` instead")]
pub fn eval(data: Value) -> Result<Value> {
    evaluate(data)
}

/// Evaluates the whole JSON
///
/// # Arguments
///
/// * `data` - A JSON to evaluate
///
/// # Examples
///
/// An object evaluation.
///
/// ```rust
/// use balena_temen::{evaluate, Value};
/// use serde_json::json;
///
/// let data = json!({
///   "$$eval": "1 + 2"
/// });
///
/// assert_eq!(evaluate(data).unwrap(), json!(3));
/// ```
///
/// Chained dependencies evaluation.
///
/// ```rust
/// use balena_temen::{evaluate, Value};
/// use serde_json::json;
///
/// let data = json!({
///     "ssid": "Zrzka 5G",
///     "id": {
///         "$$eval": "super.ssid | slugify"
///     },
///     "upperId": {
///         "$$eval": "super.id | upper"
///     }
/// });
///
/// let evaluated = json!({
///     "ssid": "Zrzka 5G",
///     "id": "zrzka-5g",
///     "upperId": "ZRZKA-5G"
/// });
///
/// assert_eq!(evaluate(data).unwrap(), evaluated);
/// ```
pub fn evaluate(data: Value) -> Result<Value> {
    let engine = Engine::default();
    let mut context = Context::default();

    if let Some(items) = items_to_eval(&data, &Identifier::default(), engine.eval_keyword())? {
        eval_with_items(data, &items, &engine, &mut context)
    } else {
        Ok(data)
    }
}

/// Evaluates the whole JSON with custom [`Engine`]
///
/// # Arguments
///
/// * `data` - A JSON to evaluate
///
/// # Examples
///
/// ```rust
/// use balena_temen::{Context, evaluate_with_engine, Engine, EngineBuilder, Value};
/// use serde_json::json;
///
/// let mut context = Context::default();
/// let engine: Engine = EngineBuilder::default()
///     .eval_keyword("evalMePlease")
///     .into();
///
/// let data = json!({
///   "evalMePlease": "1 + 2"
/// });
///
/// assert_eq!(evaluate_with_engine(data, &engine, &mut context).unwrap(), json!(3));
/// ```
///
/// Check the [`eval`] function for more examples.
///
/// [`eval`]: fn.eval.html
/// [`Engine`]: struct.Engine.html
pub fn evaluate_with_engine(data: Value, engine: &Engine, context: &mut Context) -> Result<Value> {
    if let Some(items) = items_to_eval(&data, &Identifier::default(), engine.eval_keyword())? {
        eval_with_items(data, &items, engine, context)
    } else {
        Ok(data)
    }
}

#[deprecated(since = "0.0.16", note = "please use `evaluate_with_engine` instead")]
pub fn eval_with_engine(data: Value, engine: &Engine, context: &mut Context) -> Result<Value> {
    evaluate_with_engine(data, engine, context)
}

#[cfg(target_arch = "wasm32")]
pub mod wasm {
    // https://github.com/rustwasm/console_error_panic_hook#readme
    pub use console_error_panic_hook::set_once as set_panic_hook;
    use wasm_bindgen::prelude::*;

    use super::evaluate;

    /// Evaluates the whole JSON
    #[wasm_bindgen(js_name = "evaluate")]
    pub fn js_evaluate(data: JsValue) -> Result<JsValue, JsValue> {
        // use console.log for nice errors from Rust-land
        console_error_panic_hook::set_once();

        let data = data.into_serde().map_err(|e| JsValue::from(format!("{:#?}", e)))?;

        let evaluated = evaluate(data).map_err(|e| JsValue::from(format!("{:#?}", e)))?;

        let result = JsValue::from_serde(&evaluated).map_err(|e| JsValue::from(format!("{:#?}", e)))?;

        Ok(result)
    }

    #[cfg(test)]
    mod tests {
        use serde_json::{json, Value};
        use wasm_bindgen::prelude::*;
        use wasm_bindgen_test::*;

        use super::js_evaluate;

        wasm_bindgen_test_configure!(run_in_browser);

        #[wasm_bindgen_test]
        fn run_in_browser() {
            let input = json!({
                "number": 3,
                "value": {
                    "$$eval": "super.number + 5"
                }
            });
            let js_input = JsValue::from_serde(&input).unwrap();
            let js_output: JsValue = js_evaluate(js_input).unwrap();
            let output: Value = js_output.into_serde().unwrap();

            let valid_output = json!({
                "number": 3,
                "value": 8
            });

            assert_eq!(output, valid_output);
        }
    }
}