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
//! FEL evaluation environment with field resolution, repeats, MIP state, and instances.
//!
//! Provides `FormspecEnvironment`, a concrete `Environment` impl backed by
//! nested data dicts, repeat context, MIP states, named instances, and variables.
//!
//! Helpers such as `project_repeat_field` resolve repeat-group keys into projected field values.
#![allow(clippy::missing_docs_in_private_items)]
use rust_decimal::Decimal;
use std::collections::HashMap;

use crate::error::MissingTimezoneContextError;
use crate::evaluator::Environment;
use crate::types::{Date as TypeDate, Value as TypeValue, parse_datetime_literal};

// ── Data structures ─────────────────────────────────────────────

/// Repeat-group iteration context (§4.3).
#[derive(Debug, Clone)]
pub struct RepeatContext {
    /// The current row value.
    pub current: TypeValue,
    /// 1-based index within the repeat group.
    pub index: usize,
    /// Total instance count.
    pub count: usize,
    /// Parent repeat context (for nested repeats).
    pub parent: Option<Box<RepeatContext>>,
    /// All rows in the collection (for prev/next navigation).
    pub collection: Vec<TypeValue>,
}

/// XForms Model Item Properties for a single field path.
#[derive(Debug, Clone)]
pub struct MipState {
    /// `valid($path)` result when set for this path.
    pub valid: bool,
    /// `relevant($path)`.
    pub relevant: bool,
    /// `readonly($path)`.
    pub readonly: bool,
    /// `required($path)`.
    pub required: bool,
}

#[allow(missing_docs)]
impl Default for MipState {
    fn default() -> Self {
        Self {
            valid: true,
            relevant: true,
            readonly: false,
            required: false,
        }
    }
}

// ── FormspecEnvironment ─────────────────────────────────────────

/// A full-featured environment for FEL evaluation within a Formspec engine.
///
/// Supports:
/// - Field resolution via `$field.path` (walks nested data dict)
/// - Named instances via `@instance('name')`
/// - Repeat context via `@current`, `@index`, `@count`
/// - MIP state queries via `valid()`, `relevant()`, etc.
/// - Environment variables via `@variableName` when no host catalog is active
/// - Mapping-style context via host-specific `Environment` implementations
/// - Locale via `locale()` and `pluralCategory()`
/// - Runtime metadata via `runtimeMeta(key)`
pub struct FormspecEnvironment {
    /// Primary data dict — backs `$field` references.
    pub data: HashMap<String, TypeValue>,
    /// Named secondary instances — backs `@instance('name')`.
    pub instances: HashMap<String, TypeValue>,
    /// MIP states per dotted field path.
    pub mip_states: HashMap<String, MipState>,
    /// Environment variables — backs `@variableName` when no host catalog is active.
    pub variables: HashMap<String, TypeValue>,
    /// Current repeat context (if inside a repeat iteration).
    pub repeat_context: Option<RepeatContext>,
    /// Current runtime date for today()/now().
    pub current_datetime: Option<TypeDate>,
    /// Active locale code (BCP 47) — backs `locale()` and default for `pluralCategory()`.
    pub locale: Option<String>,
    /// The active Locale document's `formats.date` — a pattern per `formatDate` style name
    /// (`short` … `full`) that replaces the built-in rendering of that style.
    pub date_formats: HashMap<String, String>,
    /// Runtime metadata bag — backs `runtimeMeta(key)`.
    pub meta: HashMap<String, TypeValue>,
}

impl FormspecEnvironment {
    /// Empty environment (no data, instances, or repeat context).
    pub fn new() -> Self {
        Self {
            data: HashMap::new(),
            instances: HashMap::new(),
            mip_states: HashMap::new(),
            variables: HashMap::new(),
            repeat_context: None,
            current_datetime: None,
            locale: None,
            date_formats: HashMap::new(),
            meta: HashMap::new(),
        }
    }

    /// Set a field value by dotted path (e.g., "address.city").
    pub fn set_field(&mut self, path: &str, value: TypeValue) {
        self.data.insert(path.to_string(), value);
    }

    /// Set a named instance.
    pub fn set_instance(&mut self, name: &str, value: TypeValue) {
        self.instances.insert(name.to_string(), value);
    }

    /// Set MIP state for a field path.
    pub fn set_mip(&mut self, path: &str, state: MipState) {
        self.mip_states.insert(path.to_string(), state);
    }

    /// Set a variable value.
    pub fn set_variable(&mut self, name: &str, value: TypeValue) {
        self.variables.insert(name.to_string(), value);
    }

