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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use propositions::*;

/// A proposition made up of the disjunction of possibly negated terms.
///
/// For example the proposition `p \/ ~q \/ r` would be represetnted as the
/// following.
///
/// ```
/// let clause = resolution_prover::Clause {
///     parts: vec!(
///         resolution_prover::ClausePart::Term("p".to_string()),
///         resolution_prover::ClausePart::NegatedTerm("q".to_string()),
///         resolution_prover::ClausePart::Term("r".to_string())
///     )
/// };
/// ```
#[derive(Clone)]
#[derive(Debug)]
#[derive(Eq)]
#[derive(Hash)]
#[derive(PartialEq)]
pub struct Clause {
    pub parts: Vec<ClausePart>
}

impl Clause {
    /// Converts the given proposition into the corresponding clauses. Note
    /// that one proposition could break down into one or more clauses.
    ///
    /// ```
    /// let prop1 = resolution_prover::term("hello".to_string());
    ///
    /// let expected = vec!(resolution_prover::Clause {
    ///     parts: vec!(
    ///         resolution_prover::ClausePart::Term("hello".to_string())
    ///     )
    /// });
    ///
    /// assert_eq!(
    ///     resolution_prover::Clause::from_proposition(prop1),
    ///     expected
    /// );
    /// ```
    pub fn from_proposition(prop: Proposition) -> Vec<Clause> {
        let all_parts = Clause::break_into_clauses(prop);

        all_parts.iter()
            .map(|parts| Clause { parts: parts.to_vec() })
            .collect()
    }

    /// Breaks down the given proposition into the parts of the equivalent
    /// clauses.
    ///
    /// In the returned value, the first level of `Vec` represents the
    /// different clauses, and the second level of `Vec` represents the parts
    /// of that specific clause.
    fn break_into_clauses(prop: Proposition) -> Vec<Vec<ClausePart>> {
        let no_implication = Clause::eliminate_implication(prop);
        let red_negations = Clause::reduce_negation(no_implication);
        let bubbled = Clause::bubble_up_ands(red_negations);
        let or_not_props = Clause::split_on_ands(bubbled);

        or_not_props.iter()
            .map(|p| Clause::from_or_not_prop(p))
            .collect()
    }

    /// Converts the given proposition to an equivalent proposition that does
    /// not use any instances of implication or biconditional.
    ///
    /// The conversions are done by breaking biconditionals into the and of
    /// the implication in each direction, and then converting the implications
    /// into the disjunction of the negation of the antecedent and the
    /// consequent.
    fn eliminate_implication(prop: Proposition) -> Proposition {
        match prop {
            Proposition::Implies(a, b) => {
                let a_simpl = Clause::eliminate_implication(*a);
                let b_simpl = Clause::eliminate_implication(*b);
                or(not(a_simpl), b_simpl)
            },
            Proposition::Iff(a, b) => {
                and(
                    Clause::eliminate_implication(implies(*a.clone(), *b.clone())),
                    Clause::eliminate_implication(implies(*b, *a))
                )
            }
            p => p
        }
    }

    /// Reduces the score of the negation in the given proposition, moving the
    /// negation inwards as far as possible.
    ///
    /// The conversion is done by eliminating double negations and using
    /// deMorgan's law.
    ///
    /// # Panics
    ///
    /// This function assumes that all implications and biconditionals have
    /// already been removed from the proposition, and will panic upon finding
    /// any.
    fn reduce_negation(prop: Proposition) -> Proposition {
        match prop {
            Proposition::Not(a) => {
                let a2 = *a; // Pull the value out to allow multiple matching
                match a2 {
                    Proposition::Not(b) => Clause::reduce_negation(*b),
                    Proposition::And(b, c) => or(
                        Clause::reduce_negation(not(*b)),
                        Clause::reduce_negation(not(*c))
                    ),
                    Proposition::Or(b, c) => and(
                        Clause::reduce_negation(not(*b)),
                        Clause::reduce_negation(not(*c))
                    ),
                    Proposition::Term(b) => not(term(b)),
                    p => panic!("Unexpected implies or iff: {}", not(p))
                }
            },
            Proposition::Or(a, b) => or(
                Clause::reduce_negation(*a),
                Clause::reduce_negation(*b)
            ),
            Proposition::And(a, b) => and(
                Clause::reduce_negation(*a),
                Clause::reduce_negation(*b)
            ),
            Proposition::Term(a) => term(a),
            p => panic!("Unexpected implies or iff: {}", p)
        }
    }

    /// Bubbles up the conjunctions in the given proposition so that the
    /// proposition becomes the conjunctions of terms and disjunctions.
    ///
    /// This conversion is done by using the distributed property of
    /// conujunctions and disjunctions.
    fn bubble_up_ands(prop: Proposition) -> Proposition {
        match Clause::bubble_up_ands_(prop, false) {
            (p, _) => p
        }
    }

