domainforge-core 0.21.2

Rust core library implementing the SEA DSL primitives and validation engine.
Documentation
//! Render the policy IR as Rego v1 terms over `rego/lib.rego`.

use super::ir::{BoolIr, CmpOp, CollectionIr, PolicyIr, ValueIr};
use crate::policy::Quantifier;

fn json(value: &impl serde::Serialize) -> String {
    // A JSON scalar/string is a valid Rego term.
    serde_json::to_string(value).expect("JSON scalars serialize")
}

fn collection(c: &CollectionIr) -> String {
    match &c.entity_type {
        None => format!("input.facts.{}", c.name),
        Some(ty) => format!(
            "[x | some x in input.facts.{}; lib.field(x, \"entity\") == {}]",
            c.name,
            json(ty)
        ),
    }
}

fn value(v: &ValueIr) -> String {
    match v {
        ValueIr::Scalar(s) => json(s),
        ValueIr::Field { var, field } => format!("lib.field(v{var}, {})", json(field)),
        ValueIr::Count {
            collection: c,
            filter: None,
            ..
        } => format!("count({})", collection(c)),
        ValueIr::Count {
            var,
            collection: c,
            filter: Some(filter),
        } => format!(
            "count([1 | some v{var} in {}; {} == \"true\"])",
            collection(c),
            boolean(filter)
        ),
    }
}

/// Per-item filter results of a filtered count, so a failing filter fails the
/// comparison (`lib.guard`) instead of merely dropping the item.
fn filter_results(v: &ValueIr) -> Option<String> {
    match v {
        ValueIr::Count {
            var,
            collection: c,
            filter: Some(filter),
        } => Some(format!(
            "[{} | some v{var} in {}]",
            boolean(filter),
            collection(c)
        )),
        _ => None,
    }
}

fn boolean(b: &BoolIr) -> String {
    match b {
        BoolIr::Const(true) => "\"true\"".to_string(),
        BoolIr::Const(false) => "\"false\"".to_string(),
        BoolIr::Not(inner) => format!("lib.not3({})", boolean(inner)),
        BoolIr::And(l, r) => format!("lib.and3({}, {})", boolean(l), boolean(r)),
        BoolIr::Or(l, r) => format!("lib.or3({}, {})", boolean(l), boolean(r)),
        BoolIr::Cmp { op, left, right } => {
            let function = match op {
                CmpOp::Eq => "cmp_eq",
                CmpOp::Ne => "cmp_ne",
                CmpOp::Lt => "cmp_lt",
                CmpOp::Lte => "cmp_lte",
                CmpOp::Gt => "cmp_gt",
                CmpOp::Gte => "cmp_gte",
                CmpOp::Contains => "str_contains",
                CmpOp::StartsWith => "str_startswith",
                CmpOp::EndsWith => "str_endswith",
            };
            let mut term = format!("lib.{function}({}, {})", value(left), value(right));
            for results in [filter_results(right), filter_results(left)]
                .into_iter()
                .flatten()
            {
                term = format!("lib.guard({results}, {term})");
            }
            term
        }
        BoolIr::Quantified {
            quantifier,
            var,
            collection: c,
            condition,
        } => {
            let function = match quantifier {
                Quantifier::ForAll => "forall3",
                Quantifier::Exists => "exists3",
                Quantifier::ExistsUnique => "exists_unique",
            };
            format!(
                "lib.{function}([{} | some v{var} in {}])",
                boolean(condition),
                collection(c)
            )
        }
    }
}

/// The generated module: one `conditions[key]` rule per policy.
pub fn policies_module(policies: &[PolicyIr], model_hash: &str) -> String {
    let rules: String = policies
        .iter()
        .map(|policy| {
            format!(
                "\n# {} {} priority {}\nconditions[{}] := {}\n",
                policy.modality,
                policy.kind,
                policy.priority,
                json(&policy.key),
                boolean(&policy.condition)
            )
        })
        .collect();

    let mut out = String::new();
    out.push_str("# Generated by `domainforge project --format rego`. Do not edit.\n");
    out.push_str(&format!("# Source model: {model_hash}\n"));
    out.push_str("package domainforge.policy\n\nimport rego.v1\n");
    // `opa check --strict` rejects an unused import.
    if rules.contains("lib.") {
        out.push_str("\nimport data.domainforge.sea.lib\n");
    }
    out.push_str(&rules);
    out
}