Skip to main content

domainforge_core/policy/
expression.rs

1use rust_decimal::Decimal;
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6pub struct WindowSpec {
7    pub duration: u64,
8    pub unit: String,
9}
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub enum Expression {
13    Literal(serde_json::Value),
14
15    QuantityLiteral {
16        value: Decimal,
17        unit: String,
18    },
19
20    TimeLiteral(String), // ISO 8601 timestamp
21
22    IntervalLiteral {
23        start: String, // Time string (e.g., "09:00")
24        end: String,   // Time string (e.g., "17:00")
25    },
26
27    Variable(String),
28
29    GroupBy {
30        variable: String,
31        collection: Box<Expression>,
32        filter: Option<Box<Expression>>,
33        key: Box<Expression>,
34        condition: Box<Expression>,
35    },
36
37    Binary {
38        op: BinaryOp,
39        left: Box<Expression>,
40        right: Box<Expression>,
41    },
42
43    Unary {
44        op: UnaryOp,
45        operand: Box<Expression>,
46    },
47
48    Cast {
49        operand: Box<Expression>,
50        target_type: String,
51    },
52
53    Quantifier {
54        quantifier: Quantifier,
55        variable: String,
56        collection: Box<Expression>,
57        condition: Box<Expression>,
58    },
59
60    MemberAccess {
61        object: String,
62        member: String,
63    },
64
65    Aggregation {
66        function: AggregateFunction,
67        collection: Box<Expression>,
68        field: Option<String>,
69        filter: Option<Box<Expression>>,
70    },
71
72    AggregationComprehension {
73        function: AggregateFunction,
74        variable: String,
75        collection: Box<Expression>,
76        window: Option<WindowSpec>,
77        predicate: Box<Expression>,
78        projection: Box<Expression>,
79        target_unit: Option<String>,
80    },
81
82    /// Contextual role reference `role<SymbolRef>` from ADR-013 §2.
83    /// Outside application validation this is an opaque, unevaluated leaf;
84    /// application policy evaluation resolves it against the typed context.
85    RoleReference {
86        role: String,
87    },
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91pub enum BinaryOp {
92    And,
93    Or,
94
95    Equal,
96    NotEqual,
97    GreaterThan,
98    LessThan,
99    GreaterThanOrEqual,
100    LessThanOrEqual,
101
102    Plus,
103    Minus,
104    Multiply,
105    Divide,
106
107    Contains,
108    StartsWith,
109    EndsWith,
110    Matches,
111
112    HasRole,
113
114    // Temporal operators
115    Before,
116    After,
117    During,
118}
119
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub enum UnaryOp {
122    Not,
123    Negate,
124}
125
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127pub enum Quantifier {
128    ForAll,
129    Exists,
130    ExistsUnique,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134pub enum AggregateFunction {
135    Count,
136    Sum,
137    Min,
138    Max,
139    Avg,
140}
141
142impl Expression {
143    /// Returns a canonical normalized form of this expression.
144    ///
145    /// The normalized form applies various simplification rules:
146    /// - Identity elimination (`true AND x` → `x`)
147    /// - Domination (`false AND x` → `false`)
148    /// - Idempotence (`a AND a` → `a`)
149    /// - Absorption (`a OR (a AND b)` → `a`)
150    /// - Double negation (`NOT NOT x` → `x`)
151    /// - Commutative sorting (operands sorted lexicographically)
152    #[must_use]
153    pub fn normalize(&self) -> super::NormalizedExpression {
154        super::NormalizedExpression::new(self)
155    }
156
157    /// Returns true if two expressions are semantically equivalent.
158    ///
159    /// Two expressions are equivalent if their normalized forms are identical.
160    #[must_use]
161    pub fn is_equivalent(&self, other: &Expression) -> bool {
162        self.normalize() == other.normalize()
163    }
164
165    pub fn literal(value: impl Into<serde_json::Value>) -> Self {
166        Expression::Literal(value.into())
167    }
168
169    pub fn variable(name: &str) -> Self {
170        Expression::Variable(name.to_string())
171    }
172
173    pub fn binary(op: BinaryOp, left: Expression, right: Expression) -> Self {
174        Expression::Binary {
175            op,
176            left: Box::new(left),
177            right: Box::new(right),
178        }
179    }
180
181    pub fn unary(op: UnaryOp, operand: Expression) -> Self {
182        Expression::Unary {
183            op,
184            operand: Box::new(operand),
185        }
186    }
187
188    pub fn quantifier(
189        q: Quantifier,
190        var: &str,
191        collection: Expression,
192        condition: Expression,
193    ) -> Self {
194        Expression::Quantifier {
195            quantifier: q,
196            variable: var.to_string(),
197            collection: Box::new(collection),
198            condition: Box::new(condition),
199        }
200    }
201
202    pub fn cast(operand: Expression, target_type: impl Into<String>) -> Self {
203        Expression::Cast {
204            operand: Box::new(operand),
205            target_type: target_type.into(),
206        }
207    }
208
209    pub fn comparison(
210        var: &str,
211        op: &str,
212        value: impl Into<serde_json::Value>,
213    ) -> Result<Self, String> {
214        let op = match op {
215            ">" => BinaryOp::GreaterThan,
216            "<" => BinaryOp::LessThan,
217            ">=" => BinaryOp::GreaterThanOrEqual,
218            "<=" => BinaryOp::LessThanOrEqual,
219            "==" => BinaryOp::Equal,
220            "!=" => BinaryOp::NotEqual,
221            _ => return Err(format!("Unknown operator: {}", op)),
222        };
223
224        Ok(Expression::binary(
225            op,
226            Expression::variable(var),
227            Expression::literal(value),
228        ))
229    }
230
231    pub fn aggregation(
232        function: AggregateFunction,
233        collection: Expression,
234        field: Option<impl Into<String>>,
235        filter: Option<Expression>,
236    ) -> Self {
237        Expression::Aggregation {
238            function,
239            collection: Box::new(collection),
240            field: field.map(|f| f.into()),
241            filter: filter.map(Box::new),
242        }
243    }
244
245    pub fn member_access(object: &str, member: &str) -> Self {
246        Expression::MemberAccess {
247            object: object.to_string(),
248            member: member.to_string(),
249        }
250    }
251}
252
253impl fmt::Display for Expression {
254    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
255        match self {
256            Expression::Literal(v) => write!(f, "{}", v),
257            Expression::QuantityLiteral { value, unit } => {
258                write!(f, "{} {}", value, unit)
259            }
260            Expression::TimeLiteral(timestamp) => write!(f, "\"{}\"", timestamp),
261            Expression::IntervalLiteral { start, end } => {
262                write!(f, "interval(\"{}\", \"{}\")", start, end)
263            }
264            Expression::Variable(n) => write!(f, "{}", n),
265            Expression::GroupBy {
266                variable,
267                collection,
268                filter,
269                key,
270                condition,
271            } => {
272                write!(f, "group_by({} in {}", variable, collection)?;
273                if let Some(flt) = filter {
274                    write!(f, " WHERE {}", flt)?;
275                }
276                write!(f, ": {}) {{ {} }}", key, condition)
277            }
278            Expression::Binary { op, left, right } => {
279                write!(f, "({} {} {})", left, op, right)
280            }
281            Expression::Unary { op, operand } => {
282                write!(f, "{} {}", op, operand)
283            }
284            Expression::Cast {
285                operand,
286                target_type,
287            } => {
288                write!(f, "{} as \"{}\"", operand, target_type)
289            }
290            Expression::Quantifier {
291                quantifier,
292                variable,
293                collection,
294                condition,
295            } => {
296                write!(
297                    f,
298                    "{}({} in {}: {})",
299                    quantifier, variable, collection, condition
300                )
301            }
302            Expression::MemberAccess { object, member } => {
303                write!(f, "{}.{}", object, member)
304            }
305            Expression::Aggregation {
306                function,
307                collection,
308                field,
309                filter,
310            } => {
311                write!(f, "{}({}", function, collection)?;
312                if let Some(fld) = field {
313                    write!(f, ".{}", fld)?;
314                }
315                if let Some(flt) = filter {
316                    write!(f, " WHERE {}", flt)?;
317                }
318                write!(f, ")")
319            }
320            Expression::AggregationComprehension {
321                function,
322                variable,
323                collection,
324                window,
325                predicate,
326                projection,
327                target_unit,
328            } => {
329                write!(f, "{}({} in {}", function, variable, collection)?;
330                if let Some(w) = window {
331                    write!(f, " OVER LAST {} \"{}\"", w.duration, w.unit)?;
332                }
333                match predicate.as_ref() {
334                    Expression::Literal(serde_json::Value::Bool(true)) => {
335                        write!(f, ": {}", projection)?;
336                    }
337                    _ => {
338                        write!(f, " WHERE {}: {}", predicate, projection)?;
339                    }
340                }
341                if let Some(unit) = target_unit {
342                    write!(f, " AS \"{}\"", unit)?;
343                }
344                write!(f, ")")
345            }
346            Expression::RoleReference { role } => write!(f, "role<{}>", role),
347        }
348    }
349}
350
351impl fmt::Display for BinaryOp {
352    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
353        match self {
354            BinaryOp::And => write!(f, "AND"),
355            BinaryOp::Or => write!(f, "OR"),
356            BinaryOp::Equal => write!(f, "=="),
357            BinaryOp::NotEqual => write!(f, "!="),
358            BinaryOp::GreaterThan => write!(f, ">"),
359            BinaryOp::LessThan => write!(f, "<"),
360            BinaryOp::GreaterThanOrEqual => write!(f, ">="),
361            BinaryOp::LessThanOrEqual => write!(f, "<="),
362            BinaryOp::Plus => write!(f, "+"),
363            BinaryOp::Minus => write!(f, "-"),
364            BinaryOp::Multiply => write!(f, "*"),
365            BinaryOp::Divide => write!(f, "/"),
366            BinaryOp::Contains => write!(f, "CONTAINS"),
367            BinaryOp::StartsWith => write!(f, "STARTS_WITH"),
368            BinaryOp::EndsWith => write!(f, "ENDS_WITH"),
369            BinaryOp::Matches => write!(f, "MATCHES"),
370            BinaryOp::HasRole => write!(f, "HAS_ROLE"),
371            BinaryOp::Before => write!(f, "BEFORE"),
372            BinaryOp::After => write!(f, "AFTER"),
373            BinaryOp::During => write!(f, "DURING"),
374        }
375    }
376}
377
378impl fmt::Display for UnaryOp {
379    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
380        match self {
381            UnaryOp::Not => write!(f, "NOT"),
382            UnaryOp::Negate => write!(f, "-"),
383        }
384    }
385}
386
387impl fmt::Display for Quantifier {
388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389        match self {
390            Quantifier::ForAll => write!(f, "ForAll"),
391            Quantifier::Exists => write!(f, "Exists"),
392            Quantifier::ExistsUnique => write!(f, "ExistsUnique"),
393        }
394    }
395}
396
397impl fmt::Display for AggregateFunction {
398    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399        match self {
400            AggregateFunction::Count => write!(f, "COUNT"),
401            AggregateFunction::Sum => write!(f, "SUM"),
402            AggregateFunction::Min => write!(f, "MIN"),
403            AggregateFunction::Max => write!(f, "MAX"),
404            AggregateFunction::Avg => write!(f, "AVG"),
405        }
406    }
407}