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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
//!
//! Expression parsing proceeds in recursive manner in the order of operator precedence:
//! `<=>`, `=>`, `|`, `&` and `^`. For each operator, if there is no occurrence in the root of the
//! token tree, we forward the tree to next operator. If there is an occurrence, we split
//! the token tree at this point. Left part goes to the next operator, right part is processed
//! by the same operator to extract additional occurrences.

use super::super::NOT_IN_VAR_NAME;
use super::BooleanExpression;
use super::BooleanExpression::*;
use std::iter::Peekable;
use std::str::Chars;

/// **(internal)** Tokens that can appear in the boolean expression.
/// The tokens form a token tree defined by parenthesis groups.
#[derive(Debug, Eq, PartialEq)]
enum ExprToken {
    Not,                    // '!'
    And,                    // '&'
    Or,                     // '|'
    Xor,                    // '^'
    Imp,                    // '=>'
    Iff,                    // '<=>'
    Id(String),             // 'variable'
    Tokens(Vec<ExprToken>), // A block of tokens inside parentheses
}

/// Takes a `String` and turns it into a `BooleanExpression` or `Error` if the string is not valid.
///
/// Syntax for the formula is described in the tutorial.
pub fn parse_boolean_expression(from: &str) -> Result<BooleanExpression, String> {
    let tokens = tokenize_group(&mut from.chars().peekable(), true)?;
    Ok(*(parse_formula(&tokens)?))
}

/// **(internal)** Process a peekable iterator of characters into a vector of `ExprToken`s.
///
/// The outer method always consumes the opening parenthesis and the recursive call consumes the
/// closing parenthesis. Use `top_level` to indicate that there will be no closing parenthesis.
fn tokenize_group(data: &mut Peekable<Chars>, top_level: bool) -> Result<Vec<ExprToken>, String> {
    let mut output = Vec::new();
    while let Some(c) = data.next() {
        match c {
            c if c.is_whitespace() => { /* skip whitespace */ }
            // single char operators
            '!' => output.push(ExprToken::Not),
            '&' => output.push(ExprToken::And),
            '|' => output.push(ExprToken::Or),
            '^' => output.push(ExprToken::Xor),
            '=' => {
                if Some('>') == data.next() {
                    output.push(ExprToken::Imp);
                } else {
                    return Err("Expected '>' after '='.".to_string());
                }
            }
            '<' => {
                if Some('=') == data.next() {
                    if Some('>') == data.next() {
                        output.push(ExprToken::Iff)
                    } else {
                        return Err("Expected '>' after '='.".to_string());
                    }
                } else {
                    return Err("Expected '=' after '<'.".to_string());
                }
            }
            // '>' is invalid as a start of a token
            '>' => return Err("Unexpected '>'.".to_string()),
            ')' => {
                return if !top_level {
                    Ok(output)
                } else {
                    Err("Unexpected ')'.".to_string())
                }
            }
            '(' => {
                // start a nested token group
                let tokens = tokenize_group(data, false)?;
                output.push(ExprToken::Tokens(tokens));
            }
            _ => {
                // start of a variable name
                let mut name = vec![c];
                while let Some(c) = data.peek() {
                    if c.is_whitespace() || NOT_IN_VAR_NAME.contains(c) {
                        break;
                    } else {
                        name.push(*c);
                        data.next(); // advance iterator
                    }
                }
                output.push(ExprToken::Id(name.into_iter().collect()));
            }
        }
    }
    if top_level {
        Ok(output)
    } else {
        Err("Expected ')'.".to_string())
    }
}

/// **(internal)** Parse a `ExprToken` tree into a `BooleanExpression` (or error if invalid).
fn parse_formula(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    iff(data)
}

/// **(internal)** Utility method to find first occurrence of a specific token in the token tree.
fn index_of_first(data: &[ExprToken], token: ExprToken) -> Option<usize> {
    data.iter().position(|t| *t == token)
}

/// **(internal)** Recursive parsing step 1: extract `<=>` operators.
fn iff(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    let iff_token = index_of_first(data, ExprToken::Iff);
    Ok(if let Some(iff_token) = iff_token {
        Box::new(Iff(
            imp(&data[..iff_token])?,
            iff(&data[(iff_token + 1)..])?,
        ))
    } else {
        imp(data)?
    })
}

/// **(internal)** Recursive parsing step 2: extract `=>` operators.
fn imp(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    let imp_token = index_of_first(data, ExprToken::Imp);
    Ok(if let Some(imp_token) = imp_token {
        Box::new(Imp(or(&data[..imp_token])?, imp(&data[(imp_token + 1)..])?))
    } else {
        or(data)?
    })
}

