fel-core 0.3.0

Formspec Expression Language — parser, evaluator, and dependency analysis
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
//! Static dependency extraction — field refs, context refs, and MIP dependencies.
//!
//! Walks the AST without evaluation to find field references,
//! context references, MIP dependencies, and structural flags.
//!
//! The `walk` helper and related functions recurse the AST to populate [`Dependencies`].
#![allow(clippy::missing_docs_in_private_items)]
use std::collections::HashSet;

use crate::ast::{Expr, PathDotJoin, PathSegment};

/// Dependencies extracted from a FEL expression.
#[derive(Debug, Clone, Default)]
pub struct Dependencies {
    /// Field paths referenced (e.g., `["firstName", "address.city"]`).
    pub fields: HashSet<String>,
    /// Context references (e.g., `["@current", "@index"]`).
    pub context_refs: HashSet<String>,
    /// Instance references from `@instance('name')`.
    pub instance_refs: HashSet<String>,
    /// MIP dependencies: fields used in valid/relevant/readonly/required.
    pub mip_deps: HashSet<String>,
    /// Whether bare `$` (self-reference) appears.
    pub has_self_ref: bool,
    /// Whether any `[*]` wildcard appears.
    pub has_wildcard: bool,
    /// Whether prev() or next() is called.
    pub uses_prev_next: bool,
}

/// Extract dependencies from an AST expression.
pub fn extract_dependencies(expr: &Expr) -> Dependencies {
    let mut deps = Dependencies::default();
    let mut let_vars: Vec<String> = Vec::new();
    walk(expr, &mut deps, &mut let_vars);
    deps
}

