oxiz-proof 0.2.2

Proof generation and checking for OxiZ SMT solver
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
//! Carcara proof format compatibility.
//!
//! Carcara is a proof checker for SMT proofs in Alethe format.
//! This module provides utilities to ensure Alethe proofs are compatible
//! with Carcara's requirements and validation rules.
//!
//! ## Carcara Requirements
//!
//! - Proofs must be in valid Alethe format
//! - Step indices must be sequential and unique
//! - All premises must be previously defined
//! - Rules must be correctly applied according to Carcara's semantics
//!
//! ## References
//!
//! Carcara: <https://github.com/ufmg-smite/carcara>

use crate::alethe::{AletheProof, AletheRule, AletheStep, StepIndex, TermRef};
use rustc_hash::FxHashSet;
use std::io::{self, Write};

/// Carcara-compatible proof builder
///
/// Ensures that generated Alethe proofs meet Carcara's requirements
#[derive(Debug, Default)]
pub struct CarcaraProof {
    /// The underlying Alethe proof
    proof: AletheProof,
    /// Set of defined step indices (for validation)
    defined_steps: FxHashSet<StepIndex>,
    /// Next available step index
    next_index: StepIndex,
}

impl CarcaraProof {
    /// Create a new Carcara-compatible proof
    #[must_use]
    pub fn new() -> Self {
        Self {
            proof: AletheProof::new(),
            defined_steps: FxHashSet::default(),
            next_index: 1,
        }
    }

    /// Allocate a new unique step index
    #[allow(dead_code)]
    fn alloc_index(&mut self) -> StepIndex {
        let idx = self.next_index;
        self.next_index += 1;
        idx
    }

    /// Add an assumption step
    ///
    /// # Errors
    ///
    /// Returns an error if the step index is already used
    pub fn add_assume(&mut self, term: impl Into<TermRef>) -> Result<StepIndex, String> {
        let index = self.proof.assume(term);

        if !self.defined_steps.insert(index) {
            return Err(format!("Step index {} already defined", index));
        }

        self.next_index = index + 1;
        Ok(index)
    }

    /// Add a proof step with validation
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The step index is already used
    /// - Any premise is not yet defined
    /// - The rule application is invalid
    #[allow(clippy::too_many_arguments)]
    pub fn add_step(
        &mut self,
        clause: Vec<TermRef>,
        rule: AletheRule,
        premises: Vec<StepIndex>,
        args: Vec<TermRef>,
    ) -> Result<StepIndex, String> {
        // Validate all premises are defined
        for &premise in &premises {
            if !self.defined_steps.contains(&premise) {
                return Err(format!("Premise {} not yet defined", premise));
            }
        }

        let index = self.proof.step(clause, rule, premises, args);

        if !self.defined_steps.insert(index) {
            return Err(format!("Step index {} already defined", index));
        }

        self.next_index = index + 1;
        Ok(index)
    }

    /// Add an anchor for subproofs
    ///
    /// # Errors
    ///
    /// Returns an error if the step index is already used
    pub fn add_anchor(&mut self, args: Vec<(String, TermRef)>) -> Result<StepIndex, String> {
        let index = self.proof.anchor(args);

        if !self.defined_steps.insert(index) {
            return Err(format!("Step index {} already defined", index));
        }

        self.next_index = index + 1;
        Ok(index)
    }

    /// Validate the proof for Carcara compatibility
    ///
    /// Checks:
    /// - All step indices are unique
    /// - All premises are defined before use
    /// - No circular dependencies
    pub fn validate(&self) -> Result<(), String> {
        let mut seen_indices = FxHashSet::default();

        for step in self.proof.steps() {
            let index = match step {
                AletheStep::Assume { index, .. } => *index,
                AletheStep::Step {
                    index, premises, ..
                } => {
                    // Check all premises are already seen
                    for &premise in premises {
                        if !seen_indices.contains(&premise) {
                            return Err(format!(
                                "Step {} uses undefined premise {}",
                                index, premise
                            ));
                        }
                    }
                    *index
                }
                AletheStep::Anchor { step, .. } => *step,
                AletheStep::DefineFun { .. } => continue,
            };

            if !seen_indices.insert(index) {
                return Err(format!("Duplicate step index: {}", index));
            }
        }

        Ok(())
    }

    /// Get the underlying Alethe proof
    #[must_use]
    pub fn alethe_proof(&self) -> &AletheProof {
        &self.proof
    }

    /// Write the proof in Carcara-compatible Alethe format
    pub fn write<W: Write>(&self, writer: W) -> io::Result<()> {
        self.proof.write(writer)
    }

    /// Get the number of steps in the proof
    #[must_use]
    pub fn len(&self) -> usize {
        self.proof.len()
    }

    /// Check if the proof is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.proof.is_empty()
    }

    /// Clear the proof
    pub fn clear(&mut self) {
        self.proof.clear();
        self.defined_steps.clear();
        self.next_index = 1;
    }
}

/// Validate a proof for Carcara compatibility
///
/// This function checks that an existing Alethe proof meets Carcara's requirements
pub fn validate_for_carcara(proof: &AletheProof) -> Result<(), String> {
    let mut seen_indices = FxHashSet::default();

    for step in proof.steps() {
        let index = match step {
            AletheStep::Assume { index, .. } => *index,
            AletheStep::Step {
                index, premises, ..
            } => {
                // Check all premises are already seen
                for &premise in premises {
                    if !seen_indices.contains(&premise) {
                        return Err(format!("Step {} uses undefined premise {}", index, premise));
                    }
                }
                *index
            }
            AletheStep::Anchor { step, .. } => *step,
            AletheStep::DefineFun { .. } => continue,
        };

        if !seen_indices.insert(index) {
            return Err(format!("Duplicate step index: {}", index));
        }
    }

    Ok(())
}

