Skip to main content

domainforge_core/policy/
normalize.rs

1//! Canonical Expression Normalizer
2//!
3//! Transforms policy expressions into a deterministic, minimal canonical form.
4//! This enables:
5//! - Semantic equivalence checking via normalized comparison
6//! - Stable caching with deterministic hash keys
7//! - Consistent hover signatures in LSP
8//! - Deterministic golden test output
9//!
10//! # Normalization Rules Applied
11//!
12//! 1. **Commutativity**: Sort operands of AND/OR/==/!=/+/* lexicographically
13//! 2. **Identity**: Remove identity elements (`true AND x` → `x`, `false OR x` → `x`)
14//! 3. **Idempotence**: Deduplicate identical operands (`a AND a` → `a`)
15//! 4. **Absorption**: Remove absorbed terms (`a OR (a AND b)` → `a`)
16//! 5. **Domination**: Short-circuit dominating elements (`false AND x` → `false`)
17//! 6. **Double Negation**: Eliminate `NOT NOT x` → `x`
18//! 7. **Chain Flattening**: Flatten nested same-operator chains
19//! 8. Comparison negation: NOT (a == b) → a != b
20
21use super::{BinaryOp, Expression, UnaryOp};
22use std::fmt;
23use std::hash::{Hash, Hasher};
24use xxhash_rust::xxh64::Xxh64;
25
26/// A normalized expression with precomputed stable hash.
27///
28/// `NormalizedExpression` wraps an `Expression` that has been transformed
29/// into canonical form, along with a stable hash value that remains consistent
30/// across runs and platforms.
31#[derive(Clone)]
32pub struct NormalizedExpression {
33    inner: Expression,
34    hash: u64,
35}
36
37impl NormalizedExpression {
38    /// Create a normalized form of the given expression.
39    pub fn new(expr: &Expression) -> Self {
40        let normalized = normalize_expr(expr);
41        let hash = compute_stable_hash(&normalized);
42        Self {
43            inner: normalized,
44            hash,
45        }
46    }
47
48    /// Access the normalized expression.
49    pub fn inner(&self) -> &Expression {
50        &self.inner
51    }
52
53    /// Consume and return the inner normalized expression.
54    pub fn into_inner(self) -> Expression {
55        self.inner
56    }
57
58    /// Get the stable hash value for this normalized expression.
59    ///
60    /// This hash is deterministic across runs and platforms, making it
61    /// suitable for cache keys.
62    pub fn stable_hash(&self) -> u64 {
63        self.hash
64    }
65}
66
67impl PartialEq for NormalizedExpression {
68    fn eq(&self, other: &Self) -> bool {
69        // Fast path: compare hashes first
70        self.hash == other.hash && self.inner == other.inner
71    }
72}
73
74impl Eq for NormalizedExpression {}
75
76impl Hash for NormalizedExpression {
77    fn hash<H: Hasher>(&self, state: &mut H) {
78        self.hash.hash(state);
79    }
80}
81
82impl fmt::Display for NormalizedExpression {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write!(f, "{}", self.inner)
85    }
86}
87
88impl fmt::Debug for NormalizedExpression {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        f.debug_struct("NormalizedExpression")
91            .field("inner", &self.inner)
92            .field("hash", &format!("{:016x}", self.hash))
93            .finish()
94    }
95}
96
97// ============================================================================
98// Stable Hashing
99// ============================================================================
100
101/// Compute a stable hash using Xxh64 which is portable and deterministic.
102fn compute_stable_hash(expr: &Expression) -> u64 {
103    // Use a fixed seed (0) for stability across runs and updates
104    let mut hasher = Xxh64::new(0);
105    hash_expression(expr, &mut hasher);
106    hasher.finish()
107}
108
109/// Recursively hash an expression in a stable, deterministic manner.
110fn hash_expression<H: Hasher>(expr: &Expression, hasher: &mut H) {
111    // Hash discriminant first for type differentiation
112    std::mem::discriminant(expr).hash(hasher);
113
114    match expr {
115        Expression::Literal(v) => {
116            // Use string representation for consistent JSON value hashing
117            v.to_string().hash(hasher);
118        }
119        Expression::Variable(s) => s.hash(hasher),
120        Expression::QuantityLiteral { value, unit } => {
121            value.to_string().hash(hasher);
122            unit.hash(hasher);
123        }
124        Expression::TimeLiteral(s) => s.hash(hasher),
125        Expression::IntervalLiteral { start, end } => {
126            start.hash(hasher);
127            end.hash(hasher);
128        }
129        Expression::MemberAccess { object, member } => {
130            object.hash(hasher);
131            member.hash(hasher);
132        }
133        Expression::Binary { op, left, right } => {
134            std::mem::discriminant(op).hash(hasher);
135            hash_expression(left, hasher);
136            hash_expression(right, hasher);
137        }
138        Expression::Unary { op, operand } => {
139            std::mem::discriminant(op).hash(hasher);
140            hash_expression(operand, hasher);
141        }
142        Expression::Cast {
143            operand,
144            target_type,
145        } => {
146            hash_expression(operand, hasher);
147            target_type.hash(hasher);
148        }
149        Expression::Quantifier {
150            quantifier,
151            variable,
152            collection,
153            condition,
154        } => {
155            std::mem::discriminant(quantifier).hash(hasher);
156            variable.hash(hasher);
157            hash_expression(collection, hasher);
158            hash_expression(condition, hasher);
159        }
160        Expression::GroupBy {
161            variable,
162            collection,
163            filter,
164            key,
165            condition,
166        } => {
167            variable.hash(hasher);
168            hash_expression(collection, hasher);
169            if let Some(f) = filter {
170                true.hash(hasher);
171                hash_expression(f, hasher);
172            } else {
173                false.hash(hasher);
174            }
175            hash_expression(key, hasher);
176            hash_expression(condition, hasher);
177        }
178        Expression::Aggregation {
179            function,
180            collection,
181            field,
182            filter,
183        } => {
184            std::mem::discriminant(function).hash(hasher);
185            hash_expression(collection, hasher);
186            field.hash(hasher);
187            if let Some(f) = filter {
188                true.hash(hasher);
189                hash_expression(f, hasher);
190            } else {
191                false.hash(hasher);
192            }
193        }
194        Expression::AggregationComprehension {
195            function,
196            variable,
197            collection,
198            window,
199            predicate,
200            projection,
201            target_unit,
202        } => {
203            std::mem::discriminant(function).hash(hasher);
204            variable.hash(hasher);
205            hash_expression(collection, hasher);
206            if let Some(w) = window {
207                true.hash(hasher);
208                w.duration.hash(hasher);
209                w.unit.hash(hasher);
210            } else {
211                false.hash(hasher);
212            }
213            hash_expression(predicate, hasher);
214            hash_expression(projection, hasher);
215            target_unit.hash(hasher);
216        }
217        Expression::RoleReference { role } => role.hash(hasher),
218    }
219}
220
221// ============================================================================
222// Main Normalization Logic
223// ============================================================================
224
225/// Normalize an expression into canonical form.
226fn normalize_expr(expr: &Expression) -> Expression {
227    match expr {
228        // Leaf nodes: pass through as-is
229        Expression::Literal(_)
230        | Expression::Variable(_)
231        | Expression::QuantityLiteral { .. }
232        | Expression::TimeLiteral(_)
233        | Expression::IntervalLiteral { .. }
234        | Expression::MemberAccess { .. }
235        | Expression::RoleReference { .. } => expr.clone(),
236
237        // Binary: normalize children, apply optimizations, sort commutative ops
238        Expression::Binary { op, left, right } => {
239            let l = normalize_expr(left);
240            let r = normalize_expr(right);
241            normalize_binary(op.clone(), l, r)
242        }
243
244        // Unary: normalize child, apply double negation and De Morgan
245        Expression::Unary { op, operand } => {
246            let inner = normalize_expr(operand);
247            normalize_unary(op.clone(), inner)
248        }
249
250        // Cast: normalize operand
251        Expression::Cast {
252            operand,
253            target_type,
254        } => Expression::Cast {
255            operand: Box::new(normalize_expr(operand)),
256            target_type: target_type.clone(),
257        },
258
259        // Quantifier: normalize collection and condition
260        Expression::Quantifier {
261            quantifier,
262            variable,
263            collection,
264            condition,
265        } => Expression::Quantifier {
266            quantifier: quantifier.clone(),
267            variable: variable.clone(),
268            collection: Box::new(normalize_expr(collection)),
269            condition: Box::new(normalize_expr(condition)),
270        },
271
272        // GroupBy: normalize all sub-expressions
273        Expression::GroupBy {
274            variable,
275            collection,
276            filter,
277            key,
278            condition,
279        } => Expression::GroupBy {
280            variable: variable.clone(),
281            collection: Box::new(normalize_expr(collection)),
282            filter: filter.as_ref().map(|f| Box::new(normalize_expr(f))),
283            key: Box::new(normalize_expr(key)),
284            condition: Box::new(normalize_expr(condition)),
285        },
286
287        // Aggregation: normalize sub-expressions
288        Expression::Aggregation {
289            function,
290            collection,
291            field,
292            filter,
293        } => Expression::Aggregation {
294            function: function.clone(),
295            collection: Box::new(normalize_expr(collection)),
296            field: field.clone(),
297            filter: filter.as_ref().map(|f| Box::new(normalize_expr(f))),
298        },
299
300        // AggregationComprehension: normalize sub-expressions
301        Expression::AggregationComprehension {
302            function,
303            variable,
304            collection,
305            window,
306            predicate,
307            projection,
308            target_unit,
309        } => Expression::AggregationComprehension {
310            function: function.clone(),
311            variable: variable.clone(),
312            collection: Box::new(normalize_expr(collection)),
313            window: window.clone(),
314            predicate: Box::new(normalize_expr(predicate)),
315            projection: Box::new(normalize_expr(projection)),
316            target_unit: target_unit.clone(),
317        },
318    }
319}
320
321// ============================================================================
322// Binary Expression Normalization
323// ============================================================================
324
325/// Normalize a binary expression with comprehensive optimization rules.
326fn normalize_binary(op: BinaryOp, left: Expression, right: Expression) -> Expression {
327    // 1. Identity elimination for AND
328    if op == BinaryOp::And {
329        if is_true_literal(&left) {
330            return right;
331        }
332        if is_true_literal(&right) {
333            return left;
334        }
335    }
336
337    // 2. Identity elimination for OR
338    if op == BinaryOp::Or {
339        if is_false_literal(&left) {
340            return right;
341        }
342        if is_false_literal(&right) {
343            return left;
344        }
345    }
346
347    // 3. Domination rules (short-circuit)
348    if op == BinaryOp::And && (is_false_literal(&left) || is_false_literal(&right)) {
349        return Expression::Literal(serde_json::Value::Bool(false));
350    }
351    if op == BinaryOp::Or && (is_true_literal(&left) || is_true_literal(&right)) {
352        return Expression::Literal(serde_json::Value::Bool(true));
353    }
354
355    // 4. Idempotence: a AND a → a, a OR a → a
356    if (op == BinaryOp::And || op == BinaryOp::Or) && left == right {
357        return left;
358    }
359
360    // 5. Absorption: a OR (a AND b) → a, a AND (a OR b) → a
361    if op == BinaryOp::Or {
362        if let Some(result) = try_absorb(&left, &right, BinaryOp::And) {
363            return result;
364        }
365        if let Some(result) = try_absorb(&right, &left, BinaryOp::And) {
366            return result;
367        }
368    }
369    if op == BinaryOp::And {
370        if let Some(result) = try_absorb(&left, &right, BinaryOp::Or) {
371            return result;
372        }
373        if let Some(result) = try_absorb(&right, &left, BinaryOp::Or) {
374            return result;
375        }
376    }
377
378    // 6. Flatten chains: (a AND b) AND c → collect [a, b, c] and rebuild sorted
379    if is_commutative(&op) {
380        let mut operands = collect_chain(&op, &left);
381        operands.extend(collect_chain(&op, &right));
382
383        // Deduplicate (idempotence across chain)
384        operands.sort_by_key(expr_cmp_key);
385        operands.dedup();
386
387        // Re-apply absorption across the flattened chain
388        // e.g. (A) AND (A OR B) -> A
389        let partner_op = match op {
390            BinaryOp::Or => Some(BinaryOp::And),
391            BinaryOp::And => Some(BinaryOp::Or),
392            _ => None,
393        };
394
395        if let Some(partner) = partner_op {
396            let mut indices_to_remove = std::collections::HashSet::new();
397            for i in 0..operands.len() {
398                if indices_to_remove.contains(&i) {
399                    continue;
400                }
401                for j in (i + 1)..operands.len() {
402                    if indices_to_remove.contains(&j) {
403                        continue;
404                    }
405
406                    // Check if i absorbs j
407                    if try_absorb(&operands[i], &operands[j], partner.clone()).is_some() {
408                        indices_to_remove.insert(j);
409                        continue;
410                    }
411
412                    // Check if j absorbs i
413                    if try_absorb(&operands[j], &operands[i], partner.clone()).is_some() {
414                        indices_to_remove.insert(i);
415                        break; // i is removed, move to next i
416                    }
417                }
418            }
419
420            if !indices_to_remove.is_empty() {
421                let mut new_operands = Vec::with_capacity(operands.len() - indices_to_remove.len());
422                for (i, op) in operands.into_iter().enumerate() {
423                    if !indices_to_remove.contains(&i) {
424                        new_operands.push(op);
425                    }
426                }
427                operands = new_operands;
428                // Re-sort/dedup not strictly necessary if order preserved and absorption is clean,
429                // but good for safety if absorption produced duplicates (unlikely here).
430            }
431        }
432
433        // Rebuild balanced tree
434        return build_balanced_tree(op, operands);
435    }
436
437    // 7. Non-commutative: just preserve order
438    Expression::Binary {
439        op,
440        left: Box::new(left),
441        right: Box::new(right),
442    }
443}
444
445/// Check for absorption pattern: if `outer` can absorb `inner`.
446/// Returns `Some(outer)` if absorption applies, `None` otherwise.
447fn try_absorb(outer: &Expression, inner: &Expression, inner_op: BinaryOp) -> Option<Expression> {
448    // Check if inner is a binary expression with inner_op containing outer
449    if let Expression::Binary { op, left, right } = inner {
450        if *op == inner_op && (left.as_ref() == outer || right.as_ref() == outer) {
451            return Some(outer.clone());
452        }
453    }
454    None
455}
456
457/// Collect all operands from a chain of the same operator.
458fn collect_chain(op: &BinaryOp, expr: &Expression) -> Vec<Expression> {
459    if let Expression::Binary {
460        op: inner_op,
461        left,
462        right,
463    } = expr
464    {
465        if inner_op == op {
466            let mut result = collect_chain(op, left);
467            result.extend(collect_chain(op, right));
468            return result;
469        }
470    }
471    vec![expr.clone()]
472}
473
474/// Build a balanced binary tree from a list of operands.
475fn build_balanced_tree(op: BinaryOp, mut operands: Vec<Expression>) -> Expression {
476    if operands.is_empty() {
477        // Return identity element
478        return match op {
479            BinaryOp::And => Expression::Literal(serde_json::Value::Bool(true)),
480            BinaryOp::Or => Expression::Literal(serde_json::Value::Bool(false)),
481            BinaryOp::Plus => Expression::Literal(serde_json::Value::Number(0.into())),
482            BinaryOp::Multiply => Expression::Literal(serde_json::Value::Number(1.into())),
483            _ => Expression::Literal(serde_json::Value::Null),
484        };
485    }
486
487    if operands.len() == 1 {
488        return operands.remove(0);
489    }
490
491    // Build left-to-right for determinism (after sorting)
492    let first = operands.remove(0);
493    operands
494        .into_iter()
495        .fold(first, |acc, next| Expression::Binary {
496            op: op.clone(),
497            left: Box::new(acc),
498            right: Box::new(next),
499        })
500}
501
502// ============================================================================
503// Unary Expression Normalization
504// ============================================================================
505
506/// Normalize a unary expression with double negation elimination and De Morgan.
507fn normalize_unary(op: UnaryOp, operand: Expression) -> Expression {
508    match op {
509        UnaryOp::Not => {
510            // Double negation elimination: NOT NOT x → x
511            if let Expression::Unary {
512                op: UnaryOp::Not,
513                operand: inner,
514            } = &operand
515            {
516                return inner.as_ref().clone();
517            }
518
519            // Comparison negation: NOT (a == b) → a != b, NOT (a != b) → a == b
520            if let Expression::Binary {
521                op: inner_op,
522                left,
523                right,
524            } = &operand
525            {
526                let maybe_negated = match inner_op {
527                    BinaryOp::Equal => Some(BinaryOp::NotEqual),
528                    BinaryOp::NotEqual => Some(BinaryOp::Equal),
529                    BinaryOp::GreaterThan => Some(BinaryOp::LessThanOrEqual),
530                    BinaryOp::LessThan => Some(BinaryOp::GreaterThanOrEqual),
531                    BinaryOp::GreaterThanOrEqual => Some(BinaryOp::LessThan),
532                    BinaryOp::LessThanOrEqual => Some(BinaryOp::GreaterThan),
533                    _ => None,
534                };
535                if let Some(negated_op) = maybe_negated {
536                    return Expression::Binary {
537                        op: negated_op,
538                        left: left.clone(),
539                        right: right.clone(),
540                    };
541                }
542            }
543
544            Expression::Unary {
545                op: UnaryOp::Not,
546                operand: Box::new(operand),
547            }
548        }
549        UnaryOp::Negate => Expression::Unary {
550            op: UnaryOp::Negate,
551            operand: Box::new(operand),
552        },
553    }
554}
555
556// ============================================================================
557// Helper Functions
558// ============================================================================
559
560/// Check if an operator is commutative (operand order doesn't matter).
561fn is_commutative(op: &BinaryOp) -> bool {
562    matches!(
563        op,
564        BinaryOp::And
565            | BinaryOp::Or
566            | BinaryOp::Equal
567            | BinaryOp::NotEqual
568            | BinaryOp::Plus
569            | BinaryOp::Multiply
570    )
571}
572
573/// Generate a comparison key for lexicographic sorting of expressions.
574fn expr_cmp_key(expr: &Expression) -> String {
575    // Use canonical serialization for stable comparison
576    canonical_serialize(expr)
577}
578
579/// Recursively serialized expression to a stable string representation
580fn canonical_serialize(expr: &Expression) -> String {
581    use std::fmt::Write;
582    let mut out = String::new();
583
584    match expr {
585        Expression::Literal(v) => write!(out, "Lit({})", v).unwrap(),
586        Expression::Variable(s) => write!(out, "Var({})", s).unwrap(),
587        Expression::QuantityLiteral { value, unit } => {
588            write!(out, "Quant({}, {:?})", value, unit).unwrap()
589        }
590        Expression::TimeLiteral(s) => write!(out, "Time({})", s).unwrap(),
591        Expression::IntervalLiteral { start, end } => {
592            write!(out, "Int({}, {})", start, end).unwrap()
593        }
594        Expression::MemberAccess { object, member } => {
595            write!(out, "Mem({}, {})", object, member).unwrap()
596        }
597        Expression::Binary { op, left, right } => write!(
598            out,
599            "Bin({:?}, {}, {})",
600            op,
601            canonical_serialize(left),
602            canonical_serialize(right)
603        )
604        .unwrap(),
605        Expression::Unary { op, operand } => {
606            write!(out, "Un({:?}, {})", op, canonical_serialize(operand)).unwrap()
607        }
608        Expression::Cast {
609            operand,
610            target_type,
611        } => write!(
612            out,
613            "Cast({}, {:?})",
614            canonical_serialize(operand),
615            target_type
616        )
617        .unwrap(),
618        Expression::Quantifier {
619            quantifier,
620            variable,
621            collection,
622            condition,
623        } => write!(
624            out,
625            "Quant({:?}, {}, {}, {})",
626            quantifier,
627            variable,
628            canonical_serialize(collection),
629            canonical_serialize(condition)
630        )
631        .unwrap(),
632        Expression::GroupBy {
633            variable,
634            collection,
635            filter,
636            key,
637            condition,
638        } => {
639            let f_str = filter
640                .as_ref()
641                .map(|f| canonical_serialize(f))
642                .unwrap_or_else(|| "None".into());
643            write!(
644                out,
645                "Group({}, {}, {}, {}, {})",
646                variable,
647                canonical_serialize(collection),
648                f_str,
649                canonical_serialize(key),
650                canonical_serialize(condition)
651            )
652            .unwrap()
653        }
654        Expression::Aggregation {
655            function,
656            collection,
657            field,
658            filter,
659        } => {
660            let f_str = filter
661                .as_ref()
662                .map(|f| canonical_serialize(f))
663                .unwrap_or_else(|| "None".into());
664            let field_str = field.as_ref().map(|s| s.as_str()).unwrap_or("None");
665            write!(
666                out,
667                "Agg({:?}, {}, {}, {})",
668                function,
669                canonical_serialize(collection),
670                field_str,
671                f_str
672            )
673            .unwrap()
674        }
675        Expression::AggregationComprehension {
676            function,
677            variable,
678            collection,
679            window,
680            predicate,
681            projection,
682            target_unit,
683        } => {
684            let w_str = window
685                .as_ref()
686                .map(|w| format!("{:?}", w))
687                .unwrap_or_else(|| "None".into());
688            let tu_str = target_unit.as_deref().unwrap_or("None");
689            write!(
690                out,
691                "AggComp({:?}, {}, {}, {}, {}, {}, {})",
692                function,
693                variable,
694                canonical_serialize(collection),
695                w_str,
696                canonical_serialize(predicate),
697                canonical_serialize(projection),
698                tu_str
699            )
700            .unwrap()
701        }
702        Expression::RoleReference { role } => write!(out, "RoleRef({})", role).unwrap(),
703    }
704    out
705}
706
707/// Check if expression is the literal `true`.
708fn is_true_literal(expr: &Expression) -> bool {
709    matches!(expr, Expression::Literal(v) if v.as_bool() == Some(true))
710}
711
712/// Check if expression is the literal `false`.
713fn is_false_literal(expr: &Expression) -> bool {
714    matches!(expr, Expression::Literal(v) if v.as_bool() == Some(false))
715}
716
717// ============================================================================
718// Tests
719// ============================================================================
720
721#[cfg(test)]
722mod tests {
723    use super::*;
724    use crate::policy::Quantifier;
725
726    #[test]
727    fn test_literal_normalization() {
728        let expr = Expression::literal(true);
729        let norm = NormalizedExpression::new(&expr);
730        assert_eq!(norm.to_string(), "true");
731    }
732
733    #[test]
734    fn test_variable_normalization() {
735        let expr = Expression::variable("x");
736        let norm = NormalizedExpression::new(&expr);
737        assert_eq!(norm.to_string(), "x");
738    }
739
740    #[test]
741    fn test_commutative_sorting_and() {
742        // b AND a should normalize to (a AND b)
743        let expr = Expression::binary(
744            BinaryOp::And,
745            Expression::variable("b"),
746            Expression::variable("a"),
747        );
748        let norm = NormalizedExpression::new(&expr);
749        assert_eq!(norm.to_string(), "(a AND b)");
750    }
751
752    #[test]
753    fn test_commutative_sorting_or() {
754        // z OR y should normalize to (y OR z)
755        let expr = Expression::binary(
756            BinaryOp::Or,
757            Expression::variable("z"),
758            Expression::variable("y"),
759        );
760        let norm = NormalizedExpression::new(&expr);
761        assert_eq!(norm.to_string(), "(y OR z)");
762    }
763
764    #[test]
765    fn test_identity_elimination_and_true() {
766        // true AND x → x
767        let expr = Expression::binary(
768            BinaryOp::And,
769            Expression::literal(true),
770            Expression::variable("x"),
771        );
772        let norm = NormalizedExpression::new(&expr);
773        assert_eq!(norm.to_string(), "x");
774    }
775
776    #[test]
777    fn test_identity_elimination_and_true_right() {
778        // x AND true → x
779        let expr = Expression::binary(
780            BinaryOp::And,
781            Expression::variable("x"),
782            Expression::literal(true),
783        );
784        let norm = NormalizedExpression::new(&expr);
785        assert_eq!(norm.to_string(), "x");
786    }
787
788    #[test]
789    fn test_identity_elimination_or_false() {
790        // false OR x → x
791        let expr = Expression::binary(
792            BinaryOp::Or,
793            Expression::literal(false),
794            Expression::variable("x"),
795        );
796        let norm = NormalizedExpression::new(&expr);
797        assert_eq!(norm.to_string(), "x");
798    }
799
800    #[test]
801    fn test_domination_and_false() {
802        // false AND x → false
803        let expr = Expression::binary(
804            BinaryOp::And,
805            Expression::literal(false),
806            Expression::variable("x"),
807        );
808        let norm = NormalizedExpression::new(&expr);
809        assert_eq!(norm.to_string(), "false");
810    }
811
812    #[test]
813    fn test_domination_or_true() {
814        // true OR x → true
815        let expr = Expression::binary(
816            BinaryOp::Or,
817            Expression::literal(true),
818            Expression::variable("x"),
819        );
820        let norm = NormalizedExpression::new(&expr);
821        assert_eq!(norm.to_string(), "true");
822    }
823
824    #[test]
825    fn test_idempotence_and() {
826        // a AND a → a
827        let expr = Expression::binary(
828            BinaryOp::And,
829            Expression::variable("a"),
830            Expression::variable("a"),
831        );
832        let norm = NormalizedExpression::new(&expr);
833        assert_eq!(norm.to_string(), "a");
834    }
835
836    #[test]
837    fn test_idempotence_or() {
838        // a OR a → a
839        let expr = Expression::binary(
840            BinaryOp::Or,
841            Expression::variable("a"),
842            Expression::variable("a"),
843        );
844        let norm = NormalizedExpression::new(&expr);
845        assert_eq!(norm.to_string(), "a");
846    }
847
848    #[test]
849    fn test_absorption_or() {
850        // a OR (a AND b) → a
851        let expr = Expression::binary(
852            BinaryOp::Or,
853            Expression::variable("a"),
854            Expression::binary(
855                BinaryOp::And,
856                Expression::variable("a"),
857                Expression::variable("b"),
858            ),
859        );
860        let norm = NormalizedExpression::new(&expr);
861        assert_eq!(norm.to_string(), "a");
862    }
863
864    #[test]
865    fn test_absorption_and() {
866        // a AND (a OR b) → a
867        let expr = Expression::binary(
868            BinaryOp::And,
869            Expression::variable("a"),
870            Expression::binary(
871                BinaryOp::Or,
872                Expression::variable("a"),
873                Expression::variable("b"),
874            ),
875        );
876        let norm = NormalizedExpression::new(&expr);
877        assert_eq!(norm.to_string(), "a");
878    }
879
880    #[test]
881    fn test_double_negation_elimination() {
882        // NOT NOT x → x
883        let expr = Expression::unary(
884            UnaryOp::Not,
885            Expression::unary(UnaryOp::Not, Expression::variable("x")),
886        );
887        let norm = NormalizedExpression::new(&expr);
888        assert_eq!(norm.to_string(), "x");
889    }
890
891    #[test]
892    fn test_de_morgan_equal() {
893        // NOT (a == b) → a != b
894        let expr = Expression::unary(
895            UnaryOp::Not,
896            Expression::binary(
897                BinaryOp::Equal,
898                Expression::variable("a"),
899                Expression::variable("b"),
900            ),
901        );
902        let norm = NormalizedExpression::new(&expr);
903        assert_eq!(norm.to_string(), "(a != b)");
904    }
905
906    #[test]
907    fn test_de_morgan_not_equal() {
908        // NOT (a != b) → a == b
909        let expr = Expression::unary(
910            UnaryOp::Not,
911            Expression::binary(
912                BinaryOp::NotEqual,
913                Expression::variable("a"),
914                Expression::variable("b"),
915            ),
916        );
917        let norm = NormalizedExpression::new(&expr);
918        assert_eq!(norm.to_string(), "(a == b)");
919    }
920
921    #[test]
922    fn test_de_morgan_greater_than() {
923        // NOT (a > b) → a <= b
924        let expr = Expression::unary(
925            UnaryOp::Not,
926            Expression::binary(
927                BinaryOp::GreaterThan,
928                Expression::variable("a"),
929                Expression::variable("b"),
930            ),
931        );
932        let norm = NormalizedExpression::new(&expr);
933        assert_eq!(norm.to_string(), "(a <= b)");
934    }
935
936    #[test]
937    fn test_chain_flattening_and() {
938        // (a AND b) AND c → (a AND b AND c) sorted
939        let expr = Expression::binary(
940            BinaryOp::And,
941            Expression::binary(
942                BinaryOp::And,
943                Expression::variable("c"),
944                Expression::variable("a"),
945            ),
946            Expression::variable("b"),
947        );
948        let norm = NormalizedExpression::new(&expr);
949        // Should be sorted: a AND b AND c
950        assert_eq!(norm.to_string(), "((a AND b) AND c)");
951    }
952
953    #[test]
954    fn test_chain_deduplication() {
955        // a AND b AND a → a AND b (sorted)
956        let expr = Expression::binary(
957            BinaryOp::And,
958            Expression::binary(
959                BinaryOp::And,
960                Expression::variable("a"),
961                Expression::variable("b"),
962            ),
963            Expression::variable("a"),
964        );
965        let norm = NormalizedExpression::new(&expr);
966        assert_eq!(norm.to_string(), "(a AND b)");
967    }
968
969    #[test]
970    fn test_equivalence_commutative() {
971        let a_and_b = Expression::binary(
972            BinaryOp::And,
973            Expression::variable("a"),
974            Expression::variable("b"),
975        );
976        let b_and_a = Expression::binary(
977            BinaryOp::And,
978            Expression::variable("b"),
979            Expression::variable("a"),
980        );
981        let norm1 = NormalizedExpression::new(&a_and_b);
982        let norm2 = NormalizedExpression::new(&b_and_a);
983        assert_eq!(norm1, norm2);
984    }
985
986    #[test]
987    fn test_stable_hash_deterministic() {
988        let expr = Expression::binary(
989            BinaryOp::Or,
990            Expression::variable("x"),
991            Expression::literal(false),
992        );
993        let h1 = NormalizedExpression::new(&expr).stable_hash();
994        let h2 = NormalizedExpression::new(&expr).stable_hash();
995        assert_eq!(h1, h2);
996    }
997
998    #[test]
999    fn test_nested_normalization() {
1000        // (true AND (b OR a)) → (a OR b)
1001        let nested = Expression::binary(
1002            BinaryOp::And,
1003            Expression::literal(true),
1004            Expression::binary(
1005                BinaryOp::Or,
1006                Expression::variable("b"),
1007                Expression::variable("a"),
1008            ),
1009        );
1010        let norm = NormalizedExpression::new(&nested);
1011        assert_eq!(norm.to_string(), "(a OR b)");
1012    }
1013
1014    #[test]
1015    fn test_quantifier_normalization() {
1016        let expr = Expression::quantifier(
1017            Quantifier::ForAll,
1018            "x",
1019            Expression::variable("items"),
1020            Expression::binary(
1021                BinaryOp::And,
1022                Expression::literal(true),
1023                Expression::variable("valid"),
1024            ),
1025        );
1026        let norm = NormalizedExpression::new(&expr);
1027        // Condition should be simplified: true AND valid → valid
1028        assert!(norm.to_string().contains("valid"));
1029        assert!(!norm.to_string().contains("true"));
1030    }
1031}