fn walk(expr: &Expr, deps: &mut Dependencies, let_vars: &mut Vec<String>) {
    match expr {
        Expr::FieldRef { name, path } => {
            match name {
                None => {
                    // Bare `$` is rebound inside countWhere / every / some and *Where predicates;
                    // only mark self-ref if not suppressed.
                    if !let_vars.contains(&"$".to_string()) {
                        deps.has_self_ref = true;
                    }
                }
                Some(n) => {
                    // Skip let-bound variables
                    if !let_vars.contains(n) {
                        let mut full_path = n.clone();
                        for seg in path {
                            if matches!(seg, PathSegment::Wildcard) {
                                deps.has_wildcard = true;
                            }
                            seg.append_to_path(&mut full_path, PathDotJoin::AlwaysPrefix);
                        }
                        deps.fields.insert(full_path);
                    }
                }
            }
        }

        Expr::VarRef { name, path } => {
            if !let_vars.contains(name) {
                let mut full_path = name.clone();
                for seg in path {
                    if matches!(seg, PathSegment::Wildcard) {
                        deps.has_wildcard = true;
                    }
                    seg.append_to_path(&mut full_path, PathDotJoin::AlwaysPrefix);
                }
                deps.fields.insert(full_path);
            }
        }

        Expr::ContextRef {
            name,
            called,
            arg,
            tail,
        } => {
            if name == "instance"
                && let Some(instance_name) = arg
            {
                deps.instance_refs.insert(instance_name.clone());
            }
            let mut ref_str = String::with_capacity(
                1 + name.len() + arg.as_ref().map(|a| 4 + a.len()).unwrap_or(0) + tail.len() * 2,
            );
            ref_str.push('@');
            ref_str.push_str(name);
            if *called {
                if let Some(a) = arg {
                    ref_str.push_str("('");
                    ref_str.push_str(a);
                    ref_str.push_str("')");
                } else {
                    ref_str.push_str("()");
                }
            }
            for t in tail {
                ref_str.push('.');
                ref_str.push_str(t);
            }
            deps.context_refs.insert(ref_str);
        }

        Expr::FunctionCall { name, args } => {
            match name.as_str() {
                "valid" | "relevant" | "readonly" | "required" => {
                    // MIP: extract field path from first arg
                    if let Some(first) = args.first() {
                        let path = extract_field_path_str(first);
                        if !path.is_empty() {
                            deps.mip_deps.insert(path);
                        }
                    }
                    // Still walk args for other deps
                    for arg in args {
                        walk(arg, deps, let_vars);
                    }
                }
                "prev" | "next" => {
                    deps.uses_prev_next = true;
                }
                "parent" => {
                    deps.uses_prev_next = true;
                }
                "instance" => {
                    if let Some(Expr::String(name)) = args.first() {
                        deps.instance_refs.insert(name.clone());
                    }
                    for arg in args {
                        walk(arg, deps, let_vars);
                    }
                }
                "countWhere" | "every" | "some" | "sumWhere" | "avgWhere" | "minWhere"
                | "maxWhere" | "moneySumWhere" => {
                    // First arg: normal walk
                    if let Some(first) = args.first() {
                        walk(first, deps, let_vars);
                    }
                    // Second arg: bare $ is rebound, so don't count it
                    // But still walk for other refs
                    if let Some(second) = args.get(1) {
                        let mut inner_vars = let_vars.clone();
                        inner_vars.push("$".to_string());
                        walk(second, deps, &mut inner_vars);
                    }
                }
                _ => {
                    for arg in args {
                        walk(arg, deps, let_vars);
                    }
                }
            }
        }

        Expr::LetBinding { name, value, body } => {
            walk(value, deps, let_vars);
            let_vars.push(name.clone());
            walk(body, deps, let_vars);
            let_vars.pop();
        }

        Expr::BinaryOp { left, right, .. } => {
            walk(left, deps, let_vars);
            walk(right, deps, let_vars);
        }

        Expr::UnaryOp { operand, .. } => {
            walk(operand, deps, let_vars);
        }

        Expr::Ternary {
            condition,
            then_branch,
            else_branch,
        }
        | Expr::IfThenElse {
            condition,
            then_branch,
            else_branch,
        } => {
            walk(condition, deps, let_vars);
            walk(then_branch, deps, let_vars);
            walk(else_branch, deps, let_vars);
        }

        Expr::Membership {
            value, container, ..
        } => {
            walk(value, deps, let_vars);
            walk(container, deps, let_vars);
        }

        Expr::NullCoalesce { left, right } => {
            walk(left, deps, let_vars);
            walk(right, deps, let_vars);
        }

        Expr::PostfixAccess { expr, path } => {
            if let Some(field_path) = extend_field_path(expr, path) {
                deps.fields.insert(field_path);
            } else {
                walk(expr, deps, let_vars);
            }
            for seg in path {
                if matches!(seg, PathSegment::Wildcard) {
                    deps.has_wildcard = true;
                }
            }
        }

        Expr::Array(elems) => {
            for elem in elems {
                walk(elem, deps, let_vars);
            }
        }

        Expr::Object(entries) => {
            for (_, val) in entries {
                walk(val, deps, let_vars);
            }
        }

        // Leaf nodes — no deps
        Expr::Null
        | Expr::Boolean(_)
        | Expr::Number(_)
        | Expr::String(_)
        | Expr::DateLiteral(_)
        | Expr::DateTimeLiteral(_) => {}
    }
}

fn extract_field_path_str(expr: &Expr) -> String {
    match expr {
        Expr::FieldRef { name, path } => {
            let mut result = name.as_deref().unwrap_or("").to_string();
            for seg in path {
                seg.append_to_path(&mut result, PathDotJoin::PrefixWhenNonempty);
            }
            result
        }
        Expr::VarRef { name, path } => {
            let mut result = name.clone();
            for seg in path {
                seg.append_to_path(&mut result, PathDotJoin::PrefixWhenNonempty);
            }
            result
        }
        _ => String::new(),
    }
}

fn extend_field_path(expr: &Expr, extra_path: &[PathSegment]) -> Option<String> {
    match expr {
        Expr::FieldRef { .. } | Expr::VarRef { .. } => {
            let mut path = extract_field_path_str(expr);
            for seg in extra_path {
                seg.append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
            }
            if path.is_empty() { None } else { Some(path) }
        }
        Expr::PostfixAccess { expr, path } => {
            let mut combined = path.clone();
            combined.extend_from_slice(extra_path);
            extend_field_path(expr, &combined)
        }
        _ => None,
    }
}

use crate::wire_style::JsonWireStyle;

/// Serialize [`Dependencies`] for WASM / JSON FFI (camelCase keys).
pub fn dependencies_to_json_value(deps: &Dependencies) -> serde_json::Value {
    dependencies_to_json_value_styled(deps, JsonWireStyle::JsCamel)
}

