hypen-engine 0.4.91

A Rust implementation of the Hypen engine
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
//! Expression evaluation using exprimo
//!
//! Supports JavaScript-like expressions in bindings:
//! - `@{state.selected ? '#FFA7E1' : '#374151'}`
//! - `@{item.count > 10 ? 'many' : 'few'}`
//! - `@{state.user.name + ' (' + state.user.role + ')'}`

use exprimo::Evaluator;
use serde_json::Value;
use std::collections::{HashMap, HashSet};

use super::{Binding, BindingSource};
use crate::error::EngineError;

/// Evaluate an expression string with the given context
///
/// The context should contain flattened variables like:
/// - `state` -> the full state object
/// - `item` -> the current item (in list iteration)
///
/// # Example
/// ```
/// use serde_json::json;
/// use std::collections::HashMap;
/// use hypen_engine::reactive::evaluate_expression;
///
/// let mut context = HashMap::new();
/// context.insert("selected".to_string(), json!(true));
///
/// let result = evaluate_expression("selected ? 'yes' : 'no'", &context);
/// assert_eq!(result, Ok(json!("yes")));
/// ```
pub fn evaluate_expression(
    expr: &str,
    context: &HashMap<String, Value>,
) -> Result<Value, EngineError> {
    let evaluator = Evaluator::new(context.clone(), HashMap::new());
    evaluator
        .evaluate(expr)
        .map_err(|e| EngineError::ExpressionError(e.to_string()))
}

/// Build a context for expression evaluation from state, optional item, and data sources.
///
/// Flattens `state`, `item`, and data source objects so that expressions can access:
/// - `state.user.name` via path traversal
/// - `item.selected` via path traversal
/// - `spacetime.messages` via data source path traversal
pub fn build_expression_context(
    state: &Value,
    item: Option<&Value>,
    data_sources: Option<&indexmap::IndexMap<String, Value>>,
) -> HashMap<String, Value> {
    let mut context = HashMap::new();

    // Add the full state object
    context.insert("state".to_string(), state.clone());

    // Add the full item object if present
    if let Some(item_value) = item {
        context.insert("item".to_string(), item_value.clone());
    }

    // Add data source states as top-level context entries
    if let Some(ds_map) = data_sources {
        for (provider, ds_state) in ds_map {
            context.insert(provider.clone(), ds_state.clone());
        }
    }

    context
}

/// Extract all state, item, and data source bindings from an expression string
///
/// This scans the expression for `state.xxx`, `item.xxx`, and `provider.xxx`
/// patterns and returns Binding objects for dependency tracking. Any
/// `identifier.path` that isn't `state.` or `item.` is treated as a potential
/// data source binding (validated at the dependency graph level).
///
/// # Example
/// ```
/// use hypen_engine::reactive::extract_bindings_from_expression;
///
/// let bindings = extract_bindings_from_expression("state.selected ? '#FFA7E1' : '#374151'");
/// assert_eq!(bindings.len(), 1);
/// assert_eq!(bindings[0].full_path(), "selected");
/// ```
pub fn extract_bindings_from_expression(expr: &str) -> Vec<Binding> {
    let mut bindings = Vec::new();
    let mut seen_paths: HashSet<String> = HashSet::new();

    // Find all state.xxx and item.xxx patterns
    for prefix in &["state.", "item."] {
        let source = if *prefix == "state." {
            BindingSource::State
        } else {
            BindingSource::Item
        };

        let mut search_pos = 0;
        while let Some(start) = expr[search_pos..].find(prefix) {
            let abs_start = search_pos + start;

            // Check that this isn't in the middle of another identifier
            // (e.g., "mystate.x" should not match)
            if abs_start > 0 {
                let prev_char = expr.chars().nth(abs_start - 1).unwrap_or(' ');
                if prev_char.is_ascii_alphanumeric() || prev_char == '_' {
                    search_pos = abs_start + prefix.len();
                    continue;
                }
            }

            // Extract the path after the prefix
            let path_start = abs_start + prefix.len();
            let mut path_end = path_start;

            // Consume valid path characters (alphanumeric, underscore, and dots)
            let chars: Vec<char> = expr.chars().collect();
            while path_end < chars.len() {
                let c = chars[path_end];
                if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
                    path_end += 1;
                } else {
                    break;
                }
            }

            if path_end > path_start {
                let path_str: String = chars[path_start..path_end].iter().collect();
                // Remove trailing dots
                let path_str = path_str.trim_end_matches('.');

                if !path_str.is_empty() {
                    let full_path = format!("{}{}", prefix, path_str);
                    if !seen_paths.contains(&full_path) {
                        seen_paths.insert(full_path);
                        let path: Vec<String> =
                            path_str.split('.').map(|s| s.to_string()).collect();
                        bindings.push(Binding::new(source.clone(), path));
                    }
                }
            }

            search_pos = path_end.max(abs_start + prefix.len());
        }
    }

    // Also find potential data source references: identifier.path patterns that
    // aren't state.* or item.*. E.g., `spacetime.status == 'connected'`
    extract_data_source_bindings_from_expression(expr, &mut bindings, &mut seen_paths);

    bindings
}

