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
use std::{rc::Rc, str::FromStr};
use logos::{Lexer, Logos};
use malachite_bigint::{BigInt, Sign};
use veripb_formula::prelude::*;
use veripb_parser::error::ParserError;
use crate::prelude::*;
use super::{Rule, RuleToken};
// Tokens for postfix notation cutting planes proofs.
#[derive(Debug, Logos, PartialEq, Eq)]
#[logos(skip r"[ \t\r\n]")]
enum PolToken {
// The integer is either used as constraint ID or for division/multiplication.
#[regex("[+-]?[0-9]+")]
Integer,
// OPB variable name.
#[regex("[a-zA-Z_][_a-zA-Z0-9\\-\\^\\[\\]\\{\\}]+")]
Var,
// Negation symbol for a literal.
#[regex("~[a-zA-Z_][_a-zA-Z0-9\\-\\^\\[\\]\\{\\}]+")]
NegatedVar,
// Saturate constraint.
#[token("s")]
Saturate,
// Divide constraint in normalized form by integer.
#[token("d")]
NormalizedFormDivide,
// Weaken constraint by variable.
#[token("w")]
Weaken,
// Multiply constraint by integer.
#[token("*")]
Multiply,
// Add two constraints together.
#[token("+")]
Add,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Instruction {
ConstraintId(isize),
LiteralAxiom(Lit),
NormalizedFormDivide(BigInt),
VariableFormDivide(BigInt),
NormalizedFormMIR(BigInt),
VariableFormMIR(BigInt),
Multiply(BigInt),
Weaken(VarIdx),
LowerRHS(BigInt),
Add,
Saturate,
}
#[derive(Debug, PartialEq, Eq)]
pub struct PolRule {
instructions: Vec<Instruction>,
}
impl PolRule {
pub fn new(instructions: Vec<Instruction>) -> Self {
Self { instructions }
}
#[inline]
pub fn parse(lex: Lexer<RuleToken>, context: &mut Context) -> Result<Self, ParserError> {
let mut lex = lex.morph();
let mut instructions = Vec::new();
let mut integer_buf: Option<&str> = None;
let mut var_buffer: Option<VarIdx> = None;
while let Some(token) = lex.next() {
if let Some(slice) = integer_buf {
integer_buf = None;
match token {
Ok(PolToken::NormalizedFormDivide) => {
let divisor = BigInt::from_str(slice).unwrap();
if divisor.sign() != Sign::Plus {
return Err(ParserError::token_error(
lex.span(),
"positive integer as divisor",
));
}
instructions.push(Instruction::NormalizedFormDivide(divisor));
continue;
}
Ok(PolToken::Multiply) => {
let factor = BigInt::from_str(slice).unwrap();
if factor.sign() == Sign::Minus {
return Err(ParserError::token_error(
lex.span(),
"non-negative integer as factor",
));
}
instructions.push(Instruction::Multiply(factor));
continue;
}
_ => instructions.push(Instruction::ConstraintId(slice.parse().unwrap())),
}
} else if token == Ok(PolToken::NormalizedFormDivide) || token == Ok(PolToken::Multiply)
{
return Err(ParserError::token_error(
lex.span(),
"integer before division or multiplication in cutting planes step",
));
}
if let Some(var_idx) = var_buffer {
var_buffer = None;
match token {
Ok(PolToken::Weaken) => {
instructions.push(Instruction::Weaken(var_idx));
continue;
}
_ => {
instructions.push(Instruction::LiteralAxiom(Lit::from_var(var_idx, false)));
}
}
} else if token == Ok(PolToken::Weaken) {
return Err(ParserError::token_error(
lex.span(),
"variable name before weakening rule",
));
}
match token {
Ok(PolToken::Integer) => integer_buf = Some(lex.slice()),
Ok(PolToken::Var) => var_buffer = Some(context.var_names.add_by_name(lex.slice())),
Ok(PolToken::NegatedVar) => instructions.push(Instruction::LiteralAxiom(
Lit::from_var(context.var_names.add_by_name(&lex.slice()[1..]), true),
)),
Ok(PolToken::Saturate) => instructions.push(Instruction::Saturate),
Ok(PolToken::Add) => instructions.push(Instruction::Add),
Err(_) => {
return Err(ParserError::token_error(
lex.span(),
"integer, literal, '+', '*', 'd', 's', or 'w'",
))
}
_ => {}
}
}
if let Some(slice) = integer_buf {
instructions.push(Instruction::ConstraintId(slice.parse().unwrap()))
}
if let Some(var_idx) = var_buffer {
instructions.push(Instruction::LiteralAxiom(Lit::from_var(var_idx, false)));
}
Ok(PolRule { instructions })
}
}
impl Rule for PolRule {
fn compute(
&mut self,
context: &mut Context,
database: &mut Database,
) -> Result<Vec<Rc<DBConstraint>>, CheckingError> {
let mut stack: Vec<PBConstraintEnum> = Vec::new();
// We optimize cutting planes derivations by accumulating successive additions of literal axioms
// and adding them to the base constraint in one go.
// Boolean tracking whether the top of the stack is a literal axiom (possibly multiplied with a constant).
let mut top_is_literal_axiom = false;
// Vector of terms keeping track of the literal axioms that still need to be added.
let mut literal_axiom_stash = Vec::new();
// Vector keeping track of variables that still need to be weakened.
let mut weakening_stash = Vec::new();
for instruction in self.instructions.iter_mut() {
if !literal_axiom_stash.is_empty() {
// We need to process the literal axiom stash if we encounter an operation that does not extend the
// current sequence of literal axiom additions.
let need_to_process_stash = if top_is_literal_axiom {
// Multiplying the literal axiom on the top of the stack or adding it extends the current sequence.
!matches!(instruction, Instruction::Multiply(_) | Instruction::Add)
} else {
// Only pushing a new literal axiom on the stack extend the current sequence.
!matches!(instruction, Instruction::LiteralAxiom(_))
};
if need_to_process_stash {
let last = if top_is_literal_axiom {
// If there is still a literal axiom on top of the stack, we remove it temporarily
// in order to carry out the addition on the correct constraint.
stack.pop()
} else {
None
};
if let Some(first) = stack.last_mut() {
// Create constraint from literal axioms to be added.
let second = constraint_from_terms(
std::mem::take(&mut literal_axiom_stash),
0.into(),
);
// Add constraint containing literal axioms.
if let Some(replacement) = first.add(&second) {
stack.pop();
stack.push(replacement);
}
// Restore temporarily removed literal axiom.
if let Some(last) = last {
stack.push(last);
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
}
}
if !weakening_stash.is_empty() {
// We need to process the weakening stash if we have no additional weakening step.
if !matches!(instruction, Instruction::Weaken(_)) {
if let Some(constraint) = stack.last_mut() {
if let Some(replacement) =
constraint.weaken_all(std::mem::take(&mut weakening_stash))
{
stack.pop();
stack.push(replacement);
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
}
}
match instruction {
Instruction::ConstraintId(index) => {
*index = database.normalize_id(*index);
let constraint = database.get_entry_usize(*index as usize)?;
if context.only_core && !constraint.is_core_constraint_id(*index as usize) {
return Err(CheckingError::CoreSubproofUsingNonCoreConstraint(*index));
}
stack.push(constraint.constraint.clone());
top_is_literal_axiom = false;
}
Instruction::LiteralAxiom(lit) => {
stack.push(Cardinality::from_lits(vec![*lit], 0).into());
top_is_literal_axiom = true;
}
Instruction::Saturate => {
match stack.last_mut() {
Some(constraint) => constraint.saturate(),
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
}
top_is_literal_axiom = false;
}
Instruction::Weaken(var_idx) => {
weakening_stash.push(*var_idx);
top_is_literal_axiom = false;
}
Instruction::NormalizedFormDivide(divisor) => {
match stack.last_mut() {
Some(constraint) => constraint.normalized_form_div(divisor),
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
}
top_is_literal_axiom = false;
}
Instruction::VariableFormDivide(divisor) => {
match stack.last_mut() {
Some(constraint) => {
if let Some(replacement) = constraint.variable_form_div(divisor) {
stack.pop();
stack.push(replacement);
}
}
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
}
top_is_literal_axiom = false;
}
Instruction::NormalizedFormMIR(divisor) => {
match stack.last_mut() {
Some(constraint) => {
if let Some(replacement) = constraint.normalized_form_mir(divisor) {
stack.pop();
stack.push(replacement);
}
}
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
}
top_is_literal_axiom = false;
}
Instruction::VariableFormMIR(divisor) => {
match stack.last_mut() {
Some(constraint) => {
if let Some(replacement) = constraint.variable_form_mir(divisor) {
stack.pop();
stack.push(replacement);
}
}
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
}
top_is_literal_axiom = false;
}
Instruction::Multiply(factor) => match stack.last_mut() {
Some(constraint) => {
if let Some(replacement) = constraint.multiply(factor) {
stack.pop();
stack.push(replacement);
}
}
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
},
Instruction::Add => {
if let Some(second) = stack.pop() {
if !top_is_literal_axiom {
// The top is not a literal axiom, so we just add it.
if let Some(first) = stack.last_mut() {
if let Some(replacement) = first.add(&second) {
stack.pop();
stack.push(replacement);
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
} else {
// Store the literal axiom for adding it later.
if let Some(term) = second.get_term(0) {
literal_axiom_stash.push(term);
}
top_is_literal_axiom = false;
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
}
Instruction::LowerRHS(amount) => match stack.last_mut() {
Some(constraint) => {
if let Some(replacement) = constraint.lower_rhs(amount) {
stack.pop();
stack.push(replacement);
}
}
None => return Err(CheckingError::NotEnoughConstraintsOnStack),
},
}
}
if !literal_axiom_stash.is_empty() {
// Process the remaining literal axioms that still need to be added.
if let Some(first) = stack.last_mut() {
let second =
constraint_from_terms(std::mem::take(&mut literal_axiom_stash), 0.into());
if let Some(replacement) = first.add(&second) {
stack.pop();
stack.push(replacement);
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
}
if !weakening_stash.is_empty() {
// Process remaining weakening steps.
if let Some(constraint) = stack.last_mut() {
if let Some(replacement) =
constraint.weaken_all(std::mem::take(&mut weakening_stash))
{
stack.pop();
stack.push(replacement);
}
} else {
return Err(CheckingError::NotEnoughConstraintsOnStack);
}
}
if stack.len() != 1 {
return Err(CheckingError::StackNotOne(stack.len()));
}
Ok(vec![Rc::new(DBConstraint::from(
stack.pop().unwrap().into_smallest_type(),
))])
}
#[inline]
fn elaborate(
&self,
context: &mut Context,
database: &Database,
) -> Result<(), ElaborationError> {
let elaborator = context.elaborator.as_mut().unwrap();
elaborator.write("pol");
for instruction in self.instructions.iter() {
elaborator.write(" ");
match instruction {
Instruction::ConstraintId(index) => {
let constraint = database
.get_entry_usize(*index as usize)
.expect("constraint at this ID was successfully accessed before");
elaborator.write(
&constraint
.get_out_id(*index as usize)
.expect("constraint should have output ID")
.to_string(),
);
}
Instruction::LiteralAxiom(lit) => {
elaborator.write(&lit.to_pretty_string(&context.var_names))
}
Instruction::NormalizedFormDivide(big_int) => {
elaborator.write(&big_int.to_string());
elaborator.write(" d");
}
Instruction::VariableFormDivide(big_int) => {
elaborator.write(&big_int.to_string());
elaborator.write(" c");
}
Instruction::NormalizedFormMIR(big_int) => {
elaborator.write(&big_int.to_string());
elaborator.write(" n");
}
Instruction::VariableFormMIR(big_int) => {
elaborator.write(&big_int.to_string());
elaborator.write(" m");
}
Instruction::Multiply(big_int) => {
elaborator.write(&big_int.to_string());
elaborator.write(" *");
}
Instruction::Weaken(var) => {
elaborator.write(&var.to_pretty_string(&context.var_names));
elaborator.write(" w");
}
Instruction::Add => elaborator.write("+"),
Instruction::Saturate => elaborator.write("s"),
Instruction::LowerRHS(amount) => {
elaborator.write(&amount.to_string());
elaborator.write(" -");
}
}
}
elaborator.writeln(";");
Ok(())
}
#[inline]
fn is_subproof_friendly(&self) -> bool {
true
}
}