/// Serialize [`Dependencies`] with explicit host key style.
pub fn dependencies_to_json_value_styled(
    deps: &Dependencies,
    style: JsonWireStyle,
) -> serde_json::Value {
    match style {
        JsonWireStyle::JsCamel => serde_json::json!({
            "fields": deps.fields.iter().collect::<Vec<_>>(),
            "contextRefs": deps.context_refs.iter().collect::<Vec<_>>(),
            "instanceRefs": deps.instance_refs.iter().collect::<Vec<_>>(),
            "mipDeps": deps.mip_deps.iter().collect::<Vec<_>>(),
            "hasSelfRef": deps.has_self_ref,
            "hasWildcard": deps.has_wildcard,
            "usesPrevNext": deps.uses_prev_next,
        }),
        JsonWireStyle::PythonSnake => serde_json::json!({
            "fields": deps.fields.iter().collect::<Vec<_>>(),
            "context_refs": deps.context_refs.iter().collect::<Vec<_>>(),
            "instance_refs": deps.instance_refs.iter().collect::<Vec<_>>(),
            "mip_deps": deps.mip_deps.iter().collect::<Vec<_>>(),
            "has_self_ref": deps.has_self_ref,
            "has_wildcard": deps.has_wildcard,
            "uses_prev_next": deps.uses_prev_next,
        }),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::missing_docs_in_private_items)]
    use super::*;
    use crate::parser;

    fn deps(input: &str) -> Dependencies {
        let expr = parser::parse(input).unwrap();
        extract_dependencies(&expr)
    }

    #[test]
    fn test_simple_field_ref() {
        let d = deps("$name");
        assert!(d.fields.contains("name"));
    }

    #[test]
    fn test_nested_field_ref() {
        let d = deps("$address.city");
        assert!(d.fields.contains("address.city"));
    }

    #[test]
    fn test_wildcard_detection() {
        let d = deps("$items[*].qty");
        assert!(d.has_wildcard);
        assert!(d.fields.contains("items[*].qty"));
    }

    #[test]
    fn test_bare_dollar() {
        let d = deps("$");
        assert!(d.has_self_ref);
    }

    #[test]
    fn test_context_ref() {
        let d = deps("@index");
        assert!(d.context_refs.contains("@index"));
    }

    #[test]
    fn test_instance_ref() {
        let d = deps("@instance('priorYear').total");
        assert!(d.instance_refs.contains("priorYear"));
    }

    #[test]
    fn test_let_binding_excludes_bound_var() {
        let d = deps("let x = $a in x + $b");
        assert!(d.fields.contains("a"));
        assert!(d.fields.contains("b"));
        assert!(!d.fields.contains("x"));
    }

    #[test]
    fn test_mip_deps() {
        let d = deps("valid($name)");
        assert!(d.mip_deps.contains("name"));
    }

    #[test]
    fn test_prev_next_detection() {
        let d = deps("prev()");
        assert!(d.uses_prev_next);
    }

    #[test]
    fn test_multiple_fields() {
        let d = deps("$a + $b * $c");
        assert_eq!(d.fields.len(), 3);
        assert!(d.fields.contains("a"));
        assert!(d.fields.contains("b"));
        assert!(d.fields.contains("c"));
    }

    /// Spec: core/spec.md §3.6.1, fel-grammar.md §4 precedence 7 —
    /// NullCoalesce (`??`) dep extraction must walk both sides.
    #[test]
    fn null_coalesce_extracts_deps_from_both_sides() {
        let d = deps("$fieldA ?? $fieldB");
        assert!(
            d.fields.contains("fieldA"),
            "left side of ?? must produce a dep"
        );
        assert!(
            d.fields.contains("fieldB"),
            "right side of ?? must produce a dep"
        );
        assert_eq!(d.fields.len(), 2);
    }

    /// Spec: core/spec.md §3.6.1, fel-grammar.md §4 precedence 1 —
    /// Ternary (`? :`) dep extraction must walk condition, true-branch, and false-branch.
    #[test]
    fn ternary_extracts_deps_from_all_three_branches() {
        let d = deps("$cond ? $yes : $no");
        assert!(d.fields.contains("cond"), "condition must produce a dep");
        assert!(d.fields.contains("yes"), "true-branch must produce a dep");
        assert!(d.fields.contains("no"), "false-branch must produce a dep");
        assert_eq!(d.fields.len(), 3);
    }

    /// Spec: core/spec.md §3.6.1, fel-grammar.md §4.2-4.3 —
    /// Field refs nested inside object and array literals must be found.
    #[test]
    fn object_and_array_literal_dep_extraction() {
        let d = deps("{total: $price, items: [$qty, $tax]}");
        assert!(
            d.fields.contains("price"),
            "object value must produce a dep"
        );
        assert!(d.fields.contains("qty"), "array element must produce a dep");
        assert!(d.fields.contains("tax"), "array element must produce a dep");
        assert_eq!(d.fields.len(), 3);
    }

    /// Spec: core/spec.md §3.5.1 — countWhere's predicate rebinds `$` to the
    /// current element. Bare `$` inside the predicate is NOT a field self-ref.
    #[test]
    fn count_where_rebinds_bare_dollar() {
        let d = deps("countWhere($items, $ > 3)");
        assert!(
            d.fields.contains("items"),
            "first arg field ref must be found"
        );
        assert!(
            !d.has_self_ref,
            "bare $ in countWhere predicate is rebound, not a self-ref"
        );
        // The predicate's `$` should NOT appear in fields
        assert_eq!(d.fields.len(), 1);
    }

    /// Spec: core/spec.md §3.5.1 — `every` rebinds `$` like `countWhere`.
    #[test]
    fn every_rebinds_bare_dollar() {
        let d = deps("every($items, $ > 0)");
        assert!(d.fields.contains("items"));
        assert!(!d.has_self_ref);
        assert_eq!(d.fields.len(), 1);
    }

    /// Spec: core/spec.md §3.5.1 — `sumWhere` rebinds `$` like `countWhere` (via `filter_where`).
    #[test]
    fn sum_where_rebinds_bare_dollar() {
        let d = deps("sumWhere($items, $ > 0)");
        assert!(d.fields.contains("items"));
        assert!(!d.has_self_ref);
        assert_eq!(d.fields.len(), 1);
    }

    /// Spec: core/spec.md §3.6.1 — deeply nested function calls (3+ levels)
    /// must recursively extract all deps.
    #[test]
    fn deeply_nested_function_calls_extract_all_deps() {
        let d = deps("sum(round($a + $b) + every($items, $ > $threshold))");
        assert!(d.fields.contains("a"));
        assert!(d.fields.contains("b"));
        assert!(d.fields.contains("items"));
        assert!(d.fields.contains("threshold"));
        assert_eq!(d.fields.len(), 4);
    }

    mod path_segment_append {
        use super::deps;
        use crate::ast::{PathDotJoin, PathSegment};

        #[test]
        fn walk_style_always_prefixes_dot_segments() {
            let mut path = "items".to_string();
            PathSegment::Dot("qty".into()).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
            assert_eq!(path, "items.qty");
        }

        #[test]
        fn extract_style_skips_dot_on_empty_base() {
            let mut path = String::new();
            PathSegment::Dot("a".into()).append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
            assert_eq!(path, "a");
        }

        #[test]
        fn extract_style_prefixes_dot_when_base_nonempty() {
            let mut path = "items".to_string();
            PathSegment::Dot("qty".into())
                .append_to_path(&mut path, PathDotJoin::PrefixWhenNonempty);
            assert_eq!(path, "items.qty");
        }

        #[test]
        fn index_and_wildcard_rendering() {
            let mut path = "items".to_string();
            PathSegment::Index(2).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
            PathSegment::Wildcard.append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
            PathSegment::Dot("qty".into()).append_to_path(&mut path, PathDotJoin::AlwaysPrefix);
            assert_eq!(path, "items[2][*].qty");
        }

        #[test]
        fn mip_empty_base_wildcard_path() {
            let d = deps("valid($[*])");
            assert!(d.mip_deps.contains("[*]"));
        }

        #[test]
        fn indexed_field_path_round_trip() {
            let d = deps("$rows[2].id");
            assert!(d.fields.contains("rows[2].id"));
        }
    }
}