oxiz-solver 0.2.0

Main CDCL(T) Solver API for OxiZ
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
//! Advanced Model Builder for Theory Combination
//!
//! This module provides sophisticated model construction for CDCL(T) solving,
//! including:
//! - Theory-specific model building
//! - Witness generation for existential quantifiers
//! - Model minimization and optimization
//! - Cross-theory consistency checking

#![allow(dead_code, missing_docs)] // Under development

#[allow(unused_imports)]
use crate::prelude::*;

/// Represents a model assignment for a term
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelValue {
    /// The term being assigned
    pub term: TermId,
    /// The value assigned to the term
    pub value: Value,
    /// The theory that generated this assignment
    pub theory: Theory,
    /// Whether this is a witness for an existential quantifier
    pub is_witness: bool,
}

/// Value types in the model
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
    /// Boolean value
    Bool(bool),
    /// Integer value
    Int(i64),
    /// Rational value (numerator, denominator)
    Rat(i64, u64),
    /// Bit-vector value (value, width)
    BitVec(u64, usize),
    /// Array value (maps indices to values)
    Array(Box<ArrayValue>),
    /// Uninterpreted function application
    UFApp(String, Vec<Value>),
    /// Datatype constructor
    Constructor(String, Vec<Value>),
}

/// Array value representation
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArrayValue {
    /// Default value for unspecified indices
    pub default: Value,
    /// Explicit mappings
    pub mappings: BTreeMap<Value, Value>,
}

/// Theory identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Theory {
    Core,
    Arithmetic,
    BitVector,
    Array,
    Datatype,
    String,
    Uninterpreted,
}

/// Placeholder term ID
pub type TermId = usize;

/// Statistics for model building
#[derive(Debug, Clone, Default)]
pub struct ModelBuilderStats {
    pub models_built: u64,
    pub witnesses_generated: u64,
    pub consistency_checks: u64,
    pub minimization_steps: u64,
    pub theory_calls: u64,
}

/// Configuration for model building
#[derive(Debug, Clone)]
pub struct ModelBuilderConfig {
    /// Enable model minimization
    pub enable_minimization: bool,
    /// Generate witnesses for existential quantifiers
    pub generate_witnesses: bool,
    /// Check cross-theory consistency
    pub check_consistency: bool,
    /// Maximum number of minimization iterations
    pub max_minimization_iters: usize,
}

impl Default for ModelBuilderConfig {
    fn default() -> Self {
        Self {
            enable_minimization: true,
            generate_witnesses: true,
            check_consistency: true,
            max_minimization_iters: 10,
        }
    }
}

/// Advanced model builder for theory combination
pub struct AdvancedModelBuilder {
    /// Current model assignments
    assignments: FxHashMap<TermId, ModelValue>,
    /// Equivalence classes from equality propagation
    equiv_classes: FxHashMap<TermId, TermId>,
    /// Terms that need witnesses
    witness_obligations: FxHashSet<TermId>,
    /// Theory-specific model fragments
    theory_models: FxHashMap<Theory, TheoryModel>,
    /// Configuration
    config: ModelBuilderConfig,
    /// Statistics
    stats: ModelBuilderStats,
}

/// Theory-specific model fragment
#[derive(Debug, Clone)]
struct TheoryModel {
    /// Assignments specific to this theory
    assignments: FxHashMap<TermId, Value>,
    /// Constraints that must be satisfied
    constraints: Vec<TermId>,
}

impl AdvancedModelBuilder {
    /// Create a new model builder
    pub fn new(config: ModelBuilderConfig) -> Self {
        Self {
            assignments: FxHashMap::default(),
            equiv_classes: FxHashMap::default(),
            witness_obligations: FxHashSet::default(),
            theory_models: FxHashMap::default(),
            config,
            stats: ModelBuilderStats::default(),
        }
    }

    /// Build a model from the current solver state
    pub fn build_model(
        &mut self,
        boolean_assignments: &FxHashMap<TermId, bool>,
        equiv_classes: &FxHashMap<TermId, TermId>,
    ) -> Result<Model, String> {
        self.stats.models_built += 1;
        self.equiv_classes = equiv_classes.clone();

        // Phase 1: Build theory-specific models
        self.build_theory_models(boolean_assignments)?;

        // Phase 2: Generate witnesses for existential quantifiers
        if self.config.generate_witnesses {
            self.generate_witnesses()?;
        }

        // Phase 3: Check cross-theory consistency
        if self.config.check_consistency {
            self.check_cross_theory_consistency()?;
        }

        // Phase 4: Minimize model if requested
        if self.config.enable_minimization {
            self.minimize_model()?;
        }

        // Construct final model
        let model = Model {
            assignments: self.assignments.clone(),
            equiv_classes: self.equiv_classes.clone(),
        };

        Ok(model)
    }