    /// Set the active locale code (BCP 47).
    pub fn set_locale(&mut self, code: &str) {
        self.locale = Some(code.to_string());
    }

    /// Set the pattern a `formatDate` style renders with (Locale `formats.date.<style>`).
    pub fn set_date_format(&mut self, style: &str, pattern: &str) {
        self.date_formats
            .insert(style.to_string(), pattern.to_string());
    }

    /// Set a runtime metadata value.
    pub fn set_meta(&mut self, key: &str, value: TypeValue) {
        self.meta.insert(key.to_string(), value);
    }

    /// Set the current runtime datetime from an ISO string.
    pub fn set_now_from_iso(&mut self, iso: &str) {
        let candidate = if iso.starts_with('@') {
            iso.to_string()
        } else {
            format!("@{iso}")
        };
        self.current_datetime = parse_datetime_literal(&candidate);
    }

    /// Enter a repeat context.
    pub fn push_repeat(
        &mut self,
        current: TypeValue,
        index: usize,
        count: usize,
        collection: Vec<TypeValue>,
    ) {
        let parent = self.repeat_context.take().map(Box::new);
        self.repeat_context = Some(RepeatContext {
            current,
            index,
            count,
            parent,
            collection,
        });
    }

    /// Leave the current repeat context, restoring the parent.
    pub fn pop_repeat(&mut self) {
        if let Some(ctx) = self.repeat_context.take() {
            self.repeat_context = ctx.parent.map(|b| *b);
        }
    }
}

#[allow(missing_docs)]
impl Default for FormspecEnvironment {
    fn default() -> Self {
        Self::new()
    }
}

/// Walks a nested value by string path segments; on an array, projects each element (`rows.score`).
///
/// A missing key or a scalar in the middle of the path resolves to `Null`.
pub fn resolve_value_path(val: &TypeValue, segments: &[String]) -> TypeValue {
    let mut current = val.clone();
    for seg in segments {
        match &current {
            TypeValue::Object(entries) => match entries.get(seg.as_str()) {
                Some(v) => current = v.clone(),
                None => return TypeValue::Null,
            },
            TypeValue::Array(entries) => {
                current = TypeValue::Array(
                    entries
                        .iter()
                        .map(|entry| match entry {
                            TypeValue::Object(fields) => {
                                fields.get(seg.as_str()).cloned().unwrap_or(TypeValue::Null)
                            }
                            _ => TypeValue::Null,
                        })
                        .collect(),
                );
            }
            _ => return TypeValue::Null,
        }
    }
    current
}

fn project_repeat_field(
    data: &HashMap<String, TypeValue>,
    segments: &[String],
) -> Option<TypeValue> {
    if segments.len() < 2 {
        return None;
    }

    // Try each possible split point: the repeat group name could span 1..N-1 segments.
    // For ["publications", "pub_entries", "pub_title"], try:
    //   split=1 → prefix "publications["       suffix ".pub_entries.pub_title"
    //   split=2 → prefix "publications.pub_entries[" suffix ".pub_title"
    for split in 1..segments.len() {
        let group_path = segments[..split].join(".");
        let prefix = format!("{group_path}[");
        let suffix = format!(".{}", segments[split..].join("."));
        let mut projected = Vec::new();

        for (key, value) in data {
            let Some(rest) = key.strip_prefix(&prefix) else {
                continue;
            };
            let Some((idx, tail)) = rest.split_once(']') else {
                continue;
            };
            if tail != suffix {
                continue;
            }
            let Ok(index) = idx.parse::<usize>() else {
                continue;
            };
            projected.push((index, value.clone()));
        }

        if !projected.is_empty() {
            projected.sort_by_key(|(index, _)| *index);
            return Some(TypeValue::Array(
                projected.into_iter().map(|(_, value)| value).collect(),
            ));
        }
    }

    None
}

fn mip_path(path: &[String]) -> String {
    path.join(".")
}

#[allow(missing_docs)]
impl Environment for FormspecEnvironment {
    fn resolve_field(&self, segments: &[String]) -> TypeValue {
        if segments.is_empty() {
            // Bare $: the node the host bound for this evaluation (data[""], e.g. the field a Bind
            // constraint targets), else the repeat row being evaluated, else null.
            if let Some(val) = self.data.get("") {
                return val.clone();
            }
            if let Some(ctx) = &self.repeat_context {
                return ctx.current.clone();
            }
            return TypeValue::Null;
        }

        let key = segments.join(".");
        // Check flat lookup first (handles dotted keys like "address.city")
        if let Some(val) = self.data.get(&key) {
            return val.clone();
        }
        // Check first segment then walk
        if let Some(val) = self.data.get(&segments[0]) {
            if segments.len() == 1 {
                return val.clone();
            }
            return resolve_value_path(val, &segments[1..]);
        }
        if let Some(projected) = project_repeat_field(&self.data, segments) {
            return projected;
        }
        TypeValue::Null
    }

