vortex_expr/forms/
cnf.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use vortex_error::VortexResult;

use super::nnf::nnf;
use crate::traversal::{Node as _, NodeVisitor, TraversalOrder};
use crate::{BinaryExpr, ExprRef, Operator};

/// Return an equivalent expression in Conjunctive Normal Form (CNF).
///
/// A CNF expression is a vector of vectors. The outer vector is a conjunction. The inner vectors
/// are disjunctions. Neither [Operator::And] nor [Operator::Or] may appear in the
/// disjunctions. Moreover, each disjunction in a CNF expression must be in Negative Normal Form.
///
/// # Examples
///
/// All the NNF examples also apply to CNF, for example double negation is removed entirely:
///
/// ```
/// use vortex_expr::{not, col};
/// use vortex_expr::forms::cnf::cnf;
///
/// let double_negation = not(not(col("a")));
/// let cnfed = cnf(double_negation).unwrap();
/// assert_eq!(cnfed, vec![vec![col("a")]]);
/// ```
///
/// Unlike NNF, CNF, lifts conjunctions to the top-level and distributions disjunctions such that
/// there is at most one disjunction for each conjunction operand:
///
/// ```
/// use vortex_expr::{not, col, or, and};
/// use vortex_expr::forms::cnf::cnf;
///
/// assert_eq!(
///     cnf(
///         or(
///             or(
///                 and(col("a"), col("b")),
///                 col("c")
///             ),
///             col("d")
///         )
///     ).unwrap(),
///     vec![
///         vec![col("a"), col("c"), col("d")],
///         vec![col("b"), col("c"), col("d")]
///     ]
/// );
/// ```
///
/// ```
/// use vortex_expr::{not, col, or, and};
/// use vortex_expr::forms::cnf::cnf;
///
/// assert_eq!(
///     cnf(
///         or(
///             and(col("a"), col("b")),
///             col("c"),
///         )
///     ).unwrap(),
///     vec![
///         vec![col("a"), col("c")],
///         vec![col("b"), col("c")],
///     ]
/// );
/// ```
///
/// Vortex extends the CNF definition to any Boolean-valued expression, even ones with non-Boolean
/// parameters:
///
/// ```
/// use vortex_expr::{not, col, or, and, gt_eq, lit, not_eq, lt, eq};
/// use vortex_expr::forms::cnf::cnf;
/// use itertools::Itertools;
///
/// assert_eq!(
///     cnf(
///         or(
///             and(
///                 gt_eq(col("earnings"), lit(50_000)),
///                 not_eq(col("role"), lit("Manager"))
///             ),
///             col("special_flag")
///         ),
///     ).unwrap(),
///     vec![
///         vec![
///             gt_eq(col("earnings"), lit(50_000)),
///             col("special_flag")
///         ],
///         vec![
///             not_eq(col("role"), lit("Manager")),
///             col("special_flag")
///         ]
///     ]
/// );
/// ```
///
/// ```
/// use vortex_expr::{not, col, or, and, gt_eq, lit, not_eq, lt, eq};
/// use vortex_expr::forms::cnf::cnf;
/// use itertools::Itertools;
///
/// assert_eq!(
///     cnf(
///         or(
///             or(
///                 and(
///                     gt_eq(col("earnings"), lit(50_000)),
///                     not_eq(col("role"), lit("Manager"))
///                 ),
///                 col("special_flag")
///             ),
///             and(
///                 lt(col("tenure"), lit(5)),
///                 eq(col("role"), lit("Engineer"))
///             ),
///         )
///     ).unwrap(),
///     vec![
///         vec![
///             gt_eq(col("earnings"), lit(50_000)),
///             col("special_flag"),
///             lt(col("tenure"), lit(5)),
///         ],
///         vec![
///             gt_eq(col("earnings"), lit(50_000)),
///             col("special_flag"),
///             eq(col("role"), lit("Engineer")),
///         ],
///         vec![
///             not_eq(col("role"), lit("Manager")),
///             col("special_flag"),
///             lt(col("tenure"), lit(5)),
///         ],
///         vec![
///             not_eq(col("role"), lit("Manager")),
///             col("special_flag"),
///             eq(col("role"), lit("Engineer")),
///         ],
///     ]
/// );
/// ```
///
pub fn cnf(expr: ExprRef) -> VortexResult<Vec<Vec<ExprRef>>> {
    let nnf = nnf(expr)?;

    let mut visitor = CNFVisitor::default();
    nnf.accept(&mut visitor)?;
    Ok(visitor.finish())
}

#[derive(Default)]
struct CNFVisitor {
    conjuncts_of_disjuncts: Vec<Vec<ExprRef>>,
}

impl CNFVisitor {
    fn finish(self) -> Vec<Vec<ExprRef>> {
        self.conjuncts_of_disjuncts
    }
}

impl NodeVisitor<'_> for CNFVisitor {
    type NodeTy = ExprRef;

    fn visit_down(&mut self, node: &ExprRef) -> VortexResult<TraversalOrder> {
        if let Some(binary_expr) = node.as_any().downcast_ref::<BinaryExpr>() {
            match binary_expr.op() {
                Operator::And => return Ok(TraversalOrder::Continue),
                Operator::Or => {
                    let mut visitor = CNFVisitor::default();
                    binary_expr.lhs().accept(&mut visitor)?;
                    let lhs_conjuncts = visitor.finish();

                    let mut visitor = CNFVisitor::default();
                    binary_expr.rhs().accept(&mut visitor)?;
                    let rhs_conjuncts = visitor.finish();

                    self.conjuncts_of_disjuncts
                        .extend(lhs_conjuncts.iter().flat_map(|lhs_disjunct| {
                            rhs_conjuncts.iter().map(|rhs_disjunct| {
                                let mut lhs_copy = lhs_disjunct.clone();
                                lhs_copy.extend(rhs_disjunct.iter().cloned());
                                lhs_copy
                            })
                        }));

                    return Ok(TraversalOrder::Skip);
                }
                _ => {}
            }
        }
        // Anything other than And and Or are terminals from the perspective of CNF
        self.conjuncts_of_disjuncts.push(vec![node.clone()]);
        Ok(TraversalOrder::Skip)
    }
}