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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! FEL source normalization before host evaluation (parity with TS `normalizeExpressionForWasmEvaluation`).
//!
//! Rewrites bare `$`, qualified repeat group refs (`$group.field`), and repeat row aliases into wildcard paths.
#![allow(clippy::missing_docs_in_private_items)]

use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;

use regex::Regex;
use serde_json::{Map, Value};

static RE_TRAILING_INDEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[\d+\]$").expect("valid regex"));
static RE_PATH_SEGMENT: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"([^\[.\]]+\[\d+\]|[^\[.\]]+)").expect("valid regex"));
static RE_REPEAT_SEG: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(.+)\[(\d+)\]$").expect("valid regex"));
static RE_INDEX_BRACKET: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\[(\d+)\]").expect("valid regex"));
static RE_REPEAT_ALIAS: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(.*)\[(\d+)\]\.([^\[.\]]+)$").expect("valid regex"));

/// Inputs for [`prepare_for_host`], mirroring the engine WASM prepass.
#[derive(Debug, Clone)]
pub struct PrepareHostInput<'a> {
    /// Raw FEL expression.
    pub expression: &'a str,
    /// Dotted path of the item being evaluated (may include `[n]` indices).
    pub current_item_path: &'a str,
    /// When true, bare `$` (not `$identifier`) becomes `$` + current field leaf name.
    pub replace_self_ref: bool,
    /// Repeat row counts keyed by group base path (e.g. `line_items` → 2).
    pub repeat_counts: &'a HashMap<String, u32>,
    /// Keys from the flat field snapshot (e.g. `rows[0].score`) used to infer repeat aliases.
    pub field_paths: &'a [String],
}

/// One enclosing repeat instance along `current_item_path`.
#[derive(Debug, Clone)]
struct RepeatAncestor {
    group_path: String,
    index: usize,
}

fn is_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_'
}

/// Cursor over a char slice that skips quoted spans (`'` / `"`) and honors `\` escapes.
struct QuoteAwareCursor<'a> {
    chars: &'a [char],
    idx: usize,
    quote: Option<char>,
}

impl<'a> QuoteAwareCursor<'a> {
    fn new(chars: &'a [char]) -> Self {
        Self {
            chars,
            idx: 0,
            quote: None,
        }
    }
    fn len(&self) -> usize {
        self.chars.len()
    }
    fn idx(&self) -> usize {
        self.idx
    }
    fn at(&self, i: usize) -> Option<char> {
        self.chars.get(i).copied()
    }
    fn step_quote(&mut self, out: &mut String) -> bool {
        let Some(c) = self.at(self.idx) else {
            return false;
        };
        if let Some(q) = self.quote {
            out.push(c);
            if c == '\\' && self.idx + 1 < self.len() {
                out.push(self.chars[self.idx + 1]);
                self.idx += 2;
                return true;
            }
            if c == q {
                self.quote = None;
            }
            self.idx += 1;
            return true;
        }
        if c == '"' || c == '\'' {
            self.quote = Some(c);
            out.push(c);
            self.idx += 1;
            return true;
        }
        false
    }
    fn push_current(&mut self, out: &mut String) {
        if let Some(c) = self.at(self.idx) {
            out.push(c);
            self.idx += 1;
        }
    }
    fn advance_to(&mut self, next: usize) {
        self.idx = next;
    }
}

/// Strips trailing `[n]` from the last path segment (TS `splitIndexedPath` last + replace).
fn current_field_leaf(item_path: &str) -> String {
    let segments = path_segments(item_path);
    let Some(last) = segments.last().map(String::as_str) else {
        return String::new();
    };
    RE_TRAILING_INDEX.replace(last, "").to_string()
}

fn path_segments(path: &str) -> Vec<String> {
    // Same tokenization as TS `/[^.[\]]+\[\d+\]|[^.[\]]+/g` — `]` must not appear bare in a Rust char class.
    RE_PATH_SEGMENT
        .find_iter(path)
        .map(|m| m.as_str().to_string())
        .collect()
}