    fn bubble_up_ands_(prop: Proposition, cleared: bool) -> (Proposition, bool) {
        let handled = match (prop, cleared) {
            (p, true) => p,
            (Proposition::Term(a), _) => term(a),
            (Proposition::Not(a), _) =>
                not(Clause::bubble_up_ands_(*a, false).0),
            (Proposition::Or(a, b), _) => {
                let a_bubbled = Clause::bubble_up_ands_(*a, false).0;
                let b_bubbled = Clause::bubble_up_ands_(*b, false).0;

                or(a_bubbled, b_bubbled)
            },
            (Proposition::And(a, b), _) => {
                let a_bubbled = Clause::bubble_up_ands_(*a, false).0;
                let b_bubbled = Clause::bubble_up_ands_(*b, false).0;

                and(a_bubbled, b_bubbled)
            },
            (p, _) => Clause::bubble_up_ands_(p, false).0,
        };

        match handled {
            Proposition::Or(a, b) => {
                let a2 = *a;
                let b2 = *b;
                match (a2, b2) {
                    (Proposition::And(c, d), e) =>
                        (and(
                            or(*c, e.clone()),
                            or(*d, e)
                        ), true),
                    (c, Proposition::And(d, e)) =>
                        (and(
                            or(c.clone(), *d),
                            or(c, *e)
                        ), true),
                    (p1, p2) => (or(p1, p2), true)
                }
            },
            Proposition::And(a, b) => (and(*a, *b), true),
            Proposition::Not(a) => (not(*a), true),
            Proposition::Term(a) => (term(a), true),
            p => panic!("Unexpected implies or iff: {}", p)
        }
    }

    /// Splits the given proposition on its conjunctions.
    ///
    /// Assumes that the proposition has already had its conjunctions bubbled
    /// up.
    fn split_on_ands(prop: Proposition) -> Vec<Proposition> {
        match prop {
            Proposition::And(a, b) => {
                let mut a_parts = Clause::split_on_ands(*a);
                let mut b_parts = Clause::split_on_ands(*b);

                a_parts.append(&mut b_parts);

                a_parts
            },
            p => vec!(p)
        }
    }

    /// Converts the given proposition into a set of clause parts by splitting
    /// it on the disjunctions.
    ///
    /// Assumes that the proposition has been simplified to contain only
    /// disjunctions, negations, and raw terms.
    fn from_or_not_prop(prop: &Proposition) -> Vec<ClausePart> {
        match *prop {
            Proposition::Or(ref a, ref b) => {
                let mut a_parts = Clause::from_or_not_prop(&*a);
                let mut b_parts = Clause::from_or_not_prop(&*b);

                a_parts.append(&mut b_parts);

                a_parts
            },
            Proposition::Not(ref inner) => {
                match **inner {
                    Proposition::Term(ref a) =>
                        vec!(ClausePart::NegatedTerm(a.clone())),
                    _ => panic!("Proposition contained non-(or, not) term: {}", prop)
                }
            },
            Proposition::Term(ref a) => vec!(ClausePart::Term(a.clone())),
            _ => panic!("Proposition contained non-(or, not) term: {}", prop)
        }
    }
}

/// A term or negated term that is part of a clause.
///
/// For example, `p` and `~q` can be represented as the following.
///
/// ```
/// let p = resolution_prover::ClausePart::Term("p".to_string());
///
/// let not_q = resolution_prover::ClausePart::NegatedTerm("q".to_string());
/// ```
#[derive(Clone)]
#[derive(Debug)]
#[derive(Eq)]
#[derive(Hash)]
#[derive(PartialEq)]
pub enum ClausePart {
    Term(String),
    NegatedTerm(String)
}