/// **(internal)** Recursive parsing step 3: extract `|` operators.
fn or(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    let or_token = index_of_first(data, ExprToken::Or);
    Ok(if let Some(or_token) = or_token {
        Box::new(Or(and(&data[..or_token])?, or(&data[(or_token + 1)..])?))
    } else {
        and(data)?
    })
}

/// **(internal)** Recursive parsing step 4: extract `&` operators.
fn and(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    let and_token = index_of_first(data, ExprToken::And);
    Ok(if let Some(and_token) = and_token {
        Box::new(And(
            xor(&data[..and_token])?,
            and(&data[(and_token + 1)..])?,
        ))
    } else {
        xor(data)?
    })
}

/// **(internal)** Recursive parsing step 5: extract `^` operators.
fn xor(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    let xor_token = index_of_first(data, ExprToken::Xor);
    Ok(if let Some(xor_token) = xor_token {
        Box::new(Xor(
            terminal(&data[..xor_token])?,
            xor(&data[(xor_token + 1)..])?,
        ))
    } else {
        terminal(data)?
    })
}

/// **(internal)** Recursive parsing step 6: extract terminals and negations.
fn terminal(data: &[ExprToken]) -> Result<Box<BooleanExpression>, String> {
    if data.is_empty() {
        Err("Expected formula, found nothing :(".to_string())
    } else if data[0] == ExprToken::Not {
        Ok(Box::new(Not(terminal(&data[1..])?)))
    } else if data.len() > 1 {
        Err(format!(
            "Expected variable name or (...), but found {:?}.",
            data
        ))
    } else {
        match &data[0] {
            ExprToken::Id(name) => {
                if name == "true" {
                    Ok(Box::new(Const(true)))
                } else if name == "false" {
                    Ok(Box::new(Const(false)))
                } else {
                    Ok(Box::new(Variable(name.clone())))
                }
            }
            ExprToken::Tokens(inner) => Ok(parse_formula(inner)?),
            _ => unreachable!(
                "Other tokens are matched by remaining functions, nothing else should remain."
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_boolean_formula_basic() {
        let inputs = vec![
            "v_1+{14}",      // just a variable name with fancy symbols
            "!v_1",          // negation
            "true",          // true
            "false",         // false
            "(v_1 & v_2)",   // and
            "(v_1 | v_2)",   // or
            "(v_1 ^ v_2)",   // xor
            "(v_1 => v_2)",  // imp
            "(v_1 <=> v_2)", // iff
        ];
        for input in inputs {
            assert_eq!(
                input,
                format!("{}", parse_boolean_expression(input).unwrap())
            );
        }
    }

    #[test]
    fn parse_boolean_formula_operator_priority() {
        assert_eq!(
            "(((((!a ^ !b) & !c) | !d) => !e) <=> !f)",
            format!(
                "{}",
                parse_boolean_expression("!a ^ !b & !c | !d => !e <=> !f").unwrap()
            )
        )
    }

    #[test]
    fn parse_boolean_formula_operator_associativity() {
        assert_eq!(
            "(a & (b & c))",
            format!("{}", parse_boolean_expression("a & b & c").unwrap())
        );
        assert_eq!(
            "(a | (b | c))",
            format!("{}", parse_boolean_expression("a | b | c").unwrap())
        );
        assert_eq!(
            "(a ^ (b ^ c))",
            format!("{}", parse_boolean_expression("a ^ b ^ c").unwrap())
        );
        assert_eq!(
            "(a => (b => c))",
            format!("{}", parse_boolean_expression("a => b => c").unwrap())
        );
        assert_eq!(
            "(a <=> (b <=> c))",
            format!("{}", parse_boolean_expression("a <=> b <=> c").unwrap())
        );
    }

    #[test]
    fn parse_boolean_formula_complex() {
        assert_eq!(
            "((a & !!b) => (!(t | (!!a & b)) <=> (x ^ y)))",
            format!(
                "{}",
                parse_boolean_expression("a &!(!b)   => (!(t | !!a&b) <=> x^y)").unwrap()
            )
        )
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_token_1() {
        parse_boolean_expression("a = b").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_token_2() {
        parse_boolean_expression("a < b").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_token_3() {
        parse_boolean_expression("a <= b").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_token_4() {
        parse_boolean_expression("a > b").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_parentheses_1() {
        parse_boolean_expression("(a").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_parentheses_2() {
        parse_boolean_expression("b)").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_parentheses_3() {
        parse_boolean_expression("(a & (b)").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_parentheses_4() {
        parse_boolean_expression("a & (b))").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_formula_1() {
        parse_boolean_expression("a & & b").unwrap();
    }

    #[test]
    #[should_panic]
    fn parse_boolean_formula_invalid_formula_2() {
        parse_boolean_expression("a & c d & b").unwrap();
    }
}