fn get_repeat_ancestors(path: &str, repeats: &HashMap<String, u32>) -> Vec<RepeatAncestor> {
    let mut ancestors = Vec::new();
    let mut current = String::new();

    for segment in path_segments(path) {
        if let Some(caps) = RE_REPEAT_SEG.captures(&segment) {
            let g1 = caps.get(1).expect("group 1").as_str();
            let idx: usize = caps
                .get(2)
                .and_then(|m| m.as_str().parse().ok())
                .unwrap_or(0);
            let new_base = if current.is_empty() {
                g1.to_string()
            } else {
                format!("{current}.{g1}")
            };
            if repeats.contains_key(&new_base) {
                ancestors.push(RepeatAncestor {
                    group_path: new_base.clone(),
                    index: idx,
                });
            }
            current = format!("{new_base}[{idx}]");
        } else {
            current = if current.is_empty() {
                segment.clone()
            } else {
                format!("{current}.{segment}")
            };
        }
    }
    ancestors
}

/// FEL uses 1-based repeat indices in paths; flat data uses 0-based.
fn to_fel_indexed_path(path: &str) -> String {
    RE_INDEX_BRACKET
        .replace_all(path, |caps: &regex::Captures| {
            let n: i64 = caps
                .get(1)
                .and_then(|m| m.as_str().parse().ok())
                .unwrap_or(0);
            format!("[{}]", n + 1)
        })
        .to_string()
}

fn to_repeat_wildcard_path(alias: &str) -> String {
    match alias.rfind('.') {
        Some(i) => format!("{}[*].{}", &alias[..i], &alias[i + 1..]),
        None => format!("{alias}[*]"),
    }
}

/// Repeat row aliases inferred from flat field paths: `rows[0].score` yields `rows.score`,
/// which [`prepare_with_aliases`] rewrites to the wildcard path `$rows[*].score`.
///
/// Building the set is O(paths); a host that evaluates many expressions against one
/// field set builds it once and reuses it, so each prepare costs O(aliases × expression).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RepeatAliases {
    /// Distinct aliases, longest first so a longer alias is never shadowed by its prefix.
    aliases: Vec<String>,
}

impl RepeatAliases {
    /// Aliases for every `<group>[<n>].<field>` path in `paths` (duplicates ignored).
    pub fn from_field_paths<'a>(paths: impl IntoIterator<Item = &'a str>) -> Self {
        let mut seen = HashSet::new();
        let mut aliases = Vec::new();
        for p in paths {
            if let Some(caps) = RE_REPEAT_ALIAS.captures(p) {
                let base = caps.get(1).expect("base").as_str();
                let field = caps.get(3).expect("field").as_str();
                let alias = format!("{base}.{field}");
                if seen.insert(alias.clone()) {
                    aliases.push(alias);
                }
            }
        }
        aliases.sort_by_key(|a| std::cmp::Reverse(a.len()));
        Self { aliases }
    }

    /// The aliases, longest first.
    pub fn as_slice(&self) -> &[String] {
        &self.aliases
    }
}

fn replace_bare_current_field_refs(expr: &str, current_field: &str) -> String {
    if current_field.is_empty() || !expr.contains('$') {
        return expr.to_string();
    }
    let chars: Vec<char> = expr.chars().collect();
    let mut out = String::with_capacity(expr.len() + current_field.len());
    let mut cur = QuoteAwareCursor::new(&chars);

    while cur.idx() < cur.len() {
        if cur.step_quote(&mut out) {
            continue;
        }
        let i = cur.idx();
        let c = chars[i];
        if c == '$' {
            let prev_ok = i == 0 || !is_ident_char(chars[i - 1]);
            let next_ok = i + 1 >= chars.len() || !is_ident_char(chars[i + 1]);
            if prev_ok && next_ok {
                out.push('$');
                out.push_str(current_field);
                cur.advance_to(i + 1);
                continue;
            }
        }
        cur.push_current(&mut out);
    }
    out
}