impl ClausePart {
    /// Returns the negated version of the clause part.
    ///
    /// ```
    /// let clausePart = resolution_prover::ClausePart::Term("p".to_string());
    ///
    /// let neg = clausePart.negate();
    ///
    /// let expected_1 =
    ///     resolution_prover::ClausePart::NegatedTerm("p".to_string());
    ///
    /// assert_eq!(neg, expected_1);
    ///
    /// let double_neg = neg.negate();
    ///
    /// assert_eq!(double_neg, clausePart);
    /// ```
    pub fn negate(&self) -> ClausePart {
        match self {
            ClausePart::Term(a) => ClausePart::NegatedTerm(a.clone()),
            ClausePart::NegatedTerm(a) => ClausePart::Term(a.clone())
        }
    }
}

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

    #[test]
    fn eliminate_implication_implies() {
        let prop = implies(
            term("a".to_string()),
            term("b".to_string())
        );

        let expected = or(
            not(term("a".to_string())),
            term("b".to_string())
        );

        assert_eq!(Clause::eliminate_implication(prop), expected);
    }

    #[test]
    fn eliminate_implication_iff() {
        let prop = iff(
            term("a".to_string()),
            term("b".to_string())
        );

        let expected = and(
            or(
                not(term("a".to_string())),
                term("b".to_string())
            ),
            or(
                not(term("b".to_string())),
                term("a".to_string())
            )
        );

        assert_eq!(Clause::eliminate_implication(prop), expected);
    }

    #[test]
    fn eliminate_implication_and() {
        let prop = and(
            term("a".to_string()),
            term("b".to_string())
        );

        let expected = and(
            term("a".to_string()),
            term("b".to_string())
        );

        assert_eq!(Clause::eliminate_implication(prop), expected);
    }

    #[test]
    fn eliminate_implication_or() {
        let prop = or(
            term("a".to_string()),
            term("b".to_string())
        );

        let expected = or(
            term("a".to_string()),
            term("b".to_string())
        );

        assert_eq!(Clause::eliminate_implication(prop), expected);
    }

    #[test]
    fn eliminate_implication_not() {
        let prop = not(
            term("b".to_string())
        );

        let expected = not(
            term("b".to_string())
        );

        assert_eq!(Clause::eliminate_implication(prop), expected);
    }

    #[test]
    fn reduce_negation_term() {
        let prop = term("b".to_string());

        let expected = term("b".to_string());

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_double_negation() {
        let prop = not(not(
            term("b".to_string())
        ));

        let expected = term("b".to_string());

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_not_and() {
        let prop = not(and(
            term("a".to_string()),
            term("b".to_string())
        ));

        let expected = or(
            not(term("a".to_string())),
            not(term("b".to_string()))
        );

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_not_or() {
        let prop = not(or(
            term("a".to_string()),
            term("b".to_string())
        ));

        let expected = and(
            not(term("a".to_string())),
            not(term("b".to_string()))
        );

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_nested_not_or_double_negation() {
        let prop = not(or(
            term("a".to_string()),
            not(not(term("b".to_string())))
        ));

        let expected = and(
            not(term("a".to_string())),
            not(term("b".to_string()))
        );

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_nested_not_or_or() {
        let prop = not(or(
            term("a".to_string()),
            or(
                term("b".to_string()),
                not(term("c".to_string())),
            )
        ));

        let expected = and(
            not(term("a".to_string())),
            and(
                not(term("b".to_string())),
                term("c".to_string())
            ),
        );

        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_nested_and_not_and() {
        let prop = and(
            not(and(
                term("a".to_string()),
                term("b".to_string())
            )),
            term("c".to_string())
        );

        let expected = and(
            or(
                not(term("a".to_string())),
                not(term("b".to_string()))
            ),
            term("c".to_string())
        );


        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn reduce_negation_nested_or_not_and() {
        let prop = or(
            not(and(
                term("a".to_string()),
                term("b".to_string())
            )),
            term("c".to_string())
        );

        let expected = or(
            or(
                not(term("a".to_string())),
                not(term("b".to_string()))
            ),
            term("c".to_string())
        );


        assert_eq!(Clause::reduce_negation(prop), expected);
    }

    #[test]
    fn bubble_up_ands_term() {
        let prop = term("a".to_string());

        let expected = term("a".to_string());

        assert_eq!(Clause::bubble_up_ands(prop), expected);
    }

    #[test]
    fn bubble_up_ands_or() {
        let prop = or(
            term("a".to_string()),
            term("b".to_string())
        );

        let expected = or(
            term("a".to_string()),
            term("b".to_string())
        );

        assert_eq!(Clause::bubble_up_ands(prop), expected);
    }

    #[test]
    fn bubble_up_ands_or_and_left() {
        let prop = or(
            and(
                term("a".to_string()),
                term("b".to_string())
            ),
            term("c".to_string()),
        );

        let expected = and(
            or(
                term("a".to_string()),
                term("c".to_string())
            ),
            or(
                term("b".to_string()),
                term("c".to_string())
            ),
        );

        assert_eq!(Clause::bubble_up_ands(prop), expected);
    }

    #[test]
    fn bubble_up_ands_or_and_right() {
        let prop = or(
            term("a".to_string()),
            and(
                term("b".to_string()),
                term("c".to_string())
            )
        );

        let expected = and(
            or(
                term("a".to_string()),
                term("b".to_string())
            ),
            or(
                term("a".to_string()),
                term("c".to_string())
            ),
        );

        assert_eq!(Clause::bubble_up_ands(prop), expected);
    }

    #[test]
    fn bubble_up_ands_not() {
        let prop = not(term("a".to_string()));

        let expected = not(term("a".to_string()));

        assert_eq!(Clause::bubble_up_ands(prop), expected);
    }
}