sat-solver 0.2.1

A SAT solver implemented in Rust, focusing on performance, efficiency and experimentation.
Documentation
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
//! Defines traits and implementations for literal propagation in a SAT solver.
//!
//! Propagation is the process of deducing new assignments based on the current
//! partial assignment and the clauses of the formula. The most common form is
//! Unit Propagation: if a clause becomes unit (all but one of its literals are
//! false, and the remaining one is unassigned), then that remaining literal
//! must be assigned true to satisfy the clause.
//!
//! This module provides:
//! - The `Propagator` trait, defining a common interface for different propagation strategies.
//! - `WatchedLiterals`: An efficient implementation of unit propagation using the
//!   watched literals scheme. Each clause watches two of its non-false literals.
//!   Propagation only needs to occur when one of these watched literals becomes false.
//! - `UnitSearch`: A simpler, less optimised propagator that iterates through all clauses
//!   to find unit clauses or conflicts.
//! - `UnitPropagationWithPureLiterals`: A propagator that combines unit propagation
//!   with the heuristic of assigning pure literals (literals that appear with only
//!   one polarity in the remaining active formula).

use crate::sat::assignment::Assignment;
use crate::sat::clause::Clause;
use crate::sat::clause_storage::LiteralStorage;
use crate::sat::cnf::Cnf;
use crate::sat::literal::Literal;
use crate::sat::literal::Variable;
use crate::sat::preprocessing::PureLiteralElimination;
use crate::sat::trail::{Reason, Trail};
use clap::ValueEnum;
use itertools::Itertools;
use smallvec::SmallVec;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};

/// Trait defining the interface for a literal propagation mechanism.
///
/// Implementors of this trait are responsible for identifying and applying
/// consequences of the current partial assignment (e.g. unit propagation).
///
/// # Type Parameters
///
/// * `L`: The `Literal` type.
/// * `S`: The `LiteralStorage` type for clauses.
/// * `A`: The `Assignment` type managing variable states.
pub trait Propagator<L: Literal, S: LiteralStorage<L>, A: Assignment>: Debug + Clone {
    /// Creates a new propagator instance
    ///
    /// # Arguments
    ///
    /// * `cnf`: A reference to the `Cnf` formula.
    fn new(cnf: &Cnf<L, S>) -> Self;

    /// Informs the propagator about a new clause being added to the formula.
    /// This is particularly relevant for watched literal schemes to set up watches.
    ///
    /// # Arguments
    ///
    /// * `clause`: The clause being added.
    /// * `idx`: The index of the clause in the `Cnf`'s clause list.
    fn add_clause(&mut self, clause: &Clause<L, S>, idx: usize);

    /// Performs propagation based on the current assignments in the `trail`.
    ///
    /// It iterates through newly assigned literals on the `trail` (those not yet processed
    /// by `propagate`) and deduces further assignments. Enqueued assignments are added
    /// to the `trail` and `assignment` state.
    ///
    /// # Arguments
    ///
    /// * `trail`: Mutable reference to the `Trail`, where new propagations are enqueued.
    /// * `assignment`: Mutable reference to the `Assignment` state.
    /// * `cnf`: Mutable reference to the `Cnf` formula (e.g. for clause access, modification for watched literals).
    ///
    /// # Returns
    ///
    /// - `Some(clause_idx)` if a conflict is detected (clause at `clause_idx` is falsified).
    /// - `None` if propagation completes without conflict.
    fn propagate(
        &mut self,
        trail: &mut Trail<L, S>,
        assignment: &mut A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize>;

    /// Returns the total number of propagations performed by this instance.
    fn num_propagations(&self) -> usize;

    /// Helper function to add a propagated literal to the trail.
    ///
    /// This is a static method often used by propagator implementations.
    /// The propagated literal is assigned at the current decision level of the trail.
    ///
    /// # Arguments
    ///
    /// * `lit`: The literal being propagated.
    /// * `clause_idx`: The index of the clause that forced this propagation (the reason).
    /// * `trail`: Mutable reference to the `Trail`.
    fn add_propagation(lit: L, clause_idx: usize, trail: &mut Trail<L, S>) {
        trail.push(lit, trail.decision_level(), Reason::Clause(clause_idx));
    }

    /// Cleans up internal propagator state related to learnt clauses.
    ///
    /// When learnt clauses are removed or re-indexed during clause database cleaning,
    /// the propagator (especially watched literals) needs to update its references.
    ///
    /// # Arguments
    ///
    /// * `learnt_idx`: An index used to determine which watches to clean. For example,
    ///   watches to clauses with indices `>= learnt_idx` might be removed if
    ///   that part of the clause database was rebuilt.
    fn cleanup_learnt(&mut self, learnt_idx: usize);
}

/// Implements unit propagation using the watched literals scheme (also known as two-watched literals or 2WL).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WatchedLiterals<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize = 8> {
    watches: Vec<SmallVec<[usize; N]>>,
    num_propagations: usize,
    marker: PhantomData<*const (L, S, A)>,
}