/// Extract data source bindings (identifier.path patterns not starting with state/item)
fn extract_data_source_bindings_from_expression(
    expr: &str,
    bindings: &mut Vec<Binding>,
    seen_paths: &mut HashSet<String>,
) {
    let chars: Vec<char> = expr.chars().collect();
    let len = chars.len();
    let mut pos = 0;

    // Reserved identifiers that are NOT data source providers
    let reserved = ["state", "item", "true", "false", "null"];

    while pos < len {
        // Find the start of an identifier
        if !chars[pos].is_ascii_alphabetic() && chars[pos] != '_' {
            pos += 1;
            continue;
        }

        // Check not preceded by alphanumeric (part of another identifier)
        if pos > 0 && (chars[pos - 1].is_ascii_alphanumeric() || chars[pos - 1] == '_') {
            pos += 1;
            continue;
        }

        // Consume the identifier
        let ident_start = pos;
        while pos < len && (chars[pos].is_ascii_alphanumeric() || chars[pos] == '_') {
            pos += 1;
        }
        let ident: String = chars[ident_start..pos].iter().collect();

        // Must be followed by a dot and more path segments
        if pos >= len || chars[pos] != '.' {
            continue;
        }

        // Skip reserved words
        if reserved.contains(&ident.as_str()) {
            continue;
        }

        // Consume the dot and path segments
        let path_start = pos + 1; // skip the dot
        let mut path_end = path_start;
        while path_end < len
            && (chars[path_end].is_ascii_alphanumeric()
                || chars[path_end] == '_'
                || chars[path_end] == '.')
        {
            path_end += 1;
        }

        if path_end > path_start {
            let path_str: String = chars[path_start..path_end].iter().collect();
            let path_str = path_str.trim_end_matches('.');
            if !path_str.is_empty() {
                let full_path = format!("{}.{}", ident, path_str);
                if !seen_paths.contains(&full_path) {
                    seen_paths.insert(full_path);
                    let path: Vec<String> =
                        path_str.split('.').map(|s| s.to_string()).collect();
                    bindings.push(Binding::data_source(&ident, path));
                }
            }
        }

        pos = path_end;
    }
}

/// Build a reusable [`Evaluator`] from state, optional item, and data sources.
///
/// Use this when you need to evaluate multiple expressions against the same
/// state — `Evaluator::new` clones its context internally, so building once
/// and reusing avoids paying the clone for every expression.
pub fn build_evaluator(
    state: &Value,
    item: Option<&Value>,
    data_sources: Option<&indexmap::IndexMap<String, Value>>,
) -> Evaluator {
    let context = build_expression_context(state, item, data_sources);
    Evaluator::new(context, HashMap::new())
}