    /// Build theory-specific models
    fn build_theory_models(
        &mut self,
        boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        // Build arithmetic model
        self.build_arithmetic_model(boolean_assignments)?;

        // Build bit-vector model
        self.build_bitvector_model(boolean_assignments)?;

        // Build array model
        self.build_array_model(boolean_assignments)?;

        // Build datatype model
        self.build_datatype_model(boolean_assignments)?;

        // Build uninterpreted function model
        self.build_uf_model(boolean_assignments)?;

        Ok(())
    }

    /// Build arithmetic model from linear constraints
    fn build_arithmetic_model(
        &mut self,
        boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        self.stats.theory_calls += 1;

        // Collect arithmetic constraints
        let mut bounds: FxHashMap<TermId, (Option<i64>, Option<i64>)> = FxHashMap::default();

        for (&term, &value) in boolean_assignments {
            if value {
                // Parse constraint and update bounds
                self.update_arithmetic_bounds(term, &mut bounds)?;
            }
        }

        // Generate satisfying assignments
        for (term, (lower, upper)) in bounds {
            let value = match (lower, upper) {
                (Some(l), Some(u)) if l <= u => {
                    // Choose midpoint
                    Value::Int((l + u) / 2)
                }
                (Some(l), None) => Value::Int(l),
                (None, Some(u)) => Value::Int(u),
                (None, None) => Value::Int(0),
                _ => return Err("Inconsistent arithmetic bounds".to_string()),
            };

            self.assignments.insert(
                term,
                ModelValue {
                    term,
                    value,
                    theory: Theory::Arithmetic,
                    is_witness: false,
                },
            );
        }

        Ok(())
    }

    /// Update arithmetic bounds from a constraint
    fn update_arithmetic_bounds(
        &self,
        _term: TermId,
        bounds: &mut FxHashMap<TermId, (Option<i64>, Option<i64>)>,
    ) -> Result<(), String> {
        // Placeholder: Parse term and update bounds
        // In real implementation, would parse constraints like x <= 5, x >= 2
        let var = 0; // Placeholder
        let bound_pair = bounds.entry(var).or_insert((None, None));

        // Example: update lower bound
        if bound_pair.0.is_none_or(|v| v < 0) {
            bound_pair.0 = Some(0);
        }

        Ok(())
    }

    /// Build bit-vector model
    fn build_bitvector_model(
        &mut self,
        _boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        self.stats.theory_calls += 1;

        // Placeholder: Build satisfying bit-vector assignments
        // Would use bit-blasting results or interval analysis

        Ok(())
    }

    /// Build array model with extensionality
    fn build_array_model(
        &mut self,
        _boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        self.stats.theory_calls += 1;

        // Placeholder: Build array model
        // Would construct ArrayValue with explicit store operations

        Ok(())
    }

    /// Build datatype model with constructor consistency
    fn build_datatype_model(
        &mut self,
        _boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        self.stats.theory_calls += 1;

        // Placeholder: Ensure constructor disjointness and injectivity

        Ok(())
    }

    /// Build uninterpreted function model
    fn build_uf_model(
        &mut self,
        _boolean_assignments: &FxHashMap<TermId, bool>,
    ) -> Result<(), String> {
        self.stats.theory_calls += 1;

        // Use equivalence classes to determine function values
        // Functions on equivalent arguments must have equivalent results

        Ok(())
    }

    /// Generate witnesses for existential quantifiers
    fn generate_witnesses(&mut self) -> Result<(), String> {
        let obligations: Vec<_> = self.witness_obligations.iter().copied().collect();

        for term in obligations {
            self.stats.witnesses_generated += 1;

            // Determine the theory and generate an appropriate witness
            let theory = self.determine_theory(term);
            let witness_value = self.generate_theory_witness(term, theory)?;

            self.assignments.insert(
                term,
                ModelValue {
                    term,
                    value: witness_value,
                    theory,
                    is_witness: true,
                },
            );
        }

        Ok(())
    }

