veripb 3.0.2

VeriPB is a proof checker for verifying pseudo-Boolean certificates of satisfiability, unsatisfiability, and optimality bounds.
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
use std::{
    fmt::{Display, Formatter},
    rc::Rc,
    str::FromStr,
};

use logos::{Lexer, Logos};
use malachite_bigint::BigInt;
use veripb_formula::{pb_constraint::constraint_from_terms, prelude::*};
use veripb_parser::{assignment_parser::parse_bool_assignment_to_raw_vec, error::ParserError};

use crate::prelude::*;

#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub enum Bound {
    Bounded(BigInt),
    Unbounded,
}

impl Bound {
    #[inline]
    pub fn unwrap(self) -> BigInt {
        match self {
            Self::Bounded(bound) => bound,
            Self::Unbounded => {
                panic!("Cannot unwrap an unbounded bound to the value of the bound!")
            }
        }
    }
}

impl Display for Bound {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Bound::Unbounded => write!(f, "INF")?,
            Bound::Bounded(bound) => write!(f, "{bound}")?,
        }

        Ok(())
    }
}

#[derive(Debug, Logos)]
#[logos(skip r"[ \t\r\n]")]
enum ConclusionData {
    #[token(":")]
    Hint,

    #[regex("[+-]?[0-9]+", |lex| Bound::Bounded(BigInt::from_str(lex.slice()).unwrap())) ]
    #[token("INF", |_lex| Bound::Unbounded)]
    Bound(Bound),
}

#[derive(Debug, Logos)]
#[logos(skip r"[ \t\r\n]")]
pub enum ConclusionResult {
    #[token("SAT")]
    Satisfiable,

    #[token("UNSAT")]
    Unsatisfiable,

    #[token("BOUNDS")]
    Bounds,

    #[token("NONE")]
    None,
}

impl Display for ConclusionResult {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            f,
            "{}",
            match self {
                Self::Satisfiable => "SAT",
                Self::Unsatisfiable => "UNSAT",
                Self::Bounds => "BOUNDS",
                Self::None => "NONE",
            }
        )
    }
}

#[derive(Debug)]
pub struct ConclusionRule {
    result: ConclusionResult,
    lower_bound: Option<Bound>,
    upper_bound: Option<Bound>,
    constraint_id_hint: Option<isize>,
    solution_hint: Option<Vec<Lit>>,
    propagated_solution: Option<Assignment<BooleanVar>>,
}

impl ConclusionRule {
    #[inline]
    pub fn new(
        result: ConclusionResult,
        lower_bound: Option<Bound>,
        upper_bound: Option<Bound>,
        constraint_id_hint: Option<isize>,
        solution_hint: Option<Vec<Lit>>,
    ) -> Self {
        ConclusionRule {
            result,
            lower_bound,
            upper_bound,
            constraint_id_hint,
            solution_hint,
            propagated_solution: None,
        }
    }

    pub fn parse(lex: Lexer<RuleToken>, context: &mut Context) -> Result<Self, ParserError> {
        let mut lex = lex.morph();
        match lex.next() {
            Some(Ok(ConclusionResult::None)) => Ok(ConclusionRule::new(
                ConclusionResult::None,
                None,
                None,
                None,
                None,
            )),
            Some(Ok(ConclusionResult::Unsatisfiable)) => {
                let mut rule =
                    ConclusionRule::new(ConclusionResult::Unsatisfiable, None, None, None, None);
                let mut lex = lex.morph();
                match lex.next() {
                    Some(Ok(ConclusionData::Hint)) => {
                        rule.constraint_id_hint = Some(IntegerToken::parse(&mut lex.morph())?)
                    }
                    None => {}
                    _ => {
                        return Err(ParserError::token_error(
                            lex.span(),
                            "':' to start hint or end-of-line",
                        ));
                    }
                }
                Ok(rule)
            }
            Some(Ok(ConclusionResult::Satisfiable)) => {
                let mut rule =
                    ConclusionRule::new(ConclusionResult::Satisfiable, None, None, None, None);
                let mut lex = lex.morph();
                match lex.next() {
                    Some(Ok(ConclusionData::Hint)) => {
                        rule.solution_hint = Some(parse_bool_assignment_to_raw_vec(
                            &mut lex.morph(),
                            &mut context.var_names,
                        )?);
                    }
                    None => {}
                    _ => {
                        return Err(ParserError::token_error(
                            lex.span(),
                            "':' to start hint or end-of-line",
                        ));
                    }
                }
                Ok(rule)
            }
            Some(Ok(ConclusionResult::Bounds)) => {
                let mut rule =
                    ConclusionRule::new(ConclusionResult::Bounds, None, None, None, None);
                let mut lex = lex.morph();
                match lex.next() {
                    Some(Ok(ConclusionData::Bound(bound))) => rule.lower_bound = Some(bound),
                    _ => {
                        return Err(ParserError::token_error(
                            lex.span(),
                            "integer or 'INF' for lower bound",
                        ));
                    }
                }
                rule.upper_bound = match lex.next() {
                    Some(Ok(ConclusionData::Bound(bound))) => Some(bound),
                    Some(Ok(ConclusionData::Hint)) => {
                        let mut lex_inner = lex.morph();
                        rule.constraint_id_hint = Some(IntegerToken::parse(&mut lex_inner)?);
                        let mut lex_inner = lex_inner.morph();
                        if let Some(Ok(ConclusionData::Bound(bound))) = lex_inner.next() {
                            lex = lex_inner.morph();
                            Some(bound)
                        } else {
                            return Err(ParserError::token_error(
                                lex_inner.span(),
                                "constraint ID for lower bounding constraint",
                            ));
                        }
                    }
                    _ => {
                        return Err(ParserError::token_error(
                            lex.span(),
                            "':' for hint or integer or 'INF' for upper bound",
                        ));
                    }
                };
                match lex.next() {
                    Some(Ok(ConclusionData::Hint)) => {
                        rule.solution_hint = Some(parse_bool_assignment_to_raw_vec(
                            &mut lex.morph(),
                            &mut context.var_names,
                        )?);
                    }
                    None => {}
                    _ => {
                        return Err(ParserError::token_error(
                            lex.span(),
                            "':' to start hint or end-of-line",
                        ));
                    }
                }
                Ok(rule)
            }
            _ => Err(ParserError::token_error(
                lex.span(),
                "conclusion result 'NONE', 'UNSAT', 'SAT', or 'BOUNDS'",
            )),
        }
    }