    fn resolve_context(&self, name: &str, arg: Option<&str>, tail: &[String]) -> TypeValue {
        match name {
            "current" => {
                if let Some(ctx) = &self.repeat_context {
                    let base = ctx.current.clone();
                    if tail.is_empty() {
                        base
                    } else {
                        resolve_value_path(&base, tail)
                    }
                } else {
                    TypeValue::Null
                }
            }
            "index" => {
                if let Some(ctx) = &self.repeat_context {
                    TypeValue::Number(Decimal::from(ctx.index as i64))
                } else {
                    TypeValue::Null
                }
            }
            "count" => {
                if let Some(ctx) = &self.repeat_context {
                    TypeValue::Number(Decimal::from(ctx.count as i64))
                } else {
                    TypeValue::Null
                }
            }
            "instance" => {
                if let Some(inst_name) = arg {
                    if let Some(val) = self.instances.get(inst_name) {
                        if tail.is_empty() {
                            val.clone()
                        } else {
                            resolve_value_path(val, tail)
                        }
                    } else {
                        TypeValue::Null
                    }
                } else {
                    TypeValue::Null
                }
            }
            // Definition variables: @variableName
            _ => {
                if let Some(val) = self.variables.get(name) {
                    if tail.is_empty() {
                        val.clone()
                    } else {
                        resolve_value_path(val, tail)
                    }
                } else {
                    TypeValue::Null
                }
            }
        }
    }

