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        Expression::RoleReference { .. } => {
261            Err("uses role reference (not auto-groundable outside application policy)".to_string())
262        }
263    }
264}
265
266/// Evaluate with the same semantics `render` emits. `flow_q` binds `f.quantity`.
267fn eval(expr: &Expression, ctx: &GroundCtx, flow_q: Option<i128>) -> Result<V, String> {
268    match expr {
269        Expression::Literal(v) => match v {
270            serde_json::Value::Bool(b) => Ok(V::P(*b)),
271            serde_json::Value::Number(n) => {
272                let d = n
273                    .to_string()
274                    .parse::<Decimal>()
275                    .map_err(|e| format!("unsupported numeric literal {n}: {e}"))?;
276                Ok(V::N(scaled(d, ctx.scale)?))
277            }
278            serde_json::Value::String(s) => Ok(V::S(s.clone())),
279            other => Err(format!("unsupported literal {other}")),
280        },
281        Expression::QuantityLiteral { value, .. } => Ok(V::N(scaled(*value, ctx.scale)?)),
282        Expression::MemberAccess { .. } => {
283            flow_q.map(V::N).ok_or_else(|| "no flow bound".to_string())
284        }
285        Expression::Binary { op, left, right } => {
286            let l = eval(left, ctx, flow_q)?;
287            let r = eval(right, ctx, flow_q)?;
288            match (op, l, r) {
289                (BinaryOp::And, V::P(a), V::P(b)) => Ok(V::P(a && b)),
290                (BinaryOp::Or, V::P(a), V::P(b)) => Ok(V::P(a || b)),
291                (BinaryOp::Equal, a, b) => Ok(V::P(a == b)),
292                (BinaryOp::NotEqual, a, b) => Ok(V::P(a != b)),
293                (BinaryOp::GreaterThan, V::N(a), V::N(b)) => Ok(V::P(a > b)),
294                (BinaryOp::LessThan, V::N(a), V::N(b)) => Ok(V::P(a < b)),
295                (BinaryOp::GreaterThanOrEqual, V::N(a), V::N(b)) => Ok(V::P(a >= b)),
296                (BinaryOp::LessThanOrEqual, V::N(a), V::N(b)) => Ok(V::P(a <= b)),
297                (BinaryOp::Plus, V::N(a), V::N(b)) => a
298                    .checked_add(b)
299                    .map(V::N)
300                    .ok_or_else(|| "arithmetic overflow".to_string()),
301                (BinaryOp::Minus, V::N(a), V::N(b)) => a
302                    .checked_sub(b)
303                    .map(V::N)
304                    .ok_or_else(|| "arithmetic overflow".to_string()),
305                (other, _, _) => Err(defer_op(other)),
306            }
307        }
308        Expression::Unary { op, operand } => {
309            let o = eval(operand, ctx, flow_q)?;
310            match (op, o) {
311                (UnaryOp::Not, V::P(b)) => Ok(V::P(!b)),
312                (UnaryOp::Negate, V::N(n)) => n
313                    .checked_neg()
314                    .map(V::N)
315                    .ok_or_else(|| "arithmetic overflow".to_string()),
316                _ => Err("type error in unary operator".to_string()),
317            }
318        }
319        other => Err(format!("unsupported expression {other:?}")),
320    }
321}
322
323const LEAN_KEYWORDS: &[&str] = &[
324    "abbrev",
325    "axiom",
326    "by",
327    "class",
328    "def",
329    "deriving",
330    "do",
331    "else",
332    "end",
333    "example",
334    "fun",
335    "if",
336    "import",
337    "in",
338    "inductive",
339    "instance",
340    "let",
341    "match",
342    "namespace",
343    "open",
344    "sorry",
345    "structure",
346    "then",
347    "theorem",
348    "where",
349];
350
351/// Sanitize a `.sea` name into a valid Lean identifier (deterministic).
352pub fn lean_ident(name: &str) -> String {
353    let mut out = String::with_capacity(name.len());
354    for c in name.chars() {
355        if c.is_ascii_alphanumeric() || c == '_' {
356            out.push(c);
357        } else {
358            out.push('_');
359        }
360    }
361    if out.is_empty() || out.chars().next().is_some_and(|c| c.is_ascii_digit()) {
362        out.insert(0, 'X');
363    }
364    if LEAN_KEYWORDS.contains(&out.as_str()) {
365        out.push('_');
366    }
367    out
368}
369
370/// Deterministically deduplicate sanitized identifiers (`_2`, `_3`, … suffixes).
371pub fn unique_idents<'a>(names: impl Iterator<Item = &'a str>) -> Vec<String> {
372    let mut seen = std::collections::BTreeMap::<String, usize>::new();
373    let mut out = Vec::new();
374    for name in names {
375        let base = lean_ident(name);
376        let n = seen.entry(base.clone()).or_insert(0);
377        *n += 1;
378        if *n == 1 {
379            out.push(base);
380        } else {
381            out.push(format!("{base}_{n}"));
382        }
383    }
384    out
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    fn ctx(quantities: &[i128]) -> GroundCtx {
392        GroundCtx {
393            scale: 0,
394            flow_quantities: Some(quantities.to_vec()),
395        }
396    }
397
398    fn num(n: i64) -> Expression {
399        Expression::Literal(serde_json::json!(n))
400    }
401
402    fn flow_quantity() -> Expression {
403        Expression::MemberAccess {
404            object: "Flow".to_string(),
405            member: "quantity".to_string(),
406        }
407    }
408
409    fn gt(l: Expression, r: Expression) -> Expression {
410        Expression::Binary {
411            op: BinaryOp::GreaterThan,
412            left: Box::new(l),
413            right: Box::new(r),
414        }
415    }
416
417    #[test]
418    fn flow_policy_renders_and_holds() {
419        let expr = gt(flow_quantity(), num(0));
420        match lower_policy(&expr, &ctx(&[100, 5])) {
421            Lowered::Groundable { lean, holds } => {
422                assert_eq!(lean, "∀ f ∈ flows, (f.quantity > 0)");
423                assert!(holds);
424            }
425            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
426        }
427    }
428
429    #[test]
430    fn violated_flow_policy_grounds_false() {
431        let expr = gt(flow_quantity(), num(1000));
432        match lower_policy(&expr, &ctx(&[100])) {
433            Lowered::Groundable { holds, .. } => assert!(!holds),
434            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
435        }
436    }
437
438    #[test]
439    fn empty_flows_are_vacuously_true() {
440        let expr = gt(flow_quantity(), num(0));
441        match lower_policy(&expr, &ctx(&[])) {
442            Lowered::Groundable { holds, .. } => assert!(holds),
443            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
444        }
445    }
446
447    #[test]
448    fn flow_policy_defers_without_flow_context() {
449        let expr = gt(flow_quantity(), num(0));
450        let no_flows = GroundCtx {
451            scale: 0,
452            flow_quantities: None,
453        };
454        assert!(matches!(
455            lower_policy(&expr, &no_flows),
456            Lowered::Deferred { .. }
457        ));
458    }
459
460    #[test]
461    fn closed_expressions_ground_without_quantifier() {
462        let expr = Expression::Binary {
463            op: BinaryOp::And,
464            left: Box::new(gt(num(3), num(2))),
465            right: Box::new(Expression::Unary {
466                op: UnaryOp::Not,
467                operand: Box::new(gt(num(1), num(2))),
468            }),
469        };
470        match lower_policy(&expr, &ctx(&[])) {
471            Lowered::Groundable { lean, holds } => {
472                assert_eq!(lean, "((3 > 2) ∧ (¬ (1 > 2)))");
473                assert!(holds);
474            }
475            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
476        }
477    }
478
479    #[test]
480    fn string_equality_grounds() {
481        let expr = Expression::Binary {
482            op: BinaryOp::Equal,
483            left: Box::new(Expression::Literal(serde_json::json!("a\"b"))),
484            right: Box::new(Expression::Literal(serde_json::json!("a\"b"))),
485        };
486        match lower_policy(&expr, &ctx(&[])) {
487            Lowered::Groundable { lean, holds } => {
488                assert_eq!(lean, "(\"a\\\"b\" = \"a\\\"b\")");
489                assert!(holds);
490            }
491            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
492        }
493    }
494
495    #[test]
496    fn decimals_share_the_model_scale() {
497        let expr = gt(
498            flow_quantity(),
499            Expression::QuantityLiteral {
500                value: "1.5".parse().unwrap(),
501                unit: "units".to_string(),
502            },
503        );
504        let c = GroundCtx {
505            scale: 2,
506            flow_quantities: Some(vec![160]), // 1.60 scaled
507        };
508        match lower_policy(&expr, &c) {
509            Lowered::Groundable { lean, holds } => {
510                assert_eq!(lean, "∀ f ∈ flows, (f.quantity > 150)");
511                assert!(holds);
512            }
513            Lowered::Deferred { reason } => panic!("deferred: {reason}"),
514        }
515    }
516
517    #[test]
518    fn unsupported_constructs_defer_with_reason() {
519        let cases: Vec<(Expression, &str)> = vec![
520            (
521                Expression::MemberAccess {
522                    object: "Entity".to_string(),
523                    member: "name".to_string(),
524                },
525                "Entity.name",
526            ),
527            (
528                Expression::Cast {
529                    operand: Box::new(num(1)),
530                    target_type: "int".to_string(),
531                },
532                "cast",
533            ),
534            (Expression::Variable("x".to_string()), "free variable"),
535            (
536                Expression::Binary {
537                    op: BinaryOp::Multiply,
538                    left: Box::new(num(2)),
539                    right: Box::new(num(3)),
540                },
541                "Multiply",
542            ),
543        ];
544        for (expr, needle) in cases {
545            match lower_policy(&expr, &ctx(&[])) {
546                Lowered::Deferred { reason } => {
547                    assert!(reason.contains(needle), "reason `{reason}` ∌ `{needle}`")
548                }
549                Lowered::Groundable { lean, .. } => panic!("unexpectedly grounded: {lean}"),
550            }
551        }
552    }
553
554    #[test]
555    fn idents_are_sanitized_and_deduplicated() {
556        assert_eq!(lean_ident("Camera Units"), "Camera_Units");
557        assert_eq!(lean_ident("9lives"), "X9lives");
558        assert_eq!(lean_ident("theorem"), "theorem_");
559        let ids = unique_idents(["A B", "A_B", "ok"].into_iter());
560        assert_eq!(ids, vec!["A_B", "A_B_2", "ok"]);
561    }
562}