impl<L: Literal, S: LiteralStorage<L> + Debug, A: Assignment, const N: usize> Propagator<L, S, A>
    for WatchedLiterals<L, S, A, N>
{
    fn new(cnf: &Cnf<L, S>) -> Self {
        let num_literal_indices = if cnf.num_vars == 0 {
            0
        } else {
            cnf.num_vars * 2
        };
        let st = vec![SmallVec::new(); num_literal_indices];

        let mut wl = Self {
            watches: st,
            num_propagations: 0,
            marker: PhantomData,
        };

        for (i, clause) in cnf
            .iter()
            .enumerate()
            .filter(|(_, c)| c.len() >= 2 && !c.is_unit() && !c.is_deleted())
        {
            wl.add_clause(clause, i);
        }
        wl
    }

    fn add_clause(&mut self, clause: &Clause<L, S>, idx: usize) {
        if clause.len() < 2 || clause.is_deleted() {
            return;
        }
        let a = clause[0];
        let b = clause[1];
        debug_assert_ne!(
            a.variable(),
            b.variable(),
            "Clause {idx}: Attempting to watch two \
        literals of the same variable: {a:?} and {b:?}"
        );

        self[a].push(idx);
        self[b].push(idx);
    }

    fn propagate(
        &mut self,
        trail: &mut Trail<L, S>,
        assignment: &mut A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        while trail.curr_idx < trail.len() {
            let lit = trail[trail.curr_idx].lit;
            trail.curr_idx = trail.curr_idx.wrapping_add(1);
            assignment.assign(lit);
            self.num_propagations = self.num_propagations.wrapping_add(1);

            let watch_list_clone = self[lit.negated().index()].clone();
            if let Some(idx) = self.propagate_watch(&watch_list_clone, trail, assignment, cnf) {
                return Some(idx);
            }
        }
        None
    }

    fn num_propagations(&self) -> usize {
        self.num_propagations
    }

    fn cleanup_learnt(&mut self, learnt_idx: usize) {
        for i in &mut self.watches {
            i.retain(|&mut j| j < learnt_idx);
        }
    }
}