fn resolve_qualified_group_refs(expression: &str, repeat_ancestors: &[RepeatAncestor]) -> String {
    if repeat_ancestors.is_empty() {
        return expression.to_string();
    }

    let mut replacements: Vec<(String, String, bool)> = Vec::new();
    for (idx, anc) in repeat_ancestors.iter().enumerate() {
        let group_name = anc
            .group_path
            .rsplit('.')
            .next()
            .unwrap_or(anc.group_path.as_str())
            .to_string();
        let concrete_prefix = format!("{}[{}]", anc.group_path, anc.index);
        let is_innermost = idx == repeat_ancestors.len() - 1;
        replacements.push((group_name, concrete_prefix, is_innermost));
    }
    replacements.sort_by(|a, b| b.0.len().cmp(&a.0.len()));

    let mut result = expression.to_string();
    for (group_name, concrete_prefix, is_innermost) in replacements {
        result = replace_qualified_group_ref_outside_quotes(
            &result,
            &group_name,
            &concrete_prefix,
            is_innermost,
        );
    }
    result
}

fn replace_qualified_group_ref_outside_quotes(
    expr: &str,
    group_name: &str,
    concrete_prefix: &str,
    is_innermost: bool,
) -> String {
    if group_name.is_empty() {
        return expr.to_string();
    }
    let chars: Vec<char> = expr.chars().collect();
    let group_chars: Vec<char> = group_name.chars().collect();
    let mut out = String::with_capacity(expr.len());
    let mut cur = QuoteAwareCursor::new(&chars);

    while cur.idx() < cur.len() {
        if cur.step_quote(&mut out) {
            continue;
        }

        let i = cur.idx();
        let has_group = i + 1 + group_chars.len() < chars.len()
            && chars[i] == '$'
            && chars[i + 1..i + 1 + group_chars.len()] == group_chars[..];
        let dot_idx = i + 1 + group_chars.len();
        if has_group && chars[dot_idx] == '.' && dot_idx + 1 < chars.len() {
            let field_start = dot_idx + 1;
            if is_ident_start(chars[field_start]) {
                let mut j = field_start + 1;
                while j < chars.len() && is_ident_char(chars[j]) {
                    j += 1;
                }
                let field: String = chars[field_start..j].iter().collect();
                if is_innermost {
                    out.push_str(&field);
                } else {
                    out.push_str(&format!("{}.{field}", to_fel_indexed_path(concrete_prefix)));
                }
                cur.advance_to(j);
                continue;
            }
        }

        cur.push_current(&mut out);
    }

    out
}

fn is_blocked_implicit_prefix(c: char) -> bool {
    // Treat `.` as blocked so `rows.score` inside `x.rows.score` is not rewritten to
    // `x.$rows[*].score` (invalid FEL: `.` must be followed by an identifier, not `$`).
    is_ident_char(c) || matches!(c, '$' | '@' | '.')
}

fn suffix_continues_alias(c: Option<char>) -> bool {
    c.is_some_and(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '[')
}

fn slice_eq_chars(chars: &[char], start: usize, needle: &[char]) -> bool {
    start + needle.len() <= chars.len() && chars[start..start + needle.len()] == needle[..]
}