    /// Checks if the database contains a contradiction.
    #[inline]
    fn check_contradiction(&self, database: &Database) -> Result<isize, CheckingError> {
        match self.constraint_id_hint {
            None => {
                if let Some(contradicting_id) = database.contains_contradiction() {
                    Ok(contradicting_id as isize)
                } else {
                    Err(CheckingError::NoContradicitionInDB)
                }
            }
            Some(hint) => {
                let constraint = database.get_entry(hint)?;
                if constraint.is_contradicting() {
                    return Ok(database.normalize_id(hint));
                }
                Err(CheckingError::HintNoContradiction(hint))
            }
        }
    }

    /// Check if the proof contains a solution or the hint is a correct solution.
    ///
    /// Returns the propagated solution if a solution was given as a hint.
    #[inline]
    fn check_solution(
        &self,
        context: &mut Context,
    ) -> Result<Option<Assignment<BooleanVar>>, CheckingError> {
        match &self.solution_hint {
            Some(solution) => {
                // Do not propagate the assignment, as the hint given in the conclusion has to be a full assignment.
                let assignment = Assignment::from(solution)
                    .ok_or(CheckingError::ConclusionSolutionConflicting)?;
                for constraint in context.original_constraints.iter() {
                    if !constraint.is_satisfied(&assignment) {
                        return Err(CheckingError::OriginalConstraintNotSatisfied);
                    }
                }
                Ok(Some(assignment))
            }
            None => {
                if context.best_valid_objective_value.is_none() {
                    return Err(CheckingError::SolutionMissing(self.result.to_string()));
                }
                Ok(None)
            }
        }
    }
}