    /// Determine which theory a term belongs to
    fn determine_theory(&self, _term: TermId) -> Theory {
        // Placeholder: analyze term structure
        Theory::Core
    }

    /// Generate a witness value for a specific theory
    fn generate_theory_witness(&self, _term: TermId, theory: Theory) -> Result<Value, String> {
        match theory {
            Theory::Arithmetic => Ok(Value::Int(0)),
            Theory::BitVector => Ok(Value::BitVec(0, 32)),
            Theory::Core => Ok(Value::Bool(false)),
            _ => Ok(Value::Int(0)),
        }
    }

    /// Check consistency across theories
    fn check_cross_theory_consistency(&mut self) -> Result<(), String> {
        self.stats.consistency_checks += 1;

        // Check that shared terms have consistent values across theories
        let mut shared_terms: FxHashMap<TermId, Vec<Theory>> = FxHashMap::default();

        for assignment in self.assignments.values() {
            shared_terms
                .entry(assignment.term)
                .or_default()
                .push(assignment.theory);
        }

        for (term, theories) in shared_terms {
            if theories.len() > 1 {
                // Verify all theories agree on the value
                let values: Vec<_> = theories
                    .iter()
                    .filter_map(|&theory| {
                        self.theory_models
                            .get(&theory)
                            .and_then(|m| m.assignments.get(&term))
                    })
                    .collect();

                if values.windows(2).any(|w| w[0] != w[1]) {
                    return Err(format!("Cross-theory inconsistency for term {}", term));
                }
            }
        }

        Ok(())
    }

    /// Minimize the model by removing unnecessary assignments
    fn minimize_model(&mut self) -> Result<(), String> {
        let mut iteration = 0;

        while iteration < self.config.max_minimization_iters {
            self.stats.minimization_steps += 1;
            iteration += 1;

            let initial_size = self.assignments.len();

            // Try to remove each assignment and check if model is still valid
            let terms: Vec<_> = self.assignments.keys().copied().collect();

            for term in terms {
                // Check if this assignment is necessary
                if !self.is_assignment_necessary(term)? {
                    self.assignments.remove(&term);
                }
            }

            // Stop if no progress
            if self.assignments.len() == initial_size {
                break;
            }
        }

        Ok(())
    }

    /// Check if an assignment is necessary for model validity
    fn is_assignment_necessary(&self, _term: TermId) -> Result<bool, String> {
        // Placeholder: would check if removing this assignment
        // causes constraint violations
        Ok(true)
    }

    /// Add a witness obligation for existential quantifier
    pub fn add_witness_obligation(&mut self, term: TermId) {
        self.witness_obligations.insert(term);
    }

    /// Get statistics
    pub fn stats(&self) -> &ModelBuilderStats {
        &self.stats
    }

    /// Reset the builder
    pub fn reset(&mut self) {
        self.assignments.clear();
        self.equiv_classes.clear();
        self.witness_obligations.clear();
        self.theory_models.clear();
    }
}

/// Complete model with all assignments
#[derive(Debug, Clone)]
pub struct Model {
    /// All term assignments
    pub assignments: FxHashMap<TermId, ModelValue>,
    /// Equivalence classes
    pub equiv_classes: FxHashMap<TermId, TermId>,
}

impl Model {
    /// Evaluate a term in this model
    pub fn eval(&self, term: TermId) -> Option<&Value> {
        // First check direct assignment
        if let Some(assignment) = self.assignments.get(&term) {
            return Some(&assignment.value);
        }

        // Check equivalence class representative
        if let Some(&repr) = self.equiv_classes.get(&term)
            && let Some(assignment) = self.assignments.get(&repr)
        {
            return Some(&assignment.value);
        }

        None
    }

    /// Check if a boolean term is true in this model
    pub fn is_true(&self, term: TermId) -> bool {
        matches!(self.eval(term), Some(Value::Bool(true)))
    }

    /// Get all assignments for a specific theory
    pub fn theory_assignments(&self, theory: Theory) -> Vec<&ModelValue> {
        self.assignments
            .values()
            .filter(|v| v.theory == theory)
            .collect()
    }