/// Implicit `alias` → `wildcard`: prefix must be start or not `$@.` / identifier char; suffix must not continue an identifier.
fn replace_implicit_repeat_alias(expr: &str, alias: &str, wildcard: &str) -> String {
    if alias.is_empty() {
        return expr.to_string();
    }
    let chars: Vec<char> = expr.chars().collect();
    let needle: Vec<char> = alias.chars().collect();
    let mut out = String::with_capacity(expr.len());
    let mut i = 0;
    while i < chars.len() {
        if slice_eq_chars(&chars, i, &needle)
            && (i == 0 || !is_blocked_implicit_prefix(chars[i - 1]))
            && !suffix_continues_alias(chars.get(i + needle.len()).copied())
        {
            out.push_str(wildcard);
            i += needle.len();
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

/// Second pass: `$alias` → `wildcard` (look-ahead not available in the `regex` crate).
fn replace_explicit_dollar_repeat_alias(expr: &str, alias: &str, wildcard: &str) -> String {
    if alias.is_empty() {
        return expr.to_string();
    }
    let chars: Vec<char> = expr.chars().collect();
    let needle: Vec<char> = alias.chars().collect();
    let mut out = String::with_capacity(expr.len());
    let mut i = 0;
    while i < chars.len() {
        if chars.get(i) == Some(&'$')
            && slice_eq_chars(&chars, i + 1, &needle)
            && !suffix_continues_alias(chars.get(i + 1 + needle.len()).copied())
        {
            out.push_str(wildcard);
            i += 1 + needle.len();
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

fn apply_repeat_alias_pass(expr: &str, alias: &str, wildcard_with_dollar: &str) -> String {
    let after_implicit = replace_implicit_repeat_alias(expr, alias, wildcard_with_dollar);
    replace_explicit_dollar_repeat_alias(&after_implicit, alias, wildcard_with_dollar)
}

/// Owned inputs for [`prepare`] after JSON / host parsing.
#[derive(Debug, Clone)]
pub struct PrepareHostOptions {
    /// Raw FEL expression.
    pub expression: String,
    /// Item path for repeat / self-ref normalization.
    pub current_item_path: String,
    /// When true, bare `$` becomes `$` + current field leaf name.
    pub replace_self_ref: bool,
    /// Repeat row counts by group base path.
    pub repeat_counts: HashMap<String, u32>,
    /// Flat field paths for repeat alias inference.
    pub field_paths: Vec<String>,
}

/// Parses prepare-FEL options from a JSON object (WASM / Python hosts).
pub fn host_options_from_json(obj: &Map<String, Value>) -> Result<PrepareHostOptions, String> {
    let expression = obj
        .get("expression")
        .and_then(|x| x.as_str())
        .ok_or("expression (string) is required")?
        .to_string();
    let current_item_path = obj
        .get("currentItemPath")
        .or_else(|| obj.get("current_item_path"))
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();
    let replace_self_ref = obj
        .get("replaceSelfRef")
        .or_else(|| obj.get("replace_self_ref"))
        .and_then(|x| x.as_bool())
        .unwrap_or(false);

    let mut repeat_counts: HashMap<String, u32> = HashMap::new();
    if let Some(rc) = obj
        .get("repeatCounts")
        .or_else(|| obj.get("repeat_counts"))
        .and_then(|x| x.as_object())
    {
        for (k, val) in rc.iter() {
            if let Some(n) = val
                .as_u64()
                .or_else(|| val.as_i64().filter(|&i| i >= 0).map(|i| i as u64))
                && n <= u32::MAX as u64
            {
                repeat_counts.insert(k.clone(), n as u32);
            }
        }
    }

    let mut field_paths: Vec<String> = Vec::new();
    if let Some(arr) = obj
        .get("fieldPaths")
        .or_else(|| obj.get("field_paths"))
        .and_then(|x| x.as_array())
    {
        for p in arr {
            if let Some(s) = p.as_str() {
                field_paths.push(s.to_string());
            }
        }
    } else if let Some(vmap) = obj
        .get("valuesByPath")
        .or_else(|| obj.get("values_by_path"))
        .and_then(|x| x.as_object())
    {
        field_paths.extend(vmap.keys().cloned());
    }

    Ok(PrepareHostOptions {
        expression,
        current_item_path,
        replace_self_ref,
        repeat_counts,
        field_paths,
    })
}

/// Normalizes using owned options (convenience after [`host_options_from_json`]).
pub fn prepare(opts: &PrepareHostOptions) -> String {
    prepare_for_host(PrepareHostInput {
        expression: &opts.expression,
        current_item_path: &opts.current_item_path,
        replace_self_ref: opts.replace_self_ref,
        repeat_counts: &opts.repeat_counts,
        field_paths: &opts.field_paths,
    })
}

/// Applies the same normalization pass the TypeScript engine runs before WASM FEL evaluation.
pub fn prepare_for_host(input: PrepareHostInput<'_>) -> String {
    prepare_with_aliases(
        input.expression,
        input.current_item_path,
        input.replace_self_ref,
        input.repeat_counts,
        &RepeatAliases::from_field_paths(input.field_paths.iter().map(String::as_str)),
    )
}

/// [`prepare_for_host`] with the repeat aliases already built from the field paths.
pub fn prepare_with_aliases(
    expression: &str,
    current_item_path: &str,
    replace_self_ref: bool,
    repeat_counts: &HashMap<String, u32>,
    aliases: &RepeatAliases,
) -> String {
    let leaf = current_field_leaf(current_item_path);
    let mut normalized = expression.to_string();
    if replace_self_ref && !leaf.is_empty() {
        normalized = replace_bare_current_field_refs(&normalized, &leaf);
    }
    let ancestors = get_repeat_ancestors(current_item_path, repeat_counts);
    normalized = resolve_qualified_group_refs(&normalized, &ancestors);
    for alias in aliases.as_slice() {
        let wildcard = format!("${}", to_repeat_wildcard_path(alias));
        normalized = apply_repeat_alias_pass(&normalized, alias, &wildcard);
    }
    normalized
}

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

    fn prep(
        expr: &str,
        path: &str,
        replace: bool,
        repeats: &[(&str, u32)],
        paths: &[&str],
    ) -> String {
        let rc: HashMap<String, u32> = repeats.iter().map(|(k, v)| (k.to_string(), *v)).collect();
        let fp: Vec<String> = paths.iter().map(|s| (*s).to_string()).collect();
        prepare_for_host(PrepareHostInput {
            expression: expr,
            current_item_path: path,
            replace_self_ref: replace,
            repeat_counts: &rc,
            field_paths: &fp,
        })
    }

    #[test]
    fn bare_dollar_replaces_with_current_field_leaf() {
        assert_eq!(prep("$ * 2", "items[0].qty", true, &[], &[]), "$qty * 2");
    }

    #[test]
    fn qualified_innermost_repeat_becomes_sibling_field() {
        let out = prep(
            "$line_items.qty * $line_items.price",
            "line_items[0].total",
            false,
            &[("line_items", 2)],
            &[],
        );
        assert_eq!(out, "qty * price");
    }

    #[test]
    fn qualified_outer_repeat_uses_fel_one_based_indices() {
        let out = prep(
            "$orders.discount + $items.qty",
            "orders[0].items[1].line_total",
            false,
            &[("orders", 1), ("orders[0].items", 3)],
            &[],
        );
        assert_eq!(out, "orders[1].discount + qty");
    }

    #[test]
    fn repeat_alias_implicit_and_explicit() {
        let out = prep(
            "rows.score + $rows.score + x.rows.score",
            "",
            false,
            &[],
            &["rows[0].score", "rows[1].score"],
        );
        assert_eq!(out, "$rows[*].score + $rows[*].score + x.rows.score");
    }

    #[test]
    fn prebuilt_aliases_match_per_call_inference_and_sort_longest_first() {
        let aliases = RepeatAliases::from_field_paths([
            "rows[0].s",
            "rows[1].s",
            "rows[0].score",
            "plain",
            "rows[0].sub[2].x",
        ]);
        assert_eq!(
            aliases.as_slice(),
            &[
                "rows[0].sub.x".to_string(),
                "rows.score".to_string(),
                "rows.s".to_string()
            ]
        );
        let counts = HashMap::new();
        assert_eq!(
            prepare_with_aliases("rows.score + $rows.s", "", false, &counts, &aliases),
            prep(
                "rows.score + $rows.s",
                "",
                false,
                &[],
                &[
                    "rows[0].s",
                    "rows[1].s",
                    "rows[0].score",
                    "plain",
                    "rows[0].sub[2].x"
                ],
            ),
        );
    }

    #[test]
    fn escaped_quote_inside_literal_preserves_dollar_group_ref() {
        let out = prep(
            "if($line_items.qty > 0, 'it\\'s $line_items.qty', \"ok\")",
            "line_items[0].total",
            false,
            &[("line_items", 2)],
            &[],
        );
        assert!(
            out.contains("$line_items.qty") || out.contains("line_items.qty"),
            "rewrites outside quotes only; got: {out}"
        );
        assert!(out.contains("it's") || out.contains("it\\'s"));
    }

    #[test]
    fn qualified_repeat_reference_inside_string_literal_is_not_rewritten() {
        let out = prep(
            "if($line_items.qty > 0, '$line_items.qty', \"x $line_items.qty y\")",
            "line_items[0].total",
            false,
            &[("line_items", 2)],
            &[],
        );
        assert_eq!(
            out,
            "if(qty > 0, '$line_items.qty', \"x $line_items.qty y\")"
        );
    }
}