Skip to main content

domainforge_core/projection/lean/
expr.rs

1//! Lowers `policy::Expression` into Lean 4 propositions.
2//!
3//! Every policy is classified as either *groundable* — fully evaluable over
4//! the declared model, emitted with a `by decide` proof — or *deferred*,
5//! emitted as a documented proof obligation stub. The Rust evaluator here
6//! evaluates exactly the semantics that get emitted to Lean (same scaled
7//! integers, same operators), so a `decide` proof emitted as "holds" is
8//! guaranteed to check.
9
10use crate::policy::{BinaryOp, Expression, Quantifier, UnaryOp};
11use rust_decimal::Decimal;
12
13/// Result of lowering one policy expression.
14pub enum Lowered {
15    /// A well-formed Lean `Prop`, plus whether the declared model satisfies it.
16    Groundable { lean: String, holds: bool },
17    /// Not auto-groundable in v1; becomes a proof obligation stub.
18    Deferred { reason: String },
19}
20
21/// Ground context shared by all policies of one model.
22pub struct GroundCtx {
23    /// Shared decimal scale `k`: every quantity is an integer `value × 10⁻ᵏ`.
24    pub scale: u32,
25    /// Scaled flow quantities, in the same order as the emitted `flows` list.
26    /// `None` when the model emits no `flows` definition (flow-referencing
27    /// policies must then defer).
28    pub flow_quantities: Option<Vec<i128>>,
29}
30
31#[derive(Clone, Copy, PartialEq, Debug)]
32enum Kind {
33    Num,
34    Str,
35    Prop,
36}
37
38#[derive(Clone, PartialEq, Debug)]
39enum V {
40    N(i128),
41    S(String),
42    P(bool),
43}
44
45pub fn lower_policy(expr: &Expression, ctx: &GroundCtx) -> Lowered {
46    let (body, kind) = match render(expr, ctx) {
47        Ok(r) => r,
48        Err(reason) => return Lowered::Deferred { reason },
49    };
50    if kind != Kind::Prop {
51        return Lowered::Deferred {
52            reason: "expression is not a proposition".to_string(),
53        };
54    }
55    if uses_flow(expr) {
56        let Some(quantities) = &ctx.flow_quantities else {
57            return Lowered::Deferred {
58                reason: "references Flow.quantity but the model declares no flows".to_string(),
59            };
60        };
61        let mut holds = true;
62        for q in quantities {
63            match eval(expr, ctx, Some(*q)) {
64                Ok(V::P(b)) => holds &= b,
65                Ok(_) => unreachable!("render checked Prop kind"),
66                Err(reason) => return Lowered::Deferred { reason },
67            }
68        }
69        Lowered::Groundable {
70            lean: format!("∀ f ∈ flows, {body}"),
71            holds,
72        }
73    } else {
74        match eval(expr, ctx, None) {
75            Ok(V::P(holds)) => Lowered::Groundable { lean: body, holds },
76            Ok(_) => unreachable!("render checked Prop kind"),
77            Err(reason) => Lowered::Deferred { reason },
78        }
79    }
80}
81
82/// Collect every decimal literal in an expression (for shared-scale computation).
83pub fn collect_decimals(expr: &Expression, out: &mut Vec<Decimal>) {
84    match expr {
85        Expression::Literal(serde_json::Value::Number(n)) => {
86            if let Ok(d) = n.to_string().parse::<Decimal>() {
87                out.push(d);
88            }
89        }
90        Expression::QuantityLiteral { value, .. } => out.push(*value),
91        Expression::Binary { left, right, .. } => {
92            collect_decimals(left, out);
93            collect_decimals(right, out);
94        }
95        Expression::Unary { operand, .. } | Expression::Cast { operand, .. } => {
96            collect_decimals(operand, out);
97        }
98        Expression::Quantifier {
99            collection,
100            condition,
101            ..
102        } => {
103            collect_decimals(collection, out);
104            collect_decimals(condition, out);
105        }
106        _ => {}
107    }
108}
109
110/// Scale a decimal to the shared integer scale `k`.
111pub fn scaled(d: Decimal, k: u32) -> Result<i128, String> {
112    let d = d.normalize();
113    if d.scale() > k {
114        return Err(format!("decimal {d} exceeds shared scale {k}"));
115    }
116    let factor = 10i128
117        .checked_pow(k - d.scale())
118        .ok_or_else(|| format!("scale {k} too large"))?;
119    d.mantissa()
120        .checked_mul(factor)
121        .ok_or_else(|| format!("scaled value of {d} overflows"))
122}
123
124fn uses_flow(expr: &Expression) -> bool {
125    match expr {
126        Expression::MemberAccess { object, member } => object == "Flow" && member == "quantity",
127        Expression::Binary { left, right, .. } => uses_flow(left) || uses_flow(right),
128        Expression::Unary { operand, .. } => uses_flow(operand),
129        _ => false,
130    }
131}
132
133fn escape_lean_string(s: &str) -> String {
134    s.replace('\\', "\\\\").replace('"', "\\\"")
135}
136
137fn numeral(v: i128) -> String {
138    if v < 0 {
139        format!("({v})")
140    } else {
141        v.to_string()
142    }
143}
144
145fn defer_op(op: &BinaryOp) -> String {
146    format!("uses operator {op:?} (not auto-groundable in v1)")
147}
148
149/// Render to a Lean term. The string is flow-independent (`Flow.quantity`
150/// renders as the bound variable `f.quantity`).
151fn render(expr: &Expression, ctx: &GroundCtx) -> Result<(String, Kind), String> {
152    match expr {
153        Expression::Literal(v) => match v {
154            serde_json::Value::Bool(true) => Ok(("True".to_string(), Kind::Prop)),
155            serde_json::Value::Bool(false) => Ok(("False".to_string(), Kind::Prop)),
156            serde_json::Value::Number(n) => {
157                let d = n
158                    .to_string()
159                    .parse::<Decimal>()
160                    .map_err(|e| format!("unsupported numeric literal {n}: {e}"))?;
161                Ok((numeral(scaled(d, ctx.scale)?), Kind::Num))
162            }
163            serde_json::Value::String(s) => {
164                Ok((format!("\"{}\"", escape_lean_string(s)), Kind::Str))
165            }
166            other => Err(format!("unsupported literal {other} (not auto-groundable)")),
167        },
168        Expression::QuantityLiteral { value, .. } => {
169            Ok((numeral(scaled(*value, ctx.scale)?), Kind::Num))
170        }
171        Expression::MemberAccess { object, member } => {
172            if object == "Flow" && member == "quantity" {
173                Ok(("f.quantity".to_string(), Kind::Num))
174            } else {
175                Err(format!(
176                    "references {object}.{member} (only Flow.quantity is auto-groundable in v1)"
177                ))
178            }
179        }
180        Expression::Binary { op, left, right } => {
181            let (l, lk) = render(left, ctx)?;
182            let (r, rk) = render(right, ctx)?;
183            let prop = |sym: &str| -> Result<(String, Kind), String> {
184                Ok((format!("({l} {sym} {r})"), Kind::Prop))
185            };
186            match op {
187                BinaryOp::And | BinaryOp::Or => {
188                    if lk != Kind::Prop || rk != Kind::Prop {
189                        return Err("boolean operator applied to non-propositions".to_string());
190                    }
191                    prop(if *op == BinaryOp::And { "∧" } else { "∨" })
192                }
193                BinaryOp::Equal | BinaryOp::NotEqual => {
194                    if lk != rk || lk == Kind::Prop {
195                        return Err("equality on mismatched or non-comparable operands".to_string());
196                    }
197                    prop(if *op == BinaryOp::Equal { "=" } else { "≠" })
198                }
199                BinaryOp::GreaterThan
200                | BinaryOp::LessThan
201                | BinaryOp::GreaterThanOrEqual
202                | BinaryOp::LessThanOrEqual => {
203                    if lk != Kind::Num || rk != Kind::Num {
204                        return Err("ordering comparison on non-numeric operands".to_string());
205                    }
206                    prop(match op {
207                        BinaryOp::GreaterThan => ">",
208                        BinaryOp::LessThan => "<",
209                        BinaryOp::GreaterThanOrEqual => "≥",
210                        _ => "≤",
211                    })
212                }
213                BinaryOp::Plus | BinaryOp::Minus => {
214                    if lk != Kind::Num || rk != Kind::Num {
215                        return Err("arithmetic on non-numeric operands".to_string());
216                    }
217                    let sym = if *op == BinaryOp::Plus { "+" } else { "-" };
218                    Ok((format!("({l} {sym} {r})"), Kind::Num))
219                }
220                // ponytail: Multiply/Divide change the shared decimal scale;
221                // support them by tracking per-term scale if models need it.
222                other => Err(defer_op(other)),
223            }
224        }
225        Expression::Unary { op, operand } => {
226            let (o, k) = render(operand, ctx)?;
227            match op {
228                UnaryOp::Not => {
229                    if k != Kind::Prop {
230                        return Err("negation of a non-proposition".to_string());
231                    }
232                    Ok((format!("(¬ {o})"), Kind::Prop))
233                }
234                UnaryOp::Negate => {
235                    if k != Kind::Num {
236                        return Err("arithmetic negation of a non-number".to_string());
237                    }
238                    Ok((format!("(-{o})"), Kind::Num))
239                }
240            }
241        }
242        Expression::TimeLiteral(_) => Err("uses a time literal (not auto-groundable)".to_string()),
243        Expression::IntervalLiteral { .. } => {
244            Err("uses an interval literal (not auto-groundable)".to_string())
245        }
246        Expression::Variable(v) => Err(format!("uses free variable `{v}` (not auto-groundable)")),
247        Expression::GroupBy { .. } => Err("uses group-by (not auto-groundable)".to_string()),
248        Expression::Cast { .. } => Err("uses a cast (not auto-groundable)".to_string()),
249        Expression::Quantifier { quantifier, .. } => Err(format!(
250            "uses quantifier {} (not auto-groundable in v1)",
251            match quantifier {
252                Quantifier::ForAll => "forall",
253                Quantifier::Exists => "exists",
254                Quantifier::ExistsUnique => "exists-unique",
255            }
256        )),
257        Expression::Aggregation { .. } | Expression::AggregationComprehension { .. } => {
258            Err("uses aggregation (not auto-groundable)".to_string())
259        }
260    }
261}
262
263/// Evaluate with the same semantics `render` emits. `flow_q` binds `f.quantity`.
264fn eval(expr: &Expression, ctx: &GroundCtx, flow_q: Option<i128>) -> Result<V, String> {
265    match expr {
266        Expression::Literal(v) => match v {
267            serde_json::Value::Bool(b) => Ok(V::P(*b)),
268            serde_json::Value::Number(n) => {
269                let d = n
270                    .to_string()
271                    .parse::<Decimal>()
272                    .map_err(|e| format!("unsupported numeric literal {n}: {e}"))?;
273                Ok(V::N(scaled(d, ctx.scale)?))
274            }
275            serde_json::Value::String(s) => Ok(V::S(s.clone())),
276            other => Err(format!("unsupported literal {other}")),
277        },
278        Expression::QuantityLiteral { value, .. } => Ok(V::N(scaled(*value, ctx.scale)?)),
279        Expression::MemberAccess { .. } => {
280            flow_q.map(V::N).ok_or_else(|| "no flow bound".to_string())
281        }
282        Expression::Binary { op, left, right } => {
283            let l = eval(left, ctx, flow_q)?;
284            let r = eval(right, ctx, flow_q)?;
285            match (op, l, r) {
286                (BinaryOp::And, V::P(a), V::P(b)) => Ok(V::P(a && b)),
287                (BinaryOp::Or, V::P(a), V::P(b)) => Ok(V::P(a || b)),
288                (BinaryOp::Equal, a, b) => Ok(V::P(a == b)),
289                (BinaryOp::NotEqual, a, b) => Ok(V::P(a != b)),
290                (BinaryOp::GreaterThan, V::N(a), V::N(b)) => Ok(V::P(a > b)),
291                (BinaryOp::LessThan, V::N(a), V::N(b)) => Ok(V::P(a < b)),
292                (BinaryOp::GreaterThanOrEqual, V::N(a), V::N(b)) => Ok(V::P(a >= b)),
293                (BinaryOp::LessThanOrEqual, V::N(a), V::N(b)) => Ok(V::P(a <= b)),
294                (BinaryOp::Plus, V::N(a), V::N(b)) => a
295                    .checked_add(b)
296                    .map(V::N)
297                    .ok_or_else(|| "arithmetic overflow".to_string()),
298                (BinaryOp::Minus, V::N(a), V::N(b)) => a
299                    .checked_sub(b)
300                    .map(V::N)
301                    .ok_or_else(|| "arithmetic overflow".to_string()),
302                (other, _, _) => Err(defer_op(other)),
303            }
304        }
305        Expression::Unary { op, operand } => {
306            let o = eval(operand, ctx, flow_q)?;
307            match (op, o) {
308                (UnaryOp::Not, V::P(b)) => Ok(V::P(!b)),
309                (UnaryOp::Negate, V::N(n)) => n
310                    .checked_neg()
311                    .map(V::N)
312                    .ok_or_else(|| "arithmetic overflow".to_string()),
313                _ => Err("type error in unary operator".to_string()),
314            }
315        }
316        other => Err(format!("unsupported expression {other:?}")),
317    }
318}
319
320const LEAN_KEYWORDS: &[&str] = &[
321    "abbrev",
322    "axiom",
323    "by",
324    "class",
325    "def",
326    "deriving",
327    "do",
328    "else",
329    "end",
330    "example",
331    "fun",
332    "if",
333    "import",
334    "in",
335    "inductive",
336    "instance",
337    "let",
338    "match",
339    "namespace",
340    "open",
341    "sorry",
342    "structure",
343    "then",
344    "theorem",
345    "where",
346];
347
348/// Sanitize a `.sea` name into a valid Lean identifier (deterministic).
349pub fn lean_ident(name: &str) -> String {
350    let mut out = String::with_capacity(name.len());
351    for c in name.chars() {
352        if c.is_ascii_alphanumeric() || c == '_' {
353            out.push(c);
354        } else {
355            out.push('_');
356        }
357    }
358    if out.is_empty() || out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
359        out.insert(0, 'X');
360    }
361    if LEAN_KEYWORDS.contains(&out.as_str()) {
362        out.push('_');
363    }
364    out
365}
366
367/// Deterministically deduplicate sanitized identifiers (`_2`, `_3`, … suffixes).
368pub fn unique_idents<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
369    let mut seen = std::collections::BTreeMap::<String, usize>::new();
370    let mut out = Vec::new();
371    for name in names {
372        let base = lean_ident(name);
373        let n = seen.entry(base.clone()).or_insert(0);
374        *n += 1;
375        if *n == 1 {
376            out.push(base);
377        } else {
378            out.push(format!("{base}_{n}"));
379        }
380    }
381    out
382}
383
384#[cfg(test)]
385mod tests {
386    use super::*;
387
388    fn ctx(quantities: &[i128]) -> GroundCtx {
389        GroundCtx {
390            scale: 0,
391            flow_quantities: Some(quantities.to_vec()),
392        }
393    }
394
395    fn num(n: i64) -> Expression {
396        Expression::Literal(serde_json::json!(n))
397    }
398
399    fn flow_quantity() -> Expression {
400        Expression::MemberAccess {
401            object: "Flow".to_string(),
402            member: "quantity".to_string(),
403        }
404    }
405
406    fn gt(l: Expression, r: Expression) -> Expression {
407        Expression::Binary {
408            op: BinaryOp::GreaterThan,
409            left: Box::new(l),
410            right: Box::new(r),
411        }
412    }
413
414    #[test]
415    fn flow_policy_renders_and_holds() {
416        let expr = gt(flow_quantity(), num(0));
417        match lower_policy(&expr, &ctx(&[100, 5])) {
418            Lowered::Groundable { lean, holds } => {
419                assert_eq!(lean, "∀ f ∈ flows, (f.quantity > 0)");
420                assert!(holds);
421            }
422            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
423        }
424    }
425
426    #[test]
427    fn violated_flow_policy_grounds_false() {
428        let expr = gt(flow_quantity(), num(1000));
429        match lower_policy(&expr, &ctx(&[100])) {
430            Lowered::Groundable { holds, .. } => assert!(!holds),
431            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
432        }
433    }
434
435    #[test]
436    fn empty_flows_are_vacuously_true() {
437        let expr = gt(flow_quantity(), num(0));
438        match lower_policy(&expr, &ctx(&[])) {
439            Lowered::Groundable { holds, .. } => assert!(holds),
440            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
441        }
442    }
443
444    #[test]
445    fn flow_policy_defers_without_flow_context() {
446        let expr = gt(flow_quantity(), num(0));
447        let no_flows = GroundCtx {
448            scale: 0,
449            flow_quantities: None,
450        };
451        assert!(matches!(
452            lower_policy(&expr, &no_flows),
453            Lowered::Deferred { .. }
454        ));
455    }
456
457    #[test]
458    fn closed_expressions_ground_without_quantifier() {
459        let expr = Expression::Binary {
460            op: BinaryOp::And,
461            left: Box::new(gt(num(3), num(2))),
462            right: Box::new(Expression::Unary {
463                op: UnaryOp::Not,
464                operand: Box::new(gt(num(1), num(2))),
465            }),
466        };
467        match lower_policy(&expr, &ctx(&[])) {
468            Lowered::Groundable { lean, holds } => {
469                assert_eq!(lean, "((3 > 2) ∧ (¬ (1 > 2)))");
470                assert!(holds);
471            }
472            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
473        }
474    }
475
476    #[test]
477    fn string_equality_grounds() {
478        let expr = Expression::Binary {
479            op: BinaryOp::Equal,
480            left: Box::new(Expression::Literal(serde_json::json!("a\"b"))),
481            right: Box::new(Expression::Literal(serde_json::json!("a\"b"))),
482        };
483        match lower_policy(&expr, &ctx(&[])) {
484            Lowered::Groundable { lean, holds } => {
485                assert_eq!(lean, "(\"a\\\"b\" = \"a\\\"b\")");
486                assert!(holds);
487            }
488            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
489        }
490    }
491
492    #[test]
493    fn decimals_share_the_model_scale() {
494        let expr = gt(
495            flow_quantity(),
496            Expression::QuantityLiteral {
497                value: "1.5".parse().unwrap(),
498                unit: "units".to_string(),
499            },
500        );
501        let c = GroundCtx {
502            scale: 2,
503            flow_quantities: Some(vec![160]), // 1.60 scaled
504        };
505        match lower_policy(&expr, &c) {
506            Lowered::Groundable { lean, holds } => {
507                assert_eq!(lean, "∀ f ∈ flows, (f.quantity > 150)");
508                assert!(holds);
509            }
510            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
511        }
512    }
513
514    #[test]
515    fn unsupported_constructs_defer_with_reason() {
516        let cases: Vec<(Expression, &str)> = vec![
517            (
518                Expression::MemberAccess {
519                    object: "Entity".to_string(),
520                    member: "name".to_string(),
521                },
522                "Entity.name",
523            ),
524            (
525                Expression::Cast {
526                    operand: Box::new(num(1)),
527                    target_type: "int".to_string(),
528                },
529                "cast",
530            ),
531            (Expression::Variable("x".to_string()), "free variable"),
532            (
533                Expression::Binary {
534                    op: BinaryOp::Multiply,
535                    left: Box::new(num(2)),
536                    right: Box::new(num(3)),
537                },
538                "Multiply",
539            ),
540        ];
541        for (expr, needle) in cases {
542            match lower_policy(&expr, &ctx(&[])) {
543                Lowered::Deferred { reason } => {
544                    assert!(reason.contains(needle), "reason `{reason}` ∌ `{needle}`")
545                }
546                Lowered::Groundable { lean, .. } => panic!("unexpectedly grounded: {lean}"),
547            }
548        }
549    }
550
551    #[test]
552    fn idents_are_sanitized_and_deduplicated() {
553        assert_eq!(lean_ident("Camera Units"), "Camera_Units");
554        assert_eq!(lean_ident("9lives"), "X9lives");
555        assert_eq!(lean_ident("theorem"), "theorem_");
556        let ids = unique_idents(["A B", "A_B", "ok"].into_iter());
557        assert_eq!(ids, vec!["A_B", "A_B_2", "ok"]);
558    }
559}