blob: a3c33f2ef459965fc30f1b00207cf08e54b79866 [file] [log] [blame]
Florian Hahn35a2e582020-09-15 10:28:25 +01001#!/usr/bin/env python
2
3"""
4Helper script to convert the log generated by '-debug-only=constraint-system'
5to a Python script that uses Z3 to verify the decisions using Z3's Python API.
6
7Example usage:
8
9> cat path/to/file.log
10---
11x6 + -1 * x7 <= -1
12x6 + -1 * x7 <= -2
13sat
14
15> ./convert-constraint-log-to-z3.py path/to/file.log > check.py && python ./check.py
16
17> cat check.py
18 from z3 import *
19x3 = Int("x3")
20x1 = Int("x1")
21x2 = Int("x2")
22s = Solver()
23s.add(x1 + -1 * x2 <= 0)
24s.add(x2 + -1 * x3 <= 0)
25s.add(-1 * x1 + x3 <= -1)
26assert(s.check() == unsat)
27print('all checks passed')
28"""
29
30
31import argparse
32import re
33
34
35def main():
36 parser = argparse.ArgumentParser(
Tobias Hieta3c762872023-05-15 11:02:42 +020037 description="Convert constraint log to script to verify using Z3."
38 )
39 parser.add_argument(
40 "log_file", metavar="log", type=str, help="constraint-system log file"
41 )
Florian Hahn35a2e582020-09-15 10:28:25 +010042 args = parser.parse_args()
43
Tobias Hieta3c762872023-05-15 11:02:42 +020044 content = ""
45 with open(args.log_file, "rt") as f:
Florian Hahn35a2e582020-09-15 10:28:25 +010046 content = f.read()
47
Tobias Hieta3c762872023-05-15 11:02:42 +020048 groups = content.split("---")
49 var_re = re.compile("x\d+")
Florian Hahn35a2e582020-09-15 10:28:25 +010050
Tobias Hieta3c762872023-05-15 11:02:42 +020051 print("from z3 import *")
Florian Hahn35a2e582020-09-15 10:28:25 +010052 for group in groups:
Tobias Hieta3c762872023-05-15 11:02:42 +020053 constraints = [g.strip() for g in group.split("\n") if g.strip() != ""]
Florian Hahn35a2e582020-09-15 10:28:25 +010054 variables = set()
55 for c in constraints[:-1]:
56 for m in var_re.finditer(c):
57 variables.add(m.group())
58 if len(variables) == 0:
59 continue
60 for v in variables:
61 print('{} = Int("{}")'.format(v, v))
Tobias Hieta3c762872023-05-15 11:02:42 +020062 print("s = Solver()")
Florian Hahn35a2e582020-09-15 10:28:25 +010063 for c in constraints[:-1]:
Tobias Hieta3c762872023-05-15 11:02:42 +020064 print("s.add({})".format(c))
Florian Hahn35a2e582020-09-15 10:28:25 +010065 expected = constraints[-1].strip()
Tobias Hieta3c762872023-05-15 11:02:42 +020066 print("assert(s.check() == {})".format(expected))
Florian Hahn35a2e582020-09-15 10:28:25 +010067 print('print("all checks passed")')
68
69
Tobias Hieta3c762872023-05-15 11:02:42 +020070if __name__ == "__main__":
Florian Hahn35a2e582020-09-15 10:28:25 +010071 main()