Skip to main content

fel_core/
environment.rs

1//! FEL evaluation environment with field resolution, repeats, MIP state, and instances.
2//!
3//! Provides `FormspecEnvironment`, a concrete `Environment` impl backed by
4//! nested data dicts, repeat context, MIP states, named instances, and variables.
5//!
6//! Helpers such as `project_repeat_field` resolve repeat-group keys into projected field values.
7#![allow(clippy::missing_docs_in_private_items)]
8use rust_decimal::Decimal;
9use std::collections::HashMap;
10
11use crate::error::MissingTimezoneContextError;
12use crate::evaluator::Environment;
13use crate::types::{Date as TypeDate, Value as TypeValue, parse_datetime_literal};
14
15// ── Data structures ─────────────────────────────────────────────
16
17/// Repeat-group iteration context (§4.3).
18#[derive(Debug, Clone)]
19pub struct RepeatContext {
20    /// The current row value.
21    pub current: TypeValue,
22    /// 1-based index within the repeat group.
23    pub index: usize,
24    /// Total instance count.
25    pub count: usize,
26    /// Parent repeat context (for nested repeats).
27    pub parent: Option<Box<RepeatContext>>,
28    /// All rows in the collection (for prev/next navigation).
29    pub collection: Vec<TypeValue>,
30}
31
32/// XForms Model Item Properties for a single field path.
33#[derive(Debug, Clone)]
34pub struct MipState {
35    /// `valid($path)` result when set for this path.
36    pub valid: bool,
37    /// `relevant($path)`.
38    pub relevant: bool,
39    /// `readonly($path)`.
40    pub readonly: bool,
41    /// `required($path)`.
42    pub required: bool,
43}
44
45#[allow(missing_docs)]
46impl Default for MipState {
47    fn default() -> Self {
48        Self {
49            valid: true,
50            relevant: true,
51            readonly: false,
52            required: false,
53        }
54    }
55}
56
57// ── FormspecEnvironment ─────────────────────────────────────────
58
59/// A full-featured environment for FEL evaluation within a Formspec engine.
60///
61/// Supports:
62/// - Field resolution via `$field.path` (walks nested data dict)
63/// - Named instances via `@instance('name')`
64/// - Repeat context via `@current`, `@index`, `@count`
65/// - MIP state queries via `valid()`, `relevant()`, etc.
66/// - Environment variables via `@variableName` when no host catalog is active
67/// - Mapping-style context via host-specific `Environment` implementations
68/// - Locale via `locale()` and `pluralCategory()`
69/// - Runtime metadata via `runtimeMeta(key)`
70pub struct FormspecEnvironment {
71    /// Primary data dict — backs `$field` references.
72    pub data: HashMap<String, TypeValue>,
73    /// Named secondary instances — backs `@instance('name')`.
74    pub instances: HashMap<String, TypeValue>,
75    /// MIP states per dotted field path.
76    pub mip_states: HashMap<String, MipState>,
77    /// Environment variables — backs `@variableName` when no host catalog is active.
78    pub variables: HashMap<String, TypeValue>,
79    /// Current repeat context (if inside a repeat iteration).
80    pub repeat_context: Option<RepeatContext>,
81    /// Current runtime date for today()/now().
82    pub current_datetime: Option<TypeDate>,
83    /// Active locale code (BCP 47) — backs `locale()` and default for `pluralCategory()`.
84    pub locale: Option<String>,
85    /// The active Locale document's `formats.date` — a pattern per `formatDate` style name
86    /// (`short` … `full`) that replaces the built-in rendering of that style.
87    pub date_formats: HashMap<String, String>,
88    /// Runtime metadata bag — backs `runtimeMeta(key)`.
89    pub meta: HashMap<String, TypeValue>,
90}
91
92impl FormspecEnvironment {
93    /// Empty environment (no data, instances, or repeat context).
94    pub fn new() -> Self {
95        Self {
96            data: HashMap::new(),
97            instances: HashMap::new(),
98            mip_states: HashMap::new(),
99            variables: HashMap::new(),
100            repeat_context: None,
101            current_datetime: None,
102            locale: None,
103            date_formats: HashMap::new(),
104            meta: HashMap::new(),
105        }
106    }
107
108    /// Set a field value by dotted path (e.g., "address.city").
109    pub fn set_field(&mut self, path: &str, value: TypeValue) {
110        self.data.insert(path.to_string(), value);
111    }
112
113    /// Set a named instance.
114    pub fn set_instance(&mut self, name: &str, value: TypeValue) {
115        self.instances.insert(name.to_string(), value);
116    }
117
118    /// Set MIP state for a field path.
119    pub fn set_mip(&mut self, path: &str, state: MipState) {
120        self.mip_states.insert(path.to_string(), state);
121    }
122
123    /// Set a variable value.
124    pub fn set_variable(&mut self, name: &str, value: TypeValue) {
125        self.variables.insert(name.to_string(), value);
126    }
127
128    /// Set the active locale code (BCP 47).
129    pub fn set_locale(&mut self, code: &str) {
130        self.locale = Some(code.to_string());
131    }
132
133    /// Set the pattern a `formatDate` style renders with (Locale `formats.date.<style>`).
134    pub fn set_date_format(&mut self, style: &str, pattern: &str) {
135        self.date_formats
136            .insert(style.to_string(), pattern.to_string());
137    }
138
139    /// Set a runtime metadata value.
140    pub fn set_meta(&mut self, key: &str, value: TypeValue) {
141        self.meta.insert(key.to_string(), value);
142    }
143
144    /// Set the current runtime datetime from an ISO string.
145    pub fn set_now_from_iso(&mut self, iso: &str) {
146        let candidate = if iso.starts_with('@') {
147            iso.to_string()
148        } else {
149            format!("@{iso}")
150        };
151        self.current_datetime = parse_datetime_literal(&candidate);
152    }
153
154    /// Enter a repeat context.
155    pub fn push_repeat(
156        &mut self,
157        current: TypeValue,
158        index: usize,
159        count: usize,
160        collection: Vec<TypeValue>,
161    ) {
162        let parent = self.repeat_context.take().map(Box::new);
163        self.repeat_context = Some(RepeatContext {
164            current,
165            index,
166            count,
167            parent,
168            collection,
169        });
170    }
171
172    /// Leave the current repeat context, restoring the parent.
173    pub fn pop_repeat(&mut self) {
174        if let Some(ctx) = self.repeat_context.take() {
175            self.repeat_context = ctx.parent.map(|b| *b);
176        }
177    }
178}
179
180#[allow(missing_docs)]
181impl Default for FormspecEnvironment {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187/// Walks a nested value by string path segments; on an array, projects each element (`rows.score`).
188///
189/// A missing key or a scalar in the middle of the path resolves to `Null`.
190pub fn resolve_value_path(val: &TypeValue, segments: &[String]) -> TypeValue {
191    let mut current = val.clone();
192    for seg in segments {
193        match &current {
194            TypeValue::Object(entries) => match entries.get(seg.as_str()) {
195                Some(v) => current = v.clone(),
196                None => return TypeValue::Null,
197            },
198            TypeValue::Array(entries) => {
199                current = TypeValue::Array(
200                    entries
201                        .iter()
202                        .map(|entry| match entry {
203                            TypeValue::Object(fields) => {
204                                fields.get(seg.as_str()).cloned().unwrap_or(TypeValue::Null)
205                            }
206                            _ => TypeValue::Null,
207                        })
208                        .collect(),
209                );
210            }
211            _ => return TypeValue::Null,
212        }
213    }
214    current
215}
216
217fn project_repeat_field(
218    data: &HashMap<String, TypeValue>,
219    segments: &[String],
220) -> Option<TypeValue> {
221    if segments.len() < 2 {
222        return None;
223    }
224
225    // Try each possible split point: the repeat group name could span 1..N-1 segments.
226    // For ["publications", "pub_entries", "pub_title"], try:
227    //   split=1 → prefix "publications["       suffix ".pub_entries.pub_title"
228    //   split=2 → prefix "publications.pub_entries[" suffix ".pub_title"
229    for split in 1..segments.len() {
230        let group_path = segments[..split].join(".");
231        let prefix = format!("{group_path}[");
232        let suffix = format!(".{}", segments[split..].join("."));
233        let mut projected = Vec::new();
234
235        for (key, value) in data {
236            let Some(rest) = key.strip_prefix(&prefix) else {
237                continue;
238            };
239            let Some((idx, tail)) = rest.split_once(']') else {
240                continue;
241            };
242            if tail != suffix {
243                continue;
244            }
245            let Ok(index) = idx.parse::<usize>() else {
246                continue;
247            };
248            projected.push((index, value.clone()));
249        }
250
251        if !projected.is_empty() {
252            projected.sort_by_key(|(index, _)| *index);
253            return Some(TypeValue::Array(
254                projected.into_iter().map(|(_, value)| value).collect(),
255            ));
256        }
257    }
258
259    None
260}
261
262fn mip_path(path: &[String]) -> String {
263    path.join(".")
264}
265
266#[allow(missing_docs)]
267impl Environment for FormspecEnvironment {
268    fn resolve_field(&self, segments: &[String]) -> TypeValue {
269        if segments.is_empty() {
270            // Bare $: the node the host bound for this evaluation (data[""], e.g. the field a Bind
271            // constraint targets), else the repeat row being evaluated, else null.
272            if let Some(val) = self.data.get("") {
273                return val.clone();
274            }
275            if let Some(ctx) = &self.repeat_context {
276                return ctx.current.clone();
277            }
278            return TypeValue::Null;
279        }
280
281        let key = segments.join(".");
282        // Check flat lookup first (handles dotted keys like "address.city")
283        if let Some(val) = self.data.get(&key) {
284            return val.clone();
285        }
286        // Check first segment then walk
287        if let Some(val) = self.data.get(&segments[0]) {
288            if segments.len() == 1 {
289                return val.clone();
290            }
291            return resolve_value_path(val, &segments[1..]);
292        }
293        if let Some(projected) = project_repeat_field(&self.data, segments) {
294            return projected;
295        }
296        TypeValue::Null
297    }
298
299    fn resolve_context(&self, name: &str, arg: Option<&str>, tail: &[String]) -> TypeValue {
300        match name {
301            "current" => {
302                if let Some(ctx) = &self.repeat_context {
303                    let base = ctx.current.clone();
304                    if tail.is_empty() {
305                        base
306                    } else {
307                        resolve_value_path(&base, tail)
308                    }
309                } else {
310                    TypeValue::Null
311                }
312            }
313            "index" => {
314                if let Some(ctx) = &self.repeat_context {
315                    TypeValue::Number(Decimal::from(ctx.index as i64))
316                } else {
317                    TypeValue::Null
318                }
319            }
320            "count" => {
321                if let Some(ctx) = &self.repeat_context {
322                    TypeValue::Number(Decimal::from(ctx.count as i64))
323                } else {
324                    TypeValue::Null
325                }
326            }
327            "instance" => {
328                if let Some(inst_name) = arg {
329                    if let Some(val) = self.instances.get(inst_name) {
330                        if tail.is_empty() {
331                            val.clone()
332                        } else {
333                            resolve_value_path(val, tail)
334                        }
335                    } else {
336                        TypeValue::Null
337                    }
338                } else {
339                    TypeValue::Null
340                }
341            }
342            // Definition variables: @variableName
343            _ => {
344                if let Some(val) = self.variables.get(name) {
345                    if tail.is_empty() {
346                        val.clone()
347                    } else {
348                        resolve_value_path(val, tail)
349                    }
350                } else {
351                    TypeValue::Null
352                }
353            }
354        }
355    }
356
357    fn mip_valid(&self, path: &[String]) -> TypeValue {
358        let key = mip_path(path);
359        TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.valid))
360    }
361
362    fn mip_relevant(&self, path: &[String]) -> TypeValue {
363        let key = mip_path(path);
364        TypeValue::Boolean(self.mip_states.get(&key).is_none_or(|s| s.relevant))
365    }
366
367    fn mip_readonly(&self, path: &[String]) -> TypeValue {
368        let key = mip_path(path);
369        TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.readonly))
370    }
371
372    fn mip_required(&self, path: &[String]) -> TypeValue {
373        let key = mip_path(path);
374        TypeValue::Boolean(self.mip_states.get(&key).is_some_and(|s| s.required))
375    }
376
377    fn repeat_prev(&self) -> TypeValue {
378        if let Some(ctx) = &self.repeat_context
379            && ctx.index > 1
380        {
381            return ctx
382                .collection
383                .get(ctx.index - 2)
384                .cloned()
385                .unwrap_or(TypeValue::Null);
386        }
387        TypeValue::Null
388    }
389
390    fn repeat_next(&self) -> TypeValue {
391        if let Some(ctx) = &self.repeat_context
392            && ctx.index < ctx.count
393        {
394            return ctx
395                .collection
396                .get(ctx.index)
397                .cloned()
398                .unwrap_or(TypeValue::Null);
399        }
400        TypeValue::Null
401    }
402
403    fn repeat_parent(&self) -> TypeValue {
404        if let Some(ctx) = &self.repeat_context
405            && let Some(parent) = &ctx.parent
406        {
407            return parent.current.clone();
408        }
409        TypeValue::Null
410    }
411
412    fn current_date(&self) -> Result<TypeDate, MissingTimezoneContextError> {
413        // Delegate to current_datetime so the "is clock configured?" check
414        // has one source of truth (CODE-NIT N4 from fs-wbo9 review).
415        self.current_datetime().map(|dt| TypeDate::Date {
416            year: dt.year(),
417            month: dt.month(),
418            day: dt.day(),
419        })
420    }
421
422    fn current_datetime(&self) -> Result<TypeDate, MissingTimezoneContextError> {
423        self.current_datetime
424            .clone()
425            .ok_or_else(MissingTimezoneContextError::not_configured)
426    }
427
428    fn locale(&self) -> Option<&str> {
429        self.locale.as_deref()
430    }
431
432    fn date_format(&self, style: &str) -> Option<&str> {
433        self.date_formats.get(style).map(String::as_str)
434    }
435
436    fn runtime_meta(&self, key: &str) -> TypeValue {
437        self.meta.get(key).cloned().unwrap_or(TypeValue::Null)
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    #![allow(clippy::missing_docs_in_private_items)]
444    use super::*;
445    use indexmap::IndexMap;
446
447    fn s(v: &str) -> TypeValue {
448        TypeValue::String(v.to_string())
449    }
450
451    fn num(n: i64) -> TypeValue {
452        TypeValue::Number(Decimal::from(n))
453    }
454
455    #[test]
456    fn test_basic_field_resolution() {
457        let mut env = FormspecEnvironment::new();
458        env.set_field("name", s("Alice"));
459        env.set_field("age", num(30));
460
461        assert_eq!(env.resolve_field(&["name".into()]), s("Alice"));
462        assert_eq!(env.resolve_field(&["age".into()]), num(30));
463        assert_eq!(env.resolve_field(&["missing".into()]), TypeValue::Null);
464    }
465
466    #[test]
467    fn test_nested_field_resolution() {
468        let mut env = FormspecEnvironment::new();
469        let addr = TypeValue::Object(IndexMap::from([
470            ("city".to_string(), s("NYC")),
471            ("zip".to_string(), s("10001")),
472        ]));
473        env.set_field("address", addr);
474
475        assert_eq!(
476            env.resolve_field(&["address".into(), "city".into()]),
477            s("NYC")
478        );
479        assert_eq!(
480            env.resolve_field(&["address".into(), "missing".into()]),
481            TypeValue::Null
482        );
483    }
484
485    #[test]
486    fn test_repeat_field_projection_from_flat_rows() {
487        let mut env = FormspecEnvironment::new();
488        env.set_field("rows[0].score", num(80));
489        env.set_field("rows[1].score", num(30));
490        env.set_field("rows[2].score", num(50));
491
492        assert_eq!(
493            env.resolve_field(&["rows".into(), "score".into()]),
494            TypeValue::Array(vec![num(80), num(30), num(50)]),
495        );
496    }
497
498    #[test]
499    fn test_repeat_context() {
500        let mut env = FormspecEnvironment::new();
501        let items = vec![num(10), num(20), num(30)];
502        env.push_repeat(num(20), 2, 3, items);
503
504        // @current
505        assert_eq!(env.resolve_context("current", None, &[]), num(20));
506        // @index (1-based)
507        assert_eq!(env.resolve_context("index", None, &[]), num(2));
508        // @count
509        assert_eq!(env.resolve_context("count", None, &[]), num(3));
510        // prev() — item at index 1 (0-indexed: 0)
511        assert_eq!(env.repeat_prev(), num(10));
512        // next() — item at index 3 (0-indexed: 2)
513        assert_eq!(env.repeat_next(), num(30));
514    }
515
516    #[test]
517    fn test_nested_repeat_context() {
518        let mut env = FormspecEnvironment::new();
519        let outer = vec![s("A"), s("B")];
520        env.push_repeat(s("A"), 1, 2, outer);
521
522        let inner = vec![num(1), num(2), num(3)];
523        env.push_repeat(num(2), 2, 3, inner);
524
525        // Inner context active
526        assert_eq!(env.resolve_context("current", None, &[]), num(2));
527        // parent() returns outer current
528        assert_eq!(env.repeat_parent(), s("A"));
529
530        env.pop_repeat();
531        // Outer context restored
532        assert_eq!(env.resolve_context("current", None, &[]), s("A"));
533    }
534
535    #[test]
536    fn test_named_instances() {
537        let mut env = FormspecEnvironment::new();
538        let config = TypeValue::Object(IndexMap::from([("maxRetries".to_string(), num(3))]));
539        env.set_instance("config", config);
540
541        assert_eq!(
542            env.resolve_context("instance", Some("config"), &["maxRetries".into()]),
543            num(3)
544        );
545        assert_eq!(
546            env.resolve_context("instance", Some("missing"), &[]),
547            TypeValue::Null
548        );
549    }
550
551    #[test]
552    fn test_variables() {
553        let mut env = FormspecEnvironment::new();
554        env.set_variable("total", num(100));
555
556        assert_eq!(env.resolve_context("total", None, &[]), num(100));
557    }
558
559    #[test]
560    fn test_mip_states() {
561        let mut env = FormspecEnvironment::new();
562        env.set_mip(
563            "email",
564            MipState {
565                valid: false,
566                relevant: true,
567                readonly: false,
568                required: true,
569            },
570        );
571
572        assert_eq!(env.mip_valid(&["email".into()]), TypeValue::Boolean(false));
573        assert_eq!(
574            env.mip_relevant(&["email".into()]),
575            TypeValue::Boolean(true)
576        );
577        assert_eq!(
578            env.mip_readonly(&["email".into()]),
579            TypeValue::Boolean(false)
580        );
581        assert_eq!(
582            env.mip_required(&["email".into()]),
583            TypeValue::Boolean(true)
584        );
585
586        // Default MIP for unknown fields
587        assert_eq!(env.mip_valid(&["unknown".into()]), TypeValue::Boolean(true));
588        assert_eq!(
589            env.mip_required(&["unknown".into()]),
590            TypeValue::Boolean(false)
591        );
592    }
593
594    #[test]
595    fn test_bare_dollar_in_repeat() {
596        let mut env = FormspecEnvironment::new();
597        let items = vec![num(10), num(20)];
598        env.push_repeat(num(10), 1, 2, items);
599
600        // Bare $ resolves to repeat context current
601        assert_eq!(env.resolve_field(&[]), num(10));
602    }
603}