/// Evaluate a template string against a pre-built [`Evaluator`].
///
/// Substitutes every `@{...}` segment with the evaluator's result. Callers
/// that need a one-shot evaluation against fresh state should pair this
/// with [`build_evaluator`].
pub fn evaluate_template_string(
    template: &str,
    evaluator: &Evaluator,
) -> Result<String, EngineError> {
    let mut result = template.to_string();
    let mut pos = 0;

    while let Some(start) = result[pos..].find("@{") {
        let abs_start = pos + start;

        // Find matching closing brace, handling nested braces
        let mut depth = 1;
        let mut end_pos = abs_start + 2;
        let chars: Vec<char> = result.chars().collect();

        while end_pos < chars.len() && depth > 0 {
            match chars[end_pos] {
                '{' => depth += 1,
                '}' => depth -= 1,
                _ => {}
            }
            if depth > 0 {
                end_pos += 1;
            }
        }

        if depth != 0 {
            return Err(EngineError::ExpressionError(
                "Unclosed expression in template".to_string(),
            ));
        }

        // Extract the expression content
        let expr_content: String = chars[abs_start + 2..end_pos].iter().collect();

        // Evaluate the expression directly via the evaluator (no context clone)
        let value = evaluator
            .evaluate(&expr_content)
            .map_err(|e| EngineError::ExpressionError(e.to_string()))?;

        // Convert to string
        let replacement = match &value {
            Value::String(s) => s.clone(),
            Value::Number(n) => n.to_string(),
            Value::Bool(b) => b.to_string(),
            Value::Null => "null".to_string(),
            _ => serde_json::to_string(&value).unwrap_or_default(),
        };

        // Replace in result
        let pattern: String = chars[abs_start..=end_pos].iter().collect();
        result = result.replacen(&pattern, &replacement, 1);

        // Reset position to search from beginning (replacement might be shorter/longer)
        pos = 0;
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_simple_expression() {
        let mut context = HashMap::new();
        context.insert("x".to_string(), json!(5));
        context.insert("y".to_string(), json!(3));

        let result = evaluate_expression("x + y", &context).unwrap();
        // exprimo returns floats for arithmetic, so compare as f64
        assert_eq!(result.as_f64().unwrap(), 8.0);
    }

    #[test]
    fn test_ternary_expression() {
        let mut context = HashMap::new();
        context.insert("selected".to_string(), json!(true));

        let result = evaluate_expression("selected ? 'yes' : 'no'", &context).unwrap();
        assert_eq!(result, json!("yes"));
    }

    #[test]
    fn test_ternary_with_colors() {
        let mut context = HashMap::new();
        context.insert("selected".to_string(), json!(true));

        let result = evaluate_expression("selected ? '#FFA7E1' : '#374151'", &context).unwrap();
        assert_eq!(result, json!("#FFA7E1"));
    }

    #[test]
    fn test_comparison_expression() {
        let mut context = HashMap::new();
        context.insert("count".to_string(), json!(15));

        let result = evaluate_expression("count > 10", &context).unwrap();
        assert_eq!(result, json!(true));
    }

    #[test]
    fn test_state_object_access() {
        let context =
            build_expression_context(&json!({"user": {"name": "Alice", "age": 30}}), None, None);

        let result = evaluate_expression("state.user.name", &context).unwrap();
        assert_eq!(result, json!("Alice"));
    }

    #[test]
    fn test_item_object_access() {
        let context = build_expression_context(
            &json!({}),
            Some(&json!({"name": "Item 1", "selected": true})),
            None,
        );

        let result = evaluate_expression("item.name", &context).unwrap();
        assert_eq!(result, json!("Item 1"));
    }

    #[test]
    fn test_item_ternary() {
        let context =
            build_expression_context(&json!({}), Some(&json!({"selected": true})), None);

        let result =
            evaluate_expression("item.selected ? '#FFA7E1' : '#374151'", &context).unwrap();
        assert_eq!(result, json!("#FFA7E1"));
    }

    #[test]
    fn test_template_string_simple() {
        let state = json!({"user": {"name": "Alice"}});
        let evaluator = build_evaluator(&state, None, None);
        let result = evaluate_template_string("Hello @{state.user.name}!", &evaluator).unwrap();
        assert_eq!(result, "Hello Alice!");
    }

    #[test]
    fn test_template_string_with_expression() {
        let state = json!({"selected": true});
        let evaluator = build_evaluator(&state, None, None);
        let result = evaluate_template_string(
            "Color: @{state.selected ? '#FFA7E1' : '#374151'}",
            &evaluator,
        )
        .unwrap();
        assert_eq!(result, "Color: #FFA7E1");
    }

    #[test]
    fn test_template_string_multiple_expressions() {
        let state = json!({"name": "Alice", "count": 5});
        let evaluator = build_evaluator(&state, None, None);
        let result =
            evaluate_template_string("@{state.name} has @{state.count} items", &evaluator)
                .unwrap();
        assert_eq!(result, "Alice has 5 items");
    }

    #[test]
    fn test_template_with_item() {
        let state = json!({});
        let item = json!({"name": "Product", "price": 99});
        let evaluator = build_evaluator(&state, Some(&item), None);
        let result = evaluate_template_string("@{item.name}: $@{item.price}", &evaluator).unwrap();
        assert_eq!(result, "Product: $99");
    }

    #[test]
    fn test_string_concatenation() {
        let mut context = HashMap::new();
        context.insert("first".to_string(), json!("Hello"));
        context.insert("second".to_string(), json!("World"));

        let result = evaluate_expression("first + ' ' + second", &context).unwrap();
        assert_eq!(result, json!("Hello World"));
    }

    #[test]
    fn test_logical_and() {
        let mut context = HashMap::new();
        context.insert("a".to_string(), json!(true));
        context.insert("b".to_string(), json!(false));

        let result = evaluate_expression("a && b", &context).unwrap();
        assert_eq!(result, json!(false));
    }

    #[test]
    fn test_logical_or() {
        let mut context = HashMap::new();
        context.insert("a".to_string(), json!(false));
        context.insert("b".to_string(), json!(true));

        let result = evaluate_expression("a || b", &context).unwrap();
        assert_eq!(result, json!(true));
    }

    #[test]
    fn test_complex_expression() {
        let context = build_expression_context(
            &json!({
                "user": {
                    "premium": true,
                    "age": 25
                }
            }),
            None,
            None,
        );

        let result = evaluate_expression(
            "state.user.premium && state.user.age >= 18 ? 'VIP Adult' : 'Standard'",
            &context,
        )
        .unwrap();
        assert_eq!(result, json!("VIP Adult"));
    }
}