impl Rule for ConclusionRule {
    fn compute(
        &mut self,
        context: &mut Context,
        database: &mut Database,
    ) -> Result<Vec<Rc<DBConstraint>>, CheckingError> {
        // Check order of footer rules.
        if context.has_conclusion {
            return Err(CheckingError::DoubleConclusion);
        }
        if !context.has_output || context.has_end_proof {
            return Err(CheckingError::WrongFooterOrder("conclusion"));
        }

        // Perform the necessary checks for each conclusion.
        match self.result {
            ConclusionResult::None => {}
            ConclusionResult::Unsatisfiable => {
                if context.best_objective_value.is_some() {
                    return Err(CheckingError::ConclusionUnsatSolutionLogged);
                }
                if context.objective.is_some() {
                    return Err(CheckingError::ConclusionUnsatObjective);
                }

                self.constraint_id_hint = Some(self.check_contradiction(database)?);
            }
            ConclusionResult::Satisfiable => {
                if context.objective.is_some() {
                    return Err(CheckingError::ConclusionSatWithObjective);
                }

                self.propagated_solution = self.check_solution(context)?;
            }
            ConclusionResult::Bounds => {
                if context.objective.is_none() {
                    return Err(CheckingError::ConclusionBoundsNoObjective);
                }

                // Check lower bound.
                match self.lower_bound.as_ref().unwrap() {
                    Bound::Unbounded => {
                        if self.upper_bound != Some(Bound::Unbounded) {
                            return Err(CheckingError::ConclusionBoundsInfeasibleAndUpper);
                        }
                        if context.best_objective_value.is_some() {
                            return Err(CheckingError::ConclusionBoundsInfeasibleAndSolutionLogged);
                        }

                        self.constraint_id_hint = Some(self.check_contradiction(database)?);
                    }
                    Bound::Bounded(bound) => {
                        // Check that lower bound is not better than best logged solution.
                        if context
                            .best_objective_value
                            .as_ref()
                            .is_some_and(|best| bound > best)
                        {
                            return Err(CheckingError::ConclusionBoundsLBLargerBestSolution);
                        }
                        // Construct lower bounding constraint.
                        let constraint = constraint_from_terms::<BigInt>(
                            context
                                .objective
                                .as_ref()
                                .unwrap()
                                .terms
                                .values()
                                .cloned()
                                .collect(),
                            bound.to_owned() - &context.objective.as_ref().unwrap().constant,
                        );
                        let db_constraint = Rc::new(DBConstraint::from(constraint));

                        if let Some(contradicting_id) = database.contains_contradiction() {
                            self.constraint_id_hint = Some(contradicting_id as isize);
                        } else {
                            self.constraint_id_hint = Some(check_implication(
                                context,
                                database,
                                &db_constraint,
                                self.constraint_id_hint,
                            )?);
                        }
                    }
                }

                // Check upper bound.
                match self.upper_bound.as_ref().unwrap() {
                    Bound::Unbounded => {}
                    Bound::Bounded(bound) => {
                        if self.lower_bound > self.upper_bound {
                            return Err(CheckingError::ConclusionBoundsLowerGreaterUpper(
                                self.lower_bound.to_owned().unwrap().unwrap(),
                                self.upper_bound.to_owned().unwrap().unwrap(),
                            ));
                        }

                        match self.check_solution(context)? {
                            Some(assignment) => {
                                let value = context
                                    .original_objective
                                    .as_ref()
                                    .unwrap()
                                    .evaluate(&assignment)
                                    .ok_or(CheckingError::ObjectiveUnassigned)?;
                                if *bound != value {
                                    return Err(
                                        CheckingError::ConclusionBoundsUpperBoundMismatchHint(
                                            bound.to_owned(),
                                            value,
                                        ),
                                    );
                                }
                                self.propagated_solution = Some(assignment);
                            }
                            None => {
                                if bound != context.best_valid_objective_value.as_ref().unwrap() {
                                    return Err(
                                        CheckingError::ConclusionBoundsUpperBoundMismatchRecorded(
                                            bound.to_owned(),
                                            context.best_valid_objective_value.clone().unwrap(),
                                        ),
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        // Print the verification statement for each conclusion.
        if context.args.print_verification_result {
            match self.result {
                ConclusionResult::None => println!("s VERIFIED NO CONCLUSION"),
                ConclusionResult::Unsatisfiable => println!("s VERIFIED UNSATISFIABLE"),
                ConclusionResult::Satisfiable => println!("s VERIFIED SATISFIABLE"),
                ConclusionResult::Bounds => println!(
                    "s VERIFIED BOUNDS {} <= obj <= {}",
                    self.lower_bound.as_ref().unwrap(),
                    self.upper_bound.as_ref().unwrap()
                ),
            }
        }

        context.has_conclusion = true;
        Ok(vec![])
    }

    #[inline]
    fn elaborate(
        &self,
        context: &mut Context,
        database: &Database,
    ) -> Result<(), ElaborationError> {
        let elaborator = context.elaborator.as_mut().unwrap();
        elaborator.write("conclusion ");
        match self.result {
            ConclusionResult::Satisfiable => {
                elaborator.write("SAT");
                if let Some(assignment) = self.propagated_solution.as_ref() {
                    elaborator.write(" : ");
                    elaborator.write(&assignment.to_pretty_string(&context.var_names));
                }
            }
            ConclusionResult::Unsatisfiable => {
                elaborator.write("UNSAT : ");
                let index = self.constraint_id_hint.unwrap();
                let constraint = database
                    .get_entry_usize(index as usize)
                    .expect("constraint already accessed before");
                elaborator.write(
                    &constraint
                        .get_out_id(index as usize)
                        .expect("constraint should have output ID")
                        .to_string(),
                );
            }
            ConclusionResult::Bounds => {
                elaborator.write("BOUNDS ");
                elaborator.write(&self.lower_bound.as_ref().unwrap().to_string());
                elaborator.write(" : ");
                let index = self.constraint_id_hint.unwrap();
                let constraint = database
                    .get_entry_usize(index as usize)
                    .expect("constraint already accessed before");
                elaborator.write(
                    &constraint
                        .get_out_id(index as usize)
                        .expect("constraint should have output ID")
                        .to_string(),
                );
                elaborator.write(" ");
                elaborator.write(&self.upper_bound.as_ref().unwrap().to_string());
                if self.upper_bound != Some(Bound::Unbounded) {
                    if let Some(assignment) = self.propagated_solution.as_ref() {
                        elaborator.write(" : ");
                        elaborator.write(&assignment.to_pretty_string(&context.var_names));
                    }
                }
            }
            ConclusionResult::None => elaborator.write("NONE"),
        }
        elaborator.writeln(";");
        Ok(())
    }
}