    fn mip_valid(&self, path: &[String]) -> TypeValue {
        let key = mip_path(path);
        TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.valid))
    }

    fn mip_relevant(&self, path: &[String]) -> TypeValue {
        let key = mip_path(path);
        TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.relevant))
    }

    fn mip_readonly(&self, path: &[String]) -> TypeValue {
        let key = mip_path(path);
        TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.readonly))
    }

    fn mip_required(&self, path: &[String]) -> TypeValue {
        let key = mip_path(path);
        TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.required))
    }

    fn repeat_prev(&self) -> TypeValue {
        if let Some(ctx) = &self.repeat_context
            && ctx.index > 1
        {
            return ctx
                .collection
                .get(ctx.index - 2)
                .cloned()
                .unwrap_or(TypeValue::Null);
        }
        TypeValue::Null
    }

    fn repeat_next(&self) -> TypeValue {
        if let Some(ctx) = &self.repeat_context
            && ctx.index < ctx.count
        {
            return ctx
                .collection
                .get(ctx.index)
                .cloned()
                .unwrap_or(TypeValue::Null);
        }
        TypeValue::Null
    }

    fn repeat_parent(&self) -> TypeValue {
        if let Some(ctx) = &self.repeat_context
            && let Some(parent) = &ctx.parent
        {
            return parent.current.clone();
        }
        TypeValue::Null
    }

    fn current_date(&self) -> Result<TypeDate, MissingTimezoneContextError> {
        // Delegate to current_datetime so the "is clock configured?" check
        // has one source of truth (CODE-NIT N4 from fs-wbo9 review).
        self.current_datetime().map(|dt| TypeDate::Date {
            year: dt.year(),
            month: dt.month(),
            day: dt.day(),
        })
    }

    fn current_datetime(&self) -> Result<TypeDate, MissingTimezoneContextError> {
        self.current_datetime
            .clone()
            .ok_or_else(MissingTimezoneContextError::not_configured)
    }

    fn locale(&self) -> Option<&str> {
        self.locale.as_deref()
    }

    fn date_format(&self, style: &str) -> Option<&str> {
        self.date_formats.get(style).map(String::as_str)
    }

    fn runtime_meta(&self, key: &str) -> TypeValue {
        self.meta.get(key).cloned().unwrap_or(TypeValue::Null)
    }
}

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

    fn s(v: &str) -> TypeValue {
        TypeValue::String(v.to_string())
    }

    fn num(n: i64) -> TypeValue {
        TypeValue::Number(Decimal::from(n))
    }

    #[test]
    fn test_basic_field_resolution() {
        let mut env = FormspecEnvironment::new();
        env.set_field("name", s("Alice"));
        env.set_field("age", num(30));

        assert_eq!(env.resolve_field(&["name".into()]), s("Alice"));
        assert_eq!(env.resolve_field(&["age".into()]), num(30));
        assert_eq!(env.resolve_field(&["missing".into()]), TypeValue::Null);
    }

    #[test]
    fn test_nested_field_resolution() {
        let mut env = FormspecEnvironment::new();
        let addr = TypeValue::Object(IndexMap::from([
            ("city".to_string(), s("NYC")),
            ("zip".to_string(), s("10001")),
        ]));
        env.set_field("address", addr);

        assert_eq!(
            env.resolve_field(&["address".into(), "city".into()]),
            s("NYC")
        );
        assert_eq!(
            env.resolve_field(&["address".into(), "missing".into()]),
            TypeValue::Null
        );
    }

    #[test]
    fn test_repeat_field_projection_from_flat_rows() {
        let mut env = FormspecEnvironment::new();
        env.set_field("rows[0].score", num(80));
        env.set_field("rows[1].score", num(30));
        env.set_field("rows[2].score", num(50));

        assert_eq!(
            env.resolve_field(&["rows".into(), "score".into()]),
            TypeValue::Array(vec![num(80), num(30), num(50)]),
        );
    }

    #[test]
    fn test_repeat_context() {
        let mut env = FormspecEnvironment::new();
        let items = vec![num(10), num(20), num(30)];
        env.push_repeat(num(20), 2, 3, items);

        // @current
        assert_eq!(env.resolve_context("current", None, &[]), num(20));
        // @index (1-based)
        assert_eq!(env.resolve_context("index", None, &[]), num(2));
        // @count
        assert_eq!(env.resolve_context("count", None, &[]), num(3));
        // prev() — item at index 1 (0-indexed: 0)
        assert_eq!(env.repeat_prev(), num(10));
        // next() — item at index 3 (0-indexed: 2)
        assert_eq!(env.repeat_next(), num(30));
    }

    #[test]
    fn test_nested_repeat_context() {
        let mut env = FormspecEnvironment::new();
        let outer = vec![s("A"), s("B")];
        env.push_repeat(s("A"), 1, 2, outer);

        let inner = vec![num(1), num(2), num(3)];
        env.push_repeat(num(2), 2, 3, inner);

        // Inner context active
        assert_eq!(env.resolve_context("current", None, &[]), num(2));
        // parent() returns outer current
        assert_eq!(env.repeat_parent(), s("A"));

        env.pop_repeat();
        // Outer context restored
        assert_eq!(env.resolve_context("current", None, &[]), s("A"));
    }

    #[test]
    fn test_named_instances() {
        let mut env = FormspecEnvironment::new();
        let config = TypeValue::Object(IndexMap::from([("maxRetries".to_string(), num(3))]));
        env.set_instance("config", config);

        assert_eq!(
            env.resolve_context("instance", Some("config"), &["maxRetries".into()]),
            num(3)
        );
        assert_eq!(
            env.resolve_context("instance", Some("missing"), &[]),
            TypeValue::Null
        );
    }

    #[test]
    fn test_variables() {
        let mut env = FormspecEnvironment::new();
        env.set_variable("total", num(100));

        assert_eq!(env.resolve_context("total", None, &[]), num(100));
    }

    #[test]
    fn test_mip_states() {
        let mut env = FormspecEnvironment::new();
        env.set_mip(
            "email",
            MipState {
                valid: false,
                relevant: true,
                readonly: false,
                required: true,
            },
        );

        assert_eq!(env.mip_valid(&["email".into()]), TypeValue::Boolean(false));
        assert_eq!(
            env.mip_relevant(&["email".into()]),
            TypeValue::Boolean(true)
        );
        assert_eq!(
            env.mip_readonly(&["email".into()]),
            TypeValue::Boolean(false)
        );
        assert_eq!(
            env.mip_required(&["email".into()]),
            TypeValue::Boolean(true)
        );

        // Default MIP for unknown fields
        assert_eq!(env.mip_valid(&["unknown".into()]), TypeValue::Boolean(true));
        assert_eq!(
            env.mip_required(&["unknown".into()]),
            TypeValue::Boolean(false)
        );
    }

    #[test]
    fn test_bare_dollar_in_repeat() {
        let mut env = FormspecEnvironment::new();
        let items = vec![num(10), num(20)];
        env.push_repeat(num(10), 1, 2, items);

        // Bare $ resolves to repeat context current
        assert_eq!(env.resolve_field(&[]), num(10));
    }
}