/// Convert an Alethe proof to Carcara-compatible format
///
/// This ensures step indices are sequential and all dependencies are satisfied
pub fn to_carcara_format(proof: &AletheProof) -> Result<CarcaraProof, String> {
    let mut carcara = CarcaraProof::new();
    let mut index_map: rustc_hash::FxHashMap<StepIndex, StepIndex> =
        rustc_hash::FxHashMap::default();

    for step in proof.steps() {
        match step {
            AletheStep::Assume { index, term } => {
                let new_index = carcara.add_assume(term.clone())?;
                index_map.insert(*index, new_index);
            }
            AletheStep::Step {
                index,
                clause,
                rule,
                premises,
                args,
            } => {
                // Map old premise indices to new ones
                let new_premises: Vec<StepIndex> = premises
                    .iter()
                    .map(|p| {
                        index_map
                            .get(p)
                            .copied()
                            .ok_or_else(|| format!("Premise {} not found in index map", p))
                    })
                    .collect::<Result<Vec<_>, String>>()?;

                let new_index =
                    carcara.add_step(clause.clone(), *rule, new_premises, args.clone())?;
                index_map.insert(*index, new_index);
            }
            AletheStep::Anchor { step, args } => {
                let new_index = carcara.add_anchor(args.clone())?;
                index_map.insert(*step, new_index);
            }
            AletheStep::DefineFun { .. } => {
                // Define-fun steps don't have indices, pass through
                continue;
            }
        }
    }

    Ok(carcara)
}

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

    #[test]
    fn test_carcara_proof_creation() {
        let proof = CarcaraProof::new();
        assert!(proof.is_empty());
        assert_eq!(proof.len(), 0);
    }

    #[test]
    fn test_add_assume() {
        let mut proof = CarcaraProof::new();
        let idx = proof
            .add_assume("p")
            .expect("test operation should succeed");
        assert_eq!(idx, 1);
        assert_eq!(proof.len(), 1);
    }

    #[test]
    fn test_add_step_with_premise() {
        let mut proof = CarcaraProof::new();
        let p1 = proof
            .add_assume("p")
            .expect("test operation should succeed");
        let p2 = proof
            .add_assume("q")
            .expect("test operation should succeed");

        let step = proof.add_step(
            vec!["(or p q)".to_string()],
            AletheRule::Resolution,
            vec![p1, p2],
            vec![],
        );

        assert!(step.is_ok());
        assert_eq!(proof.len(), 3);
    }

    #[test]
    fn test_undefined_premise_error() {
        let mut proof = CarcaraProof::new();

        // Try to use premise 99 which doesn't exist
        let result = proof.add_step(
            vec!["p".to_string()],
            AletheRule::Resolution,
            vec![99],
            vec![],
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not yet defined"));
    }

    #[test]
    fn test_validation() {
        let mut proof = CarcaraProof::new();
        proof
            .add_assume("p")
            .expect("test operation should succeed");
        proof
            .add_assume("q")
            .expect("test operation should succeed");

        let result = proof.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_sequential_indices() {
        let mut proof = CarcaraProof::new();
        let i1 = proof
            .add_assume("p")
            .expect("test operation should succeed");
        let i2 = proof
            .add_assume("q")
            .expect("test operation should succeed");
        let i3 = proof
            .add_assume("r")
            .expect("test operation should succeed");

        assert_eq!(i1, 1);
        assert_eq!(i2, 2);
        assert_eq!(i3, 3);
    }

    #[test]
    fn test_clear() {
        let mut proof = CarcaraProof::new();
        proof
            .add_assume("p")
            .expect("test operation should succeed");
        proof
            .add_assume("q")
            .expect("test operation should succeed");

        assert_eq!(proof.len(), 2);

        proof.clear();
        assert!(proof.is_empty());

        // After clear, indices should start from 1 again
        let idx = proof
            .add_assume("r")
            .expect("test operation should succeed");
        assert_eq!(idx, 1);
    }

    #[test]
    fn test_anchor() {
        let mut proof = CarcaraProof::new();
        let idx = proof
            .add_anchor(vec![("x".to_string(), "Int".to_string())])
            .expect("test operation should succeed");
        assert_eq!(idx, 1);
        assert_eq!(proof.len(), 1);
    }

    #[test]
    fn test_validate_for_carcara() {
        let mut alethe = AletheProof::new();
        alethe.assume("p");
        alethe.assume("q");

        let result = validate_for_carcara(&alethe);
        assert!(result.is_ok());
    }

    #[test]
    fn test_to_carcara_format() {
        let mut alethe = AletheProof::new();
        let p = alethe.assume("p");
        let q = alethe.assume("q");
        alethe.step(
            vec!["(or p q)".to_string()],
            AletheRule::Resolution,
            vec![p, q],
            vec![],
        );

        let carcara = to_carcara_format(&alethe).expect("test operation should succeed");
        assert_eq!(carcara.len(), 3);
        assert!(carcara.validate().is_ok());
    }
}