    /// Get witness assignments
    pub fn witnesses(&self) -> Vec<&ModelValue> {
        self.assignments.values().filter(|v| v.is_witness).collect()
    }
}

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

    #[test]
    fn test_model_builder_creation() {
        let config = ModelBuilderConfig::default();
        let builder = AdvancedModelBuilder::new(config);
        assert_eq!(builder.stats.models_built, 0);
    }

    #[test]
    fn test_arithmetic_model_simple() {
        let config = ModelBuilderConfig::default();
        let mut builder = AdvancedModelBuilder::new(config);

        let assignments = FxHashMap::default();
        let equiv_classes = FxHashMap::default();

        let result = builder.build_model(&assignments, &equiv_classes);
        assert!(result.is_ok());
        assert_eq!(builder.stats.models_built, 1);
    }

    #[test]
    fn test_witness_generation() {
        let config = ModelBuilderConfig {
            generate_witnesses: true,
            ..Default::default()
        };
        let mut builder = AdvancedModelBuilder::new(config);

        builder.add_witness_obligation(42);
        assert!(builder.witness_obligations.contains(&42));

        let result = builder.generate_witnesses();
        assert!(result.is_ok());
        assert_eq!(builder.stats.witnesses_generated, 1);
    }

    #[test]
    fn test_model_evaluation() {
        let mut assignments = FxHashMap::default();
        assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(42),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );

        let model = Model {
            assignments,
            equiv_classes: FxHashMap::default(),
        };

        assert_eq!(model.eval(1), Some(&Value::Int(42)));
        assert_eq!(model.eval(2), None);
    }

    #[test]
    fn test_model_with_equivalence() {
        let mut assignments = FxHashMap::default();
        assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(42),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );

        let mut equiv_classes = FxHashMap::default();
        equiv_classes.insert(2, 1); // 2 is equivalent to 1

        let model = Model {
            assignments,
            equiv_classes,
        };

        assert_eq!(model.eval(2), Some(&Value::Int(42)));
    }

    #[test]
    fn test_theory_assignments_filter() {
        let mut assignments = FxHashMap::default();
        assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(42),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );
        assignments.insert(
            2,
            ModelValue {
                term: 2,
                value: Value::BitVec(0xff, 8),
                theory: Theory::BitVector,
                is_witness: false,
            },
        );

        let model = Model {
            assignments,
            equiv_classes: FxHashMap::default(),
        };

        let arith_assignments = model.theory_assignments(Theory::Arithmetic);
        assert_eq!(arith_assignments.len(), 1);
        assert_eq!(arith_assignments[0].term, 1);
    }

    #[test]
    fn test_witness_filter() {
        let mut assignments = FxHashMap::default();
        assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(0),
                theory: Theory::Arithmetic,
                is_witness: true,
            },
        );
        assignments.insert(
            2,
            ModelValue {
                term: 2,
                value: Value::Int(5),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );

        let model = Model {
            assignments,
            equiv_classes: FxHashMap::default(),
        };

        let witnesses = model.witnesses();
        assert_eq!(witnesses.len(), 1);
        assert_eq!(witnesses[0].term, 1);
    }

    #[test]
    fn test_consistency_check() {
        let config = ModelBuilderConfig {
            check_consistency: true,
            ..Default::default()
        };
        let mut builder = AdvancedModelBuilder::new(config);

        let result = builder.check_cross_theory_consistency();
        assert!(result.is_ok());
        assert_eq!(builder.stats.consistency_checks, 1);
    }

    #[test]
    fn test_minimization() {
        let config = ModelBuilderConfig {
            enable_minimization: true,
            max_minimization_iters: 5,
            ..Default::default()
        };
        let mut builder = AdvancedModelBuilder::new(config);

        // Add some assignments
        builder.assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(42),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );

        let result = builder.minimize_model();
        assert!(result.is_ok());
        assert!(builder.stats.minimization_steps > 0);
    }

    #[test]
    fn test_reset() {
        let mut builder = AdvancedModelBuilder::new(ModelBuilderConfig::default());

        builder.assignments.insert(
            1,
            ModelValue {
                term: 1,
                value: Value::Int(42),
                theory: Theory::Arithmetic,
                is_witness: false,
            },
        );
        builder.add_witness_obligation(2);

        builder.reset();
        assert!(builder.assignments.is_empty());
        assert!(builder.witness_obligations.is_empty());
    }
}