Skip to main content

rustev_core/
expr.rs

1//! References, expressions and predicates of registry `rustev.exact/1`:
2//! typing (compile phase e) and evaluation (spec 002, 3.4 and 3.8).
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use rustev_contract::decimal::{ArithError, Decimal, Rounding};
7use rustev_contract::definition::{CmpOp, Expr, Literal, Predicate};
8use rustev_contract::time::{DurationMs, Timestamp};
9
10use crate::value::{Ty, Value};
11
12/// A parsed reference.
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
14pub enum Ref {
15    /// An input, optionally followed by a record field path
16    /// (`input:trip.dates/check_in`).
17    Input(String, Vec<String>),
18    Step(String),
19    /// A field path inside the current item of a per-item operator.
20    Item(Vec<String>),
21    /// The item bound to a fan-out instance key (projections only).
22    Bind(String),
23    Now,
24}
25
26impl Ref {
27    pub fn parse(s: &str) -> Result<Ref, String> {
28        if s == "now" {
29            return Ok(Ref::Now);
30        }
31        let (kind, rest) = s
32            .split_once(':')
33            .ok_or_else(|| format!("reference {s:?} has no kind"))?;
34        if rest.is_empty() {
35            return Err(format!("reference {s:?} names nothing"));
36        }
37        match kind {
38            "input" => {
39                let mut parts = rest.split('/');
40                let name = parts.next().unwrap_or_default().to_string();
41                let path: Vec<String> = parts.map(String::from).collect();
42                if name.is_empty() || path.iter().any(String::is_empty) {
43                    return Err(format!("reference {s:?} has an empty part"));
44                }
45                Ok(Ref::Input(name, path))
46            }
47            "step" => Ok(Ref::Step(rest.into())),
48            "bind" => Ok(Ref::Bind(rest.into())),
49            "item" => {
50                let path: Vec<String> = rest.split('.').map(String::from).collect();
51                if path.iter().any(String::is_empty) {
52                    return Err(format!("reference {s:?} has an empty field"));
53                }
54                Ok(Ref::Item(path))
55            }
56            _ => Err(format!("reference {s:?} has unknown kind {kind:?}")),
57        }
58    }
59}
60
61/// The type of a step's result as expressions see it.
62#[derive(Debug, Clone, PartialEq)]
63pub enum StepTy {
64    ModelRanking(u64),
65    Selection(Ty),
66    Exact(Ty),
67    /// A semantic value and its fan-out binds; exact expressions cannot read
68    /// it, only `weighted_rank@1` components and the policy can.
69    Semantic(crate::sem::SemKind, Vec<String>),
70}
71
72/// Types visible while typing an expression.
73pub struct TyEnv<'a> {
74    pub inputs: &'a BTreeMap<String, Ty>,
75    pub steps: &'a BTreeMap<String, StepTy>,
76    pub item: Option<&'a Ty>,
77    /// A version 2 definition: step references may carry a field path
78    /// (`step:<id>/<field>`) and item paths may use `/` (spec 032, 3.4.4
79    /// and 3.5.4). Version 2 step ids and field names hold no `/` or `.`.
80    pub v2: bool,
81}
82
83/// A version 2 step reference's id and field path.
84pub fn split_step(s: &str) -> (String, Vec<String>) {
85    let mut parts = s.split('/');
86    let id = parts.next().unwrap_or_default().to_string();
87    (id, parts.map(String::from).collect())
88}
89
90/// A version 2 item path, with `/` as well as `.` separating fields.
91pub fn split_item(path: Vec<String>) -> Vec<String> {
92    path.iter()
93        .flat_map(|p| p.split('/').map(String::from))
94        .collect()
95}
96
97/// The dependency a reference names: `input:<name>` or `step:<id>` without
98/// any field path.
99pub fn base_ref(r: &str) -> String {
100    match r.strip_prefix("input:") {
101        Some(rest) => format!("input:{}", rest.split('/').next().unwrap_or_default()),
102        None => r.to_string(),
103    }
104}
105
106/// [`base_ref`] for a version 2 definition, whose step references may carry
107/// a field path.
108pub fn base_ref_v2(r: &str) -> String {
109    match r.strip_prefix("step:") {
110        Some(s) => format!("step:{}", split_step(s).0),
111        None => base_ref(r),
112    }
113}
114
115/// Every reference an expression or predicate reads, in reading order.
116pub fn expr_refs(e: &Expr, out: &mut Vec<String>) {
117    match e {
118        Expr::Ref(r) => out.push(r.clone()),
119        Expr::Lit(_) => {}
120        Expr::Add { left, right }
121        | Expr::Sub { left, right }
122        | Expr::Mul { left, right }
123        | Expr::Div { left, right } => {
124            expr_refs(left, out);
125            expr_refs(right, out);
126        }
127        Expr::Round { value, .. } | Expr::Len(value) | Expr::ToDecimal(value) => {
128            expr_refs(value, out)
129        }
130        Expr::Fx {
131            amount,
132            from,
133            to,
134            rates,
135            ..
136        } => {
137            expr_refs(amount, out);
138            expr_refs(from, out);
139            expr_refs(to, out);
140            out.push(rates.clone());
141        }
142        Expr::Graded { reference, .. } => out.push(reference.clone()),
143    }
144}
145
146pub fn predicate_refs(p: &Predicate, out: &mut Vec<String>) {
147    match p {
148        Predicate::Cmp { left, right, .. }
149        | Predicate::Under {
150            value: left,
151            ancestor: right,
152            ..
153        } => {
154            expr_refs(left, out);
155            expr_refs(right, out);
156        }
157        Predicate::All(ps) | Predicate::Any(ps) => ps.iter().for_each(|p| predicate_refs(p, out)),
158        Predicate::Not(p) => predicate_refs(p, out),
159        Predicate::Member { value, .. } => expr_refs(value, out),
160        Predicate::Present(r) | Predicate::IsConstructed { reference: r } => out.push(r.clone()),
161        Predicate::MemberRef { value, set } => {
162            expr_refs(value, out);
163            out.push(set.clone());
164        }
165    }
166}
167
168/// Whether an expression uses a construct of `rustev.exact/2` that a
169/// version 1 definition cannot carry (spec 032, 3.1.3).
170pub fn expr_uses_v2(e: &Expr) -> bool {
171    match e {
172        Expr::Graded { .. } => true,
173        Expr::Ref(_) | Expr::Lit(_) => false,
174        Expr::Add { left, right }
175        | Expr::Sub { left, right }
176        | Expr::Mul { left, right }
177        | Expr::Div { left, right } => expr_uses_v2(left) || expr_uses_v2(right),
178        Expr::Round { value, .. } | Expr::Len(value) | Expr::ToDecimal(value) => {
179            expr_uses_v2(value)
180        }
181        Expr::Fx {
182            amount, from, to, ..
183        } => expr_uses_v2(amount) || expr_uses_v2(from) || expr_uses_v2(to),
184    }
185}
186
187/// Whether a predicate uses a construct of `rustev.exact/2`.
188pub fn predicate_uses_v2(p: &Predicate) -> bool {
189    match p {
190        Predicate::MemberRef { .. } | Predicate::IsConstructed { .. } | Predicate::Under { .. } => {
191            true
192        }
193        Predicate::Cmp { left, right, .. } => expr_uses_v2(left) || expr_uses_v2(right),
194        Predicate::All(ps) | Predicate::Any(ps) => ps.iter().any(predicate_uses_v2),
195        Predicate::Not(p) => predicate_uses_v2(p),
196        Predicate::Member { value, .. } => expr_uses_v2(value),
197        Predicate::Present(_) => false,
198    }
199}
200
201/// Structural checks of compile phase b: scales in range.
202pub fn expr_structure(e: &Expr) -> Result<(), String> {
203    match e {
204        Expr::Ref(_) | Expr::Lit(_) => Ok(()),
205        Expr::Add { left, right }
206        | Expr::Sub { left, right }
207        | Expr::Mul { left, right }
208        | Expr::Div { left, right } => {
209            expr_structure(left)?;
210            expr_structure(right)
211        }
212        Expr::Round { value, scale } => {
213            if *scale > 9 {
214                return Err(format!("scale {scale} exceeds 9"));
215            }
216            expr_structure(value)
217        }
218        Expr::Fx {
219            amount,
220            from,
221            to,
222            scale,
223            ..
224        } => {
225            if *scale > 9 {
226                return Err(format!("scale {scale} exceeds 9"));
227            }
228            expr_structure(amount)?;
229            expr_structure(from)?;
230            expr_structure(to)
231        }
232        Expr::Len(v) | Expr::ToDecimal(v) => expr_structure(v),
233        Expr::Graded { reference, .. } => match Ref::parse(reference)? {
234            Ref::Input(..) | Ref::Step(_) | Ref::Item(_) => Ok(()),
235            _ => Err(format!("a grade requirement reads {reference:?}")),
236        },
237    }
238}
239
240pub fn predicate_structure(p: &Predicate) -> Result<(), String> {
241    match p {
242        Predicate::Cmp { left, right, .. }
243        | Predicate::Under {
244            value: left,
245            ancestor: right,
246            ..
247        } => {
248            expr_structure(left)?;
249            expr_structure(right)
250        }
251        Predicate::All(ps) | Predicate::Any(ps) => ps.iter().try_for_each(predicate_structure),
252        Predicate::Not(p) => predicate_structure(p),
253        Predicate::Member { value, set } => {
254            if set.is_empty() {
255                return Err("member set is empty".into());
256            }
257            expr_structure(value)
258        }
259        Predicate::IsConstructed { reference } => Ref::parse(reference).map(|_| ()),
260        Predicate::Present(r) => match Ref::parse(r)? {
261            Ref::Step(s) if !s.contains('/') => Ok(()),
262            Ref::Input(_, p) if p.is_empty() => Ok(()),
263            _ => Err(format!(
264                "present() takes an input or a bare step reference, not {r:?}"
265            )),
266        },
267        Predicate::MemberRef { value, set } => {
268            expr_structure(value)?;
269            match Ref::parse(set)? {
270                Ref::Input(..) | Ref::Step(_) => Ok(()),
271                _ => Err(format!("member_ref set {set:?} must be an input or step")),
272            }
273        }
274    }
275}
276
277fn field_ty<'t>(ty: &'t Ty, path: &[String]) -> Result<&'t Ty, String> {
278    field_ty_mode(ty, path, false)
279}
280
281fn field_ty_mode<'t>(
282    ty: &'t Ty,
283    path: &[String],
284    preserve_nullable: bool,
285) -> Result<&'t Ty, String> {
286    let unwrap = |t: &'t Ty| match t {
287        // Reading a nullable field yields its type; `null` is missing.
288        Ty::Nullable(inner) => inner.as_ref(),
289        t => t,
290    };
291    // A root is never nullable (`nullable` is a record field type only,
292    // spec 032 3.4.1), so only a field read is unwrapped.
293    let mut cur = ty;
294    for (index, f) in path.iter().enumerate() {
295        if f.is_empty() {
296            return Err("a path has an empty field name".into());
297        }
298        match cur {
299            Ty::Record(fields) => {
300                cur = fields
301                    .iter()
302                    .find(|(n, _)| n == f)
303                    .map(|(_, t)| t)
304                    .ok_or_else(|| format!("no field {f:?}"))?;
305                if !preserve_nullable || index + 1 < path.len() {
306                    cur = unwrap(cur);
307                }
308            }
309            other => return Err(format!("{} has no field {f:?}", other.name())),
310        }
311    }
312    Ok(cur)
313}
314
315/// Plan 3 acquired-key projection (spec 036 acceptance): one list of
316/// records becomes a bounded text list. Metadata uses the same `*` path.
317fn step_field_ty(ty: &Ty, path: &[String]) -> Result<Ty, String> {
318    let Some(index) = path.iter().position(|p| p == "*") else {
319        return field_ty(ty, path).cloned();
320    };
321    let Ty::List { item, max } = field_ty(ty, &path[..index])? else {
322        return Err("text projection requires a list of records".into());
323    };
324    if !matches!(item.as_ref(), Ty::Record(_)) || index + 1 == path.len() {
325        return Err("text projection requires a record field".into());
326    }
327    let projected = field_ty(item, &path[index + 1..])?;
328    if !matches!(projected, Ty::Text { .. }) {
329        return Err("text projection requires a text field".into());
330    }
331    Ok(Ty::List {
332        item: Box::new(projected.clone()),
333        max: *max,
334    })
335}
336
337/// The type of a reference, or a kind mismatch.
338pub fn ref_ty(r: &str, env: &TyEnv<'_>) -> Result<Ty, String> {
339    match Ref::parse(r)? {
340        Ref::Input(n, path) => {
341            let t = env
342                .inputs
343                .get(&n)
344                .ok_or_else(|| format!("unknown input {n:?}"))?;
345            field_ty(t, &path).cloned()
346        }
347        Ref::Step(s) => {
348            let (s, path) = if env.v2 { split_step(&s) } else { (s, vec![]) };
349            if s.is_empty() {
350                return Err(format!("{r:?} names no step"));
351            }
352            match env.steps.get(&s) {
353                Some(StepTy::Exact(t)) => step_field_ty(t, &path),
354                Some(StepTy::Selection(ty)) if path.is_empty() => Ok(ty.clone()),
355                Some(StepTy::Selection(_)) | Some(StepTy::ModelRanking(_)) => {
356                    Err("ranking value kind cannot be read here".into())
357                }
358                Some(StepTy::Semantic(..)) => Err(format!(
359                    "step {s:?} is semantic; exact operators cannot read it"
360                )),
361                None => Err(format!("unknown step {s:?}")),
362            }
363        }
364        Ref::Item(path) => {
365            let item = env
366                .item
367                .ok_or_else(|| format!("{r:?} outside a per-item operator"))?;
368            let path = if env.v2 { split_item(path) } else { path };
369            field_ty(item, &path).cloned()
370        }
371        Ref::Now => Ok(Ty::Timestamp),
372        Ref::Bind(_) => Err(format!("{r:?} is only valid in a projection")),
373    }
374}
375
376fn is_currency(t: &Ty) -> bool {
377    matches!(t, Ty::Text { .. } | Ty::Enum(_))
378}
379
380/// The static type of an expression (compile phase e). Values never convert
381/// silently: integer and decimal mix only through `to_decimal`.
382pub fn type_expr(e: &Expr, env: &TyEnv<'_>) -> Result<Ty, String> {
383    let bin = |l: &Expr, r: &Expr| -> Result<(Ty, Ty), String> {
384        Ok((type_expr(l, env)?, type_expr(r, env)?))
385    };
386    match e {
387        Expr::Ref(r) => ref_ty(r, env),
388        Expr::Lit(l) => Ok(Value::literal_ty(l)),
389        Expr::Add { left, right } => match bin(left, right)? {
390            (Ty::Integer, Ty::Integer) => Ok(Ty::Integer),
391            (Ty::Decimal, Ty::Decimal) => Ok(Ty::Decimal),
392            (Ty::Timestamp, Ty::Duration) => Ok(Ty::Timestamp),
393            (Ty::Duration, Ty::Duration) => Ok(Ty::Duration),
394            (a, b) => Err(format!("cannot add {} and {}", a.name(), b.name())),
395        },
396        Expr::Sub { left, right } => match bin(left, right)? {
397            (Ty::Integer, Ty::Integer) => Ok(Ty::Integer),
398            (Ty::Decimal, Ty::Decimal) => Ok(Ty::Decimal),
399            (Ty::Timestamp, Ty::Duration) => Ok(Ty::Timestamp),
400            (Ty::Timestamp, Ty::Timestamp) => Ok(Ty::Duration),
401            (Ty::Duration, Ty::Duration) => Ok(Ty::Duration),
402            (a, b) => Err(format!("cannot subtract {} from {}", b.name(), a.name())),
403        },
404        Expr::Mul { left, right } => match bin(left, right)? {
405            (Ty::Integer, Ty::Integer) => Ok(Ty::Integer),
406            (Ty::Decimal, Ty::Decimal) => Ok(Ty::Decimal),
407            (a, b) => Err(format!("cannot multiply {} by {}", a.name(), b.name())),
408        },
409        Expr::Div { left, right } => match bin(left, right)? {
410            (Ty::Decimal, Ty::Decimal) => Ok(Ty::Decimal),
411            (a, b) => Err(format!(
412                "cannot divide {} by {} (only decimals divide)",
413                a.name(),
414                b.name()
415            )),
416        },
417        Expr::Round { value, .. } => match type_expr(value, env)? {
418            Ty::Decimal => Ok(Ty::Decimal),
419            t => Err(format!("cannot round {}", t.name())),
420        },
421        Expr::Fx {
422            amount,
423            from,
424            to,
425            rates,
426            ..
427        } => {
428            if type_expr(amount, env)? != Ty::Decimal {
429                return Err("fx amount must be a decimal".into());
430            }
431            if !is_currency(&type_expr(from, env)?) || !is_currency(&type_expr(to, env)?) {
432                return Err("fx currencies must be text or enum".into());
433            }
434            match ref_ty(rates, env)? {
435                Ty::List { item, .. } => match item.as_ref() {
436                    Ty::Record(f)
437                        if f.iter().any(|(n, t)| n == "currency" && is_currency(t))
438                            && f.iter().any(|(n, t)| n == "rate" && *t == Ty::Decimal) =>
439                    {
440                        Ok(Ty::Decimal)
441                    }
442                    _ => Err(
443                        "fx rates must be a list of records with `currency` and decimal `rate`"
444                            .into(),
445                    ),
446                },
447                t => Err(format!("fx rates must be a list, not {}", t.name())),
448            }
449        }
450        Expr::Len(v) => match type_expr(v, env)? {
451            Ty::List { .. } => Ok(Ty::Integer),
452            t => Err(format!("len() of {}", t.name())),
453        },
454        Expr::ToDecimal(v) => match type_expr(v, env)? {
455            Ty::Integer => Ok(Ty::Decimal),
456            t => Err(format!("to_decimal() of {}", t.name())),
457        },
458        Expr::Graded { reference, .. } => ref_ty(reference, env),
459    }
460}
461
462fn literal_fits(l: &Literal, t: &Ty) -> bool {
463    match (l, t) {
464        (Literal::Enum(s), Ty::Enum(opts)) => opts.contains(s),
465        _ => Value::literal_ty(l).same_shape(t),
466    }
467}
468
469fn operand_fits(e: &Expr, t_other: &Ty, t_self: &Ty) -> bool {
470    match e {
471        Expr::Lit(l) => literal_fits(l, t_other),
472        _ => t_self.same_shape(t_other),
473    }
474}
475
476/// Validate segment ancestry operands in phase e, including policy positions.
477pub(crate) fn type_under(p: &Predicate, env: &TyEnv<'_>) -> Result<(), String> {
478    match p {
479        Predicate::Under { .. } => type_predicate(p, env),
480        Predicate::All(ps) | Predicate::Any(ps) => ps.iter().try_for_each(|p| type_under(p, env)),
481        Predicate::Not(p) => type_under(p, env),
482        _ => Ok(()),
483    }
484}
485
486pub fn type_predicate(p: &Predicate, env: &TyEnv<'_>) -> Result<(), String> {
487    match p {
488        Predicate::Under {
489            value, ancestor, ..
490        } => {
491            for (name, expr) in [("value", value), ("ancestor", ancestor)] {
492                let ty = type_expr(expr, env)?;
493                let declared = if let Expr::Ref(r) | Expr::Graded { reference: r, .. } = expr {
494                    match Ref::parse(r)? {
495                        Ref::Input(n, path) => Some(field_ty_mode(&env.inputs[&n], &path, true)?),
496                        Ref::Item(path) => {
497                            let path = if env.v2 { split_item(path) } else { path };
498                            Some(field_ty_mode(env.item.unwrap(), &path, true)?)
499                        }
500                        Ref::Step(s) => {
501                            let (s, path) = if env.v2 { split_step(&s) } else { (s, vec![]) };
502                            match env.steps.get(&s) {
503                                Some(StepTy::Exact(t)) => Some(field_ty_mode(t, &path, true)?),
504                                _ => None,
505                            }
506                        }
507                        _ => None,
508                    }
509                } else {
510                    None
511                };
512                if declared.is_some_and(|t| matches!(t, Ty::Nullable(_))) {
513                    return Err(format!("under {name} requires non-nullable text"));
514                }
515                if !matches!(ty, Ty::Text { .. }) {
516                    return Err(format!("under {name} requires text, got {}", ty.name()));
517                }
518            }
519            Ok(())
520        }
521        Predicate::Cmp { left, op, right } => {
522            let (lt, rt) = (type_expr(left, env)?, type_expr(right, env)?);
523            if matches!(lt, Ty::Maybe(_)) || matches!(rt, Ty::Maybe(_)) {
524                return Err("a maybe value cannot be compared".into());
525            }
526            if !(operand_fits(left, &rt, &lt) && operand_fits(right, &lt, &rt)) {
527                return Err(format!("cannot compare {} with {}", lt.name(), rt.name()));
528            }
529            let ordered = !matches!(op, CmpOp::Eq | CmpOp::Ne);
530            if ordered && !lt.is_orderable() {
531                return Err(format!("{} has no order", lt.name()));
532            }
533            if !ordered
534                && !matches!(
535                    lt,
536                    Ty::Bool
537                        | Ty::Integer
538                        | Ty::Decimal
539                        | Ty::Text { .. }
540                        | Ty::Enum(_)
541                        | Ty::Timestamp
542                        | Ty::Duration
543                )
544            {
545                return Err(format!("{} cannot be tested for equality", lt.name()));
546            }
547            Ok(())
548        }
549        Predicate::All(ps) | Predicate::Any(ps) => {
550            ps.iter().try_for_each(|p| type_predicate(p, env))
551        }
552        Predicate::Not(p) => type_predicate(p, env),
553        Predicate::Member { value, set } => {
554            let t = type_expr(value, env)?;
555            if set.iter().all(|l| literal_fits(l, &t)) {
556                Ok(())
557            } else {
558                Err(format!("member set does not match {}", t.name()))
559            }
560        }
561        Predicate::IsConstructed { reference } => ref_ty(reference, env).map(|_| ()),
562        Predicate::Present(r) => match Ref::parse(r)? {
563            Ref::Step(s) if env.v2 && !s.contains('/') => ref_ty(r, env).map(|_| ()),
564            Ref::Input(n, p) if p.is_empty() && env.inputs.contains_key(&n) => Ok(()),
565            _ => Err(format!("present() of unknown input {r:?}")),
566        },
567        Predicate::MemberRef { value, set } => {
568            let t = type_expr(value, env)?;
569            let textual = matches!(t, Ty::Text { .. } | Ty::Enum(_));
570            match ref_ty(set, env)? {
571                Ty::List { item, .. } if textual && item.same_shape(&t) => Ok(()),
572                // A map's keys are its members, never its values (spec 032,
573                // 3.7.2).
574                Ty::Map { .. } if textual => Ok(()),
575                s => Err(format!(
576                    "member_ref of {} in {}: the set is a list of text or enum values, or a map",
577                    t.name(),
578                    s.name()
579                )),
580            }
581        }
582    }
583}
584
585/// Why evaluation produced no value; becomes the step's unresolved reason.
586#[derive(Debug, Clone, PartialEq, Eq)]
587pub enum Fault {
588    /// Overflow, division by zero, an out-of-range timestamp.
589    Invalid(String),
590    /// A missing fact, e.g. `fx.rates.EUR`.
591    Missing(String),
592    /// Two different values for one fact.
593    Conflict(String),
594    /// A read of an absent value or a `null` field, naming its path
595    /// (spec 032, 3.4.4); only plan 3 values can be absent.
596    Absent(String),
597}
598
599impl From<ArithError> for Fault {
600    fn from(e: ArithError) -> Self {
601        Fault::Invalid(e.to_string())
602    }
603}
604
605/// Values visible while evaluating.
606pub struct Scope<'a> {
607    pub constructed: Option<&'a BTreeSet<String>>,
608    pub now: Timestamp,
609    pub inputs: &'a BTreeMap<String, Value>,
610    pub steps: &'a BTreeMap<String, Value>,
611    pub present: &'a BTreeSet<String>,
612    pub item: Option<&'a Value>,
613    /// See [`TyEnv::v2`].
614    pub v2: bool,
615}
616
617/// Reads `path` from `v`. A `null` or absent value on the way is missing
618/// evidence named by `name`. That includes the root: `field_ty` does not
619/// unwrap a root because no root is typed nullable (spec 032 3.4.1), so a
620/// null root can only be a fault, never a value.
621fn field<'v>(v: &'v Value, path: &[String], name: &dyn Fn() -> String) -> Result<&'v Value, Fault> {
622    let present = |v: &'v Value| match v {
623        Value::Null | Value::Absent(_) => Err(Fault::Absent(name())),
624        v => Ok(v),
625    };
626    let mut cur = present(v)?;
627    for f in path {
628        match cur {
629            Value::Record(m) => {
630                cur = present(
631                    m.get(f)
632                        .ok_or_else(|| Fault::Invalid(format!("no field {f:?}")))?,
633                )?
634            }
635            _ => return Err(Fault::Invalid(format!("no field {f:?}"))),
636        }
637    }
638    Ok(cur)
639}
640
641fn step_field(v: &Value, path: &[String], name: &dyn Fn() -> String) -> Result<Value, Fault> {
642    let Some(index) = path.iter().position(|p| p == "*") else {
643        return field(v, path, name).cloned();
644    };
645    let Value::List(items) = field(v, &path[..index], name)? else {
646        return Err(Fault::Invalid("text projection requires a list".into()));
647    };
648    items
649        .iter()
650        .map(|item| match field(item, &path[index + 1..], name)? {
651            Value::Text(text) => Ok(Value::Text(text.clone())),
652            _ => Err(Fault::Invalid(
653                "text projection requires a text field".into(),
654            )),
655        })
656        .collect::<Result<Vec<_>, _>>()
657        .map(Value::List)
658}
659
660pub fn eval_ref(r: &str, s: &Scope<'_>) -> Result<Value, Fault> {
661    match Ref::parse(r).map_err(Fault::Invalid)? {
662        Ref::Input(n, path) => {
663            let v = s.inputs.get(&n).ok_or_else(|| Fault::Missing(n.clone()))?;
664            field(v, &path, &|| {
665                [vec![n.clone()], path.clone()].concat().join("/")
666            })
667            .cloned()
668        }
669        Ref::Step(n) if s.v2 => {
670            let (id, path) = split_step(&n);
671            if id.is_empty() {
672                return Err(Fault::Invalid(format!("{r:?} names no step")));
673            }
674            let v = s.steps.get(&id).ok_or_else(|| Fault::Missing(id.clone()))?;
675            step_field(v, &path, &|| format!("step:{n}"))
676        }
677        Ref::Step(n) => s.steps.get(&n).cloned().ok_or(Fault::Missing(n)),
678        Ref::Item(path) => {
679            let item = s
680                .item
681                .ok_or_else(|| Fault::Invalid("no current item".into()))?;
682            let path = if s.v2 { split_item(path) } else { path };
683            // `Ref::parse` refuses a bare `item:`; the fallback keeps a
684            // missing-evidence name non-empty regardless.
685            let name = || {
686                if path.is_empty() {
687                    "item".to_string()
688                } else {
689                    path.join("/")
690                }
691            };
692            field(item, &path, &name).cloned()
693        }
694        Ref::Now => Ok(Value::Timestamp(s.now)),
695        Ref::Bind(b) => Err(Fault::Invalid(format!("bind:{b} outside a projection"))),
696    }
697}
698
699fn time_err(_: rustev_contract::time::TimeRangeError) -> Fault {
700    Fault::Invalid("timestamp or duration out of range".into())
701}
702
703fn rate(rates: &[Value], currency: &str, table: &str) -> Result<Decimal, Fault> {
704    let mut found: Option<Decimal> = None;
705    for r in rates {
706        let (Ok(Value::Text(c) | Value::Enum(c)), Ok(Value::Decimal(v))) = (
707            field(r, &["currency".into()], &String::new),
708            field(r, &["rate".into()], &String::new),
709        ) else {
710            continue;
711        };
712        if c == currency {
713            match found {
714                Some(prev) if prev != *v => {
715                    return Err(Fault::Conflict(format!("{table}.{currency}")));
716                }
717                _ => found = Some(*v),
718            }
719        }
720    }
721    found.ok_or_else(|| Fault::Missing(format!("{table}.{currency}")))
722}
723
724/// `amount / rate(from) * rate(to)`, each step half-even at 10^-9, then
725/// rescaled half-even to `scale` (`fx_convert@1`).
726pub fn fx(
727    amount: Decimal,
728    from: &str,
729    to: &str,
730    rates: &[Value],
731    table: &str,
732    scale: u32,
733) -> Result<Decimal, Fault> {
734    let rf = rate(rates, from, table)?;
735    let rt = rate(rates, to, table)?;
736    let base = amount.checked_div(rf, Rounding::HalfEven)?;
737    Ok(base
738        .checked_mul(rt, Rounding::HalfEven)?
739        .round_to_scale(scale, Rounding::HalfEven)?)
740}
741
742fn text_of(v: Value) -> Result<String, Fault> {
743    match v {
744        Value::Text(s) | Value::Enum(s) => Ok(s),
745        _ => Err(Fault::Invalid("expected text".into())),
746    }
747}
748
749pub fn eval_expr(e: &Expr, s: &Scope<'_>) -> Result<Value, Fault> {
750    let bin = |l: &Expr, r: &Expr| -> Result<(Value, Value), Fault> {
751        Ok((eval_expr(l, s)?, eval_expr(r, s)?))
752    };
753    let overflow = || Fault::Invalid("integer overflow".into());
754    match e {
755        Expr::Ref(r) => eval_ref(r, s),
756        Expr::Lit(l) => Ok(Value::from_literal(l)),
757        Expr::Add { left, right } => match bin(left, right)? {
758            (Value::Integer(a), Value::Integer(b)) => {
759                a.checked_add(b).map(Value::Integer).ok_or_else(overflow)
760            }
761            (Value::Decimal(a), Value::Decimal(b)) => Ok(Value::Decimal(a.checked_add(b)?)),
762            (Value::Timestamp(a), Value::Duration(b)) => {
763                a.checked_add(b).map(Value::Timestamp).map_err(time_err)
764            }
765            (Value::Duration(a), Value::Duration(b)) => {
766                a.0.checked_add(b.0)
767                    .map(|d| Value::Duration(DurationMs(d)))
768                    .ok_or_else(overflow)
769            }
770            _ => Err(Fault::Invalid("ill-typed add".into())),
771        },
772        Expr::Sub { left, right } => match bin(left, right)? {
773            (Value::Integer(a), Value::Integer(b)) => {
774                a.checked_sub(b).map(Value::Integer).ok_or_else(overflow)
775            }
776            (Value::Decimal(a), Value::Decimal(b)) => Ok(Value::Decimal(a.checked_sub(b)?)),
777            (Value::Timestamp(a), Value::Duration(b)) => {
778                a.checked_sub(b).map(Value::Timestamp).map_err(time_err)
779            }
780            (Value::Timestamp(a), Value::Timestamp(b)) => {
781                a.since(b).map(Value::Duration).map_err(time_err)
782            }
783            (Value::Duration(a), Value::Duration(b)) => {
784                a.0.checked_sub(b.0)
785                    .map(|d| Value::Duration(DurationMs(d)))
786                    .ok_or_else(|| Fault::Invalid("negative duration".into()))
787            }
788            _ => Err(Fault::Invalid("ill-typed sub".into())),
789        },
790        Expr::Mul { left, right } => match bin(left, right)? {
791            (Value::Integer(a), Value::Integer(b)) => {
792                a.checked_mul(b).map(Value::Integer).ok_or_else(overflow)
793            }
794            (Value::Decimal(a), Value::Decimal(b)) => {
795                Ok(Value::Decimal(a.checked_mul(b, Rounding::HalfEven)?))
796            }
797            _ => Err(Fault::Invalid("ill-typed mul".into())),
798        },
799        Expr::Div { left, right } => match bin(left, right)? {
800            (Value::Decimal(a), Value::Decimal(b)) => {
801                Ok(Value::Decimal(a.checked_div(b, Rounding::HalfEven)?))
802            }
803            _ => Err(Fault::Invalid("ill-typed div".into())),
804        },
805        Expr::Round { value, scale } => match eval_expr(value, s)? {
806            Value::Decimal(d) => Ok(Value::Decimal(
807                d.round_to_scale(*scale, Rounding::HalfEven)?,
808            )),
809            _ => Err(Fault::Invalid("ill-typed round".into())),
810        },
811        Expr::Fx {
812            amount,
813            from,
814            to,
815            rates,
816            scale,
817        } => {
818            let Value::Decimal(a) = eval_expr(amount, s)? else {
819                return Err(Fault::Invalid("ill-typed fx".into()));
820            };
821            let from = text_of(eval_expr(from, s)?)?;
822            let to = text_of(eval_expr(to, s)?)?;
823            let Value::List(table) = eval_ref(rates, s)? else {
824                return Err(Fault::Invalid("ill-typed fx rates".into()));
825            };
826            let name = rates.strip_prefix("input:").unwrap_or(rates);
827            Ok(Value::Decimal(fx(a, &from, &to, &table, name, *scale)?))
828        }
829        Expr::Len(v) => match eval_expr(v, s)? {
830            Value::Selection(s) => i64::try_from(s.entries.len())
831                .map(Value::Integer)
832                .map_err(|_| overflow()),
833            Value::List(items) => i64::try_from(items.len())
834                .map(Value::Integer)
835                .map_err(|_| overflow()),
836            _ => Err(Fault::Invalid("ill-typed len".into())),
837        },
838        Expr::ToDecimal(v) => match eval_expr(v, s)? {
839            Value::Integer(i) => Ok(Value::Decimal(Decimal::from_i64(i))),
840            _ => Err(Fault::Invalid("ill-typed to_decimal".into())),
841        },
842        // The grade requirement is checked by the evaluator before the
843        // expression is evaluated (spec 032, 3.9.1); the value is the
844        // reference's own.
845        Expr::Graded { reference, .. } => eval_ref(reference, s),
846    }
847}
848
849fn cmp_values(a: &Value, op: CmpOp, b: &Value) -> Result<bool, Fault> {
850    use std::cmp::Ordering;
851    let ord: Option<Ordering> = match (a, b) {
852        (Value::Integer(x), Value::Integer(y)) => Some(x.cmp(y)),
853        (Value::Decimal(x), Value::Decimal(y)) => Some(x.cmp(y)),
854        (Value::Timestamp(x), Value::Timestamp(y)) => Some(x.cmp(y)),
855        (Value::Duration(x), Value::Duration(y)) => Some(x.cmp(y)),
856        _ => None,
857    };
858    Ok(match (op, ord) {
859        (CmpOp::Eq, _) => {
860            a == b
861                || matches!((a, b), (Value::Text(x), Value::Text(y)) | (Value::Enum(x), Value::Enum(y)) if x == y)
862        }
863        (CmpOp::Ne, _) => a != b,
864        (CmpOp::Lt, Some(o)) => o == Ordering::Less,
865        (CmpOp::Le, Some(o)) => o != Ordering::Greater,
866        (CmpOp::Gt, Some(o)) => o == Ordering::Greater,
867        (CmpOp::Ge, Some(o)) => o != Ordering::Less,
868        _ => return Err(Fault::Invalid("ill-typed comparison".into())),
869    })
870}
871
872pub fn eval_predicate(p: &Predicate, s: &Scope<'_>) -> Result<bool, Fault> {
873    match p {
874        Predicate::Under {
875            value,
876            ancestor,
877            separator,
878        } => {
879            let value = eval_expr(value, s)?;
880            let ancestor = eval_expr(ancestor, s)?;
881            let sep = separator.as_byte();
882            for (name, operand) in [("value", &value), ("ancestor", &ancestor)] {
883                let Value::Text(text) = operand else {
884                    return Err(Fault::Invalid(format!("under {name} requires text")));
885                };
886                if text
887                    .as_bytes()
888                    .split(|b| *b == sep)
889                    .any(|part| part.is_empty())
890                {
891                    return Err(Fault::Invalid(format!("under {name} has an empty segment")));
892                }
893            }
894            let (Value::Text(value), Value::Text(ancestor)) = (value, ancestor) else {
895                unreachable!("validated text operands")
896            };
897            Ok(value
898                .as_bytes()
899                .strip_prefix(ancestor.as_bytes())
900                .is_some_and(|suffix| suffix.first() == Some(&sep)))
901        }
902        Predicate::Cmp { left, op, right } => {
903            cmp_values(&eval_expr(left, s)?, *op, &eval_expr(right, s)?)
904        }
905        Predicate::All(ps) => {
906            for p in ps {
907                if !eval_predicate(p, s)? {
908                    return Ok(false);
909                }
910            }
911            Ok(true)
912        }
913        Predicate::Any(ps) => {
914            for p in ps {
915                if eval_predicate(p, s)? {
916                    return Ok(true);
917                }
918            }
919            Ok(false)
920        }
921        Predicate::Not(p) => Ok(!eval_predicate(p, s)?),
922        Predicate::Member { value, set } => {
923            let v = eval_expr(value, s)?;
924            Ok(set.iter().any(|l| Value::from_literal(l) == v))
925        }
926        Predicate::IsConstructed { reference } => Ok(s
927            .constructed
928            .is_some_and(|set| set.contains(&base_ref_v2(reference)))
929            && eval_ref(reference, s).is_ok()),
930        Predicate::Present(r) if s.v2 => Ok(eval_ref(r, s).is_ok()),
931        Predicate::Present(r) => Ok(r
932            .strip_prefix("input:")
933            .is_some_and(|n| s.present.contains(n))),
934        Predicate::MemberRef { value, set } => {
935            let v = match eval_expr(value, s)? {
936                Value::Text(x) | Value::Enum(x) => x,
937                _ => return Err(Fault::Invalid("member_ref of a non-text value".into())),
938            };
939            match eval_ref(set, s)? {
940                Value::List(items) => Ok(items
941                    .iter()
942                    .any(|i| matches!(i, Value::Text(x) | Value::Enum(x) if *x == v))),
943                Value::Map(m) => Ok(m.contains_key(&v)),
944                _ => Err(Fault::Invalid("member_ref of a non-set".into())),
945            }
946        }
947    }
948}
949
950#[cfg(test)]
951mod tests {
952    use super::*;
953    use rustev_contract::definition::Literal as L;
954
955    fn dec(s: &str) -> Decimal {
956        Decimal::parse(s).unwrap()
957    }
958
959    fn rates(v: &[(&str, &str)]) -> Vec<Value> {
960        v.iter()
961            .map(|(c, r)| {
962                Value::Record(
963                    [
964                        ("currency".to_string(), Value::Text(c.to_string())),
965                        ("rate".to_string(), Value::Decimal(dec(r))),
966                    ]
967                    .into(),
968                )
969            })
970            .collect()
971    }
972
973    #[test]
974    fn plan_three_text_projection_checks_bounds_types_and_absence() {
975        let text = Ty::Text { max_bytes: 32 };
976        let records = Ty::List {
977            item: Box::new(Ty::Record(vec![
978                ("key".into(), text.clone()),
979                ("count".into(), Ty::Integer),
980            ])),
981            max: 4,
982        };
983        let ty = Ty::Record(vec![("items".into(), records)]);
984        let path: Vec<String> = ["items", "*", "key"].map(String::from).into();
985        assert_eq!(
986            step_field_ty(&ty, &path).unwrap(),
987            Ty::List {
988                item: Box::new(text),
989                max: 4
990            }
991        );
992        for p in [
993            vec!["items", "*", "count"],
994            vec!["items", "*", "unknown"],
995            vec!["items", "*"],
996            vec!["*", "key"],
997            vec!["items", "*", "key", "*", "x"],
998        ] {
999            assert!(
1000                step_field_ty(&ty, &p.into_iter().map(String::from).collect::<Vec<_>>()).is_err()
1001            );
1002        }
1003        let inputs = BTreeMap::new();
1004        let steps = BTreeMap::from([("lookup".into(), StepTy::Exact(ty))]);
1005        let mut env = TyEnv {
1006            inputs: &inputs,
1007            steps: &steps,
1008            item: None,
1009            v2: true,
1010        };
1011        assert!(ref_ty("step:lookup/items/*/key", &env).is_ok());
1012        env.v2 = false;
1013        assert!(ref_ty("step:lookup/items/*/key", &env).is_err());
1014        let value = |keys: Vec<Value>| {
1015            Value::Record(BTreeMap::from([(
1016                "items".into(),
1017                Value::List(
1018                    keys.into_iter()
1019                        .map(|key| Value::Record(BTreeMap::from([("key".into(), key)])))
1020                        .collect(),
1021                ),
1022            )]))
1023        };
1024        let keys = vec![
1025            Value::Text("b".into()),
1026            Value::Text("a".into()),
1027            Value::Text("b".into()),
1028        ];
1029        assert_eq!(
1030            step_field(&value(keys.clone()), &path, &|| "lookup".into()).unwrap(),
1031            Value::List(keys)
1032        );
1033        assert_eq!(
1034            step_field(&value(vec![]), &path, &|| "lookup".into()).unwrap(),
1035            Value::List(vec![])
1036        );
1037        assert!(matches!(
1038            step_field(&value(vec![Value::Null]), &path, &|| "lookup/key".into()),
1039            Err(Fault::Absent(_))
1040        ));
1041    }
1042
1043    #[test]
1044    fn fx_converts_through_the_base_and_rounds_half_even() {
1045        let t = rates(&[("USD", "1"), ("EUR", "0.8"), ("JPY", "150")]);
1046        assert_eq!(fx(dec("100"), "EUR", "USD", &t, "fx", 2), Ok(dec("125")));
1047        assert_eq!(fx(dec("1"), "USD", "JPY", &t, "fx", 0), Ok(dec("150")));
1048        // 0.125 at scale 2 is a tie: half-even gives 0.12; 0.135 gives 0.14.
1049        let t2 = rates(&[("A", "1"), ("B", "0.125"), ("C", "0.135")]);
1050        assert_eq!(fx(dec("1"), "A", "B", &t2, "fx", 2), Ok(dec("0.12")));
1051        assert_eq!(fx(dec("1"), "A", "C", &t2, "fx", 2), Ok(dec("0.14")));
1052    }
1053
1054    #[test]
1055    fn fx_missing_conflicting_and_zero_rates_are_faults() {
1056        let t = rates(&[("USD", "1"), ("EUR", "0.8"), ("EUR", "0.9"), ("ZZZ", "0")]);
1057        assert_eq!(
1058            fx(dec("1"), "GBP", "USD", &t, "fx", 2),
1059            Err(Fault::Missing("fx.GBP".into()))
1060        );
1061        assert_eq!(
1062            fx(dec("1"), "EUR", "USD", &t, "fx", 2),
1063            Err(Fault::Conflict("fx.EUR".into()))
1064        );
1065        assert!(matches!(
1066            fx(dec("1"), "ZZZ", "USD", &t, "fx", 2),
1067            Err(Fault::Invalid(_))
1068        ));
1069        // Duplicate but equal rates are not a conflict.
1070        let same = rates(&[("USD", "1"), ("EUR", "0.8"), ("EUR", "0.8")]);
1071        assert!(fx(dec("1"), "EUR", "USD", &same, "fx", 2).is_ok());
1072    }
1073
1074    #[test]
1075    fn arithmetic_overflow_is_a_fault_not_a_wrap() {
1076        let inputs = BTreeMap::new();
1077        let steps = BTreeMap::new();
1078        let present = BTreeSet::new();
1079        let s = Scope {
1080            constructed: None,
1081            now: Timestamp::from_ms(0).unwrap(),
1082            inputs: &inputs,
1083            steps: &steps,
1084            present: &present,
1085            item: None,
1086            v2: false,
1087        };
1088        let big = Expr::Lit(L::Integer(i64::MAX));
1089        let add = Expr::Add {
1090            left: Box::new(big.clone()),
1091            right: Box::new(Expr::Lit(L::Integer(1))),
1092        };
1093        assert!(matches!(eval_expr(&add, &s), Err(Fault::Invalid(_))));
1094        let div0 = Expr::Div {
1095            left: Box::new(Expr::Lit(L::Decimal(dec("1")))),
1096            right: Box::new(Expr::Lit(L::Decimal(dec("0")))),
1097        };
1098        assert!(matches!(eval_expr(&div0, &s), Err(Fault::Invalid(_))));
1099        let back = Expr::Sub {
1100            left: Box::new(Expr::Ref("now".into())),
1101            right: Box::new(Expr::Lit(L::DurationMs(1))),
1102        };
1103        assert!(matches!(eval_expr(&back, &s), Err(Fault::Invalid(_))));
1104        // Negative control: in-range arithmetic succeeds.
1105        let ok = Expr::Add {
1106            left: Box::new(Expr::Lit(L::Integer(1))),
1107            right: Box::new(Expr::Lit(L::Integer(1))),
1108        };
1109        assert_eq!(eval_expr(&ok, &s), Ok(Value::Integer(2)));
1110    }
1111
1112    #[test]
1113    fn an_empty_field_name_in_a_path_is_refused() {
1114        let rec = Ty::Record(vec![("a".into(), Ty::Integer)]);
1115        assert_eq!(field_ty(&rec, &["a".into()]), Ok(&Ty::Integer));
1116        let e = field_ty(&rec, &["".into(), "a".into()]).unwrap_err();
1117        assert!(e.contains("empty field name"), "{e}");
1118    }
1119
1120    #[test]
1121    fn version_2_step_paths_split_at_the_step_id() {
1122        assert_eq!(
1123            split_step("join/match/total"),
1124            (
1125                "join".to_string(),
1126                vec!["match".to_string(), "total".to_string()]
1127            )
1128        );
1129        assert_eq!(split_step("plain"), ("plain".to_string(), vec![]));
1130        // `Ref::parse` takes a step reference whole, so a version 2 path
1131        // with an empty id is refused where it is split.
1132        assert!(Ref::parse("step:/a").is_ok());
1133        let inputs = BTreeMap::new();
1134        let steps = BTreeMap::from([("".to_string(), StepTy::Exact(Ty::Bool))]);
1135        let env = TyEnv {
1136            inputs: &inputs,
1137            steps: &steps,
1138            item: None,
1139            v2: true,
1140        };
1141        let e = ref_ty("step:/a", &env).unwrap_err();
1142        assert!(e.contains("names no step"), "{e}");
1143        let values = BTreeMap::from([("".to_string(), Value::Bool(true))]);
1144        let present = BTreeSet::new();
1145        let s = Scope {
1146            constructed: None,
1147            now: Timestamp::from_ms(0).unwrap(),
1148            inputs: &BTreeMap::new(),
1149            steps: &values,
1150            present: &present,
1151            item: None,
1152            v2: true,
1153        };
1154        assert!(
1155            matches!(eval_ref("step:/a", &s), Err(Fault::Invalid(e)) if e.contains("names no step"))
1156        );
1157        assert_eq!(base_ref_v2("step:join/match"), "step:join");
1158        assert_eq!(base_ref_v2("input:a/b"), "input:a");
1159        // Version 1 keeps a step reference whole.
1160        assert_eq!(base_ref("step:join/match"), "step:join/match");
1161        assert_eq!(
1162            split_item(vec!["match/total".into(), "unit".into()]),
1163            vec!["match", "total", "unit"]
1164        );
1165    }
1166
1167    #[test]
1168    fn member_ref_of_a_map_tests_its_keys() {
1169        let map_ty = Ty::Map {
1170            key_max: 8,
1171            value: Box::new(Ty::Text { max_bytes: 8 }),
1172            max: 4,
1173        };
1174        let tys = BTreeMap::from([
1175            ("codes".to_string(), map_ty),
1176            (
1177                "tier".to_string(),
1178                Ty::Enum(vec!["gold".into(), "eu".into()]),
1179            ),
1180            ("n".to_string(), Ty::Integer),
1181        ]);
1182        let step_tys = BTreeMap::new();
1183        let env = TyEnv {
1184            inputs: &tys,
1185            steps: &step_tys,
1186            item: None,
1187            v2: true,
1188        };
1189        let member = |value: &str| Predicate::MemberRef {
1190            value: Expr::Ref(value.into()),
1191            set: "input:codes".into(),
1192        };
1193        assert!(type_predicate(&member("input:tier"), &env).is_ok());
1194        assert!(
1195            type_predicate(&member("input:n"), &env).is_err(),
1196            "a non-text value"
1197        );
1198
1199        let inputs = BTreeMap::from([
1200            (
1201                "codes".to_string(),
1202                Value::Map(BTreeMap::from([(
1203                    "eu".to_string(),
1204                    Value::Text("gold".into()),
1205                )])),
1206            ),
1207            ("tier".to_string(), Value::Enum("eu".into())),
1208            ("other".to_string(), Value::Enum("gold".into())),
1209        ]);
1210        let steps = BTreeMap::new();
1211        let present = BTreeSet::new();
1212        let s = Scope {
1213            constructed: None,
1214            now: Timestamp::from_ms(0).unwrap(),
1215            inputs: &inputs,
1216            steps: &steps,
1217            present: &present,
1218            item: None,
1219            v2: true,
1220        };
1221        assert_eq!(eval_predicate(&member("input:tier"), &s), Ok(true));
1222        assert_eq!(
1223            eval_predicate(&member("input:other"), &s),
1224            Ok(false),
1225            "a map's values are not its members"
1226        );
1227    }
1228
1229    #[test]
1230    fn a_reference_that_names_nothing_is_refused() {
1231        for r in ["item:", "input:", "step:", "bind:"] {
1232            assert!(Ref::parse(r).is_err(), "{r}");
1233        }
1234        let item = Value::Null;
1235        let inputs = BTreeMap::new();
1236        let steps = BTreeMap::new();
1237        let present = BTreeSet::new();
1238        let s = Scope {
1239            constructed: None,
1240            now: Timestamp::from_ms(0).unwrap(),
1241            inputs: &inputs,
1242            steps: &steps,
1243            present: &present,
1244            item: Some(&item),
1245            v2: true,
1246        };
1247        assert_eq!(eval_ref("item:a", &s), Err(Fault::Absent("a".into())));
1248    }
1249
1250    #[test]
1251    fn integers_and_decimals_do_not_mix_silently() {
1252        let inputs = BTreeMap::new();
1253        let steps = BTreeMap::new();
1254        let env = TyEnv {
1255            inputs: &inputs,
1256            steps: &steps,
1257            item: None,
1258            v2: false,
1259        };
1260        let mixed = Expr::Add {
1261            left: Box::new(Expr::Lit(L::Integer(1))),
1262            right: Box::new(Expr::Lit(L::Decimal(dec("1")))),
1263        };
1264        assert!(type_expr(&mixed, &env).is_err());
1265        let explicit = Expr::Add {
1266            left: Box::new(Expr::ToDecimal(Box::new(Expr::Lit(L::Integer(1))))),
1267            right: Box::new(Expr::Lit(L::Decimal(dec("1")))),
1268        };
1269        assert_eq!(type_expr(&explicit, &env), Ok(Ty::Decimal));
1270        let int_div = Expr::Div {
1271            left: Box::new(Expr::Lit(L::Integer(1))),
1272            right: Box::new(Expr::Lit(L::Integer(1))),
1273        };
1274        assert!(type_expr(&int_div, &env).is_err());
1275    }
1276
1277    #[test]
1278    fn enum_literals_must_be_declared_options() {
1279        let inputs: BTreeMap<String, Ty> = [(
1280            "tier".to_string(),
1281            Ty::Enum(vec!["free".into(), "enterprise".into()]),
1282        )]
1283        .into();
1284        let steps = BTreeMap::new();
1285        let env = TyEnv {
1286            inputs: &inputs,
1287            steps: &steps,
1288            item: None,
1289            v2: false,
1290        };
1291        let ok = Predicate::Cmp {
1292            left: Expr::Ref("input:tier".into()),
1293            op: CmpOp::Eq,
1294            right: Expr::Lit(L::Enum("enterprise".into())),
1295        };
1296        assert!(type_predicate(&ok, &env).is_ok());
1297        let bad = Predicate::Cmp {
1298            left: Expr::Ref("input:tier".into()),
1299            op: CmpOp::Eq,
1300            right: Expr::Lit(L::Enum("gold".into())),
1301        };
1302        assert!(type_predicate(&bad, &env).is_err());
1303        let text = Predicate::Cmp {
1304            left: Expr::Ref("input:tier".into()),
1305            op: CmpOp::Eq,
1306            right: Expr::Lit(L::Text("enterprise".into())),
1307        };
1308        assert!(type_predicate(&text, &env).is_err(), "text is not an enum");
1309        let ordered = Predicate::Cmp {
1310            left: Expr::Ref("input:tier".into()),
1311            op: CmpOp::Lt,
1312            right: Expr::Lit(L::Enum("free".into())),
1313        };
1314        assert!(
1315            type_predicate(&ordered, &env).is_err(),
1316            "enums have no order"
1317        );
1318    }
1319
1320    #[test]
1321    fn references_parse_strictly() {
1322        assert_eq!(
1323            Ref::parse("input:a.b"),
1324            Ok(Ref::Input("a.b".into(), vec![]))
1325        );
1326        assert_eq!(
1327            Ref::parse("input:a.b/c/d"),
1328            Ok(Ref::Input("a.b".into(), vec!["c".into(), "d".into()]))
1329        );
1330        assert_eq!(
1331            Ref::parse("item:price.amount"),
1332            Ok(Ref::Item(vec!["price".into(), "amount".into()]))
1333        );
1334        assert_eq!(Ref::parse("now"), Ok(Ref::Now));
1335        for bad in [
1336            "",
1337            "input:",
1338            "x:y",
1339            "item:a..b",
1340            "plain",
1341            "input:a//b",
1342            "input:/b",
1343        ] {
1344            assert!(Ref::parse(bad).is_err(), "{bad:?}");
1345        }
1346    }
1347}