impl<L: Literal, S: LiteralStorage<L> + Debug, A: Assignment, const N: usize>
    WatchedLiterals<L, S, A, N>
{
    /// Propagates watches for the given indices.
    /// /// This method iterates through the provided indices and processes each clause
    /// using `process_clause`. If a clause is found to be falsified, it returns the index
    /// of that clause.
    ///
    /// # Arguments
    /// * `indices`: A slice of indices representing the clauses to process.
    /// * `trail`: A mutable reference to the `Trail` where new propagations are added.
    /// * `assignment`: A reference to the current `Assignment` state.
    /// * `cnf`: A mutable reference to the `Cnf` formula containing the clauses.
    ///
    /// # Returns
    /// * `Some(usize)`: If a clause is found to be falsified, returns the index of that clause.
    /// * `None`: If no clauses are falsified, returns `None`.
    pub fn propagate_watch(
        &mut self,
        indices: &[usize],
        trail: &mut Trail<L, S>,
        assignment: &A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        indices
            .iter()
            .find_map(|&idx| self.process_clause(idx, trail, assignment, cnf))
    }

    /// Processes a clause by checking the values of its watched literals.
    /// This method checks the first two literals of the clause and determines
    /// the outcome based on their values:
    /// - If the first literal is true, the clause is satisfied, and no further action is needed.
    /// - If both literals are false, the clause is falsified, and its index is returned.
    /// - If the first literal is unassigned, it is handled by calling `handle_false`.
    /// - If the second literal is unassigned, it is swapped with the first literal,
    ///   and `handle_false` is called for the second literal.
    ///
    /// # Arguments
    ///
    /// * `clause_idx`: The index of the clause to process.
    /// * `trail`: A mutable reference to the `Trail` where new propagations are added.
    /// * `assignment`: A reference to the current `Assignment` state.
    /// * `cnf`: A mutable reference to the `Cnf` formula containing the clauses.
    ///
    /// # Returns
    ///
    /// * `Some(usize)`: If the clause is found to be falsified, returns the index of that clause.
    /// * `None`: If the clause is satisfied or not falsified, returns `None`.
    pub fn process_clause(
        &mut self,
        clause_idx: usize,
        trail: &mut Trail<L, S>,
        assignment: &A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        let clause = &mut cnf[clause_idx];

        let first = clause[0];
        let second = clause[1];

        let first_value = assignment.literal_value(first);

        if first_value == Some(true) {
            return None;
        }

        let second_value = assignment.literal_value(second);

        match (first_value, second_value) {
            (Some(false), Some(false)) => {
                debug_assert!(
                    clause
                        .iter()
                        .all(|&l| assignment.literal_value(l) == Some(false)),
                    "Clause: {clause:?} is not false, Values: {:?}, idx: {clause_idx}, trail: \
                    {:?}",
                    clause
                        .iter()
                        .map(|&l| assignment.literal_value(l))
                        .collect_vec(),
                    trail,
                );
                Some(clause_idx)
            }
            (None, Some(false)) => {
                self.handle_false(first, clause_idx, assignment, cnf, trail);
                None
            }
            (Some(false), None) => {
                clause.swap(0, 1);
                self.handle_false(second, clause_idx, assignment, cnf, trail);
                None
            }
            (_, Some(true)) => {
                clause.swap(0, 1);
                None
            }
            (Some(true), _) | (None, None) => None,
        }
    }

    fn handle_false(
        &mut self,
        other_lit: L,
        clause_idx: usize,
        assignment: &A,
        cnf: &mut Cnf<L, S>,
        trail: &mut Trail<L, S>,
    ) {
        if let Some(new_lit_idx) = Self::find_new_watch(clause_idx, cnf, assignment) {
            self.handle_new_watch(clause_idx, new_lit_idx, cnf);
        } else {
            debug_assert!(
                assignment.literal_value(other_lit).is_none(),
                "In handle_false, \
            other_lit ({other_lit:?}) was expected to be unassigned but is {:?}. Clause idx \
            {clause_idx}",
                assignment.literal_value(other_lit)
            );
            Self::add_propagation(other_lit, clause_idx, trail);
        }
    }

    fn find_new_watch(clause_idx: usize, cnf: &Cnf<L, S>, assignment: &A) -> Option<usize> {
        let clause = &cnf[clause_idx];
        clause
            .iter()
            .skip(2)
            .position(|&l| assignment.literal_value(l) != Some(false))
            .map(|i| i.wrapping_add(2))
    }

    fn handle_new_watch(&mut self, clause_idx: usize, new_lit_idx: usize, cnf: &mut Cnf<L, S>) {
        debug_assert!(new_lit_idx >= 2);

        let new_lit = cnf[clause_idx][new_lit_idx];
        let prev_lit = cnf[clause_idx][1];

        cnf[clause_idx].swap(1, new_lit_idx);

        self[new_lit].push(clause_idx);

        if let Some(pos) = self[prev_lit].iter().position(|&i| i == clause_idx) {
            self[prev_lit].swap_remove(pos);
        }
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> Index<usize>
    for WatchedLiterals<L, S, A, N>
{
    type Output = SmallVec<[usize; N]>;
    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        unsafe { self.watches.get_unchecked(index) }
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> IndexMut<usize>
    for WatchedLiterals<L, S, A, N>
{
    #[inline]
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        unsafe { self.watches.get_unchecked_mut(index) }
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> Index<Variable>
    for WatchedLiterals<L, S, A, N>
{
    type Output = SmallVec<[usize; N]>;
    #[inline]
    fn index(&self, index: Variable) -> &Self::Output {
        &self[index as usize]
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> IndexMut<Variable>
    for WatchedLiterals<L, S, A, N>
{
    #[inline]
    fn index_mut(&mut self, index: Variable) -> &mut Self::Output {
        &mut self[index as usize]
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> Index<L>
    for WatchedLiterals<L, S, A, N>
{
    type Output = SmallVec<[usize; N]>;
    #[inline]
    fn index(&self, index: L) -> &Self::Output {
        &self[index.index()]
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment, const N: usize> IndexMut<L>
    for WatchedLiterals<L, S, A, N>
{
    #[inline]
    fn index_mut(&mut self, index: L) -> &mut Self::Output {
        &mut self[index.index()]
    }
}

/// A simple unit propagation strategy that iterates through all clauses.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UnitSearch<L: Literal, S: LiteralStorage<L>, A: Assignment>(
    usize, // num_propagations
    PhantomData<(L, S, A)>,
);

impl<L: Literal, S: LiteralStorage<L>, A: Assignment> Propagator<L, S, A> for UnitSearch<L, S, A> {
    fn new(_: &Cnf<L, S>) -> Self {
        Self(0, PhantomData)
    }

    fn add_clause(&mut self, _: &Clause<L, S>, _: usize) {}

    fn propagate(
        &mut self,
        trail: &mut Trail<L, S>,
        assignment: &mut A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        loop {
            let mut new_propagations_this_scan = false;
            while trail.curr_idx < trail.len() {
                let lit = trail[trail.curr_idx].lit;
                trail.curr_idx = trail.curr_idx.wrapping_add(1);
                assignment.assign(lit);
                self.0 = self.0.wrapping_add(1);
            }

            match Self::process_cnf_scan(trail, assignment, cnf) {
                Some(ScanResult::Conflict(idx)) => return Some(idx),
                Some(ScanResult::Propagated) => new_propagations_this_scan = true,
                None => {}
            }

            if !new_propagations_this_scan && trail.curr_idx == trail.len() {
                return None;
            }
        }
    }

    fn num_propagations(&self) -> usize {
        self.0
    }

    fn cleanup_learnt(&mut self, _: usize) {}
}

enum UnitSearchResult<L: Literal> {
    Unsat(usize),
    Unit(L),
    Continue,
}

enum ScanResult {
    Conflict(usize),
    Propagated,
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment> UnitSearch<L, S, A> {
    fn process_cnf_scan(
        trail: &mut Trail<L, S>,
        assignment: &A,
        cnf: &Cnf<L, S>,
    ) -> Option<ScanResult> {
        let mut propagated_in_scan = false;
        for (idx, clause) in cnf.iter().enumerate() {
            if clause.is_deleted() {
                continue;
            }
            match Self::process_clause_eval(clause, assignment, idx) {
                UnitSearchResult::Unsat(idx) => return Some(ScanResult::Conflict(idx)),
                UnitSearchResult::Unit(lit) => {
                    if assignment.var_value(lit.variable()).is_none() {
                        Self::add_propagation(lit, idx, trail);
                        propagated_in_scan = true;
                    }
                }
                UnitSearchResult::Continue => {}
            }
        }
        if propagated_in_scan {
            Some(ScanResult::Propagated)
        } else {
            None
        }
    }

    fn process_clause_eval(
        clause: &Clause<L, S>,
        assignment: &A,
        idx: usize,
    ) -> UnitSearchResult<L> {
        let mut unassigned_lit_opt = None;
        let mut num_unassigned = 0;

        for &lit in clause.iter() {
            match assignment.literal_value(lit) {
                Some(true) => return UnitSearchResult::Continue,
                Some(false) => {}
                None => {
                    num_unassigned += 1;
                    if unassigned_lit_opt.is_none() {
                        unassigned_lit_opt = Some(lit);
                    }
                    if num_unassigned > 1 {
                        return UnitSearchResult::Continue;
                    }
                }
            }
        }

        if num_unassigned == 1 {
            UnitSearchResult::Unit(
                unassigned_lit_opt
                    .expect("num_unassigned is 1, so unassigned_lit_opt must be Some"),
            )
        } else if num_unassigned == 0 {
            UnitSearchResult::Unsat(idx)
        } else {
            UnitSearchResult::Continue
        }
    }
}

/// A propagator that combines `UnitSearch` with periodic pure literal assignment.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct UnitPropagationWithPureLiterals<L: Literal, S: LiteralStorage<L>, A: Assignment>(
    UnitSearch<L, S, A>,
);

impl<L: Literal, S: LiteralStorage<L>, A: Assignment> Propagator<L, S, A>
    for UnitPropagationWithPureLiterals<L, S, A>
{
    fn new(cnf: &Cnf<L, S>) -> Self {
        Self(UnitSearch::new(cnf))
    }

    fn add_clause(&mut self, clause: &Clause<L, S>, idx: usize) {
        self.0.add_clause(clause, idx);
    }

    fn propagate(
        &mut self,
        trail: &mut Trail<L, S>,
        assignment: &mut A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        loop {
            if let Some(idx) = self.0.propagate(trail, assignment, cnf) {
                return Some(idx);
            }

            let trail_len_before_pures = trail.len();
            let curr_idx_before_pures = trail.curr_idx;

            Self::find_pure_literals_assign(trail, assignment, cnf);

            if curr_idx_before_pures == trail.len() && trail_len_before_pures == trail.len() {
                return None;
            }
        }
    }

    fn num_propagations(&self) -> usize {
        self.0.num_propagations()
    }

    fn cleanup_learnt(&mut self, learnt_idx: usize) {
        self.0.cleanup_learnt(learnt_idx);
    }
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment> UnitPropagationWithPureLiterals<L, S, A> {
    fn find_pure_literals_assign(trail: &mut Trail<L, S>, assignment: &A, cnf: &Cnf<L, S>) {
        let pures = PureLiteralElimination::find_pures(&cnf.clauses);
        for &lit in &pures {
            if assignment.var_value(lit.variable()).is_none() {
                Self::add_propagation(lit, 0, trail);
            }
        }
    }
}

/// Enum representing different propagator implementations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PropagatorImpls<L: Literal, S: LiteralStorage<L>, A: Assignment> {
    /// Watched literals propagator.
    WatchedLiterals(WatchedLiterals<L, S, A>),
    /// Unit search propagator.
    UnitSearch(UnitSearch<L, S, A>),
    /// Unit propagation with pure literals propagator.
    UnitPropagationWithPureLiterals(UnitPropagationWithPureLiterals<L, S, A>),
}

impl<L: Literal, S: LiteralStorage<L>, A: Assignment> Propagator<L, S, A>
    for PropagatorImpls<L, S, A>
{
    fn new(cnf: &Cnf<L, S>) -> Self {
        Self::WatchedLiterals(WatchedLiterals::new(cnf))
    }

    fn add_clause(&mut self, clause: &Clause<L, S>, idx: usize) {
        match self {
            Self::WatchedLiterals(wl) => wl.add_clause(clause, idx),
            Self::UnitSearch(us) => us.add_clause(clause, idx),
            Self::UnitPropagationWithPureLiterals(up) => up.add_clause(clause, idx),
        }
    }

    fn propagate(
        &mut self,
        trail: &mut Trail<L, S>,
        assignment: &mut A,
        cnf: &mut Cnf<L, S>,
    ) -> Option<usize> {
        match self {
            Self::WatchedLiterals(wl) => wl.propagate(trail, assignment, cnf),
            Self::UnitSearch(us) => us.propagate(trail, assignment, cnf),
            Self::UnitPropagationWithPureLiterals(up) => up.propagate(trail, assignment, cnf),
        }
    }

    fn num_propagations(&self) -> usize {
        match self {
            Self::WatchedLiterals(wl) => wl.num_propagations(),
            Self::UnitSearch(us) => us.num_propagations(),
            Self::UnitPropagationWithPureLiterals(up) => up.num_propagations(),
        }
    }

    fn cleanup_learnt(&mut self, learnt_idx: usize) {
        match self {
            Self::WatchedLiterals(wl) => wl.cleanup_learnt(learnt_idx),
            Self::UnitSearch(us) => us.cleanup_learnt(learnt_idx),
            Self::UnitPropagationWithPureLiterals(up) => up.cleanup_learnt(learnt_idx),
        }
    }
}

/// Enum representing the type of propagator to use in the SAT solver.
#[derive(Debug, Clone, PartialEq, Eq, Copy, Hash, Default, ValueEnum)]
pub enum PropagatorType {
    /// Watched literals propagator, which uses the watched literals scheme for efficient unit propagation.
    #[default]
    WatchedLiterals,
    /// Unit search propagator, which iterates through clauses to find unit clauses.
    UnitSearch,
    /// Unit propagation with pure literals, which combines unit propagation with the heuristic of assigning pure literals.
    UnitPropagationWithPureLiterals,
}

impl Display for PropagatorType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WatchedLiterals => write!(f, "watched-literals"),
            Self::UnitSearch => write!(f, "unit-search"),
            Self::UnitPropagationWithPureLiterals => {
                write!(f, "unit-propagation-with-pure-literals")
            }
        }
    }
}

impl PropagatorType {
    /// Converts the `PropagatorType` to a specific propagator implementation.
    #[must_use]
    pub fn to_impl<L: Literal, S: LiteralStorage<L>, A: Assignment>(
        self,
        cnf: &Cnf<L, S>,
    ) -> PropagatorImpls<L, S, A> {
        match self {
            Self::WatchedLiterals => PropagatorImpls::WatchedLiterals(WatchedLiterals::new(cnf)),
            Self::UnitSearch => PropagatorImpls::UnitSearch(UnitSearch::new(cnf)),
            Self::UnitPropagationWithPureLiterals => {
                PropagatorImpls::UnitPropagationWithPureLiterals(
                    UnitPropagationWithPureLiterals::new(cnf),
                )
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sat::assignment::VecAssignment;
    use crate::sat::literal::PackedLiteral;

    type TestLiteral = PackedLiteral;
    type TestClauseStorage = SmallVec<[TestLiteral; 8]>;
    type TestCnf = Cnf<TestLiteral, TestClauseStorage>;
    type TestAssignment = VecAssignment;
    type TestTrail = Trail<TestLiteral, TestClauseStorage>;

    fn lit(val: i32) -> TestLiteral {
        TestLiteral::from_i32(val)
    }

    fn setup_test_environment(
        clauses_dimacs: Vec<Vec<i32>>,
        num_total_vars: usize,
    ) -> (TestCnf, TestTrail, TestAssignment) {
        let mut cnf = TestCnf::new(clauses_dimacs);
        let effective_num_vars = cnf.num_vars.max(num_total_vars);
        cnf.num_vars = effective_num_vars;

        let trail = TestTrail::new(&cnf.clauses, effective_num_vars);
        let assignment = TestAssignment::new(effective_num_vars);
        (cnf, trail, assignment)
    }

    #[test]
    fn test_watched_literals_new_and_add_clause() {
        let (cnf, _trail, _assignment) =
            setup_test_environment(vec![vec![1, 2, -3], vec![-1, 4]], 5);
        let propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);

        assert_eq!(propagator.watches.len(), cnf.num_vars * 2);

        assert!(propagator[lit(1)].contains(&0));
        assert!(propagator[lit(2)].contains(&0));
        assert!(!propagator[lit(-3)].contains(&0));

        assert!(propagator[lit(-1)].contains(&1));
        assert!(propagator[lit(4)].contains(&1));
    }

    #[test]
    fn test_watched_literals_simple_propagation() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2], vec![-2, 3]], 4);
        let mut propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);

        trail.push(lit(1), 1, Reason::Decision);

        let conflict = propagator.propagate(&mut trail, &mut assignment, &mut cnf);
        assert!(conflict.is_none());

        assert_eq!(trail.len(), 3);
        assert_eq!(trail.t[0].lit, lit(1));
        assert_eq!(trail.t[1].lit, lit(2));
        assert_eq!(trail.t[1].reason, Reason::Clause(0));
        assert_eq!(trail.t[2].lit, lit(3));
        assert_eq!(trail.t[2].reason, Reason::Clause(1));

        assert_eq!(assignment.literal_value(lit(1)), Some(true));
        assert_eq!(assignment.literal_value(lit(2)), Some(true));
        assert_eq!(assignment.literal_value(lit(3)), Some(true));
        assert_eq!(propagator.num_propagations(), 3);
    }

    #[test]
    fn test_watched_literals_conflict() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2], vec![-1, -2]], 3);
        let mut propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);

        trail.push(lit(1), 1, Reason::Decision);

        let conflict_idx = propagator.propagate(&mut trail, &mut assignment, &mut cnf);
        assert!(conflict_idx.is_some());
        assert_eq!(conflict_idx.unwrap(), 1);
    }

    #[test]
    fn test_watched_literals_find_new_watch() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2, 3, -4]], 5);
        let mut propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);

        trail.push(lit(1), 1, Reason::Decision);

        let conflict = propagator.propagate(&mut trail, &mut assignment, &mut cnf);
        assert!(conflict.is_none());

        assert!(propagator[lit(2)].contains(&0));
        assert!(propagator[lit(3)].contains(&0));
        assert!(!propagator[lit(-1)].contains(&0));
        assert!(!propagator[lit(-4)].contains(&0));
    }

    #[test]
    fn test_unit_search_simple_propagation() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2], vec![-2, 3]], 4);
        let mut propagator = UnitSearch::new(&cnf);

        trail.push(lit(1), 1, Reason::Decision);
        let conflict = propagator.propagate(&mut trail, &mut assignment, &mut cnf);

        assert!(conflict.is_none());
        assert_eq!(trail.len(), 3);
        assert_eq!(trail.t[0].lit, lit(1));
        assert_eq!(trail.t[1].lit, lit(2));
        assert_eq!(trail.t[2].lit, lit(3));
        assert_eq!(assignment.var_value(lit(3).variable()), Some(true));
        assert_eq!(propagator.num_propagations(), 3);
    }

    #[test]
    fn test_unit_search_conflict() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2], vec![-1, -2]], 3);
        let mut propagator = UnitSearch::new(&cnf);
        trail.push(lit(1), 1, Reason::Decision);
        let conflict_idx = propagator.propagate(&mut trail, &mut assignment, &mut cnf);
        assert!(conflict_idx.is_some());
        assert_eq!(conflict_idx.unwrap(), 1);
    }

    #[test]
    fn test_unit_prop_with_pures() {
        let (mut cnf, mut trail, mut assignment) =
            setup_test_environment(vec![vec![-1, 2], vec![3]], 4);
        let mut propagator = UnitPropagationWithPureLiterals::new(&cnf);

        trail.push(lit(1), 1, Reason::Decision);
        let conflict = propagator.propagate(&mut trail, &mut assignment, &mut cnf);

        assert!(conflict.is_none());
        assert_eq!(trail.len(), 3);

        assert_eq!(assignment.var_value(lit(3).variable()), Some(true));
    }

    #[test]
    fn test_watched_literals_empty_cnf() {
        let (cnf, _trail, _assignment) = setup_test_environment(vec![], 1);
        let propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);
        assert_eq!(propagator.watches.len(), 2);
    }

    #[test]
    fn test_watched_literals_unit_clause_in_cnf() {
        let (cnf, _trail, _assignment) = setup_test_environment(vec![vec![1], vec![-2, 3]], 4);
        let propagator = WatchedLiterals::<_, _, TestAssignment>::new(&cnf);
        assert!(!propagator[lit(1)].contains(&0));
        assert!(propagator[lit(-2)].contains(&1));
        assert!(propagator[lit(3)].contains(&1));
    }
}